-
Notifications
You must be signed in to change notification settings - Fork 236
/
worker.js
4898 lines (4427 loc) · 166 KB
/
worker.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var MyBundle = (function (exports) {
"use strict";
/**
* @license
* Copyright 2019 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
const proxyMarker = Symbol("Comlink.proxy");
const createEndpoint = Symbol("Comlink.endpoint");
const releaseProxy = Symbol("Comlink.releaseProxy");
const finalizer = Symbol("Comlink.finalizer");
const throwMarker = Symbol("Comlink.thrown");
const isObject = (val) =>
(typeof val === "object" && val !== null) || typeof val === "function";
/**
* Internal transfer handle to handle objects marked to proxy.
*/
const proxyTransferHandler = {
canHandle: (val) => isObject(val) && val[proxyMarker],
serialize(obj) {
const { port1, port2 } = new MessageChannel();
expose(obj, port1);
return [port2, [port2]];
},
deserialize(port) {
port.start();
return wrap(port);
},
};
/**
* Internal transfer handler to handle thrown exceptions.
*/
const throwTransferHandler = {
canHandle: (value) => isObject(value) && throwMarker in value,
serialize({ value }) {
let serialized;
if (value instanceof Error) {
serialized = {
isError: true,
value: {
message: value.message,
name: value.name,
stack: value.stack,
},
};
} else {
serialized = { isError: false, value };
}
return [serialized, []];
},
deserialize(serialized) {
if (serialized.isError) {
throw Object.assign(
new Error(serialized.value.message),
serialized.value
);
}
throw serialized.value;
},
};
/**
* Allows customizing the serialization of certain values.
*/
const transferHandlers = new Map([
["proxy", proxyTransferHandler],
["throw", throwTransferHandler],
]);
function isAllowedOrigin(allowedOrigins, origin) {
for (const allowedOrigin of allowedOrigins) {
if (origin === allowedOrigin || allowedOrigin === "*") {
return true;
}
if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {
return true;
}
}
return false;
}
function expose(obj, ep = globalThis, allowedOrigins = ["*"]) {
ep.addEventListener("message", function callback(ev) {
if (!ev || !ev.data) {
return;
}
if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
return;
}
const { id, type, path } = Object.assign({ path: [] }, ev.data);
const argumentList = (ev.data.argumentList || []).map(fromWireValue);
let returnValue;
try {
const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);
const rawValue = path.reduce((obj, prop) => obj[prop], obj);
switch (type) {
case "GET" /* MessageType.GET */:
{
returnValue = rawValue;
}
break;
case "SET" /* MessageType.SET */:
{
parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
returnValue = true;
}
break;
case "APPLY" /* MessageType.APPLY */:
{
returnValue = rawValue.apply(parent, argumentList);
}
break;
case "CONSTRUCT" /* MessageType.CONSTRUCT */:
{
const value = new rawValue(...argumentList);
returnValue = proxy(value);
}
break;
case "ENDPOINT" /* MessageType.ENDPOINT */:
{
const { port1, port2 } = new MessageChannel();
expose(obj, port2);
returnValue = transfer(port1, [port1]);
}
break;
case "RELEASE" /* MessageType.RELEASE */:
{
returnValue = undefined;
}
break;
default:
return;
}
} catch (value) {
returnValue = { value, [throwMarker]: 0 };
}
Promise.resolve(returnValue)
.catch((value) => {
return { value, [throwMarker]: 0 };
})
.then((returnValue) => {
const [wireValue, transferables] = toWireValue(returnValue);
ep.postMessage(
Object.assign(Object.assign({}, wireValue), { id }),
transferables
);
if (type === "RELEASE" /* MessageType.RELEASE */) {
// detach and deactive after sending release response above.
ep.removeEventListener("message", callback);
closeEndPoint(ep);
if (finalizer in obj && typeof obj[finalizer] === "function") {
obj[finalizer]();
}
}
})
.catch((error) => {
// Send Serialization Error To Caller
const [wireValue, transferables] = toWireValue({
value: new TypeError("Unserializable return value"),
[throwMarker]: 0,
});
ep.postMessage(
Object.assign(Object.assign({}, wireValue), { id }),
transferables
);
});
});
if (ep.start) {
ep.start();
}
}
function isMessagePort(endpoint) {
return endpoint.constructor.name === "MessagePort";
}
function closeEndPoint(endpoint) {
if (isMessagePort(endpoint)) endpoint.close();
}
function wrap(ep, target) {
const pendingListeners = new Map();
ep.addEventListener("message", function handleMessage(ev) {
const { data } = ev;
if (!data || !data.id) {
return;
}
const resolver = pendingListeners.get(data.id);
if (!resolver) {
return;
}
try {
resolver(data);
} finally {
pendingListeners.delete(data.id);
}
});
return createProxy(ep, pendingListeners, [], target);
}
function throwIfProxyReleased(isReleased) {
if (isReleased) {
throw new Error("Proxy has been released and is not useable");
}
}
function releaseEndpoint(ep) {
return requestResponseMessage(ep, new Map(), {
type: "RELEASE" /* MessageType.RELEASE */,
}).then(() => {
closeEndPoint(ep);
});
}
const proxyCounter = new WeakMap();
const proxyFinalizers =
"FinalizationRegistry" in globalThis &&
new FinalizationRegistry((ep) => {
const newCount = (proxyCounter.get(ep) || 0) - 1;
proxyCounter.set(ep, newCount);
if (newCount === 0) {
releaseEndpoint(ep);
}
});
function registerProxy(proxy, ep) {
const newCount = (proxyCounter.get(ep) || 0) + 1;
proxyCounter.set(ep, newCount);
if (proxyFinalizers) {
proxyFinalizers.register(proxy, ep, proxy);
}
}
function unregisterProxy(proxy) {
if (proxyFinalizers) {
proxyFinalizers.unregister(proxy);
}
}
function createProxy(
ep,
pendingListeners,
path = [],
target = function () {}
) {
let isProxyReleased = false;
const proxy = new Proxy(target, {
get(_target, prop) {
throwIfProxyReleased(isProxyReleased);
if (prop === releaseProxy) {
return () => {
unregisterProxy(proxy);
releaseEndpoint(ep);
pendingListeners.clear();
isProxyReleased = true;
};
}
if (prop === "then") {
if (path.length === 0) {
return { then: () => proxy };
}
const r = requestResponseMessage(ep, pendingListeners, {
type: "GET" /* MessageType.GET */,
path: path.map((p) => p.toString()),
}).then(fromWireValue);
return r.then.bind(r);
}
return createProxy(ep, pendingListeners, [...path, prop]);
},
set(_target, prop, rawValue) {
throwIfProxyReleased(isProxyReleased);
// FIXME: ES6 Proxy Handler `set` methods are supposed to return a
// boolean. To show good will, we return true asynchronously ¯\_(ツ)_/¯
const [value, transferables] = toWireValue(rawValue);
return requestResponseMessage(
ep,
pendingListeners,
{
type: "SET" /* MessageType.SET */,
path: [...path, prop].map((p) => p.toString()),
value,
},
transferables
).then(fromWireValue);
},
apply(_target, _thisArg, rawArgumentList) {
throwIfProxyReleased(isProxyReleased);
const last = path[path.length - 1];
if (last === createEndpoint) {
return requestResponseMessage(ep, pendingListeners, {
type: "ENDPOINT" /* MessageType.ENDPOINT */,
}).then(fromWireValue);
}
// We just pretend that `bind()` didn’t happen.
if (last === "bind") {
return createProxy(ep, pendingListeners, path.slice(0, -1));
}
const [argumentList, transferables] = processArguments(rawArgumentList);
return requestResponseMessage(
ep,
pendingListeners,
{
type: "APPLY" /* MessageType.APPLY */,
path: path.map((p) => p.toString()),
argumentList,
},
transferables
).then(fromWireValue);
},
construct(_target, rawArgumentList) {
throwIfProxyReleased(isProxyReleased);
const [argumentList, transferables] = processArguments(rawArgumentList);
return requestResponseMessage(
ep,
pendingListeners,
{
type: "CONSTRUCT" /* MessageType.CONSTRUCT */,
path: path.map((p) => p.toString()),
argumentList,
},
transferables
).then(fromWireValue);
},
});
registerProxy(proxy, ep);
return proxy;
}
function myFlat(arr) {
return Array.prototype.concat.apply([], arr);
}
function processArguments(argumentList) {
const processed = argumentList.map(toWireValue);
return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
}
const transferCache = new WeakMap();
function transfer(obj, transfers) {
transferCache.set(obj, transfers);
return obj;
}
function proxy(obj) {
return Object.assign(obj, { [proxyMarker]: true });
}
function toWireValue(value) {
for (const [name, handler] of transferHandlers) {
if (handler.canHandle(value)) {
const [serializedValue, transferables] = handler.serialize(value);
return [
{
type: "HANDLER" /* WireValueType.HANDLER */,
name,
value: serializedValue,
},
transferables,
];
}
}
return [
{
type: "RAW" /* WireValueType.RAW */,
value,
},
transferCache.get(value) || [],
];
}
function fromWireValue(value) {
switch (value.type) {
case "HANDLER" /* WireValueType.HANDLER */:
return transferHandlers.get(value.name).deserialize(value.value);
case "RAW" /* WireValueType.RAW */:
return value.value;
}
}
function requestResponseMessage(ep, pendingListeners, msg, transfers) {
return new Promise((resolve) => {
const id = generateUUID();
pendingListeners.set(id, resolve);
if (ep.start) {
ep.start();
}
ep.postMessage(Object.assign({ id }, msg), transfers);
});
}
function generateUUID() {
return new Array(4)
.fill(0)
.map(() =>
Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)
)
.join("-");
}
function getDefaultExportFromCjs(x) {
return x &&
x.__esModule &&
Object.prototype.hasOwnProperty.call(x, "default")
? x["default"]
: x;
}
var lunr$1 = { exports: {} };
/**
* lunr - http://lunrjs.com - A bit like Solr, but much smaller and not as bright - 2.3.9
* Copyright (C) 2020 Oliver Nightingale
* @license MIT
*/
lunr$1.exports;
var hasRequiredLunr;
function requireLunr() {
if (hasRequiredLunr) return lunr$1.exports;
hasRequiredLunr = 1;
(function (module, exports) {
(function () {
/**
* A convenience function for configuring and constructing
* a new lunr Index.
*
* A lunr.Builder instance is created and the pipeline setup
* with a trimmer, stop word filter and stemmer.
*
* This builder object is yielded to the configuration function
* that is passed as a parameter, allowing the list of fields
* and other builder parameters to be customised.
*
* All documents _must_ be added within the passed config function.
*
* @example
* var idx = lunr(function () {
* this.field('title')
* this.field('body')
* this.ref('id')
*
* documents.forEach(function (doc) {
* this.add(doc)
* }, this)
* })
*
* @see {@link lunr.Builder}
* @see {@link lunr.Pipeline}
* @see {@link lunr.trimmer}
* @see {@link lunr.stopWordFilter}
* @see {@link lunr.stemmer}
* @namespace {function} lunr
*/
var lunr = function (config) {
var builder = new lunr.Builder();
builder.pipeline.add(lunr.trimmer, lunr.stopWordFilter, lunr.stemmer);
builder.searchPipeline.add(lunr.stemmer);
config.call(builder, builder);
return builder.build();
};
lunr.version = "2.3.9";
/*!
* lunr.utils
* Copyright (C) 2020 Oliver Nightingale
*/
/**
* A namespace containing utils for the rest of the lunr library
* @namespace lunr.utils
*/
lunr.utils = {};
/**
* Print a warning message to the console.
*
* @param {String} message The message to be printed.
* @memberOf lunr.utils
* @function
*/
lunr.utils.warn = (function (global) {
/* eslint-disable no-console */
return function (message) {
console?.warn(message);
};
/* eslint-enable no-console */
})(this);
/**
* Convert an object to a string.
*
* In the case of `null` and `undefined` the function returns
* the empty string, in all other cases the result of calling
* `toString` on the passed object is returned.
*
* @param {Any} obj The object to convert to a string.
* @return {String} string representation of the passed object.
* @memberOf lunr.utils
*/
lunr.utils.asString = function (obj) {
if (obj === void 0 || obj === null) {
return "";
} else {
return obj.toString();
}
};
/**
* Clones an object.
*
* Will create a copy of an existing object such that any mutations
* on the copy cannot affect the original.
*
* Only shallow objects are supported, passing a nested object to this
* function will cause a TypeError.
*
* Objects with primitives, and arrays of primitives are supported.
*
* @param {Object} obj The object to clone.
* @return {Object} a clone of the passed object.
* @throws {TypeError} when a nested object is passed.
* @memberOf Utils
*/
lunr.utils.clone = function (obj) {
if (obj === null || obj === undefined) {
return obj;
}
var clone = Object.create(null),
keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
var key = keys[i],
val = obj[key];
if (Array.isArray(val)) {
clone[key] = val.slice();
continue;
}
if (
typeof val === "string" ||
typeof val === "number" ||
typeof val === "boolean"
) {
clone[key] = val;
continue;
}
throw new TypeError(
"clone is not deep and does not support nested objects"
);
}
return clone;
};
lunr.FieldRef = function (docRef, fieldName, stringValue) {
this.docRef = docRef;
this.fieldName = fieldName;
this._stringValue = stringValue;
};
lunr.FieldRef.joiner = "/";
lunr.FieldRef.fromString = function (s) {
var n = s.indexOf(lunr.FieldRef.joiner);
if (n === -1) {
throw "malformed field ref string";
}
var fieldRef = s.slice(0, n),
docRef = s.slice(n + 1);
return new lunr.FieldRef(docRef, fieldRef, s);
};
lunr.FieldRef.prototype.toString = function () {
if (this._stringValue == undefined) {
this._stringValue =
this.fieldName + lunr.FieldRef.joiner + this.docRef;
}
return this._stringValue;
};
/*!
* lunr.Set
* Copyright (C) 2020 Oliver Nightingale
*/
/**
* A lunr set.
*
* @constructor
*/
lunr.Set = function (elements) {
this.elements = Object.create(null);
if (elements) {
this.length = elements.length;
for (var i = 0; i < this.length; i++) {
this.elements[elements[i]] = true;
}
} else {
this.length = 0;
}
};
/**
* A complete set that contains all elements.
*
* @static
* @readonly
* @type {lunr.Set}
*/
lunr.Set.complete = {
intersect: function (other) {
return other;
},
union: function () {
return this;
},
contains: function () {
return true;
},
};
/**
* An empty set that contains no elements.
*
* @static
* @readonly
* @type {lunr.Set}
*/
lunr.Set.empty = {
intersect: function () {
return this;
},
union: function (other) {
return other;
},
contains: function () {
return false;
},
};
/**
* Returns true if this set contains the specified object.
*
* @param {object} object - Object whose presence in this set is to be tested.
* @returns {boolean} - True if this set contains the specified object.
*/
lunr.Set.prototype.contains = function (object) {
return !!this.elements[object];
};
/**
* Returns a new set containing only the elements that are present in both
* this set and the specified set.
*
* @param {lunr.Set} other - set to intersect with this set.
* @returns {lunr.Set} a new set that is the intersection of this and the specified set.
*/
lunr.Set.prototype.intersect = function (other) {
var a,
b,
elements,
intersection = [];
if (other === lunr.Set.complete) {
return this;
}
if (other === lunr.Set.empty) {
return other;
}
if (this.length < other.length) {
a = this;
b = other;
} else {
a = other;
b = this;
}
elements = Object.keys(a.elements);
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element in b.elements) {
intersection.push(element);
}
}
return new lunr.Set(intersection);
};
/**
* Returns a new set combining the elements of this and the specified set.
*
* @param {lunr.Set} other - set to union with this set.
* @return {lunr.Set} a new set that is the union of this and the specified set.
*/
lunr.Set.prototype.union = function (other) {
if (other === lunr.Set.complete) {
return lunr.Set.complete;
}
if (other === lunr.Set.empty) {
return this;
}
return new lunr.Set(
Object.keys(this.elements).concat(Object.keys(other.elements))
);
};
/**
* A function to calculate the inverse document frequency for
* a posting. This is shared between the builder and the index
*
* @private
* @param {object} posting - The posting for a given term
* @param {number} documentCount - The total number of documents.
*/
lunr.idf = function (posting, documentCount) {
var documentsWithTerm = 0;
for (var fieldName in posting) {
if (fieldName == "_index") continue; // Ignore the term index, its not a field
documentsWithTerm += Object.keys(posting[fieldName]).length;
}
var x =
(documentCount - documentsWithTerm + 0.5) /
(documentsWithTerm + 0.5);
return Math.log(1 + Math.abs(x));
};
/**
* A token wraps a string representation of a token
* as it is passed through the text processing pipeline.
*
* @constructor
* @param {string} [str=''] - The string token being wrapped.
* @param {object} [metadata={}] - Metadata associated with this token.
*/
lunr.Token = function (str, metadata) {
this.str = str || "";
this.metadata = metadata || {};
};
/**
* Returns the token string that is being wrapped by this object.
*
* @returns {string}
*/
lunr.Token.prototype.toString = function () {
return this.str;
};
/**
* A token update function is used when updating or optionally
* when cloning a token.
*
* @callback lunr.Token~updateFunction
* @param {string} str - The string representation of the token.
* @param {Object} metadata - All metadata associated with this token.
*/
/**
* Applies the given function to the wrapped string token.
*
* @example
* token.update(function (str, metadata) {
* return str.toUpperCase()
* })
*
* @param {lunr.Token~updateFunction} fn - A function to apply to the token string.
* @returns {lunr.Token}
*/
lunr.Token.prototype.update = function (fn) {
this.str = fn(this.str, this.metadata);
return this;
};
/**
* Creates a clone of this token. Optionally a function can be
* applied to the cloned token.
*
* @param {lunr.Token~updateFunction} [fn] - An optional function to apply to the cloned token.
* @returns {lunr.Token}
*/
lunr.Token.prototype.clone = function (fn) {
fn =
fn ||
function (s) {
return s;
};
return new lunr.Token(fn(this.str, this.metadata), this.metadata);
};
/*!
* lunr.tokenizer
* Copyright (C) 2020 Oliver Nightingale
*/
/**
* A function for splitting a string into tokens ready to be inserted into
* the search index. Uses `lunr.tokenizer.separator` to split strings, change
* the value of this property to change how strings are split into tokens.
*
* This tokenizer will convert its parameter to a string by calling `toString` and
* then will split this string on the character in `lunr.tokenizer.separator`.
* Arrays will have their elements converted to strings and wrapped in a lunr.Token.
*
* Optional metadata can be passed to the tokenizer, this metadata will be cloned and
* added as metadata to every token that is created from the object to be tokenized.
*
* @static
* @param {?(string|object|object[])} obj - The object to convert into tokens
* @param {?object} metadata - Optional metadata to associate with every token
* @returns {lunr.Token[]}
* @see {@link lunr.Pipeline}
*/
lunr.tokenizer = function (obj, metadata) {
if (obj == null || obj == undefined) {
return [];
}
if (Array.isArray(obj)) {
return obj.map(function (t) {
return new lunr.Token(
lunr.utils.asString(t).toLowerCase(),
lunr.utils.clone(metadata)
);
});
}
var str = obj.toString().toLowerCase(),
len = str.length,
tokens = [];
for (var sliceEnd = 0, sliceStart = 0; sliceEnd <= len; sliceEnd++) {
var char = str.charAt(sliceEnd),
sliceLength = sliceEnd - sliceStart;
if (char.match(lunr.tokenizer.separator) || sliceEnd == len) {
if (sliceLength > 0) {
var tokenMetadata = lunr.utils.clone(metadata) || {};
tokenMetadata["position"] = [sliceStart, sliceLength];
tokenMetadata["index"] = tokens.length;
tokens.push(
new lunr.Token(str.slice(sliceStart, sliceEnd), tokenMetadata)
);
}
sliceStart = sliceEnd + 1;
}
}
return tokens;
};
/**
* The separator used to split a string into tokens. Override this property to change the behaviour of
* `lunr.tokenizer` behaviour when tokenizing strings. By default this splits on whitespace and hyphens.
*
* @static
* @see lunr.tokenizer
*/
lunr.tokenizer.separator = /[\s\-]+/;
/*!
* lunr.Pipeline
* Copyright (C) 2020 Oliver Nightingale
*/
/**
* lunr.Pipelines maintain an ordered list of functions to be applied to all
* tokens in documents entering the search index and queries being ran against
* the index.
*
* An instance of lunr.Index created with the lunr shortcut will contain a
* pipeline with a stop word filter and an English language stemmer. Extra
* functions can be added before or after either of these functions or these
* default functions can be removed.
*
* When run the pipeline will call each function in turn, passing a token, the
* index of that token in the original list of all tokens and finally a list of
* all the original tokens.
*
* The output of functions in the pipeline will be passed to the next function
* in the pipeline. To exclude a token from entering the index the function
* should return undefined, the rest of the pipeline will not be called with
* this token.
*
* For serialisation of pipelines to work, all functions used in an instance of
* a pipeline should be registered with lunr.Pipeline. Registered functions can
* then be loaded. If trying to load a serialised pipeline that uses functions
* that are not registered an error will be thrown.
*
* If not planning on serialising the pipeline then registering pipeline functions
* is not necessary.
*
* @constructor
*/
lunr.Pipeline = function () {
this._stack = [];
};
lunr.Pipeline.registeredFunctions = Object.create(null);
/**
* A pipeline function maps lunr.Token to lunr.Token. A lunr.Token contains the token
* string as well as all known metadata. A pipeline function can mutate the token string
* or mutate (or add) metadata for a given token.
*
* A pipeline function can indicate that the passed token should be discarded by returning
* null, undefined or an empty string. This token will not be passed to any downstream pipeline
* functions and will not be added to the index.
*
* Multiple tokens can be returned by returning an array of tokens. Each token will be passed
* to any downstream pipeline functions and all will returned tokens will be added to the index.
*
* Any number of pipeline functions may be chained together using a lunr.Pipeline.
*
* @interface lunr.PipelineFunction
* @param {lunr.Token} token - A token from the document being processed.
* @param {number} i - The index of this token in the complete list of tokens for this document/field.
* @param {lunr.Token[]} tokens - All tokens for this document/field.
* @returns {(?lunr.Token|lunr.Token[])}
*/
/**
* Register a function with the pipeline.
*
* Functions that are used in the pipeline should be registered if the pipeline
* needs to be serialised, or a serialised pipeline needs to be loaded.
*
* Registering a function does not add it to a pipeline, functions must still be
* added to instances of the pipeline for them to be used when running a pipeline.
*
* @param {lunr.PipelineFunction} fn - The function to check for.
* @param {String} label - The label to register this function with
*/
lunr.Pipeline.registerFunction = function (fn, label) {
if (label in this.registeredFunctions) {
lunr.utils.warn(
"Overwriting existing registered function: " + label
);
}
fn.label = label;
lunr.Pipeline.registeredFunctions[fn.label] = fn;
};
/**
* Warns if the function is not registered as a Pipeline function.
*
* @param {lunr.PipelineFunction} fn - The function to check for.
* @private
*/
lunr.Pipeline.warnIfFunctionNotRegistered = function (fn) {
var isRegistered = fn.label && fn.label in this.registeredFunctions;
if (!isRegistered) {
lunr.utils.warn(
"Function is not registered with pipeline. This may cause problems when serialising the index.\n",
fn
);
}
};
/**
* Loads a previously serialised pipeline.
*
* All functions to be loaded must already be registered with lunr.Pipeline.
* If any function from the serialised data has not been registered then an
* error will be thrown.
*
* @param {Object} serialised - The serialised pipeline to load.
* @returns {lunr.Pipeline}
*/
lunr.Pipeline.load = function (serialised) {
var pipeline = new lunr.Pipeline();
serialised.forEach(function (fnName) {
var fn = lunr.Pipeline.registeredFunctions[fnName];
if (fn) {
pipeline.add(fn);
} else {
throw new Error("Cannot load unregistered function: " + fnName);
}
});
return pipeline;
};
/**
* Adds new functions to the end of the pipeline.
*
* Logs a warning if the function has not been registered.
*
* @param {lunr.PipelineFunction[]} functions - Any number of functions to add to the pipeline.
*/
lunr.Pipeline.prototype.add = function () {