@h4ad/serverless-adapter 4.2.1 → 4.2.3

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 (75) hide show
  1. package/lib/adapters/apollo-server/index.cjs +4 -3
  2. package/lib/adapters/apollo-server/index.cjs.map +1 -1
  3. package/lib/adapters/apollo-server/index.mjs +1 -1
  4. package/lib/adapters/aws/index.cjs +4 -3
  5. package/lib/adapters/aws/index.cjs.map +1 -1
  6. package/lib/adapters/aws/index.d.cts +6 -0
  7. package/lib/adapters/aws/index.d.ts +6 -0
  8. package/lib/adapters/aws/index.mjs +1 -1
  9. package/lib/adapters/aws/index.mjs.map +1 -1
  10. package/lib/adapters/azure/index.cjs +3 -2
  11. package/lib/adapters/azure/index.cjs.map +1 -1
  12. package/lib/adapters/azure/index.mjs +1 -1
  13. package/lib/adapters/digital-ocean/index.cjs +4 -3
  14. package/lib/adapters/digital-ocean/index.cjs.map +1 -1
  15. package/lib/adapters/digital-ocean/index.mjs +1 -1
  16. package/lib/adapters/dummy/index.cjs +3 -2
  17. package/lib/adapters/dummy/index.cjs.map +1 -1
  18. package/lib/adapters/dummy/index.mjs +1 -1
  19. package/lib/adapters/huawei/index.cjs +3 -2
  20. package/lib/adapters/huawei/index.cjs.map +1 -1
  21. package/lib/adapters/huawei/index.mjs +1 -1
  22. package/lib/chunk-L4VRXTKP.mjs +13 -0
  23. package/lib/chunk-L4VRXTKP.mjs.map +1 -0
  24. package/lib/{chunk-7DI442G5.mjs → chunk-N5ADYIHA.mjs} +2 -2
  25. package/lib/{chunk-TNR3TUP7.mjs → chunk-SQ2M27T2.mjs} +2 -2
  26. package/lib/frameworks/apollo-server/index.cjs +3 -2
  27. package/lib/frameworks/apollo-server/index.cjs.map +1 -1
  28. package/lib/frameworks/apollo-server/index.mjs +1 -1
  29. package/lib/frameworks/body-parser/index.cjs +3 -2
  30. package/lib/frameworks/body-parser/index.cjs.map +1 -1
  31. package/lib/frameworks/body-parser/index.mjs +1 -1
  32. package/lib/frameworks/cors/index.cjs +4 -3
  33. package/lib/frameworks/cors/index.cjs.map +1 -1
  34. package/lib/frameworks/cors/index.mjs +1 -1
  35. package/lib/frameworks/deepkit/index.cjs +3 -2
  36. package/lib/frameworks/deepkit/index.cjs.map +1 -1
  37. package/lib/frameworks/deepkit/index.mjs +1 -1
  38. package/lib/frameworks/lazy/index.cjs +3 -2
  39. package/lib/frameworks/lazy/index.cjs.map +1 -1
  40. package/lib/frameworks/lazy/index.mjs +1 -1
  41. package/lib/frameworks/trpc/index.cjs +3 -2
  42. package/lib/frameworks/trpc/index.cjs.map +1 -1
  43. package/lib/frameworks/trpc/index.mjs +1 -1
  44. package/lib/handlers/aws/index.cjs +7 -6
  45. package/lib/handlers/aws/index.cjs.map +1 -1
  46. package/lib/handlers/aws/index.mjs +1 -1
  47. package/lib/handlers/azure/index.cjs +3 -2
  48. package/lib/handlers/azure/index.cjs.map +1 -1
  49. package/lib/handlers/azure/index.mjs +1 -1
  50. package/lib/handlers/default/index.cjs +4 -3
  51. package/lib/handlers/default/index.cjs.map +1 -1
  52. package/lib/handlers/default/index.mjs +1 -1
  53. package/lib/handlers/digital-ocean/index.cjs +3 -2
  54. package/lib/handlers/digital-ocean/index.cjs.map +1 -1
  55. package/lib/handlers/digital-ocean/index.mjs +1 -1
  56. package/lib/handlers/firebase/index.cjs +3 -2
  57. package/lib/handlers/firebase/index.cjs.map +1 -1
  58. package/lib/handlers/firebase/index.mjs +1 -1
  59. package/lib/handlers/gcp/index.cjs +3 -2
  60. package/lib/handlers/gcp/index.cjs.map +1 -1
  61. package/lib/handlers/gcp/index.mjs +1 -1
  62. package/lib/handlers/huawei/index.cjs +3 -2
  63. package/lib/handlers/huawei/index.cjs.map +1 -1
  64. package/lib/handlers/huawei/index.mjs +1 -1
  65. package/lib/index.cjs +8 -7
  66. package/lib/index.cjs.map +1 -1
  67. package/lib/index.d.cts +4 -1
  68. package/lib/index.d.ts +4 -1
  69. package/lib/index.mjs +1 -1
  70. package/lib/index.mjs.map +1 -1
  71. package/package.json +1 -1
  72. package/lib/chunk-MQYXRLYI.mjs +0 -12
  73. package/lib/chunk-MQYXRLYI.mjs.map +0 -1
  74. /package/lib/{chunk-7DI442G5.mjs.map → chunk-N5ADYIHA.mjs.map} +0 -0
  75. /package/lib/{chunk-TNR3TUP7.mjs.map → chunk-SQ2M27T2.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/frameworks/cors/index.ts","../../../src/frameworks/cors/cors.framework.ts","../../../src/network/request.ts","../../../src/network/response.ts","../../../src/network/utils.ts","../../../src/network/response-stream.ts","../../../src/core/no-op.ts","../../../src/core/logger.ts","../../../src/core/optional.ts","../../../src/core/stream.ts"],"sourcesContent":["export * from './cors.framework';\n","//#region Imports\n\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport cors, { type CorsOptions } from 'cors';\nimport type { FrameworkContract } from '../../contracts';\nimport { getDefaultIfUndefined } from '../../core';\n\n//#endregion\n\n/**\n * The options to customize {@link CorsFramework}\n *\n * @breadcrumb Frameworks / CorsFramework\n * @public\n */\nexport type CorsFrameworkOptions = CorsOptions & {\n /**\n * Send error 403 when cors is invalid. From what I read in `cors`, `fastify/cors` and [this problem](https://stackoverflow.com/questions/57212248/why-is-http-request-been-processed-in-action-even-when-cors-is-not-enabled)\n * it is normal to process the request even if the origin is invalid.\n * So this option will respond with error if this method was called from an invalid origin (or not allowed method) like [access control lib](https://github.com/primus/access-control/blob/master/index.js#L95-L115) .\n *\n * @defaultValue true\n */\n forbiddenOnInvalidOriginOrMethod?: boolean;\n};\n\n/**\n * The framework that handles cors for your api without relying on internals of the framework\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { ServerlessAdapter } from '@h4ad/serverless-adapter';\n * import { ExpressFramework } from '@h4ad/serverless-adapter/lib/frameworks/express';\n * import { CorsFramework } from '@h4ad/serverless-adapter/lib/frameworks/cors';\n *\n * const expressFramework = new ExpressFramework();\n * const options: CorsOptions = {}; // customize the options\n * const framework = new CorsFramework(expressFramework, options);\n *\n * export const handler = ServerlessAdapter.new(null)\n * .setFramework(framework)\n * // set other configurations and then build\n * .build();\n * ```\n *\n * @breadcrumb Frameworks / CorsFramework\n * @public\n */\nexport class CorsFramework<TApp> implements FrameworkContract<TApp> {\n //#region Constructor\n\n /**\n * Default Constructor\n */\n constructor(\n protected readonly framework: FrameworkContract<TApp>,\n protected readonly options?: CorsFrameworkOptions,\n ) {\n this.cachedCorsInstance = cors(this.options);\n }\n\n //#endregion\n\n /**\n * All cors headers that can be added by cors package\n */\n protected readonly corsHeaders: string[] = [\n 'Access-Control-Max-Age',\n 'Access-Control-Expose-Headers',\n 'Access-Control-Allow-Headers',\n 'Access-Control-Request-Headers',\n 'Access-Control-Allow-Credentials',\n 'Access-Control-Allow-Methods',\n 'Access-Control-Allow-Origin',\n ];\n\n /**\n * The cached instance of cors\n */\n protected readonly cachedCorsInstance: ReturnType<typeof cors>;\n\n //#region Public Methods\n\n /**\n * {@inheritDoc}\n */\n public sendRequest(\n app: TApp,\n request: IncomingMessage,\n response: ServerResponse,\n ): void {\n this.cachedCorsInstance(\n request,\n response,\n this.onCorsNext(app, request, response),\n );\n }\n\n //#endregion\n\n //#region Protected Methods\n\n /**\n * Handle next execution called by the cors package\n */\n protected onCorsNext(\n app: TApp,\n request: IncomingMessage,\n response: ServerResponse,\n ): () => void {\n return () => {\n this.formatHeaderValuesAddedByCorsPackage(response);\n\n const errorOnInvalidOrigin = getDefaultIfUndefined(\n this.options?.forbiddenOnInvalidOriginOrMethod,\n true,\n );\n\n if (errorOnInvalidOrigin) {\n const allowedOrigin = response.getHeader('access-control-allow-origin');\n const isInvalidOrigin = this.isInvalidOriginOrMethodIsNotAllowed(\n request,\n allowedOrigin,\n );\n\n if (isInvalidOrigin) {\n response.statusCode = 403;\n response.setHeader('Content-Type', 'text/plain');\n response.end(\n [\n 'Invalid HTTP Access Control (CORS) request:',\n ` Origin: ${request.headers.origin}`,\n ` Method: ${request.method}`,\n ].join('\\n'),\n );\n\n return;\n }\n }\n\n this.framework.sendRequest(app, request, response);\n };\n }\n\n /**\n * Format the headers to be standardized with the rest of the library, such as ApiGatewayV2.\n * Also, some frameworks don't support headers as an array, so we need to format the values.\n */\n protected formatHeaderValuesAddedByCorsPackage(\n response: ServerResponse,\n ): void {\n for (const corsHeader of this.corsHeaders) {\n const value = response.getHeader(corsHeader);\n\n if (value === undefined) continue;\n\n response.removeHeader(corsHeader);\n response.setHeader(\n corsHeader.toLowerCase(),\n Array.isArray(value) ? value.join(',') : value,\n );\n }\n }\n\n /**\n * Check if the origin is invalid or if the method is not allowed.\n * Highly inspired by [access-control](https://github.com/primus/access-control/blob/master/index.js#L95-L115)\n */\n protected isInvalidOriginOrMethodIsNotAllowed(\n request: IncomingMessage,\n allowedOrigin: number | string | string[] | undefined,\n ): boolean {\n if (!allowedOrigin) return true;\n\n if (\n !!request.headers.origin &&\n allowedOrigin !== '*' &&\n request.headers.origin !== allowedOrigin\n )\n return true;\n\n const notPermitedInMethods =\n this.options &&\n Array.isArray(this.options.methods) &&\n this.options.methods.every(\n m => m.toLowerCase() !== request.method?.toLowerCase(),\n );\n const differentMethod =\n this.options &&\n typeof this.options.methods === 'string' &&\n this.options.methods\n .split(',')\n .every(m => m.trim().toLowerCase() !== request.method?.toLowerCase());\n\n if (this.options?.methods && (notPermitedInMethods || differentMethod))\n return true;\n\n return false;\n }\n\n //#endregion\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport type { SingleValueHeaders } from '../@types';\nimport { NO_OP } from '../core';\n\nconst HTTPS_PORT = 443;\n\n/**\n * The properties to create a {@link ServerlessRequest}\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport interface ServerlessRequestProps {\n /**\n * The HTTP Method of the request\n */\n method: string;\n\n /**\n * The URL requested\n */\n url: string;\n\n /**\n * The headers from the event source\n */\n headers: SingleValueHeaders;\n\n /**\n * The body from the event source\n */\n body?: Buffer | Uint8Array;\n\n /**\n * The IP Address from caller\n */\n remoteAddress?: string;\n}\n\n/**\n * The class that represents an {@link http#IncomingMessage} created by the library to represent an actual request to the framework.\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport class ServerlessRequest extends IncomingMessage {\n constructor({\n method,\n url,\n headers,\n body,\n remoteAddress,\n }: ServerlessRequestProps) {\n super({\n encrypted: true,\n readable: false,\n remoteAddress,\n address: () => ({ port: HTTPS_PORT }) as AddressInfo,\n end: NO_OP,\n destroy: NO_OP,\n } as any);\n\n this.statusCode = 200;\n this.statusMessage = 'OK';\n this.complete = true;\n this.httpVersion = '1.1';\n this.httpVersionMajor = 1;\n this.httpVersionMinor = 1;\n this.method = method;\n this.headers = headers;\n this.body = body;\n this.url = url;\n this.ip = remoteAddress;\n\n this._read = () => {\n this.push(body);\n this.push(null);\n };\n }\n\n ip?: string;\n body?: Buffer | Uint8Array;\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport { NO_OP } from '../core';\nimport { getString } from './utils';\n\nconst headerEnd = '\\r\\n\\r\\n';\nconst endChunked = '0\\r\\n\\r\\n';\n\nconst BODY = Symbol('Response body');\nconst HEADERS = Symbol('Response headers');\n\nfunction addData(stream: ServerlessResponse, data: Uint8Array | string) {\n if (\n Buffer.isBuffer(data) ||\n typeof data === 'string' ||\n data instanceof Uint8Array\n )\n stream[BODY].push(Buffer.from(data));\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n\n/**\n * The properties to create a {@link ServerlessResponse}.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport interface ServerlessResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * Once it's happens, we use the properties from this response to built the response to the cloud.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport class ServerlessResponse extends ServerResponse {\n constructor({ method }: ServerlessResponseProps) {\n super({ method } as any);\n\n this[BODY] = [];\n this[HEADERS] = {};\n\n this.useChunkedEncodingByDefault = false;\n this.chunkedEncoding = false;\n this._header = '';\n\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 1;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (this._header === '' || this._wroteHeader) {\n if (!this.chunkedEncoding) addData(this, data);\n else {\n if (writesToIgnore > 0) writesToIgnore--;\n else if (data !== endChunked) {\n addData(this, data);\n writesToIgnore = 3;\n }\n }\n } else {\n const string = getString(data);\n const index = string.indexOf(headerEnd);\n\n if (index !== -1) {\n const remainder = string.slice(index + headerEnd.length);\n\n if (remainder && !this.chunkedEncoding) addData(this, remainder);\n\n this._wroteHeader = true;\n }\n }\n\n if (typeof cb === 'function') cb();\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n\n _header: string;\n _headers?: Record<any, any>;\n _wroteHeader?: boolean;\n\n [BODY]: any[];\n [HEADERS]: Record<any, any>;\n\n get headers(): Record<any, any> {\n return this[HEADERS];\n }\n\n static from(res: IncomingMessage) {\n const response = new ServerlessResponse({ method: res.method });\n\n response.statusCode = res.statusCode || 0;\n response[HEADERS] = res.headers;\n response[BODY] = (res as any).body ? [Buffer.from((res as any).body)] : [];\n response.end();\n\n return response;\n }\n\n static body(res: ServerlessResponse): Buffer {\n return Buffer.concat(res[BODY]);\n }\n\n static headers(res: ServerlessResponse) {\n const headers = res.getHeaders();\n\n return Object.assign(headers, res[HEADERS]);\n }\n\n override setHeader(\n key: string,\n value: number | string | readonly string[],\n ): any {\n if (this._wroteHeader) this[HEADERS][key] = value;\n else super.setHeader(key, value);\n }\n\n override writeHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): any {\n const headersObjOrArray =\n typeof statusMessage === 'string' ? obj : statusMessage;\n\n const arrayHeaders = Array.isArray(headersObjOrArray)\n ? headersObjOrArray\n : [headersObjOrArray || {}];\n\n for (const headers of arrayHeaders) {\n for (const name in headers) {\n this.setHeader(name, headers[name]!);\n\n if (!this._wroteHeader) {\n // we only need to initiate super.headers once\n // writeHead will add the other headers itself\n break;\n }\n }\n }\n\n return this.callNativeWriteHead(statusCode, statusMessage, obj);\n }\n\n /**\n * I use ignore here because in nodejs 12.x, statusMessage can be string | OutgoingHttpHeaders\n * But in nodejs \\>=14.x, statusMessage can also be OutgoingHttpHeaders[]\n * I take care of these cases above, but here I can't handle it well, so I give up\n * nodejs 12.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v12/http.d.ts#L229\n * nodejs 14.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v14/http.d.ts#L263\n */\n protected callNativeWriteHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): this {\n return super.writeHead(statusCode, statusMessage, obj);\n }\n}\n","/**\n * Get the data from a buffer, string, or Uint8Array\n *\n * @breadcrumb Network\n * @param data - The data that was written inside the stream\n */\nexport function getString(data: Buffer | string | unknown) {\n if (Buffer.isBuffer(data)) return data.toString('utf8');\n else if (typeof data === 'string') return data;\n else if (data instanceof Uint8Array) return new TextDecoder().decode(data);\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n","import { ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { Writable } from 'node:stream';\nimport type { BothValueHeaders } from '../@types';\nimport { type ILogger, NO_OP, parseHeaders } from '../core';\nimport { getString } from './utils';\n\nconst endChunked = '0\\r\\n\\r\\n';\nconst headerEnd = '\\r\\n\\r\\n';\nconst endStatusSeparator = '\\r\\n';\n\n/**\n * The properties to create a {@link ServerlessStreamResponse}.\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport interface ServerlessStreamResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n\n /**\n * The callback to receive the headers when they are written to the stream\n * You need to return a writable stream be able to continue writing the response\n *\n * @param statusCode - The status code of the response\n * @param headers - The headers of the response\n */\n onReceiveHeaders: (statusCode: number, headers: BothValueHeaders) => Writable;\n\n /**\n * Instance of the logger\n */\n log: ILogger;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * This response is specially built to deal with transfer-encoding: chunked\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport class ServerlessStreamResponse extends ServerResponse {\n constructor({\n method,\n onReceiveHeaders,\n log,\n }: ServerlessStreamResponseProps) {\n super({ method } as any);\n\n this.useChunkedEncodingByDefault = true;\n this.chunkedEncoding = true;\n\n let internalWritable: Writable | null = null;\n let isFirstCall = true;\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 0;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n // very unlikely, I don't even know how to reproduce this, but exist on types\n // istanbul ignore if\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n log.debug('SERVERLESS_ADAPTER:RESPONSE_STREAM:DATA', () => ({\n data: Buffer.isBuffer(data) ? data.toString('utf8') : data,\n encoding,\n }));\n\n if (!isFirstCall && internalWritable) {\n if (data === endChunked) {\n internalWritable.end(cb);\n\n return true;\n }\n\n if (writesToIgnore > 0) {\n writesToIgnore--;\n return true;\n }\n\n internalWritable.write(data, cb);\n writesToIgnore = 3;\n } else if (isFirstCall) {\n isFirstCall = false;\n\n const stringData = getString(data);\n const endStatusIndex = stringData.indexOf(endStatusSeparator);\n const status = +stringData.slice(0, endStatusIndex).split(' ')[1];\n const endHeaderIndex = stringData.indexOf(headerEnd);\n\n const headerData = stringData.slice(\n endStatusIndex + 2,\n endHeaderIndex,\n );\n const headers = parseHeaders(headerData);\n log.debug(\n 'SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS',\n () => ({\n headers,\n }),\n );\n\n writesToIgnore = 1;\n internalWritable = onReceiveHeaders(status, headers);\n\n // If we get an endChunked right after header which means the response body is empty, we need to immediately end the writable\n if (stringData.substring(endHeaderIndex + 4) === endChunked)\n internalWritable.end();\n }\n\n return true;\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n}\n","/**\n * No operation function is used when we need to pass a function, but we don't want to specify any behavior.\n *\n * @breadcrumb Core\n * @public\n */\nexport const NO_OP: (...args: any[]) => any = () => void 0;\n","import { NO_OP } from './no-op';\n\n/**\n * The type representing the possible log levels to choose from.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LogLevels =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'none';\n\n/**\n * The options to customize {@link ILogger}\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerOptions = {\n /**\n * Select the log level, {@link LogLevels | see more}.\n *\n * @defaultValue error\n */\n level: LogLevels;\n};\n\n/**\n * The log function used in any level.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerFN = (message: any, ...additional: any[]) => void;\n\n/**\n * The interface representing the logger, you can provide a custom logger by implementing this interface.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type ILogger = Record<Exclude<LogLevels, 'none'>, LoggerFN>;\n\n/**\n * The symbol used to check against an ILogger instace to verify if that ILogger was created by this library\n *\n * @breadcrumb Core / Logger\n * @public\n */\nconst InternalLoggerSymbol = Symbol('InternalLogger');\n\nconst logLevels: Record<\n LogLevels,\n [level: LogLevels, consoleMethod: keyof Console][]\n> = {\n debug: [\n ['debug', 'debug'],\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n verbose: [\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n info: [\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n warn: [\n ['warn', 'warn'],\n ['error', 'error'],\n ],\n error: [['error', 'error']],\n none: [],\n};\n\nconst lazyPrint = (value: () => any | unknown) => {\n if (typeof value === 'function') return value();\n\n return value;\n};\n\nconst print =\n (fn: string) =>\n (message: any, ...additional: (() => any)[]) =>\n console[fn](message, ...additional.map(lazyPrint));\n\n/**\n * The method used to create a simple logger instance to use in this library.\n *\n * @remarks Behind the scenes, this simple logger sends the message to the `console` methods.\n *\n * @example\n * ```typescript\n * const logger = createDefaultLogger();\n *\n * logger.error('An error happens.');\n * // An error happens.\n * ```\n *\n * @param level - Select the level of the log\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function createDefaultLogger(\n { level }: LoggerOptions = { level: 'error' },\n): ILogger {\n const levels = logLevels[level];\n\n if (!levels) throw new Error('Invalid log level');\n\n const logger = {\n [InternalLoggerSymbol]: true,\n error: NO_OP,\n debug: NO_OP,\n info: NO_OP,\n verbose: NO_OP,\n warn: NO_OP,\n } as ILogger;\n\n for (const [level, consoleMethod] of levels)\n logger[level] = print(consoleMethod);\n\n return logger;\n}\n\n/**\n * The method used to chck if logger was created by this library, or it was defined by the user.\n *\n * @param logger - The instance of the logger to check\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function isInternalLogger(logger: ILogger): boolean {\n return !!logger[InternalLoggerSymbol];\n}\n","/**\n * Return the defaultValue whether the value is undefined, otherwise, return the value.\n *\n * @example\n * ```typescript\n * const value1 = getDefaultIfUndefined(undefined, true);\n * const value2 = getDefaultIfUndefined(false, true);\n *\n * console.log(value1);\n * // true\n * console.log(value2);\n * // false\n * ```\n *\n * @param value - The value to be checked\n * @param defaultValue - The default value when value is undefined\n *\n * @breadcrumb Core\n * @public\n */\nexport function getDefaultIfUndefined<T>(\n value: T | undefined,\n defaultValue: T,\n): T {\n if (value === undefined) return defaultValue;\n\n return value;\n}\n","//#region Imports\n\nimport { Readable, Writable } from 'node:stream';\n\n//#endregion\n\n/**\n * Check if stream already ended\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function isStreamEnded(stream: Readable | Writable): boolean {\n if ('readableEnded' in stream && stream.readableEnded) return true;\n\n if ('writableEnded' in stream && stream.writableEnded) return true;\n\n return false;\n}\n\n/**\n * Wait asynchronous the stream to complete\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function waitForStreamComplete<TStream extends Readable | Writable>(\n stream: TStream,\n): Promise<TStream> {\n if (isStreamEnded(stream)) return Promise.resolve(stream);\n\n return new Promise<TStream>((resolve, reject) => {\n // Reading the {@link https://github.com/nodejs/node/blob/v12.22.9/lib/events.js#L262 | emit source code},\n // it's almost impossible to complete being called twice because the emit function runs synchronously and removes the other listeners,\n // but I'll leave it at that because I didn't write that code, so I couldn't figure out what the author thought when he wrote this.\n let isComplete = false;\n\n function complete(err: any) {\n /* istanbul ignore next */\n if (isComplete) return;\n\n isComplete = true;\n\n stream.removeListener('error', complete);\n stream.removeListener('end', complete);\n stream.removeListener('finish', complete);\n\n if (err) reject(err);\n else resolve(stream);\n }\n\n stream.once('error', complete);\n stream.once('end', complete);\n stream.once('finish', complete);\n });\n}\n"],"mappings":"6mBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GCGA,IAAAI,EAAuC,qBCFvC,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U,YAAYD,EAAKC,EAASC,CAAQ,CACnD,CACF,CAMU,qCACRA,EACM,CACN,QAAWG,KAAc,KAAK,YAAa,CACzC,IAAMC,EAAQJ,EAAS,UAAUG,CAAU,EAEvCC,IAAU,SAEdJ,EAAS,aAAaG,CAAU,EAChCH,EAAS,UACPG,EAAW,YAAY,EACvB,MAAM,QAAQC,CAAK,EAAIA,EAAM,KAAK,GAAG,EAAIA,CAC3C,EACF,CACF,CAMU,oCACRL,EACAG,EACS,CAGT,GAFI,CAACA,GAGDH,EAAQ,QAAQ,QAClBG,IAAkB,KAClBH,EAAQ,QAAQ,SAAWG,EAE3B,MAAO,GAET,IAAMG,EACJ,KAAK,SACL,MAAM,QAAQ,KAAK,QAAQ,OAAO,GAClC,KAAK,QAAQ,QAAQ,MACnBC,GAAKA,EAAE,YAAY,IAAMP,EAAQ,QAAQ,YAAY,CACvD,EACIQ,EACJ,KAAK,SACL,OAAO,KAAK,QAAQ,SAAY,UAChC,KAAK,QAAQ,QACV,MAAM,GAAG,EACT,MAAMD,GAAKA,EAAE,KAAK,EAAE,YAAY,IAAMP,EAAQ,QAAQ,YAAY,CAAC,EAExE,MAAI,QAAK,SAAS,UAAYM,GAAwBE,GAIxD,CAGF","names":["cors_exports","__export","CorsFramework","__toCommonJS","import_cors","import_node_http","import_node_http","getString","data","__name","headerEnd","endChunked","BODY","HEADERS","addData","stream","data","__name","ServerlessResponse","_ServerlessResponse","method","writesToIgnore","socket","NO_OP","encoding","cb","string","getString","index","remainder","res","response","headers","key","value","statusCode","statusMessage","obj","headersObjOrArray","arrayHeaders","name","import_node_http","NO_OP","__name","InternalLoggerSymbol","getDefaultIfUndefined","value","defaultValue","__name","import_node_stream","CorsFramework","framework","options","cors","__name","app","request","response","getDefaultIfUndefined","allowedOrigin","corsHeader","value","notPermitedInMethods","m","differentMethod"]}
1
+ {"version":3,"sources":["../../../src/frameworks/cors/index.ts","../../../src/frameworks/cors/cors.framework.ts","../../../src/network/request.ts","../../../src/network/response.ts","../../../src/network/utils.ts","../../../src/network/response-stream.ts","../../../src/core/no-op.ts","../../../src/core/logger.ts","../../../src/core/optional.ts","../../../src/core/stream.ts"],"sourcesContent":["export * from './cors.framework';\n","//#region Imports\n\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport cors, { type CorsOptions } from 'cors';\nimport type { FrameworkContract } from '../../contracts';\nimport { getDefaultIfUndefined } from '../../core';\n\n//#endregion\n\n/**\n * The options to customize {@link CorsFramework}\n *\n * @breadcrumb Frameworks / CorsFramework\n * @public\n */\nexport type CorsFrameworkOptions = CorsOptions & {\n /**\n * Send error 403 when cors is invalid. From what I read in `cors`, `fastify/cors` and [this problem](https://stackoverflow.com/questions/57212248/why-is-http-request-been-processed-in-action-even-when-cors-is-not-enabled)\n * it is normal to process the request even if the origin is invalid.\n * So this option will respond with error if this method was called from an invalid origin (or not allowed method) like [access control lib](https://github.com/primus/access-control/blob/master/index.js#L95-L115) .\n *\n * @defaultValue true\n */\n forbiddenOnInvalidOriginOrMethod?: boolean;\n};\n\n/**\n * The framework that handles cors for your api without relying on internals of the framework\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { ServerlessAdapter } from '@h4ad/serverless-adapter';\n * import { ExpressFramework } from '@h4ad/serverless-adapter/lib/frameworks/express';\n * import { CorsFramework } from '@h4ad/serverless-adapter/lib/frameworks/cors';\n *\n * const expressFramework = new ExpressFramework();\n * const options: CorsOptions = {}; // customize the options\n * const framework = new CorsFramework(expressFramework, options);\n *\n * export const handler = ServerlessAdapter.new(null)\n * .setFramework(framework)\n * // set other configurations and then build\n * .build();\n * ```\n *\n * @breadcrumb Frameworks / CorsFramework\n * @public\n */\nexport class CorsFramework<TApp> implements FrameworkContract<TApp> {\n //#region Constructor\n\n /**\n * Default Constructor\n */\n constructor(\n protected readonly framework: FrameworkContract<TApp>,\n protected readonly options?: CorsFrameworkOptions,\n ) {\n this.cachedCorsInstance = cors(this.options);\n }\n\n //#endregion\n\n /**\n * All cors headers that can be added by cors package\n */\n protected readonly corsHeaders: string[] = [\n 'Access-Control-Max-Age',\n 'Access-Control-Expose-Headers',\n 'Access-Control-Allow-Headers',\n 'Access-Control-Request-Headers',\n 'Access-Control-Allow-Credentials',\n 'Access-Control-Allow-Methods',\n 'Access-Control-Allow-Origin',\n ];\n\n /**\n * The cached instance of cors\n */\n protected readonly cachedCorsInstance: ReturnType<typeof cors>;\n\n //#region Public Methods\n\n /**\n * {@inheritDoc}\n */\n public sendRequest(\n app: TApp,\n request: IncomingMessage,\n response: ServerResponse,\n ): void {\n this.cachedCorsInstance(\n request,\n response,\n this.onCorsNext(app, request, response),\n );\n }\n\n //#endregion\n\n //#region Protected Methods\n\n /**\n * Handle next execution called by the cors package\n */\n protected onCorsNext(\n app: TApp,\n request: IncomingMessage,\n response: ServerResponse,\n ): () => void {\n return () => {\n this.formatHeaderValuesAddedByCorsPackage(response);\n\n const errorOnInvalidOrigin = getDefaultIfUndefined(\n this.options?.forbiddenOnInvalidOriginOrMethod,\n true,\n );\n\n if (errorOnInvalidOrigin) {\n const allowedOrigin = response.getHeader('access-control-allow-origin');\n const isInvalidOrigin = this.isInvalidOriginOrMethodIsNotAllowed(\n request,\n allowedOrigin,\n );\n\n if (isInvalidOrigin) {\n response.statusCode = 403;\n response.setHeader('Content-Type', 'text/plain');\n response.end(\n [\n 'Invalid HTTP Access Control (CORS) request:',\n ` Origin: ${request.headers.origin}`,\n ` Method: ${request.method}`,\n ].join('\\n'),\n );\n\n return;\n }\n }\n\n this.framework.sendRequest(app, request, response);\n };\n }\n\n /**\n * Format the headers to be standardized with the rest of the library, such as ApiGatewayV2.\n * Also, some frameworks don't support headers as an array, so we need to format the values.\n */\n protected formatHeaderValuesAddedByCorsPackage(\n response: ServerResponse,\n ): void {\n for (const corsHeader of this.corsHeaders) {\n const value = response.getHeader(corsHeader);\n\n if (value === undefined) continue;\n\n response.removeHeader(corsHeader);\n response.setHeader(\n corsHeader.toLowerCase(),\n Array.isArray(value) ? value.join(',') : value,\n );\n }\n }\n\n /**\n * Check if the origin is invalid or if the method is not allowed.\n * Highly inspired by [access-control](https://github.com/primus/access-control/blob/master/index.js#L95-L115)\n */\n protected isInvalidOriginOrMethodIsNotAllowed(\n request: IncomingMessage,\n allowedOrigin: number | string | string[] | undefined,\n ): boolean {\n if (!allowedOrigin) return true;\n\n if (\n !!request.headers.origin &&\n allowedOrigin !== '*' &&\n request.headers.origin !== allowedOrigin\n )\n return true;\n\n const notPermitedInMethods =\n this.options &&\n Array.isArray(this.options.methods) &&\n this.options.methods.every(\n m => m.toLowerCase() !== request.method?.toLowerCase(),\n );\n const differentMethod =\n this.options &&\n typeof this.options.methods === 'string' &&\n this.options.methods\n .split(',')\n .every(m => m.trim().toLowerCase() !== request.method?.toLowerCase());\n\n if (this.options?.methods && (notPermitedInMethods || differentMethod))\n return true;\n\n return false;\n }\n\n //#endregion\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport type { SingleValueHeaders } from '../@types';\nimport { NO_OP } from '../core';\n\nconst HTTPS_PORT = 443;\n\n/**\n * The properties to create a {@link ServerlessRequest}\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport interface ServerlessRequestProps {\n /**\n * The HTTP Method of the request\n */\n method: string;\n\n /**\n * The URL requested\n */\n url: string;\n\n /**\n * The headers from the event source\n */\n headers: SingleValueHeaders;\n\n /**\n * The body from the event source\n */\n body?: Buffer | Uint8Array;\n\n /**\n * The IP Address from caller\n */\n remoteAddress?: string;\n}\n\n/**\n * The class that represents an {@link http#IncomingMessage} created by the library to represent an actual request to the framework.\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport class ServerlessRequest extends IncomingMessage {\n constructor({\n method,\n url,\n headers,\n body,\n remoteAddress,\n }: ServerlessRequestProps) {\n super({\n encrypted: true,\n readable: false,\n remoteAddress,\n address: () => ({ port: HTTPS_PORT }) as AddressInfo,\n end: NO_OP,\n destroy: NO_OP,\n } as any);\n\n this.statusCode = 200;\n this.statusMessage = 'OK';\n this.complete = true;\n this.httpVersion = '1.1';\n this.httpVersionMajor = 1;\n this.httpVersionMinor = 1;\n this.method = method;\n this.headers = headers;\n this.body = body;\n this.url = url;\n this.ip = remoteAddress;\n\n this._read = () => {\n this.push(body);\n this.push(null);\n };\n }\n\n ip?: string;\n body?: Buffer | Uint8Array;\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport { NO_OP } from '../core';\nimport { getString } from './utils';\n\nconst headerEnd = '\\r\\n\\r\\n';\nconst endChunked = '0\\r\\n\\r\\n';\n\nconst BODY = Symbol('Response body');\nconst HEADERS = Symbol('Response headers');\n\nfunction addData(stream: ServerlessResponse, data: Uint8Array | string) {\n if (\n Buffer.isBuffer(data) ||\n typeof data === 'string' ||\n data instanceof Uint8Array\n )\n stream[BODY].push(Buffer.from(data));\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n\n/**\n * The properties to create a {@link ServerlessResponse}.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport interface ServerlessResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * Once it's happens, we use the properties from this response to built the response to the cloud.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport class ServerlessResponse extends ServerResponse {\n constructor({ method }: ServerlessResponseProps) {\n super({ method } as any);\n\n this[BODY] = [];\n this[HEADERS] = {};\n\n this.useChunkedEncodingByDefault = false;\n this.chunkedEncoding = false;\n this._header = '';\n\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 1;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (this._header === '' || this._wroteHeader) {\n if (!this.chunkedEncoding) addData(this, data);\n else {\n if (writesToIgnore > 0) writesToIgnore--;\n else if (data !== endChunked) {\n addData(this, data);\n writesToIgnore = 3;\n }\n }\n } else {\n const string = getString(data);\n const index = string.indexOf(headerEnd);\n\n if (index !== -1) {\n const remainder = string.slice(index + headerEnd.length);\n\n if (remainder && !this.chunkedEncoding) addData(this, remainder);\n\n this._wroteHeader = true;\n }\n }\n\n if (typeof cb === 'function') cb();\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n\n _header: string;\n _headers?: Record<any, any>;\n _wroteHeader?: boolean;\n\n [BODY]: any[];\n [HEADERS]: Record<any, any>;\n\n get headers(): Record<any, any> {\n return this[HEADERS];\n }\n\n static from(res: IncomingMessage) {\n const response = new ServerlessResponse({ method: res.method });\n\n response.statusCode = res.statusCode || 0;\n response[HEADERS] = res.headers;\n response[BODY] = (res as any).body ? [Buffer.from((res as any).body)] : [];\n response.end();\n\n return response;\n }\n\n static body(res: ServerlessResponse): Buffer {\n return Buffer.concat(res[BODY]);\n }\n\n static headers(res: ServerlessResponse) {\n const headers = res.getHeaders();\n\n return Object.assign(headers, res[HEADERS]);\n }\n\n override setHeader(\n key: string,\n value: number | string | readonly string[],\n ): any {\n if (this._wroteHeader) this[HEADERS][key] = value;\n else super.setHeader(key, value);\n }\n\n override writeHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): any {\n const headersObjOrArray =\n typeof statusMessage === 'string' ? obj : statusMessage;\n\n const arrayHeaders = Array.isArray(headersObjOrArray)\n ? headersObjOrArray\n : [headersObjOrArray || {}];\n\n for (const headers of arrayHeaders) {\n for (const name in headers) {\n this.setHeader(name, headers[name]!);\n\n if (!this._wroteHeader) {\n // we only need to initiate super.headers once\n // writeHead will add the other headers itself\n break;\n }\n }\n }\n\n return this.callNativeWriteHead(statusCode, statusMessage, obj);\n }\n\n /**\n * I use ignore here because in nodejs 12.x, statusMessage can be string | OutgoingHttpHeaders\n * But in nodejs \\>=14.x, statusMessage can also be OutgoingHttpHeaders[]\n * I take care of these cases above, but here I can't handle it well, so I give up\n * nodejs 12.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v12/http.d.ts#L229\n * nodejs 14.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v14/http.d.ts#L263\n */\n protected callNativeWriteHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): this {\n return super.writeHead(statusCode, statusMessage, obj);\n }\n}\n","/**\n * Get the data from a buffer, string, or Uint8Array\n *\n * @breadcrumb Network\n * @param data - The data that was written inside the stream\n */\nexport function getString(data: Buffer | string | unknown) {\n if (Buffer.isBuffer(data)) return data.toString('utf8');\n else if (typeof data === 'string') return data;\n else if (data instanceof Uint8Array) return new TextDecoder().decode(data);\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n","import { ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { Writable } from 'node:stream';\nimport type { BothValueHeaders } from '../@types';\nimport { type ILogger, NO_OP, parseHeaders } from '../core';\nimport { getString } from './utils';\n\n// header or data crlf\nconst crlfBuffer = Buffer.from('\\r\\n');\n\nconst endChunked = '0\\r\\n\\r\\n';\nconst headerEnd = '\\r\\n\\r\\n';\nconst endStatusSeparator = '\\r\\n';\n\n/**\n * The properties to create a {@link ServerlessStreamResponse}.\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport interface ServerlessStreamResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n\n /**\n * The callback to receive the headers when they are written to the stream\n * You need to return a writable stream be able to continue writing the response\n *\n * @param statusCode - The status code of the response\n * @param headers - The headers of the response\n */\n onReceiveHeaders: (statusCode: number, headers: BothValueHeaders) => Writable;\n\n /**\n * Instance of the logger\n */\n log: ILogger;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * This response is specially built to deal with transfer-encoding: chunked\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport class ServerlessStreamResponse extends ServerResponse {\n constructor({\n method,\n onReceiveHeaders,\n log,\n }: ServerlessStreamResponseProps) {\n super({ method } as any);\n\n this.useChunkedEncodingByDefault = true;\n this.chunkedEncoding = true;\n\n let internalWritable: Writable | null = null;\n let firstCrlfBufferEncountered = false;\n let chunkEncountered = false;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n // very unlikely, I don't even know how to reproduce this, but exist on types\n // istanbul ignore if\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n log.debug('SERVERLESS_ADAPTER:RESPONSE_STREAM:DATA', () => ({\n data: Buffer.isBuffer(data) ? data.toString('utf8') : data,\n encoding,\n }));\n\n if (!internalWritable) {\n const stringData = getString(data);\n const endStatusIndex = stringData.indexOf(endStatusSeparator);\n const status = +stringData.slice(0, endStatusIndex).split(' ')[1];\n const endHeaderIndex = stringData.indexOf(headerEnd);\n\n const headerData = stringData.slice(\n endStatusIndex + 2,\n endHeaderIndex,\n );\n const headers = parseHeaders(headerData);\n log.debug(\n 'SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS',\n () => ({\n headers,\n }),\n );\n\n internalWritable = onReceiveHeaders(status, headers);\n\n // If we get an endChunked right after header which means the response body is empty, we need to immediately end the writable\n if (stringData.substring(endHeaderIndex + 4) === endChunked)\n internalWritable.end();\n\n return true;\n }\n\n // node sends the last chunk crlf as a string:\n // https://github.com/nodejs/node/blob/v22.8.0/lib/_http_outgoing.js#L1131\n if (data === endChunked) {\n internalWritable.end(cb);\n return true;\n }\n\n // check for header or data crlf\n // node sends the header and data crlf as a buffer\n // below code is aligned to following node implementation of the HTTP/1.1 chunked transfer coding:\n // https://github.com/nodejs/node/blob/v22.8.0/lib/_http_outgoing.js#L1012-L1015\n // for reference: https://datatracker.ietf.org/doc/html/rfc9112#section-7\n if (Buffer.isBuffer(data) && crlfBuffer.equals(data)) {\n const isHeaderCrlf = !firstCrlfBufferEncountered;\n if (isHeaderCrlf) {\n firstCrlfBufferEncountered = true;\n return true;\n }\n\n const isDataCrlf = firstCrlfBufferEncountered && chunkEncountered;\n if (isDataCrlf) {\n // done with chunk\n firstCrlfBufferEncountered = false;\n chunkEncountered = false;\n return true;\n }\n\n // the crlf *is* the chunk\n }\n\n const isContentLength = !firstCrlfBufferEncountered;\n if (isContentLength) {\n // discard content length\n return true;\n }\n\n // write chunk\n chunkEncountered = true;\n internalWritable.write(data, cb);\n return true;\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n}\n","/**\n * No operation function is used when we need to pass a function, but we don't want to specify any behavior.\n *\n * @breadcrumb Core\n * @public\n */\nexport const NO_OP: (...args: any[]) => any = () => void 0;\n","import { NO_OP } from './no-op';\n\n/**\n * The type representing the possible log levels to choose from.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LogLevels =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'none';\n\n/**\n * The options to customize {@link ILogger}\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerOptions = {\n /**\n * Select the log level, {@link LogLevels | see more}.\n *\n * @defaultValue error\n */\n level: LogLevels;\n};\n\n/**\n * The log function used in any level.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerFN = (message: any, ...additional: any[]) => void;\n\n/**\n * The interface representing the logger, you can provide a custom logger by implementing this interface.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type ILogger = Record<Exclude<LogLevels, 'none'>, LoggerFN>;\n\n/**\n * The symbol used to check against an ILogger instace to verify if that ILogger was created by this library\n *\n * @breadcrumb Core / Logger\n * @public\n */\nconst InternalLoggerSymbol = Symbol('InternalLogger');\n\nconst logLevels: Record<\n LogLevels,\n [level: LogLevels, consoleMethod: keyof Console][]\n> = {\n debug: [\n ['debug', 'debug'],\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n verbose: [\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n info: [\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n warn: [\n ['warn', 'warn'],\n ['error', 'error'],\n ],\n error: [['error', 'error']],\n none: [],\n};\n\nconst lazyPrint = (value: () => any | unknown) => {\n if (typeof value === 'function') return value();\n\n return value;\n};\n\nconst print =\n (fn: string) =>\n (message: any, ...additional: (() => any)[]) =>\n console[fn](message, ...additional.map(lazyPrint));\n\n/**\n * The method used to create a simple logger instance to use in this library.\n *\n * @remarks Behind the scenes, this simple logger sends the message to the `console` methods.\n *\n * @example\n * ```typescript\n * const logger = createDefaultLogger();\n *\n * logger.error('An error happens.');\n * // An error happens.\n * ```\n *\n * @param level - Select the level of the log\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function createDefaultLogger(\n { level }: LoggerOptions = { level: 'error' },\n): ILogger {\n const levels = logLevels[level];\n\n if (!levels) throw new Error('Invalid log level');\n\n const logger = {\n [InternalLoggerSymbol]: true,\n error: NO_OP,\n debug: NO_OP,\n info: NO_OP,\n verbose: NO_OP,\n warn: NO_OP,\n } as ILogger;\n\n for (const [level, consoleMethod] of levels)\n logger[level] = print(consoleMethod);\n\n return logger;\n}\n\n/**\n * The method used to chck if logger was created by this library, or it was defined by the user.\n *\n * @param logger - The instance of the logger to check\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function isInternalLogger(logger: ILogger): boolean {\n return !!logger[InternalLoggerSymbol];\n}\n","/**\n * Return the defaultValue whether the value is undefined, otherwise, return the value.\n *\n * @example\n * ```typescript\n * const value1 = getDefaultIfUndefined(undefined, true);\n * const value2 = getDefaultIfUndefined(false, true);\n *\n * console.log(value1);\n * // true\n * console.log(value2);\n * // false\n * ```\n *\n * @param value - The value to be checked\n * @param defaultValue - The default value when value is undefined\n *\n * @breadcrumb Core\n * @public\n */\nexport function getDefaultIfUndefined<T>(\n value: T | undefined,\n defaultValue: T,\n): T {\n if (value === undefined) return defaultValue;\n\n return value;\n}\n","//#region Imports\n\nimport { Readable, Writable } from 'node:stream';\n\n//#endregion\n\n/**\n * Check if stream already ended\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function isStreamEnded(stream: Readable | Writable): boolean {\n if ('readableEnded' in stream && stream.readableEnded) return true;\n\n if ('writableEnded' in stream && stream.writableEnded) return true;\n\n return false;\n}\n\n/**\n * Wait asynchronous the stream to complete\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function waitForStreamComplete<TStream extends Readable | Writable>(\n stream: TStream,\n): Promise<TStream> {\n if (isStreamEnded(stream)) return Promise.resolve(stream);\n\n return new Promise<TStream>((resolve, reject) => {\n // Reading the {@link https://github.com/nodejs/node/blob/v12.22.9/lib/events.js#L262 | emit source code},\n // it's almost impossible to complete being called twice because the emit function runs synchronously and removes the other listeners,\n // but I'll leave it at that because I didn't write that code, so I couldn't figure out what the author thought when he wrote this.\n let isComplete = false;\n\n function complete(err: any) {\n /* istanbul ignore next */\n if (isComplete) return;\n\n isComplete = true;\n\n stream.removeListener('error', complete);\n stream.removeListener('end', complete);\n stream.removeListener('finish', complete);\n\n if (err) reject(err);\n else resolve(stream);\n }\n\n stream.once('error', complete);\n stream.once('end', complete);\n stream.once('finish', complete);\n });\n}\n"],"mappings":"6mBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,m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,MAAM,GACnC,aAAaA,EAAQ,MAAM,EAC7B,EAAE,KAAK;AAAA,CAAI,CACb,EAEA,MACF,CACF,CAEA,KAAK,UAAU,YAAYD,EAAKC,EAASC,CAAQ,CACnD,CACF,CAMU,qCACRA,EACM,CACN,QAAWG,KAAc,KAAK,YAAa,CACzC,IAAMC,EAAQJ,EAAS,UAAUG,CAAU,EAEvCC,IAAU,SAEdJ,EAAS,aAAaG,CAAU,EAChCH,EAAS,UACPG,EAAW,YAAY,EACvB,MAAM,QAAQC,CAAK,EAAIA,EAAM,KAAK,GAAG,EAAIA,CAC3C,EACF,CACF,CAMU,oCACRL,EACAG,EACS,CAGT,GAFI,CAACA,GAGDH,EAAQ,QAAQ,QAClBG,IAAkB,KAClBH,EAAQ,QAAQ,SAAWG,EAE3B,MAAO,GAET,IAAMG,EACJ,KAAK,SACL,MAAM,QAAQ,KAAK,QAAQ,OAAO,GAClC,KAAK,QAAQ,QAAQ,MACnBC,GAAKA,EAAE,YAAY,IAAMP,EAAQ,QAAQ,YAAY,CACvD,EACIQ,EACJ,KAAK,SACL,OAAO,KAAK,QAAQ,SAAY,UAChC,KAAK,QAAQ,QACV,MAAM,GAAG,EACT,MAAMD,GAAKA,EAAE,KAAK,EAAE,YAAY,IAAMP,EAAQ,QAAQ,YAAY,CAAC,EAExE,MAAI,QAAK,SAAS,UAAYM,GAAwBE,GAIxD,CAGF","names":["cors_exports","__export","CorsFramework","__toCommonJS","import_cors","import_node_http","import_node_http","getString","data","__name","headerEnd","endChunked","BODY","HEADERS","addData","stream","data","__name","ServerlessResponse","_ServerlessResponse","method","writesToIgnore","socket","NO_OP","encoding","cb","string","getString","index","remainder","res","response","headers","key","value","statusCode","statusMessage","obj","headersObjOrArray","arrayHeaders","name","import_node_http","crlfBuffer","NO_OP","__name","InternalLoggerSymbol","getDefaultIfUndefined","value","defaultValue","__name","import_node_stream","CorsFramework","framework","options","cors","__name","app","request","response","getDefaultIfUndefined","allowedOrigin","corsHeader","value","notPermitedInMethods","m","differentMethod"]}
@@ -1,3 +1,3 @@
1
- import{s as i}from"../../chunk-MQYXRLYI.mjs";import{a as n}from"../../chunk-OYOJMOFP.mjs";import a from"cors";var d=class{constructor(t,e){this.framework=t;this.options=e;this.cachedCorsInstance=a(this.options)}static{n(this,"CorsFramework")}corsHeaders=["Access-Control-Max-Age","Access-Control-Expose-Headers","Access-Control-Allow-Headers","Access-Control-Request-Headers","Access-Control-Allow-Credentials","Access-Control-Allow-Methods","Access-Control-Allow-Origin"];cachedCorsInstance;sendRequest(t,e,o){this.cachedCorsInstance(e,o,this.onCorsNext(t,e,o))}onCorsNext(t,e,o){return()=>{if(this.formatHeaderValuesAddedByCorsPackage(o),i(this.options?.forbiddenOnInvalidOriginOrMethod,!0)){let r=o.getHeader("access-control-allow-origin");if(this.isInvalidOriginOrMethodIsNotAllowed(e,r)){o.statusCode=403,o.setHeader("Content-Type","text/plain"),o.end(["Invalid HTTP Access Control (CORS) request:",` Origin: ${e.headers.origin}`,` Method: ${e.method}`].join(`
1
+ import{t as i}from"../../chunk-L4VRXTKP.mjs";import{a as n}from"../../chunk-OYOJMOFP.mjs";import a from"cors";var d=class{constructor(t,e){this.framework=t;this.options=e;this.cachedCorsInstance=a(this.options)}static{n(this,"CorsFramework")}corsHeaders=["Access-Control-Max-Age","Access-Control-Expose-Headers","Access-Control-Allow-Headers","Access-Control-Request-Headers","Access-Control-Allow-Credentials","Access-Control-Allow-Methods","Access-Control-Allow-Origin"];cachedCorsInstance;sendRequest(t,e,o){this.cachedCorsInstance(e,o,this.onCorsNext(t,e,o))}onCorsNext(t,e,o){return()=>{if(this.formatHeaderValuesAddedByCorsPackage(o),i(this.options?.forbiddenOnInvalidOriginOrMethod,!0)){let r=o.getHeader("access-control-allow-origin");if(this.isInvalidOriginOrMethodIsNotAllowed(e,r)){o.statusCode=403,o.setHeader("Content-Type","text/plain"),o.end(["Invalid HTTP Access Control (CORS) request:",` Origin: ${e.headers.origin}`,` Method: ${e.method}`].join(`
2
2
  `));return}}this.framework.sendRequest(t,e,o)}}formatHeaderValuesAddedByCorsPackage(t){for(let e of this.corsHeaders){let o=t.getHeader(e);o!==void 0&&(t.removeHeader(e),t.setHeader(e.toLowerCase(),Array.isArray(o)?o.join(","):o))}}isInvalidOriginOrMethodIsNotAllowed(t,e){if(!e||t.headers.origin&&e!=="*"&&t.headers.origin!==e)return!0;let o=this.options&&Array.isArray(this.options.methods)&&this.options.methods.every(r=>r.toLowerCase()!==t.method?.toLowerCase()),s=this.options&&typeof this.options.methods=="string"&&this.options.methods.split(",").every(r=>r.trim().toLowerCase()!==t.method?.toLowerCase());return!!(this.options?.methods&&(o||s))}};export{d as CorsFramework};
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1,6 +1,7 @@
1
- "use strict";var l=Object.defineProperty;var T=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var n=(t,e)=>l(t,"name",{value:e,configurable:!0});var A=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},C=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of E(e))!w.call(t,o)&&o!==r&&l(t,o,{get:()=>e[o],enumerable:!(s=T(e,o))||s.enumerable});return t};var k=t=>C(l({},"__esModule",{value:!0}),t);var I={};A(I,{HttpDeepkitFramework:()=>m});module.exports=k(I);var b=require("@deepkit/http");var B=require("http");var v=require("http");function c(t){if(Buffer.isBuffer(t))return t.toString("utf8");if(typeof t=="string")return t;if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw new Error(`response.write() of unexpected type: ${typeof t}`)}n(c,"getString");var S=`\r
1
+ "use strict";var l=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var n=(t,e)=>l(t,"name",{value:e,configurable:!0});var A=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},C=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of E(e))!w.call(t,o)&&o!==r&&l(t,o,{get:()=>e[o],enumerable:!(s=b(e,o))||s.enumerable});return t};var k=t=>C(l({},"__esModule",{value:!0}),t);var O={};A(O,{HttpDeepkitFramework:()=>m});module.exports=k(O);var T=require("@deepkit/http");var B=require("http");var v=require("http");function c(t){if(Buffer.isBuffer(t))return t.toString("utf8");if(typeof t=="string")return t;if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw new Error(`response.write() of unexpected type: ${typeof t}`)}n(c,"getString");var S=`\r
2
2
  \r
3
3
  `,H=`0\r
4
4
  \r
5
- `,u=Symbol("Response body"),p=Symbol("Response headers");function g(t,e){if(Buffer.isBuffer(e)||typeof e=="string"||e instanceof Uint8Array)t[u].push(Buffer.from(e));else throw new Error(`response.write() of unexpected type: ${typeof e}`)}n(g,"addData");var y=class t extends v.ServerResponse{static{n(this,"ServerlessResponse")}constructor({method:e}){super({method:e}),this[u]=[],this[p]={},this.useChunkedEncodingByDefault=!1,this.chunkedEncoding=!1,this._header="";let r=1,s={_writableState:{},writable:!0,on:d,removeListener:d,destroy:d,cork:d,uncork:d,write:(o,i,a)=>{if(typeof i=="function"&&(a=i,i=null),this._header===""||this._wroteHeader)this.chunkedEncoding?r>0?r--:o!==H&&(g(this,o),r=3):g(this,o);else{let f=c(o),h=f.indexOf(S);if(h!==-1){let x=f.slice(h+S.length);x&&!this.chunkedEncoding&&g(this,x),this._wroteHeader=!0}}typeof a=="function"&&a()}};this.assignSocket(s)}_header;_headers;_wroteHeader;[u];[p];get headers(){return this[p]}static from(e){let r=new t({method:e.method});return r.statusCode=e.statusCode||0,r[p]=e.headers,r[u]=e.body?[Buffer.from(e.body)]:[],r.end(),r}static body(e){return Buffer.concat(e[u])}static headers(e){let r=e.getHeaders();return Object.assign(r,e[p])}setHeader(e,r){this._wroteHeader?this[p][e]=r:super.setHeader(e,r)}writeHead(e,r,s){let o=typeof r=="string"?s:r,i=Array.isArray(o)?o:[o||{}];for(let a of i)for(let f in a)if(this.setHeader(f,a[f]),!this._wroteHeader)break;return this.callNativeWriteHead(e,r,s)}callNativeWriteHead(e,r,s){return super.writeHead(e,r,s)}};var L=require("http");function R(t,e=",",r=!1){return Object.keys(t).reduce((s,o)=>{let i=r?o.toLowerCase():o,a=t[o];return Array.isArray(a)?s[i]=a.join(e):s[i]=(a??"")+"",s},{})}n(R,"getFlattenedHeadersMap");var d=n(()=>{},"NO_OP");var me=Symbol("InternalLogger");var Te=require("stream");var m=class{static{n(this,"HttpDeepkitFramework")}sendRequest(e,r,s){let o=R(r.headers),i=new b.RequestBuilder(r.url,r.method).headers(o);r.body&&(i=Buffer.isBuffer(r.body)?i.body(r.body):i.body(Buffer.from(r.body)));let a=i.build();e.handleRequest(a,s)}};0&&(module.exports={HttpDeepkitFramework});
5
+ `,p=Symbol("Response body"),d=Symbol("Response headers");function g(t,e){if(Buffer.isBuffer(e)||typeof e=="string"||e instanceof Uint8Array)t[p].push(Buffer.from(e));else throw new Error(`response.write() of unexpected type: ${typeof e}`)}n(g,"addData");var y=class t extends v.ServerResponse{static{n(this,"ServerlessResponse")}constructor({method:e}){super({method:e}),this[p]=[],this[d]={},this.useChunkedEncodingByDefault=!1,this.chunkedEncoding=!1,this._header="";let r=1,s={_writableState:{},writable:!0,on:f,removeListener:f,destroy:f,cork:f,uncork:f,write:(o,i,a)=>{if(typeof i=="function"&&(a=i,i=null),this._header===""||this._wroteHeader)this.chunkedEncoding?r>0?r--:o!==H&&(g(this,o),r=3):g(this,o);else{let u=c(o),h=u.indexOf(S);if(h!==-1){let x=u.slice(h+S.length);x&&!this.chunkedEncoding&&g(this,x),this._wroteHeader=!0}}typeof a=="function"&&a()}};this.assignSocket(s)}_header;_headers;_wroteHeader;[p];[d];get headers(){return this[d]}static from(e){let r=new t({method:e.method});return r.statusCode=e.statusCode||0,r[d]=e.headers,r[p]=e.body?[Buffer.from(e.body)]:[],r.end(),r}static body(e){return Buffer.concat(e[p])}static headers(e){let r=e.getHeaders();return Object.assign(r,e[d])}setHeader(e,r){this._wroteHeader?this[d][e]=r:super.setHeader(e,r)}writeHead(e,r,s){let o=typeof r=="string"?s:r,i=Array.isArray(o)?o:[o||{}];for(let a of i)for(let u in a)if(this.setHeader(u,a[u]),!this._wroteHeader)break;return this.callNativeWriteHead(e,r,s)}callNativeWriteHead(e,r,s){return super.writeHead(e,r,s)}};var L=require("http");var q=Buffer.from(`\r
6
+ `);function R(t,e=",",r=!1){return Object.keys(t).reduce((s,o)=>{let i=r?o.toLowerCase():o,a=t[o];return Array.isArray(a)?s[i]=a.join(e):s[i]=(a??"")+"",s},{})}n(R,"getFlattenedHeadersMap");var f=n(()=>{},"NO_OP");var he=Symbol("InternalLogger");var Ee=require("stream");var m=class{static{n(this,"HttpDeepkitFramework")}sendRequest(e,r,s){let o=R(r.headers),i=new T.RequestBuilder(r.url,r.method).headers(o);r.body&&(i=Buffer.isBuffer(r.body)?i.body(r.body):i.body(Buffer.from(r.body)));let a=i.build();e.handleRequest(a,s)}};0&&(module.exports={HttpDeepkitFramework});
6
7
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/frameworks/deepkit/index.ts","../../../src/frameworks/deepkit/http-deepkit.framework.ts","../../../src/network/request.ts","../../../src/network/response.ts","../../../src/network/utils.ts","../../../src/network/response-stream.ts","../../../src/core/headers.ts","../../../src/core/no-op.ts","../../../src/core/logger.ts","../../../src/core/stream.ts"],"sourcesContent":["export * from './http-deepkit.framework';\n","//#region\n\nimport type { ServerResponse } from 'http';\nimport { HttpKernel, HttpResponse, RequestBuilder } from '@deepkit/http';\nimport type { FrameworkContract } from '../../contracts';\nimport { getFlattenedHeadersMap } from '../../core';\nimport { ServerlessRequest } from '../../network';\n\n//#endregion\n\n/**\n * The framework that forwards requests to express handler\n *\n * @breadcrumb Frameworks / HttpDeepkitFramework\n * @public\n */\nexport class HttpDeepkitFramework implements FrameworkContract<HttpKernel> {\n /**\n * {@inheritDoc}\n */\n public sendRequest(\n app: HttpKernel,\n request: ServerlessRequest,\n response: ServerResponse,\n ): void {\n const flattenedHeaders = getFlattenedHeadersMap(request.headers);\n\n let requestBuilder = new RequestBuilder(\n request.url!,\n request.method,\n ).headers(flattenedHeaders);\n\n if (request.body) {\n requestBuilder = Buffer.isBuffer(request.body)\n ? requestBuilder.body(request.body)\n : requestBuilder.body(Buffer.from(request.body));\n }\n\n const httpRequest = requestBuilder.build();\n\n app.handleRequest(httpRequest, response as HttpResponse);\n }\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport type { SingleValueHeaders } from '../@types';\nimport { NO_OP } from '../core';\n\nconst HTTPS_PORT = 443;\n\n/**\n * The properties to create a {@link ServerlessRequest}\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport interface ServerlessRequestProps {\n /**\n * The HTTP Method of the request\n */\n method: string;\n\n /**\n * The URL requested\n */\n url: string;\n\n /**\n * The headers from the event source\n */\n headers: SingleValueHeaders;\n\n /**\n * The body from the event source\n */\n body?: Buffer | Uint8Array;\n\n /**\n * The IP Address from caller\n */\n remoteAddress?: string;\n}\n\n/**\n * The class that represents an {@link http#IncomingMessage} created by the library to represent an actual request to the framework.\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport class ServerlessRequest extends IncomingMessage {\n constructor({\n method,\n url,\n headers,\n body,\n remoteAddress,\n }: ServerlessRequestProps) {\n super({\n encrypted: true,\n readable: false,\n remoteAddress,\n address: () => ({ port: HTTPS_PORT }) as AddressInfo,\n end: NO_OP,\n destroy: NO_OP,\n } as any);\n\n this.statusCode = 200;\n this.statusMessage = 'OK';\n this.complete = true;\n this.httpVersion = '1.1';\n this.httpVersionMajor = 1;\n this.httpVersionMinor = 1;\n this.method = method;\n this.headers = headers;\n this.body = body;\n this.url = url;\n this.ip = remoteAddress;\n\n this._read = () => {\n this.push(body);\n this.push(null);\n };\n }\n\n ip?: string;\n body?: Buffer | Uint8Array;\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport { NO_OP } from '../core';\nimport { getString } from './utils';\n\nconst headerEnd = '\\r\\n\\r\\n';\nconst endChunked = '0\\r\\n\\r\\n';\n\nconst BODY = Symbol('Response body');\nconst HEADERS = Symbol('Response headers');\n\nfunction addData(stream: ServerlessResponse, data: Uint8Array | string) {\n if (\n Buffer.isBuffer(data) ||\n typeof data === 'string' ||\n data instanceof Uint8Array\n )\n stream[BODY].push(Buffer.from(data));\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n\n/**\n * The properties to create a {@link ServerlessResponse}.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport interface ServerlessResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * Once it's happens, we use the properties from this response to built the response to the cloud.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport class ServerlessResponse extends ServerResponse {\n constructor({ method }: ServerlessResponseProps) {\n super({ method } as any);\n\n this[BODY] = [];\n this[HEADERS] = {};\n\n this.useChunkedEncodingByDefault = false;\n this.chunkedEncoding = false;\n this._header = '';\n\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 1;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (this._header === '' || this._wroteHeader) {\n if (!this.chunkedEncoding) addData(this, data);\n else {\n if (writesToIgnore > 0) writesToIgnore--;\n else if (data !== endChunked) {\n addData(this, data);\n writesToIgnore = 3;\n }\n }\n } else {\n const string = getString(data);\n const index = string.indexOf(headerEnd);\n\n if (index !== -1) {\n const remainder = string.slice(index + headerEnd.length);\n\n if (remainder && !this.chunkedEncoding) addData(this, remainder);\n\n this._wroteHeader = true;\n }\n }\n\n if (typeof cb === 'function') cb();\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n\n _header: string;\n _headers?: Record<any, any>;\n _wroteHeader?: boolean;\n\n [BODY]: any[];\n [HEADERS]: Record<any, any>;\n\n get headers(): Record<any, any> {\n return this[HEADERS];\n }\n\n static from(res: IncomingMessage) {\n const response = new ServerlessResponse({ method: res.method });\n\n response.statusCode = res.statusCode || 0;\n response[HEADERS] = res.headers;\n response[BODY] = (res as any).body ? [Buffer.from((res as any).body)] : [];\n response.end();\n\n return response;\n }\n\n static body(res: ServerlessResponse): Buffer {\n return Buffer.concat(res[BODY]);\n }\n\n static headers(res: ServerlessResponse) {\n const headers = res.getHeaders();\n\n return Object.assign(headers, res[HEADERS]);\n }\n\n override setHeader(\n key: string,\n value: number | string | readonly string[],\n ): any {\n if (this._wroteHeader) this[HEADERS][key] = value;\n else super.setHeader(key, value);\n }\n\n override writeHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): any {\n const headersObjOrArray =\n typeof statusMessage === 'string' ? obj : statusMessage;\n\n const arrayHeaders = Array.isArray(headersObjOrArray)\n ? headersObjOrArray\n : [headersObjOrArray || {}];\n\n for (const headers of arrayHeaders) {\n for (const name in headers) {\n this.setHeader(name, headers[name]!);\n\n if (!this._wroteHeader) {\n // we only need to initiate super.headers once\n // writeHead will add the other headers itself\n break;\n }\n }\n }\n\n return this.callNativeWriteHead(statusCode, statusMessage, obj);\n }\n\n /**\n * I use ignore here because in nodejs 12.x, statusMessage can be string | OutgoingHttpHeaders\n * But in nodejs \\>=14.x, statusMessage can also be OutgoingHttpHeaders[]\n * I take care of these cases above, but here I can't handle it well, so I give up\n * nodejs 12.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v12/http.d.ts#L229\n * nodejs 14.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v14/http.d.ts#L263\n */\n protected callNativeWriteHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): this {\n return super.writeHead(statusCode, statusMessage, obj);\n }\n}\n","/**\n * Get the data from a buffer, string, or Uint8Array\n *\n * @breadcrumb Network\n * @param data - The data that was written inside the stream\n */\nexport function getString(data: Buffer | string | unknown) {\n if (Buffer.isBuffer(data)) return data.toString('utf8');\n else if (typeof data === 'string') return data;\n else if (data instanceof Uint8Array) return new TextDecoder().decode(data);\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n","import { ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { Writable } from 'node:stream';\nimport type { BothValueHeaders } from '../@types';\nimport { type ILogger, NO_OP, parseHeaders } from '../core';\nimport { getString } from './utils';\n\nconst endChunked = '0\\r\\n\\r\\n';\nconst headerEnd = '\\r\\n\\r\\n';\nconst endStatusSeparator = '\\r\\n';\n\n/**\n * The properties to create a {@link ServerlessStreamResponse}.\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport interface ServerlessStreamResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n\n /**\n * The callback to receive the headers when they are written to the stream\n * You need to return a writable stream be able to continue writing the response\n *\n * @param statusCode - The status code of the response\n * @param headers - The headers of the response\n */\n onReceiveHeaders: (statusCode: number, headers: BothValueHeaders) => Writable;\n\n /**\n * Instance of the logger\n */\n log: ILogger;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * This response is specially built to deal with transfer-encoding: chunked\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport class ServerlessStreamResponse extends ServerResponse {\n constructor({\n method,\n onReceiveHeaders,\n log,\n }: ServerlessStreamResponseProps) {\n super({ method } as any);\n\n this.useChunkedEncodingByDefault = true;\n this.chunkedEncoding = true;\n\n let internalWritable: Writable | null = null;\n let isFirstCall = true;\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 0;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n // very unlikely, I don't even know how to reproduce this, but exist on types\n // istanbul ignore if\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n log.debug('SERVERLESS_ADAPTER:RESPONSE_STREAM:DATA', () => ({\n data: Buffer.isBuffer(data) ? data.toString('utf8') : data,\n encoding,\n }));\n\n if (!isFirstCall && internalWritable) {\n if (data === endChunked) {\n internalWritable.end(cb);\n\n return true;\n }\n\n if (writesToIgnore > 0) {\n writesToIgnore--;\n return true;\n }\n\n internalWritable.write(data, cb);\n writesToIgnore = 3;\n } else if (isFirstCall) {\n isFirstCall = false;\n\n const stringData = getString(data);\n const endStatusIndex = stringData.indexOf(endStatusSeparator);\n const status = +stringData.slice(0, endStatusIndex).split(' ')[1];\n const endHeaderIndex = stringData.indexOf(headerEnd);\n\n const headerData = stringData.slice(\n endStatusIndex + 2,\n endHeaderIndex,\n );\n const headers = parseHeaders(headerData);\n log.debug(\n 'SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS',\n () => ({\n headers,\n }),\n );\n\n writesToIgnore = 1;\n internalWritable = onReceiveHeaders(status, headers);\n\n // If we get an endChunked right after header which means the response body is empty, we need to immediately end the writable\n if (stringData.substring(endHeaderIndex + 4) === endChunked)\n internalWritable.end();\n }\n\n return true;\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n}\n","//#region Imports\n\nimport type { BothValueHeaders } from '../@types';\n\n//#endregion\n\n/**\n * Transform a header map and make sure the value is not an array\n *\n * @example\n * ```typescript\n * const headers = { 'accept-encoding': 'gzip', 'accept-language': ['en-US', 'en;q=0.9'] };\n * const flattenedHeaders = getFlattenedHeadersMap(headers, ',', true);\n * console.log(flattenedHeaders);\n * // { 'accept-encoding': 'gzip', 'accept-language': 'en-US,en;q=0.9' }\n * ```\n *\n * @param headersMap - The initial headers\n * @param separator - The separator used when we join the array of header's value\n * @param lowerCaseKey - Should put all keys in lowercase\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport function getFlattenedHeadersMap(\n headersMap: BothValueHeaders,\n separator: string = ',',\n lowerCaseKey: boolean = false,\n): Record<string, string> {\n return Object.keys(headersMap).reduce((acc, headerKey) => {\n const newKey = lowerCaseKey ? headerKey.toLowerCase() : headerKey;\n const headerValue = headersMap[headerKey];\n\n if (Array.isArray(headerValue)) acc[newKey] = headerValue.join(separator);\n else acc[newKey] = (headerValue ?? '') + '';\n\n return acc;\n }, {});\n}\n\n/**\n * Transforms a header map into a multi-value map header.\n *\n * @example\n * ```typescript\n * const headers = { 'accept-encoding': 'gzip', 'connection': ['keep-alive'] };\n * const multiValueHeaders = getMultiValueHeadersMap(headers);\n * console.log(multiValueHeaders);\n * // { 'accept-encoding': ['gzip'], 'connection': ['keep-alive'] }\n * ```\n *\n * @param headersMap - The initial headers\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport function getMultiValueHeadersMap(\n headersMap: BothValueHeaders,\n): Record<string, string[]> {\n return Object.keys(headersMap).reduce((acc, headerKey) => {\n const headerValue = headersMap[headerKey];\n\n acc[headerKey.toLowerCase()] = Array.isArray(headerValue)\n ? headerValue.map(String)\n : [String(headerValue)];\n\n return acc;\n }, {});\n}\n\n/**\n * The wrapper that holds the information about single value headers and cookies\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport type FlattenedHeadersAndCookies = {\n /**\n * Just the single value headers\n */\n headers: Record<string, string>;\n\n /**\n * The list of cookies\n */\n cookies: string[];\n};\n\n/**\n * Transforms a header map into a single value headers and cookies\n *\n * @param headersMap - The initial headers\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport function getFlattenedHeadersMapAndCookies(\n headersMap: BothValueHeaders,\n): FlattenedHeadersAndCookies {\n return Object.keys(headersMap).reduce(\n (acc, headerKey) => {\n const headerValue = headersMap[headerKey];\n const lowerHeaderKey = headerKey.toLowerCase();\n\n if (Array.isArray(headerValue)) {\n if (lowerHeaderKey !== 'set-cookie')\n acc.headers[headerKey] = headerValue.join(',');\n else acc.cookies.push(...headerValue);\n } else {\n if (lowerHeaderKey === 'set-cookie' && headerValue !== undefined)\n acc.cookies.push(headerValue ?? '');\n else acc.headers[headerKey] = String(headerValue ?? '');\n }\n\n return acc;\n },\n {\n cookies: [],\n headers: {},\n } as FlattenedHeadersAndCookies,\n );\n}\n\n/**\n * Parse HTTP Raw Headers\n * Attribution to {@link https://github.com/kesla/parse-headers/blob/master/parse-headers.js}\n *\n * @param headers - The raw headers\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport function parseHeaders(\n headers: string,\n): Record<string, string | string[]> {\n if (!headers) return {};\n\n const result = {};\n const headersArr = headers.trim().split('\\n');\n\n for (let i = 0; i < headersArr.length; i++) {\n const row = headersArr[i];\n const index = row.indexOf(':');\n const key = row.slice(0, index).trim().toLowerCase();\n const value = row.slice(index + 1).trim();\n\n if (typeof result[key] === 'undefined') result[key] = value;\n else if (Array.isArray(result[key])) result[key].push(value);\n else result[key] = [result[key], value];\n }\n\n return result;\n}\n","/**\n * No operation function is used when we need to pass a function, but we don't want to specify any behavior.\n *\n * @breadcrumb Core\n * @public\n */\nexport const NO_OP: (...args: any[]) => any = () => void 0;\n","import { NO_OP } from './no-op';\n\n/**\n * The type representing the possible log levels to choose from.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LogLevels =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'none';\n\n/**\n * The options to customize {@link ILogger}\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerOptions = {\n /**\n * Select the log level, {@link LogLevels | see more}.\n *\n * @defaultValue error\n */\n level: LogLevels;\n};\n\n/**\n * The log function used in any level.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerFN = (message: any, ...additional: any[]) => void;\n\n/**\n * The interface representing the logger, you can provide a custom logger by implementing this interface.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type ILogger = Record<Exclude<LogLevels, 'none'>, LoggerFN>;\n\n/**\n * The symbol used to check against an ILogger instace to verify if that ILogger was created by this library\n *\n * @breadcrumb Core / Logger\n * @public\n */\nconst InternalLoggerSymbol = Symbol('InternalLogger');\n\nconst logLevels: Record<\n LogLevels,\n [level: LogLevels, consoleMethod: keyof Console][]\n> = {\n debug: [\n ['debug', 'debug'],\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n verbose: [\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n info: [\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n warn: [\n ['warn', 'warn'],\n ['error', 'error'],\n ],\n error: [['error', 'error']],\n none: [],\n};\n\nconst lazyPrint = (value: () => any | unknown) => {\n if (typeof value === 'function') return value();\n\n return value;\n};\n\nconst print =\n (fn: string) =>\n (message: any, ...additional: (() => any)[]) =>\n console[fn](message, ...additional.map(lazyPrint));\n\n/**\n * The method used to create a simple logger instance to use in this library.\n *\n * @remarks Behind the scenes, this simple logger sends the message to the `console` methods.\n *\n * @example\n * ```typescript\n * const logger = createDefaultLogger();\n *\n * logger.error('An error happens.');\n * // An error happens.\n * ```\n *\n * @param level - Select the level of the log\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function createDefaultLogger(\n { level }: LoggerOptions = { level: 'error' },\n): ILogger {\n const levels = logLevels[level];\n\n if (!levels) throw new Error('Invalid log level');\n\n const logger = {\n [InternalLoggerSymbol]: true,\n error: NO_OP,\n debug: NO_OP,\n info: NO_OP,\n verbose: NO_OP,\n warn: NO_OP,\n } as ILogger;\n\n for (const [level, consoleMethod] of levels)\n logger[level] = print(consoleMethod);\n\n return logger;\n}\n\n/**\n * The method used to chck if logger was created by this library, or it was defined by the user.\n *\n * @param logger - The instance of the logger to check\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function isInternalLogger(logger: ILogger): boolean {\n return !!logger[InternalLoggerSymbol];\n}\n","//#region Imports\n\nimport { Readable, Writable } from 'node:stream';\n\n//#endregion\n\n/**\n * Check if stream already ended\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function isStreamEnded(stream: Readable | Writable): boolean {\n if ('readableEnded' in stream && stream.readableEnded) return true;\n\n if ('writableEnded' in stream && stream.writableEnded) return true;\n\n return false;\n}\n\n/**\n * Wait asynchronous the stream to complete\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function waitForStreamComplete<TStream extends Readable | Writable>(\n stream: TStream,\n): Promise<TStream> {\n if (isStreamEnded(stream)) return Promise.resolve(stream);\n\n return new Promise<TStream>((resolve, reject) => {\n // Reading the {@link https://github.com/nodejs/node/blob/v12.22.9/lib/events.js#L262 | emit source code},\n // it's almost impossible to complete being called twice because the emit function runs synchronously and removes the other listeners,\n // but I'll leave it at that because I didn't write that code, so I couldn't figure out what the author thought when he wrote this.\n let isComplete = false;\n\n function complete(err: any) {\n /* istanbul ignore next */\n if (isComplete) return;\n\n isComplete = true;\n\n stream.removeListener('error', complete);\n stream.removeListener('end', complete);\n stream.removeListener('finish', complete);\n\n if (err) reject(err);\n else resolve(stream);\n }\n\n stream.once('error', complete);\n stream.once('end', complete);\n stream.once('finish', complete);\n });\n}\n"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAA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,CACF","names":["deepkit_exports","__export","HttpDeepkitFramework","__toCommonJS","import_http","import_node_http","import_node_http","getString","data","__name","headerEnd","endChunked","BODY","HEADERS","addData","stream","data","__name","ServerlessResponse","_ServerlessResponse","method","writesToIgnore","socket","NO_OP","encoding","cb","string","getString","index","remainder","res","response","headers","key","value","statusCode","statusMessage","obj","headersObjOrArray","arrayHeaders","name","import_node_http","getFlattenedHeadersMap","headersMap","separator","lowerCaseKey","acc","headerKey","newKey","headerValue","__name","NO_OP","__name","InternalLoggerSymbol","import_node_stream","HttpDeepkitFramework","__name","app","request","response","flattenedHeaders","getFlattenedHeadersMap","requestBuilder","httpRequest"]}
1
+ {"version":3,"sources":["../../../src/frameworks/deepkit/index.ts","../../../src/frameworks/deepkit/http-deepkit.framework.ts","../../../src/network/request.ts","../../../src/network/response.ts","../../../src/network/utils.ts","../../../src/network/response-stream.ts","../../../src/core/headers.ts","../../../src/core/no-op.ts","../../../src/core/logger.ts","../../../src/core/stream.ts"],"sourcesContent":["export * from './http-deepkit.framework';\n","//#region\n\nimport type { ServerResponse } from 'http';\nimport { HttpKernel, HttpResponse, RequestBuilder } from '@deepkit/http';\nimport type { FrameworkContract } from '../../contracts';\nimport { getFlattenedHeadersMap } from '../../core';\nimport { ServerlessRequest } from '../../network';\n\n//#endregion\n\n/**\n * The framework that forwards requests to express handler\n *\n * @breadcrumb Frameworks / HttpDeepkitFramework\n * @public\n */\nexport class HttpDeepkitFramework implements FrameworkContract<HttpKernel> {\n /**\n * {@inheritDoc}\n */\n public sendRequest(\n app: HttpKernel,\n request: ServerlessRequest,\n response: ServerResponse,\n ): void {\n const flattenedHeaders = getFlattenedHeadersMap(request.headers);\n\n let requestBuilder = new RequestBuilder(\n request.url!,\n request.method,\n ).headers(flattenedHeaders);\n\n if (request.body) {\n requestBuilder = Buffer.isBuffer(request.body)\n ? requestBuilder.body(request.body)\n : requestBuilder.body(Buffer.from(request.body));\n }\n\n const httpRequest = requestBuilder.build();\n\n app.handleRequest(httpRequest, response as HttpResponse);\n }\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport type { SingleValueHeaders } from '../@types';\nimport { NO_OP } from '../core';\n\nconst HTTPS_PORT = 443;\n\n/**\n * The properties to create a {@link ServerlessRequest}\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport interface ServerlessRequestProps {\n /**\n * The HTTP Method of the request\n */\n method: string;\n\n /**\n * The URL requested\n */\n url: string;\n\n /**\n * The headers from the event source\n */\n headers: SingleValueHeaders;\n\n /**\n * The body from the event source\n */\n body?: Buffer | Uint8Array;\n\n /**\n * The IP Address from caller\n */\n remoteAddress?: string;\n}\n\n/**\n * The class that represents an {@link http#IncomingMessage} created by the library to represent an actual request to the framework.\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport class ServerlessRequest extends IncomingMessage {\n constructor({\n method,\n url,\n headers,\n body,\n remoteAddress,\n }: ServerlessRequestProps) {\n super({\n encrypted: true,\n readable: false,\n remoteAddress,\n address: () => ({ port: HTTPS_PORT }) as AddressInfo,\n end: NO_OP,\n destroy: NO_OP,\n } as any);\n\n this.statusCode = 200;\n this.statusMessage = 'OK';\n this.complete = true;\n this.httpVersion = '1.1';\n this.httpVersionMajor = 1;\n this.httpVersionMinor = 1;\n this.method = method;\n this.headers = headers;\n this.body = body;\n this.url = url;\n this.ip = remoteAddress;\n\n this._read = () => {\n this.push(body);\n this.push(null);\n };\n }\n\n ip?: string;\n body?: Buffer | Uint8Array;\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport { NO_OP } from '../core';\nimport { getString } from './utils';\n\nconst headerEnd = '\\r\\n\\r\\n';\nconst endChunked = '0\\r\\n\\r\\n';\n\nconst BODY = Symbol('Response body');\nconst HEADERS = Symbol('Response headers');\n\nfunction addData(stream: ServerlessResponse, data: Uint8Array | string) {\n if (\n Buffer.isBuffer(data) ||\n typeof data === 'string' ||\n data instanceof Uint8Array\n )\n stream[BODY].push(Buffer.from(data));\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n\n/**\n * The properties to create a {@link ServerlessResponse}.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport interface ServerlessResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * Once it's happens, we use the properties from this response to built the response to the cloud.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport class ServerlessResponse extends ServerResponse {\n constructor({ method }: ServerlessResponseProps) {\n super({ method } as any);\n\n this[BODY] = [];\n this[HEADERS] = {};\n\n this.useChunkedEncodingByDefault = false;\n this.chunkedEncoding = false;\n this._header = '';\n\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 1;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (this._header === '' || this._wroteHeader) {\n if (!this.chunkedEncoding) addData(this, data);\n else {\n if (writesToIgnore > 0) writesToIgnore--;\n else if (data !== endChunked) {\n addData(this, data);\n writesToIgnore = 3;\n }\n }\n } else {\n const string = getString(data);\n const index = string.indexOf(headerEnd);\n\n if (index !== -1) {\n const remainder = string.slice(index + headerEnd.length);\n\n if (remainder && !this.chunkedEncoding) addData(this, remainder);\n\n this._wroteHeader = true;\n }\n }\n\n if (typeof cb === 'function') cb();\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n\n _header: string;\n _headers?: Record<any, any>;\n _wroteHeader?: boolean;\n\n [BODY]: any[];\n [HEADERS]: Record<any, any>;\n\n get headers(): Record<any, any> {\n return this[HEADERS];\n }\n\n static from(res: IncomingMessage) {\n const response = new ServerlessResponse({ method: res.method });\n\n response.statusCode = res.statusCode || 0;\n response[HEADERS] = res.headers;\n response[BODY] = (res as any).body ? [Buffer.from((res as any).body)] : [];\n response.end();\n\n return response;\n }\n\n static body(res: ServerlessResponse): Buffer {\n return Buffer.concat(res[BODY]);\n }\n\n static headers(res: ServerlessResponse) {\n const headers = res.getHeaders();\n\n return Object.assign(headers, res[HEADERS]);\n }\n\n override setHeader(\n key: string,\n value: number | string | readonly string[],\n ): any {\n if (this._wroteHeader) this[HEADERS][key] = value;\n else super.setHeader(key, value);\n }\n\n override writeHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): any {\n const headersObjOrArray =\n typeof statusMessage === 'string' ? obj : statusMessage;\n\n const arrayHeaders = Array.isArray(headersObjOrArray)\n ? headersObjOrArray\n : [headersObjOrArray || {}];\n\n for (const headers of arrayHeaders) {\n for (const name in headers) {\n this.setHeader(name, headers[name]!);\n\n if (!this._wroteHeader) {\n // we only need to initiate super.headers once\n // writeHead will add the other headers itself\n break;\n }\n }\n }\n\n return this.callNativeWriteHead(statusCode, statusMessage, obj);\n }\n\n /**\n * I use ignore here because in nodejs 12.x, statusMessage can be string | OutgoingHttpHeaders\n * But in nodejs \\>=14.x, statusMessage can also be OutgoingHttpHeaders[]\n * I take care of these cases above, but here I can't handle it well, so I give up\n * nodejs 12.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v12/http.d.ts#L229\n * nodejs 14.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v14/http.d.ts#L263\n */\n protected callNativeWriteHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): this {\n return super.writeHead(statusCode, statusMessage, obj);\n }\n}\n","/**\n * Get the data from a buffer, string, or Uint8Array\n *\n * @breadcrumb Network\n * @param data - The data that was written inside the stream\n */\nexport function getString(data: Buffer | string | unknown) {\n if (Buffer.isBuffer(data)) return data.toString('utf8');\n else if (typeof data === 'string') return data;\n else if (data instanceof Uint8Array) return new TextDecoder().decode(data);\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n","import { ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { Writable } from 'node:stream';\nimport type { BothValueHeaders } from '../@types';\nimport { type ILogger, NO_OP, parseHeaders } from '../core';\nimport { getString } from './utils';\n\n// header or data crlf\nconst crlfBuffer = Buffer.from('\\r\\n');\n\nconst endChunked = '0\\r\\n\\r\\n';\nconst headerEnd = '\\r\\n\\r\\n';\nconst endStatusSeparator = '\\r\\n';\n\n/**\n * The properties to create a {@link ServerlessStreamResponse}.\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport interface ServerlessStreamResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n\n /**\n * The callback to receive the headers when they are written to the stream\n * You need to return a writable stream be able to continue writing the response\n *\n * @param statusCode - The status code of the response\n * @param headers - The headers of the response\n */\n onReceiveHeaders: (statusCode: number, headers: BothValueHeaders) => Writable;\n\n /**\n * Instance of the logger\n */\n log: ILogger;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * This response is specially built to deal with transfer-encoding: chunked\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport class ServerlessStreamResponse extends ServerResponse {\n constructor({\n method,\n onReceiveHeaders,\n log,\n }: ServerlessStreamResponseProps) {\n super({ method } as any);\n\n this.useChunkedEncodingByDefault = true;\n this.chunkedEncoding = true;\n\n let internalWritable: Writable | null = null;\n let firstCrlfBufferEncountered = false;\n let chunkEncountered = false;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n // very unlikely, I don't even know how to reproduce this, but exist on types\n // istanbul ignore if\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n log.debug('SERVERLESS_ADAPTER:RESPONSE_STREAM:DATA', () => ({\n data: Buffer.isBuffer(data) ? data.toString('utf8') : data,\n encoding,\n }));\n\n if (!internalWritable) {\n const stringData = getString(data);\n const endStatusIndex = stringData.indexOf(endStatusSeparator);\n const status = +stringData.slice(0, endStatusIndex).split(' ')[1];\n const endHeaderIndex = stringData.indexOf(headerEnd);\n\n const headerData = stringData.slice(\n endStatusIndex + 2,\n endHeaderIndex,\n );\n const headers = parseHeaders(headerData);\n log.debug(\n 'SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS',\n () => ({\n headers,\n }),\n );\n\n internalWritable = onReceiveHeaders(status, headers);\n\n // If we get an endChunked right after header which means the response body is empty, we need to immediately end the writable\n if (stringData.substring(endHeaderIndex + 4) === endChunked)\n internalWritable.end();\n\n return true;\n }\n\n // node sends the last chunk crlf as a string:\n // https://github.com/nodejs/node/blob/v22.8.0/lib/_http_outgoing.js#L1131\n if (data === endChunked) {\n internalWritable.end(cb);\n return true;\n }\n\n // check for header or data crlf\n // node sends the header and data crlf as a buffer\n // below code is aligned to following node implementation of the HTTP/1.1 chunked transfer coding:\n // https://github.com/nodejs/node/blob/v22.8.0/lib/_http_outgoing.js#L1012-L1015\n // for reference: https://datatracker.ietf.org/doc/html/rfc9112#section-7\n if (Buffer.isBuffer(data) && crlfBuffer.equals(data)) {\n const isHeaderCrlf = !firstCrlfBufferEncountered;\n if (isHeaderCrlf) {\n firstCrlfBufferEncountered = true;\n return true;\n }\n\n const isDataCrlf = firstCrlfBufferEncountered && chunkEncountered;\n if (isDataCrlf) {\n // done with chunk\n firstCrlfBufferEncountered = false;\n chunkEncountered = false;\n return true;\n }\n\n // the crlf *is* the chunk\n }\n\n const isContentLength = !firstCrlfBufferEncountered;\n if (isContentLength) {\n // discard content length\n return true;\n }\n\n // write chunk\n chunkEncountered = true;\n internalWritable.write(data, cb);\n return true;\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n}\n","//#region Imports\n\nimport type { BothValueHeaders } from '../@types';\n\n//#endregion\n\n/**\n * Transform a header map and make sure the value is not an array\n *\n * @example\n * ```typescript\n * const headers = { 'accept-encoding': 'gzip', 'accept-language': ['en-US', 'en;q=0.9'] };\n * const flattenedHeaders = getFlattenedHeadersMap(headers, ',', true);\n * console.log(flattenedHeaders);\n * // { 'accept-encoding': 'gzip', 'accept-language': 'en-US,en;q=0.9' }\n * ```\n *\n * @param headersMap - The initial headers\n * @param separator - The separator used when we join the array of header's value\n * @param lowerCaseKey - Should put all keys in lowercase\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport function getFlattenedHeadersMap(\n headersMap: BothValueHeaders,\n separator: string = ',',\n lowerCaseKey: boolean = false,\n): Record<string, string> {\n return Object.keys(headersMap).reduce((acc, headerKey) => {\n const newKey = lowerCaseKey ? headerKey.toLowerCase() : headerKey;\n const headerValue = headersMap[headerKey];\n\n if (Array.isArray(headerValue)) acc[newKey] = headerValue.join(separator);\n else acc[newKey] = (headerValue ?? '') + '';\n\n return acc;\n }, {});\n}\n\n/**\n * Transforms a header map into a multi-value map header.\n *\n * @example\n * ```typescript\n * const headers = { 'accept-encoding': 'gzip', 'connection': ['keep-alive'] };\n * const multiValueHeaders = getMultiValueHeadersMap(headers);\n * console.log(multiValueHeaders);\n * // { 'accept-encoding': ['gzip'], 'connection': ['keep-alive'] }\n * ```\n *\n * @param headersMap - The initial headers\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport function getMultiValueHeadersMap(\n headersMap: BothValueHeaders,\n): Record<string, string[]> {\n return Object.keys(headersMap).reduce((acc, headerKey) => {\n const headerValue = headersMap[headerKey];\n\n acc[headerKey.toLowerCase()] = Array.isArray(headerValue)\n ? headerValue.map(String)\n : [String(headerValue)];\n\n return acc;\n }, {});\n}\n\n/**\n * The wrapper that holds the information about single value headers and cookies\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport type FlattenedHeadersAndCookies = {\n /**\n * Just the single value headers\n */\n headers: Record<string, string>;\n\n /**\n * The list of cookies\n */\n cookies: string[];\n};\n\n/**\n * Transforms a header map into a single value headers and cookies\n *\n * @param headersMap - The initial headers\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport function getFlattenedHeadersMapAndCookies(\n headersMap: BothValueHeaders,\n): FlattenedHeadersAndCookies {\n return Object.keys(headersMap).reduce(\n (acc, headerKey) => {\n const headerValue = headersMap[headerKey];\n const lowerHeaderKey = headerKey.toLowerCase();\n\n if (Array.isArray(headerValue)) {\n if (lowerHeaderKey !== 'set-cookie')\n acc.headers[headerKey] = headerValue.join(',');\n else acc.cookies.push(...headerValue);\n } else {\n if (lowerHeaderKey === 'set-cookie' && headerValue !== undefined)\n acc.cookies.push(headerValue ?? '');\n else acc.headers[headerKey] = String(headerValue ?? '');\n }\n\n return acc;\n },\n {\n cookies: [],\n headers: {},\n } as FlattenedHeadersAndCookies,\n );\n}\n\n/**\n * Parse HTTP Raw Headers\n * Attribution to {@link https://github.com/kesla/parse-headers/blob/master/parse-headers.js}\n *\n * @param headers - The raw headers\n *\n * @breadcrumb Core / Headers\n * @public\n */\nexport function parseHeaders(\n headers: string,\n): Record<string, string | string[]> {\n if (!headers) return {};\n\n const result = {};\n const headersArr = headers.trim().split('\\n');\n\n for (let i = 0; i < headersArr.length; i++) {\n const row = headersArr[i];\n const index = row.indexOf(':');\n const key = row.slice(0, index).trim().toLowerCase();\n const value = row.slice(index + 1).trim();\n\n if (typeof result[key] === 'undefined') result[key] = value;\n else if (Array.isArray(result[key])) result[key].push(value);\n else result[key] = [result[key], value];\n }\n\n return result;\n}\n\nexport function keysToLowercase<T extends Record<string, unknown>>(\n obj: T,\n): { [K in keyof T as Lowercase<string & K>]: T[K] } {\n const result: any = {};\n for (const [k, v] of Object.entries(obj)) result[k.toLowerCase()] = v;\n\n return result as { [K in keyof T as Lowercase<string & K>]: T[K] };\n}\n","/**\n * No operation function is used when we need to pass a function, but we don't want to specify any behavior.\n *\n * @breadcrumb Core\n * @public\n */\nexport const NO_OP: (...args: any[]) => any = () => void 0;\n","import { NO_OP } from './no-op';\n\n/**\n * The type representing the possible log levels to choose from.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LogLevels =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'none';\n\n/**\n * The options to customize {@link ILogger}\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerOptions = {\n /**\n * Select the log level, {@link LogLevels | see more}.\n *\n * @defaultValue error\n */\n level: LogLevels;\n};\n\n/**\n * The log function used in any level.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerFN = (message: any, ...additional: any[]) => void;\n\n/**\n * The interface representing the logger, you can provide a custom logger by implementing this interface.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type ILogger = Record<Exclude<LogLevels, 'none'>, LoggerFN>;\n\n/**\n * The symbol used to check against an ILogger instace to verify if that ILogger was created by this library\n *\n * @breadcrumb Core / Logger\n * @public\n */\nconst InternalLoggerSymbol = Symbol('InternalLogger');\n\nconst logLevels: Record<\n LogLevels,\n [level: LogLevels, consoleMethod: keyof Console][]\n> = {\n debug: [\n ['debug', 'debug'],\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n verbose: [\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n info: [\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n warn: [\n ['warn', 'warn'],\n ['error', 'error'],\n ],\n error: [['error', 'error']],\n none: [],\n};\n\nconst lazyPrint = (value: () => any | unknown) => {\n if (typeof value === 'function') return value();\n\n return value;\n};\n\nconst print =\n (fn: string) =>\n (message: any, ...additional: (() => any)[]) =>\n console[fn](message, ...additional.map(lazyPrint));\n\n/**\n * The method used to create a simple logger instance to use in this library.\n *\n * @remarks Behind the scenes, this simple logger sends the message to the `console` methods.\n *\n * @example\n * ```typescript\n * const logger = createDefaultLogger();\n *\n * logger.error('An error happens.');\n * // An error happens.\n * ```\n *\n * @param level - Select the level of the log\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function createDefaultLogger(\n { level }: LoggerOptions = { level: 'error' },\n): ILogger {\n const levels = logLevels[level];\n\n if (!levels) throw new Error('Invalid log level');\n\n const logger = {\n [InternalLoggerSymbol]: true,\n error: NO_OP,\n debug: NO_OP,\n info: NO_OP,\n verbose: NO_OP,\n warn: NO_OP,\n } as ILogger;\n\n for (const [level, consoleMethod] of levels)\n logger[level] = print(consoleMethod);\n\n return logger;\n}\n\n/**\n * The method used to chck if logger was created by this library, or it was defined by the user.\n *\n * @param logger - The instance of the logger to check\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function isInternalLogger(logger: ILogger): boolean {\n return !!logger[InternalLoggerSymbol];\n}\n","//#region Imports\n\nimport { Readable, Writable } from 'node:stream';\n\n//#endregion\n\n/**\n * Check if stream already ended\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function isStreamEnded(stream: Readable | Writable): boolean {\n if ('readableEnded' in stream && stream.readableEnded) return true;\n\n if ('writableEnded' in stream && stream.writableEnded) return true;\n\n return false;\n}\n\n/**\n * Wait asynchronous the stream to complete\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function waitForStreamComplete<TStream extends Readable | Writable>(\n stream: TStream,\n): Promise<TStream> {\n if (isStreamEnded(stream)) return Promise.resolve(stream);\n\n return new Promise<TStream>((resolve, reject) => {\n // Reading the {@link https://github.com/nodejs/node/blob/v12.22.9/lib/events.js#L262 | emit source code},\n // it's almost impossible to complete being called twice because the emit function runs synchronously and removes the other listeners,\n // but I'll leave it at that because I didn't write that code, so I couldn't figure out what the author thought when he wrote this.\n let isComplete = false;\n\n function complete(err: any) {\n /* istanbul ignore next */\n if (isComplete) return;\n\n isComplete = true;\n\n stream.removeListener('error', complete);\n stream.removeListener('end', complete);\n stream.removeListener('finish', complete);\n\n if (err) reject(err);\n else resolve(stream);\n }\n\n stream.once('error', complete);\n stream.once('end', complete);\n stream.once('finish', complete);\n });\n}\n"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,0BAAAE,IAAA,eAAAC,EAAAH,GCGA,IAAAI,EAAyD,yBCFzD,IAAAC,EAAgC,gBCAhC,IAAAC,EAAgD,gBCKzC,SAASC,EAAUC,EAAiC,CACzD,GAAI,OAAO,SAASA,CAAI,EAAG,OAAOA,EAAK,SAAS,MAAM,EACjD,GAAI,OAAOA,GAAS,SAAU,OAAOA,EACrC,GAAIA,aAAgB,WAAY,OAAO,IAAI,YAAY,EAAE,OAAOA,CAAI,EACpE,MAAM,IAAI,MAAM,wCAAwC,OAAOA,CAAI,EAAE,CAC5E,CALgBC,EAAAF,EAAA,aDAhB,IAAMG,EAAY;AAAA;AAAA,EACZC,EAAa;AAAA;AAAA,EAEbC,EAAO,OAAO,eAAe,EAC7BC,EAAU,OAAO,kBAAkB,EAEzC,SAASC,EAAQC,EAA4BC,EAA2B,CACtE,GACE,OAAO,SAASA,CAAI,GACpB,OAAOA,GAAS,UAChBA,aAAgB,WAEhBD,EAAOH,CAAI,EAAE,KAAK,OAAO,KAAKI,CAAI,CAAC,MAChC,OAAM,IAAI,MAAM,wCAAwC,OAAOA,CAAI,EAAE,CAC5E,CARSC,EAAAH,EAAA,WA8BF,IAAMI,EAAN,MAAMC,UAA2B,gBAAe,CA1CvD,MA0CuD,CAAAF,EAAA,2BACrD,YAAY,CAAE,OAAAG,CAAO,EAA4B,CAC/C,MAAM,CAAE,OAAAA,CAAO,CAAQ,EAEvB,KAAKR,CAAI,EAAI,CAAC,EACd,KAAKC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AIlE,YACLC,EACAC,EACAC,EACM,CACN,IAAMC,EAAmBC,EAAuBH,EAAQ,OAAO,EAE3DI,EAAiB,IAAI,iBACvBJ,EAAQ,IACRA,EAAQ,MACV,EAAE,QAAQE,CAAgB,EAEtBF,EAAQ,OACVI,EAAiB,OAAO,SAASJ,EAAQ,IAAI,EACzCI,EAAe,KAAKJ,EAAQ,IAAI,EAChCI,EAAe,KAAK,OAAO,KAAKJ,EAAQ,IAAI,CAAC,GAGnD,IAAMK,EAAcD,EAAe,MAAM,EAEzCL,EAAI,cAAcM,EAAaJ,CAAwB,CACzD,CACF","names":["deepkit_exports","__export","HttpDeepkitFramework","__toCommonJS","import_http","import_node_http","import_node_http","getString","data","__name","headerEnd","endChunked","BODY","HEADERS","addData","stream","data","__name","ServerlessResponse","_ServerlessResponse","method","writesToIgnore","socket","NO_OP","encoding","cb","string","getString","index","remainder","res","response","headers","key","value","statusCode","statusMessage","obj","headersObjOrArray","arrayHeaders","name","import_node_http","crlfBuffer","getFlattenedHeadersMap","headersMap","separator","lowerCaseKey","acc","headerKey","newKey","headerValue","__name","NO_OP","__name","InternalLoggerSymbol","import_node_stream","HttpDeepkitFramework","__name","app","request","response","flattenedHeaders","getFlattenedHeadersMap","requestBuilder","httpRequest"]}
@@ -1,2 +1,2 @@
1
- import{h as o}from"../../chunk-MQYXRLYI.mjs";import{a as r}from"../../chunk-OYOJMOFP.mjs";import{RequestBuilder as m}from"@deepkit/http";var s=class{static{r(this,"HttpDeepkitFramework")}sendRequest(p,e,d){let n=o(e.headers),t=new m(e.url,e.method).headers(n);e.body&&(t=Buffer.isBuffer(e.body)?t.body(e.body):t.body(Buffer.from(e.body)));let l=t.build();p.handleRequest(l,d)}};export{s as HttpDeepkitFramework};
1
+ import{h as o}from"../../chunk-L4VRXTKP.mjs";import{a as r}from"../../chunk-OYOJMOFP.mjs";import{RequestBuilder as m}from"@deepkit/http";var s=class{static{r(this,"HttpDeepkitFramework")}sendRequest(p,e,d){let n=o(e.headers),t=new m(e.url,e.method).headers(n);e.body&&(t=Buffer.isBuffer(e.body)?t.body(e.body):t.body(Buffer.from(e.body)));let l=t.build();p.handleRequest(l,d)}};export{s as HttpDeepkitFramework};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1,6 +1,7 @@
1
- "use strict";var l=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var n=(t,e)=>l(t,"name",{value:e,configurable:!0});var b=(t,e)=>{for(var r in e)l(t,r,{get:e[r],enumerable:!0})},w=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of E(e))!T.call(t,o)&&o!==r&&l(t,o,{get:()=>e[o],enumerable:!(s=A(e,o))||s.enumerable});return t};var C=t=>w(l({},"__esModule",{value:!0}),t);var _={};b(_,{LazyFramework:()=>m});module.exports=C(_);var k=require("http");var R=require("http");function f(t){if(Buffer.isBuffer(t))return t.toString("utf8");if(typeof t=="string")return t;if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw new Error(`response.write() of unexpected type: ${typeof t}`)}n(f,"getString");var x=`\r
1
+ "use strict";var c=Object.defineProperty;var v=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var n=(t,e)=>c(t,"name",{value:e,configurable:!0});var w=(t,e)=>{for(var r in e)c(t,r,{get:e[r],enumerable:!0})},b=(t,e,r,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of E(e))!A.call(t,o)&&o!==r&&c(t,o,{get:()=>e[o],enumerable:!(s=v(e,o))||s.enumerable});return t};var C=t=>b(c({},"__esModule",{value:!0}),t);var _={};w(_,{LazyFramework:()=>m});module.exports=C(_);var k=require("http");var R=require("http");function l(t){if(Buffer.isBuffer(t))return t.toString("utf8");if(typeof t=="string")return t;if(t instanceof Uint8Array)return new TextDecoder().decode(t);throw new Error(`response.write() of unexpected type: ${typeof t}`)}n(l,"getString");var S=`\r
2
2
  \r
3
3
  `,L=`0\r
4
4
  \r
5
- `,c=Symbol("Response body"),d=Symbol("Response headers");function g(t,e){if(Buffer.isBuffer(e)||typeof e=="string"||e instanceof Uint8Array)t[c].push(Buffer.from(e));else throw new Error(`response.write() of unexpected type: ${typeof e}`)}n(g,"addData");var y=class t extends R.ServerResponse{static{n(this,"ServerlessResponse")}constructor({method:e}){super({method:e}),this[c]=[],this[d]={},this.useChunkedEncodingByDefault=!1,this.chunkedEncoding=!1,this._header="";let r=1,s={_writableState:{},writable:!0,on:i,removeListener:i,destroy:i,cork:i,uncork:i,write:(o,p,a)=>{if(typeof p=="function"&&(a=p,p=null),this._header===""||this._wroteHeader)this.chunkedEncoding?r>0?r--:o!==L&&(g(this,o),r=3):g(this,o);else{let u=f(o),h=u.indexOf(x);if(h!==-1){let S=u.slice(h+x.length);S&&!this.chunkedEncoding&&g(this,S),this._wroteHeader=!0}}typeof a=="function"&&a()}};this.assignSocket(s)}_header;_headers;_wroteHeader;[c];[d];get headers(){return this[d]}static from(e){let r=new t({method:e.method});return r.statusCode=e.statusCode||0,r[d]=e.headers,r[c]=e.body?[Buffer.from(e.body)]:[],r.end(),r}static body(e){return Buffer.concat(e[c])}static headers(e){let r=e.getHeaders();return Object.assign(r,e[d])}setHeader(e,r){this._wroteHeader?this[d][e]=r:super.setHeader(e,r)}writeHead(e,r,s){let o=typeof r=="string"?s:r,p=Array.isArray(o)?o:[o||{}];for(let a of p)for(let u in a)if(this.setHeader(u,a[u]),!this._wroteHeader)break;return this.callNativeWriteHead(e,r,s)}callNativeWriteHead(e,r,s){return super.writeHead(e,r,s)}};var B=require("http");var i=n(()=>{},"NO_OP");var H=Symbol("InternalLogger"),I={debug:[["debug","debug"],["verbose","debug"],["info","info"],["error","error"],["warn","warn"]],verbose:[["verbose","debug"],["info","info"],["error","error"],["warn","warn"]],info:[["info","info"],["error","error"],["warn","warn"]],warn:[["warn","warn"],["error","error"]],error:[["error","error"]],none:[]},O=n(t=>typeof t=="function"?t():t,"lazyPrint"),P=n(t=>(e,...r)=>console[t](e,...r.map(O)),"print");function v({level:t}={level:"error"}){let e=I[t];if(!e)throw new Error("Invalid log level");let r={[H]:!0,error:i,debug:i,info:i,verbose:i,warn:i};for(let[s,o]of e)r[s]=P(o);return r}n(v,"createDefaultLogger");var be=require("stream");var m=class{constructor(e,r,s=v()){this.framework=e;this.factory=r;this.logger=s;this.delayedFactory=Promise.resolve().then(()=>r()).then(o=>{this.cachedApp=o}).catch(o=>{this.logger.error("SERVERLESS_ADAPTER:LAZY_FRAMEWORK: An error occours during the creation of your app."),this.logger.error(o)})}static{n(this,"LazyFramework")}cachedApp;delayedFactory;sendRequest(e,r,s){if(this.cachedApp)return this.framework.sendRequest(this.cachedApp,r,s);this.delayedFactory.then(()=>this.cachedApp?this.framework.sendRequest(this.cachedApp,r,s):s.emit("error",new Error("SERVERLESS_ADAPTER:LAZY_FRAMEWORK: The instance of the app returned by the factory is not valid, see the logs to learn more.")))}};0&&(module.exports={LazyFramework});
5
+ `,u=Symbol("Response body"),d=Symbol("Response headers");function g(t,e){if(Buffer.isBuffer(e)||typeof e=="string"||e instanceof Uint8Array)t[u].push(Buffer.from(e));else throw new Error(`response.write() of unexpected type: ${typeof e}`)}n(g,"addData");var y=class t extends R.ServerResponse{static{n(this,"ServerlessResponse")}constructor({method:e}){super({method:e}),this[u]=[],this[d]={},this.useChunkedEncodingByDefault=!1,this.chunkedEncoding=!1,this._header="";let r=1,s={_writableState:{},writable:!0,on:i,removeListener:i,destroy:i,cork:i,uncork:i,write:(o,f,a)=>{if(typeof f=="function"&&(a=f,f=null),this._header===""||this._wroteHeader)this.chunkedEncoding?r>0?r--:o!==L&&(g(this,o),r=3):g(this,o);else{let p=l(o),h=p.indexOf(S);if(h!==-1){let x=p.slice(h+S.length);x&&!this.chunkedEncoding&&g(this,x),this._wroteHeader=!0}}typeof a=="function"&&a()}};this.assignSocket(s)}_header;_headers;_wroteHeader;[u];[d];get headers(){return this[d]}static from(e){let r=new t({method:e.method});return r.statusCode=e.statusCode||0,r[d]=e.headers,r[u]=e.body?[Buffer.from(e.body)]:[],r.end(),r}static body(e){return Buffer.concat(e[u])}static headers(e){let r=e.getHeaders();return Object.assign(r,e[d])}setHeader(e,r){this._wroteHeader?this[d][e]=r:super.setHeader(e,r)}writeHead(e,r,s){let o=typeof r=="string"?s:r,f=Array.isArray(o)?o:[o||{}];for(let a of f)for(let p in a)if(this.setHeader(p,a[p]),!this._wroteHeader)break;return this.callNativeWriteHead(e,r,s)}callNativeWriteHead(e,r,s){return super.writeHead(e,r,s)}};var B=require("http");var Z=Buffer.from(`\r
6
+ `);var i=n(()=>{},"NO_OP");var H=Symbol("InternalLogger"),I={debug:[["debug","debug"],["verbose","debug"],["info","info"],["error","error"],["warn","warn"]],verbose:[["verbose","debug"],["info","info"],["error","error"],["warn","warn"]],info:[["info","info"],["error","error"],["warn","warn"]],warn:[["warn","warn"],["error","error"]],error:[["error","error"]],none:[]},O=n(t=>typeof t=="function"?t():t,"lazyPrint"),P=n(t=>(e,...r)=>console[t](e,...r.map(O)),"print");function T({level:t}={level:"error"}){let e=I[t];if(!e)throw new Error("Invalid log level");let r={[H]:!0,error:i,debug:i,info:i,verbose:i,warn:i};for(let[s,o]of e)r[s]=P(o);return r}n(T,"createDefaultLogger");var be=require("stream");var m=class{constructor(e,r,s=T()){this.framework=e;this.factory=r;this.logger=s;this.delayedFactory=Promise.resolve().then(()=>r()).then(o=>{this.cachedApp=o}).catch(o=>{this.logger.error("SERVERLESS_ADAPTER:LAZY_FRAMEWORK: An error occours during the creation of your app."),this.logger.error(o)})}static{n(this,"LazyFramework")}cachedApp;delayedFactory;sendRequest(e,r,s){if(this.cachedApp)return this.framework.sendRequest(this.cachedApp,r,s);this.delayedFactory.then(()=>this.cachedApp?this.framework.sendRequest(this.cachedApp,r,s):s.emit("error",new Error("SERVERLESS_ADAPTER:LAZY_FRAMEWORK: The instance of the app returned by the factory is not valid, see the logs to learn more.")))}};0&&(module.exports={LazyFramework});
6
7
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/frameworks/lazy/index.ts","../../../src/network/request.ts","../../../src/network/response.ts","../../../src/network/utils.ts","../../../src/network/response-stream.ts","../../../src/core/no-op.ts","../../../src/core/logger.ts","../../../src/core/stream.ts","../../../src/frameworks/lazy/lazy.framework.ts"],"sourcesContent":["export * from './lazy.framework';\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport type { SingleValueHeaders } from '../@types';\nimport { NO_OP } from '../core';\n\nconst HTTPS_PORT = 443;\n\n/**\n * The properties to create a {@link ServerlessRequest}\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport interface ServerlessRequestProps {\n /**\n * The HTTP Method of the request\n */\n method: string;\n\n /**\n * The URL requested\n */\n url: string;\n\n /**\n * The headers from the event source\n */\n headers: SingleValueHeaders;\n\n /**\n * The body from the event source\n */\n body?: Buffer | Uint8Array;\n\n /**\n * The IP Address from caller\n */\n remoteAddress?: string;\n}\n\n/**\n * The class that represents an {@link http#IncomingMessage} created by the library to represent an actual request to the framework.\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport class ServerlessRequest extends IncomingMessage {\n constructor({\n method,\n url,\n headers,\n body,\n remoteAddress,\n }: ServerlessRequestProps) {\n super({\n encrypted: true,\n readable: false,\n remoteAddress,\n address: () => ({ port: HTTPS_PORT }) as AddressInfo,\n end: NO_OP,\n destroy: NO_OP,\n } as any);\n\n this.statusCode = 200;\n this.statusMessage = 'OK';\n this.complete = true;\n this.httpVersion = '1.1';\n this.httpVersionMajor = 1;\n this.httpVersionMinor = 1;\n this.method = method;\n this.headers = headers;\n this.body = body;\n this.url = url;\n this.ip = remoteAddress;\n\n this._read = () => {\n this.push(body);\n this.push(null);\n };\n }\n\n ip?: string;\n body?: Buffer | Uint8Array;\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport { NO_OP } from '../core';\nimport { getString } from './utils';\n\nconst headerEnd = '\\r\\n\\r\\n';\nconst endChunked = '0\\r\\n\\r\\n';\n\nconst BODY = Symbol('Response body');\nconst HEADERS = Symbol('Response headers');\n\nfunction addData(stream: ServerlessResponse, data: Uint8Array | string) {\n if (\n Buffer.isBuffer(data) ||\n typeof data === 'string' ||\n data instanceof Uint8Array\n )\n stream[BODY].push(Buffer.from(data));\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n\n/**\n * The properties to create a {@link ServerlessResponse}.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport interface ServerlessResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * Once it's happens, we use the properties from this response to built the response to the cloud.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport class ServerlessResponse extends ServerResponse {\n constructor({ method }: ServerlessResponseProps) {\n super({ method } as any);\n\n this[BODY] = [];\n this[HEADERS] = {};\n\n this.useChunkedEncodingByDefault = false;\n this.chunkedEncoding = false;\n this._header = '';\n\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 1;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (this._header === '' || this._wroteHeader) {\n if (!this.chunkedEncoding) addData(this, data);\n else {\n if (writesToIgnore > 0) writesToIgnore--;\n else if (data !== endChunked) {\n addData(this, data);\n writesToIgnore = 3;\n }\n }\n } else {\n const string = getString(data);\n const index = string.indexOf(headerEnd);\n\n if (index !== -1) {\n const remainder = string.slice(index + headerEnd.length);\n\n if (remainder && !this.chunkedEncoding) addData(this, remainder);\n\n this._wroteHeader = true;\n }\n }\n\n if (typeof cb === 'function') cb();\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n\n _header: string;\n _headers?: Record<any, any>;\n _wroteHeader?: boolean;\n\n [BODY]: any[];\n [HEADERS]: Record<any, any>;\n\n get headers(): Record<any, any> {\n return this[HEADERS];\n }\n\n static from(res: IncomingMessage) {\n const response = new ServerlessResponse({ method: res.method });\n\n response.statusCode = res.statusCode || 0;\n response[HEADERS] = res.headers;\n response[BODY] = (res as any).body ? [Buffer.from((res as any).body)] : [];\n response.end();\n\n return response;\n }\n\n static body(res: ServerlessResponse): Buffer {\n return Buffer.concat(res[BODY]);\n }\n\n static headers(res: ServerlessResponse) {\n const headers = res.getHeaders();\n\n return Object.assign(headers, res[HEADERS]);\n }\n\n override setHeader(\n key: string,\n value: number | string | readonly string[],\n ): any {\n if (this._wroteHeader) this[HEADERS][key] = value;\n else super.setHeader(key, value);\n }\n\n override writeHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): any {\n const headersObjOrArray =\n typeof statusMessage === 'string' ? obj : statusMessage;\n\n const arrayHeaders = Array.isArray(headersObjOrArray)\n ? headersObjOrArray\n : [headersObjOrArray || {}];\n\n for (const headers of arrayHeaders) {\n for (const name in headers) {\n this.setHeader(name, headers[name]!);\n\n if (!this._wroteHeader) {\n // we only need to initiate super.headers once\n // writeHead will add the other headers itself\n break;\n }\n }\n }\n\n return this.callNativeWriteHead(statusCode, statusMessage, obj);\n }\n\n /**\n * I use ignore here because in nodejs 12.x, statusMessage can be string | OutgoingHttpHeaders\n * But in nodejs \\>=14.x, statusMessage can also be OutgoingHttpHeaders[]\n * I take care of these cases above, but here I can't handle it well, so I give up\n * nodejs 12.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v12/http.d.ts#L229\n * nodejs 14.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v14/http.d.ts#L263\n */\n protected callNativeWriteHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): this {\n return super.writeHead(statusCode, statusMessage, obj);\n }\n}\n","/**\n * Get the data from a buffer, string, or Uint8Array\n *\n * @breadcrumb Network\n * @param data - The data that was written inside the stream\n */\nexport function getString(data: Buffer | string | unknown) {\n if (Buffer.isBuffer(data)) return data.toString('utf8');\n else if (typeof data === 'string') return data;\n else if (data instanceof Uint8Array) return new TextDecoder().decode(data);\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n","import { ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { Writable } from 'node:stream';\nimport type { BothValueHeaders } from '../@types';\nimport { type ILogger, NO_OP, parseHeaders } from '../core';\nimport { getString } from './utils';\n\nconst endChunked = '0\\r\\n\\r\\n';\nconst headerEnd = '\\r\\n\\r\\n';\nconst endStatusSeparator = '\\r\\n';\n\n/**\n * The properties to create a {@link ServerlessStreamResponse}.\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport interface ServerlessStreamResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n\n /**\n * The callback to receive the headers when they are written to the stream\n * You need to return a writable stream be able to continue writing the response\n *\n * @param statusCode - The status code of the response\n * @param headers - The headers of the response\n */\n onReceiveHeaders: (statusCode: number, headers: BothValueHeaders) => Writable;\n\n /**\n * Instance of the logger\n */\n log: ILogger;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * This response is specially built to deal with transfer-encoding: chunked\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport class ServerlessStreamResponse extends ServerResponse {\n constructor({\n method,\n onReceiveHeaders,\n log,\n }: ServerlessStreamResponseProps) {\n super({ method } as any);\n\n this.useChunkedEncodingByDefault = true;\n this.chunkedEncoding = true;\n\n let internalWritable: Writable | null = null;\n let isFirstCall = true;\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 0;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n // very unlikely, I don't even know how to reproduce this, but exist on types\n // istanbul ignore if\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n log.debug('SERVERLESS_ADAPTER:RESPONSE_STREAM:DATA', () => ({\n data: Buffer.isBuffer(data) ? data.toString('utf8') : data,\n encoding,\n }));\n\n if (!isFirstCall && internalWritable) {\n if (data === endChunked) {\n internalWritable.end(cb);\n\n return true;\n }\n\n if (writesToIgnore > 0) {\n writesToIgnore--;\n return true;\n }\n\n internalWritable.write(data, cb);\n writesToIgnore = 3;\n } else if (isFirstCall) {\n isFirstCall = false;\n\n const stringData = getString(data);\n const endStatusIndex = stringData.indexOf(endStatusSeparator);\n const status = +stringData.slice(0, endStatusIndex).split(' ')[1];\n const endHeaderIndex = stringData.indexOf(headerEnd);\n\n const headerData = stringData.slice(\n endStatusIndex + 2,\n endHeaderIndex,\n );\n const headers = parseHeaders(headerData);\n log.debug(\n 'SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS',\n () => ({\n headers,\n }),\n );\n\n writesToIgnore = 1;\n internalWritable = onReceiveHeaders(status, headers);\n\n // If we get an endChunked right after header which means the response body is empty, we need to immediately end the writable\n if (stringData.substring(endHeaderIndex + 4) === endChunked)\n internalWritable.end();\n }\n\n return true;\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n}\n","/**\n * No operation function is used when we need to pass a function, but we don't want to specify any behavior.\n *\n * @breadcrumb Core\n * @public\n */\nexport const NO_OP: (...args: any[]) => any = () => void 0;\n","import { NO_OP } from './no-op';\n\n/**\n * The type representing the possible log levels to choose from.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LogLevels =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'none';\n\n/**\n * The options to customize {@link ILogger}\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerOptions = {\n /**\n * Select the log level, {@link LogLevels | see more}.\n *\n * @defaultValue error\n */\n level: LogLevels;\n};\n\n/**\n * The log function used in any level.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerFN = (message: any, ...additional: any[]) => void;\n\n/**\n * The interface representing the logger, you can provide a custom logger by implementing this interface.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type ILogger = Record<Exclude<LogLevels, 'none'>, LoggerFN>;\n\n/**\n * The symbol used to check against an ILogger instace to verify if that ILogger was created by this library\n *\n * @breadcrumb Core / Logger\n * @public\n */\nconst InternalLoggerSymbol = Symbol('InternalLogger');\n\nconst logLevels: Record<\n LogLevels,\n [level: LogLevels, consoleMethod: keyof Console][]\n> = {\n debug: [\n ['debug', 'debug'],\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n verbose: [\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n info: [\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n warn: [\n ['warn', 'warn'],\n ['error', 'error'],\n ],\n error: [['error', 'error']],\n none: [],\n};\n\nconst lazyPrint = (value: () => any | unknown) => {\n if (typeof value === 'function') return value();\n\n return value;\n};\n\nconst print =\n (fn: string) =>\n (message: any, ...additional: (() => any)[]) =>\n console[fn](message, ...additional.map(lazyPrint));\n\n/**\n * The method used to create a simple logger instance to use in this library.\n *\n * @remarks Behind the scenes, this simple logger sends the message to the `console` methods.\n *\n * @example\n * ```typescript\n * const logger = createDefaultLogger();\n *\n * logger.error('An error happens.');\n * // An error happens.\n * ```\n *\n * @param level - Select the level of the log\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function createDefaultLogger(\n { level }: LoggerOptions = { level: 'error' },\n): ILogger {\n const levels = logLevels[level];\n\n if (!levels) throw new Error('Invalid log level');\n\n const logger = {\n [InternalLoggerSymbol]: true,\n error: NO_OP,\n debug: NO_OP,\n info: NO_OP,\n verbose: NO_OP,\n warn: NO_OP,\n } as ILogger;\n\n for (const [level, consoleMethod] of levels)\n logger[level] = print(consoleMethod);\n\n return logger;\n}\n\n/**\n * The method used to chck if logger was created by this library, or it was defined by the user.\n *\n * @param logger - The instance of the logger to check\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function isInternalLogger(logger: ILogger): boolean {\n return !!logger[InternalLoggerSymbol];\n}\n","//#region Imports\n\nimport { Readable, Writable } from 'node:stream';\n\n//#endregion\n\n/**\n * Check if stream already ended\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function isStreamEnded(stream: Readable | Writable): boolean {\n if ('readableEnded' in stream && stream.readableEnded) return true;\n\n if ('writableEnded' in stream && stream.writableEnded) return true;\n\n return false;\n}\n\n/**\n * Wait asynchronous the stream to complete\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function waitForStreamComplete<TStream extends Readable | Writable>(\n stream: TStream,\n): Promise<TStream> {\n if (isStreamEnded(stream)) return Promise.resolve(stream);\n\n return new Promise<TStream>((resolve, reject) => {\n // Reading the {@link https://github.com/nodejs/node/blob/v12.22.9/lib/events.js#L262 | emit source code},\n // it's almost impossible to complete being called twice because the emit function runs synchronously and removes the other listeners,\n // but I'll leave it at that because I didn't write that code, so I couldn't figure out what the author thought when he wrote this.\n let isComplete = false;\n\n function complete(err: any) {\n /* istanbul ignore next */\n if (isComplete) return;\n\n isComplete = true;\n\n stream.removeListener('error', complete);\n stream.removeListener('end', complete);\n stream.removeListener('finish', complete);\n\n if (err) reject(err);\n else resolve(stream);\n }\n\n stream.once('error', complete);\n stream.once('end', complete);\n stream.once('finish', complete);\n });\n}\n","//#region Imports\n\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { FrameworkContract } from '../../contracts';\nimport { type ILogger, createDefaultLogger } from '../../core';\n\n//#endregion\n\n/**\n * The framework that asynchronously instantiates your application and forwards the request to the framework as quickly as possible.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { ServerlessAdapter } from '@h4ad/serverless-adapter';\n * import { ExpressFramework } from '@h4ad/serverless-adapter/lib/frameworks/express';\n * import { LazyFramework } from '@h4ad/serverless-adapter/lib/frameworks/lazy';\n *\n * const expressFramework = new ExpressFramework();\n * const factory = async () => {\n * const app = express();\n *\n * // do some asynchronous stuffs like create the database;\n * await new Promise(resolve => setTimeout(resolve, 100);\n *\n * return app;\n * };\n * const framework = new LazyFramework(expressFramework, factory);\n *\n * export const handler = ServerlessAdapter.new(null)\n * .setFramework(framework)\n * // set other configurations and then build\n * .build();\n * ```\n *\n * @breadcrumb Frameworks / LazyFramework\n * @public\n */\nexport class LazyFramework<TApp> implements FrameworkContract<null> {\n //#region Constructor\n\n /**\n * Default Constructor\n */\n constructor(\n protected readonly framework: FrameworkContract<TApp>,\n protected readonly factory: () => Promise<TApp>,\n protected readonly logger: ILogger = createDefaultLogger(),\n ) {\n this.delayedFactory = Promise.resolve()\n .then(() => factory())\n .then(app => {\n this.cachedApp = app;\n })\n .catch((error: Error) => {\n // deal with the error only when receive some request\n // to be able to return some message to user\n this.logger.error(\n 'SERVERLESS_ADAPTER:LAZY_FRAMEWORK: An error occours during the creation of your app.',\n );\n this.logger.error(error);\n });\n }\n\n //#endregion\n\n //#region Protected Properties\n\n /**\n * The cached version of the app\n */\n protected cachedApp?: TApp;\n\n /**\n * The delayed factory to create an instance of the app\n */\n protected readonly delayedFactory: Promise<void>;\n\n //#endregion\n\n //#region Public Methods\n\n /**\n * {@inheritDoc}\n */\n public sendRequest(\n _app: null,\n request: IncomingMessage,\n response: ServerResponse,\n ): void {\n if (this.cachedApp)\n return this.framework.sendRequest(this.cachedApp, request, response);\n\n this.delayedFactory.then(() => {\n if (!this.cachedApp) {\n return response.emit(\n 'error',\n new Error(\n 'SERVERLESS_ADAPTER:LAZY_FRAMEWORK: The instance of the app returned by the factory is not valid, see the logs to learn more.',\n ),\n );\n }\n\n return this.framework.sendRequest(this.cachedApp, request, response);\n });\n }\n\n //#endregion\n}\n"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GCCA,IAAAI,EAAgC,gBCAhC,IAAAC,EAAgD,gBCKzC,SAASC,EAAUC,EAAiC,CACzD,GAAI,OAAO,SAASA,CAAI,EAAG,OAAOA,EAAK,SAAS,MAAM,EACjD,GAAI,OAAOA,GAAS,SAAU,OAAOA,EACrC,GAAIA,aAAgB,WAAY,OAAO,IAAI,YAAY,EAAE,OAAOA,CAAI,EACpE,MAAM,IAAI,MAAM,wCAAwC,OAAOA,CAAI,EAAE,CAC5E,CALgBC,EAAAF,EAAA,aDAhB,IAAMG,EAAY;AAAA;AAAA,EACZC,EAAa;AAAA;AAAA,EAEbC,EAAO,OAAO,eAAe,EAC7BC,EAAU,OAAO,kBAAkB,EAEzC,SAASC,EAAQC,EAA4BC,EAA2B,CACtE,GACE,OAAO,SAASA,CAAI,GACpB,OAAOA,GAAS,UAChBA,aAAgB,WAEhBD,EAAOH,CAAI,EAAE,KAAK,OAAO,KAAKI,CAAI,CAAC,MAChC,OAAM,IAAI,MAAM,wCAAwC,OAAOA,CAAI,EAAE,CAC5E,CARSC,EAAAH,EAAA,WA8BF,IAAMI,EAAN,MAAMC,UAA2B,gBAAe,CA1CvD,MA0CuD,CAAAF,EAAA,2BACrD,YAAY,CAAE,OAAAG,CAAO,EAA4B,CAC/C,MAAM,CAAE,OAAAA,CAAO,CA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AIH,CACH,CAGF","names":["lazy_exports","__export","LazyFramework","__toCommonJS","import_node_http","import_node_http","getString","data","__name","headerEnd","endChunked","BODY","HEADERS","addData","stream","data","__name","ServerlessResponse","_ServerlessResponse","method","writesToIgnore","socket","NO_OP","encoding","cb","string","getString","index","remainder","res","response","headers","key","value","statusCode","statusMessage","obj","headersObjOrArray","arrayHeaders","name","import_node_http","NO_OP","__name","InternalLoggerSymbol","logLevels","lazyPrint","__name","value","print","fn","message","additional","createDefaultLogger","level","levels","logger","NO_OP","consoleMethod","import_node_stream","LazyFramework","framework","factory","logger","createDefaultLogger","app","error","__name","_app","request","response"]}
1
+ {"version":3,"sources":["../../../src/frameworks/lazy/index.ts","../../../src/network/request.ts","../../../src/network/response.ts","../../../src/network/utils.ts","../../../src/network/response-stream.ts","../../../src/core/no-op.ts","../../../src/core/logger.ts","../../../src/core/stream.ts","../../../src/frameworks/lazy/lazy.framework.ts"],"sourcesContent":["export * from './lazy.framework';\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport type { SingleValueHeaders } from '../@types';\nimport { NO_OP } from '../core';\n\nconst HTTPS_PORT = 443;\n\n/**\n * The properties to create a {@link ServerlessRequest}\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport interface ServerlessRequestProps {\n /**\n * The HTTP Method of the request\n */\n method: string;\n\n /**\n * The URL requested\n */\n url: string;\n\n /**\n * The headers from the event source\n */\n headers: SingleValueHeaders;\n\n /**\n * The body from the event source\n */\n body?: Buffer | Uint8Array;\n\n /**\n * The IP Address from caller\n */\n remoteAddress?: string;\n}\n\n/**\n * The class that represents an {@link http#IncomingMessage} created by the library to represent an actual request to the framework.\n *\n * @breadcrumb Network / ServerlessRequest\n * @public\n */\nexport class ServerlessRequest extends IncomingMessage {\n constructor({\n method,\n url,\n headers,\n body,\n remoteAddress,\n }: ServerlessRequestProps) {\n super({\n encrypted: true,\n readable: false,\n remoteAddress,\n address: () => ({ port: HTTPS_PORT }) as AddressInfo,\n end: NO_OP,\n destroy: NO_OP,\n } as any);\n\n this.statusCode = 200;\n this.statusMessage = 'OK';\n this.complete = true;\n this.httpVersion = '1.1';\n this.httpVersionMajor = 1;\n this.httpVersionMinor = 1;\n this.method = method;\n this.headers = headers;\n this.body = body;\n this.url = url;\n this.ip = remoteAddress;\n\n this._read = () => {\n this.push(body);\n this.push(null);\n };\n }\n\n ip?: string;\n body?: Buffer | Uint8Array;\n}\n","// ATTRIBUTION: https://github.com/dougmoscrop/serverless-http\nimport { IncomingMessage, ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport { NO_OP } from '../core';\nimport { getString } from './utils';\n\nconst headerEnd = '\\r\\n\\r\\n';\nconst endChunked = '0\\r\\n\\r\\n';\n\nconst BODY = Symbol('Response body');\nconst HEADERS = Symbol('Response headers');\n\nfunction addData(stream: ServerlessResponse, data: Uint8Array | string) {\n if (\n Buffer.isBuffer(data) ||\n typeof data === 'string' ||\n data instanceof Uint8Array\n )\n stream[BODY].push(Buffer.from(data));\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n\n/**\n * The properties to create a {@link ServerlessResponse}.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport interface ServerlessResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * Once it's happens, we use the properties from this response to built the response to the cloud.\n *\n * @breadcrumb Network / ServerlessResponse\n * @public\n */\nexport class ServerlessResponse extends ServerResponse {\n constructor({ method }: ServerlessResponseProps) {\n super({ method } as any);\n\n this[BODY] = [];\n this[HEADERS] = {};\n\n this.useChunkedEncodingByDefault = false;\n this.chunkedEncoding = false;\n this._header = '';\n\n // this ignore is used because I need to ignore these write calls:\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L934-L935\n // https://github.com/nodejs/node/blob/main/lib/_http_outgoing.js#L937\n let writesToIgnore = 1;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (this._header === '' || this._wroteHeader) {\n if (!this.chunkedEncoding) addData(this, data);\n else {\n if (writesToIgnore > 0) writesToIgnore--;\n else if (data !== endChunked) {\n addData(this, data);\n writesToIgnore = 3;\n }\n }\n } else {\n const string = getString(data);\n const index = string.indexOf(headerEnd);\n\n if (index !== -1) {\n const remainder = string.slice(index + headerEnd.length);\n\n if (remainder && !this.chunkedEncoding) addData(this, remainder);\n\n this._wroteHeader = true;\n }\n }\n\n if (typeof cb === 'function') cb();\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n\n _header: string;\n _headers?: Record<any, any>;\n _wroteHeader?: boolean;\n\n [BODY]: any[];\n [HEADERS]: Record<any, any>;\n\n get headers(): Record<any, any> {\n return this[HEADERS];\n }\n\n static from(res: IncomingMessage) {\n const response = new ServerlessResponse({ method: res.method });\n\n response.statusCode = res.statusCode || 0;\n response[HEADERS] = res.headers;\n response[BODY] = (res as any).body ? [Buffer.from((res as any).body)] : [];\n response.end();\n\n return response;\n }\n\n static body(res: ServerlessResponse): Buffer {\n return Buffer.concat(res[BODY]);\n }\n\n static headers(res: ServerlessResponse) {\n const headers = res.getHeaders();\n\n return Object.assign(headers, res[HEADERS]);\n }\n\n override setHeader(\n key: string,\n value: number | string | readonly string[],\n ): any {\n if (this._wroteHeader) this[HEADERS][key] = value;\n else super.setHeader(key, value);\n }\n\n override writeHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): any {\n const headersObjOrArray =\n typeof statusMessage === 'string' ? obj : statusMessage;\n\n const arrayHeaders = Array.isArray(headersObjOrArray)\n ? headersObjOrArray\n : [headersObjOrArray || {}];\n\n for (const headers of arrayHeaders) {\n for (const name in headers) {\n this.setHeader(name, headers[name]!);\n\n if (!this._wroteHeader) {\n // we only need to initiate super.headers once\n // writeHead will add the other headers itself\n break;\n }\n }\n }\n\n return this.callNativeWriteHead(statusCode, statusMessage, obj);\n }\n\n /**\n * I use ignore here because in nodejs 12.x, statusMessage can be string | OutgoingHttpHeaders\n * But in nodejs \\>=14.x, statusMessage can also be OutgoingHttpHeaders[]\n * I take care of these cases above, but here I can't handle it well, so I give up\n * nodejs 12.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v12/http.d.ts#L229\n * nodejs 14.x ref: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v14/http.d.ts#L263\n */\n protected callNativeWriteHead(\n statusCode: number,\n statusMessage?: string | any | any[],\n obj?: any | any[],\n ): this {\n return super.writeHead(statusCode, statusMessage, obj);\n }\n}\n","/**\n * Get the data from a buffer, string, or Uint8Array\n *\n * @breadcrumb Network\n * @param data - The data that was written inside the stream\n */\nexport function getString(data: Buffer | string | unknown) {\n if (Buffer.isBuffer(data)) return data.toString('utf8');\n else if (typeof data === 'string') return data;\n else if (data instanceof Uint8Array) return new TextDecoder().decode(data);\n else throw new Error(`response.write() of unexpected type: ${typeof data}`);\n}\n","import { ServerResponse } from 'node:http';\nimport type { Socket } from 'node:net';\nimport type { Writable } from 'node:stream';\nimport type { BothValueHeaders } from '../@types';\nimport { type ILogger, NO_OP, parseHeaders } from '../core';\nimport { getString } from './utils';\n\n// header or data crlf\nconst crlfBuffer = Buffer.from('\\r\\n');\n\nconst endChunked = '0\\r\\n\\r\\n';\nconst headerEnd = '\\r\\n\\r\\n';\nconst endStatusSeparator = '\\r\\n';\n\n/**\n * The properties to create a {@link ServerlessStreamResponse}.\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport interface ServerlessStreamResponseProps {\n /**\n * The HTTP Method from request\n */\n method?: string;\n\n /**\n * The callback to receive the headers when they are written to the stream\n * You need to return a writable stream be able to continue writing the response\n *\n * @param statusCode - The status code of the response\n * @param headers - The headers of the response\n */\n onReceiveHeaders: (statusCode: number, headers: BothValueHeaders) => Writable;\n\n /**\n * Instance of the logger\n */\n log: ILogger;\n}\n\n/**\n * The class that represents a response instance used to send to the framework and wait until the framework finishes processing the request.\n * This response is specially built to deal with transfer-encoding: chunked\n *\n * @breadcrumb Network / ServerlessStreamResponse\n * @public\n */\nexport class ServerlessStreamResponse extends ServerResponse {\n constructor({\n method,\n onReceiveHeaders,\n log,\n }: ServerlessStreamResponseProps) {\n super({ method } as any);\n\n this.useChunkedEncodingByDefault = true;\n this.chunkedEncoding = true;\n\n let internalWritable: Writable | null = null;\n let firstCrlfBufferEncountered = false;\n let chunkEncountered = false;\n\n const socket: Partial<Socket> & { _writableState: any } = {\n _writableState: {},\n writable: true,\n on: NO_OP,\n removeListener: NO_OP,\n destroy: NO_OP,\n cork: NO_OP,\n uncork: NO_OP,\n write: (\n data: Uint8Array | string,\n encoding?: string | null | (() => void),\n cb?: () => void,\n ): any => {\n // very unlikely, I don't even know how to reproduce this, but exist on types\n // istanbul ignore if\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n log.debug('SERVERLESS_ADAPTER:RESPONSE_STREAM:DATA', () => ({\n data: Buffer.isBuffer(data) ? data.toString('utf8') : data,\n encoding,\n }));\n\n if (!internalWritable) {\n const stringData = getString(data);\n const endStatusIndex = stringData.indexOf(endStatusSeparator);\n const status = +stringData.slice(0, endStatusIndex).split(' ')[1];\n const endHeaderIndex = stringData.indexOf(headerEnd);\n\n const headerData = stringData.slice(\n endStatusIndex + 2,\n endHeaderIndex,\n );\n const headers = parseHeaders(headerData);\n log.debug(\n 'SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS',\n () => ({\n headers,\n }),\n );\n\n internalWritable = onReceiveHeaders(status, headers);\n\n // If we get an endChunked right after header which means the response body is empty, we need to immediately end the writable\n if (stringData.substring(endHeaderIndex + 4) === endChunked)\n internalWritable.end();\n\n return true;\n }\n\n // node sends the last chunk crlf as a string:\n // https://github.com/nodejs/node/blob/v22.8.0/lib/_http_outgoing.js#L1131\n if (data === endChunked) {\n internalWritable.end(cb);\n return true;\n }\n\n // check for header or data crlf\n // node sends the header and data crlf as a buffer\n // below code is aligned to following node implementation of the HTTP/1.1 chunked transfer coding:\n // https://github.com/nodejs/node/blob/v22.8.0/lib/_http_outgoing.js#L1012-L1015\n // for reference: https://datatracker.ietf.org/doc/html/rfc9112#section-7\n if (Buffer.isBuffer(data) && crlfBuffer.equals(data)) {\n const isHeaderCrlf = !firstCrlfBufferEncountered;\n if (isHeaderCrlf) {\n firstCrlfBufferEncountered = true;\n return true;\n }\n\n const isDataCrlf = firstCrlfBufferEncountered && chunkEncountered;\n if (isDataCrlf) {\n // done with chunk\n firstCrlfBufferEncountered = false;\n chunkEncountered = false;\n return true;\n }\n\n // the crlf *is* the chunk\n }\n\n const isContentLength = !firstCrlfBufferEncountered;\n if (isContentLength) {\n // discard content length\n return true;\n }\n\n // write chunk\n chunkEncountered = true;\n internalWritable.write(data, cb);\n return true;\n },\n };\n\n this.assignSocket(socket as unknown as Socket);\n }\n}\n","/**\n * No operation function is used when we need to pass a function, but we don't want to specify any behavior.\n *\n * @breadcrumb Core\n * @public\n */\nexport const NO_OP: (...args: any[]) => any = () => void 0;\n","import { NO_OP } from './no-op';\n\n/**\n * The type representing the possible log levels to choose from.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LogLevels =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'none';\n\n/**\n * The options to customize {@link ILogger}\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerOptions = {\n /**\n * Select the log level, {@link LogLevels | see more}.\n *\n * @defaultValue error\n */\n level: LogLevels;\n};\n\n/**\n * The log function used in any level.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type LoggerFN = (message: any, ...additional: any[]) => void;\n\n/**\n * The interface representing the logger, you can provide a custom logger by implementing this interface.\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport type ILogger = Record<Exclude<LogLevels, 'none'>, LoggerFN>;\n\n/**\n * The symbol used to check against an ILogger instace to verify if that ILogger was created by this library\n *\n * @breadcrumb Core / Logger\n * @public\n */\nconst InternalLoggerSymbol = Symbol('InternalLogger');\n\nconst logLevels: Record<\n LogLevels,\n [level: LogLevels, consoleMethod: keyof Console][]\n> = {\n debug: [\n ['debug', 'debug'],\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n verbose: [\n ['verbose', 'debug'],\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n info: [\n ['info', 'info'],\n ['error', 'error'],\n ['warn', 'warn'],\n ],\n warn: [\n ['warn', 'warn'],\n ['error', 'error'],\n ],\n error: [['error', 'error']],\n none: [],\n};\n\nconst lazyPrint = (value: () => any | unknown) => {\n if (typeof value === 'function') return value();\n\n return value;\n};\n\nconst print =\n (fn: string) =>\n (message: any, ...additional: (() => any)[]) =>\n console[fn](message, ...additional.map(lazyPrint));\n\n/**\n * The method used to create a simple logger instance to use in this library.\n *\n * @remarks Behind the scenes, this simple logger sends the message to the `console` methods.\n *\n * @example\n * ```typescript\n * const logger = createDefaultLogger();\n *\n * logger.error('An error happens.');\n * // An error happens.\n * ```\n *\n * @param level - Select the level of the log\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function createDefaultLogger(\n { level }: LoggerOptions = { level: 'error' },\n): ILogger {\n const levels = logLevels[level];\n\n if (!levels) throw new Error('Invalid log level');\n\n const logger = {\n [InternalLoggerSymbol]: true,\n error: NO_OP,\n debug: NO_OP,\n info: NO_OP,\n verbose: NO_OP,\n warn: NO_OP,\n } as ILogger;\n\n for (const [level, consoleMethod] of levels)\n logger[level] = print(consoleMethod);\n\n return logger;\n}\n\n/**\n * The method used to chck if logger was created by this library, or it was defined by the user.\n *\n * @param logger - The instance of the logger to check\n *\n * @breadcrumb Core / Logger\n * @public\n */\nexport function isInternalLogger(logger: ILogger): boolean {\n return !!logger[InternalLoggerSymbol];\n}\n","//#region Imports\n\nimport { Readable, Writable } from 'node:stream';\n\n//#endregion\n\n/**\n * Check if stream already ended\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function isStreamEnded(stream: Readable | Writable): boolean {\n if ('readableEnded' in stream && stream.readableEnded) return true;\n\n if ('writableEnded' in stream && stream.writableEnded) return true;\n\n return false;\n}\n\n/**\n * Wait asynchronous the stream to complete\n *\n * @param stream - The stream\n *\n * @breadcrumb Core / Stream\n * @public\n */\nexport function waitForStreamComplete<TStream extends Readable | Writable>(\n stream: TStream,\n): Promise<TStream> {\n if (isStreamEnded(stream)) return Promise.resolve(stream);\n\n return new Promise<TStream>((resolve, reject) => {\n // Reading the {@link https://github.com/nodejs/node/blob/v12.22.9/lib/events.js#L262 | emit source code},\n // it's almost impossible to complete being called twice because the emit function runs synchronously and removes the other listeners,\n // but I'll leave it at that because I didn't write that code, so I couldn't figure out what the author thought when he wrote this.\n let isComplete = false;\n\n function complete(err: any) {\n /* istanbul ignore next */\n if (isComplete) return;\n\n isComplete = true;\n\n stream.removeListener('error', complete);\n stream.removeListener('end', complete);\n stream.removeListener('finish', complete);\n\n if (err) reject(err);\n else resolve(stream);\n }\n\n stream.once('error', complete);\n stream.once('end', complete);\n stream.once('finish', complete);\n });\n}\n","//#region Imports\n\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { FrameworkContract } from '../../contracts';\nimport { type ILogger, createDefaultLogger } from '../../core';\n\n//#endregion\n\n/**\n * The framework that asynchronously instantiates your application and forwards the request to the framework as quickly as possible.\n *\n * @example\n * ```typescript\n * import express from 'express';\n * import { ServerlessAdapter } from '@h4ad/serverless-adapter';\n * import { ExpressFramework } from '@h4ad/serverless-adapter/lib/frameworks/express';\n * import { LazyFramework } from '@h4ad/serverless-adapter/lib/frameworks/lazy';\n *\n * const expressFramework = new ExpressFramework();\n * const factory = async () => {\n * const app = express();\n *\n * // do some asynchronous stuffs like create the database;\n * await new Promise(resolve => setTimeout(resolve, 100);\n *\n * return app;\n * };\n * const framework = new LazyFramework(expressFramework, factory);\n *\n * export const handler = ServerlessAdapter.new(null)\n * .setFramework(framework)\n * // set other configurations and then build\n * .build();\n * ```\n *\n * @breadcrumb Frameworks / LazyFramework\n * @public\n */\nexport class LazyFramework<TApp> implements FrameworkContract<null> {\n //#region Constructor\n\n /**\n * Default Constructor\n */\n constructor(\n protected readonly framework: FrameworkContract<TApp>,\n protected readonly factory: () => Promise<TApp>,\n protected readonly logger: ILogger = createDefaultLogger(),\n ) {\n this.delayedFactory = Promise.resolve()\n .then(() => factory())\n .then(app => {\n this.cachedApp = app;\n })\n .catch((error: Error) => {\n // deal with the error only when receive some request\n // to be able to return some message to user\n this.logger.error(\n 'SERVERLESS_ADAPTER:LAZY_FRAMEWORK: An error occours during the creation of your app.',\n );\n this.logger.error(error);\n });\n }\n\n //#endregion\n\n //#region Protected Properties\n\n /**\n * The cached version of the app\n */\n protected cachedApp?: TApp;\n\n /**\n * The delayed factory to create an instance of the app\n */\n protected readonly delayedFactory: Promise<void>;\n\n //#endregion\n\n //#region Public Methods\n\n /**\n * {@inheritDoc}\n */\n public sendRequest(\n _app: null,\n request: IncomingMessage,\n response: ServerResponse,\n ): void {\n if (this.cachedApp)\n return this.framework.sendRequest(this.cachedApp, request, response);\n\n this.delayedFactory.then(() => {\n if (!this.cachedApp) {\n return response.emit(\n 'error',\n new Error(\n 'SERVERLESS_ADAPTER:LAZY_FRAMEWORK: The instance of the app returned by the factory is not valid, see the logs to learn more.',\n ),\n );\n }\n\n return this.framework.sendRequest(this.cachedApp, request, response);\n });\n }\n\n //#endregion\n}\n"],"mappings":"4dAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mBAAAE,IAAA,eAAAC,EAAAH,GCCA,IAAAI,EAAgC,gBCAhC,IAA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,EAAG,GACxB,MAAOa,EACP,MAAOA,EACP,KAAMA,EACN,QAASA,EACT,KAAMA,CACR,EAEA,OAAW,CAACH,EAAOI,CAAa,IAAKH,EACnCC,EAAOF,CAAK,EAAIL,EAAMS,CAAa,EAErC,OAAOF,CACT,CApBgBT,EAAAM,EAAA,uBChHhB,IAAAM,GAAmC,kBCoC5B,IAAMC,EAAN,KAA6D,CAMlE,YACqBC,EACAC,EACAC,EAAkBC,EAAoB,EACzD,CAHmB,eAAAH,EACA,aAAAC,EACA,YAAAC,EAEnB,KAAK,eAAiB,QAAQ,QAAQ,EACnC,KAAK,IAAMD,EAAQ,CAAC,EACpB,KAAKG,GAAO,CACX,KAAK,UAAYA,CACnB,CAAC,EACA,MAAOC,GAAiB,CAGvB,KAAK,OAAO,MACV,sFACF,EACA,KAAK,OAAO,MAAMA,CAAK,CACzB,CAAC,CACL,CA9DF,MAsCoE,CAAAC,EAAA,sBAiCxD,UAKS,eASZ,YACLC,EACAC,EACAC,EACM,CACN,GAAI,KAAK,UACP,OAAO,KAAK,UAAU,YAAY,KAAK,UAAWD,EAASC,CAAQ,EAErE,KAAK,eAAe,KAAK,IAClB,KAAK,UASH,KAAK,UAAU,YAAY,KAAK,UAAWD,EAASC,CAAQ,EAR1DA,EAAS,KACd,QACA,IAAI,MACF,8HACF,CACF,CAIH,CACH,CAGF","names":["lazy_exports","__export","LazyFramework","__toCommonJS","import_node_http","import_node_http","getString","data","__name","headerEnd","endChunked","BODY","HEADERS","addData","stream","data","__name","ServerlessResponse","_ServerlessResponse","method","writesToIgnore","socket","NO_OP","encoding","cb","string","getString","index","remainder","res","response","headers","key","value","statusCode","statusMessage","obj","headersObjOrArray","arrayHeaders","name","import_node_http","crlfBuffer","NO_OP","__name","InternalLoggerSymbol","logLevels","lazyPrint","__name","value","print","fn","message","additional","createDefaultLogger","level","levels","logger","NO_OP","consoleMethod","import_node_stream","LazyFramework","framework","factory","logger","createDefaultLogger","app","error","__name","_app","request","response"]}
@@ -1,2 +1,2 @@
1
- import{q as p}from"../../chunk-MQYXRLYI.mjs";import{a as o}from"../../chunk-OYOJMOFP.mjs";var c=class{constructor(a,e,r=p()){this.framework=a;this.factory=e;this.logger=r;this.delayedFactory=Promise.resolve().then(()=>e()).then(t=>{this.cachedApp=t}).catch(t=>{this.logger.error("SERVERLESS_ADAPTER:LAZY_FRAMEWORK: An error occours during the creation of your app."),this.logger.error(t)})}static{o(this,"LazyFramework")}cachedApp;delayedFactory;sendRequest(a,e,r){if(this.cachedApp)return this.framework.sendRequest(this.cachedApp,e,r);this.delayedFactory.then(()=>this.cachedApp?this.framework.sendRequest(this.cachedApp,e,r):r.emit("error",new Error("SERVERLESS_ADAPTER:LAZY_FRAMEWORK: The instance of the app returned by the factory is not valid, see the logs to learn more.")))}};export{c as LazyFramework};
1
+ import{r as p}from"../../chunk-L4VRXTKP.mjs";import{a as o}from"../../chunk-OYOJMOFP.mjs";var c=class{constructor(a,e,r=p()){this.framework=a;this.factory=e;this.logger=r;this.delayedFactory=Promise.resolve().then(()=>e()).then(t=>{this.cachedApp=t}).catch(t=>{this.logger.error("SERVERLESS_ADAPTER:LAZY_FRAMEWORK: An error occours during the creation of your app."),this.logger.error(t)})}static{o(this,"LazyFramework")}cachedApp;delayedFactory;sendRequest(a,e,r){if(this.cachedApp)return this.framework.sendRequest(this.cachedApp,e,r);this.delayedFactory.then(()=>this.cachedApp?this.framework.sendRequest(this.cachedApp,e,r):r.emit("error",new Error("SERVERLESS_ADAPTER:LAZY_FRAMEWORK: The instance of the app returned by the factory is not valid, see the logs to learn more.")))}};export{c as LazyFramework};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1,6 +1,7 @@
1
- "use strict";var l=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var w=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var s=(r,e)=>l(r,"name",{value:e,configurable:!0});var H=(r,e)=>{for(var t in e)l(r,t,{get:e[t],enumerable:!0})},k=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of w(e))!E.call(r,n)&&n!==t&&l(r,n,{get:()=>e[n],enumerable:!(o=b(e,n))||o.enumerable});return r};var B=r=>k(l({},"__esModule",{value:!0}),r);var P={};H(P,{BufferToJSObjectTransformer:()=>h,TrpcFramework:()=>x});module.exports=B(P);var A=require("@trpc/server/adapters/node-http");var L=require("http");var S=require("http");function c(r){if(Buffer.isBuffer(r))return r.toString("utf8");if(typeof r=="string")return r;if(r instanceof Uint8Array)return new TextDecoder().decode(r);throw new Error(`response.write() of unexpected type: ${typeof r}`)}s(c,"getString");var v=`\r
1
+ "use strict";var c=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var b=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var s=(r,e)=>c(r,"name",{value:e,configurable:!0});var H=(r,e)=>{for(var t in e)c(r,t,{get:e[t],enumerable:!0})},k=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of b(e))!E.call(r,n)&&n!==t&&c(r,n,{get:()=>e[n],enumerable:!(o=w(e,n))||o.enumerable});return r};var B=r=>k(c({},"__esModule",{value:!0}),r);var P={};H(P,{BufferToJSObjectTransformer:()=>h,TrpcFramework:()=>x});module.exports=B(P);var A=require("@trpc/server/adapters/node-http");var L=require("http");var S=require("http");function l(r){if(Buffer.isBuffer(r))return r.toString("utf8");if(typeof r=="string")return r;if(r instanceof Uint8Array)return new TextDecoder().decode(r);throw new Error(`response.write() of unexpected type: ${typeof r}`)}s(l,"getString");var v=`\r
2
2
  \r
3
3
  `,O=`0\r
4
4
  \r
5
- `,f=Symbol("Response body"),p=Symbol("Response headers");function g(r,e){if(Buffer.isBuffer(e)||typeof e=="string"||e instanceof Uint8Array)r[f].push(Buffer.from(e));else throw new Error(`response.write() of unexpected type: ${typeof e}`)}s(g,"addData");var m=class r extends S.ServerResponse{static{s(this,"ServerlessResponse")}constructor({method:e}){super({method:e}),this[f]=[],this[p]={},this.useChunkedEncodingByDefault=!1,this.chunkedEncoding=!1,this._header="";let t=1,o={_writableState:{},writable:!0,on:d,removeListener:d,destroy:d,cork:d,uncork:d,write:(n,i,a)=>{if(typeof i=="function"&&(a=i,i=null),this._header===""||this._wroteHeader)this.chunkedEncoding?t>0?t--:n!==O&&(g(this,n),t=3):g(this,n);else{let u=c(n),T=u.indexOf(v);if(T!==-1){let C=u.slice(T+v.length);C&&!this.chunkedEncoding&&g(this,C),this._wroteHeader=!0}}typeof a=="function"&&a()}};this.assignSocket(o)}_header;_headers;_wroteHeader;[f];[p];get headers(){return this[p]}static from(e){let t=new r({method:e.method});return t.statusCode=e.statusCode||0,t[p]=e.headers,t[f]=e.body?[Buffer.from(e.body)]:[],t.end(),t}static body(e){return Buffer.concat(e[f])}static headers(e){let t=e.getHeaders();return Object.assign(t,e[p])}setHeader(e,t){this._wroteHeader?this[p][e]=t:super.setHeader(e,t)}writeHead(e,t,o){let n=typeof t=="string"?o:t,i=Array.isArray(n)?n:[n||{}];for(let a of i)for(let u in a)if(this.setHeader(u,a[u]),!this._wroteHeader)break;return this.callNativeWriteHead(e,t,o)}callNativeWriteHead(e,t,o){return super.writeHead(e,t,o)}};var I=require("http");function y(r,e=",",t=!1){return Object.keys(r).reduce((o,n)=>{let i=t?n.toLowerCase():n,a=r[n];return Array.isArray(a)?o[i]=a.join(e):o[i]=(a??"")+"",o},{})}s(y,"getFlattenedHeadersMap");var d=s(()=>{},"NO_OP");var xe=Symbol("InternalLogger");function R(r,e){return r===void 0?e:r}s(R,"getDefaultIfUndefined");var be=require("stream");var h=class{static{s(this,"BufferToJSObjectTransformer")}deserialize(e){return e instanceof Buffer?JSON.parse(e.toString("utf-8")):e}serialize(e){return e}},x=class{constructor(e){this.options=e}static{s(this,"TrpcFramework")}sendRequest(e,t,o){let n=this.getSafeUrlForTrpc(t);(0,A.nodeHTTPRequestHandler)({req:t,res:o,path:n,router:e,...this.options,createContext:i=>this.mergeDefaultContextWithOptionsContext(i)})}getSafeUrlForTrpc(e){let t=e.url;return t.startsWith("/")&&(t=t.slice(1)),t.includes("?")&&(t=t.split("?")[0]),t}mergeDefaultContextWithOptionsContext(e){let o=R(this.options?.createContext,()=>{})(e);return o&&o.then?o.then(n=>this.wrapResolvedContextWithDefaultContext(n,e)):this.wrapResolvedContextWithDefaultContext(o,e)}wrapResolvedContextWithDefaultContext(e,t){let o=t.req,n=t.res;return{...e,request:o,response:n,getUrl:()=>o.url,getMethod:()=>o.method,getHeaders:()=>y(o.headers,",",!0),setHeader:(i,a)=>{n.setHeader(i,a)},removeHeader:i=>{n.removeHeader(i)},getHeader:i=>y(o.headers,",",!0)[i.toLowerCase()],setStatus:i=>{n.statusCode=i,n.statusMessage=void 0},getIp:()=>o.connection.remoteAddress}}};0&&(module.exports={BufferToJSObjectTransformer,TrpcFramework});
5
+ `,f=Symbol("Response body"),p=Symbol("Response headers");function g(r,e){if(Buffer.isBuffer(e)||typeof e=="string"||e instanceof Uint8Array)r[f].push(Buffer.from(e));else throw new Error(`response.write() of unexpected type: ${typeof e}`)}s(g,"addData");var m=class r extends S.ServerResponse{static{s(this,"ServerlessResponse")}constructor({method:e}){super({method:e}),this[f]=[],this[p]={},this.useChunkedEncodingByDefault=!1,this.chunkedEncoding=!1,this._header="";let t=1,o={_writableState:{},writable:!0,on:d,removeListener:d,destroy:d,cork:d,uncork:d,write:(n,i,a)=>{if(typeof i=="function"&&(a=i,i=null),this._header===""||this._wroteHeader)this.chunkedEncoding?t>0?t--:n!==O&&(g(this,n),t=3):g(this,n);else{let u=l(n),T=u.indexOf(v);if(T!==-1){let C=u.slice(T+v.length);C&&!this.chunkedEncoding&&g(this,C),this._wroteHeader=!0}}typeof a=="function"&&a()}};this.assignSocket(o)}_header;_headers;_wroteHeader;[f];[p];get headers(){return this[p]}static from(e){let t=new r({method:e.method});return t.statusCode=e.statusCode||0,t[p]=e.headers,t[f]=e.body?[Buffer.from(e.body)]:[],t.end(),t}static body(e){return Buffer.concat(e[f])}static headers(e){let t=e.getHeaders();return Object.assign(t,e[p])}setHeader(e,t){this._wroteHeader?this[p][e]=t:super.setHeader(e,t)}writeHead(e,t,o){let n=typeof t=="string"?o:t,i=Array.isArray(n)?n:[n||{}];for(let a of i)for(let u in a)if(this.setHeader(u,a[u]),!this._wroteHeader)break;return this.callNativeWriteHead(e,t,o)}callNativeWriteHead(e,t,o){return super.writeHead(e,t,o)}};var I=require("http");var Y=Buffer.from(`\r
6
+ `);function y(r,e=",",t=!1){return Object.keys(r).reduce((o,n)=>{let i=t?n.toLowerCase():n,a=r[n];return Array.isArray(a)?o[i]=a.join(e):o[i]=(a??"")+"",o},{})}s(y,"getFlattenedHeadersMap");var d=s(()=>{},"NO_OP");var Te=Symbol("InternalLogger");function R(r,e){return r===void 0?e:r}s(R,"getDefaultIfUndefined");var be=require("stream");var h=class{static{s(this,"BufferToJSObjectTransformer")}deserialize(e){return e instanceof Buffer?JSON.parse(e.toString("utf-8")):e}serialize(e){return e}},x=class{constructor(e){this.options=e}static{s(this,"TrpcFramework")}sendRequest(e,t,o){let n=this.getSafeUrlForTrpc(t);(0,A.nodeHTTPRequestHandler)({req:t,res:o,path:n,router:e,...this.options,createContext:i=>this.mergeDefaultContextWithOptionsContext(i)})}getSafeUrlForTrpc(e){let t=e.url;return t.startsWith("/")&&(t=t.slice(1)),t.includes("?")&&(t=t.split("?")[0]),t}mergeDefaultContextWithOptionsContext(e){let o=R(this.options?.createContext,()=>{})(e);return o&&o.then?o.then(n=>this.wrapResolvedContextWithDefaultContext(n,e)):this.wrapResolvedContextWithDefaultContext(o,e)}wrapResolvedContextWithDefaultContext(e,t){let o=t.req,n=t.res;return{...e,request:o,response:n,getUrl:()=>o.url,getMethod:()=>o.method,getHeaders:()=>y(o.headers,",",!0),setHeader:(i,a)=>{n.setHeader(i,a)},removeHeader:i=>{n.removeHeader(i)},getHeader:i=>y(o.headers,",",!0)[i.toLowerCase()],setStatus:i=>{n.statusCode=i,n.statusMessage=void 0},getIp:()=>o.connection.remoteAddress}}};0&&(module.exports={BufferToJSObjectTransformer,TrpcFramework});
6
7
  //# sourceMappingURL=index.cjs.map