firebase-functions 3.24.1 → 4.0.0-rc.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.
Files changed (130) hide show
  1. package/README.md +7 -9
  2. package/lib/bin/firebase-functions.js +13 -15
  3. package/lib/common/app.d.ts +14 -0
  4. package/lib/common/app.js +62 -0
  5. package/lib/common/change.d.ts +0 -5
  6. package/lib/common/change.js +5 -7
  7. package/lib/common/config.d.ts +6 -0
  8. package/lib/common/config.js +49 -0
  9. package/lib/common/debug.js +2 -2
  10. package/lib/common/encoding.d.ts +0 -8
  11. package/lib/common/encoding.js +6 -29
  12. package/lib/common/options.d.ts +14 -0
  13. package/lib/common/options.js +44 -0
  14. package/lib/common/params.d.ts +32 -0
  15. package/lib/common/params.js +23 -0
  16. package/lib/common/providers/database.d.ts +17 -19
  17. package/lib/common/providers/database.js +68 -39
  18. package/lib/common/providers/https.d.ts +11 -52
  19. package/lib/common/providers/https.js +115 -110
  20. package/lib/common/providers/identity.d.ts +8 -8
  21. package/lib/common/providers/identity.js +71 -79
  22. package/lib/common/providers/tasks.d.ts +11 -10
  23. package/lib/common/providers/tasks.js +10 -9
  24. package/lib/common/timezone.js +538 -538
  25. package/lib/common/trace.d.ts +14 -0
  26. package/lib/common/trace.js +69 -0
  27. package/lib/{encoder.d.ts → common/utilities/encoder.d.ts} +0 -0
  28. package/lib/{encoder.js → common/utilities/encoder.js} +1 -1
  29. package/lib/{utilities → common/utilities}/path-pattern.d.ts +0 -0
  30. package/lib/{utilities → common/utilities}/path-pattern.js +17 -16
  31. package/lib/{utilities → common/utilities}/path.d.ts +0 -0
  32. package/lib/{utilities → common/utilities}/path.js +5 -7
  33. package/lib/{utils.d.ts → common/utilities/utils.d.ts} +1 -1
  34. package/lib/{utils.js → common/utilities/utils.js} +18 -12
  35. package/lib/logger/common.d.ts +1 -3
  36. package/lib/logger/common.js +9 -14
  37. package/lib/logger/compat.js +9 -9
  38. package/lib/logger/index.d.ts +1 -1
  39. package/lib/logger/index.js +24 -30
  40. package/lib/{v2/params → params}/index.d.ts +22 -9
  41. package/lib/{v2/params → params}/index.js +22 -14
  42. package/lib/params/types.d.ts +180 -0
  43. package/lib/params/types.js +289 -0
  44. package/lib/runtime/loader.js +12 -14
  45. package/lib/runtime/manifest.d.ts +56 -24
  46. package/lib/runtime/manifest.js +114 -4
  47. package/lib/v1/cloud-functions.d.ts +232 -0
  48. package/lib/v1/cloud-functions.js +205 -0
  49. package/lib/v1/config.d.ts +8 -0
  50. package/lib/v1/config.js +75 -0
  51. package/lib/{function-builder.d.ts → v1/function-builder.d.ts} +16 -16
  52. package/lib/{function-builder.js → v1/function-builder.js} +56 -46
  53. package/lib/v1/function-configuration.d.ts +197 -0
  54. package/lib/v1/function-configuration.js +70 -0
  55. package/lib/v1/index.d.ts +20 -0
  56. package/lib/{index.js → v1/index.js} +5 -10
  57. package/lib/{providers → v1/providers}/analytics.d.ts +5 -11
  58. package/lib/{providers → v1/providers}/analytics.js +49 -43
  59. package/lib/{providers → v1/providers}/auth.d.ts +28 -18
  60. package/lib/{providers → v1/providers}/auth.js +45 -34
  61. package/lib/{providers → v1/providers}/database.d.ts +25 -42
  62. package/lib/{providers → v1/providers}/database.js +46 -46
  63. package/lib/{providers → v1/providers}/firestore.d.ts +15 -33
  64. package/lib/{providers → v1/providers}/firestore.js +40 -44
  65. package/lib/{providers → v1/providers}/https.d.ts +3 -8
  66. package/lib/{providers → v1/providers}/https.js +14 -22
  67. package/lib/{providers → v1/providers}/pubsub.d.ts +8 -16
  68. package/lib/{providers → v1/providers}/pubsub.js +22 -26
  69. package/lib/{providers → v1/providers}/remoteConfig.d.ts +2 -11
  70. package/lib/{providers → v1/providers}/remoteConfig.js +9 -9
  71. package/lib/{providers → v1/providers}/storage.d.ts +11 -26
  72. package/lib/{providers → v1/providers}/storage.js +24 -29
  73. package/lib/{providers → v1/providers}/tasks.d.ts +6 -8
  74. package/lib/{providers → v1/providers}/tasks.js +12 -17
  75. package/lib/{providers → v1/providers}/testLab.d.ts +86 -46
  76. package/lib/{providers → v1/providers}/testLab.js +14 -14
  77. package/lib/v2/core.d.ts +4 -5
  78. package/lib/v2/index.d.ts +16 -14
  79. package/lib/v2/index.js +5 -1
  80. package/lib/v2/options.d.ts +52 -32
  81. package/lib/v2/options.js +32 -47
  82. package/lib/v2/providers/alerts/alerts.d.ts +20 -18
  83. package/lib/v2/providers/alerts/alerts.js +9 -6
  84. package/lib/v2/providers/alerts/appDistribution.d.ts +28 -26
  85. package/lib/v2/providers/alerts/appDistribution.js +8 -7
  86. package/lib/v2/providers/alerts/billing.d.ts +5 -5
  87. package/lib/v2/providers/alerts/billing.js +5 -4
  88. package/lib/v2/providers/alerts/crashlytics.d.ts +32 -30
  89. package/lib/v2/providers/alerts/crashlytics.js +10 -9
  90. package/lib/v2/providers/alerts/index.d.ts +5 -5
  91. package/lib/v2/providers/alerts/performance.d.ts +3 -3
  92. package/lib/v2/providers/alerts/performance.js +5 -7
  93. package/lib/v2/providers/database.d.ts +41 -38
  94. package/lib/v2/providers/database.js +22 -17
  95. package/lib/v2/providers/eventarc.d.ts +25 -23
  96. package/lib/v2/providers/eventarc.js +10 -7
  97. package/lib/v2/providers/https.d.ts +43 -33
  98. package/lib/v2/providers/https.js +18 -56
  99. package/lib/v2/providers/identity.d.ts +25 -23
  100. package/lib/v2/providers/identity.js +10 -7
  101. package/lib/v2/providers/pubsub.d.ts +25 -23
  102. package/lib/v2/providers/pubsub.js +11 -27
  103. package/lib/v2/providers/remoteConfig.d.ts +63 -0
  104. package/lib/v2/providers/remoteConfig.js +65 -0
  105. package/lib/v2/providers/scheduler.d.ts +14 -12
  106. package/lib/v2/providers/scheduler.js +16 -14
  107. package/lib/v2/providers/storage.d.ts +32 -30
  108. package/lib/v2/providers/storage.js +16 -32
  109. package/lib/v2/providers/tasks.d.ts +30 -26
  110. package/lib/v2/providers/tasks.js +14 -31
  111. package/lib/v2/providers/testLab.d.ts +110 -0
  112. package/lib/v2/providers/testLab.js +65 -0
  113. package/lib/v2/trace.d.ts +4 -0
  114. package/lib/v2/trace.js +21 -0
  115. package/package.json +61 -66
  116. package/lib/apps.d.ts +0 -35
  117. package/lib/apps.js +0 -112
  118. package/lib/cloud-functions.d.ts +0 -231
  119. package/lib/cloud-functions.js +0 -251
  120. package/lib/config.d.ts +0 -24
  121. package/lib/config.js +0 -117
  122. package/lib/function-configuration.d.ts +0 -108
  123. package/lib/function-configuration.js +0 -71
  124. package/lib/handler-builder.d.ts +0 -256
  125. package/lib/handler-builder.js +0 -349
  126. package/lib/index.d.ts +0 -19
  127. package/lib/setup.d.ts +0 -1
  128. package/lib/setup.js +0 -60
  129. package/lib/v2/params/types.d.ts +0 -118
  130. package/lib/v2/params/types.js +0 -196
package/lib/apps.js DELETED
@@ -1,112 +0,0 @@
1
- "use strict";
2
- // The MIT License (MIT)
3
- //
4
- // Copyright (c) 2017 Firebase
5
- //
6
- // Permission is hereby granted, free of charge, to any person obtaining a copy
7
- // of this software and associated documentation files (the "Software"), to deal
8
- // in the Software without restriction, including without limitation the rights
9
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- // copies of the Software, and to permit persons to whom the Software is
11
- // furnished to do so, subject to the following conditions:
12
- //
13
- // The above copyright notice and this permission notice shall be included in all
14
- // copies or substantial portions of the Software.
15
- //
16
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- // SOFTWARE.
23
- Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.apps = void 0;
25
- const firebase = require("firebase-admin");
26
- const _ = require("lodash");
27
- const config_1 = require("./config");
28
- function apps() {
29
- if (typeof apps.singleton === 'undefined') {
30
- apps.init();
31
- }
32
- return apps.singleton;
33
- }
34
- exports.apps = apps;
35
- (function (apps) {
36
- /** @hidden */
37
- apps.garbageCollectionInterval = 2 * 60 * 1000;
38
- /** @hidden */
39
- function delay(delay) {
40
- return new Promise((resolve) => {
41
- setTimeout(resolve, delay);
42
- });
43
- }
44
- apps.delay = delay;
45
- apps.init = () => (apps.singleton = new Apps());
46
- class Apps {
47
- constructor() {
48
- this._refCounter = {};
49
- }
50
- _appAlive(appName) {
51
- try {
52
- const app = firebase.app(appName);
53
- return !_.get(app, 'isDeleted_');
54
- }
55
- catch (e) {
56
- return false;
57
- }
58
- }
59
- _destroyApp(appName) {
60
- if (!this._appAlive(appName)) {
61
- return;
62
- }
63
- firebase
64
- .app(appName)
65
- .delete()
66
- .catch(_.noop);
67
- }
68
- retain() {
69
- const increment = (n) => {
70
- return (n || 0) + 1;
71
- };
72
- // Increment counter for admin because function might use event.data.ref
73
- _.update(this._refCounter, '__admin__', increment);
74
- }
75
- release() {
76
- const decrement = (n) => {
77
- return n - 1;
78
- };
79
- return delay(apps.garbageCollectionInterval).then(() => {
80
- _.update(this._refCounter, '__admin__', decrement);
81
- _.forEach(this._refCounter, (count, key) => {
82
- if (count <= 0) {
83
- this._destroyApp(key);
84
- }
85
- });
86
- });
87
- }
88
- get admin() {
89
- if (this._emulatedAdminApp) {
90
- return this._emulatedAdminApp;
91
- }
92
- if (this._appAlive('__admin__')) {
93
- return firebase.app('__admin__');
94
- }
95
- return firebase.initializeApp(this.firebaseArgs, '__admin__');
96
- }
97
- /**
98
- * This function allows the Firebase Emulator Suite to override the FirebaseApp instance
99
- * used by the Firebase Functions SDK. Developers should never call this function for
100
- * other purposes.
101
- */
102
- setEmulatedAdminApp(app) {
103
- this._emulatedAdminApp = app;
104
- }
105
- get firebaseArgs() {
106
- return _.assign({}, (0, config_1.firebaseConfig)(), {
107
- credential: firebase.credential.applicationDefault(),
108
- });
109
- }
110
- }
111
- apps.Apps = Apps;
112
- })(apps = exports.apps || (exports.apps = {}));
@@ -1,231 +0,0 @@
1
- import { Request, Response } from 'express';
2
- import { DeploymentOptions, FailurePolicy, Schedule } from './function-configuration';
3
- export { Request, Response };
4
- import { Duration } from './common/encoding';
5
- import { ManifestEndpoint, ManifestRequiredAPI } from './runtime/manifest';
6
- export { Change } from './common/change';
7
- /**
8
- * @hidden
9
- *
10
- * Wire format for an event.
11
- */
12
- export interface Event {
13
- context: {
14
- eventId: string;
15
- timestamp: string;
16
- eventType: string;
17
- resource: Resource;
18
- domain?: string;
19
- };
20
- data: any;
21
- }
22
- /**
23
- * The context in which an event occurred.
24
- *
25
- * An EventContext describes:
26
- * - The time an event occurred.
27
- * - A unique identifier of the event.
28
- * - The resource on which the event occurred, if applicable.
29
- * - Authorization of the request that triggered the event, if applicable and
30
- * available.
31
- */
32
- export interface EventContext {
33
- /**
34
- * Authentication information for the user that triggered the function.
35
- * This object contains `uid` and `token` properties for authenticated users.
36
- * For more detail including token keys, see the
37
- * [security rules reference](/docs/firestore/reference/security/#properties).
38
- *
39
- * This field is only populated for Realtime Database triggers and Callable
40
- * functions. For an unauthenticated user, this field is null. For Firebase
41
- * admin users and event types that do not provide user information, this field
42
- * does not exist.
43
- */
44
- auth?: {
45
- token: object;
46
- uid: string;
47
- };
48
- /**
49
- * The level of permissions for a user. Valid values are:
50
- *
51
- * * `ADMIN` Developer user or user authenticated via a service account.
52
- * * `USER` Known user.
53
- * * `UNAUTHENTICATED` Unauthenticated action
54
- * * `null` For event types that do not provide user information (all except
55
- * Realtime Database).
56
- */
57
- authType?: 'ADMIN' | 'USER' | 'UNAUTHENTICATED';
58
- /**
59
- * The event’s unique identifier.
60
- */
61
- eventId: string;
62
- /**
63
- * Type of event. Possible values are:
64
- *
65
- * * `google.analytics.event.log`
66
- * * `google.firebase.auth.user.create`
67
- * * `google.firebase.auth.user.delete`
68
- * * `google.firebase.database.ref.write`
69
- * * `google.firebase.database.ref.create`
70
- * * `google.firebase.database.ref.update`
71
- * * `google.firebase.database.ref.delete`
72
- * * `google.firestore.document.write`
73
- * * `google.firestore.document.create`
74
- * * `google.firestore.document.update`
75
- * * `google.firestore.document.delete`
76
- * * `google.pubsub.topic.publish`
77
- * * `google.firebase.remoteconfig.update`
78
- * * `google.storage.object.finalize`
79
- * * `google.storage.object.archive`
80
- * * `google.storage.object.delete`
81
- * * `google.storage.object.metadataUpdate`
82
- * * `google.testing.testMatrix.complete`
83
- */
84
- eventType: string;
85
- /**
86
- * An object containing the values of the wildcards in the `path` parameter
87
- * provided to the [`ref()`](providers_database_.html#ref) method for a Realtime
88
- * Database trigger. Cannot be accessed while inside the handler namespace.
89
- */
90
- params: {
91
- [option: string]: any;
92
- };
93
- /**
94
- * The resource that emitted the event. Valid values are:
95
- *
96
- * * Analytics &mdash; `projects/<projectId>/events/<analyticsEventType>`
97
- * * Realtime Database &mdash;
98
- `projects/_/instances/<databaseInstance>/refs/<databasePath>`
99
- * * Storage &mdash;
100
- `projects/_/buckets/<bucketName>/objects/<fileName>#<generation>`
101
- * * Authentication &mdash; `projects/<projectId>`
102
- * * Pub/Sub &mdash; `projects/<projectId>/topics/<topicName>`
103
- *
104
- * Because Realtime Database instances and Cloud Storage buckets are globally
105
- * unique and not tied to the project, their resources start with `projects/_`.
106
- * Underscore is not a valid project name.
107
- */
108
- resource: Resource;
109
- /**
110
- * Timestamp for the event as an
111
- * [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) string.
112
- */
113
- timestamp: string;
114
- }
115
- /**
116
- * Resource is a standard format for defining a resource
117
- * (google.rpc.context.AttributeContext.Resource). In Cloud Functions, it is the
118
- * resource that triggered the function - such as a storage bucket.
119
- */
120
- export interface Resource {
121
- service: string;
122
- name: string;
123
- type?: string;
124
- labels?: {
125
- [tag: string]: string;
126
- };
127
- }
128
- /**
129
- * TriggerAnnotion is used internally by the firebase CLI to understand what
130
- * type of Cloud Function to deploy.
131
- */
132
- interface TriggerAnnotation {
133
- availableMemoryMb?: number;
134
- blockingTrigger?: {
135
- eventType: string;
136
- options?: Record<string, unknown>;
137
- };
138
- eventTrigger?: {
139
- eventType: string;
140
- resource: string;
141
- service: string;
142
- };
143
- failurePolicy?: FailurePolicy;
144
- httpsTrigger?: {
145
- invoker?: string[];
146
- };
147
- labels?: {
148
- [key: string]: string;
149
- };
150
- regions?: string[];
151
- schedule?: Schedule;
152
- timeout?: Duration;
153
- vpcConnector?: string;
154
- vpcConnectorEgressSettings?: string;
155
- serviceAccountEmail?: string;
156
- ingressSettings?: string;
157
- secrets?: string[];
158
- }
159
- /**
160
- * A Runnable has a `run` method which directly invokes the user-defined
161
- * function - useful for unit testing.
162
- */
163
- export interface Runnable<T> {
164
- run: (data: T, context: any) => PromiseLike<any> | any;
165
- }
166
- /**
167
- * The Cloud Function type for HTTPS triggers. This should be exported from your
168
- * JavaScript file to define a Cloud Function.
169
- *
170
- * This type is a special JavaScript function which takes Express
171
- * [`Request`](https://expressjs.com/en/api.html#req) and
172
- * [`Response`](https://expressjs.com/en/api.html#res) objects as its only
173
- * arguments.
174
- */
175
- export interface HttpsFunction {
176
- (req: Request, resp: Response): void | Promise<void>;
177
- /** @alpha */
178
- __trigger: TriggerAnnotation;
179
- /** @alpha */
180
- __endpoint: ManifestEndpoint;
181
- /** @alpha */
182
- __requiredAPIs?: ManifestRequiredAPI[];
183
- }
184
- /**
185
- * The Cloud Function type for Blocking triggers.
186
- */
187
- export interface BlockingFunction {
188
- (req: Request, resp: Response): void | Promise<void>;
189
- /** @alpha */
190
- __trigger: TriggerAnnotation;
191
- /** @alpha */
192
- __endpoint: ManifestEndpoint;
193
- /** @alpha */
194
- __requiredAPIs?: ManifestRequiredAPI[];
195
- }
196
- /**
197
- * The Cloud Function type for all non-HTTPS triggers. This should be exported
198
- * from your JavaScript file to define a Cloud Function.
199
- *
200
- * This type is a special JavaScript function which takes a templated
201
- * `Event` object as its only argument.
202
- */
203
- export interface CloudFunction<T> extends Runnable<T> {
204
- (input: any, context?: any): PromiseLike<any> | any;
205
- /** @alpha */
206
- __trigger: TriggerAnnotation;
207
- /** @alpha */
208
- __endpoint: ManifestEndpoint;
209
- /** @alpha */
210
- __requiredAPIs?: ManifestRequiredAPI[];
211
- }
212
- /** @hidden */
213
- export interface MakeCloudFunctionArgs<EventData> {
214
- after?: (raw: Event) => void;
215
- before?: (raw: Event) => void;
216
- contextOnlyHandler?: (context: EventContext) => PromiseLike<any> | any;
217
- dataConstructor?: (raw: Event) => EventData;
218
- eventType: string;
219
- handler?: (data: EventData, context: EventContext) => PromiseLike<any> | any;
220
- labels?: Record<string, string>;
221
- legacyEventType?: string;
222
- options?: DeploymentOptions;
223
- provider: string;
224
- service: string;
225
- triggerResource: () => string;
226
- }
227
- /** @hidden */
228
- export declare function makeCloudFunction<EventData>({ after, before, contextOnlyHandler, dataConstructor, eventType, handler, labels, legacyEventType, options, provider, service, triggerResource, }: MakeCloudFunctionArgs<EventData>): CloudFunction<EventData>;
229
- /** @hidden */
230
- export declare function optionsToTrigger(options: DeploymentOptions): any;
231
- export declare function optionsToEndpoint(options: DeploymentOptions): ManifestEndpoint;
@@ -1,251 +0,0 @@
1
- "use strict";
2
- // The MIT License (MIT)
3
- //
4
- // Copyright (c) 2017 Firebase
5
- //
6
- // Permission is hereby granted, free of charge, to any person obtaining a copy
7
- // of this software and associated documentation files (the "Software"), to deal
8
- // in the Software without restriction, including without limitation the rights
9
- // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- // copies of the Software, and to permit persons to whom the Software is
11
- // furnished to do so, subject to the following conditions:
12
- //
13
- // The above copyright notice and this permission notice shall be included in all
14
- // copies or substantial portions of the Software.
15
- //
16
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- // SOFTWARE.
23
- Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.optionsToEndpoint = exports.optionsToTrigger = exports.makeCloudFunction = exports.Change = void 0;
25
- const _ = require("lodash");
26
- const function_configuration_1 = require("./function-configuration");
27
- const logger_1 = require("./logger");
28
- const encoding_1 = require("./common/encoding");
29
- var change_1 = require("./common/change");
30
- Object.defineProperty(exports, "Change", { enumerable: true, get: function () { return change_1.Change; } });
31
- /** @hidden */
32
- const WILDCARD_REGEX = new RegExp('{[^/{}]*}', 'g');
33
- /** @hidden */
34
- function makeCloudFunction({ after = () => { }, before = () => { }, contextOnlyHandler, dataConstructor = (raw) => raw.data, eventType, handler, labels = {}, legacyEventType, options = {}, provider, service, triggerResource, }) {
35
- const cloudFunction = (data, context) => {
36
- if (legacyEventType && context.eventType === legacyEventType) {
37
- /*
38
- * v1beta1 event flow has different format for context, transform them to
39
- * new format.
40
- */
41
- context.eventType = provider + '.' + eventType;
42
- context.resource = {
43
- service,
44
- name: context.resource,
45
- };
46
- }
47
- const event = {
48
- data,
49
- context,
50
- };
51
- if (provider === 'google.firebase.database') {
52
- context.authType = _detectAuthType(event);
53
- if (context.authType !== 'ADMIN') {
54
- context.auth = _makeAuth(event, context.authType);
55
- }
56
- else {
57
- delete context.auth;
58
- }
59
- }
60
- if (triggerResource() == null) {
61
- Object.defineProperty(context, 'params', {
62
- get: () => {
63
- throw new Error('context.params is not available when using the handler namespace.');
64
- },
65
- });
66
- }
67
- else {
68
- context.params = context.params || _makeParams(context, triggerResource);
69
- }
70
- before(event);
71
- let promise;
72
- if (labels && labels['deployment-scheduled']) {
73
- // Scheduled function do not have meaningful data, so exclude it
74
- promise = contextOnlyHandler(context);
75
- }
76
- else {
77
- const dataOrChange = dataConstructor(event);
78
- promise = handler(dataOrChange, context);
79
- }
80
- if (typeof promise === 'undefined') {
81
- (0, logger_1.warn)('Function returned undefined, expected Promise or value');
82
- }
83
- return Promise.resolve(promise)
84
- .then((result) => {
85
- after(event);
86
- return result;
87
- })
88
- .catch((err) => {
89
- after(event);
90
- return Promise.reject(err);
91
- });
92
- };
93
- Object.defineProperty(cloudFunction, '__trigger', {
94
- get: () => {
95
- if (triggerResource() == null) {
96
- return {};
97
- }
98
- const trigger = _.assign(optionsToTrigger(options), {
99
- eventTrigger: {
100
- resource: triggerResource(),
101
- eventType: legacyEventType || provider + '.' + eventType,
102
- service,
103
- },
104
- });
105
- if (!_.isEmpty(labels)) {
106
- trigger.labels = { ...trigger.labels, ...labels };
107
- }
108
- return trigger;
109
- },
110
- });
111
- Object.defineProperty(cloudFunction, '__endpoint', {
112
- get: () => {
113
- if (triggerResource() == null) {
114
- return undefined;
115
- }
116
- const endpoint = {
117
- platform: 'gcfv1',
118
- ...optionsToEndpoint(options),
119
- };
120
- if (options.schedule) {
121
- endpoint.scheduleTrigger = options.schedule;
122
- }
123
- else {
124
- endpoint.eventTrigger = {
125
- eventType: legacyEventType || provider + '.' + eventType,
126
- eventFilters: {
127
- resource: triggerResource(),
128
- },
129
- retry: !!options.failurePolicy,
130
- };
131
- }
132
- // Note: We intentionally don't make use of labels args here.
133
- // labels is used to pass SDK-defined labels to the trigger, which isn't
134
- // something we will do in the container contract world.
135
- endpoint.labels = { ...endpoint.labels };
136
- return endpoint;
137
- },
138
- });
139
- if (options.schedule) {
140
- cloudFunction.__requiredAPIs = [
141
- {
142
- api: 'cloudscheduler.googleapis.com',
143
- reason: 'Needed for scheduled functions.',
144
- },
145
- ];
146
- }
147
- cloudFunction.run = handler || contextOnlyHandler;
148
- return cloudFunction;
149
- }
150
- exports.makeCloudFunction = makeCloudFunction;
151
- /** @hidden */
152
- function _makeParams(context, triggerResourceGetter) {
153
- if (context.params) {
154
- // In unit testing, user may directly provide `context.params`.
155
- return context.params;
156
- }
157
- if (!context.resource) {
158
- // In unit testing, `resource` may be unpopulated for a test event.
159
- return {};
160
- }
161
- const triggerResource = triggerResourceGetter();
162
- const wildcards = triggerResource.match(WILDCARD_REGEX);
163
- const params = {};
164
- if (wildcards) {
165
- const triggerResourceParts = _.split(triggerResource, '/');
166
- const eventResourceParts = _.split(context.resource.name, '/');
167
- _.forEach(wildcards, (wildcard) => {
168
- const wildcardNoBraces = wildcard.slice(1, -1);
169
- const position = _.indexOf(triggerResourceParts, wildcard);
170
- params[wildcardNoBraces] = eventResourceParts[position];
171
- });
172
- }
173
- return params;
174
- }
175
- /** @hidden */
176
- function _makeAuth(event, authType) {
177
- if (authType === 'UNAUTHENTICATED') {
178
- return null;
179
- }
180
- return {
181
- uid: _.get(event, 'context.auth.variable.uid'),
182
- token: _.get(event, 'context.auth.variable.token'),
183
- };
184
- }
185
- /** @hidden */
186
- function _detectAuthType(event) {
187
- if (_.get(event, 'context.auth.admin')) {
188
- return 'ADMIN';
189
- }
190
- if (_.has(event, 'context.auth.variable')) {
191
- return 'USER';
192
- }
193
- return 'UNAUTHENTICATED';
194
- }
195
- /** @hidden */
196
- function optionsToTrigger(options) {
197
- const trigger = {};
198
- (0, encoding_1.copyIfPresent)(trigger, options, 'regions', 'schedule', 'minInstances', 'maxInstances', 'ingressSettings', 'vpcConnectorEgressSettings', 'vpcConnector', 'labels', 'secrets');
199
- (0, encoding_1.convertIfPresent)(trigger, options, 'failurePolicy', 'failurePolicy', (policy) => {
200
- if (policy === false) {
201
- return undefined;
202
- }
203
- else if (policy === true) {
204
- return function_configuration_1.DEFAULT_FAILURE_POLICY;
205
- }
206
- else {
207
- return policy;
208
- }
209
- });
210
- (0, encoding_1.convertIfPresent)(trigger, options, 'timeout', 'timeoutSeconds', encoding_1.durationFromSeconds);
211
- (0, encoding_1.convertIfPresent)(trigger, options, 'availableMemoryMb', 'memory', (mem) => {
212
- const memoryLookup = {
213
- '128MB': 128,
214
- '256MB': 256,
215
- '512MB': 512,
216
- '1GB': 1024,
217
- '2GB': 2048,
218
- '4GB': 4096,
219
- '8GB': 8192,
220
- };
221
- return memoryLookup[mem];
222
- });
223
- (0, encoding_1.convertIfPresent)(trigger, options, 'serviceAccountEmail', 'serviceAccount', encoding_1.serviceAccountFromShorthand);
224
- return trigger;
225
- }
226
- exports.optionsToTrigger = optionsToTrigger;
227
- function optionsToEndpoint(options) {
228
- const endpoint = {};
229
- (0, encoding_1.copyIfPresent)(endpoint, options, 'minInstances', 'maxInstances', 'ingressSettings', 'labels', 'timeoutSeconds');
230
- (0, encoding_1.convertIfPresent)(endpoint, options, 'region', 'regions');
231
- (0, encoding_1.convertIfPresent)(endpoint, options, 'serviceAccountEmail', 'serviceAccount', (sa) => sa);
232
- (0, encoding_1.convertIfPresent)(endpoint, options, 'secretEnvironmentVariables', 'secrets', (secrets) => secrets.map((secret) => ({ key: secret })));
233
- if (options === null || options === void 0 ? void 0 : options.vpcConnector) {
234
- endpoint.vpc = { connector: options.vpcConnector };
235
- (0, encoding_1.convertIfPresent)(endpoint.vpc, options, 'egressSettings', 'vpcConnectorEgressSettings');
236
- }
237
- (0, encoding_1.convertIfPresent)(endpoint, options, 'availableMemoryMb', 'memory', (mem) => {
238
- const memoryLookup = {
239
- '128MB': 128,
240
- '256MB': 256,
241
- '512MB': 512,
242
- '1GB': 1024,
243
- '2GB': 2048,
244
- '4GB': 4096,
245
- '8GB': 8192,
246
- };
247
- return memoryLookup[mem];
248
- });
249
- return endpoint;
250
- }
251
- exports.optionsToEndpoint = optionsToEndpoint;
package/lib/config.d.ts DELETED
@@ -1,24 +0,0 @@
1
- import * as firebase from 'firebase-admin';
2
- export declare function config(): config.Config;
3
- /**
4
- * Store and retrieve project configuration data such as third-party API
5
- * keys or other settings. You can set configuration values using the
6
- * Firebase CLI as described in
7
- * [Environment Configuration](/docs/functions/config-env).
8
- */
9
- export declare namespace config {
10
- /**
11
- * The Functions configuration interface.
12
- *
13
- * Access via `functions.config()`.
14
- */
15
- interface Config {
16
- [key: string]: any;
17
- }
18
- /** @hidden */
19
- let singleton: config.Config;
20
- }
21
- /** @hidden */
22
- export declare let firebaseConfigCache: firebase.AppOptions | null;
23
- /** @hidden */
24
- export declare function firebaseConfig(): firebase.AppOptions | null;