firebase-functions 4.7.0 → 4.8.1

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,7 @@
1
+ /**
2
+ * Registers a callback that should be run when in a production environment
3
+ * before executing any functions code.
4
+ * Calling this function more than once leads to undefined behavior.
5
+ * @param callback initialization callback to be run before any function executes.
6
+ */
7
+ export declare function onInit(callback: () => unknown): void;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.withInit = exports.onInit = void 0;
4
+ const logger = require("../logger");
5
+ let initCallback = null;
6
+ let didInit = false;
7
+ /**
8
+ * Registers a callback that should be run when in a production environment
9
+ * before executing any functions code.
10
+ * Calling this function more than once leads to undefined behavior.
11
+ * @param callback initialization callback to be run before any function executes.
12
+ */
13
+ function onInit(callback) {
14
+ if (initCallback) {
15
+ logger.warn("Setting onInit callback more than once. Only the most recent callback will be called");
16
+ }
17
+ initCallback = callback;
18
+ didInit = false;
19
+ }
20
+ exports.onInit = onInit;
21
+ /** @internal */
22
+ function withInit(func) {
23
+ return async (...args) => {
24
+ if (!didInit) {
25
+ if (initCallback) {
26
+ await initCallback();
27
+ }
28
+ didInit = true;
29
+ }
30
+ // Note: This cast is actually inaccurate because it may be a promise, but
31
+ // it doesn't actually matter because the async function will promisify
32
+ // non-promises and forward promises.
33
+ return func(...args);
34
+ };
35
+ }
36
+ exports.withInit = withInit;
@@ -1,3 +1,4 @@
1
+ import { Expression } from "../params";
1
2
  /**
2
3
  * A type that splits literal string S with delimiter D.
3
4
  *
@@ -27,6 +28,6 @@ export type Extract<Part extends string> = Part extends `{${infer Param}=**}` ?
27
28
  *
28
29
  * For flexibility reasons, ParamsOf<string> is Record<string, string>
29
30
  */
30
- export type ParamsOf<PathPattern extends string> = string extends PathPattern ? Record<string, string> : {
31
- [Key in Extract<Split<NullSafe<PathPattern>, "/">[number]>]: string;
31
+ export type ParamsOf<PathPattern extends string | Expression<string>> = PathPattern extends Expression<string> ? Record<string, string> : string extends PathPattern ? Record<string, string> : {
32
+ [Key in Extract<Split<NullSafe<Exclude<PathPattern, Expression<string>>>, "/">[number]>]: string;
32
33
  };
@@ -8,65 +8,65 @@ export { ParamOptions, Expression };
8
8
  type SecretOrExpr = Param<any> | SecretParam;
9
9
  export declare const declaredParams: SecretOrExpr[];
10
10
  /**
11
- * A builtin param that resolves to the default RTDB database URL associated
11
+ * A built-in parameter that resolves to the default RTDB database URL associated
12
12
  * with the project, without prompting the deployer. Empty string if none exists.
13
13
  */
14
14
  export declare const databaseURL: Param<string>;
15
15
  /**
16
- * A builtin param that resolves to the Cloud project ID associated with
16
+ * A built-in parameter that resolves to the Cloud project ID associated with
17
17
  * the project, without prompting the deployer.
18
18
  */
19
19
  export declare const projectID: Param<string>;
20
20
  /**
21
- * A builtin param that resolves to the Cloud project ID, without prompting
21
+ * A built-in parameter that resolves to the Cloud project ID, without prompting
22
22
  * the deployer.
23
23
  */
24
24
  export declare const gcloudProject: Param<string>;
25
25
  /**
26
- * A builtin param that resolves to the Cloud storage bucket associated
26
+ * A builtin parameter that resolves to the Cloud storage bucket associated
27
27
  * with the function, without prompting the deployer. Empty string if not
28
28
  * defined.
29
29
  */
30
30
  export declare const storageBucket: Param<string>;
31
31
  /**
32
32
  * Declares a secret param, that will persist values only in Cloud Secret Manager.
33
- * Secrets are stored interally as bytestrings. Use ParamOptions.`as` to provide type
33
+ * Secrets are stored interally as bytestrings. Use `ParamOptions.as` to provide type
34
34
  * hinting during parameter resolution.
35
35
  *
36
- * @param name The name of the environment variable to use to load the param.
37
- * @param options Configuration options for the param.
38
- * @returns A Param with a `string` return type for `.value`.
36
+ * @param name The name of the environment variable to use to load the parameter.
37
+ * @param options Configuration options for the parameter.
38
+ * @returns A parameter with a `string` return type for `.value`.
39
39
  */
40
40
  export declare function defineSecret(name: string): SecretParam;
41
41
  /**
42
- * Declare a string param.
42
+ * Declare a string parameter.
43
43
  *
44
- * @param name The name of the environment variable to use to load the param.
45
- * @param options Configuration options for the param.
46
- * @returns A Param with a `string` return type for `.value`.
44
+ * @param name The name of the environment variable to use to load the parameter.
45
+ * @param options Configuration options for the parameter.
46
+ * @returns A parameter with a `string` return type for `.value`.
47
47
  */
48
48
  export declare function defineString(name: string, options?: ParamOptions<string>): StringParam;
49
49
  /**
50
- * Declare a boolean param.
50
+ * Declare a boolean parameter.
51
51
  *
52
- * @param name The name of the environment variable to use to load the param.
53
- * @param options Configuration options for the param.
54
- * @returns A Param with a `boolean` return type for `.value`.
52
+ * @param name The name of the environment variable to use to load the parameter.
53
+ * @param options Configuration options for the parameter.
54
+ * @returns A parameter with a `boolean` return type for `.value`.
55
55
  */
56
56
  export declare function defineBoolean(name: string, options?: ParamOptions<boolean>): BooleanParam;
57
57
  /**
58
- * Declare an integer param.
58
+ * Declare an integer parameter.
59
59
  *
60
- * @param name The name of the environment variable to use to load the param.
61
- * @param options Configuration options for the param.
62
- * @returns A Param with a `number` return type for `.value`.
60
+ * @param name The name of the environment variable to use to load the parameter.
61
+ * @param options Configuration options for the parameter.
62
+ * @returns A parameter with a `number` return type for `.value`.
63
63
  */
64
64
  export declare function defineInt(name: string, options?: ParamOptions<number>): IntParam;
65
65
  /**
66
- * Declare a list param.
66
+ * Declare a list parameter.
67
67
  *
68
- * @param name The name of the environment variable to use to load the param.
69
- * @param options Configuration options for the param.
70
- * @returns A Param with a `string[]` return type for `.value`.
68
+ * @param name The name of the environment variable to use to load the parameter.
69
+ * @param options Configuration options for the parameter.
70
+ * @returns A parameter with a `string[]` return type for `.value`.
71
71
  */
72
72
  export declare function defineList(name: string, options?: ParamOptions<string[]>): ListParam;
@@ -34,7 +34,7 @@ Object.defineProperty(exports, "select", { enumerable: true, get: function () {
34
34
  Object.defineProperty(exports, "multiSelect", { enumerable: true, get: function () { return types_2.multiSelect; } });
35
35
  exports.declaredParams = [];
36
36
  /**
37
- * Use a helper to manage the list such that params are uniquely
37
+ * Use a helper to manage the list such that parameters are uniquely
38
38
  * registered once only but order is preserved.
39
39
  * @internal
40
40
  */
@@ -55,34 +55,34 @@ function clearParams() {
55
55
  }
56
56
  exports.clearParams = clearParams;
57
57
  /**
58
- * A builtin param that resolves to the default RTDB database URL associated
58
+ * A built-in parameter that resolves to the default RTDB database URL associated
59
59
  * with the project, without prompting the deployer. Empty string if none exists.
60
60
  */
61
61
  exports.databaseURL = new types_1.InternalExpression("DATABASE_URL", (env) => { var _a; return ((_a = JSON.parse(env.FIREBASE_CONFIG)) === null || _a === void 0 ? void 0 : _a.databaseURL) || ""; });
62
62
  /**
63
- * A builtin param that resolves to the Cloud project ID associated with
63
+ * A built-in parameter that resolves to the Cloud project ID associated with
64
64
  * the project, without prompting the deployer.
65
65
  */
66
66
  exports.projectID = new types_1.InternalExpression("PROJECT_ID", (env) => { var _a; return ((_a = JSON.parse(env.FIREBASE_CONFIG)) === null || _a === void 0 ? void 0 : _a.projectId) || ""; });
67
67
  /**
68
- * A builtin param that resolves to the Cloud project ID, without prompting
68
+ * A built-in parameter that resolves to the Cloud project ID, without prompting
69
69
  * the deployer.
70
70
  */
71
71
  exports.gcloudProject = new types_1.InternalExpression("GCLOUD_PROJECT", (env) => { var _a; return ((_a = JSON.parse(env.FIREBASE_CONFIG)) === null || _a === void 0 ? void 0 : _a.projectId) || ""; });
72
72
  /**
73
- * A builtin param that resolves to the Cloud storage bucket associated
73
+ * A builtin parameter that resolves to the Cloud storage bucket associated
74
74
  * with the function, without prompting the deployer. Empty string if not
75
75
  * defined.
76
76
  */
77
77
  exports.storageBucket = new types_1.InternalExpression("STORAGE_BUCKET", (env) => { var _a; return ((_a = JSON.parse(env.FIREBASE_CONFIG)) === null || _a === void 0 ? void 0 : _a.storageBucket) || ""; });
78
78
  /**
79
79
  * Declares a secret param, that will persist values only in Cloud Secret Manager.
80
- * Secrets are stored interally as bytestrings. Use ParamOptions.`as` to provide type
80
+ * Secrets are stored interally as bytestrings. Use `ParamOptions.as` to provide type
81
81
  * hinting during parameter resolution.
82
82
  *
83
- * @param name The name of the environment variable to use to load the param.
84
- * @param options Configuration options for the param.
85
- * @returns A Param with a `string` return type for `.value`.
83
+ * @param name The name of the environment variable to use to load the parameter.
84
+ * @param options Configuration options for the parameter.
85
+ * @returns A parameter with a `string` return type for `.value`.
86
86
  */
87
87
  function defineSecret(name) {
88
88
  const param = new types_1.SecretParam(name);
@@ -91,11 +91,11 @@ function defineSecret(name) {
91
91
  }
92
92
  exports.defineSecret = defineSecret;
93
93
  /**
94
- * Declare a string param.
94
+ * Declare a string parameter.
95
95
  *
96
- * @param name The name of the environment variable to use to load the param.
97
- * @param options Configuration options for the param.
98
- * @returns A Param with a `string` return type for `.value`.
96
+ * @param name The name of the environment variable to use to load the parameter.
97
+ * @param options Configuration options for the parameter.
98
+ * @returns A parameter with a `string` return type for `.value`.
99
99
  */
100
100
  function defineString(name, options = {}) {
101
101
  const param = new types_1.StringParam(name, options);
@@ -104,11 +104,11 @@ function defineString(name, options = {}) {
104
104
  }
105
105
  exports.defineString = defineString;
106
106
  /**
107
- * Declare a boolean param.
107
+ * Declare a boolean parameter.
108
108
  *
109
- * @param name The name of the environment variable to use to load the param.
110
- * @param options Configuration options for the param.
111
- * @returns A Param with a `boolean` return type for `.value`.
109
+ * @param name The name of the environment variable to use to load the parameter.
110
+ * @param options Configuration options for the parameter.
111
+ * @returns A parameter with a `boolean` return type for `.value`.
112
112
  */
113
113
  function defineBoolean(name, options = {}) {
114
114
  const param = new types_1.BooleanParam(name, options);
@@ -117,11 +117,11 @@ function defineBoolean(name, options = {}) {
117
117
  }
118
118
  exports.defineBoolean = defineBoolean;
119
119
  /**
120
- * Declare an integer param.
120
+ * Declare an integer parameter.
121
121
  *
122
- * @param name The name of the environment variable to use to load the param.
123
- * @param options Configuration options for the param.
124
- * @returns A Param with a `number` return type for `.value`.
122
+ * @param name The name of the environment variable to use to load the parameter.
123
+ * @param options Configuration options for the parameter.
124
+ * @returns A parameter with a `number` return type for `.value`.
125
125
  */
126
126
  function defineInt(name, options = {}) {
127
127
  const param = new types_1.IntParam(name, options);
@@ -130,11 +130,11 @@ function defineInt(name, options = {}) {
130
130
  }
131
131
  exports.defineInt = defineInt;
132
132
  /**
133
- * Declare a float param.
133
+ * Declare a float parameter.
134
134
  *
135
- * @param name The name of the environment variable to use to load the param.
136
- * @param options Configuration options for the param.
137
- * @returns A Param with a `number` return type for `.value`.
135
+ * @param name The name of the environment variable to use to load the parameter.
136
+ * @param options Configuration options for the parameter.
137
+ * @returns A parameter with a `number` return type for `.value`.
138
138
  *
139
139
  * @internal
140
140
  */
@@ -145,11 +145,11 @@ function defineFloat(name, options = {}) {
145
145
  }
146
146
  exports.defineFloat = defineFloat;
147
147
  /**
148
- * Declare a list param.
148
+ * Declare a list parameter.
149
149
  *
150
- * @param name The name of the environment variable to use to load the param.
151
- * @param options Configuration options for the param.
152
- * @returns A Param with a `string[]` return type for `.value`.
150
+ * @param name The name of the environment variable to use to load the parameter.
151
+ * @param options Configuration options for the parameter.
152
+ * @returns A parameter with a `string[]` return type for `.value`.
153
153
  */
154
154
  function defineList(name, options = {}) {
155
155
  const param = new types_1.ListParam(name, options);
@@ -1,8 +1,9 @@
1
1
  export declare abstract class Expression<T extends string | number | boolean | string[]> {
2
- /** Returns the Expression's runtime value, based on the CLI's resolution of params. */
2
+ /** Returns the expression's runtime value, based on the CLI's resolution of parameters. */
3
3
  value(): T;
4
- /** Returns the Expression's representation as a braced CEL expression. */
4
+ /** Returns the expression's representation as a braced CEL expression. */
5
5
  toCEL(): string;
6
+ /** Returns the expression's representation as JSON. */
6
7
  toJSON(): string;
7
8
  }
8
9
  /**
@@ -25,7 +26,7 @@ export declare class CompareExpression<T extends string | number | boolean | str
25
26
  rhs: T | Expression<T>;
26
27
  constructor(cmp: "==" | "!=" | ">" | ">=" | "<" | "<=", lhs: Expression<T>, rhs: T | Expression<T>);
27
28
  toString(): string;
28
- /** Returns a TernaryExpression which can resolve to one of two values, based on the resolution of this comparison. */
29
+ /** Returns a `TernaryExpression` which can resolve to one of two values, based on the resolution of this comparison. */
29
30
  thenElse<retT extends string | number | boolean | string[]>(ifTrue: retT | Expression<retT>, ifFalse: retT | Expression<retT>): TernaryExpression<retT>;
30
31
  }
31
32
  /** @hidden */
@@ -40,8 +41,8 @@ export declare function multiSelect(options: string[]): MultiSelectInput;
40
41
  export declare function multiSelect(options: Record<string, string>): MultiSelectInput;
41
42
  type ParamInput<T> = TextInput<T> | SelectInput<T> | (T extends string[] ? MultiSelectInput : never) | (T extends string ? ResourceInput : never);
42
43
  /**
43
- * Specifies that a Param's value should be determined by prompting the user
44
- * to type it in interactively at deploy-time. Input that does not match the
44
+ * Specifies that a parameter's value should be determined by prompting the user
45
+ * to type it in interactively at deploy time. Input that does not match the
45
46
  * provided validationRegex, if present, will be retried.
46
47
  */
47
48
  export interface TextInput<T = unknown> {
@@ -61,7 +62,7 @@ export interface TextInput<T = unknown> {
61
62
  };
62
63
  }
63
64
  /**
64
- * Specifies that a Param's value should be determined by having the user
65
+ * Specifies that a parameter's value should be determined by having the user
65
66
  * select from a list containing all the project's resources of a certain
66
67
  * type. Currently, only type:"storage.googleapis.com/Bucket" is supported.
67
68
  */
@@ -70,10 +71,13 @@ export interface ResourceInput {
70
71
  type: "storage.googleapis.com/Bucket";
71
72
  };
72
73
  }
74
+ /**
75
+ * Autogenerate a list of buckets in a project that a user can select from.
76
+ */
73
77
  export declare const BUCKET_PICKER: ResourceInput;
74
78
  /**
75
- * Specifies that a Param's value should be determined by having the user select
76
- * from a list of pre-canned options interactively at deploy-time.
79
+ * Specifies that a parameter's value should be determined by having the user select
80
+ * from a list of pre-canned options interactively at deploy time.
77
81
  */
78
82
  export interface SelectInput<T = unknown> {
79
83
  select: {
@@ -81,9 +85,9 @@ export interface SelectInput<T = unknown> {
81
85
  };
82
86
  }
83
87
  /**
84
- * Specifies that a Param's value should be determined by having the user select
85
- * a subset from a list of pre-canned options interactively at deploy-time.
86
- * Will result in errors if used on Params of type other than string[].
88
+ * Specifies that a parameter's value should be determined by having the user select
89
+ * a subset from a list of pre-canned options interactively at deploy time.
90
+ * Will result in errors if used on parameters of type other than `string[]`.
87
91
  */
88
92
  export interface MultiSelectInput {
89
93
  multiSelect: {
@@ -91,24 +95,24 @@ export interface MultiSelectInput {
91
95
  };
92
96
  }
93
97
  /**
94
- * One of the options provided to a SelectInput, containing a value and
98
+ * One of the options provided to a `SelectInput`, containing a value and
95
99
  * optionally a human-readable label to display in the selection interface.
96
100
  */
97
101
  export interface SelectOptions<T = unknown> {
98
102
  label?: string;
99
103
  value: T;
100
104
  }
101
- /** The wire representation of a Param when it's sent to the CLI. A superset of ParamOptions. */
105
+ /** The wire representation of a parameter when it's sent to the CLI. A superset of `ParamOptions`. */
102
106
  export type ParamSpec<T extends string | number | boolean | string[]> = {
103
107
  /** The name of the parameter which will be stored in .env files. Use UPPERCASE. */
104
108
  name: string;
105
109
  /** An optional default value to be used while prompting for input. Can be a literal or another parametrized expression. */
106
110
  default?: T | Expression<T>;
107
- /** An optional human-readable string to be used as a replacement for the Param's name when prompting. */
111
+ /** An optional human-readable string to be used as a replacement for the parameter's name when prompting. */
108
112
  label?: string;
109
- /** An optional long-form description of the Param to be displayed while prompting. */
113
+ /** An optional long-form description of the parameter to be displayed while prompting. */
110
114
  description?: string;
111
- /** The way in which the Firebase CLI will prompt for the value of this Param. Defaults to a TextInput. */
115
+ /** The way in which the Firebase CLI will prompt for the value of this parameter. Defaults to a TextInput. */
112
116
  input?: ParamInput<T>;
113
117
  };
114
118
  /**
@@ -127,7 +131,7 @@ export type WireParamSpec<T extends string | number | boolean | string[]> = {
127
131
  type: ParamValueType;
128
132
  input?: ParamInput<T>;
129
133
  };
130
- /** Configuration options which can be used to customize the prompting behavior of a Param. */
134
+ /** Configuration options which can be used to customize the prompting behavior of a parameter. */
131
135
  export type ParamOptions<T extends string | number | boolean | string[]> = Omit<ParamSpec<T>, "name" | "type">;
132
136
  /**
133
137
  * Represents a parametrized value that will be read from .env files if present,
@@ -139,22 +143,22 @@ export declare abstract class Param<T extends string | number | boolean | string
139
143
  readonly options: ParamOptions<T>;
140
144
  static type: ParamValueType;
141
145
  constructor(name: string, options?: ParamOptions<T>);
142
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
146
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
143
147
  cmp(cmp: "==" | "!=" | ">" | ">=" | "<" | "<=", rhs: T | Expression<T>): CompareExpression<T>;
144
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
148
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
145
149
  equals(rhs: T | Expression<T>): CompareExpression<T>;
146
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
150
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
147
151
  notEquals(rhs: T | Expression<T>): CompareExpression<T>;
148
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
152
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
149
153
  greaterThan(rhs: T | Expression<T>): CompareExpression<T>;
150
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
154
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
151
155
  greaterThanOrEqualTo(rhs: T | Expression<T>): CompareExpression<T>;
152
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
156
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
153
157
  lessThan(rhs: T | Expression<T>): CompareExpression<T>;
154
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
158
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
155
159
  lessThanOrEqualTo(rhs: T | Expression<T>): CompareExpression<T>;
156
160
  /**
157
- * Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression.
161
+ * Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression.
158
162
  * @deprecated A typo. Use lessThanOrEqualTo instead.
159
163
  */
160
164
  lessThanorEqualTo(rhs: T | Expression<T>): CompareExpression<T>;
@@ -29,7 +29,7 @@ const logger = require("../logger");
29
29
  * an Expression<number> as the value of an option that normally accepts numbers.
30
30
  */
31
31
  class Expression {
32
- /** Returns the Expression's runtime value, based on the CLI's resolution of params. */
32
+ /** Returns the expression's runtime value, based on the CLI's resolution of parameters. */
33
33
  value() {
34
34
  if (process.env.FUNCTIONS_CONTROL_API === "true") {
35
35
  logger.warn(`${this.toString()}.value() invoked during function deployment, instead of during runtime.`);
@@ -42,10 +42,11 @@ class Expression {
42
42
  runtimeValue() {
43
43
  throw new Error("Not implemented");
44
44
  }
45
- /** Returns the Expression's representation as a braced CEL expression. */
45
+ /** Returns the expression's representation as a braced CEL expression. */
46
46
  toCEL() {
47
47
  return `{{ ${this.toString()} }}`;
48
48
  }
49
+ /** Returns the expression's representation as JSON. */
49
50
  toJSON() {
50
51
  return this.toString();
51
52
  }
@@ -55,8 +56,8 @@ function valueOf(arg) {
55
56
  return arg instanceof Expression ? arg.runtimeValue() : arg;
56
57
  }
57
58
  /**
58
- * Returns how an entity (either an Expression or a literal value) should be represented in CEL.
59
- * - Expressions delegate to the .toString() method, which is used by the WireManifest
59
+ * Returns how an entity (either an `Expression` or a literal value) should be represented in CEL.
60
+ * - Expressions delegate to the `.toString()` method, which is used by the WireManifest
60
61
  * - Strings have to be quoted explicitly
61
62
  * - Arrays are represented as []-delimited, parsable JSON
62
63
  * - Numbers and booleans are not quoted explicitly
@@ -136,7 +137,7 @@ class CompareExpression extends Expression {
136
137
  const rhsStr = refOf(this.rhs);
137
138
  return `${this.lhs} ${this.cmp} ${rhsStr}`;
138
139
  }
139
- /** Returns a TernaryExpression which can resolve to one of two values, based on the resolution of this comparison. */
140
+ /** Returns a `TernaryExpression` which can resolve to one of two values, based on the resolution of this comparison. */
140
141
  thenElse(ifTrue, ifFalse) {
141
142
  return new TernaryExpression(this, ifTrue, ifFalse);
142
143
  }
@@ -174,6 +175,9 @@ function multiSelect(options) {
174
175
  };
175
176
  }
176
177
  exports.multiSelect = multiSelect;
178
+ /**
179
+ * Autogenerate a list of buckets in a project that a user can select from.
180
+ */
177
181
  exports.BUCKET_PICKER = {
178
182
  resource: {
179
183
  type: "storage.googleapis.com/Bucket",
@@ -194,36 +198,36 @@ class Param extends Expression {
194
198
  runtimeValue() {
195
199
  throw new Error("Not implemented");
196
200
  }
197
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
201
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
198
202
  cmp(cmp, rhs) {
199
203
  return new CompareExpression(cmp, this, rhs);
200
204
  }
201
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
205
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
202
206
  equals(rhs) {
203
207
  return this.cmp("==", rhs);
204
208
  }
205
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
209
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
206
210
  notEquals(rhs) {
207
211
  return this.cmp("!=", rhs);
208
212
  }
209
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
213
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
210
214
  greaterThan(rhs) {
211
215
  return this.cmp(">", rhs);
212
216
  }
213
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
217
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
214
218
  greaterThanOrEqualTo(rhs) {
215
219
  return this.cmp(">=", rhs);
216
220
  }
217
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
221
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
218
222
  lessThan(rhs) {
219
223
  return this.cmp("<", rhs);
220
224
  }
221
- /** Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression. */
225
+ /** Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression. */
222
226
  lessThanOrEqualTo(rhs) {
223
227
  return this.cmp("<=", rhs);
224
228
  }
225
229
  /**
226
- * Returns a parametrized expression of Boolean type, based on comparing the value of this param to a literal or a different expression.
230
+ * Returns a parametrized expression of Boolean type, based on comparing the value of this parameter to a literal or a different expression.
227
231
  * @deprecated A typo. Use lessThanOrEqualTo instead.
228
232
  */
229
233
  lessThanorEqualTo(rhs) {
@@ -303,7 +307,7 @@ exports.StringParam = StringParam;
303
307
  /**
304
308
  * A CEL expression which represents an internal Firebase variable. This class
305
309
  * cannot be instantiated by developers, but we provide several canned instances
306
- * of it to make available params that will never have to be defined at
310
+ * of it to make available parameters that will never have to be defined at
307
311
  * deployment time, and can always be read from process.env.
308
312
  * @internal
309
313
  */
@@ -28,12 +28,14 @@ const encoding_1 = require("../common/encoding");
28
28
  const manifest_1 = require("../runtime/manifest");
29
29
  const options_1 = require("../common/options");
30
30
  const types_1 = require("../params/types");
31
+ const onInit_1 = require("../common/onInit");
31
32
  var change_1 = require("../common/change");
32
33
  Object.defineProperty(exports, "Change", { enumerable: true, get: function () { return change_1.Change; } });
33
34
  /** @internal */
34
35
  const WILDCARD_REGEX = new RegExp("{[^/{}]*}", "g");
35
36
  /** @internal */
36
37
  function makeCloudFunction({ contextOnlyHandler, dataConstructor = (raw) => raw.data, eventType, handler, labels = {}, legacyEventType, options = {}, provider, service, triggerResource, }) {
38
+ handler = (0, onInit_1.withInit)(handler);
37
39
  const cloudFunction = (data, context) => {
38
40
  if (legacyEventType && context.eventType === legacyEventType) {
39
41
  /*
package/lib/v1/index.d.ts CHANGED
@@ -20,3 +20,4 @@ export * from "./function-builder";
20
20
  export * from "./function-configuration";
21
21
  import * as params from "../params";
22
22
  export { params };
23
+ export { onInit } from "../common/onInit";
package/lib/v1/index.js CHANGED
@@ -35,7 +35,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
35
35
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
36
36
  };
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
- exports.params = exports.app = exports.logger = exports.testLab = exports.tasks = exports.storage = exports.remoteConfig = exports.pubsub = exports.https = exports.firestore = exports.database = exports.auth = exports.analytics = void 0;
38
+ exports.onInit = exports.params = exports.app = exports.logger = exports.testLab = exports.tasks = exports.storage = exports.remoteConfig = exports.pubsub = exports.https = exports.firestore = exports.database = exports.auth = exports.analytics = void 0;
39
39
  // Providers:
40
40
  const logger = require("../logger");
41
41
  exports.logger = logger;
@@ -69,3 +69,5 @@ __exportStar(require("./function-configuration"), exports);
69
69
  // NOTE: Equivalent to `export * as params from "../params"` but api-extractor doesn't support that syntax.
70
70
  const params = require("../params");
71
71
  exports.params = params;
72
+ var onInit_1 = require("../common/onInit");
73
+ Object.defineProperty(exports, "onInit", { enumerable: true, get: function () { return onInit_1.onInit; } });
@@ -27,6 +27,8 @@ const https_1 = require("../../common/providers/https");
27
27
  Object.defineProperty(exports, "HttpsError", { enumerable: true, get: function () { return https_1.HttpsError; } });
28
28
  const cloud_functions_1 = require("../cloud-functions");
29
29
  const manifest_1 = require("../../runtime/manifest");
30
+ const onInit_1 = require("../../common/onInit");
31
+ const trace_1 = require("../../v2/trace");
30
32
  /**
31
33
  * Handle HTTP requests.
32
34
  * @param handler A function that takes a request and response object,
@@ -48,7 +50,7 @@ exports.onCall = onCall;
48
50
  function _onRequestWithOptions(handler, options) {
49
51
  // lets us add __endpoint without altering handler:
50
52
  const cloudFunction = (req, res) => {
51
- return handler(req, res);
53
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(req, res);
52
54
  };
53
55
  cloudFunction.__trigger = {
54
56
  ...(0, cloud_functions_1.optionsToTrigger)(options),
@@ -71,12 +73,14 @@ function _onCallWithOptions(handler, options) {
71
73
  // onCallHandler sniffs the function length of the passed-in callback
72
74
  // and the user could have only tried to listen to data. Wrap their handler
73
75
  // in another handler to avoid accidentally triggering the v2 API
74
- const fixedLen = (data, context) => handler(data, context);
75
- const func = (0, https_1.onCallHandler)({
76
+ const fixedLen = (data, context) => {
77
+ return (0, onInit_1.withInit)(handler)(data, context);
78
+ };
79
+ const func = (0, trace_1.wrapTraceContext)((0, https_1.onCallHandler)({
76
80
  enforceAppCheck: options.enforceAppCheck,
77
81
  consumeAppCheckToken: options.consumeAppCheckToken,
78
82
  cors: { origin: true, methods: "POST" },
79
- }, fixedLen);
83
+ }, fixedLen));
80
84
  func.__trigger = {
81
85
  labels: {},
82
86
  ...(0, cloud_functions_1.optionsToTrigger)(options),
@@ -90,7 +94,7 @@ function _onCallWithOptions(handler, options) {
90
94
  ...(0, cloud_functions_1.optionsToEndpoint)(options),
91
95
  callableTrigger: {},
92
96
  };
93
- func.run = handler;
97
+ func.run = fixedLen;
94
98
  return func;
95
99
  }
96
100
  exports._onCallWithOptions = _onCallWithOptions;
package/lib/v2/core.d.ts CHANGED
@@ -6,6 +6,7 @@ import { Change } from "../common/change";
6
6
  import { ManifestEndpoint } from "../runtime/manifest";
7
7
  export { Change };
8
8
  export { ParamsOf } from "../common/params";
9
+ export { onInit } from "../common/onInit";
9
10
  /**
10
11
  * A `CloudEventBase` is the base of a cross-platform format for encoding a serverless event.
11
12
  * For more information, see https://github.com/cloudevents/spec.
package/lib/v2/core.js CHANGED
@@ -21,10 +21,12 @@
21
21
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
22
  // SOFTWARE.
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.Change = void 0;
24
+ exports.onInit = exports.Change = void 0;
25
25
  /**
26
26
  * Core functionality of the Cloud Functions for Firebase 2nd gen SDK.
27
27
  * @packageDocumentation
28
28
  */
29
29
  const change_1 = require("../common/change");
30
30
  Object.defineProperty(exports, "Change", { enumerable: true, get: function () { return change_1.Change; } });
31
+ var onInit_1 = require("../common/onInit");
32
+ Object.defineProperty(exports, "onInit", { enumerable: true, get: function () { return onInit_1.onInit; } });
package/lib/v2/index.d.ts CHANGED
@@ -20,7 +20,7 @@ import * as testLab from "./providers/testLab";
20
20
  import * as firestore from "./providers/firestore";
21
21
  export { alerts, database, storage, https, identity, pubsub, logger, tasks, eventarc, scheduler, remoteConfig, testLab, firestore, };
22
22
  export { setGlobalOptions, GlobalOptions, SupportedRegion, MemoryOption, VpcEgressSetting, IngressSetting, EventHandlerOptions, } from "./options";
23
- export { CloudFunction, CloudEvent, ParamsOf } from "./core";
23
+ export { CloudFunction, CloudEvent, ParamsOf, onInit } from "./core";
24
24
  export { Change } from "../common/change";
25
25
  import * as params from "../params";
26
26
  export { params };
package/lib/v2/index.js CHANGED
@@ -21,7 +21,7 @@
21
21
  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
22
  // SOFTWARE.
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.params = exports.Change = exports.setGlobalOptions = exports.firestore = exports.testLab = exports.remoteConfig = exports.scheduler = exports.eventarc = exports.tasks = exports.logger = exports.pubsub = exports.identity = exports.https = exports.storage = exports.database = exports.alerts = void 0;
24
+ exports.params = exports.Change = exports.onInit = exports.setGlobalOptions = exports.firestore = exports.testLab = exports.remoteConfig = exports.scheduler = exports.eventarc = exports.tasks = exports.logger = exports.pubsub = exports.identity = exports.https = exports.storage = exports.database = exports.alerts = void 0;
25
25
  /**
26
26
  * The 2nd gen API for Cloud Functions for Firebase.
27
27
  * This SDK supports deep imports. For example, the namespace
@@ -57,6 +57,8 @@ const firestore = require("./providers/firestore");
57
57
  exports.firestore = firestore;
58
58
  var options_1 = require("./options");
59
59
  Object.defineProperty(exports, "setGlobalOptions", { enumerable: true, get: function () { return options_1.setGlobalOptions; } });
60
+ var core_1 = require("./core");
61
+ Object.defineProperty(exports, "onInit", { enumerable: true, get: function () { return core_1.onInit; } });
60
62
  var change_1 = require("../common/change");
61
63
  Object.defineProperty(exports, "Change", { enumerable: true, get: function () { return change_1.Change; } });
62
64
  // NOTE: Equivalent to `export * as params from "../params"` but api-extractor doesn't support that syntax.
@@ -25,12 +25,13 @@ exports.convertAlertAndApp = exports.getOptsAndAlertTypeAndApp = exports.getEndp
25
25
  const manifest_1 = require("../../../runtime/manifest");
26
26
  const trace_1 = require("../../trace");
27
27
  const options = require("../../options");
28
+ const onInit_1 = require("../../../common/onInit");
28
29
  /** @internal */
29
30
  exports.eventType = "google.firebase.firebasealerts.alerts.v1.published";
30
31
  function onAlertPublished(alertTypeOrOpts, handler) {
31
32
  const [opts, alertType, appId] = getOptsAndAlertTypeAndApp(alertTypeOrOpts);
32
33
  const func = (raw) => {
33
- return (0, trace_1.wrapTraceContext)(handler)(convertAlertAndApp(raw));
34
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(convertAlertAndApp(raw));
34
35
  };
35
36
  func.run = handler;
36
37
  func.__endpoint = getEndpointAnnotation(opts, alertType, appId);
@@ -24,6 +24,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.getOptsAndApp = exports.onInAppFeedbackPublished = exports.onNewTesterIosDevicePublished = exports.inAppFeedbackAlert = exports.newTesterIosDeviceAlert = void 0;
25
25
  const trace_1 = require("../../trace");
26
26
  const alerts_1 = require("./alerts");
27
+ const onInit_1 = require("../../../common/onInit");
27
28
  /** @internal */
28
29
  exports.newTesterIosDeviceAlert = "appDistribution.newTesterIosDevice";
29
30
  /** @internal */
@@ -41,7 +42,7 @@ function onNewTesterIosDevicePublished(appIdOrOptsOrHandler, handler) {
41
42
  }
42
43
  const [opts, appId] = getOptsAndApp(appIdOrOptsOrHandler);
43
44
  const func = (raw) => {
44
- return (0, trace_1.wrapTraceContext)(handler)((0, alerts_1.convertAlertAndApp)(raw));
45
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))((0, alerts_1.convertAlertAndApp)(raw));
45
46
  };
46
47
  func.run = handler;
47
48
  func.__endpoint = (0, alerts_1.getEndpointAnnotation)(opts, exports.newTesterIosDeviceAlert, appId);
@@ -61,7 +62,7 @@ function onInAppFeedbackPublished(appIdOrOptsOrHandler, handler) {
61
62
  }
62
63
  const [opts, appId] = getOptsAndApp(appIdOrOptsOrHandler);
63
64
  const func = (raw) => {
64
- return (0, trace_1.wrapTraceContext)(handler)((0, alerts_1.convertAlertAndApp)(raw));
65
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))((0, alerts_1.convertAlertAndApp)(raw));
65
66
  };
66
67
  func.run = handler;
67
68
  func.__endpoint = (0, alerts_1.getEndpointAnnotation)(opts, exports.inAppFeedbackAlert, appId);
@@ -24,6 +24,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.onOperation = exports.onPlanAutomatedUpdatePublished = exports.onPlanUpdatePublished = exports.planAutomatedUpdateAlert = exports.planUpdateAlert = void 0;
25
25
  const trace_1 = require("../../trace");
26
26
  const alerts_1 = require("./alerts");
27
+ const onInit_1 = require("../../../common/onInit");
27
28
  /** @internal */
28
29
  exports.planUpdateAlert = "billing.planUpdate";
29
30
  /** @internal */
@@ -55,7 +56,7 @@ function onOperation(alertType, optsOrHandler, handler) {
55
56
  optsOrHandler = {};
56
57
  }
57
58
  const func = (raw) => {
58
- return (0, trace_1.wrapTraceContext)(handler)((0, alerts_1.convertAlertAndApp)(raw));
59
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))((0, alerts_1.convertAlertAndApp)(raw));
59
60
  };
60
61
  func.run = handler;
61
62
  func.__endpoint = (0, alerts_1.getEndpointAnnotation)(optsOrHandler, alertType);
@@ -24,6 +24,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.getOptsAndApp = exports.onOperation = exports.onNewAnrIssuePublished = exports.onVelocityAlertPublished = exports.onStabilityDigestPublished = exports.onRegressionAlertPublished = exports.onNewNonfatalIssuePublished = exports.onNewFatalIssuePublished = exports.newAnrIssueAlert = exports.velocityAlert = exports.stabilityDigestAlert = exports.regressionAlert = exports.newNonfatalIssueAlert = exports.newFatalIssueAlert = void 0;
25
25
  const trace_1 = require("../../trace");
26
26
  const alerts_1 = require("./alerts");
27
+ const onInit_1 = require("../../../common/onInit");
27
28
  /** @internal */
28
29
  exports.newFatalIssueAlert = "crashlytics.newFatalIssue";
29
30
  /** @internal */
@@ -104,7 +105,7 @@ function onOperation(alertType, appIdOrOptsOrHandler, handler) {
104
105
  }
105
106
  const [opts, appId] = getOptsAndApp(appIdOrOptsOrHandler);
106
107
  const func = (raw) => {
107
- return (0, trace_1.wrapTraceContext)(handler((0, alerts_1.convertAlertAndApp)(raw)));
108
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))((0, alerts_1.convertAlertAndApp)(raw));
108
109
  };
109
110
  func.run = handler;
110
111
  func.__endpoint = (0, alerts_1.getEndpointAnnotation)(opts, alertType, appId);
@@ -1,7 +1,3 @@
1
- /**
2
- * Cloud functions to handle Firebase Performance Monitoring events from Firebase Alerts.
3
- * @packageDocumentation
4
- */
5
1
  import { CloudEvent, CloudFunction } from "../../core";
6
2
  import { EventHandlerOptions } from "../../options";
7
3
  import { FirebaseAlertData } from "./alerts";
@@ -22,6 +22,12 @@
22
22
  // SOFTWARE.
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.convertPayload = exports.getOptsAndApp = exports.onThresholdAlertPublished = exports.thresholdAlert = void 0;
25
+ /**
26
+ * Cloud functions to handle Firebase Performance Monitoring events from Firebase Alerts.
27
+ * @packageDocumentation
28
+ */
29
+ const onInit_1 = require("../../../common/onInit");
30
+ const trace_1 = require("../../trace");
25
31
  const alerts_1 = require("./alerts");
26
32
  /** @internal */
27
33
  exports.thresholdAlert = "performance.threshold";
@@ -41,7 +47,7 @@ function onThresholdAlertPublished(appIdOrOptsOrHandler, handler) {
41
47
  const event = (0, alerts_1.convertAlertAndApp)(raw);
42
48
  const convertedPayload = convertPayload(event.data.payload);
43
49
  event.data.payload = convertedPayload;
44
- return handler(event);
50
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler(event)));
45
51
  };
46
52
  func.run = handler;
47
53
  func.__endpoint = (0, alerts_1.getEndpointAnnotation)(opts, exports.thresholdAlert, appId);
@@ -31,6 +31,7 @@ const utils_1 = require("../../common/utilities/utils");
31
31
  const manifest_1 = require("../../runtime/manifest");
32
32
  const trace_1 = require("../trace");
33
33
  const options = require("../options");
34
+ const onInit_1 = require("../../common/onInit");
34
35
  /** @internal */
35
36
  exports.writtenEventType = "google.firebase.database.ref.v1.written";
36
37
  /** @internal */
@@ -181,7 +182,9 @@ function onChangedOperation(eventType, referenceOrOpts, handler) {
181
182
  const instanceUrl = getInstance(event);
182
183
  const params = makeParams(event, pathPattern, instancePattern);
183
184
  const databaseEvent = makeChangedDatabaseEvent(event, instanceUrl, params);
184
- return (0, trace_1.wrapTraceContext)(handler)(databaseEvent);
185
+ // Intentionally put init in the context of traces in case there is something
186
+ // expensive to observe.
187
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(databaseEvent);
185
188
  };
186
189
  func.run = handler;
187
190
  func.__endpoint = makeEndpoint(eventType, opts, pathPattern, instancePattern);
@@ -200,7 +203,7 @@ function onOperation(eventType, referenceOrOpts, handler) {
200
203
  const params = makeParams(event, pathPattern, instancePattern);
201
204
  const data = eventType === exports.deletedEventType ? event.data.data : event.data.delta;
202
205
  const databaseEvent = makeDatabaseEvent(event, data, instanceUrl, params);
203
- return handler(databaseEvent);
206
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(databaseEvent);
204
207
  };
205
208
  func.run = handler;
206
209
  func.__endpoint = makeEndpoint(eventType, opts, pathPattern, instancePattern);
@@ -30,6 +30,7 @@ const encoding_1 = require("../../common/encoding");
30
30
  const manifest_1 = require("../../runtime/manifest");
31
31
  const trace_1 = require("../trace");
32
32
  const options = require("../options");
33
+ const onInit_1 = require("../../common/onInit");
33
34
  function onCustomEventPublished(eventTypeOrOpts, handler) {
34
35
  var _a;
35
36
  let opts;
@@ -42,7 +43,7 @@ function onCustomEventPublished(eventTypeOrOpts, handler) {
42
43
  opts = eventTypeOrOpts;
43
44
  }
44
45
  const func = (raw) => {
45
- return (0, trace_1.wrapTraceContext)(handler)(raw);
46
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(raw);
46
47
  };
47
48
  func.run = handler;
48
49
  const channel = (_a = opts.channel) !== null && _a !== void 0 ? _a : "locations/us-central1/channels/firebase";
@@ -2,6 +2,7 @@ import * as firestore from "firebase-admin/firestore";
2
2
  import { ParamsOf } from "../../common/params";
3
3
  import { Change, CloudEvent, CloudFunction } from "../core";
4
4
  import { EventHandlerOptions } from "../options";
5
+ import { Expression } from "../../params";
5
6
  export { Change };
6
7
  /** A Firestore DocumentSnapshot */
7
8
  export type DocumentSnapshot = firestore.DocumentSnapshot;
@@ -28,11 +29,11 @@ export interface FirestoreEvent<T, Params = Record<string, string>> extends Clou
28
29
  /** DocumentOptions extend EventHandlerOptions with provided document and optional database and namespace. */
29
30
  export interface DocumentOptions<Document extends string = string> extends EventHandlerOptions {
30
31
  /** The document path */
31
- document: Document;
32
+ document: Document | Expression<string>;
32
33
  /** The Firestore database */
33
- database?: string;
34
+ database?: string | Expression<string>;
34
35
  /** The Firestore namespace */
35
- namespace?: string;
36
+ namespace?: string | Expression<string>;
36
37
  }
37
38
  /**
38
39
  * Event handler which triggers when a document is created, updated, or deleted in Firestore.
@@ -31,6 +31,7 @@ Object.defineProperty(exports, "Change", { enumerable: true, get: function () {
31
31
  const options_1 = require("../options");
32
32
  const firestore_1 = require("../../common/providers/firestore");
33
33
  const trace_1 = require("../trace");
34
+ const onInit_1 = require("../../common/onInit");
34
35
  /** @internal */
35
36
  exports.writtenEventType = "google.cloud.firestore.document.v1.written";
36
37
  /** @internal */
@@ -92,7 +93,10 @@ function getOpts(documentOrOpts) {
92
93
  opts = {};
93
94
  }
94
95
  else {
95
- document = (0, path_1.normalizePath)(documentOrOpts.document);
96
+ document =
97
+ typeof documentOrOpts.document === "string"
98
+ ? (0, path_1.normalizePath)(documentOrOpts.document)
99
+ : documentOrOpts.document;
96
100
  database = documentOrOpts.database || "(default)";
97
101
  namespace = documentOrOpts.namespace || "(default)";
98
102
  opts = { ...documentOrOpts };
@@ -190,9 +194,13 @@ function makeEndpoint(eventType, opts, document, database, namespace) {
190
194
  namespace,
191
195
  };
192
196
  const eventFilterPathPatterns = {};
193
- document.hasWildcards()
194
- ? (eventFilterPathPatterns.document = document.getValue())
195
- : (eventFilters.document = document.getValue());
197
+ const maybePattern = typeof document === "string" ? new path_pattern_1.PathPattern(document).hasWildcards() : true;
198
+ if (maybePattern) {
199
+ eventFilterPathPatterns.document = document;
200
+ }
201
+ else {
202
+ eventFilters.document = document;
203
+ }
196
204
  return {
197
205
  ...(0, manifest_1.initV2Endpoint)((0, options_1.getGlobalOptions)(), opts),
198
206
  platform: "gcfv2",
@@ -214,32 +222,32 @@ exports.makeEndpoint = makeEndpoint;
214
222
  /** @internal */
215
223
  function onOperation(eventType, documentOrOpts, handler) {
216
224
  const { document, database, namespace, opts } = getOpts(documentOrOpts);
217
- const documentPattern = new path_pattern_1.PathPattern(document);
218
225
  // wrap the handler
219
226
  const func = (raw) => {
220
227
  const event = raw;
228
+ const documentPattern = new path_pattern_1.PathPattern(typeof document === "string" ? document : document.value());
221
229
  const params = makeParams(event.document, documentPattern);
222
230
  const firestoreEvent = makeFirestoreEvent(eventType, event, params);
223
- return (0, trace_1.wrapTraceContext)(handler)(firestoreEvent);
231
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(firestoreEvent);
224
232
  };
225
233
  func.run = handler;
226
- func.__endpoint = makeEndpoint(eventType, opts, documentPattern, database, namespace);
234
+ func.__endpoint = makeEndpoint(eventType, opts, document, database, namespace);
227
235
  return func;
228
236
  }
229
237
  exports.onOperation = onOperation;
230
238
  /** @internal */
231
239
  function onChangedOperation(eventType, documentOrOpts, handler) {
232
240
  const { document, database, namespace, opts } = getOpts(documentOrOpts);
233
- const documentPattern = new path_pattern_1.PathPattern(document);
234
241
  // wrap the handler
235
242
  const func = (raw) => {
236
243
  const event = raw;
244
+ const documentPattern = new path_pattern_1.PathPattern(typeof document === "string" ? document : document.value());
237
245
  const params = makeParams(event.document, documentPattern);
238
246
  const firestoreEvent = makeChangedFirestoreEvent(event, params);
239
- return handler(firestoreEvent);
247
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(firestoreEvent);
240
248
  };
241
249
  func.run = handler;
242
- func.__endpoint = makeEndpoint(eventType, opts, documentPattern, database, namespace);
250
+ func.__endpoint = makeEndpoint(eventType, opts, document, database, namespace);
243
251
  return func;
244
252
  }
245
253
  exports.onChangedOperation = onChangedOperation;
@@ -175,10 +175,10 @@ export declare function onRequest(handler: (request: Request, response: express.
175
175
  * @param handler - A function that takes a {@link https.CallableRequest}.
176
176
  * @returns A function that you can export and deploy.
177
177
  */
178
- export declare function onCall<T = any, Return = any | Promise<any>>(opts: CallableOptions, handler: (request: CallableRequest<T>) => Return): CallableFunction<T, Return>;
178
+ export declare function onCall<T = any, Return = any | Promise<any>>(opts: CallableOptions, handler: (request: CallableRequest<T>) => Return): CallableFunction<T, Return extends Promise<unknown> ? Return : Promise<Return>>;
179
179
  /**
180
180
  * Declares a callable method for clients to call using a Firebase SDK.
181
181
  * @param handler - A function that takes a {@link https.CallableRequest}.
182
182
  * @returns A function that you can export and deploy.
183
183
  */
184
- export declare function onCall<T = any, Return = any | Promise<any>>(handler: (request: CallableRequest<T>) => Return): CallableFunction<T, Return>;
184
+ export declare function onCall<T = any, Return = any | Promise<any>>(handler: (request: CallableRequest<T>) => Return): CallableFunction<T, Return extends Promise<unknown> ? Return : Promise<Return>>;
@@ -34,6 +34,7 @@ const https_1 = require("../../common/providers/https");
34
34
  Object.defineProperty(exports, "HttpsError", { enumerable: true, get: function () { return https_1.HttpsError; } });
35
35
  const manifest_1 = require("../../runtime/manifest");
36
36
  const options = require("../options");
37
+ const onInit_1 = require("../../common/onInit");
37
38
  function onRequest(optsOrHandler, handler) {
38
39
  let opts;
39
40
  if (arguments.length === 1) {
@@ -49,17 +50,24 @@ function onRequest(optsOrHandler, handler) {
49
50
  // Respect `cors: false` to turn off cors even if debug feature is enabled.
50
51
  origin = opts.cors === false ? false : true;
51
52
  }
53
+ // Arrays cause the access-control-allow-origin header to be dynamic based
54
+ // on the origin header of the request. If there is only one element in the
55
+ // array, this is unnecessary.
56
+ if (Array.isArray(origin) && origin.length === 1) {
57
+ origin = origin[1];
58
+ }
59
+ const middleware = cors({ origin });
52
60
  const userProvidedHandler = handler;
53
61
  handler = (req, res) => {
54
62
  return new Promise((resolve) => {
55
63
  res.on("finish", resolve);
56
- cors({ origin })(req, res, () => {
64
+ middleware(req, res, () => {
57
65
  resolve(userProvidedHandler(req, res));
58
66
  });
59
67
  });
60
68
  };
61
69
  }
62
- handler = (0, trace_1.wrapTraceContext)(handler);
70
+ handler = (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler));
63
71
  Object.defineProperty(handler, "__trigger", {
64
72
  get: () => {
65
73
  const baseOpts = options.optionsToTriggerAnnotations(options.getGlobalOptions());
@@ -115,10 +123,16 @@ function onCall(optsOrHandler, handler) {
115
123
  else {
116
124
  opts = optsOrHandler;
117
125
  }
118
- const origin = (0, debug_1.isDebugFeatureEnabled)("enableCors") ? true : "cors" in opts ? opts.cors : true;
126
+ let origin = (0, debug_1.isDebugFeatureEnabled)("enableCors") ? true : "cors" in opts ? opts.cors : true;
127
+ // Arrays cause the access-control-allow-origin header to be dynamic based
128
+ // on the origin header of the request. If there is only one element in the
129
+ // array, this is unnecessary.
130
+ if (Array.isArray(origin) && origin.length === 1) {
131
+ origin = origin[1];
132
+ }
119
133
  // onCallHandler sniffs the function length to determine which API to present.
120
134
  // fix the length to prevent api versions from being mismatched.
121
- const fixedLen = (req) => handler(req);
135
+ const fixedLen = (req) => (0, onInit_1.withInit)(handler)(req);
122
136
  let func = (0, https_1.onCallHandler)({
123
137
  cors: { origin, methods: "POST" },
124
138
  enforceAppCheck: (_a = opts.enforceAppCheck) !== null && _a !== void 0 ? _a : options.getGlobalOptions().enforceAppCheck,
@@ -161,7 +175,7 @@ function onCall(optsOrHandler, handler) {
161
175
  },
162
176
  callableTrigger: {},
163
177
  };
164
- func.run = handler;
178
+ func.run = (0, onInit_1.withInit)(handler);
165
179
  return func;
166
180
  }
167
181
  exports.onCall = onCall;
@@ -27,6 +27,7 @@ Object.defineProperty(exports, "HttpsError", { enumerable: true, get: function (
27
27
  const trace_1 = require("../trace");
28
28
  const manifest_1 = require("../../runtime/manifest");
29
29
  const options = require("../options");
30
+ const onInit_1 = require("../../common/onInit");
30
31
  /**
31
32
  * Handles an event that is triggered before a user is created
32
33
  * @param optsOrHandler - Either an object containing function options, or an event handler (run before user creation)
@@ -55,7 +56,7 @@ function beforeOperation(eventType, optsOrHandler, handler) {
55
56
  // Create our own function that just calls the provided function so we know for sure that
56
57
  // handler takes one argument. This is something common/providers/identity depends on.
57
58
  const wrappedHandler = (event) => handler(event);
58
- const func = (0, trace_1.wrapTraceContext)((0, identity_1.wrapHandler)(eventType, wrappedHandler));
59
+ const func = (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)((0, identity_1.wrapHandler)(eventType, wrappedHandler)));
59
60
  const legacyEventType = `providers/cloud.auth/eventTypes/user.${eventType}`;
60
61
  /** Endpoint */
61
62
  const baseOptsEndpoint = options.optionsToEndpoint(options.getGlobalOptions());
@@ -30,6 +30,7 @@ const encoding_1 = require("../../common/encoding");
30
30
  const manifest_1 = require("../../runtime/manifest");
31
31
  const trace_1 = require("../trace");
32
32
  const options = require("../options");
33
+ const onInit_1 = require("../../common/onInit");
33
34
  /**
34
35
  * Google Cloud Pub/Sub is a globally distributed message bus that automatically scales as you need it.
35
36
  * You can create a function ({@link onMessagePublished}) that handles pub/sub events by using functions.pubsub.
@@ -125,7 +126,7 @@ function onMessagePublished(topicOrOptions, handler) {
125
126
  const func = (raw) => {
126
127
  const messagePublishedData = raw.data;
127
128
  messagePublishedData.message = new Message(messagePublishedData.message);
128
- return (0, trace_1.wrapTraceContext)(handler)(raw);
129
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(raw);
129
130
  };
130
131
  func.run = handler;
131
132
  Object.defineProperty(func, "__trigger", {
@@ -22,8 +22,10 @@
22
22
  // SOFTWARE.
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.onConfigUpdated = exports.eventType = void 0;
25
+ const onInit_1 = require("../../common/onInit");
25
26
  const manifest_1 = require("../../runtime/manifest");
26
27
  const options_1 = require("../options");
28
+ const trace_1 = require("../trace");
27
29
  /** @internal */
28
30
  exports.eventType = "google.firebase.remoteconfig.remoteConfig.v1.updated";
29
31
  /**
@@ -40,9 +42,9 @@ function onConfigUpdated(optsOrHandler, handler) {
40
42
  }
41
43
  const baseOpts = (0, options_1.optionsToEndpoint)((0, options_1.getGlobalOptions)());
42
44
  const specificOpts = (0, options_1.optionsToEndpoint)(optsOrHandler);
43
- const func = (raw) => {
45
+ const func = (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)((raw) => {
44
46
  return handler(raw);
45
- };
47
+ }));
46
48
  func.run = handler;
47
49
  const ep = {
48
50
  ...(0, manifest_1.initV2Endpoint)((0, options_1.getGlobalOptions)(), optsOrHandler),
@@ -27,6 +27,7 @@ const manifest_1 = require("../../runtime/manifest");
27
27
  const trace_1 = require("../trace");
28
28
  const logger = require("../../logger");
29
29
  const options = require("../options");
30
+ const onInit_1 = require("../../common/onInit");
30
31
  /** @internal */
31
32
  function getOpts(args) {
32
33
  if (typeof args === "string") {
@@ -72,7 +73,7 @@ function onSchedule(args, handler) {
72
73
  res.status(500).send();
73
74
  }
74
75
  };
75
- const func = (0, trace_1.wrapTraceContext)(httpFunc);
76
+ const func = (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(httpFunc));
76
77
  func.run = handler;
77
78
  const globalOpts = options.getGlobalOptions();
78
79
  const baseOptsEndpoint = options.optionsToEndpoint(globalOpts);
@@ -31,6 +31,7 @@ const encoding_1 = require("../../common/encoding");
31
31
  const manifest_1 = require("../../runtime/manifest");
32
32
  const trace_1 = require("../trace");
33
33
  const options = require("../options");
34
+ const onInit_1 = require("../../common/onInit");
34
35
  /** @internal */
35
36
  exports.archivedEvent = "google.cloud.storage.object.v1.archived";
36
37
  /** @internal */
@@ -102,7 +103,7 @@ function onOperation(eventType, bucketOrOptsOrHandler, handler) {
102
103
  }
103
104
  const [opts, bucket] = getOptsAndBucket(bucketOrOptsOrHandler);
104
105
  const func = (raw) => {
105
- return (0, trace_1.wrapTraceContext)(handler)(raw);
106
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(raw);
106
107
  };
107
108
  func.run = handler;
108
109
  Object.defineProperty(func, "__trigger", {
@@ -31,6 +31,7 @@ const tasks_1 = require("../../common/providers/tasks");
31
31
  const options = require("../options");
32
32
  const trace_1 = require("../trace");
33
33
  const manifest_1 = require("../../runtime/manifest");
34
+ const onInit_1 = require("../../common/onInit");
34
35
  function onTaskDispatched(optsOrHandler, handler) {
35
36
  let opts;
36
37
  if (arguments.length === 1) {
@@ -43,7 +44,7 @@ function onTaskDispatched(optsOrHandler, handler) {
43
44
  // onDispatchHandler sniffs the function length to determine which API to present.
44
45
  // fix the length to prevent api versions from being mismatched.
45
46
  const fixedLen = (req) => handler(req);
46
- const func = (0, trace_1.wrapTraceContext)((0, tasks_1.onDispatchHandler)(fixedLen));
47
+ const func = (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)((0, tasks_1.onDispatchHandler)(fixedLen)));
47
48
  Object.defineProperty(func, "__trigger", {
48
49
  get: () => {
49
50
  const baseOpts = options.optionsToTriggerAnnotations(options.getGlobalOptions());
@@ -22,6 +22,7 @@
22
22
  // SOFTWARE.
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
24
  exports.onTestMatrixCompleted = exports.eventType = void 0;
25
+ const onInit_1 = require("../../common/onInit");
25
26
  const manifest_1 = require("../../runtime/manifest");
26
27
  const options_1 = require("../options");
27
28
  const trace_1 = require("../trace");
@@ -43,7 +44,7 @@ function onTestMatrixCompleted(optsOrHandler, handler) {
43
44
  const baseOpts = (0, options_1.optionsToEndpoint)((0, options_1.getGlobalOptions)());
44
45
  const specificOpts = (0, options_1.optionsToEndpoint)(optsOrHandler);
45
46
  const func = (raw) => {
46
- return (0, trace_1.wrapTraceContext)(handler)(raw);
47
+ return (0, trace_1.wrapTraceContext)((0, onInit_1.withInit)(handler))(raw);
47
48
  };
48
49
  func.run = handler;
49
50
  const ep = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "firebase-functions",
3
- "version": "4.7.0",
3
+ "version": "4.8.1",
4
4
  "description": "Firebase SDK for Cloud Functions",
5
5
  "keywords": [
6
6
  "firebase",
@@ -110,6 +110,9 @@
110
110
  "v2": [
111
111
  "lib/v2"
112
112
  ],
113
+ "v2/core": [
114
+ "lib/v2/core"
115
+ ],
113
116
  "v2/alerts": [
114
117
  "lib/v2/providers/alerts"
115
118
  ],