@zintrust/core 0.1.1 → 0.1.3

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 (487) hide show
  1. package/README.md +3 -3
  2. package/bin/zintrust.d.ts.map +1 -1
  3. package/bin/zintrust.js +18 -1
  4. package/package.json +15 -1
  5. package/src/boot/Application.d.ts.map +1 -1
  6. package/src/boot/Application.js +46 -3
  7. package/src/boot/Server.d.ts.map +1 -1
  8. package/src/boot/Server.js +3 -4
  9. package/src/boot/bootstrap.js +77 -6
  10. package/src/builder/BundleOptimizer.d.ts.map +1 -1
  11. package/src/builder/BundleOptimizer.js +6 -4
  12. package/src/cache/drivers/KVDriver.d.ts.map +1 -1
  13. package/src/cache/drivers/KVDriver.js +6 -6
  14. package/src/cache/drivers/RedisDriver.js +1 -1
  15. package/src/cli/BaseCommand.d.ts +2 -2
  16. package/src/cli/BaseCommand.d.ts.map +1 -1
  17. package/src/cli/BaseCommand.js +2 -1
  18. package/src/cli/CLI.d.ts.map +1 -1
  19. package/src/cli/CLI.js +11 -4
  20. package/src/cli/commands/AddCommand.js +1 -1
  21. package/src/cli/commands/ConfigCommand.d.ts.map +1 -1
  22. package/src/cli/commands/ConfigCommand.js +34 -4
  23. package/src/cli/commands/D1MigrateCommand.d.ts +4 -0
  24. package/src/cli/commands/D1MigrateCommand.d.ts.map +1 -1
  25. package/src/cli/commands/D1MigrateCommand.js +4 -3
  26. package/src/cli/commands/FixCommand.d.ts.map +1 -1
  27. package/src/cli/commands/FixCommand.js +3 -16
  28. package/src/cli/commands/LogsCleanupCommand.d.ts +6 -0
  29. package/src/cli/commands/LogsCleanupCommand.d.ts.map +1 -0
  30. package/src/cli/commands/LogsCleanupCommand.js +20 -0
  31. package/src/cli/commands/LogsCommand.d.ts.map +1 -1
  32. package/src/cli/commands/LogsCommand.js +1 -1
  33. package/src/cli/commands/MakeMailTemplateCommand.d.ts +10 -0
  34. package/src/cli/commands/MakeMailTemplateCommand.d.ts.map +1 -0
  35. package/src/cli/commands/MakeMailTemplateCommand.js +74 -0
  36. package/src/cli/commands/MakeNotificationTemplateCommand.d.ts +10 -0
  37. package/src/cli/commands/MakeNotificationTemplateCommand.d.ts.map +1 -0
  38. package/src/cli/commands/MakeNotificationTemplateCommand.js +113 -0
  39. package/src/cli/commands/NewCommand.d.ts +4 -0
  40. package/src/cli/commands/NewCommand.d.ts.map +1 -1
  41. package/src/cli/commands/NewCommand.js +33 -20
  42. package/src/cli/commands/PluginCommand.d.ts.map +1 -1
  43. package/src/cli/commands/PluginCommand.js +8 -4
  44. package/src/cli/commands/PrepareCommand.d.ts.map +1 -1
  45. package/src/cli/commands/PrepareCommand.js +1 -1
  46. package/src/cli/commands/QACommand.d.ts.map +1 -1
  47. package/src/cli/commands/QACommand.js +11 -20
  48. package/src/cli/commands/SecretsCommand.d.ts +16 -0
  49. package/src/cli/commands/SecretsCommand.d.ts.map +1 -0
  50. package/src/cli/commands/SecretsCommand.js +91 -0
  51. package/src/cli/commands/StartCommand.d.ts.map +1 -1
  52. package/src/cli/commands/StartCommand.js +2 -2
  53. package/src/cli/commands/TemplatesCommand.d.ts +3 -0
  54. package/src/cli/commands/TemplatesCommand.d.ts.map +1 -0
  55. package/src/cli/commands/TemplatesCommand.js +65 -0
  56. package/src/cli/commands/index.d.ts +5 -0
  57. package/src/cli/commands/index.d.ts.map +1 -1
  58. package/src/cli/commands/index.js +5 -0
  59. package/src/cli/config/ConfigManager.js +1 -1
  60. package/src/cli/index.d.ts +2 -1
  61. package/src/cli/index.d.ts.map +1 -1
  62. package/src/cli/index.js +2 -1
  63. package/src/cli/scaffolding/ControllerGenerator.js +1 -1
  64. package/src/cli/scaffolding/FeatureScaffolder.js +4 -4
  65. package/src/cli/scaffolding/FileGenerator.js +1 -1
  66. package/src/cli/scaffolding/ModelGenerator.js +1 -1
  67. package/src/cli/scaffolding/ProjectScaffolder.d.ts.map +1 -1
  68. package/src/cli/scaffolding/ProjectScaffolder.js +61 -11
  69. package/src/cli/scaffolding/ResponseFactoryGenerator.d.ts.map +1 -1
  70. package/src/cli/scaffolding/ResponseFactoryGenerator.js +3 -2
  71. package/src/cli/scaffolding/RouteGenerator.js +1 -1
  72. package/src/cli/scaffolding/ServiceIntegrationTestGenerator.js +1 -1
  73. package/src/cli/scaffolding/ServiceScaffolder.js +2 -2
  74. package/src/cli/scaffolding/TemplateGenerator.d.ts +40 -0
  75. package/src/cli/scaffolding/TemplateGenerator.d.ts.map +1 -0
  76. package/src/cli/scaffolding/TemplateGenerator.js +172 -0
  77. package/src/cli/scaffolding/index.d.ts +1 -0
  78. package/src/cli/scaffolding/index.d.ts.map +1 -1
  79. package/src/cli/scaffolding/index.js +1 -0
  80. package/src/cli/utils/spawn.js +1 -1
  81. package/src/common/AwsSigV4.d.ts +41 -0
  82. package/src/common/AwsSigV4.d.ts.map +1 -0
  83. package/src/common/AwsSigV4.js +69 -0
  84. package/src/common/index.d.ts +39 -0
  85. package/src/common/index.d.ts.map +1 -1
  86. package/src/common/index.js +101 -8
  87. package/src/common/uuid.d.ts +3 -0
  88. package/src/common/uuid.d.ts.map +1 -0
  89. package/src/common/uuid.js +30 -0
  90. package/src/config/FileLogWriter.d.ts +22 -0
  91. package/src/config/FileLogWriter.d.ts.map +1 -0
  92. package/src/config/FileLogWriter.js +192 -0
  93. package/src/config/SecretsManager.d.ts.map +1 -1
  94. package/src/config/SecretsManager.js +37 -11
  95. package/src/config/StartupConfigValidator.d.ts +15 -0
  96. package/src/config/StartupConfigValidator.d.ts.map +1 -0
  97. package/src/config/StartupConfigValidator.js +86 -0
  98. package/src/config/app.d.ts +2 -1
  99. package/src/config/app.d.ts.map +1 -1
  100. package/src/config/app.js +65 -15
  101. package/src/config/broadcast.d.ts +47 -0
  102. package/src/config/broadcast.d.ts.map +1 -0
  103. package/src/config/broadcast.js +54 -0
  104. package/src/config/cache.d.ts +13 -17
  105. package/src/config/cache.d.ts.map +1 -1
  106. package/src/config/cache.js +9 -11
  107. package/src/config/cloudflare.d.ts +26 -0
  108. package/src/config/cloudflare.d.ts.map +1 -0
  109. package/src/config/cloudflare.js +38 -0
  110. package/src/config/env.d.ts +6 -0
  111. package/src/config/env.d.ts.map +1 -1
  112. package/src/config/env.js +6 -0
  113. package/src/config/index.d.ts +52 -28
  114. package/src/config/index.d.ts.map +1 -1
  115. package/src/config/index.js +3 -0
  116. package/src/config/logger.d.ts +2 -0
  117. package/src/config/logger.d.ts.map +1 -1
  118. package/src/config/logger.js +270 -11
  119. package/src/config/logging/HttpLogger.d.ts +23 -0
  120. package/src/config/logging/HttpLogger.d.ts.map +1 -0
  121. package/src/config/logging/HttpLogger.js +93 -0
  122. package/src/config/logging/KvLogger.d.ts +22 -0
  123. package/src/config/logging/KvLogger.d.ts.map +1 -0
  124. package/src/config/logging/KvLogger.js +143 -0
  125. package/src/config/logging/SlackLogger.d.ts +23 -0
  126. package/src/config/logging/SlackLogger.d.ts.map +1 -0
  127. package/src/config/logging/SlackLogger.js +119 -0
  128. package/src/config/mail.d.ts +81 -0
  129. package/src/config/mail.d.ts.map +1 -0
  130. package/src/config/mail.js +73 -0
  131. package/src/config/middleware.d.ts +8 -0
  132. package/src/config/middleware.d.ts.map +1 -0
  133. package/src/config/middleware.js +18 -0
  134. package/src/config/notification.d.ts +62 -0
  135. package/src/config/notification.d.ts.map +1 -0
  136. package/src/config/notification.js +43 -0
  137. package/src/config/security.d.ts.map +1 -1
  138. package/src/config/security.js +2 -2
  139. package/src/config/startup.d.ts +23 -0
  140. package/src/config/startup.d.ts.map +1 -0
  141. package/src/config/startup.js +15 -0
  142. package/src/config/storage.d.ts +21 -35
  143. package/src/config/storage.d.ts.map +1 -1
  144. package/src/config/storage.js +57 -37
  145. package/src/database/migrations/index.d.ts +1 -1
  146. package/src/database/migrations/index.d.ts.map +1 -1
  147. package/src/database/migrations/index.js +2 -1
  148. package/src/features/Queue.js +1 -25
  149. package/src/health/RuntimeHealthProbes.d.ts +13 -0
  150. package/src/health/RuntimeHealthProbes.d.ts.map +1 -0
  151. package/src/health/RuntimeHealthProbes.js +62 -0
  152. package/src/health/StartupHealthChecks.d.ts +26 -0
  153. package/src/health/StartupHealthChecks.d.ts.map +1 -0
  154. package/src/health/StartupHealthChecks.js +124 -0
  155. package/src/http/ErrorResponse.d.ts +28 -0
  156. package/src/http/ErrorResponse.d.ts.map +1 -0
  157. package/src/http/ErrorResponse.js +42 -0
  158. package/src/http/Kernel.d.ts +5 -0
  159. package/src/http/Kernel.d.ts.map +1 -1
  160. package/src/http/Kernel.js +96 -30
  161. package/src/http/RequestContext.d.ts +20 -0
  162. package/src/http/RequestContext.d.ts.map +1 -0
  163. package/src/http/RequestContext.js +77 -0
  164. package/src/index.d.ts +9 -1
  165. package/src/index.d.ts.map +1 -1
  166. package/src/index.js +8 -2
  167. package/src/microservices/MicroserviceManager.d.ts.map +1 -1
  168. package/src/microservices/MicroserviceManager.js +9 -6
  169. package/src/microservices/PostgresAdapter.d.ts.map +1 -1
  170. package/src/microservices/PostgresAdapter.js +3 -1
  171. package/src/microservices/ServiceBundler.d.ts.map +1 -1
  172. package/src/microservices/ServiceBundler.js +6 -4
  173. package/src/microservices/ServiceHealthMonitor.js +2 -2
  174. package/src/middleware/CsrfMiddleware.d.ts.map +1 -1
  175. package/src/middleware/CsrfMiddleware.js +2 -19
  176. package/src/middleware/ErrorHandlerMiddleware.d.ts +6 -0
  177. package/src/middleware/ErrorHandlerMiddleware.d.ts.map +1 -0
  178. package/src/middleware/ErrorHandlerMiddleware.js +33 -0
  179. package/src/middleware/LoggingMiddleware.d.ts +9 -0
  180. package/src/middleware/LoggingMiddleware.d.ts.map +1 -0
  181. package/src/middleware/LoggingMiddleware.js +36 -0
  182. package/src/middleware/index.d.ts +2 -0
  183. package/src/middleware/index.d.ts.map +1 -1
  184. package/src/middleware/index.js +2 -0
  185. package/src/node-singletons/async_hooks.d.ts +9 -0
  186. package/src/node-singletons/async_hooks.d.ts.map +1 -0
  187. package/src/node-singletons/async_hooks.js +8 -0
  188. package/src/node-singletons/fs.d.ts +2 -2
  189. package/src/node-singletons/fs.d.ts.map +1 -1
  190. package/src/node-singletons/fs.js +2 -2
  191. package/src/node-singletons/http.d.ts +1 -1
  192. package/src/node-singletons/http.d.ts.map +1 -1
  193. package/src/node-singletons/http.js +1 -1
  194. package/src/node-singletons/index.d.ts +4 -0
  195. package/src/node-singletons/index.d.ts.map +1 -1
  196. package/src/node-singletons/index.js +4 -0
  197. package/src/node-singletons/net.d.ts +9 -0
  198. package/src/node-singletons/net.d.ts.map +1 -0
  199. package/src/node-singletons/net.js +8 -0
  200. package/src/node-singletons/os.d.ts +3 -3
  201. package/src/node-singletons/os.d.ts.map +1 -1
  202. package/src/node-singletons/os.js +3 -4
  203. package/src/node-singletons/path.d.ts +3 -1
  204. package/src/node-singletons/path.d.ts.map +1 -1
  205. package/src/node-singletons/path.js +3 -1
  206. package/src/node-singletons/perf-hooks.d.ts +3 -1
  207. package/src/node-singletons/perf-hooks.d.ts.map +1 -1
  208. package/src/node-singletons/perf-hooks.js +3 -1
  209. package/src/node-singletons/process.d.ts +23 -0
  210. package/src/node-singletons/process.d.ts.map +1 -0
  211. package/src/node-singletons/process.js +8 -0
  212. package/src/node-singletons/readline.d.ts +3 -3
  213. package/src/node-singletons/readline.d.ts.map +1 -1
  214. package/src/node-singletons/readline.js +3 -4
  215. package/src/node-singletons/tls.d.ts +9 -0
  216. package/src/node-singletons/tls.d.ts.map +1 -0
  217. package/src/node-singletons/tls.js +8 -0
  218. package/src/node-singletons/url.d.ts +3 -1
  219. package/src/node-singletons/url.d.ts.map +1 -1
  220. package/src/node-singletons/url.js +3 -1
  221. package/src/orm/ConnectionManager.d.ts +6 -1
  222. package/src/orm/ConnectionManager.d.ts.map +1 -1
  223. package/src/orm/ConnectionManager.js +14 -0
  224. package/src/orm/DatabaseAdapter.d.ts +6 -0
  225. package/src/orm/DatabaseAdapter.d.ts.map +1 -1
  226. package/src/orm/QueryBuilder.d.ts +8 -1
  227. package/src/orm/QueryBuilder.d.ts.map +1 -1
  228. package/src/orm/QueryBuilder.js +188 -28
  229. package/src/orm/adapters/D1Adapter.d.ts.map +1 -1
  230. package/src/orm/adapters/D1Adapter.js +18 -12
  231. package/src/orm/adapters/MySQLAdapter.d.ts.map +1 -1
  232. package/src/orm/adapters/MySQLAdapter.js +4 -0
  233. package/src/orm/adapters/PostgreSQLAdapter.d.ts.map +1 -1
  234. package/src/orm/adapters/PostgreSQLAdapter.js +4 -0
  235. package/src/orm/adapters/SQLServerAdapter.d.ts.map +1 -1
  236. package/src/orm/adapters/SQLServerAdapter.js +4 -0
  237. package/src/orm/adapters/SQLiteAdapter.d.ts.map +1 -1
  238. package/src/orm/adapters/SQLiteAdapter.js +4 -0
  239. package/src/performance/CodeGenerationBenchmark.js +3 -3
  240. package/src/performance/Optimizer.d.ts +1 -1
  241. package/src/performance/Optimizer.d.ts.map +1 -1
  242. package/src/performance/Optimizer.js +150 -75
  243. package/src/performance/establish-baseline.js +3 -3
  244. package/src/runtime/PluginManager.d.ts +3 -1
  245. package/src/runtime/PluginManager.d.ts.map +1 -1
  246. package/src/runtime/PluginManager.js +124 -28
  247. package/src/runtime/RuntimeDetector.d.ts.map +1 -1
  248. package/src/runtime/RuntimeDetector.js +47 -6
  249. package/src/runtime/adapters/CloudflareAdapter.js +2 -2
  250. package/src/runtime/adapters/FargateAdapter.d.ts.map +1 -1
  251. package/src/runtime/adapters/FargateAdapter.js +2 -1
  252. package/src/runtime/adapters/LambdaAdapter.d.ts.map +1 -1
  253. package/src/runtime/adapters/LambdaAdapter.js +4 -2
  254. package/src/runtime/adapters/NodeServerAdapter.d.ts.map +1 -1
  255. package/src/runtime/adapters/NodeServerAdapter.js +2 -1
  256. package/src/scheduler/ScheduleRunner.d.ts +18 -0
  257. package/src/scheduler/ScheduleRunner.d.ts.map +1 -0
  258. package/src/scheduler/ScheduleRunner.js +155 -0
  259. package/src/scheduler/index.d.ts +3 -0
  260. package/src/scheduler/index.d.ts.map +1 -0
  261. package/src/scheduler/index.js +1 -0
  262. package/src/scheduler/types.d.ts +16 -0
  263. package/src/scheduler/types.d.ts.map +1 -0
  264. package/src/scheduler/types.js +4 -0
  265. package/src/schedules/index.d.ts +2 -0
  266. package/src/schedules/index.d.ts.map +1 -0
  267. package/src/schedules/index.js +1 -0
  268. package/src/schedules/log-cleanup.d.ts +4 -0
  269. package/src/schedules/log-cleanup.d.ts.map +1 -0
  270. package/src/schedules/log-cleanup.js +18 -0
  271. package/src/scripts/GenerateEnvArtifacts.d.ts +13 -0
  272. package/src/scripts/GenerateEnvArtifacts.d.ts.map +1 -0
  273. package/src/scripts/GenerateEnvArtifacts.js +171 -0
  274. package/src/scripts/TemplateSync.js +109 -70
  275. package/src/security/CsrfTokenManager.js +1 -1
  276. package/src/security/Encryptor.js +1 -1
  277. package/src/security/Hash.d.ts +14 -0
  278. package/src/security/Hash.d.ts.map +1 -0
  279. package/src/security/Hash.js +81 -0
  280. package/src/security/StartupSecretValidation.d.ts +20 -0
  281. package/src/security/StartupSecretValidation.d.ts.map +1 -0
  282. package/src/security/StartupSecretValidation.js +61 -0
  283. package/src/security/UrlValidator.d.ts +0 -1
  284. package/src/security/UrlValidator.d.ts.map +1 -1
  285. package/src/security/UrlValidator.js +1 -2
  286. package/src/security/Xss.d.ts +14 -0
  287. package/src/security/Xss.d.ts.map +1 -0
  288. package/src/security/Xss.js +57 -0
  289. package/src/security/XssProtection.d.ts.map +1 -1
  290. package/src/security/XssProtection.js +155 -17
  291. package/src/templates/adapters/MySQLAdapter.ts.tpl +5 -0
  292. package/src/templates/adapters/PostgreSQLAdapter.ts.tpl +5 -0
  293. package/src/templates/adapters/SQLServerAdapter.ts.tpl +5 -0
  294. package/src/templates/adapters/SQLiteAdapter.ts.tpl +5 -0
  295. package/src/templates/features/Queue.ts.tpl +1 -29
  296. package/src/templates/project/basic/.env.example.tpl +48 -0
  297. package/src/templates/project/basic/.env.tpl +89 -94
  298. package/src/templates/project/basic/app/Toolkit/Broadcast/sendBroadcast.ts.tpl +7 -0
  299. package/src/templates/project/basic/app/Toolkit/Mail/sendWelcomeEmail.ts.tpl +30 -0
  300. package/src/templates/project/basic/app/Toolkit/Notification/sendSlackNotification.ts.tpl +10 -0
  301. package/src/templates/project/basic/app/Toolkit/Notification/sendSms.ts.tpl +13 -0
  302. package/src/templates/project/basic/config/FileLogWriter.ts.tpl +240 -0
  303. package/src/templates/project/basic/config/SecretsManager.ts.tpl +44 -21
  304. package/src/templates/project/basic/config/StartupConfigValidator.ts.tpl +151 -0
  305. package/src/templates/project/basic/config/app.ts.tpl +84 -15
  306. package/src/templates/project/basic/config/broadcast.ts.tpl +97 -0
  307. package/src/templates/project/basic/config/cache.ts.tpl +19 -23
  308. package/src/templates/project/basic/config/cloudflare.ts.tpl +57 -0
  309. package/src/templates/project/basic/config/env.ts.tpl +7 -1
  310. package/src/templates/project/basic/config/index.ts.tpl +3 -0
  311. package/src/templates/project/basic/config/logger.ts.tpl +301 -11
  312. package/src/templates/project/basic/config/logging/HttpLogger.ts.tpl +121 -0
  313. package/src/templates/project/basic/config/logging/KvLogger.ts.tpl +181 -0
  314. package/src/templates/project/basic/config/logging/SlackLogger.ts.tpl +156 -0
  315. package/src/templates/project/basic/config/mail.ts.tpl +141 -0
  316. package/src/templates/project/basic/config/middleware.ts.tpl +27 -0
  317. package/src/templates/project/basic/config/notification.ts.tpl +86 -0
  318. package/src/templates/project/basic/config/security.ts.tpl +4 -5
  319. package/src/templates/project/basic/config/startup.ts.tpl +27 -0
  320. package/src/templates/project/basic/config/storage.ts.tpl +77 -42
  321. package/src/templates/project/basic/database/migrations/index.ts.tpl +1 -1
  322. package/src/templates/project/basic/package.json.tpl +1 -1
  323. package/src/templates/project/basic/routes/api.ts.tpl +11 -37
  324. package/src/templates/project/basic/routes/broadcast.ts.tpl +32 -0
  325. package/src/templates/project/basic/routes/health.ts.tpl +134 -0
  326. package/src/templates/project/basic/routes/storage.ts.tpl +42 -0
  327. package/src/templates/project/basic/src/index.ts.tpl +38 -11
  328. package/src/templates/project/basic/template.json +3 -0
  329. package/src/toolkit/Secrets/EnvFile.d.ts +15 -0
  330. package/src/toolkit/Secrets/EnvFile.d.ts.map +1 -0
  331. package/src/toolkit/Secrets/EnvFile.js +63 -0
  332. package/src/toolkit/Secrets/Manifest.d.ts +24 -0
  333. package/src/toolkit/Secrets/Manifest.d.ts.map +1 -0
  334. package/src/toolkit/Secrets/Manifest.js +71 -0
  335. package/src/toolkit/Secrets/index.d.ts +42 -0
  336. package/src/toolkit/Secrets/index.d.ts.map +1 -0
  337. package/src/toolkit/Secrets/index.js +119 -0
  338. package/src/toolkit/Secrets/providers/AwsSecretsManager.d.ts +14 -0
  339. package/src/toolkit/Secrets/providers/AwsSecretsManager.d.ts.map +1 -0
  340. package/src/toolkit/Secrets/providers/AwsSecretsManager.js +131 -0
  341. package/src/toolkit/Secrets/providers/CloudflareKv.d.ts +9 -0
  342. package/src/toolkit/Secrets/providers/CloudflareKv.d.ts.map +1 -0
  343. package/src/toolkit/Secrets/providers/CloudflareKv.js +73 -0
  344. package/src/tools/broadcast/Broadcast.d.ts +7 -0
  345. package/src/tools/broadcast/Broadcast.d.ts.map +1 -0
  346. package/src/tools/broadcast/Broadcast.js +37 -0
  347. package/src/tools/broadcast/drivers/BaseDriver.d.ts +5 -0
  348. package/src/tools/broadcast/drivers/BaseDriver.d.ts.map +1 -0
  349. package/src/tools/broadcast/drivers/BaseDriver.js +8 -0
  350. package/src/tools/broadcast/drivers/InMemory.d.ts +18 -0
  351. package/src/tools/broadcast/drivers/InMemory.d.ts.map +1 -0
  352. package/src/tools/broadcast/drivers/InMemory.js +16 -0
  353. package/src/tools/broadcast/drivers/Pusher.d.ts +8 -0
  354. package/src/tools/broadcast/drivers/Pusher.d.ts.map +1 -0
  355. package/src/tools/broadcast/drivers/Pusher.js +75 -0
  356. package/src/tools/broadcast/drivers/Redis.d.ts +19 -0
  357. package/src/tools/broadcast/drivers/Redis.d.ts.map +1 -0
  358. package/src/tools/broadcast/drivers/Redis.js +73 -0
  359. package/src/tools/broadcast/drivers/RedisHttps.d.ts +14 -0
  360. package/src/tools/broadcast/drivers/RedisHttps.d.ts.map +1 -0
  361. package/src/tools/broadcast/drivers/RedisHttps.js +50 -0
  362. package/src/tools/broadcast/index.d.ts +7 -0
  363. package/src/tools/broadcast/index.d.ts.map +1 -0
  364. package/src/tools/broadcast/index.js +6 -0
  365. package/src/tools/http/Http.d.ts +49 -0
  366. package/src/tools/http/Http.d.ts.map +1 -0
  367. package/src/tools/http/Http.js +169 -0
  368. package/src/tools/http/HttpResponse.d.ts +32 -0
  369. package/src/tools/http/HttpResponse.d.ts.map +1 -0
  370. package/src/tools/http/HttpResponse.js +80 -0
  371. package/src/tools/http/index.d.ts +15 -0
  372. package/src/tools/http/index.d.ts.map +1 -0
  373. package/src/tools/http/index.js +9 -0
  374. package/src/tools/mail/Mail.d.ts +22 -0
  375. package/src/tools/mail/Mail.d.ts.map +1 -0
  376. package/src/tools/mail/Mail.js +105 -0
  377. package/src/tools/mail/attachments.d.ts +23 -0
  378. package/src/tools/mail/attachments.d.ts.map +1 -0
  379. package/src/tools/mail/attachments.js +26 -0
  380. package/src/tools/mail/drivers/BaseDriver.d.ts +5 -0
  381. package/src/tools/mail/drivers/BaseDriver.d.ts.map +1 -0
  382. package/src/tools/mail/drivers/BaseDriver.js +8 -0
  383. package/src/tools/mail/drivers/Mailgun.d.ts +31 -0
  384. package/src/tools/mail/drivers/Mailgun.d.ts.map +1 -0
  385. package/src/tools/mail/drivers/Mailgun.js +81 -0
  386. package/src/tools/mail/drivers/SendGrid.d.ts +29 -0
  387. package/src/tools/mail/drivers/SendGrid.d.ts.map +1 -0
  388. package/src/tools/mail/drivers/SendGrid.js +57 -0
  389. package/src/tools/mail/drivers/Ses.d.ts +24 -0
  390. package/src/tools/mail/drivers/Ses.d.ts.map +1 -0
  391. package/src/tools/mail/drivers/Ses.js +116 -0
  392. package/src/tools/mail/drivers/Smtp.d.ts +38 -0
  393. package/src/tools/mail/drivers/Smtp.d.ts.map +1 -0
  394. package/src/tools/mail/drivers/Smtp.js +327 -0
  395. package/src/tools/mail/templates/index.d.ts +27 -0
  396. package/src/tools/mail/templates/index.d.ts.map +1 -0
  397. package/src/tools/mail/templates/index.js +35 -0
  398. package/src/tools/mail/templates/markdown/index.d.ts +17 -0
  399. package/src/tools/mail/templates/markdown/index.d.ts.map +1 -0
  400. package/src/tools/mail/templates/markdown/index.js +49 -0
  401. package/src/tools/mail/templates/markdown/registry.d.ts +15 -0
  402. package/src/tools/mail/templates/markdown/registry.d.ts.map +1 -0
  403. package/src/tools/mail/templates/markdown/registry.js +34 -0
  404. package/src/tools/mail/templates/markdown/validator.d.ts +16 -0
  405. package/src/tools/mail/templates/markdown/validator.d.ts.map +1 -0
  406. package/src/tools/mail/templates/markdown/validator.js +24 -0
  407. package/src/tools/mail/testing.d.ts +41 -0
  408. package/src/tools/mail/testing.d.ts.map +1 -0
  409. package/src/tools/mail/testing.js +34 -0
  410. package/src/tools/notification/Driver.d.ts +11 -0
  411. package/src/tools/notification/Driver.d.ts.map +1 -0
  412. package/src/tools/notification/Driver.js +1 -0
  413. package/src/tools/notification/Notification.d.ts +11 -0
  414. package/src/tools/notification/Notification.d.ts.map +1 -0
  415. package/src/tools/notification/Notification.js +11 -0
  416. package/src/tools/notification/Registry.d.ts +10 -0
  417. package/src/tools/notification/Registry.d.ts.map +1 -0
  418. package/src/tools/notification/Registry.js +22 -0
  419. package/src/tools/notification/Service.d.ts +6 -0
  420. package/src/tools/notification/Service.d.ts.map +1 -0
  421. package/src/tools/notification/Service.js +18 -0
  422. package/src/tools/notification/config.d.ts +5 -0
  423. package/src/tools/notification/config.d.ts.map +1 -0
  424. package/src/tools/notification/config.js +5 -0
  425. package/src/tools/notification/drivers/BaseDriver.d.ts +5 -0
  426. package/src/tools/notification/drivers/BaseDriver.d.ts.map +1 -0
  427. package/src/tools/notification/drivers/BaseDriver.js +8 -0
  428. package/src/tools/notification/drivers/Console.d.ts +7 -0
  429. package/src/tools/notification/drivers/Console.d.ts.map +1 -0
  430. package/src/tools/notification/drivers/Console.js +13 -0
  431. package/src/tools/notification/drivers/Slack.d.ts +16 -0
  432. package/src/tools/notification/drivers/Slack.d.ts.map +1 -0
  433. package/src/tools/notification/drivers/Slack.js +24 -0
  434. package/src/tools/notification/drivers/Termii.d.ts +10 -0
  435. package/src/tools/notification/drivers/Termii.d.ts.map +1 -0
  436. package/src/tools/notification/drivers/Termii.js +47 -0
  437. package/src/tools/notification/drivers/Twilio.d.ts +21 -0
  438. package/src/tools/notification/drivers/Twilio.d.ts.map +1 -0
  439. package/src/tools/notification/drivers/Twilio.js +48 -0
  440. package/src/tools/notification/templates/markdown/index.d.ts +15 -0
  441. package/src/tools/notification/templates/markdown/index.d.ts.map +1 -0
  442. package/src/tools/notification/templates/markdown/index.js +38 -0
  443. package/src/tools/notification/templates/markdown/registry.d.ts +15 -0
  444. package/src/tools/notification/templates/markdown/registry.d.ts.map +1 -0
  445. package/src/tools/notification/templates/markdown/registry.js +36 -0
  446. package/src/tools/notification/testing.d.ts +19 -0
  447. package/src/tools/notification/testing.d.ts.map +1 -0
  448. package/src/tools/notification/testing.js +35 -0
  449. package/src/tools/notification/testingHelpers.d.ts +12 -0
  450. package/src/tools/notification/testingHelpers.d.ts.map +1 -0
  451. package/src/tools/notification/testingHelpers.js +32 -0
  452. package/src/tools/queue/Queue.d.ts +23 -0
  453. package/src/tools/queue/Queue.d.ts.map +1 -0
  454. package/src/tools/queue/Queue.js +38 -0
  455. package/src/tools/queue/drivers/InMemory.d.ts +10 -0
  456. package/src/tools/queue/drivers/InMemory.d.ts.map +1 -0
  457. package/src/tools/queue/drivers/InMemory.js +55 -0
  458. package/src/tools/queue/drivers/Redis.d.ts +10 -0
  459. package/src/tools/queue/drivers/Redis.d.ts.map +1 -0
  460. package/src/tools/queue/drivers/Redis.js +91 -0
  461. package/src/tools/storage/LocalSignedUrl.d.ts +12 -0
  462. package/src/tools/storage/LocalSignedUrl.d.ts.map +1 -0
  463. package/src/tools/storage/LocalSignedUrl.js +108 -0
  464. package/src/tools/storage/drivers/Gcs.d.ts +20 -0
  465. package/src/tools/storage/drivers/Gcs.d.ts.map +1 -0
  466. package/src/tools/storage/drivers/Gcs.js +152 -0
  467. package/src/tools/storage/drivers/Local.d.ts +18 -0
  468. package/src/tools/storage/drivers/Local.d.ts.map +1 -0
  469. package/src/tools/storage/drivers/Local.js +89 -0
  470. package/src/tools/storage/drivers/R2.d.ts +20 -0
  471. package/src/tools/storage/drivers/R2.d.ts.map +1 -0
  472. package/src/tools/storage/drivers/R2.js +73 -0
  473. package/src/tools/storage/drivers/S3.d.ts +26 -0
  474. package/src/tools/storage/drivers/S3.d.ts.map +1 -0
  475. package/src/tools/storage/drivers/S3.js +258 -0
  476. package/src/tools/storage/index.d.ts +24 -0
  477. package/src/tools/storage/index.d.ts.map +1 -0
  478. package/src/tools/storage/index.js +111 -0
  479. package/src/tools/storage/testing.d.ts +23 -0
  480. package/src/tools/storage/testing.d.ts.map +1 -0
  481. package/src/tools/storage/testing.js +52 -0
  482. package/src/tools/templates/MarkdownRenderer.d.ts +14 -0
  483. package/src/tools/templates/MarkdownRenderer.d.ts.map +1 -0
  484. package/src/tools/templates/MarkdownRenderer.js +300 -0
  485. package/src/tools/templates/index.d.ts +5 -0
  486. package/src/tools/templates/index.d.ts.map +1 -0
  487. package/src/tools/templates/index.js +4 -0
@@ -3,6 +3,7 @@
3
3
  * Sealed namespace pattern - all exports through Logger namespace
4
4
  * Replaces console.* calls throughout the codebase
5
5
  */
6
+ import { appConfig } from '@config/app';
6
7
  import { Env } from '@config/env';
7
8
 
8
9
  interface ILogger {
@@ -13,8 +14,146 @@ interface ILogger {
13
14
  fatal(message: string, error?: unknown, category?: string): void;
14
15
  }
15
16
 
16
- const isDevelopment = Env.NODE_ENV === 'development' || Env.NODE_ENV === undefined;
17
- const isProduction = Env.NODE_ENV === 'production';
17
+ const isDevelopment = (): boolean => appConfig.isDevelopment();
18
+ const isProduction = (): boolean => appConfig.isProduction();
19
+
20
+ const getLogFormat = (): string => Env.get('LOG_FORMAT', 'text');
21
+ const isJsonFormat = (value: unknown): value is 'json' => value === 'json';
22
+
23
+ const SENSITIVE_FIELDS = new Set<string>([
24
+ 'password',
25
+ 'token',
26
+ 'authorization',
27
+ 'secret',
28
+ 'apikey',
29
+ 'api_key',
30
+ 'jwt',
31
+ 'bearer',
32
+ ]);
33
+
34
+ const redactSensitiveData = (data: unknown): unknown => {
35
+ const seen = new WeakSet<object>();
36
+
37
+ const walk = (value: unknown): unknown => {
38
+ if (Array.isArray(value)) {
39
+ if (seen.has(value)) return '[Circular]';
40
+ seen.add(value);
41
+ return value.map((v) => walk(v));
42
+ }
43
+
44
+ if (typeof value === 'object' && value !== null) {
45
+ const asObj = value as Record<string, unknown>;
46
+ if (seen.has(asObj)) return '[Circular]';
47
+ seen.add(asObj);
48
+
49
+ const out: Record<string, unknown> = {};
50
+ for (const [key, inner] of Object.entries(asObj)) {
51
+ if (SENSITIVE_FIELDS.has(key.toLowerCase())) {
52
+ out[key] = '[REDACTED]';
53
+ } else {
54
+ out[key] = walk(inner);
55
+ }
56
+ }
57
+ return out;
58
+ }
59
+
60
+ return value;
61
+ };
62
+
63
+ return walk(data);
64
+ };
65
+
66
+ const safeStringify = (obj: unknown, indent: boolean = false): string => {
67
+ const seen = new WeakSet<object>();
68
+ return JSON.stringify(
69
+ obj,
70
+ (_key: string, value: unknown) => {
71
+ if (typeof value === 'object' && value !== null) {
72
+ const asObj = value;
73
+ if (seen.has(asObj)) return '[Circular]';
74
+ seen.add(asObj);
75
+ }
76
+ return value;
77
+ },
78
+ indent ? 2 : 0
79
+ );
80
+ };
81
+
82
+ type FileWriterModule = { FileLogWriter: { write: (line: string) => void } };
83
+
84
+ let fileWriterPromise: Promise<FileWriterModule> | undefined;
85
+ let fileWriter: FileWriterModule['FileLogWriter'] | undefined;
86
+
87
+ const getFileWriter = (): void => {
88
+ if (fileWriter !== undefined) return;
89
+ if (fileWriterPromise !== undefined) return;
90
+ fileWriterPromise = import('@config/FileLogWriter')
91
+ .then((mod) => {
92
+ fileWriter = mod.FileLogWriter;
93
+ return mod;
94
+ })
95
+ .catch(() => {
96
+ fileWriterPromise = undefined;
97
+ return { FileLogWriter: { write: (_line: string) => undefined } };
98
+ });
99
+ };
100
+
101
+ const shouldLogToFile = (): boolean => {
102
+ // Prefer dynamic lookup so late-bound env (tests, some runtimes) is respected.
103
+ if (!Env.getBool('LOG_TO_FILE', false)) return false;
104
+ if (typeof process === 'undefined') return false;
105
+ return true;
106
+ };
107
+
108
+ const buildFileLine = (params: {
109
+ formatted: string;
110
+ data?: unknown;
111
+ errorMessage?: string;
112
+ }): string => {
113
+ if (isJsonFormat(getLogFormat())) return params.formatted;
114
+
115
+ let line = params.formatted;
116
+ if (typeof params.errorMessage === 'string' && params.errorMessage.length > 0) {
117
+ line = `${line} ${params.errorMessage}`;
118
+ } else if (params.data !== undefined && params.data !== '') {
119
+ line = `${line} ${safeStringify(redactSensitiveData(params.data))}`;
120
+ }
121
+ return line;
122
+ };
123
+
124
+ const writeToFile = (line: string): void => {
125
+ if (!shouldLogToFile()) return;
126
+
127
+ if (fileWriter !== undefined) {
128
+ fileWriter.write(line);
129
+ return;
130
+ }
131
+
132
+ getFileWriter();
133
+ fileWriterPromise?.then((mod) => mod.FileLogWriter.write(line));
134
+ };
135
+
136
+ const formatLogMessage = (params: {
137
+ level: 'debug' | 'info' | 'warn' | 'error' | 'fatal';
138
+ message: string;
139
+ data?: unknown;
140
+ category?: string;
141
+ errorMessage?: string;
142
+ }): string => {
143
+ if (isJsonFormat(getLogFormat())) {
144
+ return safeStringify({
145
+ timestamp: new Date().toISOString(),
146
+ level: params.level,
147
+ message: params.message,
148
+ category: params.category,
149
+ data: redactSensitiveData(params.data),
150
+ error: params.errorMessage,
151
+ });
152
+ }
153
+
154
+ // text format
155
+ return `[${params.level.toUpperCase()}] ${params.message}`;
156
+ };
18
157
 
19
158
  /**
20
159
  * Helper to extract error message from unknown error type
@@ -26,38 +165,174 @@ const getErrorMessage = (error?: unknown): string => {
26
165
  if (error instanceof Error) {
27
166
  return error.message;
28
167
  }
29
- return String(error);
168
+
169
+ if (typeof error === 'string') return error;
170
+ if (typeof error === 'number' || typeof error === 'bigint') return error.toString();
171
+ if (typeof error === 'boolean') return error ? 'true' : 'false';
172
+ if (typeof error === 'symbol') return error.toString();
173
+ if (typeof error === 'function') return '[Function]';
174
+
175
+ try {
176
+ return safeStringify(error);
177
+ } catch {
178
+ return '[Unserializable error]';
179
+ }
180
+ };
181
+
182
+ type CloudLogEvent = {
183
+ timestamp: string;
184
+ level: 'debug' | 'info' | 'warn' | 'error' | 'fatal';
185
+ message: string;
186
+ category?: string;
187
+ data?: unknown;
188
+ error?: string;
189
+ };
190
+
191
+ const emitCloudLogs = (event: CloudLogEvent): void => {
192
+ // Lazy-load to avoid cycles and avoid cost when disabled.
193
+ void (async (): Promise<void> => {
194
+ try {
195
+ if (event.level === 'error' || event.level === 'fatal') {
196
+ const mod = await import('@config/logging/KvLogger');
197
+ void mod.KvLogger.enqueue(event);
198
+ }
199
+ } catch {
200
+ // best-effort
201
+ }
202
+
203
+ try {
204
+ if (event.level === 'warn' || event.level === 'error' || event.level === 'fatal') {
205
+ const mod = await import('@config/logging/SlackLogger');
206
+ void mod.SlackLogger.enqueue(event);
207
+ }
208
+ } catch {
209
+ // best-effort
210
+ }
211
+
212
+ try {
213
+ const mod = await import('@config/logging/HttpLogger');
214
+ void mod.HttpLogger.enqueue(event);
215
+ } catch {
216
+ // best-effort
217
+ }
218
+ })();
30
219
  };
31
220
 
32
221
  // Private helper functions
33
222
  const logDebug = (message: string, data?: unknown, category?: string): void => {
34
223
  String(category);
35
- if (isDevelopment) {
36
- console.debug(`[DEBUG] ${message}`, data ?? ''); // eslint-disable-line no-console
224
+ if (isDevelopment()) {
225
+ const timestamp = new Date().toISOString();
226
+ const out = formatLogMessage({ level: 'debug', message, data, category });
227
+ writeToFile(buildFileLine({ formatted: out, data }));
228
+ if (isJsonFormat(getLogFormat())) {
229
+ console.debug(out); // eslint-disable-line no-console
230
+ return;
231
+ }
232
+ console.debug(out, data ?? ''); // eslint-disable-line no-console
233
+
234
+ emitCloudLogs({
235
+ timestamp,
236
+ level: 'debug',
237
+ message,
238
+ category,
239
+ data: redactSensitiveData(data),
240
+ });
37
241
  }
38
242
  };
39
243
 
40
244
  const logInfo = (message: string, data?: unknown, category?: string): void => {
41
245
  String(category);
42
- console.log(`[INFO] ${message}`, data ?? ''); // eslint-disable-line no-console
246
+ const timestamp = new Date().toISOString();
247
+ const out = formatLogMessage({ level: 'info', message, data, category });
248
+ writeToFile(buildFileLine({ formatted: out, data }));
249
+ if (isJsonFormat(getLogFormat())) {
250
+ console.log(out); // eslint-disable-line no-console
251
+ } else {
252
+ console.log(out, data ?? ''); // eslint-disable-line no-console
253
+ }
254
+
255
+ emitCloudLogs({
256
+ timestamp,
257
+ level: 'info',
258
+ message,
259
+ category,
260
+ data: redactSensitiveData(data),
261
+ });
43
262
  };
44
263
 
45
264
  const logWarn = (message: string, data?: unknown, category?: string): void => {
46
265
  String(category);
47
- console.warn(`[WARN] ${message}`, data ?? ''); // eslint-disable-line no-console
266
+ const timestamp = new Date().toISOString();
267
+ const out = formatLogMessage({ level: 'warn', message, data, category });
268
+ writeToFile(buildFileLine({ formatted: out, data }));
269
+ if (isJsonFormat(getLogFormat())) {
270
+ console.warn(out); // eslint-disable-line no-console
271
+ } else {
272
+ console.warn(out, data ?? ''); // eslint-disable-line no-console
273
+ }
274
+
275
+ emitCloudLogs({
276
+ timestamp,
277
+ level: 'warn',
278
+ message,
279
+ category,
280
+ data: redactSensitiveData(data),
281
+ });
48
282
  };
49
283
 
50
284
  const logError = (message: string, error?: unknown, category?: string): void => {
51
285
  const errorMessage = getErrorMessage(error);
52
286
  String(category);
53
- console.error(`[ERROR] ${message}`, errorMessage); // eslint-disable-line no-console
287
+ const timestamp = new Date().toISOString();
288
+ const out = formatLogMessage({
289
+ level: 'error',
290
+ message,
291
+ category,
292
+ errorMessage,
293
+ });
294
+ writeToFile(buildFileLine({ formatted: out, errorMessage }));
295
+ if (isJsonFormat(getLogFormat())) {
296
+ console.error(out); // eslint-disable-line no-console
297
+ } else {
298
+ console.error(out, errorMessage); // eslint-disable-line no-console
299
+ }
300
+
301
+ emitCloudLogs({
302
+ timestamp,
303
+ level: 'error',
304
+ message,
305
+ category,
306
+ error: errorMessage,
307
+ });
54
308
  };
55
309
 
56
310
  const logFatal = (message: string, error?: unknown, category?: string): void => {
57
311
  const errorMessage = getErrorMessage(error);
58
312
  String(category);
59
- console.error(`[FATAL] ${message}`, errorMessage); // eslint-disable-line no-console
60
- if (isProduction && typeof process !== 'undefined') {
313
+ const timestamp = new Date().toISOString();
314
+ const out = formatLogMessage({
315
+ level: 'fatal',
316
+ message,
317
+ category,
318
+ errorMessage,
319
+ });
320
+ writeToFile(buildFileLine({ formatted: out, errorMessage }));
321
+ if (isJsonFormat(getLogFormat())) {
322
+ console.error(out); // eslint-disable-line no-console
323
+ } else {
324
+ console.error(out, errorMessage); // eslint-disable-line no-console
325
+ }
326
+
327
+ emitCloudLogs({
328
+ timestamp,
329
+ level: 'fatal',
330
+ message,
331
+ category,
332
+ error: errorMessage,
333
+ });
334
+
335
+ if (isProduction() && typeof process !== 'undefined') {
61
336
  process.exit(1);
62
337
  }
63
338
  };
@@ -82,13 +357,28 @@ const createLoggerScope = (scope: string): ILogger => {
82
357
  };
83
358
  };
84
359
 
85
- // Sealed namespace with all logger functionality
360
+ // Expose log cleanup API and sealed namespace with all logger functionality
361
+ export const cleanLogsOnce = async (): Promise<string[]> => {
362
+ if (!shouldLogToFile()) return [];
363
+
364
+ try {
365
+ const mod = await import('@config/FileLogWriter');
366
+ const deleted = mod.cleanOnce();
367
+ logInfo('Log cleanup executed', { deletedCount: deleted.length });
368
+ return deleted;
369
+ } catch (err: unknown) {
370
+ logError('Log cleanup failed', err as Error);
371
+ return [];
372
+ }
373
+ };
374
+
86
375
  export const Logger = Object.freeze({
87
376
  debug: logDebug,
88
377
  info: logInfo,
89
378
  warn: logWarn,
90
379
  error: logError,
91
380
  fatal: logFatal,
381
+ cleanLogsOnce,
92
382
  scope: createLoggerScope,
93
383
  });
94
384
 
@@ -0,0 +1,121 @@
1
+ /**
2
+ * HTTP Endpoint Logger
3
+ * Sends logs to an external HTTP logging service.
4
+ *
5
+ * Enabled via env:
6
+ * - HTTP_LOG_ENABLED (default: false)
7
+ * - HTTP_LOG_ENDPOINT_URL
8
+ * - HTTP_LOG_BATCH_SIZE (default: 50)
9
+ * - HTTP_LOG_AUTH_TOKEN (optional)
10
+ */
11
+
12
+ import { delay } from '@common/index';
13
+ import { Env } from '@config/env';
14
+ import { ErrorFactory } from '@exceptions/ZintrustError';
15
+ import { HttpClient } from '@httpClient/Http';
16
+
17
+ export type HttpLogEvent = {
18
+ timestamp: string;
19
+ level: 'debug' | 'info' | 'warn' | 'error' | 'fatal';
20
+ message: string;
21
+ category?: string;
22
+ data?: unknown;
23
+ error?: string;
24
+ };
25
+
26
+ const isEnabled = (): boolean => Env.getBool('HTTP_LOG_ENABLED', false);
27
+
28
+ let buffer: HttpLogEvent[] = [];
29
+ let flushPromise: Promise<void> | undefined;
30
+
31
+ const postBatch = async (events: HttpLogEvent[]): Promise<void> => {
32
+ const endpoint = Env.get('HTTP_LOG_ENDPOINT_URL').trim();
33
+ if (endpoint.length === 0) {
34
+ throw ErrorFactory.createConfigError(
35
+ 'HTTP_LOG_ENDPOINT_URL is required when HTTP logging is enabled'
36
+ );
37
+ }
38
+
39
+ const token = Env.get('HTTP_LOG_AUTH_TOKEN').trim();
40
+
41
+ const builder = HttpClient.post(endpoint, {
42
+ sentAt: new Date().toISOString(),
43
+ count: events.length,
44
+ events,
45
+ });
46
+
47
+ if (token.length > 0) {
48
+ builder.withAuth(token, 'Bearer');
49
+ }
50
+
51
+ await builder.send();
52
+ };
53
+
54
+ const flushNow = async (): Promise<void> => {
55
+ const toSend = buffer;
56
+ buffer = [];
57
+
58
+ if (!isEnabled()) return;
59
+ if (toSend.length === 0) return;
60
+
61
+ const maxRetries = 3;
62
+
63
+ const attemptPost = async (attempt: number): Promise<void> => {
64
+ try {
65
+ await postBatch(toSend);
66
+ } catch {
67
+ if (attempt >= maxRetries) return;
68
+ const backoffMs = 100 * 2 ** attempt;
69
+ await delay(backoffMs);
70
+ await attemptPost(attempt + 1);
71
+ }
72
+ };
73
+
74
+ await attemptPost(0);
75
+ };
76
+
77
+ const scheduleFlush = async (): Promise<void> => {
78
+ if (flushPromise !== undefined) return flushPromise;
79
+
80
+ const promise = new Promise<void>((resolve) => {
81
+ const run = async (): Promise<void> => {
82
+ try {
83
+ await flushNow();
84
+ } finally {
85
+ resolve(undefined);
86
+ }
87
+ };
88
+
89
+ if (typeof globalThis.setTimeout !== 'function') {
90
+ void run();
91
+ return;
92
+ }
93
+
94
+ globalThis.setTimeout(() => {
95
+ void run();
96
+ }, 0);
97
+ });
98
+
99
+ flushPromise = promise.finally(() => {
100
+ flushPromise = undefined;
101
+ });
102
+
103
+ return flushPromise;
104
+ };
105
+
106
+ export const HttpLogger = Object.freeze({
107
+ async enqueue(event: HttpLogEvent): Promise<void> {
108
+ if (!isEnabled()) return Promise.resolve(); // NOSONAR
109
+
110
+ buffer.push(event);
111
+
112
+ const batchSize = Math.max(1, Env.getInt('HTTP_LOG_BATCH_SIZE', 50));
113
+ if (buffer.length >= batchSize) {
114
+ return scheduleFlush();
115
+ }
116
+
117
+ return scheduleFlush();
118
+ },
119
+ });
120
+
121
+ export default HttpLogger;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * KV Logger
3
+ * Writes batches of log events to a KV namespace (Cloudflare Workers compatible)
4
+ *
5
+ * Enabled via env:
6
+ * - KV_LOG_ENABLED (default: false)
7
+ * - KV_NAMESPACE (binding name; default: 'CACHE')
8
+ * - KV_LOG_RETENTION_DAYS (default: 30)
9
+ */
10
+
11
+ import { Cloudflare } from '@config/cloudflare';
12
+ import { Env } from '@config/env';
13
+
14
+ export type KvLogEvent = {
15
+ timestamp: string;
16
+ level: 'debug' | 'info' | 'warn' | 'error' | 'fatal';
17
+ message: string;
18
+ category?: string;
19
+ data?: unknown;
20
+ error?: string;
21
+ };
22
+
23
+ type KVNamespace = NonNullable<ReturnType<typeof Cloudflare.getKVBinding>>;
24
+
25
+ type PutOptions = { expiration?: number; expirationTtl?: number; metadata?: unknown };
26
+
27
+ const getRetentionTtlSeconds = (): number => {
28
+ const days = Env.getInt('KV_LOG_RETENTION_DAYS', 30);
29
+ const safeDays = Number.isFinite(days) && days > 0 ? days : 30;
30
+ return safeDays * 24 * 60 * 60;
31
+ };
32
+
33
+ const getKvBindingName = (): string => {
34
+ const name = Env.get('KV_NAMESPACE', 'CACHE').trim();
35
+ return name.length > 0 ? name : 'CACHE';
36
+ };
37
+
38
+ const isEnabled = (): boolean => Env.getBool('KV_LOG_ENABLED', false);
39
+
40
+ const safeRandom = (): string => {
41
+ try {
42
+ // Prefer crypto if available
43
+ const cryptoObj = (globalThis as unknown as { crypto?: Crypto }).crypto;
44
+ if (cryptoObj?.getRandomValues) {
45
+ const bytes = new Uint8Array(8);
46
+ cryptoObj.getRandomValues(bytes);
47
+ return Array.from(bytes)
48
+ .map((b) => b.toString(16).padStart(2, '0'))
49
+ .join('');
50
+ }
51
+ } catch {
52
+ // fall through
53
+ }
54
+ const generate = Math.random().toString(16).slice(2); // NOSONAR
55
+ const fallback = generate + Math.random().toString(16).slice(2); // NOSONAR this is not used for security
56
+ return fallback;
57
+ };
58
+
59
+ const buildKey = (timestampIso: string): string => {
60
+ const date = timestampIso.slice(0, 10);
61
+ const hour = timestampIso.slice(11, 13);
62
+ return `logs:${date}:${hour}:${safeRandom()}`;
63
+ };
64
+
65
+ let buffer: KvLogEvent[] = [];
66
+ let flushTimer: ReturnType<typeof setTimeout> | undefined;
67
+ let flushPromise: Promise<void> | undefined;
68
+
69
+ const scheduleFlush = async (): Promise<void> => {
70
+ if (flushPromise !== undefined) return flushPromise;
71
+
72
+ // Fixed small batching window to reduce KV write volume.
73
+ const windowMs = 1000;
74
+
75
+ const promise = new Promise<void>((resolve) => {
76
+ const run = async (): Promise<void> => {
77
+ try {
78
+ await flushNow();
79
+ } finally {
80
+ resolve(undefined);
81
+ }
82
+ };
83
+
84
+ if (typeof globalThis.setTimeout !== 'function') {
85
+ // microtask-ish
86
+ void run();
87
+ return;
88
+ }
89
+
90
+ flushTimer = globalThis.setTimeout(() => {
91
+ flushTimer = undefined;
92
+ void run();
93
+ }, windowMs);
94
+ });
95
+
96
+ flushPromise = promise.finally(() => {
97
+ flushPromise = undefined;
98
+ });
99
+
100
+ return flushPromise;
101
+ };
102
+
103
+ const getKv = (): KVNamespace | null => {
104
+ const bindingName = getKvBindingName();
105
+ return Cloudflare.getKVBinding(bindingName);
106
+ };
107
+
108
+ const putBatch = async (kv: KVNamespace, events: KvLogEvent[]): Promise<void> => {
109
+ if (events.length === 0) return;
110
+
111
+ const timestamp = events.at(-1)?.timestamp ?? new Date().toISOString();
112
+ const key = buildKey(timestamp);
113
+
114
+ const payload = JSON.stringify({
115
+ version: 1,
116
+ createdAt: new Date().toISOString(),
117
+ count: events.length,
118
+ events,
119
+ });
120
+
121
+ const opts: PutOptions = { expirationTtl: getRetentionTtlSeconds() };
122
+
123
+ await kv.put(key, payload, opts);
124
+ };
125
+
126
+ const flushNow = async (): Promise<void> => {
127
+ if (!isEnabled()) {
128
+ buffer = [];
129
+ return;
130
+ }
131
+
132
+ const kv = getKv();
133
+ if (kv === null) {
134
+ buffer = [];
135
+ return;
136
+ }
137
+
138
+ const toSend = buffer;
139
+ buffer = [];
140
+
141
+ try {
142
+ await putBatch(kv, toSend);
143
+ } catch {
144
+ // Best-effort: never throw from logging.
145
+ }
146
+ };
147
+
148
+ const flushSoon = async (): Promise<void> => {
149
+ if (flushPromise !== undefined) return flushPromise;
150
+
151
+ flushPromise = Promise.resolve()
152
+ .then(async () => flushNow())
153
+ .finally(() => {
154
+ flushPromise = undefined;
155
+ });
156
+
157
+ return flushPromise;
158
+ };
159
+
160
+ export const KvLogger = Object.freeze({
161
+ async enqueue(event: KvLogEvent): Promise<void> {
162
+ if (!isEnabled()) return Promise.resolve();
163
+
164
+ buffer.push(event);
165
+
166
+ // Basic size guard: flush if it gets too large
167
+ const maxBatch = 100;
168
+ if (buffer.length >= maxBatch) {
169
+ // Cancel scheduled flush and flush immediately
170
+ if (flushTimer !== undefined) {
171
+ globalThis.clearTimeout(flushTimer);
172
+ flushTimer = undefined;
173
+ }
174
+ return flushSoon();
175
+ }
176
+
177
+ return scheduleFlush();
178
+ },
179
+ });
180
+
181
+ export default KvLogger;