eventregistry 10.0.0 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/AGENT-RECIPES.md +86 -0
  2. package/CHANGELOG.md +47 -0
  3. package/MIGRATION.md +22 -4
  4. package/README.md +49 -1
  5. package/dist/cjs/abort.d.ts +14 -0
  6. package/dist/cjs/abort.js +71 -0
  7. package/dist/cjs/abort.js.map +1 -0
  8. package/dist/cjs/base.js +8 -2
  9. package/dist/cjs/base.js.map +1 -1
  10. package/dist/cjs/errors.d.ts +66 -0
  11. package/dist/cjs/errors.js +75 -0
  12. package/dist/cjs/errors.js.map +1 -0
  13. package/dist/cjs/eventRegistry.d.ts +47 -15
  14. package/dist/cjs/eventRegistry.js +237 -185
  15. package/dist/cjs/eventRegistry.js.map +1 -1
  16. package/dist/cjs/fluent/recent.d.ts +7 -2
  17. package/dist/cjs/fluent/recent.js +7 -3
  18. package/dist/cjs/fluent/recent.js.map +1 -1
  19. package/dist/cjs/guards.d.ts +12 -0
  20. package/dist/cjs/guards.js +75 -0
  21. package/dist/cjs/guards.js.map +1 -0
  22. package/dist/cjs/http.d.ts +5 -0
  23. package/dist/cjs/http.js +64 -11
  24. package/dist/cjs/http.js.map +1 -1
  25. package/dist/cjs/index.d.ts +7 -0
  26. package/dist/cjs/index.js +17 -4
  27. package/dist/cjs/index.js.map +1 -1
  28. package/dist/cjs/logger.d.ts +2 -0
  29. package/dist/cjs/logger.js +6 -2
  30. package/dist/cjs/logger.js.map +1 -1
  31. package/dist/cjs/mutex.d.ts +2 -1
  32. package/dist/cjs/mutex.js +19 -2
  33. package/dist/cjs/mutex.js.map +1 -1
  34. package/dist/cjs/query.js +4 -4
  35. package/dist/cjs/query.js.map +1 -1
  36. package/dist/cjs/queryArticle.js +3 -2
  37. package/dist/cjs/queryArticle.js.map +1 -1
  38. package/dist/cjs/queryArticles.d.ts +6 -6
  39. package/dist/cjs/queryArticles.js +19 -18
  40. package/dist/cjs/queryArticles.js.map +1 -1
  41. package/dist/cjs/queryEvent.d.ts +1 -0
  42. package/dist/cjs/queryEvent.js +11 -5
  43. package/dist/cjs/queryEvent.js.map +1 -1
  44. package/dist/cjs/queryEvents.js +8 -7
  45. package/dist/cjs/queryEvents.js.map +1 -1
  46. package/dist/cjs/queryIterator.d.ts +2 -0
  47. package/dist/cjs/queryIterator.js +18 -10
  48. package/dist/cjs/queryIterator.js.map +1 -1
  49. package/dist/cjs/queryMentions.d.ts +1 -0
  50. package/dist/cjs/queryMentions.js +14 -8
  51. package/dist/cjs/queryMentions.js.map +1 -1
  52. package/dist/cjs/queryStory.d.ts +9 -6
  53. package/dist/cjs/queryStory.js +4 -4
  54. package/dist/cjs/queryStory.js.map +1 -1
  55. package/dist/cjs/recent.d.ts +18 -6
  56. package/dist/cjs/recent.js +26 -8
  57. package/dist/cjs/recent.js.map +1 -1
  58. package/dist/cjs/recentFeed.d.ts +35 -0
  59. package/dist/cjs/recentFeed.js +76 -0
  60. package/dist/cjs/recentFeed.js.map +1 -0
  61. package/dist/cjs/returnInfo.js +2 -2
  62. package/dist/cjs/returnInfo.js.map +1 -1
  63. package/dist/cjs/topicPage.js +7 -3
  64. package/dist/cjs/topicPage.js.map +1 -1
  65. package/dist/cjs/types.d.ts +63 -7
  66. package/dist/cjs/usage.d.ts +39 -0
  67. package/dist/cjs/usage.js +62 -0
  68. package/dist/cjs/usage.js.map +1 -0
  69. package/dist/cjs/version.d.ts +1 -1
  70. package/dist/cjs/version.js +1 -1
  71. package/dist/esm/abort.d.ts +14 -0
  72. package/dist/esm/abort.js +65 -0
  73. package/dist/esm/abort.js.map +1 -0
  74. package/dist/esm/analytics.d.ts +2 -2
  75. package/dist/esm/base.js +8 -2
  76. package/dist/esm/base.js.map +1 -1
  77. package/dist/esm/counts.d.ts +2 -2
  78. package/dist/esm/dailyShares.d.ts +2 -2
  79. package/dist/esm/errors.d.ts +66 -0
  80. package/dist/esm/errors.js +67 -0
  81. package/dist/esm/errors.js.map +1 -0
  82. package/dist/esm/eventForText.d.ts +3 -3
  83. package/dist/esm/eventRegistry.d.ts +67 -35
  84. package/dist/esm/eventRegistry.js +238 -186
  85. package/dist/esm/eventRegistry.js.map +1 -1
  86. package/dist/esm/fluent/analytics.d.ts +2 -2
  87. package/dist/esm/fluent/articles.d.ts +5 -5
  88. package/dist/esm/fluent/counts.d.ts +2 -2
  89. package/dist/esm/fluent/eventForText.d.ts +1 -1
  90. package/dist/esm/fluent/events.d.ts +5 -5
  91. package/dist/esm/fluent/info.d.ts +2 -2
  92. package/dist/esm/fluent/mentions.d.ts +3 -3
  93. package/dist/esm/fluent/recent.d.ts +9 -4
  94. package/dist/esm/fluent/recent.js +7 -3
  95. package/dist/esm/fluent/recent.js.map +1 -1
  96. package/dist/esm/fluent/shares.d.ts +2 -2
  97. package/dist/esm/fluent/stories.d.ts +3 -3
  98. package/dist/esm/fluent/topicPages.d.ts +3 -3
  99. package/dist/esm/fluent/trends.d.ts +3 -3
  100. package/dist/esm/guards.d.ts +12 -0
  101. package/dist/esm/guards.js +70 -0
  102. package/dist/esm/guards.js.map +1 -0
  103. package/dist/esm/helpers/analytics.d.ts +2 -2
  104. package/dist/esm/helpers/articles.d.ts +4 -4
  105. package/dist/esm/helpers/counts.d.ts +2 -2
  106. package/dist/esm/helpers/eventForText.d.ts +1 -1
  107. package/dist/esm/helpers/events.d.ts +4 -4
  108. package/dist/esm/helpers/info.d.ts +2 -2
  109. package/dist/esm/helpers/mentions.d.ts +2 -2
  110. package/dist/esm/helpers/recent.d.ts +2 -2
  111. package/dist/esm/helpers/shares.d.ts +2 -2
  112. package/dist/esm/helpers/stories.d.ts +3 -3
  113. package/dist/esm/helpers/topicPages.d.ts +3 -3
  114. package/dist/esm/helpers/trends.d.ts +3 -3
  115. package/dist/esm/helpers/uri.d.ts +2 -2
  116. package/dist/esm/http.d.ts +5 -0
  117. package/dist/esm/http.js +64 -11
  118. package/dist/esm/http.js.map +1 -1
  119. package/dist/esm/index.d.ts +54 -47
  120. package/dist/esm/index.js +4 -0
  121. package/dist/esm/index.js.map +1 -1
  122. package/dist/esm/info.d.ts +2 -2
  123. package/dist/esm/logger.d.ts +2 -0
  124. package/dist/esm/logger.js +6 -2
  125. package/dist/esm/logger.js.map +1 -1
  126. package/dist/esm/mutex.d.ts +2 -1
  127. package/dist/esm/mutex.js +19 -2
  128. package/dist/esm/mutex.js.map +1 -1
  129. package/dist/esm/query.d.ts +2 -2
  130. package/dist/esm/query.js +4 -4
  131. package/dist/esm/query.js.map +1 -1
  132. package/dist/esm/queryArticle.d.ts +3 -3
  133. package/dist/esm/queryArticle.js +3 -2
  134. package/dist/esm/queryArticle.js.map +1 -1
  135. package/dist/esm/queryArticles.d.ts +12 -12
  136. package/dist/esm/queryArticles.js +19 -18
  137. package/dist/esm/queryArticles.js.map +1 -1
  138. package/dist/esm/queryEvent.d.ts +6 -5
  139. package/dist/esm/queryEvent.js +11 -5
  140. package/dist/esm/queryEvent.js.map +1 -1
  141. package/dist/esm/queryEvents.d.ts +6 -6
  142. package/dist/esm/queryEvents.js +8 -7
  143. package/dist/esm/queryEvents.js.map +1 -1
  144. package/dist/esm/queryIterator.d.ts +2 -0
  145. package/dist/esm/queryIterator.js +18 -10
  146. package/dist/esm/queryIterator.js.map +1 -1
  147. package/dist/esm/queryMentions.d.ts +4 -3
  148. package/dist/esm/queryMentions.js +14 -8
  149. package/dist/esm/queryMentions.js.map +1 -1
  150. package/dist/esm/queryStory.d.ts +11 -8
  151. package/dist/esm/queryStory.js +4 -4
  152. package/dist/esm/queryStory.js.map +1 -1
  153. package/dist/esm/recent.d.ts +21 -9
  154. package/dist/esm/recent.js +26 -8
  155. package/dist/esm/recent.js.map +1 -1
  156. package/dist/esm/recentFeed.d.ts +35 -0
  157. package/dist/esm/recentFeed.js +70 -0
  158. package/dist/esm/recentFeed.js.map +1 -0
  159. package/dist/esm/returnInfo.d.ts +1 -1
  160. package/dist/esm/returnInfo.js +2 -2
  161. package/dist/esm/returnInfo.js.map +1 -1
  162. package/dist/esm/topicPage.d.ts +3 -3
  163. package/dist/esm/topicPage.js +7 -3
  164. package/dist/esm/topicPage.js.map +1 -1
  165. package/dist/esm/topicPages.d.ts +1 -1
  166. package/dist/esm/trends.d.ts +2 -2
  167. package/dist/esm/types.d.ts +69 -13
  168. package/dist/esm/usage.d.ts +39 -0
  169. package/dist/esm/usage.js +58 -0
  170. package/dist/esm/usage.js.map +1 -0
  171. package/dist/esm/version.d.ts +1 -1
  172. package/dist/esm/version.js +1 -1
  173. package/package.json +21 -12
  174. package/src/abort.ts +70 -0
  175. package/src/base.ts +8 -2
  176. package/src/errors.ts +105 -0
  177. package/src/eventRegistry.ts +285 -185
  178. package/src/fluent/recent.ts +9 -5
  179. package/src/guards.ts +79 -0
  180. package/src/http.ts +70 -11
  181. package/src/index.ts +7 -0
  182. package/src/logger.ts +7 -2
  183. package/src/mutex.ts +20 -2
  184. package/src/query.ts +4 -4
  185. package/src/queryArticle.ts +3 -2
  186. package/src/queryArticles.ts +25 -17
  187. package/src/queryEvent.ts +12 -5
  188. package/src/queryEvents.ts +9 -8
  189. package/src/queryIterator.ts +20 -9
  190. package/src/queryMentions.ts +16 -9
  191. package/src/queryStory.ts +11 -4
  192. package/src/recent.ts +35 -10
  193. package/src/recentFeed.ts +91 -0
  194. package/src/returnInfo.ts +2 -2
  195. package/src/topicPage.ts +7 -3
  196. package/src/types.ts +66 -7
  197. package/src/usage.ts +79 -0
  198. package/src/version.ts +1 -1
@@ -1,9 +1,13 @@
1
- import * as fs from "fs";
1
+ import * as fs from "node:fs";
2
2
  import { Mutex } from "./mutex";
3
+ import { ErApiError, ErBudgetExceededError, ErValidationError } from "./errors";
4
+ import { validateResponse } from "./guards";
5
+ import { Usage } from "./usage";
6
+ import { abortableSleep, composeSignal } from "./abort";
3
7
  import { erFetch, ErHttpResponse } from "./http";
4
8
  import { ConceptInfoFlags, ReturnInfo } from "./returnInfo";
5
9
  import { ER } from "./types";
6
- import { QueryParamsBase, sleep } from "./base";
10
+ import { QueryParamsBase } from "./base";
7
11
  import { QueryArticle } from "./queryArticle";
8
12
  import { QueryArticles } from "./queryArticles";
9
13
  import { QueryEvents } from "./queryEvents";
@@ -50,59 +54,70 @@ function firstMatchField<T, K extends keyof T>(matches: T[] | undefined, field:
50
54
  * @class EventRegistry
51
55
  * Main class responsible for obtaining results form the Event Registry
52
56
  */
57
+ const USAGE_PATH = "/api/v1/usage";
58
+
59
+ /** Build the request params for the prefix suggesters from either call style (positional page/count or an args object). */
60
+ function pagedSuggestParams(prefix: string, pageOrArgs: number | ER.SuggestPagedArguments = {}, count?: number) {
61
+ const { page = 1, count: argsCount = 20, ...otherParams } = typeof pageOrArgs === "number" ? { page: pageOrArgs, count } : pageOrArgs;
62
+ if (page <= 0) {
63
+ throw new Error("Page parameter should be above 0.");
64
+ }
65
+ return { prefix, page, count: argsCount, ...otherParams };
66
+ }
67
+
53
68
  export class EventRegistry {
54
69
  public logger: Logger;
55
70
  /** Ergonomic article search/iterate/get façade — see `ArticlesFluent`. */
56
- public readonly articles: ArticlesFluent;
71
+ public readonly articles!: ArticlesFluent;
57
72
  /** Ergonomic event search/iterate/get façade — see `EventsFluent`. */
58
- public readonly events: EventsFluent;
73
+ public readonly events!: EventsFluent;
59
74
  /** Ergonomic mentions search/iterate façade — see `MentionsFluent`. */
60
- public readonly mentions: MentionsFluent;
75
+ public readonly mentions!: MentionsFluent;
61
76
  /** Ergonomic story lookup façade — see `StoriesFluent`. */
62
- public readonly stories: StoriesFluent;
77
+ public readonly stories!: StoriesFluent;
63
78
  /** Ergonomic trending concepts/categories façade — see `TrendsFluent`. */
64
- public readonly trends: TrendsFluent;
79
+ public readonly trends!: TrendsFluent;
65
80
  /** Ergonomic concept/category mention-count façade — see `CountsFluent`. */
66
- public readonly counts: CountsFluent;
81
+ public readonly counts!: CountsFluent;
67
82
  /** Ergonomic top-shared articles/events façade — see `SharesFluent`. */
68
- public readonly shares: SharesFluent;
83
+ public readonly shares!: SharesFluent;
69
84
  /** Ergonomic recent activity façade — see `RecentFluent`. */
70
- public readonly recent: RecentFluent;
85
+ public readonly recent!: RecentFluent;
71
86
  /** Ergonomic source/concept/category info façade — see `InfoFluent`. */
72
- public readonly info: InfoFluent;
87
+ public readonly info!: InfoFluent;
73
88
  /** Ergonomic topic page listing/loading/building façade — see `TopicPagesFluent`. */
74
- public readonly topicPages: TopicPagesFluent;
89
+ public readonly topicPages!: TopicPagesFluent;
75
90
  /** Ergonomic text analytics façade — see `AnalyticsFluent`. */
76
- public readonly analytics: AnalyticsFluent;
91
+ public readonly analytics!: AnalyticsFluent;
77
92
  /** Ergonomic callable form of `GetEventForText.compute()`. */
78
- public readonly eventForText: EventForTextFluent;
93
+ public readonly eventForText!: EventForTextFluent;
79
94
  /** Ergonomic concept uri resolution — see `helpers/uri.conceptUri`. */
80
- public readonly concepts: {
95
+ public readonly concepts!: {
81
96
  uri: (label: string, args?: ER.GetConceptUriArguments) => Promise<string>;
82
97
  };
83
98
  /** Ergonomic category uri resolution — see `helpers/uri.categoryUri`. */
84
- public readonly categories: {
99
+ public readonly categories!: {
85
100
  uri: (label: string) => Promise<string>;
86
101
  };
87
102
  /** Ergonomic news source/source group uri resolution — see `helpers/uri.sourceUri`. */
88
- public readonly sources: {
103
+ public readonly sources!: {
89
104
  uri: (label: string, dataType?: ER.DataType[] | ER.DataType) => Promise<string>;
90
105
  groupUri: (label: string) => Promise<string>;
91
106
  };
92
107
  /** Ergonomic location uri resolution — see `helpers/uri.locationUri`. */
93
- public readonly locations: {
108
+ public readonly locations!: {
94
109
  uri: (label: string, args?: ER.GetLocationUriArguments) => Promise<string>;
95
110
  };
96
111
  /** Ergonomic event type uri resolution — see `helpers/uri.eventTypeUri`. */
97
- public readonly eventTypes: {
112
+ public readonly eventTypes!: {
98
113
  uri: (label: string) => Promise<string>;
99
114
  };
100
115
  /** Ergonomic concept class uri resolution — see `helpers/uri.conceptClassUri`. */
101
- public readonly conceptClasses: {
116
+ public readonly conceptClasses!: {
102
117
  uri: (label: string, lang?: string) => Promise<string>;
103
118
  };
104
119
  /** Ergonomic author uri resolution — see `helpers/uri.authorUri`. */
105
- public readonly authors: {
120
+ public readonly authors!: {
106
121
  uri: (label: string) => Promise<string>;
107
122
  };
108
123
  private config: ER.Config = {
@@ -110,14 +125,18 @@ export class EventRegistry {
110
125
  hostAnalytics: "https://analytics.eventregistry.org",
111
126
  logging: false,
112
127
  minDelayBetweenRequests: 0.5,
113
- repeatFailedRequestCount: -1,
128
+ repeatFailedRequestCount: 5,
114
129
  verboseOutput: false,
115
130
  allowUseOfArchive: true
116
131
  };
132
+ /** Token and request accounting plus the optional `maxTokens` budget guard. */
133
+ public readonly usage: Usage;
117
134
  private headers = new Headers();
118
135
  private dailyAvailableRequests = -1;
119
136
  private remainingAvailableRequests = -1;
120
137
  private lastQueryTime = 0;
138
+ /** `minDelayBetweenRequests` converted to milliseconds. */
139
+ private minDelayMs = 500;
121
140
  private _logRequests = false;
122
141
  private readonly lock: Mutex;
123
142
  private extraParams: Record<string, unknown> | null = null;
@@ -128,7 +147,11 @@ export class EventRegistry {
128
147
  const settingsPath = config.settingsFName || "settings.json";
129
148
  let fileSettings: ER.Config = {};
130
149
  if (fs && fs.existsSync(settingsPath)) {
131
- fileSettings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
150
+ try {
151
+ fileSettings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
152
+ } catch (err) {
153
+ throw new Error(`Could not read the settings file '${settingsPath}': ${err instanceof Error ? err.message : String(err)}`);
154
+ }
132
155
  }
133
156
 
134
157
  this.config = {
@@ -140,6 +163,7 @@ export class EventRegistry {
140
163
  apiKey: config.apiKey !== undefined ? config.apiKey : fileSettings.apiKey
141
164
  };
142
165
 
166
+ this.usage = new Usage(this.config.maxTokens);
143
167
  this._logRequests = this.config.logging ?? false;
144
168
  this.logger = new Logger({ logging: this.config.logging, logRequests: this._logRequests });
145
169
 
@@ -154,42 +178,76 @@ export class EventRegistry {
154
178
  }
155
179
  this.logger.debug(`Event Registry host: ${this.config.host}`);
156
180
  this.logger.debug(`Text analytics host: ${this.config.hostAnalytics}`);
157
- this.config.minDelayBetweenRequests = (this.config.minDelayBetweenRequests ?? 0.5) * 1000;
158
-
159
- this.articles = new ArticlesFluent(this);
160
- this.events = new EventsFluent(this);
161
- this.mentions = new MentionsFluent(this);
162
- this.stories = new StoriesFluent(this);
163
- this.trends = new TrendsFluent(this);
164
- this.counts = new CountsFluent(this);
165
- this.shares = new SharesFluent(this);
166
- this.recent = new RecentFluent(this);
167
- this.info = new InfoFluent(this);
168
- this.topicPages = new TopicPagesFluent(this);
169
- this.analytics = new AnalyticsFluent(this);
170
- this.eventForText = createEventForTextFluent(this);
171
- this.concepts = {
172
- uri: (label: string, args?: ER.GetConceptUriArguments) => resolveConceptUri(this, label, args)
173
- };
174
- this.categories = {
175
- uri: (label: string) => resolveCategoryUri(this, label)
176
- };
177
- this.sources = {
178
- uri: (label: string, dataType?: ER.DataType[] | ER.DataType) => resolveSourceUri(this, label, dataType),
179
- groupUri: (label: string) => resolveSourceGroupUri(this, label)
180
- };
181
- this.locations = {
182
- uri: (label: string, args?: ER.GetLocationUriArguments) => resolveLocationUri(this, label, args)
183
- };
184
- this.eventTypes = {
185
- uri: (label: string) => resolveEventTypeUri(this, label)
186
- };
187
- this.conceptClasses = {
188
- uri: (label: string, lang?: string) => resolveConceptClassUri(this, label, lang)
181
+ this.minDelayMs = (this.config.minDelayBetweenRequests ?? 0.5) * 1000;
182
+
183
+ Object.assign(this, this.buildNamespaces(this));
184
+ }
185
+
186
+ /** Namespaces (`er.articles`, `er.concepts`, …) bound to `self`, so a `withOptions` view routes through itself. */
187
+ private buildNamespaces(self: EventRegistry) {
188
+ return {
189
+ articles: new ArticlesFluent(self),
190
+ events: new EventsFluent(self),
191
+ mentions: new MentionsFluent(self),
192
+ stories: new StoriesFluent(self),
193
+ trends: new TrendsFluent(self),
194
+ counts: new CountsFluent(self),
195
+ shares: new SharesFluent(self),
196
+ recent: new RecentFluent(self),
197
+ info: new InfoFluent(self),
198
+ topicPages: new TopicPagesFluent(self),
199
+ analytics: new AnalyticsFluent(self),
200
+ eventForText: createEventForTextFluent(self),
201
+ concepts: {
202
+ uri: (label: string, args?: ER.GetConceptUriArguments) => resolveConceptUri(self, label, args)
203
+ },
204
+ categories: {
205
+ uri: (label: string) => resolveCategoryUri(self, label)
206
+ },
207
+ sources: {
208
+ uri: (label: string, dataType?: ER.DataType[] | ER.DataType) => resolveSourceUri(self, label, dataType),
209
+ groupUri: (label: string) => resolveSourceGroupUri(self, label)
210
+ },
211
+ locations: {
212
+ uri: (label: string, args?: ER.GetLocationUriArguments) => resolveLocationUri(self, label, args)
213
+ },
214
+ eventTypes: {
215
+ uri: (label: string) => resolveEventTypeUri(self, label)
216
+ },
217
+ conceptClasses: {
218
+ uri: (label: string, lang?: string) => resolveConceptClassUri(self, label, lang)
219
+ },
220
+ authors: {
221
+ uri: (label: string) => resolveAuthorUri(self, label)
222
+ }
189
223
  };
190
- this.authors = {
191
- uri: (label: string) => resolveAuthorUri(this, label)
224
+ }
225
+
226
+ /** Signals and deadline applied to every call made through this instance (or `withOptions` view). */
227
+ private get requestScope(): { signals: AbortSignal[]; timeoutMs?: number } {
228
+ return { signals: this.config.signal ? [this.config.signal] : [], timeoutMs: this.config.timeoutMs };
229
+ }
230
+
231
+ /**
232
+ * Return a view of this client whose every call (classic, helpers, fluent namespaces and iterators)
233
+ * also observes `options.signal` and `options.timeoutMs`. State (rate limit, usage, headers, queue)
234
+ * is shared with this instance. A view's signal adds to, and its `timeoutMs` replaces, the inherited ones.
235
+ */
236
+ public withOptions(options: ER.RequestOptions): EventRegistry {
237
+ const scope = this.requestScope;
238
+ const overrides: Record<string | symbol, unknown> = {
239
+ requestScope: {
240
+ signals: options.signal ? [...scope.signals, options.signal] : scope.signals,
241
+ timeoutMs: options.timeoutMs ?? scope.timeoutMs
242
+ }
192
243
  };
244
+ const view: EventRegistry = new Proxy(this, {
245
+ get: (target, prop, receiver) => prop in overrides ? overrides[prop] : Reflect.get(target, prop, receiver) as unknown,
246
+ // writes (rate-limit bookkeeping, headers, ...) land on the shared root instance
247
+ set: (target, prop, value) => Reflect.set(target, prop, value)
248
+ });
249
+ Object.assign(overrides, this.buildNamespaces(view));
250
+ return view;
193
251
  }
194
252
 
195
253
  public getHost(): string {
@@ -206,11 +264,11 @@ export class EventRegistry {
206
264
 
207
265
  /** Minimum delay between requests in seconds (constructor units). */
208
266
  public getMinDelayBetweenRequests(): number {
209
- return (this.config.minDelayBetweenRequests ?? 500) / 1000;
267
+ return this.minDelayMs / 1000;
210
268
  }
211
269
 
212
270
  public getRepeatFailedRequestCount(): number {
213
- return this.config.repeatFailedRequestCount ?? -1;
271
+ return this.config.repeatFailedRequestCount ?? 5;
214
272
  }
215
273
 
216
274
  /**
@@ -284,7 +342,7 @@ export class EventRegistry {
284
342
  private createErrorResponse<T>(error: unknown): ErHttpResponse<T> {
285
343
  const message = error instanceof Error ? error.message : String(error);
286
344
  return {
287
- data: { error: message } as T,
345
+ data: (error instanceof ErApiError ? { error: message, apiError: error } : { error: message }) as T,
288
346
  status: 0,
289
347
  statusText: "error",
290
348
  headers: new Headers()
@@ -310,90 +368,67 @@ export class EventRegistry {
310
368
  /**
311
369
  * Main method for executing the search queries.
312
370
  * @param query instance of Query class
371
+ * @param options `signal` / `timeoutMs` for this call only
313
372
  */
314
373
  public async execQuery<T = ER.SuccessfulResponse<unknown>>(
315
374
  query: { path: string; getQueryParams: () => Record<string, unknown> },
316
- allowUseOfArchive: boolean = this.config.allowUseOfArchive ?? true
375
+ allowUseOfArchive: boolean = this.config.allowUseOfArchive ?? true,
376
+ options?: ER.RequestOptions
317
377
  ): Promise<ER.Response<T>> {
318
378
  const params = query.getQueryParams();
319
- const request = await this.jsonRequest<ER.Response<T>>(query.path, params, allowUseOfArchive);
379
+ const request = await this.jsonRequest<ER.Response<T>>(query.path, params, allowUseOfArchive, options);
320
380
  if (!request?.data && this.config?.verboseOutput) {
321
381
  this.logger.error("Request did not return with the 'data' property.");
322
382
  }
323
- return (request?.data || {} as ER.Response<T>);
383
+ const data = request?.data || {} as ER.Response<T>;
384
+ if (this.config.validate) {
385
+ const issues = validateResponse(data);
386
+ if (issues.length > 0) {
387
+ throw new ErValidationError(query.path, issues);
388
+ }
389
+ }
390
+ return data;
391
+ }
392
+
393
+ /** Merge instance/view defaults with per-call options into one signal (caller must `dispose()`). */
394
+ private composeCallScope(options?: ER.RequestOptions): { signal?: AbortSignal; dispose: () => void } {
395
+ const scope = this.requestScope;
396
+ return composeSignal([...scope.signals, options?.signal], options?.timeoutMs ?? scope.timeoutMs);
397
+ }
398
+
399
+ private async acquireLock(scope: { signal?: AbortSignal; dispose: () => void }): Promise<void> {
400
+ try {
401
+ await this.lock.acquire(scope.signal);
402
+ } catch (error) {
403
+ scope.dispose();
404
+ throw error;
405
+ }
324
406
  }
325
407
 
326
408
  /**
327
409
  * Wait until minDelayBetweenRequests has elapsed since the last attempt.
328
410
  * Must run while holding `this.lock`.
329
411
  */
330
- private async waitForTurn(): Promise<void> {
412
+ private async waitForTurn(signal?: AbortSignal): Promise<void> {
331
413
  const now = Date.now();
332
- const minDelayBetweenRequests = this.config.minDelayBetweenRequests ?? 500;
333
- if (this.lastQueryTime && now - this.lastQueryTime < minDelayBetweenRequests) {
334
- await sleep(minDelayBetweenRequests - (now - this.lastQueryTime));
414
+ if (this.lastQueryTime && now - this.lastQueryTime < this.minDelayMs) {
415
+ await abortableSleep(this.minDelayMs - (now - this.lastQueryTime), signal);
335
416
  }
336
417
  }
337
418
 
338
- public async jsonRequestAnalytics<T = unknown>(path: string, parameters?: Record<string, unknown>, headers?: Record<string, unknown>, cookies?: Record<string, unknown>): Promise<ErHttpResponse<T>> {
339
- let request: ErHttpResponse<T>;
340
- await this.lock.acquire();
341
- try {
342
- await this.waitForTurn();
343
- parameters = {
344
- ...parameters,
345
- ...(this.extraParams || {}),
346
- apiKey: this.config?.apiKey
347
- };
348
- let requestHeaders: Record<string, string> = {...(headers as Record<string, string> || {})};
349
- if (!!headers) {
350
- requestHeaders = {...(headers as Record<string, string>)};
351
- }
352
- if (!!cookies) {
353
- const cookieString = Object.keys(cookies).map((key) => key + "=" + cookies[key]).join(";") + ";";
354
- requestHeaders = {...requestHeaders, Cookie: cookieString};
355
- }
356
- try {
357
- request = await erFetch<T>({
358
- url: `${this.config.hostAnalytics}${path}`,
359
- method: "POST",
360
- body: parameters,
361
- headers: requestHeaders,
362
- timeoutMs: 600_000,
363
- retry: this.config.repeatFailedRequestCount,
364
- retryDelayMs: 5000,
365
- stopStatusCodes: this.stopStatusCodes
366
- });
367
- } finally {
368
- this.lastQueryTime = Date.now();
369
- }
370
- this.headers = request.headers;
371
- if (request?.status !== 200) {
372
- throw new Error(request?.statusText);
373
- }
374
- const errorMessage = (request?.data as Record<string, string>)?.error || "";
375
- if (errorMessage) {
376
- throw new Error(errorMessage);
377
- }
378
- } catch (error: unknown) {
379
- request = this.createErrorResponse<T>(error);
380
- const err = error as { stack?: string; message?: string; response?: { status?: number; statusText?: string; data?: unknown }; errno?: unknown };
381
- if (this.config.verboseOutput) {
382
- this.logger.error("Event Registry Analytics exception while executing the request.");
383
- if (err && err.stack && err.message) {
384
- this.logger.error(err.message);
385
- } else {
386
- this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${err?.response?.data}`);
387
- }
388
- }
389
- // try to print out the error that should be passed by in case the server is down or responds with errors
390
- if (this.config?.logging) {
391
- this.logger.error(String(err?.errno ?? error));
392
- }
393
- } finally {
394
- this.lock.release();
419
+ public async jsonRequestAnalytics<T = unknown>(path: string, parameters?: Record<string, unknown>, headers?: Record<string, unknown>, cookies?: Record<string, unknown>, options?: ER.RequestOptions): Promise<ErHttpResponse<T>> {
420
+ const requestHeaders: Record<string, string> = { ...(headers as Record<string, string> | undefined) };
421
+ if (cookies) {
422
+ requestHeaders.Cookie = Object.keys(cookies).map((key) => key + "=" + String(cookies[key])).join(";") + ";";
395
423
  }
396
- return request;
424
+ return this.send<T>({
425
+ label: "Event Registry Analytics",
426
+ url: `${this.config.hostAnalytics}${path}`,
427
+ path,
428
+ parameters,
429
+ headers: requestHeaders,
430
+ options
431
+ });
397
432
  }
398
433
 
399
434
  /**
@@ -401,68 +436,118 @@ export class EventRegistry {
401
436
  * @param path url on er (e.g. "/api/v1/article")
402
437
  * @param parameters Optional parameters to be included in the request
403
438
  */
404
- public async jsonRequest<T = unknown>(path: string, parameters?: Record<string, unknown>, allowUseOfArchive: boolean = this.config.allowUseOfArchive ?? true): Promise<ErHttpResponse<T>> {
439
+ public async jsonRequest<T = unknown>(path: string, parameters?: Record<string, unknown>, allowUseOfArchive: boolean = this.config.allowUseOfArchive ?? true, options?: ER.RequestOptions): Promise<ErHttpResponse<T>> {
440
+ return this.send<T>({
441
+ label: "Event Registry",
442
+ url: `${this.config.host}${path}`,
443
+ path,
444
+ parameters,
445
+ allowUseOfArchive,
446
+ options,
447
+ budgeted: path !== USAGE_PATH,
448
+ logged: true,
449
+ readsRateLimit: true
450
+ });
451
+ }
452
+
453
+ /**
454
+ * Shared by `jsonRequest` and `jsonRequestAnalytics`: queue behind the lock, honour the minimum delay and
455
+ * the token budget, POST with retries, record usage, and turn failures into an error response.
456
+ */
457
+ private async send<T>(spec: {
458
+ label: string;
459
+ url: string;
460
+ path: string;
461
+ parameters?: Record<string, unknown>;
462
+ headers?: Record<string, string>;
463
+ allowUseOfArchive?: boolean;
464
+ options?: ER.RequestOptions;
465
+ budgeted?: boolean;
466
+ logged?: boolean;
467
+ readsRateLimit?: boolean;
468
+ }): Promise<ErHttpResponse<T>> {
469
+ const { label, url, path, headers, options, allowUseOfArchive = true, budgeted = true } = spec;
405
470
  let request: ErHttpResponse<T>;
406
- await this.lock.acquire();
471
+ const scope = this.composeCallScope(options);
472
+ await this.acquireLock(scope);
407
473
  try {
408
- await this.waitForTurn();
409
- if (this._logRequests) {
410
- if (Object.keys(parameters || {}).length > 0) {
411
- this.logger.logRequest("# " + JSON.stringify(parameters) + "\n");
474
+ await this.waitForTurn(scope.signal);
475
+ if (budgeted) {
476
+ this.usage.assertWithinBudget(path);
477
+ }
478
+ if (spec.logged && this._logRequests) {
479
+ if (Object.keys(spec.parameters || {}).length > 0) {
480
+ this.logger.logRequest("# " + JSON.stringify(spec.parameters) + "\n");
412
481
  }
413
482
  this.logger.logRequest(path + "\n\n");
414
483
  }
415
- parameters = {
416
- ...parameters,
484
+ let parameters: Record<string, unknown> = {
485
+ ...spec.parameters,
417
486
  ...(this.extraParams || {}),
418
487
  apiKey: this.config?.apiKey
419
488
  };
420
489
  if (!allowUseOfArchive) {
421
- parameters = {...parameters, forceMaxDataTimeWindow: 31};
490
+ parameters = { ...parameters, forceMaxDataTimeWindow: 31 };
422
491
  }
423
492
  try {
424
493
  request = await erFetch<T>({
425
- url: `${this.config.host}${path}`,
494
+ url,
426
495
  method: "POST",
427
496
  body: parameters,
497
+ headers,
498
+ signal: scope.signal,
428
499
  timeoutMs: 600_000,
429
500
  retry: this.config.repeatFailedRequestCount,
430
- retryDelayMs: 5000,
501
+ retryDelayMs: this.config.retryDelayMs,
502
+ maxRetryDelayMs: this.config.maxRetryDelayMs,
431
503
  stopStatusCodes: this.stopStatusCodes
432
504
  });
433
505
  } finally {
434
506
  this.lastQueryTime = Date.now();
435
507
  }
436
508
  this.headers = request.headers;
509
+ this.usage.record(path, request.headers);
437
510
  if (request?.status !== 200) {
438
511
  throw new Error(request?.statusText);
439
512
  }
440
- if (this.getLastHeader("warning")) {
441
- this.logger.warn(`WARNING: ${this.getLastHeader("warning")}`);
513
+ if (spec.readsRateLimit) {
514
+ if (this.getLastHeader("warning")) {
515
+ this.logger.warn(`WARNING: ${this.getLastHeader("warning")}`);
516
+ }
517
+ this.dailyAvailableRequests = Number(this.getLastHeader("x-ratelimit-limit", "-1"));
518
+ this.remainingAvailableRequests = Number(this.getLastHeader("x-ratelimit-remaining", "-1"));
442
519
  }
443
- this.dailyAvailableRequests = Number(this.getLastHeader("x-ratelimit-limit", "-1"));
444
- this.remainingAvailableRequests = Number(this.getLastHeader("x-ratelimit-remaining", "-1"));
445
520
  const errorMessage = (request?.data as Record<string, string>)?.error || "";
446
521
  if (errorMessage) {
447
522
  throw new Error(errorMessage);
448
523
  }
449
524
  } catch (error: unknown) {
450
- request = this.createErrorResponse<T>(error);
525
+ if (error instanceof ErBudgetExceededError) {
526
+ throw error;
527
+ }
528
+ if (scope.signal?.aborted) {
529
+ throw scope.signal.reason;
530
+ }
451
531
  const err = error as { stack?: string; message?: string; response?: { status?: number; statusText?: string; data?: unknown }; errno?: unknown };
452
- // try to print out the error that should be passed by in case the server is down or responds with errors
453
532
  if (this.config.verboseOutput) {
454
- this.logger.error("Event Registry exception while executing the request.");
533
+ this.logger.error(`${label} exception while executing the request.`);
455
534
  if (err && err.stack && err.message) {
456
535
  this.logger.error(err.message);
457
536
  } else {
458
- this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${err?.response?.data}`);
537
+ this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${String(err?.response?.data)}`);
459
538
  }
460
539
  }
540
+ // try to print out the error that should be passed by in case the server is down or responds with errors
461
541
  if (this.config?.logging) {
462
542
  this.logger.error(String(err?.errno ?? error));
463
543
  }
544
+ if (this.config.throwOnError) {
545
+ throw error;
546
+ }
547
+ request = this.createErrorResponse<T>(error);
464
548
  } finally {
465
549
  this.lock.release();
550
+ scope.dispose();
466
551
  }
467
552
  return request;
468
553
  }
@@ -514,16 +599,29 @@ export class EventRegistry {
514
599
  /**
515
600
  * Return the number of used and total available tokens. Can be used at any time (also before making queries)
516
601
  */
517
- public async getUsageInfo(): Promise<ER.UsageInfo> {
518
- const request = await this.jsonRequest("/api/v1/usage");
602
+ public async getUsageInfo(options?: ER.RequestOptions): Promise<ER.UsageInfo> {
603
+ const request = await this.jsonRequest(USAGE_PATH, undefined, undefined, options);
519
604
  return request.data as ER.UsageInfo;
520
605
  }
521
606
 
607
+ /**
608
+ * Tokens still available on the account (`availableTokens - usedTokens` from the usage endpoint).
609
+ * Makes one request; it is exempt from the `maxTokens` guard.
610
+ */
611
+ public async getRemainingTokens(options?: ER.RequestOptions): Promise<number> {
612
+ const info = await this.getUsageInfo(options);
613
+ return info.availableTokens - info.usedTokens;
614
+ }
615
+
522
616
  public async getServiceStatus(): Promise<ER.UsageInfo> {
523
617
  const request = await this.jsonRequest("/api/v1/getServiceStatus");
524
618
  return request.data as ER.UsageInfo;
525
619
  }
526
620
 
621
+ /**
622
+ * Return the GET URL for the query. Parameters are URL-encoded, arrays become repeated keys,
623
+ * objects are JSON-encoded, and apiKey is always left out so the URL is safe to log or share.
624
+ */
527
625
  public getUrl(query: QueryArticles | QueryArticle | QueryEvents | QueryEvent) {
528
626
  if (!(query instanceof QueryParamsBase)) {
529
627
  if (this.config.verboseOutput) {
@@ -531,7 +629,26 @@ export class EventRegistry {
531
629
  }
532
630
  }
533
631
  const allParams = query.getQueryParams();
534
- return `${this.config?.host}${query?.path}?${Object.keys(allParams).map(key => `${key}=${allParams[key]}`).join("&")}`;
632
+ const searchParams = new URLSearchParams();
633
+ const append = (key: string, value: unknown) => {
634
+ if (value === undefined || value === null) {
635
+ return;
636
+ }
637
+ // Objects are serialised above, so only primitives reach String().
638
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
639
+ searchParams.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
640
+ };
641
+ for (const [key, value] of Object.entries(allParams)) {
642
+ if (key === "apiKey") {
643
+ continue;
644
+ }
645
+ if (Array.isArray(value)) {
646
+ value.forEach((item) => append(key, item));
647
+ } else {
648
+ append(key, value);
649
+ }
650
+ }
651
+ return `${this.config?.host}${query?.path}?${searchParams.toString()}`;
535
652
  }
536
653
 
537
654
  /**
@@ -686,19 +803,20 @@ export class EventRegistry {
686
803
  * @param radiusKm radius in kilometers around the coordinates inside which the news sources should be located
687
804
  * @param count number of returned suggestions
688
805
  */
689
- public async suggestSourcesAtCoordinate(latitude: number, longitude: number, radiusKm: number, count = 20, ...otherParams: unknown[]) {
806
+ public async suggestSourcesAtCoordinate(latitude: number, longitude: number, radiusKm: number, countOrArgs: number | ER.SuggestSourcesAtCoordinateArguments = 20) {
690
807
  if (typeof latitude !== "number") {
691
808
  throw new Error("The 'latitude' should be a number");
692
809
  }
693
810
  if (typeof longitude !== "number") {
694
811
  throw new Error("The 'longitude' should be a number");
695
812
  }
813
+ const { count = 20, ...otherParams } = typeof countOrArgs === "number" ? { count: countOrArgs } : countOrArgs;
696
814
  const params = {
697
815
  action: "getSourcesAtCoordinate",
698
816
  lat: latitude,
699
817
  lon: longitude,
700
818
  radius: radiusKm,
701
- count: count,
819
+ count,
702
820
  ...otherParams
703
821
  };
704
822
  const request = await this.jsonRequest("/api/v1/suggestSourcesFast", params);
@@ -730,16 +848,10 @@ export class EventRegistry {
730
848
  * @param page: page of results
731
849
  * @param count: number of returned suggestions
732
850
  */
733
- public async suggestAuthors(prefix: string, page = 1, count = 20, ...otherParams: unknown[]) {
734
- if (page <= 0) {
735
- throw new Error("Page parameter should be above 0.");
736
- }
737
- const params = {
738
- prefix,
739
- page,
740
- count,
741
- ...otherParams
742
- };
851
+ public async suggestAuthors(prefix: string, args?: ER.SuggestPagedArguments): Promise<ER.Author[]>;
852
+ public async suggestAuthors(prefix: string, page?: number, count?: number): Promise<ER.Author[]>;
853
+ public async suggestAuthors(prefix: string, pageOrArgs?: number | ER.SuggestPagedArguments, count?: number) {
854
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
743
855
  const request = await this.jsonRequest<ER.Author[]>("/api/v1/suggestAuthorsFast", params);
744
856
  return request.data;
745
857
  }
@@ -750,16 +862,10 @@ export class EventRegistry {
750
862
  * @param page: page of results
751
863
  * @param count: number of returned suggestions
752
864
  */
753
- public async suggestEventTypes(prefix: string, page = 1, count = 20, ...otherParams: unknown[]) {
754
- if (page <= 0) {
755
- throw new Error("Page parameter should be above 0.");
756
- }
757
- const params = {
758
- prefix,
759
- page,
760
- count,
761
- ...otherParams
762
- };
865
+ public async suggestEventTypes(prefix: string, args?: ER.SuggestPagedArguments): Promise<UriSuggestion[]>;
866
+ public async suggestEventTypes(prefix: string, page?: number, count?: number): Promise<UriSuggestion[]>;
867
+ public async suggestEventTypes(prefix: string, pageOrArgs?: number | ER.SuggestPagedArguments, count?: number) {
868
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
763
869
  const request = await this.jsonRequest<UriSuggestion[]>("/api/v1/eventType/suggestEventTypes", params);
764
870
  return request.data;
765
871
  }
@@ -770,22 +876,16 @@ export class EventRegistry {
770
876
  * @param page: page of results
771
877
  * @param count: number of returned suggestions
772
878
  */
773
- public async suggestIndustries(prefix: string, page = 1, count = 20, ...otherParams: unknown[]) {
774
- if (page <= 0) {
775
- throw new Error("Page parameter should be above 0.");
776
- }
777
- const params = {
778
- prefix,
779
- page,
780
- count,
781
- ...otherParams
782
- };
879
+ public async suggestIndustries(prefix: string, args?: ER.SuggestPagedArguments): Promise<unknown>;
880
+ public async suggestIndustries(prefix: string, page?: number, count?: number): Promise<unknown>;
881
+ public async suggestIndustries(prefix: string, pageOrArgs?: number | ER.SuggestPagedArguments, count?: number) {
882
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
783
883
  const request = await this.jsonRequest("/api/v1/eventType/suggestIndustries", params);
784
884
  return request.data;
785
885
  }
786
886
 
787
887
  /**
788
- * Return a list of SDG uris. Note: Industries can only be used when querying mentions (QueryMentions, QueryMentionsIter)
888
+ * Return a list of SDG uris. Note: SDGs can only be used when querying mentions (QueryMentions, QueryMentionsIter)
789
889
  */
790
890
  public async getSdgUris() {
791
891
  const request = await this.jsonRequest("/api/v1/eventType/sdg/getItems");
@@ -954,7 +1054,7 @@ export class EventRegistry {
954
1054
  }
955
1055
 
956
1056
  /**
957
- * Return information about the latest imported article
1057
+ * Return the list of source groups
958
1058
  */
959
1059
  public async getSourceGroups() {
960
1060
  const request = await this.jsonRequest("/api/v1/sourceGroup/getSourceGroups", { action: "getSourceGroups"});
@@ -977,7 +1077,7 @@ export class EventRegistry {
977
1077
  */
978
1078
  export class ArticleMapper {
979
1079
  private er: EventRegistry;
980
- private articleUrlToUri: Record<string, unknown> = {};
1080
+ private readonly articleUrlToUri = new Map<string, unknown>();
981
1081
  private rememberMappings = true;
982
1082
 
983
1083
  constructor(er: EventRegistry, rememberMapping = true) {
@@ -992,13 +1092,13 @@ export class ArticleMapper {
992
1092
  * @param articleUrl string containing the article url
993
1093
  */
994
1094
  public async getArticleUri(articleUrl: string) {
995
- if (this.articleUrlToUri.hasOwnProperty(articleUrl)) {
996
- return this.articleUrlToUri[articleUrl];
1095
+ if (this.articleUrlToUri.has(articleUrl)) {
1096
+ return this.articleUrlToUri.get(articleUrl);
997
1097
  }
998
1098
  const response = await this.er.getArticleUris(articleUrl);
999
1099
  const value = response?.[articleUrl];
1000
1100
  if (this.rememberMappings && value) {
1001
- this.articleUrlToUri = { ...this.articleUrlToUri, [articleUrl]: value };
1101
+ this.articleUrlToUri.set(articleUrl, value);
1002
1102
  }
1003
1103
  return value;
1004
1104
  }