odac 0.9.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 (213) hide show
  1. package/.editorconfig +21 -0
  2. package/.github/workflows/auto-pr-description.yml +49 -0
  3. package/.github/workflows/release.yml +32 -0
  4. package/.github/workflows/test-coverage.yml +58 -0
  5. package/.husky/pre-commit +2 -0
  6. package/.kiro/steering/code-style.md +56 -0
  7. package/.kiro/steering/product.md +20 -0
  8. package/.kiro/steering/structure.md +77 -0
  9. package/.kiro/steering/tech.md +87 -0
  10. package/.prettierrc +10 -0
  11. package/.releaserc.js +134 -0
  12. package/AGENTS.md +84 -0
  13. package/CHANGELOG.md +181 -0
  14. package/CODE_OF_CONDUCT.md +83 -0
  15. package/CONTRIBUTING.md +63 -0
  16. package/LICENSE +661 -0
  17. package/README.md +57 -0
  18. package/SECURITY.md +26 -0
  19. package/bin/candy +10 -0
  20. package/bin/candypack +10 -0
  21. package/cli/index.js +3 -0
  22. package/cli/src/Cli.js +348 -0
  23. package/cli/src/Connector.js +93 -0
  24. package/cli/src/Monitor.js +416 -0
  25. package/core/Candy.js +87 -0
  26. package/core/Commands.js +239 -0
  27. package/core/Config.js +1094 -0
  28. package/core/Lang.js +52 -0
  29. package/core/Log.js +43 -0
  30. package/core/Process.js +26 -0
  31. package/docs/backend/01-overview/01-whats-in-the-candy-box.md +9 -0
  32. package/docs/backend/01-overview/02-super-handy-helper-functions.md +9 -0
  33. package/docs/backend/01-overview/03-development-server.md +79 -0
  34. package/docs/backend/02-structure/01-typical-project-layout.md +39 -0
  35. package/docs/backend/03-config/00-configuration-overview.md +214 -0
  36. package/docs/backend/03-config/01-database-connection.md +60 -0
  37. package/docs/backend/03-config/02-static-route-mapping-optional.md +20 -0
  38. package/docs/backend/03-config/03-request-timeout.md +11 -0
  39. package/docs/backend/03-config/04-environment-variables.md +227 -0
  40. package/docs/backend/03-config/05-early-hints.md +352 -0
  41. package/docs/backend/04-routing/01-basic-page-routes.md +28 -0
  42. package/docs/backend/04-routing/02-controller-less-view-routes.md +43 -0
  43. package/docs/backend/04-routing/03-api-and-data-routes.md +20 -0
  44. package/docs/backend/04-routing/04-authentication-aware-routes.md +48 -0
  45. package/docs/backend/04-routing/05-advanced-routing.md +14 -0
  46. package/docs/backend/04-routing/06-error-pages.md +101 -0
  47. package/docs/backend/04-routing/07-cron-jobs.md +149 -0
  48. package/docs/backend/05-controllers/01-how-to-build-a-controller.md +17 -0
  49. package/docs/backend/05-controllers/02-your-trusty-candy-assistant.md +20 -0
  50. package/docs/backend/05-controllers/03-controller-classes.md +93 -0
  51. package/docs/backend/05-forms/01-custom-forms.md +395 -0
  52. package/docs/backend/05-forms/02-automatic-database-insert.md +297 -0
  53. package/docs/backend/06-request-and-response/01-the-request-object-what-is-the-user-asking-for.md +96 -0
  54. package/docs/backend/06-request-and-response/02-sending-a-response-replying-to-the-user.md +40 -0
  55. package/docs/backend/07-views/01-the-view-directory.md +73 -0
  56. package/docs/backend/07-views/02-rendering-a-view.md +179 -0
  57. package/docs/backend/07-views/03-template-syntax.md +181 -0
  58. package/docs/backend/07-views/03-variables.md +328 -0
  59. package/docs/backend/07-views/04-request-data.md +231 -0
  60. package/docs/backend/07-views/05-conditionals.md +290 -0
  61. package/docs/backend/07-views/06-loops.md +353 -0
  62. package/docs/backend/07-views/07-translations.md +358 -0
  63. package/docs/backend/07-views/08-backend-javascript.md +398 -0
  64. package/docs/backend/07-views/09-comments.md +297 -0
  65. package/docs/backend/08-database/01-database-connection.md +99 -0
  66. package/docs/backend/08-database/02-using-mysql.md +322 -0
  67. package/docs/backend/09-validation/01-the-validator-service.md +424 -0
  68. package/docs/backend/10-authentication/01-user-logins-with-authjs.md +53 -0
  69. package/docs/backend/10-authentication/02-foiling-villains-with-csrf-protection.md +55 -0
  70. package/docs/backend/10-authentication/03-register.md +134 -0
  71. package/docs/backend/10-authentication/04-candy-register-forms.md +676 -0
  72. package/docs/backend/10-authentication/05-session-management.md +159 -0
  73. package/docs/backend/10-authentication/06-candy-login-forms.md +596 -0
  74. package/docs/backend/11-mail/01-the-mail-service.md +42 -0
  75. package/docs/backend/12-streaming/01-streaming-overview.md +300 -0
  76. package/docs/backend/13-utilities/01-candy-var.md +504 -0
  77. package/docs/frontend/01-overview/01-introduction.md +146 -0
  78. package/docs/frontend/02-ajax-navigation/01-quick-start.md +608 -0
  79. package/docs/frontend/02-ajax-navigation/02-configuration.md +370 -0
  80. package/docs/frontend/02-ajax-navigation/03-advanced-usage.md +519 -0
  81. package/docs/frontend/03-forms/01-form-handling.md +420 -0
  82. package/docs/frontend/04-api-requests/01-get-post.md +443 -0
  83. package/docs/frontend/05-streaming/01-client-streaming.md +163 -0
  84. package/docs/index.json +452 -0
  85. package/docs/server/01-installation/01-quick-install.md +19 -0
  86. package/docs/server/01-installation/02-manual-installation-via-npm.md +9 -0
  87. package/docs/server/02-get-started/01-core-concepts.md +7 -0
  88. package/docs/server/02-get-started/02-basic-commands.md +57 -0
  89. package/docs/server/02-get-started/03-cli-reference.md +276 -0
  90. package/docs/server/02-get-started/04-cli-quick-reference.md +102 -0
  91. package/docs/server/03-service/01-start-a-new-service.md +57 -0
  92. package/docs/server/03-service/02-delete-a-service.md +48 -0
  93. package/docs/server/04-web/01-create-a-website.md +36 -0
  94. package/docs/server/04-web/02-list-websites.md +9 -0
  95. package/docs/server/04-web/03-delete-a-website.md +29 -0
  96. package/docs/server/05-subdomain/01-create-a-subdomain.md +32 -0
  97. package/docs/server/05-subdomain/02-list-subdomains.md +33 -0
  98. package/docs/server/05-subdomain/03-delete-a-subdomain.md +41 -0
  99. package/docs/server/06-ssl/01-renew-an-ssl-certificate.md +34 -0
  100. package/docs/server/07-mail/01-create-a-mail-account.md +23 -0
  101. package/docs/server/07-mail/02-delete-a-mail-account.md +20 -0
  102. package/docs/server/07-mail/03-list-mail-accounts.md +20 -0
  103. package/docs/server/07-mail/04-change-account-password.md +23 -0
  104. package/eslint.config.mjs +120 -0
  105. package/framework/index.js +4 -0
  106. package/framework/src/Auth.js +309 -0
  107. package/framework/src/Candy.js +81 -0
  108. package/framework/src/Config.js +79 -0
  109. package/framework/src/Env.js +60 -0
  110. package/framework/src/Lang.js +57 -0
  111. package/framework/src/Mail.js +83 -0
  112. package/framework/src/Mysql.js +575 -0
  113. package/framework/src/Request.js +301 -0
  114. package/framework/src/Route/Cron.js +128 -0
  115. package/framework/src/Route/Internal.js +439 -0
  116. package/framework/src/Route.js +455 -0
  117. package/framework/src/Server.js +15 -0
  118. package/framework/src/Stream.js +163 -0
  119. package/framework/src/Token.js +37 -0
  120. package/framework/src/Validator.js +271 -0
  121. package/framework/src/Var.js +211 -0
  122. package/framework/src/View/EarlyHints.js +190 -0
  123. package/framework/src/View/Form.js +600 -0
  124. package/framework/src/View.js +513 -0
  125. package/framework/web/candy.js +838 -0
  126. package/jest.config.js +22 -0
  127. package/locale/de-DE.json +80 -0
  128. package/locale/en-US.json +79 -0
  129. package/locale/es-ES.json +80 -0
  130. package/locale/fr-FR.json +80 -0
  131. package/locale/pt-BR.json +80 -0
  132. package/locale/ru-RU.json +80 -0
  133. package/locale/tr-TR.json +85 -0
  134. package/locale/zh-CN.json +80 -0
  135. package/package.json +86 -0
  136. package/server/index.js +5 -0
  137. package/server/src/Api.js +88 -0
  138. package/server/src/DNS.js +940 -0
  139. package/server/src/Hub.js +535 -0
  140. package/server/src/Mail.js +571 -0
  141. package/server/src/SSL.js +180 -0
  142. package/server/src/Server.js +27 -0
  143. package/server/src/Service.js +248 -0
  144. package/server/src/Subdomain.js +64 -0
  145. package/server/src/Web/Firewall.js +170 -0
  146. package/server/src/Web/Proxy.js +134 -0
  147. package/server/src/Web.js +451 -0
  148. package/server/src/mail/imap.js +1091 -0
  149. package/server/src/mail/server.js +32 -0
  150. package/server/src/mail/smtp.js +786 -0
  151. package/test/cli/Cli.test.js +36 -0
  152. package/test/core/Candy.test.js +234 -0
  153. package/test/core/Commands.test.js +538 -0
  154. package/test/core/Config.test.js +1435 -0
  155. package/test/core/Lang.test.js +250 -0
  156. package/test/core/Process.test.js +156 -0
  157. package/test/framework/Route.test.js +239 -0
  158. package/test/framework/View/EarlyHints.test.js +282 -0
  159. package/test/scripts/check-coverage.js +132 -0
  160. package/test/server/Api.test.js +647 -0
  161. package/test/server/Client.test.js +338 -0
  162. package/test/server/DNS.test.js +2050 -0
  163. package/test/server/DNS.test.js.bak +2084 -0
  164. package/test/server/Log.test.js +73 -0
  165. package/test/server/Mail.account.test_.js +460 -0
  166. package/test/server/Mail.init.test_.js +411 -0
  167. package/test/server/Mail.test_.js +1340 -0
  168. package/test/server/SSL.test_.js +1491 -0
  169. package/test/server/Server.test.js +765 -0
  170. package/test/server/Service.test_.js +1127 -0
  171. package/test/server/Subdomain.test.js +440 -0
  172. package/test/server/Web/Firewall.test.js +175 -0
  173. package/test/server/Web.test_.js +1562 -0
  174. package/test/server/__mocks__/acme-client.js +17 -0
  175. package/test/server/__mocks__/bcrypt.js +50 -0
  176. package/test/server/__mocks__/child_process.js +389 -0
  177. package/test/server/__mocks__/crypto.js +432 -0
  178. package/test/server/__mocks__/fs.js +450 -0
  179. package/test/server/__mocks__/globalCandy.js +227 -0
  180. package/test/server/__mocks__/http-proxy.js +105 -0
  181. package/test/server/__mocks__/http.js +575 -0
  182. package/test/server/__mocks__/https.js +272 -0
  183. package/test/server/__mocks__/index.js +249 -0
  184. package/test/server/__mocks__/mail/server.js +100 -0
  185. package/test/server/__mocks__/mail/smtp.js +31 -0
  186. package/test/server/__mocks__/mailparser.js +81 -0
  187. package/test/server/__mocks__/net.js +369 -0
  188. package/test/server/__mocks__/node-forge.js +328 -0
  189. package/test/server/__mocks__/os.js +320 -0
  190. package/test/server/__mocks__/path.js +291 -0
  191. package/test/server/__mocks__/selfsigned.js +8 -0
  192. package/test/server/__mocks__/server/src/mail/server.js +100 -0
  193. package/test/server/__mocks__/server/src/mail/smtp.js +31 -0
  194. package/test/server/__mocks__/smtp-server.js +106 -0
  195. package/test/server/__mocks__/sqlite3.js +394 -0
  196. package/test/server/__mocks__/testFactories.js +299 -0
  197. package/test/server/__mocks__/testHelpers.js +363 -0
  198. package/test/server/__mocks__/tls.js +229 -0
  199. package/watchdog/index.js +3 -0
  200. package/watchdog/src/Watchdog.js +156 -0
  201. package/web/config.json +5 -0
  202. package/web/controller/page/about.js +27 -0
  203. package/web/controller/page/index.js +34 -0
  204. package/web/package.json +18 -0
  205. package/web/public/assets/css/style.css +1835 -0
  206. package/web/public/assets/js/app.js +96 -0
  207. package/web/route/www.js +19 -0
  208. package/web/skeleton/main.html +22 -0
  209. package/web/view/content/about.html +65 -0
  210. package/web/view/content/home.html +205 -0
  211. package/web/view/footer/main.html +11 -0
  212. package/web/view/head/main.html +5 -0
  213. package/web/view/header/main.html +14 -0
@@ -0,0 +1,301 @@
1
+ const nodeCrypto = require('crypto')
2
+
3
+ class CandyRequest {
4
+ #candy
5
+ #complete = false
6
+ #cookies = {received: [], sent: []}
7
+ data = {post: {}, get: {}, url: {}}
8
+ #event = {data: [], end: []}
9
+ #headers = {Server: 'CandyPack'}
10
+ #status = 200
11
+ #timeout = null
12
+ #earlyHints = null
13
+ variables = {}
14
+ isAjaxLoad = false
15
+ ajaxLoad = null
16
+ clientSkeleton = null
17
+ page = null
18
+
19
+ constructor(id, req, res, candy) {
20
+ this.id = id
21
+ this.req = req
22
+ this.res = res
23
+ this.#candy = candy
24
+ this.method = req.method.toLowerCase()
25
+ this.url = req.url
26
+ this.host = req.headers.host
27
+ this.ssl = this.header('x-candy-connection-ssl') === 'true'
28
+ this.ip = (this.header('x-candy-connection-remoteaddress') ?? req.connection.remoteAddress).replace('::ffff:', '')
29
+ delete this.req.headers['x-candy-connection-ssl']
30
+ delete this.req.headers['x-candy-connection-remoteaddress']
31
+ let route = req.headers.host.split('.')[0]
32
+ if (!Candy.Route.routes[route]) route = 'www'
33
+ this.route = route
34
+ this.#timeout = setTimeout(() => !this.res.finished && this.abort(408), Candy.Config.request.timeout)
35
+ this.#data()
36
+ if (!Candy.Request) Candy.Request = {}
37
+ if (!this.cookie('candy_client') || !this.session('_client') || this.session('_client') !== this.cookie('candy_client')) {
38
+ let client = nodeCrypto
39
+ .createHash('md5')
40
+ .update(this.ip + this.id + Date.now().toString() + Math.random().toString())
41
+ .digest('hex')
42
+ this.cookie('candy_client', client, {expires: null, httpOnly: false})
43
+ this.session('_client', client)
44
+ }
45
+ }
46
+
47
+ // - ABORT REQUEST
48
+ async abort(code) {
49
+ this.status(code)
50
+ let result = {401: 'Unauthorized', 404: 'Not Found', 408: 'Request Timeout'}[code] ?? null
51
+ if (Candy.Route.routes[this.route].error && Candy.Route.routes[this.route].error[code])
52
+ result = await Candy.Route.routes[this.route].error[code].cache(this.#candy)
53
+ this.end(result)
54
+ }
55
+
56
+ // - SET COOKIE
57
+ cookie(key, value, options = {}) {
58
+ if (value === undefined) {
59
+ if (this.#cookies.sent[key]) return this.#cookies.sent[key]
60
+ if (this.#cookies.received[key]) return this.#cookies.received[key]
61
+ value =
62
+ this.req.headers.cookie
63
+ ?.split('; ')
64
+ .find(c => c.startsWith(key + '='))
65
+ ?.split('=')[1] ?? null
66
+ if (value && value.startsWith('{') && value.endsWith('}')) value = JSON.parse(value)
67
+ this.#cookies.received[key] = value
68
+ return value
69
+ }
70
+ if (options.path === undefined) options.path = '/'
71
+ if (options.expires === undefined) options.expires = new Date(Date.now() + 1000 * 60 * 60 * 24 * 365).toUTCString()
72
+ if (options.secure === undefined) options.secure = true
73
+ if (options.httpOnly === undefined) options.httpOnly = true
74
+ if (options.sameSite === undefined) options.sameSite = 'Strict'
75
+ if (typeof value === 'object') value = JSON.stringify(value)
76
+ let cookie = `${key}=${value}`
77
+ for (const option of Object.keys(options)) if (options[option]) cookie += `; ${option}=${options[option]}`
78
+ this.#cookies.sent.push(cookie)
79
+ }
80
+
81
+ #data() {
82
+ let split = this.url.split('?')
83
+ if (split[1]) {
84
+ let data = split[1].split('&')
85
+ for (let i = 0; i < data.length; i++) {
86
+ if (data[i].indexOf('=') === -1) continue
87
+ let key = data[i].split('=')[0]
88
+ let val = data[i].split('=')[1]
89
+ this.data.get[key] = val
90
+ }
91
+ }
92
+ let body = ''
93
+ this.req.on('data', chunk => {
94
+ body += chunk.toString()
95
+ if (body.length > 1e6) {
96
+ body = ''
97
+ this.status(413)
98
+ this.end()
99
+ } else {
100
+ if (body.length > 0 && body.indexOf('Content-Disposition') === -1) return
101
+ if (body.indexOf('Content-Disposition') > -1) {
102
+ let boundary = body.split('\r\n')[0].split('; ')[1].split('=')[1]
103
+ let data = body.split(boundary)
104
+ for (let i = 0; i < data.length; i++) {
105
+ if (data[i].indexOf('Content-Disposition') === -1) continue
106
+ let key = data[i].split('name="')[1].split('"')[0]
107
+ let val = data[i].split('\r\n\r\n')[1].split('\r\n')[0]
108
+ this.data.post[key] = val
109
+ }
110
+ } else {
111
+ let data = body.split('&')
112
+ for (let i = 0; i < data.length; i++) {
113
+ if (data[i].indexOf('=') === -1) continue
114
+ let key = decodeURIComponent(data[i].split('=')[0])
115
+ let val = decodeURIComponent(data[i].split('=')[1] || '')
116
+ this.data.post[key] = val
117
+ }
118
+ }
119
+ }
120
+ for (const event of this.#event.data) {
121
+ event.callback(event.active ? chunk : body)
122
+ event.active = true
123
+ }
124
+ })
125
+ this.req.on('end', () => {
126
+ if (!body) return (this.#complete = true)
127
+ if (body.startsWith('{') && body.endsWith('}')) {
128
+ this.data.post = JSON.parse(body)
129
+ } else {
130
+ let data = body.split('&')
131
+ for (let i = 0; i < data.length; i++) {
132
+ if (data[i].indexOf('=') === -1) continue
133
+ let key = decodeURIComponent(data[i].split('=')[0])
134
+ let val = decodeURIComponent(data[i].split('=')[1] || '')
135
+ this.data.post[key] = val
136
+ }
137
+ }
138
+ this.#complete = true
139
+ for (const event of this.#event.end) event.callback()
140
+ })
141
+ }
142
+
143
+ // - RETURN REQUEST
144
+ end(data) {
145
+ if (data instanceof Promise) return data.then(result => this.end(result))
146
+ if (this.res.finished) return
147
+ if (typeof data === 'object' && data !== null && data.type !== 'Buffer') {
148
+ let json = JSON.stringify(data)
149
+ if (json.length > 0 && JSON.parse(json).type !== 'Buffer') {
150
+ data = json
151
+ this.header('Content-Type', 'application/json')
152
+ }
153
+ }
154
+ clearTimeout(this.#timeout)
155
+ this.print()
156
+ this.res.end(data)
157
+ this.req.connection.destroy()
158
+ }
159
+
160
+ // - GET
161
+ get(key) {
162
+ return this.variables[key] ? this.variables[key].value : null
163
+ }
164
+
165
+ // - SET HEADER
166
+ header(key, value) {
167
+ if (value === null) delete this.#headers[key]
168
+ else if (value !== undefined) this.#headers[key] = value
169
+ else for (const header of Object.keys(this.req.headers)) if (header.toLowerCase() === key.toLowerCase()) return this.req.headers[header]
170
+ }
171
+
172
+ // - ON EVENT
173
+ on(event, callback) {
174
+ if (this.#event[event]) this.#event[event].push({callback: callback, active: false})
175
+ else return false
176
+ }
177
+
178
+ // - PRINT HEADERS
179
+ print() {
180
+ if (this.res.headersSent) return
181
+
182
+ if (this.#earlyHints && this.#earlyHints.length > 0 && global.Candy?.View?.EarlyHints) {
183
+ global.Candy.View.EarlyHints.send(this.res, this.#earlyHints)
184
+ }
185
+
186
+ this.#headers['Set-Cookie'] = this.#cookies.sent
187
+ this.res.writeHead(this.#status, this.#headers)
188
+ }
189
+
190
+ // - SET EARLY HINTS
191
+ setEarlyHints(hints) {
192
+ this.#earlyHints = hints
193
+ }
194
+
195
+ // - HAS EARLY HINTS
196
+ hasEarlyHints() {
197
+ return this.#earlyHints !== null && this.#earlyHints.length > 0
198
+ }
199
+
200
+ // - REDIRECT
201
+ redirect(url) {
202
+ this.header('Location', url)
203
+ this.status(302)
204
+ }
205
+
206
+ // - GET REQUEST
207
+ async request(key, method) {
208
+ if (method) method = method.toUpperCase()
209
+ if ((!method || method === 'post') && (this.data.post[key] ?? null)) return this.data.post[key]
210
+ if ((!method || method === 'get') && (this.data.get[key] ?? null)) return this.data.get[key]
211
+ if ((!method || method === 'url') && (this.data.url[key] ?? null)) return this.data.url[key]
212
+ return new Promise(resolve => {
213
+ let interval = setInterval(() => {
214
+ if (this.data.post[key] !== undefined || this.data.get[key] !== undefined || this.#complete) {
215
+ clearInterval(interval)
216
+ if (!key && !method) resolve(this.data.post)
217
+ else if (!key && method) resolve(this.data[method.toLowerCase()])
218
+ else if (this.data.post[key] !== undefined && method !== 'GET') resolve(this.data.post[key])
219
+ else if (this.data.get[key] !== undefined && method !== 'GET') resolve(this.data.get[key])
220
+ else resolve()
221
+ }
222
+ }, 10)
223
+ })
224
+ }
225
+
226
+ // - SESSION
227
+ session(key, value) {
228
+ if (!Candy.Request.session) Candy.Request.session = {}
229
+ if (!Candy.Request.sessionLocks) Candy.Request.sessionLocks = {}
230
+
231
+ let pri = nodeCrypto
232
+ .createHash('md5')
233
+ .update(this.req.headers['user-agent'] ?? '.')
234
+ .digest('hex')
235
+ let pub = this.cookie('candy_session')
236
+
237
+ if (!pub || !Candy.Request.session[pub + '-' + pri]) {
238
+ const lockKey = `${this.ip}-${pri}`
239
+ const now = Date.now()
240
+
241
+ if (Candy.Request.sessionLocks[lockKey]) {
242
+ const lock = Candy.Request.sessionLocks[lockKey]
243
+ if (now - lock.timestamp < 5000 && Candy.Request.session[`${lock.sessionId}-${pri}`]) {
244
+ pub = lock.sessionId
245
+ } else {
246
+ delete Candy.Request.sessionLocks[lockKey]
247
+ }
248
+ }
249
+
250
+ if (!pub) {
251
+ const sessionLockValues = Object.values(Candy.Request.sessionLocks)
252
+ const activeSessions = new Set(sessionLockValues.map(l => l.sessionId))
253
+ do {
254
+ pub = nodeCrypto
255
+ .createHash('md5')
256
+ .update(this.ip + this.id + Date.now().toString() + Math.random().toString())
257
+ .digest('hex')
258
+ } while (Candy.Request.session[`${pub}-${pri}`] || activeSessions.has(pub))
259
+
260
+ Candy.Request.sessionLocks[lockKey] = {sessionId: pub, timestamp: now}
261
+ Candy.Request.session[`${pub}-${pri}`] = {}
262
+ this.cookie('candy_session', `${pub}`)
263
+
264
+ setTimeout(() => {
265
+ if (Candy.Request.sessionLocks[lockKey]?.timestamp === now) {
266
+ delete Candy.Request.sessionLocks[lockKey]
267
+ }
268
+ }, 5000)
269
+ }
270
+ }
271
+
272
+ if (!Candy.Request.session[pub + '-' + pri]) Candy.Request.session[pub + '-' + pri] = {}
273
+ if (value === undefined) return Candy.Request.session[pub + '-' + pri][key] ?? null
274
+ else if (value === null) delete Candy.Request.session[pub + '-' + pri][key]
275
+ else Candy.Request.session[pub + '-' + pri][key] = value
276
+ }
277
+
278
+ // - SET
279
+ set(key, value, ajax = false) {
280
+ if (typeof key === 'object') for (const k in key) this.variables[k] = {value: key[k], ajax: ajax}
281
+ else this.variables[key] = {value: value, ajax: ajax}
282
+ }
283
+
284
+ // - HTTP CODE
285
+ status(code) {
286
+ this.#status = code
287
+ }
288
+
289
+ // - CLEAR TIMEOUT (for long-running connections like SSE)
290
+ clearTimeout() {
291
+ clearTimeout(this.#timeout)
292
+ }
293
+
294
+ // - WRITE DATA
295
+ write(data) {
296
+ if (this.res.finished) return
297
+ this.res.write(data)
298
+ }
299
+ }
300
+
301
+ module.exports = CandyRequest
@@ -0,0 +1,128 @@
1
+ const fs = require('fs')
2
+
3
+ class Cron {
4
+ #interval = null
5
+ #jobs = []
6
+
7
+ init() {
8
+ if (this.#interval) return
9
+ this.#interval = setInterval(this.check.bind(this), 60 * 1000) // Check every minute
10
+ }
11
+
12
+ check() {
13
+ const now = new Date()
14
+ const minute = now.getMinutes()
15
+ const hour = now.getHours()
16
+ const day = now.getDate()
17
+ const weekDay = now.getDay()
18
+ const month = now.getMonth() + 1
19
+ const year = now.getFullYear()
20
+ const yearDay = Math.floor((now - new Date(now.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24)
21
+ const unix = Math.floor(now.getTime() / 1000)
22
+
23
+ for (const job of this.#jobs) {
24
+ if (job.updated.getTime() + 60 * 1000 > now.getTime()) continue // Skip jobs updated in the last minute
25
+ let shouldRun = true
26
+ for (const condition of job.condition) {
27
+ condition.value = parseInt(condition.value)
28
+ switch (condition.type) {
29
+ case 'minute':
30
+ if (condition.value !== minute) shouldRun = false
31
+ break
32
+ case 'hour':
33
+ if (condition.value !== hour) shouldRun = false
34
+ break
35
+ case 'day':
36
+ if (condition.value !== day) shouldRun = false
37
+ break
38
+ case 'weekDay':
39
+ if (condition.value !== weekDay) shouldRun = false
40
+ break
41
+ case 'month':
42
+ if (condition.value !== month) shouldRun = false
43
+ break
44
+ case 'year':
45
+ if (condition.value !== year) shouldRun = false
46
+ break
47
+ case 'yearDay':
48
+ if (condition.value !== yearDay) shouldRun = false
49
+ break
50
+ case 'everyMinute':
51
+ if (job.lastRun && Math.floor(unix / 60) % condition.value !== 0) shouldRun = false
52
+ break
53
+ case 'everyHour':
54
+ if (job.lastRun && Math.floor(unix / 3600) % condition.value !== 0) shouldRun = false
55
+ break
56
+ case 'everyDay':
57
+ if (job.lastRun && Math.floor(unix / 86400) % condition.value !== 0) shouldRun = false
58
+ break
59
+ case 'everyWeekDay':
60
+ if (job.lastRun && weekDay % condition.value !== 0) shouldRun = false
61
+ break
62
+ case 'everyMonth':
63
+ if (job.lastRun && (year * 12 + month) % condition.value !== 0) shouldRun = false
64
+ break
65
+ case 'everyYear':
66
+ if (job.lastRun && year % condition.value !== 0) shouldRun = false
67
+ break
68
+ case 'everyYearDay':
69
+ if (job.lastRun && condition.value !== yearDay) shouldRun = false
70
+ break
71
+ }
72
+ if (!shouldRun) break
73
+ }
74
+
75
+ if (shouldRun) {
76
+ job.lastRun = now
77
+ try {
78
+ if (job.function || fs.existsSync(job.path)) {
79
+ if (!job.function) job.function = require(job.path)
80
+ if (job.function && typeof job.function === 'function') {
81
+ job.function()
82
+ }
83
+ }
84
+ } catch (error) {
85
+ console.error(`Error executing job ${job.controller}:`, error)
86
+ }
87
+ }
88
+ }
89
+ }
90
+
91
+ job(controller) {
92
+ let path
93
+ if (typeof controller !== 'function') {
94
+ path = `${__dir}/controller/cron/${controller}.js`
95
+ if (controller.includes('.')) {
96
+ let arr = controller.split('.')
97
+ path = `${__dir}/controller/${arr[0]}/cron/${arr.slice(1).join('.')}.js`
98
+ }
99
+ }
100
+ this.#jobs.push({
101
+ controller: typeof controller === 'function' ? null : controller,
102
+ lastRun: null,
103
+ condition: [],
104
+ function: typeof controller === 'function' ? controller : null,
105
+ path,
106
+ updated: new Date()
107
+ })
108
+ let id = this.#jobs.length - 1
109
+ return {
110
+ minute: value => this.#jobs[id].condition.push({type: 'minute', value: value}),
111
+ hour: value => this.#jobs[id].condition.push({type: 'hour', value: value}),
112
+ day: value => this.#jobs[id].condition.push({type: 'day', value: value}),
113
+ weekDay: value => this.#jobs[id].condition.push({type: 'weekDay', value: value}),
114
+ month: value => this.#jobs[id].condition.push({type: 'month', value: value}),
115
+ year: value => this.#jobs[id].condition.push({type: 'year', value: value}),
116
+ yearDay: value => this.#jobs[id].condition.push({type: 'yearDay', value: value}),
117
+ everyMinute: value => this.#jobs[id].condition.push({type: 'everyMinute', value: value}),
118
+ everyHour: value => this.#jobs[id].condition.push({type: 'everyHour', value: value}),
119
+ everyDay: value => this.#jobs[id].condition.push({type: 'everyDay', value: value}),
120
+ everyWeekDay: value => this.#jobs[id].condition.push({type: 'everyWeekDay', value: value}),
121
+ everyMonth: value => this.#jobs[id].condition.push({type: 'everyMonth', value: value}),
122
+ everyYear: value => this.#jobs[id].condition.push({type: 'everyYear', value: value}),
123
+ everyYearDay: value => this.#jobs[id].condition.push({type: 'everyYearDay', value: value})
124
+ }
125
+ }
126
+ }
127
+
128
+ module.exports = new Cron()