@h4ad/serverless-adapter 4.0.0 → 4.1.0

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 (199) hide show
  1. package/lib/adapter.contract-EQE3rlgO.d.ts +278 -0
  2. package/lib/adapter.contract-y5xSjOjo.d.cts +278 -0
  3. package/lib/adapters/apollo-server/index.cjs +6 -0
  4. package/lib/adapters/apollo-server/index.cjs.map +1 -0
  5. package/lib/adapters/apollo-server/index.d.cts +61 -0
  6. package/lib/adapters/apollo-server/index.d.ts +61 -0
  7. package/lib/adapters/apollo-server/index.mjs +2 -0
  8. package/lib/adapters/apollo-server/index.mjs.map +1 -0
  9. package/lib/adapters/aws/index.cjs +6 -0
  10. package/lib/adapters/aws/index.cjs.map +1 -0
  11. package/lib/adapters/aws/index.d.cts +928 -0
  12. package/lib/adapters/aws/index.d.ts +928 -0
  13. package/lib/adapters/aws/index.mjs +2 -0
  14. package/lib/adapters/aws/index.mjs.map +1 -0
  15. package/lib/adapters/azure/index.cjs +6 -0
  16. package/lib/adapters/azure/index.cjs.map +1 -0
  17. package/lib/adapters/azure/index.d.cts +86 -0
  18. package/lib/adapters/azure/index.d.ts +86 -0
  19. package/lib/adapters/azure/index.mjs +2 -0
  20. package/lib/adapters/azure/index.mjs.map +1 -0
  21. package/lib/adapters/digital-ocean/index.cjs +6 -0
  22. package/lib/adapters/digital-ocean/index.cjs.map +1 -0
  23. package/lib/adapters/digital-ocean/index.d.cts +126 -0
  24. package/lib/adapters/digital-ocean/index.d.ts +126 -0
  25. package/lib/adapters/digital-ocean/index.mjs +2 -0
  26. package/lib/adapters/digital-ocean/index.mjs.map +1 -0
  27. package/lib/adapters/dummy/index.cjs +6 -0
  28. package/lib/adapters/dummy/index.cjs.map +1 -0
  29. package/lib/adapters/dummy/index.d.cts +37 -0
  30. package/lib/adapters/dummy/index.d.ts +37 -0
  31. package/lib/adapters/dummy/index.mjs +2 -0
  32. package/lib/adapters/dummy/index.mjs.map +1 -0
  33. package/lib/adapters/huawei/index.cjs +6 -0
  34. package/lib/adapters/huawei/index.cjs.map +1 -0
  35. package/lib/adapters/huawei/index.d.cts +365 -0
  36. package/lib/adapters/huawei/index.d.ts +365 -0
  37. package/lib/adapters/huawei/index.mjs +2 -0
  38. package/lib/adapters/huawei/index.mjs.map +1 -0
  39. package/lib/base-handler-fYEk59Xq.d.ts +35 -0
  40. package/lib/base-handler-peEBoKtZ.d.cts +35 -0
  41. package/lib/chunk-22SSVZU5.mjs +1 -0
  42. package/lib/chunk-22SSVZU5.mjs.map +1 -0
  43. package/lib/chunk-57ZKWTH4.mjs +2 -0
  44. package/lib/chunk-57ZKWTH4.mjs.map +1 -0
  45. package/lib/chunk-OYOJMOFP.mjs +2 -0
  46. package/lib/chunk-OYOJMOFP.mjs.map +1 -0
  47. package/lib/chunk-PQDB5AVF.mjs +12 -0
  48. package/lib/chunk-PQDB5AVF.mjs.map +1 -0
  49. package/lib/chunk-VPGUOREQ.mjs +2 -0
  50. package/lib/chunk-VPGUOREQ.mjs.map +1 -0
  51. package/lib/constants-0cgQlFSV.d.cts +32 -0
  52. package/lib/constants-0cgQlFSV.d.ts +32 -0
  53. package/lib/framework.contract-YnJ-fl1w.d.cts +20 -0
  54. package/lib/framework.contract-YnJ-fl1w.d.ts +20 -0
  55. package/lib/frameworks/apollo-server/index.cjs +6 -0
  56. package/lib/frameworks/apollo-server/index.cjs.map +1 -0
  57. package/lib/frameworks/apollo-server/index.d.cts +72 -0
  58. package/lib/frameworks/apollo-server/index.d.ts +72 -0
  59. package/lib/frameworks/apollo-server/index.mjs +2 -0
  60. package/lib/frameworks/apollo-server/index.mjs.map +1 -0
  61. package/lib/frameworks/body-parser/index.cjs +6 -0
  62. package/lib/frameworks/body-parser/index.cjs.map +1 -0
  63. package/lib/frameworks/body-parser/index.d.cts +159 -0
  64. package/lib/frameworks/body-parser/index.d.ts +159 -0
  65. package/lib/frameworks/body-parser/index.mjs +2 -0
  66. package/lib/frameworks/body-parser/index.mjs.map +1 -0
  67. package/lib/frameworks/cors/index.cjs +7 -0
  68. package/lib/frameworks/cors/index.cjs.map +1 -0
  69. package/lib/frameworks/cors/index.d.cts +79 -0
  70. package/lib/frameworks/cors/index.d.ts +79 -0
  71. package/lib/frameworks/cors/index.mjs +3 -0
  72. package/lib/frameworks/cors/index.mjs.map +1 -0
  73. package/lib/frameworks/deepkit/index.cjs +6 -0
  74. package/lib/frameworks/deepkit/index.cjs.map +1 -0
  75. package/lib/frameworks/deepkit/index.d.cts +21 -0
  76. package/lib/frameworks/deepkit/index.d.ts +21 -0
  77. package/lib/frameworks/deepkit/index.mjs +2 -0
  78. package/lib/frameworks/deepkit/index.mjs.map +1 -0
  79. package/lib/frameworks/express/index.cjs +2 -0
  80. package/lib/frameworks/express/index.cjs.map +1 -0
  81. package/lib/frameworks/express/index.d.cts +18 -0
  82. package/lib/frameworks/express/index.d.ts +18 -0
  83. package/lib/frameworks/express/index.mjs +2 -0
  84. package/lib/frameworks/express/index.mjs.map +1 -0
  85. package/lib/frameworks/fastify/index.cjs +2 -0
  86. package/lib/frameworks/fastify/index.cjs.map +1 -0
  87. package/lib/frameworks/fastify/index.d.cts +18 -0
  88. package/lib/frameworks/fastify/index.d.ts +18 -0
  89. package/lib/frameworks/fastify/index.mjs +2 -0
  90. package/lib/frameworks/fastify/index.mjs.map +1 -0
  91. package/lib/frameworks/hapi/index.cjs +2 -0
  92. package/lib/frameworks/hapi/index.cjs.map +1 -0
  93. package/lib/frameworks/hapi/index.d.cts +18 -0
  94. package/lib/frameworks/hapi/index.d.ts +18 -0
  95. package/lib/frameworks/hapi/index.mjs +2 -0
  96. package/lib/frameworks/hapi/index.mjs.map +1 -0
  97. package/lib/frameworks/koa/index.cjs +2 -0
  98. package/lib/frameworks/koa/index.cjs.map +1 -0
  99. package/lib/frameworks/koa/index.d.cts +18 -0
  100. package/lib/frameworks/koa/index.d.ts +18 -0
  101. package/lib/frameworks/koa/index.mjs +2 -0
  102. package/lib/frameworks/koa/index.mjs.map +1 -0
  103. package/lib/frameworks/lazy/index.cjs +6 -0
  104. package/lib/frameworks/lazy/index.cjs.map +1 -0
  105. package/lib/frameworks/lazy/index.d.cts +57 -0
  106. package/lib/frameworks/lazy/index.d.ts +57 -0
  107. package/lib/frameworks/lazy/index.mjs +2 -0
  108. package/lib/frameworks/lazy/index.mjs.map +1 -0
  109. package/lib/frameworks/trpc/index.cjs +6 -0
  110. package/lib/frameworks/trpc/index.cjs.map +1 -0
  111. package/lib/frameworks/trpc/index.d.cts +154 -0
  112. package/lib/frameworks/trpc/index.d.ts +154 -0
  113. package/lib/frameworks/trpc/index.mjs +2 -0
  114. package/lib/frameworks/trpc/index.mjs.map +1 -0
  115. package/lib/handler.contract-8Cb7qLSi.d.ts +66 -0
  116. package/lib/handler.contract-TQk8iM8f.d.cts +66 -0
  117. package/lib/handlers/aws/index.cjs +12 -0
  118. package/lib/handlers/aws/index.cjs.map +1 -0
  119. package/lib/handlers/aws/index.d.cts +96 -0
  120. package/lib/handlers/aws/index.d.ts +96 -0
  121. package/lib/handlers/aws/index.mjs +2 -0
  122. package/lib/handlers/aws/index.mjs.map +1 -0
  123. package/lib/handlers/azure/index.cjs +6 -0
  124. package/lib/handlers/azure/index.cjs.map +1 -0
  125. package/lib/handlers/azure/index.d.cts +53 -0
  126. package/lib/handlers/azure/index.d.ts +53 -0
  127. package/lib/handlers/azure/index.mjs +2 -0
  128. package/lib/handlers/azure/index.mjs.map +1 -0
  129. package/lib/handlers/default/index.cjs +6 -0
  130. package/lib/handlers/default/index.cjs.map +1 -0
  131. package/lib/handlers/default/index.d.cts +95 -0
  132. package/lib/handlers/default/index.d.ts +95 -0
  133. package/lib/handlers/default/index.mjs +2 -0
  134. package/lib/handlers/default/index.mjs.map +1 -0
  135. package/lib/handlers/digital-ocean/index.cjs +6 -0
  136. package/lib/handlers/digital-ocean/index.cjs.map +1 -0
  137. package/lib/handlers/digital-ocean/index.d.cts +25 -0
  138. package/lib/handlers/digital-ocean/index.d.ts +25 -0
  139. package/lib/handlers/digital-ocean/index.mjs +2 -0
  140. package/lib/handlers/digital-ocean/index.mjs.map +1 -0
  141. package/lib/handlers/firebase/index.cjs +6 -0
  142. package/lib/handlers/firebase/index.cjs.map +1 -0
  143. package/lib/handlers/firebase/index.d.cts +59 -0
  144. package/lib/handlers/firebase/index.d.ts +59 -0
  145. package/lib/handlers/firebase/index.mjs +2 -0
  146. package/lib/handlers/firebase/index.mjs.map +1 -0
  147. package/lib/handlers/gcp/index.cjs +6 -0
  148. package/lib/handlers/gcp/index.cjs.map +1 -0
  149. package/lib/handlers/gcp/index.d.cts +33 -0
  150. package/lib/handlers/gcp/index.d.ts +33 -0
  151. package/lib/handlers/gcp/index.mjs +2 -0
  152. package/lib/handlers/gcp/index.mjs.map +1 -0
  153. package/lib/handlers/huawei/index.cjs +6 -0
  154. package/lib/handlers/huawei/index.cjs.map +1 -0
  155. package/lib/handlers/huawei/index.d.cts +62 -0
  156. package/lib/handlers/huawei/index.d.ts +62 -0
  157. package/lib/handlers/huawei/index.mjs +2 -0
  158. package/lib/handlers/huawei/index.mjs.map +1 -0
  159. package/lib/headers-K2qbcurv.d.cts +38 -0
  160. package/lib/headers-K2qbcurv.d.ts +38 -0
  161. package/lib/index.cjs +12 -0
  162. package/lib/index.cjs.map +1 -0
  163. package/lib/index.d.cts +439 -0
  164. package/lib/index.d.ts +439 -0
  165. package/lib/index.mjs +2 -0
  166. package/lib/index.mjs.map +1 -0
  167. package/lib/logger-9me5n48P.d.cts +65 -0
  168. package/lib/logger-9me5n48P.d.ts +65 -0
  169. package/lib/path-yBwCb8C1.d.cts +64 -0
  170. package/lib/path-yBwCb8C1.d.ts +64 -0
  171. package/lib/raw-request-B2vPjAfE.d.cts +32 -0
  172. package/lib/raw-request-b6AYnkxd.d.ts +32 -0
  173. package/lib/request-DNNIV9ub.d.cts +44 -0
  174. package/lib/request-sVa4pxmx.d.ts +44 -0
  175. package/lib/resolvers/aws-context/index.cjs +2 -0
  176. package/lib/resolvers/aws-context/index.cjs.map +1 -0
  177. package/lib/resolvers/aws-context/index.d.cts +25 -0
  178. package/lib/resolvers/aws-context/index.d.ts +25 -0
  179. package/lib/resolvers/aws-context/index.mjs +2 -0
  180. package/lib/resolvers/aws-context/index.mjs.map +1 -0
  181. package/lib/resolvers/callback/index.cjs +2 -0
  182. package/lib/resolvers/callback/index.cjs.map +1 -0
  183. package/lib/resolvers/callback/index.d.cts +29 -0
  184. package/lib/resolvers/callback/index.d.ts +29 -0
  185. package/lib/resolvers/callback/index.mjs +2 -0
  186. package/lib/resolvers/callback/index.mjs.map +1 -0
  187. package/lib/resolvers/dummy/index.cjs +2 -0
  188. package/lib/resolvers/dummy/index.cjs.map +1 -0
  189. package/lib/resolvers/dummy/index.d.cts +20 -0
  190. package/lib/resolvers/dummy/index.d.ts +20 -0
  191. package/lib/resolvers/dummy/index.mjs +2 -0
  192. package/lib/resolvers/dummy/index.mjs.map +1 -0
  193. package/lib/resolvers/promise/index.cjs +2 -0
  194. package/lib/resolvers/promise/index.cjs.map +1 -0
  195. package/lib/resolvers/promise/index.d.cts +20 -0
  196. package/lib/resolvers/promise/index.d.ts +20 -0
  197. package/lib/resolvers/promise/index.mjs +2 -0
  198. package/lib/resolvers/promise/index.mjs.map +1 -0
  199. package/package.json +1 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/frameworks/trpc/index.ts","../../../src/frameworks/trpc/trpc.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/optional.ts","../../../src/core/stream.ts"],"sourcesContent":["export * from './trpc.framework';\n","//#region\n\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { AnyRouter, DataTransformer } from '@trpc/server';\nimport {\n type NodeHTTPCreateContextFn,\n type NodeHTTPCreateContextFnOptions,\n type NodeHTTPHandlerOptions,\n nodeHTTPRequestHandler,\n} from '@trpc/server/adapters/node-http';\nimport type { SingleValueHeaders } from '../../@types';\nimport type { FrameworkContract } from '../../contracts';\nimport { getDefaultIfUndefined, getFlattenedHeadersMap } from '../../core';\n\n//#endregion\n\n/**\n * The transformer that is responsible to transform buffer's input to javascript objects\n *\n * @deprecated You should use {@link JsonBodyParserFramework} instead, is more reliable and enable you to use transformer of trpc to other things.\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport class BufferToJSObjectTransformer implements DataTransformer {\n /**\n * Deserialize unknown values to javascript objects\n *\n * @param value - The value to be deserialized\n */\n public deserialize(value?: unknown): any {\n if (value instanceof Buffer) return JSON.parse(value.toString('utf-8'));\n\n return value;\n }\n\n /**\n * The value to be serialized, do nothing because tRPC can handle.\n *\n * @param value - The value to be serialized\n */\n public serialize(value: any): any {\n return value;\n }\n}\n\n/**\n * The context created by this library that allows getting some information from the request and setting the status and header of the response.\n *\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport interface TrpcAdapterBaseContext {\n /**\n * The request object that will be forward to your app\n */\n request: IncomingMessage;\n\n /**\n * The response object that will be forward to your app to output the response\n */\n response: ServerResponse;\n\n /**\n * The method to set response status.\n *\n * @param statusCode - The response status that you want\n */\n setStatus(statusCode: number): void;\n\n /**\n * The method to set some header in the response\n *\n * @param name - The name of the header\n * @param value - The value to be set in the header\n */\n setHeader(name: string, value: number | string): void;\n\n /**\n * The method to remove some header from the response\n *\n * @param name - The name of the header\n */\n removeHeader(name: string): void;\n\n /**\n * The method to return the value of some header from the request\n *\n * @param name - The name of the header\n */\n getHeader(name: string): string | undefined;\n\n /**\n * The method to return the request headers\n */\n getHeaders(): SingleValueHeaders;\n\n /**\n * The method to return user's address\n */\n getIp(): string | undefined;\n\n /**\n * The method to return the URL called\n */\n getUrl(): string | undefined;\n\n /**\n * The method to return the HTTP Method in the request\n */\n getMethod(): string | undefined;\n}\n\n/**\n * This is the context merged between {@link TrpcAdapterBaseContext} and the {@link TContext} that you provided.\n *\n * This context will be merged with the context you created with `createContext` inside {@link TrpcFrameworkOptions}.\n * So to make the type work, just send the properties you've added inside {@link TContext}.\n *\n * @example\n * ```typescript\n * type MyCustomContext = { user: { name: string } };\n * type TrpcContext = TrpcAdapterContext<MyCustomContext>; // your final context type to put inside trpc.router\n * ```\n *\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport type TrpcAdapterContext<TContext> = TContext & TrpcAdapterBaseContext;\n\n/**\n * The options to customize the {@link TrpcFramework}\n *\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport type TrpcFrameworkOptions<TContext> = Omit<\n NodeHTTPHandlerOptions<AnyRouter, IncomingMessage, ServerResponse>,\n 'router' | 'createContext'\n> & {\n createContext?: (\n opts: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>,\n ) =>\n | Omit<TContext, keyof TrpcAdapterBaseContext>\n | Promise<Omit<TContext, keyof TrpcAdapterBaseContext>>;\n};\n\n/**\n * The framework that forwards requests to TRPC handler\n *\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport class TrpcFramework<\n TContext extends TrpcAdapterBaseContext,\n TRouter extends AnyRouter = AnyRouter,\n> implements FrameworkContract<TRouter>\n{\n //#region Constructor\n\n /**\n * Default constructor\n */\n constructor(protected readonly options?: TrpcFrameworkOptions<TContext>) {}\n\n //#endregion\n\n //#region Public Methods\n\n /**\n * {@inheritDoc}\n */\n public sendRequest<TRouter extends AnyRouter>(\n app: TRouter,\n request: IncomingMessage,\n response: ServerResponse,\n ): void {\n const endpoint = this.getSafeUrlForTrpc(request);\n\n nodeHTTPRequestHandler({\n req: request,\n res: response,\n path: endpoint,\n router: app,\n ...this.options,\n createContext: createContextOptions =>\n this.mergeDefaultContextWithOptionsContext(createContextOptions),\n });\n }\n\n //#endregion\n\n //#region Protected Methods\n\n /**\n * Get safe url that can be used inside Trpc.\n *\n * @example\n * ```typescript\n * const url = getSafeUrlForTrpc('/users?input=hello');\n * console.log(url); // users\n * ```\n *\n * @param request - The request object that will be forward to your app\n */\n protected getSafeUrlForTrpc(request: IncomingMessage): string {\n let url = request.url!;\n\n if (url.startsWith('/')) url = url.slice(1);\n\n if (url.includes('?')) url = url.split('?')[0];\n\n return url;\n }\n\n /**\n * Merge the default context ({@link TrpcAdapterContext}) with the context created by the user.\n *\n * @param createContextOptions - The options sent by trpc to create the context\n */\n protected mergeDefaultContextWithOptionsContext(\n createContextOptions: NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n ServerResponse\n >,\n ): TContext | Promise<TContext> {\n const createContextFromOptions: NodeHTTPCreateContextFn<\n AnyRouter,\n IncomingMessage,\n ServerResponse\n > = getDefaultIfUndefined(\n this.options?.createContext,\n () =>\n undefined as unknown as Omit<TContext, keyof TrpcAdapterBaseContext>,\n );\n\n const resolvedContext = createContextFromOptions(createContextOptions);\n\n if (resolvedContext && resolvedContext.then) {\n return resolvedContext.then(context =>\n this.wrapResolvedContextWithDefaultContext(\n context,\n createContextOptions,\n ),\n );\n }\n\n return this.wrapResolvedContextWithDefaultContext(\n resolvedContext,\n createContextOptions,\n );\n }\n\n /**\n * Wraps the resolved context from the {@link TrpcFrameworkOptions} created with `createContext` and merge\n * with the {@link TrpcAdapterContext} generated by the library.\n *\n * @param resolvedContext - The context created with `createContext` inside {@link TrpcFrameworkOptions}\n * @param createContextOptions - The options sent by trpc to create the context\n */\n protected wrapResolvedContextWithDefaultContext(\n resolvedContext: TContext,\n createContextOptions: NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n ServerResponse\n >,\n ): TContext {\n const request = createContextOptions.req;\n const response = createContextOptions.res;\n\n return {\n ...resolvedContext,\n request,\n response,\n getUrl: () => request.url,\n getMethod: () => request.method,\n getHeaders: () => getFlattenedHeadersMap(request.headers, ',', true),\n setHeader: (header, value) => {\n response.setHeader(header, value);\n },\n removeHeader: header => {\n response.removeHeader(header);\n },\n getHeader: (header: string) => {\n return getFlattenedHeadersMap(request.headers, ',', true)[\n header.toLowerCase()\n ];\n },\n setStatus: (statusCode: number) => {\n response.statusCode = statusCode;\n // force undefined to get default message for the status code\n // ref: https://nodejs.org/dist/latest-v16.x/docs/api/http.html#responsestatusmessage\n response.statusMessage = undefined as any;\n },\n getIp: () => request.connection.remoteAddress,\n };\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\n const headerData = stringData.slice(\n endStatusIndex + 2,\n stringData.indexOf(headerEnd),\n );\n const headers = parseHeaders(headerData);\n log.debug('SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS', {\n headers,\n });\n\n writesToIgnore = 1;\n internalWritable = onReceiveHeaders(status, headers);\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","/**\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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BufferToJSObjectTransformer","TrpcFramework","__toCommonJS","import_node_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","getDefaultIfUndefined","value","defaultValue","__name","import_node_stream","BufferToJSObjectTransformer","__name","value","TrpcFramework","options","app","request","response","endpoint","createContextOptions","url","resolvedContext","getDefaultIfUndefined","context","getFlattenedHeadersMap","header","statusCode"]}
@@ -0,0 +1,154 @@
1
+ import { IncomingMessage, ServerResponse } from 'http';
2
+ import { DataTransformer, AnyRouter } from '@trpc/server';
3
+ import { NodeHTTPHandlerOptions, NodeHTTPCreateContextFnOptions } from '@trpc/server/adapters/node-http';
4
+ import { S as SingleValueHeaders } from '../../headers-K2qbcurv.cjs';
5
+ import { F as FrameworkContract } from '../../framework.contract-YnJ-fl1w.cjs';
6
+
7
+ /**
8
+ * The transformer that is responsible to transform buffer's input to javascript objects
9
+ *
10
+ * @deprecated You should use {@link JsonBodyParserFramework} instead, is more reliable and enable you to use transformer of trpc to other things.
11
+ * @breadcrumb Frameworks / TrpcFramework
12
+ * @public
13
+ */
14
+ declare class BufferToJSObjectTransformer implements DataTransformer {
15
+ /**
16
+ * Deserialize unknown values to javascript objects
17
+ *
18
+ * @param value - The value to be deserialized
19
+ */
20
+ deserialize(value?: unknown): any;
21
+ /**
22
+ * The value to be serialized, do nothing because tRPC can handle.
23
+ *
24
+ * @param value - The value to be serialized
25
+ */
26
+ serialize(value: any): any;
27
+ }
28
+ /**
29
+ * The context created by this library that allows getting some information from the request and setting the status and header of the response.
30
+ *
31
+ * @breadcrumb Frameworks / TrpcFramework
32
+ * @public
33
+ */
34
+ interface TrpcAdapterBaseContext {
35
+ /**
36
+ * The request object that will be forward to your app
37
+ */
38
+ request: IncomingMessage;
39
+ /**
40
+ * The response object that will be forward to your app to output the response
41
+ */
42
+ response: ServerResponse;
43
+ /**
44
+ * The method to set response status.
45
+ *
46
+ * @param statusCode - The response status that you want
47
+ */
48
+ setStatus(statusCode: number): void;
49
+ /**
50
+ * The method to set some header in the response
51
+ *
52
+ * @param name - The name of the header
53
+ * @param value - The value to be set in the header
54
+ */
55
+ setHeader(name: string, value: number | string): void;
56
+ /**
57
+ * The method to remove some header from the response
58
+ *
59
+ * @param name - The name of the header
60
+ */
61
+ removeHeader(name: string): void;
62
+ /**
63
+ * The method to return the value of some header from the request
64
+ *
65
+ * @param name - The name of the header
66
+ */
67
+ getHeader(name: string): string | undefined;
68
+ /**
69
+ * The method to return the request headers
70
+ */
71
+ getHeaders(): SingleValueHeaders;
72
+ /**
73
+ * The method to return user's address
74
+ */
75
+ getIp(): string | undefined;
76
+ /**
77
+ * The method to return the URL called
78
+ */
79
+ getUrl(): string | undefined;
80
+ /**
81
+ * The method to return the HTTP Method in the request
82
+ */
83
+ getMethod(): string | undefined;
84
+ }
85
+ /**
86
+ * This is the context merged between {@link TrpcAdapterBaseContext} and the {@link TContext} that you provided.
87
+ *
88
+ * This context will be merged with the context you created with `createContext` inside {@link TrpcFrameworkOptions}.
89
+ * So to make the type work, just send the properties you've added inside {@link TContext}.
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * type MyCustomContext = { user: { name: string } };
94
+ * type TrpcContext = TrpcAdapterContext<MyCustomContext>; // your final context type to put inside trpc.router
95
+ * ```
96
+ *
97
+ * @breadcrumb Frameworks / TrpcFramework
98
+ * @public
99
+ */
100
+ type TrpcAdapterContext<TContext> = TContext & TrpcAdapterBaseContext;
101
+ /**
102
+ * The options to customize the {@link TrpcFramework}
103
+ *
104
+ * @breadcrumb Frameworks / TrpcFramework
105
+ * @public
106
+ */
107
+ type TrpcFrameworkOptions<TContext> = Omit<NodeHTTPHandlerOptions<AnyRouter, IncomingMessage, ServerResponse>, 'router' | 'createContext'> & {
108
+ createContext?: (opts: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>) => Omit<TContext, keyof TrpcAdapterBaseContext> | Promise<Omit<TContext, keyof TrpcAdapterBaseContext>>;
109
+ };
110
+ /**
111
+ * The framework that forwards requests to TRPC handler
112
+ *
113
+ * @breadcrumb Frameworks / TrpcFramework
114
+ * @public
115
+ */
116
+ declare class TrpcFramework<TContext extends TrpcAdapterBaseContext, TRouter extends AnyRouter = AnyRouter> implements FrameworkContract<TRouter> {
117
+ protected readonly options?: TrpcFrameworkOptions<TContext> | undefined;
118
+ /**
119
+ * Default constructor
120
+ */
121
+ constructor(options?: TrpcFrameworkOptions<TContext> | undefined);
122
+ /**
123
+ * {@inheritDoc}
124
+ */
125
+ sendRequest<TRouter extends AnyRouter>(app: TRouter, request: IncomingMessage, response: ServerResponse): void;
126
+ /**
127
+ * Get safe url that can be used inside Trpc.
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const url = getSafeUrlForTrpc('/users?input=hello');
132
+ * console.log(url); // users
133
+ * ```
134
+ *
135
+ * @param request - The request object that will be forward to your app
136
+ */
137
+ protected getSafeUrlForTrpc(request: IncomingMessage): string;
138
+ /**
139
+ * Merge the default context ({@link TrpcAdapterContext}) with the context created by the user.
140
+ *
141
+ * @param createContextOptions - The options sent by trpc to create the context
142
+ */
143
+ protected mergeDefaultContextWithOptionsContext(createContextOptions: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>): TContext | Promise<TContext>;
144
+ /**
145
+ * Wraps the resolved context from the {@link TrpcFrameworkOptions} created with `createContext` and merge
146
+ * with the {@link TrpcAdapterContext} generated by the library.
147
+ *
148
+ * @param resolvedContext - The context created with `createContext` inside {@link TrpcFrameworkOptions}
149
+ * @param createContextOptions - The options sent by trpc to create the context
150
+ */
151
+ protected wrapResolvedContextWithDefaultContext(resolvedContext: TContext, createContextOptions: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>): TContext;
152
+ }
153
+
154
+ export { BufferToJSObjectTransformer, type TrpcAdapterBaseContext, type TrpcAdapterContext, TrpcFramework, type TrpcFrameworkOptions };
@@ -0,0 +1,154 @@
1
+ import { IncomingMessage, ServerResponse } from 'http';
2
+ import { DataTransformer, AnyRouter } from '@trpc/server';
3
+ import { NodeHTTPHandlerOptions, NodeHTTPCreateContextFnOptions } from '@trpc/server/adapters/node-http';
4
+ import { S as SingleValueHeaders } from '../../headers-K2qbcurv.js';
5
+ import { F as FrameworkContract } from '../../framework.contract-YnJ-fl1w.js';
6
+
7
+ /**
8
+ * The transformer that is responsible to transform buffer's input to javascript objects
9
+ *
10
+ * @deprecated You should use {@link JsonBodyParserFramework} instead, is more reliable and enable you to use transformer of trpc to other things.
11
+ * @breadcrumb Frameworks / TrpcFramework
12
+ * @public
13
+ */
14
+ declare class BufferToJSObjectTransformer implements DataTransformer {
15
+ /**
16
+ * Deserialize unknown values to javascript objects
17
+ *
18
+ * @param value - The value to be deserialized
19
+ */
20
+ deserialize(value?: unknown): any;
21
+ /**
22
+ * The value to be serialized, do nothing because tRPC can handle.
23
+ *
24
+ * @param value - The value to be serialized
25
+ */
26
+ serialize(value: any): any;
27
+ }
28
+ /**
29
+ * The context created by this library that allows getting some information from the request and setting the status and header of the response.
30
+ *
31
+ * @breadcrumb Frameworks / TrpcFramework
32
+ * @public
33
+ */
34
+ interface TrpcAdapterBaseContext {
35
+ /**
36
+ * The request object that will be forward to your app
37
+ */
38
+ request: IncomingMessage;
39
+ /**
40
+ * The response object that will be forward to your app to output the response
41
+ */
42
+ response: ServerResponse;
43
+ /**
44
+ * The method to set response status.
45
+ *
46
+ * @param statusCode - The response status that you want
47
+ */
48
+ setStatus(statusCode: number): void;
49
+ /**
50
+ * The method to set some header in the response
51
+ *
52
+ * @param name - The name of the header
53
+ * @param value - The value to be set in the header
54
+ */
55
+ setHeader(name: string, value: number | string): void;
56
+ /**
57
+ * The method to remove some header from the response
58
+ *
59
+ * @param name - The name of the header
60
+ */
61
+ removeHeader(name: string): void;
62
+ /**
63
+ * The method to return the value of some header from the request
64
+ *
65
+ * @param name - The name of the header
66
+ */
67
+ getHeader(name: string): string | undefined;
68
+ /**
69
+ * The method to return the request headers
70
+ */
71
+ getHeaders(): SingleValueHeaders;
72
+ /**
73
+ * The method to return user's address
74
+ */
75
+ getIp(): string | undefined;
76
+ /**
77
+ * The method to return the URL called
78
+ */
79
+ getUrl(): string | undefined;
80
+ /**
81
+ * The method to return the HTTP Method in the request
82
+ */
83
+ getMethod(): string | undefined;
84
+ }
85
+ /**
86
+ * This is the context merged between {@link TrpcAdapterBaseContext} and the {@link TContext} that you provided.
87
+ *
88
+ * This context will be merged with the context you created with `createContext` inside {@link TrpcFrameworkOptions}.
89
+ * So to make the type work, just send the properties you've added inside {@link TContext}.
90
+ *
91
+ * @example
92
+ * ```typescript
93
+ * type MyCustomContext = { user: { name: string } };
94
+ * type TrpcContext = TrpcAdapterContext<MyCustomContext>; // your final context type to put inside trpc.router
95
+ * ```
96
+ *
97
+ * @breadcrumb Frameworks / TrpcFramework
98
+ * @public
99
+ */
100
+ type TrpcAdapterContext<TContext> = TContext & TrpcAdapterBaseContext;
101
+ /**
102
+ * The options to customize the {@link TrpcFramework}
103
+ *
104
+ * @breadcrumb Frameworks / TrpcFramework
105
+ * @public
106
+ */
107
+ type TrpcFrameworkOptions<TContext> = Omit<NodeHTTPHandlerOptions<AnyRouter, IncomingMessage, ServerResponse>, 'router' | 'createContext'> & {
108
+ createContext?: (opts: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>) => Omit<TContext, keyof TrpcAdapterBaseContext> | Promise<Omit<TContext, keyof TrpcAdapterBaseContext>>;
109
+ };
110
+ /**
111
+ * The framework that forwards requests to TRPC handler
112
+ *
113
+ * @breadcrumb Frameworks / TrpcFramework
114
+ * @public
115
+ */
116
+ declare class TrpcFramework<TContext extends TrpcAdapterBaseContext, TRouter extends AnyRouter = AnyRouter> implements FrameworkContract<TRouter> {
117
+ protected readonly options?: TrpcFrameworkOptions<TContext> | undefined;
118
+ /**
119
+ * Default constructor
120
+ */
121
+ constructor(options?: TrpcFrameworkOptions<TContext> | undefined);
122
+ /**
123
+ * {@inheritDoc}
124
+ */
125
+ sendRequest<TRouter extends AnyRouter>(app: TRouter, request: IncomingMessage, response: ServerResponse): void;
126
+ /**
127
+ * Get safe url that can be used inside Trpc.
128
+ *
129
+ * @example
130
+ * ```typescript
131
+ * const url = getSafeUrlForTrpc('/users?input=hello');
132
+ * console.log(url); // users
133
+ * ```
134
+ *
135
+ * @param request - The request object that will be forward to your app
136
+ */
137
+ protected getSafeUrlForTrpc(request: IncomingMessage): string;
138
+ /**
139
+ * Merge the default context ({@link TrpcAdapterContext}) with the context created by the user.
140
+ *
141
+ * @param createContextOptions - The options sent by trpc to create the context
142
+ */
143
+ protected mergeDefaultContextWithOptionsContext(createContextOptions: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>): TContext | Promise<TContext>;
144
+ /**
145
+ * Wraps the resolved context from the {@link TrpcFrameworkOptions} created with `createContext` and merge
146
+ * with the {@link TrpcAdapterContext} generated by the library.
147
+ *
148
+ * @param resolvedContext - The context created with `createContext` inside {@link TrpcFrameworkOptions}
149
+ * @param createContextOptions - The options sent by trpc to create the context
150
+ */
151
+ protected wrapResolvedContextWithDefaultContext(resolvedContext: TContext, createContextOptions: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>): TContext;
152
+ }
153
+
154
+ export { BufferToJSObjectTransformer, type TrpcAdapterBaseContext, type TrpcAdapterContext, TrpcFramework, type TrpcFrameworkOptions };
@@ -0,0 +1,2 @@
1
+ import{h as a,s as i}from"../../chunk-PQDB5AVF.mjs";import{a as s}from"../../chunk-OYOJMOFP.mjs";import{nodeHTTPRequestHandler as C}from"@trpc/server/adapters/node-http";var p=class{static{s(this,"BufferToJSObjectTransformer")}deserialize(e){return e instanceof Buffer?JSON.parse(e.toString("utf-8")):e}serialize(e){return e}},d=class{constructor(e){this.options=e}static{s(this,"TrpcFramework")}sendRequest(e,t,r){let n=this.getSafeUrlForTrpc(t);C({req:t,res:r,path:n,router:e,...this.options,createContext:o=>this.mergeDefaultContextWithOptionsContext(o)})}getSafeUrlForTrpc(e){let t=e.url;return t.startsWith("/")&&(t=t.slice(1)),t.includes("?")&&(t=t.split("?")[0]),t}mergeDefaultContextWithOptionsContext(e){let r=i(this.options?.createContext,()=>{})(e);return r&&r.then?r.then(n=>this.wrapResolvedContextWithDefaultContext(n,e)):this.wrapResolvedContextWithDefaultContext(r,e)}wrapResolvedContextWithDefaultContext(e,t){let r=t.req,n=t.res;return{...e,request:r,response:n,getUrl:()=>r.url,getMethod:()=>r.method,getHeaders:()=>a(r.headers,",",!0),setHeader:(o,m)=>{n.setHeader(o,m)},removeHeader:o=>{n.removeHeader(o)},getHeader:o=>a(r.headers,",",!0)[o.toLowerCase()],setStatus:o=>{n.statusCode=o,n.statusMessage=void 0},getIp:()=>r.connection.remoteAddress}}};export{p as BufferToJSObjectTransformer,d as TrpcFramework};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/frameworks/trpc/trpc.framework.ts"],"sourcesContent":["//#region\n\nimport type { IncomingMessage, ServerResponse } from 'http';\nimport type { AnyRouter, DataTransformer } from '@trpc/server';\nimport {\n type NodeHTTPCreateContextFn,\n type NodeHTTPCreateContextFnOptions,\n type NodeHTTPHandlerOptions,\n nodeHTTPRequestHandler,\n} from '@trpc/server/adapters/node-http';\nimport type { SingleValueHeaders } from '../../@types';\nimport type { FrameworkContract } from '../../contracts';\nimport { getDefaultIfUndefined, getFlattenedHeadersMap } from '../../core';\n\n//#endregion\n\n/**\n * The transformer that is responsible to transform buffer's input to javascript objects\n *\n * @deprecated You should use {@link JsonBodyParserFramework} instead, is more reliable and enable you to use transformer of trpc to other things.\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport class BufferToJSObjectTransformer implements DataTransformer {\n /**\n * Deserialize unknown values to javascript objects\n *\n * @param value - The value to be deserialized\n */\n public deserialize(value?: unknown): any {\n if (value instanceof Buffer) return JSON.parse(value.toString('utf-8'));\n\n return value;\n }\n\n /**\n * The value to be serialized, do nothing because tRPC can handle.\n *\n * @param value - The value to be serialized\n */\n public serialize(value: any): any {\n return value;\n }\n}\n\n/**\n * The context created by this library that allows getting some information from the request and setting the status and header of the response.\n *\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport interface TrpcAdapterBaseContext {\n /**\n * The request object that will be forward to your app\n */\n request: IncomingMessage;\n\n /**\n * The response object that will be forward to your app to output the response\n */\n response: ServerResponse;\n\n /**\n * The method to set response status.\n *\n * @param statusCode - The response status that you want\n */\n setStatus(statusCode: number): void;\n\n /**\n * The method to set some header in the response\n *\n * @param name - The name of the header\n * @param value - The value to be set in the header\n */\n setHeader(name: string, value: number | string): void;\n\n /**\n * The method to remove some header from the response\n *\n * @param name - The name of the header\n */\n removeHeader(name: string): void;\n\n /**\n * The method to return the value of some header from the request\n *\n * @param name - The name of the header\n */\n getHeader(name: string): string | undefined;\n\n /**\n * The method to return the request headers\n */\n getHeaders(): SingleValueHeaders;\n\n /**\n * The method to return user's address\n */\n getIp(): string | undefined;\n\n /**\n * The method to return the URL called\n */\n getUrl(): string | undefined;\n\n /**\n * The method to return the HTTP Method in the request\n */\n getMethod(): string | undefined;\n}\n\n/**\n * This is the context merged between {@link TrpcAdapterBaseContext} and the {@link TContext} that you provided.\n *\n * This context will be merged with the context you created with `createContext` inside {@link TrpcFrameworkOptions}.\n * So to make the type work, just send the properties you've added inside {@link TContext}.\n *\n * @example\n * ```typescript\n * type MyCustomContext = { user: { name: string } };\n * type TrpcContext = TrpcAdapterContext<MyCustomContext>; // your final context type to put inside trpc.router\n * ```\n *\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport type TrpcAdapterContext<TContext> = TContext & TrpcAdapterBaseContext;\n\n/**\n * The options to customize the {@link TrpcFramework}\n *\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport type TrpcFrameworkOptions<TContext> = Omit<\n NodeHTTPHandlerOptions<AnyRouter, IncomingMessage, ServerResponse>,\n 'router' | 'createContext'\n> & {\n createContext?: (\n opts: NodeHTTPCreateContextFnOptions<IncomingMessage, ServerResponse>,\n ) =>\n | Omit<TContext, keyof TrpcAdapterBaseContext>\n | Promise<Omit<TContext, keyof TrpcAdapterBaseContext>>;\n};\n\n/**\n * The framework that forwards requests to TRPC handler\n *\n * @breadcrumb Frameworks / TrpcFramework\n * @public\n */\nexport class TrpcFramework<\n TContext extends TrpcAdapterBaseContext,\n TRouter extends AnyRouter = AnyRouter,\n> implements FrameworkContract<TRouter>\n{\n //#region Constructor\n\n /**\n * Default constructor\n */\n constructor(protected readonly options?: TrpcFrameworkOptions<TContext>) {}\n\n //#endregion\n\n //#region Public Methods\n\n /**\n * {@inheritDoc}\n */\n public sendRequest<TRouter extends AnyRouter>(\n app: TRouter,\n request: IncomingMessage,\n response: ServerResponse,\n ): void {\n const endpoint = this.getSafeUrlForTrpc(request);\n\n nodeHTTPRequestHandler({\n req: request,\n res: response,\n path: endpoint,\n router: app,\n ...this.options,\n createContext: createContextOptions =>\n this.mergeDefaultContextWithOptionsContext(createContextOptions),\n });\n }\n\n //#endregion\n\n //#region Protected Methods\n\n /**\n * Get safe url that can be used inside Trpc.\n *\n * @example\n * ```typescript\n * const url = getSafeUrlForTrpc('/users?input=hello');\n * console.log(url); // users\n * ```\n *\n * @param request - The request object that will be forward to your app\n */\n protected getSafeUrlForTrpc(request: IncomingMessage): string {\n let url = request.url!;\n\n if (url.startsWith('/')) url = url.slice(1);\n\n if (url.includes('?')) url = url.split('?')[0];\n\n return url;\n }\n\n /**\n * Merge the default context ({@link TrpcAdapterContext}) with the context created by the user.\n *\n * @param createContextOptions - The options sent by trpc to create the context\n */\n protected mergeDefaultContextWithOptionsContext(\n createContextOptions: NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n ServerResponse\n >,\n ): TContext | Promise<TContext> {\n const createContextFromOptions: NodeHTTPCreateContextFn<\n AnyRouter,\n IncomingMessage,\n ServerResponse\n > = getDefaultIfUndefined(\n this.options?.createContext,\n () =>\n undefined as unknown as Omit<TContext, keyof TrpcAdapterBaseContext>,\n );\n\n const resolvedContext = createContextFromOptions(createContextOptions);\n\n if (resolvedContext && resolvedContext.then) {\n return resolvedContext.then(context =>\n this.wrapResolvedContextWithDefaultContext(\n context,\n createContextOptions,\n ),\n );\n }\n\n return this.wrapResolvedContextWithDefaultContext(\n resolvedContext,\n createContextOptions,\n );\n }\n\n /**\n * Wraps the resolved context from the {@link TrpcFrameworkOptions} created with `createContext` and merge\n * with the {@link TrpcAdapterContext} generated by the library.\n *\n * @param resolvedContext - The context created with `createContext` inside {@link TrpcFrameworkOptions}\n * @param createContextOptions - The options sent by trpc to create the context\n */\n protected wrapResolvedContextWithDefaultContext(\n resolvedContext: TContext,\n createContextOptions: NodeHTTPCreateContextFnOptions<\n IncomingMessage,\n ServerResponse\n >,\n ): TContext {\n const request = createContextOptions.req;\n const response = createContextOptions.res;\n\n return {\n ...resolvedContext,\n request,\n response,\n getUrl: () => request.url,\n getMethod: () => request.method,\n getHeaders: () => getFlattenedHeadersMap(request.headers, ',', true),\n setHeader: (header, value) => {\n response.setHeader(header, value);\n },\n removeHeader: header => {\n response.removeHeader(header);\n },\n getHeader: (header: string) => {\n return getFlattenedHeadersMap(request.headers, ',', true)[\n header.toLowerCase()\n ];\n },\n setStatus: (statusCode: number) => {\n response.statusCode = statusCode;\n // force undefined to get default message for the status code\n // ref: https://nodejs.org/dist/latest-v16.x/docs/api/http.html#responsestatusmessage\n response.statusMessage = undefined as any;\n },\n getIp: () => request.connection.remoteAddress,\n };\n }\n\n //#endregion\n}\n"],"mappings":"iGAIA,OAIE,0BAAAA,MACK,kCAcA,IAAMC,EAAN,KAA6D,CAvBpE,MAuBoE,CAAAC,EAAA,oCAM3D,YAAYC,EAAsB,CACvC,OAA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tDU,EAAO,YAAY,CACrB,EAEF,UAAYC,GAAuB,CACjCV,EAAS,WAAaU,EAGtBV,EAAS,cAAgB,MAC3B,EACA,MAAO,IAAMD,EAAQ,WAAW,aAClC,CACF,CAGF","names":["nodeHTTPRequestHandler","BufferToJSObjectTransformer","__name","value","TrpcFramework","options","app","request","response","endpoint","nodeHTTPRequestHandler","createContextOptions","url","resolvedContext","getDefaultIfUndefined","context","getFlattenedHeadersMap","header","statusCode"]}
@@ -0,0 +1,66 @@
1
+ import { A as AdapterContract, R as ResolverContract } from './adapter.contract-EQE3rlgO.js';
2
+ import { F as FrameworkContract } from './framework.contract-YnJ-fl1w.js';
3
+ import { I as ILogger } from './logger-9me5n48P.js';
4
+
5
+ /**
6
+ * The interface representing the binary settings implementation by function
7
+ *
8
+ * @breadcrumb Types / BinarySettings
9
+ * @public
10
+ */
11
+ interface BinarySettingsFunction {
12
+ /**
13
+ * This property can be a function that receives the response headers and returns whether that response should be encoded as binary.
14
+ * Otherwise, you can specify not to treat any response as binary by putting `false` in this property.
15
+ *
16
+ * @remarks Setting this property prevents the `contentTypes` and `contentEncodings` properties from being used.
17
+ */
18
+ isBinary: ((headers: Record<string, string | string[] | undefined>) => boolean) | false;
19
+ }
20
+ /**
21
+ * The interface representing the binary settings implementation by looking inside the headers
22
+ *
23
+ * @breadcrumb Types / BinarySettings
24
+ * @public
25
+ */
26
+ interface BinarySettingsContentHeaders {
27
+ /**
28
+ * The list of content types that will be treated as binary
29
+ */
30
+ contentTypes: string[];
31
+ /**
32
+ * The list of content encodings that will be treated as binary
33
+ */
34
+ contentEncodings: string[];
35
+ }
36
+ /**
37
+ * The interface representing the settings for whether the response should be treated as binary or not
38
+ *
39
+ * @remarks Encoded as binary means the response body will be converted to base64
40
+ *
41
+ * @breadcrumb Types / BinarySettings
42
+ * @public
43
+ */
44
+ type BinarySettings = BinarySettingsFunction | BinarySettingsContentHeaders;
45
+
46
+ /**
47
+ * The function used to handle serverless requests
48
+ *
49
+ * @breadcrumb Contracts / HandlerContract
50
+ * @public
51
+ */
52
+ type ServerlessHandler<TReturn> = (...args: any[]) => TReturn;
53
+ /**
54
+ * The interface that represents the contract between the handler and the real implementation
55
+ *
56
+ * @breadcrumb Contracts / HandlerContract
57
+ * @public
58
+ */
59
+ interface HandlerContract<TApp, TEvent, TContext, TCallback, TResponse, TReturn> {
60
+ /**
61
+ * Get the handler that will handle serverless requests
62
+ */
63
+ getHandler(app: TApp, framework: FrameworkContract<TApp>, adapters: AdapterContract<TEvent, TContext, TResponse>[], resolverFactory: ResolverContract<TEvent, TContext, TCallback, TResponse, TReturn>, binarySettings: BinarySettings, respondWithErrors: boolean, log: ILogger): ServerlessHandler<TReturn>;
64
+ }
65
+
66
+ export type { BinarySettings as B, HandlerContract as H, ServerlessHandler as S, BinarySettingsFunction as a, BinarySettingsContentHeaders as b };
@@ -0,0 +1,66 @@
1
+ import { A as AdapterContract, R as ResolverContract } from './adapter.contract-y5xSjOjo.cjs';
2
+ import { F as FrameworkContract } from './framework.contract-YnJ-fl1w.cjs';
3
+ import { I as ILogger } from './logger-9me5n48P.cjs';
4
+
5
+ /**
6
+ * The interface representing the binary settings implementation by function
7
+ *
8
+ * @breadcrumb Types / BinarySettings
9
+ * @public
10
+ */
11
+ interface BinarySettingsFunction {
12
+ /**
13
+ * This property can be a function that receives the response headers and returns whether that response should be encoded as binary.
14
+ * Otherwise, you can specify not to treat any response as binary by putting `false` in this property.
15
+ *
16
+ * @remarks Setting this property prevents the `contentTypes` and `contentEncodings` properties from being used.
17
+ */
18
+ isBinary: ((headers: Record<string, string | string[] | undefined>) => boolean) | false;
19
+ }
20
+ /**
21
+ * The interface representing the binary settings implementation by looking inside the headers
22
+ *
23
+ * @breadcrumb Types / BinarySettings
24
+ * @public
25
+ */
26
+ interface BinarySettingsContentHeaders {
27
+ /**
28
+ * The list of content types that will be treated as binary
29
+ */
30
+ contentTypes: string[];
31
+ /**
32
+ * The list of content encodings that will be treated as binary
33
+ */
34
+ contentEncodings: string[];
35
+ }
36
+ /**
37
+ * The interface representing the settings for whether the response should be treated as binary or not
38
+ *
39
+ * @remarks Encoded as binary means the response body will be converted to base64
40
+ *
41
+ * @breadcrumb Types / BinarySettings
42
+ * @public
43
+ */
44
+ type BinarySettings = BinarySettingsFunction | BinarySettingsContentHeaders;
45
+
46
+ /**
47
+ * The function used to handle serverless requests
48
+ *
49
+ * @breadcrumb Contracts / HandlerContract
50
+ * @public
51
+ */
52
+ type ServerlessHandler<TReturn> = (...args: any[]) => TReturn;
53
+ /**
54
+ * The interface that represents the contract between the handler and the real implementation
55
+ *
56
+ * @breadcrumb Contracts / HandlerContract
57
+ * @public
58
+ */
59
+ interface HandlerContract<TApp, TEvent, TContext, TCallback, TResponse, TReturn> {
60
+ /**
61
+ * Get the handler that will handle serverless requests
62
+ */
63
+ getHandler(app: TApp, framework: FrameworkContract<TApp>, adapters: AdapterContract<TEvent, TContext, TResponse>[], resolverFactory: ResolverContract<TEvent, TContext, TCallback, TResponse, TReturn>, binarySettings: BinarySettings, respondWithErrors: boolean, log: ILogger): ServerlessHandler<TReturn>;
64
+ }
65
+
66
+ export type { BinarySettings as B, HandlerContract as H, ServerlessHandler as S, BinarySettingsFunction as a, BinarySettingsContentHeaders as b };
@@ -0,0 +1,12 @@
1
+ "use strict";var h=Object.defineProperty;var U=Object.getOwnPropertyDescriptor;var q=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var i=(r,e)=>h(r,"name",{value:e,configurable:!0});var j=(r,e)=>{for(var t in e)h(r,t,{get:e[t],enumerable:!0})},$=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of q(e))!G.call(r,n)&&n!==t&&h(r,n,{get:()=>e[n],enumerable:!(o=U(e,n))||o.enumerable});return r};var Q=r=>$(h({},"__esModule",{value:!0}),r);var ee={};j(ee,{AwsStreamHandler:()=>C});module.exports=Q(ee);var at=require("stream"),F=require("util");var P=require("http");var Y=443,y=class extends P.IncomingMessage{static{i(this,"ServerlessRequest")}constructor({method:e,url:t,headers:o,body:n,remoteAddress:s}){super({encrypted:!0,readable:!1,remoteAddress:s,address:()=>({port:Y}),end:u,destroy:u}),this.statusCode=200,this.statusMessage="OK",this.complete=!0,this.httpVersion="1.1",this.httpVersionMajor=1,this.httpVersionMinor=1,this.method=e,this.headers=o,this.body=n,this.url=t,this.ip=s,this._read=()=>{this.push(n),this.push(null)}}ip;body};var H=require("http");function x(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}`)}i(x,"getString");var L=`\r
2
+ \r
3
+ `,z=`0\r
4
+ \r
5
+ `,A=Symbol("Response body"),S=Symbol("Response headers");function b(r,e){if(Buffer.isBuffer(e)||typeof e=="string"||e instanceof Uint8Array)r[A].push(Buffer.from(e));else throw new Error(`response.write() of unexpected type: ${typeof e}`)}i(b,"addData");var v=class r extends H.ServerResponse{static{i(this,"ServerlessResponse")}constructor({method:e}){super({method:e}),this[A]=[],this[S]={},this.useChunkedEncodingByDefault=!1,this.chunkedEncoding=!1,this._header="";let t=1,o={_writableState:{},writable:!0,on:u,removeListener:u,destroy:u,cork:u,uncork:u,write:(n,s,a)=>{if(typeof s=="function"&&(a=s,s=null),this._header===""||this._wroteHeader)this.chunkedEncoding?t>0?t--:n!==z&&(b(this,n),t=3):b(this,n);else{let d=x(n),p=d.indexOf(L);if(p!==-1){let c=d.slice(p+L.length);c&&!this.chunkedEncoding&&b(this,c),this._wroteHeader=!0}}typeof a=="function"&&a()}};this.assignSocket(o)}_header;_headers;_wroteHeader;[A];[S];get headers(){return this[S]}static from(e){let t=new r({method:e.method});return t.statusCode=e.statusCode||0,t[S]=e.headers,t[A]=e.body?[Buffer.from(e.body)]:[],t.end(),t}static body(e){return Buffer.concat(e[A])}static headers(e){let t=e.getHeaders();return Object.assign(t,e[S])}setHeader(e,t){this._wroteHeader?this[S][e]=t:super.setHeader(e,t)}writeHead(e,t,o){let n=typeof t=="string"?o:t,s=Array.isArray(n)?n:[n||{}];for(let a of s)for(let d in a)if(this.setHeader(d,a[d]),!this._wroteHeader)break;return this.callNativeWriteHead(e,t,o)}callNativeWriteHead(e,t,o){return super.writeHead(e,t,o)}};var _=require("http");var K=`0\r
6
+ \r
7
+ `,X=`\r
8
+ \r
9
+ `,J=`\r
10
+ `,T=class extends _.ServerResponse{static{i(this,"ServerlessStreamResponse")}constructor({method:e,onReceiveHeaders:t,log:o}){super({method:e}),this.useChunkedEncodingByDefault=!0,this.chunkedEncoding=!0;let n=null,s=!0,a=0,d={_writableState:{},writable:!0,on:u,removeListener:u,destroy:u,cork:u,uncork:u,write:(p,c,f)=>{if(typeof c=="function"&&(f=c,c=null),o.debug("SERVERLESS_ADAPTER:RESPONSE_STREAM:DATA",()=>({data:Buffer.isBuffer(p)?p.toString("utf8"):p,encoding:c})),!s&&n){if(p===K)return n.end(f),!0;if(a>0)return a--,!0;n.write(p,f),a=3}else if(s){s=!1;let l=x(p),g=l.indexOf(J),E=+l.slice(0,g).split(" ")[1],R=l.slice(g+2,l.indexOf(X)),m=B(R);o.debug("SERVERLESS_ADAPTER:RESPONSE_STREAM:FRAMEWORK_HEADERS",{headers:m}),a=1,n=t(E,m)}return!0}};this.assignSocket(d)}};var w=class{static{i(this,"BaseHandler")}getAdapterByEventAndContext(e,t,o,n){let s=o.filter(a=>a.canHandle(e,t,n));if(s.length===0)throw new Error("SERVERLESS_ADAPTER: Couldn't find adapter to handle this event.");if(s.length>1)throw new Error(`SERVERLESS_ADAPTER: Two or more adapters was resolved by the event, the adapters are: ${o.map(a=>a.getAdapterName()).join(", ")}.`);return s[0]}getServerlessRequestResponseFromAdapterRequest(e){let t=new y({method:e.method,headers:e.headers,body:e.body,remoteAddress:e.remoteAddress,url:e.path}),o=new v({method:e.method});return[t,o]}};var I={context:null,event:null};function O({event:r,context:e}){I.event=r,I.context=e}i(O,"setCurrentInvoke");function V(r,e=",",t=!1){return Object.keys(r).reduce((o,n)=>{let s=t?n.toLowerCase():n,a=r[n];return Array.isArray(a)?o[s]=a.join(e):o[s]=(a??"")+"",o},{})}i(V,"getFlattenedHeadersMap");function B(r){if(!r)return{};let e={},t=r.trim().split(`
11
+ `);for(let o=0;o<t.length;o++){let n=t[o],s=n.indexOf(":"),a=n.slice(0,s).trim().toLowerCase(),d=n.slice(s+1).trim();typeof e[a]>"u"?e[a]=d:Array.isArray(e[a])?e[a].push(d):e[a]=[e[a],d]}return e}i(B,"parseHeaders");var u=i(()=>{},"NO_OP");var Ve=Symbol("InternalLogger");var qe=require("stream");function Z(r){return!!("readableEnded"in r&&r.readableEnded||"writableEnded"in r&&r.writableEnded)}i(Z,"isStreamEnded");function W(r){return Z(r)?Promise.resolve(r):new Promise((e,t)=>{let o=!1;function n(s){o||(o=!0,r.removeListener("error",n),r.removeListener("end",n),r.removeListener("finish",n),s?t(s):e(r))}i(n,"complete"),r.once("error",n),r.once("end",n),r.once("finish",n)})}i(W,"waitForStreamComplete");var C=class extends w{static{i(this,"AwsStreamHandler")}getHandler(e,t,o,n,s,a,d){return awslambda.streamifyResponse(async(p,c,f)=>{let l={response:c,context:f};this.onReceiveRequest(d,p,l,s,a);let g=this.getAdapterByEventAndContext(p,l,o,d);this.onResolveAdapter(d,g),O({event:p,context:f}),await this.forwardRequestToFramework(e,t,p,l,g,s,d)})}onReceiveRequest(e,t,o,n,s){e.debug("SERVERLESS_ADAPTER:PROXY",()=>({event:t,context:(0,F.inspect)(o,{depth:null}),binarySettings:n,respondWithErrors:s}))}onResolveAdapter(e,t){e.debug("SERVERLESS_ADAPTER:RESOLVED_ADAPTER_NAME: ",t.getAdapterName())}onResolveRequestValues(e,t){e.debug("SERVERLESS_ADAPTER:FORWARD_REQUEST_TO_FRAMEWORK:REQUEST_VALUES",()=>({requestValues:{...t,body:t.body?.toString()}}))}onForwardResponseAdapterResponse(e,t){e.debug("SERVERLESS_ADAPTER:FORWARD_RESPONSE:EVENT_SOURCE_RESPONSE",{successResponse:t})}async forwardRequestToFramework(e,t,o,n,s,a,d){let p=s.getRequest(o,n,d);this.onResolveRequestValues(d,p);let c=new y({method:p.method,headers:p.headers,body:p.body,remoteAddress:p.remoteAddress,url:p.path}),f=new T({method:p.method,onReceiveHeaders:(l,g)=>{let E=V(g),R={statusCode:l,headers:E},m=g["set-cookie"];m&&(R.cookies=Array.isArray(m)?m:[m],delete g["set-cookie"],delete E["set-cookie"]),this.onForwardResponseAdapterResponse(d,R);let k=awslambda.HttpResponseStream.from(n.response,R),D=l>=100&&l<200,M=l===304||l===204,N=p.method==="HEAD";return(D||M||N)&&(k.write(""),f.end()),k},log:d});t.sendRequest(e,c,f),d.debug("SERVERLESS_ADAPTER:FORWARD_REQUEST_TO_FRAMEWORK:WAITING_STREAM_COMPLETE"),await W(f),d.debug("SERVERLESS_ADAPTER:FORWARD_REQUEST_TO_FRAMEWORK:STREAM_COMPLETE"),n.response.end()}};0&&(module.exports={AwsStreamHandler});
12
+ //# sourceMappingURL=index.cjs.map