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
@@ -34,8 +34,12 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.ArticleMapper = exports.EventRegistry = void 0;
37
- const fs = __importStar(require("fs"));
37
+ const fs = __importStar(require("node:fs"));
38
38
  const mutex_1 = require("./mutex");
39
+ const errors_1 = require("./errors");
40
+ const guards_1 = require("./guards");
41
+ const usage_1 = require("./usage");
42
+ const abort_1 = require("./abort");
39
43
  const http_1 = require("./http");
40
44
  const returnInfo_1 = require("./returnInfo");
41
45
  const base_1 = require("./base");
@@ -66,6 +70,15 @@ function firstMatchField(matches, field) {
66
70
  * @class EventRegistry
67
71
  * Main class responsible for obtaining results form the Event Registry
68
72
  */
73
+ const USAGE_PATH = "/api/v1/usage";
74
+ /** Build the request params for the prefix suggesters from either call style (positional page/count or an args object). */
75
+ function pagedSuggestParams(prefix, pageOrArgs = {}, count) {
76
+ const { page = 1, count: argsCount = 20, ...otherParams } = typeof pageOrArgs === "number" ? { page: pageOrArgs, count } : pageOrArgs;
77
+ if (page <= 0) {
78
+ throw new Error("Page parameter should be above 0.");
79
+ }
80
+ return { prefix, page, count: argsCount, ...otherParams };
81
+ }
69
82
  class EventRegistry {
70
83
  constructor(config = {}) {
71
84
  this.config = {
@@ -73,7 +86,7 @@ class EventRegistry {
73
86
  hostAnalytics: "https://analytics.eventregistry.org",
74
87
  logging: false,
75
88
  minDelayBetweenRequests: 0.5,
76
- repeatFailedRequestCount: -1,
89
+ repeatFailedRequestCount: 5,
77
90
  verboseOutput: false,
78
91
  allowUseOfArchive: true
79
92
  };
@@ -81,6 +94,8 @@ class EventRegistry {
81
94
  this.dailyAvailableRequests = -1;
82
95
  this.remainingAvailableRequests = -1;
83
96
  this.lastQueryTime = 0;
97
+ /** `minDelayBetweenRequests` converted to milliseconds. */
98
+ this.minDelayMs = 500;
84
99
  this._logRequests = false;
85
100
  this.extraParams = null;
86
101
  this.stopStatusCodes = [204, 400, 401, 403, 530];
@@ -88,7 +103,12 @@ class EventRegistry {
88
103
  const settingsPath = config.settingsFName || "settings.json";
89
104
  let fileSettings = {};
90
105
  if (fs && fs.existsSync(settingsPath)) {
91
- fileSettings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
106
+ try {
107
+ fileSettings = JSON.parse(fs.readFileSync(settingsPath, "utf8"));
108
+ }
109
+ catch (err) {
110
+ throw new Error(`Could not read the settings file '${settingsPath}': ${err instanceof Error ? err.message : String(err)}`);
111
+ }
92
112
  }
93
113
  this.config = {
94
114
  ...this.config,
@@ -98,6 +118,7 @@ class EventRegistry {
98
118
  hostAnalytics: config.hostAnalytics ?? fileSettings.hostAnalytics ?? this.config.hostAnalytics,
99
119
  apiKey: config.apiKey !== undefined ? config.apiKey : fileSettings.apiKey
100
120
  };
121
+ this.usage = new usage_1.Usage(this.config.maxTokens);
101
122
  this._logRequests = this.config.logging ?? false;
102
123
  this.logger = new logger_1.Logger({ logging: this.config.logging, logRequests: this._logRequests });
103
124
  if (config.apiKey) {
@@ -111,41 +132,72 @@ class EventRegistry {
111
132
  }
112
133
  this.logger.debug(`Event Registry host: ${this.config.host}`);
113
134
  this.logger.debug(`Text analytics host: ${this.config.hostAnalytics}`);
114
- this.config.minDelayBetweenRequests = (this.config.minDelayBetweenRequests ?? 0.5) * 1000;
115
- this.articles = new articles_1.ArticlesFluent(this);
116
- this.events = new events_1.EventsFluent(this);
117
- this.mentions = new mentions_1.MentionsFluent(this);
118
- this.stories = new stories_1.StoriesFluent(this);
119
- this.trends = new trends_1.TrendsFluent(this);
120
- this.counts = new counts_1.CountsFluent(this);
121
- this.shares = new shares_1.SharesFluent(this);
122
- this.recent = new recent_1.RecentFluent(this);
123
- this.info = new info_1.InfoFluent(this);
124
- this.topicPages = new topicPages_1.TopicPagesFluent(this);
125
- this.analytics = new analytics_1.AnalyticsFluent(this);
126
- this.eventForText = (0, eventForText_1.createEventForTextFluent)(this);
127
- this.concepts = {
128
- uri: (label, args) => (0, uri_1.conceptUri)(this, label, args)
129
- };
130
- this.categories = {
131
- uri: (label) => (0, uri_1.categoryUri)(this, label)
132
- };
133
- this.sources = {
134
- uri: (label, dataType) => (0, uri_1.sourceUri)(this, label, dataType),
135
- groupUri: (label) => (0, uri_1.sourceGroupUri)(this, label)
136
- };
137
- this.locations = {
138
- uri: (label, args) => (0, uri_1.locationUri)(this, label, args)
139
- };
140
- this.eventTypes = {
141
- uri: (label) => (0, uri_1.eventTypeUri)(this, label)
142
- };
143
- this.conceptClasses = {
144
- uri: (label, lang) => (0, uri_1.conceptClassUri)(this, label, lang)
135
+ this.minDelayMs = (this.config.minDelayBetweenRequests ?? 0.5) * 1000;
136
+ Object.assign(this, this.buildNamespaces(this));
137
+ }
138
+ /** Namespaces (`er.articles`, `er.concepts`, …) bound to `self`, so a `withOptions` view routes through itself. */
139
+ buildNamespaces(self) {
140
+ return {
141
+ articles: new articles_1.ArticlesFluent(self),
142
+ events: new events_1.EventsFluent(self),
143
+ mentions: new mentions_1.MentionsFluent(self),
144
+ stories: new stories_1.StoriesFluent(self),
145
+ trends: new trends_1.TrendsFluent(self),
146
+ counts: new counts_1.CountsFluent(self),
147
+ shares: new shares_1.SharesFluent(self),
148
+ recent: new recent_1.RecentFluent(self),
149
+ info: new info_1.InfoFluent(self),
150
+ topicPages: new topicPages_1.TopicPagesFluent(self),
151
+ analytics: new analytics_1.AnalyticsFluent(self),
152
+ eventForText: (0, eventForText_1.createEventForTextFluent)(self),
153
+ concepts: {
154
+ uri: (label, args) => (0, uri_1.conceptUri)(self, label, args)
155
+ },
156
+ categories: {
157
+ uri: (label) => (0, uri_1.categoryUri)(self, label)
158
+ },
159
+ sources: {
160
+ uri: (label, dataType) => (0, uri_1.sourceUri)(self, label, dataType),
161
+ groupUri: (label) => (0, uri_1.sourceGroupUri)(self, label)
162
+ },
163
+ locations: {
164
+ uri: (label, args) => (0, uri_1.locationUri)(self, label, args)
165
+ },
166
+ eventTypes: {
167
+ uri: (label) => (0, uri_1.eventTypeUri)(self, label)
168
+ },
169
+ conceptClasses: {
170
+ uri: (label, lang) => (0, uri_1.conceptClassUri)(self, label, lang)
171
+ },
172
+ authors: {
173
+ uri: (label) => (0, uri_1.authorUri)(self, label)
174
+ }
145
175
  };
146
- this.authors = {
147
- uri: (label) => (0, uri_1.authorUri)(this, label)
176
+ }
177
+ /** Signals and deadline applied to every call made through this instance (or `withOptions` view). */
178
+ get requestScope() {
179
+ return { signals: this.config.signal ? [this.config.signal] : [], timeoutMs: this.config.timeoutMs };
180
+ }
181
+ /**
182
+ * Return a view of this client whose every call (classic, helpers, fluent namespaces and iterators)
183
+ * also observes `options.signal` and `options.timeoutMs`. State (rate limit, usage, headers, queue)
184
+ * is shared with this instance. A view's signal adds to, and its `timeoutMs` replaces, the inherited ones.
185
+ */
186
+ withOptions(options) {
187
+ const scope = this.requestScope;
188
+ const overrides = {
189
+ requestScope: {
190
+ signals: options.signal ? [...scope.signals, options.signal] : scope.signals,
191
+ timeoutMs: options.timeoutMs ?? scope.timeoutMs
192
+ }
148
193
  };
194
+ const view = new Proxy(this, {
195
+ get: (target, prop, receiver) => prop in overrides ? overrides[prop] : Reflect.get(target, prop, receiver),
196
+ // writes (rate-limit bookkeeping, headers, ...) land on the shared root instance
197
+ set: (target, prop, value) => Reflect.set(target, prop, value)
198
+ });
199
+ Object.assign(overrides, this.buildNamespaces(view));
200
+ return view;
149
201
  }
150
202
  getHost() {
151
203
  return this.config.host ?? "https://eventregistry.org";
@@ -158,10 +210,10 @@ class EventRegistry {
158
210
  }
159
211
  /** Minimum delay between requests in seconds (constructor units). */
160
212
  getMinDelayBetweenRequests() {
161
- return (this.config.minDelayBetweenRequests ?? 500) / 1000;
213
+ return this.minDelayMs / 1000;
162
214
  }
163
215
  getRepeatFailedRequestCount() {
164
- return this.config.repeatFailedRequestCount ?? -1;
216
+ return this.config.repeatFailedRequestCount ?? 5;
165
217
  }
166
218
  /**
167
219
  * Check the latest Node.js SDK version and log if this client is outdated.
@@ -233,7 +285,7 @@ class EventRegistry {
233
285
  createErrorResponse(error) {
234
286
  const message = error instanceof Error ? error.message : String(error);
235
287
  return {
236
- data: { error: message },
288
+ data: (error instanceof errors_1.ErApiError ? { error: message, apiError: error } : { error: message }),
237
289
  status: 0,
238
290
  statusText: "error",
239
291
  headers: new Headers()
@@ -255,108 +307,101 @@ class EventRegistry {
255
307
  /**
256
308
  * Main method for executing the search queries.
257
309
  * @param query instance of Query class
310
+ * @param options `signal` / `timeoutMs` for this call only
258
311
  */
259
- async execQuery(query, allowUseOfArchive = this.config.allowUseOfArchive ?? true) {
312
+ async execQuery(query, allowUseOfArchive = this.config.allowUseOfArchive ?? true, options) {
260
313
  const params = query.getQueryParams();
261
- const request = await this.jsonRequest(query.path, params, allowUseOfArchive);
314
+ const request = await this.jsonRequest(query.path, params, allowUseOfArchive, options);
262
315
  if (!request?.data && this.config?.verboseOutput) {
263
316
  this.logger.error("Request did not return with the 'data' property.");
264
317
  }
265
- return (request?.data || {});
318
+ const data = request?.data || {};
319
+ if (this.config.validate) {
320
+ const issues = (0, guards_1.validateResponse)(data);
321
+ if (issues.length > 0) {
322
+ throw new errors_1.ErValidationError(query.path, issues);
323
+ }
324
+ }
325
+ return data;
326
+ }
327
+ /** Merge instance/view defaults with per-call options into one signal (caller must `dispose()`). */
328
+ composeCallScope(options) {
329
+ const scope = this.requestScope;
330
+ return (0, abort_1.composeSignal)([...scope.signals, options?.signal], options?.timeoutMs ?? scope.timeoutMs);
331
+ }
332
+ async acquireLock(scope) {
333
+ try {
334
+ await this.lock.acquire(scope.signal);
335
+ }
336
+ catch (error) {
337
+ scope.dispose();
338
+ throw error;
339
+ }
266
340
  }
267
341
  /**
268
342
  * Wait until minDelayBetweenRequests has elapsed since the last attempt.
269
343
  * Must run while holding `this.lock`.
270
344
  */
271
- async waitForTurn() {
345
+ async waitForTurn(signal) {
272
346
  const now = Date.now();
273
- const minDelayBetweenRequests = this.config.minDelayBetweenRequests ?? 500;
274
- if (this.lastQueryTime && now - this.lastQueryTime < minDelayBetweenRequests) {
275
- await (0, base_1.sleep)(minDelayBetweenRequests - (now - this.lastQueryTime));
347
+ if (this.lastQueryTime && now - this.lastQueryTime < this.minDelayMs) {
348
+ await (0, abort_1.abortableSleep)(this.minDelayMs - (now - this.lastQueryTime), signal);
276
349
  }
277
350
  }
278
- async jsonRequestAnalytics(path, parameters, headers, cookies) {
279
- let request;
280
- await this.lock.acquire();
281
- try {
282
- await this.waitForTurn();
283
- parameters = {
284
- ...parameters,
285
- ...(this.extraParams || {}),
286
- apiKey: this.config?.apiKey
287
- };
288
- let requestHeaders = { ...(headers || {}) };
289
- if (!!headers) {
290
- requestHeaders = { ...headers };
291
- }
292
- if (!!cookies) {
293
- const cookieString = Object.keys(cookies).map((key) => key + "=" + cookies[key]).join(";") + ";";
294
- requestHeaders = { ...requestHeaders, Cookie: cookieString };
295
- }
296
- try {
297
- request = await (0, http_1.erFetch)({
298
- url: `${this.config.hostAnalytics}${path}`,
299
- method: "POST",
300
- body: parameters,
301
- headers: requestHeaders,
302
- timeoutMs: 600000,
303
- retry: this.config.repeatFailedRequestCount,
304
- retryDelayMs: 5000,
305
- stopStatusCodes: this.stopStatusCodes
306
- });
307
- }
308
- finally {
309
- this.lastQueryTime = Date.now();
310
- }
311
- this.headers = request.headers;
312
- if (request?.status !== 200) {
313
- throw new Error(request?.statusText);
314
- }
315
- const errorMessage = request?.data?.error || "";
316
- if (errorMessage) {
317
- throw new Error(errorMessage);
318
- }
351
+ async jsonRequestAnalytics(path, parameters, headers, cookies, options) {
352
+ const requestHeaders = { ...headers };
353
+ if (cookies) {
354
+ requestHeaders.Cookie = Object.keys(cookies).map((key) => key + "=" + String(cookies[key])).join(";") + ";";
319
355
  }
320
- catch (error) {
321
- request = this.createErrorResponse(error);
322
- const err = error;
323
- if (this.config.verboseOutput) {
324
- this.logger.error("Event Registry Analytics exception while executing the request.");
325
- if (err && err.stack && err.message) {
326
- this.logger.error(err.message);
327
- }
328
- else {
329
- this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${err?.response?.data}`);
330
- }
331
- }
332
- // try to print out the error that should be passed by in case the server is down or responds with errors
333
- if (this.config?.logging) {
334
- this.logger.error(String(err?.errno ?? error));
335
- }
336
- }
337
- finally {
338
- this.lock.release();
339
- }
340
- return request;
356
+ return this.send({
357
+ label: "Event Registry Analytics",
358
+ url: `${this.config.hostAnalytics}${path}`,
359
+ path,
360
+ parameters,
361
+ headers: requestHeaders,
362
+ options
363
+ });
341
364
  }
342
365
  /**
343
366
  * Make a request for json data
344
367
  * @param path url on er (e.g. "/api/v1/article")
345
368
  * @param parameters Optional parameters to be included in the request
346
369
  */
347
- async jsonRequest(path, parameters, allowUseOfArchive = this.config.allowUseOfArchive ?? true) {
370
+ async jsonRequest(path, parameters, allowUseOfArchive = this.config.allowUseOfArchive ?? true, options) {
371
+ return this.send({
372
+ label: "Event Registry",
373
+ url: `${this.config.host}${path}`,
374
+ path,
375
+ parameters,
376
+ allowUseOfArchive,
377
+ options,
378
+ budgeted: path !== USAGE_PATH,
379
+ logged: true,
380
+ readsRateLimit: true
381
+ });
382
+ }
383
+ /**
384
+ * Shared by `jsonRequest` and `jsonRequestAnalytics`: queue behind the lock, honour the minimum delay and
385
+ * the token budget, POST with retries, record usage, and turn failures into an error response.
386
+ */
387
+ async send(spec) {
388
+ const { label, url, path, headers, options, allowUseOfArchive = true, budgeted = true } = spec;
348
389
  let request;
349
- await this.lock.acquire();
390
+ const scope = this.composeCallScope(options);
391
+ await this.acquireLock(scope);
350
392
  try {
351
- await this.waitForTurn();
352
- if (this._logRequests) {
353
- if (Object.keys(parameters || {}).length > 0) {
354
- this.logger.logRequest("# " + JSON.stringify(parameters) + "\n");
393
+ await this.waitForTurn(scope.signal);
394
+ if (budgeted) {
395
+ this.usage.assertWithinBudget(path);
396
+ }
397
+ if (spec.logged && this._logRequests) {
398
+ if (Object.keys(spec.parameters || {}).length > 0) {
399
+ this.logger.logRequest("# " + JSON.stringify(spec.parameters) + "\n");
355
400
  }
356
401
  this.logger.logRequest(path + "\n\n");
357
402
  }
358
- parameters = {
359
- ...parameters,
403
+ let parameters = {
404
+ ...spec.parameters,
360
405
  ...(this.extraParams || {}),
361
406
  apiKey: this.config?.apiKey
362
407
  };
@@ -365,12 +410,15 @@ class EventRegistry {
365
410
  }
366
411
  try {
367
412
  request = await (0, http_1.erFetch)({
368
- url: `${this.config.host}${path}`,
413
+ url,
369
414
  method: "POST",
370
415
  body: parameters,
416
+ headers,
417
+ signal: scope.signal,
371
418
  timeoutMs: 600000,
372
419
  retry: this.config.repeatFailedRequestCount,
373
- retryDelayMs: 5000,
420
+ retryDelayMs: this.config.retryDelayMs,
421
+ maxRetryDelayMs: this.config.maxRetryDelayMs,
374
422
  stopStatusCodes: this.stopStatusCodes
375
423
  });
376
424
  }
@@ -378,38 +426,51 @@ class EventRegistry {
378
426
  this.lastQueryTime = Date.now();
379
427
  }
380
428
  this.headers = request.headers;
429
+ this.usage.record(path, request.headers);
381
430
  if (request?.status !== 200) {
382
431
  throw new Error(request?.statusText);
383
432
  }
384
- if (this.getLastHeader("warning")) {
385
- this.logger.warn(`WARNING: ${this.getLastHeader("warning")}`);
433
+ if (spec.readsRateLimit) {
434
+ if (this.getLastHeader("warning")) {
435
+ this.logger.warn(`WARNING: ${this.getLastHeader("warning")}`);
436
+ }
437
+ this.dailyAvailableRequests = Number(this.getLastHeader("x-ratelimit-limit", "-1"));
438
+ this.remainingAvailableRequests = Number(this.getLastHeader("x-ratelimit-remaining", "-1"));
386
439
  }
387
- this.dailyAvailableRequests = Number(this.getLastHeader("x-ratelimit-limit", "-1"));
388
- this.remainingAvailableRequests = Number(this.getLastHeader("x-ratelimit-remaining", "-1"));
389
440
  const errorMessage = request?.data?.error || "";
390
441
  if (errorMessage) {
391
442
  throw new Error(errorMessage);
392
443
  }
393
444
  }
394
445
  catch (error) {
395
- request = this.createErrorResponse(error);
446
+ if (error instanceof errors_1.ErBudgetExceededError) {
447
+ throw error;
448
+ }
449
+ if (scope.signal?.aborted) {
450
+ throw scope.signal.reason;
451
+ }
396
452
  const err = error;
397
- // try to print out the error that should be passed by in case the server is down or responds with errors
398
453
  if (this.config.verboseOutput) {
399
- this.logger.error("Event Registry exception while executing the request.");
454
+ this.logger.error(`${label} exception while executing the request.`);
400
455
  if (err && err.stack && err.message) {
401
456
  this.logger.error(err.message);
402
457
  }
403
458
  else {
404
- this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${err?.response?.data}`);
459
+ this.logger.error(`${err?.response?.status}: ${err?.response?.statusText} => ${String(err?.response?.data)}`);
405
460
  }
406
461
  }
462
+ // try to print out the error that should be passed by in case the server is down or responds with errors
407
463
  if (this.config?.logging) {
408
464
  this.logger.error(String(err?.errno ?? error));
409
465
  }
466
+ if (this.config.throwOnError) {
467
+ throw error;
468
+ }
469
+ request = this.createErrorResponse(error);
410
470
  }
411
471
  finally {
412
472
  this.lock.release();
473
+ scope.dispose();
413
474
  }
414
475
  return request;
415
476
  }
@@ -454,14 +515,26 @@ class EventRegistry {
454
515
  /**
455
516
  * Return the number of used and total available tokens. Can be used at any time (also before making queries)
456
517
  */
457
- async getUsageInfo() {
458
- const request = await this.jsonRequest("/api/v1/usage");
518
+ async getUsageInfo(options) {
519
+ const request = await this.jsonRequest(USAGE_PATH, undefined, undefined, options);
459
520
  return request.data;
460
521
  }
522
+ /**
523
+ * Tokens still available on the account (`availableTokens - usedTokens` from the usage endpoint).
524
+ * Makes one request; it is exempt from the `maxTokens` guard.
525
+ */
526
+ async getRemainingTokens(options) {
527
+ const info = await this.getUsageInfo(options);
528
+ return info.availableTokens - info.usedTokens;
529
+ }
461
530
  async getServiceStatus() {
462
531
  const request = await this.jsonRequest("/api/v1/getServiceStatus");
463
532
  return request.data;
464
533
  }
534
+ /**
535
+ * Return the GET URL for the query. Parameters are URL-encoded, arrays become repeated keys,
536
+ * objects are JSON-encoded, and apiKey is always left out so the URL is safe to log or share.
537
+ */
465
538
  getUrl(query) {
466
539
  if (!(query instanceof base_1.QueryParamsBase)) {
467
540
  if (this.config.verboseOutput) {
@@ -469,7 +542,27 @@ class EventRegistry {
469
542
  }
470
543
  }
471
544
  const allParams = query.getQueryParams();
472
- return `${this.config?.host}${query?.path}?${Object.keys(allParams).map(key => `${key}=${allParams[key]}`).join("&")}`;
545
+ const searchParams = new URLSearchParams();
546
+ const append = (key, value) => {
547
+ if (value === undefined || value === null) {
548
+ return;
549
+ }
550
+ // Objects are serialised above, so only primitives reach String().
551
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
552
+ searchParams.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
553
+ };
554
+ for (const [key, value] of Object.entries(allParams)) {
555
+ if (key === "apiKey") {
556
+ continue;
557
+ }
558
+ if (Array.isArray(value)) {
559
+ value.forEach((item) => append(key, item));
560
+ }
561
+ else {
562
+ append(key, value);
563
+ }
564
+ }
565
+ return `${this.config?.host}${query?.path}?${searchParams.toString()}`;
473
566
  }
474
567
  /**
475
568
  * Return a list of concepts that contain the given prefix.
@@ -599,19 +692,20 @@ class EventRegistry {
599
692
  * @param radiusKm radius in kilometers around the coordinates inside which the news sources should be located
600
693
  * @param count number of returned suggestions
601
694
  */
602
- async suggestSourcesAtCoordinate(latitude, longitude, radiusKm, count = 20, ...otherParams) {
695
+ async suggestSourcesAtCoordinate(latitude, longitude, radiusKm, countOrArgs = 20) {
603
696
  if (typeof latitude !== "number") {
604
697
  throw new Error("The 'latitude' should be a number");
605
698
  }
606
699
  if (typeof longitude !== "number") {
607
700
  throw new Error("The 'longitude' should be a number");
608
701
  }
702
+ const { count = 20, ...otherParams } = typeof countOrArgs === "number" ? { count: countOrArgs } : countOrArgs;
609
703
  const params = {
610
704
  action: "getSourcesAtCoordinate",
611
705
  lat: latitude,
612
706
  lon: longitude,
613
707
  radius: radiusKm,
614
- count: count,
708
+ count,
615
709
  ...otherParams
616
710
  };
617
711
  const request = await this.jsonRequest("/api/v1/suggestSourcesFast", params);
@@ -635,65 +729,23 @@ class EventRegistry {
635
729
  const request = await this.jsonRequest("/api/v1/suggestSourcesFast", params);
636
730
  return request.data;
637
731
  }
638
- /**
639
- * Return a list of news sources that match the prefix
640
- * @param prefix: input text that should be contained in the author name and source url
641
- * @param page: page of results
642
- * @param count: number of returned suggestions
643
- */
644
- async suggestAuthors(prefix, page = 1, count = 20, ...otherParams) {
645
- if (page <= 0) {
646
- throw new Error("Page parameter should be above 0.");
647
- }
648
- const params = {
649
- prefix,
650
- page,
651
- count,
652
- ...otherParams
653
- };
732
+ async suggestAuthors(prefix, pageOrArgs, count) {
733
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
654
734
  const request = await this.jsonRequest("/api/v1/suggestAuthorsFast", params);
655
735
  return request.data;
656
736
  }
657
- /**
658
- * Return a list of event types that match the prefix
659
- * @param prefix: input text that should be contained in the industry name
660
- * @param page: page of results
661
- * @param count: number of returned suggestions
662
- */
663
- async suggestEventTypes(prefix, page = 1, count = 20, ...otherParams) {
664
- if (page <= 0) {
665
- throw new Error("Page parameter should be above 0.");
666
- }
667
- const params = {
668
- prefix,
669
- page,
670
- count,
671
- ...otherParams
672
- };
737
+ async suggestEventTypes(prefix, pageOrArgs, count) {
738
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
673
739
  const request = await this.jsonRequest("/api/v1/eventType/suggestEventTypes", params);
674
740
  return request.data;
675
741
  }
676
- /**
677
- * Return a list of industries that match the prefix. Note: Industries can only be used when querying mentions (QueryMentions, QueryMentionsIter)
678
- * @param prefix: input text that should be contained in the industry name
679
- * @param page: page of results
680
- * @param count: number of returned suggestions
681
- */
682
- async suggestIndustries(prefix, page = 1, count = 20, ...otherParams) {
683
- if (page <= 0) {
684
- throw new Error("Page parameter should be above 0.");
685
- }
686
- const params = {
687
- prefix,
688
- page,
689
- count,
690
- ...otherParams
691
- };
742
+ async suggestIndustries(prefix, pageOrArgs, count) {
743
+ const params = pagedSuggestParams(prefix, pageOrArgs, count);
692
744
  const request = await this.jsonRequest("/api/v1/eventType/suggestIndustries", params);
693
745
  return request.data;
694
746
  }
695
747
  /**
696
- * Return a list of SDG uris. Note: Industries can only be used when querying mentions (QueryMentions, QueryMentionsIter)
748
+ * Return a list of SDG uris. Note: SDGs can only be used when querying mentions (QueryMentions, QueryMentionsIter)
697
749
  */
698
750
  async getSdgUris() {
699
751
  const request = await this.jsonRequest("/api/v1/eventType/sdg/getItems");
@@ -838,7 +890,7 @@ class EventRegistry {
838
890
  return request.data;
839
891
  }
840
892
  /**
841
- * Return information about the latest imported article
893
+ * Return the list of source groups
842
894
  */
843
895
  async getSourceGroups() {
844
896
  const request = await this.jsonRequest("/api/v1/sourceGroup/getSourceGroups", { action: "getSourceGroups" });
@@ -860,7 +912,7 @@ exports.EventRegistry = EventRegistry;
860
912
  */
861
913
  class ArticleMapper {
862
914
  constructor(er, rememberMapping = true) {
863
- this.articleUrlToUri = {};
915
+ this.articleUrlToUri = new Map();
864
916
  this.rememberMappings = true;
865
917
  this.er = er;
866
918
  this.rememberMappings = rememberMapping;
@@ -872,13 +924,13 @@ class ArticleMapper {
872
924
  * @param articleUrl string containing the article url
873
925
  */
874
926
  async getArticleUri(articleUrl) {
875
- if (this.articleUrlToUri.hasOwnProperty(articleUrl)) {
876
- return this.articleUrlToUri[articleUrl];
927
+ if (this.articleUrlToUri.has(articleUrl)) {
928
+ return this.articleUrlToUri.get(articleUrl);
877
929
  }
878
930
  const response = await this.er.getArticleUris(articleUrl);
879
931
  const value = response?.[articleUrl];
880
932
  if (this.rememberMappings && value) {
881
- this.articleUrlToUri = { ...this.articleUrlToUri, [articleUrl]: value };
933
+ this.articleUrlToUri.set(articleUrl, value);
882
934
  }
883
935
  return value;
884
936
  }