@forinda/kickjs 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/README.md +85 -584
  2. package/dist/adapter-BqGjZCSm.d.mts +122 -0
  3. package/dist/adapter-BqGjZCSm.d.mts.map +1 -0
  4. package/dist/app-module-CcEbAVtB.d.mts +33 -0
  5. package/dist/app-module-CcEbAVtB.d.mts.map +1 -0
  6. package/dist/application-DNHj-_UL.mjs +449 -0
  7. package/dist/application-DNHj-_UL.mjs.map +1 -0
  8. package/dist/bootstrap-DLEZaJ3b.mjs +205 -0
  9. package/dist/bootstrap-DLEZaJ3b.mjs.map +1 -0
  10. package/dist/{core/cache.d.ts → cache-DJeMaGqb.d.mts} +33 -31
  11. package/dist/cache-DJeMaGqb.d.mts.map +1 -0
  12. package/dist/chunk-C5Qp-JxE.mjs +15 -0
  13. package/dist/container-nBSIhyqV.d.mts +141 -0
  14. package/dist/container-nBSIhyqV.d.mts.map +1 -0
  15. package/dist/core/adapter.d.mts +3 -0
  16. package/dist/core/adapter.mjs +11 -0
  17. package/dist/core/app-module.d.mts +3 -0
  18. package/dist/core/app-module.mjs +11 -0
  19. package/dist/core/cache.d.mts +3 -0
  20. package/dist/core/cache.mjs +113 -0
  21. package/dist/core/cache.mjs.map +1 -0
  22. package/dist/core/container.d.mts +3 -0
  23. package/dist/core/container.mjs +426 -0
  24. package/dist/core/container.mjs.map +1 -0
  25. package/dist/core/cron.d.mts +3 -0
  26. package/dist/core/cron.mjs +42 -0
  27. package/dist/core/cron.mjs.map +1 -0
  28. package/dist/core/decorators.d.mts +3 -0
  29. package/dist/core/decorators.mjs +213 -0
  30. package/dist/core/decorators.mjs.map +1 -0
  31. package/dist/core/errors.d.mts +3 -0
  32. package/dist/core/errors.mjs +97 -0
  33. package/dist/core/errors.mjs.map +1 -0
  34. package/dist/core/interfaces.d.mts +3 -0
  35. package/dist/core/interfaces.mjs +44 -0
  36. package/dist/core/interfaces.mjs.map +1 -0
  37. package/dist/core/logger.d.mts +3 -0
  38. package/dist/core/logger.mjs +217 -0
  39. package/dist/core/logger.mjs.map +1 -0
  40. package/dist/core/path.d.mts +3 -0
  41. package/dist/core/path.mjs +45 -0
  42. package/dist/core/path.mjs.map +1 -0
  43. package/dist/core/plugin.d.mts +3 -0
  44. package/dist/core/plugin.mjs +11 -0
  45. package/dist/core/reactivity.d.mts +3 -0
  46. package/dist/core/reactivity.mjs +189 -0
  47. package/dist/core/reactivity.mjs.map +1 -0
  48. package/dist/core-BL_H8fEZ.mjs +121 -0
  49. package/dist/core-BL_H8fEZ.mjs.map +1 -0
  50. package/dist/{core/cron.d.ts → cron-RKhH5TOd.d.mts} +16 -14
  51. package/dist/cron-RKhH5TOd.d.mts.map +1 -0
  52. package/dist/decorators-CQ93ak6Z.d.mts +154 -0
  53. package/dist/decorators-CQ93ak6Z.d.mts.map +1 -0
  54. package/dist/errors-te5Km00o.d.mts +68 -0
  55. package/dist/errors-te5Km00o.d.mts.map +1 -0
  56. package/dist/http/application.d.mts +220 -0
  57. package/dist/http/application.d.mts.map +1 -0
  58. package/dist/http/application.mjs +12 -0
  59. package/dist/http/bootstrap.d.mts +43 -0
  60. package/dist/http/bootstrap.d.mts.map +1 -0
  61. package/dist/http/bootstrap.mjs +12 -0
  62. package/dist/http/context.d.mts +131 -0
  63. package/dist/http/context.d.mts.map +1 -0
  64. package/dist/http/context.mjs +220 -0
  65. package/dist/http/context.mjs.map +1 -0
  66. package/dist/http/middleware/cors.d.mts +48 -0
  67. package/dist/http/middleware/cors.d.mts.map +1 -0
  68. package/dist/http/middleware/cors.mjs +83 -0
  69. package/dist/http/middleware/cors.mjs.map +1 -0
  70. package/dist/http/middleware/csrf.d.mts +52 -0
  71. package/dist/http/middleware/csrf.d.mts.map +1 -0
  72. package/dist/http/middleware/csrf.mjs +72 -0
  73. package/dist/http/middleware/csrf.mjs.map +1 -0
  74. package/dist/http/middleware/error-handler.d.mts +11 -0
  75. package/dist/http/middleware/error-handler.d.mts.map +1 -0
  76. package/dist/http/middleware/error-handler.mjs +52 -0
  77. package/dist/http/middleware/error-handler.mjs.map +1 -0
  78. package/dist/http/middleware/helmet.d.mts +41 -0
  79. package/dist/http/middleware/helmet.d.mts.map +1 -0
  80. package/dist/http/middleware/helmet.mjs +51 -0
  81. package/dist/http/middleware/helmet.mjs.map +1 -0
  82. package/dist/http/middleware/rate-limit.d.mts +56 -0
  83. package/dist/http/middleware/rate-limit.d.mts.map +1 -0
  84. package/dist/http/middleware/rate-limit.mjs +101 -0
  85. package/dist/http/middleware/rate-limit.mjs.map +1 -0
  86. package/dist/http/middleware/request-id.d.mts +10 -0
  87. package/dist/http/middleware/request-id.d.mts.map +1 -0
  88. package/dist/http/middleware/request-id.mjs +26 -0
  89. package/dist/http/middleware/request-id.mjs.map +1 -0
  90. package/dist/http/middleware/request-logger.d.mts +32 -0
  91. package/dist/http/middleware/request-logger.d.mts.map +1 -0
  92. package/dist/http/middleware/request-logger.mjs +49 -0
  93. package/dist/http/middleware/request-logger.mjs.map +1 -0
  94. package/dist/http/middleware/session.d.mts +67 -0
  95. package/dist/http/middleware/session.d.mts.map +1 -0
  96. package/dist/http/middleware/session.mjs +152 -0
  97. package/dist/http/middleware/session.mjs.map +1 -0
  98. package/dist/http/middleware/spa.d.mts +101 -0
  99. package/dist/http/middleware/spa.d.mts.map +1 -0
  100. package/dist/http/middleware/spa.mjs +108 -0
  101. package/dist/http/middleware/spa.mjs.map +1 -0
  102. package/dist/http/middleware/{upload.d.ts → upload.d.mts} +21 -17
  103. package/dist/http/middleware/upload.d.mts.map +1 -0
  104. package/dist/http/middleware/upload.mjs +191 -0
  105. package/dist/http/middleware/upload.mjs.map +1 -0
  106. package/dist/http/middleware/validate.d.mts +18 -0
  107. package/dist/http/middleware/validate.d.mts.map +1 -0
  108. package/dist/http/middleware/validate.mjs +62 -0
  109. package/dist/http/middleware/validate.mjs.map +1 -0
  110. package/dist/http/middleware/views.d.mts +62 -0
  111. package/dist/http/middleware/views.d.mts.map +1 -0
  112. package/dist/http/middleware/views.mjs +65 -0
  113. package/dist/http/middleware/views.mjs.map +1 -0
  114. package/dist/http/query/index.d.mts +3 -0
  115. package/dist/http/query/index.mjs +12 -0
  116. package/dist/http/{router-builder.d.ts → router-builder.d.mts} +9 -5
  117. package/dist/http/router-builder.d.mts.map +1 -0
  118. package/dist/http/router-builder.mjs +67 -0
  119. package/dist/http/router-builder.mjs.map +1 -0
  120. package/dist/index-C0gbnpSg.d.mts +107 -0
  121. package/dist/index-C0gbnpSg.d.mts.map +1 -0
  122. package/dist/index-Cls52etj.d.mts +148 -0
  123. package/dist/index-Cls52etj.d.mts.map +1 -0
  124. package/dist/index.d.mts +133 -0
  125. package/dist/index.d.mts.map +1 -0
  126. package/dist/index.mjs +126 -0
  127. package/dist/index.mjs.map +1 -0
  128. package/dist/interfaces-D-48zotH.d.mts +52 -0
  129. package/dist/interfaces-D-48zotH.d.mts.map +1 -0
  130. package/dist/logger-Dzj-TF0t.d.mts +119 -0
  131. package/dist/logger-Dzj-TF0t.d.mts.map +1 -0
  132. package/dist/metadata-fmvikBA0.mjs +76 -0
  133. package/dist/metadata-fmvikBA0.mjs.map +1 -0
  134. package/dist/{core/path.d.ts → path-LmwfhfyH.d.mts} +7 -3
  135. package/dist/path-LmwfhfyH.d.mts.map +1 -0
  136. package/dist/plugin-DIoPIpSm.d.mts +95 -0
  137. package/dist/plugin-DIoPIpSm.d.mts.map +1 -0
  138. package/dist/query-7cdHF6ry.mjs +164 -0
  139. package/dist/query-7cdHF6ry.mjs.map +1 -0
  140. package/dist/{core/reactivity.d.ts → reactivity-BbS-99ow.d.mts} +21 -20
  141. package/dist/reactivity-BbS-99ow.d.mts.map +1 -0
  142. package/package.json +73 -43
  143. package/dist/chunk-DVVP7zzD.js +0 -7
  144. package/dist/core/adapter.d.ts +0 -109
  145. package/dist/core/adapter.d.ts.map +0 -1
  146. package/dist/core/adapter.js +0 -0
  147. package/dist/core/app-module.d.ts +0 -28
  148. package/dist/core/app-module.d.ts.map +0 -1
  149. package/dist/core/app-module.js +0 -0
  150. package/dist/core/cache.d.ts.map +0 -1
  151. package/dist/core/cache.js +0 -57
  152. package/dist/core/container.d.ts +0 -63
  153. package/dist/core/container.d.ts.map +0 -1
  154. package/dist/core/container.js +0 -117
  155. package/dist/core/cron.d.ts.map +0 -1
  156. package/dist/core/cron.js +0 -22
  157. package/dist/core/decorators.d.ts +0 -153
  158. package/dist/core/decorators.d.ts.map +0 -1
  159. package/dist/core/decorators.js +0 -141
  160. package/dist/core/errors.d.ts +0 -64
  161. package/dist/core/errors.d.ts.map +0 -1
  162. package/dist/core/errors.js +0 -67
  163. package/dist/core/index.d.ts +0 -14
  164. package/dist/core/index.d.ts.map +0 -1
  165. package/dist/core/interfaces.d.ts +0 -44
  166. package/dist/core/interfaces.d.ts.map +0 -1
  167. package/dist/core/interfaces.js +0 -25
  168. package/dist/core/logger.d.ts +0 -43
  169. package/dist/core/logger.d.ts.map +0 -1
  170. package/dist/core/logger.js +0 -54
  171. package/dist/core/path.d.ts.map +0 -1
  172. package/dist/core/path.js +0 -12
  173. package/dist/core/plugin.d.ts +0 -90
  174. package/dist/core/plugin.d.ts.map +0 -1
  175. package/dist/core/plugin.js +0 -0
  176. package/dist/core/reactivity.d.ts.map +0 -1
  177. package/dist/core/reactivity.js +0 -101
  178. package/dist/core-B6Okew3W.js +0 -7
  179. package/dist/http/application.d.ts +0 -103
  180. package/dist/http/application.d.ts.map +0 -1
  181. package/dist/http/application.js +0 -167
  182. package/dist/http/bootstrap.d.ts +0 -22
  183. package/dist/http/bootstrap.d.ts.map +0 -1
  184. package/dist/http/bootstrap.js +0 -40
  185. package/dist/http/context.d.ts +0 -129
  186. package/dist/http/context.d.ts.map +0 -1
  187. package/dist/http/context.js +0 -115
  188. package/dist/http/index.d.ts +0 -16
  189. package/dist/http/index.d.ts.map +0 -1
  190. package/dist/http/middleware/cors.d.ts +0 -43
  191. package/dist/http/middleware/cors.d.ts.map +0 -1
  192. package/dist/http/middleware/cors.js +0 -31
  193. package/dist/http/middleware/csrf.d.ts +0 -47
  194. package/dist/http/middleware/csrf.d.ts.map +0 -1
  195. package/dist/http/middleware/csrf.js +0 -25
  196. package/dist/http/middleware/error-handler.d.ts +0 -6
  197. package/dist/http/middleware/error-handler.d.ts.map +0 -1
  198. package/dist/http/middleware/error-handler.js +0 -37
  199. package/dist/http/middleware/helmet.d.ts +0 -36
  200. package/dist/http/middleware/helmet.d.ts.map +0 -1
  201. package/dist/http/middleware/helmet.js +0 -20
  202. package/dist/http/middleware/rate-limit.d.ts +0 -51
  203. package/dist/http/middleware/rate-limit.d.ts.map +0 -1
  204. package/dist/http/middleware/rate-limit.js +0 -46
  205. package/dist/http/middleware/request-id.d.ts +0 -5
  206. package/dist/http/middleware/request-id.d.ts.map +0 -1
  207. package/dist/http/middleware/request-id.js +0 -12
  208. package/dist/http/middleware/request-logger.d.ts +0 -27
  209. package/dist/http/middleware/request-logger.d.ts.map +0 -1
  210. package/dist/http/middleware/request-logger.js +0 -16
  211. package/dist/http/middleware/session.d.ts +0 -62
  212. package/dist/http/middleware/session.d.ts.map +0 -1
  213. package/dist/http/middleware/session.js +0 -76
  214. package/dist/http/middleware/spa.d.ts +0 -93
  215. package/dist/http/middleware/spa.d.ts.map +0 -1
  216. package/dist/http/middleware/spa.js +0 -52
  217. package/dist/http/middleware/upload.d.ts.map +0 -1
  218. package/dist/http/middleware/upload.js +0 -119
  219. package/dist/http/middleware/validate.d.ts +0 -13
  220. package/dist/http/middleware/validate.d.ts.map +0 -1
  221. package/dist/http/middleware/validate.js +0 -45
  222. package/dist/http/middleware/views.d.ts +0 -56
  223. package/dist/http/middleware/views.d.ts.map +0 -1
  224. package/dist/http/middleware/views.js +0 -18
  225. package/dist/http/query/index.d.ts +0 -4
  226. package/dist/http/query/index.d.ts.map +0 -1
  227. package/dist/http/query/index.js +0 -10
  228. package/dist/http/query/parse-query.d.ts +0 -44
  229. package/dist/http/query/parse-query.d.ts.map +0 -1
  230. package/dist/http/query/types.d.ts +0 -100
  231. package/dist/http/query/types.d.ts.map +0 -1
  232. package/dist/http/router-builder.d.ts.map +0 -1
  233. package/dist/http/router-builder.js +0 -37
  234. package/dist/index.d.ts +0 -25
  235. package/dist/index.d.ts.map +0 -1
  236. package/dist/index.js +0 -103
  237. package/dist/query-Bym31XRp.js +0 -88
@@ -0,0 +1,152 @@
1
+ /**
2
+ * @forinda/kickjs v2.1.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import { createHmac, randomUUID, timingSafeEqual } from "node:crypto";
12
+ //#region src/http/middleware/session.ts
13
+ var MemoryStore = class {
14
+ sessions = /* @__PURE__ */ new Map();
15
+ cleanupInterval;
16
+ constructor() {
17
+ this.cleanupInterval = setInterval(() => this.purge(), 6e4);
18
+ this.cleanupInterval.unref();
19
+ }
20
+ async get(sid) {
21
+ const entry = this.sessions.get(sid);
22
+ if (!entry) return null;
23
+ if (Date.now() > entry.expires) {
24
+ this.sessions.delete(sid);
25
+ return null;
26
+ }
27
+ return entry.data;
28
+ }
29
+ async set(sid, data, maxAge) {
30
+ this.sessions.set(sid, {
31
+ data,
32
+ expires: Date.now() + maxAge
33
+ });
34
+ }
35
+ async destroy(sid) {
36
+ this.sessions.delete(sid);
37
+ }
38
+ async touch(sid, maxAge) {
39
+ const entry = this.sessions.get(sid);
40
+ if (entry) entry.expires = Date.now() + maxAge;
41
+ }
42
+ purge() {
43
+ const now = Date.now();
44
+ for (const [sid, entry] of this.sessions) if (now > entry.expires) this.sessions.delete(sid);
45
+ }
46
+ };
47
+ function sign(value, secret) {
48
+ return `s:${value}.${createHmac("sha256", secret).update(value).digest("base64url")}`;
49
+ }
50
+ function unsign(signed, secret) {
51
+ if (!signed.startsWith("s:")) return false;
52
+ const raw = signed.slice(2);
53
+ const dotIndex = raw.lastIndexOf(".");
54
+ if (dotIndex === -1) return false;
55
+ const value = raw.slice(0, dotIndex);
56
+ const providedSig = raw.slice(dotIndex + 1);
57
+ const expectedSig = createHmac("sha256", secret).update(value).digest("base64url");
58
+ const a = Buffer.from(providedSig);
59
+ const b = Buffer.from(expectedSig);
60
+ if (a.length !== b.length || !timingSafeEqual(a, b)) return false;
61
+ return value;
62
+ }
63
+ /**
64
+ * Session management middleware.
65
+ *
66
+ * Attaches a `req.session` object with `id`, `data`, `regenerate()`,
67
+ * `destroy()`, and `save()` methods. Session IDs are signed with
68
+ * HMAC-SHA256 to prevent cookie tampering.
69
+ *
70
+ * @example
71
+ * ```ts
72
+ * import { session } from '@forinda/kickjs-http'
73
+ *
74
+ * bootstrap({
75
+ * modules,
76
+ * middleware: [
77
+ * cookieParser(),
78
+ * session({ secret: process.env.SESSION_SECRET! }),
79
+ * // ... other middleware
80
+ * ],
81
+ * })
82
+ * ```
83
+ */
84
+ function session(options) {
85
+ const { secret, cookieName = "kick.sid", maxAge = 864e5, rolling = false, saveUninitialized = true, store = new MemoryStore(), cookie: cookieOpts = {} } = options;
86
+ const cookieDefaults = {
87
+ httpOnly: cookieOpts.httpOnly ?? true,
88
+ secure: cookieOpts.secure ?? process.env.NODE_ENV === "production",
89
+ sameSite: cookieOpts.sameSite ?? "lax",
90
+ path: cookieOpts.path ?? "/",
91
+ ...cookieOpts.domain ? { domain: cookieOpts.domain } : {},
92
+ maxAge
93
+ };
94
+ return async (req, res, next) => {
95
+ const signedCookie = (req.cookies || {})[cookieName];
96
+ let sid = false;
97
+ let sessionData = null;
98
+ let isNew = false;
99
+ if (signedCookie) {
100
+ sid = unsign(signedCookie, secret);
101
+ if (sid) sessionData = await store.get(sid);
102
+ }
103
+ if (!sid || !sessionData) {
104
+ sid = randomUUID();
105
+ sessionData = {};
106
+ isNew = true;
107
+ }
108
+ let currentSid = sid;
109
+ let currentData = { ...sessionData };
110
+ let destroyed = false;
111
+ const sessionObj = {
112
+ get id() {
113
+ return currentSid;
114
+ },
115
+ data: currentData,
116
+ async regenerate() {
117
+ await store.destroy(currentSid);
118
+ currentSid = randomUUID();
119
+ currentData = {};
120
+ sessionObj.data = currentData;
121
+ await store.set(currentSid, currentData, maxAge);
122
+ res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
123
+ },
124
+ async destroy() {
125
+ await store.destroy(currentSid);
126
+ destroyed = true;
127
+ currentData = {};
128
+ sessionObj.data = currentData;
129
+ res.clearCookie(cookieName, { path: cookieDefaults.path });
130
+ },
131
+ async save() {
132
+ if (!destroyed) await store.set(currentSid, currentData, maxAge);
133
+ }
134
+ };
135
+ req.session = sessionObj;
136
+ if (isNew) res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
137
+ res.on("finish", async () => {
138
+ if (destroyed) return;
139
+ if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return;
140
+ await store.set(currentSid, currentData, maxAge);
141
+ if (rolling && !isNew) {
142
+ if (store.touch) await store.touch(currentSid, maxAge);
143
+ }
144
+ });
145
+ if (rolling && !isNew) res.cookie(cookieName, sign(currentSid, secret), cookieDefaults);
146
+ next();
147
+ };
148
+ }
149
+ //#endregion
150
+ export { session };
151
+
152
+ //# sourceMappingURL=session.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.mjs","names":[],"sources":["../../../src/http/middleware/session.ts"],"sourcesContent":["import { randomUUID, createHmac, timingSafeEqual } from 'node:crypto'\nimport type { Request, Response, NextFunction } from 'express'\n\nexport interface SessionData {\n [key: string]: unknown\n}\n\nexport interface SessionStore {\n get(sid: string): Promise<SessionData | null>\n set(sid: string, data: SessionData, maxAge: number): Promise<void>\n destroy(sid: string): Promise<void>\n touch?(sid: string, maxAge: number): Promise<void>\n}\n\nexport interface Session {\n id: string\n data: SessionData\n regenerate(): Promise<void>\n destroy(): Promise<void>\n save(): Promise<void>\n}\n\nexport interface SessionOptions {\n /** Secret used to sign the session cookie (required) */\n secret: string\n /** Cookie name (default: 'kick.sid') */\n cookieName?: string\n /** Session max age in milliseconds (default: 86400000 = 24h) */\n maxAge?: number\n /** Reset maxAge on every response (default: false) */\n rolling?: boolean\n /** Save new sessions that have not been modified (default: true) */\n saveUninitialized?: boolean\n /** Cookie options */\n cookie?: {\n httpOnly?: boolean\n secure?: boolean\n sameSite?: 'strict' | 'lax' | 'none'\n path?: string\n domain?: string\n }\n /** Custom session store (default: in-memory store with TTL cleanup) */\n store?: SessionStore\n}\n\n// ── In-Memory Store ───────────────────────────────────────────────────\n\nclass MemoryStore implements SessionStore {\n private sessions = new Map<string, { data: SessionData; expires: number }>()\n private cleanupInterval: ReturnType<typeof setInterval>\n\n constructor() {\n // Purge expired sessions every 60 seconds\n this.cleanupInterval = setInterval(() => this.purge(), 60_000)\n this.cleanupInterval.unref()\n }\n\n async get(sid: string): Promise<SessionData | null> {\n const entry = this.sessions.get(sid)\n if (!entry) return null\n if (Date.now() > entry.expires) {\n this.sessions.delete(sid)\n return null\n }\n return entry.data\n }\n\n async set(sid: string, data: SessionData, maxAge: number): Promise<void> {\n this.sessions.set(sid, { data, expires: Date.now() + maxAge })\n }\n\n async destroy(sid: string): Promise<void> {\n this.sessions.delete(sid)\n }\n\n async touch(sid: string, maxAge: number): Promise<void> {\n const entry = this.sessions.get(sid)\n if (entry) {\n entry.expires = Date.now() + maxAge\n }\n }\n\n private purge() {\n const now = Date.now()\n for (const [sid, entry] of this.sessions) {\n if (now > entry.expires) {\n this.sessions.delete(sid)\n }\n }\n }\n}\n\n// ── Cookie Signing ────────────────────────────────────────────────────\n\nfunction sign(value: string, secret: string): string {\n const signature = createHmac('sha256', secret).update(value).digest('base64url')\n return `s:${value}.${signature}`\n}\n\nfunction unsign(signed: string, secret: string): string | false {\n if (!signed.startsWith('s:')) return false\n const raw = signed.slice(2)\n const dotIndex = raw.lastIndexOf('.')\n if (dotIndex === -1) return false\n\n const value = raw.slice(0, dotIndex)\n const providedSig = raw.slice(dotIndex + 1)\n const expectedSig = createHmac('sha256', secret).update(value).digest('base64url')\n\n const a = Buffer.from(providedSig)\n const b = Buffer.from(expectedSig)\n\n if (a.length !== b.length || !timingSafeEqual(a, b)) {\n return false\n }\n\n return value\n}\n\n// ── Middleware Factory ────────────────────────────────────────────────\n\n/**\n * Session management middleware.\n *\n * Attaches a `req.session` object with `id`, `data`, `regenerate()`,\n * `destroy()`, and `save()` methods. Session IDs are signed with\n * HMAC-SHA256 to prevent cookie tampering.\n *\n * @example\n * ```ts\n * import { session } from '@forinda/kickjs-http'\n *\n * bootstrap({\n * modules,\n * middleware: [\n * cookieParser(),\n * session({ secret: process.env.SESSION_SECRET! }),\n * // ... other middleware\n * ],\n * })\n * ```\n */\nexport function session(options: SessionOptions) {\n const {\n secret,\n cookieName = 'kick.sid',\n maxAge = 86_400_000,\n rolling = false,\n saveUninitialized = true,\n store = new MemoryStore(),\n cookie: cookieOpts = {},\n } = options\n\n const cookieDefaults = {\n httpOnly: cookieOpts.httpOnly ?? true,\n secure: cookieOpts.secure ?? process.env.NODE_ENV === 'production',\n sameSite: cookieOpts.sameSite ?? ('lax' as const),\n path: cookieOpts.path ?? '/',\n ...(cookieOpts.domain ? { domain: cookieOpts.domain } : {}),\n maxAge,\n }\n\n return async (req: Request, res: Response, next: NextFunction) => {\n const cookies = (req as any).cookies || {}\n const signedCookie = cookies[cookieName]\n let sid: string | false = false\n let sessionData: SessionData | null = null\n let isNew = false\n\n // Attempt to recover existing session\n if (signedCookie) {\n sid = unsign(signedCookie, secret)\n if (sid) {\n sessionData = await store.get(sid)\n }\n }\n\n // Create new session if none found\n if (!sid || !sessionData) {\n sid = randomUUID()\n sessionData = {}\n isNew = true\n }\n\n let currentSid = sid as string\n let currentData = { ...sessionData }\n let destroyed = false\n\n const sessionObj: Session = {\n get id() {\n return currentSid\n },\n data: currentData,\n\n async regenerate() {\n await store.destroy(currentSid)\n currentSid = randomUUID()\n currentData = {}\n sessionObj.data = currentData\n await store.set(currentSid, currentData, maxAge)\n res.cookie(cookieName, sign(currentSid, secret), cookieDefaults)\n },\n\n async destroy() {\n await store.destroy(currentSid)\n destroyed = true\n currentData = {}\n sessionObj.data = currentData\n res.clearCookie(cookieName, { path: cookieDefaults.path })\n },\n\n async save() {\n if (!destroyed) {\n await store.set(currentSid, currentData, maxAge)\n }\n },\n }\n\n ;(req as any).session = sessionObj\n\n // Set cookie for new sessions\n if (isNew) {\n res.cookie(cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n // Auto-save on response finish\n res.on('finish', async () => {\n if (destroyed) return\n if (isNew && !saveUninitialized && Object.keys(currentData).length === 0) return\n\n await store.set(currentSid, currentData, maxAge)\n\n if (rolling && !isNew) {\n if (store.touch) {\n await store.touch(currentSid, maxAge)\n }\n }\n })\n\n // Rolling: refresh cookie on every response\n if (rolling && !isNew) {\n res.cookie(cookieName, sign(currentSid, secret), cookieDefaults)\n }\n\n next()\n }\n}\n"],"mappings":";;;;;;;;;;;;AA+CA,IAAM,cAAN,MAA0C;CACxC,2BAAmB,IAAI,KAAqD;CAC5E;CAEA,cAAc;AAEZ,OAAK,kBAAkB,kBAAkB,KAAK,OAAO,EAAE,IAAO;AAC9D,OAAK,gBAAgB,OAAO;;CAG9B,MAAM,IAAI,KAA0C;EAClD,MAAM,QAAQ,KAAK,SAAS,IAAI,IAAI;AACpC,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI,KAAK,KAAK,GAAG,MAAM,SAAS;AAC9B,QAAK,SAAS,OAAO,IAAI;AACzB,UAAO;;AAET,SAAO,MAAM;;CAGf,MAAM,IAAI,KAAa,MAAmB,QAA+B;AACvE,OAAK,SAAS,IAAI,KAAK;GAAE;GAAM,SAAS,KAAK,KAAK,GAAG;GAAQ,CAAC;;CAGhE,MAAM,QAAQ,KAA4B;AACxC,OAAK,SAAS,OAAO,IAAI;;CAG3B,MAAM,MAAM,KAAa,QAA+B;EACtD,MAAM,QAAQ,KAAK,SAAS,IAAI,IAAI;AACpC,MAAI,MACF,OAAM,UAAU,KAAK,KAAK,GAAG;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;AAGlE,QAAM"}
@@ -0,0 +1,101 @@
1
+
2
+ import { r as AppAdapter, t as AdapterContext } from "../../adapter-BqGjZCSm.mjs";
3
+ //#region src/http/middleware/spa.d.ts
4
+ interface SpaAdapterOptions {
5
+ /**
6
+ * Directory containing the built SPA files (index.html, assets, etc.)
7
+ * Default: 'dist/client'
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * // Vue: 'dist'
12
+ * // React (Vite): 'dist'
13
+ * // React (CRA): 'build'
14
+ * // Svelte: 'build'
15
+ * // Angular: 'dist/my-app/browser'
16
+ * ```
17
+ */
18
+ clientDir?: string;
19
+ /**
20
+ * URL prefix for API routes. SPA fallback only applies to
21
+ * non-API routes (routes NOT starting with this prefix).
22
+ * Default: '/api'
23
+ *
24
+ * Set to an array for multiple prefixes:
25
+ * ```ts
26
+ * apiPrefix: ['/api', '/graphql', '/_debug']
27
+ * ```
28
+ */
29
+ apiPrefix?: string | string[];
30
+ /**
31
+ * Additional paths to exclude from SPA fallback.
32
+ * These paths will NOT serve index.html.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * exclude: ['/health', '/metrics', '/ws']
37
+ * ```
38
+ */
39
+ exclude?: string[];
40
+ /**
41
+ * Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')
42
+ * Set to false to disable caching headers.
43
+ */
44
+ cacheControl?: string | false;
45
+ /**
46
+ * Cache-Control for index.html (default: 'no-cache')
47
+ * index.html should not be cached to ensure clients get fresh builds.
48
+ */
49
+ indexCacheControl?: string;
50
+ }
51
+ /**
52
+ * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside
53
+ * your KickJS API. API routes are handled by controllers; everything else
54
+ * falls back to index.html for client-side routing.
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { SpaAdapter } from '@forinda/kickjs-http/spa'
59
+ *
60
+ * bootstrap({
61
+ * modules,
62
+ * adapters: [
63
+ * new SpaAdapter({
64
+ * clientDir: 'dist/client', // or 'build', 'dist', etc.
65
+ * apiPrefix: '/api',
66
+ * }),
67
+ * ],
68
+ * })
69
+ * ```
70
+ *
71
+ * File structure:
72
+ * ```
73
+ * dist/
74
+ * client/ ← SPA build output
75
+ * index.html
76
+ * assets/
77
+ * app.js
78
+ * style.css
79
+ * server/ ← KickJS server
80
+ * ```
81
+ */
82
+ declare class SpaAdapter implements AppAdapter {
83
+ private options;
84
+ name: string;
85
+ private clientDir;
86
+ private apiPrefixes;
87
+ private excludePaths;
88
+ private cacheControl;
89
+ private indexCacheControl;
90
+ private indexHtml;
91
+ constructor(options?: SpaAdapterOptions);
92
+ beforeMount({
93
+ app
94
+ }: AdapterContext): void;
95
+ beforeStart({
96
+ app
97
+ }: AdapterContext): void;
98
+ }
99
+ //#endregion
100
+ export { SpaAdapter, SpaAdapterOptions };
101
+ //# sourceMappingURL=spa.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spa.d.mts","names":[],"sources":["../../../src/http/middleware/spa.ts"],"mappings":";;;UAMiB,iBAAA;;;AAAjB;;;;;;;;;;;EAcE,SAAA;EAqEsB;;;;;;;;;;EAzDtB,SAAA;EAkEoB;;;;;;;;;EAvDpB,OAAA;EAuDoB;;;;EAjDpB,YAAA;EAoGA;;;;EA9FA,iBAAA;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAkCW,UAAA,YAAsB,UAAA;EAAA,QASb,OAAA;EARpB,IAAA;EAAA,QACQ,SAAA;EAAA,QACA,WAAA;EAAA,QACA,YAAA;EAAA,QACA,YAAA;EAAA,QACA,iBAAA;EAAA,QACA,SAAA;cAEY,OAAA,GAAS,iBAAA;EAU7B,WAAA,CAAA;IAAc;EAAA,GAAO,cAAA;EAyCrB,WAAA,CAAA;IAAc;EAAA,GAAO,cAAA;AAAA"}
@@ -0,0 +1,108 @@
1
+ /**
2
+ * @forinda/kickjs v2.1.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import { t as __require } from "../../chunk-C5Qp-JxE.mjs";
12
+ import { Logger } from "../../core/logger.mjs";
13
+ import "../../core-BL_H8fEZ.mjs";
14
+ import { join, resolve } from "node:path";
15
+ import { existsSync, readFileSync } from "node:fs";
16
+ //#region src/http/middleware/spa.ts
17
+ const log = Logger.for("SpaAdapter");
18
+ /**
19
+ * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside
20
+ * your KickJS API. API routes are handled by controllers; everything else
21
+ * falls back to index.html for client-side routing.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { SpaAdapter } from '@forinda/kickjs-http/spa'
26
+ *
27
+ * bootstrap({
28
+ * modules,
29
+ * adapters: [
30
+ * new SpaAdapter({
31
+ * clientDir: 'dist/client', // or 'build', 'dist', etc.
32
+ * apiPrefix: '/api',
33
+ * }),
34
+ * ],
35
+ * })
36
+ * ```
37
+ *
38
+ * File structure:
39
+ * ```
40
+ * dist/
41
+ * client/ ← SPA build output
42
+ * index.html
43
+ * assets/
44
+ * app.js
45
+ * style.css
46
+ * server/ ← KickJS server
47
+ * ```
48
+ */
49
+ var SpaAdapter = class {
50
+ name = "SpaAdapter";
51
+ clientDir;
52
+ apiPrefixes;
53
+ excludePaths;
54
+ cacheControl;
55
+ indexCacheControl;
56
+ indexHtml = null;
57
+ constructor(options = {}) {
58
+ this.options = options;
59
+ this.clientDir = resolve(options.clientDir ?? "dist/client");
60
+ this.excludePaths = options.exclude ?? [];
61
+ this.cacheControl = options.cacheControl ?? "public, max-age=31536000, immutable";
62
+ this.indexCacheControl = options.indexCacheControl ?? "no-cache";
63
+ const prefix = options.apiPrefix ?? "/api";
64
+ this.apiPrefixes = Array.isArray(prefix) ? prefix : [prefix];
65
+ }
66
+ beforeMount({ app }) {
67
+ if (!existsSync(this.clientDir)) {
68
+ log.warn(`SPA client directory not found: ${this.clientDir}`);
69
+ log.warn("Build your frontend first, or set clientDir to the correct path.");
70
+ return;
71
+ }
72
+ const indexPath = join(this.clientDir, "index.html");
73
+ if (existsSync(indexPath)) this.indexHtml = readFileSync(indexPath, "utf-8");
74
+ else {
75
+ log.warn(`index.html not found in ${this.clientDir}`);
76
+ return;
77
+ }
78
+ try {
79
+ const express = __require("express");
80
+ const staticOpts = {};
81
+ if (this.cacheControl) staticOpts.setHeaders = (res, filePath) => {
82
+ if (filePath.endsWith(".html")) res.setHeader("Cache-Control", this.indexCacheControl);
83
+ else res.setHeader("Cache-Control", this.cacheControl);
84
+ };
85
+ app.use(express.static(this.clientDir, staticOpts));
86
+ } catch {
87
+ log.error("express.static not available — SPA static file serving disabled");
88
+ return;
89
+ }
90
+ log.info(`Serving SPA from ${this.clientDir}`);
91
+ }
92
+ beforeStart({ app }) {
93
+ if (!this.indexHtml) return;
94
+ app.use((req, res, next) => {
95
+ for (const prefix of this.apiPrefixes) if (req.path.startsWith(prefix)) return next();
96
+ for (const path of this.excludePaths) if (req.path.startsWith(path)) return next();
97
+ if (req.path.includes(".")) return next();
98
+ if (req.method !== "GET") return next();
99
+ res.setHeader("Content-Type", "text/html");
100
+ res.setHeader("Cache-Control", this.indexCacheControl);
101
+ res.send(this.indexHtml);
102
+ });
103
+ }
104
+ };
105
+ //#endregion
106
+ export { SpaAdapter };
107
+
108
+ //# sourceMappingURL=spa.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spa.mjs","names":[],"sources":["../../../src/http/middleware/spa.ts"],"sourcesContent":["import { existsSync, readFileSync } from 'node:fs'\nimport { resolve, join } from 'node:path'\nimport { Logger, type AppAdapter, type AdapterContext } from '../../core'\n\nconst log = Logger.for('SpaAdapter')\n\nexport interface SpaAdapterOptions {\n /**\n * Directory containing the built SPA files (index.html, assets, etc.)\n * Default: 'dist/client'\n *\n * @example\n * ```ts\n * // Vue: 'dist'\n * // React (Vite): 'dist'\n * // React (CRA): 'build'\n * // Svelte: 'build'\n * // Angular: 'dist/my-app/browser'\n * ```\n */\n clientDir?: string\n\n /**\n * URL prefix for API routes. SPA fallback only applies to\n * non-API routes (routes NOT starting with this prefix).\n * Default: '/api'\n *\n * Set to an array for multiple prefixes:\n * ```ts\n * apiPrefix: ['/api', '/graphql', '/_debug']\n * ```\n */\n apiPrefix?: string | string[]\n\n /**\n * Additional paths to exclude from SPA fallback.\n * These paths will NOT serve index.html.\n *\n * @example\n * ```ts\n * exclude: ['/health', '/metrics', '/ws']\n * ```\n */\n exclude?: string[]\n\n /**\n * Cache-Control header for static assets (default: 'public, max-age=31536000, immutable')\n * Set to false to disable caching headers.\n */\n cacheControl?: string | false\n\n /**\n * Cache-Control for index.html (default: 'no-cache')\n * index.html should not be cached to ensure clients get fresh builds.\n */\n indexCacheControl?: string\n}\n\n/**\n * SPA adapter — serve a Vue, React, Svelte, or Angular build alongside\n * your KickJS API. API routes are handled by controllers; everything else\n * falls back to index.html for client-side routing.\n *\n * @example\n * ```ts\n * import { SpaAdapter } from '@forinda/kickjs-http/spa'\n *\n * bootstrap({\n * modules,\n * adapters: [\n * new SpaAdapter({\n * clientDir: 'dist/client', // or 'build', 'dist', etc.\n * apiPrefix: '/api',\n * }),\n * ],\n * })\n * ```\n *\n * File structure:\n * ```\n * dist/\n * client/ ← SPA build output\n * index.html\n * assets/\n * app.js\n * style.css\n * server/ ← KickJS server\n * ```\n */\nexport class SpaAdapter implements AppAdapter {\n name = 'SpaAdapter'\n private clientDir: string\n private apiPrefixes: string[]\n private excludePaths: string[]\n private cacheControl: string | false\n private indexCacheControl: string\n private indexHtml: string | null = null\n\n constructor(private options: SpaAdapterOptions = {}) {\n this.clientDir = resolve(options.clientDir ?? 'dist/client')\n this.excludePaths = options.exclude ?? []\n this.cacheControl = options.cacheControl ?? 'public, max-age=31536000, immutable'\n this.indexCacheControl = options.indexCacheControl ?? 'no-cache'\n\n const prefix = options.apiPrefix ?? '/api'\n this.apiPrefixes = Array.isArray(prefix) ? prefix : [prefix]\n }\n\n beforeMount({ app }: AdapterContext): void {\n if (!existsSync(this.clientDir)) {\n log.warn(`SPA client directory not found: ${this.clientDir}`)\n log.warn('Build your frontend first, or set clientDir to the correct path.')\n return\n }\n\n // Read index.html into memory\n const indexPath = join(this.clientDir, 'index.html')\n if (existsSync(indexPath)) {\n this.indexHtml = readFileSync(indexPath, 'utf-8')\n } else {\n log.warn(`index.html not found in ${this.clientDir}`)\n return\n }\n\n // Serve static files with cache headers\n try {\n // Dynamic import to avoid hard dependency on express.static\n const express = require('express')\n const staticOpts: any = {}\n\n if (this.cacheControl) {\n staticOpts.setHeaders = (res: any, filePath: string) => {\n if (filePath.endsWith('.html')) {\n res.setHeader('Cache-Control', this.indexCacheControl)\n } else {\n res.setHeader('Cache-Control', this.cacheControl as string)\n }\n }\n }\n\n app.use(express.static(this.clientDir, staticOpts))\n } catch {\n log.error('express.static not available — SPA static file serving disabled')\n return\n }\n\n log.info(`Serving SPA from ${this.clientDir}`)\n }\n\n beforeStart({ app }: AdapterContext): void {\n if (!this.indexHtml) return\n\n // SPA fallback: serve index.html for all non-API, non-file routes\n app.use((req: any, res: any, next: any) => {\n // Skip API routes\n for (const prefix of this.apiPrefixes) {\n if (req.path.startsWith(prefix)) return next()\n }\n\n // Skip excluded paths\n for (const path of this.excludePaths) {\n if (req.path.startsWith(path)) return next()\n }\n\n // Skip requests for files (have an extension)\n if (req.path.includes('.')) return next()\n\n // Skip non-GET requests\n if (req.method !== 'GET') return next()\n\n // Serve index.html\n res.setHeader('Content-Type', 'text/html')\n res.setHeader('Cache-Control', this.indexCacheControl)\n res.send(this.indexHtml)\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAIA,MAAM,MAAM,OAAO,IAAI,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqFpC,IAAa,aAAb,MAA8C;CAC5C,OAAO;CACP;CACA;CACA;CACA;CACA;CACA,YAAmC;CAEnC,YAAY,UAAqC,EAAE,EAAE;AAAjC,OAAA,UAAA;AAClB,OAAK,YAAY,QAAQ,QAAQ,aAAa,cAAc;AAC5D,OAAK,eA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AAI,UAAU,gBAAgB,YAAY;AAC1C,OAAI,UAAU,iBAAiB,KAAK,kBAAkB;AACtD,OAAI,KAAK,KAAK,UAAU;IACxB"}
@@ -1,6 +1,9 @@
1
- import type { Request, Response, NextFunction, RequestHandler } from 'express';
2
- import { type Options as MulterOptions } from 'multer';
3
- import type { BaseUploadOptions, FileUploadConfig } from '../../core';
1
+
2
+ import { f as FileUploadConfig, i as BaseUploadOptions } from "../../decorators-CQ93ak6Z.mjs";
3
+ import { NextFunction, Request, RequestHandler, Response } from "express";
4
+ import { Options } from "multer";
5
+
6
+ //#region src/http/middleware/upload.d.ts
4
7
  /**
5
8
  * Resolves a list of file type identifiers to MIME type strings.
6
9
  * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).
@@ -11,17 +14,17 @@ import type { BaseUploadOptions, FileUploadConfig } from '../../core';
11
14
  * // → ['image/jpeg', 'image/png', 'application/pdf']
12
15
  * ```
13
16
  */
14
- export declare function resolveMimeTypes(types: string[]): string[];
17
+ declare function resolveMimeTypes(types: string[]): string[];
15
18
  /**
16
19
  * Upload options for the middleware.
17
20
  * Extends BaseUploadOptions from core (shared with @FileUpload decorator)
18
21
  * and adds Multer-specific storage options.
19
22
  */
20
- export interface UploadOptions extends BaseUploadOptions {
21
- /** Multer storage config (default: memory storage) */
22
- storage?: MulterOptions['storage'];
23
- /** Multer dest for disk storage shorthand */
24
- dest?: string;
23
+ interface UploadOptions extends BaseUploadOptions {
24
+ /** Multer storage config (default: memory storage) */
25
+ storage?: Options['storage'];
26
+ /** Multer dest for disk storage shorthand */
27
+ dest?: string;
25
28
  }
26
29
  /**
27
30
  * Single file upload middleware. Attaches the file to `req.file`.
@@ -58,18 +61,19 @@ declare function none(options?: UploadOptions): RequestHandler;
58
61
  * }
59
62
  * ```
60
63
  */
61
- export declare function cleanupFiles(): (req: Request, res: Response, next: NextFunction) => void;
64
+ declare function cleanupFiles(): (req: Request, res: Response, next: NextFunction) => void;
62
65
  /**
63
66
  * Build upload middleware from a @FileUpload decorator config.
64
67
  * Used internally by the router builder when it detects FILE_UPLOAD metadata.
65
68
  * Accepts the same FileUploadConfig interface used by the @FileUpload decorator.
66
69
  */
67
- export declare function buildUploadMiddleware(config: FileUploadConfig): RequestHandler;
70
+ declare function buildUploadMiddleware(config: FileUploadConfig): RequestHandler;
68
71
  /** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */
69
- export declare const upload: {
70
- single: typeof single;
71
- array: typeof array;
72
- none: typeof none;
72
+ declare const upload: {
73
+ single: typeof single;
74
+ array: typeof array;
75
+ none: typeof none;
73
76
  };
74
- export {};
75
- //# sourceMappingURL=upload.d.ts.map
77
+ //#endregion
78
+ export { UploadOptions, buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
79
+ //# sourceMappingURL=upload.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upload.d.mts","names":[],"sources":["../../../src/http/middleware/upload.ts"],"mappings":";;;;;;;;;AAsEA;;;;;AAYA;;iBAZgB,gBAAA,CAAiB,KAAA;;;;;;UAYhB,aAAA,SAAsB,iBAAA;EAIjC;EAFJ,OAAA,GAAU,OAAA;EAmEG;EAjEb,IAAA;AAAA;;;;;;;AAiE6E;;;;;;iBAAtE,MAAA,CAAO,SAAA,UAAmB,OAAA,GAAS,aAAA,GAAqB,cAAA;;;;iBAQxD,KAAA,CAAM,SAAA,UAAmB,QAAA,WAAe,OAAA,GAAS,aAAA,GAAqB,cAAA;AAAc;;;AAAA,iBAQpF,IAAA,CAAK,OAAA,GAAS,aAAA,GAAqB,cAAA;;;;;;AAmB5C;;;;;;;;;iBAAgB,YAAA,CAAA,IACN,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,QAAA,EAAU,IAAA,EAAM,YAAA;;;;;;iBA+B7B,qBAAA,CAAsB,MAAA,EAAQ,gBAAA,GAAmB,cAAA;AAAjE;AAAA,cAmBa,MAAA"}
@@ -0,0 +1,191 @@
1
+ /**
2
+ * @forinda/kickjs v2.1.0
3
+ *
4
+ * Copyright (c) Felix Orinda
5
+ *
6
+ * This source code is licensed under the MIT license found in the
7
+ * LICENSE file in the root directory of this source tree.
8
+ *
9
+ * @license MIT
10
+ */
11
+ import { unlink } from "node:fs/promises";
12
+ import multer from "multer";
13
+ //#region src/http/middleware/upload.ts
14
+ /**
15
+ * Maps short file extensions to their MIME types.
16
+ * Users can pass `['jpg', 'png', 'pdf']` instead of full MIME strings.
17
+ */
18
+ const MIME_MAP = {
19
+ jpg: "image/jpeg",
20
+ jpeg: "image/jpeg",
21
+ png: "image/png",
22
+ gif: "image/gif",
23
+ webp: "image/webp",
24
+ svg: "image/svg+xml",
25
+ bmp: "image/bmp",
26
+ ico: "image/x-icon",
27
+ tiff: "image/tiff",
28
+ tif: "image/tiff",
29
+ avif: "image/avif",
30
+ pdf: "application/pdf",
31
+ doc: "application/msword",
32
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
33
+ xls: "application/vnd.ms-excel",
34
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
35
+ ppt: "application/vnd.ms-powerpoint",
36
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
37
+ odt: "application/vnd.oasis.opendocument.text",
38
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
39
+ odp: "application/vnd.oasis.opendocument.presentation",
40
+ rtf: "application/rtf",
41
+ txt: "text/plain",
42
+ csv: "text/csv",
43
+ zip: "application/zip",
44
+ gz: "application/gzip",
45
+ tar: "application/x-tar",
46
+ rar: "application/vnd.rar",
47
+ "7z": "application/x-7z-compressed",
48
+ mp3: "audio/mpeg",
49
+ wav: "audio/wav",
50
+ ogg: "audio/ogg",
51
+ flac: "audio/flac",
52
+ aac: "audio/aac",
53
+ mp4: "video/mp4",
54
+ webm: "video/webm",
55
+ avi: "video/x-msvideo",
56
+ mov: "video/quicktime",
57
+ mkv: "video/x-matroska",
58
+ json: "application/json",
59
+ xml: "application/xml",
60
+ html: "text/html"
61
+ };
62
+ /**
63
+ * Resolves a list of file type identifiers to MIME type strings.
64
+ * Accepts short extensions (`'jpg'`, `'pdf'`) or full MIME types (`'image/jpeg'`).
65
+ *
66
+ * @example
67
+ * ```ts
68
+ * resolveMimeTypes(['jpg', 'png', 'application/pdf'])
69
+ * // → ['image/jpeg', 'image/png', 'application/pdf']
70
+ * ```
71
+ */
72
+ function resolveMimeTypes(types) {
73
+ return types.map((t) => {
74
+ return MIME_MAP[t.toLowerCase().replace(/^\./, "")] ?? t;
75
+ });
76
+ }
77
+ function createMulter(options) {
78
+ const mimeMap = options.customMimeMap ? {
79
+ ...MIME_MAP,
80
+ ...options.customMimeMap
81
+ } : MIME_MAP;
82
+ const limits = { fileSize: options.maxSize ?? 5 * 1024 * 1024 };
83
+ let fileFilter;
84
+ if (typeof options.allowedTypes === "function") {
85
+ const filterFn = options.allowedTypes;
86
+ fileFilter = (_req, file, cb) => {
87
+ if (filterFn(file.mimetype, file.originalname)) cb(null, true);
88
+ else cb(/* @__PURE__ */ new Error(`File type ${file.mimetype} is not allowed`));
89
+ };
90
+ } else if (Array.isArray(options.allowedTypes)) {
91
+ const resolvedTypes = options.allowedTypes.map((t) => {
92
+ return mimeMap[t.toLowerCase().replace(/^\./, "")] ?? t;
93
+ });
94
+ fileFilter = (_req, file, cb) => {
95
+ if (resolvedTypes.some((type) => {
96
+ if (type.endsWith("/*")) return file.mimetype.startsWith(type.replace("/*", "/"));
97
+ return file.mimetype === type;
98
+ })) cb(null, true);
99
+ else cb(/* @__PURE__ */ new Error(`File type ${file.mimetype} is not allowed`));
100
+ };
101
+ }
102
+ return multer({
103
+ limits,
104
+ ...fileFilter ? { fileFilter } : {},
105
+ ...options.storage ? { storage: options.storage } : {},
106
+ ...options.dest ? { dest: options.dest } : {}
107
+ });
108
+ }
109
+ /**
110
+ * Single file upload middleware. Attaches the file to `req.file`.
111
+ *
112
+ * @example
113
+ * ```ts
114
+ * @Post('/avatar')
115
+ * @Middleware(upload.single('avatar', { maxSize: 2 * 1024 * 1024, allowedTypes: ['jpg', 'png'] }))
116
+ * async uploadAvatar(ctx: RequestContext) {
117
+ * ctx.json({ filename: ctx.file.originalname })
118
+ * }
119
+ * ```
120
+ */
121
+ function single(fieldName, options = {}) {
122
+ return createMulter(options).single(fieldName);
123
+ }
124
+ /**
125
+ * Multiple file upload middleware. Attaches files to `req.files`.
126
+ */
127
+ function array(fieldName, maxCount = 10, options = {}) {
128
+ return createMulter(options).array(fieldName, maxCount);
129
+ }
130
+ /**
131
+ * No file upload — just parse multipart form data without file fields.
132
+ */
133
+ function none(options = {}) {
134
+ return createMulter(options).none();
135
+ }
136
+ /**
137
+ * Removes temporary files from disk after the response is sent.
138
+ * Attach this as Express middleware after the upload middleware.
139
+ * Works with both `req.file` (single) and `req.files` (array).
140
+ *
141
+ * @example
142
+ * ```ts
143
+ * @Post('/process')
144
+ * @Middleware(upload.single('document', { dest: '/tmp/uploads' }), cleanupFiles())
145
+ * async processDocument(ctx: RequestContext) {
146
+ * ctx.json({ ok: true })
147
+ * }
148
+ * ```
149
+ */
150
+ function cleanupFiles() {
151
+ return (req, res, next) => {
152
+ res.on("finish", async () => {
153
+ const files = [];
154
+ if (req.file?.path) files.push(req.file);
155
+ if (Array.isArray(req.files)) {
156
+ for (const f of req.files) if (f?.path) files.push(f);
157
+ }
158
+ for (const file of files) try {
159
+ await unlink(file.path);
160
+ } catch {}
161
+ });
162
+ next();
163
+ };
164
+ }
165
+ /**
166
+ * Build upload middleware from a @FileUpload decorator config.
167
+ * Used internally by the router builder when it detects FILE_UPLOAD metadata.
168
+ * Accepts the same FileUploadConfig interface used by the @FileUpload decorator.
169
+ */
170
+ function buildUploadMiddleware(config) {
171
+ const options = {};
172
+ if (config.maxSize) options.maxSize = config.maxSize;
173
+ if (config.allowedTypes) options.allowedTypes = config.allowedTypes;
174
+ if (config.customMimeMap) options.customMimeMap = config.customMimeMap;
175
+ const fieldName = config.fieldName ?? "file";
176
+ switch (config.mode) {
177
+ case "single": return single(fieldName, options);
178
+ case "array": return array(fieldName, config.maxCount ?? 10, options);
179
+ case "none": return none(options);
180
+ }
181
+ }
182
+ /** Upload middleware factory with `.single()`, `.array()`, `.none()` methods */
183
+ const upload = {
184
+ single,
185
+ array,
186
+ none
187
+ };
188
+ //#endregion
189
+ export { buildUploadMiddleware, cleanupFiles, resolveMimeTypes, upload };
190
+
191
+ //# sourceMappingURL=upload.mjs.map