@webiny/handler 0.0.0-unstable.e53eceafb5 → 0.0.0-unstable.e6f0dc8ca7

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 (95) hide show
  1. package/Context.d.ts +1 -1
  2. package/Context.js +6 -14
  3. package/Context.js.map +1 -1
  4. package/PreHandler/IPreHandler.d.ts +1 -1
  5. package/PreHandler/IPreHandler.js +1 -7
  6. package/PreHandler/IPreHandler.js.map +1 -1
  7. package/PreHandler/IfNotOptionsRequest.d.ts +3 -3
  8. package/PreHandler/IfNotOptionsRequest.js +6 -13
  9. package/PreHandler/IfNotOptionsRequest.js.map +1 -1
  10. package/PreHandler/IfOptionsRequest.d.ts +3 -3
  11. package/PreHandler/IfOptionsRequest.js +6 -13
  12. package/PreHandler/IfOptionsRequest.js.map +1 -1
  13. package/PreHandler/PreHandler.d.ts +3 -3
  14. package/PreHandler/PreHandler.js +5 -12
  15. package/PreHandler/PreHandler.js.map +1 -1
  16. package/PreHandler/ProcessBeforeHandlerPlugins.d.ts +4 -4
  17. package/PreHandler/ProcessBeforeHandlerPlugins.js +5 -12
  18. package/PreHandler/ProcessBeforeHandlerPlugins.js.map +1 -1
  19. package/PreHandler/ProcessContextPlugins.d.ts +4 -4
  20. package/PreHandler/ProcessContextPlugins.js +5 -12
  21. package/PreHandler/ProcessContextPlugins.js.map +1 -1
  22. package/PreHandler/ProcessHandlerOnRequestPlugins.d.ts +4 -4
  23. package/PreHandler/ProcessHandlerOnRequestPlugins.js +6 -13
  24. package/PreHandler/ProcessHandlerOnRequestPlugins.js.map +1 -1
  25. package/PreHandler/RegisterExtensions.d.ts +10 -0
  26. package/PreHandler/RegisterExtensions.js +14 -0
  27. package/PreHandler/RegisterExtensions.js.map +1 -0
  28. package/PreHandler/SendEarlyOptionsResponse.d.ts +3 -3
  29. package/PreHandler/SendEarlyOptionsResponse.js +6 -13
  30. package/PreHandler/SendEarlyOptionsResponse.js.map +1 -1
  31. package/PreHandler/SetDefaultHeaders.d.ts +3 -3
  32. package/PreHandler/SetDefaultHeaders.js +8 -15
  33. package/PreHandler/SetDefaultHeaders.js.map +1 -1
  34. package/README.md +10 -14
  35. package/ResponseHeaders.d.ts +0 -1
  36. package/ResponseHeaders.js +1 -8
  37. package/ResponseHeaders.js.map +1 -1
  38. package/abstractions/Reply.d.ts +5 -0
  39. package/abstractions/Reply.js +4 -0
  40. package/abstractions/Reply.js.map +1 -0
  41. package/abstractions/Request.d.ts +5 -0
  42. package/abstractions/Request.js +4 -0
  43. package/abstractions/Request.js.map +1 -0
  44. package/abstractions/Route.d.ts +25 -0
  45. package/abstractions/Route.js +29 -0
  46. package/abstractions/Route.js.map +1 -0
  47. package/exports/api.d.ts +1 -0
  48. package/exports/api.js +3 -0
  49. package/exports/api.js.map +1 -0
  50. package/fastify.d.ts +5 -4
  51. package/fastify.js +108 -69
  52. package/fastify.js.map +1 -1
  53. package/index.d.ts +17 -13
  54. package/index.js +20 -149
  55. package/index.js.map +1 -1
  56. package/package.json +19 -18
  57. package/plugins/BeforeHandlerPlugin.d.ts +1 -1
  58. package/plugins/BeforeHandlerPlugin.js +3 -11
  59. package/plugins/BeforeHandlerPlugin.js.map +1 -1
  60. package/plugins/EventPlugin.d.ts +3 -3
  61. package/plugins/EventPlugin.js +3 -12
  62. package/plugins/EventPlugin.js.map +1 -1
  63. package/plugins/HandlerErrorPlugin.d.ts +1 -1
  64. package/plugins/HandlerErrorPlugin.js +3 -11
  65. package/plugins/HandlerErrorPlugin.js.map +1 -1
  66. package/plugins/HandlerOnRequestPlugin.d.ts +1 -1
  67. package/plugins/HandlerOnRequestPlugin.js +3 -10
  68. package/plugins/HandlerOnRequestPlugin.js.map +1 -1
  69. package/plugins/HandlerResultPlugin.d.ts +1 -1
  70. package/plugins/HandlerResultPlugin.js +3 -11
  71. package/plugins/HandlerResultPlugin.js.map +1 -1
  72. package/plugins/ModifyFastifyPlugin.d.ts +1 -1
  73. package/plugins/ModifyFastifyPlugin.js +3 -11
  74. package/plugins/ModifyFastifyPlugin.js.map +1 -1
  75. package/plugins/ModifyResponseHeadersPlugin.d.ts +3 -3
  76. package/plugins/ModifyResponseHeadersPlugin.js +3 -11
  77. package/plugins/ModifyResponseHeadersPlugin.js.map +1 -1
  78. package/plugins/OnRequestResponseSendPlugin.js +3 -12
  79. package/plugins/OnRequestResponseSendPlugin.js.map +1 -1
  80. package/plugins/OnRequestTimeoutPlugin.js +3 -11
  81. package/plugins/OnRequestTimeoutPlugin.js.map +1 -1
  82. package/plugins/RegisterExtensionPlugin.d.ts +12 -0
  83. package/plugins/RegisterExtensionPlugin.js +16 -0
  84. package/plugins/RegisterExtensionPlugin.js.map +1 -0
  85. package/plugins/RoutePlugin.d.ts +2 -2
  86. package/plugins/RoutePlugin.js +3 -11
  87. package/plugins/RoutePlugin.js.map +1 -1
  88. package/stringifyError.js +1 -8
  89. package/stringifyError.js.map +1 -1
  90. package/suppressPunycodeWarnings.d.ts +1 -4
  91. package/suppressPunycodeWarnings.js +1 -2
  92. package/suppressPunycodeWarnings.js.map +1 -1
  93. package/types.d.ts +3 -3
  94. package/types.js +1 -13
  95. package/types.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"names":["_utils","require","_ResponseHeaders","_IPreHandler","createDefaultHeaders","ResponseHeaders","create","getWebinyVersionHeaders","getDefaultOptionsHeaders","getDefaultHeaders","routes","headers","keys","Object","all","every","key","length","set","allowedMethods","filter","type","Array","isArray","sort","join","SetDefaultHeaders","constructor","definedRoutes","execute","request","reply","isOptionsRequest","method","defaultHeaders","initialHeaders","merge","getHeaders","Action","CONTINUE","exports"],"sources":["SetDefaultHeaders.ts"],"sourcesContent":["import type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { getWebinyVersionHeaders } from \"@webiny/utils\";\nimport { ResponseHeaders } from \"~/ResponseHeaders\";\nimport type { DefinedContextRoutes, HTTPMethods } from \"~/types\";\nimport type { IPreHandler } from \"~/PreHandler/IPreHandler\";\nimport { Action } from \"~/PreHandler/IPreHandler\";\n\nfunction createDefaultHeaders() {\n return ResponseHeaders.create({\n \"content-type\": \"application/json; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"access-control-allow-origin\": \"*\",\n \"access-control-allow-headers\": \"*\",\n \"access-control-allow-methods\": \"OPTIONS,POST,GET,DELETE,PUT,PATCH\",\n ...getWebinyVersionHeaders()\n });\n}\n\nconst getDefaultOptionsHeaders = () => {\n return ResponseHeaders.create({\n \"access-control-max-age\": \"86400\",\n \"cache-control\": \"public, max-age=86400\"\n });\n};\n\nconst getDefaultHeaders = (routes: DefinedContextRoutes): ResponseHeaders => {\n const headers = createDefaultHeaders();\n\n /**\n * If we are accepting all headers, just output that one.\n */\n const keys = Object.keys(routes) as HTTPMethods[];\n const all = keys.every(key => routes[key].length > 0);\n if (all) {\n headers.set(\"access-control-allow-methods\", \"*\");\n } else {\n const allowedMethods = keys\n .filter(type => {\n if (!routes[type] || !Array.isArray(routes[type])) {\n return false;\n }\n return routes[type].length > 0;\n })\n .sort()\n .join(\",\");\n\n headers.set(\"access-control-allow-methods\", allowedMethods);\n }\n\n return headers;\n};\n\nexport class SetDefaultHeaders implements IPreHandler {\n private readonly definedRoutes: DefinedContextRoutes;\n\n constructor(definedRoutes: DefinedContextRoutes) {\n this.definedRoutes = definedRoutes;\n }\n\n execute(request: FastifyRequest, reply: FastifyReply) {\n const isOptionsRequest = request.method === \"OPTIONS\";\n /**\n * Our default headers are always set. Users can override them.\n */\n const defaultHeaders = getDefaultHeaders(this.definedRoutes);\n\n const initialHeaders = isOptionsRequest\n ? defaultHeaders.merge(getDefaultOptionsHeaders())\n : defaultHeaders;\n\n reply.headers(initialHeaders.getHeaders());\n\n return Action.CONTINUE;\n }\n}\n"],"mappings":";;;;;;AACA,IAAAA,MAAA,GAAAC,OAAA;AACA,IAAAC,gBAAA,GAAAD,OAAA;AAGA,IAAAE,YAAA,GAAAF,OAAA;AAEA,SAASG,oBAAoBA,CAAA,EAAG;EAC5B,O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AGlDC,WAAWA,CAACC,aAAmC,EAAE;IAC7C,IAAI,CAACA,aAAa,GAAGA,aAAa;EACtC;EAEAC,OAAOA,CAACC,OAAuB,EAAEC,KAAmB,EAAE;IAClD,MAAMC,gBAAgB,GAAGF,OAAO,CAACG,MAAM,KAAK,SAAS;IACrD;AACR;AACA;IACQ,MAAMC,cAAc,GAAGzB,iBAAiB,CAAC,IAAI,CAACmB,aAAa,CAAC;IAE5D,MAAMO,cAAc,GAAGH,gBAAgB,GACjCE,cAAc,CAACE,KAAK,CAAC5B,wBAAwB,CAAC,CAAC,CAAC,GAChD0B,cAAc;IAEpBH,KAAK,CAACpB,OAAO,CAACwB,cAAc,CAACE,UAAU,CAAC,CAAC,CAAC;IAE1C,OAAOC,mBAAM,CAACC,QAAQ;EAC1B;AACJ;AAACC,OAAA,CAAAd,iBAAA,GAAAA,iBAAA","ignoreList":[]}
1
+ {"version":3,"names":["getWebinyVersionHeaders","ResponseHeaders","Action","createDefaultHeaders","create","getDefaultOptionsHeaders","getDefaultHeaders","routes","headers","keys","Object","all","every","key","length","set","allowedMethods","filter","type","Array","isArray","sort","join","SetDefaultHeaders","constructor","definedRoutes","execute","request","reply","isOptionsRequest","method","defaultHeaders","initialHeaders","merge","getHeaders","CONTINUE"],"sources":["SetDefaultHeaders.ts"],"sourcesContent":["import type { FastifyReply, FastifyRequest } from \"fastify\";\nimport { getWebinyVersionHeaders } from \"@webiny/utils\";\nimport { ResponseHeaders } from \"~/ResponseHeaders.js\";\nimport type { DefinedContextRoutes, HTTPMethods } from \"~/types.js\";\nimport type { IPreHandler } from \"~/PreHandler/IPreHandler.js\";\nimport { Action } from \"~/PreHandler/IPreHandler.js\";\n\nfunction createDefaultHeaders() {\n return ResponseHeaders.create({\n \"content-type\": \"application/json; charset=utf-8\",\n \"cache-control\": \"no-store\",\n \"access-control-allow-origin\": \"*\",\n \"access-control-allow-headers\": \"*\",\n \"access-control-allow-methods\": \"OPTIONS,POST,GET,DELETE,PUT,PATCH\",\n ...getWebinyVersionHeaders()\n });\n}\n\nconst getDefaultOptionsHeaders = () => {\n return ResponseHeaders.create({\n \"access-control-max-age\": \"86400\",\n \"cache-control\": \"public, max-age=86400\"\n });\n};\n\nconst getDefaultHeaders = (routes: DefinedContextRoutes): ResponseHeaders => {\n const headers = createDefaultHeaders();\n\n /**\n * If we are accepting all headers, just output that one.\n */\n const keys = Object.keys(routes) as HTTPMethods[];\n const all = keys.every(key => routes[key].length > 0);\n if (all) {\n headers.set(\"access-control-allow-methods\", \"*\");\n } else {\n const allowedMethods = keys\n .filter(type => {\n if (!routes[type] || !Array.isArray(routes[type])) {\n return false;\n }\n return routes[type].length > 0;\n })\n .sort()\n .join(\",\");\n\n headers.set(\"access-control-allow-methods\", allowedMethods);\n }\n\n return headers;\n};\n\nexport class SetDefaultHeaders implements IPreHandler {\n private readonly definedRoutes: DefinedContextRoutes;\n\n constructor(definedRoutes: DefinedContextRoutes) {\n this.definedRoutes = definedRoutes;\n }\n\n execute(request: FastifyRequest, reply: FastifyReply) {\n const isOptionsRequest = request.method === \"OPTIONS\";\n /**\n * Our default headers are always set. Users can override them.\n */\n const defaultHeaders = getDefaultHeaders(this.definedRoutes);\n\n const initialHeaders = isOptionsRequest\n ? defaultHeaders.merge(getDefaultOptionsHeaders())\n : defaultHeaders;\n\n reply.headers(initialHeaders.getHeaders());\n\n return Action.CONTINUE;\n }\n}\n"],"mappings":"AACA,SAASA,uBAAuB,QAAQ,eAAe;AACvD,SAASC,eAAe;AAGxB,SAASC,MAAM;AAEf,SAASC,oBAAoBA,CAAA,EAAG;EAC5B,OAAOF,eAAe,CAACG,MAAM,CAAC;IAC1B,cAAc,EAAE,iCAAiC;IACjD,eAAe,EAAE,UAAU;IAC3B,6BAA6B,EAAE,GAAG;IAClC,8BAA8B,EAAE,GAAG;IACnC,8BAA8B,EAAE,mCAAmC;IACnE,GAAGJ,uBAAuB,CAAC;EAC/B,CAAC,CAAC;AACN;AAEA,MAAMK,wBAAwB,GAAGA,C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ACmB,aAAa,CAAC;IAE5D,MAAMO,cAAc,GAAGH,gBAAgB,GACjCE,cAAc,CAACE,KAAK,CAAC5B,wBAAwB,CAAC,CAAC,CAAC,GAChD0B,cAAc;IAEpBH,KAAK,CAACpB,OAAO,CAACwB,cAAc,CAACE,UAAU,CAAC,CAAC,CAAC;IAE1C,OAAOhC,MAAM,CAACiC,QAAQ;EAC1B;AACJ","ignoreList":[]}
package/README.md CHANGED
@@ -1,15 +1,11 @@
1
1
  # @webiny/handler
2
- [![](https://img.shields.io/npm/dw/@webiny/handler.svg)](https://www.npmjs.com/package/@webiny/handler)
3
- [![](https://img.shields.io/npm/v/@webiny/handler.svg)](https://www.npmjs.com/package/@webiny/handler)
4
- [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier)
5
- [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-square)](http://makeapullrequest.com)
6
-
7
- ## Install
8
- ```
9
- npm install --save @webiny/handler
10
- ```
11
-
12
- Or if you prefer yarn:
13
- ```
14
- yarn add @webiny/handler
15
- ```
2
+
3
+ > [!NOTE]
4
+ > This package is part of the [Webiny](https://www.webiny.com) monorepo.
5
+ > It’s **included in every Webiny project by default** and is not meant to be used as a standalone package.
6
+
7
+ 📘 **Documentation:** [https://www.webiny.com/docs](https://www.webiny.com/docs)
8
+
9
+ ---
10
+
11
+ _This README file is automatically generated during the publish process._
@@ -1,4 +1,3 @@
1
- /// <reference types="node" />
2
1
  import type * as http from "http";
3
2
  type ExtraHeaders = {
4
3
  "content-type"?: string | undefined;
@@ -1,15 +1,9 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.ResponseHeaders = void 0;
7
1
  // Extract known standard headers, and remove all non-string keys.
8
2
 
9
3
  function isFunction(setter) {
10
4
  return typeof setter === "function";
11
5
  }
12
- class ResponseHeaders {
6
+ export class ResponseHeaders {
13
7
  headers = new Map();
14
8
  constructor(initialHeaders) {
15
9
  if (initialHeaders) {
@@ -41,6 +35,5 @@ class ResponseHeaders {
41
35
  return new ResponseHeaders(initialHeaders);
42
36
  }
43
37
  }
44
- exports.ResponseHeaders = ResponseHeaders;
45
38
 
46
39
  //# sourceMappingURL=ResponseHeaders.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["isFunction","setter","ResponseHeaders","headers","Map","constructor","initialHeaders","Object","keys","forEach","key","set","header","previousValue","get","newValue","merge","create","getHeaders","fromEntries","exports"],"sources":["ResponseHeaders.ts"],"sourcesContent":["import type * as http from \"http\";\n\ntype ExtraHeaders = {\n \"content-type\"?: string | undefined;\n \"x-webiny-version\"?: http.OutgoingHttpHeader | undefined;\n};\n\ntype AllHeaders = http.OutgoingHttpHeaders & ExtraHeaders;\n\nexport type StandardHeaderValue = http.OutgoingHttpHeader | undefined;\n\n// Extract known standard headers, and remove all non-string keys.\nexport type StandardHeaders = {\n [K in keyof AllHeaders as string extends K\n ? never\n : number extends K\n ? never\n : K]: http.OutgoingHttpHeaders[K];\n} & {\n [name: string]: StandardHeaderValue;\n};\n\nfunction isFunction<T>(setter: unknown): setter is (value: T) => T {\n return typeof setter === \"function\";\n}\n\ntype Setter<T> = ((value: T) => T) | T;\n\nexport class ResponseHeaders {\n private readonly headers = new Map<keyof StandardHeaders, StandardHeaderValue>();\n\n private constructor(initialHeaders?: StandardHeaders) {\n if (initialHeaders) {\n (Object.keys(initialHeaders) as Array<keyof StandardHeaders>).forEach(key => {\n this.headers.set(key, initialHeaders[key]);\n });\n }\n }\n\n set<T extends keyof StandardHeaders>(header: T, setter: Setter<StandardHeaders[T]>) {\n if (isFunction<StandardHeaders[T]>(setter)) {\n const previousValue = this.headers.get(header) as StandardHeaders[T];\n const newValue = setter(previousValue);\n this.headers.set(header, newValue);\n return this;\n }\n\n this.headers.set(header, setter);\n\n return this;\n }\n\n merge(headers: ResponseHeaders) {\n return ResponseHeaders.create({ ...this.getHeaders(), ...headers.getHeaders() });\n }\n\n getHeaders() {\n return Object.fromEntries(this.headers);\n }\n\n static create(initialHeaders?: StandardHeaders) {\n return new ResponseHeaders(initialHeaders);\n }\n}\n"],"mappings":";;;;;;AAWA;;AAWA,SAASA,UAAUA,CAAIC,MAAe,EAA6B;EAC/D,OAAO,OAAOA,MAAM,KAAK,UAAU;AACvC;AAIO,MAAMC,eAAe,CAAC;EACRC,OAAO,GAAG,IAAIC,GAAG,CAA6C,CAAC;EAExEC,WAAWA,CAACC,cAAgC,EAAE;IAClD,IAAIA,cAAc,EAAE;MACfC,MAAM,CAACC,IAAI,CAACF,cAAc,CAAC,CAAkCG,OAAO,CAACC,GAAG,IAAI;QACzE,IAAI,CAACP,OAAO,CAACQ,GAAG,CAACD,GAAG,EAAEJ,cAAc,CAACI,GAAG,CAAC,CAAC;MAC9C,CAAC,CAAC;IACN;EACJ;EAEAC,GAAGA,CAAkCC,MAAS,EAAEX,MAAkC,EAAE;IAChF,IAAID,UAAU,CAAqBC,MAAM,CAAC,EAAE;MACxC,MAAMY,aAAa,GAAG,IAAI,CAACV,OAAO,CAACW,GAAG,CAACF,MAAM,CAAuB;MACpE,MAAMG,QAAQ,GAAGd,MAAM,CAACY,aAAa,CAAC;MACtC,IAAI,CAACV,OAAO,CAACQ,GAAG,CAACC,MAAM,EAAEG,QAAQ,CAAC;MAClC,OAAO,IAAI;IACf;IAEA,IAAI,CAACZ,OAAO,CAACQ,GAAG,CAACC,MAAM,EAAEX,MAAM,CAAC;IAEhC,OAAO,IAAI;EACf;EAEAe,KAAKA,CAACb,OAAwB,EAAE;IAC5B,OAAOD,eAAe,CAACe,MAAM,CAAC;MAAE,GAAG,IAAI,CAACC,UAAU,CAAC,CAAC;MAAE,GAAGf,OAAO,CAACe,UAAU,CAAC;IAAE,CAAC,CAAC;EACpF;EAEAA,UAAUA,CAAA,EAAG;IACT,OAAOX,MAAM,CAACY,WAAW,CAAC,IAAI,CAAChB,OAAO,CAAC;EAC3C;EAEA,OAAOc,MAAMA,CAACX,cAAgC,EAAE;IAC5C,OAAO,IAAIJ,eAAe,CAACI,cAAc,CAAC;EAC9C;AACJ;AAACc,OAAA,CAAAlB,eAAA,GAAAA,eAAA","ignoreList":[]}
1
+ {"version":3,"names":["isFunction","setter","ResponseHeaders","headers","Map","constructor","initialHeaders","Object","keys","forEach","key","set","header","previousValue","get","newValue","merge","create","getHeaders","fromEntries"],"sources":["ResponseHeaders.ts"],"sourcesContent":["import type * as http from \"http\";\n\ntype ExtraHeaders = {\n \"content-type\"?: string | undefined;\n \"x-webiny-version\"?: http.OutgoingHttpHeader | undefined;\n};\n\ntype AllHeaders = http.OutgoingHttpHeaders & ExtraHeaders;\n\nexport type StandardHeaderValue = http.OutgoingHttpHeader | undefined;\n\n// Extract known standard headers, and remove all non-string keys.\nexport type StandardHeaders = {\n [K in keyof AllHeaders as string extends K\n ? never\n : number extends K\n ? never\n : K]: http.OutgoingHttpHeaders[K];\n} & {\n [name: string]: StandardHeaderValue;\n};\n\nfunction isFunction<T>(setter: unknown): setter is (value: T) => T {\n return typeof setter === \"function\";\n}\n\ntype Setter<T> = ((value: T) => T) | T;\n\nexport class ResponseHeaders {\n private readonly headers = new Map<keyof StandardHeaders, StandardHeaderValue>();\n\n private constructor(initialHeaders?: StandardHeaders) {\n if (initialHeaders) {\n (Object.keys(initialHeaders) as Array<keyof StandardHeaders>).forEach(key => {\n this.headers.set(key, initialHeaders[key]);\n });\n }\n }\n\n set<T extends keyof StandardHeaders>(header: T, setter: Setter<StandardHeaders[T]>) {\n if (isFunction<StandardHeaders[T]>(setter)) {\n const previousValue = this.headers.get(header) as StandardHeaders[T];\n const newValue = setter(previousValue);\n this.headers.set(header, newValue);\n return this;\n }\n\n this.headers.set(header, setter);\n\n return this;\n }\n\n merge(headers: ResponseHeaders) {\n return ResponseHeaders.create({ ...this.getHeaders(), ...headers.getHeaders() });\n }\n\n getHeaders() {\n return Object.fromEntries(this.headers);\n }\n\n static create(initialHeaders?: StandardHeaders) {\n return new ResponseHe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":[]}
@@ -0,0 +1,5 @@
1
+ import type { Reply as IReply } from "../types.js";
2
+ export declare const Reply: import("@webiny/di").Abstraction<IReply>;
3
+ export declare namespace Reply {
4
+ type Interface = IReply;
5
+ }
@@ -0,0 +1,4 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ export const Reply = createAbstraction("Reply");
3
+
4
+ //# sourceMappingURL=Reply.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["createAbstraction","Reply"],"sources":["Reply.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Reply as IReply } from \"~/types.js\";\n\nexport const Reply = createAbstraction<IReply>(\"Reply\");\n\nexport namespace Reply {\n export type Interface = IReply;\n}\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,qBAAqB;AAGvD,OAAO,MAAMC,KAAK,GAAGD,iBAAiB,CAAS,OAAO,CAAC","ignoreList":[]}
@@ -0,0 +1,5 @@
1
+ import type { Request as IRequest } from "../types.js";
2
+ export declare const Request: import("@webiny/di").Abstraction<IRequest>;
3
+ export declare namespace Request {
4
+ type Interface = IRequest;
5
+ }
@@ -0,0 +1,4 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ export const Request = createAbstraction("Request");
3
+
4
+ //# sourceMappingURL=Request.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["createAbstraction","Request"],"sources":["Request.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { Request as IRequest } from \"~/types.js\";\n\nexport const Request = createAbstraction<IRequest>(\"Request\");\n\nexport namespace Request {\n export type Interface = IRequest;\n}\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,qBAAqB;AAGvD,OAAO,MAAMC,OAAO,GAAGD,iBAAiB,CAAW,SAAS,CAAC","ignoreList":[]}
@@ -0,0 +1,25 @@
1
+ import type { FastifyRequest, FastifyReply } from "fastify";
2
+ export interface IRouteRequest {
3
+ body: unknown;
4
+ headers: Record<string, string | string[] | undefined>;
5
+ method: string;
6
+ url: string;
7
+ params: unknown;
8
+ query: unknown;
9
+ }
10
+ export interface IRouteReply {
11
+ code(statusCode: number): this;
12
+ send(data?: unknown): void;
13
+ header(key: string, value: unknown): this;
14
+ }
15
+ export interface IRoute {
16
+ execute(request: IRouteRequest, reply: IRouteReply): Promise<void>;
17
+ }
18
+ export declare const Route: import("@webiny/di").Abstraction<IRoute>;
19
+ export declare namespace Route {
20
+ type Interface = IRoute;
21
+ type Request = IRouteRequest;
22
+ type Reply = IRouteReply;
23
+ }
24
+ export declare function toRouteRequest(req: FastifyRequest): IRouteRequest;
25
+ export declare function toRouteReply(reply: FastifyReply): IRouteReply;
@@ -0,0 +1,29 @@
1
+ import { createAbstraction } from "@webiny/feature/api";
2
+ export const Route = createAbstraction("Route");
3
+ export function toRouteRequest(req) {
4
+ return {
5
+ body: req.body,
6
+ headers: req.headers,
7
+ method: req.method,
8
+ url: req.url,
9
+ params: req.params ?? {},
10
+ query: req.query ?? {}
11
+ };
12
+ }
13
+ export function toRouteReply(reply) {
14
+ return {
15
+ code(statusCode) {
16
+ reply.code(statusCode);
17
+ return this;
18
+ },
19
+ send(data) {
20
+ reply.send(data);
21
+ },
22
+ header(key, value) {
23
+ reply.header(key, value);
24
+ return this;
25
+ }
26
+ };
27
+ }
28
+
29
+ //# sourceMappingURL=Route.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["createAbstraction","Route","toRouteRequest","req","body","headers","method","url","params","query","toRouteReply","reply","code","statusCode","send","data","header","key","value"],"sources":["Route.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { FastifyRequest, FastifyReply } from \"fastify\";\n\nexport interface IRouteRequest {\n body: unknown;\n headers: Record<string, string | string[] | undefined>;\n method: string;\n url: string;\n params: unknown;\n query: unknown;\n}\n\nexport interface IRouteReply {\n code(statusCode: number): this;\n send(data?: unknown): void;\n header(key: string, value: unknown): this;\n}\n\nexport interface IRoute {\n execute(request: IRouteRequest, reply: IRouteReply): Promise<void>;\n}\n\nexport const Route = createAbstraction<IRoute>(\"Route\");\n\nexport namespace Route {\n export type Interface = IRoute;\n export type Request = IRouteRequest;\n export type Reply = IRouteReply;\n}\n\nexport function toRouteRequest(req: FastifyRequest): IRouteRequest {\n return {\n body: req.body,\n headers: req.headers as Record<string, string | string[] | undefined>,\n method: req.method,\n url: req.url,\n params: (req.params as Record<string, string>) ?? {},\n query: (req.query as Record<string, string | string[]>) ?? {}\n };\n}\n\nexport function toRouteReply(reply: FastifyReply): IRouteReply {\n return {\n code(statusCode) {\n reply.code(statusCode);\n return this;\n },\n send(data) {\n reply.send(data);\n },\n header(key, value) {\n reply.header(key, value as string);\n return this;\n }\n };\n}\n"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,qBAAqB;AAsBvD,OAAO,MAAMC,KAAK,GAAGD,iBAAiB,CAAS,OAAO,CAAC;AAQvD,OAAO,SAASE,cAAcA,CAACC,GAAmB,EAAiB;EAC/D,OAAO;IACHC,IAAI,EAAED,GAAG,CAACC,IAAI;IACdC,OAAO,EAAEF,GAAG,CAACE,OAAwD;IACrEC,MAAM,EAAEH,GAAG,CAACG,MAAM;IAClBC,GAAG,EAAEJ,GAAG,CAACI,GAAG;IACZC,MAAM,EAAGL,GAAG,CAACK,MAAM,IAA+B,CAAC,CAAC;IACpDC,KAAK,EAAGN,GAAG,CAACM,KAAK,IAA0C,CAAC;EAChE,CAAC;AACL;AAEA,OAAO,SAASC,YAAYA,CAACC,KAAmB,EAAe;EAC3D,OAAO;IACHC,IAAIA,CAACC,UAAU,EAAE;MACbF,KAAK,CAACC,IAAI,CAACC,UAAU,CAAC;MACtB,OAAO,IAAI;IACf,CAAC;IACDC,IAAIA,CAACC,IAAI,EAAE;MACPJ,KAAK,CAACG,IAAI,CAACC,IAAI,CAAC;IACpB,CAAC;IACDC,MAAMA,CAACC,GAAG,EAAEC,KAAK,EAAE;MACfP,KAAK,CAACK,MAAM,CAACC,GAAG,EAAEC,KAAe,CAAC;MAClC,OAAO,IAAI;IACf;EACJ,CAAC;AACL","ignoreList":[]}
@@ -0,0 +1 @@
1
+ export { Route } from "../abstractions/Route.js";
package/exports/api.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Route } from "../abstractions/Route.js";
2
+
3
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"names":["Route"],"sources":["api.ts"],"sourcesContent":["export { Route } from \"~/abstractions/Route.js\";\n"],"mappings":"AAAA,SAASA,KAAK","ignoreList":[]}
package/fastify.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- /// <reference types="node" />
2
- import type { PluginCollection } from "@webiny/plugins/types";
3
- import { PluginsContainer } from "@webiny/plugins/types";
1
+ import type { PluginCollection } from "@webiny/plugins/types.js";
2
+ import { PluginsContainer } from "@webiny/plugins/types.js";
4
3
  import type { FastifyInstance, FastifyServerOptions as ServerOptions } from "fastify";
5
4
  export interface CreateHandlerParams {
6
5
  plugins: PluginCollection | PluginsContainer;
7
6
  options?: ServerOptions;
8
7
  debug?: boolean;
9
8
  }
10
- export declare const createHandler: (params: CreateHandlerParams) => FastifyInstance<import("fastify").RawServerDefault, import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault> & PromiseLike<FastifyInstance<import("fastify").RawServerDefault, import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>>;
9
+ export declare const createHandler: (params: CreateHandlerParams) => FastifyInstance<import("fastify").RawServerDefault, import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault> & PromiseLike<FastifyInstance<import("fastify").RawServerDefault, import("http").IncomingMessage, import("http").ServerResponse<import("http").IncomingMessage>, import("fastify").FastifyBaseLogger, import("fastify").FastifyTypeProviderDefault>> & {
10
+ __linterBrands: "SafePromiseLike";
11
+ };
package/fastify.js CHANGED
@@ -1,48 +1,49 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
- Object.defineProperty(exports, "__esModule", {
5
- value: true
6
- });
7
- exports.createHandler = void 0;
8
- var _types = require("@webiny/plugins/types");
9
- var _fastify = _interopRequireDefault(require("fastify"));
10
- var _utils = require("@webiny/utils");
11
- var _Context = require("./Context");
12
- var _error = _interopRequireDefault(require("@webiny/error"));
13
- var _RoutePlugin = require("./plugins/RoutePlugin");
14
- var _handlerClient = require("@webiny/handler-client");
15
- var _cookie = _interopRequireDefault(require("@fastify/cookie"));
16
- var _compress = _interopRequireDefault(require("@fastify/compress"));
17
- var _api = require("@webiny/api");
18
- var _BeforeHandlerPlugin = require("./plugins/BeforeHandlerPlugin");
19
- var _HandlerResultPlugin = require("./plugins/HandlerResultPlugin");
20
- var _HandlerErrorPlugin = require("./plugins/HandlerErrorPlugin");
21
- var _ModifyFastifyPlugin = require("./plugins/ModifyFastifyPlugin");
22
- var _HandlerOnRequestPlugin = require("./plugins/HandlerOnRequestPlugin");
23
- var _ResponseHeaders = require("./ResponseHeaders");
24
- var _ModifyResponseHeadersPlugin = require("./plugins/ModifyResponseHeadersPlugin");
25
- var _SetDefaultHeaders = require("./PreHandler/SetDefaultHeaders");
26
- var _PreHandler = require("./PreHandler/PreHandler");
27
- var _stringifyError = require("./stringifyError");
28
- var _ProcessHandlerOnRequestPlugins = require("./PreHandler/ProcessHandlerOnRequestPlugins");
29
- var _ProcessContextPlugins = require("./PreHandler/ProcessContextPlugins");
30
- var _IfNotOptionsRequest = require("./PreHandler/IfNotOptionsRequest");
31
- var _ProcessBeforeHandlerPlugins = require("./PreHandler/ProcessBeforeHandlerPlugins");
32
- var _IfOptionsRequest = require("./PreHandler/IfOptionsRequest");
33
- var _SendEarlyOptionsResponse = require("./PreHandler/SendEarlyOptionsResponse");
34
- var _OnRequestTimeoutPlugin = require("./plugins/OnRequestTimeoutPlugin.js");
35
- var _OnRequestResponseSendPlugin = require("./plugins/OnRequestResponseSendPlugin.js");
1
+ import { PluginsContainer } from "@webiny/plugins/types.js";
2
+ import fastify from "fastify";
3
+ import { middleware } from "@webiny/utils";
4
+ import { Context } from "./Context.js";
5
+ import WebinyError from "@webiny/error";
6
+ import { RoutePlugin } from "./plugins/RoutePlugin.js";
7
+ import fastifyCookie from "@fastify/cookie";
8
+ import fastifyCompress from "@fastify/compress";
9
+ import { ContextPlugin } from "@webiny/api";
10
+ import { BeforeHandlerPlugin } from "./plugins/BeforeHandlerPlugin.js";
11
+ import { HandlerResultPlugin } from "./plugins/HandlerResultPlugin.js";
12
+ import { HandlerErrorPlugin } from "./plugins/HandlerErrorPlugin.js";
13
+ import { ModifyFastifyPlugin } from "./plugins/ModifyFastifyPlugin.js";
14
+ import { HandlerOnRequestPlugin } from "./plugins/HandlerOnRequestPlugin.js";
15
+ import { ResponseHeaders } from "./ResponseHeaders.js";
16
+ import { ModifyResponseHeadersPlugin } from "./plugins/ModifyResponseHeadersPlugin.js";
17
+ import { SetDefaultHeaders } from "./PreHandler/SetDefaultHeaders.js";
18
+ import { PreHandler } from "./PreHandler/PreHandler.js";
19
+ import { stringifyError } from "./stringifyError.js";
20
+ import { ProcessHandlerOnRequestPlugins } from "./PreHandler/ProcessHandlerOnRequestPlugins.js";
21
+ import { ProcessContextPlugins } from "./PreHandler/ProcessContextPlugins.js";
22
+ import { IfNotOptionsRequest } from "./PreHandler/IfNotOptionsRequest.js";
23
+ import { ProcessBeforeHandlerPlugins } from "./PreHandler/ProcessBeforeHandlerPlugins.js";
24
+ import { IfOptionsRequest } from "./PreHandler/IfOptionsRequest.js";
25
+ import { SendEarlyOptionsResponse } from "./PreHandler/SendEarlyOptionsResponse.js";
26
+ import { OnRequestTimeoutPlugin } from "./plugins/OnRequestTimeoutPlugin.js";
27
+ import { OnRequestResponseSendPlugin } from "./plugins/OnRequestResponseSendPlugin.js";
28
+ import { Request } from "./abstractions/Request.js";
29
+ import { Reply } from "./abstractions/Reply.js";
30
+ import { RegisterExtensionPlugin } from "./plugins/RegisterExtensionPlugin.js";
31
+ import { RegisterExtensions } from "./PreHandler/RegisterExtensions.js";
36
32
  const modifyResponseHeaders = (app, request, reply) => {
37
- const modifyHeaders = app.webiny.plugins.byType(_ModifyResponseHeadersPlugin.ModifyResponseHeadersPlugin.type);
33
+ const modifyHeaders = app.webiny.plugins.byType(ModifyResponseHeadersPlugin.type);
38
34
  const replyHeaders = reply.getHeaders();
39
- const headers = _ResponseHeaders.ResponseHeaders.create(replyHeaders);
35
+ const headers = ResponseHeaders.create(replyHeaders);
40
36
  modifyHeaders.forEach(plugin => {
41
37
  plugin.modify(request, headers);
42
38
  });
43
- reply.headers(headers.getHeaders());
39
+
40
+ // Exclude 'set-cookie' header to avoid duplication.
41
+ // Cookies are managed by @fastify/cookie and calling reply.headers() with 'set-cookie' duplicates them.
42
+ const headersToSet = headers.getHeaders();
43
+ delete headersToSet["set-cookie"];
44
+ reply.headers(headersToSet);
44
45
  };
45
- const createHandler = params => {
46
+ export const createHandler = params => {
46
47
  const definedRoutes = {
47
48
  POST: [],
48
49
  GET: [],
@@ -75,7 +76,7 @@ const createHandler = params => {
75
76
  }
76
77
  console.error(`Error while registering onAll route. One of the routes is already defined.`);
77
78
  console.error(JSON.stringify(all));
78
- throw new _error.default(`You cannot override a route with onAll() method, please remove unnecessary route from the system.`, "OVERRIDE_ROUTE_ERROR", {
79
+ throw new WebinyError(`You cannot override a route with onAll() method, please remove unnecessary route from the system.`, "OVERRIDE_ROUTE_ERROR", {
79
80
  type,
80
81
  path
81
82
  });
@@ -85,7 +86,7 @@ const createHandler = params => {
85
86
  return;
86
87
  }
87
88
  console.error(`Error while trying to override route: [${type}] ${path}`);
88
- throw new _error.default(`When you are trying to override existing route, you must send "override" parameter when adding that route.`, "OVERRIDE_ROUTE_ERROR", {
89
+ throw new WebinyError(`When you are trying to override existing route, you must send "override" parameter when adding that route.`, "OVERRIDE_ROUTE_ERROR", {
89
90
  type,
90
91
  path
91
92
  });
@@ -103,10 +104,11 @@ const createHandler = params => {
103
104
  /**
104
105
  * We must attach the server to our internal context if we want to have it accessible.
105
106
  */
106
- const app = (0, _fastify.default)({
107
+ const app = fastify({
107
108
  bodyLimit: 536870912,
108
109
  // 512MB
109
110
  disableRequestLogging: true,
111
+ allowErrorHandlerOverride: true,
110
112
  ...(params.options || {})
111
113
  });
112
114
 
@@ -132,7 +134,7 @@ const createHandler = params => {
132
134
  *
133
135
  * https://github.com/fastify/fastify-cookie
134
136
  */
135
- app.register(_cookie.default, {
137
+ app.register(fastifyCookie, {
136
138
  parseOptions: {} // options for parsing cookies
137
139
  });
138
140
  /**
@@ -140,7 +142,7 @@ const createHandler = params => {
140
142
  *
141
143
  * https://github.com/fastify/fastify-compress
142
144
  */
143
- app.register(_compress.default, {
145
+ app.register(fastifyCompress, {
144
146
  global: true,
145
147
  threshold: 1024,
146
148
  onUnsupportedEncoding: (encoding, _, reply) => {
@@ -188,15 +190,10 @@ const createHandler = params => {
188
190
  }
189
191
  };
190
192
  let context;
191
- const plugins = new _types.PluginsContainer([
192
- /**
193
- * We must have handlerClient by default.
194
- * And it must be one of the first context plugins applied.
195
- */
196
- (0, _handlerClient.createHandlerClient)()]);
193
+ const plugins = new PluginsContainer([]);
197
194
  plugins.merge(params.plugins || []);
198
195
  try {
199
- context = new _Context.Context({
196
+ context = new Context({
200
197
  plugins,
201
198
  /**
202
199
  * Inserted via webpack at build time.
@@ -206,7 +203,7 @@ const createHandler = params => {
206
203
  });
207
204
  } catch (ex) {
208
205
  console.error(`Error while constructing the Context.`);
209
- console.error((0, _stringifyError.stringifyError)(ex));
206
+ console.error(stringifyError(ex));
210
207
  throw ex;
211
208
  }
212
209
 
@@ -215,6 +212,26 @@ const createHandler = params => {
215
212
  */
216
213
  app.decorate("webiny", context);
217
214
 
215
+ /**
216
+ * To prevent Unsupported Media Type errors on OPTIONS requests with a body,
217
+ * we need to have a custom parser
218
+ */
219
+ app.addContentTypeParser("application/json", {
220
+ parseAs: "string",
221
+ bodyLimit: 1024 * 1024
222
+ }, (req, body, done) => {
223
+ if (req.method === "OPTIONS") {
224
+ done(null, undefined);
225
+ return;
226
+ }
227
+ try {
228
+ const json = typeof body === "string" ? body : body.toString("utf8");
229
+ done(null, JSON.parse(json));
230
+ } catch (err) {
231
+ done(err);
232
+ }
233
+ });
234
+
218
235
  /**
219
236
  * With this we ensure that an undefined request body is not parsed on OPTIONS requests,
220
237
  * in case there's a `content-type` header set for whatever reason.
@@ -238,20 +255,27 @@ const createHandler = params => {
238
255
  app.addHook("preHandler", async (request, reply) => {
239
256
  app.webiny.request = request;
240
257
  app.webiny.reply = reply;
258
+
259
+ // Bind request and reply to DI container for runtime access
260
+ if (app.webiny.container) {
261
+ app.webiny.container.registerInstance(Request, request);
262
+ app.webiny.container.registerInstance(Reply, reply);
263
+ }
241
264
  /**
242
265
  * Default code to 200 - so we do not need to set it again.
243
266
  * Usually we set errors manually when we use reply.send.
244
267
  */
245
268
  reply.code(200);
246
- const handlerOnRequestPlugins = app.webiny.plugins.byType(_HandlerOnRequestPlugin.HandlerOnRequestPlugin.type);
247
- const contextPlugins = app.webiny.plugins.byType(_api.ContextPlugin.type);
248
- const beforeHandlerPlugins = app.webiny.plugins.byType(_BeforeHandlerPlugin.BeforeHandlerPlugin.type);
249
- const modifyHeadersPlugins = app.webiny.plugins.byType(_ModifyResponseHeadersPlugin.ModifyResponseHeadersPlugin.type);
250
- const preHandler = new _PreHandler.PreHandler([new _SetDefaultHeaders.SetDefaultHeaders(definedRoutes), new _ProcessHandlerOnRequestPlugins.ProcessHandlerOnRequestPlugins(handlerOnRequestPlugins), new _IfNotOptionsRequest.IfNotOptionsRequest([new _ProcessContextPlugins.ProcessContextPlugins(app.webiny, contextPlugins), new _ProcessBeforeHandlerPlugins.ProcessBeforeHandlerPlugins(app.webiny, beforeHandlerPlugins)]), new _IfOptionsRequest.IfOptionsRequest([new _SendEarlyOptionsResponse.SendEarlyOptionsResponse(modifyHeadersPlugins)])]);
269
+ const handlerOnRequestPlugins = app.webiny.plugins.byType(HandlerOnRequestPlugin.type);
270
+ const contextPlugins = app.webiny.plugins.byType(ContextPlugin.type);
271
+ const beforeHandlerPlugins = app.webiny.plugins.byType(BeforeHandlerPlugin.type);
272
+ const modifyHeadersPlugins = app.webiny.plugins.byType(ModifyResponseHeadersPlugin.type);
273
+ const registerExtensionPlugins = app.webiny.plugins.byType(RegisterExtensionPlugin.type);
274
+ const preHandler = new PreHandler([new RegisterExtensions(registerExtensionPlugins), new SetDefaultHeaders(definedRoutes), new ProcessHandlerOnRequestPlugins(handlerOnRequestPlugins), new IfNotOptionsRequest([new ProcessContextPlugins(app.webiny, contextPlugins), new ProcessBeforeHandlerPlugins(app.webiny, beforeHandlerPlugins)]), new IfOptionsRequest([new SendEarlyOptionsResponse(modifyHeadersPlugins)])]);
251
275
  await preHandler.execute(request, reply, app.webiny);
252
276
  });
253
277
  app.addHook("preSerialization", async (_, __, payload) => {
254
- const plugins = app.webiny.plugins.byType(_HandlerResultPlugin.HandlerResultPlugin.type);
278
+ const plugins = app.webiny.plugins.byType(HandlerResultPlugin.type);
255
279
  let name;
256
280
  try {
257
281
  for (const plugin of plugins) {
@@ -260,7 +284,7 @@ const createHandler = params => {
260
284
  }
261
285
  } catch (ex) {
262
286
  console.error(`Error while running the "HandlerResultPlugin" ${name ? `(${name})` : ""} plugin in the preSerialization hook.`);
263
- console.error((0, _stringifyError.stringifyError)(ex));
287
+ console.error(stringifyError(ex));
264
288
  throw ex;
265
289
  }
266
290
  return payload;
@@ -273,6 +297,22 @@ const createHandler = params => {
273
297
  console.warn("Reply already sent, cannot send the result (handler:setErrorHandler).");
274
298
  return reply;
275
299
  }
300
+ if (error.code?.startsWith("Authentication/")) {
301
+ return reply.status(401).headers({
302
+ "Cache-Control": "no-store"
303
+ }).send(JSON.stringify({
304
+ message: error.message,
305
+ code: error.code
306
+ }));
307
+ }
308
+ if (error.code === "Tenancy/TenantDisabled") {
309
+ return reply.status(503).headers({
310
+ "Cache-Control": "no-store"
311
+ }).send(JSON.stringify({
312
+ message: error.message,
313
+ code: error.code
314
+ }));
315
+ }
276
316
  return reply.status(500).headers({
277
317
  "Cache-Control": "no-store"
278
318
  }).send(
@@ -286,13 +326,13 @@ const createHandler = params => {
286
326
  }));
287
327
  });
288
328
  app.addHook("onError", async (_, reply, error) => {
289
- const plugins = app.webiny.plugins.byType(_HandlerErrorPlugin.HandlerErrorPlugin.type);
329
+ const plugins = app.webiny.plugins.byType(HandlerErrorPlugin.type);
290
330
  /**
291
331
  * Log error to cloud, as these can be extremely annoying to debug!
292
332
  */
293
333
  console.error("Logging error in @webiny/handler");
294
334
  try {
295
- console.error((0, _stringifyError.stringifyError)(error));
335
+ console.error(stringifyError(error));
296
336
  } catch (ex) {
297
337
  console.warn("Could not stringify error:");
298
338
  console.log(error);
@@ -316,7 +356,7 @@ const createHandler = params => {
316
356
  } else {
317
357
  console.warn("Reply already sent, cannot send the result (handler:addHook:onError).");
318
358
  }
319
- const handler = (0, _utils.middleware)(plugins.map(pl => {
359
+ const handler = middleware(plugins.map(pl => {
320
360
  return (context, error, next) => {
321
361
  return pl.handle(context, error, next);
322
362
  };
@@ -330,7 +370,7 @@ const createHandler = params => {
330
370
  */
331
371
  app.addHook("onSend", async (request, reply, input) => {
332
372
  modifyResponseHeaders(app, request, reply);
333
- const plugins = app.webiny.plugins.byType(_OnRequestResponseSendPlugin.OnRequestResponseSendPlugin.type);
373
+ const plugins = app.webiny.plugins.byType(OnRequestResponseSendPlugin.type);
334
374
  let payload = input;
335
375
  for (const plugin of plugins) {
336
376
  payload = await plugin.exec(request, reply, payload);
@@ -345,7 +385,7 @@ const createHandler = params => {
345
385
  await context.benchmark.output();
346
386
  });
347
387
  app.addHook("onTimeout", async (request, reply) => {
348
- const plugins = app.webiny.plugins.byType(_OnRequestTimeoutPlugin.OnRequestTimeoutPlugin.type);
388
+ const plugins = app.webiny.plugins.byType(OnRequestTimeoutPlugin.type);
349
389
  for (const plugin of plugins) {
350
390
  await plugin.exec(request, reply);
351
391
  }
@@ -355,7 +395,7 @@ const createHandler = params => {
355
395
  /**
356
396
  * With these plugins we give users possibility to do anything they want on our fastify instance.
357
397
  */
358
- const modifyPlugins = app.webiny.plugins.byType(_ModifyFastifyPlugin.ModifyFastifyPlugin.type);
398
+ const modifyPlugins = app.webiny.plugins.byType(ModifyFastifyPlugin.type);
359
399
  let modifyFastifyPluginName;
360
400
  try {
361
401
  for (const plugin of modifyPlugins) {
@@ -364,7 +404,7 @@ const createHandler = params => {
364
404
  }
365
405
  } catch (ex) {
366
406
  console.error(`Error while running the "ModifyFastifyPlugin" ${modifyFastifyPluginName ? `(${modifyFastifyPluginName})` : ""} plugin in the end of the "createHandler" callable.`);
367
- console.error((0, _stringifyError.stringifyError)(ex));
407
+ console.error(stringifyError(ex));
368
408
  throw ex;
369
409
  }
370
410
 
@@ -375,7 +415,7 @@ const createHandler = params => {
375
415
  *
376
416
  * Routes are registered in fastify but events must be handled in package which implements cloud specific methods.
377
417
  */
378
- const routePlugins = app.webiny.plugins.byType(_RoutePlugin.RoutePlugin.type);
418
+ const routePlugins = app.webiny.plugins.byType(RoutePlugin.type);
379
419
 
380
420
  /**
381
421
  * Add routes to the system.
@@ -391,11 +431,10 @@ const createHandler = params => {
391
431
  }
392
432
  } catch (ex) {
393
433
  console.error(`Error while running the "RoutePlugin" ${routePluginName ? `(${routePluginName})` : ""} plugin in the beginning of the "createHandler" callable.`);
394
- console.error((0, _stringifyError.stringifyError)(ex));
434
+ console.error(stringifyError(ex));
395
435
  throw ex;
396
436
  }
397
437
  return app;
398
438
  };
399
- exports.createHandler = createHandler;
400
439
 
401
440
  //# sourceMappingURL=fastify.js.map