@omnizap-system/omnizap 2.5.12

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 (425) hide show
  1. package/.clusterfuzzlite/Dockerfile +10 -0
  2. package/.env.example +907 -0
  3. package/.github/codeql/codeql-config.yml +10 -0
  4. package/.github/dependabot.yml +35 -0
  5. package/.github/workflows/ci.yml +73 -0
  6. package/.github/workflows/codeql.yml +106 -0
  7. package/.github/workflows/db-migration-check.yml +98 -0
  8. package/.github/workflows/dependency-review.yml +22 -0
  9. package/.github/workflows/deploy.yml +95 -0
  10. package/.github/workflows/release.yml +106 -0
  11. package/.github/workflows/security-attest-provenance.yml +51 -0
  12. package/.github/workflows/security-gitleaks.yml +34 -0
  13. package/.github/workflows/security-runner-hardening.yml +31 -0
  14. package/.github/workflows/security-scorecard.yml +44 -0
  15. package/.github/workflows/security-zap-baseline.yml +44 -0
  16. package/.github/workflows/security-zap-full-scan.yml +43 -0
  17. package/.github/workflows/security-zizmor.yml +36 -0
  18. package/.github/workflows/wiki-sync.yml +44 -0
  19. package/.gitleaks.toml +15 -0
  20. package/.prettierrc +34 -0
  21. package/CODE_OF_CONDUCT.md +114 -0
  22. package/LICENSE +56 -0
  23. package/README.md +110 -0
  24. package/SECURITY.md +110 -0
  25. package/app/config/index.js +4 -0
  26. package/app/configParts/adminIdentity.js +92 -0
  27. package/app/configParts/baileysConfig.js +1818 -0
  28. package/app/configParts/groupUtils.js +692 -0
  29. package/app/configParts/loggerConfig.js +394 -0
  30. package/app/configParts/messagePersistenceService.js +305 -0
  31. package/app/connection/baileysCompatibility.test.js +40 -0
  32. package/app/connection/baileysDbAuthState.js +344 -0
  33. package/app/connection/socketController.js +2243 -0
  34. package/app/controllers/messageController.js +7 -0
  35. package/app/controllers/messagePipeline/commandMiddleware.js +146 -0
  36. package/app/controllers/messagePipeline/conversationMiddleware.js +183 -0
  37. package/app/controllers/messagePipeline/messagePipelineMiddlewares.test.js +522 -0
  38. package/app/controllers/messagePipeline/postProcessingMiddleware.js +41 -0
  39. package/app/controllers/messagePipeline/preProcessingMiddlewares.js +166 -0
  40. package/app/controllers/messageProcessingPipeline.js +699 -0
  41. package/app/modules/adminModule/AGENT.md +4056 -0
  42. package/app/modules/adminModule/adminAiHelpService.js +56 -0
  43. package/app/modules/adminModule/adminConfigRuntime.js +177 -0
  44. package/app/modules/adminModule/commandConfig.json +7122 -0
  45. package/app/modules/adminModule/groupCommandHandlers.js +1823 -0
  46. package/app/modules/adminModule/groupCommandHandlers.test.js +350 -0
  47. package/app/modules/adminModule/groupEventHandlers.js +399 -0
  48. package/app/modules/aiModule/AGENT.md +547 -0
  49. package/app/modules/aiModule/aiAiHelpService.js +14 -0
  50. package/app/modules/aiModule/aiConfigRuntime.js +135 -0
  51. package/app/modules/aiModule/catCommand.js +967 -0
  52. package/app/modules/aiModule/commandConfig.json +981 -0
  53. package/app/modules/analyticsModule/messageAnalysisEventRepository.js +83 -0
  54. package/app/modules/gameModule/AGENT.md +196 -0
  55. package/app/modules/gameModule/commandConfig.json +366 -0
  56. package/app/modules/gameModule/diceCommand.js +42 -0
  57. package/app/modules/gameModule/gameAiHelpService.js +14 -0
  58. package/app/modules/gameModule/gameConfigRuntime.js +68 -0
  59. package/app/modules/menuModule/AGENT.md +205 -0
  60. package/app/modules/menuModule/commandConfig.json +366 -0
  61. package/app/modules/menuModule/common.js +316 -0
  62. package/app/modules/menuModule/menuAiHelpService.js +14 -0
  63. package/app/modules/menuModule/menuConfigRuntime.js +68 -0
  64. package/app/modules/menuModule/menus.js +66 -0
  65. package/app/modules/playModule/AGENT.md +321 -0
  66. package/app/modules/playModule/commandConfig.json +584 -0
  67. package/app/modules/playModule/playAiHelpService.js +14 -0
  68. package/app/modules/playModule/playCommand.js +1417 -0
  69. package/app/modules/playModule/playConfigRuntime.js +68 -0
  70. package/app/modules/quoteModule/AGENT.md +199 -0
  71. package/app/modules/quoteModule/commandConfig.json +366 -0
  72. package/app/modules/quoteModule/quoteAiHelpService.js +14 -0
  73. package/app/modules/quoteModule/quoteCommand.js +842 -0
  74. package/app/modules/quoteModule/quoteConfigRuntime.js +68 -0
  75. package/app/modules/rpgPokemonModule/AGENT.md +229 -0
  76. package/app/modules/rpgPokemonModule/commandConfig.json +386 -0
  77. package/app/modules/rpgPokemonModule/rpgBattleCanvasRenderer.js +795 -0
  78. package/app/modules/rpgPokemonModule/rpgBattleService.js +2110 -0
  79. package/app/modules/rpgPokemonModule/rpgBattleService.test.js +770 -0
  80. package/app/modules/rpgPokemonModule/rpgEvolutionUtils.js +22 -0
  81. package/app/modules/rpgPokemonModule/rpgPokemonAiHelpService.js +14 -0
  82. package/app/modules/rpgPokemonModule/rpgPokemonCommand.js +174 -0
  83. package/app/modules/rpgPokemonModule/rpgPokemonConfigRuntime.js +68 -0
  84. package/app/modules/rpgPokemonModule/rpgPokemonDomain.js +192 -0
  85. package/app/modules/rpgPokemonModule/rpgPokemonDomain.test.js +93 -0
  86. package/app/modules/rpgPokemonModule/rpgPokemonEvolution.test.js +46 -0
  87. package/app/modules/rpgPokemonModule/rpgPokemonMessages.js +746 -0
  88. package/app/modules/rpgPokemonModule/rpgPokemonRepository.js +1847 -0
  89. package/app/modules/rpgPokemonModule/rpgPokemonService.js +6839 -0
  90. package/app/modules/rpgPokemonModule/rpgProfileCanvasRenderer.js +354 -0
  91. package/app/modules/statsModule/AGENT.md +320 -0
  92. package/app/modules/statsModule/commandConfig.json +540 -0
  93. package/app/modules/statsModule/globalRankingCommand.js +64 -0
  94. package/app/modules/statsModule/rankingCommand.js +41 -0
  95. package/app/modules/statsModule/rankingCommon.js +1305 -0
  96. package/app/modules/statsModule/statsAiHelpService.js +14 -0
  97. package/app/modules/statsModule/statsConfigRuntime.js +68 -0
  98. package/app/modules/stickerModule/AGENT.md +692 -0
  99. package/app/modules/stickerModule/addStickerMetadata.js +239 -0
  100. package/app/modules/stickerModule/commandConfig.json +1216 -0
  101. package/app/modules/stickerModule/convertToWebp.js +367 -0
  102. package/app/modules/stickerModule/stickerAiHelpService.js +14 -0
  103. package/app/modules/stickerModule/stickerCommand.js +446 -0
  104. package/app/modules/stickerModule/stickerConfigRuntime.js +68 -0
  105. package/app/modules/stickerModule/stickerConvertCommand.js +159 -0
  106. package/app/modules/stickerModule/stickerTextCommand.js +653 -0
  107. package/app/modules/stickerPackModule/AGENT.md +215 -0
  108. package/app/modules/stickerPackModule/autoPackCollectorRuntime.js +20 -0
  109. package/app/modules/stickerPackModule/autoPackCollectorService.js +357 -0
  110. package/app/modules/stickerPackModule/commandConfig.json +387 -0
  111. package/app/modules/stickerPackModule/domainEventOutboxRepository.js +227 -0
  112. package/app/modules/stickerPackModule/domainEvents.js +52 -0
  113. package/app/modules/stickerPackModule/semanticReclassificationEngine.js +429 -0
  114. package/app/modules/stickerPackModule/semanticReclassificationEngine.test.js +75 -0
  115. package/app/modules/stickerPackModule/semanticThemeClusterService.js +544 -0
  116. package/app/modules/stickerPackModule/stickerAssetClassificationRepository.js +400 -0
  117. package/app/modules/stickerPackModule/stickerAssetRepository.js +400 -0
  118. package/app/modules/stickerPackModule/stickerAssetReprocessQueueRepository.js +175 -0
  119. package/app/modules/stickerPackModule/stickerAutoPackByTagsRuntime.js +3702 -0
  120. package/app/modules/stickerPackModule/stickerClassificationBackgroundRuntime.js +559 -0
  121. package/app/modules/stickerPackModule/stickerClassificationService.js +557 -0
  122. package/app/modules/stickerPackModule/stickerDedicatedTaskWorkerRuntime.js +249 -0
  123. package/app/modules/stickerPackModule/stickerDomainEventBus.js +65 -0
  124. package/app/modules/stickerPackModule/stickerDomainEventConsumerRuntime.js +208 -0
  125. package/app/modules/stickerPackModule/stickerMarketplaceDriftService.js +99 -0
  126. package/app/modules/stickerPackModule/stickerObjectStorageService.js +285 -0
  127. package/app/modules/stickerPackModule/stickerPackAiHelpService.js +14 -0
  128. package/app/modules/stickerPackModule/stickerPackCommandHandlers.js +1148 -0
  129. package/app/modules/stickerPackModule/stickerPackConfigRuntime.js +68 -0
  130. package/app/modules/stickerPackModule/stickerPackEngagementRepository.js +152 -0
  131. package/app/modules/stickerPackModule/stickerPackErrors.js +30 -0
  132. package/app/modules/stickerPackModule/stickerPackInteractionEventRepository.js +101 -0
  133. package/app/modules/stickerPackModule/stickerPackItemRepository.js +432 -0
  134. package/app/modules/stickerPackModule/stickerPackMarketplaceService.js +313 -0
  135. package/app/modules/stickerPackModule/stickerPackMessageService.js +268 -0
  136. package/app/modules/stickerPackModule/stickerPackRepository.js +450 -0
  137. package/app/modules/stickerPackModule/stickerPackScoreSnapshotRepository.js +179 -0
  138. package/app/modules/stickerPackModule/stickerPackScoreSnapshotRuntime.js +271 -0
  139. package/app/modules/stickerPackModule/stickerPackService.js +733 -0
  140. package/app/modules/stickerPackModule/stickerPackServiceRuntime.js +32 -0
  141. package/app/modules/stickerPackModule/stickerPackUtils.js +107 -0
  142. package/app/modules/stickerPackModule/stickerStorageService.js +559 -0
  143. package/app/modules/stickerPackModule/stickerWorkerPipelineRuntime.js +242 -0
  144. package/app/modules/stickerPackModule/stickerWorkerTaskQueueRepository.js +242 -0
  145. package/app/modules/systemMetricsModule/AGENT.md +193 -0
  146. package/app/modules/systemMetricsModule/commandConfig.json +344 -0
  147. package/app/modules/systemMetricsModule/pingCommand.js +399 -0
  148. package/app/modules/systemMetricsModule/systemMetricsAiHelpService.js +14 -0
  149. package/app/modules/systemMetricsModule/systemMetricsConfigRuntime.js +68 -0
  150. package/app/modules/tiktokModule/AGENT.md +196 -0
  151. package/app/modules/tiktokModule/commandConfig.json +366 -0
  152. package/app/modules/tiktokModule/tiktokAiHelpService.js +14 -0
  153. package/app/modules/tiktokModule/tiktokCommand.js +716 -0
  154. package/app/modules/tiktokModule/tiktokConfigRuntime.js +68 -0
  155. package/app/modules/userModule/AGENT.md +200 -0
  156. package/app/modules/userModule/commandConfig.json +386 -0
  157. package/app/modules/userModule/userAiHelpService.js +14 -0
  158. package/app/modules/userModule/userCommand.js +1155 -0
  159. package/app/modules/userModule/userConfigRuntime.js +68 -0
  160. package/app/modules/waifuPicsModule/AGENT.md +431 -0
  161. package/app/modules/waifuPicsModule/commandConfig.json +780 -0
  162. package/app/modules/waifuPicsModule/waifuPicsAiHelpService.js +14 -0
  163. package/app/modules/waifuPicsModule/waifuPicsCommand.js +586 -0
  164. package/app/modules/waifuPicsModule/waifuPicsConfigRuntime.js +68 -0
  165. package/app/observability/metrics.js +766 -0
  166. package/app/services/ai/aiHelpResponseCacheRepository.js +280 -0
  167. package/app/services/ai/aiLearningRepository.js +400 -0
  168. package/app/services/ai/commandConfigEnrichmentRepository.js +769 -0
  169. package/app/services/ai/commandConfigEnrichmentService.js +452 -0
  170. package/app/services/ai/commandConfigValidationService.js +443 -0
  171. package/app/services/ai/commandToolBuilderService.js +192 -0
  172. package/app/services/ai/conversationRouterService.js +516 -0
  173. package/app/services/ai/geminiService.js +115 -0
  174. package/app/services/ai/geminiService.test.js +87 -0
  175. package/app/services/ai/globalModuleAiHelpService.js +1412 -0
  176. package/app/services/ai/globalToolCallingService.js +203 -0
  177. package/app/services/ai/messageCommandExecutionService.js +391 -0
  178. package/app/services/ai/moduleAiHelpCoreService.js +1099 -0
  179. package/app/services/ai/moduleAiHelpWrapperFactory.js +65 -0
  180. package/app/services/ai/moduleCommandConfigRuntimeService.js +113 -0
  181. package/app/services/ai/moduleToolExecutorService.js +464 -0
  182. package/app/services/ai/moduleToolRegistryService.js +178 -0
  183. package/app/services/ai/toolCandidateSelectorService.js +781 -0
  184. package/app/services/auth/googleWebLinkService.js +80 -0
  185. package/app/services/auth/whatsappLoginLinkService.js +230 -0
  186. package/app/services/external/pokeApiService.js +398 -0
  187. package/app/services/group/groupMetadataService.js +311 -0
  188. package/app/services/infra/dbWriteQueue.js +874 -0
  189. package/app/services/infra/featureFlagService.js +131 -0
  190. package/app/services/infra/queueUtils.js +55 -0
  191. package/app/services/messaging/captchaService.js +491 -0
  192. package/app/services/messaging/messagePersistenceService.js +1 -0
  193. package/app/services/messaging/newsBroadcastService.js +347 -0
  194. package/app/services/sticker/stickerFocusService.js +347 -0
  195. package/app/services/sticker/stickerFocusService.test.js +43 -0
  196. package/app/store/aiPromptStore.js +38 -0
  197. package/app/store/conversationSessionStore.js +131 -0
  198. package/app/store/groupConfigStore.js +58 -0
  199. package/app/store/premiumUserStore.js +54 -0
  200. package/app/utils/antiLink/antiLinkModule.js +700 -0
  201. package/app/utils/http/getImageBufferModule.js +18 -0
  202. package/app/utils/json/jsonSanitizer.js +113 -0
  203. package/app/utils/json/jsonSanitizer.test.js +40 -0
  204. package/app/utils/systemMetrics/systemMetricsModule.js +88 -0
  205. package/app/workers/aiLearningWorker.js +605 -0
  206. package/app/workers/commandConfigEnrichmentWorker.js +242 -0
  207. package/database/index.js +2075 -0
  208. package/database/init.js +151 -0
  209. package/database/migrations/.gitkeep +0 -0
  210. package/database/migrations/20260307_d0_hardening_down.sql +64 -0
  211. package/database/migrations/20260307_d0_hardening_up.sql +79 -0
  212. package/database/migrations/20260307_d1_terms_acceptance_down.sql +11 -0
  213. package/database/migrations/20260307_d1_terms_acceptance_up.sql +37 -0
  214. package/database/migrations/20260307_d2_auth_hardening_down.sql +75 -0
  215. package/database/migrations/20260307_d2_auth_hardening_up.sql +100 -0
  216. package/database/migrations/20260314_d7_canonical_sender_down.sql +53 -0
  217. package/database/migrations/20260314_d7_canonical_sender_up.sql +114 -0
  218. package/database/migrations/20260406_d30_security_analytics_down.sql +95 -0
  219. package/database/migrations/20260406_d30_security_analytics_up.sql +292 -0
  220. package/database/migrations/20260407_d31_web_google_session_token_hardening_down.sql +2 -0
  221. package/database/migrations/20260407_d31_web_google_session_token_hardening_up.sql +17 -0
  222. package/database/migrations/20260408_d32_ai_help_response_cache_down.sql +1 -0
  223. package/database/migrations/20260408_d32_ai_help_response_cache_up.sql +22 -0
  224. package/database/migrations/20260409_d33_ai_learning_tables_down.sql +4 -0
  225. package/database/migrations/20260409_d33_ai_learning_tables_up.sql +52 -0
  226. package/database/migrations/20260410_d34_command_config_enrichment_down.sql +3 -0
  227. package/database/migrations/20260410_d34_command_config_enrichment_up.sql +48 -0
  228. package/database/schema.sql +1186 -0
  229. package/docker-compose.yml +104 -0
  230. package/docs/audits/stickerCatalogController-out-of-scope.md +103 -0
  231. package/docs/audits/stickerCatalogController-symbols.md +58 -0
  232. package/docs/compliance/acceptable-use-policy-2026-03-07.md +35 -0
  233. package/docs/compliance/dpa-b2b-standard-2026-03-07.md +80 -0
  234. package/docs/compliance/monthly-compliance-checklist-2026-03-07.md +88 -0
  235. package/docs/compliance/notice-and-takedown-policy-2026-03-07.md +34 -0
  236. package/docs/compliance/privacy-policy-2026-03-07.md +75 -0
  237. package/docs/compliance/subprocessors-inventory-2026-03-07.md +16 -0
  238. package/docs/database/production-db-evolution-runbook-2026q1.md +365 -0
  239. package/docs/security/dsar-lgpd-runbook-2026-03-07.md +86 -0
  240. package/docs/security/incident-response-lgpd-anpd-runbook-2026-03-07.md +77 -0
  241. package/docs/security/network-hardening-runbook-2026-03-07.md +137 -0
  242. package/docs/seo/omnizap-seo-playbook-br-2026-02-28.md +238 -0
  243. package/docs/seo/satellite-page-template.md +116 -0
  244. package/docs/seo/satellite-pages-phase1.json +364 -0
  245. package/docs/wiki/Home.md +120 -0
  246. package/docs/wiki/pair-extraordinaire-2026-03-08.md +3 -0
  247. package/docs/wiki/recent-changes-2026-03-08.md +47 -0
  248. package/ecosystem.prod.config.cjs +135 -0
  249. package/eslint.config.js +89 -0
  250. package/index.js +488 -0
  251. package/ml/clip_classifier/Dockerfile +18 -0
  252. package/ml/clip_classifier/README.md +118 -0
  253. package/ml/clip_classifier/adaptive_scoring.py +40 -0
  254. package/ml/clip_classifier/classifier.py +654 -0
  255. package/ml/clip_classifier/embedding_store.py +481 -0
  256. package/ml/clip_classifier/env_loader.py +15 -0
  257. package/ml/clip_classifier/llm_label_expander.py +144 -0
  258. package/ml/clip_classifier/main.py +213 -0
  259. package/ml/clip_classifier/requirements.txt +10 -0
  260. package/ml/clip_classifier/similarity_engine.py +74 -0
  261. package/new-logo.png +0 -0
  262. package/observability/alert-rules.yml +60 -0
  263. package/observability/grafana/dashboards/omnizap-mysql.json +136 -0
  264. package/observability/grafana/dashboards/omnizap-overview.json +170 -0
  265. package/observability/grafana/provisioning/dashboards/dashboards.yml +11 -0
  266. package/observability/grafana/provisioning/datasources/datasources.yml +15 -0
  267. package/observability/loki-config.yml +38 -0
  268. package/observability/mysql-setup.sql +46 -0
  269. package/observability/prometheus.yml +35 -0
  270. package/observability/promtail-config.yml +84 -0
  271. package/observability/sticker-catalog-slo.md +83 -0
  272. package/observability/sticker-scale-hardening-rollout.md +128 -0
  273. package/package.json +144 -0
  274. package/public/apple-touch-icon.png +0 -0
  275. package/public/assets/css/commands-react.input.css +71 -0
  276. package/public/assets/css/create-pack-react.input.css +31 -0
  277. package/public/assets/css/home-react.input.css +106 -0
  278. package/public/assets/css/login-react.input.css +58 -0
  279. package/public/assets/css/stickers-react.input.css +18 -0
  280. package/public/assets/css/terms-react.input.css +115 -0
  281. package/public/assets/css/user-react.input.css +57 -0
  282. package/public/assets/images/brand-icon-192.png +0 -0
  283. package/public/assets/images/brand-logo-128.webp +0 -0
  284. package/public/assets/images/hero-banner-1280.jpg +0 -0
  285. package/public/comandos/commands-catalog.json +4517 -0
  286. package/public/css/api-docs.css +161 -0
  287. package/public/css/stickers-admin.css +1288 -0
  288. package/public/css/styles.css +679 -0
  289. package/public/css/systemadm/admin.css +474 -0
  290. package/public/css/systemadm/base.css +73 -0
  291. package/public/css/systemadm/components.css +662 -0
  292. package/public/css/systemadm/layout.css +229 -0
  293. package/public/css/systemadm/tokens.css +56 -0
  294. package/public/favicon-16x16.png +0 -0
  295. package/public/favicon-32x32.png +0 -0
  296. package/public/favicon.ico +0 -0
  297. package/public/js/apps/apiDocsApp.js +235 -0
  298. package/public/js/apps/commandsReactApp.js +528 -0
  299. package/public/js/apps/createPackApp.js +1646 -0
  300. package/public/js/apps/homeReactApp.js +942 -0
  301. package/public/js/apps/loginReactApp.js +496 -0
  302. package/public/js/apps/stickersAdminApp.js +1753 -0
  303. package/public/js/apps/stickersApp.js +3797 -0
  304. package/public/js/apps/termsReactApp.js +528 -0
  305. package/public/js/apps/userApp.js +2540 -0
  306. package/public/js/apps/userProfile/actions.js +66 -0
  307. package/public/js/apps/userReactApp.js +547 -0
  308. package/public/js/catalog.js +950 -0
  309. package/public/pages/api-docs.html +40 -0
  310. package/public/pages/aup.html +158 -0
  311. package/public/pages/comandos.html +41 -0
  312. package/public/pages/dpa.html +227 -0
  313. package/public/pages/home.html +45 -0
  314. package/public/pages/licenca.html +182 -0
  315. package/public/pages/login.html +40 -0
  316. package/public/pages/notice-and-takedown.html +234 -0
  317. package/public/pages/politica-de-privacidade.html +251 -0
  318. package/public/pages/seo-bot-whatsapp-para-grupo.html +350 -0
  319. package/public/pages/seo-bot-whatsapp-sem-programar.html +350 -0
  320. package/public/pages/seo-como-automatizar-avisos-no-whatsapp.html +350 -0
  321. package/public/pages/seo-como-criar-comandos-whatsapp.html +350 -0
  322. package/public/pages/seo-como-evitar-spam-no-whatsapp.html +350 -0
  323. package/public/pages/seo-como-moderar-grupo-whatsapp.html +350 -0
  324. package/public/pages/seo-como-organizar-comunidade-whatsapp.html +350 -0
  325. package/public/pages/seo-melhor-bot-whatsapp-para-grupos.html +350 -0
  326. package/public/pages/stickers-admin.html +31 -0
  327. package/public/pages/stickers-create.html +41 -0
  328. package/public/pages/stickers.html +45 -0
  329. package/public/pages/suboperadores.html +237 -0
  330. package/public/pages/termos-de-uso-texto-integral.html +241 -0
  331. package/public/pages/termos-de-uso.html +41 -0
  332. package/public/pages/user-password-reset.html +32 -0
  333. package/public/pages/user-systemadm.html +508 -0
  334. package/public/pages/user.html +39 -0
  335. package/public/robots.txt +9 -0
  336. package/public/site.webmanifest +24 -0
  337. package/public/sitemap.xml +98 -0
  338. package/schemas/command-config.schema.json +582 -0
  339. package/scripts/baileys-compat-smoke.mjs +12 -0
  340. package/scripts/cache-bust.mjs +142 -0
  341. package/scripts/deploy.sh +916 -0
  342. package/scripts/email-broadcast-terms-update.mjs +170 -0
  343. package/scripts/enrich-command-discovery-fields.mjs +286 -0
  344. package/scripts/generate-command-config-schema.mjs +273 -0
  345. package/scripts/generate-commands-catalog.mjs +308 -0
  346. package/scripts/generate-module-agents.mjs +631 -0
  347. package/scripts/generate-seo-satellite-pages.mjs +400 -0
  348. package/scripts/github-deploy-notify.mjs +174 -0
  349. package/scripts/github-release-notify.mjs +219 -0
  350. package/scripts/release.sh +599 -0
  351. package/scripts/run-codeql-local.sh +116 -0
  352. package/scripts/run-prettier-all.mjs +25 -0
  353. package/scripts/security-smoketest.mjs +581 -0
  354. package/scripts/sticker-catalog-loadtest.mjs +210 -0
  355. package/scripts/sticker-worker-task.mjs +119 -0
  356. package/scripts/sync-readme-snapshot.mjs +133 -0
  357. package/scripts/validate-command-config-schema.mjs +130 -0
  358. package/scripts/validate-command-configs.mjs +15 -0
  359. package/scripts/wiki-sync.sh +191 -0
  360. package/server/auth/googleWebAuth/googleWebAuthRuntime.js +62 -0
  361. package/server/auth/googleWebAuth/googleWebAuthService.js +807 -0
  362. package/server/auth/jwt/webJwtService.js +147 -0
  363. package/server/auth/stickerCatalogAuthContext.js +165 -0
  364. package/server/auth/termsAcceptance/termsAcceptanceHandler.js +189 -0
  365. package/server/auth/userPassword/index.js +14 -0
  366. package/server/auth/userPassword/userPasswordAuthService.js +422 -0
  367. package/server/auth/userPassword/userPasswordCrypto.js +199 -0
  368. package/server/auth/userPassword/userPasswordCrypto.test.js +76 -0
  369. package/server/auth/userPassword/userPasswordRecoveryService.js +728 -0
  370. package/server/auth/validation/authSchemas.js +236 -0
  371. package/server/auth/webAccount/webAccountHandlers.js +1434 -0
  372. package/server/controllers/admin/adminBanService.js +138 -0
  373. package/server/controllers/admin/adminPanelHandlers.js +2083 -0
  374. package/server/controllers/admin/stickerCatalogAdminContext.js +17 -0
  375. package/server/controllers/admin/systemAdminController.js +201 -0
  376. package/server/controllers/email/emailAutomationController.js +239 -0
  377. package/server/controllers/metricsController.js +21 -0
  378. package/server/controllers/seo/stickerCatalogSeoContext.js +514 -0
  379. package/server/controllers/sticker/nonCatalogHandlers.js +303 -0
  380. package/server/controllers/sticker/stickerCatalogController.js +4700 -0
  381. package/server/controllers/system/contactController.js +115 -0
  382. package/server/controllers/system/githubController.js +137 -0
  383. package/server/controllers/system/stickerCatalogSystemContext.js +758 -0
  384. package/server/controllers/system/storageController.js +154 -0
  385. package/server/controllers/system/systemController.js +135 -0
  386. package/server/controllers/system/systemMetricsController.js +156 -0
  387. package/server/controllers/system/visitController.js +90 -0
  388. package/server/controllers/userController.js +145 -0
  389. package/server/email/emailAutomationRuntime.js +225 -0
  390. package/server/email/emailAutomationService.js +125 -0
  391. package/server/email/emailOutboxRepository.js +282 -0
  392. package/server/email/emailTemplateService.js +480 -0
  393. package/server/email/emailTransportService.js +156 -0
  394. package/server/http/clientIp.js +95 -0
  395. package/server/http/httpRequestUtils.js +262 -0
  396. package/server/http/httpRequestUtils.test.js +80 -0
  397. package/server/http/httpServer.js +180 -0
  398. package/server/http/requestContext.js +20 -0
  399. package/server/http/siteRoutingUtils.js +87 -0
  400. package/server/index.js +1 -0
  401. package/server/middleware/cachePolicy.js +26 -0
  402. package/server/middleware/cachePolicyHelpers.js +1 -0
  403. package/server/middleware/endpointRateLimit.js +181 -0
  404. package/server/middleware/rateLimit.js +70 -0
  405. package/server/middleware/requireAdminAuth.js +48 -0
  406. package/server/middleware/securityHeaders.js +97 -0
  407. package/server/routes/admin/systemAdminRouter.js +64 -0
  408. package/server/routes/email/emailAutomationRouter.js +46 -0
  409. package/server/routes/health/healthRouter.js +41 -0
  410. package/server/routes/indexRouter.js +234 -0
  411. package/server/routes/metrics/metricsRouter.js +58 -0
  412. package/server/routes/static/staticPageRouter.js +134 -0
  413. package/server/routes/sticker/catalogHandlers/catalogAdminHttp.js +105 -0
  414. package/server/routes/sticker/catalogHandlers/catalogAuthHttp.js +77 -0
  415. package/server/routes/sticker/catalogHandlers/catalogPublicHttp.js +120 -0
  416. package/server/routes/sticker/catalogHandlers/catalogUploadHttp.js +83 -0
  417. package/server/routes/sticker/catalogRouter.js +77 -0
  418. package/server/routes/sticker/stickerApiRouter.js +84 -0
  419. package/server/routes/sticker/stickerDataRouter.js +145 -0
  420. package/server/routes/sticker/stickerSiteRouter.js +43 -0
  421. package/server/routes/user/userApiPaths.js +66 -0
  422. package/server/routes/user/userRouter.js +65 -0
  423. package/server/utils/safePath.js +26 -0
  424. package/utils/logger/loggerModule.js +35 -0
  425. package/vite.config.mjs +38 -0
@@ -0,0 +1,544 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ import OpenAI from 'openai';
4
+
5
+ import { executeQuery, TABLES } from '../../../database/index.js';
6
+ import logger from '#logger';
7
+ import { findStickerClassificationByAssetId, updateStickerClassificationSemanticCluster } from './stickerAssetClassificationRepository.js';
8
+
9
+ const parseEnvBool = (value, fallback) => {
10
+ if (value === undefined || value === null || value === '') return fallback;
11
+ const normalized = String(value).trim().toLowerCase();
12
+ if (['1', 'true', 'yes', 'y', 'on'].includes(normalized)) return true;
13
+ if (['0', 'false', 'no', 'n', 'off'].includes(normalized)) return false;
14
+ return fallback;
15
+ };
16
+
17
+ const ENABLE_SEMANTIC_CLUSTERING = parseEnvBool(process.env.ENABLE_SEMANTIC_CLUSTERING, false);
18
+ const OPENAI_TIMEOUT_MS = Math.max(1_000, Number(process.env.SEMANTIC_CLUSTER_OPENAI_TIMEOUT_MS) || 10_000);
19
+ const EMBEDDING_MODEL = String(process.env.SEMANTIC_CLUSTER_EMBEDDING_MODEL || 'text-embedding-3-small').trim() || 'text-embedding-3-small';
20
+ const SLUG_MODEL = String(process.env.SEMANTIC_CLUSTER_SLUG_MODEL || 'gpt-4o-mini').trim() || 'gpt-4o-mini';
21
+ const SIMILARITY_THRESHOLD = Number.isFinite(Number(process.env.SEMANTIC_CLUSTER_SIMILARITY_THRESHOLD)) ? Math.max(0.5, Math.min(0.99, Number(process.env.SEMANTIC_CLUSTER_SIMILARITY_THRESHOLD))) : 0.87;
22
+ const MAX_CLUSTER_SCAN = Math.max(100, Math.min(20_000, Number(process.env.SEMANTIC_CLUSTER_MAX_SCAN) || 5_000));
23
+ const MAX_SUGGESTIONS_PER_ASSET = Math.max(1, Math.min(20, Number(process.env.SEMANTIC_CLUSTER_MAX_SUGGESTIONS_PER_ASSET) || 8));
24
+ const CLUSTERING_CONCURRENCY = Math.max(1, Math.min(8, Number(process.env.SEMANTIC_CLUSTER_CONCURRENCY) || 2));
25
+ const RESOLUTION_CACHE_TTL_MS = Math.max(5_000, Number(process.env.SEMANTIC_CLUSTER_MEMORY_CACHE_TTL_MS) || 5 * 60 * 1000);
26
+ const SEMANTIC_CLUSTER_REPROCESS_EXISTING = parseEnvBool(process.env.SEMANTIC_CLUSTER_REPROCESS_EXISTING, false);
27
+
28
+ let cachedClient = null;
29
+ const inMemorySuggestionCache = new Map();
30
+ const inMemoryClusterById = new Map();
31
+ let inMemoryClusterList = {
32
+ expiresAt: 0,
33
+ items: [],
34
+ };
35
+ let clusterListPending = null;
36
+
37
+ const pendingTasksByAssetId = new Map();
38
+ let queueDrainScheduled = false;
39
+ let queueRunning = 0;
40
+
41
+ const normalizeSuggestion = (value) =>
42
+ String(value || '')
43
+ .trim()
44
+ .toLowerCase()
45
+ .replace(/\s+/g, ' ')
46
+ .slice(0, 512);
47
+
48
+ const normalizeSlug = (value) => {
49
+ const normalized = String(value || '')
50
+ .trim()
51
+ .toLowerCase()
52
+ .normalize('NFD')
53
+ .replace(/[\u0300-\u036f]/g, '')
54
+ .replace(/[^a-z0-9]+/g, '_')
55
+ .replace(/^_+|_+$/g, '')
56
+ .replace(/_+/g, '_');
57
+ if (!normalized) return '';
58
+ return normalized.split('_').filter(Boolean).slice(0, 2).join('_');
59
+ };
60
+
61
+ const fallbackSlugFromSuggestion = (suggestionText) => {
62
+ const normalized = normalizeSuggestion(suggestionText);
63
+ if (!normalized) return 'misc_theme';
64
+ const slug = normalizeSlug(normalized);
65
+ return slug || 'misc_theme';
66
+ };
67
+
68
+ const hashSuggestion = (normalizedSuggestion) =>
69
+ createHash('sha256')
70
+ .update(String(normalizedSuggestion || ''), 'utf8')
71
+ .digest('hex');
72
+
73
+ const serializeEmbedding = (embedding = []) => {
74
+ const vector = Array.isArray(embedding) ? embedding : [];
75
+ const clean = vector.map((value) => Number(value)).filter((value) => Number.isFinite(value));
76
+ if (!clean.length) return { dim: 0, buffer: Buffer.alloc(0) };
77
+ const buffer = Buffer.allocUnsafe(clean.length * 4);
78
+ for (let index = 0; index < clean.length; index += 1) {
79
+ buffer.writeFloatLE(clean[index], index * 4);
80
+ }
81
+ return { dim: clean.length, buffer };
82
+ };
83
+
84
+ const parseEmbedding = (raw, dim = 0) => {
85
+ if (!Buffer.isBuffer(raw) || raw.length < 4) return [];
86
+ const vectorSize = Math.floor(raw.length / 4);
87
+ const size = dim > 0 ? Math.min(dim, vectorSize) : vectorSize;
88
+ if (size <= 0) return [];
89
+ const output = new Array(size);
90
+ for (let index = 0; index < size; index += 1) {
91
+ output[index] = raw.readFloatLE(index * 4);
92
+ }
93
+ return output;
94
+ };
95
+
96
+ const cosineSimilarity = (left, right) => {
97
+ if (!Array.isArray(left) || !Array.isArray(right) || !left.length || !right.length) return 0;
98
+ const size = Math.min(left.length, right.length);
99
+ if (size <= 0) return 0;
100
+
101
+ let dot = 0;
102
+ let leftNorm = 0;
103
+ let rightNorm = 0;
104
+ for (let index = 0; index < size; index += 1) {
105
+ const leftValue = Number(left[index] || 0);
106
+ const rightValue = Number(right[index] || 0);
107
+ dot += leftValue * rightValue;
108
+ leftNorm += leftValue * leftValue;
109
+ rightNorm += rightValue * rightValue;
110
+ }
111
+
112
+ if (leftNorm <= 0 || rightNorm <= 0) return 0;
113
+ return Math.max(-1, Math.min(1, dot / (Math.sqrt(leftNorm) * Math.sqrt(rightNorm))));
114
+ };
115
+
116
+ const resolveOpenAIClient = () => {
117
+ if (cachedClient) return cachedClient;
118
+ const apiKey = String(process.env.OPENAI_API_KEY || '').trim();
119
+ if (!apiKey) return null;
120
+ cachedClient = new OpenAI({
121
+ apiKey,
122
+ timeout: OPENAI_TIMEOUT_MS,
123
+ maxRetries: 0,
124
+ });
125
+ return cachedClient;
126
+ };
127
+
128
+ const shouldRunSemanticClustering = () => ENABLE_SEMANTIC_CLUSTERING && Boolean(resolveOpenAIClient());
129
+
130
+ const getSuggestionCacheRow = async (normalizedSuggestion) => {
131
+ const normalized = normalizeSuggestion(normalizedSuggestion);
132
+ if (!normalized) return null;
133
+
134
+ const rows = await executeQuery(
135
+ `SELECT suggestion_hash, normalized_text, semantic_cluster_id, canonical_slug, embedding_dim, embedding, last_similarity
136
+ FROM ${TABLES.SEMANTIC_THEME_SUGGESTION_CACHE}
137
+ WHERE normalized_text = ?
138
+ LIMIT 1`,
139
+ [normalized],
140
+ );
141
+ const row = rows?.[0] || null;
142
+ if (!row) return null;
143
+
144
+ return {
145
+ suggestion_hash: row.suggestion_hash,
146
+ normalized_text: row.normalized_text,
147
+ semantic_cluster_id: Number(row.semantic_cluster_id || 0) || null,
148
+ canonical_slug: row.canonical_slug || null,
149
+ embedding: parseEmbedding(row.embedding, Number(row.embedding_dim || 0)),
150
+ last_similarity: Number.isFinite(Number(row.last_similarity)) ? Number(row.last_similarity) : null,
151
+ };
152
+ };
153
+
154
+ const upsertSuggestionCacheRow = async ({ suggestionText, normalizedText, semanticClusterId, canonicalSlug, embedding = [], similarity = null }) => {
155
+ const normalized = normalizeSuggestion(normalizedText || suggestionText);
156
+ if (!normalized || !semanticClusterId) return false;
157
+ const suggestionHash = hashSuggestion(normalized);
158
+ const { dim, buffer } = serializeEmbedding(embedding);
159
+ if (dim <= 0 || !buffer.length) return false;
160
+
161
+ await executeQuery(
162
+ `INSERT INTO ${TABLES.SEMANTIC_THEME_SUGGESTION_CACHE}
163
+ (suggestion_hash, suggestion_text, normalized_text, semantic_cluster_id, canonical_slug, embedding_dim, embedding, last_similarity)
164
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
165
+ ON DUPLICATE KEY UPDATE
166
+ suggestion_text = VALUES(suggestion_text),
167
+ normalized_text = VALUES(normalized_text),
168
+ semantic_cluster_id = VALUES(semantic_cluster_id),
169
+ canonical_slug = VALUES(canonical_slug),
170
+ embedding_dim = VALUES(embedding_dim),
171
+ embedding = VALUES(embedding),
172
+ last_similarity = VALUES(last_similarity),
173
+ updated_at = CURRENT_TIMESTAMP`,
174
+ [suggestionHash, String(suggestionText || normalized).slice(0, 512), normalized, semanticClusterId, canonicalSlug || null, dim, buffer, similarity !== null && Number.isFinite(Number(similarity)) ? Number(Number(similarity).toFixed(6)) : null],
175
+ );
176
+ return true;
177
+ };
178
+
179
+ const listSemanticClusters = async () => {
180
+ const now = Date.now();
181
+ if (inMemoryClusterList.expiresAt > now && Array.isArray(inMemoryClusterList.items)) {
182
+ return inMemoryClusterList.items;
183
+ }
184
+ if (clusterListPending) return clusterListPending;
185
+
186
+ clusterListPending = executeQuery(
187
+ `SELECT id, canonical_slug, embedding_dim, embedding
188
+ FROM ${TABLES.SEMANTIC_THEME_CLUSTER}
189
+ ORDER BY id DESC
190
+ LIMIT ${Math.max(1, MAX_CLUSTER_SCAN)}`,
191
+ [],
192
+ )
193
+ .then((rows) => {
194
+ const parsed = (Array.isArray(rows) ? rows : [])
195
+ .map((row) => ({
196
+ id: Number(row.id || 0),
197
+ canonical_slug: row.canonical_slug || null,
198
+ embedding: parseEmbedding(row.embedding, Number(row.embedding_dim || 0)),
199
+ }))
200
+ .filter((row) => row.id > 0 && Array.isArray(row.embedding) && row.embedding.length > 0);
201
+ inMemoryClusterList = {
202
+ expiresAt: Date.now() + RESOLUTION_CACHE_TTL_MS,
203
+ items: parsed,
204
+ };
205
+ for (const cluster of parsed) {
206
+ inMemoryClusterById.set(cluster.id, cluster);
207
+ }
208
+ return parsed;
209
+ })
210
+ .finally(() => {
211
+ clusterListPending = null;
212
+ });
213
+
214
+ return clusterListPending;
215
+ };
216
+
217
+ const createSemanticCluster = async ({ canonicalSlug, embedding }) => {
218
+ const slug = normalizeSlug(canonicalSlug) || 'misc_theme';
219
+ const { dim, buffer } = serializeEmbedding(embedding);
220
+ if (!buffer.length || dim <= 0) {
221
+ throw new Error('embedding_invalid_for_cluster');
222
+ }
223
+
224
+ const result = await executeQuery(
225
+ `INSERT INTO ${TABLES.SEMANTIC_THEME_CLUSTER}
226
+ (canonical_slug, embedding_dim, embedding)
227
+ VALUES (?, ?, ?)`,
228
+ [slug, dim, buffer],
229
+ );
230
+ const clusterId = Number(result?.insertId || 0);
231
+ if (!clusterId) {
232
+ throw new Error('cluster_insert_failed');
233
+ }
234
+
235
+ const created = {
236
+ id: clusterId,
237
+ canonical_slug: slug,
238
+ embedding: Array.isArray(embedding) ? embedding : [],
239
+ };
240
+ inMemoryClusterById.set(clusterId, created);
241
+ inMemoryClusterList = {
242
+ expiresAt: 0,
243
+ items: [],
244
+ };
245
+ return created;
246
+ };
247
+
248
+ const generateEmbedding = async (text) => {
249
+ const client = resolveOpenAIClient();
250
+ if (!client) return null;
251
+
252
+ const response = await client.embeddings.create({
253
+ model: EMBEDDING_MODEL,
254
+ input: text,
255
+ });
256
+ const vector = response?.data?.[0]?.embedding;
257
+ if (!Array.isArray(vector) || !vector.length) return null;
258
+ const clean = vector.map((value) => Number(value)).filter((value) => Number.isFinite(value));
259
+ return clean.length ? clean : null;
260
+ };
261
+
262
+ const generateCanonicalSlug = async (suggestionText) => {
263
+ const fallback = fallbackSlugFromSuggestion(suggestionText);
264
+ const client = resolveOpenAIClient();
265
+ if (!client) return fallback;
266
+
267
+ try {
268
+ const completion = await client.chat.completions.create({
269
+ model: SLUG_MODEL,
270
+ temperature: 0,
271
+ max_tokens: 32,
272
+ response_format: { type: 'json_object' },
273
+ messages: [
274
+ {
275
+ role: 'system',
276
+ content: 'Normalize short theme phrases into a canonical 1-2 word lowercase slug with underscores. Return JSON: {"slug":"..."}',
277
+ },
278
+ {
279
+ role: 'user',
280
+ content: String(suggestionText || ''),
281
+ },
282
+ ],
283
+ });
284
+ const content = String(completion?.choices?.[0]?.message?.content || '').trim();
285
+ if (!content) return fallback;
286
+ const parsed = JSON.parse(content);
287
+ const slug = normalizeSlug(parsed?.slug);
288
+ return slug || fallback;
289
+ } catch {
290
+ return fallback;
291
+ }
292
+ };
293
+
294
+ const resolveClusterBySimilarity = async (embedding, threshold = SIMILARITY_THRESHOLD) => {
295
+ const clusters = await listSemanticClusters();
296
+ if (!clusters.length) return null;
297
+
298
+ let best = null;
299
+ for (const cluster of clusters) {
300
+ const similarity = cosineSimilarity(embedding, cluster.embedding);
301
+ if (similarity < threshold) continue;
302
+ if (!best || similarity > best.similarity) {
303
+ best = {
304
+ id: cluster.id,
305
+ canonical_slug: cluster.canonical_slug,
306
+ similarity,
307
+ };
308
+ }
309
+ }
310
+ return best;
311
+ };
312
+
313
+ const resolveSemanticCluster = async (suggestionText) => {
314
+ const normalizedSuggestion = normalizeSuggestion(suggestionText);
315
+ if (!normalizedSuggestion) return null;
316
+ if (!shouldRunSemanticClustering()) return null;
317
+
318
+ const memoryCached = inMemorySuggestionCache.get(normalizedSuggestion);
319
+ if (memoryCached && memoryCached.expiresAt > Date.now()) {
320
+ return memoryCached.value;
321
+ }
322
+
323
+ const dbCached = await getSuggestionCacheRow(normalizedSuggestion);
324
+ if (dbCached?.semantic_cluster_id) {
325
+ const payload = {
326
+ semantic_cluster_id: dbCached.semantic_cluster_id,
327
+ semantic_cluster_slug: normalizeSlug(dbCached.canonical_slug),
328
+ similarity: dbCached.last_similarity,
329
+ created: false,
330
+ source: 'cache',
331
+ suggestion: normalizedSuggestion,
332
+ };
333
+ inMemorySuggestionCache.set(normalizedSuggestion, {
334
+ expiresAt: Date.now() + RESOLUTION_CACHE_TTL_MS,
335
+ value: payload,
336
+ });
337
+ return payload;
338
+ }
339
+
340
+ const embedding = await generateEmbedding(normalizedSuggestion);
341
+ if (!embedding?.length) return null;
342
+
343
+ const matched = await resolveClusterBySimilarity(embedding, SIMILARITY_THRESHOLD);
344
+ if (matched?.id) {
345
+ const payload = {
346
+ semantic_cluster_id: matched.id,
347
+ semantic_cluster_slug: normalizeSlug(matched.canonical_slug) || null,
348
+ similarity: Number(matched.similarity.toFixed(6)),
349
+ created: false,
350
+ source: 'similarity',
351
+ suggestion: normalizedSuggestion,
352
+ };
353
+
354
+ await upsertSuggestionCacheRow({
355
+ suggestionText,
356
+ normalizedText: normalizedSuggestion,
357
+ semanticClusterId: payload.semantic_cluster_id,
358
+ canonicalSlug: payload.semantic_cluster_slug,
359
+ embedding,
360
+ similarity: payload.similarity,
361
+ });
362
+ inMemorySuggestionCache.set(normalizedSuggestion, {
363
+ expiresAt: Date.now() + RESOLUTION_CACHE_TTL_MS,
364
+ value: payload,
365
+ });
366
+ return payload;
367
+ }
368
+
369
+ const canonicalSlug = await generateCanonicalSlug(normalizedSuggestion);
370
+ const createdCluster = await createSemanticCluster({
371
+ canonicalSlug,
372
+ embedding,
373
+ });
374
+ const payload = {
375
+ semantic_cluster_id: createdCluster.id,
376
+ semantic_cluster_slug: normalizeSlug(createdCluster.canonical_slug) || canonicalSlug,
377
+ similarity: 1,
378
+ created: true,
379
+ source: 'new_cluster',
380
+ suggestion: normalizedSuggestion,
381
+ };
382
+ await upsertSuggestionCacheRow({
383
+ suggestionText,
384
+ normalizedText: normalizedSuggestion,
385
+ semanticClusterId: payload.semantic_cluster_id,
386
+ canonicalSlug: payload.semantic_cluster_slug,
387
+ embedding,
388
+ similarity: 1,
389
+ });
390
+ inMemorySuggestionCache.set(normalizedSuggestion, {
391
+ expiresAt: Date.now() + RESOLUTION_CACHE_TTL_MS,
392
+ value: payload,
393
+ });
394
+ return payload;
395
+ };
396
+
397
+ const pickPrimaryCluster = (matches) => {
398
+ if (!Array.isArray(matches) || !matches.length) return null;
399
+ const tally = new Map();
400
+ for (const match of matches) {
401
+ const id = Number(match?.semantic_cluster_id || 0);
402
+ if (!id) continue;
403
+ const current = tally.get(id) || {
404
+ semantic_cluster_id: id,
405
+ semantic_cluster_slug: normalizeSlug(match?.semantic_cluster_slug || '') || null,
406
+ count: 0,
407
+ best_similarity: -1,
408
+ };
409
+ current.count += 1;
410
+ current.best_similarity = Math.max(current.best_similarity, Number(match?.similarity || 0));
411
+ if (!current.semantic_cluster_slug && match?.semantic_cluster_slug) {
412
+ current.semantic_cluster_slug = normalizeSlug(match.semantic_cluster_slug);
413
+ }
414
+ tally.set(id, current);
415
+ }
416
+
417
+ const ranked = Array.from(tally.values()).sort((left, right) => {
418
+ if (right.count !== left.count) return right.count - left.count;
419
+ if (right.best_similarity !== left.best_similarity) return right.best_similarity - left.best_similarity;
420
+ return left.semantic_cluster_id - right.semantic_cluster_id;
421
+ });
422
+ return ranked[0] || null;
423
+ };
424
+
425
+ const sanitizeSuggestions = (values = []) => {
426
+ const suggestions = [];
427
+ const seen = new Set();
428
+ for (const value of Array.isArray(values) ? values : []) {
429
+ const normalized = normalizeSuggestion(value);
430
+ if (!normalized || seen.has(normalized)) continue;
431
+ seen.add(normalized);
432
+ suggestions.push(normalized);
433
+ if (suggestions.length >= MAX_SUGGESTIONS_PER_ASSET) break;
434
+ }
435
+ return suggestions;
436
+ };
437
+
438
+ const resolveSuggestionsToPrimaryCluster = async ({ suggestions = [], fallbackText = '' } = {}) => {
439
+ const normalizedSuggestions = sanitizeSuggestions(suggestions);
440
+ if (!normalizedSuggestions.length && fallbackText) {
441
+ normalizedSuggestions.push(normalizeSuggestion(fallbackText));
442
+ }
443
+ if (!normalizedSuggestions.length) return null;
444
+
445
+ const matches = [];
446
+ for (const suggestion of normalizedSuggestions) {
447
+ const resolved = await resolveSemanticCluster(suggestion);
448
+ if (resolved?.semantic_cluster_id) {
449
+ matches.push(resolved);
450
+ }
451
+ }
452
+ if (!matches.length) return null;
453
+
454
+ const primary = pickPrimaryCluster(matches);
455
+ if (!primary?.semantic_cluster_id) return null;
456
+
457
+ return {
458
+ semantic_cluster_id: primary.semantic_cluster_id,
459
+ semantic_cluster_slug: primary.semantic_cluster_slug || fallbackSlugFromSuggestion(normalizedSuggestions[0] || ''),
460
+ matches,
461
+ };
462
+ };
463
+
464
+ const scheduleQueueDrain = () => {
465
+ if (queueDrainScheduled) return;
466
+ queueDrainScheduled = true;
467
+ setImmediate(() => {
468
+ queueDrainScheduled = false;
469
+ void drainSemanticClusterQueue();
470
+ });
471
+ };
472
+
473
+ const processSemanticClusterTask = async (task) => {
474
+ const assetId = String(task?.assetId || '').trim();
475
+ if (!assetId || !shouldRunSemanticClustering()) return;
476
+
477
+ try {
478
+ const current = await findStickerClassificationByAssetId(assetId);
479
+ if (!current) return;
480
+ if (current.semantic_cluster_id && !SEMANTIC_CLUSTER_REPROCESS_EXISTING && !task?.force) {
481
+ return;
482
+ }
483
+
484
+ const result = await resolveSuggestionsToPrimaryCluster({
485
+ suggestions: task?.suggestions || current.llm_pack_suggestions || [],
486
+ fallbackText: task?.fallbackText || current.category || '',
487
+ });
488
+ if (!result?.semantic_cluster_id) return;
489
+
490
+ await updateStickerClassificationSemanticCluster(assetId, {
491
+ semanticClusterId: result.semantic_cluster_id,
492
+ semanticClusterSlug: result.semantic_cluster_slug,
493
+ });
494
+ } catch (error) {
495
+ logger.warn('Falha ao processar clusterização semântica de sugestão LLM.', {
496
+ action: 'semantic_theme_cluster_task_failed',
497
+ asset_id: assetId,
498
+ error: error?.message,
499
+ });
500
+ }
501
+ };
502
+
503
+ const drainSemanticClusterQueue = async () => {
504
+ while (queueRunning < CLUSTERING_CONCURRENCY && pendingTasksByAssetId.size > 0) {
505
+ const firstEntry = pendingTasksByAssetId.entries().next().value;
506
+ if (!firstEntry) break;
507
+ const [assetId, task] = firstEntry;
508
+ pendingTasksByAssetId.delete(assetId);
509
+ queueRunning += 1;
510
+ void processSemanticClusterTask(task)
511
+ .catch(() => {})
512
+ .finally(() => {
513
+ queueRunning = Math.max(0, queueRunning - 1);
514
+ scheduleQueueDrain();
515
+ });
516
+ }
517
+ };
518
+
519
+ export const enqueueSemanticClusterResolution = ({ assetId, suggestions = [], fallbackText = '', force = false } = {}) => {
520
+ const normalizedAssetId = String(assetId || '').trim();
521
+ if (!normalizedAssetId || !ENABLE_SEMANTIC_CLUSTERING) return false;
522
+
523
+ pendingTasksByAssetId.set(normalizedAssetId, {
524
+ assetId: normalizedAssetId,
525
+ suggestions: sanitizeSuggestions(suggestions),
526
+ fallbackText: String(fallbackText || '')
527
+ .trim()
528
+ .slice(0, 255),
529
+ force: Boolean(force),
530
+ });
531
+ scheduleQueueDrain();
532
+ return true;
533
+ };
534
+
535
+ export const semanticClusterConfig = {
536
+ enabled: ENABLE_SEMANTIC_CLUSTERING,
537
+ similarity_threshold: SIMILARITY_THRESHOLD,
538
+ embedding_model: EMBEDDING_MODEL,
539
+ slug_model: SLUG_MODEL,
540
+ max_cluster_scan: MAX_CLUSTER_SCAN,
541
+ queue_concurrency: CLUSTERING_CONCURRENCY,
542
+ };
543
+
544
+ export const isSemanticClusteringEnabled = () => ENABLE_SEMANTIC_CLUSTERING;