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,431 +1,599 @@
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 { resolve } from 'path';
11
- import type { Context, Next } from '@nocobase/actions';
12
- import { Plugin, type InstallOptions } from '@nocobase/server';
13
- import {
14
- ACL_SNIPPET,
15
- DATA_VIEWS_COLLECTION,
16
- MCP_RELATIVE_PATH,
17
- MCP_RESOURCE_NAME,
18
- MCP_SERVER_NAME,
19
- REPORTS_COLLECTION,
20
- SERVICE_RESOURCE,
21
- } from '../shared/constants';
22
- import type { ID, ReportRuntimeOverrides } from '../shared/types';
23
- import { canManageReports } from './acl-guard';
24
- import { ElasticReportMcpServer } from './mcp/ElasticReportMcpServer';
25
- import { createElasticReportToolCatalog, type ElasticReportToolDefinition } from './mcp/ElasticReportToolCatalog';
26
- import { ElasticsearchConnectionService } from './services/ElasticsearchConnectionService';
27
- import { ElasticReportService, extractCurrentUserId } from './services/ElasticReportService';
28
-
29
- interface AIToolsManagerLike {
30
- registerTools: (
31
- tools: Array<{
32
- scope: 'CUSTOM' | 'GENERAL' | 'SPECIFIED';
33
- defaultPermission: 'ALLOW' | 'ASK';
34
- execution: 'backend' | 'frontend';
35
- introduction: { title: string; about: string };
36
- definition: { name: string; description: string; schema: Record<string, unknown> };
37
- invoke: (ctx: Context, args: Record<string, unknown>) => Promise<unknown>;
38
- }>,
39
- ) => void;
40
- }
41
-
42
- interface AIMcpManagerLike {
43
- registerMCP: (registration: Record<string, unknown>) => Promise<void>;
44
- }
45
-
46
- function isRecord(value: unknown): value is Record<string, unknown> {
47
- return typeof value === 'object' && value !== null && !Array.isArray(value);
48
- }
49
-
50
- function getActionPayload(ctx: Context): Record<string, unknown> {
51
- const query = isRecord(ctx.request?.query) ? ctx.request.query : {};
52
- const actionParams = isRecord(ctx.action?.params) ? ctx.action.params : {};
53
- const body = isRecord(ctx.request?.body) ? ctx.request.body : {};
54
- const paramValues = isRecord(actionParams.values) ? actionParams.values : {};
55
- return {
56
- ...query,
57
- ...actionParams,
58
- ...body,
59
- ...paramValues,
60
- };
61
- }
62
-
63
- function parseIdParam(value: unknown, label: string): ID {
64
- if (typeof value === 'number' && Number.isFinite(value)) return value;
65
- if (typeof value === 'string' && value.trim()) return value.trim();
66
- const err = new Error(`${label} is required`) as Error & { status?: number };
67
- err.status = 400;
68
- throw err;
69
- }
70
-
71
- export class PluginElasticReportServer extends Plugin {
72
- public connectionService!: ElasticsearchConnectionService;
73
- public reportService!: ElasticReportService;
74
- public mcpServer!: ElasticReportMcpServer;
75
- private toolsCatalog: ElasticReportToolDefinition[] = [];
76
- private readonly schemaCollections = [DATA_VIEWS_COLLECTION, REPORTS_COLLECTION];
77
-
78
- async beforeLoad() {
79
- await this.db.import({
80
- directory: resolve(__dirname, 'collections'),
81
- });
82
- this.connectionService = new ElasticsearchConnectionService(this.app);
83
- this.reportService = new ElasticReportService(this.app, this.connectionService);
84
- this.toolsCatalog = createElasticReportToolCatalog(this.app, this.reportService);
85
- this.mcpServer = new ElasticReportMcpServer({
86
- version: this.options?.version || '0.1.0',
87
- tools: this.toolsCatalog,
88
- logger: this.app.logger,
89
- });
90
- }
91
-
92
- async load() {
93
- this.registerServiceResource();
94
- this.registerMcpEndpoint();
95
- this.registerAclRules();
96
- this.registerAITools();
97
- await this.registerPluginMcpClientEntry();
98
-
99
- this.app.on('beforeStop', async () => {
100
- await this.connectionService?.close();
101
- });
102
- }
103
-
104
- async install(_options?: InstallOptions) {
105
- await this.ensureSchema();
106
- }
107
-
108
- async upgrade() {
109
- await this.ensureSchema();
110
- }
111
-
112
- private getApiBasePath(): string {
113
- const rawPrefix = this.app.resourcer?.options?.prefix ?? process.env.API_BASE_PATH ?? '/api';
114
- const cleaned = rawPrefix.replace(/\/+/g, '/').replace(/\/$/, '');
115
- return cleaned;
116
- }
117
-
118
- private getMcpEndpointPath(): string {
119
- return `${this.getApiBasePath()}${MCP_RELATIVE_PATH}`;
120
- }
121
-
122
- private resolveInternalMcpUrl(): string {
123
- const port = process.env.APP_PORT || '13000';
124
- const host = process.env.ELASTIC_REPORT_MCP_INTERNAL_HOST || `http://127.0.0.1:${port}`;
125
- return `${host.replace(/\/$/, '')}${this.getMcpEndpointPath()}`;
126
- }
127
-
128
- private registerServiceResource() {
129
- this.app.resourceManager.define({
130
- name: SERVICE_RESOURCE,
131
- actions: {
132
- listConnections: async (ctx: Context, next: Next) => {
133
- ctx.body = await this.reportService.listConnections();
134
- await next();
135
- },
136
-
137
- listIndices: async (ctx: Context, next: Next) => {
138
- const payload = getActionPayload(ctx);
139
- const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
140
- if (!dataSourceKey) {
141
- ctx.throw(400, 'dataSourceKey is required');
142
- }
143
- const indexPattern =
144
- typeof payload.indexPattern === 'string' && payload.indexPattern.trim() ? payload.indexPattern.trim() : '*';
145
- try {
146
- ctx.body = await this.reportService.listIndices(dataSourceKey, indexPattern);
147
- } catch (error) {
148
- ctx.throw(400, error instanceof Error ? error.message : String(error));
149
- }
150
- await next();
151
- },
152
-
153
- inspectFields: async (ctx: Context, next: Next) => {
154
- const payload = getActionPayload(ctx);
155
- try {
156
- if (payload.dataViewId !== undefined && payload.dataViewId !== null && String(payload.dataViewId).trim()) {
157
- const refresh = payload.refresh === true || payload.refresh === 'true';
158
- ctx.body = await this.reportService.inspectDataViewFields(
159
- parseIdParam(payload.dataViewId, 'dataViewId'),
160
- refresh,
161
- );
162
- } else {
163
- const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
164
- const indexPattern = typeof payload.indexPattern === 'string' ? payload.indexPattern.trim() : '';
165
- if (!dataSourceKey || !indexPattern) {
166
- ctx.throw(400, 'Either dataViewId or (dataSourceKey + indexPattern) is required');
167
- }
168
- const fields = await this.reportService.inspectFieldsBySource(dataSourceKey, indexPattern);
169
- ctx.body = { fields };
170
- }
171
- } catch (error) {
172
- const status = (error as { status?: number } | undefined)?.status ?? 400;
173
- ctx.throw(status, error instanceof Error ? error.message : String(error));
174
- }
175
- await next();
176
- },
177
-
178
- upsertDataView: async (ctx: Context, next: Next) => {
179
- const payload = getActionPayload(ctx);
180
- try {
181
- ctx.body = await this.reportService.upsertDataView(
182
- {
183
- ...(payload.id !== undefined && payload.id !== null && String(payload.id).trim() !== ''
184
- ? { id: parseIdParam(payload.id, 'id') }
185
- : {}),
186
- title: typeof payload.title === 'string' ? payload.title : '',
187
- dataSourceKey: typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey : '',
188
- indexPattern: typeof payload.indexPattern === 'string' ? payload.indexPattern : '',
189
- timeField: typeof payload.timeField === 'string' ? payload.timeField : null,
190
- description: typeof payload.description === 'string' ? payload.description : null,
191
- },
192
- extractCurrentUserId(ctx),
193
- );
194
- } catch (error) {
195
- ctx.throw(400, error instanceof Error ? error.message : String(error));
196
- }
197
- await next();
198
- },
199
-
200
- previewReport: async (ctx: Context, next: Next) => {
201
- const payload = getActionPayload(ctx);
202
- try {
203
- const dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
204
- ctx.body = await this.reportService.previewReport({
205
- dataViewId,
206
- spec: payload.spec,
207
- overrides: isRecord(payload.overrides) ? (payload.overrides as ReportRuntimeOverrides) : undefined,
208
- });
209
- } catch (error) {
210
- const status = (error as { status?: number } | undefined)?.status ?? 400;
211
- ctx.throw(status, error instanceof Error ? error.message : String(error));
212
- }
213
- await next();
214
- },
215
-
216
- saveReport: async (ctx: Context, next: Next) => {
217
- const payload = getActionPayload(ctx);
218
- try {
219
- ctx.body = await this.reportService.saveReport(
220
- {
221
- ...(payload.id !== undefined && payload.id !== null && String(payload.id).trim() !== ''
222
- ? { id: parseIdParam(payload.id, 'id') }
223
- : {}),
224
- title: typeof payload.title === 'string' ? payload.title : '',
225
- description: typeof payload.description === 'string' ? payload.description : null,
226
- dataViewId: parseIdParam(payload.dataViewId, 'dataViewId'),
227
- spec: payload.spec,
228
- published: payload.published !== false,
229
- },
230
- extractCurrentUserId(ctx),
231
- );
232
- } catch (error) {
233
- ctx.throw(400, error instanceof Error ? error.message : String(error));
234
- }
235
- await next();
236
- },
237
-
238
- listPublishedReports: async (ctx: Context, next: Next) => {
239
- const payload = getActionPayload(ctx);
240
- const search = typeof payload.search === 'string' ? payload.search : undefined;
241
- ctx.body = await this.reportService.listReports({
242
- publishedOnly: true,
243
- search,
244
- });
245
- await next();
246
- },
247
-
248
- getReportMeta: async (ctx: Context, next: Next) => {
249
- const payload = getActionPayload(ctx);
250
- const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
251
- try {
252
- const reportId = parseIdParam(rawId, 'reportId');
253
- const report = await this.reportService.getReport(reportId);
254
- const isManager = canManageReports(this.app, ctx);
255
- if (!isManager && !report.published) {
256
- ctx.throw(404, 'Report not found');
257
- }
258
- const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
259
- ctx.body = { report, dataView, fields };
260
- } catch (error) {
261
- const status = (error as { status?: number } | undefined)?.status ?? 400;
262
- ctx.throw(status, error instanceof Error ? error.message : String(error));
263
- }
264
- await next();
265
- },
266
-
267
- runReport: async (ctx: Context, next: Next) => {
268
- const payload = getActionPayload(ctx);
269
- const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
270
- try {
271
- const reportId = parseIdParam(rawId, 'reportId');
272
- const isManager = canManageReports(this.app, ctx);
273
- ctx.body = await this.reportService.runSavedReport({
274
- reportId,
275
- overrides: isRecord(payload.overrides) ? (payload.overrides as ReportRuntimeOverrides) : undefined,
276
- requirePublished: !isManager,
277
- });
278
- } catch (error) {
279
- const status = (error as { status?: number } | undefined)?.status ?? 400;
280
- ctx.throw(status, error instanceof Error ? error.message : String(error));
281
- }
282
- await next();
283
- },
284
-
285
- getMcpInfo: async (ctx: Context, next: Next) => {
286
- ctx.body = {
287
- serverName: MCP_SERVER_NAME,
288
- endpointPath: this.getMcpEndpointPath(),
289
- internalUrl: this.resolveInternalMcpUrl(),
290
- useUserContext: true,
291
- tools: this.mcpServer.getToolsMetadata(),
292
- };
293
- await next();
294
- },
295
- },
296
- });
297
- }
298
-
299
- private registerMcpEndpoint() {
300
- const mcpActionHandler = async (ctx: Context) => {
301
- await this.mcpServer.handleRequest(ctx);
302
- };
303
-
304
- this.app.resourceManager.define({
305
- name: MCP_RESOURCE_NAME,
306
- actions: {
307
- list: mcpActionHandler,
308
- create: mcpActionHandler,
309
- },
310
- only: ['list', 'create'],
311
- });
312
- }
313
-
314
- private registerAclRules() {
315
- // Viewers on pages can list published reports, inspect report metadata, and run published reports.
316
- this.app.acl.allow(SERVICE_RESOURCE, ['listPublishedReports', 'getReportMeta', 'runReport'], 'loggedIn');
317
- // Dedicated MCP endpoint requires authentication; tool-level ACL enforces read vs manage permissions.
318
- this.app.acl.allow(MCP_RESOURCE_NAME, '*', 'loggedIn');
319
-
320
- // Full studio & data-view management is grouped under the plugin settings snippet.
321
- this.app.acl.registerSnippet({
322
- name: ACL_SNIPPET,
323
- actions: [
324
- `${DATA_VIEWS_COLLECTION}:list`,
325
- `${DATA_VIEWS_COLLECTION}:get`,
326
- `${DATA_VIEWS_COLLECTION}:create`,
327
- `${DATA_VIEWS_COLLECTION}:update`,
328
- `${DATA_VIEWS_COLLECTION}:destroy`,
329
- `${REPORTS_COLLECTION}:list`,
330
- `${REPORTS_COLLECTION}:get`,
331
- `${REPORTS_COLLECTION}:create`,
332
- `${REPORTS_COLLECTION}:update`,
333
- `${REPORTS_COLLECTION}:destroy`,
334
- `${SERVICE_RESOURCE}:*`,
335
- ],
336
- });
337
- }
338
-
339
- private registerAITools() {
340
- const toolsManager = (this.app as unknown as { aiManager?: { toolsManager?: AIToolsManagerLike } }).aiManager
341
- ?.toolsManager;
342
- if (!toolsManager) {
343
- this.app.logger?.info?.(
344
- '[plugin-elastic-report] aiManager.toolsManager is not present; skipping direct AI tool registration',
345
- );
346
- return;
347
- }
348
-
349
- toolsManager.registerTools(
350
- this.toolsCatalog.map((tool) => ({
351
- scope: 'CUSTOM',
352
- defaultPermission: tool.defaultPermission,
353
- execution: 'backend',
354
- introduction: {
355
- title: tool.title,
356
- about: tool.description,
357
- },
358
- definition: {
359
- name: `${MCP_SERVER_NAME}-${tool.name}`,
360
- description: tool.description,
361
- schema: tool.inputSchema,
362
- },
363
- invoke: async (ctx: Context, args: Record<string, unknown>) => {
364
- return tool.execute(isRecord(args) ? args : {}, ctx);
365
- },
366
- })),
367
- );
368
- }
369
-
370
- private async registerPluginMcpClientEntry() {
371
- const mcpManager = (this.app as unknown as { aiManager?: { mcpManager?: AIMcpManagerLike } }).aiManager?.mcpManager;
372
- if (!mcpManager || typeof mcpManager.registerMCP !== 'function') {
373
- return;
374
- }
375
-
376
- try {
377
- await mcpManager.registerMCP({
378
- [MCP_SERVER_NAME]: {
379
- title: 'Elastic Report MCP',
380
- description: 'Dedicated MCP server for Kibana-style Elasticsearch reports and Data Views',
381
- transport: 'http',
382
- url: this.resolveInternalMcpUrl(),
383
- headers: {
384
- Authorization: 'Bearer {{ctx.request.token}}',
385
- 'X-Role': '{{ctx.request.headers.x-role}}',
386
- },
387
- useUserContext: true,
388
- enabled: true,
389
- },
390
- });
391
- } catch (error) {
392
- this.app.logger?.warn?.('[plugin-elastic-report] Could not pre-register MCP client entry:', error);
393
- }
394
- }
395
-
396
- private async ensureCollectionSchema(collectionName: string) {
397
- const collection = this.db.getCollection(collectionName);
398
- if (!collection) return;
399
-
400
- const queryInterface = this.db.sequelize.getQueryInterface();
401
- const tableName = collection.getTableNameWithSchema();
402
- let columns: Record<string, unknown> | null = null;
403
-
404
- try {
405
- columns = await queryInterface.describeTable(tableName);
406
- } catch {
407
- await collection.model.sync();
408
- columns = await queryInterface.describeTable(tableName);
409
- }
410
-
411
- const attributes = collection.model.rawAttributes as Record<string, Record<string, unknown> & { field?: string }>;
412
- for (const [attributeName, attribute] of Object.entries(attributes)) {
413
- const columnName = attribute.field || attributeName;
414
- if (columns && columnName in columns) {
415
- continue;
416
- }
417
- const columnDefinition = { ...attribute };
418
- delete columnDefinition.Model;
419
- delete columnDefinition.fieldName;
420
- await queryInterface.addColumn(tableName, columnName, columnDefinition);
421
- }
422
- }
423
-
424
- private async ensureSchema() {
425
- for (const collectionName of this.schemaCollections) {
426
- await this.ensureCollectionSchema(collectionName);
427
- }
428
- }
429
- }
430
-
431
- export default PluginElasticReportServer;
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 { resolve } from 'path';
11
+ import type { Context, Next } from '@nocobase/actions';
12
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
13
+ import { Plugin, type InstallOptions } from '@nocobase/server';
14
+ import {
15
+ ACL_SNIPPET,
16
+ DATA_VIEWS_COLLECTION,
17
+ MCP_RELATIVE_PATH,
18
+ MCP_RESOURCE_NAME,
19
+ MCP_SERVER_NAME,
20
+ REPORTS_COLLECTION,
21
+ SERVICE_RESOURCE,
22
+ WORKFLOW_INSTRUCTION_TYPE,
23
+ } from '../shared/constants';
24
+ import type { ExportFormat, ID, ReportRuntimeOverrides } from '../shared/types';
25
+ import {
26
+ assertCanAccessDataView,
27
+ assertCanAccessReport,
28
+ assertCanManageReports,
29
+ canAccessReport,
30
+ normalizeRoleList,
31
+ } from './acl-guard';
32
+ import { ElasticReportMcpServer } from './mcp/ElasticReportMcpServer';
33
+ import { createReportBlockTools } from './report-block-tools';
34
+ import { createElasticReportToolCatalog, type ElasticReportToolDefinition } from './mcp/ElasticReportToolCatalog';
35
+ import { ElasticsearchConnectionService } from './services/ElasticsearchConnectionService';
36
+ import { ElasticReportService, extractCurrentUserId, extractServerUserContext } from './services/ElasticReportService';
37
+ import { ReportExportService } from './services/ReportExportService';
38
+ import { ElasticReportQueryInstruction } from './workflow/ElasticReportQueryInstruction';
39
+
40
+ interface AIToolsManagerLike {
41
+ registerTools: (
42
+ tools: Array<{
43
+ scope: 'CUSTOM' | 'GENERAL' | 'SPECIFIED';
44
+ defaultPermission: 'ALLOW' | 'ASK';
45
+ execution: 'backend' | 'frontend';
46
+ introduction: { title: string; about: string };
47
+ definition: { name: string; description: string; schema: Record<string, unknown> };
48
+ invoke: (ctx: Context, args: Record<string, unknown>) => Promise<unknown>;
49
+ }>,
50
+ ) => void;
51
+ }
52
+
53
+ interface AIMcpManagerLike {
54
+ registerMCP: (registration: Record<string, unknown>) => Promise<void>;
55
+ }
56
+
57
+ function isRecord(value: unknown): value is Record<string, unknown> {
58
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
59
+ }
60
+
61
+ function getActionPayload(ctx: Context): Record<string, unknown> {
62
+ const query = isRecord(ctx.request?.query) ? ctx.request.query : {};
63
+ const actionParams = isRecord(ctx.action?.params) ? ctx.action.params : {};
64
+ const body = isRecord(ctx.request?.body) ? ctx.request.body : {};
65
+ const paramValues = isRecord(actionParams.values) ? actionParams.values : {};
66
+ return {
67
+ ...query,
68
+ ...actionParams,
69
+ ...body,
70
+ ...paramValues,
71
+ };
72
+ }
73
+
74
+ function parseIdParam(value: unknown, label: string): ID {
75
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
76
+ if (typeof value === 'string' && value.trim()) return value.trim();
77
+ const err = new Error(`${label} is required`) as Error & { status?: number };
78
+ err.status = 400;
79
+ throw err;
80
+ }
81
+
82
+ function parseOverridesParam(raw: unknown): ReportRuntimeOverrides | undefined {
83
+ if (isRecord(raw)) {
84
+ return raw as ReportRuntimeOverrides;
85
+ }
86
+ if (typeof raw === 'string' && raw.trim()) {
87
+ try {
88
+ const parsed = JSON.parse(raw);
89
+ return isRecord(parsed) ? (parsed as ReportRuntimeOverrides) : undefined;
90
+ } catch {
91
+ return undefined;
92
+ }
93
+ }
94
+ return undefined;
95
+ }
96
+
97
+ export class PluginElasticReportServer extends Plugin {
98
+ public connectionService!: ElasticsearchConnectionService;
99
+ public reportService!: ElasticReportService;
100
+ public exportService!: ReportExportService;
101
+ public mcpServer!: ElasticReportMcpServer;
102
+ private toolsCatalog: ElasticReportToolDefinition[] = [];
103
+ private readonly schemaCollections = [DATA_VIEWS_COLLECTION, REPORTS_COLLECTION];
104
+
105
+ async beforeLoad() {
106
+ await this.db.import({
107
+ directory: resolve(__dirname, 'collections'),
108
+ });
109
+ this.connectionService = new ElasticsearchConnectionService(this.app);
110
+ this.reportService = new ElasticReportService(this.app, this.connectionService);
111
+ this.exportService = new ReportExportService(this.connectionService, this.reportService);
112
+ this.toolsCatalog = createElasticReportToolCatalog(this.app, this.reportService);
113
+ this.mcpServer = new ElasticReportMcpServer({
114
+ version: this.options?.version || '0.8.0',
115
+ tools: this.toolsCatalog,
116
+ logger: this.app.logger,
117
+ });
118
+ }
119
+
120
+ async load() {
121
+ this.registerServiceResource();
122
+ this.registerMcpEndpoint();
123
+ this.registerAclRules();
124
+ this.registerWorkflowInstructions();
125
+ this.registerAITools();
126
+ await this.registerPluginMcpClientEntry();
127
+
128
+ this.app.on('beforeStop', async () => {
129
+ await this.connectionService?.close();
130
+ });
131
+ }
132
+
133
+ private registerWorkflowInstructions() {
134
+ const workflow = this.app.pm.get('workflow') as WorkflowPlugin | undefined;
135
+ if (!workflow || typeof workflow.registerInstruction !== 'function') {
136
+ return;
137
+ }
138
+ workflow.registerInstruction(
139
+ WORKFLOW_INSTRUCTION_TYPE,
140
+ new ElasticReportQueryInstruction(workflow, this.reportService),
141
+ );
142
+ }
143
+
144
+ async install(_options?: InstallOptions) {
145
+ await this.ensureSchema();
146
+ }
147
+
148
+ async upgrade() {
149
+ await this.ensureSchema();
150
+ }
151
+
152
+ private getApiBasePath(): string {
153
+ const rawPrefix = this.app.resourcer?.options?.prefix ?? process.env.API_BASE_PATH ?? '/api';
154
+ const cleaned = rawPrefix.replace(/\/+/g, '/').replace(/\/$/, '');
155
+ return cleaned;
156
+ }
157
+
158
+ private getMcpEndpointPath(): string {
159
+ return `${this.getApiBasePath()}${MCP_RELATIVE_PATH}`;
160
+ }
161
+
162
+ private resolveInternalMcpUrl(): string {
163
+ const port = process.env.APP_PORT || '13000';
164
+ const host = process.env.ELASTIC_REPORT_MCP_INTERNAL_HOST || `http://127.0.0.1:${port}`;
165
+ return `${host.replace(/\/$/, '')}${this.getMcpEndpointPath()}`;
166
+ }
167
+
168
+ private registerServiceResource() {
169
+ this.app.resourceManager.define({
170
+ name: SERVICE_RESOURCE,
171
+ actions: {
172
+ listConnections: async (ctx: Context, next: Next) => {
173
+ assertCanManageReports(this.app, ctx);
174
+ ctx.body = await this.reportService.listConnections();
175
+ await next();
176
+ },
177
+
178
+ testConnection: async (ctx: Context, next: Next) => {
179
+ assertCanManageReports(this.app, ctx);
180
+ const payload = getActionPayload(ctx);
181
+ const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
182
+ if (!dataSourceKey) {
183
+ ctx.throw(400, 'dataSourceKey is required');
184
+ }
185
+ const indexPattern =
186
+ typeof payload.indexPattern === 'string' && payload.indexPattern.trim() ? payload.indexPattern.trim() : '*';
187
+ try {
188
+ ctx.body = await this.reportService.testConnection(dataSourceKey, indexPattern);
189
+ } catch (error) {
190
+ ctx.throw(400, error instanceof Error ? error.message : String(error));
191
+ }
192
+ await next();
193
+ },
194
+
195
+ listRoles: async (ctx: Context, next: Next) => {
196
+ assertCanManageReports(this.app, ctx);
197
+ ctx.body = await this.reportService.listAvailableRoles();
198
+ await next();
199
+ },
200
+
201
+ listIndices: async (ctx: Context, next: Next) => {
202
+ assertCanManageReports(this.app, ctx);
203
+ const payload = getActionPayload(ctx);
204
+ const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
205
+ if (!dataSourceKey) {
206
+ ctx.throw(400, 'dataSourceKey is required');
207
+ }
208
+ const indexPattern =
209
+ typeof payload.indexPattern === 'string' && payload.indexPattern.trim() ? payload.indexPattern.trim() : '*';
210
+ try {
211
+ ctx.body = await this.reportService.listIndices(dataSourceKey, indexPattern);
212
+ } catch (error) {
213
+ ctx.throw(400, error instanceof Error ? error.message : String(error));
214
+ }
215
+ await next();
216
+ },
217
+
218
+ inspectFields: async (ctx: Context, next: Next) => {
219
+ const payload = getActionPayload(ctx);
220
+ try {
221
+ if (payload.dataViewId !== undefined && payload.dataViewId !== null && String(payload.dataViewId).trim()) {
222
+ const dvId = parseIdParam(payload.dataViewId, 'dataViewId');
223
+ const refresh = payload.refresh === true || payload.refresh === 'true';
224
+ if (refresh) {
225
+ assertCanManageReports(this.app, ctx);
226
+ } else {
227
+ const dv = await this.reportService.getDataView(dvId);
228
+ assertCanAccessDataView(this.app, ctx, dv);
229
+ }
230
+ ctx.body = await this.reportService.inspectDataViewFields(dvId, refresh);
231
+ } else {
232
+ assertCanManageReports(this.app, ctx);
233
+ const dataSourceKey = typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey.trim() : '';
234
+ const indexPattern = typeof payload.indexPattern === 'string' ? payload.indexPattern.trim() : '';
235
+ if (!dataSourceKey || !indexPattern) {
236
+ ctx.throw(400, 'Either dataViewId or (dataSourceKey + indexPattern) is required');
237
+ }
238
+ const fields = await this.reportService.inspectFieldsBySource(dataSourceKey, indexPattern);
239
+ ctx.body = { fields };
240
+ }
241
+ } catch (error) {
242
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
243
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
244
+ }
245
+ await next();
246
+ },
247
+
248
+ upsertDataView: async (ctx: Context, next: Next) => {
249
+ assertCanManageReports(this.app, ctx);
250
+ const payload = getActionPayload(ctx);
251
+ try {
252
+ ctx.body = await this.reportService.upsertDataView(
253
+ {
254
+ ...(payload.id !== undefined && payload.id !== null && String(payload.id).trim() !== ''
255
+ ? { id: parseIdParam(payload.id, 'id') }
256
+ : {}),
257
+ title: typeof payload.title === 'string' ? payload.title : '',
258
+ dataSourceKey: typeof payload.dataSourceKey === 'string' ? payload.dataSourceKey : '',
259
+ indexPattern: typeof payload.indexPattern === 'string' ? payload.indexPattern : '',
260
+ timeField: typeof payload.timeField === 'string' ? payload.timeField : null,
261
+ description: typeof payload.description === 'string' ? payload.description : null,
262
+ ...(payload.allowedRoles !== undefined
263
+ ? { allowedRoles: normalizeRoleList(payload.allowedRoles) }
264
+ : {}),
265
+ },
266
+ extractCurrentUserId(ctx),
267
+ );
268
+ } catch (error) {
269
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
270
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
271
+ }
272
+ await next();
273
+ },
274
+
275
+ previewReport: async (ctx: Context, next: Next) => {
276
+ assertCanManageReports(this.app, ctx);
277
+ const payload = getActionPayload(ctx);
278
+ try {
279
+ const dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
280
+ ctx.body = await this.reportService.previewReport({
281
+ dataViewId,
282
+ spec: payload.spec,
283
+ overrides: parseOverridesParam(payload.overrides),
284
+ userContext: extractServerUserContext(ctx),
285
+ });
286
+ } catch (error) {
287
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
288
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
289
+ }
290
+ await next();
291
+ },
292
+
293
+ saveReport: async (ctx: Context, next: Next) => {
294
+ assertCanManageReports(this.app, ctx);
295
+ const payload = getActionPayload(ctx);
296
+ try {
297
+ ctx.body = await this.reportService.saveReport(
298
+ {
299
+ ...(payload.id !== undefined && payload.id !== null && String(payload.id).trim() !== ''
300
+ ? { id: parseIdParam(payload.id, 'id') }
301
+ : {}),
302
+ title: typeof payload.title === 'string' ? payload.title : '',
303
+ description: typeof payload.description === 'string' ? payload.description : null,
304
+ dataViewId: parseIdParam(payload.dataViewId, 'dataViewId'),
305
+ spec: payload.spec,
306
+ published: payload.published !== false,
307
+ ...(payload.allowedRoles !== undefined
308
+ ? { allowedRoles: normalizeRoleList(payload.allowedRoles) }
309
+ : {}),
310
+ },
311
+ extractCurrentUserId(ctx),
312
+ );
313
+ } catch (error) {
314
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
315
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
316
+ }
317
+ await next();
318
+ },
319
+
320
+ listPublishedReports: async (ctx: Context, next: Next) => {
321
+ const payload = getActionPayload(ctx);
322
+ const search = typeof payload.search === 'string' ? payload.search : undefined;
323
+ const publishedReports = await this.reportService.listReports({
324
+ publishedOnly: true,
325
+ search,
326
+ });
327
+ ctx.body = publishedReports.filter((report) => canAccessReport(this.app, ctx, report, report.dataView));
328
+ await next();
329
+ },
330
+
331
+ getReportMeta: async (ctx: Context, next: Next) => {
332
+ const payload = getActionPayload(ctx);
333
+ const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
334
+ try {
335
+ const reportId = parseIdParam(rawId, 'reportId');
336
+ const report = await this.reportService.getReport(reportId);
337
+ const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
338
+ assertCanAccessReport(this.app, ctx, report, dataView);
339
+ ctx.body = { report, dataView, fields };
340
+ } catch (error) {
341
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
342
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
343
+ }
344
+ await next();
345
+ },
346
+
347
+ runReport: async (ctx: Context, next: Next) => {
348
+ const payload = getActionPayload(ctx);
349
+ const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
350
+ try {
351
+ const reportId = parseIdParam(rawId, 'reportId');
352
+ const report = await this.reportService.getReport(reportId);
353
+ const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
354
+ assertCanAccessReport(this.app, ctx, report, dataView);
355
+ ctx.body = await this.reportService.runSavedReport({
356
+ reportId,
357
+ overrides: parseOverridesParam(payload.overrides),
358
+ requirePublished: false,
359
+ userContext: extractServerUserContext(ctx),
360
+ });
361
+ } catch (error) {
362
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
363
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
364
+ }
365
+ await next();
366
+ },
367
+
368
+ inspectTopValues: async (ctx: Context, next: Next) => {
369
+ const payload = getActionPayload(ctx);
370
+ try {
371
+ const field = typeof payload.field === 'string' ? payload.field.trim() : '';
372
+ if (!field) {
373
+ ctx.throw(400, 'field is required');
374
+ }
375
+ let dataViewId: ID;
376
+ let reportId: ID | undefined;
377
+ if (payload.reportId !== undefined && payload.reportId !== null && String(payload.reportId).trim() !== '') {
378
+ reportId = parseIdParam(payload.reportId, 'reportId');
379
+ const report = await this.reportService.getReport(reportId);
380
+ const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
381
+ assertCanAccessReport(this.app, ctx, report, dataView);
382
+ dataViewId = report.dataViewId;
383
+ } else {
384
+ dataViewId = parseIdParam(payload.dataViewId, 'dataViewId');
385
+ const dataView = await this.reportService.getDataView(dataViewId);
386
+ assertCanAccessDataView(this.app, ctx, dataView);
387
+ }
388
+
389
+ ctx.body = await this.reportService.inspectFieldTopValues({
390
+ dataViewId,
391
+ ...(reportId !== undefined ? { reportId } : {}),
392
+ field,
393
+ size: typeof payload.size === 'number' ? payload.size : Number(payload.size) || 10,
394
+ overrides: parseOverridesParam(payload.overrides),
395
+ userContext: extractServerUserContext(ctx),
396
+ });
397
+ } catch (error) {
398
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
399
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
400
+ }
401
+ await next();
402
+ },
403
+
404
+ exportReport: async (ctx: Context, next: Next) => {
405
+ const payload = getActionPayload(ctx);
406
+ const rawId = payload.reportId ?? ctx.action?.params?.filterByTk;
407
+ try {
408
+ const reportId = parseIdParam(rawId, 'reportId');
409
+ const report = await this.reportService.getReport(reportId);
410
+ const dataView = report.dataView ?? (await this.reportService.getDataView(report.dataViewId));
411
+ assertCanAccessReport(this.app, ctx, report, dataView);
412
+
413
+ const format: ExportFormat = payload.format === 'ndjson' ? 'ndjson' : 'csv';
414
+ const columns = Array.isArray(payload.columns)
415
+ ? payload.columns.filter((c): c is string => typeof c === 'string' && Boolean(c.trim()))
416
+ : typeof payload.columns === 'string' && payload.columns.trim()
417
+ ? payload.columns
418
+ .split(',')
419
+ .map((c) => c.trim())
420
+ .filter(Boolean)
421
+ : undefined;
422
+ const maxRows =
423
+ typeof payload.maxRows === 'number'
424
+ ? payload.maxRows
425
+ : payload.maxRows !== undefined
426
+ ? Number(payload.maxRows)
427
+ : undefined;
428
+
429
+ const { stream, filename, contentType } = await this.exportService.createExportStream({
430
+ reportId,
431
+ format,
432
+ overrides: parseOverridesParam(payload.overrides),
433
+ ...(columns ? { columns } : {}),
434
+ ...(maxRows !== undefined && Number.isFinite(maxRows) ? { maxRows } : {}),
435
+ userContext: extractServerUserContext(ctx),
436
+ });
437
+
438
+ ctx.withoutDataWrapping = true;
439
+ ctx.status = 200;
440
+ ctx.type = contentType;
441
+ ctx.set('Content-Disposition', `attachment; filename="${filename}"`);
442
+ ctx.body = stream;
443
+ } catch (error) {
444
+ const status = (error as { status?: number } | undefined)?.status ?? 400;
445
+ ctx.throw(status, error instanceof Error ? error.message : String(error));
446
+ }
447
+ await next();
448
+ },
449
+
450
+ getMcpInfo: async (ctx: Context, next: Next) => {
451
+ ctx.body = {
452
+ serverName: MCP_SERVER_NAME,
453
+ endpointPath: this.getMcpEndpointPath(),
454
+ internalUrl: this.resolveInternalMcpUrl(),
455
+ useUserContext: true,
456
+ tools: this.mcpServer.getToolsMetadata(),
457
+ };
458
+ await next();
459
+ },
460
+ },
461
+ });
462
+ }
463
+
464
+ private registerMcpEndpoint() {
465
+ const mcpActionHandler = async (ctx: Context) => {
466
+ await this.mcpServer.handleRequest(ctx);
467
+ };
468
+
469
+ this.app.resourceManager.define({
470
+ name: MCP_RESOURCE_NAME,
471
+ actions: {
472
+ list: mcpActionHandler,
473
+ create: mcpActionHandler,
474
+ },
475
+ only: ['list', 'create'],
476
+ });
477
+ }
478
+
479
+ private registerAclRules() {
480
+ // Viewers on pages can list published reports, inspect report metadata/top-values, run, and export published reports.
481
+ this.app.acl.allow(
482
+ SERVICE_RESOURCE,
483
+ ['listPublishedReports', 'getReportMeta', 'runReport', 'inspectTopValues', 'exportReport'],
484
+ 'loggedIn',
485
+ );
486
+ // Dedicated MCP endpoint requires authentication; tool-level ACL enforces read vs manage permissions.
487
+ this.app.acl.allow(MCP_RESOURCE_NAME, '*', 'loggedIn');
488
+
489
+ // Full studio & data-view management is grouped under the plugin settings snippet.
490
+ this.app.acl.registerSnippet({
491
+ name: ACL_SNIPPET,
492
+ actions: [
493
+ `${DATA_VIEWS_COLLECTION}:list`,
494
+ `${DATA_VIEWS_COLLECTION}:get`,
495
+ `${DATA_VIEWS_COLLECTION}:create`,
496
+ `${DATA_VIEWS_COLLECTION}:update`,
497
+ `${DATA_VIEWS_COLLECTION}:destroy`,
498
+ `${REPORTS_COLLECTION}:list`,
499
+ `${REPORTS_COLLECTION}:get`,
500
+ `${REPORTS_COLLECTION}:create`,
501
+ `${REPORTS_COLLECTION}:update`,
502
+ `${REPORTS_COLLECTION}:destroy`,
503
+ `${SERVICE_RESOURCE}:*`,
504
+ ],
505
+ });
506
+ }
507
+
508
+ private registerAITools() {
509
+ const toolsManager = (this.app as unknown as { aiManager?: { toolsManager?: AIToolsManagerLike } }).aiManager
510
+ ?.toolsManager;
511
+ if (!toolsManager) {
512
+ this.app.logger?.info?.(
513
+ '[plugin-elastic-report] aiManager.toolsManager is not present; skipping direct AI tool registration',
514
+ );
515
+ return;
516
+ }
517
+
518
+ toolsManager.registerTools(
519
+ [...this.toolsCatalog, ...createReportBlockTools(this.app, this.reportService)].map((tool) => ({
520
+ scope: 'CUSTOM',
521
+ defaultPermission: tool.defaultPermission,
522
+ execution: 'backend',
523
+ introduction: {
524
+ title: tool.title,
525
+ about: tool.description,
526
+ },
527
+ definition: {
528
+ name: `${MCP_SERVER_NAME}-${tool.name}`,
529
+ description: tool.description,
530
+ schema: tool.inputSchema,
531
+ },
532
+ invoke: async (ctx: Context, args: Record<string, unknown>) => {
533
+ return tool.execute(isRecord(args) ? args : {}, ctx);
534
+ },
535
+ })),
536
+ );
537
+ }
538
+
539
+ private async registerPluginMcpClientEntry() {
540
+ const mcpManager = (this.app as unknown as { aiManager?: { mcpManager?: AIMcpManagerLike } }).aiManager?.mcpManager;
541
+ if (!mcpManager || typeof mcpManager.registerMCP !== 'function') {
542
+ return;
543
+ }
544
+
545
+ try {
546
+ await mcpManager.registerMCP({
547
+ [MCP_SERVER_NAME]: {
548
+ title: 'Elastic Report MCP',
549
+ description: 'Dedicated MCP server for Kibana-style Elasticsearch reports and Data Views',
550
+ transport: 'http',
551
+ url: this.resolveInternalMcpUrl(),
552
+ headers: {
553
+ Authorization: 'Bearer {{ctx.request.token}}',
554
+ 'X-Role': '{{ctx.request.headers.x-role}}',
555
+ },
556
+ useUserContext: true,
557
+ enabled: true,
558
+ },
559
+ });
560
+ } catch (error) {
561
+ this.app.logger?.warn?.('[plugin-elastic-report] Could not pre-register MCP client entry:', error);
562
+ }
563
+ }
564
+
565
+ private async ensureCollectionSchema(collectionName: string) {
566
+ const collection = this.db.getCollection(collectionName);
567
+ if (!collection) return;
568
+
569
+ const queryInterface = this.db.sequelize.getQueryInterface();
570
+ const tableName = collection.getTableNameWithSchema();
571
+ let columns: Record<string, unknown> | null = null;
572
+
573
+ try {
574
+ columns = await queryInterface.describeTable(tableName);
575
+ } catch {
576
+ await collection.model.sync();
577
+ columns = await queryInterface.describeTable(tableName);
578
+ }
579
+
580
+ for (const [attributeName, attribute] of Object.entries(collection.model.rawAttributes)) {
581
+ const columnName = attribute.field || attributeName;
582
+ if (columns && columnName in columns) {
583
+ continue;
584
+ }
585
+ const columnDefinition: typeof attribute & { Model?: unknown; fieldName?: string } = { ...attribute };
586
+ delete columnDefinition.Model;
587
+ delete columnDefinition.fieldName;
588
+ await queryInterface.addColumn(tableName, columnName, columnDefinition);
589
+ }
590
+ }
591
+
592
+ private async ensureSchema() {
593
+ for (const collectionName of this.schemaCollections) {
594
+ await this.ensureCollectionSchema(collectionName);
595
+ }
596
+ }
597
+ }
598
+
599
+ export default PluginElasticReportServer;