plugin-elastic-report 0.1.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/client-v2.d.ts +2 -2
  2. package/client-v2.js +1 -1
  3. package/client.d.ts +2 -2
  4. package/client.js +1 -1
  5. package/dist/ai/skills/elastic-report/SKILLS.md +52 -0
  6. package/dist/client/357.0dd385384cab5dbf.js +10 -0
  7. package/dist/client/index.js +1 -1
  8. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  9. package/dist/client-v2/857.a5bf9637d5fd4ef5.js +10 -0
  10. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  11. package/dist/client-v2/index.js +1 -1
  12. package/dist/externalVersion.js +5 -3
  13. package/dist/locale/en-US.json +213 -99
  14. package/dist/locale/vi-VN.json +213 -99
  15. package/dist/locale/zh-CN.json +213 -99
  16. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  17. package/dist/server/acl-guard.js +97 -25
  18. package/dist/server/collections/es-report-data-views.js +6 -0
  19. package/dist/server/collections/es-reports.js +6 -0
  20. package/dist/server/mcp/ElasticReportToolCatalog.js +238 -14
  21. package/dist/server/plugin.js +156 -22
  22. package/dist/server/report-block-tools.js +340 -0
  23. package/dist/server/services/ElasticReportService.js +137 -17
  24. package/dist/server/services/ElasticsearchConnectionService.js +274 -34
  25. package/dist/server/services/ReportExportService.js +243 -0
  26. package/dist/server/services/ReportQueryCompiler.js +532 -91
  27. package/dist/server/workflow/ElasticReportQueryInstruction.js +123 -0
  28. package/dist/shared/constants.js +26 -2
  29. package/package.json +3 -3
  30. package/server.d.ts +2 -2
  31. package/server.js +1 -1
  32. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  33. package/src/client/index.tsx +34 -19
  34. package/src/client/workflow-instructions.tsx +44 -0
  35. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -311
  36. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -0
  37. package/src/client-v2/api.ts +320 -224
  38. package/src/client-v2/bus/DashboardFilterBus.ts +212 -0
  39. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -399
  40. package/src/client-v2/components/ElasticFilterBar.tsx +372 -0
  41. package/src/client-v2/components/ElasticKqlInput.tsx +421 -0
  42. package/src/client-v2/components/ElasticReportBlock.tsx +306 -160
  43. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -707
  44. package/src/client-v2/components/HighlightText.tsx +50 -50
  45. package/src/client-v2/components/ReportSelect.tsx +85 -72
  46. package/src/client-v2/index.tsx +14 -14
  47. package/src/client-v2/locale.ts +23 -23
  48. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -0
  49. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -85
  50. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1047
  51. package/src/client-v2/plugin.tsx +107 -52
  52. package/src/client-v2/report-destination.tsx +126 -0
  53. package/src/client-v2/utils/kqlAutocomplete.ts +861 -0
  54. package/src/client-v2/workflow/instructions.tsx +149 -0
  55. package/src/index.ts +11 -11
  56. package/src/locale/en-US.json +213 -99
  57. package/src/locale/vi-VN.json +213 -99
  58. package/src/locale/zh-CN.json +213 -99
  59. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  60. package/src/server/__tests__/query-compiler.test.ts +620 -231
  61. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -377
  62. package/src/server/acl-guard.ts +194 -103
  63. package/src/server/collections/es-report-data-views.ts +64 -58
  64. package/src/server/collections/es-reports.ts +80 -74
  65. package/src/server/index.ts +15 -15
  66. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  67. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -417
  68. package/src/server/plugin.ts +599 -431
  69. package/src/server/report-block-tools.ts +400 -0
  70. package/src/server/services/ElasticReportService.ts +494 -326
  71. package/src/server/services/ElasticsearchConnectionService.ts +728 -401
  72. package/src/server/services/ReportExportService.ts +282 -0
  73. package/src/server/services/ReportQueryCompiler.ts +1552 -1017
  74. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -0
  75. package/src/shared/constants.ts +39 -29
  76. package/src/shared/types.ts +272 -175
  77. package/ai/skills/elastic-report/SKILLS.md +0 -32
  78. package/dist/client-v2/851.488fdbf5bc5b6a36.js +0 -10
  79. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  80. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,401 +1,728 @@
1
- /**
2
- * This file is part of the NocoBase (R) project.
3
- * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
- * Authors: NocoBase Team.
5
- *
6
- * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
- * For more information, please refer to: https://www.nocobase.com/agreement.
8
- */
9
-
10
- import { Client, type ClientOptions } from '@elastic/elasticsearch';
11
- import type { Application } from '@nocobase/server';
12
- import type { EsConnectionSummary, EsFieldCapability } from '../../shared/types';
13
-
14
- export interface EsReadOnlyClient {
15
- readIndices(indexPattern?: string): Promise<string[]>;
16
- inspectFields(indexPattern: string): Promise<EsFieldCapability[]>;
17
- search(indexPattern: string, body: Record<string, unknown>): Promise<unknown>;
18
- }
19
-
20
- interface RawEsClientLike {
21
- cat?: {
22
- indices: (params: { index: string; format: 'json'; h: 'index' }) => Promise<unknown>;
23
- };
24
- fieldCaps?: (params: { index: string; fields: string }) => Promise<unknown>;
25
- indices?: {
26
- getMapping: (params: { index: string }) => Promise<unknown>;
27
- };
28
- search: (params: { index: string; body?: Record<string, unknown>; [key: string]: unknown }) => Promise<unknown>;
29
- close?: () => Promise<void>;
30
- }
31
-
32
- interface DataSourceConnectionOptions {
33
- nodes?: string;
34
- username?: string;
35
- password?: string;
36
- apiKey?: string;
37
- indexPattern?: string;
38
- rejectUnauthorized?: boolean;
39
- }
40
-
41
- function isRecord(value: unknown): value is Record<string, unknown> {
42
- return typeof value === 'object' && value !== null && !Array.isArray(value);
43
- }
44
-
45
- function isRawEsClientLike(value: unknown): value is RawEsClientLike {
46
- return isRecord(value) && typeof value.search === 'function';
47
- }
48
-
49
- function normaliseApiKey(raw: string): string {
50
- const trimmed = raw.trim();
51
- if (trimmed.includes(':')) {
52
- return Buffer.from(trimmed).toString('base64');
53
- }
54
- return trimmed;
55
- }
56
-
57
- function extractConnectionOptions(raw: unknown): DataSourceConnectionOptions {
58
- if (!isRecord(raw)) return {};
59
- if (typeof raw.nodes === 'string') return raw as DataSourceConnectionOptions;
60
- if (isRecord(raw.options)) return raw.options as DataSourceConnectionOptions;
61
- return raw as DataSourceConnectionOptions;
62
- }
63
-
64
- function buildEsClientOptions(opts: DataSourceConnectionOptions): ClientOptions {
65
- const nodes = (opts.nodes || 'http://localhost:9200')
66
- .split(',')
67
- .map((item) => item.trim())
68
- .filter(Boolean);
69
- const clientOpts: ClientOptions = {
70
- nodes,
71
- requestTimeout: 20000,
72
- };
73
- if (opts.apiKey) {
74
- clientOpts.auth = { apiKey: normaliseApiKey(opts.apiKey) };
75
- } else if (opts.username) {
76
- clientOpts.auth = {
77
- username: opts.username,
78
- password: opts.password || '',
79
- };
80
- }
81
- if (opts.rejectUnauthorized === false) {
82
- clientOpts.tls = { rejectUnauthorized: false };
83
- }
84
- return clientOpts;
85
- }
86
-
87
- function assertSafeIndexPattern(indexPattern: string): string {
88
- const clean = indexPattern.trim();
89
- if (!clean) {
90
- throw new Error('Index pattern is required');
91
- }
92
- if (clean.includes('/') || clean.includes('..') || clean.includes('?') || clean.includes('#')) {
93
- throw new Error('Invalid index pattern');
94
- }
95
- const segments = clean
96
- .split(',')
97
- .map((s) => s.trim())
98
- .filter(Boolean);
99
- if (segments.length === 0) {
100
- throw new Error('Index pattern is required');
101
- }
102
- if (segments.some((seg) => seg.startsWith('.') && seg !== '.*')) {
103
- throw new Error('System dot-indices cannot be queried in reports');
104
- }
105
- return segments.join(',');
106
- }
107
-
108
- const AGGREGATABLE_ES_TYPES = new Set([
109
- 'keyword',
110
- 'constant_keyword',
111
- 'wildcard',
112
- 'long',
113
- 'integer',
114
- 'short',
115
- 'byte',
116
- 'double',
117
- 'float',
118
- 'half_float',
119
- 'scaled_float',
120
- 'unsigned_long',
121
- 'boolean',
122
- 'date',
123
- 'date_nanos',
124
- 'ip',
125
- ]);
126
-
127
- function flattenMappingProperties(
128
- properties: Record<string, unknown>,
129
- prefix = '',
130
- out: Map<string, EsFieldCapability> = new Map(),
131
- ): Map<string, EsFieldCapability> {
132
- for (const [name, rawDef] of Object.entries(properties)) {
133
- if (!isRecord(rawDef)) continue;
134
- const fullPath = prefix ? `${prefix}.${name}` : name;
135
- const esType = typeof rawDef.type === 'string' ? rawDef.type : undefined;
136
-
137
- if (esType) {
138
- const aggregatable = AGGREGATABLE_ES_TYPES.has(esType);
139
- out.set(fullPath, {
140
- name: fullPath,
141
- type: esType,
142
- searchable: esType !== 'binary',
143
- aggregatable,
144
- });
145
- }
146
-
147
- if (isRecord(rawDef.fields)) {
148
- for (const [subName, rawSub] of Object.entries(rawDef.fields)) {
149
- if (!isRecord(rawSub)) continue;
150
- const subType = typeof rawSub.type === 'string' ? rawSub.type : 'keyword';
151
- const subPath = `${fullPath}.${subName}`;
152
- out.set(subPath, {
153
- name: subPath,
154
- type: subType,
155
- searchable: true,
156
- aggregatable: AGGREGATABLE_ES_TYPES.has(subType),
157
- isSubfield: true,
158
- });
159
- }
160
- }
161
-
162
- if (isRecord(rawDef.properties)) {
163
- flattenMappingProperties(rawDef.properties, fullPath, out);
164
- }
165
- }
166
- return out;
167
- }
168
-
169
- export function normalizeFieldCapabilitiesResponse(rawFieldCaps: unknown): EsFieldCapability[] {
170
- const root = isRecord(rawFieldCaps) && isRecord(rawFieldCaps.fields) ? rawFieldCaps.fields : {};
171
- const map = new Map<string, EsFieldCapability>();
172
-
173
- for (const [fieldName, typeBuckets] of Object.entries(root)) {
174
- if (fieldName.startsWith('_') && fieldName !== '_id' && fieldName !== '_index') {
175
- continue;
176
- }
177
- if (!isRecord(typeBuckets)) continue;
178
-
179
- let chosenType = 'string';
180
- let searchable = false;
181
- let aggregatable = false;
182
-
183
- for (const [typeName, rawCap] of Object.entries(typeBuckets)) {
184
- if (!isRecord(rawCap)) continue;
185
- chosenType = typeName;
186
- if (rawCap.searchable === true) searchable = true;
187
- if (rawCap.aggregatable === true) aggregatable = true;
188
- }
189
-
190
- map.set(fieldName, {
191
- name: fieldName,
192
- type: chosenType,
193
- searchable,
194
- aggregatable,
195
- });
196
- }
197
-
198
- return linkKeywordSubfields(map);
199
- }
200
-
201
- function linkKeywordSubfields(map: Map<string, EsFieldCapability>): EsFieldCapability[] {
202
- for (const [name, cap] of map.entries()) {
203
- const keywordCandidate = `${name}.keyword`;
204
- const sub = map.get(keywordCandidate);
205
- if (sub && sub.aggregatable) {
206
- cap.keywordSubfield = keywordCandidate;
207
- sub.isSubfield = true;
208
- }
209
- }
210
-
211
- return Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
212
- }
213
-
214
- function wrapEsClient(rawClient: RawEsClientLike): EsReadOnlyClient {
215
- return {
216
- async readIndices(indexPattern = '*'): Promise<string[]> {
217
- const safePattern = indexPattern.trim() || '*';
218
- if (!rawClient.cat?.indices) {
219
- return [];
220
- }
221
- const response = await rawClient.cat.indices({
222
- index: safePattern,
223
- format: 'json',
224
- h: 'index',
225
- });
226
- const unwrapped = isRecord(response) && Array.isArray(response.body) ? response.body : response;
227
- if (!Array.isArray(unwrapped)) return [];
228
- return unwrapped
229
- .map((row) => (isRecord(row) && typeof row.index === 'string' ? row.index.trim() : ''))
230
- .filter((idx) => Boolean(idx) && !idx.startsWith('.'))
231
- .sort((a, b) => a.localeCompare(b));
232
- },
233
-
234
- async inspectFields(indexPattern: string): Promise<EsFieldCapability[]> {
235
- const safePattern = assertSafeIndexPattern(indexPattern);
236
- if (rawClient.fieldCaps) {
237
- const raw = await rawClient.fieldCaps({
238
- index: safePattern,
239
- fields: '*',
240
- });
241
- const unwrapped = isRecord(raw) && isRecord(raw.body) ? raw.body : raw;
242
- const parsed = normalizeFieldCapabilitiesResponse(unwrapped);
243
- if (parsed.length > 0) {
244
- return parsed;
245
- }
246
- }
247
-
248
- if (rawClient.indices?.getMapping) {
249
- const rawMapping = await rawClient.indices.getMapping({ index: safePattern });
250
- const unwrapped = isRecord(rawMapping) && isRecord(rawMapping.body) ? rawMapping.body : rawMapping;
251
- if (isRecord(unwrapped)) {
252
- const merged = new Map<string, EsFieldCapability>();
253
- for (const indexEntry of Object.values(unwrapped)) {
254
- if (!isRecord(indexEntry)) continue;
255
- const mappings = isRecord(indexEntry.mappings) ? indexEntry.mappings : undefined;
256
- const props = mappings && isRecord(mappings.properties) ? mappings.properties : undefined;
257
- if (props) {
258
- flattenMappingProperties(props, '', merged);
259
- }
260
- }
261
- return linkKeywordSubfields(merged);
262
- }
263
- }
264
-
265
- return [];
266
- },
267
-
268
- async search(indexPattern: string, body: Record<string, unknown>): Promise<unknown> {
269
- const safePattern = assertSafeIndexPattern(indexPattern);
270
- // Elasticsearch v8 client accepts top-level search params (`{ index, ...body }`).
271
- const response = await rawClient.search({
272
- index: safePattern,
273
- ...body,
274
- });
275
- return isRecord(response) && isRecord(response.body) ? response.body : response;
276
- },
277
- };
278
- }
279
-
280
- export class ElasticsearchConnectionService {
281
- private readonly fallbackClients = new Map<string, Client>();
282
-
283
- constructor(private readonly app: Application) {}
284
-
285
- async close(): Promise<void> {
286
- const clients = Array.from(this.fallbackClients.values());
287
- this.fallbackClients.clear();
288
- await Promise.allSettled(clients.map((client) => client.close()));
289
- }
290
-
291
- /**
292
- * Discover all Elasticsearch data sources configured via `plugin-data-source-elasticsearch`
293
- * without leaking sensitive credentials (`password`, `apiKey`).
294
- */
295
- async listConnections(): Promise<EsConnectionSummary[]> {
296
- const byKey = new Map<string, EsConnectionSummary>();
297
-
298
- const dsManager = this.app.dataSourceManager as unknown as {
299
- dataSources?: Map<string, unknown>;
300
- };
301
-
302
- if (dsManager?.dataSources instanceof Map) {
303
- for (const [key, ds] of dsManager.dataSources.entries()) {
304
- if (!isRecord(ds)) continue;
305
- const cm = isRecord(ds.collectionManager) ? ds.collectionManager : undefined;
306
- const pubOpts = typeof ds.publicOptions === 'function' ? ds.publicOptions() : undefined;
307
- const opts = extractConnectionOptions(pubOpts ?? ds.options);
308
- const isEs = isRawEsClientLike(cm?.esClient) || ds.constructor?.name === 'ElasticsearchDataSource';
309
- if (!isEs) continue;
310
-
311
- byKey.set(key, {
312
- key,
313
- displayName: typeof ds.displayName === 'string' && ds.displayName ? ds.displayName : key,
314
- status: 'loaded',
315
- ...(typeof opts.indexPattern === 'string' ? { indexPattern: opts.indexPattern } : {}),
316
- ...(typeof opts.nodes === 'string' ? { nodes: opts.nodes } : {}),
317
- });
318
- }
319
- }
320
-
321
- try {
322
- const repo = this.app.db.getRepository('dataSources');
323
- if (repo) {
324
- const rows = await repo.find({
325
- filter: { type: 'elasticsearch' },
326
- });
327
- for (const row of rows) {
328
- const plain = typeof row?.toJSON === 'function' ? row.toJSON() : row;
329
- if (!isRecord(plain) || typeof plain.key !== 'string' || !plain.key.trim()) continue;
330
- const key = plain.key.trim();
331
- const opts = extractConnectionOptions(plain.options);
332
- const existing = byKey.get(key);
333
- byKey.set(key, {
334
- key,
335
- displayName:
336
- typeof plain.displayName === 'string' && plain.displayName.trim()
337
- ? plain.displayName.trim()
338
- : existing?.displayName ?? key,
339
- status: typeof plain.status === 'string' ? plain.status : existing?.status ?? 'configured',
340
- ...(typeof opts.indexPattern === 'string'
341
- ? { indexPattern: opts.indexPattern }
342
- : existing?.indexPattern
343
- ? { indexPattern: existing.indexPattern }
344
- : {}),
345
- ...(typeof opts.nodes === 'string'
346
- ? { nodes: opts.nodes }
347
- : existing?.nodes
348
- ? { nodes: existing.nodes }
349
- : {}),
350
- });
351
- }
352
- }
353
- } catch {
354
- // `dataSources` table may not exist in lightweight unit test setups without plugin-data-source-manager.
355
- }
356
-
357
- return Array.from(byKey.values()).sort((a, b) => a.displayName.localeCompare(b.displayName));
358
- }
359
-
360
- async getClient(dataSourceKey: string): Promise<EsReadOnlyClient> {
361
- const cleanKey = dataSourceKey.trim();
362
- if (!cleanKey) {
363
- throw new Error('Elasticsearch dataSourceKey is required');
364
- }
365
-
366
- const liveDs = this.app.dataSourceManager?.get(cleanKey) as unknown;
367
- if (
368
- isRecord(liveDs) &&
369
- isRecord(liveDs.collectionManager) &&
370
- isRawEsClientLike(liveDs.collectionManager.esClient)
371
- ) {
372
- return wrapEsClient(liveDs.collectionManager.esClient);
373
- }
374
-
375
- const cached = this.fallbackClients.get(cleanKey);
376
- if (cached) {
377
- return wrapEsClient(cached as unknown as RawEsClientLike);
378
- }
379
-
380
- const repo = this.app.db.getRepository('dataSources');
381
- const record = repo
382
- ? await repo.findOne({
383
- filter: { key: cleanKey, type: 'elasticsearch' },
384
- })
385
- : null;
386
-
387
- if (!record) {
388
- throw new Error(`Elasticsearch data source "${cleanKey}" was not found or is not loaded`);
389
- }
390
-
391
- const plain = typeof record.toJSON === 'function' ? record.toJSON() : record;
392
- const opts = extractConnectionOptions(isRecord(plain) ? plain.options : undefined);
393
- if (!opts.nodes) {
394
- throw new Error(`Elasticsearch data source "${cleanKey}" has no configured nodes`);
395
- }
396
-
397
- const client = new Client(buildEsClientOptions(opts));
398
- this.fallbackClients.set(cleanKey, client);
399
- return wrapEsClient(client as unknown as RawEsClientLike);
400
- }
401
- }
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import { Client, type ClientOptions } from '@elastic/elasticsearch';
11
+ import type { Application } from '@nocobase/server';
12
+ import type { EsConnectionHealthResult, EsConnectionSummary, EsFieldCapability } from '../../shared/types';
13
+
14
+ export interface EsSearchCallOptions {
15
+ pitId?: string;
16
+ keepAlive?: string;
17
+ }
18
+
19
+ export interface EsReadOnlyClient {
20
+ testConnection(indexPattern?: string): Promise<EsConnectionHealthResult>;
21
+ readIndices(indexPattern?: string): Promise<string[]>;
22
+ inspectFields(indexPattern: string): Promise<EsFieldCapability[]>;
23
+ openPit(indexPattern: string, keepAlive?: string): Promise<string | null>;
24
+ closePit(pitId: string): Promise<void>;
25
+ search(indexPattern: string, body: Record<string, unknown>, options?: EsSearchCallOptions): Promise<unknown>;
26
+ }
27
+
28
+ interface RawEsClientLike {
29
+ info?: () => Promise<unknown>;
30
+ ping?: () => Promise<unknown>;
31
+ cluster?: {
32
+ health?: () => Promise<unknown>;
33
+ };
34
+ cat?: {
35
+ indices: (params: { index: string; format: 'json'; h: 'index' }) => Promise<unknown>;
36
+ };
37
+ fieldCaps?: (params: { index: string; fields: string }) => Promise<unknown>;
38
+ indices?: {
39
+ getMapping: (params: { index: string }) => Promise<unknown>;
40
+ resolveIndex?: (params: { name: string }) => Promise<unknown>;
41
+ };
42
+ openPointInTime?: (params: { index: string; keep_alive: string }) => Promise<unknown>;
43
+ closePointInTime?: (params: { id: string }) => Promise<unknown>;
44
+ search: (params: { index?: string; body?: Record<string, unknown>; [key: string]: unknown }) => Promise<unknown>;
45
+ close?: () => Promise<void>;
46
+ }
47
+
48
+ type EsEndpointMode = 'nodes' | 'cloud';
49
+ type EsAuthMode = 'none' | 'basic' | 'apiKey' | 'bearer';
50
+ type EsTlsMode = 'verify' | 'caFingerprint' | 'caCert' | 'skip';
51
+
52
+ export interface DataSourceConnectionOptions {
53
+ endpointMode?: EsEndpointMode;
54
+ nodes?: string;
55
+ cloudId?: string;
56
+ authMode?: EsAuthMode;
57
+ username?: string;
58
+ password?: string;
59
+ apiKey?: string;
60
+ bearerToken?: string;
61
+ tlsMode?: EsTlsMode;
62
+ caFingerprint?: string;
63
+ caCert?: string;
64
+ tlsServerName?: string;
65
+ rejectUnauthorized?: boolean;
66
+ requestTimeoutMs?: number;
67
+ maxRetries?: number;
68
+ compression?: boolean;
69
+ indexPattern?: string;
70
+ hasApiKey?: boolean;
71
+ hasBearerToken?: boolean;
72
+ hasCaCert?: boolean;
73
+ }
74
+
75
+ function isRecord(value: unknown): value is Record<string, unknown> {
76
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
77
+ }
78
+
79
+ function toNonEmptyString(value: unknown): string | undefined {
80
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
81
+ }
82
+
83
+ function isRawEsClientLike(value: unknown): value is RawEsClientLike {
84
+ return isRecord(value) && typeof value.search === 'function';
85
+ }
86
+
87
+ function normaliseApiKey(raw: string): string {
88
+ const trimmed = raw.trim();
89
+ if (trimmed.includes(':')) {
90
+ return Buffer.from(trimmed).toString('base64');
91
+ }
92
+ return trimmed;
93
+ }
94
+
95
+ function normalizeCaFingerprint(raw: string): string {
96
+ const cleaned = raw.replace(/[\s:]/g, '').toLowerCase();
97
+ if (!/^[0-9a-f]{64}$/.test(cleaned)) {
98
+ throw new Error('Invalid CA SHA-256 fingerprint: expected 64 hexadecimal characters');
99
+ }
100
+ return cleaned;
101
+ }
102
+
103
+ export function inferConnectionModes(opts: DataSourceConnectionOptions): {
104
+ endpointMode: EsEndpointMode;
105
+ authMode: EsAuthMode;
106
+ tlsMode: EsTlsMode;
107
+ } {
108
+ const endpointMode: EsEndpointMode =
109
+ opts.endpointMode === 'cloud' || opts.endpointMode === 'nodes'
110
+ ? opts.endpointMode
111
+ : toNonEmptyString(opts.cloudId)
112
+ ? 'cloud'
113
+ : 'nodes';
114
+
115
+ let authMode: EsAuthMode = 'none';
116
+ if (
117
+ opts.authMode === 'none' ||
118
+ opts.authMode === 'basic' ||
119
+ opts.authMode === 'apiKey' ||
120
+ opts.authMode === 'bearer'
121
+ ) {
122
+ authMode = opts.authMode;
123
+ } else if (opts.hasBearerToken === true || toNonEmptyString(opts.bearerToken)) {
124
+ authMode = 'bearer';
125
+ } else if (opts.hasApiKey === true || toNonEmptyString(opts.apiKey)) {
126
+ authMode = 'apiKey';
127
+ } else if (toNonEmptyString(opts.username)) {
128
+ authMode = 'basic';
129
+ }
130
+
131
+ let tlsMode: EsTlsMode = 'verify';
132
+ if (
133
+ opts.tlsMode === 'verify' ||
134
+ opts.tlsMode === 'caFingerprint' ||
135
+ opts.tlsMode === 'caCert' ||
136
+ opts.tlsMode === 'skip'
137
+ ) {
138
+ tlsMode = opts.tlsMode;
139
+ } else if (toNonEmptyString(opts.caFingerprint)) {
140
+ tlsMode = 'caFingerprint';
141
+ } else if (opts.hasCaCert === true || toNonEmptyString(opts.caCert)) {
142
+ tlsMode = 'caCert';
143
+ } else if (opts.rejectUnauthorized === false) {
144
+ tlsMode = 'skip';
145
+ }
146
+
147
+ return { endpointMode, authMode, tlsMode };
148
+ }
149
+
150
+ function extractConnectionOptions(raw: unknown): DataSourceConnectionOptions {
151
+ if (!isRecord(raw)) return {};
152
+ if (typeof raw.nodes === 'string' || typeof raw.cloudId === 'string' || typeof raw.endpointMode === 'string') {
153
+ return raw as DataSourceConnectionOptions;
154
+ }
155
+ if (isRecord(raw.options)) return raw.options as DataSourceConnectionOptions;
156
+ return raw as DataSourceConnectionOptions;
157
+ }
158
+
159
+ export function buildEsClientOptions(opts: DataSourceConnectionOptions): ClientOptions {
160
+ const { endpointMode, authMode, tlsMode } = inferConnectionModes(opts);
161
+ const timeoutMs =
162
+ typeof opts.requestTimeoutMs === 'number' && Number.isFinite(opts.requestTimeoutMs) && opts.requestTimeoutMs >= 1000
163
+ ? Math.min(300000, Math.trunc(opts.requestTimeoutMs))
164
+ : 30000;
165
+
166
+ const clientOpts: ClientOptions = {
167
+ requestTimeout: timeoutMs,
168
+ };
169
+
170
+ if (endpointMode === 'cloud') {
171
+ const cloudId = toNonEmptyString(opts.cloudId);
172
+ if (!cloudId) {
173
+ throw new Error('Elasticsearch data source has no configured Cloud ID');
174
+ }
175
+ clientOpts.cloud = { id: cloudId };
176
+ } else {
177
+ const nodes = (opts.nodes || 'http://localhost:9200')
178
+ .split(',')
179
+ .map((item) => item.trim())
180
+ .filter(Boolean);
181
+ clientOpts.nodes = nodes;
182
+ }
183
+
184
+ if (authMode === 'bearer') {
185
+ const bearer = toNonEmptyString(opts.bearerToken);
186
+ if (bearer) {
187
+ clientOpts.auth = { bearer };
188
+ }
189
+ } else if (authMode === 'apiKey') {
190
+ const apiKey = toNonEmptyString(opts.apiKey);
191
+ if (apiKey) {
192
+ clientOpts.auth = { apiKey: normaliseApiKey(apiKey) };
193
+ }
194
+ } else if (authMode === 'basic') {
195
+ const username = toNonEmptyString(opts.username);
196
+ if (username) {
197
+ clientOpts.auth = {
198
+ username,
199
+ password: opts.password || '',
200
+ };
201
+ }
202
+ }
203
+
204
+ const servername = toNonEmptyString(opts.tlsServerName);
205
+ if (tlsMode === 'caFingerprint') {
206
+ const fp = toNonEmptyString(opts.caFingerprint);
207
+ if (fp) {
208
+ clientOpts.caFingerprint = normalizeCaFingerprint(fp);
209
+ // Required by @elastic/elasticsearch UndiciConnection so self-signed ES 8.x CA chains reach isCaFingerprintMatch()
210
+ clientOpts.tls = {
211
+ rejectUnauthorized: false,
212
+ ...(servername ? { servername } : {}),
213
+ };
214
+ } else if (servername) {
215
+ clientOpts.tls = { servername };
216
+ }
217
+ } else if (tlsMode === 'caCert') {
218
+ const ca = toNonEmptyString(opts.caCert);
219
+ clientOpts.tls = {
220
+ ...(ca ? { ca } : {}),
221
+ rejectUnauthorized: true,
222
+ ...(servername ? { servername } : {}),
223
+ };
224
+ } else if (tlsMode === 'skip') {
225
+ clientOpts.tls = {
226
+ rejectUnauthorized: false,
227
+ ...(servername ? { servername } : {}),
228
+ };
229
+ } else if (servername) {
230
+ clientOpts.tls = {
231
+ rejectUnauthorized: true,
232
+ servername,
233
+ };
234
+ }
235
+
236
+ if (typeof opts.maxRetries === 'number' && Number.isFinite(opts.maxRetries) && opts.maxRetries >= 0) {
237
+ clientOpts.maxRetries = Math.min(10, Math.trunc(opts.maxRetries));
238
+ }
239
+ if (opts.compression === true) {
240
+ clientOpts.compression = true;
241
+ }
242
+
243
+ return clientOpts;
244
+ }
245
+
246
+ function assertSafeIndexPattern(indexPattern: string): string {
247
+ const clean = indexPattern.trim();
248
+ if (!clean) {
249
+ throw new Error('Index pattern is required');
250
+ }
251
+ if (clean.includes('/') || clean.includes('..') || clean.includes('?') || clean.includes('#')) {
252
+ throw new Error('Invalid index pattern');
253
+ }
254
+ const segments = clean
255
+ .split(',')
256
+ .map((s) => s.trim())
257
+ .filter(Boolean);
258
+ if (segments.length === 0) {
259
+ throw new Error('Index pattern is required');
260
+ }
261
+ if (segments.some((seg) => seg.startsWith('.') && seg !== '.*')) {
262
+ throw new Error('System dot-indices cannot be queried in reports');
263
+ }
264
+ return segments.join(',');
265
+ }
266
+
267
+ const AGGREGATABLE_ES_TYPES = new Set([
268
+ 'keyword',
269
+ 'constant_keyword',
270
+ 'wildcard',
271
+ 'long',
272
+ 'integer',
273
+ 'short',
274
+ 'byte',
275
+ 'double',
276
+ 'float',
277
+ 'half_float',
278
+ 'scaled_float',
279
+ 'unsigned_long',
280
+ 'boolean',
281
+ 'date',
282
+ 'date_nanos',
283
+ 'ip',
284
+ ]);
285
+
286
+ function flattenMappingProperties(
287
+ properties: Record<string, unknown>,
288
+ prefix = '',
289
+ out: Map<string, EsFieldCapability> = new Map(),
290
+ ): Map<string, EsFieldCapability> {
291
+ for (const [name, rawDef] of Object.entries(properties)) {
292
+ if (!isRecord(rawDef)) continue;
293
+ const fullPath = prefix ? `${prefix}.${name}` : name;
294
+ const esType = typeof rawDef.type === 'string' ? rawDef.type : undefined;
295
+
296
+ if (esType) {
297
+ const aggregatable = AGGREGATABLE_ES_TYPES.has(esType);
298
+ out.set(fullPath, {
299
+ name: fullPath,
300
+ type: esType,
301
+ searchable: esType !== 'binary',
302
+ aggregatable,
303
+ });
304
+ }
305
+
306
+ if (isRecord(rawDef.fields)) {
307
+ for (const [subName, rawSub] of Object.entries(rawDef.fields)) {
308
+ if (!isRecord(rawSub)) continue;
309
+ const subType = typeof rawSub.type === 'string' ? rawSub.type : 'keyword';
310
+ const subPath = `${fullPath}.${subName}`;
311
+ out.set(subPath, {
312
+ name: subPath,
313
+ type: subType,
314
+ searchable: true,
315
+ aggregatable: AGGREGATABLE_ES_TYPES.has(subType),
316
+ isSubfield: true,
317
+ });
318
+ }
319
+ }
320
+
321
+ if (isRecord(rawDef.properties)) {
322
+ flattenMappingProperties(rawDef.properties, fullPath, out);
323
+ }
324
+ }
325
+ return out;
326
+ }
327
+
328
+ export function normalizeFieldCapabilitiesResponse(rawFieldCaps: unknown): EsFieldCapability[] {
329
+ const root = isRecord(rawFieldCaps) && isRecord(rawFieldCaps.fields) ? rawFieldCaps.fields : {};
330
+ const map = new Map<string, EsFieldCapability>();
331
+
332
+ for (const [fieldName, typeBuckets] of Object.entries(root)) {
333
+ if (fieldName.startsWith('_') && fieldName !== '_id' && fieldName !== '_index') {
334
+ continue;
335
+ }
336
+ if (!isRecord(typeBuckets)) continue;
337
+
338
+ let chosenType = 'string';
339
+ let searchable = false;
340
+ let aggregatable = false;
341
+
342
+ for (const [typeName, rawCap] of Object.entries(typeBuckets)) {
343
+ if (!isRecord(rawCap)) continue;
344
+ chosenType = typeName;
345
+ if (rawCap.searchable === true) searchable = true;
346
+ if (rawCap.aggregatable === true) aggregatable = true;
347
+ }
348
+
349
+ map.set(fieldName, {
350
+ name: fieldName,
351
+ type: chosenType,
352
+ searchable,
353
+ aggregatable,
354
+ });
355
+ }
356
+
357
+ return linkKeywordSubfields(map);
358
+ }
359
+
360
+ function linkKeywordSubfields(map: Map<string, EsFieldCapability>): EsFieldCapability[] {
361
+ for (const [name, cap] of map.entries()) {
362
+ const keywordCandidate = `${name}.keyword`;
363
+ const sub = map.get(keywordCandidate);
364
+ if (sub && sub.aggregatable) {
365
+ cap.keywordSubfield = keywordCandidate;
366
+ sub.isSubfield = true;
367
+ }
368
+ }
369
+
370
+ return Array.from(map.values()).sort((a, b) => a.name.localeCompare(b.name));
371
+ }
372
+
373
+ function collectResolvedIndexNames(rawResolve: unknown, out: Set<string>): void {
374
+ const unwrapped = isRecord(rawResolve) && isRecord(rawResolve.body) ? rawResolve.body : rawResolve;
375
+ if (!isRecord(unwrapped)) return;
376
+
377
+ for (const bucketKey of ['indices', 'data_streams', 'aliases'] as const) {
378
+ const arr = unwrapped[bucketKey];
379
+ if (!Array.isArray(arr)) continue;
380
+ for (const entry of arr) {
381
+ if (!isRecord(entry) || entry.open === false) continue;
382
+ const name = toNonEmptyString(entry.name);
383
+ if (name && !name.startsWith('.')) {
384
+ out.add(name);
385
+ }
386
+ }
387
+ }
388
+ }
389
+
390
+ function wrapEsClient(rawClient: RawEsClientLike): EsReadOnlyClient {
391
+ return {
392
+ async testConnection(indexPattern = '*'): Promise<EsConnectionHealthResult> {
393
+ const safePattern = assertSafeIndexPattern(indexPattern || '*');
394
+
395
+ if (typeof rawClient.info === 'function') {
396
+ try {
397
+ const rawInfo = await rawClient.info();
398
+ const info = isRecord(rawInfo) && isRecord(rawInfo.body) ? rawInfo.body : rawInfo;
399
+ const clusterName = isRecord(info) ? toNonEmptyString(info.cluster_name) : undefined;
400
+ const versionObj = isRecord(info) && isRecord(info.version) ? info.version : undefined;
401
+ const version = versionObj ? toNonEmptyString(versionObj.number) : undefined;
402
+ if (clusterName || version) {
403
+ return {
404
+ ok: true,
405
+ ...(clusterName ? { clusterName } : {}),
406
+ ...(version ? { version } : {}),
407
+ };
408
+ }
409
+ } catch (err) {
410
+ const statusCode = isRecord(err) && typeof err.statusCode === 'number' ? err.statusCode : undefined;
411
+ if (statusCode === 403 && rawClient.fieldCaps) {
412
+ await rawClient.fieldCaps({ index: safePattern, fields: '@timestamp' });
413
+ return { ok: true, limitedPrivileges: true };
414
+ }
415
+ throw err;
416
+ }
417
+ }
418
+
419
+ if (typeof rawClient.cluster?.health === 'function') {
420
+ try {
421
+ const rawHealth = await rawClient.cluster.health();
422
+ const health = isRecord(rawHealth) && isRecord(rawHealth.body) ? rawHealth.body : rawHealth;
423
+ const clusterName = isRecord(health) ? toNonEmptyString(health.cluster_name) : undefined;
424
+ if (clusterName) {
425
+ return { ok: true, clusterName };
426
+ }
427
+ } catch (err) {
428
+ const statusCode = isRecord(err) && typeof err.statusCode === 'number' ? err.statusCode : undefined;
429
+ if (statusCode === 403 && rawClient.fieldCaps) {
430
+ await rawClient.fieldCaps({ index: safePattern, fields: '@timestamp' });
431
+ return { ok: true, limitedPrivileges: true };
432
+ }
433
+ throw err;
434
+ }
435
+ }
436
+
437
+ if (typeof rawClient.ping === 'function') {
438
+ const pong = await rawClient.ping();
439
+ if (pong) {
440
+ return { ok: true };
441
+ }
442
+ }
443
+
444
+ if (rawClient.fieldCaps) {
445
+ await rawClient.fieldCaps({ index: safePattern, fields: '@timestamp' });
446
+ return { ok: true };
447
+ }
448
+
449
+ return { ok: true };
450
+ },
451
+
452
+ async readIndices(indexPattern = '*'): Promise<string[]> {
453
+ const safePattern = assertSafeIndexPattern(indexPattern || '*');
454
+ const names = new Set<string>();
455
+
456
+ const resolvePromise =
457
+ typeof rawClient.indices?.resolveIndex === 'function'
458
+ ? rawClient.indices.resolveIndex({ name: safePattern })
459
+ : Promise.resolve(null);
460
+ const catPromise =
461
+ typeof rawClient.cat?.indices === 'function'
462
+ ? rawClient.cat.indices({ index: safePattern, format: 'json', h: 'index' })
463
+ : Promise.resolve(null);
464
+
465
+ const [resolveOutcome, catOutcome] = await Promise.allSettled([resolvePromise, catPromise]);
466
+
467
+ if (resolveOutcome.status === 'fulfilled' && resolveOutcome.value) {
468
+ collectResolvedIndexNames(resolveOutcome.value, names);
469
+ }
470
+
471
+ if (catOutcome.status === 'fulfilled' && catOutcome.value) {
472
+ const unwrapped =
473
+ isRecord(catOutcome.value) && Array.isArray(catOutcome.value.body) ? catOutcome.value.body : catOutcome.value;
474
+ if (Array.isArray(unwrapped)) {
475
+ for (const row of unwrapped) {
476
+ const idx = isRecord(row) ? toNonEmptyString(row.index) : undefined;
477
+ if (idx && !idx.startsWith('.')) {
478
+ names.add(idx);
479
+ }
480
+ }
481
+ }
482
+ }
483
+
484
+ if (
485
+ resolveOutcome.status === 'rejected' &&
486
+ (catOutcome.status === 'rejected' || typeof rawClient.cat?.indices !== 'function')
487
+ ) {
488
+ throw resolveOutcome.reason;
489
+ }
490
+ if (catOutcome.status === 'rejected' && typeof rawClient.indices?.resolveIndex !== 'function') {
491
+ throw catOutcome.reason;
492
+ }
493
+ if (resolveOutcome.status === 'rejected' && catOutcome.status === 'rejected') {
494
+ throw catOutcome.reason || resolveOutcome.reason;
495
+ }
496
+
497
+ return Array.from(names).sort((a, b) => a.localeCompare(b));
498
+ },
499
+
500
+ async inspectFields(indexPattern: string): Promise<EsFieldCapability[]> {
501
+ const safePattern = assertSafeIndexPattern(indexPattern);
502
+ if (rawClient.fieldCaps) {
503
+ const raw = await rawClient.fieldCaps({
504
+ index: safePattern,
505
+ fields: '*',
506
+ });
507
+ const unwrapped = isRecord(raw) && isRecord(raw.body) ? raw.body : raw;
508
+ const parsed = normalizeFieldCapabilitiesResponse(unwrapped);
509
+ if (parsed.length > 0) {
510
+ return parsed;
511
+ }
512
+ }
513
+
514
+ if (rawClient.indices?.getMapping) {
515
+ const rawMapping = await rawClient.indices.getMapping({ index: safePattern });
516
+ const unwrapped = isRecord(rawMapping) && isRecord(rawMapping.body) ? rawMapping.body : rawMapping;
517
+ if (isRecord(unwrapped)) {
518
+ const merged = new Map<string, EsFieldCapability>();
519
+ for (const indexEntry of Object.values(unwrapped)) {
520
+ if (!isRecord(indexEntry)) continue;
521
+ const mappings = isRecord(indexEntry.mappings) ? indexEntry.mappings : undefined;
522
+ const props = mappings && isRecord(mappings.properties) ? mappings.properties : undefined;
523
+ if (props) {
524
+ flattenMappingProperties(props, '', merged);
525
+ }
526
+ }
527
+ return linkKeywordSubfields(merged);
528
+ }
529
+ }
530
+
531
+ return [];
532
+ },
533
+
534
+ async openPit(indexPattern: string, keepAlive = '1m'): Promise<string | null> {
535
+ const safePattern = assertSafeIndexPattern(indexPattern);
536
+ if (typeof rawClient.openPointInTime !== 'function') {
537
+ return null;
538
+ }
539
+ try {
540
+ const raw = await rawClient.openPointInTime({
541
+ index: safePattern,
542
+ keep_alive: keepAlive,
543
+ });
544
+ const unwrapped = isRecord(raw) && isRecord(raw.body) ? raw.body : raw;
545
+ return isRecord(unwrapped) && typeof unwrapped.id === 'string' && unwrapped.id ? unwrapped.id : null;
546
+ } catch {
547
+ return null;
548
+ }
549
+ },
550
+
551
+ async closePit(pitId: string): Promise<void> {
552
+ if (!pitId || typeof rawClient.closePointInTime !== 'function') {
553
+ return;
554
+ }
555
+ try {
556
+ await rawClient.closePointInTime({ id: pitId });
557
+ } catch {
558
+ // Ignore already-expired PIT cleanup errors.
559
+ }
560
+ },
561
+
562
+ async search(indexPattern: string, body: Record<string, unknown>, options?: EsSearchCallOptions): Promise<unknown> {
563
+ if (options?.pitId) {
564
+ const response = await rawClient.search({
565
+ ...body,
566
+ pit: {
567
+ id: options.pitId,
568
+ keep_alive: options.keepAlive ?? '1m',
569
+ },
570
+ });
571
+ return isRecord(response) && isRecord(response.body) ? response.body : response;
572
+ }
573
+ const safePattern = assertSafeIndexPattern(indexPattern);
574
+ const response = await rawClient.search({
575
+ index: safePattern,
576
+ ...body,
577
+ });
578
+ return isRecord(response) && isRecord(response.body) ? response.body : response;
579
+ },
580
+ };
581
+ }
582
+
583
+ export class ElasticsearchConnectionService {
584
+ private readonly fallbackClients = new Map<string, { signature: string; client: Client }>();
585
+
586
+ constructor(private readonly app: Application) {}
587
+
588
+ async close(): Promise<void> {
589
+ const entries = Array.from(this.fallbackClients.values());
590
+ this.fallbackClients.clear();
591
+ await Promise.allSettled(entries.map((entry) => entry.client.close()));
592
+ }
593
+
594
+ /**
595
+ * Discover all Elasticsearch data sources configured via `plugin-data-source-elasticsearch`
596
+ * without leaking sensitive credentials (`password`, `apiKey`, `bearerToken`, `caCert`).
597
+ */
598
+ async listConnections(): Promise<EsConnectionSummary[]> {
599
+ const byKey = new Map<string, EsConnectionSummary>();
600
+
601
+ const dsManager = this.app.dataSourceManager as unknown as {
602
+ dataSources?: Map<string, unknown>;
603
+ };
604
+
605
+ if (dsManager?.dataSources instanceof Map) {
606
+ for (const [key, ds] of dsManager.dataSources.entries()) {
607
+ if (!isRecord(ds)) continue;
608
+ const cm = isRecord(ds.collectionManager) ? ds.collectionManager : undefined;
609
+ const pubOpts = typeof ds.publicOptions === 'function' ? ds.publicOptions() : undefined;
610
+ const opts = extractConnectionOptions(pubOpts ?? ds.options);
611
+ const isEs = isRawEsClientLike(cm?.esClient) || ds.constructor?.name === 'ElasticsearchDataSource';
612
+ if (!isEs) continue;
613
+
614
+ const modes = inferConnectionModes(opts);
615
+ byKey.set(key, {
616
+ key,
617
+ displayName: typeof ds.displayName === 'string' && ds.displayName ? ds.displayName : key,
618
+ status: 'loaded',
619
+ endpointMode: modes.endpointMode,
620
+ authMode: modes.authMode,
621
+ tlsMode: modes.tlsMode,
622
+ cloudConfigured: modes.endpointMode === 'cloud',
623
+ ...(typeof opts.indexPattern === 'string' ? { indexPattern: opts.indexPattern } : {}),
624
+ ...(typeof opts.nodes === 'string' ? { nodes: opts.nodes } : {}),
625
+ });
626
+ }
627
+ }
628
+
629
+ try {
630
+ const repo = this.app.db.getRepository('dataSources');
631
+ if (repo) {
632
+ const rows = await repo.find({
633
+ filter: { type: 'elasticsearch' },
634
+ });
635
+ for (const row of rows) {
636
+ const plain = typeof row?.toJSON === 'function' ? row.toJSON() : row;
637
+ if (!isRecord(plain) || typeof plain.key !== 'string' || !plain.key.trim()) continue;
638
+ const key = plain.key.trim();
639
+ const opts = extractConnectionOptions(plain.options);
640
+ const modes = inferConnectionModes(opts);
641
+ const existing = byKey.get(key);
642
+ byKey.set(key, {
643
+ key,
644
+ displayName:
645
+ typeof plain.displayName === 'string' && plain.displayName.trim()
646
+ ? plain.displayName.trim()
647
+ : existing?.displayName ?? key,
648
+ status: typeof plain.status === 'string' ? plain.status : existing?.status ?? 'configured',
649
+ endpointMode: modes.endpointMode,
650
+ authMode: modes.authMode,
651
+ tlsMode: modes.tlsMode,
652
+ cloudConfigured: modes.endpointMode === 'cloud',
653
+ ...(typeof opts.indexPattern === 'string'
654
+ ? { indexPattern: opts.indexPattern }
655
+ : existing?.indexPattern
656
+ ? { indexPattern: existing.indexPattern }
657
+ : {}),
658
+ ...(typeof opts.nodes === 'string'
659
+ ? { nodes: opts.nodes }
660
+ : existing?.nodes
661
+ ? { nodes: existing.nodes }
662
+ : {}),
663
+ });
664
+ }
665
+ }
666
+ } catch {
667
+ // `dataSources` table may not exist in lightweight unit test setups without plugin-data-source-manager.
668
+ }
669
+
670
+ return Array.from(byKey.values()).sort((a, b) => a.displayName.localeCompare(b.displayName));
671
+ }
672
+
673
+ async getClient(dataSourceKey: string): Promise<EsReadOnlyClient> {
674
+ const cleanKey = dataSourceKey.trim();
675
+ if (!cleanKey) {
676
+ throw new Error('Elasticsearch dataSourceKey is required');
677
+ }
678
+
679
+ const liveDs = this.app.dataSourceManager?.get(cleanKey) as unknown;
680
+ if (
681
+ isRecord(liveDs) &&
682
+ isRecord(liveDs.collectionManager) &&
683
+ isRawEsClientLike(liveDs.collectionManager.esClient)
684
+ ) {
685
+ return wrapEsClient(liveDs.collectionManager.esClient);
686
+ }
687
+
688
+ const repo = this.app.db.getRepository('dataSources');
689
+ const record = repo
690
+ ? await repo.findOne({
691
+ filter: { key: cleanKey, type: 'elasticsearch' },
692
+ })
693
+ : null;
694
+
695
+ if (!record) {
696
+ const existingCached = this.fallbackClients.get(cleanKey);
697
+ if (existingCached) {
698
+ return wrapEsClient(existingCached.client as unknown as RawEsClientLike);
699
+ }
700
+ throw new Error(`Elasticsearch data source "${cleanKey}" was not found or is not loaded`);
701
+ }
702
+
703
+ const plain = typeof record.toJSON === 'function' ? record.toJSON() : record;
704
+ const opts = extractConnectionOptions(isRecord(plain) ? plain.options : undefined);
705
+ const { endpointMode } = inferConnectionModes(opts);
706
+ if (endpointMode === 'cloud') {
707
+ if (!toNonEmptyString(opts.cloudId)) {
708
+ throw new Error(`Elasticsearch data source "${cleanKey}" has no configured Cloud ID`);
709
+ }
710
+ } else if (!toNonEmptyString(opts.nodes)) {
711
+ throw new Error(`Elasticsearch data source "${cleanKey}" has no configured nodes`);
712
+ }
713
+
714
+ const signature = JSON.stringify(opts);
715
+ const cached = this.fallbackClients.get(cleanKey);
716
+ if (cached && cached.signature === signature) {
717
+ return wrapEsClient(cached.client as unknown as RawEsClientLike);
718
+ }
719
+ if (cached) {
720
+ await cached.client.close().catch(() => undefined);
721
+ this.fallbackClients.delete(cleanKey);
722
+ }
723
+
724
+ const client = new Client(buildEsClientOptions(opts));
725
+ this.fallbackClients.set(cleanKey, { signature, client });
726
+ return wrapEsClient(client as unknown as RawEsClientLike);
727
+ }
728
+ }