@webiny/handler 0.0.0-unstable.78f581c1d2 → 0.0.0-unstable.7be00a75a9

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 (100) hide show
  1. package/Context.d.ts +18 -9
  2. package/Context.js +11 -27
  3. package/Context.js.map +1 -1
  4. package/PreHandler/IPreHandler.d.ts +9 -0
  5. package/PreHandler/IPreHandler.js +8 -0
  6. package/PreHandler/IPreHandler.js.map +1 -0
  7. package/PreHandler/IfNotOptionsRequest.d.ts +9 -0
  8. package/PreHandler/IfNotOptionsRequest.js +18 -0
  9. package/PreHandler/IfNotOptionsRequest.js.map +1 -0
  10. package/PreHandler/IfOptionsRequest.d.ts +9 -0
  11. package/PreHandler/IfOptionsRequest.js +18 -0
  12. package/PreHandler/IfOptionsRequest.js.map +1 -0
  13. package/PreHandler/PreHandler.d.ts +9 -0
  14. package/PreHandler/PreHandler.js +16 -0
  15. package/PreHandler/PreHandler.js.map +1 -0
  16. package/PreHandler/ProcessBeforeHandlerPlugins.d.ts +10 -0
  17. package/PreHandler/ProcessBeforeHandlerPlugins.js +25 -0
  18. package/PreHandler/ProcessBeforeHandlerPlugins.js.map +1 -0
  19. package/PreHandler/ProcessContextPlugins.d.ts +10 -0
  20. package/PreHandler/ProcessContextPlugins.js +25 -0
  21. package/PreHandler/ProcessContextPlugins.js.map +1 -0
  22. package/PreHandler/ProcessHandlerOnRequestPlugins.d.ts +10 -0
  23. package/PreHandler/ProcessHandlerOnRequestPlugins.js +25 -0
  24. package/PreHandler/ProcessHandlerOnRequestPlugins.js.map +1 -0
  25. package/PreHandler/RegisterExtensions.d.ts +10 -0
  26. package/PreHandler/RegisterExtensions.js +13 -0
  27. package/PreHandler/RegisterExtensions.js.map +1 -0
  28. package/PreHandler/SendEarlyOptionsResponse.d.ts +9 -0
  29. package/PreHandler/SendEarlyOptionsResponse.js +26 -0
  30. package/PreHandler/SendEarlyOptionsResponse.js.map +1 -0
  31. package/PreHandler/SetDefaultHeaders.d.ts +9 -0
  32. package/PreHandler/SetDefaultHeaders.js +46 -0
  33. package/PreHandler/SetDefaultHeaders.js.map +1 -0
  34. package/README.md +10 -14
  35. package/ResponseHeaders.d.ts +24 -0
  36. package/ResponseHeaders.js +36 -0
  37. package/ResponseHeaders.js.map +1 -0
  38. package/abstractions/Reply.d.ts +5 -0
  39. package/abstractions/Reply.js +5 -0
  40. package/abstractions/Reply.js.map +1 -0
  41. package/abstractions/Request.d.ts +5 -0
  42. package/abstractions/Request.js +5 -0
  43. package/abstractions/Request.js.map +1 -0
  44. package/abstractions/Route.d.ts +25 -0
  45. package/abstractions/Route.js +30 -0
  46. package/abstractions/Route.js.map +1 -0
  47. package/exports/api.d.ts +1 -0
  48. package/exports/api.js +1 -0
  49. package/fastify.d.ts +8 -5
  50. package/fastify.js +311 -311
  51. package/fastify.js.map +1 -1
  52. package/index.d.ts +19 -8
  53. package/index.js +19 -109
  54. package/package.json +23 -28
  55. package/plugins/BeforeHandlerPlugin.d.ts +1 -1
  56. package/plugins/BeforeHandlerPlugin.js +15 -35
  57. package/plugins/BeforeHandlerPlugin.js.map +1 -1
  58. package/plugins/EventPlugin.d.ts +3 -3
  59. package/plugins/EventPlugin.js +12 -36
  60. package/plugins/EventPlugin.js.map +1 -1
  61. package/plugins/HandlerErrorPlugin.d.ts +6 -3
  62. package/plugins/HandlerErrorPlugin.js +15 -32
  63. package/plugins/HandlerErrorPlugin.js.map +1 -1
  64. package/plugins/HandlerOnRequestPlugin.d.ts +21 -0
  65. package/plugins/HandlerOnRequestPlugin.js +17 -0
  66. package/plugins/HandlerOnRequestPlugin.js.map +1 -0
  67. package/plugins/HandlerResultPlugin.d.ts +1 -1
  68. package/plugins/HandlerResultPlugin.js +15 -32
  69. package/plugins/HandlerResultPlugin.js.map +1 -1
  70. package/plugins/ModifyFastifyPlugin.d.ts +13 -0
  71. package/plugins/ModifyFastifyPlugin.js +17 -0
  72. package/plugins/ModifyFastifyPlugin.js.map +1 -0
  73. package/plugins/ModifyResponseHeadersPlugin.d.ts +14 -0
  74. package/plugins/ModifyResponseHeadersPlugin.js +19 -0
  75. package/plugins/ModifyResponseHeadersPlugin.js.map +1 -0
  76. package/plugins/OnRequestResponseSendPlugin.d.ts +26 -0
  77. package/plugins/OnRequestResponseSendPlugin.js +17 -0
  78. package/plugins/OnRequestResponseSendPlugin.js.map +1 -0
  79. package/plugins/OnRequestTimeoutPlugin.d.ts +12 -0
  80. package/plugins/OnRequestTimeoutPlugin.js +17 -0
  81. package/plugins/OnRequestTimeoutPlugin.js.map +1 -0
  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 +12 -28
  87. package/plugins/RoutePlugin.js.map +1 -1
  88. package/stringifyError.d.ts +5 -0
  89. package/stringifyError.js +15 -0
  90. package/stringifyError.js.map +1 -0
  91. package/suppressPunycodeWarnings.d.ts +1 -0
  92. package/suppressPunycodeWarnings.js +7 -0
  93. package/suppressPunycodeWarnings.js.map +1 -0
  94. package/types.d.ts +15 -14
  95. package/types.js +1 -19
  96. package/index.js.map +0 -1
  97. package/middleware.d.ts +0 -4
  98. package/middleware.js +0 -51
  99. package/middleware.js.map +0 -1
  100. package/types.js.map +0 -1
package/fastify.js CHANGED
@@ -1,319 +1,319 @@
1
- "use strict";
2
-
3
- var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
4
-
5
- Object.defineProperty(exports, "__esModule", {
6
- value: true
7
- });
8
- exports.createHandler = void 0;
9
-
10
- var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
11
-
12
- var _fastify = _interopRequireDefault(require("fastify"));
13
-
14
- var _utils = require("@webiny/utils");
15
-
16
- var _Context = require("./Context");
17
-
18
- var _error = _interopRequireDefault(require("@webiny/error"));
19
-
20
- var _RoutePlugin = require("./plugins/RoutePlugin");
21
-
22
- var _handlerClient = require("@webiny/handler-client");
23
-
24
- var _cookie = _interopRequireDefault(require("@fastify/cookie"));
25
-
26
- var _middleware = require("./middleware");
27
-
28
- var _api = require("@webiny/api");
29
-
30
- var _BeforeHandlerPlugin = require("./plugins/BeforeHandlerPlugin");
31
-
32
- var _HandlerResultPlugin = require("./plugins/HandlerResultPlugin");
33
-
34
- var _HandlerErrorPlugin = require("./plugins/HandlerErrorPlugin");
35
-
36
- const DEFAULT_HEADERS = (0, _objectSpread2.default)({
37
- "Cache-Control": "no-store",
38
- "Content-Type": "application/json; charset=utf-8",
39
- "Access-Control-Allow-Origin": "*",
40
- "Access-Control-Allow-Headers": "*",
41
- "Access-Control-Allow-Methods": "OPTIONS,POST,GET,DELETE,PUT,PATCH"
42
- }, (0, _utils.getWebinyVersionHeaders)());
43
-
44
- const getDefaultHeaders = routes => {
45
- /**
46
- * If we are accepting all headers, just output that one.
47
- */
48
- const keys = Object.keys(routes);
49
- const all = keys.every(key => routes[key].length > 0);
50
-
51
- if (all) {
52
- return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, DEFAULT_HEADERS), {}, {
53
- "Access-Control-Allow-Methods": "*"
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 _webiny_error from "@webiny/error";
6
+ import { RoutePlugin } from "./plugins/RoutePlugin.js";
7
+ import cookie from "@fastify/cookie";
8
+ import compress 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";
32
+ const modifyResponseHeaders = (app, request, reply)=>{
33
+ const modifyHeaders = app.webiny.plugins.byType(ModifyResponseHeadersPlugin.type);
34
+ const replyHeaders = reply.getHeaders();
35
+ const headers = ResponseHeaders.create(replyHeaders);
36
+ modifyHeaders.forEach((plugin)=>{
37
+ plugin.modify(request, headers);
54
38
  });
55
- }
56
-
57
- return (0, _objectSpread2.default)((0, _objectSpread2.default)({}, DEFAULT_HEADERS), {}, {
58
- "Access-Control-Allow-Methods": keys.filter(key => {
59
- const type = key;
60
-
61
- if (!routes[type] || Array.isArray(routes[type]) === false) {
62
- return false;
63
- }
64
-
65
- return routes[type].length > 0;
66
- }).sort().join(",")
67
- });
39
+ const headersToSet = headers.getHeaders();
40
+ delete headersToSet["set-cookie"];
41
+ reply.headers(headersToSet);
68
42
  };
69
-
70
- const OPTIONS_HEADERS = {
71
- "Access-Control-Max-Age": "86400",
72
- "Cache-Control": "public, max-age=86400"
73
- };
74
-
75
- const createHandler = params => {
76
- const definedRoutes = {
77
- POST: [],
78
- GET: [],
79
- OPTIONS: [],
80
- DELETE: [],
81
- PATCH: [],
82
- PUT: [],
83
- HEAD: [],
84
- COPY: [],
85
- LOCK: [],
86
- MKCOL: [],
87
- MOVE: [],
88
- PROPFIND: [],
89
- PROPPATCH: [],
90
- SEARCH: [],
91
- TRACE: [],
92
- UNLOCK: []
93
- };
94
-
95
- const throwOnDefinedRoute = (type, path, options) => {
96
- if (type === "ALL") {
97
- const all = Object.keys(definedRoutes).some(key => {
98
- const routes = definedRoutes[key];
99
- return routes.includes(path);
100
- });
101
-
102
- if (!all) {
103
- return;
104
- }
105
-
106
- throw new _error.default(`You cannot override a route with onAll() method, please remove unnecessary route from the system.`, "OVERRIDE_ROUTE_ERROR", {
107
- type,
108
- path
109
- });
110
- } else if (definedRoutes[type].includes(path) === false) {
111
- return;
112
- } else if ((options === null || options === void 0 ? void 0 : options.override) === true) {
113
- return;
114
- }
115
-
116
- throw new _error.default(`When you are trying to override existing route, you must send "override" parameter when adding that route.`, "OVERRIDE_ROUTE_ERROR", {
117
- type,
118
- path
43
+ const createHandler = (params)=>{
44
+ const definedRoutes = {
45
+ POST: [],
46
+ GET: [],
47
+ OPTIONS: [],
48
+ DELETE: [],
49
+ PATCH: [],
50
+ PUT: [],
51
+ HEAD: [],
52
+ COPY: [],
53
+ LOCK: [],
54
+ MKCOL: [],
55
+ MOVE: [],
56
+ PROPFIND: [],
57
+ PROPPATCH: [],
58
+ SEARCH: [],
59
+ TRACE: [],
60
+ UNLOCK: [],
61
+ REPORT: [],
62
+ MKCALENDAR: []
63
+ };
64
+ const throwOnDefinedRoute = (type, path, options)=>{
65
+ if ("ALL" === type) {
66
+ const all = Object.keys(definedRoutes).find((k)=>{
67
+ const key = k.toUpperCase();
68
+ const routes = definedRoutes[key];
69
+ return routes.includes(path);
70
+ });
71
+ if (!all) return;
72
+ console.error("Error while registering onAll route. One of the routes is already defined.");
73
+ console.error(JSON.stringify(all));
74
+ throw new _webiny_error("You cannot override a route with onAll() method, please remove unnecessary route from the system.", "OVERRIDE_ROUTE_ERROR", {
75
+ type,
76
+ path
77
+ });
78
+ }
79
+ if (false === definedRoutes[type].includes(path)) return;
80
+ if (options?.override === true) return;
81
+ console.error(`Error while trying to override route: [${type}] ${path}`);
82
+ throw new _webiny_error('When you are trying to override existing route, you must send "override" parameter when adding that route.', "OVERRIDE_ROUTE_ERROR", {
83
+ type,
84
+ path
85
+ });
86
+ };
87
+ const addDefinedRoute = (input, path)=>{
88
+ const type = input.toUpperCase();
89
+ if (!definedRoutes[type]) return;
90
+ if (definedRoutes[type].includes(path)) return;
91
+ definedRoutes[type].push(path);
92
+ };
93
+ const app = fastify({
94
+ bodyLimit: 536870912,
95
+ disableRequestLogging: true,
96
+ allowErrorHandlerOverride: true,
97
+ ...params.options || {}
119
98
  });
120
- };
121
-
122
- const addDefinedRoute = (inputType, path) => {
123
- const type = inputType.toUpperCase();
124
-
125
- if (!definedRoutes[type]) {
126
- return;
127
- } else if (definedRoutes[type].includes(path)) {
128
- return;
129
- }
130
-
131
- definedRoutes[type].push(path);
132
- };
133
- /**
134
- * We must attach the server to our internal context if we want to have it accessible.
135
- */
136
-
137
-
138
- const app = (0, _fastify.default)((0, _objectSpread2.default)({}, params.options || {}));
139
- /**
140
- * We need to register routes in our system so we can output headers later on and dissallow overriding routes.
141
- */
142
-
143
- app.addHook("onRoute", route => {
144
- const method = route.method;
145
-
146
- if (Array.isArray(method)) {
147
- for (const m of method) {
148
- addDefinedRoute(m, route.path);
149
- }
150
-
151
- return;
152
- }
153
-
154
- addDefinedRoute(method, route.path);
155
- });
156
- /**
157
- *
158
- */
159
-
160
- app.register(_cookie.default, {
161
- parseOptions: {} // options for parsing cookies
162
-
163
- });
164
- /**
165
- * Route helpers - mostly for users.
166
- */
167
-
168
- const routes = {
169
- defined: definedRoutes,
170
- onPost: (path, handler, options) => {
171
- throwOnDefinedRoute("POST", path, options);
172
- app.post(path, handler);
173
- },
174
- onGet: (path, handler, options) => {
175
- throwOnDefinedRoute("GET", path, options);
176
- app.get(path, handler);
177
- },
178
- onOptions: (path, handler, options) => {
179
- throwOnDefinedRoute("OPTIONS", path, options);
180
- app.options(path, handler);
181
- },
182
- onDelete: (path, handler, options) => {
183
- throwOnDefinedRoute("DELETE", path, options);
184
- app.delete(path, handler);
185
- },
186
- onPatch: (path, handler, options) => {
187
- throwOnDefinedRoute("PATCH", path, options);
188
- app.patch(path, handler);
189
- },
190
- onPut: (path, handler, options) => {
191
- throwOnDefinedRoute("PUT", path, options);
192
- app.put(path, handler);
193
- },
194
- onAll: (path, handler, options) => {
195
- throwOnDefinedRoute("ALL", path, options);
196
- app.all(path, handler);
197
- },
198
- onHead: (path, handler, options) => {
199
- throwOnDefinedRoute("HEAD", path, options);
200
- app.head(path, handler);
201
- }
202
- };
203
- const context = new _Context.Context({
204
- plugins: [
205
- /**
206
- * We must have handlerClient by default.
207
- * And it must be one of the first context plugins applied.
208
- */
209
- (0, _handlerClient.createHandlerClient)(), ...(params.plugins || [])],
210
-
211
- /**
212
- * Inserted via webpack on build time.
213
- */
214
- WEBINY_VERSION: process.env.WEBINY_VERSION,
215
- server: app,
216
- routes
217
- });
218
- /**
219
- * We are attaching our custom context to webiny variable on the fastify app so it is accessible everywhere
220
- */
221
-
222
- app.decorate("webiny", context);
223
- /**
224
- * We have few types of triggers:
225
- * * Events - EventPlugin
226
- * * Routes - RoutePlugin
227
- *
228
- * Routes are registered in fastify but events must be handled in package which implements cloud specific methods.
229
- */
230
-
231
- const routePlugins = app.webiny.plugins.byType(_RoutePlugin.RoutePlugin.type);
232
- /**
233
- * Add routes to the system.
234
- */
235
-
236
- for (const plugin of routePlugins) {
237
- plugin.cb((0, _objectSpread2.default)((0, _objectSpread2.default)({}, app.webiny.routes), {}, {
238
- context: app.webiny
239
- }));
240
- }
241
- /**
242
- * On every request we add default headers, which can be changed later.
243
- * Also, if it is an options request, we skip everything after this hook and output options headers.
244
- */
245
-
246
-
247
- app.addHook("onRequest", async (request, reply) => {
248
- const defaultHeaders = getDefaultHeaders(definedRoutes);
249
- reply.headers(defaultHeaders);
250
-
251
- if (request.method !== "OPTIONS") {
252
- return;
253
- }
254
-
255
- const raw = reply.code(204).hijack().raw;
256
- const headers = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, defaultHeaders), OPTIONS_HEADERS);
257
-
258
- for (const key in headers) {
259
- raw.setHeader(key, headers[key]);
260
- }
261
-
262
- raw.end("");
263
- });
264
- app.addHook("preParsing", async request => {
265
- app.webiny.request = request;
266
- const plugins = app.webiny.plugins.byType(_api.ContextPlugin.type);
267
-
268
- for (const plugin of plugins) {
269
- await plugin.apply(app.webiny);
99
+ app.addHook("onRoute", (route)=>{
100
+ const method = route.method;
101
+ if (Array.isArray(method)) {
102
+ for (const m of method)addDefinedRoute(m, route.path);
103
+ return;
104
+ }
105
+ addDefinedRoute(method, route.path);
106
+ });
107
+ app.register(cookie, {
108
+ parseOptions: {}
109
+ });
110
+ app.register(compress, {
111
+ global: true,
112
+ threshold: 1024,
113
+ onUnsupportedEncoding: (encoding, _, reply)=>{
114
+ reply.code(406);
115
+ return `We do not support the ${encoding} encoding.`;
116
+ },
117
+ inflateIfDeflated: true
118
+ });
119
+ const routes = {
120
+ defined: definedRoutes,
121
+ onPost: (path, handler, options)=>{
122
+ throwOnDefinedRoute("POST", path, options);
123
+ app.post(path, handler);
124
+ },
125
+ onGet: (path, handler, options)=>{
126
+ throwOnDefinedRoute("GET", path, options);
127
+ app.get(path, handler);
128
+ },
129
+ onOptions: (path, handler, options)=>{
130
+ throwOnDefinedRoute("OPTIONS", path, options);
131
+ app.options(path, handler);
132
+ },
133
+ onDelete: (path, handler, options)=>{
134
+ throwOnDefinedRoute("DELETE", path, options);
135
+ app.delete(path, handler);
136
+ },
137
+ onPatch: (path, handler, options)=>{
138
+ throwOnDefinedRoute("PATCH", path, options);
139
+ app.patch(path, handler);
140
+ },
141
+ onPut: (path, handler, options)=>{
142
+ throwOnDefinedRoute("PUT", path, options);
143
+ app.put(path, handler);
144
+ },
145
+ onAll: (path, handler, options)=>{
146
+ throwOnDefinedRoute("ALL", path, options);
147
+ app.all(path, handler);
148
+ },
149
+ onHead: (path, handler, options)=>{
150
+ throwOnDefinedRoute("HEAD", path, options);
151
+ app.head(path, handler);
152
+ }
153
+ };
154
+ let context;
155
+ const plugins = new PluginsContainer([]);
156
+ plugins.merge(params.plugins || []);
157
+ try {
158
+ context = new Context({
159
+ plugins,
160
+ WEBINY_VERSION: process.env.WEBINY_VERSION,
161
+ routes
162
+ });
163
+ } catch (ex) {
164
+ console.error("Error while constructing the Context.");
165
+ console.error(stringifyError(ex));
166
+ throw ex;
270
167
  }
271
- });
272
- /**
273
- *
274
- */
275
-
276
- app.addHook("preHandler", async () => {
277
- const plugins = app.webiny.plugins.byType(_BeforeHandlerPlugin.BeforeHandlerPlugin.type);
278
-
279
- for (const plugin of plugins) {
280
- await plugin.apply(app.webiny);
168
+ app.decorate("webiny", context);
169
+ app.addContentTypeParser("application/json", {
170
+ parseAs: "string",
171
+ bodyLimit: 1048576
172
+ }, (req, body, done)=>{
173
+ if ("OPTIONS" === req.method) return void done(null, void 0);
174
+ try {
175
+ const json = "string" == typeof body ? body : body.toString("utf8");
176
+ done(null, JSON.parse(json));
177
+ } catch (err) {
178
+ done(err);
179
+ }
180
+ });
181
+ app.addHook("onRequest", async (request)=>{
182
+ if ("OPTIONS" === request.method && void 0 === request.body) request.headers["content-type"] = void 0;
183
+ });
184
+ app.addHook("preHandler", async (request, reply)=>{
185
+ app.webiny.request = request;
186
+ app.webiny.reply = reply;
187
+ if (app.webiny.container) {
188
+ app.webiny.container.registerInstance(Request, request);
189
+ app.webiny.container.registerInstance(Reply, reply);
190
+ }
191
+ reply.code(200);
192
+ const handlerOnRequestPlugins = app.webiny.plugins.byType(HandlerOnRequestPlugin.type);
193
+ const contextPlugins = app.webiny.plugins.byType(ContextPlugin.type);
194
+ const beforeHandlerPlugins = app.webiny.plugins.byType(BeforeHandlerPlugin.type);
195
+ const modifyHeadersPlugins = app.webiny.plugins.byType(ModifyResponseHeadersPlugin.type);
196
+ const registerExtensionPlugins = app.webiny.plugins.byType(RegisterExtensionPlugin.type);
197
+ const preHandler = new PreHandler([
198
+ new RegisterExtensions(registerExtensionPlugins),
199
+ new SetDefaultHeaders(definedRoutes),
200
+ new ProcessHandlerOnRequestPlugins(handlerOnRequestPlugins),
201
+ new IfNotOptionsRequest([
202
+ new ProcessContextPlugins(app.webiny, contextPlugins),
203
+ new ProcessBeforeHandlerPlugins(app.webiny, beforeHandlerPlugins)
204
+ ]),
205
+ new IfOptionsRequest([
206
+ new SendEarlyOptionsResponse(modifyHeadersPlugins)
207
+ ])
208
+ ]);
209
+ await preHandler.execute(request, reply, app.webiny);
210
+ });
211
+ app.addHook("preSerialization", async (_, __, payload)=>{
212
+ const plugins = app.webiny.plugins.byType(HandlerResultPlugin.type);
213
+ let name;
214
+ try {
215
+ for (const plugin of plugins){
216
+ name = plugin.name;
217
+ await plugin.handle(app.webiny, payload);
218
+ }
219
+ } catch (ex) {
220
+ console.error(`Error while running the "HandlerResultPlugin" ${name ? `(${name})` : ""} plugin in the preSerialization hook.`);
221
+ console.error(stringifyError(ex));
222
+ throw ex;
223
+ }
224
+ return payload;
225
+ });
226
+ app.setErrorHandler(async (error, _, reply)=>{
227
+ if (reply.sent) {
228
+ console.warn("Reply already sent, cannot send the result (handler:setErrorHandler).");
229
+ return reply;
230
+ }
231
+ if (error.code?.startsWith("Authentication/")) return reply.status(401).headers({
232
+ "Cache-Control": "no-store"
233
+ }).send(JSON.stringify({
234
+ message: error.message,
235
+ code: error.code
236
+ }));
237
+ if ("Tenancy/TenantDisabled" === error.code) return reply.status(503).headers({
238
+ "Cache-Control": "no-store"
239
+ }).send(JSON.stringify({
240
+ message: error.message,
241
+ code: error.code
242
+ }));
243
+ return reply.status(500).headers({
244
+ "Cache-Control": "no-store"
245
+ }).send(JSON.stringify({
246
+ message: error.message,
247
+ code: error.code,
248
+ data: error.data
249
+ }));
250
+ });
251
+ app.addHook("onError", async (_, reply, error)=>{
252
+ const plugins = app.webiny.plugins.byType(HandlerErrorPlugin.type);
253
+ console.error("Logging error in @webiny/handler");
254
+ try {
255
+ console.error(stringifyError(error));
256
+ } catch (ex) {
257
+ console.warn("Could not stringify error:");
258
+ console.log(error);
259
+ console.error("Stringify error:", ex);
260
+ }
261
+ if (reply.sent) console.warn("Reply already sent, cannot send the result (handler:addHook:onError).");
262
+ else reply.status(500).headers({
263
+ "Cache-Control": "no-store"
264
+ }).send(JSON.stringify({
265
+ message: error.message,
266
+ code: error.code,
267
+ data: error.data
268
+ }));
269
+ const handler = middleware(plugins.map((pl)=>(context, error, next)=>pl.handle(context, error, next)));
270
+ await handler(app.webiny, error);
271
+ return reply;
272
+ });
273
+ app.addHook("onSend", async (request, reply, input)=>{
274
+ modifyResponseHeaders(app, request, reply);
275
+ const plugins = app.webiny.plugins.byType(OnRequestResponseSendPlugin.type);
276
+ let payload = input;
277
+ for (const plugin of plugins)payload = await plugin.exec(request, reply, payload);
278
+ return payload;
279
+ });
280
+ app.addHook("onResponse", async ()=>{
281
+ await context.benchmark.output();
282
+ });
283
+ app.addHook("onTimeout", async (request, reply)=>{
284
+ const plugins = app.webiny.plugins.byType(OnRequestTimeoutPlugin.type);
285
+ for (const plugin of plugins)await plugin.exec(request, reply);
286
+ await context.benchmark.output();
287
+ });
288
+ const modifyPlugins = app.webiny.plugins.byType(ModifyFastifyPlugin.type);
289
+ let modifyFastifyPluginName;
290
+ try {
291
+ for (const plugin of modifyPlugins){
292
+ modifyFastifyPluginName = plugin.name;
293
+ plugin.modify(app);
294
+ }
295
+ } catch (ex) {
296
+ console.error(`Error while running the "ModifyFastifyPlugin" ${modifyFastifyPluginName ? `(${modifyFastifyPluginName})` : ""} plugin in the end of the "createHandler" callable.`);
297
+ console.error(stringifyError(ex));
298
+ throw ex;
281
299
  }
282
- });
283
- /**
284
- *
285
- */
286
-
287
- const preSerialization = async (_, __, payload) => {
288
- const plugins = app.webiny.plugins.byType(_HandlerResultPlugin.HandlerResultPlugin.type);
289
-
290
- for (const plugin of plugins) {
291
- await plugin.handle(app.webiny, payload);
300
+ const routePlugins = app.webiny.plugins.byType(RoutePlugin.type);
301
+ let routePluginName;
302
+ try {
303
+ for (const plugin of routePlugins){
304
+ routePluginName = plugin.name;
305
+ plugin.cb({
306
+ ...app.webiny.routes,
307
+ context: app.webiny
308
+ });
309
+ }
310
+ } catch (ex) {
311
+ console.error(`Error while running the "RoutePlugin" ${routePluginName ? `(${routePluginName})` : ""} plugin in the beginning of the "createHandler" callable.`);
312
+ console.error(stringifyError(ex));
313
+ throw ex;
292
314
  }
293
-
294
- return payload;
295
- };
296
-
297
- app.addHook("preSerialization", preSerialization);
298
- app.addHook("onError", async (_, reply, error) => {
299
- const plugins = app.webiny.plugins.byType(_HandlerErrorPlugin.HandlerErrorPlugin.type); // Log error to cloud, as these can be extremely annoying to debug!
300
-
301
- console.log("@webiny/handler");
302
- console.log(JSON.stringify((0, _objectSpread2.default)((0, _objectSpread2.default)({}, error || {}), {}, {
303
- message: error === null || error === void 0 ? void 0 : error.message,
304
- code: error === null || error === void 0 ? void 0 : error.code
305
- })));
306
- const handler = (0, _middleware.middleware)(plugins.map(pl => {
307
- return (context, error, next) => {
308
- return pl.handle(context, error, next);
309
- };
310
- }));
311
- await handler(app.webiny, error);
312
- return reply.headers({
313
- "Cache-Control": "no-store"
314
- }).status(500);
315
- });
316
- return app;
315
+ return app;
317
316
  };
317
+ export { createHandler };
318
318
 
319
- exports.createHandler = createHandler;
319
+ //# sourceMappingURL=fastify.js.map