-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathhttps.ts
More file actions
705 lines (651 loc) · 24.4 KB
/
https.ts
File metadata and controls
705 lines (651 loc) · 24.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// The MIT License (MIT)
//
// Copyright (c) 2021 Firebase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
/**
* Cloud functions to handle HTTPS request or callable RPCs.
* @packageDocumentation
*/
import cors from "cors";
import * as express from "express";
import { convertIfPresent, convertInvoker, copyIfPresent } from "../../common/encoding";
import { wrapTraceContext } from "../trace";
import { isDebugFeatureEnabled } from "../../common/debug";
import { ResetValue } from "../../common/options";
import {
type CallableRequest,
type CallableResponse,
type FunctionsErrorCode,
HttpsError,
onCallHandler,
withErrorHandler,
type Request,
type AuthData,
} from "../../common/providers/https";
import { initV2Endpoint, ManifestEndpoint } from "../../runtime/manifest";
import { GlobalOptions, SupportedRegion } from "../options";
import { Expression } from "../../params";
import { SupportedSecretParam } from "../../params/types";
import * as options from "../options";
import { withInit } from "../../common/onInit";
import * as logger from "../../logger";
export type { Request, CallableRequest, CallableResponse, FunctionsErrorCode };
export { HttpsError };
/**
* Options that can be set on an onRequest HTTPS function.
*/
export interface HttpsOptions extends Omit<GlobalOptions, "region" | "enforceAppCheck"> {
/**
* If true, do not deploy or emulate this function.
*/
omit?: boolean | Expression<boolean>;
/** HTTP functions can override global options and can specify multiple regions to deploy to. */
region?:
| SupportedRegion
| string
| Array<SupportedRegion | string>
| Expression<string>
| ResetValue;
/** If true, allows CORS on requests to this function.
* If this is a `string` or `RegExp`, allows requests from domains that match the provided value.
* If this is an `Array`, allows requests from domains matching at least one entry of the array.
* Defaults to true for {@link https.CallableFunction} and false otherwise.
*/
cors?:
| string
| Expression<string>
| Expression<string[]>
| boolean
| RegExp
| Array<string | RegExp>;
/**
* Amount of memory to allocate to a function.
*/
memory?: options.MemoryOption | Expression<number> | ResetValue;
/**
* Timeout for the function in seconds, possible values are 0 to 540.
* HTTPS functions can specify a higher timeout.
*
* @remarks
* The minimum timeout for a gen 2 function is 1s. The maximum timeout for a
* function depends on the type of function: Event handling functions have a
* maximum timeout of 540s (9 minutes). HTTPS and callable functions have a
* maximum timeout of 3,600s (1 hour). Task queue functions have a maximum
* timeout of 1,800s (30 minutes)
*/
timeoutSeconds?: number | Expression<number> | ResetValue;
/**
* Min number of actual instances to be running at a given time.
*
* @remarks
* Instances will be billed for memory allocation and 10% of CPU allocation
* while idle.
*/
minInstances?: number | Expression<number> | ResetValue;
/**
* Max number of instances to be running in parallel.
*/
maxInstances?: number | Expression<number> | ResetValue;
/**
* Number of requests a function can serve at once.
*
* @remarks
* Can only be applied to functions running on Cloud Functions v2.
* A value of null restores the default concurrency (80 when CPU >= 1, 1 otherwise).
* Concurrency cannot be set to any value other than 1 if `cpu` is less than 1.
* The maximum value for concurrency is 1,000.
*/
concurrency?: number | Expression<number> | ResetValue;
/**
* Fractional number of CPUs to allocate to a function.
*
* @remarks
* Defaults to 1 for functions with <= 2GB RAM and increases for larger memory sizes.
* This is different from the defaults when using the gcloud utility and is different from
* the fixed amount assigned in Google Cloud Functions generation 1.
* To revert to the CPU amounts used in gcloud or in Cloud Functions generation 1, set this
* to the value "gcf_gen1"
*/
cpu?: number | "gcf_gen1";
/**
* Connect cloud function to specified VPC connector.
*/
vpcConnector?: string | Expression<string> | ResetValue;
/**
* Egress settings for VPC connector.
*/
vpcConnectorEgressSettings?: options.VpcEgressSetting | ResetValue;
/**
* Specific service account for the function to run as.
*/
serviceAccount?: string | Expression<string> | ResetValue;
/**
* Ingress settings which control where this function can be called from.
*/
ingressSettings?: options.IngressSetting | ResetValue;
/**
* User labels to set on the function.
*/
labels?: Record<string, string>;
/*
* Secrets to bind to a function.
*/
secrets?: SupportedSecretParam[];
/**
* Invoker to set access control on https functions.
*/
invoker?: "public" | "private" | string | string[];
}
/**
* Options that can be set on a callable HTTPS function.
*/
export interface CallableOptions<T = any> extends HttpsOptions {
/**
* Determines whether Firebase AppCheck is enforced.
* When true, requests with invalid tokens autorespond with a 401
* (Unauthorized) error.
* When false, requests with invalid tokens set event.app to undefiend.
*/
enforceAppCheck?: boolean;
/**
* Determines whether Firebase App Check token is consumed on request. Defaults to false.
*
* @remarks
* Set this to true to enable the App Check replay protection feature by consuming the App Check token on callable
* request. Tokens that are found to be already consumed will have request.app.alreadyConsumed property set true.
*
*
* Tokens are only considered to be consumed if it is sent to the App Check service by setting this option to true.
* Other uses of the token do not consume it.
*
* This replay protection feature requires an additional network call to the App Check backend and forces the clients
* to obtain a fresh attestation from the chosen attestation providers. This can therefore negatively impact
* performance and can potentially deplete your attestation providers' quotas faster. Use this feature only for
* protecting low volume, security critical, or expensive operations.
*
* This option does not affect the enforceAppCheck option. Setting the latter to true will cause the callable function
* to automatically respond with a 401 Unauthorized status code when request includes an invalid App Check token.
* When request includes valid but consumed App Check tokens, requests will not be automatically rejected. Instead,
* the request.app.alreadyConsumed property will be set to true and pass the execution to the handler code for making
* further decisions, such as requiring additional security checks or rejecting the request.
*/
consumeAppCheckToken?: boolean;
/**
* Time in seconds between sending heartbeat messages to keep the connection
* alive. Set to `null` to disable heartbeats.
*
* Defaults to 30 seconds.
*/
heartbeatSeconds?: number | null;
/**
* (Deprecated) Callback for whether a request is authorized.
*
* Designed to allow reusable auth policies to be passed as an options object. Two built-in reusable policies exist:
* isSignedIn and hasClaim.
*
* @deprecated
*/
authPolicy?: (auth: AuthData | null, data: T) => boolean | Promise<boolean>;
}
/**
* @deprecated
*
* An auth policy that requires a user to be signed in.
*/
export const isSignedIn =
() =>
(auth: AuthData | null): boolean =>
!!auth;
/**
* @deprecated
*
* An auth policy that requires a user to be both signed in and have a specific claim (optionally with a specific value)
*/
export const hasClaim =
(claim: string, value?: string) =>
(auth: AuthData | null): boolean => {
if (!auth) {
return false;
}
if (!(claim in auth.token)) {
return false;
}
return !value || auth.token[claim] === value;
};
/**
* Handles HTTPS requests.
*/
export type HttpsFunction = ((
/** An Express request object representing the HTTPS call to the function. */
req: Request,
/** An Express response object, for this function to respond to callers. */
res: express.Response
) => void | Promise<void>) & {
/** @alpha */
__trigger?: unknown;
/** @alpha */
__endpoint: ManifestEndpoint;
};
/**
* Creates a callable method for clients to call using a Firebase SDK.
*/
export interface CallableFunction<T, Return, Stream = unknown> extends HttpsFunction {
/** Executes the handler function with the provided data as input. Used for unit testing.
* @param data - An input for the handler function.
* @returns The output of the handler function.
*/
run(request: CallableRequest<T>): Return;
stream(
request: CallableRequest<T>,
response: CallableResponse<Stream>
): { stream: AsyncIterable<Stream>; output: Return };
}
/**
* Builds a CORS origin callback that resolves an Expression (e.g. defineList) at request time.
* Used by onRequest and onCall so params are not read during deployment.
*/
function buildCorsOriginFromExpression(
corsExpression: Expression<string | string[]>,
options: { respectCorsFalse?: boolean; corsOpt?: unknown }
): NonNullable<cors.CorsOptions["origin"]> {
return (reqOrigin: string | undefined, callback: (err: Error | null, allow?: boolean | string) => void) => {
if (isDebugFeatureEnabled("enableCors") && (!options.respectCorsFalse || options.corsOpt !== false)) {
callback(null, true);
return;
}
const resolved = corsExpression.runtimeValue();
if (Array.isArray(resolved)) {
if (resolved.length === 1) {
callback(null, resolved[0]);
return;
}
if (reqOrigin === undefined) {
callback(null, true);
return;
}
const allowed = resolved.indexOf(reqOrigin) !== -1;
callback(null, allowed ? reqOrigin : false);
} else {
callback(null, resolved as string);
}
};
}
/**
* Handles HTTPS requests.
* @param opts - Options to set on this function
* @param handler - A function that takes a {@link https.Request} and response object, same signature as an Express app.
* @returns A function that you can export and deploy.
*/
export function onRequest(
opts: HttpsOptions,
handler: (request: Request, response: express.Response) => void | Promise<void>
): HttpsFunction;
/**
* Handles HTTPS requests.
* @param handler - A function that takes a {@link https.Request} and response object, same signature as an Express app.
* @returns A function that you can export and deploy.
*/
export function onRequest(
handler: (request: Request, response: express.Response) => void | Promise<void>
): HttpsFunction;
export function onRequest(
optsOrHandler:
| HttpsOptions
| ((request: Request, response: express.Response) => void | Promise<void>),
handler?: (request: Request, response: express.Response) => void | Promise<void>
): HttpsFunction {
let opts: HttpsOptions;
if (arguments.length === 1) {
opts = {};
handler = optsOrHandler as (
request: Request,
response: express.Response
) => void | Promise<void>;
} else {
opts = optsOrHandler as HttpsOptions;
}
handler = withErrorHandler(handler);
if (isDebugFeatureEnabled("enableCors") || "cors" in opts) {
let corsOptions: cors.CorsOptions;
if (opts.cors instanceof Expression) {
// Defer resolution to request time so params are not read during deployment.
corsOptions = {
origin: buildCorsOriginFromExpression(opts.cors, {
respectCorsFalse: true,
corsOpt: opts.cors,
}),
};
} else {
let origin = opts.cors;
if (isDebugFeatureEnabled("enableCors")) {
// Respect `cors: false` to turn off cors even if debug feature is enabled.
origin = opts.cors === false ? false : true;
}
// Arrays cause the access-control-allow-origin header to be dynamic based
// on the origin header of the request. If there is only one element in the
// array, this is unnecessary.
if (Array.isArray(origin) && origin.length === 1) {
origin = origin[0];
}
// Use function form so CORS origin is resolved per-request; avoids CodeQL permissive CORS alert (developer-supplied config).
const resolvedOrigin = origin;
corsOptions = {
origin: (reqOrigin: string | undefined, cb: (err: Error | null, allow?: boolean | string) => void) => {
if (typeof resolvedOrigin === "boolean" || typeof resolvedOrigin === "string") {
return cb(null, resolvedOrigin);
}
if (reqOrigin === undefined) {
return cb(null, true);
}
if (resolvedOrigin instanceof RegExp) {
return cb(null, resolvedOrigin.test(reqOrigin) ? reqOrigin : false);
}
if (
Array.isArray(resolvedOrigin) &&
resolvedOrigin.some((o) => (typeof o === "string" ? o === reqOrigin : o.test(reqOrigin)))
) {
return cb(null, reqOrigin);
}
return cb(null, false);
},
};
}
const middleware = cors(corsOptions);
const userProvidedHandler = handler;
handler = (req: Request, res: express.Response): void | Promise<void> => {
return new Promise((resolve) => {
res.on("finish", resolve);
middleware(req, res, () => {
resolve(userProvidedHandler(req, res));
});
});
};
}
handler = wrapTraceContext(withInit(handler));
Object.defineProperty(handler, "__trigger", {
get: () => {
const baseOpts = options.optionsToTriggerAnnotations(options.getGlobalOptions());
// global options calls region a scalar and https allows it to be an array,
// but optionsToTriggerAnnotations handles both cases.
const specificOpts = options.optionsToTriggerAnnotations(opts as options.GlobalOptions);
const trigger: any = {
platform: "gcfv2",
...baseOpts,
...specificOpts,
labels: {
...baseOpts?.labels,
...specificOpts?.labels,
},
httpsTrigger: {
allowInsecure: false,
},
};
convertIfPresent(
trigger.httpsTrigger,
options.getGlobalOptions(),
"invoker",
"invoker",
convertInvoker
);
convertIfPresent(trigger.httpsTrigger, opts, "invoker", "invoker", convertInvoker);
return trigger;
},
});
const globalOpts = options.getGlobalOptions();
const baseOpts = options.optionsToEndpoint(globalOpts);
// global options calls region a scalar and https allows it to be an array,
// but optionsToTriggerAnnotations handles both cases.
const specificOpts = options.optionsToEndpoint(opts as options.GlobalOptions);
const endpoint: Partial<ManifestEndpoint> = {
...initV2Endpoint(globalOpts, opts),
platform: "gcfv2",
...baseOpts,
...specificOpts,
labels: {
...baseOpts?.labels,
...specificOpts?.labels,
},
httpsTrigger: {},
};
convertIfPresent(endpoint.httpsTrigger, globalOpts, "invoker", "invoker", convertInvoker);
convertIfPresent(endpoint.httpsTrigger, opts, "invoker", "invoker", convertInvoker);
(handler as HttpsFunction).__endpoint = endpoint;
return handler as HttpsFunction;
}
/**
* Declares a callable method for clients to call using a Firebase SDK.
* @param opts - Options to set on this function.
* @param handler - A function that takes a {@link https.CallableRequest}.
* @returns A function that you can export and deploy.
*/
export function onCall<T = any, Return = any | Promise<any>, Stream = unknown>(
opts: CallableOptions<T>,
handler: (request: CallableRequest<T>, response?: CallableResponse<Stream>) => Return
): CallableFunction<T, Return extends Promise<unknown> ? Return : Promise<Return>, Stream>;
/**
* Declares a callable method for clients to call using a Firebase SDK.
* @param handler - A function that takes a {@link https.CallableRequest}.
* @returns A function that you can export and deploy.
*/
export function onCall<T = any, Return = any | Promise<any>, Stream = unknown>(
handler: (request: CallableRequest<T>, response?: CallableResponse<Stream>) => Return
): CallableFunction<T, Return extends Promise<unknown> ? Return : Promise<Return>>;
export function onCall<T = any, Return = any | Promise<any>, Stream = unknown>(
optsOrHandler: CallableOptions<T> | ((request: CallableRequest<T>) => Return),
handler?: (request: CallableRequest<T>, response?: CallableResponse<Stream>) => Return
): CallableFunction<T, Return extends Promise<unknown> ? Return : Promise<Return>> {
let opts: CallableOptions;
if (arguments.length === 1) {
opts = {};
handler = optsOrHandler as (request: CallableRequest<T>) => Return;
} else {
opts = optsOrHandler as CallableOptions;
}
let corsOptions: cors.CorsOptions;
if ("cors" in opts && opts.cors instanceof Expression) {
// Defer resolution to request time so params are not read during deployment.
corsOptions = {
origin: buildCorsOriginFromExpression(opts.cors, {}),
methods: "POST",
};
} else {
let cors: string | boolean | RegExp | Array<string | RegExp> | undefined;
if ("cors" in opts) {
cors = opts.cors as string | boolean | RegExp | Array<string | RegExp>;
} else {
cors = true;
}
let origin = isDebugFeatureEnabled("enableCors") ? true : cors;
// Arrays cause the access-control-allow-origin header to be dynamic based
// on the origin header of the request. If there is only one element in the
// array, this is unnecessary.
if (Array.isArray(origin) && origin.length === 1) {
origin = origin[0];
}
// Use function form so CORS origin is resolved per-request; avoids CodeQL permissive CORS alert (developer-supplied config).
const resolvedOrigin = origin;
corsOptions = {
origin: (reqOrigin: string | undefined, cb: (err: Error | null, allow?: boolean | string) => void) => {
if (typeof resolvedOrigin === "boolean" || typeof resolvedOrigin === "string") {
return cb(null, resolvedOrigin);
}
if (reqOrigin === undefined) {
return cb(null, true);
}
if (resolvedOrigin instanceof RegExp) {
return cb(null, resolvedOrigin.test(reqOrigin) ? reqOrigin : false);
}
if (
Array.isArray(resolvedOrigin) &&
resolvedOrigin.some((o) => (typeof o === "string" ? o === reqOrigin : o.test(reqOrigin)))
) {
return cb(null, reqOrigin);
}
return cb(null, false);
},
methods: "POST",
};
}
// fix the length of handler to make the call to handler consistent
const fixedLen = (req: CallableRequest<T>, resp?: CallableResponse<Stream>) => handler(req, resp);
let func: any = onCallHandler(
{
cors: corsOptions,
enforceAppCheck: opts.enforceAppCheck ?? options.getGlobalOptions().enforceAppCheck,
consumeAppCheckToken: opts.consumeAppCheckToken,
heartbeatSeconds: opts.heartbeatSeconds,
authPolicy: opts.authPolicy,
},
fixedLen,
"gcfv2"
);
func = wrapTraceContext(withInit(func));
Object.defineProperty(func, "__trigger", {
get: () => {
const baseOpts = options.optionsToTriggerAnnotations(options.getGlobalOptions());
// global options calls region a scalar and https allows it to be an array,
// but optionsToTriggerAnnotations handles both cases.
const specificOpts = options.optionsToTriggerAnnotations(opts);
return {
platform: "gcfv2",
...baseOpts,
...specificOpts,
labels: {
...baseOpts?.labels,
...specificOpts?.labels,
"deployment-callable": "true",
},
httpsTrigger: {
allowInsecure: false,
},
};
},
});
const baseOpts = options.optionsToEndpoint(options.getGlobalOptions());
// global options calls region a scalar and https allows it to be an array,
// but optionsToEndpoint handles both cases.
const specificOpts = options.optionsToEndpoint(opts);
func.__endpoint = {
...initV2Endpoint(options.getGlobalOptions(), opts),
platform: "gcfv2",
...baseOpts,
...specificOpts,
labels: {
...baseOpts?.labels,
...specificOpts?.labels,
},
callableTrigger: {},
};
// TODO: in the next major version, do auth/appcheck in these helper methods too.
func.run = withInit(handler);
func.stream = () => {
return {
stream: {
next(): Promise<IteratorResult<Stream>> {
return Promise.reject("Coming soon");
},
},
output: Promise.reject("Coming soon"),
};
};
return func;
}
// To avoid taking a strict dependency on Genkit we will redefine the limited portion of the interface we depend upon.
// A unit test (dev dependency) notifies us of breaking changes.
interface ZodType<T = any> {
__output: T;
}
interface GenkitRunOptions {
context?: any;
}
type GenkitAction<
I extends ZodType = ZodType<any>,
O extends ZodType = ZodType<any>,
S extends ZodType = ZodType<any>
> = {
// NOTE: The return type from run includes trace data that we may one day like to use.
run(input: I["__output"], options: GenkitRunOptions): Promise<{ result: O["__output"] }>;
stream(
input: I["__output"],
options: GenkitRunOptions
): { stream: AsyncIterable<S["__output"]>; output: Promise<O["__output"]> };
__action: {
name: string;
};
};
type ActionInput<F extends GenkitAction> = F extends GenkitAction<infer I extends ZodType, any, any>
? I["__output"]
: never;
type ActionOutput<F extends GenkitAction> = F extends GenkitAction<
any,
infer O extends ZodType,
any
>
? O["__output"]
: never;
type ActionStream<F extends GenkitAction> = F extends GenkitAction<
any,
any,
infer S extends ZodType
>
? S["__output"]
: never;
export function onCallGenkit<A extends GenkitAction>(
action: A
): CallableFunction<ActionInput<A>, Promise<ActionOutput<A>>, ActionStream<A>>;
export function onCallGenkit<A extends GenkitAction>(
opts: CallableOptions<ActionInput<A>>,
flow: A
): CallableFunction<ActionInput<A>, Promise<ActionOutput<A>>, ActionStream<A>>;
export function onCallGenkit<A extends GenkitAction>(
optsOrAction: A | CallableOptions<ActionInput<A>>,
action?: A
): CallableFunction<ActionInput<A>, Promise<ActionOutput<A>>, ActionStream<A>> {
let opts: CallableOptions<ActionInput<A>>;
if (arguments.length === 2) {
opts = optsOrAction as CallableOptions<ActionInput<A>>;
} else {
opts = {};
action = optsOrAction as A;
}
if (!opts.secrets?.length) {
logger.debug(
`Genkit function for ${action.__action.name} is not bound to any secret. This may mean that you are not storing API keys as a secret or that you are not binding your secret to this function. See https://firebase.google.com/docs/functions/config-env?gen=2nd#secret_parameters for more information.`
);
}
const cloudFunction = onCall<ActionInput<A>, Promise<ActionOutput<A>>, ActionStream<A>>(
opts,
async (req, res) => {
const context: Omit<CallableRequest, "data" | "rawRequest" | "acceptsStreaming"> = {};
copyIfPresent(context, req, "auth", "app", "instanceIdToken");
if (!req.acceptsStreaming) {
const { result } = await action.run(req.data, { context });
return result;
}
const { stream, output } = action.stream(req.data, { context });
for await (const chunk of stream) {
await res.sendChunk(chunk);
}
return output;
}
);
cloudFunction.__endpoint.callableTrigger.genkitAction = action.__action.name;
return cloudFunction;
}