@futdevpro/nts-dynamo 1.15.151 → 1.15.154

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 (655) hide show
  1. package/.c8rc.json +26 -26
  2. package/.copilot/patterns.json +7 -7
  3. package/.cursor/rules/__assistant_guide.mdc +30 -30
  4. package/.cursor/rules/__main.mdc +64 -64
  5. package/.cursor/rules/_ag_backend-structure.mdc +85 -85
  6. package/.cursor/rules/_ag_backend.mdc +16 -16
  7. package/.cursor/rules/_ag_debug.mdc +7 -7
  8. package/.cursor/rules/_ag_documentation_writing_rules.mdc +372 -372
  9. package/.cursor/rules/_ag_file-refactoring.mdc +113 -113
  10. package/.cursor/rules/_ag_fixes_rules.mdc +5 -5
  11. package/.cursor/rules/_ag_frontend-structure.mdc +86 -86
  12. package/.cursor/rules/_ag_frontend.mdc +39 -39
  13. package/.cursor/rules/_ag_import-rules.mdc +44 -44
  14. package/.cursor/rules/_ag_naming.mdc +115 -115
  15. package/.cursor/rules/_ag_running_commands.mdc +4 -4
  16. package/.cursor/rules/_ag_server-controller.mdc +5 -5
  17. package/.cursor/rules/_ag_should-be.mdc +6 -6
  18. package/.cursor/rules/_ag_swearing.mdc +47 -47
  19. package/.cursor/rules/ai_development_guide.md +60 -60
  20. package/.cursor/rules/ai_directives.md +114 -114
  21. package/.cursor/rules/cursor-rules.md +160 -160
  22. package/.cursor/rules/default-command.mdc +464 -464
  23. package/.cursor/rules/error_code_pattern.md +39 -39
  24. package/.cursor/rules/saved rule mcp server use.md +15 -15
  25. package/.dynamo/pipeline.cicd.config.json +190 -190
  26. package/.dynamo/version-bump.config.json +5 -5
  27. package/.github/workflows/main.yml +438 -438
  28. package/.husky/pre-commit +3 -3
  29. package/.vscode/settings.json +10 -10
  30. package/HOWTO.md +15 -15
  31. package/LICENSE +21 -21
  32. package/README.md +790 -749
  33. package/__documentations/2026-04-28-logs-module.md +49 -49
  34. package/__documentations/2026-05-17-oai-compatible-providers.md +229 -229
  35. package/__documentations/2026-05-17-static-client-serving-howto.md +144 -144
  36. package/__documentations/2026-06-01-fr041-cors-middleware.md +96 -96
  37. package/__documentations/2026-06-01-fr047-p2p3-function-calling.md +81 -81
  38. package/__documentations/2026-06-15-fr193-memory-guard.md +73 -73
  39. package/__documentations/2026-08-08-fr292-app-version-header.md +38 -38
  40. package/__documentations/2026-08-14-field-encryption-mongoose-document-spread.md +124 -124
  41. package/__documentations/2026-08-18-artifact-compiler.md +46 -46
  42. package/__documentations/2026-08-18-mongo-transaction-control-service.md +82 -82
  43. package/__documentations/2026-08-18-standalone-account-security-and-privacy-bedrock.md +132 -132
  44. package/__documentations/2026-08-21-distributed-rate-limit-bfr-ctm-010.md +59 -59
  45. package/__documentations/2026-08-22-content-free-process-error-boundary.md +91 -0
  46. package/__documentations/2026-08-22-npm-token-state-classifier.md +92 -92
  47. package/__documentations/nts-integration-tests-2026-03-17.md +26 -26
  48. package/__documentations/plans/BEDROCK-HYPERPLAN.md +95 -95
  49. package/_specifications/BACKLOG.md +92 -92
  50. package/_specifications/TODO.md +15 -15
  51. package/_specifications/agent.md +138 -138
  52. package/build/_models/control-models/app-params.control-model.d.ts.map +1 -1
  53. package/build/_models/control-models/app-params.control-model.js +1 -2
  54. package/build/_models/control-models/app-params.control-model.js.map +1 -1
  55. package/build/_modules/server/index.d.ts +8 -0
  56. package/build/_modules/server/index.d.ts.map +1 -1
  57. package/build/_modules/server/index.js +9 -0
  58. package/build/_modules/server/index.js.map +1 -1
  59. package/build/_modules/server/safe-diagnostic/safe-diagnostic-cause.type-enum.d.ts +9 -0
  60. package/build/_modules/server/safe-diagnostic/safe-diagnostic-cause.type-enum.d.ts.map +1 -0
  61. package/build/_modules/server/safe-diagnostic/safe-diagnostic-cause.type-enum.js +13 -0
  62. package/build/_modules/server/safe-diagnostic/safe-diagnostic-cause.type-enum.js.map +1 -0
  63. package/build/_modules/server/safe-diagnostic/safe-diagnostic-stage.type-enum.d.ts +20 -0
  64. package/build/_modules/server/safe-diagnostic/safe-diagnostic-stage.type-enum.d.ts.map +1 -0
  65. package/build/_modules/server/safe-diagnostic/safe-diagnostic-stage.type-enum.js +24 -0
  66. package/build/_modules/server/safe-diagnostic/safe-diagnostic-stage.type-enum.js.map +1 -0
  67. package/build/_modules/server/safe-diagnostic/safe-diagnostic.control-service.d.ts +19 -0
  68. package/build/_modules/server/safe-diagnostic/safe-diagnostic.control-service.d.ts.map +1 -0
  69. package/build/_modules/server/safe-diagnostic/safe-diagnostic.control-service.js +83 -0
  70. package/build/_modules/server/safe-diagnostic/safe-diagnostic.control-service.js.map +1 -0
  71. package/build/_modules/server/safe-diagnostic/safe-diagnostic.interface.d.ts +19 -0
  72. package/build/_modules/server/safe-diagnostic/safe-diagnostic.interface.d.ts.map +1 -0
  73. package/build/_modules/server/safe-diagnostic/safe-diagnostic.interface.js +3 -0
  74. package/build/_modules/server/safe-diagnostic/safe-diagnostic.interface.js.map +1 -0
  75. package/build/_modules/server/server-status/db-readiness-probe-code.type-enum.d.ts +14 -0
  76. package/build/_modules/server/server-status/db-readiness-probe-code.type-enum.d.ts.map +1 -0
  77. package/build/_modules/server/server-status/db-readiness-probe-code.type-enum.js +18 -0
  78. package/build/_modules/server/server-status/db-readiness-probe-code.type-enum.js.map +1 -0
  79. package/build/_modules/server/server-status/db-readiness-probe-stage.type-enum.d.ts +8 -0
  80. package/build/_modules/server/server-status/db-readiness-probe-stage.type-enum.d.ts.map +1 -0
  81. package/build/_modules/server/server-status/db-readiness-probe-stage.type-enum.js +12 -0
  82. package/build/_modules/server/server-status/db-readiness-probe-stage.type-enum.js.map +1 -0
  83. package/build/_modules/server/server-status/db-readiness-probe.control-service.d.ts +14 -0
  84. package/build/_modules/server/server-status/db-readiness-probe.control-service.d.ts.map +1 -0
  85. package/build/_modules/server/server-status/db-readiness-probe.control-service.js +126 -0
  86. package/build/_modules/server/server-status/db-readiness-probe.control-service.js.map +1 -0
  87. package/build/_modules/server/server-status/db-readiness-probe.interface.d.ts +18 -0
  88. package/build/_modules/server/server-status/db-readiness-probe.interface.d.ts.map +1 -0
  89. package/build/_modules/server/server-status/db-readiness-probe.interface.js +3 -0
  90. package/build/_modules/server/server-status/db-readiness-probe.interface.js.map +1 -0
  91. package/build/_services/core/global.service.d.ts +3 -3
  92. package/build/_services/core/global.service.d.ts.map +1 -1
  93. package/build/_services/core/global.service.js +24 -18
  94. package/build/_services/core/global.service.js.map +1 -1
  95. package/build/_services/server/app.server.d.ts +2 -0
  96. package/build/_services/server/app.server.d.ts.map +1 -1
  97. package/build/_services/server/app.server.js +71 -199
  98. package/build/_services/server/app.server.js.map +1 -1
  99. package/eslint.config.js +3 -3
  100. package/nodemon.json +24 -24
  101. package/package.json +1 -1
  102. package/pnpm-workspace.yaml +6 -6
  103. package/scripts/_seed-out/aim-seed.fixtures.ts +161 -161
  104. package/scripts/_seed-out/llm-expand-raw.json +59 -59
  105. package/scripts/_seed-out/seed-raw.json +152 -152
  106. package/scripts/ai-fixture-seed.js +126 -126
  107. package/scripts/run-coverage-tests.js +28 -28
  108. package/spec/support/helpers/spec-reporter-loader.js +359 -359
  109. package/spec/support/helpers/ts-node-helper.js +93 -93
  110. package/spec/support/jasmine.coverage.json +24 -24
  111. package/spec/support/jasmine.json +24 -24
  112. package/src/_collections/app-version-header.util.spec.ts +108 -108
  113. package/src/_collections/app-version-header.util.ts +74 -74
  114. package/src/_collections/archive-service-registry.const.ts +21 -21
  115. package/src/_collections/archive.util.spec.ts +57 -57
  116. package/src/_collections/archive.util.ts +18 -18
  117. package/src/_collections/atlas-default-db-options.const.ts +9 -9
  118. package/src/_collections/client-safe-error.util.spec.ts +151 -151
  119. package/src/_collections/client-safe-error.util.ts +107 -107
  120. package/src/_collections/default-fallback-cache-max-age.const.spec.ts +11 -11
  121. package/src/_collections/default-fallback-cache-max-age.const.ts +2 -2
  122. package/src/_collections/default-not-found-page.const.spec.ts +19 -19
  123. package/src/_collections/default-not-found-page.const.ts +22 -22
  124. package/src/_collections/default-socket-path.const.spec.ts +12 -12
  125. package/src/_collections/default-socket-path.const.ts +2 -2
  126. package/src/_collections/field-encryption.util.spec.ts +195 -195
  127. package/src/_collections/field-encryption.util.ts +222 -222
  128. package/src/_collections/get-environment-settings.util.spec.ts +210 -210
  129. package/src/_collections/get-environment-settings.util.ts +48 -48
  130. package/src/_collections/global-settings.const.ts +126 -126
  131. package/src/_collections/load-shed.util.spec.ts +62 -62
  132. package/src/_collections/load-shed.util.ts +51 -51
  133. package/src/_collections/mongo-reconnect-guard.util.spec.ts +52 -52
  134. package/src/_collections/mongo-reconnect-guard.util.ts +172 -172
  135. package/src/_collections/npm-token-check.util.spec.ts +218 -218
  136. package/src/_collections/npm-token-check.util.ts +327 -327
  137. package/src/_collections/sample.env +21 -21
  138. package/src/_collections/security-headers.util.spec.ts +98 -98
  139. package/src/_collections/security-headers.util.ts +96 -96
  140. package/src/_collections/signed-url.util.spec.ts +198 -198
  141. package/src/_collections/signed-url.util.ts +170 -170
  142. package/src/_collections/star.controller.spec.ts +224 -224
  143. package/src/_collections/star.controller.ts +129 -129
  144. package/src/_collections/static-cache-control.util.spec.ts +47 -47
  145. package/src/_collections/static-cache-control.util.ts +25 -25
  146. package/src/_enums/data-model-type.enum.ts +14 -14
  147. package/src/_enums/data-service-function.enum.ts +24 -24
  148. package/src/_enums/predefined-data-types.enum.ts +16 -16
  149. package/src/_enums/route-security.enum.ts +12 -12
  150. package/src/_models/control-models/api-call-params.control-model.spec.ts +152 -152
  151. package/src/_models/control-models/api-call-params.control-model.ts +142 -142
  152. package/src/_models/control-models/app-ext-system-controls.control-model.spec.ts +52 -52
  153. package/src/_models/control-models/app-ext-system-controls.control-model.ts +9 -9
  154. package/src/_models/control-models/app-params.control-model.spec.ts +213 -209
  155. package/src/_models/control-models/app-params.control-model.ts +130 -129
  156. package/src/_models/control-models/app-system-controls.control-model.spec.ts +31 -31
  157. package/src/_models/control-models/app-system-controls.control-model.ts +9 -9
  158. package/src/_models/control-models/endpoint-params.control-model.spec.ts +669 -669
  159. package/src/_models/control-models/endpoint-params.control-model.ts +664 -664
  160. package/src/_models/control-models/http-settings.control-model.spec.ts +77 -77
  161. package/src/_models/control-models/http-settings.control-model.ts +37 -37
  162. package/src/_models/control-models/system-control.control-model.spec.ts +27 -27
  163. package/src/_models/control-models/system-control.control-model.ts +12 -12
  164. package/src/_models/data-models/schema-migration.data-model.ts +50 -50
  165. package/src/_models/interfaces/app-version-header-settings.interface.ts +17 -17
  166. package/src/_models/interfaces/certification-settings.interface.ts +7 -7
  167. package/src/_models/interfaces/compare-data-options.interface.ts +27 -27
  168. package/src/_models/interfaces/compare-data-result.interface.ts +12 -12
  169. package/src/_models/interfaces/cors-settings.interface.spec.ts +52 -52
  170. package/src/_models/interfaces/cors-settings.interface.ts +56 -56
  171. package/src/_models/interfaces/db-query-options.interface.ts +33 -33
  172. package/src/_models/interfaces/environment-settings.interface.ts +59 -59
  173. package/src/_models/interfaces/global-log-settings.interface.ts +171 -171
  174. package/src/_models/interfaces/global-service-settings.interface.ts +47 -47
  175. package/src/_models/interfaces/global-settings.interface.ts +294 -294
  176. package/src/_models/interfaces/migration-entry.interface.ts +19 -19
  177. package/src/_models/interfaces/mongo-transaction-settings.interface.ts +9 -9
  178. package/src/_models/interfaces/routing-module-settings.interface.ts +21 -21
  179. package/src/_models/interfaces/security-headers-settings.interface.ts +50 -50
  180. package/src/_models/interfaces/signed-url-verify-result.interface.ts +13 -13
  181. package/src/_models/interfaces/static-client-settings.interface.spec.ts +29 -29
  182. package/src/_models/interfaces/static-client-settings.interface.ts +36 -36
  183. package/src/_models/types/db-update.type.ts +100 -100
  184. package/src/_modules/account-security/_enums/account-challenge-purpose.type-enum.ts +5 -5
  185. package/src/_modules/account-security/_enums/account-refresh-token-state.type-enum.ts +6 -6
  186. package/src/_modules/account-security/_enums/account-session-state.type-enum.ts +6 -6
  187. package/src/_modules/account-security/_models/account-challenge-adapter.interface.ts +17 -17
  188. package/src/_modules/account-security/_models/account-challenge-issued.interface.ts +6 -6
  189. package/src/_modules/account-security/_models/account-challenge-record.interface.ts +13 -13
  190. package/src/_modules/account-security/_models/account-challenge-result.interface.ts +8 -8
  191. package/src/_modules/account-security/_models/account-challenge-settings.interface.ts +9 -9
  192. package/src/_modules/account-security/_models/account-password-policy.interface.ts +11 -11
  193. package/src/_modules/account-security/_models/account-password-verification.interface.ts +5 -5
  194. package/src/_modules/account-security/_models/account-refresh-token-record.interface.ts +13 -13
  195. package/src/_modules/account-security/_models/account-session-adapter.interface.ts +19 -19
  196. package/src/_modules/account-security/_models/account-session-claims.interface.ts +7 -7
  197. package/src/_modules/account-security/_models/account-session-context.interface.ts +6 -6
  198. package/src/_modules/account-security/_models/account-session-create.interface.ts +8 -8
  199. package/src/_modules/account-security/_models/account-session-record.interface.ts +21 -21
  200. package/src/_modules/account-security/_models/account-session-rotate.interface.ts +11 -11
  201. package/src/_modules/account-security/_models/account-session-settings.interface.ts +11 -11
  202. package/src/_modules/account-security/_models/account-session-token-pair.interface.ts +8 -8
  203. package/src/_modules/account-security/_models/account-session-view.interface.ts +13 -13
  204. package/src/_modules/account-security/account-challenge.control-service.spec.ts +195 -195
  205. package/src/_modules/account-security/account-challenge.control-service.ts +164 -164
  206. package/src/_modules/account-security/account-password.control-service.spec.ts +96 -96
  207. package/src/_modules/account-security/account-password.control-service.ts +288 -288
  208. package/src/_modules/account-security/account-session.control-service.spec.ts +294 -294
  209. package/src/_modules/account-security/account-session.control-service.ts +376 -376
  210. package/src/_modules/account-security/index.ts +31 -31
  211. package/src/_modules/admin-auth/_models/admin-api-key-config.interface.ts +33 -33
  212. package/src/_modules/admin-auth/admin-api-key.auth-service.spec.ts +200 -200
  213. package/src/_modules/admin-auth/admin-api-key.auth-service.ts +220 -220
  214. package/src/_modules/admin-auth/index.ts +2 -2
  215. package/src/_modules/ai/_collections/ai-model-config-validator.util.spec.ts +150 -150
  216. package/src/_modules/ai/_collections/ai-model-config-validator.util.ts +131 -131
  217. package/src/_modules/ai/_collections/ai-provider-error.util.ts +144 -144
  218. package/src/_modules/ai/_models/ai-input-interfaces.ts +117 -117
  219. package/src/_modules/ai/_models/ai-test-generation-result.interface.ts +16 -16
  220. package/src/_modules/ai/_models/interfaces/dynts-ai-cost-event-callback.interface.ts +14 -14
  221. package/src/_modules/ai/_models/interfaces/dynts-ai-cost-event.interface.ts +56 -56
  222. package/src/_modules/ai/_models/interfaces/dynts-ai-provider-error.interface.ts +16 -16
  223. package/src/_modules/ai/_modules/ai-mock/_collections/aim-default-collection.util.spec.ts +72 -72
  224. package/src/_modules/ai/_modules/ai-mock/_collections/aim-default-collection.util.ts +71 -71
  225. package/src/_modules/ai/_modules/ai-mock/_collections/aim-fixture-match.util.spec.ts +57 -57
  226. package/src/_modules/ai/_modules/ai-mock/_collections/aim-fixture-match.util.ts +60 -60
  227. package/src/_modules/ai/_modules/ai-mock/_collections/aim-fixture-serializer.util.spec.ts +56 -56
  228. package/src/_modules/ai/_modules/ai-mock/_collections/aim-fixture-serializer.util.ts +117 -117
  229. package/src/_modules/ai/_modules/ai-mock/_enums/aim-modality.enum.ts +28 -28
  230. package/src/_modules/ai/_modules/ai-mock/_models/interfaces/aim-call-input.interface.ts +14 -14
  231. package/src/_modules/ai/_modules/ai-mock/_models/interfaces/aim-error.interface.ts +11 -11
  232. package/src/_modules/ai/_modules/ai-mock/_models/interfaces/aim-fixture.interface.ts +30 -30
  233. package/src/_modules/ai/_modules/ai-mock/_models/interfaces/aim-request.interface.ts +19 -19
  234. package/src/_modules/ai/_modules/ai-mock/_models/interfaces/aim-service-collection.interface.ts +20 -20
  235. package/src/_modules/ai/_modules/ai-mock/_services/ai-embedding-mock.service.spec.ts +115 -115
  236. package/src/_modules/ai/_modules/ai-mock/_services/ai-embedding-mock.service.ts +233 -233
  237. package/src/_modules/ai/_modules/ai-mock/_services/aim-fixture-harness.service.spec.ts +134 -134
  238. package/src/_modules/ai/_modules/ai-mock/_services/aim-fixture-harness.service.ts +127 -127
  239. package/src/_modules/ai/_modules/ai-mock/_services/aim-fixture-pipeline.spec.ts +105 -105
  240. package/src/_modules/ai/_modules/ai-mock/_services/aim-fixture-store.service.spec.ts +50 -50
  241. package/src/_modules/ai/_modules/ai-mock/_services/aim-fixture-store.service.ts +65 -65
  242. package/src/_modules/ai/_modules/ai-mock/_services/aim-integration-proof.spec.ts +92 -92
  243. package/src/_modules/ai/_modules/ai-mock/_services/aim-mock.service.spec.ts +112 -112
  244. package/src/_modules/ai/_modules/ai-mock/_services/aim-mock.service.ts +155 -155
  245. package/src/_modules/ai/_modules/ai-mock/fixtures/aim-text.fixtures.ts +649 -649
  246. package/src/_modules/ai/_modules/ai-mock/index.ts +47 -47
  247. package/src/_modules/ai/_modules/anthropic/_services/aai-user-key.control-service.ts +138 -138
  248. package/src/_modules/ai/_modules/anthropic/index.ts +5 -5
  249. package/src/_modules/ai/_modules/document-ai/_collections/dai-chunking.util.spec.ts +242 -242
  250. package/src/_modules/ai/_modules/document-ai/_collections/dai-chunking.util.ts +639 -639
  251. package/src/_modules/ai/_modules/document-ai/_collections/dai-code-chunking.util.spec.ts +295 -295
  252. package/src/_modules/ai/_modules/document-ai/_collections/dai-code-chunking.util.ts +552 -552
  253. package/src/_modules/ai/_modules/document-ai/_collections/dai-document.util.spec.ts +209 -209
  254. package/src/_modules/ai/_modules/document-ai/_collections/dai-document.util.ts +85 -85
  255. package/src/_modules/ai/_modules/document-ai/_enums/dai-compare-result-type.enum.ts +7 -7
  256. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-doc-chunk.data-model.ts +146 -146
  257. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-doc-page.data-model.ts +162 -162
  258. package/src/_modules/ai/_modules/document-ai/_models/data-models/dai-document.data-model.ts +99 -99
  259. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-code-chunk.interface.ts +68 -68
  260. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-doc-chunk-compare-result.interface.ts +18 -18
  261. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-doc-page-compare-result.interface.ts +19 -19
  262. package/src/_modules/ai/_modules/document-ai/_models/interfaces/dai-document-compare-result.interface.ts +25 -25
  263. package/src/_modules/ai/_modules/document-ai/index.ts +30 -30
  264. package/src/_modules/ai/_modules/fdp-ai/_services/fdpai-user-key.control-service.ts +189 -189
  265. package/src/_modules/ai/_modules/fdp-ai/index.ts +5 -5
  266. package/src/_modules/ai/_modules/open-ai/_collections/oai-global-settings.const.ts +9 -9
  267. package/src/_modules/ai/_modules/open-ai/_collections/oai-llm-predefined-requests-hu.conts.ts +82 -82
  268. package/src/_modules/ai/_modules/open-ai/_collections/oai-llm-predefined-requests.conts.ts +75 -75
  269. package/src/_modules/ai/_modules/open-ai/_enums/oai-gpt-message-role.enum.ts +45 -45
  270. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-global-settings.interface.ts +7 -7
  271. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-gpt-message.interface.ts +7 -7
  272. package/src/_modules/ai/_modules/open-ai/_models/interfaces/oai-llm-predefined-requests.interface.ts +57 -57
  273. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-doc-chunk-data.service.ts +292 -292
  274. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-doc-page.data-service.ts +572 -572
  275. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-document.data-service.spec.ts +342 -342
  276. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-document.data-service.ts +435 -435
  277. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-vector-data.service.spec.ts +550 -550
  278. package/src/_modules/ai/_modules/open-ai/_services/data-services/oai-vector-data.service.ts +630 -630
  279. package/src/_modules/ai/_modules/open-ai/_services/oai-embedding.control-service.spec.ts +332 -332
  280. package/src/_modules/ai/_modules/open-ai/_services/oai-embedding.control-service.ts +132 -132
  281. package/src/_modules/ai/_modules/open-ai/_services/oai-llm-chat.service-base.spec.ts +462 -462
  282. package/src/_modules/ai/_modules/open-ai/_services/oai-llm-chat.service-base.ts +634 -634
  283. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.spec.ts +489 -489
  284. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.tools.spec.ts +173 -173
  285. package/src/_modules/ai/_modules/open-ai/_services/oai-llm.service-base.ts +1085 -1085
  286. package/src/_modules/ai/_modules/open-ai/_services/oai-user-key.control-service.ts +157 -157
  287. package/src/_modules/ai/_modules/open-ai/index.ts +74 -74
  288. package/src/_modules/ai/_services/ai-embedding-provider.registry.spec.ts +110 -110
  289. package/src/_modules/ai/_services/ai-embedding-provider.registry.ts +114 -114
  290. package/src/_modules/ai/_services/ai-embedding.service-base.spec.ts +98 -98
  291. package/src/_modules/ai/_services/ai-embedding.service-base.ts +48 -48
  292. package/src/_modules/ai/_services/ai-llm-chat.service-base.spec.ts +229 -229
  293. package/src/_modules/ai/_services/ai-llm-chat.service-base.ts +68 -68
  294. package/src/_modules/ai/_services/ai-llm.service-base.reconciler.spec.ts +133 -133
  295. package/src/_modules/ai/_services/ai-llm.service-base.spec.ts +250 -250
  296. package/src/_modules/ai/_services/ai-llm.service-base.ts +599 -599
  297. package/src/_modules/ai/_services/ai-provider.service-base.spec.ts +158 -158
  298. package/src/_modules/ai/_services/ai-provider.service-base.ts +67 -67
  299. package/src/_modules/ai/_services/ai-user-key.service-base.ts +59 -59
  300. package/src/_modules/ai/_services/lmstudio-embedding.control-service.spec.ts +197 -197
  301. package/src/_modules/ai/_services/lmstudio-embedding.control-service.ts +399 -399
  302. package/src/_modules/ai/index.ts +33 -33
  303. package/src/_modules/artifact-compiler/_enums/artifact-compile-outcome.type-enum.ts +5 -5
  304. package/src/_modules/artifact-compiler/_enums/artifact-compile-stage.type-enum.ts +8 -8
  305. package/src/_modules/artifact-compiler/_enums/artifact-retry-class.type-enum.ts +6 -6
  306. package/src/_modules/artifact-compiler/_models/artifact-compile.interface.ts +35 -35
  307. package/src/_modules/artifact-compiler/artifact-compiler.control-service.spec.ts +151 -151
  308. package/src/_modules/artifact-compiler/artifact-compiler.control-service.ts +356 -356
  309. package/src/_modules/artifact-compiler/index.ts +9 -9
  310. package/src/_modules/assistant/_collections/ass-global-settings.const.ts +13 -13
  311. package/src/_modules/assistant/_collections/ass.util.spec.ts +176 -176
  312. package/src/_modules/assistant/_collections/ass.util.ts +50 -50
  313. package/src/_modules/assistant/_models/ass-global-settings.interface.ts +15 -15
  314. package/src/_modules/assistant/_services/ass-io.control-service.spec.ts +140 -140
  315. package/src/_modules/assistant/_services/ass-io.control-service.ts +74 -74
  316. package/src/_modules/assistant/_services/ass-main.control-service.spec.ts +192 -192
  317. package/src/_modules/assistant/_services/ass-main.control-service.ts +107 -107
  318. package/src/_modules/assistant/index.ts +19 -19
  319. package/src/_modules/bot/_collections/bot-default-commands.const.ts +12 -12
  320. package/src/_modules/bot/_collections/bot-global-settings.const.ts +39 -39
  321. package/src/_modules/bot/_models/bot-channel-wrapper.interface.ts +62 -62
  322. package/src/_modules/bot/_models/bot-command.interface.ts +8 -8
  323. package/src/_modules/bot/_models/bot-global-settings.interface.ts +96 -96
  324. package/src/_modules/bot/_models/bot-last-mention-date.interface.ts +6 -6
  325. package/src/_modules/bot/_models/bot-last-message-date.interface.ts +5 -5
  326. package/src/_modules/bot/_models/bot-message-wrapper.interface.ts +90 -90
  327. package/src/_modules/bot/_models/bot-user-wrapper.interface.ts +41 -41
  328. package/src/_modules/bot/_modules/discord-bot/_models/dib-platform.types.ts +9 -9
  329. package/src/_modules/bot/_modules/discord-bot/_services/dib-messaging-provider.control-service.spec.ts +431 -431
  330. package/src/_modules/bot/_modules/discord-bot/_services/dib-messaging-provider.control-service.ts +641 -641
  331. package/src/_modules/bot/_modules/discord-bot/index.ts +12 -12
  332. package/src/_modules/bot/_modules/dynamo-bot/_collections/dyb-operations.util.spec.ts +160 -160
  333. package/src/_modules/bot/_modules/dynamo-bot/_collections/dyb-operations.util.ts +55 -55
  334. package/src/_modules/bot/_modules/dynamo-bot/_models/dyb-platform.types.ts +15 -15
  335. package/src/_modules/bot/_modules/dynamo-bot/_services/dyb-messaging-provider.control-service.spec.ts +374 -374
  336. package/src/_modules/bot/_modules/dynamo-bot/_services/dyb-messaging-provider.control-service.ts +447 -447
  337. package/src/_modules/bot/_modules/dynamo-bot/index.ts +15 -15
  338. package/src/_modules/bot/_modules/slack-bot/_models/slb-platform.types.ts +9 -9
  339. package/src/_modules/bot/_modules/slack-bot/_services/slb-messaging-provider.control-service.spec.ts +344 -344
  340. package/src/_modules/bot/_modules/slack-bot/_services/slb-messaging-provider.control-service.ts +197 -197
  341. package/src/_modules/bot/_modules/slack-bot/index.ts +12 -12
  342. package/src/_modules/bot/_modules/teams-bot/_models/teb-platform.types.ts +9 -9
  343. package/src/_modules/bot/_modules/teams-bot/_services/teb-messaging-provider.control-service.spec.ts +345 -345
  344. package/src/_modules/bot/_modules/teams-bot/_services/teb-messaging-provider.control-service.ts +197 -197
  345. package/src/_modules/bot/_modules/teams-bot/index.ts +11 -11
  346. package/src/_modules/bot/_services/bot-commands.control-service.spec.ts +116 -116
  347. package/src/_modules/bot/_services/bot-commands.control-service.ts +158 -158
  348. package/src/_modules/bot/_services/bot-io.control-service.spec.ts +285 -285
  349. package/src/_modules/bot/_services/bot-io.control-service.ts +329 -329
  350. package/src/_modules/bot/_services/bot-main.control-service.spec.ts +208 -208
  351. package/src/_modules/bot/_services/bot-main.control-service.ts +489 -489
  352. package/src/_modules/bot/_services/bot-messaging-provider.service-base.spec.ts +349 -349
  353. package/src/_modules/bot/_services/bot-messaging-provider.service-base.ts +158 -158
  354. package/src/_modules/bot/_services/bot-routines.control-service.spec.ts +111 -111
  355. package/src/_modules/bot/_services/bot-routines.control-service.ts +78 -78
  356. package/src/_modules/bot/index.ts +37 -37
  357. package/src/_modules/custom-data/custom-data.controller.spec.ts +49 -49
  358. package/src/_modules/custom-data/custom-data.controller.ts +67 -67
  359. package/src/_modules/custom-data/custom-data.data-service.spec.ts +54 -54
  360. package/src/_modules/custom-data/custom-data.data-service.ts +21 -21
  361. package/src/_modules/custom-data/get-custom-data-routing-module.util.spec.ts +28 -28
  362. package/src/_modules/custom-data/get-custom-data-routing-module.util.ts +24 -24
  363. package/src/_modules/custom-data/index.ts +9 -9
  364. package/src/_modules/data-readers/_collections/dynts-sqlite-reader.util.spec.ts +176 -176
  365. package/src/_modules/data-readers/_collections/dynts-sqlite-reader.util.ts +203 -203
  366. package/src/_modules/data-readers/_models/interfaces/dynts-sqlite-reader.interface.ts +33 -33
  367. package/src/_modules/data-readers/index.ts +11 -11
  368. package/src/_modules/defaults/_collections/default-endpoints.util.ts +487 -487
  369. package/src/_modules/defaults/_models/default-user.data-model.ts +72 -72
  370. package/src/_modules/defaults/_services/default-auth.service.spec.ts +269 -269
  371. package/src/_modules/defaults/_services/default-auth.service.ts +177 -177
  372. package/src/_modules/defaults/_services/default-socket-events.service.spec.ts +42 -42
  373. package/src/_modules/defaults/_services/default-socket-events.service.ts +61 -61
  374. package/src/_modules/defaults/_services/default-user.data-service.spec.ts +187 -187
  375. package/src/_modules/defaults/_services/default-user.data-service.ts +98 -98
  376. package/src/_modules/defaults/index.ts +17 -17
  377. package/src/_modules/discord-assistant/_collections/dias-global-settings.const.ts +19 -19
  378. package/src/_modules/discord-assistant/_collections/dias.util.spec.ts +366 -366
  379. package/src/_modules/discord-assistant/_collections/dias.util.ts +132 -132
  380. package/src/_modules/discord-assistant/_models/dias-global-settings.interface.ts +19 -19
  381. package/src/_modules/discord-assistant/_models/dias-knowledge.data-model.ts +52 -52
  382. package/src/_modules/discord-assistant/_services/dias-chunk.data-service.ts +177 -177
  383. package/src/_modules/discord-assistant/_services/dias-io.control-service.spec.ts +108 -108
  384. package/src/_modules/discord-assistant/_services/dias-io.control-service.ts +69 -69
  385. package/src/_modules/discord-assistant/_services/dias-main.control-service.spec.ts +22 -22
  386. package/src/_modules/discord-assistant/_services/dias-main.control-service.ts +27 -27
  387. package/src/_modules/discord-assistant/_services/dias.service-base.spec.ts +195 -195
  388. package/src/_modules/discord-assistant/_services/dias.service-base.ts +76 -76
  389. package/src/_modules/discord-assistant/index.ts +38 -38
  390. package/src/_modules/discord-assistant-voiced/_services/dias-discord-bot.control-service.spec.ts +34 -34
  391. package/src/_modules/discord-assistant-voiced/_services/dias-discord-bot.control-service.ts +11 -11
  392. package/src/_modules/discord-assistant-voiced/index.ts +36 -36
  393. package/src/_modules/discord-bot/_collections/dibo-default-commands.const.ts +16 -16
  394. package/src/_modules/discord-bot/_collections/dibo-global-settings.conts.ts +55 -55
  395. package/src/_modules/discord-bot/_collections/dibo-operations.util.spec.ts +214 -214
  396. package/src/_modules/discord-bot/_collections/dibo-operations.util.ts +387 -387
  397. package/src/_modules/discord-bot/_models/dibo-command.interface.ts +12 -12
  398. package/src/_modules/discord-bot/_models/dibo-global-settings.interface.ts +98 -98
  399. package/src/_modules/discord-bot/_models/dibo-last-mention-date.inteface.ts +7 -7
  400. package/src/_modules/discord-bot/_models/dibo-last-message-date.interface.ts +6 -6
  401. package/src/_modules/discord-bot/_services/dibo-commands.control-service.spec.ts +154 -154
  402. package/src/_modules/discord-bot/_services/dibo-commands.control-service.ts +153 -153
  403. package/src/_modules/discord-bot/_services/dibo-io.control-service.spec.ts +264 -264
  404. package/src/_modules/discord-bot/_services/dibo-io.control-service.ts +306 -306
  405. package/src/_modules/discord-bot/_services/dibo-main.control-service.spec.ts +408 -408
  406. package/src/_modules/discord-bot/_services/dibo-main.control-service.ts +487 -487
  407. package/src/_modules/discord-bot/_services/dibo-routines.control-service.spec.ts +105 -105
  408. package/src/_modules/discord-bot/_services/dibo-routines.control-service.ts +97 -97
  409. package/src/_modules/discord-bot/index.ts +36 -36
  410. package/src/_modules/local-vector-search/_enums/lvs-search-mode.enum.ts +35 -35
  411. package/src/_modules/local-vector-search/_models/data-models/lvs-vector-persist.data-model.ts +60 -60
  412. package/src/_modules/local-vector-search/_models/lvs-search-result.interface.ts +17 -17
  413. package/src/_modules/local-vector-search/_services/lvs-bm25.util.spec.ts +159 -159
  414. package/src/_modules/local-vector-search/_services/lvs-bm25.util.ts +206 -206
  415. package/src/_modules/local-vector-search/_services/lvs-doc-chunk-data.service.spec.ts +418 -418
  416. package/src/_modules/local-vector-search/_services/lvs-doc-chunk-data.service.ts +276 -276
  417. package/src/_modules/local-vector-search/_services/lvs-local-vector-search.data-service.spec.ts +480 -480
  418. package/src/_modules/local-vector-search/_services/lvs-local-vector-search.data-service.ts +416 -416
  419. package/src/_modules/local-vector-search/_services/lvs-persistent-vector-pool.control-service.spec.ts +214 -214
  420. package/src/_modules/local-vector-search/_services/lvs-persistent-vector-pool.control-service.ts +186 -186
  421. package/src/_modules/local-vector-search/_services/lvs-vector-persist.data-service.spec.ts +167 -167
  422. package/src/_modules/local-vector-search/_services/lvs-vector-persist.data-service.ts +130 -130
  423. package/src/_modules/local-vector-search/_services/lvs-vector-pool.control-service.spec.ts +509 -509
  424. package/src/_modules/local-vector-search/_services/lvs-vector-pool.control-service.ts +323 -323
  425. package/src/_modules/local-vector-search/index.ts +16 -16
  426. package/src/_modules/logs/_models/file-log-entry.interface.ts +13 -13
  427. package/src/_modules/logs/_models/file-log-read-result.interface.ts +37 -37
  428. package/src/_modules/logs/file-log.service.spec.ts +341 -341
  429. package/src/_modules/logs/file-log.service.ts +466 -466
  430. package/src/_modules/logs/file-logs.controller.spec.ts +245 -245
  431. package/src/_modules/logs/file-logs.controller.ts +165 -165
  432. package/src/_modules/logs/get-file-logs-routing-module.util.ts +51 -51
  433. package/src/_modules/logs/get-logs-routing-module.util.ts +36 -36
  434. package/src/_modules/logs/index.ts +11 -11
  435. package/src/_modules/logs/log-buffer.service.ts +101 -101
  436. package/src/_modules/logs/logs.controller.ts +109 -109
  437. package/src/_modules/logs/logs.service.ts +100 -100
  438. package/src/_modules/mcp/_models/interfaces/dynts-mcp.interface.ts +111 -111
  439. package/src/_modules/mcp/_services/dynts-mcp-server.service-base.spec.ts +151 -151
  440. package/src/_modules/mcp/_services/dynts-mcp-server.service-base.ts +125 -125
  441. package/src/_modules/mcp/_services/dynts-mcp.adapter.ts +168 -168
  442. package/src/_modules/mcp/index.ts +13 -13
  443. package/src/_modules/messaging/README.md +354 -354
  444. package/src/_modules/messaging/_collections/get-messaging-routing-module.util.ts +26 -26
  445. package/src/_modules/messaging/_collections/msg-global-settings.const.ts +22 -22
  446. package/src/_modules/messaging/_collections/msg.util.spec.ts +226 -226
  447. package/src/_modules/messaging/_collections/msg.util.ts +83 -83
  448. package/src/_modules/messaging/_models/msg-global-settings.interface.ts +37 -37
  449. package/src/_modules/messaging/_services/msg-conversation.data-service.ts +146 -146
  450. package/src/_modules/messaging/_services/msg-events.service.spec.ts +219 -219
  451. package/src/_modules/messaging/_services/msg-events.service.ts +267 -267
  452. package/src/_modules/messaging/_services/msg-integration.control-service.ts +179 -179
  453. package/src/_modules/messaging/_services/msg-main.control-service.spec.ts +147 -147
  454. package/src/_modules/messaging/_services/msg-main.control-service.ts +571 -571
  455. package/src/_modules/messaging/_services/msg-message.data-service.ts +129 -129
  456. package/src/_modules/messaging/_services/msg.controller.spec.ts +201 -201
  457. package/src/_modules/messaging/_services/msg.controller.ts +370 -370
  458. package/src/_modules/messaging/index.ts +30 -30
  459. package/src/_modules/mock/app-extended-server.mock.ts +201 -201
  460. package/src/_modules/mock/app-integration-test.mock.ts +51 -51
  461. package/src/_modules/mock/app-params.mock.spec.ts +21 -21
  462. package/src/_modules/mock/app-params.mock.ts +9 -9
  463. package/src/_modules/mock/app-server.mock.ts +188 -188
  464. package/src/_modules/mock/auth-service.mock.spec.ts +47 -47
  465. package/src/_modules/mock/auth-service.mock.ts +28 -28
  466. package/src/_modules/mock/controller.mock.spec.ts +26 -26
  467. package/src/_modules/mock/controller.mock.ts +16 -16
  468. package/src/_modules/mock/data-model.mock.spec.ts +111 -111
  469. package/src/_modules/mock/data-model.mock.ts +82 -82
  470. package/src/_modules/mock/email-service-collection.mock.spec.ts +24 -24
  471. package/src/_modules/mock/email-service-collection.mock.ts +15 -15
  472. package/src/_modules/mock/email-service.mock.spec.ts +17 -17
  473. package/src/_modules/mock/email-service.mock.ts +20 -20
  474. package/src/_modules/mock/email-template.mock.html +14 -14
  475. package/src/_modules/mock/endpoint.mock.ts +91 -91
  476. package/src/_modules/mock/socket-client.mock.spec.ts +40 -40
  477. package/src/_modules/mock/socket-client.mock.ts +45 -45
  478. package/src/_modules/mock/socket-server.mock.spec.ts +44 -44
  479. package/src/_modules/mock/socket-server.mock.ts +46 -46
  480. package/src/_modules/oauth2/_routes/oauth2.controller.spec.ts +107 -107
  481. package/src/_modules/oauth2/_routes/oauth2.controller.ts +98 -98
  482. package/src/_modules/oauth2/_services/oauth2.auth-service.spec.ts +254 -254
  483. package/src/_modules/oauth2/_services/oauth2.auth-service.ts +232 -232
  484. package/src/_modules/oauth2/_services/oauth2.control-service.spec.ts +585 -585
  485. package/src/_modules/oauth2/_services/oauth2.control-service.ts +653 -653
  486. package/src/_modules/oauth2/index.ts +17 -17
  487. package/src/_modules/privacy-lifecycle/_enums/privacy-consent-decision.type-enum.ts +5 -5
  488. package/src/_modules/privacy-lifecycle/_enums/privacy-contributor-action.type-enum.ts +10 -10
  489. package/src/_modules/privacy-lifecycle/_enums/privacy-contributor-outcome.type-enum.ts +7 -7
  490. package/src/_modules/privacy-lifecycle/_enums/privacy-request-state.type-enum.ts +15 -15
  491. package/src/_modules/privacy-lifecycle/_enums/privacy-request.type-enum.ts +9 -9
  492. package/src/_modules/privacy-lifecycle/_models/privacy-consent-input.interface.ts +12 -12
  493. package/src/_modules/privacy-lifecycle/_models/privacy-consent-persistence-result.interface.ts +7 -7
  494. package/src/_modules/privacy-lifecycle/_models/privacy-consent-record.interface.ts +15 -15
  495. package/src/_modules/privacy-lifecycle/_models/privacy-consent-result.interface.ts +7 -7
  496. package/src/_modules/privacy-lifecycle/_models/privacy-consent-view.interface.ts +13 -13
  497. package/src/_modules/privacy-lifecycle/_models/privacy-contributor-context.interface.ts +9 -9
  498. package/src/_modules/privacy-lifecycle/_models/privacy-contributor-outcome.interface.ts +14 -14
  499. package/src/_modules/privacy-lifecycle/_models/privacy-contributor-plan.interface.ts +8 -8
  500. package/src/_modules/privacy-lifecycle/_models/privacy-contributor.interface.ts +17 -17
  501. package/src/_modules/privacy-lifecycle/_models/privacy-ledger-adapter.interface.ts +21 -21
  502. package/src/_modules/privacy-lifecycle/_models/privacy-ledger-result.interface.ts +9 -9
  503. package/src/_modules/privacy-lifecycle/_models/privacy-ledger-settings.interface.ts +7 -7
  504. package/src/_modules/privacy-lifecycle/_models/privacy-legal-acceptance-input.interface.ts +10 -10
  505. package/src/_modules/privacy-lifecycle/_models/privacy-legal-acceptance-persistence-result.interface.ts +7 -7
  506. package/src/_modules/privacy-lifecycle/_models/privacy-legal-acceptance-result.interface.ts +7 -7
  507. package/src/_modules/privacy-lifecycle/_models/privacy-legal-acceptance-view.interface.ts +11 -11
  508. package/src/_modules/privacy-lifecycle/_models/privacy-legal-acceptance.interface.ts +13 -13
  509. package/src/_modules/privacy-lifecycle/_models/privacy-lifecycle-adapter.interface.ts +19 -19
  510. package/src/_modules/privacy-lifecycle/_models/privacy-lifecycle-settings.interface.ts +9 -9
  511. package/src/_modules/privacy-lifecycle/_models/privacy-request-create-result.interface.ts +7 -7
  512. package/src/_modules/privacy-lifecycle/_models/privacy-request-open.interface.ts +10 -10
  513. package/src/_modules/privacy-lifecycle/_models/privacy-request-persistence-create-result.interface.ts +7 -7
  514. package/src/_modules/privacy-lifecycle/_models/privacy-request-record.interface.ts +21 -21
  515. package/src/_modules/privacy-lifecycle/_models/privacy-request-result.interface.ts +8 -8
  516. package/src/_modules/privacy-lifecycle/_models/privacy-request-view.interface.ts +20 -20
  517. package/src/_modules/privacy-lifecycle/index.ts +40 -40
  518. package/src/_modules/privacy-lifecycle/privacy-ledger.control-service.spec.ts +206 -206
  519. package/src/_modules/privacy-lifecycle/privacy-ledger.control-service.ts +253 -253
  520. package/src/_modules/privacy-lifecycle/privacy-lifecycle.control-service.spec.ts +353 -353
  521. package/src/_modules/privacy-lifecycle/privacy-lifecycle.control-service.ts +586 -586
  522. package/src/_modules/rate-limit/_enums/rate-limit-store-kind.type-enum.ts +5 -5
  523. package/src/_modules/rate-limit/_models/rate-limit-config.interface.ts +82 -82
  524. package/src/_modules/rate-limit/_models/rate-limit-consume-request.interface.ts +9 -9
  525. package/src/_modules/rate-limit/_models/rate-limit-consume-result.interface.ts +6 -6
  526. package/src/_modules/rate-limit/_models/rate-limit-policy.interface.ts +16 -16
  527. package/src/_modules/rate-limit/_models/rate-limit-store.interface.ts +9 -9
  528. package/src/_modules/rate-limit/index.ts +8 -8
  529. package/src/_modules/rate-limit/rate-limit-in-memory.store.ts +91 -91
  530. package/src/_modules/rate-limit/rate-limit.middleware.spec.ts +488 -488
  531. package/src/_modules/rate-limit/rate-limit.middleware.ts +504 -504
  532. package/src/_modules/scheduler/_models/scheduler-job.interface.ts +35 -35
  533. package/src/_modules/scheduler/get-scheduler-routing-module.util.ts +33 -33
  534. package/src/_modules/scheduler/index.ts +8 -8
  535. package/src/_modules/scheduler/scheduler.controller.spec.ts +42 -42
  536. package/src/_modules/scheduler/scheduler.controller.ts +69 -69
  537. package/src/_modules/scheduler/scheduler.service.spec.ts +141 -141
  538. package/src/_modules/scheduler/scheduler.service.ts +176 -176
  539. package/src/_modules/scoped-config/_enums/dynts-scoped-config-level.enum.ts +22 -22
  540. package/src/_modules/scoped-config/_models/data-models/dynts-scoped-config.data-model.ts +82 -82
  541. package/src/_modules/scoped-config/_models/interfaces/dynts-scoped-config.interface.ts +107 -107
  542. package/src/_modules/scoped-config/_services/dynts-scoped-config.control-service.spec.ts +312 -312
  543. package/src/_modules/scoped-config/_services/dynts-scoped-config.control-service.ts +311 -311
  544. package/src/_modules/scoped-config/_services/dynts-scoped-config.data-service.spec.ts +123 -123
  545. package/src/_modules/scoped-config/_services/dynts-scoped-config.data-service.ts +108 -108
  546. package/src/_modules/scoped-config/index.ts +17 -17
  547. package/src/_modules/server/errors/errors.control-service.spec.ts +246 -246
  548. package/src/_modules/server/errors/errors.control-service.ts +100 -100
  549. package/src/_modules/server/errors/errors.controller.spec.ts +340 -340
  550. package/src/_modules/server/errors/errors.controller.ts +559 -559
  551. package/src/_modules/server/errors/errors.data-service.spec.ts +480 -480
  552. package/src/_modules/server/errors/errors.data-service.ts +867 -867
  553. package/src/_modules/server/index.ts +37 -27
  554. package/src/_modules/server/safe-diagnostic/safe-diagnostic-cause.type-enum.ts +8 -0
  555. package/src/_modules/server/safe-diagnostic/safe-diagnostic-stage.type-enum.ts +19 -0
  556. package/src/_modules/server/safe-diagnostic/safe-diagnostic.control-service.spec.ts +124 -0
  557. package/src/_modules/server/safe-diagnostic/safe-diagnostic.control-service.ts +99 -0
  558. package/src/_modules/server/safe-diagnostic/safe-diagnostic.interface.ts +20 -0
  559. package/src/_modules/server/server-status/db-readiness-probe-code.type-enum.ts +13 -0
  560. package/src/_modules/server/server-status/db-readiness-probe-stage.type-enum.ts +7 -0
  561. package/src/_modules/server/server-status/db-readiness-probe.control-service.spec.ts +235 -0
  562. package/src/_modules/server/server-status/db-readiness-probe.control-service.ts +158 -0
  563. package/src/_modules/server/server-status/db-readiness-probe.interface.ts +20 -0
  564. package/src/_modules/server/server-status/server-status-snapshot.control-service.spec.ts +70 -70
  565. package/src/_modules/server/server-status/server-status-snapshot.control-service.ts +17 -17
  566. package/src/_modules/server/server-status/server-status-snapshot.data-service.spec.ts +77 -77
  567. package/src/_modules/server/server-status/server-status-snapshot.data-service.ts +37 -37
  568. package/src/_modules/server/server-status/server-status.control-service.spec.ts +672 -672
  569. package/src/_modules/server/server-status/server-status.control-service.ts +490 -490
  570. package/src/_modules/server/server-status/server-status.controller.spec.ts +276 -276
  571. package/src/_modules/server/server-status/server-status.controller.ts +336 -336
  572. package/src/_modules/socket/_enums/socket-security.enum.ts +11 -11
  573. package/src/_modules/socket/_models/socket-client-service-params.control-model.spec.ts +32 -32
  574. package/src/_modules/socket/_models/socket-client-service-params.control-model.ts +22 -22
  575. package/src/_modules/socket/_models/socket-presence.control-model.spec.ts +165 -165
  576. package/src/_modules/socket/_models/socket-presence.control-model.ts +211 -211
  577. package/src/_modules/socket/_models/socket-server-service-params.control-model.spec.ts +69 -69
  578. package/src/_modules/socket/_models/socket-server-service-params.control-model.ts +33 -33
  579. package/src/_modules/socket/_services/socket-client.service.spec.ts +15 -15
  580. package/src/_modules/socket/_services/socket-client.service.ts +260 -260
  581. package/src/_modules/socket/_services/socket-server.service.spec.ts +272 -272
  582. package/src/_modules/socket/_services/socket-server.service.ts +1037 -1037
  583. package/src/_modules/socket/app-extended.integration.spec.ts +85 -85
  584. package/src/_modules/socket/app-extended.server.ts +648 -648
  585. package/src/_modules/socket/index.ts +42 -42
  586. package/src/_modules/test/get-test-routing-module.util.spec.ts +28 -28
  587. package/src/_modules/test/get-test-routing-module.util.ts +23 -23
  588. package/src/_modules/test/index.ts +11 -11
  589. package/src/_modules/test/test.controller.spec.ts +72 -72
  590. package/src/_modules/test/test.controller.ts +115 -115
  591. package/src/_modules/test-email-sink/_collections/test-email-pattern.const.ts +10 -10
  592. package/src/_modules/test-email-sink/_models/data-models/dynts-sent-test-mail.data-model.ts +41 -41
  593. package/src/_modules/test-email-sink/_services/dynts-test-email-sink.service.spec.ts +112 -112
  594. package/src/_modules/test-email-sink/_services/dynts-test-email-sink.service.ts +141 -141
  595. package/src/_modules/test-email-sink/get-sent-mail-routing-module.util.ts +29 -29
  596. package/src/_modules/test-email-sink/index.ts +11 -11
  597. package/src/_modules/test-email-sink/test-email-sink.controller.ts +83 -83
  598. package/src/_modules/usage/get-usage-routing-module.util.ts +22 -22
  599. package/src/_modules/usage/index.ts +15 -15
  600. package/src/_modules/usage/usage.controller.spec.ts +106 -106
  601. package/src/_modules/usage/usage.controller.ts +140 -140
  602. package/src/_modules/usage/usage.data-service.spec.ts +332 -332
  603. package/src/_modules/usage/usage.data-service.ts +185 -185
  604. package/src/_services/base/api.service-base.spec.ts +125 -125
  605. package/src/_services/base/api.service-base.ts +74 -74
  606. package/src/_services/base/archive-data.service.spec.ts +209 -209
  607. package/src/_services/base/archive-data.service.ts +228 -228
  608. package/src/_services/base/data.service.spec.ts +784 -784
  609. package/src/_services/base/data.service.ts +2792 -2792
  610. package/src/_services/base/db.service.encryption.spec.ts +76 -76
  611. package/src/_services/base/db.service.spec.ts +160 -160
  612. package/src/_services/base/db.service.ts +1698 -1698
  613. package/src/_services/base/singleton.service-base.spec.ts +28 -28
  614. package/src/_services/base/singleton.service-base.ts +24 -24
  615. package/src/_services/base/singleton.service.spec.ts +114 -114
  616. package/src/_services/base/singleton.service.ts +38 -38
  617. package/src/_services/core/api.service.spec.ts +187 -187
  618. package/src/_services/core/api.service.ts +627 -627
  619. package/src/_services/core/auth.service.spec.ts +159 -159
  620. package/src/_services/core/auth.service.ts +174 -174
  621. package/src/_services/core/collection-growth-monitor.service.spec.ts +119 -119
  622. package/src/_services/core/collection-growth-monitor.service.ts +234 -234
  623. package/src/_services/core/db-stats.service.ts +104 -104
  624. package/src/_services/core/diagnostics.service.spec.ts +44 -44
  625. package/src/_services/core/diagnostics.service.ts +158 -158
  626. package/src/_services/core/email.service.spec.ts +85 -85
  627. package/src/_services/core/email.service.ts +757 -757
  628. package/src/_services/core/event-loop-diag.service.spec.ts +22 -22
  629. package/src/_services/core/event-loop-diag.service.ts +144 -144
  630. package/src/_services/core/global.service.spec.ts +292 -292
  631. package/src/_services/core/global.service.ts +466 -465
  632. package/src/_services/core/memory-guard.service.spec.ts +245 -245
  633. package/src/_services/core/memory-guard.service.ts +481 -481
  634. package/src/_services/core/migration-runner.service.spec.ts +91 -91
  635. package/src/_services/core/migration-runner.service.ts +106 -106
  636. package/src/_services/core/mongo-transaction.control-service.spec.ts +165 -165
  637. package/src/_services/core/mongo-transaction.control-service.ts +148 -148
  638. package/src/_services/core/request-hunter.service.spec.ts +124 -124
  639. package/src/_services/core/request-hunter.service.ts +157 -157
  640. package/src/_services/core/service-collection.service.spec.ts +46 -46
  641. package/src/_services/core/service-collection.service.ts +6 -6
  642. package/src/_services/route/controller.service.spec.ts +53 -53
  643. package/src/_services/route/controller.service.ts +148 -148
  644. package/src/_services/route/routing-module.service.spec.ts +98 -98
  645. package/src/_services/route/routing-module.service.ts +330 -330
  646. package/src/_services/server/app-safe-diagnostic.spec.ts +124 -0
  647. package/src/_services/server/app.server-retention.spec.ts +106 -106
  648. package/src/_services/server/app.server.ts +1865 -1918
  649. package/src/_services/shared.static-service.spec.ts +99 -99
  650. package/src/_services/shared.static-service.ts +78 -78
  651. package/src/index.ts +117 -117
  652. package/tsconfig.app.json +12 -12
  653. package/tsconfig.json +42 -42
  654. package/.dynamo/logs/cicd-pipeline/output.log +0 -2883
  655. package/.dynamo/logs/cicd-pipeline/status.json +0 -74
@@ -1,2012 +1,1959 @@
1
-
2
- import Mongoose = require('mongoose');
3
- import Express = require('express');
4
- /* import Mongoose from 'mongoose';
5
- import Express from 'express'; */
6
-
7
- import * as BodyParser from 'body-parser';
8
- import * as FileSystem from 'fs';
9
- import * as Http from 'http';
10
- import * as Https from 'https';
11
- import * as Path from 'path';
12
- import * as dotenv from 'dotenv'
13
-
14
- /* import { version } from '../../../package.json'; */
15
-
16
- import {
17
- DyFM_AnyError,
18
- DyFM_Array,
19
- DyFM_Async,
20
- DyFM_Error,
21
- DyFM_error_defaults,
22
- DyFM_Error_Settings,
23
- DyFM_ErrorLevel,
24
- DyFM_Log,
25
- DyFM_resolveRetentionTtlSeconds,
26
- megabyte,
27
- second
28
- } from '@futdevpro/fsm-dynamo';
29
-
30
- import { DyNTS_defaultFallbackCacheMaxAge } from '../../_collections/default-fallback-cache-max-age.const';
31
- import { DyNTS_defaultNotFoundPageHtml } from '../../_collections/default-not-found-page.const';
32
- import { DyNTS_global_settings } from '../../_collections/global-settings.const';
33
- import { DyNTS_ClientSafeError_Util } from '../../_collections/client-safe-error.util';
34
- import { DyNTS_getEnvironment_settings } from '../../_collections/get-environment-settings.util';
35
- import { DyNTS_createSecurityHeadersMiddleware } from '../../_collections/security-headers.util';
36
- import { DyNTS_createLoadShedMiddleware } from '../../_collections/load-shed.util';
37
- import { DyNTS_createAppVersionHeaderMiddleware } from '../../_collections/app-version-header.util';
38
- import { DyNTS_AppVersionHeader_Settings } from '../../_models/interfaces/app-version-header-settings.interface';
39
- import { DyNTS_SecurityHeaders_Settings } from '../../_models/interfaces/security-headers-settings.interface';
40
- import { startMongoReconnectGuard } from '../../_collections/mongo-reconnect-guard.util';
41
- import { DyNTS_resolveStaticCacheControlHeader } from '../../_collections/static-cache-control.util';
42
- import { DyNTS_RouteSecurity } from '../../_enums/route-security.enum';
43
- import { DyNTS_App_Params } from '../../_models/control-models/app-params.control-model';
44
- import {
45
- DyNTS_AppSystemControls
46
- } from '../../_models/control-models/app-system-controls.control-model';
47
- import {
48
- DyNTS_Endpoint_Params
49
- } from '../../_models/control-models/endpoint-params.control-model';
50
- import { DyNTS_Http_Settings } from '../../_models/control-models/http-settings.control-model';
51
- import {
52
- DyNTS_Certification_Settings
53
- } from '../../_models/interfaces/certification-settings.interface';
54
- import {
55
- DyNTS_GlobalService_Settings
56
- } from '../../_models/interfaces/global-service-settings.interface';
57
- import {
58
- DyNTS_StaticClient_Settings
59
- } from '../../_models/interfaces/static-client-settings.interface';
60
- import {
61
- DyNTS_Cors_Settings
62
- } from '../../_models/interfaces/cors-settings.interface';
63
- import { DyNTS_DBService } from '../base/db.service';
64
- import { DyNTS_SingletonService } from '../base/singleton.service';
65
- import { DyNTS_GlobalService } from '../core/global.service';
66
- import { DyNTS_CollectionGrowthMonitor } from '../core/collection-growth-monitor.service';
67
- import { DyNTS_MemoryGuard } from '../core/memory-guard.service';
68
- import { DyNTS_EventLoopDiag } from '../core/event-loop-diag.service';
1
+
2
+ import Mongoose = require('mongoose');
3
+ import Express = require('express');
4
+ /* import Mongoose from 'mongoose';
5
+ import Express from 'express'; */
6
+
7
+ import * as BodyParser from 'body-parser';
8
+ import * as FileSystem from 'fs';
9
+ import * as Http from 'http';
10
+ import * as Https from 'https';
11
+ import * as Path from 'path';
12
+ import * as dotenv from 'dotenv'
13
+
14
+ /* import { version } from '../../../package.json'; */
15
+
16
+ import {
17
+ DyFM_AnyError,
18
+ DyFM_Array,
19
+ DyFM_Async,
20
+ DyFM_Error,
21
+ DyFM_error_defaults,
22
+ DyFM_Error_Settings,
23
+ DyFM_ErrorLevel,
24
+ DyFM_Log,
25
+ DyFM_resolveRetentionTtlSeconds,
26
+ megabyte,
27
+ second
28
+ } from '@futdevpro/fsm-dynamo';
29
+
30
+ import { DyNTS_defaultFallbackCacheMaxAge } from '../../_collections/default-fallback-cache-max-age.const';
31
+ import { DyNTS_defaultNotFoundPageHtml } from '../../_collections/default-not-found-page.const';
32
+ import { DyNTS_global_settings } from '../../_collections/global-settings.const';
33
+ import { DyNTS_ClientSafeError_Util } from '../../_collections/client-safe-error.util';
34
+ import { DyNTS_getEnvironment_settings } from '../../_collections/get-environment-settings.util';
35
+ import { DyNTS_createSecurityHeadersMiddleware } from '../../_collections/security-headers.util';
36
+ import { DyNTS_createLoadShedMiddleware } from '../../_collections/load-shed.util';
37
+ import { DyNTS_createAppVersionHeaderMiddleware } from '../../_collections/app-version-header.util';
38
+ import { DyNTS_AppVersionHeader_Settings } from '../../_models/interfaces/app-version-header-settings.interface';
39
+ import { DyNTS_SecurityHeaders_Settings } from '../../_models/interfaces/security-headers-settings.interface';
40
+ import { startMongoReconnectGuard } from '../../_collections/mongo-reconnect-guard.util';
41
+ import { DyNTS_resolveStaticCacheControlHeader } from '../../_collections/static-cache-control.util';
42
+ import { DyNTS_RouteSecurity } from '../../_enums/route-security.enum';
43
+ import { DyNTS_App_Params } from '../../_models/control-models/app-params.control-model';
44
+ import {
45
+ DyNTS_AppSystemControls
46
+ } from '../../_models/control-models/app-system-controls.control-model';
47
+ import {
48
+ DyNTS_Endpoint_Params
49
+ } from '../../_models/control-models/endpoint-params.control-model';
50
+ import { DyNTS_Http_Settings } from '../../_models/control-models/http-settings.control-model';
51
+ import {
52
+ DyNTS_Certification_Settings
53
+ } from '../../_models/interfaces/certification-settings.interface';
54
+ import {
55
+ DyNTS_GlobalService_Settings
56
+ } from '../../_models/interfaces/global-service-settings.interface';
57
+ import {
58
+ DyNTS_StaticClient_Settings
59
+ } from '../../_models/interfaces/static-client-settings.interface';
60
+ import {
61
+ DyNTS_Cors_Settings
62
+ } from '../../_models/interfaces/cors-settings.interface';
63
+ import { DyNTS_DBService } from '../base/db.service';
64
+ import { DyNTS_SingletonService } from '../base/singleton.service';
65
+ import { DyNTS_GlobalService } from '../core/global.service';
66
+ import { DyNTS_CollectionGrowthMonitor } from '../core/collection-growth-monitor.service';
67
+ import { DyNTS_MemoryGuard } from '../core/memory-guard.service';
68
+ import { DyNTS_EventLoopDiag } from '../core/event-loop-diag.service';
69
69
  import { DyNTS_RoutingModule } from '../route/routing-module.service';
70
70
  import { DyNTS_getStarRoute } from '../../_collections/star.controller';
71
-
72
- /**
73
- *
74
- * function MyDecorator(config: any) {
75
- return function (target: Function) {
76
- // attach metadata or modify target
77
- target.prototype.myMeta = config;
78
- };
79
- }
80
-
81
- @MyDecorator({ role: 'admin' })
82
- class User {
83
- printRole() {
84
- console.log((this as any).myMeta.role); // → "admin"
85
- }
86
- }
87
-
88
- */
89
-
90
- /**
91
- * This will be the MAIN service of our server project,
92
- * follow the types and type instructions while setting up your project
93
- *
94
- * In this service, there are abstract functions that you will need to implement,
95
- * where you need to set up the main params for your application.
96
- *
97
- * (after the example, you can find the list of services you can/should setup)
98
- *
99
- * @example
100
- * export class App extends DyNTS_AppExtended {
101
- *
102
- * ...
103
- *
104
- * // Setting up App params, and preparing project global settings
105
- * setupAppParams(): void {
106
- * this.params = new DyNTS_AppParams({
107
- * name: 'Warbots Server',
108
- * title: warbotsTitleLog,
109
- * version: version,
110
- * dbName: 'warbots',
111
- * });
112
- *
113
- * // dynamoNTS_GlobalSettings.logRequestsContent = false;
114
- * }
115
- *
116
- * ...
117
- *
118
- * // Setting up DBServices
119
- * setGlobalServiceCollection(): void {
120
- * DyNTS_GlobalService.setServices({
121
- * authService: AuthService.getInstance(),
122
- * emailServiceCollection: EmailServiceCollectionService.getInstance(),
123
- * dbModels: [
124
- * userModelParams,
125
- * userDataModelParams,
126
- * userOptionsModelParams,
127
- * userStatisticsModelParams,
128
- * userAchievementsModelParams,
129
- * userNotificationsModelParams,
130
- *
131
- * matchStatisticsModelParams,
132
- * matchDataModelParams,
133
-
134
- * DyFM_usageSession_dataParams,
135
- * DyFM_customData_dataParams,
136
- * ]
137
- * });
138
- * }
139
- *
140
- * ...
141
- *
142
- * // Setting up Routes
143
- * setupRoutingModules(): void {
144
- * this.httpPort = env.port;
145
-
146
- * this.routingModules = [
147
- * new DyNTS_RoutingModule({
148
- * route: '/user',
149
- * controllers: [
150
- * UserController.getInstance(),
151
- * UserDataController.getInstance(),
152
- * UserOptionsController.getInstance(),
153
- * UserStatisticsController.getInstance(),
154
- * UserAchievementsController.getInstance(),
155
- * UserNotificationsController.getInstance()
156
- * ]
157
- * }),
158
- * new DyNTS_RoutingModule({
159
- * route: '/match',
160
- * controllers: [
161
- * MatchController.getInstance(),
162
- * MatchDistributionController.getInstance(),
163
- * MatchStatisticsController.getInstance(),
164
- * ]
165
- * }),
166
- * new DyNTS_RoutingModule({
167
- * route: '/server',
168
- * controllers: [
169
- * ServerController.getInstance(),
170
- * ]
171
- * }),
172
-
173
- * getTestRoutingModule(),
174
- * getUsageRoutingModule()
175
- * ];
176
- * }
177
- * }
178
- *
179
- * //
180
- * // The Services available
181
- * //
182
- * // Authentication Service
183
- * // A commonly used basic service,
184
- * // which is necessary fur certain functions (such as registering call issuers)
185
- * //
186
- * // This will handle Authentication Token checking/refreshing,
187
- * // checking issuer's identifier and routeParams,
188
- * // handling JWT Token, or maybe with OAuth2 or other commonly used security procedures
189
- * //
190
- * // You can create one with this Dynamo Object:
191
- * //
192
- *
193
- * @example
194
- * // follow the instructions on the abstract class (DyNTS_AuthService)
195
- * export class AuthService extends DyNTS_AuthService {}
196
- *
197
- *
198
- *
199
- * //
200
- */
201
-
202
- /**
203
- * This will be the MAIN service of our server project,
204
- * follow the types and type instructions while setting up your project
205
- *
206
- * In this service, there are abstract functions that you will need to implement,
207
- * where you need to set up the main params for your application.
208
- *
209
- * (after the example, you can find the list of services you can/should setup)
210
- *
211
- * You need to setup the following functions:
212
- * ```ts
213
- * // this is where you set up the main params for your application
214
- * getAppParams(): DyNTS_AppParams
215
- *
216
- * // this is where you connect your main services
217
- * getGlobalServiceSettings(): DyNTS_GlobalService_Settings
218
- *
219
- * // this is where you set up your ports
220
- * getPorts(): DyNTS_PortSettings
221
- *
222
- * // this is where you set up your routes
223
- * getRoutingModules(): DyNTS_RoutingModule[]
224
- *
225
- *
226
- *
227
- * ```
228
- * optionally you can setup the following functions:
229
- * ```ts
230
- * // this is where you set up your certifications
231
- * getCertificationSettings(): DyNTS_CertificationSettings
232
- *
233
- * // this is where you set up additional root services
234
- * getRootServices(): DyNTS_SingletonService[]
235
- *
236
- * // this is where you set up your initial db entries
237
- * createEntries(): void
238
- *
239
- * // this is where you can define post setup processes
240
- * postProcess(): void
241
- *
242
- *
243
- *
244
- * ```
245
- *
246
- */
247
-
248
- /** FR-258 / SR-2 — one entry from `collection.indexes()` (only the fields the TTL-installer reads). */
249
- export interface DyNTS_TtlIndexInfo {
250
- name?: string;
251
- key?: Record<string, number>;
252
- expireAfterSeconds?: number;
253
- }
254
-
255
- /**
256
- * FR-258 / SR-2 — the minimal native-driver collection surface the TTL-installer needs. Declared
257
- * structurally (not importing mongodb types) so it stays dependency-light and is trivially mockable
258
- * in unit tests.
259
- */
260
- export interface DyNTS_TtlIndexCollection {
261
- indexes?: () => Promise<DyNTS_TtlIndexInfo[]>;
262
- createIndex: (keys: Record<string, number>, options: { expireAfterSeconds: number }) => Promise<unknown>;
263
- dropIndex?: (name: string) => Promise<unknown>;
264
- }
265
-
266
- /**
267
- * FR-258 / SR-2 outcome of {@link DyNTS_App.ensureRetentionTtlIndex}.
268
- * - `created`: no `__created` TTL index existed → one was created.
269
- * - `noop`: an index with the SAME TTL already existed → nothing done.
270
- * - `differs`: an index exists with a DIFFERENT TTL (or a non-TTL `__created` index) → left UNTOUCHED,
271
- * only a warning is emitted. We deliberately DO NOT drop+recreate at boot: rebuilding a TTL index on a
272
- * multi-GB production collection is a heavy server-side op that can starve concurrent boot queries (e.g.
273
- * the health-probe) and trip a fail-safe deploy revert. A deliberate retention CHANGE must be applied via
274
- * maintenance, not silently at every startup.
275
- */
276
- export type DyNTS_TtlIndexAction = 'created' | 'differs' | 'noop';
277
-
278
- export abstract class DyNTS_App extends DyNTS_SingletonService {
279
-
280
- protected systemControls: DyNTS_AppSystemControls = new DyNTS_AppSystemControls();
281
- get started(): boolean {
282
- return this.systemControls.app.started;
283
- }
284
- protected get superStarted(): boolean {
285
- return this.systemControls.app.started;
286
- }
287
- protected constructErrors: (Error | DyFM_Error)[] = [];
288
-
289
- /* removed since cant use version from package.json
290
- private readonly _ntsVersion: string = 'v01.07.18';
291
- protected get ntsVersion(): string {
292
- return this._ntsVersion;
293
- } */
294
-
295
- get serverName(): string {
296
- return this.params.name;
297
- }
298
-
299
- private _params: DyNTS_App_Params;
300
- protected get params(): DyNTS_App_Params {
301
- return this._params;
302
- }
303
-
304
- protected mongoose = Mongoose;
305
-
306
- private _security: DyNTS_RouteSecurity;
307
- protected get security(): DyNTS_RouteSecurity {
308
- return this._security;
309
- }
310
-
311
- protected _portSettings: DyNTS_Http_Settings = new DyNTS_Http_Settings();
312
- protected get portSettings(): DyNTS_Http_Settings {
313
- return this._portSettings;
71
+ import { DyNTS_SafeDiagnosticStage_Type } from '../../_modules/server/safe-diagnostic/safe-diagnostic-stage.type-enum';
72
+ import { DyNTS_SafeDiagnostic_Interface } from '../../_modules/server/safe-diagnostic/safe-diagnostic.interface';
73
+ import {
74
+ DyNTS_SafeDiagnostic_ControlService
75
+ } from '../../_modules/server/safe-diagnostic/safe-diagnostic.control-service';
76
+
77
+ /**
78
+ *
79
+ * function MyDecorator(config: any) {
80
+ return function (target: Function) {
81
+ // attach metadata or modify target
82
+ target.prototype.myMeta = config;
83
+ };
84
+ }
85
+
86
+ @MyDecorator({ role: 'admin' })
87
+ class User {
88
+ printRole() {
89
+ console.log((this as any).myMeta.role); // → "admin"
90
+ }
91
+ }
92
+
93
+ */
94
+
95
+ /**
96
+ * This will be the MAIN service of our server project,
97
+ * follow the types and type instructions while setting up your project
98
+ *
99
+ * In this service, there are abstract functions that you will need to implement,
100
+ * where you need to set up the main params for your application.
101
+ *
102
+ * (after the example, you can find the list of services you can/should setup)
103
+ *
104
+ * @example
105
+ * export class App extends DyNTS_AppExtended {
106
+ *
107
+ * ...
108
+ *
109
+ * // Setting up App params, and preparing project global settings
110
+ * setupAppParams(): void {
111
+ * this.params = new DyNTS_AppParams({
112
+ * name: 'Warbots Server',
113
+ * title: warbotsTitleLog,
114
+ * version: version,
115
+ * dbName: 'warbots',
116
+ * });
117
+ *
118
+ * // dynamoNTS_GlobalSettings.logRequestsContent = false;
119
+ * }
120
+ *
121
+ * ...
122
+ *
123
+ * // Setting up DBServices
124
+ * setGlobalServiceCollection(): void {
125
+ * DyNTS_GlobalService.setServices({
126
+ * authService: AuthService.getInstance(),
127
+ * emailServiceCollection: EmailServiceCollectionService.getInstance(),
128
+ * dbModels: [
129
+ * userModelParams,
130
+ * userDataModelParams,
131
+ * userOptionsModelParams,
132
+ * userStatisticsModelParams,
133
+ * userAchievementsModelParams,
134
+ * userNotificationsModelParams,
135
+ *
136
+ * matchStatisticsModelParams,
137
+ * matchDataModelParams,
138
+
139
+ * DyFM_usageSession_dataParams,
140
+ * DyFM_customData_dataParams,
141
+ * ]
142
+ * });
143
+ * }
144
+ *
145
+ * ...
146
+ *
147
+ * // Setting up Routes
148
+ * setupRoutingModules(): void {
149
+ * this.httpPort = env.port;
150
+
151
+ * this.routingModules = [
152
+ * new DyNTS_RoutingModule({
153
+ * route: '/user',
154
+ * controllers: [
155
+ * UserController.getInstance(),
156
+ * UserDataController.getInstance(),
157
+ * UserOptionsController.getInstance(),
158
+ * UserStatisticsController.getInstance(),
159
+ * UserAchievementsController.getInstance(),
160
+ * UserNotificationsController.getInstance()
161
+ * ]
162
+ * }),
163
+ * new DyNTS_RoutingModule({
164
+ * route: '/match',
165
+ * controllers: [
166
+ * MatchController.getInstance(),
167
+ * MatchDistributionController.getInstance(),
168
+ * MatchStatisticsController.getInstance(),
169
+ * ]
170
+ * }),
171
+ * new DyNTS_RoutingModule({
172
+ * route: '/server',
173
+ * controllers: [
174
+ * ServerController.getInstance(),
175
+ * ]
176
+ * }),
177
+
178
+ * getTestRoutingModule(),
179
+ * getUsageRoutingModule()
180
+ * ];
181
+ * }
182
+ * }
183
+ *
184
+ * //
185
+ * // The Services available
186
+ * //
187
+ * // Authentication Service
188
+ * // A commonly used basic service,
189
+ * // which is necessary fur certain functions (such as registering call issuers)
190
+ * //
191
+ * // This will handle Authentication Token checking/refreshing,
192
+ * // checking issuer's identifier and routeParams,
193
+ * // handling JWT Token, or maybe with OAuth2 or other commonly used security procedures
194
+ * //
195
+ * // You can create one with this Dynamo Object:
196
+ * //
197
+ *
198
+ * @example
199
+ * // follow the instructions on the abstract class (DyNTS_AuthService)
200
+ * export class AuthService extends DyNTS_AuthService {}
201
+ *
202
+ *
203
+ *
204
+ * //
205
+ */
206
+
207
+ /**
208
+ * This will be the MAIN service of our server project,
209
+ * follow the types and type instructions while setting up your project
210
+ *
211
+ * In this service, there are abstract functions that you will need to implement,
212
+ * where you need to set up the main params for your application.
213
+ *
214
+ * (after the example, you can find the list of services you can/should setup)
215
+ *
216
+ * You need to setup the following functions:
217
+ * ```ts
218
+ * // this is where you set up the main params for your application
219
+ * getAppParams(): DyNTS_AppParams
220
+ *
221
+ * // this is where you connect your main services
222
+ * getGlobalServiceSettings(): DyNTS_GlobalService_Settings
223
+ *
224
+ * // this is where you set up your ports
225
+ * getPorts(): DyNTS_PortSettings
226
+ *
227
+ * // this is where you set up your routes
228
+ * getRoutingModules(): DyNTS_RoutingModule[]
229
+ *
230
+ *
231
+ *
232
+ * ```
233
+ * optionally you can setup the following functions:
234
+ * ```ts
235
+ * // this is where you set up your certifications
236
+ * getCertificationSettings(): DyNTS_CertificationSettings
237
+ *
238
+ * // this is where you set up additional root services
239
+ * getRootServices(): DyNTS_SingletonService[]
240
+ *
241
+ * // this is where you set up your initial db entries
242
+ * createEntries(): void
243
+ *
244
+ * // this is where you can define post setup processes
245
+ * postProcess(): void
246
+ *
247
+ *
248
+ *
249
+ * ```
250
+ *
251
+ */
252
+
253
+ /** FR-258 / SR-2 — one entry from `collection.indexes()` (only the fields the TTL-installer reads). */
254
+ export interface DyNTS_TtlIndexInfo {
255
+ name?: string;
256
+ key?: Record<string, number>;
257
+ expireAfterSeconds?: number;
258
+ }
259
+
260
+ /**
261
+ * FR-258 / SR-2 — the minimal native-driver collection surface the TTL-installer needs. Declared
262
+ * structurally (not importing mongodb types) so it stays dependency-light and is trivially mockable
263
+ * in unit tests.
264
+ */
265
+ export interface DyNTS_TtlIndexCollection {
266
+ indexes?: () => Promise<DyNTS_TtlIndexInfo[]>;
267
+ createIndex: (keys: Record<string, number>, options: { expireAfterSeconds: number }) => Promise<unknown>;
268
+ dropIndex?: (name: string) => Promise<unknown>;
269
+ }
270
+
271
+ /**
272
+ * FR-258 / SR-2 outcome of {@link DyNTS_App.ensureRetentionTtlIndex}.
273
+ * - `created`: no `__created` TTL index existed one was created.
274
+ * - `noop`: an index with the SAME TTL already existed → nothing done.
275
+ * - `differs`: an index exists with a DIFFERENT TTL (or a non-TTL `__created` index) → left UNTOUCHED,
276
+ * only a warning is emitted. We deliberately DO NOT drop+recreate at boot: rebuilding a TTL index on a
277
+ * multi-GB production collection is a heavy server-side op that can starve concurrent boot queries (e.g.
278
+ * the health-probe) and trip a fail-safe deploy revert. A deliberate retention CHANGE must be applied via
279
+ * maintenance, not silently at every startup.
280
+ */
281
+ export type DyNTS_TtlIndexAction = 'created' | 'differs' | 'noop';
282
+
283
+ export abstract class DyNTS_App extends DyNTS_SingletonService {
284
+
285
+ protected systemControls: DyNTS_AppSystemControls = new DyNTS_AppSystemControls();
286
+ get started(): boolean {
287
+ return this.systemControls.app.started;
288
+ }
289
+ protected get superStarted(): boolean {
290
+ return this.systemControls.app.started;
291
+ }
292
+ protected constructErrors: (Error | DyFM_Error)[] = [];
293
+
294
+ /* removed since cant use version from package.json
295
+ private readonly _ntsVersion: string = 'v01.07.18';
296
+ protected get ntsVersion(): string {
297
+ return this._ntsVersion;
298
+ } */
299
+
300
+ get serverName(): string {
301
+ return this.params.name;
302
+ }
303
+
304
+ private _params: DyNTS_App_Params;
305
+ protected get params(): DyNTS_App_Params {
306
+ return this._params;
307
+ }
308
+
309
+ protected mongoose = Mongoose;
310
+
311
+ private _security: DyNTS_RouteSecurity;
312
+ protected get security(): DyNTS_RouteSecurity {
313
+ return this._security;
314
+ }
315
+
316
+ protected _portSettings: DyNTS_Http_Settings = new DyNTS_Http_Settings();
317
+ protected get portSettings(): DyNTS_Http_Settings {
318
+ return this._portSettings;
319
+ }
320
+
321
+ private _cert?: DyNTS_Certification_Settings;
322
+ protected get cert(): DyNTS_Certification_Settings {
323
+ return this._cert;
324
+ }
325
+
326
+ protected openExpress: Express.Application;
327
+ protected secureExpress: Express.Application;
328
+ protected httpsServer: Https.Server;
329
+ protected httpServer: Http.Server;
330
+
331
+ private globalService: DyNTS_GlobalService;
332
+ private _rootServices: DyNTS_SingletonService[] = [];
333
+
334
+ private _routingModules: DyNTS_RoutingModule[] = [];
335
+
336
+ protected readonly defaultReadyTimeout: number = 30 * second;
337
+
338
+ override readonly defaultErrorUserMsg =
339
+ `We encountered an unhandled Server Error, ` +
340
+ `\nplease contact the responsible development team.` +
341
+ `\n(Internal Server error)`;
342
+
343
+ get logSetup(): boolean {
344
+ return DyNTS_global_settings.log_settings.setup;
345
+ }
346
+ get deepLog(): boolean {
347
+ return DyNTS_global_settings.log_settings.deep;
348
+ }
349
+ get fnLogs(): boolean {
350
+ return DyNTS_global_settings.log_settings.functions;
314
351
  }
352
+ debugLog: boolean = DyNTS_global_settings.log_settings.server_debug;
315
353
 
316
- private _cert?: DyNTS_Certification_Settings;
317
- protected get cert(): DyNTS_Certification_Settings {
318
- return this._cert;
354
+ private reportSafeDiagnostic(
355
+ code: string,
356
+ stage: DyNTS_SafeDiagnosticStage_Type,
357
+ error?: unknown,
358
+ status: number = 500
359
+ ): DyNTS_SafeDiagnostic_Interface {
360
+ const configuredPrefix: string | undefined = DyNTS_global_settings.systemShortCodeName;
361
+ const prefix: string = configuredPrefix && /^[A-Z][A-Z0-9_-]{1,31}$/.test(configuredPrefix)
362
+ ? configuredPrefix
363
+ : 'DYNTS';
364
+
365
+ return DyNTS_SafeDiagnostic_ControlService.report({
366
+ code: `${prefix}|${code}`,
367
+ stage: stage,
368
+ error: error,
369
+ status: status,
370
+ });
319
371
  }
320
372
 
321
- protected openExpress: Express.Application;
322
- protected secureExpress: Express.Application;
323
- protected httpsServer: Https.Server;
324
- protected httpServer: Http.Server;
325
-
326
- private globalService: DyNTS_GlobalService;
327
- private _rootServices: DyNTS_SingletonService[] = [];
328
-
329
- private _routingModules: DyNTS_RoutingModule[] = [];
330
-
331
- protected readonly defaultReadyTimeout: number = 30 * second;
332
-
333
- override readonly defaultErrorUserMsg =
334
- `We encountered an unhandled Server Error, ` +
335
- `\nplease contact the responsible development team.` +
336
- `\n(Internal Server error)`;
373
+ private forwardSafeDiagnostic(diagnostic: DyNTS_SafeDiagnostic_Interface): void {
374
+ try {
375
+ const pending: Promise<void> | undefined = DyNTS_GlobalService.globalErrorHandler?.(
376
+ DyNTS_SafeDiagnostic_ControlService.toError(diagnostic)
377
+ );
337
378
 
338
- get logSetup(): boolean {
339
- return DyNTS_global_settings.log_settings.setup;
340
- }
341
- get deepLog(): boolean {
342
- return DyNTS_global_settings.log_settings.deep;
343
- }
344
- get fnLogs(): boolean {
345
- return DyNTS_global_settings.log_settings.functions;
379
+ void pending?.catch((error: unknown): void => {
380
+ this.reportSafeDiagnostic(
381
+ 'DYNTS-AS0-GLOBAL-HANDLER-REJECTED',
382
+ DyNTS_SafeDiagnosticStage_Type.globalErrorHandler,
383
+ error
384
+ );
385
+ });
386
+ } catch (error) {
387
+ this.reportSafeDiagnostic(
388
+ 'DYNTS-AS0-GLOBAL-HANDLER-THREW',
389
+ DyNTS_SafeDiagnosticStage_Type.globalErrorHandler,
390
+ error
391
+ );
392
+ }
346
393
  }
347
- debugLog: boolean = DyNTS_global_settings.log_settings.server_debug;
348
394
 
349
395
  constructor(/* extended?: boolean */){
350
- super();
351
-
352
- /* dotenv.config() */
353
-
396
+ super();
397
+
398
+ /* dotenv.config() */
399
+
354
400
  process.on(
355
401
  'unhandledRejection',
356
- (reason_theError: object, p_passWhatIsThis_maybeThePromise: any): void => {
357
- if (reason_theError instanceof DyFM_Error) {
358
- reason_theError.logSimple('Unhandled Rejection');
359
- } else {
360
- DyFM_Log.H_error(
361
- 'Unhandled Rejection:', (p_passWhatIsThis_maybeThePromise as Promise<any>)?.toString(),
362
- '\n Rejection reason:', (reason_theError as Error)?.stack?.split('at')?.[0],
363
- /* '\n ErrorCode:', (reason as any)?.code, */
364
- '\n\n Stack:',
365
- (reason_theError as Error)?.stack?.replaceAll?.('\n at', '\n at'),
366
- );
367
- }
368
-
369
- try {
370
- DyNTS_GlobalService.globalErrorHandler?.(
371
- new DyFM_Error({
372
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-BASE-UR`,
373
- message:
374
- `Unhandled Rejection!: "${(reason_theError as Error)?.stack?.split('at')?.[0]}"`,
375
- userMessage: this.defaultErrorUserMsg,
376
- addECToUserMsg: true,
377
- error: reason_theError as Error,
378
- additionalContent: {
379
- reason: reason_theError,
380
- rejectedPromise: p_passWhatIsThis_maybeThePromise,
381
- },
382
- systemVersion: DyNTS_global_settings.systemVersion,
383
- level: DyFM_ErrorLevel.critical,
384
- })
385
- );
386
- } catch (error) {
387
- DyFM_Log.error('globalErrorHandler (MULTILEVEL) ERROR:', error);
388
- }
389
- }
390
- );
391
-
392
- this.asyncConstruct(/* extended */).catch((error: any): void => {
393
- if (error instanceof DyFM_Error) {
394
- if (error.additionalContent?.constructErrors?.length) {
395
- error.additionalContent.constructErrors.forEach((errorItem: DyFM_Error): void => {
396
- DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', errorItem);
397
- /* if (errorItem instanceof DyFM_Error) {
398
- errorItem.logSimple(`(constructor asyncConstruct.catch) error:\n`);
399
- } else {
400
- DyFM_Log.H_warn(
401
- '(constructor asyncConstruct.catch) additional error content:\n',
402
- errorItem
403
- );
404
- } */
405
- });
406
- } else {
407
- DyFM_Log.H_warn(
408
- '(constructor asyncConstruct.catch) additional error content:\n',
409
- error?.additionalContent
410
- );
411
- }
412
- }
413
-
414
- DyFM_Error.logSimple('(constructor asyncConstruct.catch) error:', error);
415
- /* if (
416
- !DyNTS_global_settings.log_settings.highDetailedLogs &&
417
- (error instanceof DyFM_Error)
418
- ) {
419
- error.logSimple(
420
- `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)` +
421
- '\n all error messages (from this stack):\n\n"' +
422
- error._messages.join('"\n\n"') + '"\n\n'
402
+ (reason: unknown): void => {
403
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
404
+ 'DYNTS-AS0-BASE-UR',
405
+ DyNTS_SafeDiagnosticStage_Type.unhandledRejection,
406
+ reason
423
407
  );
424
- } else if (error instanceof DyFM_Error) {
425
- DyFM_Log.H_error(
426
- `Application: "${this.params?.name}" start failed. (constructor asyncConstruct.catch)`,
427
- `\n ERROR:`, error
428
- );
429
- } */
430
-
431
- const message: string =
432
- (error as DyFM_Error)?.additionalContent?.constructErrors?.flatMap(
433
- (errorItem: DyFM_Error): string[] => {
434
- return errorItem?._messages ?? [];
435
- }
436
- )?.join?.('\n') ??
437
- (error as DyFM_Error)?.errors?.flatMap(
438
- (errorItem: DyFM_AnyError): string[] =>
439
- (errorItem as DyFM_Error)?._messages ?? [ (errorItem as Error)?.message ]
440
- )?.join?.('\n') ??
441
- error?.message ??
442
- 'UNKNOWN';
443
-
444
- DyFM_Log.testError('Application start failed:\n', message);
445
-
446
- process.exit(1);
447
- });
448
- }
449
-
450
- protected async asyncConstruct(extended?: boolean): Promise<void> {
451
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. asyncConstruct');
452
-
453
- try {
454
- this.systemControls.app.init = true;
455
- this._params = this.getAppParams();
456
- DyFM_Log.log(
457
- `\n\n\n\n\n\n\n\n\n\n` +
458
- `Starting ${this._params?.name}... ` +
459
- /* `v${version}` + */
460
- `\n\n\n\n\n\n\n\n\n\n`
461
- );
462
-
463
- if (!this._params) {
464
- throw new Error('getAppParams() must return a DyNTS_AppParams object!');
465
- }
466
408
 
467
- if (this.params.systemShortCodeName) {
468
- DyNTS_global_settings.systemShortCodeName = this.params.systemShortCodeName;
469
- }
470
-
471
- if (this.params.systemName) {
472
- DyNTS_global_settings.systemName = this.params.systemName;
473
- DyFM_error_defaults.issuerSystem = this.params.systemName;
409
+ this.forwardSafeDiagnostic(diagnostic);
474
410
  }
411
+ );
475
412
 
476
- if (this.params.version) {
477
- DyNTS_global_settings.systemVersion = this.params.version;
478
- DyFM_error_defaults.systemVersion = this.params.version;
479
- }
480
-
481
- process.stdout.write(
482
- String.fromCharCode(27) + ']0;' +
483
- this._params?.name +
484
- String.fromCharCode(7)
413
+ this.asyncConstruct(/* extended */).catch((error: unknown): void => {
414
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
415
+ 'DYNTS-AS0-BOOTSTRAP-FAILED',
416
+ DyNTS_SafeDiagnosticStage_Type.bootstrap,
417
+ error
485
418
  );
486
419
 
487
- DyFM_error_defaults.issuerSystem = this._params.systemName;
488
-
489
- this.overrideDynamoNTSGlobalSettings?.();
420
+ this.forwardSafeDiagnostic(diagnostic);
490
421
 
491
- if (DyNTS_global_settings.log_settings.setup) {
492
- DyFM_Log.S_info(`env settings;\n`, {
493
- systemName: DyNTS_global_settings.systemName,
494
- systemShortCodeName: DyNTS_global_settings.systemShortCodeName,
495
- systemVersion: DyNTS_global_settings.systemVersion,
496
- environment: DyNTS_global_settings.env_settings.environment,
497
- /* log_settings: DyNTS_global_settings.log_settings,
498
- env_settings: DyNTS_global_settings.env_settings, */
499
- });
500
- }
501
-
502
- this.globalService = DyNTS_GlobalService.getInstance();
503
- await DyNTS_GlobalService.setServices(this.getGlobalServiceCollection());
504
- DyNTS_GlobalService.setParams(this.params);
505
-
506
- if (this.getPortSettings) {
507
- this._portSettings = this.getPortSettings();
508
- }
509
-
510
- if (this.getCertificationSettings) {
511
- this._cert = this.getCertificationSettings();
512
- }
513
-
514
- if (this.getApiBasePath) {
515
- DyNTS_global_settings.baseUrl = this.getApiBasePath();
516
- }
517
-
518
- if (this.getRoutingModules) {
519
- this._routingModules = this.getRoutingModules();
520
-
521
- // ezt egyelőre csak tesztelem, nem kerül be
522
- /* if (
523
- !DyNTS_global_settings.dontCreateDefaultRoute &&
524
- !this._routingModules.some((routingModule: DyNTS_RoutingModule): boolean => routingModule.route === '/*')
525
- ) {
526
- this._routingModules.push(
527
- DyNTS_getStarRoute()
422
+ process.exit(1);
423
+ });
424
+ }
425
+
426
+ protected async asyncConstruct(extended?: boolean): Promise<void> {
427
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. asyncConstruct');
428
+
429
+ try {
430
+ this.systemControls.app.init = true;
431
+ this._params = this.getAppParams();
432
+ DyFM_Log.log(
433
+ `\n\n\n\n\n\n\n\n\n\n` +
434
+ `Starting ${this._params?.name}... ` +
435
+ /* `v${version}` + */
436
+ `\n\n\n\n\n\n\n\n\n\n`
437
+ );
438
+
439
+ if (!this._params) {
440
+ throw new Error('getAppParams() must return a DyNTS_AppParams object!');
441
+ }
442
+
443
+ if (this.params.systemShortCodeName) {
444
+ DyNTS_global_settings.systemShortCodeName = this.params.systemShortCodeName;
445
+ }
446
+
447
+ if (this.params.systemName) {
448
+ DyNTS_global_settings.systemName = this.params.systemName;
449
+ DyFM_error_defaults.issuerSystem = this.params.systemName;
450
+ }
451
+
452
+ if (this.params.version) {
453
+ DyNTS_global_settings.systemVersion = this.params.version;
454
+ DyFM_error_defaults.systemVersion = this.params.version;
455
+ }
456
+
457
+ process.stdout.write(
458
+ String.fromCharCode(27) + ']0;' +
459
+ this._params?.name +
460
+ String.fromCharCode(7)
461
+ );
462
+
463
+ DyFM_error_defaults.issuerSystem = this._params.systemName;
464
+
465
+ this.overrideDynamoNTSGlobalSettings?.();
466
+
467
+ if (DyNTS_global_settings.log_settings.setup) {
468
+ DyFM_Log.S_info(`env settings;\n`, {
469
+ systemName: DyNTS_global_settings.systemName,
470
+ systemShortCodeName: DyNTS_global_settings.systemShortCodeName,
471
+ systemVersion: DyNTS_global_settings.systemVersion,
472
+ environment: DyNTS_global_settings.env_settings.environment,
473
+ /* log_settings: DyNTS_global_settings.log_settings,
474
+ env_settings: DyNTS_global_settings.env_settings, */
475
+ });
476
+ }
477
+
478
+ this.globalService = DyNTS_GlobalService.getInstance();
479
+ await DyNTS_GlobalService.setServices(this.getGlobalServiceCollection());
480
+ DyNTS_GlobalService.setParams(this.params);
481
+
482
+ if (this.getPortSettings) {
483
+ this._portSettings = this.getPortSettings();
484
+ }
485
+
486
+ if (this.getCertificationSettings) {
487
+ this._cert = this.getCertificationSettings();
488
+ }
489
+
490
+ if (this.getApiBasePath) {
491
+ DyNTS_global_settings.baseUrl = this.getApiBasePath();
492
+ }
493
+
494
+ if (this.getRoutingModules) {
495
+ this._routingModules = this.getRoutingModules();
496
+
497
+ // ezt egyelőre csak tesztelem, nem kerül be
498
+ /* if (
499
+ !DyNTS_global_settings.dontCreateDefaultRoute &&
500
+ !this._routingModules.some((routingModule: DyNTS_RoutingModule): boolean => routingModule.route === '/*')
501
+ ) {
502
+ this._routingModules.push(
503
+ DyNTS_getStarRoute()
504
+ );
505
+ } */
506
+ }
507
+
508
+ if (this._params.dbUri) {
509
+ await this.startDB();
510
+
511
+ // createEntries csak akkor fut, ha a DB tényleg fel-jött.
512
+ // Ha a startDB jelezte a hibát, de továbbment, akkor a started flag false marad,
513
+ // és nem próbálunk meg írni egy nem létező kapcsolatra.
514
+ if (this.createEntries && this.systemControls.mongoose.started) {
515
+ await this.createEntries();
516
+ }
517
+ } else {
518
+ DyFM_Log.log(
519
+ `\nNo database connection created.`,
520
+ );
521
+ }
522
+
523
+ if (this._routingModules?.length) {
524
+ if (this.logSetup) DyFM_Log.log('\nsetting up express routes...');
525
+
526
+ this.setSecurity();
527
+
528
+ await this.initExpresses();
529
+ await this.startExpresses();
530
+
531
+ if (this._security !== DyNTS_RouteSecurity.secure) {
532
+ await this.mountOpenRoutes();
533
+ }
534
+
535
+ if (this._security !== DyNTS_RouteSecurity.open && this._cert) {
536
+ await this.mountSecureRoutes();
537
+ }
538
+
539
+ // Generikus, auth-agnosztikus extension-point: custom middleware az API
540
+ // route-ok UTÁN, de a SPA static catch-all (mountStaticClient) ELŐTT.
541
+ await this.mountCustomMiddleware();
542
+
543
+ await this.mountStaticClient();
544
+
545
+ if (this.logSetup) {
546
+ DyFM_Log.log(`\nRoutes mounted.... server using security: ${this._security}`);
547
+ }
548
+ } else {
549
+ DyFM_Log.warn(
550
+ `\nNo routes mounted!`,
551
+ );
552
+ }
553
+
554
+ if (this.getRootServices) {
555
+ this._rootServices = await this.getRootServices();
556
+ }
557
+
558
+ if (this.postProcess) {
559
+ await this.postProcess().catch((error: unknown): void => {
560
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
561
+ 'DYNTS-AS0-POST-PROCESS-FAILED',
562
+ DyNTS_SafeDiagnosticStage_Type.postProcess,
563
+ error
528
564
  );
529
- } */
530
- }
531
-
532
- if (this._params.dbUri) {
533
- await this.startDB();
534
-
535
- // createEntries csak akkor fut, ha a DB tényleg fel-jött.
536
- // Ha a startDB jelezte a hibát, de továbbment, akkor a started flag false marad,
537
- // és nem próbálunk meg írni egy nem létező kapcsolatra.
538
- if (this.createEntries && this.systemControls.mongoose.started) {
539
- await this.createEntries();
540
- }
541
- } else {
542
- DyFM_Log.log(
543
- `\nNo database connection created.`,
544
- );
545
- }
546
-
547
- if (this._routingModules?.length) {
548
- if (this.logSetup) DyFM_Log.log('\nsetting up express routes...');
549
-
550
- this.setSecurity();
551
-
552
- await this.initExpresses();
553
- await this.startExpresses();
554
-
555
- if (this._security !== DyNTS_RouteSecurity.secure) {
556
- await this.mountOpenRoutes();
557
- }
558
-
559
- if (this._security !== DyNTS_RouteSecurity.open && this._cert) {
560
- await this.mountSecureRoutes();
561
- }
562
565
 
563
- // Generikus, auth-agnosztikus extension-point: custom middleware az API
564
- // route-ok UTÁN, de a SPA static catch-all (mountStaticClient) ELŐTT.
565
- await this.mountCustomMiddleware();
566
-
567
- await this.mountStaticClient();
568
-
569
- if (this.logSetup) {
570
- DyFM_Log.log(`\nRoutes mounted.... server using security: ${this._security}`);
571
- }
572
- } else {
573
- DyFM_Log.warn(
574
- `\nNo routes mounted!`,
575
- );
576
- }
577
-
578
- if (this.getRootServices) {
579
- this._rootServices = await this.getRootServices();
580
- }
581
-
582
- if (this.postProcess) {
583
- await this.postProcess().catch((error: any): void => {
584
- DyFM_Error.logSimple(`"${this._params.name}" postProcess failed:`, error);
585
- DyNTS_GlobalService.globalErrorHandler?.(error);
566
+ this.forwardSafeDiagnostic(diagnostic);
586
567
  });
587
568
  }
588
-
589
- // FR-193 — bedrock OOM korai-figyelmeztetés: feltelepítjük a heap-watchdogot, ha
590
- // engedélyezve (DyNTS_global_settings.memoryGuard.enabled, default true). Biztonságos:
591
- // a guard egy könnyű setInterval, ami SOHA nem dob; csak near-OOM küszöböknél hagy
592
- // tartós nyomot az error-sinkbe, mielőtt a fatal heap-OOM megölné a process-t.
593
- try {
594
- if (DyNTS_global_settings.memoryGuard?.enabled) {
595
- DyNTS_MemoryGuard.getInstance().install();
596
- }
569
+
570
+ // FR-193 — bedrock OOM korai-figyelmeztetés: feltelepítjük a heap-watchdogot, ha
571
+ // engedélyezve (DyNTS_global_settings.memoryGuard.enabled, default true). Biztonságos:
572
+ // a guard egy könnyű setInterval, ami SOHA nem dob; csak near-OOM küszöböknél hagy
573
+ // tartós nyomot az error-sinkbe, mielőtt a fatal heap-OOM megölné a process-t.
574
+ try {
575
+ if (DyNTS_global_settings.memoryGuard?.enabled) {
576
+ DyNTS_MemoryGuard.getInstance().install();
577
+ }
597
578
  } catch (memoryGuardError: unknown) {
598
- DyFM_Log.warn('[DyNTS_MemoryGuard] auto-install skipped (non-fatal):', memoryGuardError);
579
+ this.reportSafeDiagnostic(
580
+ 'DYNTS-AS0-MEMORY-GUARD-SKIPPED',
581
+ DyNTS_SafeDiagnosticStage_Type.memoryGuard,
582
+ memoryGuardError
583
+ );
599
584
  }
600
-
601
- // BFR-OVERSEER-007 — event-loop-lag diag a MemoryGuard MELLÉ: a „process él, HTTP néma" wedge
602
- // belső mérése (natív histogram, olcsó). Observation-only, sosem dob; a /server/diag olvas belőle.
603
- try {
604
- DyNTS_EventLoopDiag.getInstance().install();
585
+
586
+ // BFR-OVERSEER-007 — event-loop-lag diag a MemoryGuard MELLÉ: a „process él, HTTP néma" wedge
587
+ // belső mérése (natív histogram, olcsó). Observation-only, sosem dob; a /server/diag olvas belőle.
588
+ try {
589
+ DyNTS_EventLoopDiag.getInstance().install();
605
590
  } catch (eventLoopDiagError: unknown) {
606
- DyFM_Log.warn('[DyNTS_EventLoopDiag] auto-install skipped (non-fatal):', eventLoopDiagError);
591
+ this.reportSafeDiagnostic(
592
+ 'DYNTS-AS0-EVENT-LOOP-DIAG-SKIPPED',
593
+ DyNTS_SafeDiagnosticStage_Type.eventLoopDiagnostic,
594
+ eventLoopDiagError
595
+ );
607
596
  }
608
-
609
- // FR-258 / SR-4 — proactive collection-growth monitor (companion to the MemoryGuard). Warns
610
- // into the Errors-sink when a collection grows unbounded, BEFORE it can be loaded into heap and
611
- // OOM. Default-on, observation-only, never throws.
612
- try {
613
- if (DyNTS_global_settings.collectionGrowthMonitor?.enabled) {
614
- DyNTS_CollectionGrowthMonitor.getInstance().install();
615
- }
597
+
598
+ // FR-258 / SR-4 — proactive collection-growth monitor (companion to the MemoryGuard). Warns
599
+ // into the Errors-sink when a collection grows unbounded, BEFORE it can be loaded into heap and
600
+ // OOM. Default-on, observation-only, never throws.
601
+ try {
602
+ if (DyNTS_global_settings.collectionGrowthMonitor?.enabled) {
603
+ DyNTS_CollectionGrowthMonitor.getInstance().install();
604
+ }
616
605
  } catch (cgmError: unknown) {
617
- DyFM_Log.warn('[DyNTS_CollectionGrowthMonitor] auto-install skipped (non-fatal):', cgmError);
618
- }
619
-
620
- if (!extended) {
621
- await this.ready();
622
-
623
- if (this.params.title) {
624
- DyFM_Log.success(this.params.title);
625
- }
626
- DyFM_Log.info(`Version: ${this.params.version}`);
627
- /* DyFM_Log.info(`NTS Version: ${this.ntsVersion}`); */
628
- DyFM_Log.H_success(`${this.params.name} started successfully.`);
606
+ this.reportSafeDiagnostic(
607
+ 'DYNTS-AS0-COLLECTION-GROWTH-MONITOR-SKIPPED',
608
+ DyNTS_SafeDiagnosticStage_Type.collectionGrowthMonitor,
609
+ cgmError
610
+ );
629
611
  }
612
+
613
+ if (!extended) {
614
+ await this.ready();
615
+
616
+ if (this.params.title) {
617
+ DyFM_Log.success(this.params.title);
618
+ }
619
+ DyFM_Log.info(`Version: ${this.params.version}`);
620
+ /* DyFM_Log.info(`NTS Version: ${this.ntsVersion}`); */
621
+ DyFM_Log.H_success(`${this.params.name} started successfully.`);
622
+ }
630
623
  } catch (error) {
631
624
  this.constructErrors.push(error);
632
625
 
633
- if (this.deepLog) {
634
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
635
- DyFM_Log.H_error(
636
- `"${this._params.name}" start failed (in asyncConstruct (highDetailedLog)). `,
637
- `\n\n construct ERRORS:`, this.constructErrors,
638
- '\n\nlast error:', error
639
- );
640
- } else {
641
- DyFM_Log.H_error(
642
- `"${this._params.name}" start failed (in asyncConstruct). `,
643
- `\n\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
644
- '\n\nlast error:', error instanceof DyFM_Error ? error.getErrorSimplified() : error
645
- );
646
- }
647
- }
648
-
649
626
  throw new DyFM_Error({
650
- ...this._getDefaultErrorSettings('asyncConstruct', error),
651
-
652
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-001`,
653
- additionalContent: {
654
- constructErrors: this.constructErrors,
655
- systemControls: this.systemControls,
656
- systemReadies: {
657
- app: this.systemControls.app.getIsReady(),
658
- mongoose: this.systemControls.mongoose.getIsReady(),
659
- httpServer: this.systemControls.httpServer.getIsReady(),
660
- httpsServer: this.systemControls.httpsServer.getIsReady(),
661
- },
662
- },
663
- });
664
- }
665
- }
666
-
667
- async ready(timeout: number = this.defaultReadyTimeout): Promise<void> {
668
- try {
669
- if (this.fnLogs) DyFM_Log.log('\nfn:. ready');
670
-
671
- await DyFM_Async.delay(100);
672
-
673
- let ready: boolean = false;
627
+ ...this._getDefaultErrorSettings('asyncConstruct', error),
628
+
629
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-001`,
630
+ additionalContent: {
631
+ constructErrors: this.constructErrors,
632
+ systemControls: this.systemControls,
633
+ systemReadies: {
634
+ app: this.systemControls.app.getIsReady(),
635
+ mongoose: this.systemControls.mongoose.getIsReady(),
636
+ httpServer: this.systemControls.httpServer.getIsReady(),
637
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
638
+ },
639
+ },
640
+ });
641
+ }
642
+ }
643
+
644
+ async ready(timeout: number = this.defaultReadyTimeout): Promise<void> {
645
+ try {
646
+ if (this.fnLogs) DyFM_Log.log('\nfn:. ready');
647
+
648
+ await DyFM_Async.delay(100);
649
+
650
+ let ready: boolean = false;
674
651
  const start: number = +new Date();
675
652
 
676
653
  if (this.constructErrors.length) {
677
- if (this.deepLog) {
678
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
679
- DyFM_Log.H_error(
680
- `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
681
- `\n construct ERRORS:`, this.constructErrors
682
- );
683
- } else {
684
- DyFM_Log.H_error(
685
- `"${this._params.name}" start failed. (ready; constructErrors check 1)`,
686
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
687
- );
688
- }
689
- }
690
-
691
- throw new DyFM_Error({
692
- ...this._getDefaultErrorSettings(
693
- 'ready',
694
- new Error(`"${this._params.name}" start failed.`)
695
- ),
696
-
697
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R01`,
698
- additionalContent:
699
- this.constructErrors.length === 1 ?
700
- { error: this.constructErrors[0] } :
701
- { errors: this.constructErrors },
702
- });
703
- }
704
-
705
- while (!ready && +new Date() - start < timeout) {
706
- if (this.systemControls.app.init) {
707
- ready = (
708
- this.systemControls.mongoose.getIsReady() &&
709
- this.systemControls.httpServer.getIsReady() &&
710
- this.systemControls.httpsServer.getIsReady()
711
- );
712
- } else {
713
- DyFM_Log.error(`"${this._params.name}" APP NOT INITIALIZED while trying to get ready.`);
714
- }
715
-
716
- if (!ready) {
717
- await DyFM_Async.wait(100);
654
+ this.reportSafeDiagnostic(
655
+ 'DYNTS-AS0-READINESS-CONSTRUCT-ERROR',
656
+ DyNTS_SafeDiagnosticStage_Type.readiness,
657
+ this.constructErrors[0]
658
+ );
659
+
660
+ throw new DyFM_Error({
661
+ ...this._getDefaultErrorSettings(
662
+ 'ready',
663
+ new Error(`"${this._params.name}" start failed.`)
664
+ ),
665
+
666
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R01`,
667
+ additionalContent:
668
+ this.constructErrors.length === 1 ?
669
+ { error: this.constructErrors[0] } :
670
+ { errors: this.constructErrors },
671
+ });
672
+ }
673
+
674
+ while (!ready && +new Date() - start < timeout) {
675
+ if (this.systemControls.app.init) {
676
+ ready = (
677
+ this.systemControls.mongoose.getIsReady() &&
678
+ this.systemControls.httpServer.getIsReady() &&
679
+ this.systemControls.httpsServer.getIsReady()
680
+ );
718
681
  }
719
- }
720
-
682
+
683
+ if (!ready) {
684
+ await DyFM_Async.wait(100);
685
+ }
686
+ }
687
+
721
688
  if (timeout < +new Date() - start) {
722
- if (this.deepLog) {
723
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
724
- DyFM_Log.H_error(
725
- `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
726
- `\n construct ERRORS:`, this.constructErrors
727
- );
728
- } else {
729
- DyFM_Log.H_error(
730
- `"${this._params.name}" start failed. (ready; TIMEOUT check)`,
731
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
732
- );
733
- }
734
- }
735
-
736
- throw new DyFM_Error({
737
- ...this._getDefaultErrorSettings(
738
- 'ready',
739
- new Error(`"${this._params.name}" start failed. TIMEOUT`)
740
- ),
741
-
742
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R02`,
743
- additionalContent: {
744
- constructErrors: this.constructErrors,
745
- systemControls: this.systemControls,
746
- systemReadies: {
747
- mongoose: this.systemControls.mongoose.getIsReady(),
748
- httpServer: this.systemControls.httpServer.getIsReady(),
749
- httpsServer: this.systemControls.httpsServer.getIsReady(),
750
- },
751
- },
752
- });
753
- }
754
-
689
+ this.reportSafeDiagnostic(
690
+ 'DYNTS-AS0-READINESS-TIMEOUT',
691
+ DyNTS_SafeDiagnosticStage_Type.readiness,
692
+ this.constructErrors[0] ?? new Error('readiness-timeout')
693
+ );
694
+
695
+ throw new DyFM_Error({
696
+ ...this._getDefaultErrorSettings(
697
+ 'ready',
698
+ new Error(`"${this._params.name}" start failed. TIMEOUT`)
699
+ ),
700
+
701
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R02`,
702
+ additionalContent: {
703
+ constructErrors: this.constructErrors,
704
+ systemControls: this.systemControls,
705
+ systemReadies: {
706
+ mongoose: this.systemControls.mongoose.getIsReady(),
707
+ httpServer: this.systemControls.httpServer.getIsReady(),
708
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
709
+ },
710
+ },
711
+ });
712
+ }
713
+
755
714
  if (this.constructErrors.length) {
756
- if (this.deepLog) {
757
- if (DyNTS_global_settings.log_settings.highDetailedLogs) {
758
- DyFM_Log.H_error(
759
- `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
760
- `\n construct ERRORS:`, this.constructErrors
761
- );
762
- } else {
763
- DyFM_Log.H_error(
764
- `"${this._params.name}" start failed. (ready; constructErrors check 2)`,
765
- `\n construct ERRORS:`, this.getSimplifiedConstructErrors(),
766
- );
767
- }
768
- }
769
-
770
- throw new DyFM_Error({
771
- ...this._getDefaultErrorSettings(
772
- 'ready',
773
- new Error(`"${this._params.name}" start failed.`)
774
- ),
775
-
776
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R03`,
777
- additionalContent: this.constructErrors,
778
- });
779
- }
780
-
781
- if (ready) {
782
- this.systemControls.app.started = true;
783
-
784
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. ready: return');
785
-
786
- return;
787
- }
788
-
789
- this.systemControls.app.started = false;
790
-
791
- let msg: string = `"${this._params.name}" start failed. UNKNOWN`;
792
-
793
- if (this.systemControls.mongoose.init && !this.systemControls.mongoose.started) {
794
- msg += `\nMongoose start failed.`;
795
- }
796
-
797
- if (this.systemControls.httpServer.init && !this.systemControls.httpServer.started) {
798
- msg += `\nHTTP Server start failed.`;
799
- }
800
-
801
- if (this.systemControls.httpsServer.init && !this.systemControls.httpsServer.started) {
802
- msg += `\nHTTPS Server start failed.`;
803
- }
804
-
805
- DyFM_Log.error(msg, this.constructErrors);
806
-
807
- throw new DyFM_Error({
808
- ...this._getDefaultErrorSettings('ready', new Error(msg)),
809
-
810
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R04`,
811
- additionalContent: {
812
- constructErrors: this.constructErrors,
813
- systemControls: this.systemControls,
814
- systemReadies: {
815
- app: this.systemControls.app.getIsReady(),
816
- mongoose: this.systemControls.mongoose.getIsReady(),
817
- httpServer: this.systemControls.httpServer.getIsReady(),
818
- httpsServer: this.systemControls.httpsServer.getIsReady(),
819
- },
820
- },
821
- error: this.constructErrors?.[0] ?? new Error(),
822
- });
823
- } catch (error) {
824
- throw new DyFM_Error({
825
- ...this._getDefaultErrorSettings('ready', error),
826
-
827
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-READY0`,
828
- });
829
- }
830
- }
831
-
832
- protected getSimplifiedConstructErrors(): string[] {
833
- return this.constructErrors.map((error: any): any => {
834
- if (error instanceof DyFM_Error) {
835
- return error.getErrorSimplified();
836
- } else {
837
- return error;
838
- }
839
- });
840
- }
841
-
842
- async stop(dontLog?: boolean): Promise<void> {
843
- try {
844
- DyFM_Log.info('\nstopping server...\n');
845
-
846
- await this.ready();
847
-
848
- if (this.started) {
849
-
850
- if (this.systemControls.mongoose.init) {
851
- DyFM_Log.info(`\nstopping Mongoose....`);
852
-
853
- let tryCount: number = 0;
854
-
855
- while (
856
- !this.systemControls.mongoose.started &&
857
- !this.constructErrors.length &&
858
- tryCount++ < 10
859
- ) {
860
- DyFM_Log.warn(`Mongoose not even started yet....`);
861
- await DyFM_Async.wait(second);
862
- }
863
- this.systemControls.mongoose.started = false;
864
-
865
- if (this.mongoose) {
866
- await DyFM_Array.asyncForEach(
867
- Object.keys(this.mongoose.models),
868
- async (modelName): Promise<void> => {
869
- this.mongoose.deleteModel(modelName);
870
- }
871
- );
872
-
873
- const disconnect: Promise<void> = new Promise((resolve): void => {
874
- this.mongoose.connection.on('disconnecting', (): void => {
875
- resolve();
876
- });
877
- });
878
-
879
- await this.mongoose.disconnect();
880
- await this.mongoose.connection.close();
881
- await disconnect;
882
-
883
- this.mongoose.connection.removeAllListeners();
884
-
885
- while (
886
- this.mongoose.connection.readyState !== 0 &&
887
- !this.constructErrors.length
888
- ) {
889
- DyFM_Log.warn(`\nMongoose still not disconnected....`);
890
- await DyFM_Async.wait(second);
891
- }
892
- } else {
893
- DyFM_Log.error(`\nMongoose not found.`);
894
- }
895
- this.systemControls.mongoose.init = false;
896
- }
897
-
898
- if (this.systemControls.httpServer.init) {
899
- this.systemControls.httpServer.started = false;
900
-
901
- if (this.httpServer) {
902
- await new Promise((resolve): void => {
903
- this.httpServer.close(resolve);
904
- });
905
- } else {
906
- DyFM_Log.error(`\nHTTP Server not found.`);
907
- }
908
- this.systemControls.httpServer.init = false;
909
- }
910
-
911
- if (this.systemControls.httpsServer.init) {
912
- this.systemControls.httpsServer.started = false;
913
-
914
- if (this.httpsServer) {
915
- await new Promise((resolve): void => {
916
- this.httpsServer.close(resolve);
917
- });
918
- } else {
919
- DyFM_Log.error(`\nHTTPS Server not found.`);
920
- }
921
- this.systemControls.httpsServer.init = false;
922
- }
923
-
924
- await DyFM_Async.wait(second);
925
-
926
- if (!dontLog) {
927
- DyFM_Log.H_log(`"${this._params.name}" stopped successfully.`);
928
- }
929
- }
930
- } catch (error) {
931
- throw new DyFM_Error({
932
- ...this._getDefaultErrorSettings('stop', error),
933
-
934
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-STOP0`,
935
- });
936
- }
937
- }
938
-
939
- /**
940
- *
941
- */
942
- private async startDB(): Promise<void> {
943
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startDB');
944
- else if (this.logSetup) DyFM_Log.log('\nstarting DB connection...');
945
-
946
- if (!this._params.dbUri) {
947
- throw new DyFM_Error({
948
- ...this._getDefaultErrorSettings('startDB', new Error('DB URI is not set.')),
949
-
950
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
951
- });
952
- }
953
-
954
- if (!this._params.dbOptions) {
955
- throw new DyFM_Error({
956
- ...this._getDefaultErrorSettings('startDB', new Error('DB OPTIONS are not set.')),
957
-
958
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
959
- });
960
- }
961
-
962
- if (this.systemControls.mongoose.init || this.systemControls.mongoose.started) {
963
- throw new DyFM_Error({
964
- ...this._getDefaultErrorSettings('startDB', new Error('Mongoose is already initialized.')),
965
-
966
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
967
- });
968
- }
969
-
970
- try {
971
- await new Promise<void>(
972
- (resolve, reject): void => {
973
- this.systemControls.mongoose.init = true;
974
-
975
- this.mongoose.connection
715
+ this.reportSafeDiagnostic(
716
+ 'DYNTS-AS0-READINESS-LATE-CONSTRUCT-ERROR',
717
+ DyNTS_SafeDiagnosticStage_Type.readiness,
718
+ this.constructErrors[0]
719
+ );
720
+
721
+ throw new DyFM_Error({
722
+ ...this._getDefaultErrorSettings(
723
+ 'ready',
724
+ new Error(`"${this._params.name}" start failed.`)
725
+ ),
726
+
727
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R03`,
728
+ additionalContent: this.constructErrors,
729
+ });
730
+ }
731
+
732
+ if (ready) {
733
+ this.systemControls.app.started = true;
734
+
735
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. ready: return');
736
+
737
+ return;
738
+ }
739
+
740
+ this.systemControls.app.started = false;
741
+
742
+ let msg: string = `"${this._params.name}" start failed. UNKNOWN`;
743
+
744
+ if (this.systemControls.mongoose.init && !this.systemControls.mongoose.started) {
745
+ msg += `\nMongoose start failed.`;
746
+ }
747
+
748
+ if (this.systemControls.httpServer.init && !this.systemControls.httpServer.started) {
749
+ msg += `\nHTTP Server start failed.`;
750
+ }
751
+
752
+ if (this.systemControls.httpsServer.init && !this.systemControls.httpsServer.started) {
753
+ msg += `\nHTTPS Server start failed.`;
754
+ }
755
+
756
+ this.reportSafeDiagnostic(
757
+ 'DYNTS-AS0-READINESS-UNKNOWN',
758
+ DyNTS_SafeDiagnosticStage_Type.readiness,
759
+ this.constructErrors[0] ?? new Error('readiness-unknown')
760
+ );
761
+
762
+ throw new DyFM_Error({
763
+ ...this._getDefaultErrorSettings('ready', new Error(msg)),
764
+
765
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-R04`,
766
+ additionalContent: {
767
+ constructErrors: this.constructErrors,
768
+ systemControls: this.systemControls,
769
+ systemReadies: {
770
+ app: this.systemControls.app.getIsReady(),
771
+ mongoose: this.systemControls.mongoose.getIsReady(),
772
+ httpServer: this.systemControls.httpServer.getIsReady(),
773
+ httpsServer: this.systemControls.httpsServer.getIsReady(),
774
+ },
775
+ },
776
+ error: this.constructErrors?.[0] ?? new Error(),
777
+ });
778
+ } catch (error) {
779
+ throw new DyFM_Error({
780
+ ...this._getDefaultErrorSettings('ready', error),
781
+
782
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-READY0`,
783
+ });
784
+ }
785
+ }
786
+
787
+ protected getSimplifiedConstructErrors(): string[] {
788
+ return this.constructErrors.map((error: any): any => {
789
+ if (error instanceof DyFM_Error) {
790
+ return error.getErrorSimplified();
791
+ } else {
792
+ return error;
793
+ }
794
+ });
795
+ }
796
+
797
+ async stop(dontLog?: boolean): Promise<void> {
798
+ try {
799
+ DyFM_Log.info('\nstopping server...\n');
800
+
801
+ await this.ready();
802
+
803
+ if (this.started) {
804
+
805
+ if (this.systemControls.mongoose.init) {
806
+ DyFM_Log.info(`\nstopping Mongoose....`);
807
+
808
+ let tryCount: number = 0;
809
+
810
+ while (
811
+ !this.systemControls.mongoose.started &&
812
+ !this.constructErrors.length &&
813
+ tryCount++ < 10
814
+ ) {
815
+ DyFM_Log.warn(`Mongoose not even started yet....`);
816
+ await DyFM_Async.wait(second);
817
+ }
818
+ this.systemControls.mongoose.started = false;
819
+
820
+ if (this.mongoose) {
821
+ await DyFM_Array.asyncForEach(
822
+ Object.keys(this.mongoose.models),
823
+ async (modelName): Promise<void> => {
824
+ this.mongoose.deleteModel(modelName);
825
+ }
826
+ );
827
+
828
+ const disconnect: Promise<void> = new Promise((resolve): void => {
829
+ this.mongoose.connection.on('disconnecting', (): void => {
830
+ resolve();
831
+ });
832
+ });
833
+
834
+ await this.mongoose.disconnect();
835
+ await this.mongoose.connection.close();
836
+ await disconnect;
837
+
838
+ this.mongoose.connection.removeAllListeners();
839
+
840
+ while (
841
+ this.mongoose.connection.readyState !== 0 &&
842
+ !this.constructErrors.length
843
+ ) {
844
+ DyFM_Log.warn(`\nMongoose still not disconnected....`);
845
+ await DyFM_Async.wait(second);
846
+ }
847
+ } else {
848
+ DyFM_Log.error(`\nMongoose not found.`);
849
+ }
850
+ this.systemControls.mongoose.init = false;
851
+ }
852
+
853
+ if (this.systemControls.httpServer.init) {
854
+ this.systemControls.httpServer.started = false;
855
+
856
+ if (this.httpServer) {
857
+ await new Promise((resolve): void => {
858
+ this.httpServer.close(resolve);
859
+ });
860
+ } else {
861
+ DyFM_Log.error(`\nHTTP Server not found.`);
862
+ }
863
+ this.systemControls.httpServer.init = false;
864
+ }
865
+
866
+ if (this.systemControls.httpsServer.init) {
867
+ this.systemControls.httpsServer.started = false;
868
+
869
+ if (this.httpsServer) {
870
+ await new Promise((resolve): void => {
871
+ this.httpsServer.close(resolve);
872
+ });
873
+ } else {
874
+ DyFM_Log.error(`\nHTTPS Server not found.`);
875
+ }
876
+ this.systemControls.httpsServer.init = false;
877
+ }
878
+
879
+ await DyFM_Async.wait(second);
880
+
881
+ if (!dontLog) {
882
+ DyFM_Log.H_log(`"${this._params.name}" stopped successfully.`);
883
+ }
884
+ }
885
+ } catch (error) {
886
+ throw new DyFM_Error({
887
+ ...this._getDefaultErrorSettings('stop', error),
888
+
889
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-STOP0`,
890
+ });
891
+ }
892
+ }
893
+
894
+ /**
895
+ *
896
+ */
897
+ private async startDB(): Promise<void> {
898
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startDB');
899
+ else if (this.logSetup) DyFM_Log.log('\nstarting DB connection...');
900
+
901
+ if (!this._params.dbUri) {
902
+ throw new DyFM_Error({
903
+ ...this._getDefaultErrorSettings('startDB', new Error('DB URI is not set.')),
904
+
905
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
906
+ });
907
+ }
908
+
909
+ if (!this._params.dbOptions) {
910
+ throw new DyFM_Error({
911
+ ...this._getDefaultErrorSettings('startDB', new Error('DB OPTIONS are not set.')),
912
+
913
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
914
+ });
915
+ }
916
+
917
+ if (this.systemControls.mongoose.init || this.systemControls.mongoose.started) {
918
+ throw new DyFM_Error({
919
+ ...this._getDefaultErrorSettings('startDB', new Error('Mongoose is already initialized.')),
920
+
921
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
922
+ });
923
+ }
924
+
925
+ try {
926
+ await new Promise<void>(
927
+ (resolve, reject): void => {
928
+ this.systemControls.mongoose.init = true;
929
+
930
+ this.mongoose.connection
976
931
  .once('open', (): void => {
977
932
  this.systemControls.mongoose.started = true;
978
- DyFM_Log.success(`\nConnected to MongoDB (${this._params.dbUri})\n`);
979
-
980
- resolve();
981
-
982
- // FR-258 / SR-2 — install declared-retention TTL indexes. DEFERRED + fire-and-forget +
983
- // fully non-fatal: a create-if-missing index op (and the `indexes()` probes) must NOT
984
- // compete with boot-readiness. We delay it well past the deploy health-probe window so a
985
- // cold boot is never slowed by it, then run it detached. `.unref()` keeps it from holding
986
- // the event loop open. Any failure is logged but never crashes the app. (`'differs'` never
987
- // rebuilds a live index — see ensureRetentionTtlIndex.)
988
- const ttlInstallTimer: ReturnType<typeof setTimeout> = setTimeout((): void => {
989
- void this.installRetentionTtlIndexes();
990
- }, 30000);
991
- if (typeof ttlInstallTimer.unref === 'function') { ttlInstallTimer.unref(); }
992
- })
993
- .on('error', (error): void => {
994
- if (!this.systemControls.mongoose.started) {
995
- // Initial DB-csatlakozás sikertelen:
996
- // jelezzük a hibát (log + globalErrorHandler), de NEM szakítjuk meg az
997
- // App startup-ot (nincs constructErrors push, nincs reject).
998
- // A mongoose.init-et resetteljük, hogy a ready() ne várjon a DB-re.
999
- // Ha a mongoose később mégis tudna csatlakozni, az 'open' event
1000
- // beállítja a started flag-et, így a runtime DB-műveletek elindulnak.
1001
- this.systemControls.mongoose.init = false;
1002
-
1003
- const d_error: DyFM_Error = new DyFM_Error({
1004
- ...this._getDefaultErrorSettings('startDB', error),
1005
-
1006
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB1`,
1007
- message: `Unable to connect to MongoDB server (${this._params.dbUri}), ` +
1008
- `ERROR: ${error}`,
1009
- level: DyFM_ErrorLevel.serious,
1010
- });
1011
-
1012
- DyFM_Log.H_error(
1013
- `\nUnable to connect to MongoDB server (${this._params.dbUri}).` +
1014
- `\nServer will continue WITHOUT DB connection.` +
1015
- `\nDB-using endpoints will fail at runtime until connection recovers.`
1016
- );
1017
-
1018
- if (this.debugLog) DyFM_Log.S_error(
1019
- `\nMongoDB connect ERROR: `,
1020
- error
933
+ DyFM_Log.success('\nConnected to MongoDB.\n');
934
+
935
+ resolve();
936
+
937
+ // FR-258 / SR-2 — install declared-retention TTL indexes. DEFERRED + fire-and-forget +
938
+ // fully non-fatal: a create-if-missing index op (and the `indexes()` probes) must NOT
939
+ // compete with boot-readiness. We delay it well past the deploy health-probe window so a
940
+ // cold boot is never slowed by it, then run it detached. `.unref()` keeps it from holding
941
+ // the event loop open. Any failure is logged but never crashes the app. (`'differs'` never
942
+ // rebuilds a live index — see ensureRetentionTtlIndex.)
943
+ const ttlInstallTimer: ReturnType<typeof setTimeout> = setTimeout((): void => {
944
+ void this.installRetentionTtlIndexes();
945
+ }, 30000);
946
+ if (typeof ttlInstallTimer.unref === 'function') { ttlInstallTimer.unref(); }
947
+ })
948
+ .on('error', (error): void => {
949
+ if (!this.systemControls.mongoose.started) {
950
+ // Initial DB-csatlakozás sikertelen:
951
+ // jelezzük a hibát (log + globalErrorHandler), de NEM szakítjuk meg az
952
+ // App startup-ot (nincs constructErrors push, nincs reject).
953
+ // A mongoose.init-et resetteljük, hogy a ready() ne várjon a DB-re.
954
+ // Ha a mongoose később mégis tudna csatlakozni, az 'open' event
955
+ // beállítja a started flag-et, így a runtime DB-műveletek elindulnak.
956
+ this.systemControls.mongoose.init = false;
957
+
958
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
959
+ 'DYNTS-AS0-SDB1',
960
+ DyNTS_SafeDiagnosticStage_Type.databaseConnect,
961
+ error,
962
+ 503
1021
963
  );
1022
964
 
1023
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
965
+ this.forwardSafeDiagnostic(diagnostic);
1024
966
 
1025
967
  resolve();
1026
968
 
1027
969
  } else {
1028
- if (this.debugLog) DyFM_Log.error('\nMongoDB ERROR: ', error);
1029
-
1030
- const d_error: DyFM_Error = new DyFM_Error({
1031
- ...this._getDefaultErrorSettings('mongoose.connection.on(error)', error),
1032
-
1033
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB2`,
1034
- message: `MongoDB ERROR: ${error}`,
1035
- level: DyFM_ErrorLevel.critical,
1036
- });
970
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
971
+ 'DYNTS-AS0-SDB2',
972
+ DyNTS_SafeDiagnosticStage_Type.databaseRuntime,
973
+ error,
974
+ 503
975
+ );
1037
976
 
1038
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
977
+ this.forwardSafeDiagnostic(diagnostic);
1039
978
  }
1040
- });
1041
-
1042
- try {
1043
- this.mongoose.connect(
1044
- this._params.dbUri,
1045
- this._params.dbOptions
1046
- /* {
1047
- directConnection: true,
1048
- } */
1049
- );
1050
- } catch (error) {
1051
- throw new DyFM_Error({
1052
- ...this._getDefaultErrorSettings('startDB', error),
1053
-
1054
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB3`,
1055
- });
1056
- }
1057
- }
1058
- );
1059
- } catch (error) {
1060
- throw new DyFM_Error({
1061
- ...this._getDefaultErrorSettings('startDB', error),
1062
-
1063
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
1064
- });
1065
- }
1066
-
1067
- // 2026-06-20 — Mongo reconnect-guard. A MongoDB-driver a hostnevet connect-kor EGYSZER
1068
- // resolválja + cache-eli az IP-t; ha a Mongo-konténert recreate-elik (új docker-network IP),
1069
- // a driver a HALOTT IP-n ragad → ECONNREFUSED + buffering-timeout, és a service magától SOHA
1070
- // nem áll vissza. A guard sustained-disconnect (readyState !== 1) esetén — a driver saját
1071
- // grace-e UTÁN — TELJES disconnect()+connect()-et csinál → ÚJ MongoClient → ÚJ DNS-resolve →
1072
- // új IP → reconnect. Best-effort, always-on, healthy connection-t (===1) SOHA nem bánt; csak
1073
- // konténer-IP-frissítés, nem ír adatot. Lásd: mongo-reconnect-guard.util.ts.
1074
- try {
1075
- startMongoReconnectGuard({
1076
- getReadyState: (): number => this.mongoose.connection.readyState,
1077
- reconnect: async (): Promise<void> => {
1078
- await this.mongoose.disconnect().catch((): void => undefined);
1079
- await this.mongoose.connect(this._params.dbUri, this._params.dbOptions);
979
+ });
980
+
981
+ try {
982
+ this.mongoose.connect(
983
+ this._params.dbUri,
984
+ this._params.dbOptions
985
+ /* {
986
+ directConnection: true,
987
+ } */
988
+ );
989
+ } catch (error) {
990
+ throw new DyFM_Error({
991
+ ...this._getDefaultErrorSettings('startDB', error),
992
+
993
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB3`,
994
+ });
995
+ }
996
+ }
997
+ );
998
+ } catch (error) {
999
+ throw new DyFM_Error({
1000
+ ...this._getDefaultErrorSettings('startDB', error),
1001
+
1002
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SDB0`,
1003
+ });
1004
+ }
1005
+
1006
+ // 2026-06-20 — Mongo reconnect-guard. A MongoDB-driver a hostnevet connect-kor EGYSZER
1007
+ // resolválja + cache-eli az IP-t; ha a Mongo-konténert recreate-elik (új docker-network IP),
1008
+ // a driver a HALOTT IP-n ragad → ECONNREFUSED + buffering-timeout, és a service magától SOHA
1009
+ // nem áll vissza. A guard sustained-disconnect (readyState !== 1) esetén — a driver saját
1010
+ // grace-e UTÁN — TELJES disconnect()+connect()-et csinál → ÚJ MongoClient → ÚJ DNS-resolve →
1011
+ // új IP → reconnect. Best-effort, always-on, healthy connection-t (===1) SOHA nem bánt; csak
1012
+ // konténer-IP-frissítés, nem ír adatot. Lásd: mongo-reconnect-guard.util.ts.
1013
+ try {
1014
+ startMongoReconnectGuard({
1015
+ getReadyState: (): number => this.mongoose.connection.readyState,
1016
+ reconnect: async (): Promise<void> => {
1017
+ await this.mongoose.disconnect().catch((): void => undefined);
1018
+ await this.mongoose.connect(this._params.dbUri, this._params.dbOptions);
1019
+ },
1020
+ log: (msg: string): void => {
1021
+ this.reportSafeDiagnostic(
1022
+ 'DYNTS-AS0-MONGO-RECONNECT-EVENT',
1023
+ DyNTS_SafeDiagnosticStage_Type.mongoReconnectGuard,
1024
+ msg,
1025
+ 503
1026
+ );
1080
1027
  },
1081
- log: (msg: string): void => DyFM_Log.warn(msg),
1082
1028
  });
1083
1029
  } catch (guardErr) {
1084
- DyFM_Log.warn(`[mongo-reconnect-guard] failed to start (non-fatal): ${guardErr instanceof Error ? guardErr.message : String(guardErr)}`);
1085
- }
1086
- }
1087
-
1088
- /**
1089
- * FR-258 / SR-2 — install MongoDB TTL indexes for every data-model that declared `retention`.
1090
- *
1091
- * Runs ONCE right after the DB connection opens. For each registered DB service (including the
1092
- * auto-created `_archived` siblings, which inherit the parent model's `retention`), it ensures a
1093
- * TTL index on the `__created` Date field with the resolved `expireAfterSeconds` — so MongoDB
1094
- * NATIVELY auto-deletes documents older than the configured age. This is the fleet-wide defense
1095
- * against the unbounded-collection-growth → in-memory-load → GC-thrash/OOM class.
1096
- *
1097
- * Guarantees:
1098
- * - **Non-fatal** any error is logged but NEVER blocks startup (called fire-and-forget).
1099
- * - **Idempotent** an existing index with the same TTL is a no-op; a CHANGED retention (different
1100
- * `expireAfterSeconds`, or an existing non-TTL `__created` index) is reconciled by drop+recreate
1101
- * (the field index is restored immediately, so query coverage is preserved).
1102
- */
1103
- private async installRetentionTtlIndexes(): Promise<void> {
1104
- try {
1105
- const services: DyNTS_DBService<any>[] = DyNTS_GlobalService.getAllDBServices();
1106
- let ensured: number = 0;
1107
-
1108
- for (const service of services) {
1109
- const ttlSeconds: number | undefined = DyFM_resolveRetentionTtlSeconds(service?.dataParams?.retention);
1110
- if (!ttlSeconds) { continue; }
1111
-
1112
- const dataName: string = service.dataParams.dataName;
1113
- // The mongoose Model exposes the native driver collection (.indexes / .createIndex / .dropIndex).
1114
- const collection: DyNTS_TtlIndexCollection | undefined =
1115
- (service?.dataModel as unknown as { collection?: DyNTS_TtlIndexCollection })?.collection;
1116
- if (!collection || typeof collection.createIndex !== 'function') { continue; }
1117
-
1118
- try {
1119
- const action: DyNTS_TtlIndexAction = await DyNTS_App.ensureRetentionTtlIndex(collection, ttlSeconds);
1120
- if (action === 'created') {
1121
- ensured++;
1122
- if (this.logSetup) {
1123
- DyFM_Log.success(
1124
- `[FR-258 retention] TTL index created on "${dataName}" — ` +
1125
- `${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s)`,
1126
- );
1127
- }
1030
+ this.reportSafeDiagnostic(
1031
+ 'DYNTS-AS0-MONGO-RECONNECT-FAILED',
1032
+ DyNTS_SafeDiagnosticStage_Type.mongoReconnectGuard,
1033
+ guardErr,
1034
+ 503
1035
+ );
1036
+ }
1037
+ }
1038
+
1039
+ /**
1040
+ * FR-258 / SR-2 install MongoDB TTL indexes for every data-model that declared `retention`.
1041
+ *
1042
+ * Runs ONCE right after the DB connection opens. For each registered DB service (including the
1043
+ * auto-created `_archived` siblings, which inherit the parent model's `retention`), it ensures a
1044
+ * TTL index on the `__created` Date field with the resolved `expireAfterSeconds` so MongoDB
1045
+ * NATIVELY auto-deletes documents older than the configured age. This is the fleet-wide defense
1046
+ * against the unbounded-collection-growth in-memory-load GC-thrash/OOM class.
1047
+ *
1048
+ * Guarantees:
1049
+ * - **Non-fatal** — any error is logged but NEVER blocks startup (called fire-and-forget).
1050
+ * - **Idempotent** — an existing index with the same TTL is a no-op; a CHANGED retention (different
1051
+ * `expireAfterSeconds`, or an existing non-TTL `__created` index) is reconciled by drop+recreate
1052
+ * (the field index is restored immediately, so query coverage is preserved).
1053
+ */
1054
+ private async installRetentionTtlIndexes(): Promise<void> {
1055
+ try {
1056
+ const services: DyNTS_DBService<any>[] = DyNTS_GlobalService.getAllDBServices();
1057
+ let ensured: number = 0;
1058
+
1059
+ for (const service of services) {
1060
+ const ttlSeconds: number | undefined = DyFM_resolveRetentionTtlSeconds(service?.dataParams?.retention);
1061
+ if (!ttlSeconds) { continue; }
1062
+
1063
+ const dataName: string = service.dataParams.dataName;
1064
+ // The mongoose Model exposes the native driver collection (.indexes / .createIndex / .dropIndex).
1065
+ const collection: DyNTS_TtlIndexCollection | undefined =
1066
+ (service?.dataModel as unknown as { collection?: DyNTS_TtlIndexCollection })?.collection;
1067
+ if (!collection || typeof collection.createIndex !== 'function') { continue; }
1068
+
1069
+ try {
1070
+ const action: DyNTS_TtlIndexAction = await DyNTS_App.ensureRetentionTtlIndex(collection, ttlSeconds);
1071
+ if (action === 'created') {
1072
+ ensured++;
1073
+ if (this.logSetup) {
1074
+ DyFM_Log.success(
1075
+ `[FR-258 retention] TTL index created on "${dataName}" — ` +
1076
+ `${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s)`,
1077
+ );
1078
+ }
1128
1079
  } else if (action === 'differs') {
1129
1080
  // Live index has a different TTL — left untouched at boot (see ensureRetentionTtlIndex doc).
1130
- DyFM_Log.warn(
1131
- `[FR-258 retention] "${dataName}" already has a {__created} index with a DIFFERENT TTL than the ` +
1132
- `declared ${Math.round(ttlSeconds / 86400)}d (${ttlSeconds}s) — left as-is (no boot-time rebuild). ` +
1133
- `Apply the change via maintenance if intended.`,
1081
+ this.reportSafeDiagnostic(
1082
+ 'DYNTS-AS0-RETENTION-INDEX-DIFFERS',
1083
+ DyNTS_SafeDiagnosticStage_Type.retention,
1084
+ new Error('retention-index-differs')
1134
1085
  );
1135
1086
  }
1136
1087
  } catch (idxErr: unknown) {
1137
- DyFM_Log.warn(
1138
- `[FR-258 retention] TTL index on "${dataName}" failed (non-fatal): ` +
1139
- `${idxErr instanceof Error ? idxErr.message : String(idxErr)}`,
1088
+ this.reportSafeDiagnostic(
1089
+ 'DYNTS-AS0-RETENTION-INDEX-FAILED',
1090
+ DyNTS_SafeDiagnosticStage_Type.retention,
1091
+ idxErr
1140
1092
  );
1141
- }
1142
- }
1143
-
1144
- if (ensured > 0) {
1145
- DyFM_Log.success(`[FR-258 retention] ${ensured} TTL index(es) ensured (auto-retention active).`);
1146
- }
1093
+ }
1094
+ }
1095
+
1096
+ if (ensured > 0) {
1097
+ DyFM_Log.success(`[FR-258 retention] ${ensured} TTL index(es) ensured (auto-retention active).`);
1098
+ }
1147
1099
  } catch (err: unknown) {
1148
- DyFM_Log.warn(
1149
- `[FR-258 retention] TTL-installer failed (non-fatal): ` +
1150
- `${err instanceof Error ? err.message : String(err)}`,
1100
+ this.reportSafeDiagnostic(
1101
+ 'DYNTS-AS0-RETENTION-INSTALLER-FAILED',
1102
+ DyNTS_SafeDiagnosticStage_Type.retention,
1103
+ err
1151
1104
  );
1152
- }
1153
- }
1154
-
1155
- /**
1156
- * FR-258 / SR-2 — ensure a single `{ __created: 1 }` TTL index with the given `expireAfterSeconds`.
1157
- * Extracted as a pure-ish static so it is unit-testable with a mock collection. Idempotent + BOOT-SAFE:
1158
- * - no existing `__created` index → create it → `'created'`
1159
- * - existing with the SAME TTL → no-op → `'noop'`
1160
- * - existing with a DIFFERENT TTL / non-TTL → leave it as-is → `'differs'` (warn only — NO drop+recreate)
1161
- *
1162
- * The `'differs'` case intentionally does NOT mutate the live index. Dropping + recreating a TTL index on a
1163
- * large (multi-GB) production collection is a heavy server-side operation; doing it automatically inside the
1164
- * startup path can starve the concurrent boot queries (including the deploy health-probe) and trigger a
1165
- * fail-safe revert. Create-if-missing is the essential growth-prevention behaviour; a deliberate retention
1166
- * CHANGE on an already-indexed collection is a maintenance action, not a silent every-boot rebuild.
1167
- */
1168
- static async ensureRetentionTtlIndex(
1169
- collection: DyNTS_TtlIndexCollection,
1170
- ttlSeconds: number,
1171
- ): Promise<DyNTS_TtlIndexAction> {
1172
- const existingList: DyNTS_TtlIndexInfo[] = typeof collection.indexes === 'function'
1173
- ? await collection.indexes().catch((): DyNTS_TtlIndexInfo[] => [])
1174
- : [];
1175
- const existing: DyNTS_TtlIndexInfo | undefined =
1176
- existingList.find((ix): boolean => !!ix?.key && ix.key.__created === 1);
1177
-
1178
- if (!existing) {
1179
- await collection.createIndex({ __created: 1 }, { expireAfterSeconds: ttlSeconds });
1180
- return 'created';
1181
- }
1182
- if (existing.expireAfterSeconds === ttlSeconds) {
1183
- return 'noop';
1184
- }
1185
- // Retention differs from the live index (or it is a non-TTL `__created` index). Leave it UNTOUCHED at
1186
- // boot — only report it. Avoids a heavy drop+recreate competing with boot-readiness on a large collection.
1187
- return 'differs';
1188
- }
1189
-
1190
- /**
1191
- *
1192
- */
1193
- private async initExpresses(): Promise<void> {
1194
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. initExpresses');
1195
-
1196
- try {
1197
- if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1198
- if (this._portSettings.httpPort === undefined || this._portSettings.httpPort === null) {
1199
- let errorMsg: string =
1200
- `\nYou have open routes, but httpPort is not set!` +
1201
- `\nThere are ${this._routingModules.filter(
1202
- m => m.security != DyNTS_RouteSecurity.secure
1203
- ).length} open/both routes` +
1204
- `\nroot security: ${this._security}` +
1205
- `\nset httpPort in DynamoBEServer - setupRoutingModules() to enable secure routes.`;
1206
-
1207
- errorMsg += '\n\nThe routes setted to use open server:';
1208
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1209
- if (module.security != DyNTS_RouteSecurity.secure) {
1210
- errorMsg += `\n ${module.route} (security: ${module.security})`;
1211
- errorMsg += `\n subroutes using open sever:`;
1212
- module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1213
- if (endpoint.security != DyNTS_RouteSecurity.secure) {
1214
- errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1215
- }
1216
- });
1217
- }
1218
- });
1219
-
1220
- const error = new Error(`Open routes cannot be established!\n${errorMsg}`);
1221
- const errorStack: string[] = error.stack.split('\n');
1222
-
1223
- errorStack.splice(1, 2);
1224
- error.stack = errorStack.join('\n');
1225
-
1226
- DyFM_Log.error(errorMsg);
1227
-
1228
- throw error;
1229
- }
1230
-
1231
- await this.initOpenExpress();
1232
- }
1233
-
1234
- if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1235
- if (!this._cert || !this._portSettings.httpsPort) {
1236
- let errorMsg: string =
1237
- `\nYou have secure routes, but the certification paths or httpsPort are not set!` +
1238
- `\nThere are ${this._routingModules.filter(
1239
- m => m.security && m.security !== DyNTS_RouteSecurity.open
1240
- ).length} secure routes` +
1241
- `\nroot security: ${this._security}` +
1242
- `\nset...` +
1243
- `\n(missing exact howto...)` +
1244
- /* `\n httpsPort and` +
1245
- `\n cert: {` +
1246
- `\n keyPath: FileSystem.PathLike,` +
1247
- `\n certPath: FileSystem.PathLike,` +
1248
- `\n }` + */
1249
- `\nin DynamoBEServer - getRoutingModules() to enable secure routes.`;
1250
-
1251
- errorMsg += '\n\nThe routes setted to use secure server:';
1252
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1253
- if (module.security && module.security !== DyNTS_RouteSecurity.open) {
1254
- errorMsg += `\n ${module.route} (security: ${module.security})`;
1255
- errorMsg += `\n location: ${module.stackLocation}`;
1256
- errorMsg += `\n subroutes using secure sever:`;
1257
- module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1258
- if (endpoint.security && endpoint.security !== DyNTS_RouteSecurity.open) {
1259
- errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1260
- errorMsg += `\n location: ${endpoint.stackLocation}`;
1261
- }
1262
- });
1263
- }
1264
- });
1265
-
1266
- const error = new Error(`Secure routes cannot be established!\n${errorMsg}`);
1267
- const errorStack: string[] = error.stack.split('\n');
1268
-
1269
- errorStack.splice(1, 2);
1270
- error.stack = errorStack.join('\n');
1271
-
1272
- DyFM_Log.error(errorMsg);
1273
-
1274
- throw error;
1275
- }
1276
-
1277
- await this.initSecureExpress();
1278
- }
1279
- } catch (error) {
1280
- throw new DyFM_Error({
1281
- ...this._getDefaultErrorSettings('initExpresses', error),
1282
-
1283
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-IE0`,
1284
- });
1285
- }
1286
- }
1287
-
1288
- /**
1289
- *
1290
- */
1291
- protected async initOpenExpress(): Promise<void> {
1292
- if (this.fnLogs) DyFM_Log.log('\nfn:. initOpenExpress');
1293
- this.openExpress = Express();
1294
- this.openExpress.set('maxHeaderSize', 10 * megabyte); // 1024 * 1024 * 10, // 10MB
1295
- this.openExpress.use(BodyParser.urlencoded(this._portSettings.httpUrlencoded));
1296
- this.openExpress.use(BodyParser.json(this._portSettings.httpJson));
1297
- // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (az OPTIONS preflight-válaszok is kapják).
1298
- this.mountSecurityHeaders(this.openExpress);
1299
- // FR-041 — CORS allowlist enforcement. No-op if getCorsSettings() is not overridden.
1300
- this.mountCors(this.openExpress);
1301
- // FR-292 — a deployolt app-verzio minden valaszon. A CORS UTAN kell, mert az
1302
- // `Access-Control-Expose-Headers`-hoz HOZZAFUZ (kulonben a CORS felulirna).
1303
- this.mountAppVersionHeader(this.openExpress);
1304
- // BFR-OVERSEER-009 — opt-in auto-load-shed 503 CRITICAL memória-nyomásnál (esszenciális utak kivételével).
1305
- if (DyNTS_global_settings.memoryGuard?.loadShedEnabled) {
1306
- this.openExpress.use(DyNTS_createLoadShedMiddleware());
1307
- }
1308
- }
1309
-
1310
- /**
1311
- *
1312
- */
1313
- protected async initSecureExpress(): Promise<void> {
1314
- if (this.fnLogs) DyFM_Log.log('\nfn:. initSecureExpress');
1315
- this.secureExpress = Express();
1316
- this.secureExpress.use(BodyParser.urlencoded(this._portSettings.httpsUrlencoded));
1317
- this.secureExpress.use(BodyParser.json(this._portSettings.httpsJson));
1318
- // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (mint az open expressen).
1319
- this.mountSecurityHeaders(this.secureExpress);
1320
- // FR-041 — CORS allowlist enforcement (same as open express).
1321
- this.mountCors(this.secureExpress);
1322
- // FR-292 — a deployolt app-verzio minden valaszon (mint az open expressen).
1323
- this.mountAppVersionHeader(this.secureExpress);
1324
- // BFR-OVERSEER-009 — opt-in auto-load-shed 503 (mint az open expressen).
1325
- if (DyNTS_global_settings.memoryGuard?.loadShedEnabled) {
1326
- this.secureExpress.use(DyNTS_createLoadShedMiddleware());
1327
- }
1328
-
1329
- const options = {
1330
- key: FileSystem.readFileSync(this._cert.keyPath),
1331
- cert: FileSystem.readFileSync(this._cert.certPath),
1332
- maxHeaderSize: 10 * megabyte, // 1024 * 1024 * 10, // 10MB
1333
- };
1334
-
1335
- this.httpsServer = Https.createServer(options, this.secureExpress);
1336
- }
1337
-
1338
- /**
1339
- *
1340
- */
1341
- private async startExpresses(): Promise<void> {
1342
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startExpresses');
1343
-
1344
- try {
1345
- if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1346
- await new Promise<void>((resolve, reject): void => {
1347
- this.systemControls.httpsServer.init = true;
1348
- this.httpsServer
1349
- .listen(
1350
- this._portSettings.httpsPort,
1351
- this.params.secureHost,
1352
- this.params.expressBacklog,
1353
- (): void => {
1354
- this.systemControls.httpsServer.started = true;
1355
- DyFM_Log.success(
1356
- `\nHTTPS (secure) server is listening on port: ` +
1357
- `${this.params.secureHost}:${this._portSettings.httpsPort}`
1358
- );
1359
-
1360
- resolve();
1105
+ }
1106
+ }
1107
+
1108
+ /**
1109
+ * FR-258 / SR-2 — ensure a single `{ __created: 1 }` TTL index with the given `expireAfterSeconds`.
1110
+ * Extracted as a pure-ish static so it is unit-testable with a mock collection. Idempotent + BOOT-SAFE:
1111
+ * - no existing `__created` index → create it → `'created'`
1112
+ * - existing with the SAME TTL → no-op → `'noop'`
1113
+ * - existing with a DIFFERENT TTL / non-TTL → leave it as-is → `'differs'` (warn only — NO drop+recreate)
1114
+ *
1115
+ * The `'differs'` case intentionally does NOT mutate the live index. Dropping + recreating a TTL index on a
1116
+ * large (multi-GB) production collection is a heavy server-side operation; doing it automatically inside the
1117
+ * startup path can starve the concurrent boot queries (including the deploy health-probe) and trigger a
1118
+ * fail-safe revert. Create-if-missing is the essential growth-prevention behaviour; a deliberate retention
1119
+ * CHANGE on an already-indexed collection is a maintenance action, not a silent every-boot rebuild.
1120
+ */
1121
+ static async ensureRetentionTtlIndex(
1122
+ collection: DyNTS_TtlIndexCollection,
1123
+ ttlSeconds: number,
1124
+ ): Promise<DyNTS_TtlIndexAction> {
1125
+ const existingList: DyNTS_TtlIndexInfo[] = typeof collection.indexes === 'function'
1126
+ ? await collection.indexes().catch((): DyNTS_TtlIndexInfo[] => [])
1127
+ : [];
1128
+ const existing: DyNTS_TtlIndexInfo | undefined =
1129
+ existingList.find((ix): boolean => !!ix?.key && ix.key.__created === 1);
1130
+
1131
+ if (!existing) {
1132
+ await collection.createIndex({ __created: 1 }, { expireAfterSeconds: ttlSeconds });
1133
+ return 'created';
1134
+ }
1135
+ if (existing.expireAfterSeconds === ttlSeconds) {
1136
+ return 'noop';
1137
+ }
1138
+ // Retention differs from the live index (or it is a non-TTL `__created` index). Leave it UNTOUCHED at
1139
+ // boot — only report it. Avoids a heavy drop+recreate competing with boot-readiness on a large collection.
1140
+ return 'differs';
1141
+ }
1142
+
1143
+ /**
1144
+ *
1145
+ */
1146
+ private async initExpresses(): Promise<void> {
1147
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. initExpresses');
1148
+
1149
+ try {
1150
+ if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1151
+ if (this._portSettings.httpPort === undefined || this._portSettings.httpPort === null) {
1152
+ let errorMsg: string =
1153
+ `\nYou have open routes, but httpPort is not set!` +
1154
+ `\nThere are ${this._routingModules.filter(
1155
+ m => m.security != DyNTS_RouteSecurity.secure
1156
+ ).length} open/both routes` +
1157
+ `\nroot security: ${this._security}` +
1158
+ `\nset httpPort in DynamoBEServer - setupRoutingModules() to enable secure routes.`;
1159
+
1160
+ errorMsg += '\n\nThe routes setted to use open server:';
1161
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1162
+ if (module.security != DyNTS_RouteSecurity.secure) {
1163
+ errorMsg += `\n ${module.route} (security: ${module.security})`;
1164
+ errorMsg += `\n subroutes using open sever:`;
1165
+ module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1166
+ if (endpoint.security != DyNTS_RouteSecurity.secure) {
1167
+ errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1168
+ }
1169
+ });
1170
+ }
1171
+ });
1172
+
1173
+ const error = new Error(`Open routes cannot be established!\n${errorMsg}`);
1174
+ const errorStack: string[] = error.stack.split('\n');
1175
+
1176
+ errorStack.splice(1, 2);
1177
+ error.stack = errorStack.join('\n');
1178
+
1179
+ this.reportSafeDiagnostic(
1180
+ 'DYNTS-AS0-OPEN-ROUTE-CONFIGURATION',
1181
+ DyNTS_SafeDiagnosticStage_Type.routing,
1182
+ error
1183
+ );
1184
+
1185
+ throw error;
1186
+ }
1187
+
1188
+ await this.initOpenExpress();
1189
+ }
1190
+
1191
+ if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1192
+ if (!this._cert || !this._portSettings.httpsPort) {
1193
+ let errorMsg: string =
1194
+ `\nYou have secure routes, but the certification paths or httpsPort are not set!` +
1195
+ `\nThere are ${this._routingModules.filter(
1196
+ m => m.security && m.security !== DyNTS_RouteSecurity.open
1197
+ ).length} secure routes` +
1198
+ `\nroot security: ${this._security}` +
1199
+ `\nset...` +
1200
+ `\n(missing exact howto...)` +
1201
+ /* `\n httpsPort and` +
1202
+ `\n cert: {` +
1203
+ `\n keyPath: FileSystem.PathLike,` +
1204
+ `\n certPath: FileSystem.PathLike,` +
1205
+ `\n }` + */
1206
+ `\nin DynamoBEServer - getRoutingModules() to enable secure routes.`;
1207
+
1208
+ errorMsg += '\n\nThe routes setted to use secure server:';
1209
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1210
+ if (module.security && module.security !== DyNTS_RouteSecurity.open) {
1211
+ errorMsg += `\n ${module.route} (security: ${module.security})`;
1212
+ errorMsg += `\n location: ${module.stackLocation}`;
1213
+ errorMsg += `\n subroutes using secure sever:`;
1214
+ module.endpoints.forEach((endpoint: DyNTS_Endpoint_Params): void => {
1215
+ if (endpoint.security && endpoint.security !== DyNTS_RouteSecurity.open) {
1216
+ errorMsg += `\n ${endpoint.endpoint} (security: ${endpoint.security})`;
1217
+ errorMsg += `\n location: ${endpoint.stackLocation}`;
1218
+ }
1219
+ });
1220
+ }
1221
+ });
1222
+
1223
+ const error = new Error(`Secure routes cannot be established!\n${errorMsg}`);
1224
+ const errorStack: string[] = error.stack.split('\n');
1225
+
1226
+ errorStack.splice(1, 2);
1227
+ error.stack = errorStack.join('\n');
1228
+
1229
+ this.reportSafeDiagnostic(
1230
+ 'DYNTS-AS0-SECURE-ROUTE-CONFIGURATION',
1231
+ DyNTS_SafeDiagnosticStage_Type.routing,
1232
+ error
1233
+ );
1234
+
1235
+ throw error;
1236
+ }
1237
+
1238
+ await this.initSecureExpress();
1239
+ }
1240
+ } catch (error) {
1241
+ throw new DyFM_Error({
1242
+ ...this._getDefaultErrorSettings('initExpresses', error),
1243
+
1244
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-IE0`,
1245
+ });
1246
+ }
1247
+ }
1248
+
1249
+ /**
1250
+ *
1251
+ */
1252
+ protected async initOpenExpress(): Promise<void> {
1253
+ if (this.fnLogs) DyFM_Log.log('\nfn:. initOpenExpress');
1254
+ this.openExpress = Express();
1255
+ this.openExpress.set('maxHeaderSize', 10 * megabyte); // 1024 * 1024 * 10, // 10MB
1256
+ this.openExpress.use(BodyParser.urlencoded(this._portSettings.httpUrlencoded));
1257
+ this.openExpress.use(BodyParser.json(this._portSettings.httpJson));
1258
+ // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (az OPTIONS preflight-válaszok is kapják).
1259
+ this.mountSecurityHeaders(this.openExpress);
1260
+ // FR-041 — CORS allowlist enforcement. No-op if getCorsSettings() is not overridden.
1261
+ this.mountCors(this.openExpress);
1262
+ // FR-292 — a deployolt app-verzio minden valaszon. A CORS UTAN kell, mert az
1263
+ // `Access-Control-Expose-Headers`-hoz HOZZAFUZ (kulonben a CORS felulirna).
1264
+ this.mountAppVersionHeader(this.openExpress);
1265
+ // BFR-OVERSEER-009 — opt-in auto-load-shed 503 CRITICAL memória-nyomásnál (esszenciális utak kivételével).
1266
+ if (DyNTS_global_settings.memoryGuard?.loadShedEnabled) {
1267
+ this.openExpress.use(DyNTS_createLoadShedMiddleware());
1268
+ }
1269
+ }
1270
+
1271
+ /**
1272
+ *
1273
+ */
1274
+ protected async initSecureExpress(): Promise<void> {
1275
+ if (this.fnLogs) DyFM_Log.log('\nfn:. initSecureExpress');
1276
+ this.secureExpress = Express();
1277
+ this.secureExpress.use(BodyParser.urlencoded(this._portSettings.httpsUrlencoded));
1278
+ this.secureExpress.use(BodyParser.json(this._portSettings.httpsJson));
1279
+ // BFR-011 / SEC-R2-8 — security headerek a CORS ELŐTT (mint az open expressen).
1280
+ this.mountSecurityHeaders(this.secureExpress);
1281
+ // FR-041 — CORS allowlist enforcement (same as open express).
1282
+ this.mountCors(this.secureExpress);
1283
+ // FR-292 — a deployolt app-verzio minden valaszon (mint az open expressen).
1284
+ this.mountAppVersionHeader(this.secureExpress);
1285
+ // BFR-OVERSEER-009 opt-in auto-load-shed 503 (mint az open expressen).
1286
+ if (DyNTS_global_settings.memoryGuard?.loadShedEnabled) {
1287
+ this.secureExpress.use(DyNTS_createLoadShedMiddleware());
1288
+ }
1289
+
1290
+ const options = {
1291
+ key: FileSystem.readFileSync(this._cert.keyPath),
1292
+ cert: FileSystem.readFileSync(this._cert.certPath),
1293
+ maxHeaderSize: 10 * megabyte, // 1024 * 1024 * 10, // 10MB
1294
+ };
1295
+
1296
+ this.httpsServer = Https.createServer(options, this.secureExpress);
1297
+ }
1298
+
1299
+ /**
1300
+ *
1301
+ */
1302
+ private async startExpresses(): Promise<void> {
1303
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. startExpresses');
1304
+
1305
+ try {
1306
+ if (this._security && this._security !== DyNTS_RouteSecurity.open) {
1307
+ await new Promise<void>((resolve, reject): void => {
1308
+ this.systemControls.httpsServer.init = true;
1309
+ this.httpsServer
1310
+ .listen(
1311
+ this._portSettings.httpsPort,
1312
+ this.params.secureHost,
1313
+ this.params.expressBacklog,
1314
+ (): void => {
1315
+ this.systemControls.httpsServer.started = true;
1316
+ DyFM_Log.success(
1317
+ `\nHTTPS (secure) server is listening on port: ` +
1318
+ `${this.params.secureHost}:${this._portSettings.httpsPort}`
1319
+ );
1320
+
1321
+ resolve();
1361
1322
  })
1362
- .on('error', (error): void => {
1363
- if (this.debugLog) DyFM_Log.error(`\nHTTPS (secure) server ERROR`, error);
1364
-
1365
- if (!this.systemControls.httpsServer.started) {
1366
- const d_error: DyFM_Error = new DyFM_Error({
1367
- ...this._getDefaultErrorSettings('startExpresses', error),
1368
-
1369
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE1`,
1370
- message: `HTTPS (secure) start server ERROR`,
1323
+ .on('error', (error: unknown): void => {
1324
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
1325
+ 'DYNTS-AS0-HTTPS-ERROR',
1326
+ DyNTS_SafeDiagnosticStage_Type.httpsServer,
1327
+ error,
1328
+ 503
1329
+ );
1330
+
1331
+ if (!this.systemControls.httpsServer.started) {
1332
+ const d_error: DyFM_Error = new DyFM_Error({
1333
+ ...this._getDefaultErrorSettings('startExpresses', error),
1334
+
1335
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE1`,
1336
+ message: `HTTPS (secure) start server ERROR`,
1371
1337
  });
1372
1338
 
1373
1339
  this.constructErrors.push(d_error);
1374
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1375
-
1376
- reject(d_error);
1377
-
1340
+ this.forwardSafeDiagnostic(diagnostic);
1341
+
1342
+ reject(d_error);
1343
+
1378
1344
  } else {
1379
- const d_error: DyFM_Error = new DyFM_Error({
1380
- ...this._getDefaultErrorSettings('httpsServer.on(error)', error),
1381
-
1382
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE2`,
1383
- message: `HTTPS (secure) server ERROR`,
1384
- level: DyFM_ErrorLevel.serious,
1385
- });
1386
-
1387
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1345
+ this.forwardSafeDiagnostic(diagnostic);
1388
1346
  }
1389
1347
  })
1390
1348
  .on('uncaughtException', (exception): void => {
1391
- const d_error: DyFM_Error = new DyFM_Error({
1392
- ...this._getDefaultErrorSettings('httpsServer.on(uncaughtException)', exception),
1393
-
1394
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1395
- message: `HTTPS (secure) server uncaughtException`,
1396
- level: DyFM_ErrorLevel.critical,
1397
- });
1398
-
1399
- if (this.debugLog) DyFM_Log.warn(
1400
- `\nHTTPS (secure) server uncaughtException`,
1401
- d_error
1349
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
1350
+ 'DYNTS-AS0-HTTPS-UNCAUGHT',
1351
+ DyNTS_SafeDiagnosticStage_Type.httpsServer,
1352
+ exception
1402
1353
  );
1403
1354
 
1404
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1355
+ this.forwardSafeDiagnostic(diagnostic);
1405
1356
  });
1406
- });
1407
- }
1408
-
1409
- if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1410
- this.systemControls.httpServer.init = true;
1411
- await new Promise<void>((resolve, reject): void => {
1412
- this.httpServer = this.openExpress
1413
- .listen(
1414
- this._portSettings.httpPort,
1415
- this.params.openHost,
1416
- this.params.expressBacklog,
1417
- (): void => {
1418
- this.systemControls.httpServer.started = true;
1419
-
1420
- const resolvedPort: number = this.httpServer?.address?.()?.['port'] ?? this._portSettings.httpPort;
1421
-
1422
- if (this._portSettings.httpPort === 0) {
1423
- DyFM_Log.H_warn(
1424
- `\nHTTP (open) server is using a randomly selected port by the OS: ${resolvedPort}` +
1425
- `\n (httpPort was set to 0 — this is intended for testing only)`
1426
- );
1427
- }
1428
-
1429
- DyFM_Log.success(
1430
- `\nHTTP (open) server is listening on port: ` +
1431
- `${this.params.openHost}:${resolvedPort}`
1432
- );
1433
-
1434
- resolve();
1435
- }
1436
- )
1437
- .on('error', (error): void => {
1438
- if (this.debugLog) DyFM_Log.error(`\nHTTP (open) server ERROR`, error);
1439
-
1440
- if (!this.systemControls.httpServer.started) {
1441
- const d_error: DyFM_Error = new DyFM_Error({
1442
- ...this._getDefaultErrorSettings('startExpresses', error),
1443
-
1444
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1445
- message: `HTTP (open) start server ERROR`,
1446
- });
1447
-
1357
+ });
1358
+ }
1359
+
1360
+ if (this._security && this._security !== DyNTS_RouteSecurity.secure) {
1361
+ this.systemControls.httpServer.init = true;
1362
+ await new Promise<void>((resolve, reject): void => {
1363
+ this.httpServer = this.openExpress
1364
+ .listen(
1365
+ this._portSettings.httpPort,
1366
+ this.params.openHost,
1367
+ this.params.expressBacklog,
1368
+ (): void => {
1369
+ this.systemControls.httpServer.started = true;
1370
+
1371
+ const resolvedPort: number = this.httpServer?.address?.()?.['port'] ?? this._portSettings.httpPort;
1372
+
1373
+ if (this._portSettings.httpPort === 0) {
1374
+ DyFM_Log.H_warn(
1375
+ `\nHTTP (open) server is using a randomly selected port by the OS: ${resolvedPort}` +
1376
+ `\n (httpPort was set to 0 — this is intended for testing only)`
1377
+ );
1378
+ }
1379
+
1380
+ DyFM_Log.success(
1381
+ `\nHTTP (open) server is listening on port: ` +
1382
+ `${this.params.openHost}:${resolvedPort}`
1383
+ );
1384
+
1385
+ resolve();
1386
+ }
1387
+ )
1388
+ .on('error', (error: unknown): void => {
1389
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
1390
+ 'DYNTS-AS0-HTTP-ERROR',
1391
+ DyNTS_SafeDiagnosticStage_Type.httpServer,
1392
+ error,
1393
+ 503
1394
+ );
1395
+
1396
+ if (!this.systemControls.httpServer.started) {
1397
+ const d_error: DyFM_Error = new DyFM_Error({
1398
+ ...this._getDefaultErrorSettings('startExpresses', error),
1399
+
1400
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE3`,
1401
+ message: `HTTP (open) start server ERROR`,
1402
+ });
1403
+
1448
1404
  this.constructErrors.push(d_error);
1449
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1450
-
1451
- reject(d_error);
1452
-
1405
+ this.forwardSafeDiagnostic(diagnostic);
1406
+
1407
+ reject(d_error);
1408
+
1453
1409
  } else {
1454
- const d_error: DyFM_Error = new DyFM_Error({
1455
- ...this._getDefaultErrorSettings('httpServer.on(error)', error),
1456
-
1457
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE4`,
1458
- message: `HTTP (open) server ERROR`,
1459
- level: DyFM_ErrorLevel.serious,
1460
- });
1461
-
1462
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1410
+ this.forwardSafeDiagnostic(diagnostic);
1463
1411
  }
1464
1412
  })
1465
1413
  .on('uncaughtException', (exception): void => {
1466
- const d_error: DyFM_Error = new DyFM_Error({
1467
- ...this._getDefaultErrorSettings('httpServer.on(uncaughtException)', exception),
1468
-
1469
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE5`,
1470
- message: `HTTP (open) server uncaughtException`,
1471
- level: DyFM_ErrorLevel.critical,
1472
- });
1473
-
1474
- if (this.debugLog) {
1475
- DyFM_Log.warn(`\nHTTP (open) server uncaughtException`, d_error);
1476
- }
1414
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
1415
+ 'DYNTS-AS0-HTTP-UNCAUGHT',
1416
+ DyNTS_SafeDiagnosticStage_Type.httpServer,
1417
+ exception
1418
+ );
1477
1419
 
1478
- DyNTS_GlobalService.globalErrorHandler?.(d_error);
1420
+ this.forwardSafeDiagnostic(diagnostic);
1479
1421
  });
1480
- });
1481
- }
1482
- } catch (error) {
1483
- throw new DyFM_Error({
1484
- ...this._getDefaultErrorSettings('startExpresses', error),
1485
-
1486
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE0`,
1487
- });
1488
- }
1489
- }
1490
-
1491
- /**
1492
- *
1493
- */
1422
+ });
1423
+ }
1424
+ } catch (error) {
1425
+ throw new DyFM_Error({
1426
+ ...this._getDefaultErrorSettings('startExpresses', error),
1427
+
1428
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-SE0`,
1429
+ });
1430
+ }
1431
+ }
1432
+
1433
+ /**
1434
+ *
1435
+ */
1494
1436
  private async expressErrorHandling(error, req, res, next): Promise<void> {
1495
1437
  try {
1496
1438
  if (error) {
1497
- const d_error: DyFM_Error = new DyFM_Error({
1498
- ...this._getDefaultErrorSettings('expressErrorHandling', error),
1499
-
1500
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-EEH1`,
1501
- message: `Express ERROR`,
1502
- additionalContent: {
1503
- req,
1504
- res,
1505
- },
1506
- level: DyFM_ErrorLevel.error,
1507
- });
1508
-
1509
- await DyNTS_GlobalService.globalErrorHandler?.(d_error, req, res);
1439
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
1440
+ 'DYNTS-AS0-EXPRESS-ERROR',
1441
+ DyNTS_SafeDiagnosticStage_Type.expressFallback,
1442
+ error
1443
+ );
1510
1444
 
1511
- // Kliens-safe strip (BFR-FDPAUTHSERVICE-002): az express-error út eddig NYERS error-t küldött
1512
- // (0 strip) — DyFM-nél belső stack/verzió/issuer, axios-jellegű error-nál akár auth-header is
1445
+ this.forwardSafeDiagnostic(diagnostic);
1446
+
1447
+ // Kliens-safe strip (BFR-FDPAUTHSERVICE-002): az express-error út eddig NYERS error-t küldött
1448
+ // (0 strip) — DyFM-nél belső stack/verzió/issuer, axios-jellegű error-nál akár auth-header is
1513
1449
  // kimehetett. A strip-szabályok SSOT-ja a DyNTS_ClientSafeError_Util.
1514
1450
  res.send(DyNTS_ClientSafeError_Util.toClientSafe(error))
1515
1451
  } else {
1516
- DyFM_Log.H_error(
1517
- 'WTF??? express error; without error?...' +
1518
- '\nerr:', error,
1519
- '\nreq:', req,
1520
- '\nres:', res
1452
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
1453
+ 'DYNTS-AS0-EXPRESS-MISSING-ERROR',
1454
+ DyNTS_SafeDiagnosticStage_Type.expressFallback
1521
1455
  );
1522
- }
1523
- } catch (error) {
1524
- DyFM_Log.H_error(
1525
- 'MULTILEVEL ERROR (expressErrorHandling)....' +
1526
- '\n', error
1527
- );
1528
- }
1529
- }
1530
-
1531
- /**
1532
- *
1533
- */
1534
- private async mountSecureRoutes (): Promise<void> {
1535
- try {
1536
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountSecureRoutes');
1537
1456
 
1538
- if (!this.secureExpress) {
1539
- throw new Error(
1540
- 'secureExpress was not initialized. ' +
1541
- 'Secure routes require getCertificationSettings and httpsPort, and cert files must exist.' +
1542
- '\n\nYou need to set security to secure or both in any route and set httpsPort in getPortSettings.' +
1543
- '\n\nYou need to set cert files in getCertificationSettings.'
1544
- );
1457
+ this.forwardSafeDiagnostic(diagnostic);
1545
1458
  }
1546
-
1547
- this.secureExpress.use(
1548
- (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1549
- );
1550
-
1551
- await DyFM_Array.asyncForEach(
1552
- this._routingModules,
1553
- async (module: DyNTS_RoutingModule): Promise<void> => {
1554
- if (module.security !== DyNTS_RouteSecurity.open) {
1555
- if (this.logSetup) {
1556
- DyFM_Log.log(`route mount (secure): ${module.route}`);
1557
- }
1558
-
1559
- const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1560
- (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1561
- );
1562
-
1563
- if (1 < existingRoutes.length) {
1564
- const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1565
- /* const errorStack: string[] = error.stack.split('\n');
1566
-
1567
- errorStack.splice(1, 4);
1568
- error.stack = errorStack.join('\n'); */
1569
- error.stack = module.stackLocation;
1570
-
1571
- DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1572
-
1573
- throw new DyFM_Error({
1574
- ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1575
-
1576
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR1`,
1577
- message: `ROUTE DUPLICATION: ${module.route}`,
1578
- });
1579
- }
1580
-
1581
- this.secureExpress.use(module.route, module.secureRouter);
1582
- }
1583
- }
1584
- );
1585
1459
  } catch (error) {
1586
- throw new DyFM_Error({
1587
- ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1588
-
1589
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR0`,
1590
- });
1591
- }
1592
- }
1593
-
1594
- /**
1595
- *
1596
- */
1597
- private async mountOpenRoutes(): Promise<void> {
1598
- try {
1599
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountOpenRoutes');
1600
-
1601
- if (!this.openExpress) {
1602
- throw new Error(
1603
- 'openExpress was not initialized. Open routes require getOpenExpress and httpPort.' +
1604
- '\n\nYou need to set security to open or both in any route and set httpPort in getPortSettings.'
1605
- );
1606
- }
1607
-
1608
- this.openExpress.use(
1609
- (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1610
- );
1611
-
1612
- await DyFM_Array.asyncForEach(
1613
- this._routingModules,
1614
- async (module: DyNTS_RoutingModule): Promise<void> => {
1615
- if (module.security !== DyNTS_RouteSecurity.secure) {
1616
- if (this.logSetup) {
1617
- DyFM_Log.log(`route mount (open): ${module.route}`);
1618
- }
1619
-
1620
- const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1621
- (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1622
- );
1623
-
1624
- if (1 < existingRoutes.length) {
1625
- const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1626
- /* const errorStack: string[] = error.stack.split('\n');
1627
-
1628
- errorStack.splice(1, 4);
1629
- error.stack = errorStack.join('\n'); */
1630
- error.stack = module.stackLocation;
1631
-
1632
- DyFM_Log.S_error(`ROUTE DUPLICATION: ${module.route}`, error);
1633
-
1634
- throw new DyFM_Error({
1635
- ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1636
-
1637
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR1`,
1638
- message: `ROUTE DUPLICATION: ${module.route}`,
1639
- });
1640
- }
1641
-
1642
- this.openExpress.use(module.route, module.openRouter);
1643
- }
1644
- }
1460
+ const diagnostic: DyNTS_SafeDiagnostic_Interface = this.reportSafeDiagnostic(
1461
+ 'DYNTS-AS0-EXPRESS-MULTILEVEL',
1462
+ DyNTS_SafeDiagnosticStage_Type.expressFallback,
1463
+ error
1645
1464
  );
1646
- } catch (error) {
1647
- throw new DyFM_Error({
1648
- ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1649
-
1650
- errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR0`,
1651
- });
1652
- }
1653
- }
1654
-
1655
- /**
1656
- * FR-041 — CORS middleware. Echoes a matching `Access-Control-Allow-Origin`
1657
- * for any request whose Origin header is in `getCorsSettings().allowedOrigins`,
1658
- * adds the canonical `Access-Control-*` companion headers, and short-circuits
1659
- * the OPTIONS preflight with a 204.
1660
- *
1661
- * No-op when the subclass does NOT override `getCorsSettings()` — preserves
1662
- * back-compat for apps that have always been same-origin and never needed
1663
- * CORS (the typical pre-FR-041 case).
1664
- *
1665
- * Why hand-rolled instead of the `cors` npm package:
1666
- * - ~30 lines, zero new dependency.
1667
- * - Full control over Vary/credentials/preflight semantics.
1668
- * - Aligns with FDP "no unnecessary deps" philosophy.
1669
- */
1670
- /**
1671
- * BFR-011 / SEC-R2-8 — security response-headerek mountolása (a `mountCors` tükörképe).
1672
- * A `DyNTS_global_settings.securityHeaders` alapján (default-ON) minden válaszra ráteszi a
1673
- * biztonsági headereket + eltávolítja az `x-powered-by`-t. A CORS-mount ELŐTT hívandó, hogy az
1674
- * OPTIONS preflight-válaszok (amiket a mountCors 204-gyel rövidre zár) is megkapják.
1675
- */
1676
- protected mountSecurityHeaders(express: Express.Application): void {
1677
- const settings: DyNTS_SecurityHeaders_Settings | undefined = DyNTS_global_settings.securityHeaders;
1678
- if (!settings || !settings.enabled) {
1679
- return;
1680
- }
1681
1465
 
1682
- if (settings.removePoweredBy !== false) {
1683
- express.disable('x-powered-by');
1466
+ this.forwardSafeDiagnostic(diagnostic);
1684
1467
  }
1685
-
1686
- express.use(DyNTS_createSecurityHeadersMiddleware(
1687
- settings,
1688
- DyNTS_getEnvironment_settings().environment,
1689
- ));
1690
- }
1691
-
1692
- /**
1693
- * FR-292 — a deployolt app-verziot minden valaszra rateszi (`X-App-Version`), hogy a
1694
- * bongeszoben NYITVA HAGYOTT SPA eszrevegye, ha kozben ujabb kliens-build ment ki.
1695
- *
1696
- * Nem polling: a jelzes a MAR MENO API-hivasokon utazik. Az `enabled` default TRUE — egy
1697
- * informativ response-header, ami se PII-t, se belso reszletet nem szivarogtat, viszont
1698
- * enelkul minden app kulon-kulon epitene ugyanezt.
1699
- */
1700
- protected mountAppVersionHeader(express: Express.Application): void {
1701
- const settings: DyNTS_AppVersionHeader_Settings | undefined = DyNTS_global_settings.appVersionHeader;
1702
- if (settings?.enabled === false) {
1703
- return;
1704
- }
1705
- express.use(DyNTS_createAppVersionHeaderMiddleware(
1706
- (): string => DyNTS_global_settings.systemVersion,
1707
- settings?.headerName,
1708
- ));
1709
- }
1710
-
1711
- protected mountCors(express: Express.Application): void {
1712
- const settings: DyNTS_Cors_Settings | undefined = this.getCorsSettings?.();
1713
- if (!settings) {
1714
- return;
1715
- }
1716
-
1717
- const allowCreds: boolean = settings.allowCredentials !== false;
1718
- const methods: string[] = settings.allowedMethods ?? [
1719
- 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
1720
- ];
1721
- const headers: string[] = settings.allowedHeaders ?? [
1722
- 'Authorization', 'Content-Type', 'X-Admin-Key', 'X-Requested-With',
1723
- ];
1724
- const exposed: string[] = settings.exposedHeaders ?? [
1725
- 'Content-Length', 'Content-Type',
1726
- ];
1727
- const maxAge: number = settings.maxAgeSeconds ?? 86400;
1728
-
1729
- const isAllowed: (origin: string) => boolean = (origin: string): boolean => {
1730
- if (settings.allowedOrigins === '*') return true;
1731
- if (typeof settings.allowedOrigins === 'function') {
1732
- return settings.allowedOrigins(origin);
1733
- }
1734
- return settings.allowedOrigins.includes(origin);
1735
- };
1736
-
1737
- express.use((req: Express.Request, res: Express.Response, next: Express.NextFunction): void => {
1738
- const origin: string | undefined = req.headers.origin;
1739
- if (origin && isAllowed(origin)) {
1740
- // Echo the matching origin (NOT wildcard) because credentials require it.
1741
- res.setHeader('Access-Control-Allow-Origin', origin);
1742
- if (allowCreds) {
1743
- res.setHeader('Access-Control-Allow-Credentials', 'true');
1744
- }
1745
- res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
1746
- res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
1747
- res.setHeader('Access-Control-Expose-Headers', exposed.join(', '));
1748
- res.setHeader('Access-Control-Max-Age', String(maxAge));
1749
- res.setHeader('Vary', 'Origin');
1750
- }
1751
- if (req.method === 'OPTIONS') {
1752
- res.status(204).end();
1753
- return;
1754
- }
1755
- next();
1756
- });
1757
1468
  }
1758
-
1759
- /**
1760
- * Generikus, auth-agnosztikus extension-point orchestrator. A `registerCustomMiddleware`
1761
- * hookot hívja (ha a subclass override-olja) minden AKTÍV Express instance-ra
1762
- * (open + secure), az API route-ok UTÁN, de a SPA static catch-all (`app.get('*')`)
1763
- * ELŐTT — ez az EGYETLEN korrekt pont egy sub-path middleware-hez (pl. reverse-proxy),
1764
- * mert a catch-all minden utána mountolt route-ot elnyel. No-op ha nincs override (back-compat).
1765
- */
1766
- private async mountCustomMiddleware(): Promise<void> {
1767
- if (!this.registerCustomMiddleware) {
1768
- return;
1769
- }
1770
-
1771
- if (this.openExpress) {
1772
- await this.registerCustomMiddleware(this.openExpress, DyNTS_RouteSecurity.open);
1773
- }
1774
-
1775
- if (this.secureExpress) {
1776
- await this.registerCustomMiddleware(this.secureExpress, DyNTS_RouteSecurity.secure);
1777
- }
1778
-
1779
- if (this.logSetup) {
1780
- DyFM_Log.log('\nCustom middleware registered (pre-static).');
1781
- }
1782
- }
1783
-
1784
- /**
1785
- * Ha getStaticClientSettings() visszaad beállításokat, a client static fájlok a '/' alatt
1786
- * lesznek kiszolgálva (API route-ok után). SPA fallback opcionális (fallbackPath).
1787
- * Asset cache (assetCacheMaxAge, assetCacheImmutable) és fallback cache (fallbackCacheMaxAge)
1788
- * opcionálisak; ha nincs megadva fallbackCacheMaxAge, DyNTS_defaultFallbackCacheMaxAge (0) marad.
1789
- */
1790
- private async mountStaticClient(): Promise<void> {
1791
- const settings: DyNTS_StaticClient_Settings | undefined = this.getStaticClientSettings?.();
1792
- if (!settings) {
1793
- return;
1794
- }
1795
-
1796
- const absoluteRoot: string = Path.isAbsolute(settings.root)
1797
- ? settings.root
1798
- : Path.resolve(process.cwd(), settings.root);
1799
-
1800
- const hasAssetCache: boolean =
1801
- settings.assetCacheMaxAge !== undefined || settings.assetCacheImmutable === true;
1802
- const staticOptions: { setHeaders: (res: Express.Response, filePath: string) => void } | undefined =
1803
- hasAssetCache && settings.assetCacheMaxAge !== undefined
1804
- ? {
1805
- setHeaders: (res: Express.Response, filePath: string): void => {
1806
- // A HTML entry-fájlok (index.html) no-cache-t kapnak, a hash-elt asset-ek
1807
- // immutable long-cache-t — lásd DyNTS_resolveStaticCacheControlHeader (served-stale-index fix).
1808
- res.setHeader(
1809
- 'Cache-Control',
1810
- DyNTS_resolveStaticCacheControlHeader({
1811
- filePath: filePath,
1812
- assetCacheMaxAge: settings.assetCacheMaxAge!,
1813
- assetCacheImmutable: settings.assetCacheImmutable === true,
1814
- }),
1469
+
1470
+ /**
1471
+ *
1472
+ */
1473
+ private async mountSecureRoutes (): Promise<void> {
1474
+ try {
1475
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountSecureRoutes');
1476
+
1477
+ if (!this.secureExpress) {
1478
+ throw new Error(
1479
+ 'secureExpress was not initialized. ' +
1480
+ 'Secure routes require getCertificationSettings and httpsPort, and cert files must exist.' +
1481
+ '\n\nYou need to set security to secure or both in any route and set httpsPort in getPortSettings.' +
1482
+ '\n\nYou need to set cert files in getCertificationSettings.'
1483
+ );
1484
+ }
1485
+
1486
+ this.secureExpress.use(
1487
+ (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1488
+ );
1489
+
1490
+ await DyFM_Array.asyncForEach(
1491
+ this._routingModules,
1492
+ async (module: DyNTS_RoutingModule): Promise<void> => {
1493
+ if (module.security !== DyNTS_RouteSecurity.open) {
1494
+ if (this.logSetup) {
1495
+ DyFM_Log.log(`route mount (secure): ${module.route}`);
1496
+ }
1497
+
1498
+ const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1499
+ (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1500
+ );
1501
+
1502
+ if (1 < existingRoutes.length) {
1503
+ const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1504
+ /* const errorStack: string[] = error.stack.split('\n');
1505
+
1506
+ errorStack.splice(1, 4);
1507
+ error.stack = errorStack.join('\n'); */
1508
+ error.stack = module.stackLocation;
1509
+
1510
+ this.reportSafeDiagnostic(
1511
+ 'DYNTS-AS0-SECURE-ROUTE-DUPLICATION',
1512
+ DyNTS_SafeDiagnosticStage_Type.routing,
1513
+ error
1815
1514
  );
1816
- },
1817
- }
1818
- : undefined;
1819
-
1820
- const staticMiddleware: Express.Handler =
1821
- staticOptions
1822
- ? Express.static(absoluteRoot, staticOptions)
1823
- : Express.static(absoluteRoot);
1824
-
1825
- const fallbackMaxAge: number =
1826
- settings.fallbackCacheMaxAge ?? DyNTS_defaultFallbackCacheMaxAge;
1827
-
1828
- // API-namespace guard (BFR-DYNAMOBUILDER-001): a catch-all fallback NE fedje az API-prefixeket —
1829
- // egy ismeretlen `GET /api/...` 404 JSON-t kapjon, ne megtévesztő `200 + index.html`-t.
1830
- // Konfigurálható (fallbackExcludePrefixes); default a bevett FDP namespace-pár.
1831
- const excludePrefixes: string[] = settings.fallbackExcludePrefixes ?? ['/api', '/auth-api'];
1832
- const isApiNamespacePath = (path: string): boolean =>
1833
- excludePrefixes.some((prefix: string): boolean => path === prefix || path.startsWith(`${prefix}/`));
1834
-
1835
- if (this.openExpress) {
1836
- this.openExpress.use('/', staticMiddleware);
1837
- if (settings.fallbackPath) {
1838
- this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1839
- if (isApiNamespacePath(req.path)) {
1840
- res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1841
- return;
1842
- }
1843
- res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1844
- res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1845
- });
1846
- } else {
1847
- this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1848
- if (isApiNamespacePath(req.path)) {
1849
- res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1850
- return;
1851
- }
1852
- res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1853
- });
1854
- }
1855
- }
1856
-
1857
- if (this.secureExpress) {
1858
- this.secureExpress.use('/', staticMiddleware);
1859
- if (settings.fallbackPath) {
1860
- this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1861
- if (isApiNamespacePath(req.path)) {
1862
- res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1863
- return;
1864
- }
1865
- res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1866
- res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1867
- });
1868
- } else {
1869
- this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1870
- if (isApiNamespacePath(req.path)) {
1871
- res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1872
- return;
1873
- }
1874
- res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1875
- });
1876
- }
1877
- }
1878
-
1879
- if (this.logSetup) {
1880
- DyFM_Log.log(`\nStatic client mounted at / (root: ${absoluteRoot})`);
1881
- }
1882
- }
1883
-
1884
- /**
1885
- *
1886
- */
1887
- private setSecurity(): void {
1888
- if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. setSecurity');
1889
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1890
- if (!module.security) {
1891
- DyFM_Log.warn(`RoutingModule security is not set for ${module.route}\n`);
1892
-
1893
- } else if (!this._security) {
1894
- this._security = module.security;
1895
-
1896
- } else if (this._security !== module.security) {
1897
- this._security = DyNTS_RouteSecurity.both;
1898
- }
1899
- });
1900
-
1901
- if (!this._security) {
1902
- let msg = `Could not set security for the server! (${this.security})`;
1903
-
1904
- msg += '\n RoutingModules:';
1905
- this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1906
- msg += `\n ${module.route} (security: ${module.security})`;
1907
- });
1908
-
1909
- if (this._routingModules.length === 0) {
1910
- msg += '\n - no RoutingModule found -\n';
1911
- }
1912
- DyFM_Log.warn(msg);
1913
- }
1914
- }
1915
-
1916
- private _getDefaultErrorSettings(
1917
- fnName: string,
1918
- error: DyFM_AnyError
1919
- ): DyFM_Error_Settings {
1920
- return {
1921
- status: (error as DyFM_Error)?.___status ?? 500,
1922
- message: (error as Error)?.message ??
1923
- (error as DyFM_Error)?._message ??
1924
- `${fnName} was UNSUCCESSFUL (NTS)`,
1925
- userMessage: (error as DyFM_Error)?.__userMessage ?? this.defaultErrorUserMsg,
1926
- addECToUserMsg: !(error as DyFM_Error)?.__userMessage,
1927
- issuerService: `${this?.constructor?.name}-DyNTS_App`,
1928
- level: DyFM_ErrorLevel.fatal,
1929
- error: error,
1930
- systemVersion: DyNTS_global_settings.systemVersion,
1931
- };
1932
- }
1933
-
1934
- /**
1935
- * MISSING Description (TODO)
1936
- */
1937
- abstract getAppParams(): DyNTS_App_Params;
1938
-
1939
- /**
1940
- * MISSING Description (TODO)
1941
- */
1942
- abstract getGlobalServiceCollection(): DyNTS_GlobalService_Settings;
1943
-
1944
- /**
1945
- * MISSING Description (TODO)
1946
- */
1947
- abstract getPortSettings(): DyNTS_Http_Settings;
1948
-
1949
- /**
1950
- * MISSING Description (TODO)
1951
- */
1952
- overrideDynamoNTSGlobalSettings?(): void;
1953
-
1954
- /**
1955
- * Ha megadva, a visszaadott értéket használjuk a route prefix-ként
1956
- * (DyNTS_global_settings.baseUrl felülírása erre az app-ra).
1957
- */
1958
- getApiBasePath?(): string;
1959
-
1960
- /**
1961
- * MISSING Description (TODO)
1962
- */
1963
- getRoutingModules?(): DyNTS_RoutingModule[];
1964
-
1965
- /**
1966
- * MISSING Description (TODO)
1967
- */
1968
- getRootServices?(): Promise<any[]>;
1969
-
1970
- /**
1971
- * MISSING Description (TODO)
1972
- */
1973
- getCertificationSettings?(): DyNTS_Certification_Settings;
1974
-
1975
- /**
1976
- * Ha megadva, a client static fájlok a '/' alatt lesznek kiszolgálva (API route-ok után).
1977
- * Opcionális fallbackPath pl. SPA index.html-hez.
1978
- */
1979
- getStaticClientSettings?(): DyNTS_StaticClient_Settings | undefined;
1980
-
1981
- /**
1982
- * FR-041 — Ha megadva, CORS middleware mount-olódik mindkét Express instance-ra
1983
- * (open + secure). Az `allowedOrigins` listán szereplő Origin-eket echo-zza vissza,
1984
- * `Access-Control-Allow-Credentials: true`-val (default) együtt a Bearer JWT
1985
- * cross-domain auth flow miatt. OPTIONS preflight 204-gyel rövidre záródik.
1986
- * Ha undefined no CORS headers, no preflight handling — back-compat.
1987
- */
1988
- getCorsSettings?(): DyNTS_Cors_Settings | undefined;
1989
-
1990
- /**
1991
- * Opcionális generikus hook: custom Express middleware regisztrálása az API route-ok
1992
- * UTÁN és a SPA static catch-all ELŐTT. Auth-AGNOSZTIKUS framework extension-point —
1993
- * a subclass (pl. FDP base App) ezen keresztül mount-olhat reverse-proxyt egy sub-path-re
1994
- * (pl. `/auth-api`), ami a `app.get('*')` catch-all elé kell kerüljön. A hívási időzítést
1995
- * lásd: `mountCustomMiddleware`. Undefined → no-op (back-compat).
1996
- */
1997
- registerCustomMiddleware?(
1998
- express: Express.Application,
1999
- security: DyNTS_RouteSecurity,
2000
- ): void | Promise<void>;
2001
-
2002
- /**
2003
- * MISSING Description (TODO)
2004
- */
2005
- createEntries?(): Promise<void>;
2006
-
2007
- /**
2008
- * MISSING Description (TODO)
2009
- */
2010
- postProcess?(): Promise<void>;
2011
-
2012
- }
1515
+
1516
+ throw new DyFM_Error({
1517
+ ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1518
+
1519
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR1`,
1520
+ message: `ROUTE DUPLICATION: ${module.route}`,
1521
+ });
1522
+ }
1523
+
1524
+ this.secureExpress.use(module.route, module.secureRouter);
1525
+ }
1526
+ }
1527
+ );
1528
+ } catch (error) {
1529
+ throw new DyFM_Error({
1530
+ ...this._getDefaultErrorSettings('mountSecureRoutes', error),
1531
+
1532
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MSR0`,
1533
+ });
1534
+ }
1535
+ }
1536
+
1537
+ /**
1538
+ *
1539
+ */
1540
+ private async mountOpenRoutes(): Promise<void> {
1541
+ try {
1542
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. mountOpenRoutes');
1543
+
1544
+ if (!this.openExpress) {
1545
+ throw new Error(
1546
+ 'openExpress was not initialized. Open routes require getOpenExpress and httpPort.' +
1547
+ '\n\nYou need to set security to open or both in any route and set httpPort in getPortSettings.'
1548
+ );
1549
+ }
1550
+
1551
+ this.openExpress.use(
1552
+ (error, req, res, next): Promise<void> => this.expressErrorHandling(error, req, res, next)
1553
+ );
1554
+
1555
+ await DyFM_Array.asyncForEach(
1556
+ this._routingModules,
1557
+ async (module: DyNTS_RoutingModule): Promise<void> => {
1558
+ if (module.security !== DyNTS_RouteSecurity.secure) {
1559
+ if (this.logSetup) {
1560
+ DyFM_Log.log(`route mount (open): ${module.route}`);
1561
+ }
1562
+
1563
+ const existingRoutes: DyNTS_RoutingModule[] = this._routingModules.filter(
1564
+ (mod: DyNTS_RoutingModule): boolean => mod.route === module.route
1565
+ );
1566
+
1567
+ if (1 < existingRoutes.length) {
1568
+ const error: Error = new Error(`ROUTE DUPLICATION: ${module.route}`);
1569
+ /* const errorStack: string[] = error.stack.split('\n');
1570
+
1571
+ errorStack.splice(1, 4);
1572
+ error.stack = errorStack.join('\n'); */
1573
+ error.stack = module.stackLocation;
1574
+
1575
+ this.reportSafeDiagnostic(
1576
+ 'DYNTS-AS0-OPEN-ROUTE-DUPLICATION',
1577
+ DyNTS_SafeDiagnosticStage_Type.routing,
1578
+ error
1579
+ );
1580
+
1581
+ throw new DyFM_Error({
1582
+ ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1583
+
1584
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR1`,
1585
+ message: `ROUTE DUPLICATION: ${module.route}`,
1586
+ });
1587
+ }
1588
+
1589
+ this.openExpress.use(module.route, module.openRouter);
1590
+ }
1591
+ }
1592
+ );
1593
+ } catch (error) {
1594
+ throw new DyFM_Error({
1595
+ ...this._getDefaultErrorSettings('mountOpenRoutes', error),
1596
+
1597
+ errorCode: `${DyNTS_global_settings.systemShortCodeName}|DyNTS-AS0-MOR0`,
1598
+ });
1599
+ }
1600
+ }
1601
+
1602
+ /**
1603
+ * FR-041 — CORS middleware. Echoes a matching `Access-Control-Allow-Origin`
1604
+ * for any request whose Origin header is in `getCorsSettings().allowedOrigins`,
1605
+ * adds the canonical `Access-Control-*` companion headers, and short-circuits
1606
+ * the OPTIONS preflight with a 204.
1607
+ *
1608
+ * No-op when the subclass does NOT override `getCorsSettings()` — preserves
1609
+ * back-compat for apps that have always been same-origin and never needed
1610
+ * CORS (the typical pre-FR-041 case).
1611
+ *
1612
+ * Why hand-rolled instead of the `cors` npm package:
1613
+ * - ~30 lines, zero new dependency.
1614
+ * - Full control over Vary/credentials/preflight semantics.
1615
+ * - Aligns with FDP "no unnecessary deps" philosophy.
1616
+ */
1617
+ /**
1618
+ * BFR-011 / SEC-R2-8 — security response-headerek mountolása (a `mountCors` tükörképe).
1619
+ * A `DyNTS_global_settings.securityHeaders` alapján (default-ON) minden válaszra ráteszi a
1620
+ * biztonsági headereket + eltávolítja az `x-powered-by`-t. A CORS-mount ELŐTT hívandó, hogy az
1621
+ * OPTIONS preflight-válaszok (amiket a mountCors 204-gyel rövidre zár) is megkapják.
1622
+ */
1623
+ protected mountSecurityHeaders(express: Express.Application): void {
1624
+ const settings: DyNTS_SecurityHeaders_Settings | undefined = DyNTS_global_settings.securityHeaders;
1625
+ if (!settings || !settings.enabled) {
1626
+ return;
1627
+ }
1628
+
1629
+ if (settings.removePoweredBy !== false) {
1630
+ express.disable('x-powered-by');
1631
+ }
1632
+
1633
+ express.use(DyNTS_createSecurityHeadersMiddleware(
1634
+ settings,
1635
+ DyNTS_getEnvironment_settings().environment,
1636
+ ));
1637
+ }
1638
+
1639
+ /**
1640
+ * FR-292 — a deployolt app-verziot minden valaszra rateszi (`X-App-Version`), hogy a
1641
+ * bongeszoben NYITVA HAGYOTT SPA eszrevegye, ha kozben ujabb kliens-build ment ki.
1642
+ *
1643
+ * Nem polling: a jelzes a MAR MENO API-hivasokon utazik. Az `enabled` default TRUE — egy
1644
+ * informativ response-header, ami se PII-t, se belso reszletet nem szivarogtat, viszont
1645
+ * enelkul minden app kulon-kulon epitene ugyanezt.
1646
+ */
1647
+ protected mountAppVersionHeader(express: Express.Application): void {
1648
+ const settings: DyNTS_AppVersionHeader_Settings | undefined = DyNTS_global_settings.appVersionHeader;
1649
+ if (settings?.enabled === false) {
1650
+ return;
1651
+ }
1652
+ express.use(DyNTS_createAppVersionHeaderMiddleware(
1653
+ (): string => DyNTS_global_settings.systemVersion,
1654
+ settings?.headerName,
1655
+ ));
1656
+ }
1657
+
1658
+ protected mountCors(express: Express.Application): void {
1659
+ const settings: DyNTS_Cors_Settings | undefined = this.getCorsSettings?.();
1660
+ if (!settings) {
1661
+ return;
1662
+ }
1663
+
1664
+ const allowCreds: boolean = settings.allowCredentials !== false;
1665
+ const methods: string[] = settings.allowedMethods ?? [
1666
+ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS',
1667
+ ];
1668
+ const headers: string[] = settings.allowedHeaders ?? [
1669
+ 'Authorization', 'Content-Type', 'X-Admin-Key', 'X-Requested-With',
1670
+ ];
1671
+ const exposed: string[] = settings.exposedHeaders ?? [
1672
+ 'Content-Length', 'Content-Type',
1673
+ ];
1674
+ const maxAge: number = settings.maxAgeSeconds ?? 86400;
1675
+
1676
+ const isAllowed: (origin: string) => boolean = (origin: string): boolean => {
1677
+ if (settings.allowedOrigins === '*') return true;
1678
+ if (typeof settings.allowedOrigins === 'function') {
1679
+ return settings.allowedOrigins(origin);
1680
+ }
1681
+ return settings.allowedOrigins.includes(origin);
1682
+ };
1683
+
1684
+ express.use((req: Express.Request, res: Express.Response, next: Express.NextFunction): void => {
1685
+ const origin: string | undefined = req.headers.origin;
1686
+ if (origin && isAllowed(origin)) {
1687
+ // Echo the matching origin (NOT wildcard) because credentials require it.
1688
+ res.setHeader('Access-Control-Allow-Origin', origin);
1689
+ if (allowCreds) {
1690
+ res.setHeader('Access-Control-Allow-Credentials', 'true');
1691
+ }
1692
+ res.setHeader('Access-Control-Allow-Methods', methods.join(', '));
1693
+ res.setHeader('Access-Control-Allow-Headers', headers.join(', '));
1694
+ res.setHeader('Access-Control-Expose-Headers', exposed.join(', '));
1695
+ res.setHeader('Access-Control-Max-Age', String(maxAge));
1696
+ res.setHeader('Vary', 'Origin');
1697
+ }
1698
+ if (req.method === 'OPTIONS') {
1699
+ res.status(204).end();
1700
+ return;
1701
+ }
1702
+ next();
1703
+ });
1704
+ }
1705
+
1706
+ /**
1707
+ * Generikus, auth-agnosztikus extension-point orchestrator. A `registerCustomMiddleware`
1708
+ * hookot hívja (ha a subclass override-olja) minden AKTÍV Express instance-ra
1709
+ * (open + secure), az API route-ok UTÁN, de a SPA static catch-all (`app.get('*')`)
1710
+ * ELŐTT — ez az EGYETLEN korrekt pont egy sub-path middleware-hez (pl. reverse-proxy),
1711
+ * mert a catch-all minden utána mountolt route-ot elnyel. No-op ha nincs override (back-compat).
1712
+ */
1713
+ private async mountCustomMiddleware(): Promise<void> {
1714
+ if (!this.registerCustomMiddleware) {
1715
+ return;
1716
+ }
1717
+
1718
+ if (this.openExpress) {
1719
+ await this.registerCustomMiddleware(this.openExpress, DyNTS_RouteSecurity.open);
1720
+ }
1721
+
1722
+ if (this.secureExpress) {
1723
+ await this.registerCustomMiddleware(this.secureExpress, DyNTS_RouteSecurity.secure);
1724
+ }
1725
+
1726
+ if (this.logSetup) {
1727
+ DyFM_Log.log('\nCustom middleware registered (pre-static).');
1728
+ }
1729
+ }
1730
+
1731
+ /**
1732
+ * Ha getStaticClientSettings() visszaad beállításokat, a client static fájlok a '/' alatt
1733
+ * lesznek kiszolgálva (API route-ok után). SPA fallback opcionális (fallbackPath).
1734
+ * Asset cache (assetCacheMaxAge, assetCacheImmutable) és fallback cache (fallbackCacheMaxAge)
1735
+ * opcionálisak; ha nincs megadva fallbackCacheMaxAge, DyNTS_defaultFallbackCacheMaxAge (0) marad.
1736
+ */
1737
+ private async mountStaticClient(): Promise<void> {
1738
+ const settings: DyNTS_StaticClient_Settings | undefined = this.getStaticClientSettings?.();
1739
+ if (!settings) {
1740
+ return;
1741
+ }
1742
+
1743
+ const absoluteRoot: string = Path.isAbsolute(settings.root)
1744
+ ? settings.root
1745
+ : Path.resolve(process.cwd(), settings.root);
1746
+
1747
+ const hasAssetCache: boolean =
1748
+ settings.assetCacheMaxAge !== undefined || settings.assetCacheImmutable === true;
1749
+ const staticOptions: { setHeaders: (res: Express.Response, filePath: string) => void } | undefined =
1750
+ hasAssetCache && settings.assetCacheMaxAge !== undefined
1751
+ ? {
1752
+ setHeaders: (res: Express.Response, filePath: string): void => {
1753
+ // A HTML entry-fájlok (index.html) no-cache-t kapnak, a hash-elt asset-ek
1754
+ // immutable long-cache-t — lásd DyNTS_resolveStaticCacheControlHeader (served-stale-index fix).
1755
+ res.setHeader(
1756
+ 'Cache-Control',
1757
+ DyNTS_resolveStaticCacheControlHeader({
1758
+ filePath: filePath,
1759
+ assetCacheMaxAge: settings.assetCacheMaxAge!,
1760
+ assetCacheImmutable: settings.assetCacheImmutable === true,
1761
+ }),
1762
+ );
1763
+ },
1764
+ }
1765
+ : undefined;
1766
+
1767
+ const staticMiddleware: Express.Handler =
1768
+ staticOptions
1769
+ ? Express.static(absoluteRoot, staticOptions)
1770
+ : Express.static(absoluteRoot);
1771
+
1772
+ const fallbackMaxAge: number =
1773
+ settings.fallbackCacheMaxAge ?? DyNTS_defaultFallbackCacheMaxAge;
1774
+
1775
+ // API-namespace guard (BFR-DYNAMOBUILDER-001): a catch-all fallback NE fedje az API-prefixeket —
1776
+ // egy ismeretlen `GET /api/...` 404 JSON-t kapjon, ne megtévesztő `200 + index.html`-t.
1777
+ // Konfigurálható (fallbackExcludePrefixes); default a bevett FDP namespace-pár.
1778
+ const excludePrefixes: string[] = settings.fallbackExcludePrefixes ?? ['/api', '/auth-api'];
1779
+ const isApiNamespacePath = (path: string): boolean =>
1780
+ excludePrefixes.some((prefix: string): boolean => path === prefix || path.startsWith(`${prefix}/`));
1781
+
1782
+ if (this.openExpress) {
1783
+ this.openExpress.use('/', staticMiddleware);
1784
+ if (settings.fallbackPath) {
1785
+ this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1786
+ if (isApiNamespacePath(req.path)) {
1787
+ res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1788
+ return;
1789
+ }
1790
+ res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1791
+ res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1792
+ });
1793
+ } else {
1794
+ this.openExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1795
+ if (isApiNamespacePath(req.path)) {
1796
+ res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1797
+ return;
1798
+ }
1799
+ res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1800
+ });
1801
+ }
1802
+ }
1803
+
1804
+ if (this.secureExpress) {
1805
+ this.secureExpress.use('/', staticMiddleware);
1806
+ if (settings.fallbackPath) {
1807
+ this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1808
+ if (isApiNamespacePath(req.path)) {
1809
+ res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1810
+ return;
1811
+ }
1812
+ res.setHeader('Cache-Control', `max-age=${fallbackMaxAge}`);
1813
+ res.sendFile(settings.fallbackPath!, { root: absoluteRoot });
1814
+ });
1815
+ } else {
1816
+ this.secureExpress.get('*', (req: Express.Request, res: Express.Response): void => {
1817
+ if (isApiNamespacePath(req.path)) {
1818
+ res.status(404).send({ message: `Unknown API endpoint: ${req.path}` });
1819
+ return;
1820
+ }
1821
+ res.status(404).type('html').send(DyNTS_defaultNotFoundPageHtml);
1822
+ });
1823
+ }
1824
+ }
1825
+
1826
+ if (this.logSetup) {
1827
+ DyFM_Log.log(`\nStatic client mounted at / (root: ${absoluteRoot})`);
1828
+ }
1829
+ }
1830
+
1831
+ /**
1832
+ *
1833
+ */
1834
+ private setSecurity(): void {
1835
+ if (this.fnLogs && this.deepLog) DyFM_Log.log('\nfn:. setSecurity');
1836
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1837
+ if (!module.security) {
1838
+ DyFM_Log.warn(`RoutingModule security is not set for ${module.route}\n`);
1839
+
1840
+ } else if (!this._security) {
1841
+ this._security = module.security;
1842
+
1843
+ } else if (this._security !== module.security) {
1844
+ this._security = DyNTS_RouteSecurity.both;
1845
+ }
1846
+ });
1847
+
1848
+ if (!this._security) {
1849
+ let msg = `Could not set security for the server! (${this.security})`;
1850
+
1851
+ msg += '\n RoutingModules:';
1852
+ this._routingModules.forEach((module: DyNTS_RoutingModule): void => {
1853
+ msg += `\n ${module.route} (security: ${module.security})`;
1854
+ });
1855
+
1856
+ if (this._routingModules.length === 0) {
1857
+ msg += '\n - no RoutingModule found -\n';
1858
+ }
1859
+ DyFM_Log.warn(msg);
1860
+ }
1861
+ }
1862
+
1863
+ private _getDefaultErrorSettings(
1864
+ fnName: string,
1865
+ error: DyFM_AnyError
1866
+ ): DyFM_Error_Settings {
1867
+ return {
1868
+ status: (error as DyFM_Error)?.___status ?? 500,
1869
+ message: (error as Error)?.message ??
1870
+ (error as DyFM_Error)?._message ??
1871
+ `${fnName} was UNSUCCESSFUL (NTS)`,
1872
+ userMessage: (error as DyFM_Error)?.__userMessage ?? this.defaultErrorUserMsg,
1873
+ addECToUserMsg: !(error as DyFM_Error)?.__userMessage,
1874
+ issuerService: `${this?.constructor?.name}-DyNTS_App`,
1875
+ level: DyFM_ErrorLevel.fatal,
1876
+ error: error,
1877
+ systemVersion: DyNTS_global_settings.systemVersion,
1878
+ };
1879
+ }
1880
+
1881
+ /**
1882
+ * MISSING Description (TODO)
1883
+ */
1884
+ abstract getAppParams(): DyNTS_App_Params;
1885
+
1886
+ /**
1887
+ * MISSING Description (TODO)
1888
+ */
1889
+ abstract getGlobalServiceCollection(): DyNTS_GlobalService_Settings;
1890
+
1891
+ /**
1892
+ * MISSING Description (TODO)
1893
+ */
1894
+ abstract getPortSettings(): DyNTS_Http_Settings;
1895
+
1896
+ /**
1897
+ * MISSING Description (TODO)
1898
+ */
1899
+ overrideDynamoNTSGlobalSettings?(): void;
1900
+
1901
+ /**
1902
+ * Ha megadva, a visszaadott értéket használjuk a route prefix-ként
1903
+ * (DyNTS_global_settings.baseUrl felülírása erre az app-ra).
1904
+ */
1905
+ getApiBasePath?(): string;
1906
+
1907
+ /**
1908
+ * MISSING Description (TODO)
1909
+ */
1910
+ getRoutingModules?(): DyNTS_RoutingModule[];
1911
+
1912
+ /**
1913
+ * MISSING Description (TODO)
1914
+ */
1915
+ getRootServices?(): Promise<any[]>;
1916
+
1917
+ /**
1918
+ * MISSING Description (TODO)
1919
+ */
1920
+ getCertificationSettings?(): DyNTS_Certification_Settings;
1921
+
1922
+ /**
1923
+ * Ha megadva, a client static fájlok a '/' alatt lesznek kiszolgálva (API route-ok után).
1924
+ * Opcionális fallbackPath pl. SPA index.html-hez.
1925
+ */
1926
+ getStaticClientSettings?(): DyNTS_StaticClient_Settings | undefined;
1927
+
1928
+ /**
1929
+ * FR-041 — Ha megadva, CORS middleware mount-olódik mindkét Express instance-ra
1930
+ * (open + secure). Az `allowedOrigins` listán szereplő Origin-eket echo-zza vissza,
1931
+ * `Access-Control-Allow-Credentials: true`-val (default) együtt a Bearer JWT
1932
+ * cross-domain auth flow miatt. OPTIONS preflight 204-gyel rövidre záródik.
1933
+ * Ha undefined → no CORS headers, no preflight handling — back-compat.
1934
+ */
1935
+ getCorsSettings?(): DyNTS_Cors_Settings | undefined;
1936
+
1937
+ /**
1938
+ * Opcionális generikus hook: custom Express middleware regisztrálása az API route-ok
1939
+ * UTÁN és a SPA static catch-all ELŐTT. Auth-AGNOSZTIKUS framework extension-point —
1940
+ * a subclass (pl. FDP base App) ezen keresztül mount-olhat reverse-proxyt egy sub-path-re
1941
+ * (pl. `/auth-api`), ami a `app.get('*')` catch-all elé kell kerüljön. A hívási időzítést
1942
+ * lásd: `mountCustomMiddleware`. Undefined → no-op (back-compat).
1943
+ */
1944
+ registerCustomMiddleware?(
1945
+ express: Express.Application,
1946
+ security: DyNTS_RouteSecurity,
1947
+ ): void | Promise<void>;
1948
+
1949
+ /**
1950
+ * MISSING Description (TODO)
1951
+ */
1952
+ createEntries?(): Promise<void>;
1953
+
1954
+ /**
1955
+ * MISSING Description (TODO)
1956
+ */
1957
+ postProcess?(): Promise<void>;
1958
+
1959
+ }