@@ -21,13 +21,22 @@ import {getUserFunction} from './loader';
2121import { ErrorHandler } from './invoker' ;
2222import { getServer } from './server' ;
2323import { parseOptions , helpText , OptionsError } from './options' ;
24+ import {
25+ HttpFunction ,
26+ EventFunction ,
27+ CloudEventFunction ,
28+ HandlerFunction ,
29+ } from './functions' ;
2430import { loggingHandlerAddExecutionContext } from './logger' ;
2531
2632/**
2733 * Main entrypoint for the functions framework that loads the user's function
2834 * and starts the HTTP server.
35+ * @param code - A function to be executed.
2936 */
30- export const main = async ( ) => {
37+ export const main = async (
38+ code ?: HttpFunction | EventFunction | CloudEventFunction ,
39+ ) => {
3140 try {
3241 const options = parseOptions ( ) ;
3342
@@ -40,11 +49,21 @@ export const main = async () => {
4049 loggingHandlerAddExecutionContext ( ) ;
4150 }
4251
43- const loadedFunction = await getUserFunction (
44- options . sourceLocation ,
45- options . target ,
46- options . signatureType ,
47- ) ;
52+ let loadedFunction ;
53+ // If a function is provided directly, use it.
54+ if ( code ) {
55+ loadedFunction = {
56+ userFunction : code ,
57+ signatureType : options . signatureType || 'http' ,
58+ } ;
59+ } else {
60+ // Otherwise, load the function from file.
61+ loadedFunction = await getUserFunction (
62+ options . sourceLocation ,
63+ options . target ,
64+ options . signatureType ,
65+ ) ;
66+ }
4867 if ( ! loadedFunction ) {
4968 console . error ( 'Could not load the function, shutting down.' ) ;
5069 // eslint-disable-next-line no-process-exit
@@ -55,7 +74,7 @@ export const main = async () => {
5574 // It is possible to overwrite the configured signature type in code so we
5675 // reset it here based on what we loaded.
5776 options . signatureType = signatureType ;
58- const server = getServer ( userFunction ! , options ) ;
77+ const server = getServer ( userFunction as HandlerFunction , options ) ;
5978 const errorHandler = new ErrorHandler ( server ) ;
6079 server
6180 . listen ( options . port , ( ) => {
@@ -79,4 +98,7 @@ export const main = async () => {
7998} ;
8099
81100// Call the main method to load the user code and start the http server.
82- void main ( ) ;
101+ // Only call main if the module is not being required.
102+ if ( require . main === module ) {
103+ void main ( ) ;
104+ }
0 commit comments