@forklaunch/core 0.2.37 → 0.3.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 (222) hide show
  1. package/lib/{src/database/mikro/models/entities/base.entity.d.ts → base.entity-DNfmMOgd.d.mts} +3 -2
  2. package/lib/base.entity-DNfmMOgd.d.ts +27 -0
  3. package/lib/{src/cache/redisTtlCache.d.ts → cache/index.d.mts} +67 -4
  4. package/lib/cache/index.d.ts +130 -0
  5. package/lib/cache/index.js +133 -0
  6. package/lib/cache/index.mjs +105 -0
  7. package/lib/controllers/index.d.mts +5 -0
  8. package/lib/controllers/index.d.ts +5 -0
  9. package/lib/controllers/index.js +18 -0
  10. package/lib/controllers/index.mjs +0 -0
  11. package/lib/database/index.d.mts +37 -0
  12. package/lib/{src/database/mikro/models/entities/mongo.base.entity.d.ts → database/index.d.ts} +5 -2
  13. package/lib/database/index.js +78 -0
  14. package/lib/database/index.mjs +53 -0
  15. package/lib/dtoMapper/index.d.mts +215 -0
  16. package/lib/dtoMapper/index.d.ts +215 -0
  17. package/lib/dtoMapper/index.js +230 -0
  18. package/lib/dtoMapper/index.mjs +202 -0
  19. package/lib/http/index.d.mts +910 -0
  20. package/lib/http/index.d.ts +910 -0
  21. package/lib/http/index.js +2181 -0
  22. package/lib/http/index.mjs +2122 -0
  23. package/lib/services/index.d.mts +64 -0
  24. package/lib/services/index.d.ts +64 -0
  25. package/lib/services/index.js +159 -0
  26. package/lib/services/index.mjs +131 -0
  27. package/package.json +39 -26
  28. package/lib/src/cache/index.d.ts +0 -5
  29. package/lib/src/cache/index.d.ts.map +0 -1
  30. package/lib/src/cache/index.js +0 -4
  31. package/lib/src/cache/interfaces/ttlCache.interface.d.ts +0 -48
  32. package/lib/src/cache/interfaces/ttlCache.interface.d.ts.map +0 -1
  33. package/lib/src/cache/interfaces/ttlCache.interface.js +0 -1
  34. package/lib/src/cache/redisTtlCache.d.ts.map +0 -1
  35. package/lib/src/cache/redisTtlCache.js +0 -98
  36. package/lib/src/cache/types/ttlCacheRecord.types.d.ts +0 -14
  37. package/lib/src/cache/types/ttlCacheRecord.types.d.ts.map +0 -1
  38. package/lib/src/cache/types/ttlCacheRecord.types.js +0 -1
  39. package/lib/src/cache/utils/cacheKey.d.ts +0 -2
  40. package/lib/src/cache/utils/cacheKey.d.ts.map +0 -1
  41. package/lib/src/cache/utils/cacheKey.js +0 -3
  42. package/lib/src/controllers/index.d.ts +0 -2
  43. package/lib/src/controllers/index.d.ts.map +0 -1
  44. package/lib/src/controllers/index.js +0 -1
  45. package/lib/src/controllers/interfaces/controller.interface.d.ts +0 -4
  46. package/lib/src/controllers/interfaces/controller.interface.d.ts.map +0 -1
  47. package/lib/src/controllers/interfaces/controller.interface.js +0 -1
  48. package/lib/src/database/index.d.ts +0 -3
  49. package/lib/src/database/index.d.ts.map +0 -1
  50. package/lib/src/database/index.js +0 -2
  51. package/lib/src/database/mikro/models/entities/base.entity.d.ts.map +0 -1
  52. package/lib/src/database/mikro/models/entities/base.entity.js +0 -42
  53. package/lib/src/database/mikro/models/entities/mongo.base.entity.d.ts.map +0 -1
  54. package/lib/src/database/mikro/models/entities/mongo.base.entity.js +0 -51
  55. package/lib/src/dtoMapper/index.d.ts +0 -3
  56. package/lib/src/dtoMapper/index.d.ts.map +0 -1
  57. package/lib/src/dtoMapper/index.js +0 -2
  58. package/lib/src/dtoMapper/interfaces/dtoMapper.interface.d.ts +0 -18
  59. package/lib/src/dtoMapper/interfaces/dtoMapper.interface.d.ts.map +0 -1
  60. package/lib/src/dtoMapper/interfaces/dtoMapper.interface.js +0 -1
  61. package/lib/src/dtoMapper/models/baseDtoMapper.model.d.ts +0 -72
  62. package/lib/src/dtoMapper/models/baseDtoMapper.model.d.ts.map +0 -1
  63. package/lib/src/dtoMapper/models/baseDtoMapper.model.js +0 -76
  64. package/lib/src/dtoMapper/models/requestDtoMapper.model.d.ts +0 -68
  65. package/lib/src/dtoMapper/models/requestDtoMapper.model.d.ts.map +0 -1
  66. package/lib/src/dtoMapper/models/requestDtoMapper.model.js +0 -71
  67. package/lib/src/dtoMapper/models/responseDtoMapper.model.d.ts +0 -67
  68. package/lib/src/dtoMapper/models/responseDtoMapper.model.d.ts.map +0 -1
  69. package/lib/src/dtoMapper/models/responseDtoMapper.model.js +0 -68
  70. package/lib/src/dtoMapper/types/dtoMapper.types.d.ts +0 -9
  71. package/lib/src/dtoMapper/types/dtoMapper.types.d.ts.map +0 -1
  72. package/lib/src/dtoMapper/types/dtoMapper.types.js +0 -1
  73. package/lib/src/http/application/expressLikeApplication.d.ts +0 -21
  74. package/lib/src/http/application/expressLikeApplication.d.ts.map +0 -1
  75. package/lib/src/http/application/expressLikeApplication.js +0 -21
  76. package/lib/src/http/guards/isConstrainedForklaunchRouter.d.ts +0 -4
  77. package/lib/src/http/guards/isConstrainedForklaunchRouter.d.ts.map +0 -1
  78. package/lib/src/http/guards/isConstrainedForklaunchRouter.js +0 -5
  79. package/lib/src/http/guards/isExpressLikeSchemaHandler.d.ts +0 -5
  80. package/lib/src/http/guards/isExpressLikeSchemaHandler.d.ts.map +0 -1
  81. package/lib/src/http/guards/isExpressLikeSchemaHandler.js +0 -6
  82. package/lib/src/http/guards/isForklaunchExpressLikeRouter.d.ts +0 -5
  83. package/lib/src/http/guards/isForklaunchExpressLikeRouter.d.ts.map +0 -1
  84. package/lib/src/http/guards/isForklaunchExpressLikeRouter.js +0 -6
  85. package/lib/src/http/guards/isForklaunchRouter.d.ts +0 -4
  86. package/lib/src/http/guards/isForklaunchRouter.d.ts.map +0 -1
  87. package/lib/src/http/guards/isForklaunchRouter.js +0 -7
  88. package/lib/src/http/guards/isHttpContractDetails.d.ts +0 -7
  89. package/lib/src/http/guards/isHttpContractDetails.d.ts.map +0 -1
  90. package/lib/src/http/guards/isHttpContractDetails.js +0 -9
  91. package/lib/src/http/guards/isPathParamContractDetails.d.ts +0 -4
  92. package/lib/src/http/guards/isPathParamContractDetails.d.ts.map +0 -1
  93. package/lib/src/http/guards/isPathParamContractDetails.js +0 -10
  94. package/lib/src/http/guards/isResponseShape.d.ts +0 -3
  95. package/lib/src/http/guards/isResponseShape.d.ts.map +0 -1
  96. package/lib/src/http/guards/isResponseShape.js +0 -7
  97. package/lib/src/http/guards/isTypedHandler.d.ts +0 -5
  98. package/lib/src/http/guards/isTypedHandler.d.ts.map +0 -1
  99. package/lib/src/http/guards/isTypedHandler.js +0 -6
  100. package/lib/src/http/handlers/delete.d.ts +0 -9
  101. package/lib/src/http/handlers/delete.d.ts.map +0 -1
  102. package/lib/src/http/handlers/delete.js +0 -4
  103. package/lib/src/http/handlers/get.d.ts +0 -9
  104. package/lib/src/http/handlers/get.d.ts.map +0 -1
  105. package/lib/src/http/handlers/get.js +0 -4
  106. package/lib/src/http/handlers/head.d.ts +0 -9
  107. package/lib/src/http/handlers/head.d.ts.map +0 -1
  108. package/lib/src/http/handlers/head.js +0 -4
  109. package/lib/src/http/handlers/middleware.d.ts +0 -9
  110. package/lib/src/http/handlers/middleware.d.ts.map +0 -1
  111. package/lib/src/http/handlers/middleware.js +0 -4
  112. package/lib/src/http/handlers/options.d.ts +0 -9
  113. package/lib/src/http/handlers/options.d.ts.map +0 -1
  114. package/lib/src/http/handlers/options.js +0 -4
  115. package/lib/src/http/handlers/patch.d.ts +0 -9
  116. package/lib/src/http/handlers/patch.d.ts.map +0 -1
  117. package/lib/src/http/handlers/patch.js +0 -4
  118. package/lib/src/http/handlers/post.d.ts +0 -9
  119. package/lib/src/http/handlers/post.d.ts.map +0 -1
  120. package/lib/src/http/handlers/post.js +0 -4
  121. package/lib/src/http/handlers/put.d.ts +0 -9
  122. package/lib/src/http/handlers/put.d.ts.map +0 -1
  123. package/lib/src/http/handlers/put.js +0 -4
  124. package/lib/src/http/handlers/trace.d.ts +0 -9
  125. package/lib/src/http/handlers/trace.d.ts.map +0 -1
  126. package/lib/src/http/handlers/trace.js +0 -4
  127. package/lib/src/http/handlers/typedAuthHandler.d.ts +0 -5
  128. package/lib/src/http/handlers/typedAuthHandler.d.ts.map +0 -1
  129. package/lib/src/http/handlers/typedAuthHandler.js +0 -3
  130. package/lib/src/http/handlers/typedHandler.d.ts +0 -21
  131. package/lib/src/http/handlers/typedHandler.d.ts.map +0 -1
  132. package/lib/src/http/handlers/typedHandler.js +0 -30
  133. package/lib/src/http/index.d.ts +0 -23
  134. package/lib/src/http/index.d.ts.map +0 -1
  135. package/lib/src/http/index.js +0 -22
  136. package/lib/src/http/interfaces/expressLikeRouter.interface.d.ts +0 -24
  137. package/lib/src/http/interfaces/expressLikeRouter.interface.d.ts.map +0 -1
  138. package/lib/src/http/interfaces/expressLikeRouter.interface.js +0 -1
  139. package/lib/src/http/middleware/request/auth.middleware.d.ts +0 -16
  140. package/lib/src/http/middleware/request/auth.middleware.d.ts.map +0 -1
  141. package/lib/src/http/middleware/request/auth.middleware.js +0 -143
  142. package/lib/src/http/middleware/request/cors.middleware.d.ts +0 -13
  143. package/lib/src/http/middleware/request/cors.middleware.d.ts.map +0 -1
  144. package/lib/src/http/middleware/request/cors.middleware.js +0 -15
  145. package/lib/src/http/middleware/request/createContext.middleware.d.ts +0 -15
  146. package/lib/src/http/middleware/request/createContext.middleware.d.ts.map +0 -1
  147. package/lib/src/http/middleware/request/createContext.middleware.js +0 -26
  148. package/lib/src/http/middleware/request/enrichDetails.middleware.d.ts +0 -15
  149. package/lib/src/http/middleware/request/enrichDetails.middleware.d.ts.map +0 -1
  150. package/lib/src/http/middleware/request/enrichDetails.middleware.js +0 -19
  151. package/lib/src/http/middleware/request/parse.middleware.d.ts +0 -17
  152. package/lib/src/http/middleware/request/parse.middleware.d.ts.map +0 -1
  153. package/lib/src/http/middleware/request/parse.middleware.js +0 -43
  154. package/lib/src/http/middleware/response/parse.middleware.d.ts +0 -31
  155. package/lib/src/http/middleware/response/parse.middleware.d.ts.map +0 -1
  156. package/lib/src/http/middleware/response/parse.middleware.js +0 -52
  157. package/lib/src/http/openApiV3Generator/openApiV3Generator.d.ts +0 -14
  158. package/lib/src/http/openApiV3Generator/openApiV3Generator.d.ts.map +0 -1
  159. package/lib/src/http/openApiV3Generator/openApiV3Generator.js +0 -169
  160. package/lib/src/http/router/expressLikeRouter.d.ts +0 -138
  161. package/lib/src/http/router/expressLikeRouter.d.ts.map +0 -1
  162. package/lib/src/http/router/expressLikeRouter.js +0 -483
  163. package/lib/src/http/types/apiDefinition.types.d.ts +0 -260
  164. package/lib/src/http/types/apiDefinition.types.d.ts.map +0 -1
  165. package/lib/src/http/types/apiDefinition.types.js +0 -1
  166. package/lib/src/http/types/contractDetails.types.d.ts +0 -211
  167. package/lib/src/http/types/contractDetails.types.d.ts.map +0 -1
  168. package/lib/src/http/types/contractDetails.types.js +0 -1
  169. package/lib/src/http/types/expressLikeRouter.types.d.ts +0 -51
  170. package/lib/src/http/types/expressLikeRouter.types.d.ts.map +0 -1
  171. package/lib/src/http/types/expressLikeRouter.types.js +0 -1
  172. package/lib/src/http/types/router.types.d.ts +0 -32
  173. package/lib/src/http/types/router.types.d.ts.map +0 -1
  174. package/lib/src/http/types/router.types.js +0 -1
  175. package/lib/src/http/types/typedHandler.types.d.ts +0 -10
  176. package/lib/src/http/types/typedHandler.types.d.ts.map +0 -1
  177. package/lib/src/http/types/typedHandler.types.js +0 -1
  178. package/lib/src/http/utils/enrichExpressLikeSend.d.ts +0 -32
  179. package/lib/src/http/utils/enrichExpressLikeSend.d.ts.map +0 -1
  180. package/lib/src/http/utils/enrichExpressLikeSend.js +0 -50
  181. package/lib/src/http/utils/httpStatusCodes.d.ts +0 -75
  182. package/lib/src/http/utils/httpStatusCodes.d.ts.map +0 -1
  183. package/lib/src/http/utils/httpStatusCodes.js +0 -1039
  184. package/lib/src/services/configInjector.d.ts +0 -21
  185. package/lib/src/services/configInjector.d.ts.map +0 -1
  186. package/lib/src/services/configInjector.js +0 -90
  187. package/lib/src/services/index.d.ts +0 -5
  188. package/lib/src/services/index.d.ts.map +0 -1
  189. package/lib/src/services/index.js +0 -4
  190. package/lib/src/services/interfaces/baseService.d.ts +0 -15
  191. package/lib/src/services/interfaces/baseService.d.ts.map +0 -1
  192. package/lib/src/services/interfaces/baseService.js +0 -1
  193. package/lib/src/services/types/configInjector.types.d.ts +0 -25
  194. package/lib/src/services/types/configInjector.types.d.ts.map +0 -1
  195. package/lib/src/services/types/configInjector.types.js +0 -6
  196. package/lib/src/services/types/entityManager.types.d.ts +0 -4
  197. package/lib/src/services/types/entityManager.types.d.ts.map +0 -1
  198. package/lib/src/services/types/entityManager.types.js +0 -1
  199. package/lib/tests/configInjector.test.d.ts +0 -2
  200. package/lib/tests/configInjector.test.d.ts.map +0 -1
  201. package/lib/tests/configInjector.test.js +0 -105
  202. package/lib/tests/dtoMapper.test.d.ts +0 -2
  203. package/lib/tests/dtoMapper.test.d.ts.map +0 -1
  204. package/lib/tests/dtoMapper.test.js +0 -170
  205. package/lib/tests/expressLikeRouterInstantiation.test.d.ts +0 -2
  206. package/lib/tests/expressLikeRouterInstantiation.test.d.ts.map +0 -1
  207. package/lib/tests/expressLikeRouterInstantiation.test.js +0 -118
  208. package/lib/tests/http.middleware.test.d.ts +0 -2
  209. package/lib/tests/http.middleware.test.d.ts.map +0 -1
  210. package/lib/tests/http.middleware.test.js +0 -102
  211. package/lib/tests/openApiV3Generator.test.d.ts +0 -2
  212. package/lib/tests/openApiV3Generator.test.d.ts.map +0 -1
  213. package/lib/tests/openApiV3Generator.test.js +0 -66
  214. package/lib/tests/redisTtlCache.test.d.ts +0 -2
  215. package/lib/tests/redisTtlCache.test.d.ts.map +0 -1
  216. package/lib/tests/redisTtlCache.test.js +0 -49
  217. package/lib/tests/typedHandler.test.d.ts +0 -2
  218. package/lib/tests/typedHandler.test.d.ts.map +0 -1
  219. package/lib/tests/typedHandler.test.js +0 -3
  220. package/lib/vitest.config.d.ts +0 -3
  221. package/lib/vitest.config.d.ts.map +0 -1
  222. package/lib/vitest.config.js +0 -7
@@ -0,0 +1,2122 @@
1
+ // src/http/guards/isForklaunchRouter.ts
2
+ function isForklaunchRouter(maybeForklaunchRouter) {
3
+ return maybeForklaunchRouter != null && typeof maybeForklaunchRouter === "object" && "basePath" in maybeForklaunchRouter && "routes" in maybeForklaunchRouter && Array.isArray(maybeForklaunchRouter.routes);
4
+ }
5
+
6
+ // src/http/guards/isConstrainedForklaunchRouter.ts
7
+ function isConstrainedForklaunchRouter(maybeForklaunchExpressLikeRouter) {
8
+ return isForklaunchRouter(maybeForklaunchExpressLikeRouter) && "requestHandler" in maybeForklaunchExpressLikeRouter;
9
+ }
10
+
11
+ // src/http/guards/isExpressLikeSchemaHandler.ts
12
+ import { extractArgumentNames } from "@forklaunch/common";
13
+ function isExpressLikeSchemaHandler(middleware2) {
14
+ const extractedArgumentNames = typeof middleware2 === "function" && new Set(
15
+ extractArgumentNames(middleware2).map(
16
+ (argumentName) => argumentName.toLowerCase()
17
+ )
18
+ );
19
+ return extractedArgumentNames && extractedArgumentNames.size <= 3;
20
+ }
21
+
22
+ // src/http/guards/isForklaunchExpressLikeRouter.ts
23
+ function isForklaunchExpressLikeRouter(maybeForklaunchExpressLikeRouter) {
24
+ return isConstrainedForklaunchRouter(
25
+ maybeForklaunchExpressLikeRouter
26
+ ) && "basePath" in maybeForklaunchExpressLikeRouter && "internal" in maybeForklaunchExpressLikeRouter;
27
+ }
28
+
29
+ // src/http/guards/isPathParamContractDetails.ts
30
+ function isPathParamHttpContractDetails(maybePathParamHttpContractDetails) {
31
+ return maybePathParamHttpContractDetails != null && typeof maybePathParamHttpContractDetails === "object" && "name" in maybePathParamHttpContractDetails && "summary" in maybePathParamHttpContractDetails && "responses" in maybePathParamHttpContractDetails && maybePathParamHttpContractDetails.name != null && maybePathParamHttpContractDetails.summary != null && maybePathParamHttpContractDetails.responses != null;
32
+ }
33
+
34
+ // src/http/guards/isHttpContractDetails.ts
35
+ function isHttpContractDetails(maybeContractDetails) {
36
+ return isPathParamHttpContractDetails(maybeContractDetails) && "body" in maybeContractDetails && maybeContractDetails.body != null;
37
+ }
38
+
39
+ // src/http/guards/isTypedHandler.ts
40
+ function isTypedHandler(maybeTypedHandler) {
41
+ return maybeTypedHandler != null && typeof maybeTypedHandler === "object" && "_typedHandler" in maybeTypedHandler && maybeTypedHandler._typedHandler === true;
42
+ }
43
+
44
+ // src/http/middleware/request/auth.middleware.ts
45
+ import { jwtVerify } from "jose";
46
+ var invalidAuthorizationTokenFormat = [
47
+ 401,
48
+ "Invalid Authorization token format."
49
+ ];
50
+ var invalidAuthorizationSubject = [
51
+ 403,
52
+ "Invalid Authorization subject."
53
+ ];
54
+ var invalidAuthorizationTokenPermissions = [
55
+ 403,
56
+ "Invalid Authorization permissions."
57
+ ];
58
+ var invalidAuthorizationTokenRoles = [
59
+ 403,
60
+ "Invalid Authorization roles."
61
+ ];
62
+ var invalidAuthorizationToken = [
63
+ 403,
64
+ "Invalid Authorization token."
65
+ ];
66
+ var invalidAuthorizationLogin = [
67
+ 403,
68
+ "Invalid Authorization login."
69
+ ];
70
+ async function checkAuthorizationToken(authorizationMethod, authorizationToken, req) {
71
+ if (authorizationToken == null) {
72
+ return [401, "No Authorization token provided."];
73
+ }
74
+ const [tokenPrefix, token] = authorizationToken.split(" ");
75
+ let resourceId;
76
+ switch (authorizationMethod.method) {
77
+ case "jwt": {
78
+ if (tokenPrefix !== "Bearer") {
79
+ return invalidAuthorizationTokenFormat;
80
+ }
81
+ try {
82
+ const decodedJwt = await jwtVerify(
83
+ token,
84
+ new TextEncoder().encode(
85
+ // TODO: Check this at application startup if there is any route with jwt checking
86
+ process.env.JWT_SECRET
87
+ )
88
+ );
89
+ if (!decodedJwt.payload.sub) {
90
+ return invalidAuthorizationSubject;
91
+ }
92
+ resourceId = decodedJwt.payload.sub;
93
+ } catch (error) {
94
+ console.error(error);
95
+ return invalidAuthorizationToken;
96
+ }
97
+ break;
98
+ }
99
+ case "basic": {
100
+ if (authorizationToken !== "Basic") {
101
+ return invalidAuthorizationTokenFormat;
102
+ }
103
+ const [username, password] = Buffer.from(token, "base64").toString("utf-8").split(":");
104
+ if (!username || !password) {
105
+ return invalidAuthorizationTokenFormat;
106
+ }
107
+ if (!authorizationMethod.login(username, password)) {
108
+ return invalidAuthorizationLogin;
109
+ }
110
+ resourceId = username;
111
+ break;
112
+ }
113
+ case "other":
114
+ if (tokenPrefix !== authorizationMethod.tokenPrefix) {
115
+ return invalidAuthorizationTokenFormat;
116
+ }
117
+ resourceId = authorizationMethod.decodeResource(token);
118
+ break;
119
+ }
120
+ if (authorizationMethod.allowedPermissions || authorizationMethod.forbiddenPermissions) {
121
+ if (!authorizationMethod.mapPermissions) {
122
+ return [500, "No permission mapping function provided."];
123
+ }
124
+ const resourcePermissions = await authorizationMethod.mapPermissions(
125
+ resourceId,
126
+ req
127
+ );
128
+ if (authorizationMethod.allowedPermissions) {
129
+ if (resourcePermissions.intersection(authorizationMethod.allowedPermissions).size === 0) {
130
+ return invalidAuthorizationTokenPermissions;
131
+ }
132
+ }
133
+ if (authorizationMethod.forbiddenPermissions) {
134
+ if (resourcePermissions.intersection(
135
+ authorizationMethod.forbiddenPermissions
136
+ ).size !== 0) {
137
+ return invalidAuthorizationTokenPermissions;
138
+ }
139
+ }
140
+ }
141
+ if (authorizationMethod.allowedRoles || authorizationMethod.forbiddenRoles) {
142
+ if (!authorizationMethod.mapRoles) {
143
+ return [500, "No role mapping function provided."];
144
+ }
145
+ const resourceRoles = await authorizationMethod.mapRoles(resourceId, req);
146
+ if (authorizationMethod.allowedRoles) {
147
+ if (resourceRoles.intersection(authorizationMethod.allowedRoles).size === 0) {
148
+ return invalidAuthorizationTokenRoles;
149
+ }
150
+ }
151
+ if (authorizationMethod.forbiddenRoles) {
152
+ if (resourceRoles.intersection(authorizationMethod.forbiddenRoles).size !== 0) {
153
+ return invalidAuthorizationTokenRoles;
154
+ }
155
+ }
156
+ }
157
+ return [401, "Invalid Authorization method."];
158
+ }
159
+ async function parseRequestAuth(req, res, next) {
160
+ console.debug("[MIDDLEWARE] parseRequest started");
161
+ const auth = req.contractDetails.auth;
162
+ if (auth) {
163
+ const errorAndMessage = await checkAuthorizationToken(
164
+ auth,
165
+ req.headers[(auth.method === "other" ? auth.headerName : void 0) ?? "Authorization"],
166
+ req
167
+ );
168
+ if (Array.isArray(errorAndMessage)) {
169
+ res.status(errorAndMessage[0]).send(errorAndMessage[1]);
170
+ next?.(new Error(errorAndMessage[1]));
171
+ }
172
+ }
173
+ next?.();
174
+ }
175
+
176
+ // src/http/middleware/request/cors.middleware.ts
177
+ import corsMiddleware from "cors";
178
+ function cors(req, res, next) {
179
+ console.debug("[MIDDLEWARE] cors started");
180
+ if (req.method === "OPTIONS") {
181
+ res.cors = true;
182
+ }
183
+ corsMiddleware()(req, res, next ?? (() => {
184
+ }));
185
+ }
186
+
187
+ // src/http/middleware/request/createContext.middleware.ts
188
+ import { v4 } from "uuid";
189
+ function createContext(schemaValidator) {
190
+ return (req, res, next) => {
191
+ console.debug("[MIDDLEWARE] createRequestContext started");
192
+ req.schemaValidator = schemaValidator;
193
+ let correlationId = v4();
194
+ if (req.headers["x-correlation-id"]) {
195
+ correlationId = req.headers["x-correlation-id"];
196
+ }
197
+ res.setHeader("x-correlation-id", correlationId);
198
+ req.context = {
199
+ correlationId
200
+ };
201
+ next?.();
202
+ };
203
+ }
204
+
205
+ // src/http/middleware/request/enrichDetails.middleware.ts
206
+ function enrichDetails(contractDetails, requestSchema, responseSchemas) {
207
+ return (req, res, next) => {
208
+ console.debug("[MIDDLEWARE] enrichRequestDetails started");
209
+ req.contractDetails = contractDetails;
210
+ req.requestSchema = requestSchema;
211
+ res.responseSchemas = responseSchemas;
212
+ next?.();
213
+ };
214
+ }
215
+
216
+ // src/http/guards/isResponseShape.ts
217
+ function isResponseShape(maybeResponseShape) {
218
+ return maybeResponseShape != null && "body" in maybeResponseShape && "query" in maybeResponseShape && "params" in maybeResponseShape && "headers" in maybeResponseShape;
219
+ }
220
+
221
+ // src/http/middleware/request/parse.middleware.ts
222
+ function parse(req, _res, next) {
223
+ console.debug("[MIDDLEWARE] parseRequest started");
224
+ const request = {
225
+ params: req.params,
226
+ query: req.query,
227
+ headers: req.headers,
228
+ body: req.body
229
+ };
230
+ const parsedRequest = req.schemaValidator.parse(req.requestSchema, request);
231
+ if (parsedRequest.ok && isResponseShape(parsedRequest.value)) {
232
+ req.body = parsedRequest.value.body;
233
+ req.params = parsedRequest.value.params;
234
+ req.query = parsedRequest.value.query;
235
+ req.headers = parsedRequest.value.headers;
236
+ }
237
+ if (!parsedRequest.ok) {
238
+ switch (req.contractDetails.options?.requestValidation) {
239
+ default:
240
+ case "error":
241
+ next?.(new Error(`Invalid request: ${parsedRequest.error}`));
242
+ break;
243
+ case "warning":
244
+ console.warn(`Invalid request: ${parsedRequest.error}`);
245
+ break;
246
+ case "none":
247
+ break;
248
+ }
249
+ }
250
+ next?.();
251
+ }
252
+
253
+ // src/http/router/expressLikeRouter.ts
254
+ var ForklaunchExpressLikeRouter = class {
255
+ constructor(basePath, schemaValidator, internal) {
256
+ this.schemaValidator = schemaValidator;
257
+ this.internal = internal;
258
+ this.basePath = basePath;
259
+ this.internal.use(createContext(this.schemaValidator));
260
+ this.internal.use(cors);
261
+ }
262
+ requestHandler;
263
+ routers = [];
264
+ routes = [];
265
+ basePath;
266
+ /**
267
+ * Resolves middlewares based on the contract details.
268
+ *
269
+ * @param {PathParamHttpContractDetails<SV> | HttpContractDetails<SV>} contractDetails - The contract details.
270
+ * @returns {MiddlewareHandler<SV>[]} - The resolved middlewares.
271
+ */
272
+ #resolveMiddlewares(contractDetails, requestSchema, responseSchemas) {
273
+ return [
274
+ enrichDetails(contractDetails, requestSchema, responseSchemas),
275
+ parse,
276
+ parseRequestAuth
277
+ ];
278
+ }
279
+ /**
280
+ * Parses and runs the controller handler with error handling.
281
+ *
282
+ * @template P - The type of request parameters.
283
+ * @template ResBodyMap - The type of response body.
284
+ * @template ReqBody - The type of request body.
285
+ * @template ReqQuery - The type of request query.
286
+ * @template LocalsObj - The type of local variables.
287
+ * @template StatusCode - The type of status code.
288
+ * @param {MiddlewareHandler<SV, P, ResBodyMap | string, ReqBody, ReqQuery, LocalsObj, StatusCode>} requestHandler - The request handler.
289
+ * @returns {ExpressMiddlewareHandler} - The Express request handler.
290
+ */
291
+ #parseAndRunControllerHandler(requestHandler) {
292
+ return async (req, res, next) => {
293
+ if (!requestHandler) {
294
+ throw new Error("Controller handler is not defined");
295
+ }
296
+ try {
297
+ await requestHandler(req, res, next);
298
+ } catch (error) {
299
+ next?.(error);
300
+ console.error(error);
301
+ if (!res.headersSent) {
302
+ res.status(500).send("Internal Server Error");
303
+ }
304
+ }
305
+ };
306
+ }
307
+ /**
308
+ * Extracts the controller handler from the provided handlers.
309
+ *
310
+ * @template P - The type of request parameters.
311
+ * @template ResBodyMap - The type of response body.
312
+ * @template ReqBody - The type of request body.
313
+ * @template ReqQuery - The type of request query.
314
+ * @template LocalsObj - The type of local variables.
315
+ * @param {MiddlewareHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The provided handlers.
316
+ * @returns {MiddlewareHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>} - The extracted controller handler.
317
+ * @throws {Error} - Throws an error if the last argument is not a handler.
318
+ */
319
+ #extractControllerHandler(handlers) {
320
+ const controllerHandler = handlers.pop();
321
+ if (typeof controllerHandler !== "function") {
322
+ throw new Error(
323
+ `Last argument must be a handler, received: ${controllerHandler}`
324
+ );
325
+ }
326
+ return controllerHandler;
327
+ }
328
+ #compile(contractDetails) {
329
+ const schemaValidator = this.schemaValidator;
330
+ const requestSchema = schemaValidator.compile(
331
+ schemaValidator.schemify({
332
+ ...contractDetails.params ? { params: contractDetails.params } : {},
333
+ ...contractDetails.requestHeaders ? { headers: contractDetails.requestHeaders } : {},
334
+ ...contractDetails.query ? { query: contractDetails.query } : {},
335
+ ...isHttpContractDetails(contractDetails) && contractDetails.body ? { body: contractDetails.body } : {}
336
+ })
337
+ );
338
+ const responseEntries = {
339
+ 400: schemaValidator.string,
340
+ 401: schemaValidator.string,
341
+ 403: schemaValidator.string,
342
+ 404: schemaValidator.string,
343
+ 500: schemaValidator.string,
344
+ ...isPathParamHttpContractDetails(contractDetails) || isHttpContractDetails(contractDetails) ? { ...contractDetails.responses } : {}
345
+ };
346
+ const responseSchemas = {
347
+ responses: {},
348
+ ...contractDetails.responseHeaders ? {
349
+ headers: schemaValidator.compile(
350
+ schemaValidator.schemify(contractDetails.responseHeaders)
351
+ )
352
+ } : {}
353
+ };
354
+ Object.entries(responseEntries).forEach(([code, responseShape]) => {
355
+ responseSchemas.responses[Number(code)] = schemaValidator.compile(
356
+ schemaValidator.schemify(responseShape)
357
+ );
358
+ });
359
+ return {
360
+ requestSchema,
361
+ responseSchemas
362
+ };
363
+ }
364
+ /**
365
+ * Executes request locally, applying parameters
366
+ *
367
+ * @param handlers {ExpressLikeHandler<SV>}
368
+ * @param controllerHandler
369
+ * @returns
370
+ */
371
+ #localParamRequest(handlers, controllerHandler) {
372
+ return async (route, request) => {
373
+ let statusCode;
374
+ let responseMessage;
375
+ const responseHeaders = {};
376
+ const req = {
377
+ params: request?.params ?? {},
378
+ query: request?.query ?? {},
379
+ headers: request?.headers ?? {},
380
+ body: request?.body ?? {},
381
+ path: route
382
+ };
383
+ const res = {
384
+ status: (code) => {
385
+ statusCode = code;
386
+ return res;
387
+ },
388
+ send: (message) => {
389
+ responseMessage = message;
390
+ },
391
+ json: (body) => {
392
+ responseMessage = body;
393
+ },
394
+ jsonp: (body) => {
395
+ responseMessage = body;
396
+ },
397
+ setHeader: (key, value) => {
398
+ responseHeaders[key] = value;
399
+ }
400
+ };
401
+ let cursor = handlers.shift();
402
+ if (cursor) {
403
+ for (const fn of handlers) {
404
+ await cursor(req, res, (err) => {
405
+ if (err) {
406
+ throw err;
407
+ }
408
+ cursor = fn;
409
+ });
410
+ }
411
+ await cursor(req, res, async (err) => {
412
+ if (err) {
413
+ throw err;
414
+ }
415
+ });
416
+ }
417
+ const cHandler = controllerHandler;
418
+ await cHandler(req, res, (err) => {
419
+ if (err) {
420
+ throw err;
421
+ }
422
+ });
423
+ return {
424
+ code: statusCode,
425
+ response: responseMessage,
426
+ headers: responseHeaders
427
+ };
428
+ };
429
+ }
430
+ registerRoute(method, path, registrationMethod, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareAndTypedHandler) {
431
+ if (isTypedHandler(contractDetailsOrMiddlewareOrTypedHandler)) {
432
+ const { contractDetails, handlers } = contractDetailsOrMiddlewareOrTypedHandler;
433
+ return this.registerRoute(
434
+ method,
435
+ path,
436
+ registrationMethod,
437
+ contractDetails,
438
+ ...handlers
439
+ );
440
+ } else {
441
+ const maybeTypedHandler = middlewareOrMiddlewareAndTypedHandler[middlewareOrMiddlewareAndTypedHandler.length - 1];
442
+ if (isTypedHandler(maybeTypedHandler)) {
443
+ const { contractDetails, handlers } = maybeTypedHandler;
444
+ return this.registerRoute(
445
+ method,
446
+ path,
447
+ registrationMethod,
448
+ contractDetails,
449
+ ...middlewareOrMiddlewareAndTypedHandler.concat(handlers)
450
+ );
451
+ } else {
452
+ if (isExpressLikeSchemaHandler(contractDetailsOrMiddlewareOrTypedHandler) || isTypedHandler(contractDetailsOrMiddlewareOrTypedHandler)) {
453
+ throw new Error("Contract details are not defined");
454
+ }
455
+ const contractDetails = contractDetailsOrMiddlewareOrTypedHandler;
456
+ const handlers = middlewareOrMiddlewareAndTypedHandler.filter(
457
+ (handler) => isExpressLikeSchemaHandler(handler)
458
+ );
459
+ if (!isHttpContractDetails(contractDetails) && !isPathParamHttpContractDetails(contractDetails)) {
460
+ throw new Error(
461
+ "Contract details are malformed for route definition"
462
+ );
463
+ }
464
+ this.routes.push({
465
+ basePath: this.basePath,
466
+ path,
467
+ method,
468
+ contractDetails
469
+ });
470
+ const { requestSchema, responseSchemas } = this.#compile(contractDetails);
471
+ const controllerHandler = this.#extractControllerHandler(handlers);
472
+ registrationMethod.bind(this.internal)(
473
+ path,
474
+ ...this.#resolveMiddlewares(contractDetails, requestSchema, responseSchemas).concat(
475
+ handlers
476
+ ),
477
+ this.#parseAndRunControllerHandler(controllerHandler)
478
+ );
479
+ return this.#localParamRequest(
480
+ handlers,
481
+ controllerHandler
482
+ );
483
+ }
484
+ }
485
+ }
486
+ #extractHandlers(handlers, processMiddleware) {
487
+ const last = handlers.pop();
488
+ let finalHandlers = last ? [last] : [];
489
+ if (isTypedHandler(last)) {
490
+ finalHandlers = last.handlers;
491
+ }
492
+ handlers.forEach((handler) => {
493
+ if (isTypedHandler(handler)) {
494
+ throw new Error(
495
+ "Only the last argument supplied to this function can be a typed handler. Please use only middleware."
496
+ );
497
+ }
498
+ });
499
+ const middleware2 = processMiddleware ? handlers.map(processMiddleware) : handlers;
500
+ return [...middleware2, ...finalHandlers];
501
+ }
502
+ #extractMiddlewareFromEnrichedTypedHandlerArray(handlers) {
503
+ return this.#extractHandlers(handlers);
504
+ }
505
+ #extractNestableMiddlewareFromEnrichedTypedHandlerArray(handlers) {
506
+ return this.#extractHandlers(
507
+ handlers,
508
+ (handler) => isForklaunchExpressLikeRouter(handler) ? handler.internal : handler
509
+ );
510
+ }
511
+ #processTypedHandlerOrMiddleware(handler, middleware2) {
512
+ if (isTypedHandler(handler)) {
513
+ middleware2.push(...handler.handlers);
514
+ } else if (isExpressLikeSchemaHandler(handler)) {
515
+ middleware2.push(handler);
516
+ }
517
+ }
518
+ #extractMiddlewareAsRouterHandlers(contractDetailsOrMiddlewareOrTypedHandler, middlewareOrMiddlewareWithTypedHandler) {
519
+ const middleware2 = [];
520
+ this.#processTypedHandlerOrMiddleware(contractDetailsOrMiddlewareOrTypedHandler, middleware2);
521
+ middleware2.push(
522
+ ...this.#extractMiddlewareFromEnrichedTypedHandlerArray(middlewareOrMiddlewareWithTypedHandler)
523
+ );
524
+ return middleware2;
525
+ }
526
+ #extractNestableMiddlewareAsRouterHandlers(contractDetailsOrMiddlewareOrTypedHandler, middlewareOrMiddlewareWithTypedHandler) {
527
+ const middleware2 = [];
528
+ this.#processTypedHandlerOrMiddleware(
529
+ contractDetailsOrMiddlewareOrTypedHandler,
530
+ middleware2
531
+ );
532
+ if (isForklaunchExpressLikeRouter(
533
+ contractDetailsOrMiddlewareOrTypedHandler
534
+ )) {
535
+ middleware2.push(contractDetailsOrMiddlewareOrTypedHandler.internal);
536
+ }
537
+ middleware2.push(
538
+ ...this.#extractNestableMiddlewareFromEnrichedTypedHandlerArray(middlewareOrMiddlewareWithTypedHandler)
539
+ );
540
+ return middleware2;
541
+ }
542
+ registerMiddlewareHandler(registrationMethod, pathOrContractDetailsOrMiddlewareOrTypedHandler, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) {
543
+ const middleware2 = [];
544
+ if (typeof pathOrContractDetailsOrMiddlewareOrTypedHandler === "string") {
545
+ middleware2.push(
546
+ ...this.#extractMiddlewareAsRouterHandlers(
547
+ contractDetailsOrMiddlewareOrTypedHandler,
548
+ middlewareOrMiddlewareWithTypedHandler
549
+ )
550
+ );
551
+ const path = pathOrContractDetailsOrMiddlewareOrTypedHandler;
552
+ registrationMethod.bind(this.internal)(path, ...middleware2);
553
+ } else {
554
+ middleware2.push(
555
+ ...this.#extractMiddlewareAsRouterHandlers(
556
+ pathOrContractDetailsOrMiddlewareOrTypedHandler,
557
+ (isExpressLikeSchemaHandler(contractDetailsOrMiddlewareOrTypedHandler) || isTypedHandler(contractDetailsOrMiddlewareOrTypedHandler) ? [contractDetailsOrMiddlewareOrTypedHandler] : []).concat(middlewareOrMiddlewareWithTypedHandler)
558
+ )
559
+ );
560
+ registrationMethod.bind(this.internal)(...middleware2);
561
+ }
562
+ return this;
563
+ }
564
+ registerNestableMiddlewareHandler(registrationMethod, pathOrContractDetailsOrMiddlewareOrTypedHandler, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) {
565
+ const middleware2 = [];
566
+ let path;
567
+ if (typeof pathOrContractDetailsOrMiddlewareOrTypedHandler === "string") {
568
+ middleware2.push(
569
+ ...this.#extractNestableMiddlewareAsRouterHandlers(
570
+ contractDetailsOrMiddlewareOrTypedHandler,
571
+ middlewareOrMiddlewareWithTypedHandler
572
+ )
573
+ );
574
+ path = pathOrContractDetailsOrMiddlewareOrTypedHandler;
575
+ } else {
576
+ if (isConstrainedForklaunchRouter(
577
+ pathOrContractDetailsOrMiddlewareOrTypedHandler
578
+ )) {
579
+ path = pathOrContractDetailsOrMiddlewareOrTypedHandler.basePath;
580
+ }
581
+ middleware2.push(
582
+ ...this.#extractNestableMiddlewareAsRouterHandlers(
583
+ pathOrContractDetailsOrMiddlewareOrTypedHandler,
584
+ (isExpressLikeSchemaHandler(contractDetailsOrMiddlewareOrTypedHandler) || isTypedHandler(contractDetailsOrMiddlewareOrTypedHandler) || isConstrainedForklaunchRouter(
585
+ contractDetailsOrMiddlewareOrTypedHandler
586
+ ) ? [contractDetailsOrMiddlewareOrTypedHandler] : []).concat(middlewareOrMiddlewareWithTypedHandler)
587
+ )
588
+ );
589
+ }
590
+ if (path) {
591
+ registrationMethod.bind(this.internal)(path, ...middleware2);
592
+ } else {
593
+ registrationMethod.bind(this.internal)(...middleware2);
594
+ }
595
+ return this;
596
+ }
597
+ use = (pathOrContractDetailsOrMiddlewareOrTypedHandler, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
598
+ [
599
+ pathOrContractDetailsOrMiddlewareOrTypedHandler,
600
+ contractDetailsOrMiddlewareOrTypedHandler,
601
+ ...middlewareOrMiddlewareWithTypedHandler
602
+ ].forEach((arg) => {
603
+ if (isForklaunchRouter(arg)) {
604
+ this.routers.push(arg);
605
+ }
606
+ });
607
+ return this.registerNestableMiddlewareHandler(
608
+ this.internal.use,
609
+ pathOrContractDetailsOrMiddlewareOrTypedHandler,
610
+ contractDetailsOrMiddlewareOrTypedHandler,
611
+ ...middlewareOrMiddlewareWithTypedHandler
612
+ );
613
+ };
614
+ all = (pathOrContractDetailsOrMiddlewareOrTypedHandler, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
615
+ return this.registerMiddlewareHandler(
616
+ this.internal.all,
617
+ pathOrContractDetailsOrMiddlewareOrTypedHandler,
618
+ contractDetailsOrMiddlewareOrTypedHandler,
619
+ ...middlewareOrMiddlewareWithTypedHandler
620
+ );
621
+ };
622
+ connect = (pathOrContractDetailsOrMiddlewareOrTypedHandler, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
623
+ return this.registerMiddlewareHandler(
624
+ this.internal.connect,
625
+ pathOrContractDetailsOrMiddlewareOrTypedHandler,
626
+ contractDetailsOrMiddlewareOrTypedHandler,
627
+ ...middlewareOrMiddlewareWithTypedHandler
628
+ );
629
+ };
630
+ /**
631
+ * Registers a GET route with the specified contract details and handler handlers.
632
+ *
633
+ * @template P - The type of request parameters.
634
+ * @template ResBodyMap - The type of response body.
635
+ * @template ReqBody - The type of request body.
636
+ * @template ReqQuery - The type of request query.
637
+ * @template LocalsObj - The type of local variables.
638
+ * @param {string} path - The path for the route.
639
+ * @param {PathParamHttpContractDetails<SV, P, ResBodyMap, ReqQuery>} contractDetails - The contract details.
640
+ * @param {...SchemaHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The handler handlers.
641
+ * @returns {ExpressRouter} - The Express router.
642
+ */
643
+ get = (path, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
644
+ return {
645
+ get: this.registerRoute(
646
+ "get",
647
+ path,
648
+ this.internal.get,
649
+ contractDetailsOrMiddlewareOrTypedHandler,
650
+ ...middlewareOrMiddlewareWithTypedHandler
651
+ )
652
+ };
653
+ };
654
+ /**
655
+ * Registers a POST route with the specified contract details and handler handlers.
656
+ *
657
+ * @template P - The type of request parameters.
658
+ * @template ResBodyMap - The type of response body.
659
+ * @template ReqBody - The type of request body.
660
+ * @template ReqQuery - The type of request query.
661
+ * @template LocalsObj - The type of local variables.
662
+ * @param {string} path - The path for the route.
663
+ * @param {HttpContractDetails<SV, P, ResBodyMap, ReqBody, ReqQuery>} contractDetails - The contract details.
664
+ * @param {...SchemaHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The handler handlers.
665
+ * @returns {ExpressRouter} - The Expxwress router.
666
+ */
667
+ post = (path, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
668
+ return {
669
+ post: this.registerRoute(
670
+ "post",
671
+ path,
672
+ this.internal.post,
673
+ contractDetailsOrMiddlewareOrTypedHandler,
674
+ ...middlewareOrMiddlewareWithTypedHandler
675
+ )
676
+ };
677
+ };
678
+ /**
679
+ * Registers a PUT route with the specified contract details and handler handlers.
680
+ *
681
+ * @template P - The type of request parameters.
682
+ * @template ResBodyMap - The type of response body.
683
+ * @template ReqBody - The type of request body.
684
+ * @template ReqQuery - The type of request query.
685
+ * @template LocalsObj - The type of local variables.
686
+ * @param {string} path - The path for the route.
687
+ * @param {HttpContractDetails<SV, P, ResBodyMap, ReqBody, ReqQuery>} contractDetails - The contract details.
688
+ * @param {...SchemaHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The handler handlers.
689
+ * @returns {ExpressRouter} - The Express router.
690
+ */
691
+ put = (path, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
692
+ return {
693
+ put: this.registerRoute(
694
+ "put",
695
+ path,
696
+ this.internal.put,
697
+ contractDetailsOrMiddlewareOrTypedHandler,
698
+ ...middlewareOrMiddlewareWithTypedHandler
699
+ )
700
+ };
701
+ };
702
+ /**
703
+ * Registers a PATCH route with the specified contract details and handler handlers.
704
+ *
705
+ * @template P - The type of request parameters.
706
+ * @template ResBodyMap - The type of response body.
707
+ * @template ReqBody - The type of request body.
708
+ * @template ReqQuery - The type of request query.
709
+ * @template LocalsObj - The type of local variables.
710
+ * @param {string} path - The path for the route.
711
+ * @param {HttpContractDetails<SV, P, ResBodyMap, ReqBody, ReqQuery>} contractDetails - The contract details.
712
+ * @param {...SchemaHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The handler handlers.
713
+ * @returns {ExpressRouter} - The Express router.
714
+ */
715
+ patch = (path, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
716
+ return {
717
+ patch: this.registerRoute(
718
+ "patch",
719
+ path,
720
+ this.internal.patch,
721
+ contractDetailsOrMiddlewareOrTypedHandler,
722
+ ...middlewareOrMiddlewareWithTypedHandler
723
+ )
724
+ };
725
+ };
726
+ /**
727
+ * Registers a DELETE route with the specified contract details and handler handlers.
728
+ *
729
+ * @template P - The type of request parameters.
730
+ * @template ResBodyMap - The type of response body.
731
+ * @template ReqBody - The type of request body.
732
+ * @template ReqQuery - The type of request query.
733
+ * @template LocalsObj - The type of local variables.
734
+ * @param {string} path - The path for the route.
735
+ * @param {PathParamHttpContractDetails<SV, P, ResBodyMap, ReqQuery>} contractDetails - The contract details.
736
+ * @param {...SchemaHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The handler handlers.
737
+ * @returns {ExpressRouter} - The Express router.
738
+ */
739
+ delete = (path, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
740
+ return {
741
+ delete: this.registerRoute(
742
+ "delete",
743
+ path,
744
+ this.internal.delete,
745
+ contractDetailsOrMiddlewareOrTypedHandler,
746
+ ...middlewareOrMiddlewareWithTypedHandler
747
+ )
748
+ };
749
+ };
750
+ /**
751
+ * Registers a OPTIONS route with the specified contract details and handler handlers.
752
+ *
753
+ * @template P - The type of request parameters.
754
+ * @template ResBodyMap - The type of response body.
755
+ * @template ReqBody - The type of request body.
756
+ * @template ReqQuery - The type of request query.
757
+ * @template LocalsObj - The type of local variables.
758
+ * @param {string} path - The path for the route.
759
+ * @param {PathParamHttpContractDetails<SV, P, ResBodyMap, ReqQuery>} contractDetails - The contract details.
760
+ * @param {...SchemaHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The handler handlers.
761
+ * @returns {ExpressRouter} - The Express router.
762
+ */
763
+ options = (path, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
764
+ return {
765
+ options: this.registerRoute(
766
+ "options",
767
+ path,
768
+ this.internal.options,
769
+ contractDetailsOrMiddlewareOrTypedHandler,
770
+ ...middlewareOrMiddlewareWithTypedHandler
771
+ )
772
+ };
773
+ };
774
+ /**
775
+ * Registers a HEAD route with the specified contract details and handler handlers.
776
+ *
777
+ * @template P - The type of request parameters.
778
+ * @template ResBodyMap - The type of response body.
779
+ * @template ReqBody - The type of request body.
780
+ * @template ReqQuery - The type of request query.
781
+ * @template LocalsObj - The type of local variables.
782
+ * @param {string} path - The path for the route.
783
+ * @param {PathParamHttpContractDetails<SV, P, ResBodyMap, ReqQuery>} contractDetails - The contract details.
784
+ * @param {...SchemaHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The handler handlers.
785
+ * @returns {ExpressRouter} - The Express router.
786
+ */
787
+ head = (path, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
788
+ return {
789
+ head: this.registerRoute(
790
+ "head",
791
+ path,
792
+ this.internal.head,
793
+ contractDetailsOrMiddlewareOrTypedHandler,
794
+ ...middlewareOrMiddlewareWithTypedHandler
795
+ )
796
+ };
797
+ };
798
+ /**
799
+ * Registers a TRACE route with the specified contract details and handler handlers.
800
+ *
801
+ * @template P - The type of request parameters.
802
+ * @template ResBodyMap - The type of response body.
803
+ * @template ReqBody - The type of request body.
804
+ * @template ReqQuery - The type of request query.
805
+ * @template LocalsObj - The type of local variables.
806
+ * @param {string} path - The path for the route.
807
+ * @param {PathParamHttpContractDetails<SV, P, ResBodyMap, ReqQuery>} contractDetails - The contract details.
808
+ * @param {...SchemaHandler<SV, P, ResBodyMap, ReqBody, ReqQuery, LocalsObj>[]} handlers - The handler handlers.
809
+ * @returns {ExpressRouter} - The Express router.
810
+ */
811
+ trace = (path, contractDetailsOrMiddlewareOrTypedHandler, ...middlewareOrMiddlewareWithTypedHandler) => {
812
+ return {
813
+ trace: this.registerRoute(
814
+ "trace",
815
+ path,
816
+ this.internal.trace,
817
+ contractDetailsOrMiddlewareOrTypedHandler,
818
+ ...middlewareOrMiddlewareWithTypedHandler
819
+ )
820
+ };
821
+ };
822
+ };
823
+
824
+ // src/http/application/expressLikeApplication.ts
825
+ var ForklaunchExpressLikeApplication = class extends ForklaunchExpressLikeRouter {
826
+ /**
827
+ * Creates an instance of the Application class.
828
+ *
829
+ * @param {SV} schemaValidator - The schema validator.
830
+ */
831
+ constructor(schemaValidator, internal) {
832
+ super("/", schemaValidator, internal);
833
+ this.schemaValidator = schemaValidator;
834
+ this.internal = internal;
835
+ }
836
+ };
837
+
838
+ // src/http/handlers/typedHandler.ts
839
+ function typedHandler(_schemaValidator, _pathOrContractDetails, contractMethodOrContractDetails, contractDetailsOrHandler, ...handlerArray) {
840
+ let contractDetails;
841
+ let handlers;
842
+ if (typeof contractMethodOrContractDetails === "string") {
843
+ if (typeof contractDetailsOrHandler !== "function") {
844
+ contractDetails = contractDetailsOrHandler;
845
+ } else {
846
+ throw new Error("Invalid definition for contract details");
847
+ }
848
+ handlers = handlerArray;
849
+ } else {
850
+ contractDetails = contractMethodOrContractDetails;
851
+ if (typeof contractDetailsOrHandler === "function") {
852
+ handlers = [contractDetailsOrHandler, ...handlerArray];
853
+ } else {
854
+ throw new Error("Invalid definition for handler");
855
+ }
856
+ }
857
+ return {
858
+ _typedHandler: true,
859
+ contractDetails,
860
+ handlers
861
+ };
862
+ }
863
+
864
+ // src/http/handlers/delete.ts
865
+ var delete_ = (_schemaValidator, path, contractDetails, ...handlers) => {
866
+ return typedHandler(_schemaValidator, path, "delete", contractDetails, ...handlers);
867
+ };
868
+
869
+ // src/http/handlers/get.ts
870
+ var get = (_schemaValidator, path, contractDetails, ...handlers) => {
871
+ return typedHandler(_schemaValidator, path, "get", contractDetails, ...handlers);
872
+ };
873
+
874
+ // src/http/handlers/head.ts
875
+ var head = (_schemaValidator, path, contractDetails, ...handlers) => {
876
+ return typedHandler(_schemaValidator, path, "head", contractDetails, ...handlers);
877
+ };
878
+
879
+ // src/http/handlers/middleware.ts
880
+ var middleware = (_schemaValidator, path, contractDetails, ...handlers) => {
881
+ return typedHandler(_schemaValidator, path, "middleware", contractDetails, ...handlers);
882
+ };
883
+
884
+ // src/http/handlers/options.ts
885
+ var options = (_schemaValidator, path, contractDetails, ...handlers) => {
886
+ return typedHandler(_schemaValidator, path, "options", contractDetails, ...handlers);
887
+ };
888
+
889
+ // src/http/handlers/patch.ts
890
+ var patch = (_schemaValidator, path, contractDetails, ...handlers) => {
891
+ return typedHandler(_schemaValidator, path, "patch", contractDetails, ...handlers);
892
+ };
893
+
894
+ // src/http/handlers/post.ts
895
+ var post = (_schemaValidator, path, contractDetails, ...handlers) => {
896
+ return typedHandler(_schemaValidator, path, "post", contractDetails, ...handlers);
897
+ };
898
+
899
+ // src/http/handlers/put.ts
900
+ var put = (_schemaValidator, path, contractDetails, ...handlers) => {
901
+ return typedHandler(_schemaValidator, path, "put", contractDetails, ...handlers);
902
+ };
903
+
904
+ // src/http/handlers/trace.ts
905
+ var trace = (_schemaValidator, path, contractDetails, ...handlers) => {
906
+ return typedHandler(_schemaValidator, path, "trace", contractDetails, ...handlers);
907
+ };
908
+
909
+ // src/http/utils/httpStatusCodes.ts
910
+ var HTTPStatuses = {
911
+ /**
912
+ * The initial part of a request has been received and has not yet been
913
+ * rejected by the server. The server intends to send a final response after
914
+ * the request has been fully received and acted upon.
915
+ *
916
+ * When the request contains an Expect header field that includes a
917
+ * 100-continue expectation, the 100 response indicates that the server
918
+ * wishes to receive the request payload body. The client ought to continue
919
+ * sending the request and discard the 100 response.
920
+ *
921
+ * If the request did not contain an Expect header field containing the
922
+ * 100-continue expectation, the client can simply discard this interim
923
+ * response.
924
+ */
925
+ 100: "Continue",
926
+ /**
927
+ * The server understands and is willing to comply with the client's request,
928
+ * via the Upgrade header field, for a change in the application protocol
929
+ * being used on this connection.
930
+ *
931
+ * The server MUST generate an Upgrade header field in the response that
932
+ * indicates which protocol(s) will be switched to immediately after the
933
+ * empty line that terminates the 101 response.
934
+ *
935
+ * It is assumed that the server will only agree to switch protocols when it
936
+ * is advantageous to do so. For example, switching to a newer version of
937
+ * HTTP might be advantageous over older versions, and switching to a
938
+ * real-time, synchronous protocol might be advantageous when delivering
939
+ * resources that use such features.
940
+ */
941
+ 101: "Switching Protocols",
942
+ /**
943
+ * An interim response used to inform the client that the server has accepted
944
+ * the complete request, but has not yet completed it.
945
+ *
946
+ * This status code SHOULD only be sent when the server has a reasonable
947
+ * expectation that the request will take significant time to complete. As
948
+ * guidance, if a method is taking longer than 20 seconds (a reasonable, but
949
+ * arbitrary value) to process the server SHOULD return a 102 (Processing)
950
+ * response. The server MUST send a final response after the request has been
951
+ * completed.
952
+ *
953
+ * Methods can potentially take a long period of time to process, especially
954
+ * methods that support the Depth header. In such cases the client may
955
+ * time-out the connection while waiting for a response. To prevent this the
956
+ * server may return a 102 Processing status code to indicate to the client
957
+ * that the server is still processing the method.
958
+ */
959
+ 102: "Processing",
960
+ /**
961
+ * The request has succeeded.
962
+ *
963
+ * Aside from responses to CONNECT, a 200 response always has a payload,
964
+ * though an origin server MAY generate a payload body of zero length. If no
965
+ * payload is desired, an origin server ought to send 204 No Content instead.
966
+ * For CONNECT, no payload is allowed because the successful result is a
967
+ * tunnel, which begins immediately after the 200 response header section.
968
+ *
969
+ * A 200 response is cacheable by default; i.e., unless otherwise indicated
970
+ * by the method definition or explicit cache controls.
971
+ */
972
+ 200: "OK",
973
+ /**
974
+ * The request has been fulfilled and has resulted in one or more new
975
+ * resources being created.
976
+ *
977
+ * The primary resource created by the request is identified by either a
978
+ * Location header field in the response or, if no Location field is
979
+ * received, by the effective request URI.
980
+ *
981
+ * The 201 response payload typically describes and links to the resource(s)
982
+ * created. See Section 7.2 of RFC7231 for a discussion of the meaning and
983
+ * purpose of validator header fields, such as ETag and Last-Modified, in a
984
+ * 201 response.
985
+ */
986
+ 201: "Created",
987
+ /**
988
+ * The request has been accepted for processing, but the processing has not
989
+ * been completed. The request might or might not eventually be acted upon,
990
+ * as it might be disallowed when processing actually takes place.
991
+ *
992
+ * There is no facility in HTTP for re-sending a status code from an
993
+ * asynchronous operation.
994
+ *
995
+ * The 202 response is intentionally noncommittal. Its purpose is to allow a
996
+ * server to accept a request for some other process (perhaps a
997
+ * batch-oriented process that is only run once per day) without requiring
998
+ * that the user agent's connection to the server persist until the process
999
+ * is completed. The representation sent with this response ought to describe
1000
+ * the request's current status and point to (or embed) a status monitor that
1001
+ * can provide the user with an estimate of when the request will be
1002
+ * fulfilled.
1003
+ */
1004
+ 202: "Accepted",
1005
+ /**
1006
+ * The request was successful but the enclosed payload has been modified from
1007
+ * that of the origin server's 200 OK response by a transforming proxy.
1008
+ *
1009
+ * This status code allows the proxy to notify recipients when a
1010
+ * transformation has been applied, since that knowledge might impact later
1011
+ * decisions regarding the content. For example, future cache validation
1012
+ * requests for the content might only be applicable along the same request
1013
+ * path (through the same proxies).
1014
+ *
1015
+ * The 203 response is similar to the Warning code of 214 Transformation
1016
+ * Applied, which has the advantage of being applicable to responses with any
1017
+ * status code.
1018
+ *
1019
+ * A 203 response is cacheable by default; i.e., unless otherwise indicated
1020
+ * by the method definition or explicit cache controls.
1021
+ */
1022
+ 203: "Non-authoritative Information",
1023
+ /**
1024
+ * The server has successfully fulfilled the request and that there is no
1025
+ * additional content to send in the response payload body.
1026
+ *
1027
+ * Metadata in the response header fields refer to the target resource and
1028
+ * its selected representation after the requested action was applied.
1029
+ *
1030
+ * A 204 response is terminated by the first empty line after the header
1031
+ * fields because it cannot contain a message body.
1032
+ *
1033
+ * A 204 response is cacheable by default; i.e., unless otherwise indicated
1034
+ * by the method definition or explicit cache controls.
1035
+ */
1036
+ 204: "No Content",
1037
+ /**
1038
+ * He server has fulfilled the request and desires that the user agent reset
1039
+ * the "document view", which caused the request to be sent, to its original
1040
+ * state as received from the origin server.
1041
+ *
1042
+ * This response is intended to support a common data entry use case where
1043
+ * the user receives content that supports data entry (a form, notepad,
1044
+ * canvas, etc.), enters or manipulates data in that space, causes the
1045
+ * entered data to be submitted in a request, and then the data entry
1046
+ * mechanism is reset for the next entry so that the user can easily
1047
+ * initiate another input action.
1048
+ *
1049
+ * Since the 205 status code implies that no additional content will be
1050
+ * provided, a server MUST NOT generate a payload in a 205 response. In
1051
+ * other words, a server MUST do one of the following for a 205 response: a)
1052
+ * indicate a zero-length body for the response by including a
1053
+ * Content-Length header field with a value of 0; b) indicate a zero-length
1054
+ * payload for the response by including a Transfer-Encoding header field
1055
+ * with a value of chunked and a message body consisting of a single chunk
1056
+ * of zero-length; or, c) close the connection immediately after sending the
1057
+ * blank line terminating the header section.
1058
+ */
1059
+ 205: "Reset Content",
1060
+ /**
1061
+ * The server is successfully fulfilling a range request for the target
1062
+ * resource by transferring one or more parts of the selected representation
1063
+ * that correspond to the satisfiable ranges found in the request's Range
1064
+ * header field.
1065
+ *
1066
+ * If a single part is being transferred, the server generating the 206
1067
+ * response MUST generate a Content-Range header field, describing what range
1068
+ * of the selected representation is enclosed, and a payload consisting of
1069
+ * the range.
1070
+ *
1071
+ * If multiple parts are being transferred, the server generating the 206
1072
+ * response MUST generate a "multipart/byteranges" payload2, and a
1073
+ * Content-Type header field containing the multipart/byteranges media type
1074
+ * and its required boundary parameter. To avoid confusion with single-part
1075
+ * responses, a server MUST NOT generate a Content-Range header field in the
1076
+ * HTTP header section of a multiple part response (this field will be sent
1077
+ * in each part instead).
1078
+ *
1079
+ * Within the header area of each body part in the multipart payload, the
1080
+ * server MUST generate a Content-Range header field corresponding to the
1081
+ * range being enclosed in that body part. If the selected representation
1082
+ * would have had a Content-Type header field in a 200 OK response, the
1083
+ * server SHOULD generate that same Content-Type field in the header area of
1084
+ * each body part.
1085
+ *
1086
+ * When multiple ranges are requested, a server MAY coalesce any of the
1087
+ * ranges that overlap, or that are separated by a gap that is smaller than
1088
+ * the overhead of sending multiple parts, regardless of the order in which
1089
+ * the corresponding byte-range-spec appeared in the received Range header
1090
+ * field. Since the typical overhead between parts of a multipart/byteranges
1091
+ * payload is around 80 bytes, depending on the selected representation's
1092
+ * media type and the chosen boundary parameter length, it can be less
1093
+ * efficient to transfer many small disjoint parts than it is to transfer the
1094
+ * entire selected representation.
1095
+ *
1096
+ * A server MUST NOT generate a multipart response to a request for a single
1097
+ * range, since a client that does not request multiple parts might not
1098
+ * support multipart responses. However, a server MAY generate a
1099
+ * multipart/byteranges payload with only a single body part if multiple
1100
+ * ranges were requested and only one range was found to be satisfiable or
1101
+ * only one range remained after coalescing. A client that cannot process a
1102
+ * multipart/byteranges response MUST NOT generate a request that asks for
1103
+ * multiple ranges.
1104
+ *
1105
+ * When a multipart response payload is generated, the server SHOULD send the
1106
+ * parts in the same order that the corresponding byte-range-spec appeared in
1107
+ * the received Range header field, excluding those ranges that were deemed
1108
+ * unsatisfiable or that were coalesced into other ranges. A client that
1109
+ * receives a multipart response MUST inspect the Content-Range header field
1110
+ * present in each body part in order to determine which range is contained
1111
+ * in that body part; a client cannot rely on receiving the same ranges that
1112
+ * it requested, nor the same order that it requested.
1113
+ *
1114
+ * When a 206 response is generated, the server MUST generate the following
1115
+ * header fields, in addition to those required above, if the field would
1116
+ * have been sent in a 200 OK response to the same request: Date,
1117
+ * Cache-Control, ETag, Expires, Content-Location, and Vary.
1118
+ *
1119
+ * If a 206 is generated in response to a request with an If-Range header
1120
+ * field, the sender SHOULD NOT generate other representation header fields
1121
+ * beyond those required above, because the client is understood to already
1122
+ * have a prior response containing those header fields. Otherwise, the
1123
+ * sender MUST generate all of the representation header fields that would
1124
+ * have been sent in a 200 OK response to the same request.
1125
+ *
1126
+ * A 206 response is cacheable by default; i.e., unless otherwise indicated
1127
+ * by explicit cache controls.
1128
+ */
1129
+ 206: "Partial Content",
1130
+ /**
1131
+ * A Multi-Status response conveys information about multiple resources in
1132
+ * situations where multiple status codes might be appropriate.
1133
+ *
1134
+ * The default Multi-Status response body is a text/xml or application/xml
1135
+ * HTTP entity with a 'multistatus' root element. Further elements contain
1136
+ * 200, 300, 400, and 500 series status codes generated during the method
1137
+ * invocation. 100 series status codes SHOULD NOT be recorded in a 'response'
1138
+ * XML element.
1139
+ *
1140
+ * Although '207' is used as the overall response status code, the recipient
1141
+ * needs to consult the contents of the multistatus response body for further
1142
+ * information about the success or failure of the method execution. The
1143
+ * response MAY be used in success, partial success and also in failure
1144
+ * situations.
1145
+ *
1146
+ * The 'multistatus' root element holds zero or more 'response' elements in
1147
+ * any order, each with information about an individual resource. Each
1148
+ * 'response' element MUST have an 'href' element to identify the resource.
1149
+ *
1150
+ * A Multi-Status response uses one out of two distinct formats for
1151
+ * representing the status:
1152
+ *
1153
+ * 1. A 'status' element as child of the 'response' element indicates the
1154
+ * status of the message execution for the identified resource as a whole.
1155
+ * Some method definitions provide information about specific status codes
1156
+ * clients should be prepared to see in a response. However, clients MUST be
1157
+ * able to handle other status codes, using the generic rules defined in
1158
+ * RFC2616 Section 10.
1159
+ *
1160
+ * 2. For PROPFIND and PROPPATCH, the format has been extended using the
1161
+ * 'propstat' element instead of 'status', providing information about
1162
+ * individual properties of a resource. This format is specific to PROPFIND
1163
+ * and PROPPATCH, and is described in detail in RFC4918 Section 9.1 and
1164
+ * RFC4918 Section 9.2.
1165
+ */
1166
+ 207: "Multi-Status",
1167
+ /**
1168
+ * Used inside a DAV: propstat response element to avoid enumerating the
1169
+ * internal members of multiple bindings to the same collection repeatedly.
1170
+ *
1171
+ * For each binding to a collection inside the request's scope, only one will
1172
+ * be reported with a 200 status, while subsequent DAV:response elements for
1173
+ * all other bindings will use the 208 status, and no DAV:response elements
1174
+ * for their descendants are included.
1175
+ *
1176
+ * Note that the 208 status will only occur for "Depth: infinity" requests,
1177
+ * and that it is of particular importance when the multiple collection
1178
+ * bindings cause a bind loop.
1179
+ *
1180
+ * A client can request the DAV:resource-id property in a PROPFIND request to
1181
+ * guarantee that they can accurately reconstruct the binding structure of a
1182
+ * collection with multiple bindings to a single resource.
1183
+ *
1184
+ * For backward compatibility with clients not aware of the 208 status code
1185
+ * appearing in multistatus response bodies, it SHOULD NOT be used unless the
1186
+ * client has signaled support for this specification using the "DAV" request
1187
+ * header. Instead, a 508 Loop Detected status should be returned when a
1188
+ * binding loop is discovered. This allows the server to return the 508 as
1189
+ * the top-level return status, if it discovers it before it started the
1190
+ * response, or in the middle of a multistatus, if it discovers it in the
1191
+ * middle of streaming out a multistatus response.
1192
+ */
1193
+ 208: "Already Reported",
1194
+ /**
1195
+ * The server has fulfilled a GET request for the resource, and the response
1196
+ * is a representation of the result of one or more instance-manipulations
1197
+ * applied to the current instance.
1198
+ *
1199
+ * The actual current instance might not be available except by combining
1200
+ * this response with other previous or future responses, as appropriate for
1201
+ * the specific instance-manipulation(s). If so, the headers of the resulting
1202
+ * instance are the result of combining the headers from the 226 response and
1203
+ * the other instances, following the rules in section 13.5.3 of the HTTP/1.1
1204
+ * specification.
1205
+ *
1206
+ * The request MUST have included an A-IM header field listing at least one
1207
+ * instance-manipulation. The response MUST include an Etag header field
1208
+ * giving the entity tag of the current instance.
1209
+ *
1210
+ * A response received with a status code of 226 MAY be stored by a cache and
1211
+ * used in reply to a subsequent request, subject to the HTTP expiration
1212
+ * mechanism and any Cache-Control headers, and to the requirements in
1213
+ * section 10.6.
1214
+ *
1215
+ * A response received with a status code of 226 MAY be used by a cache, in
1216
+ * conjunction with a cache entry for the base instance, to create a cache
1217
+ * entry for the current instance.
1218
+ */
1219
+ 226: "IM Used",
1220
+ /**
1221
+ * The target resource has more than one representation, each with its own
1222
+ * more specific identifier, and information about the alternatives is being
1223
+ * provided so that the user (or user agent) can select a preferred
1224
+ * representation by redirecting its request to one or more of those
1225
+ * identifiers.
1226
+ *
1227
+ * In other words, the server desires that the user agent engage in reactive
1228
+ * negotiation to select the most appropriate representation(s) for its
1229
+ * needs.
1230
+ *
1231
+ * If the server has a preferred choice, the server SHOULD generate a
1232
+ * Location header field containing a preferred choice's URI reference. The
1233
+ * user agent MAY use the Location field value for automatic redirection.
1234
+ *
1235
+ * For request methods other than HEAD, the server SHOULD generate a payload
1236
+ * in the 300 response containing a list of representation metadata and URI
1237
+ * reference(s) from which the user or user agent can choose the one most
1238
+ * preferred. The user agent MAY make a selection from that list
1239
+ * automatically if it understands the provided media type. A specific format
1240
+ * for automatic selection is not defined by this specification because HTTP
1241
+ * tries to remain orthogonal to the definition of its payloads. In practice,
1242
+ * the representation is provided in some easily parsed format believed to be
1243
+ * acceptable to the user agent, as determined by shared design or content
1244
+ * negotiation, or in some commonly accepted hypertext format.
1245
+ *
1246
+ * A 300 response is cacheable by default; i.e., unless otherwise indicated
1247
+ * by the method definition or explicit cache controls.
1248
+ *
1249
+ * Note: The original proposal for the 300 status code defined the URI header
1250
+ * field as providing a list of alternative representations, such that it
1251
+ * would be usable for 200, 300, and 406 responses and be transferred in
1252
+ * responses to the HEAD method. However, lack of deployment and disagreement
1253
+ * over syntax led to both URI and Alternates (a subsequent proposal) being
1254
+ * dropped from this specification. It is possible to communicate the list
1255
+ * using a set of Link header fields3, each with a relationship of
1256
+ * "alternate", though deployment is a chicken-and-egg problem.
1257
+ */
1258
+ 300: "Multiple Choices",
1259
+ /**
1260
+ * The target resource has been assigned a new permanent URI and any future
1261
+ * references to this resource ought to use one of the enclosed URIs.
1262
+ *
1263
+ * Clients with link-editing capabilities ought to automatically re-link
1264
+ * references to the effective request URI to one or more of the new
1265
+ * references sent by the server, where possible.
1266
+ *
1267
+ * The server SHOULD generate a Location header field in the response
1268
+ * containing a preferred URI reference for the new permanent URI. The user
1269
+ * agent MAY use the Location field value for automatic redirection. The
1270
+ * server's response payload usually contains a short hypertext note with a
1271
+ * hyperlink to the new URI(s).
1272
+ *
1273
+ * Note: For historical reasons, a user agent MAY change the request method
1274
+ * from POST to GET for the subsequent request. If this behavior is
1275
+ * undesired, the 307 Temporary Redirect status code can be used instead.
1276
+ *
1277
+ * A 301 response is cacheable by default; i.e., unless otherwise indicated
1278
+ * by the method definition or explicit cache controls.
1279
+ */
1280
+ 301: "Moved Permanently",
1281
+ /**
1282
+ * The target resource resides temporarily under a different URI. Since the
1283
+ * redirection might be altered on occasion, the client ought to continue to
1284
+ * use the effective request URI for future requests.
1285
+ *
1286
+ * The server SHOULD generate a Location header field in the response
1287
+ * containing a URI reference for the different URI. The user agent MAY use
1288
+ * the Location field value for automatic redirection. The server's response
1289
+ * payload usually contains a short hypertext note with a hyperlink to the
1290
+ * different URI(s).
1291
+ *
1292
+ * Note: For historical reasons, a user agent MAY change the request method
1293
+ * from POST to GET for the subsequent request. If this behavior is
1294
+ * undesired, the 307 Temporary Redirect status code can be used instead.
1295
+ */
1296
+ 302: "Found",
1297
+ /**
1298
+ * The server is redirecting the user agent to a different resource, as
1299
+ * indicated by a URI in the Location header field, which is intended to
1300
+ * provide an indirect response to the original request.
1301
+ *
1302
+ * A user agent can perform a retrieval request targeting that URI (a GET or
1303
+ * HEAD request if using HTTP), which might also be redirected, and present
1304
+ * the eventual result as an answer to the original request. Note that the
1305
+ * new URI in the Location header field is not considered equivalent to the
1306
+ * effective request URI.
1307
+ *
1308
+ * This status code is applicable to any HTTP method. It is primarily used
1309
+ * to allow the output of a POST action to redirect the user agent to a
1310
+ * selected resource, since doing so provides the information corresponding
1311
+ * to the POST response in a form that can be separately identified,
1312
+ * bookmarked, and cached, independent of the original request.
1313
+ *
1314
+ * A 303 response to a GET request indicates that the origin server does not
1315
+ * have a representation of the target resource that can be transferred by
1316
+ * the server over HTTP. However, the Location field value refers to a
1317
+ * resource that is descriptive of the target resource, such that making a
1318
+ * retrieval request on that other resource might result in a representation
1319
+ * that is useful to recipients without implying that it represents the
1320
+ * original target resource. Note that answers to the questions of what can
1321
+ * be represented, what representations are adequate, and what might be a
1322
+ * useful description are outside the scope of HTTP.
1323
+ *
1324
+ * Except for responses to a HEAD request, the representation of a 303
1325
+ * response ought to contain a short hypertext note with a hyperlink to the
1326
+ * same URI reference provided in the Location header field.
1327
+ */
1328
+ 303: "See Other",
1329
+ /**
1330
+ * A conditional GET or HEAD request has been received and would have
1331
+ * resulted in a 200 OK response if it were not for the fact that the
1332
+ * condition evaluated to false.
1333
+ *
1334
+ * In other words, there is no need for the server to transfer a
1335
+ * representation of the target resource because the request indicates that
1336
+ * the client, which made the request conditional, already has a valid
1337
+ * representation; the server is therefore redirecting the client to make
1338
+ * use of that stored representation as if it were the payload of a 200 OK
1339
+ * response.
1340
+ *
1341
+ * The server generating a 304 response MUST generate any of the following
1342
+ * header fields that would have been sent in a 200 OK response to the same
1343
+ * request: Cache-Control, Content-Location, Date, ETag, Expires, and Vary.
1344
+ *
1345
+ * Since the goal of a 304 response is to minimize information transfer when
1346
+ * the recipient already has one or more cached representations, a sender
1347
+ * SHOULD NOT generate representation metadata other than the above listed
1348
+ * fields unless said metadata exists for the purpose of guiding cache
1349
+ * updates (e.g., Last-Modified might be useful if the response does not have
1350
+ * an ETag field).
1351
+ *
1352
+ * Requirements on a cache that receives a 304 response are defined in
1353
+ * Section 4.3.4 of RFC7234. If the conditional request originated with an
1354
+ * outbound client, such as a user agent with its own cache sending a
1355
+ * conditional GET to a shared proxy, then the proxy SHOULD forward the
1356
+ * 304 response to that client.
1357
+ *
1358
+ * A 304 response cannot contain a message-body; it is always terminated by
1359
+ * the first empty line after the header fields.
1360
+ */
1361
+ 304: "Not Modified",
1362
+ /**
1363
+ * Defined in a previous version of this specification and is now deprecated,
1364
+ * due to security concerns regarding in-band configuration of a proxy.
1365
+ */
1366
+ 305: "Use Proxy",
1367
+ /**
1368
+ * The target resource resides temporarily under a different URI and the user
1369
+ * agent MUST NOT change the request method if it performs an automatic
1370
+ * redirection to that URI.
1371
+ *
1372
+ * Since the redirection can change over time, the client ought to continue
1373
+ * using the original effective request URI for future requests.
1374
+ *
1375
+ * The server SHOULD generate a Location header field in the response
1376
+ * containing a URI reference for the different URI. The user agent MAY use
1377
+ * the Location field value for automatic redirection. The server's response
1378
+ * payload usually contains a short hypertext note with a hyperlink to the
1379
+ * different URI(s).
1380
+ *
1381
+ * Note: This status code is similar to 302 Found, except that it does not
1382
+ * allow changing the request method from POST to GET. This specification
1383
+ * defines no equivalent counterpart for 301 Moved Permanently (RFC7238,
1384
+ * however, proposes defining the status code 308 Permanent Redirect for
1385
+ * this purpose).
1386
+ */
1387
+ 307: "Temporary Redirect",
1388
+ /**
1389
+ * The target resource has been assigned a new permanent URI and any future
1390
+ * references to this resource ought to use one of the enclosed URIs.
1391
+ *
1392
+ * Clients with link editing capabilities ought to automatically re-link
1393
+ * references to the effective request URI to one or more of the new
1394
+ * references sent by the server, where possible.
1395
+ *
1396
+ * The server SHOULD generate a Location header field in the response
1397
+ * containing a preferred URI reference for the new permanent URI. The user
1398
+ * agent MAY use the Location field value for automatic redirection. The
1399
+ * server's response payload usually contains a short hypertext note with a
1400
+ * hyperlink to the new URI(s).
1401
+ *
1402
+ * A 308 response is cacheable by default; i.e., unless otherwise indicated
1403
+ * by the method definition or explicit cache controls.
1404
+ *
1405
+ * Note: This status code is similar to 301 Moved Permanently, except that it
1406
+ * does not allow changing the request method from POST to GET.
1407
+ */
1408
+ 308: "Permanent Redirect",
1409
+ /**
1410
+ * The 400 (Bad Request) status code indicates that the server cannot or
1411
+ * will not process the request due to something that is perceived to be
1412
+ * a client error (e.g., malformed request syntax, invalid request
1413
+ * message framing, or deceptive request routing).
1414
+ */
1415
+ 400: "Bad Request",
1416
+ /**
1417
+ * The request has not been applied because it lacks valid authentication
1418
+ * credentials for the target resource.
1419
+ *
1420
+ * The server generating a 401 response MUST send a WWW-Authenticate header
1421
+ * field containing at least one challenge applicable to the target resource.
1422
+ *
1423
+ * If the request included authentication credentials, then the 401 response
1424
+ * indicates that authorization has been refused for those credentials. The
1425
+ * user agent MAY repeat the request with a new or replaced Authorization
1426
+ * header field. If the 401 response contains the same challenge as the
1427
+ * prior response, and the user agent has already attempted authentication at
1428
+ * least once, then the user agent SHOULD present the enclosed representation
1429
+ * to the user, since it usually contains relevant diagnostic information.
1430
+ */
1431
+ 401: "Unauthorized",
1432
+ /**
1433
+ * The 402 (Payment Required) status code is reserved for future use.
1434
+ */
1435
+ 402: "Payment Required",
1436
+ /**
1437
+ * The 403 (Forbidden) status code indicates that the server understood
1438
+ * the request but refuses to authorize it. A server that wishes to
1439
+ * make public why the request has been forbidden can describe that
1440
+ * reason in the response payload (if any).
1441
+ *
1442
+ * If authentication credentials were provided in the request, the
1443
+ * server considers them insufficient to grant access. The client
1444
+ * SHOULD NOT automatically repeat the request with the same
1445
+ * credentials. The client MAY repeat the request with new or different
1446
+ * credentials. However, a request might be forbidden for reasons
1447
+ * unrelated to the credentials.
1448
+ *
1449
+ * An origin server that wishes to "hide" the current existence of a
1450
+ * forbidden target resource MAY instead respond with a status code of
1451
+ * 404 (Not Found).
1452
+ */
1453
+ 403: "Forbidden",
1454
+ /**
1455
+ * The 404 (Not Found) status code indicates that the origin server did
1456
+ * not find a current representation for the target resource or is not
1457
+ * willing to disclose that one exists. A 404 status code does not
1458
+ * indicate whether this lack of representation is temporary or
1459
+ * permanent; the 410 (Gone) status code is preferred over 404 if the
1460
+ * origin server knows, presumably through some configurable means, that
1461
+ * the condition is likely to be permanent.
1462
+ *
1463
+ * A 404 response is cacheable by default; i.e., unless otherwise
1464
+ * indicated by the method definition or explicit cache controls (see
1465
+ * Section 4.2.2 of [RFC7234]).
1466
+ */
1467
+ 404: "Not Found",
1468
+ /**
1469
+ * The 405 (Method Not Allowed) status code indicates that the method
1470
+ * received in the request-line is known by the origin server but not
1471
+ * supported by the target resource. The origin server MUST generate an
1472
+ * Allow header field in a 405 response containing a list of the target
1473
+ * resource's currently supported methods.
1474
+ *
1475
+ * A 405 response is cacheable by default; i.e., unless otherwise
1476
+ * indicated by the method definition or explicit cache controls (see
1477
+ * Section 4.2.2 of [RFC7234]).
1478
+ */
1479
+ 405: "Method Not Allowed",
1480
+ /**
1481
+ * The 406 (Not Acceptable) status code indicates that the target
1482
+ * resource does not have a current representation that would be
1483
+ * acceptable to the user agent, according to the proactive negotiation
1484
+ * header fields received in the request (Section 5.3), and the server
1485
+ * is unwilling to supply a default representation.
1486
+ *
1487
+ * The server SHOULD generate a payload containing a list of available
1488
+ * representation characteristics and corresponding resource identifiers
1489
+ * from which the user or user agent can choose the one most
1490
+ * appropriate. A user agent MAY automatically select the most
1491
+ * appropriate choice from that list. However, this specification does
1492
+ * not define any standard for such automatic selection, as described in
1493
+ * Section 6.4.1 of [RFC7231]
1494
+ */
1495
+ 406: "Not Acceptable",
1496
+ /**
1497
+ * Similar to 401 Unauthorized, but it indicates that the client needs to
1498
+ * authenticate itself in order to use a proxy.
1499
+ *
1500
+ * The proxy MUST send a Proxy-Authenticate header field containing a
1501
+ * challenge applicable to that proxy for the target resource. The client MAY
1502
+ * repeat the request with a new or replaced Proxy-Authorization header field.
1503
+ */
1504
+ 407: "Proxy Authentication Required",
1505
+ /**
1506
+ * The 408 (Request Timeout) status code indicates that the server did
1507
+ * not receive a complete request message within the time that it was
1508
+ * prepared to wait. A server SHOULD send the "close" connection option
1509
+ * (Section 6.1 of [RFC7230]) in the response, since 408 implies that
1510
+ * the server has decided to close the connection rather than continue
1511
+ * waiting. If the client has an outstanding request in transit, the
1512
+ * client MAY repeat that request on a new connection.
1513
+ */
1514
+ 408: "Request Timeout",
1515
+ /**
1516
+ * The 409 (Conflict) status code indicates that the request could not
1517
+ * be completed due to a conflict with the current state of the target
1518
+ * resource. This code is used in situations where the user might be
1519
+ * able to resolve the conflict and resubmit the request. The server
1520
+ * SHOULD generate a payload that includes enough information for a user
1521
+ * to recognize the source of the conflict.
1522
+ *
1523
+ * Conflicts are most likely to occur in response to a PUT request. For
1524
+ * example, if versioning were being used and the representation being
1525
+ * PUT included changes to a resource that conflict with those made by
1526
+ * an earlier (third-party) request, the origin server might use a 409
1527
+ * response to indicate that it can't complete the request. In this
1528
+ * case, the response representation would likely contain information
1529
+ * useful for merging the differences based on the revision history.
1530
+ */
1531
+ 409: "Conflict",
1532
+ /**
1533
+ * The 410 (Gone) status code indicates that access to the target
1534
+ * resource is no longer available at the origin server and that this
1535
+ * condition is likely to be permanent. If the origin server does not
1536
+ * know, or has no facility to determine, whether or not the condition
1537
+ * is permanent, the status code 404 (Not Found) ought to be used
1538
+ * instead.
1539
+ *
1540
+ * The 410 response is primarily intended to assist the task of web
1541
+ * maintenance by notifying the recipient that the resource is
1542
+ * intentionally unavailable and that the server owners desire that
1543
+ * remote links to that resource be removed. Such an event is common
1544
+ * for limited-time, promotional services and for resources belonging to
1545
+ * individuals no longer associated with the origin server's site. It
1546
+ * is not necessary to mark all permanently unavailable resources as
1547
+ * "gone" or to keep the mark for any length of time -- that is left to
1548
+ * the discretion of the server owner.
1549
+ *
1550
+ * A 410 response is cacheable by default; i.e., unless otherwise
1551
+ * indicated by the method definition or explicit cache controls (see
1552
+ * Section 4.2.2 of [RFC7234]).
1553
+ */
1554
+ 410: "Gone",
1555
+ /**
1556
+ * The 411 (Length Required) status code indicates that the server
1557
+ * refuses to accept the request without a defined Content-Length
1558
+ * (Section 3.3.2 of [RFC7230]). The client MAY repeat the request if
1559
+ * it adds a valid Content-Length header field containing the length of
1560
+ * the message body in the request message.
1561
+ */
1562
+ 411: "Length Required",
1563
+ /**
1564
+ * One or more conditions given in the request header fields evaluated to
1565
+ * false when tested on the server.
1566
+ *
1567
+ * This response code allows the client to place preconditions on the current
1568
+ * resource state (its current representations and metadata) and, thus,
1569
+ * prevent the request method from being applied if the target resource is in
1570
+ * an unexpected state.
1571
+ */
1572
+ 412: "Precondition Failed",
1573
+ /**
1574
+ * The 413 (Payload Too Large) status code indicates that the server is
1575
+ * refusing to process a request because the request payload is larger
1576
+ * than the server is willing or able to process. The server MAY close
1577
+ * the connection to prevent the client from continuing the request.
1578
+ *
1579
+ * If the condition is temporary, the server SHOULD generate a
1580
+ * Retry-After header field to indicate that it is temporary and after
1581
+ * what time the client MAY try again.
1582
+ */
1583
+ 413: "Payload Too Large",
1584
+ /**
1585
+ * The 414 (URI Too Long) status code indicates that the server is
1586
+ * refusing to service the request because the request-target (Section
1587
+ * 5.3 of [RFC7230]) is longer than the server is willing to interpret.
1588
+ * This rare condition is only likely to occur when a client has
1589
+ * improperly converted a POST request to a GET request with long query
1590
+ * information, when the client has descended into a "black hole" of
1591
+ * redirection (e.g., a redirected URI prefix that points to a suffix of
1592
+ * itself) or when the server is under attack by a client attempting to
1593
+ * exploit potential security holes.
1594
+ *
1595
+ * A 414 response is cacheable by default; i.e., unless otherwise
1596
+ * indicated by the method definition or explicit cache controls (see
1597
+ * Section 4.2.2 of [RFC7234]).
1598
+ */
1599
+ 414: "Request-URI Too Long",
1600
+ /**
1601
+ * The 415 (Unsupported Media Type) status code indicates that the
1602
+ * origin server is refusing to service the request because the payload
1603
+ * is in a format not supported by this method on the target resource.
1604
+ * The format problem might be due to the request's indicated
1605
+ * Content-Type or Content-Encoding, or as a result of inspecting the
1606
+ * data directly.
1607
+ */
1608
+ 415: "Unsupported Media Type",
1609
+ /**
1610
+ * None of the ranges in the request's Range header field overlap the
1611
+ * current extent of the selected resource or that the set of ranges
1612
+ * requested has been rejected due to invalid ranges or an excessive request
1613
+ * of small or overlapping ranges.
1614
+ *
1615
+ * For byte ranges, failing to overlap the current extent means that the
1616
+ * first-byte-pos of all of the byte-range-spec values were greater than the
1617
+ * current length of the selected representation. When this status code is
1618
+ * generated in response to a byte-range request, the sender SHOULD generate
1619
+ * a Content-Range header field specifying the current length of the selected
1620
+ * representation
1621
+ */
1622
+ 416: "Requested Range Not Satisfiable",
1623
+ /**
1624
+ * The 417 (Expectation Failed) status code indicates that the
1625
+ * expectation given in the request's Expect header field
1626
+ * (Section 5.1.1 of [RFC7231]) could not be met by at least one of the
1627
+ * inbound servers.
1628
+ */
1629
+ 417: "Expectation Failed",
1630
+ /**
1631
+ * Any attempt to brew coffee with a teapot should result in the error code
1632
+ * "418 I'm a teapot". The resulting entity body MAY be short and stout.
1633
+ */
1634
+ 418: "I'm a Teapot",
1635
+ /**
1636
+ * The request was directed at a server that is not able to produce a
1637
+ * response. This can be sent by a server that is not configured to produce
1638
+ * responses for the combination of scheme and authority that are included
1639
+ * in the request URI.
1640
+ *
1641
+ * Clients receiving a 421 Misdirected Request response from a server MAY
1642
+ * retry the request -- whether the request method is idempotent or
1643
+ * not -- over a different connection. This is possible if a connection is
1644
+ * reused or if an alternative service is selected ALT-SVC.
1645
+ *
1646
+ * This status code MUST NOT be generated by proxies.
1647
+ *
1648
+ * A 421 response is cacheable by default, i.e., unless otherwise indicated by
1649
+ * the method definition or explicit cache controls
1650
+ */
1651
+ 421: "Misdirected Request",
1652
+ /**
1653
+ * The server understands the content type of the request entity (hence a
1654
+ * 415 Unsupported Media Type status code is inappropriate), and the syntax
1655
+ * of the request entity is correct (thus a 400 Bad Request status code is
1656
+ * inappropriate) but was unable to process the contained instructions.
1657
+ *
1658
+ * For example, this error condition may occur if an XML request body contains
1659
+ * well-formed (i.e., syntactically correct), but semantically erroneous, XML
1660
+ * instructions.
1661
+ */
1662
+ 422: "Unprocessable Entity",
1663
+ /**
1664
+ * The source or destination resource of a method is locked.
1665
+ *
1666
+ * This response SHOULD contain an appropriate precondition or postcondition
1667
+ * code, such as 'lock-token-submitted' or 'no-conflicting-lock'.
1668
+ */
1669
+ 423: "Locked",
1670
+ /**
1671
+ * The method could not be performed on the resource because the requested
1672
+ * action depended on another action and that action failed.
1673
+ *
1674
+ * For example, if a command in a PROPPATCH method fails, then, at minimum,
1675
+ * the rest of the commands will also fail with 424 Failed Dependency.
1676
+ */
1677
+ 424: "Failed Dependency",
1678
+ /**
1679
+ * The 426 (Upgrade Required) status code indicates that the server
1680
+ * refuses to perform the request using the current protocol but might
1681
+ * be willing to do so after the client upgrades to a different
1682
+ * protocol. The server MUST send an Upgrade header field in a 426
1683
+ * response to indicate the required protocol(s) (Section 6.7 of
1684
+ * [RFC7230]).
1685
+ */
1686
+ 426: "Upgrade Required",
1687
+ /**
1688
+ * The origin server requires the request to be conditional.
1689
+ *
1690
+ * Its typical use is to avoid the "lost update" problem, where a client GETs
1691
+ * a resource's state, modifies it, and PUTs it back to the server, when
1692
+ * meanwhile a third party has modified the state on the server, leading
1693
+ * to a conflict. By requiring requests to be conditional, the server can
1694
+ * assure that clients are working with the correct copies.
1695
+ *
1696
+ * Responses using this status code SHOULD explain how to resubmit the request
1697
+ * successfully.
1698
+ *
1699
+ * Responses with the 428 status code MUST NOT be stored by a cache.
1700
+ */
1701
+ 428: "Precondition Required",
1702
+ /**
1703
+ * The user has sent too many requests in a given amount of time
1704
+ * ("rate limiting").
1705
+ *
1706
+ * The response representations SHOULD include details explaining the
1707
+ * condition, and MAY include a Retry-After header indicating how long to
1708
+ * wait before making a new request.
1709
+ *
1710
+ * Responses with the 429 status code MUST NOT be stored by a cache.
1711
+ */
1712
+ 429: "Too Many Requests",
1713
+ /**
1714
+ * The server is unwilling to process the request because its header fields
1715
+ * are too large. The request MAY be resubmitted after reducing the size of
1716
+ * the request header fields.
1717
+ *
1718
+ * It can be used both when the set of request header fields in total is too
1719
+ * large, and when a single header field is at fault. In the latter case, the
1720
+ * response representation SHOULD specify which header field was too large.
1721
+ */
1722
+ 431: "Request Header Fields Too Large",
1723
+ /**
1724
+ * A non-standard status code used to instruct nginx to close the connection
1725
+ * without sending a response to the client, most commonly used to deny
1726
+ * malicious or malformed requests.
1727
+ *
1728
+ * This status code is not seen by the client, it only appears in nginx log
1729
+ * files.
1730
+ */
1731
+ 444: "Connection Closed Without Response",
1732
+ /**
1733
+ * The server is denying access to the resource as a consequence of a legal
1734
+ * demand.
1735
+ *
1736
+ * The server in question might not be an origin server. This type of legal
1737
+ * demand typically most directly affects the operations of ISPs and search
1738
+ * engines.
1739
+ *
1740
+ * Responses using this status code SHOULD include an explanation, in the
1741
+ * response body, of the details of the legal demand: the party making it,
1742
+ * the applicable legislation or regulation, and what classes of person and
1743
+ * resource it applies to.
1744
+ *
1745
+ * The use of the 451 status code implies neither the existence nor
1746
+ * non-existence of the resource named in the request. That is to say, it is
1747
+ * possible that if the legal demands were removed, a request for the
1748
+ * resource still might not succeed.
1749
+ *
1750
+ * Note that in many cases clients can still access the denied resource by
1751
+ * using technical countermeasures such as a VPN or the Tor network.
1752
+ *
1753
+ * A 451 response is cacheable by default; i.e., unless otherwise indicated
1754
+ * by the method definition or explicit cache controls; see RFC7234.
1755
+ */
1756
+ 451: "Unavailable For Legal Reasons",
1757
+ /**
1758
+ * A non-standard status code introduced by nginx for the case when a client
1759
+ * closes the connection while nginx is processing the request.
1760
+ */
1761
+ 499: "Client Closed Request",
1762
+ /**
1763
+ * The 500 (Internal Server Error) status code indicates that the server
1764
+ * encountered an unexpected condition that prevented it from fulfilling
1765
+ * the request.
1766
+ */
1767
+ 500: "Internal Server Error",
1768
+ /**
1769
+ * The 501 (Not Implemented) status code indicates that the server does
1770
+ * not support the functionality required to fulfill the request. This
1771
+ * is the appropriate response when the server does not recognize the
1772
+ * request method and is not capable of supporting it for any resource.
1773
+ *
1774
+ * A 501 response is cacheable by default; i.e., unless otherwise
1775
+ * indicated by the method definition or explicit cache controls (see
1776
+ * Section 4.2.2 of [RFC7234]).
1777
+ */
1778
+ 501: "Not Implemented",
1779
+ /**
1780
+ * The 502 (Bad Gateway) status code indicates that the server, while
1781
+ * acting as a gateway or proxy, received an invalid response from an
1782
+ * inbound server it accessed while attempting to fulfill the request.
1783
+ */
1784
+ 502: "Bad Gateway",
1785
+ /**
1786
+ * The 503 (Service Unavailable) status code indicates that the server
1787
+ * is currently unable to handle the request due to a temporary overload
1788
+ * or scheduled maintenance, which will likely be alleviated after some
1789
+ * delay. The server MAY send a Retry-After header field
1790
+ * (Section 7.1.3 of [RFC7231]) to suggest an appropriate amount of time for
1791
+ * the client to wait before retrying the request.
1792
+ */
1793
+ 503: "Service Unavailable",
1794
+ /**
1795
+ * The 504 (Gateway Timeout) status code indicates that the server,
1796
+ *while acting as a gateway or proxy, did not receive a timely response
1797
+ *from an upstream server it needed to access in order to complete the
1798
+ *request.
1799
+ */
1800
+ 504: "Gateway Timeout",
1801
+ /**
1802
+ * The 505 (HTTP Version Not Supported) status code indicates that the
1803
+ *server does not support, or refuses to support, the major version of
1804
+ *HTTP that was used in the request message. The server is indicating
1805
+ *that it is unable or unwilling to complete the request using the same
1806
+ *major version as the client, as described in Section 2.6 of
1807
+ *[RFC7230], other than with this error message. The server SHOULD
1808
+ *generate a representation for the 505 response that describes why
1809
+ *that version is not supported and what other protocols are supported
1810
+ *by that server.
1811
+ */
1812
+ 505: "HTTP Version Not Supported",
1813
+ /**
1814
+ * The server has an internal configuration error: the chosen variant
1815
+ * resource is configured to engage in transparent content negotiation
1816
+ * itself, and is therefore not a proper end point in the negotiation
1817
+ * process.
1818
+ */
1819
+ 506: "Variant Also Negotiates",
1820
+ /**
1821
+ * The method could not be performed on the resource because the server is
1822
+ * unable to store the representation needed to successfully complete the
1823
+ * request.
1824
+ *
1825
+ * This condition is considered to be temporary. If the request that received
1826
+ * this status code was the result of a user action, the request MUST NOT be
1827
+ * repeated until it is requested by a separate user action.
1828
+ */
1829
+ 507: "Insufficient Storage",
1830
+ /**
1831
+ * The server terminated an operation because it encountered an infinite loop
1832
+ * while processing a request with "Depth: infinity". This status indicates
1833
+ * that the entire operation failed.
1834
+ */
1835
+ 508: "Loop Detected",
1836
+ /**
1837
+ * The policy for accessing the resource has not been met in the request. The
1838
+ * server should send back all the information necessary for the client to
1839
+ * issue an extended request.
1840
+ *
1841
+ * It is outside the scope of this specification to specify how the
1842
+ * extensions inform the client.
1843
+ *
1844
+ * If the 510 response contains information about extensions that were not
1845
+ * present in the initial request then the client MAY repeat the request if
1846
+ * it has reason to believe it can fulfill the extension policy by modifying
1847
+ * the request according to the information provided in the 510 response.
1848
+ * Otherwise the client MAY present any entity included in the 510 response
1849
+ * to the user, since that entity may include relevant diagnostic information.
1850
+ */
1851
+ 510: "Not Extended",
1852
+ /**
1853
+ * The client needs to authenticate to gain network access.
1854
+ *
1855
+ * The response representation SHOULD contain a link to a resource that
1856
+ * allows the user to submit credentials (e.g., with an HTML form).
1857
+ *
1858
+ * Note that the 511 response SHOULD NOT contain a challenge or the login
1859
+ * interface itself, because browsers would show the login interface as being
1860
+ * associated with the originally requested URL, which may cause confusion.
1861
+ *
1862
+ * The 511 status SHOULD NOT be generated by origin servers; it is intended
1863
+ * for use by intercepting proxies that are interposed as a means of
1864
+ * controlling access to the network.
1865
+ *
1866
+ * Responses with the 511 status code MUST NOT be stored by a cache.
1867
+ */
1868
+ 511: "Network Authentication Required",
1869
+ /**
1870
+ * This status code is not specified in any RFCs, but is used by some HTTP
1871
+ * proxies to signal a network connect timeout behind the proxy to a client
1872
+ * in front of the proxy.
1873
+ */
1874
+ 599: "Network Connect Timeout Error"
1875
+ };
1876
+ var isValidStatusCode = (code) => !!HTTPStatuses[code];
1877
+ var isInformational = (code) => code >= 100 && code < 200;
1878
+ var isSuccessful = (code) => code >= 200 && code < 300;
1879
+ var isRedirection = (code) => code >= 300 && code < 400;
1880
+ var isClientError = (code) => code >= 400 && code < 500;
1881
+ var isServerError = (code) => code >= 500;
1882
+ var getCodeForStatus = (status) => {
1883
+ const clnStr = status.toLocaleLowerCase().trim();
1884
+ const entry = Object.entries(HTTPStatuses).find(
1885
+ (ent) => ent[1].toLowerCase() === clnStr
1886
+ );
1887
+ if (entry) return parseInt(entry[0]);
1888
+ return null;
1889
+ };
1890
+ var httpStatusCodes_default = HTTPStatuses;
1891
+
1892
+ // src/http/openApiV3Generator/openApiV3Generator.ts
1893
+ function toUpperCase(str) {
1894
+ return str.charAt(0).toUpperCase() + str.slice(1);
1895
+ }
1896
+ function transformBasePath(basePath) {
1897
+ if (basePath.startsWith("/")) {
1898
+ return toUpperCase(basePath.slice(1));
1899
+ }
1900
+ return `/${basePath}`;
1901
+ }
1902
+ function swaggerDocument(port, tags, paths) {
1903
+ return {
1904
+ openapi: "3.1.0",
1905
+ info: {
1906
+ title: process.env.API_TITLE || "",
1907
+ version: process.env.VERSION || "1.0.0"
1908
+ },
1909
+ components: {
1910
+ securitySchemes: {
1911
+ bearer: {
1912
+ type: "http",
1913
+ scheme: "bearer",
1914
+ bearerFormat: "JWT"
1915
+ }
1916
+ }
1917
+ },
1918
+ tags,
1919
+ servers: [
1920
+ {
1921
+ url: `http://localhost:${port}`
1922
+ }
1923
+ ],
1924
+ paths
1925
+ };
1926
+ }
1927
+ function contentResolver(schemaValidator, body) {
1928
+ const bodySpec = schemaValidator.openapi(body);
1929
+ return body === schemaValidator.string ? {
1930
+ "plain/text": {
1931
+ schema: bodySpec
1932
+ }
1933
+ } : {
1934
+ "application/json": {
1935
+ schema: bodySpec
1936
+ }
1937
+ };
1938
+ }
1939
+ function generateSwaggerDocument(schemaValidator, port, routers) {
1940
+ const tags = [];
1941
+ const paths = {};
1942
+ routers.flat(Infinity).forEach((router) => {
1943
+ const controllerName = transformBasePath(router.basePath);
1944
+ tags.push({
1945
+ name: controllerName,
1946
+ description: `${controllerName} Operations`
1947
+ });
1948
+ router.routes.forEach((route) => {
1949
+ const fullPath = `${router.basePath}${route.path === "/" ? "" : route.path}`.replace(
1950
+ /:(\w+)/g,
1951
+ "{$1}"
1952
+ );
1953
+ if (!paths[fullPath]) {
1954
+ paths[fullPath] = {};
1955
+ }
1956
+ const { name, summary, query, requestHeaders } = route.contractDetails;
1957
+ const responses = {};
1958
+ for (const key in route.contractDetails.responses) {
1959
+ responses[key] = {
1960
+ description: httpStatusCodes_default[key],
1961
+ content: contentResolver(
1962
+ schemaValidator,
1963
+ route.contractDetails.responses[key]
1964
+ )
1965
+ };
1966
+ }
1967
+ const pathItemObject = {
1968
+ tags: [controllerName],
1969
+ summary: `${name}: ${summary}`,
1970
+ parameters: [],
1971
+ responses
1972
+ };
1973
+ if (route.contractDetails.params) {
1974
+ for (const key in route.contractDetails.params) {
1975
+ pathItemObject.parameters?.push({
1976
+ name: key,
1977
+ in: "path"
1978
+ });
1979
+ }
1980
+ }
1981
+ const body = route.contractDetails.body;
1982
+ if (body) {
1983
+ pathItemObject.requestBody = {
1984
+ required: true,
1985
+ content: contentResolver(schemaValidator, body)
1986
+ };
1987
+ }
1988
+ if (requestHeaders) {
1989
+ for (const key in requestHeaders) {
1990
+ pathItemObject.parameters?.push({
1991
+ name: key,
1992
+ in: "header"
1993
+ });
1994
+ }
1995
+ }
1996
+ if (query) {
1997
+ for (const key in query) {
1998
+ pathItemObject.parameters?.push({
1999
+ name: key,
2000
+ in: "query"
2001
+ });
2002
+ }
2003
+ }
2004
+ if (route.contractDetails.auth) {
2005
+ responses[401] = {
2006
+ description: httpStatusCodes_default[401],
2007
+ content: contentResolver(schemaValidator, schemaValidator.string)
2008
+ };
2009
+ responses[403] = {
2010
+ description: httpStatusCodes_default[403],
2011
+ content: contentResolver(schemaValidator, schemaValidator.string)
2012
+ };
2013
+ if (route.contractDetails.auth.method === "jwt") {
2014
+ pathItemObject.security = [
2015
+ {
2016
+ bearer: Array.from(
2017
+ route.contractDetails.auth.allowedPermissions?.values() || []
2018
+ )
2019
+ }
2020
+ ];
2021
+ }
2022
+ }
2023
+ if (route.method !== "middleware") {
2024
+ paths[fullPath][route.method] = pathItemObject;
2025
+ }
2026
+ });
2027
+ });
2028
+ return swaggerDocument(port, tags, paths);
2029
+ }
2030
+
2031
+ // src/http/middleware/response/parse.middleware.ts
2032
+ function parse2(req, res, next) {
2033
+ console.debug("[MIDDLEWARE] parseResponse started");
2034
+ const { headers, responses } = res.responseSchemas;
2035
+ const parsedResponse = req.schemaValidator.parse(
2036
+ responses?.[res.statusCode],
2037
+ res.bodyData
2038
+ );
2039
+ const parsedHeaders = req.schemaValidator.parse(
2040
+ headers ?? req.schemaValidator.unknown,
2041
+ res.getHeaders()
2042
+ );
2043
+ const parseErrors = [];
2044
+ if (!parsedHeaders.ok) {
2045
+ parseErrors.push(
2046
+ `${parsedHeaders.error ? `Header ${parsedHeaders.error}` : ""}`
2047
+ );
2048
+ }
2049
+ if (!parsedResponse.ok) {
2050
+ parseErrors.push(
2051
+ `${parsedResponse.error ? `Response ${parsedResponse.error}` : ""}`
2052
+ );
2053
+ }
2054
+ if (parseErrors.length > 0) {
2055
+ switch (req.contractDetails.options?.responseValidation) {
2056
+ default:
2057
+ case "error":
2058
+ next?.(new Error(`Invalid response:
2059
+ ${parseErrors.join("\n\n")}`));
2060
+ break;
2061
+ case "warning":
2062
+ console.warn(`Invalid response:
2063
+ ${parseErrors.join("\n\n")}`);
2064
+ break;
2065
+ case "none":
2066
+ break;
2067
+ }
2068
+ }
2069
+ next?.();
2070
+ }
2071
+
2072
+ // src/http/utils/enrichExpressLikeSend.ts
2073
+ function enrichExpressLikeSend(instance, req, res, originalSend, data, shouldEnrich) {
2074
+ let parseErrorSent;
2075
+ if (shouldEnrich) {
2076
+ if (res.statusCode === 404) {
2077
+ res.status(404);
2078
+ originalSend.call(instance, "Not Found");
2079
+ }
2080
+ parse2(req, res, (err) => {
2081
+ if (err) {
2082
+ let errorString = err.message;
2083
+ if (res.locals.errorMessage) {
2084
+ errorString += `
2085
+ ------------------
2086
+ ${res.locals.errorMessage}`;
2087
+ }
2088
+ res.status(500);
2089
+ originalSend.call(instance, errorString);
2090
+ parseErrorSent = true;
2091
+ }
2092
+ });
2093
+ }
2094
+ if (!parseErrorSent) {
2095
+ originalSend.call(instance, data);
2096
+ }
2097
+ }
2098
+ export {
2099
+ ForklaunchExpressLikeApplication,
2100
+ ForklaunchExpressLikeRouter,
2101
+ HTTPStatuses,
2102
+ delete_,
2103
+ enrichExpressLikeSend,
2104
+ generateSwaggerDocument,
2105
+ get,
2106
+ getCodeForStatus,
2107
+ head,
2108
+ isClientError,
2109
+ isForklaunchRouter,
2110
+ isInformational,
2111
+ isRedirection,
2112
+ isServerError,
2113
+ isSuccessful,
2114
+ isValidStatusCode,
2115
+ middleware,
2116
+ options,
2117
+ patch,
2118
+ post,
2119
+ put,
2120
+ trace,
2121
+ typedHandler
2122
+ };