@backstage/plugin-search-backend-node 1.2.22 → 1.2.24-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # @backstage/plugin-search-backend-node
2
2
 
3
+ ## 1.2.24-next.0
4
+
5
+ ### Patch Changes
6
+
7
+ - 6a576dc: Replace the usage of `getVoidLogger` with `mockServices.logger.mock` in order to remove the dependency with the soon-to-be-deprecated `backend-common` package.
8
+ - 5b6f979: Split backend search plugin startup into "init" and "start" stages to ensure necessary initialization has happened before startup
9
+ - Updated dependencies
10
+ - @backstage/backend-tasks@0.5.24-next.0
11
+ - @backstage/backend-common@0.22.1-next.0
12
+ - @backstage/backend-plugin-api@0.6.19-next.0
13
+ - @backstage/config@1.2.0
14
+ - @backstage/errors@1.2.4
15
+ - @backstage/plugin-permission-common@0.7.13
16
+ - @backstage/plugin-search-common@1.2.11
17
+
3
18
  ## 1.2.22
4
19
 
5
20
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-search-backend-node",
3
- "version": "1.2.22",
3
+ "version": "1.2.24-next.0",
4
4
  "main": "../dist/alpha.cjs.js",
5
5
  "types": "../dist/alpha.d.ts"
6
6
  }
package/dist/alpha.cjs.js CHANGED
@@ -3,41 +3,33 @@
3
3
  var backendPluginApi = require('@backstage/backend-plugin-api');
4
4
  var pluginSearchBackendNode = require('@backstage/plugin-search-backend-node');
5
5
 
6
- var __defProp = Object.defineProperty;
7
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
8
- var __publicField = (obj, key, value) => {
9
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
- return value;
11
- };
12
6
  class DefaultSearchIndexService {
7
+ logger;
8
+ indexBuilder = null;
9
+ scheduler = null;
13
10
  constructor(options) {
14
- __publicField(this, "logger");
15
- __publicField(this, "indexBuilder", null);
16
- __publicField(this, "scheduler", null);
17
11
  this.logger = options.logger;
18
12
  }
19
13
  static fromConfig(options) {
20
14
  return new DefaultSearchIndexService(options);
21
15
  }
22
- async start(options) {
23
- var _a;
16
+ init(options) {
24
17
  this.indexBuilder = new pluginSearchBackendNode.IndexBuilder({
25
18
  logger: this.logger,
26
19
  searchEngine: options.searchEngine
27
20
  });
28
21
  options.collators.forEach(
29
- (collator) => {
30
- var _a2;
31
- return (_a2 = this.indexBuilder) == null ? void 0 : _a2.addCollator(collator);
32
- }
22
+ (collator) => this.indexBuilder?.addCollator(collator)
33
23
  );
34
24
  options.decorators.forEach(
35
- (decorator) => {
36
- var _a2;
37
- return (_a2 = this.indexBuilder) == null ? void 0 : _a2.addDecorator(decorator);
38
- }
25
+ (decorator) => this.indexBuilder?.addDecorator(decorator)
39
26
  );
40
- const { scheduler } = await ((_a = this.indexBuilder) == null ? void 0 : _a.build());
27
+ }
28
+ async start() {
29
+ if (!this.indexBuilder) {
30
+ throw new Error("IndexBuilder is not initialized, call init first");
31
+ }
32
+ const { scheduler } = await this.indexBuilder.build();
41
33
  this.scheduler = scheduler;
42
34
  this.scheduler.start();
43
35
  }
@@ -48,8 +40,7 @@ class DefaultSearchIndexService {
48
40
  }
49
41
  }
50
42
  getDocumentTypes() {
51
- var _a, _b;
52
- return (_b = (_a = this.indexBuilder) == null ? void 0 : _a.getDocumentTypes()) != null ? _b : {};
43
+ return this.indexBuilder?.getDocumentTypes() ?? {};
53
44
  }
54
45
  }
55
46
  const searchIndexServiceRef = backendPluginApi.createServiceRef({
@@ -1 +1 @@
1
- {"version":3,"file":"alpha.cjs.js","sources":["../src/alpha.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createExtensionPoint,\n createServiceFactory,\n createServiceRef,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { DocumentTypeInfo } from '@backstage/plugin-search-common';\nimport {\n IndexBuilder,\n RegisterCollatorParameters,\n RegisterDecoratorParameters,\n Scheduler,\n SearchEngine,\n} from '@backstage/plugin-search-backend-node';\n\n/**\n * @alpha\n * Options for build method on {@link SearchIndexService}.\n */\nexport type SearchIndexServiceStartOptions = {\n searchEngine: SearchEngine;\n collators: RegisterCollatorParameters[];\n decorators: RegisterDecoratorParameters[];\n};\n\n/**\n * @alpha\n * Interface for implementation of index service.\n */\nexport interface SearchIndexService {\n /**\n * Starts indexing process\n */\n start(options: SearchIndexServiceStartOptions): Promise<void>;\n\n /**\n * Stops indexing process\n */\n stop(): Promise<void>;\n /**\n * Returns an index types list.\n */\n getDocumentTypes(): Record<string, DocumentTypeInfo>;\n}\n\n/**\n * @alpha\n * Interface for search index registry extension point.\n */\nexport interface SearchIndexRegistryExtensionPoint {\n addCollator(options: RegisterCollatorParameters): void;\n addDecorator(options: RegisterDecoratorParameters): void;\n}\n\n/**\n * @alpha\n * Interface for search engine registry extension point.\n */\nexport interface SearchEngineRegistryExtensionPoint {\n setSearchEngine(searchEngine: SearchEngine): void;\n}\n\ntype DefaultSearchIndexServiceOptions = {\n logger: LoggerService;\n};\n\n/**\n * @alpha\n * Reponsible for register the indexing task and start the schedule.\n */\nclass DefaultSearchIndexService implements SearchIndexService {\n private readonly logger: LoggerService;\n private indexBuilder: IndexBuilder | null = null;\n private scheduler: Scheduler | null = null;\n\n private constructor(options: DefaultSearchIndexServiceOptions) {\n this.logger = options.logger;\n }\n\n static fromConfig(options: DefaultSearchIndexServiceOptions) {\n return new DefaultSearchIndexService(options);\n }\n\n async start(options: SearchIndexServiceStartOptions): Promise<void> {\n this.indexBuilder = new IndexBuilder({\n logger: this.logger,\n searchEngine: options.searchEngine,\n });\n\n options.collators.forEach(collator =>\n this.indexBuilder?.addCollator(collator),\n );\n\n options.decorators.forEach(decorator =>\n this.indexBuilder?.addDecorator(decorator),\n );\n\n const { scheduler } = await this.indexBuilder?.build();\n this.scheduler = scheduler;\n this.scheduler!.start();\n }\n\n async stop(): Promise<void> {\n if (this.scheduler) {\n this.scheduler.stop();\n this.scheduler = null;\n }\n }\n\n getDocumentTypes(): Record<string, DocumentTypeInfo> {\n return this.indexBuilder?.getDocumentTypes() ?? {};\n }\n}\n\n/**\n * @alpha\n * Service that builds a search index.\n */\nexport const searchIndexServiceRef = createServiceRef<SearchIndexService>({\n id: 'search.index.service',\n defaultFactory: async service =>\n createServiceFactory({\n service,\n deps: {\n logger: coreServices.logger,\n },\n factory({ logger }) {\n return DefaultSearchIndexService.fromConfig({\n logger,\n });\n },\n }),\n});\n\n/**\n * @alpha\n * Extension point for register a search engine.\n */\nexport const searchEngineRegistryExtensionPoint =\n createExtensionPoint<SearchEngineRegistryExtensionPoint>({\n id: 'search.engine.registry',\n });\n\n/**\n * @alpha\n * Extension point for registering collators and decorators\n */\nexport const searchIndexRegistryExtensionPoint =\n createExtensionPoint<SearchIndexRegistryExtensionPoint>({\n id: 'search.index.registry',\n });\n"],"names":["IndexBuilder","_a","createServiceRef","createServiceFactory","coreServices","createExtensionPoint"],"mappings":";;;;;;;;;;;AAuFA,MAAM,yBAAwD,CAAA;AAAA,EAKpD,YAAY,OAA2C,EAAA;AAJ/D,IAAiB,aAAA,CAAA,IAAA,EAAA,QAAA,CAAA,CAAA;AACjB,IAAA,aAAA,CAAA,IAAA,EAAQ,cAAoC,EAAA,IAAA,CAAA,CAAA;AAC5C,IAAA,aAAA,CAAA,IAAA,EAAQ,WAA8B,EAAA,IAAA,CAAA,CAAA;AAGpC,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AAAA,GACx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U,IAAK,EAAA,CAAA;AACpB,MAAA,IAAA,CAAK,SAAY,GAAA,IAAA,CAAA;AAAA,KACnB;AAAA,GACF;AAAA,EAEA,gBAAqD,GAAA;AA9HvD,IAAA,IAAA,EAAA,EAAA,EAAA,CAAA;AA+HI,IAAA,OAAA,CAAO,EAAK,GAAA,CAAA,EAAA,GAAA,IAAA,CAAA,YAAA,KAAL,IAAmB,GAAA,KAAA,CAAA,GAAA,EAAA,CAAA,gBAAA,EAAA,KAAnB,YAAyC,EAAC,CAAA;AAAA,GACnD;AACF,CAAA;AAMO,MAAM,wBAAwBC,iCAAqC,CAAA;AAAA,EACxE,EAAI,EAAA,sBAAA;AAAA,EACJ,cAAA,EAAgB,OAAM,OAAA,KACpBC,qCAAqB,CAAA;AAAA,IACnB,OAAA;AAAA,IACA,IAAM,EAAA;AAAA,MACJ,QAAQC,6BAAa,CAAA,MAAA;AAAA,KACvB;AAAA,IACA,OAAA,CAAQ,EAAE,MAAA,EAAU,EAAA;AAClB,MAAA,OAAO,0BAA0B,UAAW,CAAA;AAAA,QAC1C,MAAA;AAAA,OACD,CAAA,CAAA;AAAA,KACH;AAAA,GACD,CAAA;AACL,CAAC,EAAA;AAMM,MAAM,qCACXC,qCAAyD,CAAA;AAAA,EACvD,EAAI,EAAA,wBAAA;AACN,CAAC,EAAA;AAMI,MAAM,oCACXA,qCAAwD,CAAA;AAAA,EACtD,EAAI,EAAA,uBAAA;AACN,CAAC;;;;;;"}
1
+ {"version":3,"file":"alpha.cjs.js","sources":["../src/alpha.ts"],"sourcesContent":["/*\n * Copyright 2023 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n coreServices,\n createExtensionPoint,\n createServiceFactory,\n createServiceRef,\n LoggerService,\n} from '@backstage/backend-plugin-api';\nimport { DocumentTypeInfo } from '@backstage/plugin-search-common';\nimport {\n IndexBuilder,\n RegisterCollatorParameters,\n RegisterDecoratorParameters,\n Scheduler,\n SearchEngine,\n} from '@backstage/plugin-search-backend-node';\n\n/**\n * @alpha\n * Options for the init method on {@link SearchIndexService}.\n */\nexport type SearchIndexServiceInitOptions = {\n searchEngine: SearchEngine;\n collators: RegisterCollatorParameters[];\n decorators: RegisterDecoratorParameters[];\n};\n\n/**\n * @alpha\n * Interface for implementation of index service.\n */\nexport interface SearchIndexService {\n /**\n * Initializes state in preparation for starting the search index service\n */\n init(options: SearchIndexServiceInitOptions): void;\n\n /**\n * Starts indexing process\n */\n start(): Promise<void>;\n\n /**\n * Stops indexing process\n */\n stop(): Promise<void>;\n\n /**\n * Returns an index types list.\n */\n getDocumentTypes(): Record<string, DocumentTypeInfo>;\n}\n\n/**\n * @alpha\n * Interface for search index registry extension point.\n */\nexport interface SearchIndexRegistryExtensionPoint {\n addCollator(options: RegisterCollatorParameters): void;\n addDecorator(options: RegisterDecoratorParameters): void;\n}\n\n/**\n * @alpha\n * Interface for search engine registry extension point.\n */\nexport interface SearchEngineRegistryExtensionPoint {\n setSearchEngine(searchEngine: SearchEngine): void;\n}\n\ntype DefaultSearchIndexServiceOptions = {\n logger: LoggerService;\n};\n\n/**\n * @alpha\n * Responsible for register the indexing task and start the schedule.\n */\nclass DefaultSearchIndexService implements SearchIndexService {\n private readonly logger: LoggerService;\n private indexBuilder: IndexBuilder | null = null;\n private scheduler: Scheduler | null = null;\n\n private constructor(options: DefaultSearchIndexServiceOptions) {\n this.logger = options.logger;\n }\n\n static fromConfig(options: DefaultSearchIndexServiceOptions) {\n return new DefaultSearchIndexService(options);\n }\n\n init(options: SearchIndexServiceInitOptions): void {\n this.indexBuilder = new IndexBuilder({\n logger: this.logger,\n searchEngine: options.searchEngine,\n });\n\n options.collators.forEach(collator =>\n this.indexBuilder?.addCollator(collator),\n );\n\n options.decorators.forEach(decorator =>\n this.indexBuilder?.addDecorator(decorator),\n );\n }\n\n async start(): Promise<void> {\n if (!this.indexBuilder) {\n throw new Error('IndexBuilder is not initialized, call init first');\n }\n const { scheduler } = await this.indexBuilder.build();\n this.scheduler = scheduler;\n this.scheduler!.start();\n }\n\n async stop(): Promise<void> {\n if (this.scheduler) {\n this.scheduler.stop();\n this.scheduler = null;\n }\n }\n\n getDocumentTypes(): Record<string, DocumentTypeInfo> {\n return this.indexBuilder?.getDocumentTypes() ?? {};\n }\n}\n\n/**\n * @alpha\n * Service that builds a search index.\n */\nexport const searchIndexServiceRef = createServiceRef<SearchIndexService>({\n id: 'search.index.service',\n defaultFactory: async service =>\n createServiceFactory({\n service,\n deps: {\n logger: coreServices.logger,\n },\n factory({ logger }) {\n return DefaultSearchIndexService.fromConfig({\n logger,\n });\n },\n }),\n});\n\n/**\n * @alpha\n * Extension point for register a search engine.\n */\nexport const searchEngineRegistryExtensionPoint =\n createExtensionPoint<SearchEngineRegistryExtensionPoint>({\n id: 'search.engine.registry',\n });\n\n/**\n * @alpha\n * Extension point for registering collators and decorators\n */\nexport const searchIndexRegistryExtensionPoint =\n createExtensionPoint<SearchIndexRegistryExtensionPoint>({\n id: 'search.index.registry',\n });\n"],"names":["IndexBuilder","createServiceRef","createServiceFactory","coreServices","createExtensionPoint"],"mappings":";;;;;AA6FA,MAAM,yBAAwD,CAAA;AAAA,EAC3C,MAAA,CAAA;AAAA,EACT,YAAoC,GAAA,IAAA,CAAA;AAAA,EACpC,SAA8B,GAAA,IAAA,CAAA;AAAA,EAE9B,YAAY,OAA2C,EAAA;AAC7D,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AAAA,GACxB;AAAA,EAEA,OAAO,WAAW,OAA2C,EAAA;AAC3D,IAAO,OAAA,IAAI,0BAA0B,OAAO,CAAA,CAAA;AAAA,GA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BC,qCAAqB,CAAA;AAAA,IACnB,OAAA;AAAA,IACA,IAAM,EAAA;AAAA,MACJ,QAAQC,6BAAa,CAAA,MAAA;AAAA,KACvB;AAAA,IACA,OAAA,CAAQ,EAAE,MAAA,EAAU,EAAA;AAClB,MAAA,OAAO,0BAA0B,UAAW,CAAA;AAAA,QAC1C,MAAA;AAAA,OACD,CAAA,CAAA;AAAA,KACH;AAAA,GACD,CAAA;AACL,CAAC,EAAA;AAMM,MAAM,qCACXC,qCAAyD,CAAA;AAAA,EACvD,EAAI,EAAA,wBAAA;AACN,CAAC,EAAA;AAMI,MAAM,oCACXA,qCAAwD,CAAA;AAAA,EACtD,EAAI,EAAA,uBAAA;AACN,CAAC;;;;;;"}
package/dist/alpha.d.ts CHANGED
@@ -4,9 +4,9 @@ import { SearchEngine, RegisterCollatorParameters, RegisterDecoratorParameters }
4
4
 
5
5
  /**
6
6
  * @alpha
7
- * Options for build method on {@link SearchIndexService}.
7
+ * Options for the init method on {@link SearchIndexService}.
8
8
  */
9
- type SearchIndexServiceStartOptions = {
9
+ type SearchIndexServiceInitOptions = {
10
10
  searchEngine: SearchEngine;
11
11
  collators: RegisterCollatorParameters[];
12
12
  decorators: RegisterDecoratorParameters[];
@@ -16,10 +16,14 @@ type SearchIndexServiceStartOptions = {
16
16
  * Interface for implementation of index service.
17
17
  */
18
18
  interface SearchIndexService {
19
+ /**
20
+ * Initializes state in preparation for starting the search index service
21
+ */
22
+ init(options: SearchIndexServiceInitOptions): void;
19
23
  /**
20
24
  * Starts indexing process
21
25
  */
22
- start(options: SearchIndexServiceStartOptions): Promise<void>;
26
+ start(): Promise<void>;
23
27
  /**
24
28
  * Stops indexing process
25
29
  */
@@ -60,4 +64,4 @@ declare const searchEngineRegistryExtensionPoint: _backstage_backend_plugin_api.
60
64
  */
61
65
  declare const searchIndexRegistryExtensionPoint: _backstage_backend_plugin_api.ExtensionPoint<SearchIndexRegistryExtensionPoint>;
62
66
 
63
- export { type SearchEngineRegistryExtensionPoint, type SearchIndexRegistryExtensionPoint, type SearchIndexService, type SearchIndexServiceStartOptions, searchEngineRegistryExtensionPoint, searchIndexRegistryExtensionPoint, searchIndexServiceRef };
67
+ export { type SearchEngineRegistryExtensionPoint, type SearchIndexRegistryExtensionPoint, type SearchIndexService, type SearchIndexServiceInitOptions, searchEngineRegistryExtensionPoint, searchIndexRegistryExtensionPoint, searchIndexServiceRef };
package/dist/index.cjs.js CHANGED
@@ -10,18 +10,12 @@ function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'defau
10
10
 
11
11
  var lunr__default = /*#__PURE__*/_interopDefaultCompat(lunr);
12
12
 
13
- var __defProp$7 = Object.defineProperty;
14
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
15
- var __publicField$7 = (obj, key, value) => {
16
- __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
17
- return value;
18
- };
19
13
  class Scheduler {
14
+ logger;
15
+ schedule;
16
+ abortControllers;
17
+ isRunning;
20
18
  constructor(options) {
21
- __publicField$7(this, "logger");
22
- __publicField$7(this, "schedule");
23
- __publicField$7(this, "abortControllers");
24
- __publicField$7(this, "isRunning");
25
19
  this.logger = options.logger;
26
20
  this.schedule = {};
27
21
  this.abortControllers = [];
@@ -74,19 +68,13 @@ class Scheduler {
74
68
  }
75
69
  }
76
70
 
77
- var __defProp$6 = Object.defineProperty;
78
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
79
- var __publicField$6 = (obj, key, value) => {
80
- __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
81
- return value;
82
- };
83
71
  class IndexBuilder {
72
+ collators;
73
+ decorators;
74
+ documentTypes;
75
+ searchEngine;
76
+ logger;
84
77
  constructor(options) {
85
- __publicField$6(this, "collators");
86
- __publicField$6(this, "decorators");
87
- __publicField$6(this, "documentTypes");
88
- __publicField$6(this, "searchEngine");
89
- __publicField$6(this, "logger");
90
78
  this.collators = {};
91
79
  this.decorators = {};
92
80
  this.documentTypes = {};
@@ -196,22 +184,16 @@ class IndexBuilder {
196
184
  }
197
185
  }
198
186
 
199
- var __defProp$5 = Object.defineProperty;
200
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
201
- var __publicField$5 = (obj, key, value) => {
202
- __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
203
- return value;
204
- };
205
187
  class NewlineDelimitedJsonCollatorFactory {
206
188
  constructor(type, searchPattern, reader, logger, visibilityPermission) {
207
189
  this.searchPattern = searchPattern;
208
190
  this.reader = reader;
209
191
  this.logger = logger;
210
- __publicField$5(this, "type");
211
- __publicField$5(this, "visibilityPermission");
212
192
  this.type = type;
213
193
  this.visibilityPermission = visibilityPermission;
214
194
  }
195
+ type;
196
+ visibilityPermission;
215
197
  /**
216
198
  * Returns a NewlineDelimitedJsonCollatorFactory instance from configuration
217
199
  * and a set of options.
@@ -230,14 +212,13 @@ class NewlineDelimitedJsonCollatorFactory {
230
212
  * end of the list, sorted alphabetically).
231
213
  */
232
214
  async lastUrl() {
233
- var _a;
234
215
  try {
235
216
  this.logger.info(
236
217
  `Attempting to find latest .ndjson matching ${this.searchPattern}`
237
218
  );
238
219
  const { files } = await this.reader.search(this.searchPattern);
239
220
  const candidates = files.filter((file) => file.url.endsWith(".ndjson")).sort((a, b) => a.url.localeCompare(b.url)).reverse();
240
- return (_a = candidates[0]) == null ? void 0 : _a.url;
221
+ return candidates[0]?.url;
241
222
  } catch (e) {
242
223
  this.logger.error(`Could not search for ${this.searchPattern}`, e);
243
224
  throw e;
@@ -258,37 +239,24 @@ class NewlineDelimitedJsonCollatorFactory {
258
239
  }
259
240
  }
260
241
 
261
- var __defProp$4 = Object.defineProperty;
262
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
263
- var __publicField$4 = (obj, key, value) => {
264
- __defNormalProp$4(obj, key + "" , value);
265
- return value;
266
- };
267
242
  class MissingIndexError extends Error {
243
+ /**
244
+ * An inner error that caused this error to be thrown, if any.
245
+ */
246
+ cause;
268
247
  constructor(message, cause) {
269
- var _a;
270
248
  super(message);
271
- /**
272
- * An inner error that caused this error to be thrown, if any.
273
- */
274
- __publicField$4(this, "cause");
275
- (_a = Error.captureStackTrace) == null ? void 0 : _a.call(Error, this, this.constructor);
249
+ Error.captureStackTrace?.(this, this.constructor);
276
250
  this.name = this.constructor.name;
277
251
  this.cause = errors.isError(cause) ? cause : void 0;
278
252
  }
279
253
  }
280
254
 
281
- var __defProp$3 = Object.defineProperty;
282
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
283
- var __publicField$3 = (obj, key, value) => {
284
- __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
285
- return value;
286
- };
287
255
  class BatchSearchEngineIndexer extends stream.Writable {
256
+ batchSize;
257
+ currentBatch = [];
288
258
  constructor(options) {
289
259
  super({ objectMode: true });
290
- __publicField$3(this, "batchSize");
291
- __publicField$3(this, "currentBatch", []);
292
260
  this.batchSize = options.batchSize;
293
261
  }
294
262
  /**
@@ -399,18 +367,12 @@ class DecoratorBase extends stream.Transform {
399
367
  }
400
368
  }
401
369
 
402
- var __defProp$2 = Object.defineProperty;
403
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
404
- var __publicField$2 = (obj, key, value) => {
405
- __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
406
- return value;
407
- };
408
370
  class LunrSearchEngineIndexer extends BatchSearchEngineIndexer {
371
+ schemaInitialized = false;
372
+ builder;
373
+ docStore = {};
409
374
  constructor() {
410
375
  super({ batchSize: 1e3 });
411
- __publicField$2(this, "schemaInitialized", false);
412
- __publicField$2(this, "builder");
413
- __publicField$2(this, "docStore", {});
414
376
  this.builder = new lunr__default.default.Builder();
415
377
  this.builder.pipeline.add(lunr__default.default.trimmer, lunr__default.default.stopWordFilter, lunr__default.default.stemmer);
416
378
  this.builder.searchPipeline.add(lunr__default.default.stemmer);
@@ -442,81 +404,75 @@ class LunrSearchEngineIndexer extends BatchSearchEngineIndexer {
442
404
  }
443
405
  }
444
406
 
445
- var __defProp$1 = Object.defineProperty;
446
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
447
- var __publicField$1 = (obj, key, value) => {
448
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
449
- return value;
450
- };
451
407
  class LunrSearchEngine {
408
+ lunrIndices = {};
409
+ docStore;
410
+ logger;
411
+ highlightPreTag;
412
+ highlightPostTag;
452
413
  constructor(options) {
453
- __publicField$1(this, "lunrIndices", {});
454
- __publicField$1(this, "docStore");
455
- __publicField$1(this, "logger");
456
- __publicField$1(this, "highlightPreTag");
457
- __publicField$1(this, "highlightPostTag");
458
- __publicField$1(this, "translator", ({
459
- term,
460
- filters,
461
- types,
462
- pageLimit
463
- }) => {
464
- const pageSize = pageLimit || 25;
465
- return {
466
- lunrQueryBuilder: (q) => {
467
- const termToken = lunr__default.default.tokenizer(term);
468
- q.term(termToken, {
469
- usePipeline: true,
470
- boost: 100
471
- });
472
- q.term(termToken, {
473
- usePipeline: false,
474
- boost: 10,
475
- wildcard: lunr__default.default.Query.wildcard.TRAILING
476
- });
477
- q.term(termToken, {
478
- usePipeline: false,
479
- editDistance: 2,
480
- boost: 1
481
- });
482
- if (filters) {
483
- Object.entries(filters).forEach(([field, fieldValue]) => {
484
- if (!q.allFields.includes(field)) {
485
- throw new Error(`unrecognised field ${field}`);
486
- }
487
- const value = Array.isArray(fieldValue) && fieldValue.length === 1 ? fieldValue[0] : fieldValue;
488
- if (["string", "number", "boolean"].includes(typeof value)) {
489
- q.term(
490
- lunr__default.default.tokenizer(value == null ? void 0 : value.toString()).map(lunr__default.default.stopWordFilter).filter((element) => element !== void 0),
491
- {
492
- presence: lunr__default.default.Query.presence.REQUIRED,
493
- fields: [field]
494
- }
495
- );
496
- } else if (Array.isArray(value)) {
497
- this.logger.warn(
498
- `Non-scalar filter value used for field ${field}. Consider using a different Search Engine for better results.`
499
- );
500
- q.term(lunr__default.default.tokenizer(value), {
501
- presence: lunr__default.default.Query.presence.OPTIONAL,
502
- fields: [field]
503
- });
504
- } else {
505
- this.logger.warn(`Unknown filter type used on field ${field}`);
506
- }
507
- });
508
- }
509
- },
510
- documentTypes: types,
511
- pageSize
512
- };
513
- });
514
414
  this.logger = options.logger;
515
415
  this.docStore = {};
516
416
  const uuidTag = uuid.v4();
517
417
  this.highlightPreTag = `<${uuidTag}>`;
518
418
  this.highlightPostTag = `</${uuidTag}>`;
519
419
  }
420
+ translator = ({
421
+ term,
422
+ filters,
423
+ types,
424
+ pageLimit
425
+ }) => {
426
+ const pageSize = pageLimit || 25;
427
+ return {
428
+ lunrQueryBuilder: (q) => {
429
+ const termToken = lunr__default.default.tokenizer(term);
430
+ q.term(termToken, {
431
+ usePipeline: true,
432
+ boost: 100
433
+ });
434
+ q.term(termToken, {
435
+ usePipeline: false,
436
+ boost: 10,
437
+ wildcard: lunr__default.default.Query.wildcard.TRAILING
438
+ });
439
+ q.term(termToken, {
440
+ usePipeline: false,
441
+ editDistance: 2,
442
+ boost: 1
443
+ });
444
+ if (filters) {
445
+ Object.entries(filters).forEach(([field, fieldValue]) => {
446
+ if (!q.allFields.includes(field)) {
447
+ throw new Error(`unrecognised field ${field}`);
448
+ }
449
+ const value = Array.isArray(fieldValue) && fieldValue.length === 1 ? fieldValue[0] : fieldValue;
450
+ if (["string", "number", "boolean"].includes(typeof value)) {
451
+ q.term(
452
+ lunr__default.default.tokenizer(value?.toString()).map(lunr__default.default.stopWordFilter).filter((element) => element !== void 0),
453
+ {
454
+ presence: lunr__default.default.Query.presence.REQUIRED,
455
+ fields: [field]
456
+ }
457
+ );
458
+ } else if (Array.isArray(value)) {
459
+ this.logger.warn(
460
+ `Non-scalar filter value used for field ${field}. Consider using a different Search Engine for better results.`
461
+ );
462
+ q.term(lunr__default.default.tokenizer(value), {
463
+ presence: lunr__default.default.Query.presence.OPTIONAL,
464
+ fields: [field]
465
+ });
466
+ } else {
467
+ this.logger.warn(`Unknown filter type used on field ${field}`);
468
+ }
469
+ });
470
+ }
471
+ },
472
+ documentTypes: types,
473
+ pageSize
474
+ };
475
+ };
520
476
  setTranslator(translator) {
521
477
  this.translator = translator;
522
478
  }
@@ -550,9 +506,9 @@ class LunrSearchEngine {
550
506
  const indexKeys = Object.keys(this.lunrIndices).filter(
551
507
  (type) => !documentTypes || documentTypes.includes(type)
552
508
  );
553
- if ((documentTypes == null ? void 0 : documentTypes.length) && !indexKeys.length) {
509
+ if (documentTypes?.length && !indexKeys.length) {
554
510
  throw new MissingIndexError(
555
- `Missing index for ${documentTypes == null ? void 0 : documentTypes.toString()}. This could be because the index hasn't been created yet or there was a problem during index creation.`
511
+ `Missing index for ${documentTypes?.toString()}. This could be because the index hasn't been created yet or there was a problem during index creation.`
556
512
  );
557
513
  }
558
514
  indexKeys.forEach((type) => {
@@ -624,10 +580,9 @@ function parseHighlightFields({
624
580
  const highlightFieldPositions = Object.values(positionMetadata).reduce(
625
581
  (fieldPositions, metadata) => {
626
582
  Object.keys(metadata).map((fieldKey) => {
627
- var _a, _b, _c;
628
- const validFieldMetadataPositions = (_b = (_a = metadata[fieldKey]) == null ? void 0 : _a.position) == null ? void 0 : _b.filter((position) => Array.isArray(position));
583
+ const validFieldMetadataPositions = metadata[fieldKey]?.position?.filter((position) => Array.isArray(position));
629
584
  if (validFieldMetadataPositions.length) {
630
- fieldPositions[fieldKey] = (_c = fieldPositions[fieldKey]) != null ? _c : [];
585
+ fieldPositions[fieldKey] = fieldPositions[fieldKey] ?? [];
631
586
  fieldPositions[fieldKey].push(...validFieldMetadataPositions);
632
587
  }
633
588
  });
@@ -637,31 +592,24 @@ function parseHighlightFields({
637
592
  );
638
593
  return Object.fromEntries(
639
594
  Object.entries(highlightFieldPositions).map(([field, positions]) => {
640
- var _a;
641
595
  positions.sort((a, b) => b[0] - a[0]);
642
596
  const highlightedField = positions.reduce((content, pos) => {
643
597
  return `${String(content).substring(0, pos[0])}${preTag}${String(content).substring(pos[0], pos[0] + pos[1])}${postTag}${String(content).substring(pos[0] + pos[1])}`;
644
- }, (_a = doc[field]) != null ? _a : "");
598
+ }, doc[field] ?? "");
645
599
  return [field, highlightedField];
646
600
  })
647
601
  );
648
602
  }
649
603
 
650
- var __defProp = Object.defineProperty;
651
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
652
- var __publicField = (obj, key, value) => {
653
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
654
- return value;
655
- };
656
604
  class TestPipeline {
605
+ collator;
606
+ decorator;
607
+ indexer;
657
608
  constructor({
658
609
  collator,
659
610
  decorator,
660
611
  indexer
661
612
  }) {
662
- __publicField(this, "collator");
663
- __publicField(this, "decorator");
664
- __publicField(this, "indexer");
665
613
  this.collator = collator;
666
614
  this.decorator = decorator;
667
615
  this.indexer = indexer;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/Scheduler.ts","../src/IndexBuilder.ts","../src/collators/NewlineDelimitedJsonCollatorFactory.ts","../src/errors.ts","../src/indexing/BatchSearchEngineIndexer.ts","../src/indexing/DecoratorBase.ts","../src/engines/LunrSearchEngineIndexer.ts","../src/engines/LunrSearchEngine.ts","../src/test-utils/TestPipeline.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TaskFunction, TaskRunner } from '@backstage/backend-tasks';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\ntype TaskEnvelope = {\n task: TaskFunction;\n scheduledRunner: TaskRunner;\n};\n\n/**\n * ScheduleTaskParameters\n * @public\n */\nexport type ScheduleTaskParameters = {\n id: string;\n task: TaskFunction;\n scheduledRunner: TaskRunner;\n};\n\n/**\n * Scheduler responsible for all search tasks.\n * @public\n */\nexport class Scheduler {\n private logger: LoggerService;\n private schedule: { [id: string]: TaskEnvelope };\n private abortControllers: AbortController[];\n private isRunning: boolean;\n\n constructor(options: { logger: LoggerService }) {\n this.logger = options.logger;\n this.schedule = {};\n this.abortControllers = [];\n this.isRunning = false;\n }\n\n /**\n * Adds each task and interval to the schedule.\n * When running the tasks, the scheduler waits at least for the time specified\n * in the interval once the task was completed, before running it again.\n */\n addToSchedule(options: ScheduleTaskParameters) {\n const { id, task, scheduledRunner } = options;\n\n if (this.isRunning) {\n throw new Error(\n 'Cannot add task to schedule that has already been started.',\n );\n }\n\n if (this.schedule[id]) {\n throw new Error(`Task with id ${id} already exists.`);\n }\n\n this.schedule[id] = { task, scheduledRunner };\n }\n\n /**\n * Starts the scheduling process for each task\n */\n start() {\n this.logger.info('Starting all scheduled search tasks.');\n this.isRunning = true;\n Object.keys(this.schedule).forEach(id => {\n const abortController = new AbortController();\n this.abortControllers.push(abortController);\n const { task, scheduledRunner } = this.schedule[id];\n scheduledRunner.run({\n id,\n fn: task,\n signal: abortController.signal,\n });\n });\n }\n\n /**\n * Stop all scheduled tasks.\n */\n stop() {\n this.logger.info('Stopping all scheduled search tasks.');\n for (const abortController of this.abortControllers) {\n abortController.abort();\n }\n this.abortControllers = [];\n this.isRunning = false;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentDecoratorFactory,\n DocumentTypeInfo,\n} from '@backstage/plugin-search-common';\nimport { pipeline, Transform } from 'stream';\nimport { Scheduler } from './Scheduler';\nimport {\n IndexBuilderOptions,\n RegisterCollatorParameters,\n RegisterDecoratorParameters,\n SearchEngine,\n} from './types';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\n/**\n * Used for adding collators, decorators and compile them into tasks which are added to a scheduler returned to the caller.\n * @public\n */\nexport class IndexBuilder {\n private collators: Record<string, RegisterCollatorParameters>;\n private decorators: Record<string, DocumentDecoratorFactory[]>;\n private documentTypes: Record<string, DocumentTypeInfo>;\n private searchEngine: SearchEngine;\n private logger: LoggerService;\n\n constructor(options: IndexBuilderOptions) {\n this.collators = {};\n this.decorators = {};\n this.documentTypes = {};\n this.logger = options.logger;\n this.searchEngine = options.searchEngine;\n }\n\n /**\n * Responsible for returning the registered search engine.\n */\n getSearchEngine(): SearchEngine {\n return this.searchEngine;\n }\n\n /**\n * Responsible for returning the registered document types.\n */\n getDocumentTypes(): Record<string, DocumentTypeInfo> {\n return this.documentTypes;\n }\n\n /**\n * Makes the index builder aware of a collator that should be executed at the\n * given refresh interval.\n */\n addCollator(options: RegisterCollatorParameters): void {\n const { factory, schedule } = options;\n\n this.logger.info(\n `Added ${factory.constructor.name} collator factory for type ${factory.type}`,\n );\n this.collators[factory.type] = {\n factory,\n schedule,\n };\n this.documentTypes[factory.type] = {\n visibilityPermission: factory.visibilityPermission,\n };\n }\n\n /**\n * Makes the index builder aware of a decorator. If no types are provided on\n * the decorator, it will be applied to documents from all known collators,\n * otherwise it will only be applied to documents of the given types.\n */\n addDecorator(options: RegisterDecoratorParameters): void {\n const { factory } = options;\n const types = factory.types || ['*'];\n this.logger.info(\n `Added decorator ${factory.constructor.name} to types ${types.join(\n ', ',\n )}`,\n );\n types.forEach(type => {\n if (this.decorators.hasOwnProperty(type)) {\n this.decorators[type].push(factory);\n } else {\n this.decorators[type] = [factory];\n }\n });\n }\n\n /**\n * Compiles collators and decorators into tasks, which are added to a\n * scheduler returned to the caller.\n */\n async build(): Promise<{ scheduler: Scheduler }> {\n const scheduler = new Scheduler({\n logger: this.logger,\n });\n\n Object.keys(this.collators).forEach(type => {\n const taskLogger = this.logger.child({ documentType: type });\n scheduler.addToSchedule({\n id: `search_index_${type.replace('-', '_').toLocaleLowerCase('en-US')}`,\n scheduledRunner: this.collators[type].schedule,\n task: async () => {\n // Instantiate the collator.\n const collator = await this.collators[type].factory.getCollator();\n taskLogger.info(\n `Collating documents for ${type} via ${this.collators[type].factory.constructor.name}`,\n );\n\n // Instantiate all relevant decorators.\n const decorators: Transform[] = await Promise.all(\n (this.decorators['*'] || [])\n .concat(this.decorators[type] || [])\n .map(async factory => {\n const decorator = await factory.getDecorator();\n taskLogger.info(\n `Attached decorator via ${factory.constructor.name} to ${type} index pipeline.`,\n );\n return decorator;\n }),\n );\n\n // Instantiate the indexer.\n const indexer = await this.searchEngine.getIndexer(type);\n\n // Compose collator/decorators/indexer into a pipeline\n return new Promise<void>((resolve, reject) => {\n pipeline(\n [collator, ...decorators, indexer],\n (error: NodeJS.ErrnoException | null) => {\n if (error) {\n taskLogger.error(\n `Collating documents for ${type} failed: ${error}`,\n );\n reject(error);\n } else {\n // Signal index pipeline completion!\n taskLogger.info(`Collating documents for ${type} succeeded`);\n resolve();\n }\n },\n );\n });\n },\n });\n });\n\n return {\n scheduler,\n };\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { DocumentCollatorFactory } from '@backstage/plugin-search-common';\nimport { Permission } from '@backstage/plugin-permission-common';\nimport { Readable } from 'stream';\nimport { UrlReader } from '@backstage/backend-common';\nimport { parse as parseNdjson } from 'ndjson';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\n/**\n * Options for instantiate NewlineDelimitedJsonCollatorFactory\n * @public\n */\nexport type NewlineDelimitedJsonCollatorFactoryOptions = {\n type: string;\n searchPattern: string;\n reader: UrlReader;\n logger: LoggerService;\n visibilityPermission?: Permission;\n};\n\n/**\n * Factory class producing a collator that can be used to index documents\n * sourced from the latest newline delimited JSON file matching a given search\n * pattern. \"Latest\" is determined by the name of the file (last alphabetically\n * is considered latest).\n *\n * @remarks\n * The reader provided must implement the `search()` method as well as the\n * `readUrl` method whose response includes the `stream()` method. Naturally,\n * the reader must also be configured to understand the given search pattern.\n *\n * @example\n * Here's an example configuration using Google Cloud Storage, which would\n * return the latest file under the `bucket` GCS bucket with files like\n * `xyz-2021.ndjson` or `xyz-2022.ndjson`.\n * ```ts\n * indexBuilder.addCollator({\n * schedule,\n * factory: NewlineDelimitedJsonCollatorFactory.fromConfig(env.config, {\n * type: 'techdocs',\n * searchPattern: 'https://storage.cloud.google.com/bucket/xyz-*',\n * reader: env.reader,\n * logger: env.logger,\n * })\n * });\n * ```\n *\n * @public\n */\nexport class NewlineDelimitedJsonCollatorFactory\n implements DocumentCollatorFactory\n{\n readonly type: string;\n\n public readonly visibilityPermission: Permission | undefined;\n\n private constructor(\n type: string,\n private readonly searchPattern: string,\n private readonly reader: UrlReader,\n private readonly logger: LoggerService,\n visibilityPermission: Permission | undefined,\n ) {\n this.type = type;\n this.visibilityPermission = visibilityPermission;\n }\n\n /**\n * Returns a NewlineDelimitedJsonCollatorFactory instance from configuration\n * and a set of options.\n */\n static fromConfig(\n _config: Config,\n options: NewlineDelimitedJsonCollatorFactoryOptions,\n ): NewlineDelimitedJsonCollatorFactory {\n return new NewlineDelimitedJsonCollatorFactory(\n options.type,\n options.searchPattern,\n options.reader,\n options.logger.child({ documentType: options.type }),\n options.visibilityPermission,\n );\n }\n\n /**\n * Returns the \"latest\" URL for the given search pattern (e.g. the one at the\n * end of the list, sorted alphabetically).\n */\n private async lastUrl(): Promise<string | undefined> {\n try {\n // Search for files matching the given pattern, then sort/reverse. The\n // first item in the list will be the \"latest\" file.\n this.logger.info(\n `Attempting to find latest .ndjson matching ${this.searchPattern}`,\n );\n const { files } = await this.reader.search(this.searchPattern);\n const candidates = files\n .filter(file => file.url.endsWith('.ndjson'))\n .sort((a, b) => a.url.localeCompare(b.url))\n .reverse();\n\n return candidates[0]?.url;\n } catch (e) {\n this.logger.error(`Could not search for ${this.searchPattern}`, e);\n throw e;\n }\n }\n\n async getCollator(): Promise<Readable> {\n // Search for files matching the given pattern.\n const lastUrl = await this.lastUrl();\n\n // Abort if no such file could be found.\n if (!lastUrl) {\n const noMatchingFile = `Could not find an .ndjson file matching ${this.searchPattern}`;\n this.logger.error(noMatchingFile);\n throw new Error(noMatchingFile);\n } else {\n this.logger.info(`Using latest .ndjson file ${lastUrl}`);\n }\n\n // Use the UrlReader to try and stream the file.\n const readerResponse = await this.reader.readUrl!(lastUrl);\n const stream = readerResponse.stream!();\n\n // Use ndjson's parser to turn the raw file into an object-mode stream.\n return stream.pipe(parseNdjson());\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isError } from '@backstage/errors';\n\n/**\n * Failed to query documents for index that does not exist.\n * @public\n */\nexport class MissingIndexError extends Error {\n /**\n * An inner error that caused this error to be thrown, if any.\n */\n readonly cause?: Error | undefined;\n\n constructor(message?: string, cause?: Error | unknown) {\n super(message);\n\n Error.captureStackTrace?.(this, this.constructor);\n\n this.name = this.constructor.name;\n this.cause = isError(cause) ? cause : undefined;\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertError } from '@backstage/errors';\nimport { IndexableDocument } from '@backstage/plugin-search-common';\nimport { Writable } from 'stream';\n\n/**\n * Options for {@link BatchSearchEngineIndexer}\n * @public\n */\nexport type BatchSearchEngineOptions = {\n batchSize: number;\n};\n\n/**\n * Base class encapsulating batch-based stream processing. Useful as a base\n * class for search engine indexers.\n * @public\n */\nexport abstract class BatchSearchEngineIndexer extends Writable {\n private batchSize: number;\n private currentBatch: IndexableDocument[] = [];\n\n constructor(options: BatchSearchEngineOptions) {\n super({ objectMode: true });\n this.batchSize = options.batchSize;\n }\n\n /**\n * Receives an array of indexable documents (of size this.batchSize) which\n * should be written to the search engine. This method won't be called again\n * at least until it resolves.\n */\n public abstract index(documents: IndexableDocument[]): Promise<void>;\n\n /**\n * Any asynchronous setup tasks can be performed here.\n */\n public abstract initialize(): Promise<void>;\n\n /**\n * Any asynchronous teardown tasks can be performed here.\n */\n public abstract finalize(): Promise<void>;\n\n /**\n * Encapsulates initialization logic.\n * @internal\n */\n async _construct(done: (error?: Error | null | undefined) => void) {\n try {\n await this.initialize();\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n\n /**\n * Encapsulates batch stream write logic.\n * @internal\n */\n async _write(\n doc: IndexableDocument,\n _e: any,\n done: (error?: Error | null) => void,\n ) {\n this.currentBatch.push(doc);\n if (this.currentBatch.length < this.batchSize) {\n done();\n return;\n }\n\n try {\n await this.index(this.currentBatch);\n this.currentBatch = [];\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n\n /**\n * Encapsulates finalization and final error handling logic.\n * @internal\n */\n async _final(done: (error?: Error | null) => void) {\n try {\n // Index any remaining documents.\n if (this.currentBatch.length) {\n await this.index(this.currentBatch);\n this.currentBatch = [];\n }\n await this.finalize();\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertError } from '@backstage/errors';\nimport { IndexableDocument } from '@backstage/plugin-search-common';\nimport { Transform } from 'stream';\n\n/**\n * Base class encapsulating simple async transformations. Useful as a base\n * class for Backstage search decorators.\n * @public\n */\nexport abstract class DecoratorBase extends Transform {\n constructor() {\n super({ objectMode: true });\n }\n\n /**\n * Any asynchronous setup tasks can be performed here.\n */\n public abstract initialize(): Promise<void>;\n\n /**\n * Receives a single indexable document. In your decorate method, you can:\n *\n * - Resolve `undefined` to indicate the record should be omitted.\n * - Resolve a single modified document, which could contain new fields,\n * edited fields, or removed fields.\n * - Resolve an array of indexable documents, if the purpose if the decorator\n * is to convert one document into multiple derivative documents.\n */\n public abstract decorate(\n document: IndexableDocument,\n ): Promise<IndexableDocument | IndexableDocument[] | undefined>;\n\n /**\n * Any asynchronous teardown tasks can be performed here.\n */\n public abstract finalize(): Promise<void>;\n\n /**\n * Encapsulates initialization logic.\n * @internal\n */\n async _construct(done: (error?: Error | null | undefined) => void) {\n try {\n await this.initialize();\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n\n /**\n * Encapsulates simple transform stream logic.\n * @internal\n */\n async _transform(\n document: IndexableDocument,\n _: any,\n done: (error?: Error | null) => void,\n ) {\n try {\n const decorated = await this.decorate(document);\n\n // If undefined was returned, omit the record and move on.\n if (decorated === undefined) {\n done();\n return;\n }\n\n // If an array of documents was given, push them all.\n if (Array.isArray(decorated)) {\n decorated.forEach(doc => {\n this.push(doc);\n });\n done();\n return;\n }\n\n // Otherwise, just push the decorated document.\n this.push(decorated);\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n\n /**\n * Encapsulates finalization and final error handling logic.\n * @internal\n */\n async _final(done: (error?: Error | null) => void) {\n try {\n await this.finalize();\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IndexableDocument } from '@backstage/plugin-search-common';\nimport lunr from 'lunr';\nimport { BatchSearchEngineIndexer } from '../indexing';\n\n/**\n * Lunr specific search engine indexer\n * @public\n */\nexport class LunrSearchEngineIndexer extends BatchSearchEngineIndexer {\n private schemaInitialized = false;\n private builder: lunr.Builder;\n private docStore: Record<string, IndexableDocument> = {};\n\n constructor() {\n super({ batchSize: 1000 });\n\n this.builder = new lunr.Builder();\n this.builder.pipeline.add(lunr.trimmer, lunr.stopWordFilter, lunr.stemmer);\n this.builder.searchPipeline.add(lunr.stemmer);\n this.builder.metadataWhitelist = ['position'];\n }\n\n // No async initialization required.\n async initialize(): Promise<void> {}\n async finalize(): Promise<void> {}\n\n async index(documents: IndexableDocument[]): Promise<void> {\n if (!this.schemaInitialized) {\n // Make this lunr index aware of all relevant fields.\n Object.keys(documents[0]).forEach(field => {\n this.builder.field(field);\n });\n\n // Set \"location\" field as reference field\n this.builder.ref('location');\n\n this.schemaInitialized = true;\n }\n\n documents.forEach(document => {\n // Add document to Lunar index\n this.builder.add(document);\n\n // Store documents in memory to be able to look up document using the ref during query time\n // This is not how you should implement your SearchEngine implementation! Do not copy!\n this.docStore[document.location] = document;\n });\n }\n\n buildIndex() {\n return this.builder.build();\n }\n\n getDocumentStore() {\n return this.docStore;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n IndexableDocument,\n IndexableResultSet,\n SearchQuery,\n} from '@backstage/plugin-search-common';\nimport { QueryTranslator, SearchEngine } from '../types';\nimport { MissingIndexError } from '../errors';\nimport lunr from 'lunr';\nimport { v4 as uuid } from 'uuid';\nimport { LunrSearchEngineIndexer } from './LunrSearchEngineIndexer';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\n/**\n * Type of translated query for the Lunr Search Engine.\n * @public\n */\nexport type ConcreteLunrQuery = {\n lunrQueryBuilder: lunr.Index.QueryBuilder;\n documentTypes?: string[];\n pageSize: number;\n};\n\ntype LunrResultEnvelope = {\n result: lunr.Index.Result;\n type: string;\n};\n\n/**\n * Translator responsible for translating search term and filters to a query that the Lunr Search Engine understands.\n * @public\n */\nexport type LunrQueryTranslator = (query: SearchQuery) => ConcreteLunrQuery;\n\n/**\n * Lunr specific search engine implementation.\n * @public\n */\nexport class LunrSearchEngine implements SearchEngine {\n protected lunrIndices: Record<string, lunr.Index> = {};\n protected docStore: Record<string, IndexableDocument>;\n protected logger: LoggerService;\n protected highlightPreTag: string;\n protected highlightPostTag: string;\n\n constructor(options: { logger: LoggerService }) {\n this.logger = options.logger;\n this.docStore = {};\n const uuidTag = uuid();\n this.highlightPreTag = `<${uuidTag}>`;\n this.highlightPostTag = `</${uuidTag}>`;\n }\n\n protected translator: QueryTranslator = ({\n term,\n filters,\n types,\n pageLimit,\n }: SearchQuery): ConcreteLunrQuery => {\n const pageSize = pageLimit || 25;\n\n return {\n lunrQueryBuilder: q => {\n const termToken = lunr.tokenizer(term);\n\n // Support for typeahead search is based on https://github.com/olivernn/lunr.js/issues/256#issuecomment-295407852\n // look for an exact match and apply a large positive boost\n q.term(termToken, {\n usePipeline: true,\n boost: 100,\n });\n // look for terms that match the beginning of this term and apply a\n // medium boost\n q.term(termToken, {\n usePipeline: false,\n boost: 10,\n wildcard: lunr.Query.wildcard.TRAILING,\n });\n // look for terms that match with an edit distance of 2 and apply a\n // small boost\n q.term(termToken, {\n usePipeline: false,\n editDistance: 2,\n boost: 1,\n });\n\n if (filters) {\n Object.entries(filters).forEach(([field, fieldValue]) => {\n if (!q.allFields.includes(field)) {\n // Throw for unknown field, as this will be a non match\n throw new Error(`unrecognised field ${field}`);\n }\n // Arrays are poorly supported, but we can make it better for single-item arrays,\n // which should be a common case\n const value =\n Array.isArray(fieldValue) && fieldValue.length === 1\n ? fieldValue[0]\n : fieldValue;\n\n // Require that the given field has the given value\n if (['string', 'number', 'boolean'].includes(typeof value)) {\n q.term(\n lunr\n .tokenizer(value?.toString())\n .map(lunr.stopWordFilter)\n .filter(element => element !== undefined),\n {\n presence: lunr.Query.presence.REQUIRED,\n fields: [field],\n },\n );\n } else if (Array.isArray(value)) {\n // Illustrate how multi-value filters could work.\n // But warn that Lurn supports this poorly.\n this.logger.warn(\n `Non-scalar filter value used for field ${field}. Consider using a different Search Engine for better results.`,\n );\n q.term(lunr.tokenizer(value), {\n presence: lunr.Query.presence.OPTIONAL,\n fields: [field],\n });\n } else {\n // Log a warning or something about unknown filter value\n this.logger.warn(`Unknown filter type used on field ${field}`);\n }\n });\n }\n },\n documentTypes: types,\n pageSize,\n };\n };\n\n setTranslator(translator: LunrQueryTranslator) {\n this.translator = translator;\n }\n\n async getIndexer(type: string) {\n const indexer = new LunrSearchEngineIndexer();\n const indexerLogger = this.logger.child({ documentType: type });\n let errorThrown: Error | undefined;\n\n indexer.on('error', err => {\n errorThrown = err;\n });\n\n indexer.on('close', () => {\n // Once the stream is closed, build the index and store the documents in\n // memory for later retrieval.\n const newDocuments = indexer.getDocumentStore();\n const docStoreExists = this.lunrIndices[type] !== undefined;\n const documentsIndexed = Object.keys(newDocuments).length;\n\n // Do not set the index if there was an error or if no documents were\n // indexed. This ensures search continues to work for an index, even in\n // case of transient issues in underlying collators.\n if (!errorThrown && documentsIndexed > 0) {\n this.lunrIndices[type] = indexer.buildIndex();\n this.docStore = { ...this.docStore, ...newDocuments };\n } else {\n indexerLogger.warn(\n `Index for ${type} was not ${\n docStoreExists ? 'replaced' : 'created'\n }: ${\n errorThrown\n ? 'an error was encountered'\n : 'indexer received 0 documents'\n }`,\n );\n }\n });\n\n return indexer;\n }\n\n async query(query: SearchQuery): Promise<IndexableResultSet> {\n const { lunrQueryBuilder, documentTypes, pageSize } = this.translator(\n query,\n ) as ConcreteLunrQuery;\n\n const results: LunrResultEnvelope[] = [];\n\n const indexKeys = Object.keys(this.lunrIndices).filter(\n type => !documentTypes || documentTypes.includes(type),\n );\n\n if (documentTypes?.length && !indexKeys.length) {\n throw new MissingIndexError(\n `Missing index for ${documentTypes?.toString()}. This could be because the index hasn't been created yet or there was a problem during index creation.`,\n );\n }\n\n // Iterate over the filtered list of this.lunrIndex keys.\n indexKeys.forEach(type => {\n try {\n results.push(\n ...this.lunrIndices[type].query(lunrQueryBuilder).map(result => {\n return {\n result: result,\n type: type,\n };\n }),\n );\n } catch (err) {\n // if a field does not exist on a index, we can see that as a no-match\n if (\n err instanceof Error &&\n err.message.startsWith('unrecognised field')\n ) {\n return;\n }\n throw err;\n }\n });\n\n // Sort results.\n results.sort((doc1, doc2) => {\n return doc2.result.score - doc1.result.score;\n });\n\n // Perform paging\n const { page } = decodePageCursor(query.pageCursor);\n const offset = page * pageSize;\n const hasPreviousPage = page > 0;\n const hasNextPage = results.length > offset + pageSize;\n const nextPageCursor = hasNextPage\n ? encodePageCursor({ page: page + 1 })\n : undefined;\n const previousPageCursor = hasPreviousPage\n ? encodePageCursor({ page: page - 1 })\n : undefined;\n\n // Translate results into IndexableResultSet\n const realResultSet: IndexableResultSet = {\n results: results.slice(offset, offset + pageSize).map((d, index) => ({\n type: d.type,\n document: this.docStore[d.result.ref],\n rank: page * pageSize + index + 1,\n highlight: {\n preTag: this.highlightPreTag,\n postTag: this.highlightPostTag,\n fields: parseHighlightFields({\n preTag: this.highlightPreTag,\n postTag: this.highlightPostTag,\n doc: this.docStore[d.result.ref],\n positionMetadata: d.result.matchData.metadata as any,\n }),\n },\n })),\n numberOfResults: results.length,\n nextPageCursor,\n previousPageCursor,\n };\n\n return realResultSet;\n }\n}\n\nexport function decodePageCursor(pageCursor?: string): { page: number } {\n if (!pageCursor) {\n return { page: 0 };\n }\n\n return {\n page: Number(Buffer.from(pageCursor, 'base64').toString('utf-8')),\n };\n}\n\nexport function encodePageCursor({ page }: { page: number }): string {\n return Buffer.from(`${page}`, 'utf-8').toString('base64');\n}\n\ntype ParseHighlightFieldsProps = {\n preTag: string;\n postTag: string;\n doc: any;\n positionMetadata: {\n [term: string]: {\n [field: string]: {\n position: number[][];\n };\n };\n };\n};\n\nexport function parseHighlightFields({\n preTag,\n postTag,\n doc,\n positionMetadata,\n}: ParseHighlightFieldsProps): { [field: string]: string } {\n // Merge the field positions across all query terms\n const highlightFieldPositions = Object.values(positionMetadata).reduce(\n (fieldPositions, metadata) => {\n Object.keys(metadata).map(fieldKey => {\n const validFieldMetadataPositions = metadata[\n fieldKey\n ]?.position?.filter(position => Array.isArray(position));\n if (validFieldMetadataPositions.length) {\n fieldPositions[fieldKey] = fieldPositions[fieldKey] ?? [];\n fieldPositions[fieldKey].push(...validFieldMetadataPositions);\n }\n });\n\n return fieldPositions;\n },\n {} as { [field: string]: number[][] },\n );\n\n return Object.fromEntries(\n Object.entries(highlightFieldPositions).map(([field, positions]) => {\n positions.sort((a, b) => b[0] - a[0]);\n\n const highlightedField = positions.reduce((content, pos) => {\n return (\n `${String(content).substring(0, pos[0])}${preTag}` +\n `${String(content).substring(pos[0], pos[0] + pos[1])}` +\n `${postTag}${String(content).substring(pos[0] + pos[1])}`\n );\n }, doc[field] ?? '');\n\n return [field, highlightedField];\n }),\n );\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IndexableDocument } from '@backstage/plugin-search-common';\nimport { pipeline, Readable, Transform, Writable } from 'stream';\n\n/**\n * Object resolved after a test pipeline is executed.\n * @public\n */\nexport type TestPipelineResult = {\n /**\n * If an error was emitted by the pipeline, it will be set here.\n */\n error: unknown;\n\n /**\n * A list of documents collected at the end of the pipeline. If the subject\n * under test is an indexer, this will be an empty array (because your\n * indexer should have received the documents instead).\n */\n documents: IndexableDocument[];\n};\n\n/**\n * Test utility for Backstage Search collators, decorators, and indexers.\n *\n * @example\n * An example test checking that a collator provides expected documents.\n * ```\n * it('provides expected documents', async () => {\n * const testSubject = await yourCollatorFactory.getCollator();\n * const pipeline = TestPipeline.fromCollator(testSubject);\n *\n * const { documents } = await pipeline.execute();\n *\n * expect(documents).toHaveLength(2);\n * })\n * ```\n *\n * @example\n * An example test checking that a decorator behaves as expected.\n * ```\n * it('filters private documents', async () => {\n * const testSubject = await yourDecoratorFactory.getDecorator();\n * const pipeline = TestPipeline\n * .fromDecorator(testSubject)\n * .withDocuments([{ title: 'Private', location: '/private', text: '' }]);\n *\n * const { documents } = await pipeline.execute();\n *\n * expect(documents).toHaveLength(0);\n * })\n * ```\n *\n * @public\n */\nexport class TestPipeline {\n private collator?: Readable;\n private decorator?: Transform;\n private indexer?: Writable;\n\n private constructor({\n collator,\n decorator,\n indexer,\n }: {\n collator?: Readable;\n decorator?: Transform;\n indexer?: Writable;\n }) {\n this.collator = collator;\n this.decorator = decorator;\n this.indexer = indexer;\n }\n\n /**\n * Provide the collator, decorator, or indexer to be tested.\n *\n * @deprecated Use `fromCollator`, `fromDecorator` or `fromIndexer` static\n * methods to create a test pipeline instead.\n */\n static withSubject(subject: Readable | Transform | Writable) {\n if (subject instanceof Transform) {\n return new TestPipeline({ decorator: subject });\n }\n\n if (subject instanceof Writable) {\n return new TestPipeline({ indexer: subject });\n }\n\n if (subject.readable || subject instanceof Readable) {\n return new TestPipeline({ collator: subject });\n }\n\n throw new Error(\n 'Unknown test subject: are you passing a readable, writable, or transform stream?',\n );\n }\n\n /**\n * Create a test pipeline given a collator you want to test.\n */\n static fromCollator(collator: Readable) {\n return new TestPipeline({ collator });\n }\n\n /**\n * Add a collator to the test pipeline.\n */\n withCollator(collator: Readable): this {\n this.collator = collator;\n return this;\n }\n\n /**\n * Create a test pipeline given a decorator you want to test.\n */\n static fromDecorator(decorator: Transform) {\n return new TestPipeline({ decorator });\n }\n\n /**\n * Add a decorator to the test pipeline.\n */\n withDecorator(decorator: Transform): this {\n this.decorator = decorator;\n return this;\n }\n\n /**\n * Create a test pipeline given an indexer you want to test.\n */\n static fromIndexer(indexer: Writable) {\n return new TestPipeline({ indexer });\n }\n\n /**\n * Add an indexer to the test pipeline.\n */\n withIndexer(indexer: Writable): this {\n this.indexer = indexer;\n return this;\n }\n\n /**\n * Provide documents for testing decorators and indexers.\n */\n withDocuments(documents: IndexableDocument[]): TestPipeline {\n if (this.collator) {\n throw new Error('Cannot provide documents when testing a collator.');\n }\n\n // Set a naive readable stream that just pushes all given documents.\n this.collator = new Readable({ objectMode: true });\n this.collator._read = () => {};\n process.nextTick(() => {\n documents.forEach(document => {\n this.collator!.push(document);\n });\n this.collator!.push(null);\n });\n\n return this;\n }\n\n /**\n * Execute the test pipeline so that you can make assertions about the result\n * or behavior of the given test subject.\n */\n async execute(): Promise<TestPipelineResult> {\n const documents: IndexableDocument[] = [];\n if (!this.collator) {\n throw new Error(\n 'Cannot execute pipeline without a collator or documents',\n );\n }\n\n // If we are here and there is no indexer, we are testing a collator or a\n // decorator. Set up a naive writable that captures documents in memory.\n if (!this.indexer) {\n this.indexer = new Writable({ objectMode: true });\n this.indexer._write = (document: IndexableDocument, _, done) => {\n documents.push(document);\n done();\n };\n }\n\n return new Promise<TestPipelineResult>(done => {\n const pipes: (Readable | Transform | Writable)[] = [this.collator!];\n if (this.decorator) {\n pipes.push(this.decorator);\n }\n pipes.push(this.indexer!);\n\n pipeline(pipes, (error: NodeJS.ErrnoException | null) => {\n done({\n error,\n documents,\n });\n });\n });\n }\n}\n"],"names":["__publicField","pipeline","parseNdjson","isError","Writable","assertError","Transform","lunr","uuid","Readable"],"mappings":";;;;;;;;;;;;;;;;;;AAsCO,MAAM,SAAU,CAAA;AAAA,EAMrB,YAAY,OAAoC,EAAA;AALhD,IAAQA,eAAA,CAAA,IAAA,EAAA,QAAA,CAAA,CAAA;AACR,IAAQA,eAAA,CAAA,IAAA,EAAA,UAAA,CAAA,CAAA;AACR,IA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S,CAAC,QAAA,EAA6B,GAAG,IAAS,KAAA;AAC9D,QAAA,SAAA,CAAU,KAAK,QAAQ,CAAA,CAAA;AACvB,QAAK,IAAA,EAAA,CAAA;AAAA,OACP,CAAA;AAAA,KACF;AAEA,IAAO,OAAA,IAAI,QAA4B,CAAQ,IAAA,KAAA;AAC7C,MAAM,MAAA,KAAA,GAA6C,CAAC,IAAA,CAAK,QAAS,CAAA,CAAA;AAClE,MAAA,IAAI,KAAK,SAAW,EAAA;AAClB,QAAM,KAAA,CAAA,IAAA,CAAK,KAAK,SAAS,CAAA,CAAA;AAAA,OAC3B;AACA,MAAM,KAAA,CAAA,IAAA,CAAK,KAAK,OAAQ,CAAA,CAAA;AAExB,MAASH,eAAA,CAAA,KAAA,EAAO,CAAC,KAAwC,KAAA;AACvD,QAAK,IAAA,CAAA;AAAA,UACH,KAAA;AAAA,UACA,SAAA;AAAA,SACD,CAAA,CAAA;AAAA,OACF,CAAA,CAAA;AAAA,KACF,CAAA,CAAA;AAAA,GACH;AACF;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/Scheduler.ts","../src/IndexBuilder.ts","../src/collators/NewlineDelimitedJsonCollatorFactory.ts","../src/errors.ts","../src/indexing/BatchSearchEngineIndexer.ts","../src/indexing/DecoratorBase.ts","../src/engines/LunrSearchEngineIndexer.ts","../src/engines/LunrSearchEngine.ts","../src/test-utils/TestPipeline.ts"],"sourcesContent":["/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TaskFunction, TaskRunner } from '@backstage/backend-tasks';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\ntype TaskEnvelope = {\n task: TaskFunction;\n scheduledRunner: TaskRunner;\n};\n\n/**\n * ScheduleTaskParameters\n * @public\n */\nexport type ScheduleTaskParameters = {\n id: string;\n task: TaskFunction;\n scheduledRunner: TaskRunner;\n};\n\n/**\n * Scheduler responsible for all search tasks.\n * @public\n */\nexport class Scheduler {\n private logger: LoggerService;\n private schedule: { [id: string]: TaskEnvelope };\n private abortControllers: AbortController[];\n private isRunning: boolean;\n\n constructor(options: { logger: LoggerService }) {\n this.logger = options.logger;\n this.schedule = {};\n this.abortControllers = [];\n this.isRunning = false;\n }\n\n /**\n * Adds each task and interval to the schedule.\n * When running the tasks, the scheduler waits at least for the time specified\n * in the interval once the task was completed, before running it again.\n */\n addToSchedule(options: ScheduleTaskParameters) {\n const { id, task, scheduledRunner } = options;\n\n if (this.isRunning) {\n throw new Error(\n 'Cannot add task to schedule that has already been started.',\n );\n }\n\n if (this.schedule[id]) {\n throw new Error(`Task with id ${id} already exists.`);\n }\n\n this.schedule[id] = { task, scheduledRunner };\n }\n\n /**\n * Starts the scheduling process for each task\n */\n start() {\n this.logger.info('Starting all scheduled search tasks.');\n this.isRunning = true;\n Object.keys(this.schedule).forEach(id => {\n const abortController = new AbortController();\n this.abortControllers.push(abortController);\n const { task, scheduledRunner } = this.schedule[id];\n scheduledRunner.run({\n id,\n fn: task,\n signal: abortController.signal,\n });\n });\n }\n\n /**\n * Stop all scheduled tasks.\n */\n stop() {\n this.logger.info('Stopping all scheduled search tasks.');\n for (const abortController of this.abortControllers) {\n abortController.abort();\n }\n this.abortControllers = [];\n this.isRunning = false;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentDecoratorFactory,\n DocumentTypeInfo,\n} from '@backstage/plugin-search-common';\nimport { pipeline, Transform } from 'stream';\nimport { Scheduler } from './Scheduler';\nimport {\n IndexBuilderOptions,\n RegisterCollatorParameters,\n RegisterDecoratorParameters,\n SearchEngine,\n} from './types';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\n/**\n * Used for adding collators, decorators and compile them into tasks which are added to a scheduler returned to the caller.\n * @public\n */\nexport class IndexBuilder {\n private collators: Record<string, RegisterCollatorParameters>;\n private decorators: Record<string, DocumentDecoratorFactory[]>;\n private documentTypes: Record<string, DocumentTypeInfo>;\n private searchEngine: SearchEngine;\n private logger: LoggerService;\n\n constructor(options: IndexBuilderOptions) {\n this.collators = {};\n this.decorators = {};\n this.documentTypes = {};\n this.logger = options.logger;\n this.searchEngine = options.searchEngine;\n }\n\n /**\n * Responsible for returning the registered search engine.\n */\n getSearchEngine(): SearchEngine {\n return this.searchEngine;\n }\n\n /**\n * Responsible for returning the registered document types.\n */\n getDocumentTypes(): Record<string, DocumentTypeInfo> {\n return this.documentTypes;\n }\n\n /**\n * Makes the index builder aware of a collator that should be executed at the\n * given refresh interval.\n */\n addCollator(options: RegisterCollatorParameters): void {\n const { factory, schedule } = options;\n\n this.logger.info(\n `Added ${factory.constructor.name} collator factory for type ${factory.type}`,\n );\n this.collators[factory.type] = {\n factory,\n schedule,\n };\n this.documentTypes[factory.type] = {\n visibilityPermission: factory.visibilityPermission,\n };\n }\n\n /**\n * Makes the index builder aware of a decorator. If no types are provided on\n * the decorator, it will be applied to documents from all known collators,\n * otherwise it will only be applied to documents of the given types.\n */\n addDecorator(options: RegisterDecoratorParameters): void {\n const { factory } = options;\n const types = factory.types || ['*'];\n this.logger.info(\n `Added decorator ${factory.constructor.name} to types ${types.join(\n ', ',\n )}`,\n );\n types.forEach(type => {\n if (this.decorators.hasOwnProperty(type)) {\n this.decorators[type].push(factory);\n } else {\n this.decorators[type] = [factory];\n }\n });\n }\n\n /**\n * Compiles collators and decorators into tasks, which are added to a\n * scheduler returned to the caller.\n */\n async build(): Promise<{ scheduler: Scheduler }> {\n const scheduler = new Scheduler({\n logger: this.logger,\n });\n\n Object.keys(this.collators).forEach(type => {\n const taskLogger = this.logger.child({ documentType: type });\n scheduler.addToSchedule({\n id: `search_index_${type.replace('-', '_').toLocaleLowerCase('en-US')}`,\n scheduledRunner: this.collators[type].schedule,\n task: async () => {\n // Instantiate the collator.\n const collator = await this.collators[type].factory.getCollator();\n taskLogger.info(\n `Collating documents for ${type} via ${this.collators[type].factory.constructor.name}`,\n );\n\n // Instantiate all relevant decorators.\n const decorators: Transform[] = await Promise.all(\n (this.decorators['*'] || [])\n .concat(this.decorators[type] || [])\n .map(async factory => {\n const decorator = await factory.getDecorator();\n taskLogger.info(\n `Attached decorator via ${factory.constructor.name} to ${type} index pipeline.`,\n );\n return decorator;\n }),\n );\n\n // Instantiate the indexer.\n const indexer = await this.searchEngine.getIndexer(type);\n\n // Compose collator/decorators/indexer into a pipeline\n return new Promise<void>((resolve, reject) => {\n pipeline(\n [collator, ...decorators, indexer],\n (error: NodeJS.ErrnoException | null) => {\n if (error) {\n taskLogger.error(\n `Collating documents for ${type} failed: ${error}`,\n );\n reject(error);\n } else {\n // Signal index pipeline completion!\n taskLogger.info(`Collating documents for ${type} succeeded`);\n resolve();\n }\n },\n );\n });\n },\n });\n });\n\n return {\n scheduler,\n };\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Config } from '@backstage/config';\nimport { DocumentCollatorFactory } from '@backstage/plugin-search-common';\nimport { Permission } from '@backstage/plugin-permission-common';\nimport { Readable } from 'stream';\nimport { UrlReader } from '@backstage/backend-common';\nimport { parse as parseNdjson } from 'ndjson';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\n/**\n * Options for instantiate NewlineDelimitedJsonCollatorFactory\n * @public\n */\nexport type NewlineDelimitedJsonCollatorFactoryOptions = {\n type: string;\n searchPattern: string;\n reader: UrlReader;\n logger: LoggerService;\n visibilityPermission?: Permission;\n};\n\n/**\n * Factory class producing a collator that can be used to index documents\n * sourced from the latest newline delimited JSON file matching a given search\n * pattern. \"Latest\" is determined by the name of the file (last alphabetically\n * is considered latest).\n *\n * @remarks\n * The reader provided must implement the `search()` method as well as the\n * `readUrl` method whose response includes the `stream()` method. Naturally,\n * the reader must also be configured to understand the given search pattern.\n *\n * @example\n * Here's an example configuration using Google Cloud Storage, which would\n * return the latest file under the `bucket` GCS bucket with files like\n * `xyz-2021.ndjson` or `xyz-2022.ndjson`.\n * ```ts\n * indexBuilder.addCollator({\n * schedule,\n * factory: NewlineDelimitedJsonCollatorFactory.fromConfig(env.config, {\n * type: 'techdocs',\n * searchPattern: 'https://storage.cloud.google.com/bucket/xyz-*',\n * reader: env.reader,\n * logger: env.logger,\n * })\n * });\n * ```\n *\n * @public\n */\nexport class NewlineDelimitedJsonCollatorFactory\n implements DocumentCollatorFactory\n{\n readonly type: string;\n\n public readonly visibilityPermission: Permission | undefined;\n\n private constructor(\n type: string,\n private readonly searchPattern: string,\n private readonly reader: UrlReader,\n private readonly logger: LoggerService,\n visibilityPermission: Permission | undefined,\n ) {\n this.type = type;\n this.visibilityPermission = visibilityPermission;\n }\n\n /**\n * Returns a NewlineDelimitedJsonCollatorFactory instance from configuration\n * and a set of options.\n */\n static fromConfig(\n _config: Config,\n options: NewlineDelimitedJsonCollatorFactoryOptions,\n ): NewlineDelimitedJsonCollatorFactory {\n return new NewlineDelimitedJsonCollatorFactory(\n options.type,\n options.searchPattern,\n options.reader,\n options.logger.child({ documentType: options.type }),\n options.visibilityPermission,\n );\n }\n\n /**\n * Returns the \"latest\" URL for the given search pattern (e.g. the one at the\n * end of the list, sorted alphabetically).\n */\n private async lastUrl(): Promise<string | undefined> {\n try {\n // Search for files matching the given pattern, then sort/reverse. The\n // first item in the list will be the \"latest\" file.\n this.logger.info(\n `Attempting to find latest .ndjson matching ${this.searchPattern}`,\n );\n const { files } = await this.reader.search(this.searchPattern);\n const candidates = files\n .filter(file => file.url.endsWith('.ndjson'))\n .sort((a, b) => a.url.localeCompare(b.url))\n .reverse();\n\n return candidates[0]?.url;\n } catch (e) {\n this.logger.error(`Could not search for ${this.searchPattern}`, e);\n throw e;\n }\n }\n\n async getCollator(): Promise<Readable> {\n // Search for files matching the given pattern.\n const lastUrl = await this.lastUrl();\n\n // Abort if no such file could be found.\n if (!lastUrl) {\n const noMatchingFile = `Could not find an .ndjson file matching ${this.searchPattern}`;\n this.logger.error(noMatchingFile);\n throw new Error(noMatchingFile);\n } else {\n this.logger.info(`Using latest .ndjson file ${lastUrl}`);\n }\n\n // Use the UrlReader to try and stream the file.\n const readerResponse = await this.reader.readUrl!(lastUrl);\n const stream = readerResponse.stream!();\n\n // Use ndjson's parser to turn the raw file into an object-mode stream.\n return stream.pipe(parseNdjson());\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isError } from '@backstage/errors';\n\n/**\n * Failed to query documents for index that does not exist.\n * @public\n */\nexport class MissingIndexError extends Error {\n /**\n * An inner error that caused this error to be thrown, if any.\n */\n readonly cause?: Error | undefined;\n\n constructor(message?: string, cause?: Error | unknown) {\n super(message);\n\n Error.captureStackTrace?.(this, this.constructor);\n\n this.name = this.constructor.name;\n this.cause = isError(cause) ? cause : undefined;\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertError } from '@backstage/errors';\nimport { IndexableDocument } from '@backstage/plugin-search-common';\nimport { Writable } from 'stream';\n\n/**\n * Options for {@link BatchSearchEngineIndexer}\n * @public\n */\nexport type BatchSearchEngineOptions = {\n batchSize: number;\n};\n\n/**\n * Base class encapsulating batch-based stream processing. Useful as a base\n * class for search engine indexers.\n * @public\n */\nexport abstract class BatchSearchEngineIndexer extends Writable {\n private batchSize: number;\n private currentBatch: IndexableDocument[] = [];\n\n constructor(options: BatchSearchEngineOptions) {\n super({ objectMode: true });\n this.batchSize = options.batchSize;\n }\n\n /**\n * Receives an array of indexable documents (of size this.batchSize) which\n * should be written to the search engine. This method won't be called again\n * at least until it resolves.\n */\n public abstract index(documents: IndexableDocument[]): Promise<void>;\n\n /**\n * Any asynchronous setup tasks can be performed here.\n */\n public abstract initialize(): Promise<void>;\n\n /**\n * Any asynchronous teardown tasks can be performed here.\n */\n public abstract finalize(): Promise<void>;\n\n /**\n * Encapsulates initialization logic.\n * @internal\n */\n async _construct(done: (error?: Error | null | undefined) => void) {\n try {\n await this.initialize();\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n\n /**\n * Encapsulates batch stream write logic.\n * @internal\n */\n async _write(\n doc: IndexableDocument,\n _e: any,\n done: (error?: Error | null) => void,\n ) {\n this.currentBatch.push(doc);\n if (this.currentBatch.length < this.batchSize) {\n done();\n return;\n }\n\n try {\n await this.index(this.currentBatch);\n this.currentBatch = [];\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n\n /**\n * Encapsulates finalization and final error handling logic.\n * @internal\n */\n async _final(done: (error?: Error | null) => void) {\n try {\n // Index any remaining documents.\n if (this.currentBatch.length) {\n await this.index(this.currentBatch);\n this.currentBatch = [];\n }\n await this.finalize();\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { assertError } from '@backstage/errors';\nimport { IndexableDocument } from '@backstage/plugin-search-common';\nimport { Transform } from 'stream';\n\n/**\n * Base class encapsulating simple async transformations. Useful as a base\n * class for Backstage search decorators.\n * @public\n */\nexport abstract class DecoratorBase extends Transform {\n constructor() {\n super({ objectMode: true });\n }\n\n /**\n * Any asynchronous setup tasks can be performed here.\n */\n public abstract initialize(): Promise<void>;\n\n /**\n * Receives a single indexable document. In your decorate method, you can:\n *\n * - Resolve `undefined` to indicate the record should be omitted.\n * - Resolve a single modified document, which could contain new fields,\n * edited fields, or removed fields.\n * - Resolve an array of indexable documents, if the purpose if the decorator\n * is to convert one document into multiple derivative documents.\n */\n public abstract decorate(\n document: IndexableDocument,\n ): Promise<IndexableDocument | IndexableDocument[] | undefined>;\n\n /**\n * Any asynchronous teardown tasks can be performed here.\n */\n public abstract finalize(): Promise<void>;\n\n /**\n * Encapsulates initialization logic.\n * @internal\n */\n async _construct(done: (error?: Error | null | undefined) => void) {\n try {\n await this.initialize();\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n\n /**\n * Encapsulates simple transform stream logic.\n * @internal\n */\n async _transform(\n document: IndexableDocument,\n _: any,\n done: (error?: Error | null) => void,\n ) {\n try {\n const decorated = await this.decorate(document);\n\n // If undefined was returned, omit the record and move on.\n if (decorated === undefined) {\n done();\n return;\n }\n\n // If an array of documents was given, push them all.\n if (Array.isArray(decorated)) {\n decorated.forEach(doc => {\n this.push(doc);\n });\n done();\n return;\n }\n\n // Otherwise, just push the decorated document.\n this.push(decorated);\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n\n /**\n * Encapsulates finalization and final error handling logic.\n * @internal\n */\n async _final(done: (error?: Error | null) => void) {\n try {\n await this.finalize();\n done();\n } catch (e) {\n assertError(e);\n done(e);\n }\n }\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IndexableDocument } from '@backstage/plugin-search-common';\nimport lunr from 'lunr';\nimport { BatchSearchEngineIndexer } from '../indexing';\n\n/**\n * Lunr specific search engine indexer\n * @public\n */\nexport class LunrSearchEngineIndexer extends BatchSearchEngineIndexer {\n private schemaInitialized = false;\n private builder: lunr.Builder;\n private docStore: Record<string, IndexableDocument> = {};\n\n constructor() {\n super({ batchSize: 1000 });\n\n this.builder = new lunr.Builder();\n this.builder.pipeline.add(lunr.trimmer, lunr.stopWordFilter, lunr.stemmer);\n this.builder.searchPipeline.add(lunr.stemmer);\n this.builder.metadataWhitelist = ['position'];\n }\n\n // No async initialization required.\n async initialize(): Promise<void> {}\n async finalize(): Promise<void> {}\n\n async index(documents: IndexableDocument[]): Promise<void> {\n if (!this.schemaInitialized) {\n // Make this lunr index aware of all relevant fields.\n Object.keys(documents[0]).forEach(field => {\n this.builder.field(field);\n });\n\n // Set \"location\" field as reference field\n this.builder.ref('location');\n\n this.schemaInitialized = true;\n }\n\n documents.forEach(document => {\n // Add document to Lunar index\n this.builder.add(document);\n\n // Store documents in memory to be able to look up document using the ref during query time\n // This is not how you should implement your SearchEngine implementation! Do not copy!\n this.docStore[document.location] = document;\n });\n }\n\n buildIndex() {\n return this.builder.build();\n }\n\n getDocumentStore() {\n return this.docStore;\n }\n}\n","/*\n * Copyright 2021 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n IndexableDocument,\n IndexableResultSet,\n SearchQuery,\n} from '@backstage/plugin-search-common';\nimport { QueryTranslator, SearchEngine } from '../types';\nimport { MissingIndexError } from '../errors';\nimport lunr from 'lunr';\nimport { v4 as uuid } from 'uuid';\nimport { LunrSearchEngineIndexer } from './LunrSearchEngineIndexer';\nimport { LoggerService } from '@backstage/backend-plugin-api';\n\n/**\n * Type of translated query for the Lunr Search Engine.\n * @public\n */\nexport type ConcreteLunrQuery = {\n lunrQueryBuilder: lunr.Index.QueryBuilder;\n documentTypes?: string[];\n pageSize: number;\n};\n\ntype LunrResultEnvelope = {\n result: lunr.Index.Result;\n type: string;\n};\n\n/**\n * Translator responsible for translating search term and filters to a query that the Lunr Search Engine understands.\n * @public\n */\nexport type LunrQueryTranslator = (query: SearchQuery) => ConcreteLunrQuery;\n\n/**\n * Lunr specific search engine implementation.\n * @public\n */\nexport class LunrSearchEngine implements SearchEngine {\n protected lunrIndices: Record<string, lunr.Index> = {};\n protected docStore: Record<string, IndexableDocument>;\n protected logger: LoggerService;\n protected highlightPreTag: string;\n protected highlightPostTag: string;\n\n constructor(options: { logger: LoggerService }) {\n this.logger = options.logger;\n this.docStore = {};\n const uuidTag = uuid();\n this.highlightPreTag = `<${uuidTag}>`;\n this.highlightPostTag = `</${uuidTag}>`;\n }\n\n protected translator: QueryTranslator = ({\n term,\n filters,\n types,\n pageLimit,\n }: SearchQuery): ConcreteLunrQuery => {\n const pageSize = pageLimit || 25;\n\n return {\n lunrQueryBuilder: q => {\n const termToken = lunr.tokenizer(term);\n\n // Support for typeahead search is based on https://github.com/olivernn/lunr.js/issues/256#issuecomment-295407852\n // look for an exact match and apply a large positive boost\n q.term(termToken, {\n usePipeline: true,\n boost: 100,\n });\n // look for terms that match the beginning of this term and apply a\n // medium boost\n q.term(termToken, {\n usePipeline: false,\n boost: 10,\n wildcard: lunr.Query.wildcard.TRAILING,\n });\n // look for terms that match with an edit distance of 2 and apply a\n // small boost\n q.term(termToken, {\n usePipeline: false,\n editDistance: 2,\n boost: 1,\n });\n\n if (filters) {\n Object.entries(filters).forEach(([field, fieldValue]) => {\n if (!q.allFields.includes(field)) {\n // Throw for unknown field, as this will be a non match\n throw new Error(`unrecognised field ${field}`);\n }\n // Arrays are poorly supported, but we can make it better for single-item arrays,\n // which should be a common case\n const value =\n Array.isArray(fieldValue) && fieldValue.length === 1\n ? fieldValue[0]\n : fieldValue;\n\n // Require that the given field has the given value\n if (['string', 'number', 'boolean'].includes(typeof value)) {\n q.term(\n lunr\n .tokenizer(value?.toString())\n .map(lunr.stopWordFilter)\n .filter(element => element !== undefined),\n {\n presence: lunr.Query.presence.REQUIRED,\n fields: [field],\n },\n );\n } else if (Array.isArray(value)) {\n // Illustrate how multi-value filters could work.\n // But warn that Lurn supports this poorly.\n this.logger.warn(\n `Non-scalar filter value used for field ${field}. Consider using a different Search Engine for better results.`,\n );\n q.term(lunr.tokenizer(value), {\n presence: lunr.Query.presence.OPTIONAL,\n fields: [field],\n });\n } else {\n // Log a warning or something about unknown filter value\n this.logger.warn(`Unknown filter type used on field ${field}`);\n }\n });\n }\n },\n documentTypes: types,\n pageSize,\n };\n };\n\n setTranslator(translator: LunrQueryTranslator) {\n this.translator = translator;\n }\n\n async getIndexer(type: string) {\n const indexer = new LunrSearchEngineIndexer();\n const indexerLogger = this.logger.child({ documentType: type });\n let errorThrown: Error | undefined;\n\n indexer.on('error', err => {\n errorThrown = err;\n });\n\n indexer.on('close', () => {\n // Once the stream is closed, build the index and store the documents in\n // memory for later retrieval.\n const newDocuments = indexer.getDocumentStore();\n const docStoreExists = this.lunrIndices[type] !== undefined;\n const documentsIndexed = Object.keys(newDocuments).length;\n\n // Do not set the index if there was an error or if no documents were\n // indexed. This ensures search continues to work for an index, even in\n // case of transient issues in underlying collators.\n if (!errorThrown && documentsIndexed > 0) {\n this.lunrIndices[type] = indexer.buildIndex();\n this.docStore = { ...this.docStore, ...newDocuments };\n } else {\n indexerLogger.warn(\n `Index for ${type} was not ${\n docStoreExists ? 'replaced' : 'created'\n }: ${\n errorThrown\n ? 'an error was encountered'\n : 'indexer received 0 documents'\n }`,\n );\n }\n });\n\n return indexer;\n }\n\n async query(query: SearchQuery): Promise<IndexableResultSet> {\n const { lunrQueryBuilder, documentTypes, pageSize } = this.translator(\n query,\n ) as ConcreteLunrQuery;\n\n const results: LunrResultEnvelope[] = [];\n\n const indexKeys = Object.keys(this.lunrIndices).filter(\n type => !documentTypes || documentTypes.includes(type),\n );\n\n if (documentTypes?.length && !indexKeys.length) {\n throw new MissingIndexError(\n `Missing index for ${documentTypes?.toString()}. This could be because the index hasn't been created yet or there was a problem during index creation.`,\n );\n }\n\n // Iterate over the filtered list of this.lunrIndex keys.\n indexKeys.forEach(type => {\n try {\n results.push(\n ...this.lunrIndices[type].query(lunrQueryBuilder).map(result => {\n return {\n result: result,\n type: type,\n };\n }),\n );\n } catch (err) {\n // if a field does not exist on a index, we can see that as a no-match\n if (\n err instanceof Error &&\n err.message.startsWith('unrecognised field')\n ) {\n return;\n }\n throw err;\n }\n });\n\n // Sort results.\n results.sort((doc1, doc2) => {\n return doc2.result.score - doc1.result.score;\n });\n\n // Perform paging\n const { page } = decodePageCursor(query.pageCursor);\n const offset = page * pageSize;\n const hasPreviousPage = page > 0;\n const hasNextPage = results.length > offset + pageSize;\n const nextPageCursor = hasNextPage\n ? encodePageCursor({ page: page + 1 })\n : undefined;\n const previousPageCursor = hasPreviousPage\n ? encodePageCursor({ page: page - 1 })\n : undefined;\n\n // Translate results into IndexableResultSet\n const realResultSet: IndexableResultSet = {\n results: results.slice(offset, offset + pageSize).map((d, index) => ({\n type: d.type,\n document: this.docStore[d.result.ref],\n rank: page * pageSize + index + 1,\n highlight: {\n preTag: this.highlightPreTag,\n postTag: this.highlightPostTag,\n fields: parseHighlightFields({\n preTag: this.highlightPreTag,\n postTag: this.highlightPostTag,\n doc: this.docStore[d.result.ref],\n positionMetadata: d.result.matchData.metadata as any,\n }),\n },\n })),\n numberOfResults: results.length,\n nextPageCursor,\n previousPageCursor,\n };\n\n return realResultSet;\n }\n}\n\nexport function decodePageCursor(pageCursor?: string): { page: number } {\n if (!pageCursor) {\n return { page: 0 };\n }\n\n return {\n page: Number(Buffer.from(pageCursor, 'base64').toString('utf-8')),\n };\n}\n\nexport function encodePageCursor({ page }: { page: number }): string {\n return Buffer.from(`${page}`, 'utf-8').toString('base64');\n}\n\ntype ParseHighlightFieldsProps = {\n preTag: string;\n postTag: string;\n doc: any;\n positionMetadata: {\n [term: string]: {\n [field: string]: {\n position: number[][];\n };\n };\n };\n};\n\nexport function parseHighlightFields({\n preTag,\n postTag,\n doc,\n positionMetadata,\n}: ParseHighlightFieldsProps): { [field: string]: string } {\n // Merge the field positions across all query terms\n const highlightFieldPositions = Object.values(positionMetadata).reduce(\n (fieldPositions, metadata) => {\n Object.keys(metadata).map(fieldKey => {\n const validFieldMetadataPositions = metadata[\n fieldKey\n ]?.position?.filter(position => Array.isArray(position));\n if (validFieldMetadataPositions.length) {\n fieldPositions[fieldKey] = fieldPositions[fieldKey] ?? [];\n fieldPositions[fieldKey].push(...validFieldMetadataPositions);\n }\n });\n\n return fieldPositions;\n },\n {} as { [field: string]: number[][] },\n );\n\n return Object.fromEntries(\n Object.entries(highlightFieldPositions).map(([field, positions]) => {\n positions.sort((a, b) => b[0] - a[0]);\n\n const highlightedField = positions.reduce((content, pos) => {\n return (\n `${String(content).substring(0, pos[0])}${preTag}` +\n `${String(content).substring(pos[0], pos[0] + pos[1])}` +\n `${postTag}${String(content).substring(pos[0] + pos[1])}`\n );\n }, doc[field] ?? '');\n\n return [field, highlightedField];\n }),\n );\n}\n","/*\n * Copyright 2022 The Backstage Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { IndexableDocument } from '@backstage/plugin-search-common';\nimport { pipeline, Readable, Transform, Writable } from 'stream';\n\n/**\n * Object resolved after a test pipeline is executed.\n * @public\n */\nexport type TestPipelineResult = {\n /**\n * If an error was emitted by the pipeline, it will be set here.\n */\n error: unknown;\n\n /**\n * A list of documents collected at the end of the pipeline. If the subject\n * under test is an indexer, this will be an empty array (because your\n * indexer should have received the documents instead).\n */\n documents: IndexableDocument[];\n};\n\n/**\n * Test utility for Backstage Search collators, decorators, and indexers.\n *\n * @example\n * An example test checking that a collator provides expected documents.\n * ```\n * it('provides expected documents', async () => {\n * const testSubject = await yourCollatorFactory.getCollator();\n * const pipeline = TestPipeline.fromCollator(testSubject);\n *\n * const { documents } = await pipeline.execute();\n *\n * expect(documents).toHaveLength(2);\n * })\n * ```\n *\n * @example\n * An example test checking that a decorator behaves as expected.\n * ```\n * it('filters private documents', async () => {\n * const testSubject = await yourDecoratorFactory.getDecorator();\n * const pipeline = TestPipeline\n * .fromDecorator(testSubject)\n * .withDocuments([{ title: 'Private', location: '/private', text: '' }]);\n *\n * const { documents } = await pipeline.execute();\n *\n * expect(documents).toHaveLength(0);\n * })\n * ```\n *\n * @public\n */\nexport class TestPipeline {\n private collator?: Readable;\n private decorator?: Transform;\n private indexer?: Writable;\n\n private constructor({\n collator,\n decorator,\n indexer,\n }: {\n collator?: Readable;\n decorator?: Transform;\n indexer?: Writable;\n }) {\n this.collator = collator;\n this.decorator = decorator;\n this.indexer = indexer;\n }\n\n /**\n * Provide the collator, decorator, or indexer to be tested.\n *\n * @deprecated Use `fromCollator`, `fromDecorator` or `fromIndexer` static\n * methods to create a test pipeline instead.\n */\n static withSubject(subject: Readable | Transform | Writable) {\n if (subject instanceof Transform) {\n return new TestPipeline({ decorator: subject });\n }\n\n if (subject instanceof Writable) {\n return new TestPipeline({ indexer: subject });\n }\n\n if (subject.readable || subject instanceof Readable) {\n return new TestPipeline({ collator: subject });\n }\n\n throw new Error(\n 'Unknown test subject: are you passing a readable, writable, or transform stream?',\n );\n }\n\n /**\n * Create a test pipeline given a collator you want to test.\n */\n static fromCollator(collator: Readable) {\n return new TestPipeline({ collator });\n }\n\n /**\n * Add a collator to the test pipeline.\n */\n withCollator(collator: Readable): this {\n this.collator = collator;\n return this;\n }\n\n /**\n * Create a test pipeline given a decorator you want to test.\n */\n static fromDecorator(decorator: Transform) {\n return new TestPipeline({ decorator });\n }\n\n /**\n * Add a decorator to the test pipeline.\n */\n withDecorator(decorator: Transform): this {\n this.decorator = decorator;\n return this;\n }\n\n /**\n * Create a test pipeline given an indexer you want to test.\n */\n static fromIndexer(indexer: Writable) {\n return new TestPipeline({ indexer });\n }\n\n /**\n * Add an indexer to the test pipeline.\n */\n withIndexer(indexer: Writable): this {\n this.indexer = indexer;\n return this;\n }\n\n /**\n * Provide documents for testing decorators and indexers.\n */\n withDocuments(documents: IndexableDocument[]): TestPipeline {\n if (this.collator) {\n throw new Error('Cannot provide documents when testing a collator.');\n }\n\n // Set a naive readable stream that just pushes all given documents.\n this.collator = new Readable({ objectMode: true });\n this.collator._read = () => {};\n process.nextTick(() => {\n documents.forEach(document => {\n this.collator!.push(document);\n });\n this.collator!.push(null);\n });\n\n return this;\n }\n\n /**\n * Execute the test pipeline so that you can make assertions about the result\n * or behavior of the given test subject.\n */\n async execute(): Promise<TestPipelineResult> {\n const documents: IndexableDocument[] = [];\n if (!this.collator) {\n throw new Error(\n 'Cannot execute pipeline without a collator or documents',\n );\n }\n\n // If we are here and there is no indexer, we are testing a collator or a\n // decorator. Set up a naive writable that captures documents in memory.\n if (!this.indexer) {\n this.indexer = new Writable({ objectMode: true });\n this.indexer._write = (document: IndexableDocument, _, done) => {\n documents.push(document);\n done();\n };\n }\n\n return new Promise<TestPipelineResult>(done => {\n const pipes: (Readable | Transform | Writable)[] = [this.collator!];\n if (this.decorator) {\n pipes.push(this.decorator);\n }\n pipes.push(this.indexer!);\n\n pipeline(pipes, (error: NodeJS.ErrnoException | null) => {\n done({\n error,\n documents,\n });\n });\n });\n }\n}\n"],"names":["pipeline","parseNdjson","isError","Writable","assertError","Transform","lunr","uuid","Readable"],"mappings":";;;;;;;;;;;;AAsCO,MAAM,SAAU,CAAA;AAAA,EACb,MAAA,CAAA;AAAA,EACA,QAAA,CAAA;AAAA,EACA,gBAAA,CAAA;AAAA,EACA,SAAA,CAAA;AAAA,EAER,YAAY,OAAoC,EAAA;AAC9C,IAAA,IAAA,CAAK,SAAS,OAAQ,CAAA,MAAA,CAAA;AACtB,IAAA,IAAA,CAAK,WAAW,EAAC,CAAA;AACjB,IAAA,IAAA,CAAK,mBAAmB,EAAC,CAAA;AACzB,IAAA,IAAA,CAAK,SAAY,GAAA,KAAA,CAAA;AAAA,GACnB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,cA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AAA,KAAA,EAAO,CAAC,KAAwC,KAAA;AACvD,QAAK,IAAA,CAAA;AAAA,UACH,KAAA;AAAA,UACA,SAAA;AAAA,SACD,CAAA,CAAA;AAAA,OACF,CAAA,CAAA;AAAA,KACF,CAAA,CAAA;AAAA,GACH;AACF;;;;;;;;;;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@backstage/plugin-search-backend-node",
3
- "version": "1.2.22",
3
+ "version": "1.2.24-next.0",
4
4
  "description": "A library for Backstage backend plugins that want to interact with the search backend plugin",
5
5
  "backstage": {
6
6
  "role": "node-library"
@@ -44,9 +44,9 @@
44
44
  "test": "backstage-cli package test"
45
45
  },
46
46
  "dependencies": {
47
- "@backstage/backend-common": "^0.22.0",
48
- "@backstage/backend-plugin-api": "^0.6.18",
49
- "@backstage/backend-tasks": "^0.5.23",
47
+ "@backstage/backend-common": "^0.22.1-next.0",
48
+ "@backstage/backend-plugin-api": "^0.6.19-next.0",
49
+ "@backstage/backend-tasks": "^0.5.24-next.0",
50
50
  "@backstage/config": "^1.2.0",
51
51
  "@backstage/errors": "^1.2.4",
52
52
  "@backstage/plugin-permission-common": "^0.7.13",
@@ -58,8 +58,9 @@
58
58
  "uuid": "^9.0.0"
59
59
  },
60
60
  "devDependencies": {
61
- "@backstage/backend-common": "^0.22.0",
62
- "@backstage/cli": "^0.26.5",
61
+ "@backstage/backend-common": "^0.22.1-next.0",
62
+ "@backstage/backend-test-utils": "^0.3.9-next.0",
63
+ "@backstage/cli": "^0.26.6-next.0",
63
64
  "@types/ndjson": "^2.0.1"
64
65
  }
65
66
  }