serverless-offline 9.1.7 → 9.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/package.json +4 -10
  2. package/src/ServerlessOffline.js +3 -3
  3. package/src/lambda/LambdaFunction.js +1 -4
  4. package/src/lambda/handler-runner/HandlerRunner.js +3 -11
  5. package/src/lambda/handler-runner/child-process-runner/ChildProcessRunner.js +9 -6
  6. package/src/lambda/handler-runner/child-process-runner/childProcessHelper.js +8 -5
  7. package/src/lambda/handler-runner/go-runner/GoRunner.js +3 -1
  8. package/src/lambda/handler-runner/in-process-runner/InProcessRunner.js +16 -34
  9. package/src/lambda/handler-runner/in-process-runner/aws-lambda-ric/UserFunction.js +359 -0
  10. package/src/lambda/{__tests__/fixtures → handler-runner/in-process-runner/aws-lambda-ric}/package.json +0 -0
  11. package/src/lambda/handler-runner/python-runner/PythonRunner.js +17 -19
  12. package/src/lambda/handler-runner/ruby-runner/RubyRunner.js +4 -1
  13. package/src/lambda/handler-runner/worker-thread-runner/WorkerThreadRunner.js +5 -6
  14. package/src/lambda/handler-runner/worker-thread-runner/workerThreadHelper.js +8 -5
  15. package/src/lambda/__tests__/LambdaContext.test.js +0 -30
  16. package/src/lambda/__tests__/LambdaFunction.test.js +0 -196
  17. package/src/lambda/__tests__/fixtures/Lambda/LambdaFunctionThatReturnsJSONObject.fixture.js +0 -47
  18. package/src/lambda/__tests__/fixtures/Lambda/LambdaFunctionThatReturnsNativeString.fixture.js +0 -46
  19. package/src/lambda/__tests__/fixtures/Lambda/package.json +0 -3
  20. package/src/lambda/__tests__/fixtures/lambdaFunction.fixture.js +0 -145
  21. package/src/lambda/__tests__/routes/invocations/InvocationsController.test.js +0 -42
  22. package/src/utils/__tests__/createUniqueId.test.js +0 -18
  23. package/src/utils/__tests__/formatToClfTime.test.js +0 -14
  24. package/src/utils/__tests__/generateHapiPath.test.js +0 -46
  25. package/src/utils/__tests__/lowerCaseKeys.test.js +0 -30
  26. package/src/utils/__tests__/parseHeaders.test.js +0 -13
  27. package/src/utils/__tests__/parseMultiValueHeaders.test.js +0 -24
  28. package/src/utils/__tests__/parseMultiValueQueryStringParameters.test.js +0 -159
  29. package/src/utils/__tests__/parseQueryStringParameters.test.js +0 -15
  30. package/src/utils/__tests__/splitHandlerPathAndName.test.js +0 -54
  31. package/src/utils/__tests__/unflatten.test.js +0 -32
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "dedicatedTo": "Blue, a great migrating bird.",
3
3
  "name": "serverless-offline",
4
- "version": "9.1.7",
4
+ "version": "9.2.2",
5
5
  "description": "Emulate AWS λ and API Gateway locally when developing your Serverless project",
6
6
  "license": "MIT",
7
7
  "main": "./src/index.js",
@@ -49,12 +49,6 @@
49
49
  "schedule",
50
50
  "websocket"
51
51
  ],
52
- "files": [
53
- "src/**",
54
- "package.json",
55
- "LICENSE",
56
- "README.md"
57
- ],
58
52
  "author": "David Hérault <dherault@gmail.com> (https://github.com/dherault)",
59
53
  "maintainers": [
60
54
  "Bilal Soylu (https://github.com/Bilal-S)",
@@ -195,7 +189,7 @@
195
189
  "@hapi/h2o2": "^9.1.0",
196
190
  "@hapi/hapi": "^20.2.2",
197
191
  "@serverless/utils": "^6.7.0",
198
- "aws-sdk": "^2.1187.0",
192
+ "aws-sdk": "^2.1195.0",
199
193
  "boxen": "^7.0.0",
200
194
  "chalk": "^5.0.1",
201
195
  "execa": "^6.1.0",
@@ -217,7 +211,7 @@
217
211
  },
218
212
  "devDependencies": {
219
213
  "archiver": "^5.3.1",
220
- "eslint": "^8.21.0",
214
+ "eslint": "^8.22.0",
221
215
  "eslint-config-airbnb-base": "^15.0.0",
222
216
  "eslint-config-prettier": "^8.5.0",
223
217
  "eslint-plugin-import": "^2.25.4",
@@ -227,7 +221,7 @@
227
221
  "lint-staged": "^13.0.3",
228
222
  "mocha": "^10.0.0",
229
223
  "prettier": "^2.7.1",
230
- "serverless": "^3.21.0",
224
+ "serverless": "^3.22.0",
231
225
  "standard-version": "^9.5.0"
232
226
  },
233
227
  "peerDependencies": {
@@ -245,9 +245,9 @@ export default class ServerlessOffline {
245
245
 
246
246
  log.notice()
247
247
  log.notice(
248
- `Starting Offline at stage ${provider.stage} ${chalk.gray(
249
- `(${provider.region})`,
250
- )}`,
248
+ `Starting Offline at stage ${
249
+ this.#options.stage || provider.stage
250
+ } ${chalk.gray(`(${this.#options.region || provider.region})`)}`,
251
251
  )
252
252
  log.notice()
253
253
  log.debug('options:', this.#options)
@@ -13,7 +13,7 @@ import {
13
13
  DEFAULT_LAMBDA_TIMEOUT,
14
14
  supportedRuntimes,
15
15
  } from '../config/index.js'
16
- import { createUniqueId, splitHandlerPathAndName } from '../utils/index.js'
16
+ import { createUniqueId } from '../utils/index.js'
17
17
 
18
18
  const { ceil } = Math
19
19
  const { entries, fromEntries } = Object
@@ -70,7 +70,6 @@ export default class LambdaFunction {
70
70
  const servicepath = resolve(servicePath, options.location || '')
71
71
 
72
72
  const { handler, name, package: functionPackage = {} } = functionDefinition
73
- const [handlerPath, handlerName] = splitHandlerPathAndName(handler)
74
73
 
75
74
  const memorySize =
76
75
  functionDefinition.memorySize ||
@@ -140,8 +139,6 @@ export default class LambdaFunction {
140
139
  ? resolve(servicepath, functionPackage.artifact)
141
140
  : undefined,
142
141
  handler,
143
- handlerName,
144
- handlerPath: resolve(this.#codeDir, handlerPath),
145
142
  layers: functionDefinition.layers || [],
146
143
  provider,
147
144
  runtime,
@@ -24,11 +24,9 @@ export default class HandlerRunner {
24
24
 
25
25
  async #loadRunner() {
26
26
  const { useChildProcesses, useDocker, useInProcess } = this.#options
27
+ const { handler, runtime } = this.#funOptions
27
28
 
28
- const { functionKey, handlerName, handlerPath, runtime, timeout } =
29
- this.#funOptions
30
-
31
- log.debug(`Loading handler... (${handlerPath})`)
29
+ log.debug(`Loading handler... (${handler})`)
32
30
 
33
31
  if (useDocker) {
34
32
  // https://github.com/lambci/docker-lambda/issues/329
@@ -71,13 +69,7 @@ export default class HandlerRunner {
71
69
  './in-process-runner/index.js'
72
70
  )
73
71
 
74
- return new InProcessRunner(
75
- functionKey,
76
- handlerPath,
77
- handlerName,
78
- this.#env,
79
- timeout,
80
- )
72
+ return new InProcessRunner(this.#funOptions, this.#env)
81
73
  }
82
74
 
83
75
  const { default: WorkerThreadRunner } = await import(
@@ -7,23 +7,26 @@ const __dirname = dirname(fileURLToPath(import.meta.url))
7
7
  const childProcessHelperPath = resolve(__dirname, 'childProcessHelper.js')
8
8
 
9
9
  export default class ChildProcessRunner {
10
+ #codeDir = null
11
+
10
12
  #env = null
11
13
 
12
14
  #functionKey = null
13
15
 
14
- #handlerName = null
16
+ #handler = null
15
17
 
16
- #handlerPath = null
18
+ #servicePath = null
17
19
 
18
20
  #timeout = null
19
21
 
20
22
  constructor(funOptions, env) {
21
- const { functionKey, handlerName, handlerPath, timeout } = funOptions
23
+ const { codeDir, functionKey, handler, servicePath, timeout } = funOptions
22
24
 
25
+ this.#codeDir = codeDir
23
26
  this.#env = env
24
27
  this.#functionKey = functionKey
25
- this.#handlerName = handlerName
26
- this.#handlerPath = handlerPath
28
+ this.#handler = handler
29
+ this.#servicePath = servicePath
27
30
  this.#timeout = timeout
28
31
  }
29
32
 
@@ -34,7 +37,7 @@ export default class ChildProcessRunner {
34
37
  async run(event, context) {
35
38
  const childProcess = execaNode(
36
39
  childProcessHelperPath,
37
- [this.#functionKey, this.#handlerName, this.#handlerPath],
40
+ [this.#functionKey, this.#handler, this.#servicePath, this.#codeDir],
38
41
  {
39
42
  env: this.#env,
40
43
  stdio: 'inherit',
@@ -21,18 +21,21 @@ process.on('uncaughtException', (err) => {
21
21
  })
22
22
  })
23
23
 
24
- const [, , functionKey, handlerName, handlerPath] = argv
24
+ const [, , functionKey, handler, servicePath, codeDir] = argv
25
25
 
26
26
  process.on('message', async (messageData) => {
27
27
  const { context, event, timeout } = messageData
28
28
 
29
29
  // TODO we could probably cache this in the module scope?
30
30
  const inProcessRunner = new InProcessRunner(
31
- functionKey,
32
- handlerPath,
33
- handlerName,
31
+ {
32
+ codeDir,
33
+ functionKey,
34
+ handler,
35
+ servicePath,
36
+ timeout,
37
+ },
34
38
  process.env,
35
- timeout,
36
39
  )
37
40
 
38
41
  const result = await inProcessRunner.run(event, context)
@@ -4,6 +4,7 @@ import process, { chdir, cwd } from 'node:process'
4
4
  import { parse as pathParse, resolve, sep } from 'node:path'
5
5
  import { log } from '@serverless/utils/log.js'
6
6
  import { execa } from 'execa'
7
+ import { splitHandlerPathAndName } from '../../../utils/index.js'
7
8
 
8
9
  const { parse, stringify } = JSON
9
10
 
@@ -23,7 +24,8 @@ export default class GoRunner {
23
24
  #tmpPath = null
24
25
 
25
26
  constructor(funOptions, env) {
26
- const { handlerPath, codeDir } = funOptions
27
+ const { handler, codeDir } = funOptions
28
+ const [handlerPath] = splitHandlerPathAndName(handler)
27
29
 
28
30
  this.#codeDir = codeDir
29
31
  this.#env = env
@@ -1,29 +1,32 @@
1
- import { createRequire } from 'node:module'
1
+ import { join } from 'node:path'
2
2
  import { performance } from 'node:perf_hooks'
3
3
  import process from 'node:process'
4
- import { log } from '@serverless/utils/log.js'
4
+ import { load } from './aws-lambda-ric/UserFunction.js'
5
5
 
6
6
  const { floor } = Math
7
7
  const { assign } = Object
8
8
 
9
- const require = createRequire(import.meta.url)
10
-
11
9
  export default class InProcessRunner {
10
+ #codeDir = null
11
+
12
12
  #env = null
13
13
 
14
14
  #functionKey = null
15
15
 
16
- #handlerName = null
16
+ #handler = null
17
17
 
18
- #handlerPath = null
18
+ #servicePath = null
19
19
 
20
20
  #timeout = null
21
21
 
22
- constructor(functionKey, handlerPath, handlerName, env, timeout) {
22
+ constructor(funOptions, env) {
23
+ const { codeDir, functionKey, handler, servicePath, timeout } = funOptions
24
+
25
+ this.#codeDir = codeDir
23
26
  this.#env = env
24
27
  this.#functionKey = functionKey
25
- this.#handlerName = handlerName
26
- this.#handlerPath = handlerPath
28
+ this.#handler = handler
29
+ this.#servicePath = servicePath
27
30
  this.#timeout = timeout
28
31
  }
29
32
 
@@ -32,37 +35,16 @@ export default class InProcessRunner {
32
35
  cleanup() {}
33
36
 
34
37
  async run(event, context) {
35
- // check if the handler module path exists
36
- if (!require.resolve(this.#handlerPath)) {
37
- throw new Error(
38
- `Could not find handler module '${this.#handlerPath}' for function '${
39
- this.#functionKey
40
- }'.`,
41
- )
42
- }
43
-
44
38
  // process.env should be available in the handler module scope as well as in the handler function scope
45
39
  // NOTE: Don't use Object spread (...) here!
46
40
  // otherwise the values of the attached props are not coerced to a string
47
41
  // e.g. process.env.foo = 1 should be coerced to '1' (string)
48
42
  assign(process.env, this.#env)
49
43
 
50
- let handler
51
-
52
- try {
53
- // eslint-disable-next-line import/no-dynamic-require
54
- ;({ [this.#handlerName]: handler } = require(this.#handlerPath))
55
- } catch (err) {
56
- log.error(err)
57
- }
58
-
59
- if (typeof handler !== 'function') {
60
- throw new Error(
61
- `offline: handler '${this.#handlerName}' in ${
62
- this.#handlerPath
63
- } is not a function`,
64
- )
65
- }
44
+ const handler = await load(
45
+ this.#servicePath,
46
+ join(this.#codeDir, this.#handler),
47
+ )
66
48
 
67
49
  let callback
68
50
 
@@ -0,0 +1,359 @@
1
+ 'use strict'
2
+
3
+ const { pathToFileURL } = require('node:url')
4
+
5
+ // node_modules/lambda-runtime/dist/node16/UserFunction.js
6
+ ;(function () {
7
+ const __getOwnPropNames = Object.getOwnPropertyNames
8
+ const __commonJS = (cb, mod) =>
9
+ function __require() {
10
+ return (
11
+ mod ||
12
+ (0, cb[__getOwnPropNames(cb)[0]])(
13
+ (mod = { exports: {} }).exports,
14
+ mod,
15
+ ),
16
+ mod.exports
17
+ )
18
+ }
19
+ const require_Errors = __commonJS({
20
+ 'Errors.js': function (exports2, module2) {
21
+ 'use strict'
22
+
23
+ const util = require('util')
24
+ function _isError(obj) {
25
+ return (
26
+ obj &&
27
+ obj.name &&
28
+ obj.message &&
29
+ obj.stack &&
30
+ typeof obj.name === 'string' &&
31
+ typeof obj.message === 'string' &&
32
+ typeof obj.stack === 'string'
33
+ )
34
+ }
35
+ function intoError(err) {
36
+ if (err instanceof Error) {
37
+ return err
38
+ }
39
+ return new Error(err)
40
+ }
41
+ module2.exports.intoError = intoError
42
+ function toRapidResponse(error) {
43
+ try {
44
+ if (util.types.isNativeError(error) || _isError(error)) {
45
+ return {
46
+ errorType: error.name,
47
+ errorMessage: error.message,
48
+ trace: error.stack.split('\n'),
49
+ }
50
+ }
51
+ return {
52
+ errorType: typeof error,
53
+ errorMessage: error.toString(),
54
+ trace: [],
55
+ }
56
+ } catch (_err) {
57
+ return {
58
+ errorType: 'handled',
59
+ errorMessage:
60
+ 'callback called with Error argument, but there was a problem while retrieving one or more of its message, name, and stack',
61
+ }
62
+ }
63
+ }
64
+ module2.exports.toRapidResponse = toRapidResponse
65
+ module2.exports.toFormatted = (error) => {
66
+ try {
67
+ return ` ${JSON.stringify(error, (_k, v) =>
68
+ _withEnumerableProperties(v),
69
+ )}`
70
+ } catch (err) {
71
+ return ` ${JSON.stringify(toRapidResponse(error))}`
72
+ }
73
+ }
74
+ function _withEnumerableProperties(error) {
75
+ if (error instanceof Error) {
76
+ const ret = {
77
+ errorType: error.name,
78
+ errorMessage: error.message,
79
+ code: error.code,
80
+ ...error,
81
+ }
82
+ if (typeof error.stack === 'string') {
83
+ ret.stack = error.stack.split('\n')
84
+ }
85
+ return ret
86
+ }
87
+ return error
88
+ }
89
+ const errorClasses = [
90
+ class ImportModuleError extends Error {},
91
+ class HandlerNotFound extends Error {},
92
+ class MalformedHandlerName extends Error {},
93
+ class UserCodeSyntaxError extends Error {},
94
+ class MalformedStreamingHandler extends Error {},
95
+ class InvalidStreamingOperation extends Error {},
96
+ class UnhandledPromiseRejection extends Error {
97
+ constructor(reason, promise) {
98
+ super(reason)
99
+ this.reason = reason
100
+ this.promise = promise
101
+ }
102
+ },
103
+ ]
104
+ errorClasses.forEach((e) => {
105
+ module2.exports[e.name] = e
106
+ e.prototype.name = `Runtime.${e.name}`
107
+ })
108
+ },
109
+ })
110
+ const require_VerboseLog = __commonJS({
111
+ 'VerboseLog.js': function (exports2) {
112
+ 'use strict'
113
+
114
+ const EnvVarName = 'AWS_LAMBDA_RUNTIME_VERBOSE'
115
+ const Tag = 'RUNTIME'
116
+ const Verbosity = (() => {
117
+ if (!process.env[EnvVarName]) {
118
+ return 0
119
+ }
120
+ try {
121
+ const verbosity = parseInt(process.env[EnvVarName])
122
+ return verbosity < 0 ? 0 : verbosity > 3 ? 3 : verbosity
123
+ } catch (_) {
124
+ return 0
125
+ }
126
+ })()
127
+ exports2.logger = function (category) {
128
+ return {
129
+ verbose() {
130
+ if (Verbosity >= 1) {
131
+ console.log.apply(null, [Tag, category, ...arguments])
132
+ }
133
+ },
134
+ vverbose() {
135
+ if (Verbosity >= 2) {
136
+ console.log.apply(null, [Tag, category, ...arguments])
137
+ }
138
+ },
139
+ vvverbose() {
140
+ if (Verbosity >= 3) {
141
+ console.log.apply(null, [Tag, category, ...arguments])
142
+ }
143
+ },
144
+ }
145
+ }
146
+ },
147
+ })
148
+ const require_HttpResponseStream = __commonJS({
149
+ 'HttpResponseStream.js': function (exports2, module2) {
150
+ 'use strict'
151
+
152
+ const METADATA_PRELUDE_CONTENT_TYPE =
153
+ 'application/vnd.awslambda.http-integration-response'
154
+ const DELIMITER_LEN = 8
155
+ const HttpResponseStream2 = class {
156
+ static from(underlyingStream, prelude) {
157
+ underlyingStream.setContentType(METADATA_PRELUDE_CONTENT_TYPE)
158
+ const metadataPrelude = JSON.stringify(prelude)
159
+ underlyingStream._onBeforeFirstWrite = (write) => {
160
+ write(metadataPrelude)
161
+ write(new Uint8Array(DELIMITER_LEN))
162
+ }
163
+ return underlyingStream
164
+ }
165
+ }
166
+ module2.exports.HttpResponseStream = HttpResponseStream2
167
+ },
168
+ })
169
+ const path = require('path')
170
+ const fs = require('fs')
171
+ const {
172
+ HandlerNotFound,
173
+ MalformedHandlerName,
174
+ ImportModuleError,
175
+ UserCodeSyntaxError,
176
+ } = require_Errors()
177
+ const { verbose } = require_VerboseLog().logger('LOADER')
178
+ const { HttpResponseStream } = require_HttpResponseStream()
179
+ const FUNCTION_EXPR = /^([^.]*)\.(.*)$/
180
+ const RELATIVE_PATH_SUBSTRING = '..'
181
+ const HANDLER_STREAMING = Symbol.for('aws.lambda.runtime.handler.streaming')
182
+ const STREAM_RESPONSE = 'response'
183
+ const NoGlobalAwsLambda =
184
+ process.env.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA === '1' ||
185
+ process.env.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA === 'true'
186
+ function _moduleRootAndHandler(fullHandlerString) {
187
+ const handlerString = path.basename(fullHandlerString)
188
+ const moduleRoot = fullHandlerString.substring(
189
+ 0,
190
+ fullHandlerString.indexOf(handlerString),
191
+ )
192
+ return [moduleRoot, handlerString]
193
+ }
194
+ function _splitHandlerString(handler) {
195
+ const match = handler.match(FUNCTION_EXPR)
196
+ if (!match || match.length != 3) {
197
+ throw new MalformedHandlerName('Bad handler')
198
+ }
199
+ return [match[1], match[2]]
200
+ }
201
+ function _resolveHandler(object, nestedProperty) {
202
+ return nestedProperty.split('.').reduce((nested, key) => {
203
+ return nested && nested[key]
204
+ }, object)
205
+ }
206
+ function _tryRequireFile(file, extension) {
207
+ const path2 = file + (extension || '')
208
+ verbose('Try loading as commonjs:', path2)
209
+ return fs.existsSync(path2) ? require(path2) : void 0
210
+ }
211
+ async function _tryAwaitImport(file, extension) {
212
+ const path2 = file + (extension || '')
213
+ verbose('Try loading as esmodule:', path2)
214
+ if (fs.existsSync(path2)) {
215
+ return await import(pathToFileURL(path2).href)
216
+ }
217
+ return void 0
218
+ }
219
+ function _hasFolderPackageJsonTypeModule(folder) {
220
+ if (folder.endsWith('/node_modules')) {
221
+ return false
222
+ }
223
+ const pj = path.join(folder, '/package.json')
224
+ if (fs.existsSync(pj)) {
225
+ try {
226
+ const pkg = JSON.parse(fs.readFileSync(pj))
227
+ if (pkg) {
228
+ if (pkg.type === 'module') {
229
+ verbose(`'type: module' detected in ${pj}`)
230
+ return true
231
+ }
232
+ verbose(`'type: module' not detected in ${pj}`)
233
+ return false
234
+ }
235
+ } catch (e) {
236
+ console.warn(
237
+ `${pj} cannot be read, it will be ignored for ES module detection purposes.`,
238
+ e,
239
+ )
240
+ return false
241
+ }
242
+ }
243
+ if (folder === '/') {
244
+ return false
245
+ }
246
+ return _hasFolderPackageJsonTypeModule(path.resolve(folder, '..'))
247
+ }
248
+ function _hasPackageJsonTypeModule(file) {
249
+ const jsPath = `${file}.js`
250
+ return fs.existsSync(jsPath)
251
+ ? _hasFolderPackageJsonTypeModule(path.resolve(path.dirname(jsPath)))
252
+ : false
253
+ }
254
+ async function _tryRequire(appRoot, moduleRoot, module2) {
255
+ verbose(
256
+ 'Try loading as commonjs: ',
257
+ module2,
258
+ ' with paths: ,',
259
+ appRoot,
260
+ moduleRoot,
261
+ )
262
+ const lambdaStylePath = path.resolve(appRoot, moduleRoot, module2)
263
+ const extensionless = _tryRequireFile(lambdaStylePath)
264
+ if (extensionless) {
265
+ return extensionless
266
+ }
267
+ const pjHasModule = _hasPackageJsonTypeModule(lambdaStylePath)
268
+ if (!pjHasModule) {
269
+ const loaded2 = _tryRequireFile(lambdaStylePath, '.js')
270
+ if (loaded2) {
271
+ return loaded2
272
+ }
273
+ }
274
+ const loaded =
275
+ (pjHasModule && (await _tryAwaitImport(lambdaStylePath, '.js'))) ||
276
+ (await _tryAwaitImport(lambdaStylePath, '.mjs')) ||
277
+ _tryRequireFile(lambdaStylePath, '.cjs')
278
+ if (loaded) {
279
+ return loaded
280
+ }
281
+ verbose(
282
+ 'Try loading as commonjs: ',
283
+ module2,
284
+ ' with path(s): ',
285
+ appRoot,
286
+ moduleRoot,
287
+ )
288
+ const nodeStylePath = require.resolve(module2, {
289
+ paths: [appRoot, moduleRoot],
290
+ })
291
+ return require(nodeStylePath)
292
+ }
293
+ async function _loadUserApp(appRoot, moduleRoot, module2) {
294
+ if (!NoGlobalAwsLambda) {
295
+ globalThis.awslambda = {
296
+ streamifyResponse: (handler) => {
297
+ handler[HANDLER_STREAMING] = STREAM_RESPONSE
298
+ return handler
299
+ },
300
+ HttpResponseStream,
301
+ }
302
+ }
303
+ try {
304
+ return await _tryRequire(appRoot, moduleRoot, module2)
305
+ } catch (e) {
306
+ if (e instanceof SyntaxError) {
307
+ throw new UserCodeSyntaxError(e)
308
+ } else if (e.code !== void 0 && e.code === 'MODULE_NOT_FOUND') {
309
+ verbose('globalPaths', JSON.stringify(require('module').globalPaths))
310
+ throw new ImportModuleError(e)
311
+ } else {
312
+ throw e
313
+ }
314
+ }
315
+ }
316
+ function _throwIfInvalidHandler(fullHandlerString) {
317
+ if (fullHandlerString.includes(RELATIVE_PATH_SUBSTRING)) {
318
+ throw new MalformedHandlerName(
319
+ `'${fullHandlerString}' is not a valid handler name. Use absolute paths when specifying root directories in handler names.`,
320
+ )
321
+ }
322
+ }
323
+ function _isHandlerStreaming(handler) {
324
+ if (
325
+ typeof handler[HANDLER_STREAMING] === 'undefined' ||
326
+ handler[HANDLER_STREAMING] === null ||
327
+ handler[HANDLER_STREAMING] === false
328
+ ) {
329
+ return false
330
+ }
331
+ if (handler[HANDLER_STREAMING] === STREAM_RESPONSE) {
332
+ return STREAM_RESPONSE
333
+ }
334
+ throw new MalformedStreamingHandler('Only response streaming is supported.')
335
+ }
336
+ module.exports.load = async function (appRoot, fullHandlerString) {
337
+ _throwIfInvalidHandler(fullHandlerString)
338
+ const [moduleRoot, moduleAndHandler] =
339
+ _moduleRootAndHandler(fullHandlerString)
340
+ const [module2, handlerPath] = _splitHandlerString(moduleAndHandler)
341
+ const userApp = await _loadUserApp(appRoot, moduleRoot, module2)
342
+ const handlerFunc = _resolveHandler(userApp, handlerPath)
343
+ if (!handlerFunc) {
344
+ throw new HandlerNotFound(
345
+ `${fullHandlerString} is undefined or not exported`,
346
+ )
347
+ }
348
+ if (typeof handlerFunc !== 'function') {
349
+ throw new HandlerNotFound(`${fullHandlerString} is not a function`)
350
+ }
351
+ return handlerFunc
352
+ }
353
+ module.exports.getHandlerMetadata = function (handlerFunc) {
354
+ return {
355
+ streaming: _isHandlerStreaming(handlerFunc),
356
+ }
357
+ }
358
+ module.exports.STREAM_RESPONSE = STREAM_RESPONSE
359
+ })()