@interopio/search-api 2.2.0 → 2.2.2

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.
@@ -1,2352 +1,2306 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
- typeof define === 'function' && define.amd ? define(factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global["search-api"] = factory());
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
3
+ typeof define === 'function' && define.amd ? define(factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global["search-api"] = factory());
5
5
  })(this, (function () { 'use strict';
6
6
 
7
- /******************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
-
22
- function __awaiter(thisArg, _arguments, P, generator) {
23
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
24
- return new (P || (P = Promise))(function (resolve, reject) {
25
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
26
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
27
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
28
- step((generator = generator.apply(thisArg, _arguments || [])).next());
29
- });
7
+ const urlAlphabet =
8
+ 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict';
9
+
10
+ let nanoid = (size = 21) => {
11
+ let id = '';
12
+ let bytes = crypto.getRandomValues(new Uint8Array(size));
13
+ while (size--) {
14
+ id += urlAlphabet[bytes[size] & 63];
30
15
  }
16
+ return id
17
+ };
31
18
 
32
- let nanoid = (size = 21) =>
33
- crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
34
- byte &= 63;
35
- if (byte < 36) {
36
- id += byte.toString(36);
37
- } else if (byte < 62) {
38
- id += (byte - 26).toString(36).toUpperCase();
39
- } else if (byte > 62) {
40
- id += '-';
41
- } else {
42
- id += '_';
43
- }
44
- return id
45
- }, '');
19
+ function getDefaultExportFromCjs (x) {
20
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
21
+ }
22
+
23
+ function createRegistry(options) {
24
+ if (options && options.errorHandling
25
+ && typeof options.errorHandling !== "function"
26
+ && options.errorHandling !== "log"
27
+ && options.errorHandling !== "silent"
28
+ && options.errorHandling !== "throw") {
29
+ throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
30
+ }
31
+ var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
32
+ var callbacks = {};
33
+ function add(key, callback, replayArgumentsArr) {
34
+ var callbacksForKey = callbacks[key];
35
+ if (!callbacksForKey) {
36
+ callbacksForKey = [];
37
+ callbacks[key] = callbacksForKey;
38
+ }
39
+ callbacksForKey.push(callback);
40
+ if (replayArgumentsArr) {
41
+ setTimeout(function () {
42
+ replayArgumentsArr.forEach(function (replayArgument) {
43
+ var _a;
44
+ if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) {
45
+ try {
46
+ if (Array.isArray(replayArgument)) {
47
+ callback.apply(undefined, replayArgument);
48
+ }
49
+ else {
50
+ callback.apply(undefined, [replayArgument]);
51
+ }
52
+ }
53
+ catch (err) {
54
+ _handleError(err, key);
55
+ }
56
+ }
57
+ });
58
+ }, 0);
59
+ }
60
+ return function () {
61
+ var allForKey = callbacks[key];
62
+ if (!allForKey) {
63
+ return;
64
+ }
65
+ allForKey = allForKey.reduce(function (acc, element, index) {
66
+ if (!(element === callback && acc.length === index)) {
67
+ acc.push(element);
68
+ }
69
+ return acc;
70
+ }, []);
71
+ if (allForKey.length === 0) {
72
+ delete callbacks[key];
73
+ }
74
+ else {
75
+ callbacks[key] = allForKey;
76
+ }
77
+ };
78
+ }
79
+ function execute(key) {
80
+ var argumentsArr = [];
81
+ for (var _i = 1; _i < arguments.length; _i++) {
82
+ argumentsArr[_i - 1] = arguments[_i];
83
+ }
84
+ var callbacksForKey = callbacks[key];
85
+ if (!callbacksForKey || callbacksForKey.length === 0) {
86
+ return [];
87
+ }
88
+ var results = [];
89
+ callbacksForKey.forEach(function (callback) {
90
+ try {
91
+ var result = callback.apply(undefined, argumentsArr);
92
+ results.push(result);
93
+ }
94
+ catch (err) {
95
+ results.push(undefined);
96
+ _handleError(err, key);
97
+ }
98
+ });
99
+ return results;
100
+ }
101
+ function _handleError(exceptionArtifact, key) {
102
+ var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact);
103
+ if (_userErrorHandler) {
104
+ _userErrorHandler(errParam);
105
+ return;
106
+ }
107
+ var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack;
108
+ if (options) {
109
+ switch (options.errorHandling) {
110
+ case "log":
111
+ return console.error(msg);
112
+ case "silent":
113
+ return;
114
+ case "throw":
115
+ throw new Error(msg);
116
+ }
117
+ }
118
+ console.error(msg);
119
+ }
120
+ function clear() {
121
+ callbacks = {};
122
+ }
123
+ function clearKey(key) {
124
+ var callbacksForKey = callbacks[key];
125
+ if (!callbacksForKey) {
126
+ return;
127
+ }
128
+ delete callbacks[key];
129
+ }
130
+ return {
131
+ add: add,
132
+ execute: execute,
133
+ clear: clear,
134
+ clearKey: clearKey
135
+ };
136
+ }
137
+ createRegistry.default = createRegistry;
138
+ var lib = createRegistry;
46
139
 
47
- function createRegistry(options) {
48
- if (options && options.errorHandling
49
- && typeof options.errorHandling !== "function"
50
- && options.errorHandling !== "log"
51
- && options.errorHandling !== "silent"
52
- && options.errorHandling !== "throw") {
53
- throw new Error("Invalid options passed to createRegistry. Prop errorHandling should be [\"log\" | \"silent\" | \"throw\" | (err) => void], but " + typeof options.errorHandling + " was passed");
54
- }
55
- var _userErrorHandler = options && typeof options.errorHandling === "function" && options.errorHandling;
56
- var callbacks = {};
57
- function add(key, callback, replayArgumentsArr) {
58
- var callbacksForKey = callbacks[key];
59
- if (!callbacksForKey) {
60
- callbacksForKey = [];
61
- callbacks[key] = callbacksForKey;
62
- }
63
- callbacksForKey.push(callback);
64
- if (replayArgumentsArr) {
65
- setTimeout(function () {
66
- replayArgumentsArr.forEach(function (replayArgument) {
67
- var _a;
68
- if ((_a = callbacks[key]) === null || _a === void 0 ? void 0 : _a.includes(callback)) {
69
- try {
70
- if (Array.isArray(replayArgument)) {
71
- callback.apply(undefined, replayArgument);
72
- }
73
- else {
74
- callback.apply(undefined, [replayArgument]);
75
- }
76
- }
77
- catch (err) {
78
- _handleError(err, key);
79
- }
80
- }
81
- });
82
- }, 0);
83
- }
84
- return function () {
85
- var allForKey = callbacks[key];
86
- if (!allForKey) {
87
- return;
88
- }
89
- allForKey = allForKey.reduce(function (acc, element, index) {
90
- if (!(element === callback && acc.length === index)) {
91
- acc.push(element);
92
- }
93
- return acc;
94
- }, []);
95
- if (allForKey.length === 0) {
96
- delete callbacks[key];
97
- }
98
- else {
99
- callbacks[key] = allForKey;
100
- }
101
- };
102
- }
103
- function execute(key) {
104
- var argumentsArr = [];
105
- for (var _i = 1; _i < arguments.length; _i++) {
106
- argumentsArr[_i - 1] = arguments[_i];
107
- }
108
- var callbacksForKey = callbacks[key];
109
- if (!callbacksForKey || callbacksForKey.length === 0) {
110
- return [];
111
- }
112
- var results = [];
113
- callbacksForKey.forEach(function (callback) {
114
- try {
115
- var result = callback.apply(undefined, argumentsArr);
116
- results.push(result);
117
- }
118
- catch (err) {
119
- results.push(undefined);
120
- _handleError(err, key);
121
- }
122
- });
123
- return results;
124
- }
125
- function _handleError(exceptionArtifact, key) {
126
- var errParam = exceptionArtifact instanceof Error ? exceptionArtifact : new Error(exceptionArtifact);
127
- if (_userErrorHandler) {
128
- _userErrorHandler(errParam);
129
- return;
130
- }
131
- var msg = "[ERROR] callback-registry: User callback for key \"" + key + "\" failed: " + errParam.stack;
132
- if (options) {
133
- switch (options.errorHandling) {
134
- case "log":
135
- return console.error(msg);
136
- case "silent":
137
- return;
138
- case "throw":
139
- throw new Error(msg);
140
- }
141
- }
142
- console.error(msg);
143
- }
144
- function clear() {
145
- callbacks = {};
146
- }
147
- function clearKey(key) {
148
- var callbacksForKey = callbacks[key];
149
- if (!callbacksForKey) {
150
- return;
151
- }
152
- delete callbacks[key];
153
- }
154
- return {
155
- add: add,
156
- execute: execute,
157
- clear: clear,
158
- clearKey: clearKey
159
- };
160
- }
161
- createRegistry.default = createRegistry;
162
- var lib = createRegistry;
163
140
 
164
- const SEARCH_QUERY_STATUSES = {
165
- done: "done",
166
- inProgress: "in-progress",
167
- error: "error"
168
- };
169
- const CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS = {
170
- info: "info",
171
- search: "search",
172
- cancel: "cancel"
173
- };
141
+ var CallbackRegistryFactory = /*@__PURE__*/getDefaultExportFromCjs(lib);
174
142
 
175
- /**
176
- * Wraps values in an `Ok` type.
177
- *
178
- * Example: `ok(5) // => {ok: true, result: 5}`
179
- */
180
- var ok = function (result) { return ({ ok: true, result: result }); };
181
- /**
182
- * Wraps errors in an `Err` type.
183
- *
184
- * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
185
- */
186
- var err = function (error) { return ({ ok: false, error: error }); };
187
- /**
188
- * Create a `Promise` that either resolves with the result of `Ok` or rejects
189
- * with the error of `Err`.
190
- */
191
- var asPromise = function (r) {
192
- return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
193
- };
194
- /**
195
- * Unwraps a `Result` and returns either the result of an `Ok`, or
196
- * `defaultValue`.
197
- *
198
- * Example:
199
- * ```
200
- * Result.withDefault(5, number().run(json))
201
- * ```
202
- *
203
- * It would be nice if `Decoder` had an instance method that mirrored this
204
- * function. Such a method would look something like this:
205
- * ```
206
- * class Decoder<A> {
207
- * runWithDefault = (defaultValue: A, json: any): A =>
208
- * Result.withDefault(defaultValue, this.run(json));
209
- * }
210
- *
211
- * number().runWithDefault(5, json)
212
- * ```
213
- * Unfortunately, the type of `defaultValue: A` on the method causes issues
214
- * with type inference on the `object` decoder in some situations. While these
215
- * inference issues can be solved by providing the optional type argument for
216
- * `object`s, the extra trouble and confusion doesn't seem worth it.
217
- */
218
- var withDefault = function (defaultValue, r) {
219
- return r.ok === true ? r.result : defaultValue;
220
- };
221
- /**
222
- * Return the successful result, or throw an error.
223
- */
224
- var withException = function (r) {
225
- if (r.ok === true) {
226
- return r.result;
227
- }
228
- else {
229
- throw r.error;
230
- }
231
- };
232
- /**
233
- * Apply `f` to the result of an `Ok`, or pass the error through.
234
- */
235
- var map = function (f, r) {
236
- return r.ok === true ? ok(f(r.result)) : r;
237
- };
238
- /**
239
- * Apply `f` to the result of two `Ok`s, or pass an error through. If both
240
- * `Result`s are errors then the first one is returned.
241
- */
242
- var map2 = function (f, ar, br) {
243
- return ar.ok === false ? ar :
244
- br.ok === false ? br :
245
- ok(f(ar.result, br.result));
246
- };
247
- /**
248
- * Apply `f` to the error of an `Err`, or pass the success through.
249
- */
250
- var mapError = function (f, r) {
251
- return r.ok === true ? r : err(f(r.error));
252
- };
253
- /**
254
- * Chain together a sequence of computations that may fail, similar to a
255
- * `Promise`. If the first computation fails then the error will propagate
256
- * through. If it succeeds, then `f` will be applied to the value, returning a
257
- * new `Result`.
258
- */
259
- var andThen = function (f, r) {
260
- return r.ok === true ? f(r.result) : r;
261
- };
143
+ const SEARCH_QUERY_STATUSES = {
144
+ done: "done",
145
+ inProgress: "in-progress",
146
+ error: "error"
147
+ };
148
+ const CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS = {
149
+ info: "info",
150
+ search: "search",
151
+ cancel: "cancel"
152
+ };
153
+
154
+ /**
155
+ * Wraps values in an `Ok` type.
156
+ *
157
+ * Example: `ok(5) // => {ok: true, result: 5}`
158
+ */
159
+ var ok = function (result) { return ({ ok: true, result: result }); };
160
+ /**
161
+ * Wraps errors in an `Err` type.
162
+ *
163
+ * Example: `err('on fire') // => {ok: false, error: 'on fire'}`
164
+ */
165
+ var err = function (error) { return ({ ok: false, error: error }); };
166
+ /**
167
+ * Create a `Promise` that either resolves with the result of `Ok` or rejects
168
+ * with the error of `Err`.
169
+ */
170
+ var asPromise = function (r) {
171
+ return r.ok === true ? Promise.resolve(r.result) : Promise.reject(r.error);
172
+ };
173
+ /**
174
+ * Unwraps a `Result` and returns either the result of an `Ok`, or
175
+ * `defaultValue`.
176
+ *
177
+ * Example:
178
+ * ```
179
+ * Result.withDefault(5, number().run(json))
180
+ * ```
181
+ *
182
+ * It would be nice if `Decoder` had an instance method that mirrored this
183
+ * function. Such a method would look something like this:
184
+ * ```
185
+ * class Decoder<A> {
186
+ * runWithDefault = (defaultValue: A, json: any): A =>
187
+ * Result.withDefault(defaultValue, this.run(json));
188
+ * }
189
+ *
190
+ * number().runWithDefault(5, json)
191
+ * ```
192
+ * Unfortunately, the type of `defaultValue: A` on the method causes issues
193
+ * with type inference on the `object` decoder in some situations. While these
194
+ * inference issues can be solved by providing the optional type argument for
195
+ * `object`s, the extra trouble and confusion doesn't seem worth it.
196
+ */
197
+ var withDefault = function (defaultValue, r) {
198
+ return r.ok === true ? r.result : defaultValue;
199
+ };
200
+ /**
201
+ * Return the successful result, or throw an error.
202
+ */
203
+ var withException = function (r) {
204
+ if (r.ok === true) {
205
+ return r.result;
206
+ }
207
+ else {
208
+ throw r.error;
209
+ }
210
+ };
211
+ /**
212
+ * Apply `f` to the result of an `Ok`, or pass the error through.
213
+ */
214
+ var map = function (f, r) {
215
+ return r.ok === true ? ok(f(r.result)) : r;
216
+ };
217
+ /**
218
+ * Apply `f` to the result of two `Ok`s, or pass an error through. If both
219
+ * `Result`s are errors then the first one is returned.
220
+ */
221
+ var map2 = function (f, ar, br) {
222
+ return ar.ok === false ? ar :
223
+ br.ok === false ? br :
224
+ ok(f(ar.result, br.result));
225
+ };
226
+ /**
227
+ * Apply `f` to the error of an `Err`, or pass the success through.
228
+ */
229
+ var mapError = function (f, r) {
230
+ return r.ok === true ? r : err(f(r.error));
231
+ };
232
+ /**
233
+ * Chain together a sequence of computations that may fail, similar to a
234
+ * `Promise`. If the first computation fails then the error will propagate
235
+ * through. If it succeeds, then `f` will be applied to the value, returning a
236
+ * new `Result`.
237
+ */
238
+ var andThen = function (f, r) {
239
+ return r.ok === true ? f(r.result) : r;
240
+ };
262
241
 
263
- /*! *****************************************************************************
264
- Copyright (c) Microsoft Corporation.
242
+ /*! *****************************************************************************
243
+ Copyright (c) Microsoft Corporation.
265
244
 
266
- Permission to use, copy, modify, and/or distribute this software for any
267
- purpose with or without fee is hereby granted.
245
+ Permission to use, copy, modify, and/or distribute this software for any
246
+ purpose with or without fee is hereby granted.
268
247
 
269
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
270
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
271
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
272
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
273
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
274
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
275
- PERFORMANCE OF THIS SOFTWARE.
276
- ***************************************************************************** */
277
- /* global Reflect, Promise */
248
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
249
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
250
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
251
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
252
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
253
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
254
+ PERFORMANCE OF THIS SOFTWARE.
255
+ ***************************************************************************** */
256
+ /* global Reflect, Promise */
278
257
 
279
258
 
280
259
 
281
- var __assign = function() {
282
- __assign = Object.assign || function __assign(t) {
283
- for (var s, i = 1, n = arguments.length; i < n; i++) {
284
- s = arguments[i];
285
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
286
- }
287
- return t;
288
- };
289
- return __assign.apply(this, arguments);
290
- };
260
+ var __assign = function() {
261
+ __assign = Object.assign || function __assign(t) {
262
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
263
+ s = arguments[i];
264
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
265
+ }
266
+ return t;
267
+ };
268
+ return __assign.apply(this, arguments);
269
+ };
291
270
 
292
- function __rest(s, e) {
293
- var t = {};
294
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
295
- t[p] = s[p];
296
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
297
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
298
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
299
- t[p[i]] = s[p[i]];
300
- }
301
- return t;
302
- }
271
+ function __rest(s, e) {
272
+ var t = {};
273
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
274
+ t[p] = s[p];
275
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
276
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
277
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
278
+ t[p[i]] = s[p[i]];
279
+ }
280
+ return t;
281
+ }
303
282
 
304
- function isEqual(a, b) {
305
- if (a === b) {
306
- return true;
307
- }
308
- if (a === null && b === null) {
309
- return true;
310
- }
311
- if (typeof (a) !== typeof (b)) {
312
- return false;
313
- }
314
- if (typeof (a) === 'object') {
315
- // Array
316
- if (Array.isArray(a)) {
317
- if (!Array.isArray(b)) {
318
- return false;
319
- }
320
- if (a.length !== b.length) {
321
- return false;
322
- }
323
- for (var i = 0; i < a.length; i++) {
324
- if (!isEqual(a[i], b[i])) {
325
- return false;
326
- }
327
- }
328
- return true;
329
- }
330
- // Hash table
331
- var keys = Object.keys(a);
332
- if (keys.length !== Object.keys(b).length) {
333
- return false;
334
- }
335
- for (var i = 0; i < keys.length; i++) {
336
- if (!b.hasOwnProperty(keys[i])) {
337
- return false;
338
- }
339
- if (!isEqual(a[keys[i]], b[keys[i]])) {
340
- return false;
341
- }
342
- }
343
- return true;
344
- }
345
- }
346
- /*
347
- * Helpers
348
- */
349
- var isJsonArray = function (json) { return Array.isArray(json); };
350
- var isJsonObject = function (json) {
351
- return typeof json === 'object' && json !== null && !isJsonArray(json);
352
- };
353
- var typeString = function (json) {
354
- switch (typeof json) {
355
- case 'string':
356
- return 'a string';
357
- case 'number':
358
- return 'a number';
359
- case 'boolean':
360
- return 'a boolean';
361
- case 'undefined':
362
- return 'undefined';
363
- case 'object':
364
- if (json instanceof Array) {
365
- return 'an array';
366
- }
367
- else if (json === null) {
368
- return 'null';
369
- }
370
- else {
371
- return 'an object';
372
- }
373
- default:
374
- return JSON.stringify(json);
375
- }
376
- };
377
- var expectedGot = function (expected, got) {
378
- return "expected " + expected + ", got " + typeString(got);
379
- };
380
- var printPath = function (paths) {
381
- return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
382
- };
383
- var prependAt = function (newAt, _a) {
384
- var at = _a.at, rest = __rest(_a, ["at"]);
385
- return (__assign({ at: newAt + (at || '') }, rest));
386
- };
387
- /**
388
- * Decoders transform json objects with unknown structure into known and
389
- * verified forms. You can create objects of type `Decoder<A>` with either the
390
- * primitive decoder functions, such as `boolean()` and `string()`, or by
391
- * applying higher-order decoders to the primitives, such as `array(boolean())`
392
- * or `dict(string())`.
393
- *
394
- * Each of the decoder functions are available both as a static method on
395
- * `Decoder` and as a function alias -- for example the string decoder is
396
- * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
397
- * function aliases exported with the library is recommended.
398
- *
399
- * `Decoder` exposes a number of 'run' methods, which all decode json in the
400
- * same way, but communicate success and failure in different ways. The `map`
401
- * and `andThen` methods modify decoders without having to call a 'run' method.
402
- *
403
- * Alternatively, the main decoder `run()` method returns an object of type
404
- * `Result<A, DecoderError>`. This library provides a number of helper
405
- * functions for dealing with the `Result` type, so you can do all the same
406
- * things with a `Result` as with the decoder methods.
407
- */
408
- var Decoder = /** @class */ (function () {
409
- /**
410
- * The Decoder class constructor is kept private to separate the internal
411
- * `decode` function from the external `run` function. The distinction
412
- * between the two functions is that `decode` returns a
413
- * `Partial<DecoderError>` on failure, which contains an unfinished error
414
- * report. When `run` is called on a decoder, the relevant series of `decode`
415
- * calls is made, and then on failure the resulting `Partial<DecoderError>`
416
- * is turned into a `DecoderError` by filling in the missing information.
417
- *
418
- * While hiding the constructor may seem restrictive, leveraging the
419
- * provided decoder combinators and helper functions such as
420
- * `andThen` and `map` should be enough to build specialized decoders as
421
- * needed.
422
- */
423
- function Decoder(decode) {
424
- var _this = this;
425
- this.decode = decode;
426
- /**
427
- * Run the decoder and return a `Result` with either the decoded value or a
428
- * `DecoderError` containing the json input, the location of the error, and
429
- * the error message.
430
- *
431
- * Examples:
432
- * ```
433
- * number().run(12)
434
- * // => {ok: true, result: 12}
435
- *
436
- * string().run(9001)
437
- * // =>
438
- * // {
439
- * // ok: false,
440
- * // error: {
441
- * // kind: 'DecoderError',
442
- * // input: 9001,
443
- * // at: 'input',
444
- * // message: 'expected a string, got 9001'
445
- * // }
446
- * // }
447
- * ```
448
- */
449
- this.run = function (json) {
450
- return mapError(function (error) { return ({
451
- kind: 'DecoderError',
452
- input: json,
453
- at: 'input' + (error.at || ''),
454
- message: error.message || ''
455
- }); }, _this.decode(json));
456
- };
457
- /**
458
- * Run the decoder as a `Promise`.
459
- */
460
- this.runPromise = function (json) { return asPromise(_this.run(json)); };
461
- /**
462
- * Run the decoder and return the value on success, or throw an exception
463
- * with a formatted error string.
464
- */
465
- this.runWithException = function (json) { return withException(_this.run(json)); };
466
- /**
467
- * Construct a new decoder that applies a transformation to the decoded
468
- * result. If the decoder succeeds then `f` will be applied to the value. If
469
- * it fails the error will propagated through.
470
- *
471
- * Example:
472
- * ```
473
- * number().map(x => x * 5).run(10)
474
- * // => {ok: true, result: 50}
475
- * ```
476
- */
477
- this.map = function (f) {
478
- return new Decoder(function (json) { return map(f, _this.decode(json)); });
479
- };
480
- /**
481
- * Chain together a sequence of decoders. The first decoder will run, and
482
- * then the function will determine what decoder to run second. If the result
483
- * of the first decoder succeeds then `f` will be applied to the decoded
484
- * value. If it fails the error will propagate through.
485
- *
486
- * This is a very powerful method -- it can act as both the `map` and `where`
487
- * methods, can improve error messages for edge cases, and can be used to
488
- * make a decoder for custom types.
489
- *
490
- * Example of adding an error message:
491
- * ```
492
- * const versionDecoder = valueAt(['version'], number());
493
- * const infoDecoder3 = object({a: boolean()});
494
- *
495
- * const decoder = versionDecoder.andThen(version => {
496
- * switch (version) {
497
- * case 3:
498
- * return infoDecoder3;
499
- * default:
500
- * return fail(`Unable to decode info, version ${version} is not supported.`);
501
- * }
502
- * });
503
- *
504
- * decoder.run({version: 3, a: true})
505
- * // => {ok: true, result: {a: true}}
506
- *
507
- * decoder.run({version: 5, x: 'abc'})
508
- * // =>
509
- * // {
510
- * // ok: false,
511
- * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
512
- * // }
513
- * ```
514
- *
515
- * Example of decoding a custom type:
516
- * ```
517
- * // nominal type for arrays with a length of at least one
518
- * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
519
- *
520
- * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
521
- * array(values).andThen(arr =>
522
- * arr.length > 0
523
- * ? succeed(createNonEmptyArray(arr))
524
- * : fail(`expected a non-empty array, got an empty array`)
525
- * );
526
- * ```
527
- */
528
- this.andThen = function (f) {
529
- return new Decoder(function (json) {
530
- return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
531
- });
532
- };
533
- /**
534
- * Add constraints to a decoder _without_ changing the resulting type. The
535
- * `test` argument is a predicate function which returns true for valid
536
- * inputs. When `test` fails on an input, the decoder fails with the given
537
- * `errorMessage`.
538
- *
539
- * ```
540
- * const chars = (length: number): Decoder<string> =>
541
- * string().where(
542
- * (s: string) => s.length === length,
543
- * `expected a string of length ${length}`
544
- * );
545
- *
546
- * chars(5).run('12345')
547
- * // => {ok: true, result: '12345'}
548
- *
549
- * chars(2).run('HELLO')
550
- * // => {ok: false, error: {... message: 'expected a string of length 2'}}
551
- *
552
- * chars(12).run(true)
553
- * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
554
- * ```
555
- */
556
- this.where = function (test, errorMessage) {
557
- return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
558
- };
559
- }
560
- /**
561
- * Decoder primitive that validates strings, and fails on all other input.
562
- */
563
- Decoder.string = function () {
564
- return new Decoder(function (json) {
565
- return typeof json === 'string'
566
- ? ok(json)
567
- : err({ message: expectedGot('a string', json) });
568
- });
569
- };
570
- /**
571
- * Decoder primitive that validates numbers, and fails on all other input.
572
- */
573
- Decoder.number = function () {
574
- return new Decoder(function (json) {
575
- return typeof json === 'number'
576
- ? ok(json)
577
- : err({ message: expectedGot('a number', json) });
578
- });
579
- };
580
- /**
581
- * Decoder primitive that validates booleans, and fails on all other input.
582
- */
583
- Decoder.boolean = function () {
584
- return new Decoder(function (json) {
585
- return typeof json === 'boolean'
586
- ? ok(json)
587
- : err({ message: expectedGot('a boolean', json) });
588
- });
589
- };
590
- Decoder.constant = function (value) {
591
- return new Decoder(function (json) {
592
- return isEqual(json, value)
593
- ? ok(value)
594
- : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
595
- });
596
- };
597
- Decoder.object = function (decoders) {
598
- return new Decoder(function (json) {
599
- if (isJsonObject(json) && decoders) {
600
- var obj = {};
601
- for (var key in decoders) {
602
- if (decoders.hasOwnProperty(key)) {
603
- var r = decoders[key].decode(json[key]);
604
- if (r.ok === true) {
605
- // tslint:disable-next-line:strict-type-predicates
606
- if (r.result !== undefined) {
607
- obj[key] = r.result;
608
- }
609
- }
610
- else if (json[key] === undefined) {
611
- return err({ message: "the key '" + key + "' is required but was not present" });
612
- }
613
- else {
614
- return err(prependAt("." + key, r.error));
615
- }
616
- }
617
- }
618
- return ok(obj);
619
- }
620
- else if (isJsonObject(json)) {
621
- return ok(json);
622
- }
623
- else {
624
- return err({ message: expectedGot('an object', json) });
625
- }
626
- });
627
- };
628
- Decoder.array = function (decoder) {
629
- return new Decoder(function (json) {
630
- if (isJsonArray(json) && decoder) {
631
- var decodeValue_1 = function (v, i) {
632
- return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
633
- };
634
- return json.reduce(function (acc, v, i) {
635
- return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
636
- }, ok([]));
637
- }
638
- else if (isJsonArray(json)) {
639
- return ok(json);
640
- }
641
- else {
642
- return err({ message: expectedGot('an array', json) });
643
- }
644
- });
645
- };
646
- Decoder.tuple = function (decoders) {
647
- return new Decoder(function (json) {
648
- if (isJsonArray(json)) {
649
- if (json.length !== decoders.length) {
650
- return err({
651
- message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
652
- });
653
- }
654
- var result = [];
655
- for (var i = 0; i < decoders.length; i++) {
656
- var nth = decoders[i].decode(json[i]);
657
- if (nth.ok) {
658
- result[i] = nth.result;
659
- }
660
- else {
661
- return err(prependAt("[" + i + "]", nth.error));
662
- }
663
- }
664
- return ok(result);
665
- }
666
- else {
667
- return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
668
- }
669
- });
670
- };
671
- Decoder.union = function (ad, bd) {
672
- var decoders = [];
673
- for (var _i = 2; _i < arguments.length; _i++) {
674
- decoders[_i - 2] = arguments[_i];
675
- }
676
- return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
677
- };
678
- Decoder.intersection = function (ad, bd) {
679
- var ds = [];
680
- for (var _i = 2; _i < arguments.length; _i++) {
681
- ds[_i - 2] = arguments[_i];
682
- }
683
- return new Decoder(function (json) {
684
- return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
685
- });
686
- };
687
- /**
688
- * Escape hatch to bypass validation. Always succeeds and types the result as
689
- * `any`. Useful for defining decoders incrementally, particularly for
690
- * complex objects.
691
- *
692
- * Example:
693
- * ```
694
- * interface User {
695
- * name: string;
696
- * complexUserData: ComplexType;
697
- * }
698
- *
699
- * const userDecoder: Decoder<User> = object({
700
- * name: string(),
701
- * complexUserData: anyJson()
702
- * });
703
- * ```
704
- */
705
- Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
706
- /**
707
- * Decoder identity function which always succeeds and types the result as
708
- * `unknown`.
709
- */
710
- Decoder.unknownJson = function () {
711
- return new Decoder(function (json) { return ok(json); });
712
- };
713
- /**
714
- * Decoder for json objects where the keys are unknown strings, but the values
715
- * should all be of the same type.
716
- *
717
- * Example:
718
- * ```
719
- * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
720
- * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
721
- * ```
722
- */
723
- Decoder.dict = function (decoder) {
724
- return new Decoder(function (json) {
725
- if (isJsonObject(json)) {
726
- var obj = {};
727
- for (var key in json) {
728
- if (json.hasOwnProperty(key)) {
729
- var r = decoder.decode(json[key]);
730
- if (r.ok === true) {
731
- obj[key] = r.result;
732
- }
733
- else {
734
- return err(prependAt("." + key, r.error));
735
- }
736
- }
737
- }
738
- return ok(obj);
739
- }
740
- else {
741
- return err({ message: expectedGot('an object', json) });
742
- }
743
- });
744
- };
745
- /**
746
- * Decoder for values that may be `undefined`. This is primarily helpful for
747
- * decoding interfaces with optional fields.
748
- *
749
- * Example:
750
- * ```
751
- * interface User {
752
- * id: number;
753
- * isOwner?: boolean;
754
- * }
755
- *
756
- * const decoder: Decoder<User> = object({
757
- * id: number(),
758
- * isOwner: optional(boolean())
759
- * });
760
- * ```
761
- */
762
- Decoder.optional = function (decoder) {
763
- return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
764
- };
765
- /**
766
- * Decoder that attempts to run each decoder in `decoders` and either succeeds
767
- * with the first successful decoder, or fails after all decoders have failed.
768
- *
769
- * Note that `oneOf` expects the decoders to all have the same return type,
770
- * while `union` creates a decoder for the union type of all the input
771
- * decoders.
772
- *
773
- * Examples:
774
- * ```
775
- * oneOf(string(), number().map(String))
776
- * oneOf(constant('start'), constant('stop'), succeed('unknown'))
777
- * ```
778
- */
779
- Decoder.oneOf = function () {
780
- var decoders = [];
781
- for (var _i = 0; _i < arguments.length; _i++) {
782
- decoders[_i] = arguments[_i];
783
- }
784
- return new Decoder(function (json) {
785
- var errors = [];
786
- for (var i = 0; i < decoders.length; i++) {
787
- var r = decoders[i].decode(json);
788
- if (r.ok === true) {
789
- return r;
790
- }
791
- else {
792
- errors[i] = r.error;
793
- }
794
- }
795
- var errorsList = errors
796
- .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
797
- .join('", "');
798
- return err({
799
- message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
800
- });
801
- });
802
- };
803
- /**
804
- * Decoder that always succeeds with either the decoded value, or a fallback
805
- * default value.
806
- */
807
- Decoder.withDefault = function (defaultValue, decoder) {
808
- return new Decoder(function (json) {
809
- return ok(withDefault(defaultValue, decoder.decode(json)));
810
- });
811
- };
812
- /**
813
- * Decoder that pulls a specific field out of a json structure, instead of
814
- * decoding and returning the full structure. The `paths` array describes the
815
- * object keys and array indices to traverse, so that values can be pulled out
816
- * of a nested structure.
817
- *
818
- * Example:
819
- * ```
820
- * const decoder = valueAt(['a', 'b', 0], string());
821
- *
822
- * decoder.run({a: {b: ['surprise!']}})
823
- * // => {ok: true, result: 'surprise!'}
824
- *
825
- * decoder.run({a: {x: 'cats'}})
826
- * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
827
- * ```
828
- *
829
- * Note that the `decoder` is ran on the value found at the last key in the
830
- * path, even if the last key is not found. This allows the `optional`
831
- * decoder to succeed when appropriate.
832
- * ```
833
- * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
834
- *
835
- * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
836
- * // => {ok: true, result: 'surprise!'}
837
- *
838
- * optionalDecoder.run({a: {b: 'cats'}})
839
- * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
840
- *
841
- * optionalDecoder.run({a: {b: {z: 1}}})
842
- * // => {ok: true, result: undefined}
843
- * ```
844
- */
845
- Decoder.valueAt = function (paths, decoder) {
846
- return new Decoder(function (json) {
847
- var jsonAtPath = json;
848
- for (var i = 0; i < paths.length; i++) {
849
- if (jsonAtPath === undefined) {
850
- return err({
851
- at: printPath(paths.slice(0, i + 1)),
852
- message: 'path does not exist'
853
- });
854
- }
855
- else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
856
- return err({
857
- at: printPath(paths.slice(0, i + 1)),
858
- message: expectedGot('an object', jsonAtPath)
859
- });
860
- }
861
- else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
862
- return err({
863
- at: printPath(paths.slice(0, i + 1)),
864
- message: expectedGot('an array', jsonAtPath)
865
- });
866
- }
867
- else {
868
- jsonAtPath = jsonAtPath[paths[i]];
869
- }
870
- }
871
- return mapError(function (error) {
872
- return jsonAtPath === undefined
873
- ? { at: printPath(paths), message: 'path does not exist' }
874
- : prependAt(printPath(paths), error);
875
- }, decoder.decode(jsonAtPath));
876
- });
877
- };
878
- /**
879
- * Decoder that ignores the input json and always succeeds with `fixedValue`.
880
- */
881
- Decoder.succeed = function (fixedValue) {
882
- return new Decoder(function (json) { return ok(fixedValue); });
883
- };
884
- /**
885
- * Decoder that ignores the input json and always fails with `errorMessage`.
886
- */
887
- Decoder.fail = function (errorMessage) {
888
- return new Decoder(function (json) { return err({ message: errorMessage }); });
889
- };
890
- /**
891
- * Decoder that allows for validating recursive data structures. Unlike with
892
- * functions, decoders assigned to variables can't reference themselves
893
- * before they are fully defined. We can avoid prematurely referencing the
894
- * decoder by wrapping it in a function that won't be called until use, at
895
- * which point the decoder has been defined.
896
- *
897
- * Example:
898
- * ```
899
- * interface Comment {
900
- * msg: string;
901
- * replies: Comment[];
902
- * }
903
- *
904
- * const decoder: Decoder<Comment> = object({
905
- * msg: string(),
906
- * replies: lazy(() => array(decoder))
907
- * });
908
- * ```
909
- */
910
- Decoder.lazy = function (mkDecoder) {
911
- return new Decoder(function (json) { return mkDecoder().decode(json); });
912
- };
913
- return Decoder;
914
- }());
283
+ function isEqual(a, b) {
284
+ if (a === b) {
285
+ return true;
286
+ }
287
+ if (a === null && b === null) {
288
+ return true;
289
+ }
290
+ if (typeof (a) !== typeof (b)) {
291
+ return false;
292
+ }
293
+ if (typeof (a) === 'object') {
294
+ // Array
295
+ if (Array.isArray(a)) {
296
+ if (!Array.isArray(b)) {
297
+ return false;
298
+ }
299
+ if (a.length !== b.length) {
300
+ return false;
301
+ }
302
+ for (var i = 0; i < a.length; i++) {
303
+ if (!isEqual(a[i], b[i])) {
304
+ return false;
305
+ }
306
+ }
307
+ return true;
308
+ }
309
+ // Hash table
310
+ var keys = Object.keys(a);
311
+ if (keys.length !== Object.keys(b).length) {
312
+ return false;
313
+ }
314
+ for (var i = 0; i < keys.length; i++) {
315
+ if (!b.hasOwnProperty(keys[i])) {
316
+ return false;
317
+ }
318
+ if (!isEqual(a[keys[i]], b[keys[i]])) {
319
+ return false;
320
+ }
321
+ }
322
+ return true;
323
+ }
324
+ }
325
+ /*
326
+ * Helpers
327
+ */
328
+ var isJsonArray = function (json) { return Array.isArray(json); };
329
+ var isJsonObject = function (json) {
330
+ return typeof json === 'object' && json !== null && !isJsonArray(json);
331
+ };
332
+ var typeString = function (json) {
333
+ switch (typeof json) {
334
+ case 'string':
335
+ return 'a string';
336
+ case 'number':
337
+ return 'a number';
338
+ case 'boolean':
339
+ return 'a boolean';
340
+ case 'undefined':
341
+ return 'undefined';
342
+ case 'object':
343
+ if (json instanceof Array) {
344
+ return 'an array';
345
+ }
346
+ else if (json === null) {
347
+ return 'null';
348
+ }
349
+ else {
350
+ return 'an object';
351
+ }
352
+ default:
353
+ return JSON.stringify(json);
354
+ }
355
+ };
356
+ var expectedGot = function (expected, got) {
357
+ return "expected " + expected + ", got " + typeString(got);
358
+ };
359
+ var printPath = function (paths) {
360
+ return paths.map(function (path) { return (typeof path === 'string' ? "." + path : "[" + path + "]"); }).join('');
361
+ };
362
+ var prependAt = function (newAt, _a) {
363
+ var at = _a.at, rest = __rest(_a, ["at"]);
364
+ return (__assign({ at: newAt + (at || '') }, rest));
365
+ };
366
+ /**
367
+ * Decoders transform json objects with unknown structure into known and
368
+ * verified forms. You can create objects of type `Decoder<A>` with either the
369
+ * primitive decoder functions, such as `boolean()` and `string()`, or by
370
+ * applying higher-order decoders to the primitives, such as `array(boolean())`
371
+ * or `dict(string())`.
372
+ *
373
+ * Each of the decoder functions are available both as a static method on
374
+ * `Decoder` and as a function alias -- for example the string decoder is
375
+ * defined at `Decoder.string()`, but is also aliased to `string()`. Using the
376
+ * function aliases exported with the library is recommended.
377
+ *
378
+ * `Decoder` exposes a number of 'run' methods, which all decode json in the
379
+ * same way, but communicate success and failure in different ways. The `map`
380
+ * and `andThen` methods modify decoders without having to call a 'run' method.
381
+ *
382
+ * Alternatively, the main decoder `run()` method returns an object of type
383
+ * `Result<A, DecoderError>`. This library provides a number of helper
384
+ * functions for dealing with the `Result` type, so you can do all the same
385
+ * things with a `Result` as with the decoder methods.
386
+ */
387
+ var Decoder = /** @class */ (function () {
388
+ /**
389
+ * The Decoder class constructor is kept private to separate the internal
390
+ * `decode` function from the external `run` function. The distinction
391
+ * between the two functions is that `decode` returns a
392
+ * `Partial<DecoderError>` on failure, which contains an unfinished error
393
+ * report. When `run` is called on a decoder, the relevant series of `decode`
394
+ * calls is made, and then on failure the resulting `Partial<DecoderError>`
395
+ * is turned into a `DecoderError` by filling in the missing information.
396
+ *
397
+ * While hiding the constructor may seem restrictive, leveraging the
398
+ * provided decoder combinators and helper functions such as
399
+ * `andThen` and `map` should be enough to build specialized decoders as
400
+ * needed.
401
+ */
402
+ function Decoder(decode) {
403
+ var _this = this;
404
+ this.decode = decode;
405
+ /**
406
+ * Run the decoder and return a `Result` with either the decoded value or a
407
+ * `DecoderError` containing the json input, the location of the error, and
408
+ * the error message.
409
+ *
410
+ * Examples:
411
+ * ```
412
+ * number().run(12)
413
+ * // => {ok: true, result: 12}
414
+ *
415
+ * string().run(9001)
416
+ * // =>
417
+ * // {
418
+ * // ok: false,
419
+ * // error: {
420
+ * // kind: 'DecoderError',
421
+ * // input: 9001,
422
+ * // at: 'input',
423
+ * // message: 'expected a string, got 9001'
424
+ * // }
425
+ * // }
426
+ * ```
427
+ */
428
+ this.run = function (json) {
429
+ return mapError(function (error) { return ({
430
+ kind: 'DecoderError',
431
+ input: json,
432
+ at: 'input' + (error.at || ''),
433
+ message: error.message || ''
434
+ }); }, _this.decode(json));
435
+ };
436
+ /**
437
+ * Run the decoder as a `Promise`.
438
+ */
439
+ this.runPromise = function (json) { return asPromise(_this.run(json)); };
440
+ /**
441
+ * Run the decoder and return the value on success, or throw an exception
442
+ * with a formatted error string.
443
+ */
444
+ this.runWithException = function (json) { return withException(_this.run(json)); };
445
+ /**
446
+ * Construct a new decoder that applies a transformation to the decoded
447
+ * result. If the decoder succeeds then `f` will be applied to the value. If
448
+ * it fails the error will propagated through.
449
+ *
450
+ * Example:
451
+ * ```
452
+ * number().map(x => x * 5).run(10)
453
+ * // => {ok: true, result: 50}
454
+ * ```
455
+ */
456
+ this.map = function (f) {
457
+ return new Decoder(function (json) { return map(f, _this.decode(json)); });
458
+ };
459
+ /**
460
+ * Chain together a sequence of decoders. The first decoder will run, and
461
+ * then the function will determine what decoder to run second. If the result
462
+ * of the first decoder succeeds then `f` will be applied to the decoded
463
+ * value. If it fails the error will propagate through.
464
+ *
465
+ * This is a very powerful method -- it can act as both the `map` and `where`
466
+ * methods, can improve error messages for edge cases, and can be used to
467
+ * make a decoder for custom types.
468
+ *
469
+ * Example of adding an error message:
470
+ * ```
471
+ * const versionDecoder = valueAt(['version'], number());
472
+ * const infoDecoder3 = object({a: boolean()});
473
+ *
474
+ * const decoder = versionDecoder.andThen(version => {
475
+ * switch (version) {
476
+ * case 3:
477
+ * return infoDecoder3;
478
+ * default:
479
+ * return fail(`Unable to decode info, version ${version} is not supported.`);
480
+ * }
481
+ * });
482
+ *
483
+ * decoder.run({version: 3, a: true})
484
+ * // => {ok: true, result: {a: true}}
485
+ *
486
+ * decoder.run({version: 5, x: 'abc'})
487
+ * // =>
488
+ * // {
489
+ * // ok: false,
490
+ * // error: {... message: 'Unable to decode info, version 5 is not supported.'}
491
+ * // }
492
+ * ```
493
+ *
494
+ * Example of decoding a custom type:
495
+ * ```
496
+ * // nominal type for arrays with a length of at least one
497
+ * type NonEmptyArray<T> = T[] & { __nonEmptyArrayBrand__: void };
498
+ *
499
+ * const nonEmptyArrayDecoder = <T>(values: Decoder<T>): Decoder<NonEmptyArray<T>> =>
500
+ * array(values).andThen(arr =>
501
+ * arr.length > 0
502
+ * ? succeed(createNonEmptyArray(arr))
503
+ * : fail(`expected a non-empty array, got an empty array`)
504
+ * );
505
+ * ```
506
+ */
507
+ this.andThen = function (f) {
508
+ return new Decoder(function (json) {
509
+ return andThen(function (value) { return f(value).decode(json); }, _this.decode(json));
510
+ });
511
+ };
512
+ /**
513
+ * Add constraints to a decoder _without_ changing the resulting type. The
514
+ * `test` argument is a predicate function which returns true for valid
515
+ * inputs. When `test` fails on an input, the decoder fails with the given
516
+ * `errorMessage`.
517
+ *
518
+ * ```
519
+ * const chars = (length: number): Decoder<string> =>
520
+ * string().where(
521
+ * (s: string) => s.length === length,
522
+ * `expected a string of length ${length}`
523
+ * );
524
+ *
525
+ * chars(5).run('12345')
526
+ * // => {ok: true, result: '12345'}
527
+ *
528
+ * chars(2).run('HELLO')
529
+ * // => {ok: false, error: {... message: 'expected a string of length 2'}}
530
+ *
531
+ * chars(12).run(true)
532
+ * // => {ok: false, error: {... message: 'expected a string, got a boolean'}}
533
+ * ```
534
+ */
535
+ this.where = function (test, errorMessage) {
536
+ return _this.andThen(function (value) { return (test(value) ? Decoder.succeed(value) : Decoder.fail(errorMessage)); });
537
+ };
538
+ }
539
+ /**
540
+ * Decoder primitive that validates strings, and fails on all other input.
541
+ */
542
+ Decoder.string = function () {
543
+ return new Decoder(function (json) {
544
+ return typeof json === 'string'
545
+ ? ok(json)
546
+ : err({ message: expectedGot('a string', json) });
547
+ });
548
+ };
549
+ /**
550
+ * Decoder primitive that validates numbers, and fails on all other input.
551
+ */
552
+ Decoder.number = function () {
553
+ return new Decoder(function (json) {
554
+ return typeof json === 'number'
555
+ ? ok(json)
556
+ : err({ message: expectedGot('a number', json) });
557
+ });
558
+ };
559
+ /**
560
+ * Decoder primitive that validates booleans, and fails on all other input.
561
+ */
562
+ Decoder.boolean = function () {
563
+ return new Decoder(function (json) {
564
+ return typeof json === 'boolean'
565
+ ? ok(json)
566
+ : err({ message: expectedGot('a boolean', json) });
567
+ });
568
+ };
569
+ Decoder.constant = function (value) {
570
+ return new Decoder(function (json) {
571
+ return isEqual(json, value)
572
+ ? ok(value)
573
+ : err({ message: "expected " + JSON.stringify(value) + ", got " + JSON.stringify(json) });
574
+ });
575
+ };
576
+ Decoder.object = function (decoders) {
577
+ return new Decoder(function (json) {
578
+ if (isJsonObject(json) && decoders) {
579
+ var obj = {};
580
+ for (var key in decoders) {
581
+ if (decoders.hasOwnProperty(key)) {
582
+ var r = decoders[key].decode(json[key]);
583
+ if (r.ok === true) {
584
+ // tslint:disable-next-line:strict-type-predicates
585
+ if (r.result !== undefined) {
586
+ obj[key] = r.result;
587
+ }
588
+ }
589
+ else if (json[key] === undefined) {
590
+ return err({ message: "the key '" + key + "' is required but was not present" });
591
+ }
592
+ else {
593
+ return err(prependAt("." + key, r.error));
594
+ }
595
+ }
596
+ }
597
+ return ok(obj);
598
+ }
599
+ else if (isJsonObject(json)) {
600
+ return ok(json);
601
+ }
602
+ else {
603
+ return err({ message: expectedGot('an object', json) });
604
+ }
605
+ });
606
+ };
607
+ Decoder.array = function (decoder) {
608
+ return new Decoder(function (json) {
609
+ if (isJsonArray(json) && decoder) {
610
+ var decodeValue_1 = function (v, i) {
611
+ return mapError(function (err$$1) { return prependAt("[" + i + "]", err$$1); }, decoder.decode(v));
612
+ };
613
+ return json.reduce(function (acc, v, i) {
614
+ return map2(function (arr, result) { return arr.concat([result]); }, acc, decodeValue_1(v, i));
615
+ }, ok([]));
616
+ }
617
+ else if (isJsonArray(json)) {
618
+ return ok(json);
619
+ }
620
+ else {
621
+ return err({ message: expectedGot('an array', json) });
622
+ }
623
+ });
624
+ };
625
+ Decoder.tuple = function (decoders) {
626
+ return new Decoder(function (json) {
627
+ if (isJsonArray(json)) {
628
+ if (json.length !== decoders.length) {
629
+ return err({
630
+ message: "expected a tuple of length " + decoders.length + ", got one of length " + json.length
631
+ });
632
+ }
633
+ var result = [];
634
+ for (var i = 0; i < decoders.length; i++) {
635
+ var nth = decoders[i].decode(json[i]);
636
+ if (nth.ok) {
637
+ result[i] = nth.result;
638
+ }
639
+ else {
640
+ return err(prependAt("[" + i + "]", nth.error));
641
+ }
642
+ }
643
+ return ok(result);
644
+ }
645
+ else {
646
+ return err({ message: expectedGot("a tuple of length " + decoders.length, json) });
647
+ }
648
+ });
649
+ };
650
+ Decoder.union = function (ad, bd) {
651
+ var decoders = [];
652
+ for (var _i = 2; _i < arguments.length; _i++) {
653
+ decoders[_i - 2] = arguments[_i];
654
+ }
655
+ return Decoder.oneOf.apply(Decoder, [ad, bd].concat(decoders));
656
+ };
657
+ Decoder.intersection = function (ad, bd) {
658
+ var ds = [];
659
+ for (var _i = 2; _i < arguments.length; _i++) {
660
+ ds[_i - 2] = arguments[_i];
661
+ }
662
+ return new Decoder(function (json) {
663
+ return [ad, bd].concat(ds).reduce(function (acc, decoder) { return map2(Object.assign, acc, decoder.decode(json)); }, ok({}));
664
+ });
665
+ };
666
+ /**
667
+ * Escape hatch to bypass validation. Always succeeds and types the result as
668
+ * `any`. Useful for defining decoders incrementally, particularly for
669
+ * complex objects.
670
+ *
671
+ * Example:
672
+ * ```
673
+ * interface User {
674
+ * name: string;
675
+ * complexUserData: ComplexType;
676
+ * }
677
+ *
678
+ * const userDecoder: Decoder<User> = object({
679
+ * name: string(),
680
+ * complexUserData: anyJson()
681
+ * });
682
+ * ```
683
+ */
684
+ Decoder.anyJson = function () { return new Decoder(function (json) { return ok(json); }); };
685
+ /**
686
+ * Decoder identity function which always succeeds and types the result as
687
+ * `unknown`.
688
+ */
689
+ Decoder.unknownJson = function () {
690
+ return new Decoder(function (json) { return ok(json); });
691
+ };
692
+ /**
693
+ * Decoder for json objects where the keys are unknown strings, but the values
694
+ * should all be of the same type.
695
+ *
696
+ * Example:
697
+ * ```
698
+ * dict(number()).run({chocolate: 12, vanilla: 10, mint: 37});
699
+ * // => {ok: true, result: {chocolate: 12, vanilla: 10, mint: 37}}
700
+ * ```
701
+ */
702
+ Decoder.dict = function (decoder) {
703
+ return new Decoder(function (json) {
704
+ if (isJsonObject(json)) {
705
+ var obj = {};
706
+ for (var key in json) {
707
+ if (json.hasOwnProperty(key)) {
708
+ var r = decoder.decode(json[key]);
709
+ if (r.ok === true) {
710
+ obj[key] = r.result;
711
+ }
712
+ else {
713
+ return err(prependAt("." + key, r.error));
714
+ }
715
+ }
716
+ }
717
+ return ok(obj);
718
+ }
719
+ else {
720
+ return err({ message: expectedGot('an object', json) });
721
+ }
722
+ });
723
+ };
724
+ /**
725
+ * Decoder for values that may be `undefined`. This is primarily helpful for
726
+ * decoding interfaces with optional fields.
727
+ *
728
+ * Example:
729
+ * ```
730
+ * interface User {
731
+ * id: number;
732
+ * isOwner?: boolean;
733
+ * }
734
+ *
735
+ * const decoder: Decoder<User> = object({
736
+ * id: number(),
737
+ * isOwner: optional(boolean())
738
+ * });
739
+ * ```
740
+ */
741
+ Decoder.optional = function (decoder) {
742
+ return new Decoder(function (json) { return (json === undefined || json === null ? ok(undefined) : decoder.decode(json)); });
743
+ };
744
+ /**
745
+ * Decoder that attempts to run each decoder in `decoders` and either succeeds
746
+ * with the first successful decoder, or fails after all decoders have failed.
747
+ *
748
+ * Note that `oneOf` expects the decoders to all have the same return type,
749
+ * while `union` creates a decoder for the union type of all the input
750
+ * decoders.
751
+ *
752
+ * Examples:
753
+ * ```
754
+ * oneOf(string(), number().map(String))
755
+ * oneOf(constant('start'), constant('stop'), succeed('unknown'))
756
+ * ```
757
+ */
758
+ Decoder.oneOf = function () {
759
+ var decoders = [];
760
+ for (var _i = 0; _i < arguments.length; _i++) {
761
+ decoders[_i] = arguments[_i];
762
+ }
763
+ return new Decoder(function (json) {
764
+ var errors = [];
765
+ for (var i = 0; i < decoders.length; i++) {
766
+ var r = decoders[i].decode(json);
767
+ if (r.ok === true) {
768
+ return r;
769
+ }
770
+ else {
771
+ errors[i] = r.error;
772
+ }
773
+ }
774
+ var errorsList = errors
775
+ .map(function (error) { return "at error" + (error.at || '') + ": " + error.message; })
776
+ .join('", "');
777
+ return err({
778
+ message: "expected a value matching one of the decoders, got the errors [\"" + errorsList + "\"]"
779
+ });
780
+ });
781
+ };
782
+ /**
783
+ * Decoder that always succeeds with either the decoded value, or a fallback
784
+ * default value.
785
+ */
786
+ Decoder.withDefault = function (defaultValue, decoder) {
787
+ return new Decoder(function (json) {
788
+ return ok(withDefault(defaultValue, decoder.decode(json)));
789
+ });
790
+ };
791
+ /**
792
+ * Decoder that pulls a specific field out of a json structure, instead of
793
+ * decoding and returning the full structure. The `paths` array describes the
794
+ * object keys and array indices to traverse, so that values can be pulled out
795
+ * of a nested structure.
796
+ *
797
+ * Example:
798
+ * ```
799
+ * const decoder = valueAt(['a', 'b', 0], string());
800
+ *
801
+ * decoder.run({a: {b: ['surprise!']}})
802
+ * // => {ok: true, result: 'surprise!'}
803
+ *
804
+ * decoder.run({a: {x: 'cats'}})
805
+ * // => {ok: false, error: {... at: 'input.a.b[0]' message: 'path does not exist'}}
806
+ * ```
807
+ *
808
+ * Note that the `decoder` is ran on the value found at the last key in the
809
+ * path, even if the last key is not found. This allows the `optional`
810
+ * decoder to succeed when appropriate.
811
+ * ```
812
+ * const optionalDecoder = valueAt(['a', 'b', 'c'], optional(string()));
813
+ *
814
+ * optionalDecoder.run({a: {b: {c: 'surprise!'}}})
815
+ * // => {ok: true, result: 'surprise!'}
816
+ *
817
+ * optionalDecoder.run({a: {b: 'cats'}})
818
+ * // => {ok: false, error: {... at: 'input.a.b.c' message: 'expected an object, got "cats"'}
819
+ *
820
+ * optionalDecoder.run({a: {b: {z: 1}}})
821
+ * // => {ok: true, result: undefined}
822
+ * ```
823
+ */
824
+ Decoder.valueAt = function (paths, decoder) {
825
+ return new Decoder(function (json) {
826
+ var jsonAtPath = json;
827
+ for (var i = 0; i < paths.length; i++) {
828
+ if (jsonAtPath === undefined) {
829
+ return err({
830
+ at: printPath(paths.slice(0, i + 1)),
831
+ message: 'path does not exist'
832
+ });
833
+ }
834
+ else if (typeof paths[i] === 'string' && !isJsonObject(jsonAtPath)) {
835
+ return err({
836
+ at: printPath(paths.slice(0, i + 1)),
837
+ message: expectedGot('an object', jsonAtPath)
838
+ });
839
+ }
840
+ else if (typeof paths[i] === 'number' && !isJsonArray(jsonAtPath)) {
841
+ return err({
842
+ at: printPath(paths.slice(0, i + 1)),
843
+ message: expectedGot('an array', jsonAtPath)
844
+ });
845
+ }
846
+ else {
847
+ jsonAtPath = jsonAtPath[paths[i]];
848
+ }
849
+ }
850
+ return mapError(function (error) {
851
+ return jsonAtPath === undefined
852
+ ? { at: printPath(paths), message: 'path does not exist' }
853
+ : prependAt(printPath(paths), error);
854
+ }, decoder.decode(jsonAtPath));
855
+ });
856
+ };
857
+ /**
858
+ * Decoder that ignores the input json and always succeeds with `fixedValue`.
859
+ */
860
+ Decoder.succeed = function (fixedValue) {
861
+ return new Decoder(function (json) { return ok(fixedValue); });
862
+ };
863
+ /**
864
+ * Decoder that ignores the input json and always fails with `errorMessage`.
865
+ */
866
+ Decoder.fail = function (errorMessage) {
867
+ return new Decoder(function (json) { return err({ message: errorMessage }); });
868
+ };
869
+ /**
870
+ * Decoder that allows for validating recursive data structures. Unlike with
871
+ * functions, decoders assigned to variables can't reference themselves
872
+ * before they are fully defined. We can avoid prematurely referencing the
873
+ * decoder by wrapping it in a function that won't be called until use, at
874
+ * which point the decoder has been defined.
875
+ *
876
+ * Example:
877
+ * ```
878
+ * interface Comment {
879
+ * msg: string;
880
+ * replies: Comment[];
881
+ * }
882
+ *
883
+ * const decoder: Decoder<Comment> = object({
884
+ * msg: string(),
885
+ * replies: lazy(() => array(decoder))
886
+ * });
887
+ * ```
888
+ */
889
+ Decoder.lazy = function (mkDecoder) {
890
+ return new Decoder(function (json) { return mkDecoder().decode(json); });
891
+ };
892
+ return Decoder;
893
+ }());
915
894
 
916
- /* tslint:disable:variable-name */
917
- /** See `Decoder.string` */
918
- var string = Decoder.string;
919
- /** See `Decoder.number` */
920
- var number = Decoder.number;
921
- /** See `Decoder.boolean` */
922
- Decoder.boolean;
923
- /** See `Decoder.anyJson` */
924
- var anyJson = Decoder.anyJson;
925
- /** See `Decoder.unknownJson` */
926
- Decoder.unknownJson;
927
- /** See `Decoder.constant` */
928
- var constant = Decoder.constant;
929
- /** See `Decoder.object` */
930
- var object = Decoder.object;
931
- /** See `Decoder.array` */
932
- var array = Decoder.array;
933
- /** See `Decoder.tuple` */
934
- Decoder.tuple;
935
- /** See `Decoder.dict` */
936
- Decoder.dict;
937
- /** See `Decoder.optional` */
938
- var optional = Decoder.optional;
939
- /** See `Decoder.oneOf` */
940
- var oneOf = Decoder.oneOf;
941
- /** See `Decoder.union` */
942
- Decoder.union;
943
- /** See `Decoder.intersection` */
944
- Decoder.intersection;
945
- /** See `Decoder.withDefault` */
946
- Decoder.withDefault;
947
- /** See `Decoder.valueAt` */
948
- Decoder.valueAt;
949
- /** See `Decoder.succeed` */
950
- Decoder.succeed;
951
- /** See `Decoder.fail` */
952
- Decoder.fail;
953
- /** See `Decoder.lazy` */
954
- Decoder.lazy;
895
+ /* tslint:disable:variable-name */
896
+ /** See `Decoder.string` */
897
+ var string = Decoder.string;
898
+ /** See `Decoder.number` */
899
+ var number = Decoder.number;
900
+ /** See `Decoder.boolean` */
901
+ Decoder.boolean;
902
+ /** See `Decoder.anyJson` */
903
+ var anyJson = Decoder.anyJson;
904
+ /** See `Decoder.unknownJson` */
905
+ Decoder.unknownJson;
906
+ /** See `Decoder.constant` */
907
+ var constant = Decoder.constant;
908
+ /** See `Decoder.object` */
909
+ var object = Decoder.object;
910
+ /** See `Decoder.array` */
911
+ var array = Decoder.array;
912
+ /** See `Decoder.tuple` */
913
+ Decoder.tuple;
914
+ /** See `Decoder.dict` */
915
+ Decoder.dict;
916
+ /** See `Decoder.optional` */
917
+ var optional = Decoder.optional;
918
+ /** See `Decoder.oneOf` */
919
+ var oneOf = Decoder.oneOf;
920
+ /** See `Decoder.union` */
921
+ Decoder.union;
922
+ /** See `Decoder.intersection` */
923
+ Decoder.intersection;
924
+ /** See `Decoder.withDefault` */
925
+ Decoder.withDefault;
926
+ /** See `Decoder.valueAt` */
927
+ Decoder.valueAt;
928
+ /** See `Decoder.succeed` */
929
+ Decoder.succeed;
930
+ /** See `Decoder.fail` */
931
+ Decoder.fail;
932
+ /** See `Decoder.lazy` */
933
+ Decoder.lazy;
955
934
 
956
- const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
957
- const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
958
- const searchTypeDecoder = object({
959
- name: nonEmptyStringDecoder,
960
- displayName: optional(nonEmptyStringDecoder)
961
- });
962
- const providerData = object({
963
- id: nonEmptyStringDecoder,
964
- interopId: nonEmptyStringDecoder,
965
- name: nonEmptyStringDecoder,
966
- appName: optional(nonEmptyStringDecoder),
967
- types: optional(array(searchTypeDecoder))
968
- });
969
- const providerLimitsDecoder = object({
970
- maxResults: optional(nonNegativeNumberDecoder),
971
- maxResultsPerType: optional(nonNegativeNumberDecoder)
972
- });
973
- const queryConfigDecoder = object({
974
- search: nonEmptyStringDecoder,
975
- providers: optional(array(providerData)),
976
- types: optional(array(searchTypeDecoder)),
977
- providerLimits: optional(providerLimitsDecoder)
978
- });
979
- const providerRegistrationConfig = object({
980
- name: nonEmptyStringDecoder,
981
- types: optional(array(searchTypeDecoder))
982
- });
983
- const operationDecoder = oneOf(constant("cancel"), constant("info"), constant("search"));
984
- const queryStatusDecoder = oneOf(constant("done"), constant("in-progress"), constant("error"));
985
- const searchCancelRequestDecoder = object({
986
- id: nonEmptyStringDecoder
987
- });
988
- const mainActionDecoder = object({
989
- method: nonEmptyStringDecoder,
990
- target: optional(oneOf(object({ instance: nonEmptyStringDecoder }), constant("all"))),
991
- params: optional(anyJson())
992
- });
993
- const secondaryActionDecoder = object({
994
- name: nonEmptyStringDecoder,
995
- method: nonEmptyStringDecoder,
996
- target: optional(oneOf(object({ instance: nonEmptyStringDecoder }), constant("all"))),
997
- params: optional(anyJson())
998
- });
999
- const queryResultDecoder = object({
1000
- type: searchTypeDecoder,
1001
- id: optional(nonEmptyStringDecoder),
1002
- displayName: optional(nonEmptyStringDecoder),
1003
- description: optional(nonEmptyStringDecoder),
1004
- iconURL: optional(nonEmptyStringDecoder),
1005
- metadata: optional(anyJson()),
1006
- action: optional(mainActionDecoder),
1007
- secondaryActions: optional(array(secondaryActionDecoder))
1008
- });
1009
- const legacySearchResultItemDecoder = object({
1010
- type: string(),
1011
- category: optional(string()),
1012
- id: optional(string()),
1013
- displayName: optional(string()),
1014
- description: optional(string()),
1015
- iconURL: optional(string()),
1016
- action: optional(mainActionDecoder)
1017
- });
1018
- const protocolSearchResultsBatchDecoder = object({
1019
- items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
1020
- provider: optional(providerData),
1021
- queryId: nonEmptyStringDecoder,
1022
- status: constant("in-progress")
1023
- });
1024
- const protocolSearchCompletedDecoder = object({
1025
- items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
1026
- queryId: nonEmptyStringDecoder,
1027
- status: constant("done")
1028
- });
1029
- const protocolProviderErrorDecoder = object({
1030
- items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
1031
- provider: optional(providerData),
1032
- queryId: nonEmptyStringDecoder,
1033
- errorMessage: nonEmptyStringDecoder,
1034
- status: constant("error")
1035
- });
935
+ const nonEmptyStringDecoder = string().where((s) => s.length > 0, "Expected a non-empty string");
936
+ const nonNegativeNumberDecoder = number().where((num) => num >= 0, "Expected a non-negative number");
937
+ const searchTypeDecoder = object({
938
+ name: nonEmptyStringDecoder,
939
+ displayName: optional(nonEmptyStringDecoder)
940
+ });
941
+ const providerData = object({
942
+ id: nonEmptyStringDecoder,
943
+ interopId: nonEmptyStringDecoder,
944
+ name: nonEmptyStringDecoder,
945
+ appName: optional(nonEmptyStringDecoder),
946
+ types: optional(array(searchTypeDecoder))
947
+ });
948
+ const providerLimitsDecoder = object({
949
+ maxResults: optional(nonNegativeNumberDecoder),
950
+ maxResultsPerType: optional(nonNegativeNumberDecoder)
951
+ });
952
+ const queryConfigDecoder = object({
953
+ search: nonEmptyStringDecoder,
954
+ providers: optional(array(providerData)),
955
+ types: optional(array(searchTypeDecoder)),
956
+ providerLimits: optional(providerLimitsDecoder)
957
+ });
958
+ const providerRegistrationConfig = object({
959
+ name: nonEmptyStringDecoder,
960
+ types: optional(array(searchTypeDecoder))
961
+ });
962
+ const operationDecoder = oneOf(constant("cancel"), constant("info"), constant("search"));
963
+ const queryStatusDecoder = oneOf(constant("done"), constant("in-progress"), constant("error"));
964
+ const searchCancelRequestDecoder = object({
965
+ id: nonEmptyStringDecoder
966
+ });
967
+ const mainActionDecoder = object({
968
+ method: nonEmptyStringDecoder,
969
+ target: optional(oneOf(object({ instance: nonEmptyStringDecoder }), constant("all"))),
970
+ params: optional(anyJson())
971
+ });
972
+ const secondaryActionDecoder = object({
973
+ name: nonEmptyStringDecoder,
974
+ method: nonEmptyStringDecoder,
975
+ target: optional(oneOf(object({ instance: nonEmptyStringDecoder }), constant("all"))),
976
+ params: optional(anyJson())
977
+ });
978
+ const queryResultDecoder = object({
979
+ type: searchTypeDecoder,
980
+ id: optional(nonEmptyStringDecoder),
981
+ displayName: optional(nonEmptyStringDecoder),
982
+ description: optional(nonEmptyStringDecoder),
983
+ iconURL: optional(nonEmptyStringDecoder),
984
+ metadata: optional(anyJson()),
985
+ action: optional(mainActionDecoder),
986
+ secondaryActions: optional(array(secondaryActionDecoder))
987
+ });
988
+ const legacySearchResultItemDecoder = object({
989
+ type: string(),
990
+ category: optional(string()),
991
+ id: optional(string()),
992
+ displayName: optional(string()),
993
+ description: optional(string()),
994
+ iconURL: optional(string()),
995
+ action: optional(mainActionDecoder)
996
+ });
997
+ const protocolSearchResultsBatchDecoder = object({
998
+ items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
999
+ provider: optional(providerData),
1000
+ queryId: nonEmptyStringDecoder,
1001
+ status: constant("in-progress")
1002
+ });
1003
+ const protocolSearchCompletedDecoder = object({
1004
+ items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
1005
+ queryId: nonEmptyStringDecoder,
1006
+ status: constant("done")
1007
+ });
1008
+ const protocolProviderErrorDecoder = object({
1009
+ items: array(oneOf(queryResultDecoder, legacySearchResultItemDecoder)),
1010
+ provider: optional(providerData),
1011
+ queryId: nonEmptyStringDecoder,
1012
+ errorMessage: nonEmptyStringDecoder,
1013
+ status: constant("error")
1014
+ });
1036
1015
 
1037
- class ClientController {
1038
- constructor(logger, glueController, modelFactory) {
1039
- this.logger = logger;
1040
- this.glueController = glueController;
1041
- this.modelFactory = modelFactory;
1042
- this.registry = lib();
1043
- this.activeQueryLookup = {};
1044
- this.queryIdToMasterIdLookup = {};
1045
- this.pendingDebounce = [];
1046
- this.debounceMS = 0;
1047
- }
1048
- setDebounceMS(data) {
1049
- this.logger.info(`[${data.commandId}] Setting the debounceMS to: ${data.milliseconds}`);
1050
- this.debounceMS = data.milliseconds;
1051
- this.logger.info(`[${data.commandId}] debounceMS set to: ${data.milliseconds}`);
1052
- }
1053
- getDebounceMS(data) {
1054
- this.logger.info(`[${data.commandId}] Getting the debounceMS`);
1055
- return this.debounceMS;
1056
- }
1057
- query(data, skipDebounce) {
1058
- return __awaiter(this, void 0, void 0, function* () {
1059
- if (this.debounceMS && !skipDebounce) {
1060
- return this.debounceQuery(data);
1061
- }
1062
- yield this.glueController.registerMainClientMethod(this.handleProviderCall.bind(this));
1063
- const { queryConfig, commandId } = data;
1064
- this.logger.info(`[${commandId}] Initiating a query request`);
1065
- let allProvidersInfo = yield this.glueController.getAllProvidersInfo();
1066
- this.logger.trace(`[${commandId}] Got all available providers: ${JSON.stringify(allProvidersInfo)}`);
1067
- if (queryConfig.providers) {
1068
- this.logger.info(`[${commandId}] Filtering providers by explicitly allowed providers.`);
1069
- allProvidersInfo = this.filterProvidersByAllowList(allProvidersInfo, queryConfig.providers);
1070
- }
1071
- if (queryConfig.types) {
1072
- this.logger.info(`[${commandId}] Filtering providers by explicitly allowed types.`);
1073
- allProvidersInfo = this.filterProvidersByAllowedTypes(allProvidersInfo, queryConfig.types);
1074
- }
1075
- if (!allProvidersInfo.length) {
1076
- this.logger.warn(`[${commandId}] There are no providers that can handle the query for ${data.queryConfig.search}`);
1077
- }
1078
- this.logger.info(`[${commandId}] Sending query request to providers: ${JSON.stringify(allProvidersInfo)}`);
1079
- const allQueryResponses = yield this.glueController.sendQueryRequest(queryConfig, allProvidersInfo);
1080
- this.logger.info(`[${commandId}] Received responses from the providers: ${JSON.stringify(allQueryResponses)}`);
1081
- const masterQueryId = this.generateMasterQueryId();
1082
- const queryModel = this.modelFactory.buildClientQueryModel(masterQueryId, this);
1083
- this.logger.info(`[${commandId}] The query is in progress with master id: ${masterQueryId}`);
1084
- this.activeQueryLookup[masterQueryId] = {
1085
- servers: allQueryResponses,
1086
- model: queryModel
1087
- };
1088
- allQueryResponses.forEach((response) => {
1089
- this.queryIdToMasterIdLookup[response.queryId] = masterQueryId;
1090
- });
1091
- if (!allQueryResponses.length) {
1092
- setTimeout(() => {
1093
- this.registry.execute(`on-query-completed-${masterQueryId}`);
1094
- this.cleanUpQuery(masterQueryId);
1095
- }, 0);
1096
- }
1097
- return queryModel.exposeFacade();
1098
- });
1099
- }
1100
- cancelQuery(masterQueryId, commandId) {
1101
- return __awaiter(this, void 0, void 0, function* () {
1102
- const activeQuery = this.activeQueryLookup[masterQueryId];
1103
- if (!activeQuery) {
1104
- throw new Error(`[${commandId}] Cannot cancel query: ${masterQueryId}, because this query does not exist`);
1105
- }
1106
- const interopIds = activeQuery.servers;
1107
- this.logger.info(`[${commandId}] Sending cancel query requests`);
1108
- yield Promise.all(interopIds.map((serverId) => {
1109
- this.logger.trace(`[${commandId}] Sending cancel query request to ${serverId.interopId} with queryId: ${serverId.queryId}`);
1110
- return this.glueController.sendQueryCancelRequest({ id: serverId.queryId }, { instance: serverId.interopId });
1111
- }));
1112
- this.logger.info(`[${commandId}] The query was cancelled`);
1113
- });
1114
- }
1115
- processClientOnResults(data) {
1116
- return this.registry.add(`on-query-results-${data.masterQueryId}`, data.callback);
1117
- }
1118
- processClientOnCompleted(data) {
1119
- return this.registry.add(`on-query-completed-${data.masterQueryId}`, data.callback);
1120
- }
1121
- processClientOnError(data) {
1122
- return this.registry.add(`on-query-error-${data.masterQueryId}`, data.callback);
1123
- }
1124
- handleProviderCall(args) {
1125
- return __awaiter(this, void 0, void 0, function* () {
1126
- const { status } = args;
1127
- const validatedOperation = queryStatusDecoder.runWithException(status);
1128
- const commandId = nanoid(10);
1129
- switch (validatedOperation) {
1130
- case SEARCH_QUERY_STATUSES.done:
1131
- return this.handleQueryCompleted({ completedConfig: args, commandId });
1132
- case SEARCH_QUERY_STATUSES.inProgress:
1133
- return this.handleQueryResults({ resultsBatch: args, commandId });
1134
- case SEARCH_QUERY_STATUSES.error:
1135
- return this.handleQueryError({ error: args, commandId });
1136
- default:
1137
- throw new Error(`Unrecognized status: ${status}`);
1138
- }
1139
- });
1140
- }
1141
- handleQueryResults(data) {
1142
- var _a, _b;
1143
- const { resultsBatch, commandId } = data;
1144
- this.logger.trace(`[${commandId}] Processing a results batch from provider: ${(_a = resultsBatch.provider) === null || _a === void 0 ? void 0 : _a.name} with id: ${(_b = resultsBatch.provider) === null || _b === void 0 ? void 0 : _b.id}`);
1145
- const verifiedResultsBatch = protocolSearchResultsBatchDecoder.runWithException(resultsBatch);
1146
- const masterQueryId = this.queryIdToMasterIdLookup[verifiedResultsBatch.queryId];
1147
- if (!masterQueryId) {
1148
- this.logger.warn(`[${commandId}] Received results for an unknown query. Provider ${JSON.stringify(verifiedResultsBatch.provider)}, items: ${JSON.stringify(verifiedResultsBatch.items)}`);
1149
- return;
1150
- }
1151
- this.logger.trace(`[${commandId}] The results batch is validated, forwarding to the callbacks`);
1152
- const translatedResults = this.checkTransformLegacyResults(verifiedResultsBatch.items);
1153
- const results = {
1154
- provider: verifiedResultsBatch.provider,
1155
- results: translatedResults
1156
- };
1157
- this.registry.execute(`on-query-results-${masterQueryId}`, results);
1158
- }
1159
- handleQueryCompleted(data) {
1160
- const { completedConfig, commandId } = data;
1161
- this.logger.trace(`[${commandId}] Processing a query completed message from query id: ${completedConfig.queryId}`);
1162
- const verifiedCompleteConfig = protocolSearchCompletedDecoder.runWithException(completedConfig);
1163
- const masterQueryId = this.queryIdToMasterIdLookup[verifiedCompleteConfig.queryId];
1164
- if (!masterQueryId) {
1165
- this.logger.warn(`[${commandId}] Received completed message for an unknown query. Provider query id: ${JSON.stringify(verifiedCompleteConfig.queryId)}`);
1166
- return;
1167
- }
1168
- if (verifiedCompleteConfig.items.length) {
1169
- const translatedResults = this.checkTransformLegacyResults(verifiedCompleteConfig.items);
1170
- const results = {
1171
- results: translatedResults
1172
- };
1173
- this.registry.execute(`on-query-results-${masterQueryId}`, results);
1174
- }
1175
- delete this.queryIdToMasterIdLookup[verifiedCompleteConfig.queryId];
1176
- const activeQuery = this.activeQueryLookup[masterQueryId];
1177
- activeQuery.servers = activeQuery.servers.filter((server) => server.queryId !== verifiedCompleteConfig.queryId);
1178
- if (activeQuery.servers.length) {
1179
- this.logger.trace(`[${commandId}] Waiting for more providers to complete`);
1180
- return;
1181
- }
1182
- this.logger.trace(`[${commandId}] All providers are done, marking this query as completed`);
1183
- this.registry.execute(`on-query-completed-${masterQueryId}`);
1184
- this.cleanUpQuery(masterQueryId);
1185
- }
1186
- handleQueryError(data) {
1187
- const { error, commandId } = data;
1188
- this.logger.trace(`[${commandId}] Processing an error message from query: ${error.queryId}`);
1189
- const validatedError = protocolProviderErrorDecoder.runWithException(error);
1190
- const masterQueryId = this.queryIdToMasterIdLookup[validatedError.queryId];
1191
- if (!masterQueryId) {
1192
- this.logger.warn(`[${commandId}] Received error message for an unknown query. Provider query id: ${JSON.stringify(validatedError.queryId)} and message: ${JSON.stringify(validatedError.errorMessage)}`);
1193
- return;
1194
- }
1195
- const queryError = {
1196
- error: validatedError.errorMessage,
1197
- provider: validatedError.provider
1198
- };
1199
- this.registry.execute(`on-query-error-${masterQueryId}`, queryError);
1200
- }
1201
- filterProvidersByAllowList(servers, allowed) {
1202
- const allowedLookup = allowed.reduce((lookup, allowedEntry) => {
1203
- lookup[allowedEntry.id] = true;
1204
- return lookup;
1205
- }, {});
1206
- return servers.filter((server) => {
1207
- const serverProviders = server.info.providers;
1208
- return serverProviders.some((provider) => allowedLookup[provider.id]);
1209
- });
1210
- }
1211
- filterProvidersByAllowedTypes(servers, allowed) {
1212
- const allowedLookup = allowed.reduce((lookup, allowedEntry) => {
1213
- lookup[allowedEntry.name] = true;
1214
- return lookup;
1215
- }, {});
1216
- return servers.filter((server) => {
1217
- const allTypes = server.info.supportedTypes;
1218
- if (allTypes.some((searchType) => searchType === "*")) {
1219
- return true;
1220
- }
1221
- if (!allTypes || !allTypes.length) {
1222
- return true;
1223
- }
1224
- return allTypes.some((supportedType) => allowedLookup[supportedType]);
1225
- });
1226
- }
1227
- generateMasterQueryId() {
1228
- const queryId = nanoid(10);
1229
- if (this.activeQueryLookup[queryId]) {
1230
- return this.generateMasterQueryId();
1231
- }
1232
- return queryId;
1233
- }
1234
- cleanUpQuery(masterQueryId) {
1235
- this.registry.clearKey(`on-query-results-${masterQueryId}`);
1236
- this.registry.clearKey(`on-query-completed-${masterQueryId}`);
1237
- this.registry.clearKey(`on-query-error-${masterQueryId}`);
1238
- delete this.activeQueryLookup[masterQueryId];
1239
- }
1240
- debounceQuery(data) {
1241
- return new Promise((res, rej) => {
1242
- clearTimeout(this.debounceTimer);
1243
- this.debounceTimer = setTimeout(() => {
1244
- const currentPending = [...this.pendingDebounce];
1245
- this.pendingDebounce = [];
1246
- this.query(data, true)
1247
- .then((query) => currentPending.forEach(({ resolve }) => resolve(query)))
1248
- .catch((error) => currentPending.forEach(({ reject }) => reject(error)));
1249
- }, this.debounceMS);
1250
- this.pendingDebounce.push({ resolve: res, reject: rej });
1251
- });
1252
- }
1253
- checkTransformLegacyResults(items) {
1254
- if (!items.length) {
1255
- return [];
1256
- }
1257
- const sampleItem = items[0];
1258
- if (!sampleItem || typeof sampleItem.type === "object") {
1259
- return items;
1260
- }
1261
- return items.map((item) => {
1262
- return {
1263
- type: { name: item.type, displayName: item.category },
1264
- id: item.id,
1265
- displayName: item.displayName,
1266
- description: item.description,
1267
- iconURL: item.iconURL,
1268
- action: item.action
1269
- };
1270
- });
1271
- }
1272
- }
1016
+ class ClientController {
1017
+ logger;
1018
+ glueController;
1019
+ modelFactory;
1020
+ registry = CallbackRegistryFactory();
1021
+ activeQueryLookup = {};
1022
+ queryIdToMasterIdLookup = {};
1023
+ pendingDebounce = [];
1024
+ debounceTimer;
1025
+ debounceMS = 0;
1026
+ constructor(logger, glueController, modelFactory) {
1027
+ this.logger = logger;
1028
+ this.glueController = glueController;
1029
+ this.modelFactory = modelFactory;
1030
+ }
1031
+ setDebounceMS(data) {
1032
+ this.logger.info(`[${data.commandId}] Setting the debounceMS to: ${data.milliseconds}`);
1033
+ this.debounceMS = data.milliseconds;
1034
+ this.logger.info(`[${data.commandId}] debounceMS set to: ${data.milliseconds}`);
1035
+ }
1036
+ getDebounceMS(data) {
1037
+ this.logger.info(`[${data.commandId}] Getting the debounceMS`);
1038
+ return this.debounceMS;
1039
+ }
1040
+ async query(data, skipDebounce) {
1041
+ if (this.debounceMS && !skipDebounce) {
1042
+ return this.debounceQuery(data);
1043
+ }
1044
+ await this.glueController.registerMainClientMethod(this.handleProviderCall.bind(this));
1045
+ const { queryConfig, commandId } = data;
1046
+ this.logger.info(`[${commandId}] Initiating a query request`);
1047
+ let allProvidersInfo = await this.glueController.getAllProvidersInfo();
1048
+ this.logger.trace(`[${commandId}] Got all available providers: ${JSON.stringify(allProvidersInfo)}`);
1049
+ if (queryConfig.providers) {
1050
+ this.logger.info(`[${commandId}] Filtering providers by explicitly allowed providers.`);
1051
+ allProvidersInfo = this.filterProvidersByAllowList(allProvidersInfo, queryConfig.providers);
1052
+ }
1053
+ if (queryConfig.types) {
1054
+ this.logger.info(`[${commandId}] Filtering providers by explicitly allowed types.`);
1055
+ allProvidersInfo = this.filterProvidersByAllowedTypes(allProvidersInfo, queryConfig.types);
1056
+ }
1057
+ if (!allProvidersInfo.length) {
1058
+ this.logger.warn(`[${commandId}] There are no providers that can handle the query for ${data.queryConfig.search}`);
1059
+ }
1060
+ this.logger.info(`[${commandId}] Sending query request to providers: ${JSON.stringify(allProvidersInfo)}`);
1061
+ const allQueryResponses = await this.glueController.sendQueryRequest(queryConfig, allProvidersInfo);
1062
+ this.logger.info(`[${commandId}] Received responses from the providers: ${JSON.stringify(allQueryResponses)}`);
1063
+ const masterQueryId = this.generateMasterQueryId();
1064
+ const queryModel = this.modelFactory.buildClientQueryModel(masterQueryId, this);
1065
+ this.logger.info(`[${commandId}] The query is in progress with master id: ${masterQueryId}`);
1066
+ this.activeQueryLookup[masterQueryId] = {
1067
+ servers: allQueryResponses,
1068
+ model: queryModel
1069
+ };
1070
+ allQueryResponses.forEach((response) => {
1071
+ this.queryIdToMasterIdLookup[response.queryId] = masterQueryId;
1072
+ });
1073
+ if (!allQueryResponses.length) {
1074
+ setTimeout(() => {
1075
+ this.registry.execute(`on-query-completed-${masterQueryId}`);
1076
+ this.cleanUpQuery(masterQueryId);
1077
+ }, 0);
1078
+ }
1079
+ return queryModel.exposeFacade();
1080
+ }
1081
+ async cancelQuery(masterQueryId, commandId) {
1082
+ const activeQuery = this.activeQueryLookup[masterQueryId];
1083
+ if (!activeQuery) {
1084
+ throw new Error(`[${commandId}] Cannot cancel query: ${masterQueryId}, because this query does not exist`);
1085
+ }
1086
+ const interopIds = activeQuery.servers;
1087
+ this.logger.info(`[${commandId}] Sending cancel query requests`);
1088
+ await Promise.all(interopIds.map((serverId) => {
1089
+ this.logger.trace(`[${commandId}] Sending cancel query request to ${serverId.interopId} with queryId: ${serverId.queryId}`);
1090
+ return this.glueController.sendQueryCancelRequest({ id: serverId.queryId }, { instance: serverId.interopId });
1091
+ }));
1092
+ this.logger.info(`[${commandId}] The query was cancelled`);
1093
+ }
1094
+ processClientOnResults(data) {
1095
+ return this.registry.add(`on-query-results-${data.masterQueryId}`, data.callback);
1096
+ }
1097
+ processClientOnCompleted(data) {
1098
+ return this.registry.add(`on-query-completed-${data.masterQueryId}`, data.callback);
1099
+ }
1100
+ processClientOnError(data) {
1101
+ return this.registry.add(`on-query-error-${data.masterQueryId}`, data.callback);
1102
+ }
1103
+ async handleProviderCall(args) {
1104
+ const { status } = args;
1105
+ const validatedOperation = queryStatusDecoder.runWithException(status);
1106
+ const commandId = nanoid(10);
1107
+ switch (validatedOperation) {
1108
+ case SEARCH_QUERY_STATUSES.done:
1109
+ return this.handleQueryCompleted({ completedConfig: args, commandId });
1110
+ case SEARCH_QUERY_STATUSES.inProgress:
1111
+ return this.handleQueryResults({ resultsBatch: args, commandId });
1112
+ case SEARCH_QUERY_STATUSES.error:
1113
+ return this.handleQueryError({ error: args, commandId });
1114
+ default:
1115
+ throw new Error(`Unrecognized status: ${status}`);
1116
+ }
1117
+ }
1118
+ handleQueryResults(data) {
1119
+ const { resultsBatch, commandId } = data;
1120
+ this.logger.trace(`[${commandId}] Processing a results batch from provider: ${resultsBatch.provider?.name} with id: ${resultsBatch.provider?.id}`);
1121
+ const verifiedResultsBatch = protocolSearchResultsBatchDecoder.runWithException(resultsBatch);
1122
+ const masterQueryId = this.queryIdToMasterIdLookup[verifiedResultsBatch.queryId];
1123
+ if (!masterQueryId) {
1124
+ this.logger.warn(`[${commandId}] Received results for an unknown query. Provider ${JSON.stringify(verifiedResultsBatch.provider)}, items: ${JSON.stringify(verifiedResultsBatch.items)}`);
1125
+ return;
1126
+ }
1127
+ this.logger.trace(`[${commandId}] The results batch is validated, forwarding to the callbacks`);
1128
+ const translatedResults = this.checkTransformLegacyResults(verifiedResultsBatch.items);
1129
+ const results = {
1130
+ provider: verifiedResultsBatch.provider,
1131
+ results: translatedResults
1132
+ };
1133
+ this.registry.execute(`on-query-results-${masterQueryId}`, results);
1134
+ }
1135
+ handleQueryCompleted(data) {
1136
+ const { completedConfig, commandId } = data;
1137
+ this.logger.trace(`[${commandId}] Processing a query completed message from query id: ${completedConfig.queryId}`);
1138
+ const verifiedCompleteConfig = protocolSearchCompletedDecoder.runWithException(completedConfig);
1139
+ const masterQueryId = this.queryIdToMasterIdLookup[verifiedCompleteConfig.queryId];
1140
+ if (!masterQueryId) {
1141
+ this.logger.warn(`[${commandId}] Received completed message for an unknown query. Provider query id: ${JSON.stringify(verifiedCompleteConfig.queryId)}`);
1142
+ return;
1143
+ }
1144
+ if (verifiedCompleteConfig.items.length) {
1145
+ const translatedResults = this.checkTransformLegacyResults(verifiedCompleteConfig.items);
1146
+ const results = {
1147
+ results: translatedResults
1148
+ };
1149
+ this.registry.execute(`on-query-results-${masterQueryId}`, results);
1150
+ }
1151
+ delete this.queryIdToMasterIdLookup[verifiedCompleteConfig.queryId];
1152
+ const activeQuery = this.activeQueryLookup[masterQueryId];
1153
+ activeQuery.servers = activeQuery.servers.filter((server) => server.queryId !== verifiedCompleteConfig.queryId);
1154
+ if (activeQuery.servers.length) {
1155
+ this.logger.trace(`[${commandId}] Waiting for more providers to complete`);
1156
+ return;
1157
+ }
1158
+ this.logger.trace(`[${commandId}] All providers are done, marking this query as completed`);
1159
+ this.registry.execute(`on-query-completed-${masterQueryId}`);
1160
+ this.cleanUpQuery(masterQueryId);
1161
+ }
1162
+ handleQueryError(data) {
1163
+ const { error, commandId } = data;
1164
+ this.logger.trace(`[${commandId}] Processing an error message from query: ${error.queryId}`);
1165
+ const validatedError = protocolProviderErrorDecoder.runWithException(error);
1166
+ const masterQueryId = this.queryIdToMasterIdLookup[validatedError.queryId];
1167
+ if (!masterQueryId) {
1168
+ this.logger.warn(`[${commandId}] Received error message for an unknown query. Provider query id: ${JSON.stringify(validatedError.queryId)} and message: ${JSON.stringify(validatedError.errorMessage)}`);
1169
+ return;
1170
+ }
1171
+ const queryError = {
1172
+ error: validatedError.errorMessage,
1173
+ provider: validatedError.provider
1174
+ };
1175
+ this.registry.execute(`on-query-error-${masterQueryId}`, queryError);
1176
+ }
1177
+ filterProvidersByAllowList(servers, allowed) {
1178
+ const allowedLookup = allowed.reduce((lookup, allowedEntry) => {
1179
+ lookup[allowedEntry.id] = true;
1180
+ return lookup;
1181
+ }, {});
1182
+ return servers.filter((server) => {
1183
+ const serverProviders = server.info.providers;
1184
+ return serverProviders.some((provider) => allowedLookup[provider.id]);
1185
+ });
1186
+ }
1187
+ filterProvidersByAllowedTypes(servers, allowed) {
1188
+ const allowedLookup = allowed.reduce((lookup, allowedEntry) => {
1189
+ lookup[allowedEntry.name] = true;
1190
+ return lookup;
1191
+ }, {});
1192
+ return servers.filter((server) => {
1193
+ const allTypes = server.info.supportedTypes;
1194
+ if (allTypes.some((searchType) => searchType === "*")) {
1195
+ return true;
1196
+ }
1197
+ if (!allTypes || !allTypes.length) {
1198
+ return true;
1199
+ }
1200
+ return allTypes.some((supportedType) => allowedLookup[supportedType]);
1201
+ });
1202
+ }
1203
+ generateMasterQueryId() {
1204
+ const queryId = nanoid(10);
1205
+ if (this.activeQueryLookup[queryId]) {
1206
+ return this.generateMasterQueryId();
1207
+ }
1208
+ return queryId;
1209
+ }
1210
+ cleanUpQuery(masterQueryId) {
1211
+ this.registry.clearKey(`on-query-results-${masterQueryId}`);
1212
+ this.registry.clearKey(`on-query-completed-${masterQueryId}`);
1213
+ this.registry.clearKey(`on-query-error-${masterQueryId}`);
1214
+ delete this.activeQueryLookup[masterQueryId];
1215
+ }
1216
+ debounceQuery(data) {
1217
+ return new Promise((res, rej) => {
1218
+ clearTimeout(this.debounceTimer);
1219
+ this.debounceTimer = setTimeout(() => {
1220
+ const currentPending = [...this.pendingDebounce];
1221
+ this.pendingDebounce = [];
1222
+ this.query(data, true)
1223
+ .then((query) => currentPending.forEach(({ resolve }) => resolve(query)))
1224
+ .catch((error) => currentPending.forEach(({ reject }) => reject(error)));
1225
+ }, this.debounceMS);
1226
+ this.pendingDebounce.push({ resolve: res, reject: rej });
1227
+ });
1228
+ }
1229
+ checkTransformLegacyResults(items) {
1230
+ if (!items.length) {
1231
+ return [];
1232
+ }
1233
+ const sampleItem = items[0];
1234
+ if (!sampleItem || typeof sampleItem.type === "object") {
1235
+ return items;
1236
+ }
1237
+ return items.map((item) => {
1238
+ return {
1239
+ type: { name: item.type, displayName: item.category },
1240
+ id: item.id,
1241
+ displayName: item.displayName,
1242
+ description: item.description,
1243
+ iconURL: item.iconURL,
1244
+ action: item.action
1245
+ };
1246
+ });
1247
+ }
1248
+ }
1273
1249
 
1274
- const MAIN_PROVIDER_METHOD_NAME = "T42.Search.Provider";
1275
- const MAIN_CLIENT_METHOD_NAME = "T42.Search.Client";
1276
- const SEQUELIZER_INTERVAL_MS = 10;
1277
- const FLUSH_SEQUELIZER_INTERVAL_MS = 10;
1278
- const FLUSH_TIMEOUT_MS = 100;
1279
- const STALE_QUERY_TIMEOUT_MS = 900000;
1250
+ const MAIN_PROVIDER_METHOD_NAME = "T42.Search.Provider";
1251
+ const MAIN_CLIENT_METHOD_NAME = "T42.Search.Client";
1252
+ const SEQUELIZER_INTERVAL_MS = 10;
1253
+ const FLUSH_SEQUELIZER_INTERVAL_MS = 10;
1254
+ const FLUSH_TIMEOUT_MS = 100;
1255
+ const STALE_QUERY_TIMEOUT_MS = 900000;
1280
1256
 
1281
- class GlueController {
1282
- constructor(glue) {
1283
- this.glue = glue;
1284
- }
1285
- get myAppName() {
1286
- return this.glue.interop.instance.applicationName;
1287
- }
1288
- get myInteropId() {
1289
- return this.glue.interop.instance.instance;
1290
- }
1291
- registerMainProviderMethod(handler) {
1292
- return __awaiter(this, void 0, void 0, function* () {
1293
- const mainMethodStatus = this.checkMyMethodExists(MAIN_PROVIDER_METHOD_NAME);
1294
- if (mainMethodStatus.exists) {
1295
- return;
1296
- }
1297
- yield this.glue.interop.register(MAIN_PROVIDER_METHOD_NAME, handler);
1298
- });
1299
- }
1300
- registerMainClientMethod(handler) {
1301
- return __awaiter(this, void 0, void 0, function* () {
1302
- const mainMethodStatus = this.checkMyMethodExists(MAIN_CLIENT_METHOD_NAME);
1303
- if (mainMethodStatus.exists) {
1304
- return;
1305
- }
1306
- yield this.glue.interop.register(MAIN_CLIENT_METHOD_NAME, handler);
1307
- });
1308
- }
1309
- clearMainProviderMethod() {
1310
- return __awaiter(this, void 0, void 0, function* () {
1311
- yield this.glue.interop.unregister(MAIN_PROVIDER_METHOD_NAME);
1312
- });
1313
- }
1314
- sendClientResultsBatch(batch, clientInstanceId, queryId) {
1315
- return __awaiter(this, void 0, void 0, function* () {
1316
- const interopArguments = {
1317
- items: batch.results,
1318
- provider: batch.provider,
1319
- queryId,
1320
- status: SEARCH_QUERY_STATUSES.inProgress
1321
- };
1322
- yield this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1323
- });
1324
- }
1325
- sendClientQueueCompleted(clientInstanceId, queryId) {
1326
- return __awaiter(this, void 0, void 0, function* () {
1327
- const interopArguments = {
1328
- items: [],
1329
- queryId,
1330
- status: SEARCH_QUERY_STATUSES.done
1331
- };
1332
- yield this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1333
- });
1334
- }
1335
- sendClientErrorMessage(error, clientInstanceId, queryId, provider) {
1336
- return __awaiter(this, void 0, void 0, function* () {
1337
- const interopArguments = {
1338
- items: [],
1339
- provider,
1340
- errorMessage: error,
1341
- queryId,
1342
- status: SEARCH_QUERY_STATUSES.error
1343
- };
1344
- yield this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1345
- });
1346
- }
1347
- sendQueryRequest(queryConfig, instances) {
1348
- return __awaiter(this, void 0, void 0, function* () {
1349
- if (!instances.length) {
1350
- return [];
1351
- }
1352
- const target = instances.map((inst) => ({ instance: inst.interopId }));
1353
- const invokeArgs = Object.assign({ operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search, apiVersion: "1" }, queryConfig);
1354
- const response = yield this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, invokeArgs, target);
1355
- const allReturned = response.all_return_values || [];
1356
- return allReturned.map((returnValue) => {
1357
- var _a;
1358
- return {
1359
- interopId: (_a = returnValue.executed_by) === null || _a === void 0 ? void 0 : _a.instance,
1360
- queryId: returnValue.returned.id
1361
- };
1362
- });
1363
- });
1364
- }
1365
- sendQueryCancelRequest(request, instance) {
1366
- return __awaiter(this, void 0, void 0, function* () {
1367
- const args = {
1368
- operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel,
1369
- id: request.id
1370
- };
1371
- yield this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, args, instance);
1372
- });
1373
- }
1374
- getAllProvidersInfo() {
1375
- return __awaiter(this, void 0, void 0, function* () {
1376
- if (this.glue.interop.methods().every((method) => method.name !== MAIN_PROVIDER_METHOD_NAME)) {
1377
- return [];
1378
- }
1379
- const args = {
1380
- operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info
1381
- };
1382
- const response = yield this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, args, "all");
1383
- const allReturned = response.all_return_values || [];
1384
- return allReturned.map((returnValue) => {
1385
- var _a, _b, _c, _d, _e;
1386
- const isLegacy = typeof returnValue.returned.apiVersion === "undefined";
1387
- const info = isLegacy ? {
1388
- supportedTypes: returnValue.returned.supportedTypes,
1389
- apiVersion: returnValue.returned.apiVersion,
1390
- providers: [{
1391
- interopId: (_a = returnValue.executed_by) === null || _a === void 0 ? void 0 : _a.instance,
1392
- id: (_b = returnValue.executed_by) === null || _b === void 0 ? void 0 : _b.instance,
1393
- name: (_c = returnValue.executed_by) === null || _c === void 0 ? void 0 : _c.instance,
1394
- appName: (_d = response.executed_by) === null || _d === void 0 ? void 0 : _d.application,
1395
- types: returnValue.returned.supportedTypes.map((t) => ({ name: t }))
1396
- }]
1397
- } : returnValue.returned;
1398
- return {
1399
- interopId: (_e = returnValue.executed_by) === null || _e === void 0 ? void 0 : _e.instance,
1400
- info
1401
- };
1402
- });
1403
- });
1404
- }
1405
- checkMyMethodExists(methodName) {
1406
- const myMethods = this.glue.interop.methodsForInstance({ instance: this.glue.interop.instance.instance });
1407
- return { exists: myMethods.some((method) => method.name === methodName) };
1408
- }
1409
- }
1257
+ class GlueController {
1258
+ glue;
1259
+ constructor(glue) {
1260
+ this.glue = glue;
1261
+ }
1262
+ get myAppName() {
1263
+ return this.glue.interop.instance.applicationName;
1264
+ }
1265
+ get myInteropId() {
1266
+ return this.glue.interop.instance.instance;
1267
+ }
1268
+ async registerMainProviderMethod(handler) {
1269
+ const mainMethodStatus = this.checkMyMethodExists(MAIN_PROVIDER_METHOD_NAME);
1270
+ if (mainMethodStatus.exists) {
1271
+ return;
1272
+ }
1273
+ await this.glue.interop.register(MAIN_PROVIDER_METHOD_NAME, handler);
1274
+ }
1275
+ async registerMainClientMethod(handler) {
1276
+ const mainMethodStatus = this.checkMyMethodExists(MAIN_CLIENT_METHOD_NAME);
1277
+ if (mainMethodStatus.exists) {
1278
+ return;
1279
+ }
1280
+ await this.glue.interop.register(MAIN_CLIENT_METHOD_NAME, handler);
1281
+ }
1282
+ async clearMainProviderMethod() {
1283
+ await this.glue.interop.unregister(MAIN_PROVIDER_METHOD_NAME);
1284
+ }
1285
+ async sendClientResultsBatch(batch, clientInstanceId, queryId) {
1286
+ const interopArguments = {
1287
+ items: batch.results,
1288
+ provider: batch.provider,
1289
+ queryId,
1290
+ status: SEARCH_QUERY_STATUSES.inProgress
1291
+ };
1292
+ await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1293
+ }
1294
+ async sendClientQueueCompleted(clientInstanceId, queryId) {
1295
+ const interopArguments = {
1296
+ items: [],
1297
+ queryId,
1298
+ status: SEARCH_QUERY_STATUSES.done
1299
+ };
1300
+ await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1301
+ }
1302
+ async sendClientErrorMessage(error, clientInstanceId, queryId, provider) {
1303
+ const interopArguments = {
1304
+ items: [],
1305
+ provider,
1306
+ errorMessage: error,
1307
+ queryId,
1308
+ status: SEARCH_QUERY_STATUSES.error
1309
+ };
1310
+ await this.glue.interop.invoke(MAIN_CLIENT_METHOD_NAME, interopArguments, { instance: clientInstanceId });
1311
+ }
1312
+ async sendQueryRequest(queryConfig, instances) {
1313
+ if (!instances.length) {
1314
+ return [];
1315
+ }
1316
+ const target = instances.map((inst) => ({ instance: inst.interopId }));
1317
+ const invokeArgs = {
1318
+ operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search,
1319
+ apiVersion: "1",
1320
+ ...queryConfig
1321
+ };
1322
+ const response = await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, invokeArgs, target);
1323
+ const allReturned = response.all_return_values || [];
1324
+ return allReturned.map((returnValue) => {
1325
+ return {
1326
+ interopId: returnValue.executed_by?.instance,
1327
+ queryId: returnValue.returned.id
1328
+ };
1329
+ });
1330
+ }
1331
+ async sendQueryCancelRequest(request, instance) {
1332
+ const args = {
1333
+ operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel,
1334
+ id: request.id
1335
+ };
1336
+ await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, args, instance);
1337
+ }
1338
+ async getAllProvidersInfo() {
1339
+ if (this.glue.interop.methods().every((method) => method.name !== MAIN_PROVIDER_METHOD_NAME)) {
1340
+ return [];
1341
+ }
1342
+ const args = {
1343
+ operation: CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info
1344
+ };
1345
+ const response = await this.glue.interop.invoke(MAIN_PROVIDER_METHOD_NAME, args, "all");
1346
+ const allReturned = response.all_return_values || [];
1347
+ return allReturned.map((returnValue) => {
1348
+ const isLegacy = typeof returnValue.returned.apiVersion === "undefined";
1349
+ const info = isLegacy ? {
1350
+ supportedTypes: returnValue.returned.supportedTypes,
1351
+ apiVersion: returnValue.returned.apiVersion,
1352
+ providers: [{
1353
+ interopId: returnValue.executed_by?.instance,
1354
+ id: returnValue.executed_by?.instance,
1355
+ name: returnValue.executed_by?.instance,
1356
+ appName: response.executed_by?.application,
1357
+ types: returnValue.returned.supportedTypes.map((t) => ({ name: t }))
1358
+ }]
1359
+ } : returnValue.returned;
1360
+ return {
1361
+ interopId: returnValue.executed_by?.instance,
1362
+ info
1363
+ };
1364
+ });
1365
+ }
1366
+ checkMyMethodExists(methodName) {
1367
+ const myMethods = this.glue.interop.methodsForInstance({ instance: this.glue.interop.instance.instance });
1368
+ return { exists: myMethods.some((method) => method.name === methodName) };
1369
+ }
1370
+ }
1410
1371
 
1411
- class MainController {
1412
- constructor(logger, glueController, clientController, providerController) {
1413
- this.logger = logger;
1414
- this.glueController = glueController;
1415
- this.clientController = clientController;
1416
- this.providerController = providerController;
1417
- }
1418
- setDebounceMS(data) {
1419
- this.logger.info(`[${data.commandId}] Starting setDebounceMS operation with duration ${data.milliseconds}`);
1420
- this.clientController.setDebounceMS(data);
1421
- this.logger.info(`[${data.commandId}] Operation setDebounceMS with duration ${data.milliseconds} completed`);
1422
- }
1423
- getDebounceMS(data) {
1424
- this.logger.info(`[${data.commandId}] Starting getDebounceMS operation.`);
1425
- return this.clientController.getDebounceMS(data);
1426
- }
1427
- query(data) {
1428
- return __awaiter(this, void 0, void 0, function* () {
1429
- this.logger.info(`[${data.commandId}] Starting query operation with config ${JSON.stringify(data.queryConfig)}`);
1430
- if (Array.isArray(data.queryConfig.providers) && !data.queryConfig.providers.length) {
1431
- throw new Error("Cannot sent a query with a defined empty array of providers, because this is an impossible query for complete.");
1432
- }
1433
- if (Array.isArray(data.queryConfig.types) && !data.queryConfig.types.length) {
1434
- throw new Error("Cannot sent a query with a defined empty array of types, because this is an impossible query for complete.");
1435
- }
1436
- const query = yield this.clientController.query(data);
1437
- this.logger.info(`[${data.commandId}] Operation query with config ${JSON.stringify(data.queryConfig)} completed.`);
1438
- return query;
1439
- });
1440
- }
1441
- registerProvider(data) {
1442
- return __awaiter(this, void 0, void 0, function* () {
1443
- this.logger.info(`[${data.commandId}] Starting registerProvider operation with config ${JSON.stringify(data.config)}`);
1444
- const provider = yield this.providerController.processRegisterProvider(data);
1445
- this.logger.info(`[${data.commandId}] Operation registerProvider with config ${JSON.stringify(data.config)} completed.`);
1446
- return provider;
1447
- });
1448
- }
1449
- providers(data) {
1450
- return __awaiter(this, void 0, void 0, function* () {
1451
- this.logger.info(`[${data.commandId}] Starting providers operation.`);
1452
- const allProvidersInfo = yield this.glueController.getAllProvidersInfo();
1453
- const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1454
- this.logger.info(`[${data.commandId}] Operation providers completed.`);
1455
- return allProvidersData;
1456
- });
1457
- }
1458
- types(data) {
1459
- return __awaiter(this, void 0, void 0, function* () {
1460
- this.logger.info(`[${data.commandId}] Starting types operation.`);
1461
- const allProvidersInfo = yield this.glueController.getAllProvidersInfo();
1462
- const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1463
- const allSupportedTypes = allProvidersData.filter((provData) => !!provData.types).flatMap((provData) => provData.types);
1464
- const uniqueSupportedTypes = [...new Set(allSupportedTypes)];
1465
- this.logger.info(`[${data.commandId}] Operation types completed.`);
1466
- return uniqueSupportedTypes;
1467
- });
1468
- }
1469
- }
1372
+ class MainController {
1373
+ logger;
1374
+ glueController;
1375
+ clientController;
1376
+ providerController;
1377
+ constructor(logger, glueController, clientController, providerController) {
1378
+ this.logger = logger;
1379
+ this.glueController = glueController;
1380
+ this.clientController = clientController;
1381
+ this.providerController = providerController;
1382
+ }
1383
+ setDebounceMS(data) {
1384
+ this.logger.info(`[${data.commandId}] Starting setDebounceMS operation with duration ${data.milliseconds}`);
1385
+ this.clientController.setDebounceMS(data);
1386
+ this.logger.info(`[${data.commandId}] Operation setDebounceMS with duration ${data.milliseconds} completed`);
1387
+ }
1388
+ getDebounceMS(data) {
1389
+ this.logger.info(`[${data.commandId}] Starting getDebounceMS operation.`);
1390
+ return this.clientController.getDebounceMS(data);
1391
+ }
1392
+ async query(data) {
1393
+ this.logger.info(`[${data.commandId}] Starting query operation with config ${JSON.stringify(data.queryConfig)}`);
1394
+ if (Array.isArray(data.queryConfig.providers) && !data.queryConfig.providers.length) {
1395
+ throw new Error("Cannot sent a query with a defined empty array of providers, because this is an impossible query for complete.");
1396
+ }
1397
+ if (Array.isArray(data.queryConfig.types) && !data.queryConfig.types.length) {
1398
+ throw new Error("Cannot sent a query with a defined empty array of types, because this is an impossible query for complete.");
1399
+ }
1400
+ const query = await this.clientController.query(data);
1401
+ this.logger.info(`[${data.commandId}] Operation query with config ${JSON.stringify(data.queryConfig)} completed.`);
1402
+ return query;
1403
+ }
1404
+ async registerProvider(data) {
1405
+ this.logger.info(`[${data.commandId}] Starting registerProvider operation with config ${JSON.stringify(data.config)}`);
1406
+ const provider = await this.providerController.processRegisterProvider(data);
1407
+ this.logger.info(`[${data.commandId}] Operation registerProvider with config ${JSON.stringify(data.config)} completed.`);
1408
+ return provider;
1409
+ }
1410
+ async providers(data) {
1411
+ this.logger.info(`[${data.commandId}] Starting providers operation.`);
1412
+ const allProvidersInfo = await this.glueController.getAllProvidersInfo();
1413
+ const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1414
+ this.logger.info(`[${data.commandId}] Operation providers completed.`);
1415
+ return allProvidersData;
1416
+ }
1417
+ async types(data) {
1418
+ this.logger.info(`[${data.commandId}] Starting types operation.`);
1419
+ const allProvidersInfo = await this.glueController.getAllProvidersInfo();
1420
+ const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1421
+ const allSupportedTypes = allProvidersData.filter((provData) => !!provData.types).flatMap((provData) => provData.types);
1422
+ const uniqueSupportedTypes = [...new Set(allSupportedTypes)];
1423
+ this.logger.info(`[${data.commandId}] Operation types completed.`);
1424
+ return uniqueSupportedTypes;
1425
+ }
1426
+ }
1470
1427
 
1471
- const extractErrorMsg = (error) => {
1472
- const stringError = typeof error === "string" ?
1473
- error :
1474
- error.message ? JSON.stringify(error.message) :
1475
- JSON.stringify(error);
1476
- return stringError;
1477
- };
1428
+ const extractErrorMsg = (error) => {
1429
+ const stringError = typeof error === "string" ?
1430
+ error :
1431
+ error.message ? JSON.stringify(error.message) :
1432
+ JSON.stringify(error);
1433
+ return stringError;
1434
+ };
1478
1435
 
1479
- class ProviderController {
1480
- constructor(logger, glueController, sequelizer, limitsTracker, modelsFactory) {
1481
- this.logger = logger;
1482
- this.glueController = glueController;
1483
- this.sequelizer = sequelizer;
1484
- this.limitsTracker = limitsTracker;
1485
- this.modelsFactory = modelsFactory;
1486
- this.registry = lib();
1487
- this.providersModels = {};
1488
- this.activeQueries = {};
1489
- }
1490
- processRegisterProvider(data) {
1491
- return __awaiter(this, void 0, void 0, function* () {
1492
- const { config, commandId } = data;
1493
- this.logger.info(`[${commandId}] enqueueing the provider registration process with config: ${JSON.stringify(config)}`);
1494
- const result = yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
1495
- const allProvidersInfo = yield this.glueController.getAllProvidersInfo();
1496
- const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1497
- if (allProvidersData.some((providerData) => providerData && providerData.name === config.name)) {
1498
- throw new Error(`Cannot register a new provider with name: ${config.name}, because there already is a provider with this name`);
1499
- }
1500
- yield this.glueController.registerMainProviderMethod(this.handleSearchQueryRequest.bind(this));
1501
- const modelData = {
1502
- id: nanoid(10),
1503
- name: config.name,
1504
- interopId: this.glueController.myInteropId,
1505
- appName: this.glueController.myAppName,
1506
- types: config.types
1507
- };
1508
- const model = this.modelsFactory.buildProviderModel(modelData, this);
1509
- this.providersModels[modelData.id] = model;
1510
- return model.exposeFacade();
1511
- }));
1512
- this.logger.info(`[${commandId}] the provider with name: ${config.name} has been registered.`);
1513
- return result;
1514
- });
1515
- }
1516
- processProviderOnQuery(data) {
1517
- return this.registry.add(`on-search-query-${data.id}`, data.callback);
1518
- }
1519
- processProviderOnQueryCancel(data) {
1520
- return this.registry.add(`on-cancel-query-${data.id}`, data.callback);
1521
- }
1522
- processProviderUnregister(data) {
1523
- return __awaiter(this, void 0, void 0, function* () {
1524
- this.logger.info(`[${data.commandId}] enqueueing the provider un-registration with id: ${data.id}`);
1525
- yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
1526
- this.cleanUpProvider(data.id, data.commandId);
1527
- if (Object.keys(this.providersModels).length) {
1528
- return;
1529
- }
1530
- yield this.glueController.clearMainProviderMethod();
1531
- }));
1532
- this.logger.info(`[${data.commandId}] the provider un-registration with id: ${data.id} completed`);
1533
- });
1534
- }
1535
- processProviderQueryDone(command) {
1536
- var _a;
1537
- return __awaiter(this, void 0, void 0, function* () {
1538
- const { commandId, identification } = command;
1539
- (_a = this.activeQueries[identification.queryId]) === null || _a === void 0 ? void 0 : _a.publisher.syncSuspendProvider(identification.providerId, commandId);
1540
- yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
1541
- this.logger.trace(`[${commandId}] Processing a query done command with identification: ${JSON.stringify(identification)}`);
1542
- const activeQuery = this.activeQueries[identification.queryId];
1543
- if (!activeQuery) {
1544
- this.logger.warn(`[${commandId}] Cannot mark provider: ${identification.providerId} done with query ${identification.queryId}, because there is no active query with this id`);
1545
- return;
1546
- }
1547
- yield this.cleanUpProviderQuery(identification.queryId, identification.providerId, commandId);
1548
- if (activeQuery.providersAtWork.length) {
1549
- this.logger.trace(`[${commandId}] Query done command completed, but there are more providers still at work.`);
1550
- return;
1551
- }
1552
- this.cleanUpQuery(identification.queryId, commandId);
1553
- this.logger.trace(`[${commandId}] Query is completed, signalling.`);
1554
- }));
1555
- });
1556
- }
1557
- processProviderQueryError(command) {
1558
- var _a;
1559
- const { commandId, identification, error } = command;
1560
- this.logger.warn(`[${commandId}] Processing an error sent by provider: ${identification.providerId} for query id: ${identification.queryId} -> ${error}`);
1561
- (_a = this.activeQueries[identification.queryId]) === null || _a === void 0 ? void 0 : _a.publisher.markProviderError(command);
1562
- return this.processProviderQueryDone(command);
1563
- }
1564
- processProviderQueryResult(command) {
1565
- const { commandId, identification } = command;
1566
- const activeQuery = this.activeQueries[identification.queryId];
1567
- if (!activeQuery) {
1568
- const errorMessage = `Will not send this result to the client, because there is no active query with id ${identification.queryId}. Most likely this query was cancelled.`;
1569
- this.logger.warn(`[${command}] ${errorMessage}`);
1570
- throw new Error(errorMessage);
1571
- }
1572
- if (activeQuery.publisher.checkProviderSuspended(identification.providerId)) {
1573
- const errorMessage = `Will not send this result to the client, because there is no info about this provider in the active query with id ${identification.queryId}. Most likely this query was marked as done by this provider already.`;
1574
- this.logger.warn(`[${command}] ${errorMessage}`);
1575
- throw new Error(errorMessage);
1576
- }
1577
- const requestedTypes = activeQuery.requestedTypes;
1578
- if (requestedTypes && requestedTypes.every((searchType) => searchType.name !== command.result.type.name)) {
1579
- const errorMessage = `Will not send this result to the client, because this result has a defined type: ${command.result.type.name} which is not in the explicitly requested list of types by the client.`;
1580
- this.logger.warn(`[${command}] ${errorMessage}`);
1581
- throw new Error(errorMessage);
1582
- }
1583
- const testResult = this.limitsTracker.testResultLimit(command);
1584
- if (testResult === null || testResult === void 0 ? void 0 : testResult.maxLimitHit) {
1585
- const errorMessage = `Will not process this result from provider ${command.identification.providerId}, because this provider has reached the max results limit set by the client. This provider cannot send more result, marking it as done.`;
1586
- this.logger.info(errorMessage);
1587
- setTimeout(() => this.processProviderQueryDone(command), 0);
1588
- throw new Error(errorMessage);
1589
- }
1590
- if (testResult === null || testResult === void 0 ? void 0 : testResult.maxLimitPerTypeHit) {
1591
- const errorMessage = `Will not process this result from provider ${command.identification.providerId}, because this provider has reached the max results limit per type as set by the client.`;
1592
- this.logger.info(errorMessage);
1593
- throw new Error(errorMessage);
1594
- }
1595
- this.logger.trace(`[${commandId}] An active query for query ${identification.queryId} was found and the provider is within limits, queueing the result`);
1596
- this.limitsTracker.update(command);
1597
- activeQuery.publisher.queueResult(command);
1598
- this.logger.trace(`[${commandId}] The query result was queued successfully.`);
1599
- }
1600
- handleSearchQueryRequest(args, caller) {
1601
- return __awaiter(this, void 0, void 0, function* () {
1602
- const { operation } = args;
1603
- const validatedOperation = operationDecoder.runWithException(operation);
1604
- const commandId = nanoid(10);
1605
- switch (validatedOperation) {
1606
- case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info:
1607
- return this.handleInfoOperation({ commandId });
1608
- case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search:
1609
- return this.handleSearchOperation({ args, commandId }, caller);
1610
- case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel:
1611
- return this.handleCancelOperation({ args, commandId });
1612
- default:
1613
- throw new Error(`Unrecognized operation: ${operation}`);
1614
- }
1615
- });
1616
- }
1617
- handleInfoOperation(request) {
1618
- return __awaiter(this, void 0, void 0, function* () {
1619
- this.logger.info(`[${request.commandId}] handling an info operation`);
1620
- const allSupportedTypes = Object.values(this.providersModels).flatMap((providerModel) => providerModel.myProviderData.types || []);
1621
- const uniqueSupportedTypes = [...new Set(allSupportedTypes)];
1622
- const hasWildCardTypeProvider = Object.values(this.providersModels).some((providerModel) => !providerModel.myProviderData.types);
1623
- if (hasWildCardTypeProvider) {
1624
- uniqueSupportedTypes.push({ name: "*" });
1625
- }
1626
- const providers = Object.values(this.providersModels).map((providerModel) => providerModel.myProviderData);
1627
- const response = {
1628
- supportedTypes: uniqueSupportedTypes.map((supportedType) => supportedType.name),
1629
- providers: providers,
1630
- apiVersion: "1"
1631
- };
1632
- this.logger.info(`[${request.commandId}] responding to an info operation with: ${JSON.stringify(response)}`);
1633
- return response;
1634
- });
1635
- }
1636
- handleSearchOperation(request, caller) {
1637
- return __awaiter(this, void 0, void 0, function* () {
1638
- const commandId = request.commandId;
1639
- const queryId = this.generateQueryId();
1640
- this.logger.info(`[${commandId}] Processing search operation with queryId: ${queryId} request details: ${JSON.stringify(request.args)}`);
1641
- const isLegacyRequest = this.checkRequestLegacy(request.args);
1642
- const validatedRequest = this.prepareRequest(request.args, isLegacyRequest, commandId);
1643
- this.logger.info(`[${commandId}] Search operation with queryId: ${queryId} is validated. Creating an active query and enqueueing calling the providers.`);
1644
- this.activeQueries[queryId] = {
1645
- queryId,
1646
- callerInstanceId: caller.instance,
1647
- providersAtWork: [],
1648
- requestedTypes: validatedRequest.types,
1649
- publisher: this.modelsFactory.buildPublisher(caller.instance, queryId, isLegacyRequest),
1650
- staleTimer: this.setClearStaleQueryTimer(queryId)
1651
- };
1652
- if (validatedRequest.providerLimits) {
1653
- this.limitsTracker.enableTracking(validatedRequest.providerLimits, queryId);
1654
- }
1655
- setTimeout(() => {
1656
- this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
1657
- try {
1658
- this.logger.info(`[${commandId}] Calling the providers.`);
1659
- this.callProviders(validatedRequest, queryId, commandId);
1660
- }
1661
- catch (error) {
1662
- this.logger.error(`[${commandId}] Error calling the providers: ${extractErrorMsg(error)}`);
1663
- }
1664
- }));
1665
- }, 0);
1666
- this.logger.info(`[${commandId}] Search operation with queryID: ${queryId} processed successfully.`);
1667
- return { id: queryId };
1668
- });
1669
- }
1670
- handleCancelOperation(request) {
1671
- return __awaiter(this, void 0, void 0, function* () {
1672
- yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
1673
- const validation = searchCancelRequestDecoder.run(request.args);
1674
- if (!validation.ok) {
1675
- const errorMsg = `Cannot process a cancel request, because of validation error: ${JSON.stringify(validation.error)}`;
1676
- this.logger.warn(`[${request.commandId}] ${errorMsg}`);
1677
- throw new Error(errorMsg);
1678
- }
1679
- const validatedRequest = validation.result;
1680
- const activeQuery = this.activeQueries[validatedRequest.id];
1681
- if (!activeQuery) {
1682
- return;
1683
- }
1684
- clearTimeout(activeQuery.staleTimer);
1685
- activeQuery.publisher.cancel(request.commandId);
1686
- delete this.activeQueries[validatedRequest.id];
1687
- activeQuery.providersAtWork.forEach((provider) => this.registry.execute(`on-cancel-query-${provider.myProviderData.id}`, { id: validatedRequest.id }));
1688
- }));
1689
- });
1690
- }
1691
- generateQueryId() {
1692
- const queryId = nanoid(10);
1693
- if (this.activeQueries[queryId]) {
1694
- return this.generateQueryId();
1695
- }
1696
- return queryId;
1697
- }
1698
- translateLegacySearchRequest(legacyRequest) {
1699
- var _a;
1700
- return {
1701
- search: legacyRequest.search,
1702
- types: (_a = legacyRequest.types) === null || _a === void 0 ? void 0 : _a.map((searchType) => ({ name: searchType })),
1703
- providerLimits: {
1704
- maxResults: legacyRequest.limit,
1705
- maxResultsPerType: legacyRequest.categoryLimit
1706
- }
1707
- };
1708
- }
1709
- checkRequestLegacy(searchRequest) {
1710
- return typeof searchRequest.apiVersion === "undefined";
1711
- }
1712
- callProviders(validatedRequest, queryId, commandId) {
1713
- let providers = validatedRequest.providers ?
1714
- this.getFilteredProviderModels(validatedRequest.providers)
1715
- : Object.values(this.providersModels);
1716
- this.logger.trace(`[${commandId}] initial providers filtration yielded: ${JSON.stringify(providers.map((p) => p.myProviderData.name).join(", "))}`);
1717
- providers = validatedRequest.types ? this.getFilteredProvidersBySearchTypes(providers, validatedRequest.types) : providers;
1718
- this.logger.trace(`[${commandId}] search type providers filtration yielded: ${JSON.stringify(providers.map((p) => p.myProviderData.name).join(", "))}`);
1719
- this.activeQueries[queryId].publisher.configureProviders(providers);
1720
- this.activeQueries[queryId].providersAtWork.push(...providers);
1721
- providers.forEach((provider) => this.callProvider(provider, validatedRequest, queryId, commandId));
1722
- }
1723
- callProvider(provider, validatedRequest, queryId, commandId) {
1724
- const queryModel = this.modelsFactory.buildProviderQueryModel(validatedRequest, { queryId, providerId: provider.myProviderData.id }, this);
1725
- const queryFacade = queryModel.exposeFacade();
1726
- this.logger.info(`[${commandId}] The query facade for provider: ${provider.myProviderData.id} with name ${provider.myProviderData.name} is ready, raising the event for query ID: ${queryId}.`);
1727
- this.registry.execute(`on-search-query-${provider.myProviderData.id}`, queryFacade);
1728
- }
1729
- getFilteredProviderModels(providers) {
1730
- const filtered = providers.reduce((providers, provider) => {
1731
- if (this.providersModels[provider.id]) {
1732
- providers.push(this.providersModels[provider.id]);
1733
- }
1734
- return providers;
1735
- }, []);
1736
- return filtered;
1737
- }
1738
- getFilteredProvidersBySearchTypes(providers, searchTypes) {
1739
- const filtered = providers.filter((provider) => {
1740
- var _a;
1741
- if (!provider.myProviderData.types || !provider.myProviderData.types.length) {
1742
- return true;
1743
- }
1744
- return (_a = provider.myProviderData.types) === null || _a === void 0 ? void 0 : _a.some((providerSearchType) => searchTypes.some((searchType) => searchType.name === providerSearchType.name));
1745
- });
1746
- return filtered;
1747
- }
1748
- setClearStaleQueryTimer(queryId) {
1749
- return setTimeout(() => {
1750
- const commandId = nanoid(10);
1751
- this.logger.info(`[${commandId}] Stale query timer is activated for queryId: ${queryId}`);
1752
- const activeQuery = this.activeQueries[queryId];
1753
- if (!activeQuery) {
1754
- this.logger.info(`[${commandId}] No active query was found, this was a false activation.`);
1755
- return;
1756
- }
1757
- this.logger.info(`[${commandId}] force-marking the query as done`);
1758
- this.cleanUpQuery(queryId, commandId);
1759
- this.logger.info(`[${commandId}] the stale query was cleared.`);
1760
- }, STALE_QUERY_TIMEOUT_MS);
1761
- }
1762
- prepareRequest(searchRequest, isLegacyRequest, commandId) {
1763
- const parsedRequest = isLegacyRequest ? this.translateLegacySearchRequest(searchRequest) : searchRequest;
1764
- const validation = queryConfigDecoder.run(parsedRequest);
1765
- if (!validation.ok) {
1766
- const errorMsg = `Cannot process a search request, because of validation error: ${JSON.stringify(validation.error)}`;
1767
- this.logger.warn(`[${commandId}] ${errorMsg}`);
1768
- throw new Error(errorMsg);
1769
- }
1770
- const validatedRequest = validation.result;
1771
- return validatedRequest;
1772
- }
1773
- cleanUpQuery(queryId, commandId) {
1774
- const activeQuery = this.activeQueries[queryId];
1775
- clearTimeout(activeQuery.staleTimer);
1776
- activeQuery.publisher.cleanPublisher(commandId);
1777
- delete this.activeQueries[queryId];
1778
- this.limitsTracker.cleanTracking(queryId);
1779
- }
1780
- cleanUpProvider(providerId, commandId) {
1781
- this.registry.clearKey(`on-search-query-${providerId}`);
1782
- this.registry.clearKey(`on-cancel-query-${providerId}`);
1783
- delete this.providersModels[providerId];
1784
- const queriesWithProvider = Object.values(this.activeQueries).filter((query) => !query.publisher.checkProviderSuspended(providerId));
1785
- queriesWithProvider.forEach((query) => {
1786
- this.processProviderQueryDone({
1787
- identification: {
1788
- queryId: query.queryId,
1789
- providerId
1790
- },
1791
- commandId
1792
- });
1793
- });
1794
- }
1795
- cleanUpProviderQuery(queryId, providerId, commandId) {
1796
- return __awaiter(this, void 0, void 0, function* () {
1797
- const activeQuery = this.activeQueries[queryId];
1798
- if (!activeQuery) {
1799
- this.logger.warn(`[${commandId}] Cannot clean up a provider query ${queryId} for provider ${providerId} because there is no such active query`);
1800
- return;
1801
- }
1802
- activeQuery.providersAtWork = activeQuery.providersAtWork.filter((provider) => provider.myProviderData.id !== providerId);
1803
- yield activeQuery.publisher.markProviderDone(providerId, commandId);
1804
- });
1805
- }
1806
- }
1436
+ class ProviderController {
1437
+ logger;
1438
+ glueController;
1439
+ sequelizer;
1440
+ limitsTracker;
1441
+ modelsFactory;
1442
+ registry = CallbackRegistryFactory();
1443
+ providersModels = {};
1444
+ activeQueries = {};
1445
+ constructor(logger, glueController, sequelizer, limitsTracker, modelsFactory) {
1446
+ this.logger = logger;
1447
+ this.glueController = glueController;
1448
+ this.sequelizer = sequelizer;
1449
+ this.limitsTracker = limitsTracker;
1450
+ this.modelsFactory = modelsFactory;
1451
+ }
1452
+ async processRegisterProvider(data) {
1453
+ const { config, commandId } = data;
1454
+ this.logger.info(`[${commandId}] enqueueing the provider registration process with config: ${JSON.stringify(config)}`);
1455
+ const result = await this.sequelizer.enqueue(async () => {
1456
+ const allProvidersInfo = await this.glueController.getAllProvidersInfo();
1457
+ const allProvidersData = allProvidersInfo.flatMap((provInfo) => provInfo.info.providers);
1458
+ if (allProvidersData.some((providerData) => providerData && providerData.name === config.name)) {
1459
+ throw new Error(`Cannot register a new provider with name: ${config.name}, because there already is a provider with this name`);
1460
+ }
1461
+ await this.glueController.registerMainProviderMethod(this.handleSearchQueryRequest.bind(this));
1462
+ const modelData = {
1463
+ id: nanoid(10),
1464
+ name: config.name,
1465
+ interopId: this.glueController.myInteropId,
1466
+ appName: this.glueController.myAppName,
1467
+ types: config.types
1468
+ };
1469
+ const model = this.modelsFactory.buildProviderModel(modelData, this);
1470
+ this.providersModels[modelData.id] = model;
1471
+ return model.exposeFacade();
1472
+ });
1473
+ this.logger.info(`[${commandId}] the provider with name: ${config.name} has been registered.`);
1474
+ return result;
1475
+ }
1476
+ processProviderOnQuery(data) {
1477
+ return this.registry.add(`on-search-query-${data.id}`, data.callback);
1478
+ }
1479
+ processProviderOnQueryCancel(data) {
1480
+ return this.registry.add(`on-cancel-query-${data.id}`, data.callback);
1481
+ }
1482
+ async processProviderUnregister(data) {
1483
+ this.logger.info(`[${data.commandId}] enqueueing the provider un-registration with id: ${data.id}`);
1484
+ await this.sequelizer.enqueue(async () => {
1485
+ this.cleanUpProvider(data.id, data.commandId);
1486
+ if (Object.keys(this.providersModels).length) {
1487
+ return;
1488
+ }
1489
+ await this.glueController.clearMainProviderMethod();
1490
+ });
1491
+ this.logger.info(`[${data.commandId}] the provider un-registration with id: ${data.id} completed`);
1492
+ }
1493
+ async processProviderQueryDone(command) {
1494
+ const { commandId, identification } = command;
1495
+ this.activeQueries[identification.queryId]?.publisher.syncSuspendProvider(identification.providerId, commandId);
1496
+ await this.sequelizer.enqueue(async () => {
1497
+ this.logger.trace(`[${commandId}] Processing a query done command with identification: ${JSON.stringify(identification)}`);
1498
+ const activeQuery = this.activeQueries[identification.queryId];
1499
+ if (!activeQuery) {
1500
+ this.logger.warn(`[${commandId}] Cannot mark provider: ${identification.providerId} done with query ${identification.queryId}, because there is no active query with this id`);
1501
+ return;
1502
+ }
1503
+ await this.cleanUpProviderQuery(identification.queryId, identification.providerId, commandId);
1504
+ if (activeQuery.providersAtWork.length) {
1505
+ this.logger.trace(`[${commandId}] Query done command completed, but there are more providers still at work.`);
1506
+ return;
1507
+ }
1508
+ this.cleanUpQuery(identification.queryId, commandId);
1509
+ this.logger.trace(`[${commandId}] Query is completed, signalling.`);
1510
+ });
1511
+ }
1512
+ processProviderQueryError(command) {
1513
+ const { commandId, identification, error } = command;
1514
+ this.logger.warn(`[${commandId}] Processing an error sent by provider: ${identification.providerId} for query id: ${identification.queryId} -> ${error}`);
1515
+ this.activeQueries[identification.queryId]?.publisher.markProviderError(command);
1516
+ return this.processProviderQueryDone(command);
1517
+ }
1518
+ processProviderQueryResult(command) {
1519
+ const { commandId, identification } = command;
1520
+ const activeQuery = this.activeQueries[identification.queryId];
1521
+ if (!activeQuery) {
1522
+ const errorMessage = `Will not send this result to the client, because there is no active query with id ${identification.queryId}. Most likely this query was cancelled.`;
1523
+ this.logger.warn(`[${command}] ${errorMessage}`);
1524
+ throw new Error(errorMessage);
1525
+ }
1526
+ if (activeQuery.publisher.checkProviderSuspended(identification.providerId)) {
1527
+ const errorMessage = `Will not send this result to the client, because there is no info about this provider in the active query with id ${identification.queryId}. Most likely this query was marked as done by this provider already.`;
1528
+ this.logger.warn(`[${command}] ${errorMessage}`);
1529
+ throw new Error(errorMessage);
1530
+ }
1531
+ const requestedTypes = activeQuery.requestedTypes;
1532
+ if (requestedTypes && requestedTypes.every((searchType) => searchType.name !== command.result.type.name)) {
1533
+ const errorMessage = `Will not send this result to the client, because this result has a defined type: ${command.result.type.name} which is not in the explicitly requested list of types by the client.`;
1534
+ this.logger.warn(`[${command}] ${errorMessage}`);
1535
+ throw new Error(errorMessage);
1536
+ }
1537
+ const testResult = this.limitsTracker.testResultLimit(command);
1538
+ if (testResult?.maxLimitHit) {
1539
+ const errorMessage = `Will not process this result from provider ${command.identification.providerId}, because this provider has reached the max results limit set by the client. This provider cannot send more result, marking it as done.`;
1540
+ this.logger.info(errorMessage);
1541
+ setTimeout(() => this.processProviderQueryDone(command), 0);
1542
+ throw new Error(errorMessage);
1543
+ }
1544
+ if (testResult?.maxLimitPerTypeHit) {
1545
+ const errorMessage = `Will not process this result from provider ${command.identification.providerId}, because this provider has reached the max results limit per type as set by the client.`;
1546
+ this.logger.info(errorMessage);
1547
+ throw new Error(errorMessage);
1548
+ }
1549
+ this.logger.trace(`[${commandId}] An active query for query ${identification.queryId} was found and the provider is within limits, queueing the result`);
1550
+ this.limitsTracker.update(command);
1551
+ activeQuery.publisher.queueResult(command);
1552
+ this.logger.trace(`[${commandId}] The query result was queued successfully.`);
1553
+ }
1554
+ async handleSearchQueryRequest(args, caller) {
1555
+ const { operation } = args;
1556
+ const validatedOperation = operationDecoder.runWithException(operation);
1557
+ const commandId = nanoid(10);
1558
+ switch (validatedOperation) {
1559
+ case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.info:
1560
+ return this.handleInfoOperation({ commandId });
1561
+ case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.search:
1562
+ return this.handleSearchOperation({ args, commandId }, caller);
1563
+ case CLIENT_TO_PROVIDER_PROTOCOL_OPERATIONS.cancel:
1564
+ return this.handleCancelOperation({ args, commandId });
1565
+ default:
1566
+ throw new Error(`Unrecognized operation: ${operation}`);
1567
+ }
1568
+ }
1569
+ async handleInfoOperation(request) {
1570
+ this.logger.info(`[${request.commandId}] handling an info operation`);
1571
+ const allSupportedTypes = Object.values(this.providersModels).flatMap((providerModel) => providerModel.myProviderData.types || []);
1572
+ const uniqueSupportedTypes = [...new Set(allSupportedTypes)];
1573
+ const hasWildCardTypeProvider = Object.values(this.providersModels).some((providerModel) => !providerModel.myProviderData.types);
1574
+ if (hasWildCardTypeProvider) {
1575
+ uniqueSupportedTypes.push({ name: "*" });
1576
+ }
1577
+ const providers = Object.values(this.providersModels).map((providerModel) => providerModel.myProviderData);
1578
+ const response = {
1579
+ supportedTypes: uniqueSupportedTypes.map((supportedType) => supportedType.name),
1580
+ providers: providers,
1581
+ apiVersion: "1"
1582
+ };
1583
+ this.logger.info(`[${request.commandId}] responding to an info operation with: ${JSON.stringify(response)}`);
1584
+ return response;
1585
+ }
1586
+ async handleSearchOperation(request, caller) {
1587
+ const commandId = request.commandId;
1588
+ const queryId = this.generateQueryId();
1589
+ this.logger.info(`[${commandId}] Processing search operation with queryId: ${queryId} request details: ${JSON.stringify(request.args)}`);
1590
+ const isLegacyRequest = this.checkRequestLegacy(request.args);
1591
+ const validatedRequest = this.prepareRequest(request.args, isLegacyRequest, commandId);
1592
+ this.logger.info(`[${commandId}] Search operation with queryId: ${queryId} is validated. Creating an active query and enqueueing calling the providers.`);
1593
+ this.activeQueries[queryId] = {
1594
+ queryId,
1595
+ callerInstanceId: caller.instance,
1596
+ providersAtWork: [],
1597
+ requestedTypes: validatedRequest.types,
1598
+ publisher: this.modelsFactory.buildPublisher(caller.instance, queryId, isLegacyRequest),
1599
+ staleTimer: this.setClearStaleQueryTimer(queryId)
1600
+ };
1601
+ if (validatedRequest.providerLimits) {
1602
+ this.limitsTracker.enableTracking(validatedRequest.providerLimits, queryId);
1603
+ }
1604
+ setTimeout(() => {
1605
+ this.sequelizer.enqueue(async () => {
1606
+ try {
1607
+ this.logger.info(`[${commandId}] Calling the providers.`);
1608
+ this.callProviders(validatedRequest, queryId, commandId);
1609
+ }
1610
+ catch (error) {
1611
+ this.logger.error(`[${commandId}] Error calling the providers: ${extractErrorMsg(error)}`);
1612
+ }
1613
+ });
1614
+ }, 0);
1615
+ this.logger.info(`[${commandId}] Search operation with queryID: ${queryId} processed successfully.`);
1616
+ return { id: queryId };
1617
+ }
1618
+ async handleCancelOperation(request) {
1619
+ await this.sequelizer.enqueue(async () => {
1620
+ const validation = searchCancelRequestDecoder.run(request.args);
1621
+ if (!validation.ok) {
1622
+ const errorMsg = `Cannot process a cancel request, because of validation error: ${JSON.stringify(validation.error)}`;
1623
+ this.logger.warn(`[${request.commandId}] ${errorMsg}`);
1624
+ throw new Error(errorMsg);
1625
+ }
1626
+ const validatedRequest = validation.result;
1627
+ const activeQuery = this.activeQueries[validatedRequest.id];
1628
+ if (!activeQuery) {
1629
+ return;
1630
+ }
1631
+ clearTimeout(activeQuery.staleTimer);
1632
+ activeQuery.publisher.cancel(request.commandId);
1633
+ delete this.activeQueries[validatedRequest.id];
1634
+ activeQuery.providersAtWork.forEach((provider) => this.registry.execute(`on-cancel-query-${provider.myProviderData.id}`, { id: validatedRequest.id }));
1635
+ });
1636
+ }
1637
+ generateQueryId() {
1638
+ const queryId = nanoid(10);
1639
+ if (this.activeQueries[queryId]) {
1640
+ return this.generateQueryId();
1641
+ }
1642
+ return queryId;
1643
+ }
1644
+ translateLegacySearchRequest(legacyRequest) {
1645
+ return {
1646
+ search: legacyRequest.search,
1647
+ types: legacyRequest.types?.map((searchType) => ({ name: searchType })),
1648
+ providerLimits: {
1649
+ maxResults: legacyRequest.limit,
1650
+ maxResultsPerType: legacyRequest.categoryLimit
1651
+ }
1652
+ };
1653
+ }
1654
+ checkRequestLegacy(searchRequest) {
1655
+ return typeof searchRequest.apiVersion === "undefined";
1656
+ }
1657
+ callProviders(validatedRequest, queryId, commandId) {
1658
+ let providers = validatedRequest.providers ?
1659
+ this.getFilteredProviderModels(validatedRequest.providers)
1660
+ : Object.values(this.providersModels);
1661
+ this.logger.trace(`[${commandId}] initial providers filtration yielded: ${JSON.stringify(providers.map((p) => p.myProviderData.name).join(", "))}`);
1662
+ providers = validatedRequest.types ? this.getFilteredProvidersBySearchTypes(providers, validatedRequest.types) : providers;
1663
+ this.logger.trace(`[${commandId}] search type providers filtration yielded: ${JSON.stringify(providers.map((p) => p.myProviderData.name).join(", "))}`);
1664
+ this.activeQueries[queryId].publisher.configureProviders(providers);
1665
+ this.activeQueries[queryId].providersAtWork.push(...providers);
1666
+ providers.forEach((provider) => this.callProvider(provider, validatedRequest, queryId, commandId));
1667
+ }
1668
+ callProvider(provider, validatedRequest, queryId, commandId) {
1669
+ const queryModel = this.modelsFactory.buildProviderQueryModel(validatedRequest, { queryId, providerId: provider.myProviderData.id }, this);
1670
+ const queryFacade = queryModel.exposeFacade();
1671
+ this.logger.info(`[${commandId}] The query facade for provider: ${provider.myProviderData.id} with name ${provider.myProviderData.name} is ready, raising the event for query ID: ${queryId}.`);
1672
+ this.registry.execute(`on-search-query-${provider.myProviderData.id}`, queryFacade);
1673
+ }
1674
+ getFilteredProviderModels(providers) {
1675
+ const filtered = providers.reduce((providers, provider) => {
1676
+ if (this.providersModels[provider.id]) {
1677
+ providers.push(this.providersModels[provider.id]);
1678
+ }
1679
+ return providers;
1680
+ }, []);
1681
+ return filtered;
1682
+ }
1683
+ getFilteredProvidersBySearchTypes(providers, searchTypes) {
1684
+ const filtered = providers.filter((provider) => {
1685
+ if (!provider.myProviderData.types || !provider.myProviderData.types.length) {
1686
+ return true;
1687
+ }
1688
+ return provider.myProviderData.types?.some((providerSearchType) => searchTypes.some((searchType) => searchType.name === providerSearchType.name));
1689
+ });
1690
+ return filtered;
1691
+ }
1692
+ setClearStaleQueryTimer(queryId) {
1693
+ return setTimeout(() => {
1694
+ const commandId = nanoid(10);
1695
+ this.logger.info(`[${commandId}] Stale query timer is activated for queryId: ${queryId}`);
1696
+ const activeQuery = this.activeQueries[queryId];
1697
+ if (!activeQuery) {
1698
+ this.logger.info(`[${commandId}] No active query was found, this was a false activation.`);
1699
+ return;
1700
+ }
1701
+ this.logger.info(`[${commandId}] force-marking the query as done`);
1702
+ this.cleanUpQuery(queryId, commandId);
1703
+ this.logger.info(`[${commandId}] the stale query was cleared.`);
1704
+ }, STALE_QUERY_TIMEOUT_MS);
1705
+ }
1706
+ prepareRequest(searchRequest, isLegacyRequest, commandId) {
1707
+ const parsedRequest = isLegacyRequest ? this.translateLegacySearchRequest(searchRequest) : searchRequest;
1708
+ const validation = queryConfigDecoder.run(parsedRequest);
1709
+ if (!validation.ok) {
1710
+ const errorMsg = `Cannot process a search request, because of validation error: ${JSON.stringify(validation.error)}`;
1711
+ this.logger.warn(`[${commandId}] ${errorMsg}`);
1712
+ throw new Error(errorMsg);
1713
+ }
1714
+ const validatedRequest = validation.result;
1715
+ return validatedRequest;
1716
+ }
1717
+ cleanUpQuery(queryId, commandId) {
1718
+ const activeQuery = this.activeQueries[queryId];
1719
+ clearTimeout(activeQuery.staleTimer);
1720
+ activeQuery.publisher.cleanPublisher(commandId);
1721
+ delete this.activeQueries[queryId];
1722
+ this.limitsTracker.cleanTracking(queryId);
1723
+ }
1724
+ cleanUpProvider(providerId, commandId) {
1725
+ this.registry.clearKey(`on-search-query-${providerId}`);
1726
+ this.registry.clearKey(`on-cancel-query-${providerId}`);
1727
+ delete this.providersModels[providerId];
1728
+ const queriesWithProvider = Object.values(this.activeQueries).filter((query) => !query.publisher.checkProviderSuspended(providerId));
1729
+ queriesWithProvider.forEach((query) => {
1730
+ this.processProviderQueryDone({
1731
+ identification: {
1732
+ queryId: query.queryId,
1733
+ providerId
1734
+ },
1735
+ commandId
1736
+ });
1737
+ });
1738
+ }
1739
+ async cleanUpProviderQuery(queryId, providerId, commandId) {
1740
+ const activeQuery = this.activeQueries[queryId];
1741
+ if (!activeQuery) {
1742
+ this.logger.warn(`[${commandId}] Cannot clean up a provider query ${queryId} for provider ${providerId} because there is no such active query`);
1743
+ return;
1744
+ }
1745
+ activeQuery.providersAtWork = activeQuery.providersAtWork.filter((provider) => provider.myProviderData.id !== providerId);
1746
+ await activeQuery.publisher.markProviderDone(providerId, commandId);
1747
+ }
1748
+ }
1807
1749
 
1808
- var version = "2.2.0";
1750
+ var version = "2.2.2";
1809
1751
 
1810
- class SearchFacade {
1811
- constructor(main) {
1812
- this.main = main;
1813
- }
1814
- exposeApi() {
1815
- const api = {
1816
- version,
1817
- setDebounceMS: this.setDebounceMS.bind(this),
1818
- getDebounceMS: this.getDebounceMS.bind(this),
1819
- listProviders: this.providers.bind(this),
1820
- listTypes: this.types.bind(this),
1821
- query: this.query.bind(this),
1822
- registerProvider: this.registerProvider.bind(this)
1823
- };
1824
- return Object.freeze(api);
1825
- }
1826
- setDebounceMS(milliseconds) {
1827
- nonNegativeNumberDecoder.runWithException(milliseconds);
1828
- const commandId = nanoid(10);
1829
- return this.main.setDebounceMS({ milliseconds, commandId });
1830
- }
1831
- getDebounceMS() {
1832
- const commandId = nanoid(10);
1833
- return this.main.getDebounceMS({ commandId });
1834
- }
1835
- providers() {
1836
- return __awaiter(this, void 0, void 0, function* () {
1837
- const commandId = nanoid(10);
1838
- return this.main.providers({ commandId });
1839
- });
1840
- }
1841
- types() {
1842
- return __awaiter(this, void 0, void 0, function* () {
1843
- const commandId = nanoid(10);
1844
- return this.main.types({ commandId });
1845
- });
1846
- }
1847
- query(queryConfig) {
1848
- return __awaiter(this, void 0, void 0, function* () {
1849
- const verifiedConfig = queryConfigDecoder.runWithException(queryConfig);
1850
- const commandId = nanoid(10);
1851
- return this.main.query({ queryConfig: verifiedConfig, commandId });
1852
- });
1853
- }
1854
- registerProvider(config) {
1855
- return __awaiter(this, void 0, void 0, function* () {
1856
- const verifiedConfig = providerRegistrationConfig.runWithException(config);
1857
- const commandId = nanoid(10);
1858
- return this.main.registerProvider({ config: verifiedConfig, commandId });
1859
- });
1860
- }
1861
- }
1752
+ class SearchFacade {
1753
+ main;
1754
+ constructor(main) {
1755
+ this.main = main;
1756
+ }
1757
+ exposeApi() {
1758
+ const api = {
1759
+ version,
1760
+ setDebounceMS: this.setDebounceMS.bind(this),
1761
+ getDebounceMS: this.getDebounceMS.bind(this),
1762
+ listProviders: this.providers.bind(this),
1763
+ listTypes: this.types.bind(this),
1764
+ query: this.query.bind(this),
1765
+ registerProvider: this.registerProvider.bind(this)
1766
+ };
1767
+ return Object.freeze(api);
1768
+ }
1769
+ setDebounceMS(milliseconds) {
1770
+ nonNegativeNumberDecoder.runWithException(milliseconds);
1771
+ const commandId = nanoid(10);
1772
+ return this.main.setDebounceMS({ milliseconds, commandId });
1773
+ }
1774
+ getDebounceMS() {
1775
+ const commandId = nanoid(10);
1776
+ return this.main.getDebounceMS({ commandId });
1777
+ }
1778
+ async providers() {
1779
+ const commandId = nanoid(10);
1780
+ return this.main.providers({ commandId });
1781
+ }
1782
+ async types() {
1783
+ const commandId = nanoid(10);
1784
+ return this.main.types({ commandId });
1785
+ }
1786
+ async query(queryConfig) {
1787
+ const verifiedConfig = queryConfigDecoder.runWithException(queryConfig);
1788
+ const commandId = nanoid(10);
1789
+ return this.main.query({ queryConfig: verifiedConfig, commandId });
1790
+ }
1791
+ async registerProvider(config) {
1792
+ const verifiedConfig = providerRegistrationConfig.runWithException(config);
1793
+ const commandId = nanoid(10);
1794
+ return this.main.registerProvider({ config: verifiedConfig, commandId });
1795
+ }
1796
+ }
1862
1797
 
1863
- class AsyncSequelizer {
1864
- constructor(minSequenceInterval = 0) {
1865
- this.minSequenceInterval = minSequenceInterval;
1866
- this.queue = [];
1867
- this.isExecutingQueue = false;
1868
- }
1869
- enqueue(action) {
1870
- return new Promise((resolve, reject) => {
1871
- this.queue.push({ action, resolve, reject });
1872
- this.executeQueue();
1873
- });
1874
- }
1875
- executeQueue() {
1876
- return __awaiter(this, void 0, void 0, function* () {
1877
- if (this.isExecutingQueue) {
1878
- return;
1879
- }
1880
- this.isExecutingQueue = true;
1881
- while (this.queue.length) {
1882
- const operation = this.queue.shift();
1883
- if (!operation) {
1884
- this.isExecutingQueue = false;
1885
- return;
1886
- }
1887
- try {
1888
- const actionResult = yield operation.action();
1889
- operation.resolve(actionResult);
1890
- }
1891
- catch (error) {
1892
- operation.reject(error);
1893
- }
1894
- yield this.intervalBreak();
1895
- }
1896
- this.isExecutingQueue = false;
1897
- });
1898
- }
1899
- intervalBreak() {
1900
- return new Promise((res) => setTimeout(res, this.minSequenceInterval));
1901
- }
1902
- }
1798
+ class AsyncSequelizer {
1799
+ minSequenceInterval;
1800
+ queue = [];
1801
+ isExecutingQueue = false;
1802
+ constructor(minSequenceInterval = 0) {
1803
+ this.minSequenceInterval = minSequenceInterval;
1804
+ }
1805
+ enqueue(action) {
1806
+ return new Promise((resolve, reject) => {
1807
+ this.queue.push({ action, resolve, reject });
1808
+ this.executeQueue();
1809
+ });
1810
+ }
1811
+ async executeQueue() {
1812
+ if (this.isExecutingQueue) {
1813
+ return;
1814
+ }
1815
+ this.isExecutingQueue = true;
1816
+ while (this.queue.length) {
1817
+ const operation = this.queue.shift();
1818
+ if (!operation) {
1819
+ this.isExecutingQueue = false;
1820
+ return;
1821
+ }
1822
+ try {
1823
+ const actionResult = await operation.action();
1824
+ operation.resolve(actionResult);
1825
+ }
1826
+ catch (error) {
1827
+ operation.reject(error);
1828
+ }
1829
+ await this.intervalBreak();
1830
+ }
1831
+ this.isExecutingQueue = false;
1832
+ }
1833
+ intervalBreak() {
1834
+ return new Promise((res) => setTimeout(res, this.minSequenceInterval));
1835
+ }
1836
+ }
1903
1837
 
1904
- class LimitsTracker {
1905
- constructor() {
1906
- this.limitsLookup = {};
1907
- this.limitsData = {};
1908
- }
1909
- enableTracking(limits, queryId) {
1910
- this.limitsLookup[queryId] = {};
1911
- this.limitsData[queryId] = {
1912
- maxResults: limits.maxResults ? limits.maxResults : Number.MAX_SAFE_INTEGER,
1913
- maxResultsPerType: limits.maxResultsPerType ? limits.maxResultsPerType : Number.MAX_SAFE_INTEGER
1914
- };
1915
- }
1916
- testResultLimit(command) {
1917
- const foundLookup = this.limitsLookup[command.identification.queryId];
1918
- const limitData = this.limitsData[command.identification.queryId];
1919
- if (!foundLookup || !limitData) {
1920
- return;
1921
- }
1922
- let providerStateLookup = foundLookup[command.identification.providerId];
1923
- if (!providerStateLookup) {
1924
- providerStateLookup = { total: 0 };
1925
- foundLookup[command.identification.providerId] = providerStateLookup;
1926
- }
1927
- if ((providerStateLookup.total + 1) > limitData.maxResults) {
1928
- return { maxLimitHit: true };
1929
- }
1930
- const resultTypeName = command.result.type.name;
1931
- if (!resultTypeName) {
1932
- return;
1933
- }
1934
- const currentResultTypeCount = providerStateLookup[resultTypeName] || 0;
1935
- if ((currentResultTypeCount + 1) > limitData.maxResultsPerType) {
1936
- return { maxLimitPerTypeHit: true };
1937
- }
1938
- }
1939
- update(command) {
1940
- const foundLookup = this.limitsLookup[command.identification.queryId];
1941
- const limitData = this.limitsData[command.identification.queryId];
1942
- if (!foundLookup || !limitData) {
1943
- return;
1944
- }
1945
- const providerStateLookup = foundLookup[command.identification.providerId];
1946
- providerStateLookup.total += 1;
1947
- const resultTypeName = command.result.type.name;
1948
- if (!resultTypeName) {
1949
- return;
1950
- }
1951
- providerStateLookup[resultTypeName] = providerStateLookup[resultTypeName] ? providerStateLookup[resultTypeName] + 1 : 1;
1952
- }
1953
- cleanTracking(queryId) {
1954
- delete this.limitsLookup[queryId];
1955
- delete this.limitsData[queryId];
1956
- }
1957
- }
1838
+ class LimitsTracker {
1839
+ limitsLookup = {};
1840
+ limitsData = {};
1841
+ enableTracking(limits, queryId) {
1842
+ this.limitsLookup[queryId] = {};
1843
+ this.limitsData[queryId] = {
1844
+ maxResults: limits.maxResults ? limits.maxResults : Number.MAX_SAFE_INTEGER,
1845
+ maxResultsPerType: limits.maxResultsPerType ? limits.maxResultsPerType : Number.MAX_SAFE_INTEGER
1846
+ };
1847
+ }
1848
+ testResultLimit(command) {
1849
+ const foundLookup = this.limitsLookup[command.identification.queryId];
1850
+ const limitData = this.limitsData[command.identification.queryId];
1851
+ if (!foundLookup || !limitData) {
1852
+ return;
1853
+ }
1854
+ let providerStateLookup = foundLookup[command.identification.providerId];
1855
+ if (!providerStateLookup) {
1856
+ providerStateLookup = { total: 0 };
1857
+ foundLookup[command.identification.providerId] = providerStateLookup;
1858
+ }
1859
+ if ((providerStateLookup.total + 1) > limitData.maxResults) {
1860
+ return { maxLimitHit: true };
1861
+ }
1862
+ const resultTypeName = command.result.type.name;
1863
+ if (!resultTypeName) {
1864
+ return;
1865
+ }
1866
+ const currentResultTypeCount = providerStateLookup[resultTypeName] || 0;
1867
+ if ((currentResultTypeCount + 1) > limitData.maxResultsPerType) {
1868
+ return { maxLimitPerTypeHit: true };
1869
+ }
1870
+ }
1871
+ update(command) {
1872
+ const foundLookup = this.limitsLookup[command.identification.queryId];
1873
+ const limitData = this.limitsData[command.identification.queryId];
1874
+ if (!foundLookup || !limitData) {
1875
+ return;
1876
+ }
1877
+ const providerStateLookup = foundLookup[command.identification.providerId];
1878
+ providerStateLookup.total += 1;
1879
+ const resultTypeName = command.result.type.name;
1880
+ if (!resultTypeName) {
1881
+ return;
1882
+ }
1883
+ providerStateLookup[resultTypeName] = providerStateLookup[resultTypeName] ? providerStateLookup[resultTypeName] + 1 : 1;
1884
+ }
1885
+ cleanTracking(queryId) {
1886
+ delete this.limitsLookup[queryId];
1887
+ delete this.limitsData[queryId];
1888
+ }
1889
+ }
1958
1890
 
1959
- class ClientQuery {
1960
- constructor(controller, logger, masterQueryId) {
1961
- this.controller = controller;
1962
- this.logger = logger;
1963
- this.masterQueryId = masterQueryId;
1964
- }
1965
- exposeFacade() {
1966
- const providerQueryFacade = {
1967
- cancel: this.cancel.bind(this),
1968
- onResults: this.onResults.bind(this),
1969
- onCompleted: this.onCompleted.bind(this),
1970
- onError: this.onError.bind(this)
1971
- };
1972
- return Object.freeze(providerQueryFacade);
1973
- }
1974
- cancel() {
1975
- return __awaiter(this, void 0, void 0, function* () {
1976
- const commandId = nanoid(10);
1977
- this.logger.info(`[${commandId}] received a valid query cancel request, forwarding to the controller.`);
1978
- yield this.controller.cancelQuery(this.masterQueryId, commandId);
1979
- this.logger.info(`[${commandId}] the cancel request was completed.`);
1980
- });
1981
- }
1982
- onResults(callback) {
1983
- if (typeof callback !== "function") {
1984
- throw new Error("onQuery requires a callback of type function");
1985
- }
1986
- const commandId = nanoid(10);
1987
- this.logger.info(`[${commandId}] received a valid query onResults request, forwarding to the controller.`);
1988
- const unsubscribe = this.controller.processClientOnResults({ callback, masterQueryId: this.masterQueryId, commandId });
1989
- this.logger.info(`[${commandId}] the onResults request was completed.`);
1990
- return unsubscribe;
1991
- }
1992
- onCompleted(callback) {
1993
- if (typeof callback !== "function") {
1994
- throw new Error("onQuery requires a callback of type function");
1995
- }
1996
- const commandId = nanoid(10);
1997
- this.logger.info(`[${commandId}] received a valid query onCompleted request, forwarding to the controller.`);
1998
- const unsubscribe = this.controller.processClientOnCompleted({ callback, masterQueryId: this.masterQueryId, commandId });
1999
- this.logger.info(`[${commandId}] the onCompleted request was completed.`);
2000
- return unsubscribe;
2001
- }
2002
- onError(callback) {
2003
- if (typeof callback !== "function") {
2004
- throw new Error("onQuery requires a callback of type function");
2005
- }
2006
- const commandId = nanoid(10);
2007
- this.logger.info(`[${commandId}] received a valid query onError request, forwarding to the controller.`);
2008
- const unsubscribe = this.controller.processClientOnError({ callback, masterQueryId: this.masterQueryId, commandId });
2009
- this.logger.info(`[${commandId}] the onError request was completed.`);
2010
- return unsubscribe;
2011
- }
2012
- }
1891
+ class ClientQuery {
1892
+ controller;
1893
+ logger;
1894
+ masterQueryId;
1895
+ constructor(controller, logger, masterQueryId) {
1896
+ this.controller = controller;
1897
+ this.logger = logger;
1898
+ this.masterQueryId = masterQueryId;
1899
+ }
1900
+ exposeFacade() {
1901
+ const providerQueryFacade = {
1902
+ cancel: this.cancel.bind(this),
1903
+ onResults: this.onResults.bind(this),
1904
+ onCompleted: this.onCompleted.bind(this),
1905
+ onError: this.onError.bind(this)
1906
+ };
1907
+ return Object.freeze(providerQueryFacade);
1908
+ }
1909
+ async cancel() {
1910
+ const commandId = nanoid(10);
1911
+ this.logger.info(`[${commandId}] received a valid query cancel request, forwarding to the controller.`);
1912
+ await this.controller.cancelQuery(this.masterQueryId, commandId);
1913
+ this.logger.info(`[${commandId}] the cancel request was completed.`);
1914
+ }
1915
+ onResults(callback) {
1916
+ if (typeof callback !== "function") {
1917
+ throw new Error("onQuery requires a callback of type function");
1918
+ }
1919
+ const commandId = nanoid(10);
1920
+ this.logger.info(`[${commandId}] received a valid query onResults request, forwarding to the controller.`);
1921
+ const unsubscribe = this.controller.processClientOnResults({ callback, masterQueryId: this.masterQueryId, commandId });
1922
+ this.logger.info(`[${commandId}] the onResults request was completed.`);
1923
+ return unsubscribe;
1924
+ }
1925
+ onCompleted(callback) {
1926
+ if (typeof callback !== "function") {
1927
+ throw new Error("onQuery requires a callback of type function");
1928
+ }
1929
+ const commandId = nanoid(10);
1930
+ this.logger.info(`[${commandId}] received a valid query onCompleted request, forwarding to the controller.`);
1931
+ const unsubscribe = this.controller.processClientOnCompleted({ callback, masterQueryId: this.masterQueryId, commandId });
1932
+ this.logger.info(`[${commandId}] the onCompleted request was completed.`);
1933
+ return unsubscribe;
1934
+ }
1935
+ onError(callback) {
1936
+ if (typeof callback !== "function") {
1937
+ throw new Error("onQuery requires a callback of type function");
1938
+ }
1939
+ const commandId = nanoid(10);
1940
+ this.logger.info(`[${commandId}] received a valid query onError request, forwarding to the controller.`);
1941
+ const unsubscribe = this.controller.processClientOnError({ callback, masterQueryId: this.masterQueryId, commandId });
1942
+ this.logger.info(`[${commandId}] the onError request was completed.`);
1943
+ return unsubscribe;
1944
+ }
1945
+ }
2013
1946
 
2014
- class ProviderModel {
2015
- constructor(myData, controller, logger) {
2016
- this.myData = myData;
2017
- this.controller = controller;
2018
- this.logger = logger;
2019
- }
2020
- get id() {
2021
- return this.myData.id;
2022
- }
2023
- get name() {
2024
- return this.myData.name;
2025
- }
2026
- get appName() {
2027
- return this.myData.appName;
2028
- }
2029
- get types() {
2030
- return this.myData.types;
2031
- }
2032
- get myProviderData() {
2033
- return Object.assign({}, this.myData);
2034
- }
2035
- exposeFacade() {
2036
- const providerFacade = {
2037
- interopId: this.myData.interopId,
2038
- id: this.id,
2039
- name: this.name,
2040
- appName: this.appName,
2041
- types: this.types,
2042
- onQuery: this.onQuery.bind(this),
2043
- onQueryCancel: this.onQueryCancel.bind(this),
2044
- unregister: this.unregister.bind(this)
2045
- };
2046
- return Object.freeze(providerFacade);
2047
- }
2048
- onQuery(callback) {
2049
- if (typeof callback !== "function") {
2050
- throw new Error("onQuery requires a callback of type function");
2051
- }
2052
- const commandId = nanoid(10);
2053
- this.logger.info(`[${commandId}] received a valid onQuery request, forwarding to the controller.`);
2054
- const unsubscribe = this.controller.processProviderOnQuery({ callback, id: this.id, commandId });
2055
- this.logger.info(`[${commandId}] the onQuery request was completed.`);
2056
- return unsubscribe;
2057
- }
2058
- onQueryCancel(callback) {
2059
- if (typeof callback !== "function") {
2060
- throw new Error("onQuery requires a callback of type function");
2061
- }
2062
- const commandId = nanoid(10);
2063
- this.logger.info(`[${commandId}] received a valid onQueryCancel request, forwarding to the controller.`);
2064
- const unsubscribe = this.controller.processProviderOnQueryCancel({ callback, id: this.id, commandId });
2065
- this.logger.info(`[${commandId}] the onQueryCancel request was completed.`);
2066
- return unsubscribe;
2067
- }
2068
- unregister() {
2069
- return __awaiter(this, void 0, void 0, function* () {
2070
- const commandId = nanoid(10);
2071
- this.logger.info(`[${commandId}] received a valid unregister request, forwarding to the controller.`);
2072
- yield this.controller.processProviderUnregister({ id: this.id, commandId });
2073
- this.logger.info(`[${commandId}] the unregister request was completed.`);
2074
- });
2075
- }
2076
- }
1947
+ class ProviderModel {
1948
+ myData;
1949
+ controller;
1950
+ logger;
1951
+ constructor(myData, controller, logger) {
1952
+ this.myData = myData;
1953
+ this.controller = controller;
1954
+ this.logger = logger;
1955
+ }
1956
+ get id() {
1957
+ return this.myData.id;
1958
+ }
1959
+ get name() {
1960
+ return this.myData.name;
1961
+ }
1962
+ get appName() {
1963
+ return this.myData.appName;
1964
+ }
1965
+ get types() {
1966
+ return this.myData.types;
1967
+ }
1968
+ get myProviderData() {
1969
+ return Object.assign({}, this.myData);
1970
+ }
1971
+ exposeFacade() {
1972
+ const providerFacade = {
1973
+ interopId: this.myData.interopId,
1974
+ id: this.id,
1975
+ name: this.name,
1976
+ appName: this.appName,
1977
+ types: this.types,
1978
+ onQuery: this.onQuery.bind(this),
1979
+ onQueryCancel: this.onQueryCancel.bind(this),
1980
+ unregister: this.unregister.bind(this)
1981
+ };
1982
+ return Object.freeze(providerFacade);
1983
+ }
1984
+ onQuery(callback) {
1985
+ if (typeof callback !== "function") {
1986
+ throw new Error("onQuery requires a callback of type function");
1987
+ }
1988
+ const commandId = nanoid(10);
1989
+ this.logger.info(`[${commandId}] received a valid onQuery request, forwarding to the controller.`);
1990
+ const unsubscribe = this.controller.processProviderOnQuery({ callback, id: this.id, commandId });
1991
+ this.logger.info(`[${commandId}] the onQuery request was completed.`);
1992
+ return unsubscribe;
1993
+ }
1994
+ onQueryCancel(callback) {
1995
+ if (typeof callback !== "function") {
1996
+ throw new Error("onQuery requires a callback of type function");
1997
+ }
1998
+ const commandId = nanoid(10);
1999
+ this.logger.info(`[${commandId}] received a valid onQueryCancel request, forwarding to the controller.`);
2000
+ const unsubscribe = this.controller.processProviderOnQueryCancel({ callback, id: this.id, commandId });
2001
+ this.logger.info(`[${commandId}] the onQueryCancel request was completed.`);
2002
+ return unsubscribe;
2003
+ }
2004
+ async unregister() {
2005
+ const commandId = nanoid(10);
2006
+ this.logger.info(`[${commandId}] received a valid unregister request, forwarding to the controller.`);
2007
+ await this.controller.processProviderUnregister({ id: this.id, commandId });
2008
+ this.logger.info(`[${commandId}] the unregister request was completed.`);
2009
+ }
2010
+ }
2077
2011
 
2078
- class ProviderQueryModel {
2079
- constructor(myData, controller, logger, identification) {
2080
- this.myData = myData;
2081
- this.controller = controller;
2082
- this.logger = logger;
2083
- this.identification = identification;
2084
- }
2085
- get id() {
2086
- return this.identification.queryId;
2087
- }
2088
- get search() {
2089
- return this.myData.search;
2090
- }
2091
- get providers() {
2092
- return this.myData.providers;
2093
- }
2094
- get types() {
2095
- return this.myData.types;
2096
- }
2097
- get providerLimits() {
2098
- return this.myData.providerLimits;
2099
- }
2100
- get myQueryData() {
2101
- return Object.assign({}, this.myData);
2102
- }
2103
- exposeFacade() {
2104
- const providerQueryFacade = {
2105
- id: this.id,
2106
- search: this.search,
2107
- providers: this.providers,
2108
- types: this.types,
2109
- providerLimits: this.providerLimits,
2110
- sendResult: this.sendResult.bind(this),
2111
- error: this.error.bind(this),
2112
- done: this.done.bind(this)
2113
- };
2114
- return Object.freeze(providerQueryFacade);
2115
- }
2116
- sendResult(result) {
2117
- queryResultDecoder.runWithException(result);
2118
- const commandId = nanoid(10);
2119
- this.logger.trace(`[${commandId}] Received a valid result, forwarding to the controller`);
2120
- return this.controller.processProviderQueryResult({ identification: this.identification, result, commandId });
2121
- }
2122
- error(error) {
2123
- const commandId = nanoid(10);
2124
- nonEmptyStringDecoder.runWithException(error);
2125
- this.logger.trace(`[${commandId}] Received a valid error, forwarding to the controller`);
2126
- this.controller.processProviderQueryError({ identification: this.identification, error, commandId }).catch((error) => this.logger.warn(`Error processing the error signal for this provider: ${this.id}, error: ${extractErrorMsg(error)}`));
2127
- }
2128
- done() {
2129
- const commandId = nanoid(10);
2130
- this.logger.trace(`[${commandId}] Received a valid done, forwarding to the controller`);
2131
- this.controller.processProviderQueryDone({ identification: this.identification, commandId }).catch((error) => this.logger.warn(`Error processing the done signal for this provider: ${this.identification.providerId}, error: ${extractErrorMsg(error)}`));
2132
- }
2133
- }
2012
+ class ProviderQueryModel {
2013
+ myData;
2014
+ controller;
2015
+ logger;
2016
+ identification;
2017
+ constructor(myData, controller, logger, identification) {
2018
+ this.myData = myData;
2019
+ this.controller = controller;
2020
+ this.logger = logger;
2021
+ this.identification = identification;
2022
+ }
2023
+ get id() {
2024
+ return this.identification.queryId;
2025
+ }
2026
+ get search() {
2027
+ return this.myData.search;
2028
+ }
2029
+ get providers() {
2030
+ return this.myData.providers;
2031
+ }
2032
+ get types() {
2033
+ return this.myData.types;
2034
+ }
2035
+ get providerLimits() {
2036
+ return this.myData.providerLimits;
2037
+ }
2038
+ get myQueryData() {
2039
+ return Object.assign({}, this.myData);
2040
+ }
2041
+ exposeFacade() {
2042
+ const providerQueryFacade = {
2043
+ id: this.id,
2044
+ search: this.search,
2045
+ providers: this.providers,
2046
+ types: this.types,
2047
+ providerLimits: this.providerLimits,
2048
+ sendResult: this.sendResult.bind(this),
2049
+ error: this.error.bind(this),
2050
+ done: this.done.bind(this)
2051
+ };
2052
+ return Object.freeze(providerQueryFacade);
2053
+ }
2054
+ sendResult(result) {
2055
+ queryResultDecoder.runWithException(result);
2056
+ const commandId = nanoid(10);
2057
+ this.logger.trace(`[${commandId}] Received a valid result, forwarding to the controller`);
2058
+ return this.controller.processProviderQueryResult({ identification: this.identification, result, commandId });
2059
+ }
2060
+ error(error) {
2061
+ const commandId = nanoid(10);
2062
+ nonEmptyStringDecoder.runWithException(error);
2063
+ this.logger.trace(`[${commandId}] Received a valid error, forwarding to the controller`);
2064
+ this.controller.processProviderQueryError({ identification: this.identification, error, commandId }).catch((error) => this.logger.warn(`Error processing the error signal for this provider: ${this.id}, error: ${extractErrorMsg(error)}`));
2065
+ }
2066
+ done() {
2067
+ const commandId = nanoid(10);
2068
+ this.logger.trace(`[${commandId}] Received a valid done, forwarding to the controller`);
2069
+ this.controller.processProviderQueryDone({ identification: this.identification, commandId }).catch((error) => this.logger.warn(`Error processing the done signal for this provider: ${this.identification.providerId}, error: ${extractErrorMsg(error)}`));
2070
+ }
2071
+ }
2134
2072
 
2135
- class QueryResultsPublisher {
2136
- constructor(sequelizer, glueController, logger, clientInstanceId, queryId, isLegacy) {
2137
- this.sequelizer = sequelizer;
2138
- this.glueController = glueController;
2139
- this.logger = logger;
2140
- this.clientInstanceId = clientInstanceId;
2141
- this.queryId = queryId;
2142
- this.isLegacy = isLegacy;
2143
- this.queues = {};
2144
- }
2145
- checkProviderSuspended(providerId) {
2146
- return this.queues[providerId] ? !!this.queues[providerId].suspended : false;
2147
- }
2148
- syncSuspendProvider(providerId, commandId) {
2149
- const providerQueue = this.queues[providerId];
2150
- if (!providerQueue) {
2151
- this.logger.warn(`[${commandId}] Cannot suspend provider: ${providerId}, because there is no provider queue. This happens when the provider queue was already cancelled or completed`);
2152
- return;
2153
- }
2154
- providerQueue.suspended = true;
2155
- }
2156
- configureProviders(providers) {
2157
- providers.forEach((provider) => {
2158
- this.queues[provider.myProviderData.id] = {
2159
- providerData: provider,
2160
- pendingResults: []
2161
- };
2162
- });
2163
- }
2164
- queueResult(command) {
2165
- const { commandId, identification } = command;
2166
- this.logger.trace(`[${commandId}] Queuing a new result from provider: ${identification.providerId}`);
2167
- const providerQueue = this.queues[identification.providerId];
2168
- if (!providerQueue) {
2169
- this.logger.warn(`[${commandId}] Cannot queue this result, because there is no provider queue. This happens when the provider queue was already cancelled or completed`);
2170
- return;
2171
- }
2172
- const result = this.isLegacy ? this.translateLegacySearchItem(command.result) : command.result;
2173
- providerQueue.pendingResults.push(result);
2174
- clearTimeout(providerQueue.flushTimer);
2175
- if (providerQueue.pendingResults.length === 10) {
2176
- this.logger.trace(`[${commandId}] Reached the limit in the queue buffer, flushing to the client.`);
2177
- this.flushProviderQueue(identification.providerId, commandId);
2178
- return;
2179
- }
2180
- this.logger.trace(`[${commandId}] The limit in the queue buffer is not reached yet, setting a flush timer.`);
2181
- providerQueue.flushTimer = setTimeout(() => {
2182
- this.logger.trace(`[${commandId}] Reached the time limit in the queue buffer, flushing to the client.`);
2183
- this.flushProviderQueue(identification.providerId, commandId);
2184
- }, FLUSH_TIMEOUT_MS);
2185
- }
2186
- cancel(commandId) {
2187
- this.logger.trace(`[${commandId}] Cancelling queue ${this.queryId}.`);
2188
- Object.values(this.queues).forEach((queue) => clearTimeout(queue.flushTimer));
2189
- this.queues = {};
2190
- this.logger.trace(`[${commandId}] Queue ${this.queryId} publisher cancelled.`);
2191
- }
2192
- markProviderDone(providerId, commandId) {
2193
- return __awaiter(this, void 0, void 0, function* () {
2194
- this.logger.trace(`[${commandId}] Marking provider ${providerId} as done.`);
2195
- const providerQueue = this.queues[providerId];
2196
- if (!providerQueue) {
2197
- this.logger.info(`[${commandId}] Cannot mark this queue as done, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent an error`);
2198
- return;
2199
- }
2200
- clearTimeout(providerQueue.flushTimer);
2201
- yield this.flushProviderQueue(providerId, commandId);
2202
- delete this.queues[providerId];
2203
- this.logger.trace(`[${commandId}] Provider ${providerId} marked as done.`);
2204
- });
2205
- }
2206
- markProviderError(command) {
2207
- const providerQueue = this.queues[command.identification.providerId];
2208
- if (!providerQueue) {
2209
- this.logger.warn(`[${command.commandId}] Cannot mark this provider as errored, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`);
2210
- return;
2211
- }
2212
- this.glueController.sendClientErrorMessage(command.error, this.clientInstanceId, this.queryId, providerQueue.providerData.myProviderData)
2213
- .catch((error) => this.logger.warn(`[${command.commandId}] The client errored when handling error message for query: ${this.queryId} -> ${extractErrorMsg(error)}`));
2214
- }
2215
- cleanPublisher(commandId) {
2216
- Object.values(this.queues).forEach((queue) => clearTimeout(queue.flushTimer));
2217
- this.queues = {};
2218
- this.glueController.sendClientQueueCompleted(this.clientInstanceId, this.queryId)
2219
- .catch((error) => this.logger.warn(`[${commandId}] The client errored when handling search end message for query: ${this.queryId} -> ${extractErrorMsg(error)}`));
2220
- }
2221
- flushProviderQueue(providerId, commandId) {
2222
- return __awaiter(this, void 0, void 0, function* () {
2223
- yield this.sequelizer.enqueue(() => __awaiter(this, void 0, void 0, function* () {
2224
- const providerQueue = this.queues[providerId];
2225
- if (!providerQueue) {
2226
- this.logger.warn(`[${commandId}] Cannot flush this queue, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`);
2227
- return;
2228
- }
2229
- if (!providerQueue.pendingResults.length) {
2230
- this.logger.info(`[${commandId}] This provider does not have any pending results to flush.`);
2231
- return;
2232
- }
2233
- const resultBatch = {
2234
- results: providerQueue.pendingResults,
2235
- provider: providerQueue.providerData.myProviderData
2236
- };
2237
- providerQueue.pendingResults = [];
2238
- try {
2239
- yield this.glueController.sendClientResultsBatch(resultBatch, this.clientInstanceId, this.queryId);
2240
- }
2241
- catch (error) {
2242
- this.logger.warn(`[${commandId}] The client errored when handling search results for query: ${this.queryId} -> ${extractErrorMsg(error)}`);
2243
- }
2244
- }));
2245
- });
2246
- }
2247
- translateLegacySearchItem(searchResult) {
2248
- return {
2249
- type: searchResult.type.name,
2250
- category: searchResult.type.displayName,
2251
- id: searchResult.id,
2252
- displayName: searchResult.displayName,
2253
- description: searchResult.description,
2254
- iconURL: searchResult.iconURL,
2255
- action: searchResult.action
2256
- };
2257
- }
2258
- }
2073
+ class QueryResultsPublisher {
2074
+ sequelizer;
2075
+ glueController;
2076
+ logger;
2077
+ clientInstanceId;
2078
+ queryId;
2079
+ isLegacy;
2080
+ queues = {};
2081
+ constructor(sequelizer, glueController, logger, clientInstanceId, queryId, isLegacy) {
2082
+ this.sequelizer = sequelizer;
2083
+ this.glueController = glueController;
2084
+ this.logger = logger;
2085
+ this.clientInstanceId = clientInstanceId;
2086
+ this.queryId = queryId;
2087
+ this.isLegacy = isLegacy;
2088
+ }
2089
+ checkProviderSuspended(providerId) {
2090
+ return this.queues[providerId] ? !!this.queues[providerId].suspended : false;
2091
+ }
2092
+ syncSuspendProvider(providerId, commandId) {
2093
+ const providerQueue = this.queues[providerId];
2094
+ if (!providerQueue) {
2095
+ this.logger.warn(`[${commandId}] Cannot suspend provider: ${providerId}, because there is no provider queue. This happens when the provider queue was already cancelled or completed`);
2096
+ return;
2097
+ }
2098
+ providerQueue.suspended = true;
2099
+ }
2100
+ configureProviders(providers) {
2101
+ providers.forEach((provider) => {
2102
+ this.queues[provider.myProviderData.id] = {
2103
+ providerData: provider,
2104
+ pendingResults: []
2105
+ };
2106
+ });
2107
+ }
2108
+ queueResult(command) {
2109
+ const { commandId, identification } = command;
2110
+ this.logger.trace(`[${commandId}] Queuing a new result from provider: ${identification.providerId}`);
2111
+ const providerQueue = this.queues[identification.providerId];
2112
+ if (!providerQueue) {
2113
+ this.logger.warn(`[${commandId}] Cannot queue this result, because there is no provider queue. This happens when the provider queue was already cancelled or completed`);
2114
+ return;
2115
+ }
2116
+ const result = this.isLegacy ? this.translateLegacySearchItem(command.result) : command.result;
2117
+ providerQueue.pendingResults.push(result);
2118
+ clearTimeout(providerQueue.flushTimer);
2119
+ if (providerQueue.pendingResults.length === 10) {
2120
+ this.logger.trace(`[${commandId}] Reached the limit in the queue buffer, flushing to the client.`);
2121
+ this.flushProviderQueue(identification.providerId, commandId);
2122
+ return;
2123
+ }
2124
+ this.logger.trace(`[${commandId}] The limit in the queue buffer is not reached yet, setting a flush timer.`);
2125
+ providerQueue.flushTimer = setTimeout(() => {
2126
+ this.logger.trace(`[${commandId}] Reached the time limit in the queue buffer, flushing to the client.`);
2127
+ this.flushProviderQueue(identification.providerId, commandId);
2128
+ }, FLUSH_TIMEOUT_MS);
2129
+ }
2130
+ cancel(commandId) {
2131
+ this.logger.trace(`[${commandId}] Cancelling queue ${this.queryId}.`);
2132
+ Object.values(this.queues).forEach((queue) => clearTimeout(queue.flushTimer));
2133
+ this.queues = {};
2134
+ this.logger.trace(`[${commandId}] Queue ${this.queryId} publisher cancelled.`);
2135
+ }
2136
+ async markProviderDone(providerId, commandId) {
2137
+ this.logger.trace(`[${commandId}] Marking provider ${providerId} as done.`);
2138
+ const providerQueue = this.queues[providerId];
2139
+ if (!providerQueue) {
2140
+ this.logger.info(`[${commandId}] Cannot mark this queue as done, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent an error`);
2141
+ return;
2142
+ }
2143
+ clearTimeout(providerQueue.flushTimer);
2144
+ await this.flushProviderQueue(providerId, commandId);
2145
+ delete this.queues[providerId];
2146
+ this.logger.trace(`[${commandId}] Provider ${providerId} marked as done.`);
2147
+ }
2148
+ markProviderError(command) {
2149
+ const providerQueue = this.queues[command.identification.providerId];
2150
+ if (!providerQueue) {
2151
+ this.logger.warn(`[${command.commandId}] Cannot mark this provider as errored, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`);
2152
+ return;
2153
+ }
2154
+ this.glueController.sendClientErrorMessage(command.error, this.clientInstanceId, this.queryId, providerQueue.providerData.myProviderData)
2155
+ .catch((error) => this.logger.warn(`[${command.commandId}] The client errored when handling error message for query: ${this.queryId} -> ${extractErrorMsg(error)}`));
2156
+ }
2157
+ cleanPublisher(commandId) {
2158
+ Object.values(this.queues).forEach((queue) => clearTimeout(queue.flushTimer));
2159
+ this.queues = {};
2160
+ this.glueController.sendClientQueueCompleted(this.clientInstanceId, this.queryId)
2161
+ .catch((error) => this.logger.warn(`[${commandId}] The client errored when handling search end message for query: ${this.queryId} -> ${extractErrorMsg(error)}`));
2162
+ }
2163
+ async flushProviderQueue(providerId, commandId) {
2164
+ await this.sequelizer.enqueue(async () => {
2165
+ const providerQueue = this.queues[providerId];
2166
+ if (!providerQueue) {
2167
+ this.logger.warn(`[${commandId}] Cannot flush this queue, because there is no provider queue. This happens when the provider queue was already cancelled, completed or the provider sent and error`);
2168
+ return;
2169
+ }
2170
+ if (!providerQueue.pendingResults.length) {
2171
+ this.logger.info(`[${commandId}] This provider does not have any pending results to flush.`);
2172
+ return;
2173
+ }
2174
+ const resultBatch = {
2175
+ results: providerQueue.pendingResults,
2176
+ provider: providerQueue.providerData.myProviderData
2177
+ };
2178
+ providerQueue.pendingResults = [];
2179
+ try {
2180
+ await this.glueController.sendClientResultsBatch(resultBatch, this.clientInstanceId, this.queryId);
2181
+ }
2182
+ catch (error) {
2183
+ this.logger.warn(`[${commandId}] The client errored when handling search results for query: ${this.queryId} -> ${extractErrorMsg(error)}`);
2184
+ }
2185
+ });
2186
+ }
2187
+ translateLegacySearchItem(searchResult) {
2188
+ return {
2189
+ type: searchResult.type.name,
2190
+ category: searchResult.type.displayName,
2191
+ id: searchResult.id,
2192
+ displayName: searchResult.displayName,
2193
+ description: searchResult.description,
2194
+ iconURL: searchResult.iconURL,
2195
+ action: searchResult.action
2196
+ };
2197
+ }
2198
+ }
2259
2199
 
2260
- class ModelFactory {
2261
- constructor(glueController, glue, flushSequelizer) {
2262
- this.glueController = glueController;
2263
- this.glue = glue;
2264
- this.flushSequelizer = flushSequelizer;
2265
- }
2266
- buildProviderModel(providerData, controller) {
2267
- return new ProviderModel(providerData, controller, this.glue.logger.subLogger(`search.provider.model.${providerData.name}`));
2268
- }
2269
- buildProviderQueryModel(queryConfig, identification, controller) {
2270
- return new ProviderQueryModel(queryConfig, controller, this.glue.logger.subLogger(`search.provider.${identification.providerId}.query.${identification.queryId}`), identification);
2271
- }
2272
- buildPublisher(clientInstanceId, queryId, isLegacy) {
2273
- return new QueryResultsPublisher(this.flushSequelizer, this.glueController, this.glue.logger.subLogger(`search.results.publisher.${queryId}`), clientInstanceId, queryId, isLegacy);
2274
- }
2275
- buildClientQueryModel(masterQueryId, controller) {
2276
- return new ClientQuery(controller, this.glue.logger.subLogger(`search.provider.model.${masterQueryId}`), masterQueryId);
2277
- }
2278
- }
2200
+ class ModelFactory {
2201
+ glueController;
2202
+ glue;
2203
+ flushSequelizer;
2204
+ constructor(glueController, glue, flushSequelizer) {
2205
+ this.glueController = glueController;
2206
+ this.glue = glue;
2207
+ this.flushSequelizer = flushSequelizer;
2208
+ }
2209
+ buildProviderModel(providerData, controller) {
2210
+ return new ProviderModel(providerData, controller, this.glue.logger.subLogger(`search.provider.model.${providerData.name}`));
2211
+ }
2212
+ buildProviderQueryModel(queryConfig, identification, controller) {
2213
+ return new ProviderQueryModel(queryConfig, controller, this.glue.logger.subLogger(`search.provider.${identification.providerId}.query.${identification.queryId}`), identification);
2214
+ }
2215
+ buildPublisher(clientInstanceId, queryId, isLegacy) {
2216
+ return new QueryResultsPublisher(this.flushSequelizer, this.glueController, this.glue.logger.subLogger(`search.results.publisher.${queryId}`), clientInstanceId, queryId, isLegacy);
2217
+ }
2218
+ buildClientQueryModel(masterQueryId, controller) {
2219
+ return new ClientQuery(controller, this.glue.logger.subLogger(`search.provider.model.${masterQueryId}`), masterQueryId);
2220
+ }
2221
+ }
2279
2222
 
2280
- class IoC {
2281
- constructor(glue, config) {
2282
- this.glue = glue;
2283
- this.config = config;
2284
- }
2285
- get glueController() {
2286
- if (!this._glueController) {
2287
- this._glueController = new GlueController(this.glue);
2288
- }
2289
- return this._glueController;
2290
- }
2291
- get main() {
2292
- if (!this._mainController) {
2293
- this._mainController = new MainController(this.glue.logger.subLogger("search.main.controller"), this.glueController, this.clientController, this.providerController);
2294
- }
2295
- return this._mainController;
2296
- }
2297
- get clientController() {
2298
- if (!this._clientController) {
2299
- this._clientController = new ClientController(this.glue.logger.subLogger("search.client.controller"), this.glueController, this.modelFactory);
2300
- }
2301
- return this._clientController;
2302
- }
2303
- get providerController() {
2304
- if (!this._providerController) {
2305
- this._providerController = new ProviderController(this.glue.logger.subLogger("search.provider.controller"), this.glueController, this.sequelizer, this.limitsTracker, this.modelFactory);
2306
- }
2307
- return this._providerController;
2308
- }
2309
- get facade() {
2310
- if (!this._facade) {
2311
- this._facade = new SearchFacade(this.main);
2312
- }
2313
- return this._facade;
2314
- }
2315
- get sequelizer() {
2316
- if (!this._asyncSequelizer) {
2317
- this._asyncSequelizer = new AsyncSequelizer(SEQUELIZER_INTERVAL_MS);
2318
- }
2319
- return this._asyncSequelizer;
2320
- }
2321
- get flushSequelizer() {
2322
- if (!this._flushSequelizer) {
2323
- this._flushSequelizer = new AsyncSequelizer(FLUSH_SEQUELIZER_INTERVAL_MS);
2324
- }
2325
- return this._flushSequelizer;
2326
- }
2327
- get limitsTracker() {
2328
- if (!this._limitsTracker) {
2329
- this._limitsTracker = new LimitsTracker();
2330
- }
2331
- return this._limitsTracker;
2332
- }
2333
- get modelFactory() {
2334
- if (!this._modelFactory) {
2335
- this._modelFactory = new ModelFactory(this.glueController, this.glue, this.flushSequelizer);
2336
- }
2337
- return this._modelFactory;
2338
- }
2339
- }
2223
+ class IoC {
2224
+ glue;
2225
+ config;
2226
+ _glueController;
2227
+ _facade;
2228
+ _mainController;
2229
+ _providerController;
2230
+ _clientController;
2231
+ _asyncSequelizer;
2232
+ _flushSequelizer;
2233
+ _limitsTracker;
2234
+ _modelFactory;
2235
+ constructor(glue, config) {
2236
+ this.glue = glue;
2237
+ this.config = config;
2238
+ }
2239
+ get glueController() {
2240
+ if (!this._glueController) {
2241
+ this._glueController = new GlueController(this.glue);
2242
+ }
2243
+ return this._glueController;
2244
+ }
2245
+ get main() {
2246
+ if (!this._mainController) {
2247
+ this._mainController = new MainController(this.glue.logger.subLogger("search.main.controller"), this.glueController, this.clientController, this.providerController);
2248
+ }
2249
+ return this._mainController;
2250
+ }
2251
+ get clientController() {
2252
+ if (!this._clientController) {
2253
+ this._clientController = new ClientController(this.glue.logger.subLogger("search.client.controller"), this.glueController, this.modelFactory);
2254
+ }
2255
+ return this._clientController;
2256
+ }
2257
+ get providerController() {
2258
+ if (!this._providerController) {
2259
+ this._providerController = new ProviderController(this.glue.logger.subLogger("search.provider.controller"), this.glueController, this.sequelizer, this.limitsTracker, this.modelFactory);
2260
+ }
2261
+ return this._providerController;
2262
+ }
2263
+ get facade() {
2264
+ if (!this._facade) {
2265
+ this._facade = new SearchFacade(this.main);
2266
+ }
2267
+ return this._facade;
2268
+ }
2269
+ get sequelizer() {
2270
+ if (!this._asyncSequelizer) {
2271
+ this._asyncSequelizer = new AsyncSequelizer(SEQUELIZER_INTERVAL_MS);
2272
+ }
2273
+ return this._asyncSequelizer;
2274
+ }
2275
+ get flushSequelizer() {
2276
+ if (!this._flushSequelizer) {
2277
+ this._flushSequelizer = new AsyncSequelizer(FLUSH_SEQUELIZER_INTERVAL_MS);
2278
+ }
2279
+ return this._flushSequelizer;
2280
+ }
2281
+ get limitsTracker() {
2282
+ if (!this._limitsTracker) {
2283
+ this._limitsTracker = new LimitsTracker();
2284
+ }
2285
+ return this._limitsTracker;
2286
+ }
2287
+ get modelFactory() {
2288
+ if (!this._modelFactory) {
2289
+ this._modelFactory = new ModelFactory(this.glueController, this.glue, this.flushSequelizer);
2290
+ }
2291
+ return this._modelFactory;
2292
+ }
2293
+ }
2340
2294
 
2341
- const factoryFunction = (io, config) => __awaiter(void 0, void 0, void 0, function* () {
2342
- const ioc = new IoC(io, config);
2343
- io.search = ioc.facade.exposeApi();
2344
- });
2345
- if (typeof window !== "undefined") {
2346
- window.IOSearch = factoryFunction;
2347
- }
2295
+ const factoryFunction = async (io, config) => {
2296
+ const ioc = new IoC(io, config);
2297
+ io.search = ioc.facade.exposeApi();
2298
+ };
2299
+ if (typeof window !== "undefined") {
2300
+ window.IOSearch = factoryFunction;
2301
+ }
2348
2302
 
2349
- return factoryFunction;
2303
+ return factoryFunction;
2350
2304
 
2351
2305
  }));
2352
2306
  //# sourceMappingURL=search-api.umd.js.map