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
@@ -57,9 +57,9 @@ export class QueryEvents extends Query<RequestEvents> {
57
57
  this.setQueryArrVal(keywords, "keyword", "keywordOper", "and");
58
58
  this.setQueryArrVal(conceptUri, "conceptUri", "conceptOper", "and");
59
59
  this.setQueryArrVal(categoryUri, "categoryUri", "categoryOper", "or");
60
- this.setQueryArrVal(sourceUri, "sourceUri", undefined, "or");
60
+ this.setQueryArrVal(sourceUri, "sourceUri", "sourceOper", "or");
61
61
  this.setQueryArrVal(sourceLocationUri, "sourceLocationUri", undefined, "or");
62
- this.setQueryArrVal(sourceGroupUri, "sourceGroupUri", undefined, "or");
62
+ this.setQueryArrVal(sourceGroupUri, "sourceGroupUri", "sourceGroupOper", "or");
63
63
  this.setQueryArrVal(authorUri, "authorUri", "authorOper", "or");
64
64
  this.setQueryArrVal(locationUri, "locationUri", undefined, "or");
65
65
  this.setQueryArrVal(lang, "lang", undefined, "or");
@@ -95,7 +95,7 @@ export class QueryEvents extends Query<RequestEvents> {
95
95
  }
96
96
 
97
97
  // for the negative conditions, only the OR is a valid operator type
98
- this.setQueryArrVal(ignoreKeywords, "ignoreKeywords", undefined, "or");
98
+ this.setQueryArrVal(ignoreKeywords, "ignoreKeyword", undefined, "or");
99
99
  this.setQueryArrVal(ignoreConceptUri, "ignoreConceptUri", undefined, "or");
100
100
  this.setQueryArrVal(ignoreCategoryUri, "ignoreCategoryUri", undefined, "or");
101
101
  this.setQueryArrVal(ignoreSourceUri, "ignoreSourceUri", undefined, "or");
@@ -191,16 +191,17 @@ export class QueryEventsIter extends QueryEvents implements AsyncIterable<Data.E
191
191
  private readonly engine: QueryIterationEngine<Data.Event>;
192
192
 
193
193
  constructor(er: EventRegistry, args: ER.QueryEvents.IteratorArguments = {}) {
194
- super(args as ER.QueryEvents.Arguments);
194
+ super(args);
195
195
  const {
196
196
  sortBy = "rel",
197
197
  sortByAsc = false,
198
198
  returnInfo = undefined,
199
199
  maxItems = -1
200
200
  } = args;
201
- this.er = er;
201
+ this.er = args.signal || args.timeoutMs ? er.withOptions({ signal: args.signal, timeoutMs: args.timeoutMs }) : er;
202
202
  this.engine = new QueryIterationEngine<Data.Event>({
203
203
  maxItems,
204
+ signal: args.signal,
204
205
  entityLabel: "events",
205
206
  onError: (message) => this.er.logger.error(message),
206
207
  fetchPage: async (page) => {
@@ -312,7 +313,7 @@ export class RequestEventsUriWgtList extends RequestEvents {
312
313
  ...unsupported
313
314
  } = args;
314
315
  if (Object.keys(unsupported).length !== 0) {
315
- Logger.warn(`RequestEventsUriWgtList: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
316
+ Logger.warnUnsupported("RequestEventsUriWgtList", unsupported);
316
317
  }
317
318
  if (page < 1) {
318
319
  throw new RangeError("Page has to be >= 1");
@@ -377,7 +378,7 @@ export class RequestEventsLocAggr extends RequestEvents {
377
378
  ...unsupported
378
379
  } = args;
379
380
  if (Object.keys(unsupported).length !== 0) {
380
- Logger.warn(`RequestEventsLocAggr: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
381
+ Logger.warnUnsupported("RequestEventsLocAggr", unsupported);
381
382
  }
382
383
  if (eventsSampleSize > 100000) {
383
384
  throw new RangeError("At most 100000 results can be used for computing");
@@ -403,7 +404,7 @@ export class RequestEventsLocTimeAggr extends RequestEvents {
403
404
  ...unsupported
404
405
  } = args;
405
406
  if (Object.keys(unsupported).length !== 0) {
406
- Logger.warn(`RequestEventsLocTimeAggr: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
407
+ Logger.warnUnsupported("RequestEventsLocTimeAggr", unsupported);
407
408
  }
408
409
  if (eventsSampleSize > 100000) {
409
410
  throw new RangeError("At most 100000 results can be used for computing");
@@ -1,3 +1,5 @@
1
+ import { isCancellation } from "./abort";
2
+
1
3
  /**
2
4
  * Shared pagination engine backing QueryArticlesIter and QueryEventsIter.
3
5
  * Each caller supplies a `fetchPage` closure that knows how to build/execute
@@ -11,6 +13,8 @@ export interface PageFetchResult<TItem> {
11
13
  }
12
14
 
13
15
  export interface QueryIterationEngineOptions<TItem> {
16
+ /** Caller's abort signal: once aborted no further page is requested and iteration rejects. */
17
+ signal?: AbortSignal;
14
18
  maxItems: number;
15
19
  entityLabel: string;
16
20
  fetchPage: (page: number) => Promise<PageFetchResult<TItem>>;
@@ -32,6 +36,7 @@ export class QueryIterationEngine<TItem> implements AsyncIterable<TItem> {
32
36
  public [Symbol.asyncIterator](): AsyncIterator<TItem> {
33
37
  return {
34
38
  next: async () => {
39
+ this.options.signal?.throwIfAborted();
35
40
  if (this.index >= this.items.length) {
36
41
  await this.getNextBatch();
37
42
  }
@@ -45,7 +50,7 @@ export class QueryIterationEngine<TItem> implements AsyncIterable<TItem> {
45
50
  public execQuery(callback: (item: TItem) => void, doneCallback?: (error?: string) => void): void {
46
51
  if (callback) { this.callback = callback; }
47
52
  if (doneCallback) { this.doneCallback = doneCallback; }
48
- this.iterate();
53
+ this.iterate().catch((error: unknown) => this.doneCallback(error instanceof Error ? error.message : String(error)));
49
54
  }
50
55
 
51
56
  private get current(): TItem | undefined {
@@ -53,14 +58,15 @@ export class QueryIterationEngine<TItem> implements AsyncIterable<TItem> {
53
58
  }
54
59
 
55
60
  private async iterate(): Promise<void> {
56
- if (this.current) {
57
- this.callback(this.current);
58
- this.index += 1;
59
- } else if (!await this.getNextBatch()) {
60
- this.doneCallback(this.errorMessage);
61
- return;
61
+ for (;;) {
62
+ if (this.current) {
63
+ this.callback(this.current);
64
+ this.index += 1;
65
+ } else if (!await this.getNextBatch()) {
66
+ this.doneCallback(this.errorMessage);
67
+ return;
68
+ }
62
69
  }
63
- return this.iterate();
64
70
  }
65
71
 
66
72
  public async getNextBatch(): Promise<boolean> {
@@ -79,9 +85,14 @@ export class QueryIterationEngine<TItem> implements AsyncIterable<TItem> {
79
85
  const extractedSize = maxItems !== -1 ? maxItems - this.returnedSoFar : results.length;
80
86
  const extracted = results.slice(0, extractedSize).filter(Boolean);
81
87
  this.returnedSoFar += extracted.length;
82
- this.items = [...this.items, ...extracted];
88
+ // Only the current page is buffered, so consumed items can be garbage collected.
89
+ this.items = extracted;
90
+ this.index = 0;
83
91
  return true;
84
92
  } catch (err) {
93
+ if (isCancellation(err, this.options.signal)) {
94
+ throw err;
95
+ }
85
96
  onError(err instanceof Error ? err.message : String(err));
86
97
  return false;
87
98
  }
@@ -1,3 +1,4 @@
1
+ import { isCancellation } from "./abort";
1
2
  import { Query, QueryParamsBase } from "./base";
2
3
  import { EventRegistry } from "./eventRegistry";
3
4
  import { ReturnInfo } from "./returnInfo";
@@ -44,7 +45,7 @@ export class QueryMentions extends Query<RequestMentions> {
44
45
  maxSentiment = 1,
45
46
  minSentenceIndex,
46
47
  maxSentenceIndex,
47
- requestedResult = new RequestMentions()
48
+ requestedResult = new RequestMentionsInfo()
48
49
  } = args;
49
50
 
50
51
  this.setVal("action", "getMentions");
@@ -52,9 +53,9 @@ export class QueryMentions extends Query<RequestMentions> {
52
53
  this.setQueryArrVal(keywords, "keyword", "keywordOper", "and");
53
54
  this.setQueryArrVal(conceptUri, "conceptUri", "conceptOper", "and");
54
55
  this.setQueryArrVal(categoryUri, "categoryUri", "categoryOper", "or");
55
- this.setQueryArrVal(sourceUri, "sourceUri", undefined, "or");
56
+ this.setQueryArrVal(sourceUri, "sourceUri", "sourceOper", "or");
56
57
  this.setQueryArrVal(sourceLocationUri, "sourceLocationUri", undefined, "or");
57
- this.setQueryArrVal(sourceGroupUri, "sourceGroupUri", undefined, "or");
58
+ this.setQueryArrVal(sourceGroupUri, "sourceGroupUri", "sourceGroupOper", "or");
58
59
  this.setQueryArrVal(industryUri, "industryUri", "industryOper", "or");
59
60
  this.setQueryArrVal(sdgUri, "sdgUri", undefined, "or");
60
61
  this.setQueryArrVal(sasbUri, "sasbUri", undefined, "or");
@@ -69,7 +70,7 @@ export class QueryMentions extends Query<RequestMentions> {
69
70
  }
70
71
 
71
72
  this.setQueryArrVal(ignoreEventTypeUri, "ignoreEventTypeUri", undefined, "or");
72
- this.setQueryArrVal(ignoreKeywords, "ignoreKeywords", undefined, "or");
73
+ this.setQueryArrVal(ignoreKeywords, "ignoreKeyword", undefined, "or");
73
74
  this.setQueryArrVal(ignoreConceptUri, "ignoreConceptUri", undefined, "or");
74
75
  this.setQueryArrVal(ignoreCategoryUri, "ignoreCategoryUri", undefined, "or");
75
76
  this.setQueryArrVal(ignoreSourceUri, "ignoreSourceUri", undefined, "or");
@@ -172,6 +173,7 @@ export class QueryMentions extends Query<RequestMentions> {
172
173
 
173
174
  export class QueryMentionsIter extends QueryMentions implements AsyncIterable<Record<string, unknown>> {
174
175
  private readonly er: EventRegistry;
176
+ private readonly signal?: AbortSignal;
175
177
  private readonly sortBy: "date" | "socialScore" | "none" | "rel" | "size";
176
178
  private readonly sortByAsc: boolean;
177
179
  private readonly returnInfo: ReturnInfo | undefined;
@@ -186,14 +188,15 @@ export class QueryMentionsIter extends QueryMentions implements AsyncIterable<Re
186
188
  private errorMessage!: string;
187
189
 
188
190
  constructor(er: EventRegistry, args: ER.QueryMentions.IteratorArguments = {}) {
189
- super(args as ER.QueryMentions.Arguments);
191
+ super(args);
190
192
  const {
191
193
  sortBy = "rel",
192
194
  sortByAsc = false,
193
195
  returnInfo = undefined,
194
196
  maxItems = -1
195
197
  } = args;
196
- this.er = er;
198
+ this.er = args.signal || args.timeoutMs ? er.withOptions({ signal: args.signal, timeoutMs: args.timeoutMs }) : er;
199
+ this.signal = args.signal;
197
200
  this.sortBy = sortBy;
198
201
  this.sortByAsc = sortByAsc;
199
202
  this.returnInfo = returnInfo;
@@ -203,6 +206,7 @@ export class QueryMentionsIter extends QueryMentions implements AsyncIterable<Re
203
206
  [Symbol.asyncIterator](): AsyncIterator<Record<string, unknown>> {
204
207
  return {
205
208
  next: async () => {
209
+ this.signal?.throwIfAborted();
206
210
  if (this.index >= this.items.length) {
207
211
  await this.getNextBatch();
208
212
  }
@@ -230,7 +234,7 @@ export class QueryMentionsIter extends QueryMentions implements AsyncIterable<Re
230
234
  public execQuery(callback: (item: Record<string, unknown>) => void, doneCallback?: (error?: string) => void) {
231
235
  if (callback) { this.callback = callback; }
232
236
  if (doneCallback) { this.doneCallback = doneCallback; }
233
- this.iterate();
237
+ this.iterate().catch((error: unknown) => this.doneCallback(error instanceof Error ? error.message : String(error)));
234
238
  }
235
239
 
236
240
  public static initWithComplexQuery(er: EventRegistry, complexQuery: string | Record<string, unknown>, args: ER.QueryMentions.IteratorArguments = {}) {
@@ -299,6 +303,9 @@ export class QueryMentionsIter extends QueryMentions implements AsyncIterable<Re
299
303
  this.items = [...this.items, ...results];
300
304
  return true;
301
305
  } catch (error) {
306
+ if (isCancellation(error, this.signal)) {
307
+ throw error;
308
+ }
302
309
  this.er.logger.error(error instanceof Error ? error.message : String(error));
303
310
  return false;
304
311
  }
@@ -357,7 +364,7 @@ export class RequestMentionsUriWgtList extends RequestMentions {
357
364
  ...unsupported
358
365
  } = args;
359
366
  if (Object.keys(unsupported).length !== 0) {
360
- Logger.warn(`RequestMentionsUriWgtList: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
367
+ Logger.warnUnsupported("RequestMentionsUriWgtList", unsupported);
361
368
  }
362
369
  if (page < 1) {
363
370
  throw new RangeError("Page has to be >= 1");
@@ -391,7 +398,7 @@ export class RequestMentionsConceptAggr extends RequestMentions {
391
398
  super();
392
399
  const {
393
400
  conceptCount = 25,
394
- mentionsSampleSize = 100000,
401
+ mentionsSampleSize = 20000,
395
402
  conceptScoring = "importance",
396
403
  conceptCountPerType = undefined,
397
404
  returnInfo = new ReturnInfo()
package/src/queryStory.ts CHANGED
@@ -54,7 +54,7 @@ export class RequestStoryArticles extends RequestStory {
54
54
  } = {}) {
55
55
  super();
56
56
  if (Object.keys(unsupported).length > 0) {
57
- Logger.warn(`RequestStoryArticles: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
57
+ Logger.warnUnsupported("RequestStoryArticles", unsupported);
58
58
  }
59
59
  if (page < 1) {
60
60
  throw new RangeError("Page has to be >= 1");
@@ -81,7 +81,7 @@ export class RequestStoryArticleUris extends RequestStory {
81
81
  } = {}) {
82
82
  super();
83
83
  if (Object.keys(unsupported).length > 0) {
84
- Logger.warn(`RequestStoryArticleUris: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
84
+ Logger.warnUnsupported("RequestStoryArticleUris", unsupported);
85
85
  }
86
86
  this.params = {};
87
87
  this.params["articleUrisSortBy"] = sortBy;
@@ -100,7 +100,7 @@ export class RequestStoryArticleTrend extends RequestStory {
100
100
  } = {}) {
101
101
  super();
102
102
  if (Object.keys(unsupported).length > 0) {
103
- Logger.warn(`RequestStoryArticleTrend: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
103
+ Logger.warnUnsupported("RequestStoryArticleTrend", unsupported);
104
104
  }
105
105
  this.params = {};
106
106
  this.params["articleTrendLang"] = lang;
@@ -120,10 +120,17 @@ export class RequestStorySimilarStories extends RequestStory {
120
120
  lang = [],
121
121
  returnInfo = new ReturnInfo(),
122
122
  ...unsupported
123
+ }: {
124
+ conceptInfoList?: { uri: string; wgt: number }[];
125
+ count?: number;
126
+ dateStart?: string | Date;
127
+ dateEnd?: string | Date;
128
+ lang?: string | string[];
129
+ returnInfo?: ReturnInfo;
123
130
  } = {}) {
124
131
  super();
125
132
  if (Object.keys(unsupported).length > 0) {
126
- Logger.warn(`RequestStorySimilarStories: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
133
+ Logger.warnUnsupported("RequestStorySimilarStories", unsupported);
127
134
  }
128
135
  if (count > 50) {
129
136
  throw new RangeError("At most 50 stories can be returned per call");
package/src/recent.ts CHANGED
@@ -2,12 +2,16 @@ import { QueryParamsBase } from "./base";
2
2
  import { EventRegistry } from "./eventRegistry";
3
3
  import { ReturnInfo } from "./returnInfo";
4
4
 
5
+ /** Position in the minute stream: the newest uri per stream key, as returned by the API (`newestUri`). */
6
+ export type RecentCursor = Record<string, string>;
7
+
5
8
  export class GetRecentEvents extends QueryParamsBase {
6
9
  private er: EventRegistry;
10
+ private cursor: RecentCursor = {};
7
11
  constructor(er: EventRegistry, { mandatoryLang = undefined,
8
12
  mandatoryLocation = true,
9
13
  returnInfo = new ReturnInfo()
10
- } = {}) {
14
+ }: { mandatoryLang?: string | string[]; mandatoryLocation?: boolean; returnInfo?: ReturnInfo } = {}) {
11
15
  super();
12
16
  this.er = er;
13
17
  this.setVal("recentActivityEventsMandatoryLocation", mandatoryLocation);
@@ -29,22 +33,33 @@ export class GetRecentEvents extends QueryParamsBase {
29
33
  }
30
34
  const newestUri = payload.newestUri;
31
35
  if (newestUri && typeof newestUri === "object") {
32
- for (const [key, value] of Object.entries(newestUri as Record<string, string>)) {
33
- const splitKey = key.split("");
34
- this.setVal("recentActivityEvents" + splitKey[0].toUpperCase() + splitKey.slice(1).join(""), value);
35
- }
36
+ this.setCursor(newestUri as RecentCursor);
36
37
  }
37
38
  return Array.isArray(payload.activity) ? payload.activity : [];
38
39
  }
40
+
41
+ /** The position reached by the last `getUpdates()`; persist it to resume after a restart. */
42
+ public getCursor(): RecentCursor {
43
+ return { ...this.cursor };
44
+ }
45
+
46
+ /** Continue after a position returned earlier by `getCursor()`. */
47
+ public setCursor(cursor: RecentCursor): void {
48
+ this.cursor = { ...cursor };
49
+ for (const [key, value] of Object.entries(cursor)) {
50
+ this.setVal("recentActivityEvents" + key.charAt(0).toUpperCase() + key.slice(1), value);
51
+ }
52
+ }
39
53
  }
40
54
 
41
55
  export class GetRecentArticles extends QueryParamsBase {
42
56
  private er: EventRegistry;
57
+ private cursor: RecentCursor = {};
43
58
  constructor(er: EventRegistry, { mandatorySourceLocation = undefined,
44
59
  lang = undefined,
45
60
  returnInfo = new ReturnInfo(),
46
61
  ...kwargs
47
- } = {}) {
62
+ }: { mandatorySourceLocation?: boolean; lang?: string | string[]; returnInfo?: ReturnInfo } = {}) {
48
63
  super();
49
64
  this.er = er;
50
65
  this.setVal("recentActivityArticlesMandatorySourceLocation", mandatorySourceLocation);
@@ -62,12 +77,22 @@ export class GetRecentArticles extends QueryParamsBase {
62
77
  public async getUpdates() {
63
78
  const response = await this.er.execQuery(this);
64
79
  if (response?.recentActivityArticles) {
65
- for (const [key, value] of Object.entries((response.recentActivityArticles as unknown as Record<string, string>).newestUri || {})) {
66
- const splitKey = key.split("");
67
- this.setVal("recentActivityArticles" + splitKey[0].toUpperCase() + splitKey.slice(1).join(""), value);
68
- }
80
+ this.setCursor((response.recentActivityArticles as unknown as Record<string, RecentCursor>).newestUri || {});
69
81
  return (response.recentActivityArticles as unknown as Record<string, unknown[]>).activity || [];
70
82
  }
71
83
  return [];
72
84
  }
85
+
86
+ /** The position reached by the last `getUpdates()`; persist it to resume after a restart. */
87
+ public getCursor(): RecentCursor {
88
+ return { ...this.cursor };
89
+ }
90
+
91
+ /** Continue after a position returned earlier by `getCursor()`. */
92
+ public setCursor(cursor: RecentCursor): void {
93
+ this.cursor = { ...cursor };
94
+ for (const [key, value] of Object.entries(cursor)) {
95
+ this.setVal("recentActivityArticles" + key.charAt(0).toUpperCase() + key.slice(1), value);
96
+ }
97
+ }
73
98
  }
@@ -0,0 +1,91 @@
1
+ import { abortableSleep, composeSignal } from "./abort";
2
+ import { EventRegistry } from "./eventRegistry";
3
+ import { GetRecentArticles, GetRecentEvents, RecentCursor } from "./recent";
4
+ import { ER } from "./types";
5
+
6
+ /** Options of a recent-activity feed on top of the `GetRecentArticles` / `GetRecentEvents` arguments. */
7
+ export interface RecentFeedOptions extends ER.RequestOptions {
8
+ /** Wait between polls in milliseconds. The API refreshes about once a minute. Default 60000. */
9
+ pollMs?: number;
10
+ /** Resume after a position saved from `onCursor`. Without it the feed starts at the API's current position. */
11
+ cursor?: RecentCursor;
12
+ /** Called with the new position after each poll that moved it. Awaited, so a slow store applies backpressure. */
13
+ onCursor?: (cursor: RecentCursor) => void | Promise<void>;
14
+ }
15
+
16
+ type RecentSource = Pick<GetRecentArticles, "getUpdates" | "getCursor" | "setCursor">;
17
+
18
+ /**
19
+ * Both a one-shot poll and an endless feed over one `GetRecent*` query:
20
+ * `await feed` does a single `getUpdates()` (the 10.0.0 behaviour), `for await (const item of feed)` polls forever.
21
+ * Nothing is requested until one of the two is used. Cancel a feed with `signal`; the loop then throws the abort reason.
22
+ */
23
+ export class RecentFeed<T = unknown> implements Promise<T[]>, AsyncIterable<T> {
24
+ public readonly [Symbol.toStringTag] = "RecentFeed";
25
+ private readonly options: RecentFeedOptions;
26
+ private once?: Promise<T[]>;
27
+
28
+ constructor(private readonly er: EventRegistry, private readonly create: (er: EventRegistry) => RecentSource, options: RecentFeedOptions = {}) {
29
+ this.options = options;
30
+ }
31
+
32
+ private source(): RecentSource {
33
+ const { signal, timeoutMs, cursor } = this.options;
34
+ const source = this.create(signal || timeoutMs ? this.er.withOptions({ signal, timeoutMs }) : this.er);
35
+ if (cursor) {
36
+ source.setCursor(cursor);
37
+ }
38
+ return source;
39
+ }
40
+
41
+ private poll(): Promise<T[]> {
42
+ this.once ??= this.source().getUpdates() as Promise<T[]>;
43
+ return this.once;
44
+ }
45
+
46
+ public then<R1 = T[], R2 = never>(onfulfilled?: ((value: T[]) => R1 | PromiseLike<R1>) | null, onrejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2> {
47
+ return this.poll().then(onfulfilled, onrejected);
48
+ }
49
+
50
+ public catch<R = never>(onrejected?: ((reason: unknown) => R | PromiseLike<R>) | null): Promise<T[] | R> {
51
+ return this.poll().catch(onrejected);
52
+ }
53
+
54
+ public finally(onfinally?: (() => void) | null): Promise<T[]> {
55
+ return this.poll().finally(onfinally);
56
+ }
57
+
58
+ public async *[Symbol.asyncIterator](): AsyncIterator<T> {
59
+ const { pollMs = 60_000, signal, onCursor } = this.options;
60
+ const source = this.source();
61
+ let last = JSON.stringify(source.getCursor());
62
+ for (;;) {
63
+ const items = (await source.getUpdates()) as T[];
64
+ const cursor = source.getCursor();
65
+ const serialized = JSON.stringify(cursor);
66
+ if (serialized !== last) {
67
+ last = serialized;
68
+ await onCursor?.(cursor);
69
+ }
70
+ for (const item of items) {
71
+ yield item;
72
+ }
73
+ const { signal: sleepSignal, dispose } = composeSignal([signal]);
74
+ try {
75
+ await abortableSleep(pollMs, sleepSignal);
76
+ } finally {
77
+ dispose();
78
+ }
79
+ }
80
+ }
81
+ }
82
+
83
+ export function recentArticlesFeed<T = unknown>(er: EventRegistry, args: ConstructorParameters<typeof GetRecentArticles>[1] & RecentFeedOptions = {}): RecentFeed<T> {
84
+ const { pollMs, cursor, onCursor, signal, timeoutMs, ...rest } = args;
85
+ return new RecentFeed<T>(er, (client) => new GetRecentArticles(client, rest), { pollMs, cursor, onCursor, signal, timeoutMs });
86
+ }
87
+
88
+ export function recentEventsFeed<T = unknown>(er: EventRegistry, args: ConstructorParameters<typeof GetRecentEvents>[1] & RecentFeedOptions = {}): RecentFeed<T> {
89
+ const { pollMs, cursor, onCursor, signal, timeoutMs, ...rest } = args;
90
+ return new RecentFeed<T>(er, (client) => new GetRecentEvents(client, rest), { pollMs, cursor, onCursor, signal, timeoutMs });
91
+ }
package/src/returnInfo.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { ER } from "./types";
2
- import * as fs from "fs";
2
+ import * as fs from "node:fs";
3
3
  import { Logger } from "./logger";
4
4
 
5
5
  export abstract class ReturnInfoFlagsBase {
@@ -82,7 +82,7 @@ export class ReturnInfo {
82
82
  ...unsupported
83
83
  } = {}) {
84
84
  if (Object.keys(unsupported).length > 0) {
85
- Logger.warn(`ReturnInfo: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`);
85
+ Logger.warnUnsupported("ReturnInfo", unsupported);
86
86
  }
87
87
  this.articleInfo = articleInfo;
88
88
  this.eventInfo = eventInfo;
package/src/topicPage.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as fs from "fs";
1
+ import * as fs from "node:fs";
2
2
  import { QueryParamsBase } from "./base";
3
3
  import { EventRegistry } from "./eventRegistry";
4
4
  import { ReturnInfo } from "./returnInfo";
@@ -37,11 +37,15 @@ export class TopicPage extends QueryParamsBase {
37
37
  }
38
38
 
39
39
  private isTopicPage(definition: object): definition is ER.TopicPage {
40
- return Object.keys(this.emptyTopicPage).sort().toString() === Object.keys(definition).sort().toString();
40
+ const required = Object.keys(this.emptyTopicPage);
41
+ const allowed = new Set([...required, "startSourceRankPercentile", "endSourceRankPercentile"]);
42
+ const keys = Object.keys(definition);
43
+ return required.every((key) => keys.includes(key)) && keys.every((key) => allowed.has(key));
41
44
  }
42
45
 
46
+ // A fresh copy each time: setters and add* methods mutate this.topicPage in place.
43
47
  private createEmptyTopicPage(): ER.TopicPage {
44
- return this.emptyTopicPage;
48
+ return structuredClone(this.emptyTopicPage);
45
49
  }
46
50
 
47
51
  /**
package/src/types.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  /* eslint-disable @typescript-eslint/no-shadow, @typescript-eslint/no-unused-vars */
2
2
  import { QueryItems } from "./base";
3
+ import { ErApiError } from "./errors";
3
4
  import { BaseQuery, CombinedQuery} from "./query";
4
5
  import { QueryArticles, RequestArticles } from "./queryArticles";
5
6
  import { RequestEvents } from "./queryEvents";
@@ -24,6 +25,8 @@ export namespace ER {
24
25
 
25
26
  export interface ErrorResponse<E = string> {
26
27
  error?: E;
28
+ /** Set next to `error` when the API answered with an HTTP error status: status, API code, request id and token cost. */
29
+ apiError?: ErApiError;
27
30
  }
28
31
 
29
32
  export interface Results<T = unknown> {
@@ -45,7 +48,37 @@ export namespace ER {
45
48
  [name: string]: any;
46
49
  }
47
50
 
48
- export interface Config {
51
+ /** Per-call cancellation and deadline, accepted wherever a request is made. */
52
+ export interface RequestOptions {
53
+ /** Aborts the call: waiting in the queue, the HTTP request and backoff waits all stop. */
54
+ signal?: AbortSignal;
55
+ /**
56
+ * Overall deadline in milliseconds for the call, queueing, retries and backoff waits included.
57
+ * Exceeding it rejects with `ErTimeoutError`.
58
+ */
59
+ timeoutMs?: number;
60
+ }
61
+
62
+ export interface Config extends RequestOptions {
63
+ /**
64
+ * Check every `execQuery` response against the documented top-level shapes and throw `ErValidationError`
65
+ * when one does not match (a missing results array, a result without a uri, a non-numeric counter, ...).
66
+ * Off by default; extra fields never fail validation. Meant for tests and for pipelines that must not
67
+ * continue on malformed data.
68
+ */
69
+ validate?: boolean;
70
+ /**
71
+ * Throw when a call fails instead of resolving to `{ error }`. HTTP failures throw `ErApiError`, other failures a plain `Error`.
72
+ * Off by default so existing `if (response.error)` checks keep working.
73
+ * @default false
74
+ */
75
+ throwOnError?: boolean;
76
+ /**
77
+ * Token budget for this client. Once the tokens reported by the API since construction (or `usage.reset()`)
78
+ * plus the last reported cost of the same endpoint would exceed it, calls throw `ErBudgetExceededError`
79
+ * before any request is sent. The cost of a call is only known afterwards, so the guard can overshoot by one call.
80
+ */
81
+ maxTokens?: number;
49
82
  /**
50
83
  * API key that should be used to make the requests to the Event Registry.
51
84
  * API key is assigned to each user account and can be obtained on this page:
@@ -74,9 +107,21 @@ export namespace ER {
74
107
  /**
75
108
  * If a request fails (for example, because ER is down),
76
109
  * what is the max number of times the request should be repeated.
77
- * @default -1
110
+ * Use -1 to retry indefinitely.
111
+ * @default 5
78
112
  */
79
113
  repeatFailedRequestCount?: number;
114
+ /**
115
+ * Base of the exponential backoff between retries, in milliseconds. Attempt n waits about
116
+ * `retryDelayMs * 2^n` (with jitter), capped at `maxRetryDelayMs`.
117
+ * @default 5000
118
+ */
119
+ retryDelayMs?: number;
120
+ /**
121
+ * Upper bound for a single wait between retries, in milliseconds (also caps a `Retry-After` header).
122
+ * @default 30000
123
+ */
124
+ maxRetryDelayMs?: number;
80
125
  /**
81
126
  * If true, additional info about errors etc. will be printed to console.
82
127
  */
@@ -228,6 +273,18 @@ export namespace ER {
228
273
  returnInfo?: ReturnInfo;
229
274
  }
230
275
 
276
+ export interface SuggestPagedArguments {
277
+ /** page of the results (1, 2, ...) */
278
+ page?: number;
279
+ /** number of returned suggestions */
280
+ count?: number;
281
+ }
282
+
283
+ export interface SuggestSourcesAtCoordinateArguments {
284
+ /** number of returned suggestions */
285
+ count?: number;
286
+ }
287
+
231
288
  export interface SuggestSourcesAtPlaceArguments {
232
289
  /**
233
290
  * page of the results (1, 2, ...)
@@ -970,7 +1027,7 @@ export namespace ER {
970
1027
  * - "keepOnlyHasDuplicates" (return only the articles that have been later copied by others)
971
1028
  * - "keepAll" (no filtering, default)
972
1029
  */
973
- hasDuplicateFilter?: "skipDuplicates" | "keepOnlyDuplicates" | "keepAll";
1030
+ hasDuplicateFilter?: "skipHasDuplicates" | "keepOnlyHasDuplicates" | "keepAll";
974
1031
  /**
975
1032
  * Some articles describe a known event and some don't. This filter allows you to filter the resulting articles based on this criteria.
976
1033
  * Possible values are:
@@ -1071,7 +1128,9 @@ export namespace ER {
1071
1128
  export interface RequestArticlesRecentActivityParameters {
1072
1129
  maxArticleCount?: number;
1073
1130
  updatesAfterNewsUri?: string;
1131
+ /** Python-style name; `updatesAfterBlogUri` is an alias and wins when both are set. */
1074
1132
  updatesafterBlogUri?: string;
1133
+ updatesAfterBlogUri?: string;
1075
1134
  updatesAfterPrUri?: string;
1076
1135
  updatesAfterTm?: string | Date;
1077
1136
  updatesAfterMinsAgo?: number;
@@ -1286,7 +1345,7 @@ export namespace ER {
1286
1345
  */
1287
1346
  requestedResult?: RequestArticles;
1288
1347
  }
1289
- export interface IteratorArguments extends Arguments {
1348
+ export interface IteratorArguments extends Arguments, RequestOptions {
1290
1349
  /**
1291
1350
  * how should the resulting articles be sorted. Options: "rel" (relevance), "date" (published date), "sourceImportance", "sourceImportanceRank", "sourceAlexaGlobalRank", "sourceAlexaCountryRank", "socialScore", "facebookShares"
1292
1351
  */
@@ -1323,7 +1382,7 @@ export namespace ER {
1323
1382
  export type SortByOptions = "id" | "date" | "cosSim" | "sourceImportance" | "sourceImportanceRank" | "sourceAlexaGlobalRank" | "sourceAlexaCountryRank" | "socialScore" | "facebookShares";
1324
1383
 
1325
1384
  export type RequestEvent = Record<string, never>;
1326
- export interface IteratorArguments {
1385
+ export interface IteratorArguments extends RequestOptions {
1327
1386
  /**
1328
1387
  * Array or a single language in which to return the list of matching articles
1329
1388
  */
@@ -1544,7 +1603,7 @@ export namespace ER {
1544
1603
  maxSentenceIndex?: number;
1545
1604
  requestedResult?: RequestMentions;
1546
1605
  }
1547
- export interface IteratorArguments extends Arguments {
1606
+ export interface IteratorArguments extends Arguments, RequestOptions {
1548
1607
  /**
1549
1608
  * how should the resulting mentions be sorted. Options: "none", "rel" (relevance), "date" (published date), "size", "socialScore"
1550
1609
  */
@@ -1862,7 +1921,7 @@ export namespace ER {
1862
1921
  */
1863
1922
  requestedResult?: RequestEvents;
1864
1923
  }
1865
- export interface IteratorArguments extends Arguments {
1924
+ export interface IteratorArguments extends Arguments, RequestOptions {
1866
1925
  /**
1867
1926
  * how should the resulting events be sorted. Options:
1868
1927
  * - none (no specific sorting),