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,8 +1,12 @@
1
- import * as fs from "fs";
1
+ import * as fs from "node:fs";
2
2
  import { Mutex } from "./mutex.js";
3
+ import { ErApiError, ErBudgetExceededError, ErValidationError } from "./errors.js";
4
+ import { validateResponse } from "./guards.js";
5
+ import { Usage } from "./usage.js";
6
+ import { abortableSleep, composeSignal } from "./abort.js";
3
7
  import { erFetch } from "./http.js";
4
8
  import { ConceptInfoFlags, ReturnInfo } from "./returnInfo.js";
5
- import { QueryParamsBase, sleep } from "./base.js";
9
+ import { QueryParamsBase } from "./base.js";
6
10
  import { Logger } from "./logger.js";
7
11
  import { __version__ } from "./version.js";
8
12
  import { ArticlesFluent } from "./fluent/articles.js";
@@ -30,6 +34,15 @@ function firstMatchField(matches, field) {
30
34
  * @class EventRegistry
31
35
  * Main class responsible for obtaining results form the Event Registry
32
36
  */
37
+ const USAGE_PATH = "/api/v1/usage";
38
+ /** Build the request params for the prefix suggesters from either call style (positional page/count or an args object). */
39
+ function pagedSuggestParams(prefix, pageOrArgs = {}, count) {
40
+ const { page = 1, count: argsCount = 20, ...otherParams } = typeof pageOrArgs === "number" ? { page: pageOrArgs, count } : pageOrArgs;
41
+ if (page <= 0) {
42
+ throw new Error("Page parameter should be above 0.");
43
+ }
44
+ return { prefix, page, count: argsCount, ...otherParams };
45
+ }
33
46
  export class EventRegistry {
34
47
  constructor(config = {}) {
35
48
  this.config = {
@@ -37,7 +50,7 @@ export class EventRegistry {
37
50
  hostAnalytics: "https://analytics.eventregistry.org",
38
51
  logging: false,
39
52
  minDelayBetweenRequests: 0.5,
40
- repeatFailedRequestCount: -1,
53
+ repeatFailedRequestCount: 5,
41
54
  verboseOutput: false,
42
55
  allowUseOfArchive: true
43
56
  };
@@ -45,6 +58,8 @@ export class EventRegistry {
45
58
  this.dailyAvailableRequests = -1;
46
59
  this.remainingAvailableRequests = -1;
47
60
  this.lastQueryTime = 0;
61
+ /** `minDelayBetweenRequests` converted to milliseconds. */
62
+ this.minDelayMs = 500;
48
63
  this._logRequests = false;
49
64
  this.extraParams = null;
50
65
  this.stopStatusCodes = [204, 400, 401, 403, 530];
@@ -52,7 +67,12 @@ export class EventRegistry {
52
67
  const settingsPath = config.settingsFName || "settings.json";
53
68
  let fileSettings = {};
54
69
  if (fs && fs.existsSync(settingsPath)) {
55
- fileSettings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
70
+ try {
71
+ fileSettings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
72
+ }
73
+ catch (err) {
74
+ throw new Error(`Could not read the settings file '${settingsPath}': ${err instanceof Error ? err.message : String(err)}`);
75
+ }
56
76
  }
57
77
  this.config = {
58
78
  ...this.config,
@@ -62,6 +82,7 @@ export class EventRegistry {
62
82
  hostAnalytics: config.hostAnalytics ?? fileSettings.hostAnalytics ?? this.config.hostAnalytics,
63
83
  apiKey: config.apiKey !== undefined ? config.apiKey : fileSettings.apiKey
64
84
  };
85
+ this.usage = new Usage(this.config.maxTokens);
65
86
  this._logRequests = this.config.logging ?? false;
66
87
  this.logger = new Logger({ logging: this.config.logging, logRequests: this._logRequests });
67
88
  if (config.apiKey) {
@@ -75,41 +96,72 @@ export class EventRegistry {
75
96
  }
76
97
  this.logger.debug(`Event Registry host: ${this.config.host}`);
77
98
  this.logger.debug(`Text analytics host: ${this.config.hostAnalytics}`);
78
- this.config.minDelayBetweenRequests = (this.config.minDelayBetweenRequests ?? 0.5) * 1000;
79
- this.articles = new ArticlesFluent(this);
80
- this.events = new EventsFluent(this);
81
- this.mentions = new MentionsFluent(this);
82
- this.stories = new StoriesFluent(this);
83
- this.trends = new TrendsFluent(this);
84
- this.counts = new CountsFluent(this);
85
- this.shares = new SharesFluent(this);
86
- this.recent = new RecentFluent(this);
87
- this.info = new InfoFluent(this);
88
- this.topicPages = new TopicPagesFluent(this);
89
- this.analytics = new AnalyticsFluent(this);
90
- this.eventForText = createEventForTextFluent(this);
91
- this.concepts = {
92
- uri: (label, args) => resolveConceptUri(this, label, args)
93
- };
94
- this.categories = {
95
- uri: (label) => resolveCategoryUri(this, label)
96
- };
97
- this.sources = {
98
- uri: (label, dataType) => resolveSourceUri(this, label, dataType),
99
- groupUri: (label) => resolveSourceGroupUri(this, label)
100
- };
101
- this.locations = {
102
- uri: (label, args) => resolveLocationUri(this, label, args)
103
- };
104
- this.eventTypes = {
105
- uri: (label) => resolveEventTypeUri(this, label)
106
- };
107
- this.conceptClasses = {
108
- uri: (label, lang) => resolveConceptClassUri(this, label, lang)
99
+ this.minDelayMs = (this.config.minDelayBetweenRequests ?? 0.5) * 1000;
100
+ Object.assign(this, this.buildNamespaces(this));
101
+ }
102
+ /** Namespaces (`er.articles`, `er.concepts`, …) bound to `self`, so a `withOptions` view routes through itself. */
103
+ buildNamespaces(self) {
104
+ return {
105
+ articles: new ArticlesFluent(self),
106
+ events: new EventsFluent(self),
107
+ mentions: new MentionsFluent(self),
108
+ stories: new StoriesFluent(self),
109
+ trends: new TrendsFluent(self),
110
+ counts: new CountsFluent(self),
111
+ shares: new SharesFluent(self),
112
+ recent: new RecentFluent(self),
113
+ info: new InfoFluent(self),
114
+ topicPages: new TopicPagesFluent(self),
115
+ analytics: new AnalyticsFluent(self),
116
+ eventForText: createEventForTextFluent(self),
117
+ concepts: {
118
+ uri: (label, args) => resolveConceptUri(self, label, args)
119
+ },
120
+ categories: {
121
+ uri: (label) => resolveCategoryUri(self, label)
122
+ },
123
+ sources: {
124
+ uri: (label, dataType) => resolveSourceUri(self, label, dataType),
125
+ groupUri: (label) => resolveSourceGroupUri(self, label)
126
+ },
127
+ locations: {
128
+ uri: (label, args) => resolveLocationUri(self, label, args)
129
+ },
130
+ eventTypes: {
131
+ uri: (label) => resolveEventTypeUri(self, label)
132
+ },
133
+ conceptClasses: {
134
+ uri: (label, lang) => resolveConceptClassUri(self, label, lang)
135
+ },
136
+ authors: {
137
+ uri: (label) => resolveAuthorUri(self, label)
138
+ }
109
139
  };
110
- this.authors = {
111
- uri: (label) => resolveAuthorUri(this, label)
140
+ }
141
+ /** Signals and deadline applied to every call made through this instance (or `withOptions` view). */
142
+ get requestScope() {
143
+ return { signals: this.config.signal ? [this.config.signal] : [], timeoutMs: this.config.timeoutMs };
144
+ }
145
+ /**
146
+ * Return a view of this client whose every call (classic, helpers, fluent namespaces and iterators)
147
+ * also observes `options.signal` and `options.timeoutMs`. State (rate limit, usage, headers, queue)
148
+ * is shared with this instance. A view's signal adds to, and its `timeoutMs` replaces, the inherited ones.
149
+ */
150
+ withOptions(options) {
151
+ const scope = this.requestScope;
152
+ const overrides = {
153
+ requestScope: {
154
+ signals: options.signal ? [...scope.signals, options.signal] : scope.signals,
155
+ timeoutMs: options.timeoutMs ?? scope.timeoutMs
156
+ }
112
157
  };
158
+ const view = new Proxy(this, {
159
+ get: (target, prop, receiver) => prop in overrides ? overrides[prop] : Reflect.get(target, prop, receiver),
160
+ // writes (rate-limit bookkeeping, headers, ...) land on the shared root instance
161
+ set: (target, prop, value) => Reflect.set(target, prop, value)
162
+ });
163
+ Object.assign(overrides, this.buildNamespaces(view));
164
+ return view;
113
165
  }
114
166
  getHost() {
115
167
  return this.config.host ?? "https://eventregistry.org";
@@ -122,10 +174,10 @@ export class EventRegistry {
122
174
  }
123
175
  /** Minimum delay between requests in seconds (constructor units). */
124
176
  getMinDelayBetweenRequests() {
125
- return (this.config.minDelayBetweenRequests ?? 500) / 1000;
177
+ return this.minDelayMs / 1000;
126
178
  }
127
179
  getRepeatFailedRequestCount() {
128
- return this.config.repeatFailedRequestCount ?? -1;
180
+ return this.config.repeatFailedRequestCount ?? 5;
129
181
  }
130
182
  /**
131
183
  * Check the latest Node.js SDK version and log if this client is outdated.
@@ -197,7 +249,7 @@ export class EventRegistry {
197
249
  createErrorResponse(error) {
198
250
  const message = error instanceof Error ? error.message : String(error);
199
251
  return {
200
- data: { error: message },
252
+ data: (error instanceof ErApiError ? { error: message, apiError: error } : { error: message }),
201
253
  status: 0,
202
254
  statusText: "error",
203
255
  headers: new Headers()
@@ -219,108 +271,101 @@ export class EventRegistry {
219
271
  /**
220
272
  * Main method for executing the search queries.
221
273
  * @param query instance of Query class
274
+ * @param options `signal` / `timeoutMs` for this call only
222
275
  */
223
- async execQuery(query, allowUseOfArchive = this.config.allowUseOfArchive ?? true) {
276
+ async execQuery(query, allowUseOfArchive = this.config.allowUseOfArchive ?? true, options) {
224
277
  const params = query.getQueryParams();
225
- const request = await this.jsonRequest(query.path, params, allowUseOfArchive);
278
+ const request = await this.jsonRequest(query.path, params, allowUseOfArchive, options);
226
279
  if (!request?.data && this.config?.verboseOutput) {
227
280
  this.logger.error("Request did not return with the 'data' property.");
228
281
  }
229
- return (request?.data || {});
282
+ const data = request?.data || {};
283
+ if (this.config.validate) {
284
+ const issues = validateResponse(data);
285
+ if (issues.length > 0) {
286
+ throw new ErValidationError(query.path, issues);
287
+ }
288
+ }
289
+ return data;
290
+ }
291
+ /** Merge instance/view defaults with per-call options into one signal (caller must `dispose()`). */
292
+ composeCallScope(options) {
293
+ const scope = this.requestScope;
294
+ return composeSignal([...scope.signals, options?.signal], options?.timeoutMs ?? scope.timeoutMs);
295
+ }
296
+ async acquireLock(scope) {
297
+ try {
298
+ await this.lock.acquire(scope.signal);
299
+ }
300
+ catch (error) {
301
+ scope.dispose();
302
+ throw error;
303
+ }
230
304
  }
231
305
  /**
232
306
  * Wait until minDelayBetweenRequests has elapsed since the last attempt.
233
307
  * Must run while holding `this.lock`.
234
308
  */
235
- async waitForTurn() {
309
+ async waitForTurn(signal) {
236
310
  const now = Date.now();
237
- const minDelayBetweenRequests = this.config.minDelayBetweenRequests ?? 500;
238
- if (this.lastQueryTime && now - this.lastQueryTime < minDelayBetweenRequests) {
239
- await sleep(minDelayBetweenRequests - (now - this.lastQueryTime));
311
+ if (this.lastQueryTime && now - this.lastQueryTime < this.minDelayMs) {
312
+ await abortableSleep(this.minDelayMs - (now - this.lastQueryTime), signal);
240
313
  }
241
314
  }
242
- async jsonRequestAnalytics(path, parameters, headers, cookies) {
243
- let request;
244
- await this.lock.acquire();
245
- try {
246
- await this.waitForTurn();
247
- parameters = {
248
- ...parameters,
249
- ...(this.extraParams || {}),
250
- apiKey: this.config?.apiKey
251
- };
252
- let requestHeaders = { ...(headers || {}) };
253
- if (!!headers) {
254
- requestHeaders = { ...headers };
255
- }
256
- if (!!cookies) {
257
- const cookieString = Object.keys(cookies).map((key) => key + "=" + cookies[key]).join(";") + ";";
258
- requestHeaders = { ...requestHeaders, Cookie: cookieString };
259
- }
260
- try {
261
- request = await erFetch({
262
- url: `${this.config.hostAnalytics}${path}`,
263
- method: "POST",
264
- body: parameters,
265
- headers: requestHeaders,
266
- timeoutMs: 600000,
267
- retry: this.config.repeatFailedRequestCount,
268
- retryDelayMs: 5000,
269
- stopStatusCodes: this.stopStatusCodes
270
- });
271
- }
272
- finally {
273
- this.lastQueryTime = Date.now();
274
- }
275
- this.headers = request.headers;
276
- if (request?.status !== 200) {
277
- throw new Error(request?.statusText);
278
- }
279
- const errorMessage = request?.data?.error || "";
280
- if (errorMessage) {
281
- throw new Error(errorMessage);
282
- }
315
+ async jsonRequestAnalytics(path, parameters, headers, cookies, options) {
316
+ const requestHeaders = { ...headers };
317
+ if (cookies) {
318
+ requestHeaders.Cookie = Object.keys(cookies).map((key) => key + "=" + String(cookies[key])).join(";") + ";";
283
319
  }
284
- catch (error) {
285
- request = this.createErrorResponse(error);
286
- const err = error;
287
- if (this.config.verboseOutput) {
288
- this.logger.error("Event Registry Analytics exception while executing the request.");
289
- if (err && err.stack && err.message) {
290
- this.logger.error(err.message);
291
- }
292
- else {
293
- this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${err?.response?.data}`);
294
- }
295
- }
296
- // try to print out the error that should be passed by in case the server is down or responds with errors
297
- if (this.config?.logging) {
298
- this.logger.error(String(err?.errno ?? error));
299
- }
300
- }
301
- finally {
302
- this.lock.release();
303
- }
304
- return request;
320
+ return this.send({
321
+ label: "Event Registry Analytics",
322
+ url: `${this.config.hostAnalytics}${path}`,
323
+ path,
324
+ parameters,
325
+ headers: requestHeaders,
326
+ options
327
+ });
305
328
  }
306
329
  /**
307
330
  * Make a request for json data
308
331
  * @param path url on er (e.g. "/api/v1/article")
309
332
  * @param parameters Optional parameters to be included in the request
310
333
  */
311
- async jsonRequest(path, parameters, allowUseOfArchive = this.config.allowUseOfArchive ?? true) {
334
+ async jsonRequest(path, parameters, allowUseOfArchive = this.config.allowUseOfArchive ?? true, options) {
335
+ return this.send({
336
+ label: "Event Registry",
337
+ url: `${this.config.host}${path}`,
338
+ path,
339
+ parameters,
340
+ allowUseOfArchive,
341
+ options,
342
+ budgeted: path !== USAGE_PATH,
343
+ logged: true,
344
+ readsRateLimit: true
345
+ });
346
+ }
347
+ /**
348
+ * Shared by `jsonRequest` and `jsonRequestAnalytics`: queue behind the lock, honour the minimum delay and
349
+ * the token budget, POST with retries, record usage, and turn failures into an error response.
350
+ */
351
+ async send(spec) {
352
+ const { label, url, path, headers, options, allowUseOfArchive = true, budgeted = true } = spec;
312
353
  let request;
313
- await this.lock.acquire();
354
+ const scope = this.composeCallScope(options);
355
+ await this.acquireLock(scope);
314
356
  try {
315
- await this.waitForTurn();
316
- if (this._logRequests) {
317
- if (Object.keys(parameters || {}).length > 0) {
318
- this.logger.logRequest("# " + JSON.stringify(parameters) + "\n");
357
+ await this.waitForTurn(scope.signal);
358
+ if (budgeted) {
359
+ this.usage.assertWithinBudget(path);
360
+ }
361
+ if (spec.logged && this._logRequests) {
362
+ if (Object.keys(spec.parameters || {}).length > 0) {
363
+ this.logger.logRequest("# " + JSON.stringify(spec.parameters) + "\n");
319
364
  }
320
365
  this.logger.logRequest(path + "\n\n");
321
366
  }
322
- parameters = {
323
- ...parameters,
367
+ let parameters = {
368
+ ...spec.parameters,
324
369
  ...(this.extraParams || {}),
325
370
  apiKey: this.config?.apiKey
326
371
  };
@@ -329,12 +374,15 @@ export class EventRegistry {
329
374
  }
330
375
  try {
331
376
  request = await erFetch({
332
- url: `${this.config.host}${path}`,
377
+ url,
333
378
  method: "POST",
334
379
  body: parameters,
380
+ headers,
381
+ signal: scope.signal,
335
382
  timeoutMs: 600000,
336
383
  retry: this.config.repeatFailedRequestCount,
337
- retryDelayMs: 5000,
384
+ retryDelayMs: this.config.retryDelayMs,
385
+ maxRetryDelayMs: this.config.maxRetryDelayMs,
338
386
  stopStatusCodes: this.stopStatusCodes
339
387
  });
340
388
  }
@@ -342,38 +390,51 @@ export class EventRegistry {
342
390
  this.lastQueryTime = Date.now();
343
391
  }
344
392
  this.headers = request.headers;
393
+ this.usage.record(path, request.headers);
345
394
  if (request?.status !== 200) {
346
395
  throw new Error(request?.statusText);
347
396
  }
348
- if (this.getLastHeader("warning")) {
349
- this.logger.warn(`WARNING: ${this.getLastHeader("warning")}`);
397
+ if (spec.readsRateLimit) {
398
+ if (this.getLastHeader("warning")) {
399
+ this.logger.warn(`WARNING: ${this.getLastHeader("warning")}`);
400
+ }
401
+ this.dailyAvailableRequests = Number(this.getLastHeader("x-ratelimit-limit", "-1"));
402
+ this.remainingAvailableRequests = Number(this.getLastHeader("x-ratelimit-remaining", "-1"));
350
403
  }
351
- this.dailyAvailableRequests = Number(this.getLastHeader("x-ratelimit-limit", "-1"));
352
- this.remainingAvailableRequests = Number(this.getLastHeader("x-ratelimit-remaining", "-1"));
353
404
  const errorMessage = request?.data?.error || "";
354
405
  if (errorMessage) {
355
406
  throw new Error(errorMessage);
356
407
  }
357
408
  }
358
409
  catch (error) {
359
- request = this.createErrorResponse(error);
410
+ if (error instanceof ErBudgetExceededError) {
411
+ throw error;
412
+ }
413
+ if (scope.signal?.aborted) {
414
+ throw scope.signal.reason;
415
+ }
360
416
  const err = error;
361
- // try to print out the error that should be passed by in case the server is down or responds with errors
362
417
  if (this.config.verboseOutput) {
363
- this.logger.error("Event Registry exception while executing the request.");
418
+ this.logger.error(`${label} exception while executing the request.`);
364
419
  if (err && err.stack && err.message) {
365
420
  this.logger.error(err.message);
366
421
  }
367
422
  else {
368
- this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${err?.response?.data}`);
423
+ this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${String(err?.response?.data)}`);
369
424
  }
370
425
  }
426
+ // try to print out the error that should be passed by in case the server is down or responds with errors
371
427
  if (this.config?.logging) {
372
428
  this.logger.error(String(err?.errno ?? error));
373
429
  }
430
+ if (this.config.throwOnError) {
431
+ throw error;
432
+ }
433
+ request = this.createErrorResponse(error);
374
434
  }
375
435
  finally {
376
436
  this.lock.release();
437
+ scope.dispose();
377
438
  }
378
439
  return request;
379
440
  }
@@ -418,14 +479,26 @@ export class EventRegistry {
418
479
  /**
419
480
  * Return the number of used and total available tokens. Can be used at any time (also before making queries)
420
481
  */
421
- async getUsageInfo() {
422
- const request = await this.jsonRequest("/api/v1/usage");
482
+ async getUsageInfo(options) {
483
+ const request = await this.jsonRequest(USAGE_PATH, undefined, undefined, options);
423
484
  return request.data;
424
485
  }
486
+ /**
487
+ * Tokens still available on the account (`availableTokens - usedTokens` from the usage endpoint).
488
+ * Makes one request; it is exempt from the `maxTokens` guard.
489
+ */
490
+ async getRemainingTokens(options) {
491
+ const info = await this.getUsageInfo(options);
492
+ return info.availableTokens - info.usedTokens;
493
+ }
425
494
  async getServiceStatus() {
426
495
  const request = await this.jsonRequest("/api/v1/getServiceStatus");
427
496
  return request.data;
428
497
  }
498
+ /**
499
+ * Return the GET URL for the query. Parameters are URL-encoded, arrays become repeated keys,
500
+ * objects are JSON-encoded, and apiKey is always left out so the URL is safe to log or share.
501
+ */
429
502
  getUrl(query) {
430
503
  if (!(query instanceof QueryParamsBase)) {
431
504
  if (this.config.verboseOutput) {
@@ -433,7 +506,27 @@ export class EventRegistry {
433
506
  }
434
507
  }
435
508
  const allParams = query.getQueryParams();
436
- return `${this.config?.host}${query?.path}?${Object.keys(allParams).map(key => `${key}=${allParams[key]}`).join("&")}`;
509
+ const searchParams = new URLSearchParams();
510
+ const append = (key, value) => {
511
+ if (value === undefined || value === null) {
512
+ return;
513
+ }
514
+ // Objects are serialised above, so only primitives reach String().
515
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
516
+ searchParams.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
517
+ };
518
+ for (const [key, value] of Object.entries(allParams)) {
519
+ if (key === "apiKey") {
520
+ continue;
521
+ }
522
+ if (Array.isArray(value)) {
523
+ value.forEach((item) => append(key, item));
524
+ }
525
+ else {
526
+ append(key, value);
527
+ }
528
+ }
529
+ return `${this.config?.host}${query?.path}?${searchParams.toString()}`;
437
530
  }
438
531
  /**
439
532
  * Return a list of concepts that contain the given prefix.
@@ -563,19 +656,20 @@ export class EventRegistry {
563
656
  * @param radiusKm radius in kilometers around the coordinates inside which the news sources should be located
564
657
  * @param count number of returned suggestions
565
658
  */
566
- async suggestSourcesAtCoordinate(latitude, longitude, radiusKm, count = 20, ...otherParams) {
659
+ async suggestSourcesAtCoordinate(latitude, longitude, radiusKm, countOrArgs = 20) {
567
660
  if (typeof latitude !== "number") {
568
661
  throw new Error("The 'latitude' should be a number");
569
662
  }
570
663
  if (typeof longitude !== "number") {
571
664
  throw new Error("The 'longitude' should be a number");
572
665
  }
666
+ const { count = 20, ...otherParams } = typeof countOrArgs === "number" ? { count: countOrArgs } : countOrArgs;
573
667
  const params = {
574
668
  action: "getSourcesAtCoordinate",
575
669
  lat: latitude,
576
670
  lon: longitude,
577
671
  radius: radiusKm,
578
- count: count,
672
+ count,
579
673
  ...otherParams
580
674
  };
581
675
  const request = await this.jsonRequest("/api/v1/suggestSourcesFast", params);
@@ -599,65 +693,23 @@ export class EventRegistry {
599
693
  const request = await this.jsonRequest("/api/v1/suggestSourcesFast", params);
600
694
  return request.data;
601
695
  }
602
- /**
603
- * Return a list of news sources that match the prefix
604
- * @param prefix: input text that should be contained in the author name and source url
605
- * @param page: page of results
606
- * @param count: number of returned suggestions
607
- */
608
- async suggestAuthors(prefix, page = 1, count = 20, ...otherParams) {
609
- if (page <= 0) {
610
- throw new Error("Page parameter should be above 0.");
611
- }
612
- const params = {
613
- prefix,
614
- page,
615
- count,
616
- ...otherParams
617
- };
696
+ async suggestAuthors(prefix, pageOrArgs, count) {
697
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
618
698
  const request = await this.jsonRequest("/api/v1/suggestAuthorsFast", params);
619
699
  return request.data;
620
700
  }
621
- /**
622
- * Return a list of event types that match the prefix
623
- * @param prefix: input text that should be contained in the industry name
624
- * @param page: page of results
625
- * @param count: number of returned suggestions
626
- */
627
- async suggestEventTypes(prefix, page = 1, count = 20, ...otherParams) {
628
- if (page <= 0) {
629
- throw new Error("Page parameter should be above 0.");
630
- }
631
- const params = {
632
- prefix,
633
- page,
634
- count,
635
- ...otherParams
636
- };
701
+ async suggestEventTypes(prefix, pageOrArgs, count) {
702
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
637
703
  const request = await this.jsonRequest("/api/v1/eventType/suggestEventTypes", params);
638
704
  return request.data;
639
705
  }
640
- /**
641
- * Return a list of industries that match the prefix. Note: Industries can only be used when querying mentions (QueryMentions, QueryMentionsIter)
642
- * @param prefix: input text that should be contained in the industry name
643
- * @param page: page of results
644
- * @param count: number of returned suggestions
645
- */
646
- async suggestIndustries(prefix, page = 1, count = 20, ...otherParams) {
647
- if (page <= 0) {
648
- throw new Error("Page parameter should be above 0.");
649
- }
650
- const params = {
651
- prefix,
652
- page,
653
- count,
654
- ...otherParams
655
- };
706
+ async suggestIndustries(prefix, pageOrArgs, count) {
707
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
656
708
  const request = await this.jsonRequest("/api/v1/eventType/suggestIndustries", params);
657
709
  return request.data;
658
710
  }
659
711
  /**
660
- * Return a list of SDG uris. Note: Industries can only be used when querying mentions (QueryMentions, QueryMentionsIter)
712
+ * Return a list of SDG uris. Note: SDGs can only be used when querying mentions (QueryMentions, QueryMentionsIter)
661
713
  */
662
714
  async getSdgUris() {
663
715
  const request = await this.jsonRequest("/api/v1/eventType/sdg/getItems");
@@ -802,7 +854,7 @@ export class EventRegistry {
802
854
  return request.data;
803
855
  }
804
856
  /**
805
- * Return information about the latest imported article
857
+ * Return the list of source groups
806
858
  */
807
859
  async getSourceGroups() {
808
860
  const request = await this.jsonRequest("/api/v1/sourceGroup/getSourceGroups", { action: "getSourceGroups" });
@@ -823,7 +875,7 @@ export class EventRegistry {
823
875
  */
824
876
  export class ArticleMapper {
825
877
  constructor(er, rememberMapping = true) {
826
- this.articleUrlToUri = {};
878
+ this.articleUrlToUri = new Map();
827
879
  this.rememberMappings = true;
828
880
  this.er = er;
829
881
  this.rememberMappings = rememberMapping;
@@ -835,13 +887,13 @@ export class ArticleMapper {
835
887
  * @param articleUrl string containing the article url
836
888
  */
837
889
  async getArticleUri(articleUrl) {
838
- if (this.articleUrlToUri.hasOwnProperty(articleUrl)) {
839
- return this.articleUrlToUri[articleUrl];
890
+ if (this.articleUrlToUri.has(articleUrl)) {
891
+ return this.articleUrlToUri.get(articleUrl);
840
892
  }
841
893
  const response = await this.er.getArticleUris(articleUrl);
842
894
  const value = response?.[articleUrl];
843
895
  if (this.rememberMappings && value) {
844
- this.articleUrlToUri = { ...this.articleUrlToUri, [articleUrl]: value };
896
+ this.articleUrlToUri.set(articleUrl, value);
845
897
  }
846
898
  return value;
847
899
  }