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.
- package/AGENT-RECIPES.md +86 -0
- package/CHANGELOG.md +47 -0
- package/MIGRATION.md +22 -4
- package/README.md +49 -1
- package/dist/cjs/abort.d.ts +14 -0
- package/dist/cjs/abort.js +71 -0
- package/dist/cjs/abort.js.map +1 -0
- package/dist/cjs/base.js +8 -2
- package/dist/cjs/base.js.map +1 -1
- package/dist/cjs/errors.d.ts +66 -0
- package/dist/cjs/errors.js +75 -0
- package/dist/cjs/errors.js.map +1 -0
- package/dist/cjs/eventRegistry.d.ts +47 -15
- package/dist/cjs/eventRegistry.js +237 -185
- package/dist/cjs/eventRegistry.js.map +1 -1
- package/dist/cjs/fluent/recent.d.ts +7 -2
- package/dist/cjs/fluent/recent.js +7 -3
- package/dist/cjs/fluent/recent.js.map +1 -1
- package/dist/cjs/guards.d.ts +12 -0
- package/dist/cjs/guards.js +75 -0
- package/dist/cjs/guards.js.map +1 -0
- package/dist/cjs/http.d.ts +5 -0
- package/dist/cjs/http.js +64 -11
- package/dist/cjs/http.js.map +1 -1
- package/dist/cjs/index.d.ts +7 -0
- package/dist/cjs/index.js +17 -4
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/logger.d.ts +2 -0
- package/dist/cjs/logger.js +6 -2
- package/dist/cjs/logger.js.map +1 -1
- package/dist/cjs/mutex.d.ts +2 -1
- package/dist/cjs/mutex.js +19 -2
- package/dist/cjs/mutex.js.map +1 -1
- package/dist/cjs/query.js +4 -4
- package/dist/cjs/query.js.map +1 -1
- package/dist/cjs/queryArticle.js +3 -2
- package/dist/cjs/queryArticle.js.map +1 -1
- package/dist/cjs/queryArticles.d.ts +6 -6
- package/dist/cjs/queryArticles.js +19 -18
- package/dist/cjs/queryArticles.js.map +1 -1
- package/dist/cjs/queryEvent.d.ts +1 -0
- package/dist/cjs/queryEvent.js +11 -5
- package/dist/cjs/queryEvent.js.map +1 -1
- package/dist/cjs/queryEvents.js +8 -7
- package/dist/cjs/queryEvents.js.map +1 -1
- package/dist/cjs/queryIterator.d.ts +2 -0
- package/dist/cjs/queryIterator.js +18 -10
- package/dist/cjs/queryIterator.js.map +1 -1
- package/dist/cjs/queryMentions.d.ts +1 -0
- package/dist/cjs/queryMentions.js +14 -8
- package/dist/cjs/queryMentions.js.map +1 -1
- package/dist/cjs/queryStory.d.ts +9 -6
- package/dist/cjs/queryStory.js +4 -4
- package/dist/cjs/queryStory.js.map +1 -1
- package/dist/cjs/recent.d.ts +18 -6
- package/dist/cjs/recent.js +26 -8
- package/dist/cjs/recent.js.map +1 -1
- package/dist/cjs/recentFeed.d.ts +35 -0
- package/dist/cjs/recentFeed.js +76 -0
- package/dist/cjs/recentFeed.js.map +1 -0
- package/dist/cjs/returnInfo.js +2 -2
- package/dist/cjs/returnInfo.js.map +1 -1
- package/dist/cjs/topicPage.js +7 -3
- package/dist/cjs/topicPage.js.map +1 -1
- package/dist/cjs/types.d.ts +63 -7
- package/dist/cjs/usage.d.ts +39 -0
- package/dist/cjs/usage.js +62 -0
- package/dist/cjs/usage.js.map +1 -0
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/esm/abort.d.ts +14 -0
- package/dist/esm/abort.js +65 -0
- package/dist/esm/abort.js.map +1 -0
- package/dist/esm/analytics.d.ts +2 -2
- package/dist/esm/base.js +8 -2
- package/dist/esm/base.js.map +1 -1
- package/dist/esm/counts.d.ts +2 -2
- package/dist/esm/dailyShares.d.ts +2 -2
- package/dist/esm/errors.d.ts +66 -0
- package/dist/esm/errors.js +67 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/eventForText.d.ts +3 -3
- package/dist/esm/eventRegistry.d.ts +67 -35
- package/dist/esm/eventRegistry.js +238 -186
- package/dist/esm/eventRegistry.js.map +1 -1
- package/dist/esm/fluent/analytics.d.ts +2 -2
- package/dist/esm/fluent/articles.d.ts +5 -5
- package/dist/esm/fluent/counts.d.ts +2 -2
- package/dist/esm/fluent/eventForText.d.ts +1 -1
- package/dist/esm/fluent/events.d.ts +5 -5
- package/dist/esm/fluent/info.d.ts +2 -2
- package/dist/esm/fluent/mentions.d.ts +3 -3
- package/dist/esm/fluent/recent.d.ts +9 -4
- package/dist/esm/fluent/recent.js +7 -3
- package/dist/esm/fluent/recent.js.map +1 -1
- package/dist/esm/fluent/shares.d.ts +2 -2
- package/dist/esm/fluent/stories.d.ts +3 -3
- package/dist/esm/fluent/topicPages.d.ts +3 -3
- package/dist/esm/fluent/trends.d.ts +3 -3
- package/dist/esm/guards.d.ts +12 -0
- package/dist/esm/guards.js +70 -0
- package/dist/esm/guards.js.map +1 -0
- package/dist/esm/helpers/analytics.d.ts +2 -2
- package/dist/esm/helpers/articles.d.ts +4 -4
- package/dist/esm/helpers/counts.d.ts +2 -2
- package/dist/esm/helpers/eventForText.d.ts +1 -1
- package/dist/esm/helpers/events.d.ts +4 -4
- package/dist/esm/helpers/info.d.ts +2 -2
- package/dist/esm/helpers/mentions.d.ts +2 -2
- package/dist/esm/helpers/recent.d.ts +2 -2
- package/dist/esm/helpers/shares.d.ts +2 -2
- package/dist/esm/helpers/stories.d.ts +3 -3
- package/dist/esm/helpers/topicPages.d.ts +3 -3
- package/dist/esm/helpers/trends.d.ts +3 -3
- package/dist/esm/helpers/uri.d.ts +2 -2
- package/dist/esm/http.d.ts +5 -0
- package/dist/esm/http.js +64 -11
- package/dist/esm/http.js.map +1 -1
- package/dist/esm/index.d.ts +54 -47
- package/dist/esm/index.js +4 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/info.d.ts +2 -2
- package/dist/esm/logger.d.ts +2 -0
- package/dist/esm/logger.js +6 -2
- package/dist/esm/logger.js.map +1 -1
- package/dist/esm/mutex.d.ts +2 -1
- package/dist/esm/mutex.js +19 -2
- package/dist/esm/mutex.js.map +1 -1
- package/dist/esm/query.d.ts +2 -2
- package/dist/esm/query.js +4 -4
- package/dist/esm/query.js.map +1 -1
- package/dist/esm/queryArticle.d.ts +3 -3
- package/dist/esm/queryArticle.js +3 -2
- package/dist/esm/queryArticle.js.map +1 -1
- package/dist/esm/queryArticles.d.ts +12 -12
- package/dist/esm/queryArticles.js +19 -18
- package/dist/esm/queryArticles.js.map +1 -1
- package/dist/esm/queryEvent.d.ts +6 -5
- package/dist/esm/queryEvent.js +11 -5
- package/dist/esm/queryEvent.js.map +1 -1
- package/dist/esm/queryEvents.d.ts +6 -6
- package/dist/esm/queryEvents.js +8 -7
- package/dist/esm/queryEvents.js.map +1 -1
- package/dist/esm/queryIterator.d.ts +2 -0
- package/dist/esm/queryIterator.js +18 -10
- package/dist/esm/queryIterator.js.map +1 -1
- package/dist/esm/queryMentions.d.ts +4 -3
- package/dist/esm/queryMentions.js +14 -8
- package/dist/esm/queryMentions.js.map +1 -1
- package/dist/esm/queryStory.d.ts +11 -8
- package/dist/esm/queryStory.js +4 -4
- package/dist/esm/queryStory.js.map +1 -1
- package/dist/esm/recent.d.ts +21 -9
- package/dist/esm/recent.js +26 -8
- package/dist/esm/recent.js.map +1 -1
- package/dist/esm/recentFeed.d.ts +35 -0
- package/dist/esm/recentFeed.js +70 -0
- package/dist/esm/recentFeed.js.map +1 -0
- package/dist/esm/returnInfo.d.ts +1 -1
- package/dist/esm/returnInfo.js +2 -2
- package/dist/esm/returnInfo.js.map +1 -1
- package/dist/esm/topicPage.d.ts +3 -3
- package/dist/esm/topicPage.js +7 -3
- package/dist/esm/topicPage.js.map +1 -1
- package/dist/esm/topicPages.d.ts +1 -1
- package/dist/esm/trends.d.ts +2 -2
- package/dist/esm/types.d.ts +69 -13
- package/dist/esm/usage.d.ts +39 -0
- package/dist/esm/usage.js +58 -0
- package/dist/esm/usage.js.map +1 -0
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/package.json +21 -12
- package/src/abort.ts +70 -0
- package/src/base.ts +8 -2
- package/src/errors.ts +105 -0
- package/src/eventRegistry.ts +285 -185
- package/src/fluent/recent.ts +9 -5
- package/src/guards.ts +79 -0
- package/src/http.ts +70 -11
- package/src/index.ts +7 -0
- package/src/logger.ts +7 -2
- package/src/mutex.ts +20 -2
- package/src/query.ts +4 -4
- package/src/queryArticle.ts +3 -2
- package/src/queryArticles.ts +25 -17
- package/src/queryEvent.ts +12 -5
- package/src/queryEvents.ts +9 -8
- package/src/queryIterator.ts +20 -9
- package/src/queryMentions.ts +16 -9
- package/src/queryStory.ts +11 -4
- package/src/recent.ts +35 -10
- package/src/recentFeed.ts +91 -0
- package/src/returnInfo.ts +2 -2
- package/src/topicPage.ts +7 -3
- package/src/types.ts +66 -7
- package/src/usage.ts +79 -0
- 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
|
|
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:
|
|
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
|
-
|
|
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.
|
|
79
|
-
this.
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
-
|
|
111
|
-
|
|
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
|
|
177
|
+
return this.minDelayMs / 1000;
|
|
126
178
|
}
|
|
127
179
|
getRepeatFailedRequestCount() {
|
|
128
|
-
return this.config.repeatFailedRequestCount ??
|
|
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
|
-
|
|
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
|
-
|
|
238
|
-
|
|
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
|
-
|
|
244
|
-
|
|
245
|
-
|
|
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
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
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
|
-
|
|
354
|
+
const scope = this.composeCallScope(options);
|
|
355
|
+
await this.acquireLock(scope);
|
|
314
356
|
try {
|
|
315
|
-
await this.waitForTurn();
|
|
316
|
-
if (
|
|
317
|
-
|
|
318
|
-
|
|
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
|
|
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:
|
|
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 (
|
|
349
|
-
|
|
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
|
-
|
|
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(
|
|
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(
|
|
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
|
-
|
|
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,
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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:
|
|
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
|
|
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.
|
|
839
|
-
return this.articleUrlToUri
|
|
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
|
|
896
|
+
this.articleUrlToUri.set(articleUrl, value);
|
|
845
897
|
}
|
|
846
898
|
return value;
|
|
847
899
|
}
|