euparliamentmonitor 0.8.4

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 (276) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +1005 -0
  3. package/SECURITY.md +151 -0
  4. package/package.json +131 -0
  5. package/scripts/constants/committee-indicator-map.d.ts +199 -0
  6. package/scripts/constants/committee-indicator-map.d.ts.map +1 -0
  7. package/scripts/constants/committee-indicator-map.js +1224 -0
  8. package/scripts/constants/committee-indicator-map.js.map +1 -0
  9. package/scripts/constants/config.d.ts +38 -0
  10. package/scripts/constants/config.d.ts.map +1 -0
  11. package/scripts/constants/config.js +66 -0
  12. package/scripts/constants/config.js.map +1 -0
  13. package/scripts/constants/language-articles.d.ts +84 -0
  14. package/scripts/constants/language-articles.d.ts.map +1 -0
  15. package/scripts/constants/language-articles.js +6771 -0
  16. package/scripts/constants/language-articles.js.map +1 -0
  17. package/scripts/constants/language-core.d.ts +38 -0
  18. package/scripts/constants/language-core.d.ts.map +1 -0
  19. package/scripts/constants/language-core.js +90 -0
  20. package/scripts/constants/language-core.js.map +1 -0
  21. package/scripts/constants/language-ui.d.ts +82 -0
  22. package/scripts/constants/language-ui.d.ts.map +1 -0
  23. package/scripts/constants/language-ui.js +889 -0
  24. package/scripts/constants/language-ui.js.map +1 -0
  25. package/scripts/constants/languages.d.ts +14 -0
  26. package/scripts/constants/languages.d.ts.map +1 -0
  27. package/scripts/constants/languages.js +15 -0
  28. package/scripts/constants/languages.js.map +1 -0
  29. package/scripts/generators/analysis-builders.d.ts +266 -0
  30. package/scripts/generators/analysis-builders.d.ts.map +1 -0
  31. package/scripts/generators/analysis-builders.js +2903 -0
  32. package/scripts/generators/analysis-builders.js.map +1 -0
  33. package/scripts/generators/breaking-content.d.ts +45 -0
  34. package/scripts/generators/breaking-content.d.ts.map +1 -0
  35. package/scripts/generators/breaking-content.js +530 -0
  36. package/scripts/generators/breaking-content.js.map +1 -0
  37. package/scripts/generators/committee-helpers.d.ts +54 -0
  38. package/scripts/generators/committee-helpers.d.ts.map +1 -0
  39. package/scripts/generators/committee-helpers.js +154 -0
  40. package/scripts/generators/committee-helpers.js.map +1 -0
  41. package/scripts/generators/dashboard-content.d.ts +95 -0
  42. package/scripts/generators/dashboard-content.d.ts.map +1 -0
  43. package/scripts/generators/dashboard-content.js +630 -0
  44. package/scripts/generators/dashboard-content.js.map +1 -0
  45. package/scripts/generators/deep-analysis-content.d.ts +23 -0
  46. package/scripts/generators/deep-analysis-content.d.ts.map +1 -0
  47. package/scripts/generators/deep-analysis-content.js +831 -0
  48. package/scripts/generators/deep-analysis-content.js.map +1 -0
  49. package/scripts/generators/mindmap-content.d.ts +55 -0
  50. package/scripts/generators/mindmap-content.d.ts.map +1 -0
  51. package/scripts/generators/mindmap-content.js +512 -0
  52. package/scripts/generators/mindmap-content.js.map +1 -0
  53. package/scripts/generators/motions-content.d.ts +50 -0
  54. package/scripts/generators/motions-content.d.ts.map +1 -0
  55. package/scripts/generators/motions-content.js +391 -0
  56. package/scripts/generators/motions-content.js.map +1 -0
  57. package/scripts/generators/news-enhanced.d.ts +14 -0
  58. package/scripts/generators/news-enhanced.d.ts.map +1 -0
  59. package/scripts/generators/news-enhanced.js +169 -0
  60. package/scripts/generators/news-enhanced.js.map +1 -0
  61. package/scripts/generators/news-indexes.d.ts +31 -0
  62. package/scripts/generators/news-indexes.d.ts.map +1 -0
  63. package/scripts/generators/news-indexes.js +410 -0
  64. package/scripts/generators/news-indexes.js.map +1 -0
  65. package/scripts/generators/pipeline/fetch-stage.d.ts +352 -0
  66. package/scripts/generators/pipeline/fetch-stage.d.ts.map +1 -0
  67. package/scripts/generators/pipeline/fetch-stage.js +1522 -0
  68. package/scripts/generators/pipeline/fetch-stage.js.map +1 -0
  69. package/scripts/generators/pipeline/generate-stage.d.ts +43 -0
  70. package/scripts/generators/pipeline/generate-stage.d.ts.map +1 -0
  71. package/scripts/generators/pipeline/generate-stage.js +204 -0
  72. package/scripts/generators/pipeline/generate-stage.js.map +1 -0
  73. package/scripts/generators/pipeline/output-stage.d.ts +48 -0
  74. package/scripts/generators/pipeline/output-stage.d.ts.map +1 -0
  75. package/scripts/generators/pipeline/output-stage.js +145 -0
  76. package/scripts/generators/pipeline/output-stage.js.map +1 -0
  77. package/scripts/generators/pipeline/transform-stage.d.ts +57 -0
  78. package/scripts/generators/pipeline/transform-stage.d.ts.map +1 -0
  79. package/scripts/generators/pipeline/transform-stage.js +111 -0
  80. package/scripts/generators/pipeline/transform-stage.js.map +1 -0
  81. package/scripts/generators/propositions-content.d.ts +29 -0
  82. package/scripts/generators/propositions-content.d.ts.map +1 -0
  83. package/scripts/generators/propositions-content.js +90 -0
  84. package/scripts/generators/propositions-content.js.map +1 -0
  85. package/scripts/generators/sankey-content.d.ts +45 -0
  86. package/scripts/generators/sankey-content.d.ts.map +1 -0
  87. package/scripts/generators/sankey-content.js +227 -0
  88. package/scripts/generators/sankey-content.js.map +1 -0
  89. package/scripts/generators/sitemap.d.ts +66 -0
  90. package/scripts/generators/sitemap.d.ts.map +1 -0
  91. package/scripts/generators/sitemap.js +562 -0
  92. package/scripts/generators/sitemap.js.map +1 -0
  93. package/scripts/generators/strategies/article-strategy.d.ts +146 -0
  94. package/scripts/generators/strategies/article-strategy.d.ts.map +1 -0
  95. package/scripts/generators/strategies/article-strategy.js +4 -0
  96. package/scripts/generators/strategies/article-strategy.js.map +1 -0
  97. package/scripts/generators/strategies/breaking-news-strategy.d.ts +64 -0
  98. package/scripts/generators/strategies/breaking-news-strategy.d.ts.map +1 -0
  99. package/scripts/generators/strategies/breaking-news-strategy.js +246 -0
  100. package/scripts/generators/strategies/breaking-news-strategy.js.map +1 -0
  101. package/scripts/generators/strategies/committee-reports-strategy.d.ts +93 -0
  102. package/scripts/generators/strategies/committee-reports-strategy.d.ts.map +1 -0
  103. package/scripts/generators/strategies/committee-reports-strategy.js +447 -0
  104. package/scripts/generators/strategies/committee-reports-strategy.js.map +1 -0
  105. package/scripts/generators/strategies/month-ahead-strategy.d.ts +60 -0
  106. package/scripts/generators/strategies/month-ahead-strategy.d.ts.map +1 -0
  107. package/scripts/generators/strategies/month-ahead-strategy.js +175 -0
  108. package/scripts/generators/strategies/month-ahead-strategy.js.map +1 -0
  109. package/scripts/generators/strategies/monthly-review-strategy.d.ts +66 -0
  110. package/scripts/generators/strategies/monthly-review-strategy.d.ts.map +1 -0
  111. package/scripts/generators/strategies/monthly-review-strategy.js +204 -0
  112. package/scripts/generators/strategies/monthly-review-strategy.js.map +1 -0
  113. package/scripts/generators/strategies/motions-strategy.d.ts +61 -0
  114. package/scripts/generators/strategies/motions-strategy.d.ts.map +1 -0
  115. package/scripts/generators/strategies/motions-strategy.js +215 -0
  116. package/scripts/generators/strategies/motions-strategy.js.map +1 -0
  117. package/scripts/generators/strategies/propositions-strategy.d.ts +60 -0
  118. package/scripts/generators/strategies/propositions-strategy.d.ts.map +1 -0
  119. package/scripts/generators/strategies/propositions-strategy.js +257 -0
  120. package/scripts/generators/strategies/propositions-strategy.js.map +1 -0
  121. package/scripts/generators/strategies/week-ahead-strategy.d.ts +57 -0
  122. package/scripts/generators/strategies/week-ahead-strategy.d.ts.map +1 -0
  123. package/scripts/generators/strategies/week-ahead-strategy.js +178 -0
  124. package/scripts/generators/strategies/week-ahead-strategy.js.map +1 -0
  125. package/scripts/generators/strategies/weekly-review-strategy.d.ts +63 -0
  126. package/scripts/generators/strategies/weekly-review-strategy.d.ts.map +1 -0
  127. package/scripts/generators/strategies/weekly-review-strategy.js +211 -0
  128. package/scripts/generators/strategies/weekly-review-strategy.js.map +1 -0
  129. package/scripts/generators/swot-content.d.ts +42 -0
  130. package/scripts/generators/swot-content.d.ts.map +1 -0
  131. package/scripts/generators/swot-content.js +366 -0
  132. package/scripts/generators/swot-content.js.map +1 -0
  133. package/scripts/generators/week-ahead-content.d.ts +103 -0
  134. package/scripts/generators/week-ahead-content.d.ts.map +1 -0
  135. package/scripts/generators/week-ahead-content.js +610 -0
  136. package/scripts/generators/week-ahead-content.js.map +1 -0
  137. package/scripts/index.d.ts +40 -0
  138. package/scripts/index.d.ts.map +1 -0
  139. package/scripts/index.js +53 -0
  140. package/scripts/index.js.map +1 -0
  141. package/scripts/mcp/ep-mcp-client.d.ts +471 -0
  142. package/scripts/mcp/ep-mcp-client.d.ts.map +1 -0
  143. package/scripts/mcp/ep-mcp-client.js +734 -0
  144. package/scripts/mcp/ep-mcp-client.js.map +1 -0
  145. package/scripts/mcp/mcp-connection.d.ts +264 -0
  146. package/scripts/mcp/mcp-connection.d.ts.map +1 -0
  147. package/scripts/mcp/mcp-connection.js +790 -0
  148. package/scripts/mcp/mcp-connection.js.map +1 -0
  149. package/scripts/mcp/mcp-health.d.ts +75 -0
  150. package/scripts/mcp/mcp-health.d.ts.map +1 -0
  151. package/scripts/mcp/mcp-health.js +78 -0
  152. package/scripts/mcp/mcp-health.js.map +1 -0
  153. package/scripts/mcp/mcp-retry.d.ts +94 -0
  154. package/scripts/mcp/mcp-retry.d.ts.map +1 -0
  155. package/scripts/mcp/mcp-retry.js +127 -0
  156. package/scripts/mcp/mcp-retry.js.map +1 -0
  157. package/scripts/mcp/wb-mcp-client.d.ts +38 -0
  158. package/scripts/mcp/wb-mcp-client.d.ts.map +1 -0
  159. package/scripts/mcp/wb-mcp-client.js +112 -0
  160. package/scripts/mcp/wb-mcp-client.js.map +1 -0
  161. package/scripts/templates/article-template.d.ts +9 -0
  162. package/scripts/templates/article-template.d.ts.map +1 -0
  163. package/scripts/templates/article-template.js +378 -0
  164. package/scripts/templates/article-template.js.map +1 -0
  165. package/scripts/templates/section-builders.d.ts +28 -0
  166. package/scripts/templates/section-builders.d.ts.map +1 -0
  167. package/scripts/templates/section-builders.js +142 -0
  168. package/scripts/templates/section-builders.js.map +1 -0
  169. package/scripts/types/analysis.d.ts +115 -0
  170. package/scripts/types/analysis.d.ts.map +1 -0
  171. package/scripts/types/analysis.js +4 -0
  172. package/scripts/types/analysis.js.map +1 -0
  173. package/scripts/types/common.d.ts +584 -0
  174. package/scripts/types/common.d.ts.map +1 -0
  175. package/scripts/types/common.js +96 -0
  176. package/scripts/types/common.js.map +1 -0
  177. package/scripts/types/generation.d.ts +104 -0
  178. package/scripts/types/generation.d.ts.map +1 -0
  179. package/scripts/types/generation.js +4 -0
  180. package/scripts/types/generation.js.map +1 -0
  181. package/scripts/types/index.d.ts +24 -0
  182. package/scripts/types/index.d.ts.map +1 -0
  183. package/scripts/types/index.js +16 -0
  184. package/scripts/types/index.js.map +1 -0
  185. package/scripts/types/intelligence.d.ts +129 -0
  186. package/scripts/types/intelligence.d.ts.map +1 -0
  187. package/scripts/types/intelligence.js +4 -0
  188. package/scripts/types/intelligence.js.map +1 -0
  189. package/scripts/types/mcp.d.ts +418 -0
  190. package/scripts/types/mcp.d.ts.map +1 -0
  191. package/scripts/types/mcp.js +4 -0
  192. package/scripts/types/mcp.js.map +1 -0
  193. package/scripts/types/parliament.d.ts +388 -0
  194. package/scripts/types/parliament.d.ts.map +1 -0
  195. package/scripts/types/parliament.js +4 -0
  196. package/scripts/types/parliament.js.map +1 -0
  197. package/scripts/types/quality.d.ts +114 -0
  198. package/scripts/types/quality.d.ts.map +1 -0
  199. package/scripts/types/quality.js +4 -0
  200. package/scripts/types/quality.js.map +1 -0
  201. package/scripts/types/stakeholder.d.ts +88 -0
  202. package/scripts/types/stakeholder.d.ts.map +1 -0
  203. package/scripts/types/stakeholder.js +16 -0
  204. package/scripts/types/stakeholder.js.map +1 -0
  205. package/scripts/types/visualization.d.ts +708 -0
  206. package/scripts/types/visualization.d.ts.map +1 -0
  207. package/scripts/types/visualization.js +4 -0
  208. package/scripts/types/visualization.js.map +1 -0
  209. package/scripts/types/world-bank.d.ts +85 -0
  210. package/scripts/types/world-bank.d.ts.map +1 -0
  211. package/scripts/types/world-bank.js +4 -0
  212. package/scripts/types/world-bank.js.map +1 -0
  213. package/scripts/utils/article-category.d.ts +18 -0
  214. package/scripts/utils/article-category.d.ts.map +1 -0
  215. package/scripts/utils/article-category.js +49 -0
  216. package/scripts/utils/article-category.js.map +1 -0
  217. package/scripts/utils/article-quality-scorer.d.ts +87 -0
  218. package/scripts/utils/article-quality-scorer.d.ts.map +1 -0
  219. package/scripts/utils/article-quality-scorer.js +1048 -0
  220. package/scripts/utils/article-quality-scorer.js.map +1 -0
  221. package/scripts/utils/content-metadata.d.ts +34 -0
  222. package/scripts/utils/content-metadata.d.ts.map +1 -0
  223. package/scripts/utils/content-metadata.js +249 -0
  224. package/scripts/utils/content-metadata.js.map +1 -0
  225. package/scripts/utils/content-validator.d.ts +94 -0
  226. package/scripts/utils/content-validator.d.ts.map +1 -0
  227. package/scripts/utils/content-validator.js +489 -0
  228. package/scripts/utils/content-validator.js.map +1 -0
  229. package/scripts/utils/copy-test-reports.d.ts +9 -0
  230. package/scripts/utils/copy-test-reports.d.ts.map +1 -0
  231. package/scripts/utils/copy-test-reports.js +508 -0
  232. package/scripts/utils/copy-test-reports.js.map +1 -0
  233. package/scripts/utils/file-utils.d.ts +144 -0
  234. package/scripts/utils/file-utils.d.ts.map +1 -0
  235. package/scripts/utils/file-utils.js +374 -0
  236. package/scripts/utils/file-utils.js.map +1 -0
  237. package/scripts/utils/fix-articles.d.ts +27 -0
  238. package/scripts/utils/fix-articles.d.ts.map +1 -0
  239. package/scripts/utils/fix-articles.js +510 -0
  240. package/scripts/utils/fix-articles.js.map +1 -0
  241. package/scripts/utils/generate-docs-index.d.ts +8 -0
  242. package/scripts/utils/generate-docs-index.d.ts.map +1 -0
  243. package/scripts/utils/generate-docs-index.js +275 -0
  244. package/scripts/utils/generate-docs-index.js.map +1 -0
  245. package/scripts/utils/html-sanitize.d.ts +18 -0
  246. package/scripts/utils/html-sanitize.d.ts.map +1 -0
  247. package/scripts/utils/html-sanitize.js +57 -0
  248. package/scripts/utils/html-sanitize.js.map +1 -0
  249. package/scripts/utils/intelligence-analysis.d.ts +173 -0
  250. package/scripts/utils/intelligence-analysis.d.ts.map +1 -0
  251. package/scripts/utils/intelligence-analysis.js +936 -0
  252. package/scripts/utils/intelligence-analysis.js.map +1 -0
  253. package/scripts/utils/intelligence-index.d.ts +126 -0
  254. package/scripts/utils/intelligence-index.d.ts.map +1 -0
  255. package/scripts/utils/intelligence-index.js +731 -0
  256. package/scripts/utils/intelligence-index.js.map +1 -0
  257. package/scripts/utils/metadata-utils.d.ts +14 -0
  258. package/scripts/utils/metadata-utils.d.ts.map +1 -0
  259. package/scripts/utils/metadata-utils.js +18 -0
  260. package/scripts/utils/metadata-utils.js.map +1 -0
  261. package/scripts/utils/news-metadata.d.ts +47 -0
  262. package/scripts/utils/news-metadata.d.ts.map +1 -0
  263. package/scripts/utils/news-metadata.js +259 -0
  264. package/scripts/utils/news-metadata.js.map +1 -0
  265. package/scripts/utils/validate-articles.d.ts +2 -0
  266. package/scripts/utils/validate-articles.d.ts.map +1 -0
  267. package/scripts/utils/validate-articles.js +284 -0
  268. package/scripts/utils/validate-articles.js.map +1 -0
  269. package/scripts/utils/validate-ep-api.d.ts +51 -0
  270. package/scripts/utils/validate-ep-api.d.ts.map +1 -0
  271. package/scripts/utils/validate-ep-api.js +160 -0
  272. package/scripts/utils/validate-ep-api.js.map +1 -0
  273. package/scripts/utils/world-bank-data.d.ts +84 -0
  274. package/scripts/utils/world-bank-data.d.ts.map +1 -0
  275. package/scripts/utils/world-bank-data.js +311 -0
  276. package/scripts/utils/world-bank-data.js.map +1 -0
@@ -0,0 +1,731 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Hack23 AB
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * @module Utils/IntelligenceIndex
5
+ * @description Cross-article intelligence indexing system for parliamentary trend tracking.
6
+ *
7
+ * Provides functions to build, query, and persist an {@link IntelligenceIndex} that
8
+ * tracks relationships between generated articles, detects recurring trends, and groups
9
+ * related articles into series. The index is JSON-serialisable for disk persistence.
10
+ */
11
+ import fs from 'fs';
12
+ import path from 'path';
13
+ import { ArticleCategory } from '../types/index.js';
14
+ import { RELATED_ANALYSIS_LABELS, getLocalizedString } from '../constants/languages.js';
15
+ // ─── Minimum article count to confirm a trend ────────────────────────────────
16
+ /** Minimum number of articles required to recognise a trend */
17
+ const MIN_TREND_ARTICLES = 2;
18
+ /** Maximum cross-reference results when no limit is specified */
19
+ const DEFAULT_MAX_RELATED = 10;
20
+ /**
21
+ * Keys that must never be used as lookup-map indices to prevent
22
+ * prototype-pollution attacks from untrusted article metadata.
23
+ *
24
+ * - `__proto__` — directly sets the prototype chain of plain objects
25
+ * - `constructor` — can be used to reach `Object` and mutate shared prototypes
26
+ * - `prototype` — when combined with `constructor`, enables prototype injection
27
+ */
28
+ const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
29
+ /**
30
+ * Return `true` when `key` is safe to use as a plain-object property.
31
+ * Rejects `__proto__`, `constructor`, and `prototype` to avoid prototype
32
+ * pollution when indexing untrusted topic/actor/procedure strings.
33
+ *
34
+ * @param key - The key to validate
35
+ * @returns `true` if the key is safe to use as an object property
36
+ */
37
+ function isSafeKey(key) {
38
+ return !DANGEROUS_KEYS.has(key);
39
+ }
40
+ /**
41
+ * Create a null-prototype object suitable for use as a lookup map.
42
+ * Unlike `{}`, these objects have no inherited keys, providing an extra
43
+ * layer of defence against prototype-pollution.
44
+ *
45
+ * @returns A fresh null-prototype Record for use as a lookup map
46
+ */
47
+ function createNullMap() {
48
+ return Object.create(null);
49
+ }
50
+ // ─── createEmptyIndex ────────────────────────────────────────────────────────
51
+ /**
52
+ * Create a fresh, empty {@link IntelligenceIndex}.
53
+ *
54
+ * @returns An empty index with no articles, actors, domains, trends, or series
55
+ */
56
+ export function createEmptyIndex() {
57
+ return {
58
+ articles: [],
59
+ actors: createNullMap(),
60
+ policyDomains: createNullMap(),
61
+ procedures: createNullMap(),
62
+ trends: [],
63
+ series: [],
64
+ lastUpdated: new Date().toISOString(),
65
+ };
66
+ }
67
+ // ─── addArticleToIndex ───────────────────────────────────────────────────────
68
+ /**
69
+ * Add an {@link ArticleIndexEntry} to the index and keep all lookup maps in sync.
70
+ *
71
+ * The function is immutable-safe: it returns a new index object rather than
72
+ * mutating the supplied one. Duplicate entries (same `id`) are replaced.
73
+ *
74
+ * @param index - Existing intelligence index
75
+ * @param entry - Article index entry to add
76
+ * @returns Updated index with the new entry reflected in all maps
77
+ */
78
+ export function addArticleToIndex(index, entry) {
79
+ // Replace or append
80
+ const existingIdx = index.articles.findIndex((a) => a.id === entry.id);
81
+ const oldEntry = existingIdx >= 0 ? index.articles[existingIdx] : undefined; // eslint-disable-line security/detect-object-injection -- existingIdx from findIndex
82
+ const articles = existingIdx >= 0
83
+ ? [...index.articles.slice(0, existingIdx), entry, ...index.articles.slice(existingIdx + 1)]
84
+ : [...index.articles, entry];
85
+ // Clone lookup maps (null-prototype to prevent pollution)
86
+ const actors = Object.assign(createNullMap(), index.actors);
87
+ const policyDomains = Object.assign(createNullMap(), index.policyDomains);
88
+ const procedures = Object.assign(createNullMap(), index.procedures);
89
+ // Remove stale associations from the old entry (if replacing)
90
+ if (oldEntry) {
91
+ removeIdFromMap(actors, oldEntry.keyActors, entry.id);
92
+ removeIdFromMap(policyDomains, oldEntry.keyTopics, entry.id);
93
+ removeIdFromMap(procedures, oldEntry.procedures, entry.id);
94
+ }
95
+ // Add new associations
96
+ addIdToMap(actors, entry.keyActors, entry.id);
97
+ addIdToMap(policyDomains, entry.keyTopics, entry.id);
98
+ addIdToMap(procedures, entry.procedures, entry.id);
99
+ return {
100
+ ...index,
101
+ articles,
102
+ actors,
103
+ policyDomains,
104
+ procedures,
105
+ lastUpdated: new Date().toISOString(),
106
+ };
107
+ }
108
+ // ─── buildIndexFromEntries ────────────────────────────────────────────────────
109
+ /**
110
+ * Build a complete index from an array of entries in O(n) time.
111
+ *
112
+ * Unlike calling {@link addArticleToIndex} in a loop (which clones maps on every
113
+ * call, yielding O(n²) behaviour), this function mutates local maps in a single
114
+ * pass and returns a final immutable index.
115
+ *
116
+ * @param entries - All article entries to include
117
+ * @returns A fully populated {@link IntelligenceIndex}
118
+ */
119
+ export function buildIndexFromEntries(entries) {
120
+ const actors = createNullMap();
121
+ const policyDomains = createNullMap();
122
+ const procedures = createNullMap();
123
+ for (const entry of entries) {
124
+ addIdToMap(actors, entry.keyActors, entry.id);
125
+ addIdToMap(policyDomains, entry.keyTopics, entry.id);
126
+ addIdToMap(procedures, entry.procedures, entry.id);
127
+ }
128
+ return {
129
+ articles: [...entries],
130
+ actors,
131
+ policyDomains,
132
+ procedures,
133
+ trends: [],
134
+ series: [],
135
+ lastUpdated: new Date().toISOString(),
136
+ };
137
+ }
138
+ // ─── findRelatedArticles ─────────────────────────────────────────────────────
139
+ /**
140
+ * Find articles that share topics or actors with the supplied lists.
141
+ *
142
+ * Results are scored by overlap count and returned in descending relevance order.
143
+ *
144
+ * @param index - Intelligence index to search
145
+ * @param topics - Key topics to match against `keyTopics`
146
+ * @param actors - Key actors to match against `keyActors`
147
+ * @param maxResults - Maximum number of results to return (default: 10)
148
+ * @returns Scored, sorted array of matching article entries
149
+ */
150
+ export function findRelatedArticles(index, topics, actors, maxResults = DEFAULT_MAX_RELATED) {
151
+ if (topics.length === 0 && actors.length === 0) {
152
+ return [];
153
+ }
154
+ const topicSet = new Set(topics);
155
+ const actorSet = new Set(actors);
156
+ const scored = index.articles.map((article) => {
157
+ let score = 0;
158
+ for (const t of article.keyTopics) {
159
+ if (topicSet.has(t))
160
+ score++;
161
+ }
162
+ for (const a of article.keyActors) {
163
+ if (actorSet.has(a))
164
+ score++;
165
+ }
166
+ return { article, score };
167
+ });
168
+ return scored
169
+ .filter(({ score }) => score > 0)
170
+ .sort((a, b) => b.score - a.score)
171
+ .slice(0, maxResults)
172
+ .map(({ article }) => article);
173
+ }
174
+ // ─── generateCrossReferences ─────────────────────────────────────────────────
175
+ /**
176
+ * Auto-generate {@link ArticleCrossReference} objects for an article based on
177
+ * topic and actor overlap with existing index entries.
178
+ *
179
+ * **Strength** is determined by total overlap (topics + actors):
180
+ * - ≥3 shared items → `strong`
181
+ * - 2 shared items → `moderate`
182
+ * - 1 shared item → `weak`
183
+ *
184
+ * **Relationship** is determined by date comparison:
185
+ * - Target article is older (`date < entry.date`) → `follows_up`
186
+ * - Target article is newer (`date > entry.date`) → `preceded_by`
187
+ * - Target article has the same date → `related`
188
+ *
189
+ * @param index - Intelligence index containing previously indexed articles
190
+ * @param entry - The article for which cross-references should be generated
191
+ * @returns Array of auto-generated cross-references (excludes self-references)
192
+ */
193
+ export function generateCrossReferences(index, entry) {
194
+ const related = findRelatedArticles(index, entry.keyTopics, entry.keyActors);
195
+ return related
196
+ .filter((a) => a.id !== entry.id)
197
+ .map((a) => {
198
+ const topicOverlap = a.keyTopics.filter((t) => entry.keyTopics.includes(t)).length;
199
+ const actorOverlap = a.keyActors.filter((ac) => entry.keyActors.includes(ac)).length;
200
+ const totalOverlap = topicOverlap + actorOverlap;
201
+ const strength = totalOverlap >= 3 ? 'strong' : totalOverlap === 2 ? 'moderate' : 'weak';
202
+ const relationship = a.date < entry.date ? 'follows_up' : a.date > entry.date ? 'preceded_by' : 'related';
203
+ const context = topicOverlap > 0 && actorOverlap > 0
204
+ ? `Shares ${topicOverlap} topic(s) and ${actorOverlap} actor(s)`
205
+ : topicOverlap > 0
206
+ ? `Shares ${topicOverlap} topic(s)`
207
+ : `Shares ${actorOverlap} actor(s)`;
208
+ const ref = {
209
+ targetArticleId: a.id,
210
+ relationship,
211
+ context,
212
+ strength,
213
+ };
214
+ return ref;
215
+ });
216
+ }
217
+ // ─── detectTrends ────────────────────────────────────────────────────────────
218
+ /**
219
+ * Resolve confidence level from the number of article references.
220
+ * @param count - Number of articles referencing the topic
221
+ * @returns Confidence level
222
+ */
223
+ function resolveConfidence(count) {
224
+ if (count >= 5)
225
+ return 'high';
226
+ if (count >= 3)
227
+ return 'medium';
228
+ return 'low';
229
+ }
230
+ /**
231
+ * Resolve date range from a list of articles matching a set of IDs.
232
+ * @param index - The intelligence index
233
+ * @param articleIds - IDs of articles to consider
234
+ * @returns firstSeen and lastUpdated date strings
235
+ */
236
+ function resolveDateRange(index, articleIds) {
237
+ const fallback = new Date().toISOString().slice(0, 10);
238
+ const dates = index.articles
239
+ .filter((a) => articleIds.includes(a.id))
240
+ .map((a) => a.date)
241
+ .sort();
242
+ return {
243
+ firstSeen: dates[0] ?? fallback,
244
+ lastUpdated: dates[dates.length - 1] ?? fallback,
245
+ };
246
+ }
247
+ /**
248
+ * Build a topic-based trend entry.
249
+ * @param index - Intelligence index
250
+ * @param topic - Topic key
251
+ * @param articleIds - Article IDs covering this topic
252
+ * @returns TrendDetection entry
253
+ */
254
+ function buildTopicTrend(index, topic, articleIds) {
255
+ const { firstSeen, lastUpdated } = resolveDateRange(index, articleIds);
256
+ const confidence = resolveConfidence(articleIds.length);
257
+ const direction = articleIds.length >= 4 ? 'strengthening' : 'emerging';
258
+ return {
259
+ id: `trend-topic-${slugify(topic)}`,
260
+ name: `${topic} trend`,
261
+ category: 'political',
262
+ direction,
263
+ firstSeen,
264
+ lastUpdated,
265
+ articleReferences: [...articleIds],
266
+ evidence: [`Topic "${topic}" covered in ${articleIds.length} articles`],
267
+ confidence,
268
+ };
269
+ }
270
+ /**
271
+ * Build a procedure-based trend entry.
272
+ * @param index - Intelligence index
273
+ * @param proc - Procedure reference
274
+ * @param articleIds - Article IDs covering this procedure
275
+ * @returns TrendDetection entry
276
+ */
277
+ function buildProcedureTrend(index, proc, articleIds) {
278
+ const { firstSeen, lastUpdated } = resolveDateRange(index, articleIds);
279
+ const confidence = resolveConfidence(articleIds.length);
280
+ return {
281
+ id: `trend-proc-${slugify(proc)}`,
282
+ name: `Procedure ${proc} tracking`,
283
+ category: 'legislative',
284
+ direction: 'stable',
285
+ firstSeen,
286
+ lastUpdated,
287
+ articleReferences: [...articleIds],
288
+ evidence: [`Procedure "${proc}" tracked across ${articleIds.length} articles`],
289
+ confidence,
290
+ };
291
+ }
292
+ /**
293
+ * Detect parliamentary trends from patterns across all indexed articles.
294
+ *
295
+ * A trend is formed when a topic or procedure appears in at least
296
+ * {@link MIN_TREND_ARTICLES} articles. The returned array replaces any
297
+ * previously detected trends stored in the index.
298
+ *
299
+ * @param index - Intelligence index to analyse
300
+ * @returns Array of detected {@link TrendDetection} objects
301
+ */
302
+ export function detectTrends(index) {
303
+ const trends = [];
304
+ for (const [topic, articleIds] of Object.entries(index.policyDomains)) {
305
+ if (articleIds.length >= MIN_TREND_ARTICLES) {
306
+ trends.push(buildTopicTrend(index, topic, articleIds));
307
+ }
308
+ }
309
+ for (const [proc, articleIds] of Object.entries(index.procedures)) {
310
+ if (articleIds.length >= MIN_TREND_ARTICLES) {
311
+ trends.push(buildProcedureTrend(index, proc, articleIds));
312
+ }
313
+ }
314
+ return trends;
315
+ }
316
+ // ─── findOrCreateSeries ──────────────────────────────────────────────────────
317
+ /**
318
+ * Find an existing {@link ArticleSeries} for the given procedure reference, or
319
+ * create a new one and add it to the index.
320
+ *
321
+ * **Note:** This function mutates `index.series` for convenience. Callers that
322
+ * require immutability should replace the series array after calling this.
323
+ *
324
+ * @param index - Intelligence index to search / mutate
325
+ * @param procedureRef - EP procedure reference (e.g. "2024/0001(COD)")
326
+ * @param name - Display name for the series if it needs to be created
327
+ * @returns The found or newly created series
328
+ */
329
+ export function findOrCreateSeries(index, procedureRef, name) {
330
+ const existing = index.series.find((s) => s.procedureRef === procedureRef);
331
+ if (existing) {
332
+ return existing;
333
+ }
334
+ const newSeries = {
335
+ id: `series-${slugify(procedureRef)}`,
336
+ name,
337
+ procedureRef,
338
+ articles: [],
339
+ status: 'ongoing',
340
+ summary: `Tracking legislative procedure ${procedureRef}`,
341
+ };
342
+ index.series.push(newSeries);
343
+ return newSeries;
344
+ }
345
+ // ─── normalizeArticleEntry ────────────────────────────────────────────────────
346
+ /**
347
+ * Ensure an {@link ArticleIndexEntry} loaded from disk has all required fields.
348
+ *
349
+ * Persisted JSON may be missing arrays or strings after schema evolution; this
350
+ * function fills safe defaults so downstream code never crashes on `undefined`.
351
+ *
352
+ * @param entry - Potentially partial article entry from parsed JSON
353
+ * @returns A fully populated {@link ArticleIndexEntry}
354
+ */
355
+ function normalizeArticleEntry(entry) {
356
+ const VALID_CATEGORIES = new Set(Object.values(ArticleCategory));
357
+ return {
358
+ id: typeof entry.id === 'string' ? entry.id : '',
359
+ date: typeof entry.date === 'string' ? entry.date : '',
360
+ type: typeof entry.type === 'string' && VALID_CATEGORIES.has(entry.type)
361
+ ? entry.type
362
+ : ArticleCategory.WEEK_AHEAD,
363
+ lang: typeof entry.lang === 'string' ? entry.lang : 'en',
364
+ keyTopics: Array.isArray(entry.keyTopics) ? entry.keyTopics : [],
365
+ keyActors: Array.isArray(entry.keyActors) ? entry.keyActors : [],
366
+ procedures: Array.isArray(entry.procedures) ? entry.procedures : [],
367
+ crossReferences: Array.isArray(entry.crossReferences) ? entry.crossReferences : [],
368
+ trendContributions: Array.isArray(entry.trendContributions) ? entry.trendContributions : [],
369
+ ...(typeof entry.seriesId === 'string' && { seriesId: entry.seriesId }),
370
+ };
371
+ }
372
+ // ─── rebuildLookupMaps ──────────────────────────────────────────────────────
373
+ /**
374
+ * Rebuild the actor/policyDomain/procedure reverse-lookup maps from scratch
375
+ * by scanning all articles.
376
+ *
377
+ * Used during index loading when persisted maps are missing or invalid (e.g.
378
+ * after a schema evolution), so that trend detection and lookups stay correct.
379
+ *
380
+ * @param articles - Normalised article entries to rebuild maps from
381
+ * @returns Rebuilt lookup maps
382
+ */
383
+ function rebuildLookupMaps(articles) {
384
+ const actors = createNullMap();
385
+ const policyDomains = createNullMap();
386
+ const procedures = createNullMap();
387
+ for (const article of articles) {
388
+ addIdToMap(actors, article.keyActors, article.id);
389
+ addIdToMap(policyDomains, article.keyTopics, article.id);
390
+ addIdToMap(procedures, article.procedures, article.id);
391
+ }
392
+ return { actors, policyDomains, procedures };
393
+ }
394
+ // ─── loadIntelligenceIndex ───────────────────────────────────────────────────
395
+ /**
396
+ * Load an {@link IntelligenceIndex} from a JSON file.
397
+ *
398
+ * Returns an empty index (via {@link createEmptyIndex}) if the file does not exist
399
+ * or cannot be parsed.
400
+ *
401
+ * Each loaded {@link ArticleIndexEntry} is normalised so that missing arrays
402
+ * and strings are filled with safe defaults, preventing crashes in downstream
403
+ * code that iterates over `keyTopics`, `keyActors`, etc.
404
+ *
405
+ * When any lookup map (actors, policyDomains, procedures) is missing or invalid
406
+ * but articles are present, all maps are rebuilt from the article entries so that
407
+ * trend detection and lookups remain correct across schema upgrades.
408
+ *
409
+ * @param indexPath - Absolute or relative path to the index JSON file
410
+ * @returns Loaded index, or a fresh empty index on failure
411
+ */
412
+ export function loadIntelligenceIndex(indexPath) {
413
+ if (!fs.existsSync(indexPath)) {
414
+ return createEmptyIndex();
415
+ }
416
+ try {
417
+ const content = fs.readFileSync(indexPath, 'utf-8');
418
+ const parsed = JSON.parse(content);
419
+ return mergeOntoEmpty(parsed);
420
+ }
421
+ catch {
422
+ return createEmptyIndex();
423
+ }
424
+ }
425
+ /**
426
+ * Merge partially-parsed JSON onto a fresh empty index, normalising articles and
427
+ * rebuilding lookup maps when they are missing or invalid. When maps are rebuilt
428
+ * (or when persisted trends are missing), trends are also recomputed from articles
429
+ * so trend detection stays correct across schema upgrades.
430
+ *
431
+ * @param parsed - Potentially partial index from disk
432
+ * @returns Fully populated {@link IntelligenceIndex}
433
+ */
434
+ function mergeOntoEmpty(parsed) {
435
+ const empty = createEmptyIndex();
436
+ const articles = Array.isArray(parsed.articles)
437
+ ? parsed.articles.map(normalizeArticleEntry)
438
+ : empty.articles;
439
+ const { actors, policyDomains, procedures, rebuilt } = resolveOrRebuildMaps(parsed, articles, empty);
440
+ // Build a temporary index so detectTrends can recompute from articles
441
+ const base = {
442
+ articles,
443
+ actors,
444
+ policyDomains,
445
+ procedures,
446
+ trends: empty.trends,
447
+ series: Array.isArray(parsed.series) ? parsed.series : empty.series,
448
+ lastUpdated: typeof parsed.lastUpdated === 'string' ? parsed.lastUpdated : empty.lastUpdated,
449
+ };
450
+ // Recompute trends when maps were rebuilt or when persisted trends are missing/invalid
451
+ const trends = rebuilt || !Array.isArray(parsed.trends) ? detectTrends(base) : parsed.trends;
452
+ return { ...base, trends };
453
+ }
454
+ /**
455
+ * Check whether a value is a valid lookup map (`Record<string, string[]>`).
456
+ *
457
+ * Validates that the value is a non-array object **and** that every entry
458
+ * is an array of strings. Malformed/corrupt JSON (e.g. `{ EPP: "a1" }`)
459
+ * will return `false`, triggering a map rebuild from articles on load.
460
+ *
461
+ * @param value - Value to validate
462
+ * @returns `true` if the value is a well-formed lookup map
463
+ */
464
+ function isValidMap(value) {
465
+ if (!value || typeof value !== 'object' || Array.isArray(value))
466
+ return false;
467
+ const record = value;
468
+ return Object.values(record).every((v) => Array.isArray(v) && v.every((item) => typeof item === 'string'));
469
+ }
470
+ /**
471
+ * Copy a structurally valid parsed map into a fresh null-prototype object,
472
+ * filtering out dangerous keys to maintain prototype-pollution protection
473
+ * even when loading from potentially tampered JSON.
474
+ *
475
+ * @param source - Validated lookup map from parsed JSON
476
+ * @returns A sanitised null-prototype copy with dangerous keys removed
477
+ */
478
+ function sanitizeMap(source) {
479
+ const safe = createNullMap();
480
+ for (const key of Object.keys(source)) {
481
+ if (!isSafeKey(key))
482
+ continue;
483
+ // eslint-disable-next-line security/detect-object-injection -- key validated via isSafeKey
484
+ const val = source[key];
485
+ if (val) {
486
+ // eslint-disable-next-line security/detect-object-injection -- key validated via isSafeKey
487
+ safe[key] = val;
488
+ }
489
+ }
490
+ return safe;
491
+ }
492
+ /**
493
+ * Return lookup maps from the parsed JSON when all three are valid, or rebuild
494
+ * them from the article entries when any map is missing/invalid.
495
+ *
496
+ * Valid parsed maps are always copied into fresh null-prototype objects with
497
+ * unsafe keys filtered out, so that tampered index JSON cannot reintroduce
498
+ * prototype-pollution vectors (e.g. `__proto__` keys).
499
+ *
500
+ * @param parsed - Partially parsed index from disk
501
+ * @param articles - Normalised article entries
502
+ * @param empty - Fallback empty index for defaults
503
+ * @returns Resolved or rebuilt lookup maps
504
+ */
505
+ function resolveOrRebuildMaps(parsed, articles, empty) {
506
+ const validActors = isValidMap(parsed.actors);
507
+ const validDomains = isValidMap(parsed.policyDomains);
508
+ const validProcedures = isValidMap(parsed.procedures);
509
+ if (articles.length > 0 && (!validActors || !validDomains || !validProcedures)) {
510
+ return { ...rebuildLookupMaps(articles), rebuilt: true };
511
+ }
512
+ return {
513
+ actors: validActors ? sanitizeMap(parsed.actors) : empty.actors,
514
+ policyDomains: validDomains
515
+ ? sanitizeMap(parsed.policyDomains)
516
+ : empty.policyDomains,
517
+ procedures: validProcedures
518
+ ? sanitizeMap(parsed.procedures)
519
+ : empty.procedures,
520
+ rebuilt: false,
521
+ };
522
+ }
523
+ // ─── saveIntelligenceIndex ───────────────────────────────────────────────────
524
+ /**
525
+ * Persist an {@link IntelligenceIndex} to a JSON file.
526
+ *
527
+ * Creates any missing parent directories automatically.
528
+ *
529
+ * @param index - Intelligence index to save
530
+ * @param indexPath - Absolute or relative path to the output JSON file
531
+ */
532
+ export function saveIntelligenceIndex(index, indexPath) {
533
+ const dir = path.dirname(indexPath);
534
+ if (!fs.existsSync(dir)) {
535
+ fs.mkdirSync(dir, { recursive: true });
536
+ }
537
+ fs.writeFileSync(indexPath, JSON.stringify(index, null, 2), 'utf-8');
538
+ }
539
+ // ─── buildRelatedArticlesHTML ────────────────────────────────────────────────
540
+ /**
541
+ * Generate an HTML `<section>` listing related articles, cross-references, and
542
+ * emerging trends for embedding in a generated article.
543
+ *
544
+ * Produces accessible markup with `aria-label` and `rel="noopener noreferrer"`.
545
+ * UI strings and date formatting are localised based on the `lang` parameter.
546
+ *
547
+ * @param relatedArticles - Articles related to the current article
548
+ * @param crossRefs - Cross-references from the current article
549
+ * @param trends - Trends relevant to the current article
550
+ * @param lang - Language code for localisation (defaults to 'en')
551
+ * @returns HTML string for the "Related Analysis" section, or empty string if nothing to show
552
+ */
553
+ export function buildRelatedArticlesHTML(relatedArticles, crossRefs, trends, lang) {
554
+ if (relatedArticles.length === 0 && crossRefs.length === 0 && trends.length === 0) {
555
+ return '';
556
+ }
557
+ const strings = getLocalizedString(RELATED_ANALYSIS_LABELS, lang ?? 'en');
558
+ const listItems = crossRefs
559
+ .map((ref) => {
560
+ const article = relatedArticles.find((a) => a.id === ref.targetArticleId);
561
+ const label = strings.relationships[ref.relationship] ??
562
+ strings.relatedArticle;
563
+ if (article) {
564
+ const displayDate = formatDisplayDate(article.date, lang);
565
+ const filename = `${article.id}.html`;
566
+ return ` <li><a href="${escapeAttr(filename)}" rel="noopener noreferrer">${escapeText(label)}: ${escapeText(ref.context)} (${escapeText(displayDate)})</a></li>`;
567
+ }
568
+ // Fallback: render using targetArticleId when full article metadata is unavailable
569
+ const filename = `${ref.targetArticleId}.html`;
570
+ return ` <li><a href="${escapeAttr(filename)}" rel="noopener noreferrer">${escapeText(label)}: ${escapeText(ref.context)}</a></li>`;
571
+ })
572
+ .filter(Boolean);
573
+ // Fall back: show related articles without explicit cross-refs
574
+ if (listItems.length === 0 && relatedArticles.length > 0) {
575
+ for (const article of relatedArticles) {
576
+ const displayDate = formatDisplayDate(article.date, lang);
577
+ const filename = `${article.id}.html`;
578
+ listItems.push(` <li><a href="${escapeAttr(filename)}" rel="noopener noreferrer">${escapeText(strings.relatedArticle)}: ${escapeText(article.type)} (${escapeText(displayDate)})</a></li>`);
579
+ }
580
+ }
581
+ const trendBlocks = trends
582
+ .map((trend) => {
583
+ const count = trend.articleReferences.length;
584
+ return ` <div class="emerging-trends">
585
+ <h4>${escapeText(strings.emergingTrend)}: ${escapeText(trend.name)}</h4>
586
+ <p>${count} ${escapeText(strings.trendTracking)} ${escapeText(trend.name.toLowerCase())} (${escapeText(strings.confidence)}: ${escapeText(trend.confidence)})</p>
587
+ </div>`;
588
+ })
589
+ .join('\n');
590
+ const listSection = listItems.length > 0 ? ` <ul>\n${listItems.join('\n')}\n </ul>` : '';
591
+ const parts = [
592
+ `<section class="related-articles" aria-label="${escapeAttr(strings.sectionLabel)}">`,
593
+ ];
594
+ parts.push(` <h3>${escapeText(strings.heading)}</h3>`);
595
+ if (listSection)
596
+ parts.push(listSection);
597
+ if (trendBlocks)
598
+ parts.push(trendBlocks);
599
+ parts.push('</section>');
600
+ return parts.join('\n');
601
+ }
602
+ // ─── Private helpers ──────────────────────────────────────────────────────────
603
+ /**
604
+ * Remove an article ID from every key's list in a lookup map.
605
+ * Cleans up empty arrays left behind.
606
+ * Skips dangerous keys (`__proto__`, `constructor`, `prototype`) to prevent
607
+ * prototype pollution.
608
+ * @param map - Lookup map (actor/domain/procedure → article IDs)
609
+ * @param keys - Keys to remove the article ID from
610
+ * @param articleId - Article ID to remove
611
+ */
612
+ function removeIdFromMap(map, keys, articleId) {
613
+ for (const key of keys) {
614
+ if (!isSafeKey(key))
615
+ continue;
616
+ // eslint-disable-next-line security/detect-object-injection -- key validated via isSafeKey
617
+ const list = map[key];
618
+ if (!list)
619
+ continue;
620
+ const filtered = list.filter((id) => id !== articleId);
621
+ if (filtered.length === 0) {
622
+ // eslint-disable-next-line security/detect-object-injection -- key validated via isSafeKey
623
+ delete map[key];
624
+ }
625
+ else {
626
+ // eslint-disable-next-line security/detect-object-injection -- key validated via isSafeKey
627
+ map[key] = filtered;
628
+ }
629
+ }
630
+ }
631
+ /**
632
+ * Add an article ID to every key's list in a lookup map (deduplicating).
633
+ * Skips dangerous keys (`__proto__`, `constructor`, `prototype`) to prevent
634
+ * prototype pollution.
635
+ * @param map - Lookup map (actor/domain/procedure → article IDs)
636
+ * @param keys - Keys under which to register the article ID
637
+ * @param articleId - Article ID to add
638
+ */
639
+ function addIdToMap(map, keys, articleId) {
640
+ for (const key of keys) {
641
+ if (!isSafeKey(key))
642
+ continue;
643
+ // eslint-disable-next-line security/detect-object-injection -- key validated via isSafeKey
644
+ const existing = map[key] ?? [];
645
+ if (!existing.includes(articleId)) {
646
+ // eslint-disable-next-line security/detect-object-injection -- key validated via isSafeKey
647
+ map[key] = [...existing, articleId];
648
+ }
649
+ }
650
+ }
651
+ /**
652
+ * Convert a string to a URL-safe slug.
653
+ *
654
+ * Uses Unicode-aware character classes so non-Latin scripts (e.g. Arabic,
655
+ * Hebrew, CJK) produce meaningful slugs instead of collapsing to `""`.
656
+ * When the result would still be empty (e.g. purely punctuation input) a
657
+ * short deterministic hash is returned as a fallback.
658
+ *
659
+ * @param text - Input string
660
+ * @returns Slugified string (never empty)
661
+ */
662
+ function slugify(text) {
663
+ const slug = text
664
+ .toLowerCase()
665
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
666
+ .replace(/^-+|-+$/g, '');
667
+ if (slug.length > 0)
668
+ return slug;
669
+ // Deterministic fallback: simple DJB2-style hash of the original text
670
+ let hash = 5381;
671
+ for (let i = 0; i < text.length; i++) {
672
+ hash = ((hash << 5) + hash + text.charCodeAt(i)) | 0;
673
+ }
674
+ return `h${Math.abs(hash).toString(36)}`;
675
+ }
676
+ /**
677
+ * Escape HTML attribute special characters.
678
+ * @param text - Raw text
679
+ * @returns Escaped text safe for HTML attributes
680
+ */
681
+ function escapeAttr(text) {
682
+ return text
683
+ .replace(/&/g, '&amp;')
684
+ .replace(/"/g, '&quot;')
685
+ .replace(/'/g, '&#39;')
686
+ .replace(/</g, '&lt;')
687
+ .replace(/>/g, '&gt;');
688
+ }
689
+ /**
690
+ * Escape HTML text content special characters.
691
+ * @param text - Raw text
692
+ * @returns Escaped text safe for HTML text nodes
693
+ */
694
+ function escapeText(text) {
695
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
696
+ }
697
+ /** Map from 2-letter language codes to BCP 47 locale tags for date formatting */
698
+ const LANG_TO_LOCALE = {
699
+ en: 'en-GB',
700
+ sv: 'sv-SE',
701
+ da: 'da-DK',
702
+ no: 'nb-NO',
703
+ fi: 'fi-FI',
704
+ de: 'de-DE',
705
+ fr: 'fr-FR',
706
+ es: 'es-ES',
707
+ nl: 'nl-NL',
708
+ ar: 'ar-SA',
709
+ he: 'he-IL',
710
+ ja: 'ja-JP',
711
+ ko: 'ko-KR',
712
+ zh: 'zh-CN',
713
+ };
714
+ /**
715
+ * Format an ISO date string as a human-readable date in the given locale.
716
+ * @param date - ISO date string (YYYY-MM-DD)
717
+ * @param lang - Language code (defaults to 'en')
718
+ * @returns Formatted date string
719
+ */
720
+ function formatDisplayDate(date, lang) {
721
+ const parts = date.split('-');
722
+ const year = parts[0] ?? '';
723
+ const month = parts[1] ?? '';
724
+ const day = parts[2] ?? '';
725
+ if (!year || !month || !day)
726
+ return date;
727
+ const d = new Date(Date.UTC(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10)));
728
+ const locale = LANG_TO_LOCALE[lang ?? 'en'] ?? 'en-GB';
729
+ return d.toLocaleDateString(locale, { day: 'numeric', month: 'short', timeZone: 'UTC' });
730
+ }
731
+ //# sourceMappingURL=intelligence-index.js.map