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
@@ -0,0 +1,340 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var report_block_tools_exports = {};
28
+ __export(report_block_tools_exports, {
29
+ createReportBlockTools: () => createReportBlockTools
30
+ });
31
+ module.exports = __toCommonJS(report_block_tools_exports);
32
+ var import_database = require("@nocobase/database");
33
+ var import_constants = require("../shared/constants");
34
+ var import_acl_guard = require("./acl-guard");
35
+ var import_ElasticReportService = require("./services/ElasticReportService");
36
+ const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
37
+ function fail(ctx, status, key) {
38
+ var _a;
39
+ throw Object.assign(new Error(((_a = ctx.t) == null ? void 0 : _a.call(ctx, key, { ns: import_constants.PLUGIN_NAME })) ?? key), { status });
40
+ }
41
+ const defaults = { reportId: null, showToolbar: true, compact: false, subscribeDashboardFilters: true, syncGroup: "" };
42
+ const propertySchemas = {
43
+ reportId: { type: ["number", "string"] },
44
+ showToolbar: { type: "boolean" },
45
+ compact: { type: "boolean" },
46
+ subscribeDashboardFilters: { type: "boolean" },
47
+ syncGroup: { type: "string" }
48
+ };
49
+ function isReportId(value) {
50
+ return typeof value === "string" && !!value.trim() || typeof value === "number" && Number.isSafeInteger(value);
51
+ }
52
+ function validField(key, value, expected) {
53
+ if (key === "reportId") {
54
+ return expected && value === null || isReportId(value);
55
+ }
56
+ if (key === "syncGroup") return typeof value === "string";
57
+ return Object.hasOwn(defaults, key) && typeof value === "boolean";
58
+ }
59
+ function sameSetting(key, left, right) {
60
+ if (key === "reportId" && left != null && right != null) return String(left) === String(right);
61
+ return left === right;
62
+ }
63
+ function readPatch(ctx, { changes, expected }) {
64
+ if (!isObject(changes) || !isObject(expected)) fail(ctx, 400, "Invalid block changes");
65
+ const keys = Object.keys(changes);
66
+ if (!keys.length || keys.length !== Object.keys(expected).length) fail(ctx, 400, "Invalid block changes");
67
+ for (const key of keys) {
68
+ if (!Object.hasOwn(expected, key) || !validField(key, changes[key], false) || !validField(key, expected[key], true)) {
69
+ fail(ctx, 400, "Invalid block changes");
70
+ }
71
+ }
72
+ return { changes, expected };
73
+ }
74
+ async function selectedContext(app, ctx, type) {
75
+ var _a, _b;
76
+ const values = (_b = (_a = ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values;
77
+ let items;
78
+ if (Array.isArray(values == null ? void 0 : values.messages)) {
79
+ const userMessage = values.messages.find((item) => isObject(item) && item.role === "user");
80
+ items = userMessage == null ? void 0 : userMessage.workContext;
81
+ } else if (typeof (values == null ? void 0 : values.sessionId) === "string") {
82
+ const sessionId = values.sessionId;
83
+ const owned = await app.db.getRepository("aiConversations").count({
84
+ filter: { sessionId, userId: (0, import_ElasticReportService.extractCurrentUserId)(ctx) }
85
+ });
86
+ if (owned) {
87
+ const message = await app.db.getRepository("aiMessages").findOne({
88
+ filter: { sessionId, role: "user", ...values.messageId ? { messageId: { $lte: values.messageId } } : {} },
89
+ fields: ["workContext"],
90
+ sort: ["-messageId"]
91
+ });
92
+ items = message == null ? void 0 : message.get("workContext");
93
+ }
94
+ }
95
+ const selected = Array.isArray(items) ? items.filter((item) => isObject(item) && item.type === type) : [];
96
+ return selected.length === 1 ? selected[0] : void 0;
97
+ }
98
+ async function resolvePage(app, ctx, uid, write, transaction) {
99
+ const paths = await app.db.getRepository("flowModelTreePath").find({
100
+ filter: { descendant: uid },
101
+ sort: ["depth"],
102
+ fields: ["ancestor"],
103
+ transaction
104
+ });
105
+ const ancestors = [.../* @__PURE__ */ new Set([uid, ...paths.map((path) => path.get("ancestor"))])];
106
+ const routes = app.db.getRepository("desktopRoutes");
107
+ const anchors = await routes.find({
108
+ filter: { schemaUid: { $in: ancestors }, type: { $in: ["flowPage", "tabs"] } },
109
+ transaction
110
+ });
111
+ const anchor = ancestors.map((id) => anchors.find((route) => route.get("schemaUid") === id)).find(Boolean);
112
+ const page = (anchor == null ? void 0 : anchor.get("type")) === "tabs" ? await routes.findOne({ filter: { id: anchor.get("parentId"), type: "flowPage" }, transaction }) : anchor;
113
+ if (!page || !anchor) fail(ctx, 403, "Block page unavailable");
114
+ const roles = (0, import_acl_guard.getEffectiveRoles)(ctx);
115
+ const routeIds = new Set([page.get("id"), anchor.get("id")].map(String));
116
+ if (app.db.hasCollection("uiLayouts")) {
117
+ let parentId = page.get("parentId");
118
+ while (parentId != null && !roles.includes("root")) {
119
+ if (routeIds.has(String(parentId))) fail(ctx, 403, "Block page unavailable");
120
+ routeIds.add(String(parentId));
121
+ const parent = await routes.findOne({ filterByTk: parentId, fields: ["parentId"], transaction });
122
+ if (!parent) fail(ctx, 403, "Block page unavailable");
123
+ parentId = parent.get("parentId");
124
+ }
125
+ const enabled = await app.db.getRepository("uiLayouts").find({ filter: { enabled: true }, fields: ["uid"], transaction });
126
+ const assignments = await app.db.getRepository("desktopRoutesUiLayouts").find({
127
+ filter: {
128
+ desktopRouteId: { $in: [...routeIds] },
129
+ uiLayoutUid: { $in: enabled.map((layout) => layout.get("uid")) }
130
+ },
131
+ transaction
132
+ });
133
+ const inCommonLayout = enabled.some(
134
+ (layout) => assignments.filter((link) => link.get("uiLayoutUid") === layout.get("uid")).length === routeIds.size
135
+ );
136
+ if (!inCommonLayout) fail(ctx, 403, "Block page unavailable");
137
+ }
138
+ if (!roles.includes("root")) {
139
+ const grants = await app.db.getRepository("rolesDesktopRoutes").find({
140
+ filter: { roleName: { $in: roles }, desktopRouteId: { $in: [...routeIds] } },
141
+ transaction
142
+ });
143
+ for (const grant of grants) routeIds.delete(String(grant.get("desktopRouteId")));
144
+ if (routeIds.size) fail(ctx, 403, "Block page unavailable");
145
+ }
146
+ const acl = app.acl.can({ roles, resource: "flowModels", action: "save" });
147
+ const canSave = !!acl && !Object.keys(acl.params ?? {}).length;
148
+ const shared = app.db.hasCollection("flowModelTemplates") && await app.db.getRepository("flowModelTemplates").count({
149
+ filter: { targetUid: { $in: ancestors } },
150
+ transaction
151
+ });
152
+ const canConfigure = canSave && !shared;
153
+ if (write && !canConfigure) fail(ctx, 403, "Block editing unavailable");
154
+ return { pageUid: String(page.get("schemaUid")), canConfigure };
155
+ }
156
+ function createReportBlockTools(app, reports) {
157
+ async function requirePublishedReport(id, ctx, transaction) {
158
+ const report = await reports.findReport(id, transaction);
159
+ if (!(report == null ? void 0 : report.published) || !report.dataView || !(0, import_acl_guard.canAccessReport)(app, ctx, report, report.dataView))
160
+ fail(ctx, 403, "Report unavailable for this block");
161
+ return report;
162
+ }
163
+ async function addBlock({ pageUid, tabUid, reportId }, ctx) {
164
+ (0, import_acl_guard.assertAuthenticated)(ctx);
165
+ const attachment = await selectedContext(app, ctx, import_constants.REPORT_DESTINATION_CONTEXT);
166
+ const selected = attachment == null ? void 0 : attachment.content;
167
+ if (!isObject(selected) || typeof pageUid !== "string" || !pageUid || typeof tabUid !== "string" || !tabUid || attachment.uid !== tabUid || !isReportId(reportId) || selected.pageUid !== pageUid || selected.tabUid !== tabUid || !sameSetting("reportId", selected.reportId, reportId)) {
168
+ fail(ctx, 400, "Select report block destination");
169
+ }
170
+ const options = app.db.sequelize.getDialect() === "sqlite" ? { type: import_database.Transaction.TYPES.IMMEDIATE } : { isolationLevel: import_database.Transaction.ISOLATION_LEVELS.READ_COMMITTED };
171
+ return app.db.sequelize.transaction(options, async (transaction) => {
172
+ var _a, _b;
173
+ const route = await app.db.getRepository("desktopRoutes").model.findOne({
174
+ where: { schemaUid: tabUid, type: "tabs" },
175
+ transaction,
176
+ lock: true
177
+ });
178
+ if (!route) fail(ctx, 403, "Block page unavailable");
179
+ const page = await resolvePage(app, ctx, tabUid, true, transaction);
180
+ if (page.pageUid !== pageUid) fail(ctx, 403, "Block page unavailable");
181
+ const report = await requirePublishedReport(reportId, ctx, transaction);
182
+ const repo = app.db.getRepository("flowModels");
183
+ const anchor = await repo.model.findByPk(tabUid, { transaction, lock: true });
184
+ if (!anchor) await repo.upsertModel({ uid: tabUid, use: "RootPageTabModel" }, { transaction });
185
+ const gridUid = await repo.ensureRouteContent(
186
+ { parentId: tabUid, subKey: "grid", use: "BlockGridModel" },
187
+ { transaction }
188
+ );
189
+ const grid = await repo.findModelById(gridUid, { transaction });
190
+ if ((grid == null ? void 0 : grid.use) !== "BlockGridModel") fail(ctx, 403, "Block page unavailable");
191
+ await resolvePage(app, ctx, gridUid, true, transaction);
192
+ const existing = (_b = (_a = grid.subModels) == null ? void 0 : _a.items) == null ? void 0 : _b.find(
193
+ (item) => {
194
+ var _a2, _b2, _c, _d;
195
+ return item.use === "ElasticReportBlockModel" && sameSetting(
196
+ "reportId",
197
+ ((_c = (_b2 = (_a2 = item.stepParams) == null ? void 0 : _a2.elasticReportBlockSettings) == null ? void 0 : _b2.editReport) == null ? void 0 : _c.reportId) ?? ((_d = item.props) == null ? void 0 : _d.reportId),
198
+ report.id
199
+ );
200
+ }
201
+ );
202
+ const target2 = { pageUid, tabUid, gridUid, reportId: report.id };
203
+ if (existing) return { ...target2, blockUid: existing.uid, created: false };
204
+ const blockUid = await repo.upsertModel(
205
+ {
206
+ parentId: gridUid,
207
+ subKey: "items",
208
+ subType: "array",
209
+ use: "ElasticReportBlockModel",
210
+ stepParams: { elasticReportBlockSettings: { editReport: { reportId: report.id } } }
211
+ },
212
+ { transaction }
213
+ );
214
+ transaction.afterCommit(() => {
215
+ app.emit("ws:sendToUser", {
216
+ userId: (0, import_ElasticReportService.extractCurrentUserId)(ctx),
217
+ message: { type: import_constants.BLOCK_ADDED_EVENT, payload: { gridUid, blockUid } }
218
+ });
219
+ });
220
+ return { ...target2, blockUid, created: true };
221
+ });
222
+ }
223
+ async function run(args, ctx, write) {
224
+ var _a;
225
+ (0, import_acl_guard.assertAuthenticated)(ctx);
226
+ const uid = args.blockUid;
227
+ if (typeof uid !== "string" || !uid.trim()) fail(ctx, 400, "Pick one Elastic Report block");
228
+ if (((_a = await selectedContext(app, ctx, "flow-model")) == null ? void 0 : _a.uid) !== uid) fail(ctx, 400, "Pick one Elastic Report block");
229
+ const patch = write ? readPatch(ctx, args) : void 0;
230
+ const transactionOptions = write && app.db.sequelize.getDialect() === "sqlite" ? { type: import_database.Transaction.TYPES.IMMEDIATE } : {};
231
+ return app.db.sequelize.transaction(transactionOptions, async (transaction) => {
232
+ const repo = app.db.getRepository("flowModels");
233
+ const row = await repo.model.findByPk(uid, { transaction, lock: write });
234
+ const raw = row == null ? void 0 : row.get("options");
235
+ const options = typeof raw === "string" ? JSON.parse(raw) : raw;
236
+ if (!isObject(options) || options.use !== "ElasticReportBlockModel") fail(ctx, 404, "Block page unavailable");
237
+ const page = await resolvePage(app, ctx, uid, write, transaction);
238
+ if ((write || args.pageUid !== void 0) && args.pageUid !== page.pageUid)
239
+ fail(ctx, 403, "Block page unavailable");
240
+ const steps = isObject(options.stepParams) ? options.stepParams : {};
241
+ const flow = isObject(steps.elasticReportBlockSettings) ? steps.elasticReportBlockSettings : {};
242
+ const edit = isObject(flow.editReport) ? flow.editReport : {};
243
+ const stored = { ...isObject(options.props) ? options.props : {}, ...edit };
244
+ const settings = {};
245
+ for (const [key, fallback] of Object.entries(defaults)) settings[key] = stored[key] ?? fallback;
246
+ if (patch) {
247
+ const { changes, expected } = patch;
248
+ if (typeof changes.reportId === "number" || typeof changes.reportId === "string") {
249
+ await requirePublishedReport(changes.reportId, ctx, transaction);
250
+ }
251
+ const pending = Object.keys(changes).filter((key) => !sameSetting(key, settings[key], changes[key]));
252
+ if (pending.some((key) => !sameSetting(key, settings[key], expected[key])))
253
+ fail(ctx, 409, "Block settings changed");
254
+ if (pending.length) {
255
+ const legacyProps = Object.fromEntries(
256
+ Object.keys(defaults).filter((key) => stored[key] != null && !Object.hasOwn(edit, key)).map((key) => [key, stored[key]])
257
+ );
258
+ await repo.patch(
259
+ {
260
+ uid,
261
+ stepParams: {
262
+ ...steps,
263
+ elasticReportBlockSettings: { ...flow, editReport: { ...legacyProps, ...edit, ...changes } }
264
+ }
265
+ },
266
+ { transaction }
267
+ );
268
+ }
269
+ transaction.afterCommit(() => {
270
+ app.emit("ws:sendToUser", {
271
+ userId: (0, import_ElasticReportService.extractCurrentUserId)(ctx),
272
+ message: { type: import_constants.BLOCK_SETTINGS_EVENT, payload: { blockUid: uid, changes } }
273
+ });
274
+ });
275
+ return { blockUid: uid, ...page, changes };
276
+ }
277
+ let reportTitle;
278
+ if (typeof settings.reportId === "number" || typeof settings.reportId === "string") {
279
+ const report = await reports.findReport(settings.reportId, transaction);
280
+ if ((report == null ? void 0 : report.dataView) && (0, import_acl_guard.canAccessReport)(app, ctx, report, report.dataView)) reportTitle = report.title;
281
+ if (reportTitle === void 0) settings.reportId = null;
282
+ }
283
+ return { blockUid: uid, ...page, settings, reportTitle };
284
+ });
285
+ }
286
+ const target = { blockUid: { type: "string" }, pageUid: { type: "string" } };
287
+ return [
288
+ {
289
+ name: "es_add_report_block",
290
+ title: import_constants.PLUGIN_NAME + ":Add report block",
291
+ description: "Append the published report selected in Report block destination to the selected page and tab. Reuse an existing block for that report in the same grid. Supply the exact IDs from the attached destination.",
292
+ defaultPermission: "ASK",
293
+ inputSchema: {
294
+ type: "object",
295
+ required: ["pageUid", "tabUid", "reportId"],
296
+ additionalProperties: false,
297
+ properties: {
298
+ pageUid: { type: "string" },
299
+ tabUid: { type: "string" },
300
+ reportId: propertySchemas.reportId
301
+ }
302
+ },
303
+ execute: (args, ctx = {}) => addBlock(args, ctx)
304
+ },
305
+ {
306
+ name: "es_describe_block",
307
+ title: import_constants.PLUGIN_NAME + ":Inspect selected Elastic Report block",
308
+ description: "Read display settings and the page UID of the Elastic Report block attached with Pick block.",
309
+ defaultPermission: "ALLOW",
310
+ inputSchema: { type: "object", required: ["blockUid"], properties: target, additionalProperties: false },
311
+ execute: (args, ctx = {}) => run(args, ctx, false)
312
+ },
313
+ {
314
+ name: "es_configure_block",
315
+ title: import_constants.PLUGIN_NAME + ":Configure selected Elastic Report block",
316
+ description: "Update only the picked instance. Supply the page UID and previous values from es_describe_block. Use null as the previous reportId for an unbound block.",
317
+ defaultPermission: "ASK",
318
+ inputSchema: {
319
+ type: "object",
320
+ required: ["blockUid", "pageUid", "expected", "changes"],
321
+ additionalProperties: false,
322
+ properties: {
323
+ ...target,
324
+ changes: { type: "object", minProperties: 1, additionalProperties: false, properties: propertySchemas },
325
+ expected: {
326
+ type: "object",
327
+ minProperties: 1,
328
+ additionalProperties: false,
329
+ properties: { ...propertySchemas, reportId: { type: ["number", "string", "null"] } }
330
+ }
331
+ }
332
+ },
333
+ execute: (args, ctx = {}) => run(args, ctx, true)
334
+ }
335
+ ];
336
+ }
337
+ // Annotate the CommonJS export names for ESM import in node:
338
+ 0 && (module.exports = {
339
+ createReportBlockTools
340
+ });
@@ -27,10 +27,12 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
27
27
  var ElasticReportService_exports = {};
28
28
  __export(ElasticReportService_exports, {
29
29
  ElasticReportService: () => ElasticReportService,
30
- extractCurrentUserId: () => extractCurrentUserId
30
+ extractCurrentUserId: () => extractCurrentUserId,
31
+ extractServerUserContext: () => extractServerUserContext
31
32
  });
32
33
  module.exports = __toCommonJS(ElasticReportService_exports);
33
34
  var import_constants = require("../../shared/constants");
35
+ var import_acl_guard = require("../acl-guard");
34
36
  var import_ReportQueryCompiler = require("./ReportQueryCompiler");
35
37
  function isRecord(value) {
36
38
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -51,6 +53,7 @@ function serializeDataView(row) {
51
53
  indexPattern: typeof plain.indexPattern === "string" ? plain.indexPattern : "",
52
54
  timeField: typeof plain.timeField === "string" && plain.timeField.trim() ? plain.timeField.trim() : null,
53
55
  description: typeof plain.description === "string" ? plain.description : null,
56
+ allowedRoles: (0, import_acl_guard.normalizeRoleList)(plain.allowedRoles),
54
57
  cachedFields: Array.isArray(plain.cachedFields) ? plain.cachedFields : null,
55
58
  ...typeof plain.createdAt === "string" ? { createdAt: plain.createdAt } : {},
56
59
  ...typeof plain.updatedAt === "string" ? { updatedAt: plain.updatedAt } : {}
@@ -68,6 +71,7 @@ function serializeReport(row) {
68
71
  visualization: spec.visualization,
69
72
  spec,
70
73
  published: plain.published !== false,
74
+ allowedRoles: (0, import_acl_guard.normalizeRoleList)(plain.allowedRoles),
71
75
  ...typeof plain.createdAt === "string" ? { createdAt: plain.createdAt } : {},
72
76
  ...typeof plain.updatedAt === "string" ? { updatedAt: plain.updatedAt } : {}
73
77
  };
@@ -80,6 +84,25 @@ class ElasticReportService {
80
84
  async listConnections() {
81
85
  return this.connections.listConnections();
82
86
  }
87
+ async testConnection(dataSourceKey, indexPattern = "*") {
88
+ const client = await this.connections.getClient(dataSourceKey);
89
+ return client.testConnection(indexPattern);
90
+ }
91
+ async listAvailableRoles() {
92
+ if (!this.app.db.hasCollection("roles")) {
93
+ return [];
94
+ }
95
+ const rows = await this.app.db.getRepository("roles").find({
96
+ sort: ["name"]
97
+ });
98
+ return rows.map((row) => {
99
+ const plain = toPlainObject(row);
100
+ const name = typeof plain.name === "string" ? plain.name.trim() : "";
101
+ const rawTitle = typeof plain.title === "string" && plain.title.trim() ? plain.title.trim() : name;
102
+ const title = rawTitle.replace(/^\{\{\s*t\(\s*['"](.+?)['"]\s*\)\s*\}\}$/, "$1");
103
+ return { name, title };
104
+ }).filter((r) => Boolean(r.name) && r.name !== "anonymous");
105
+ }
83
106
  async listIndices(dataSourceKey, indexPattern = "*") {
84
107
  const client = await this.connections.getClient(dataSourceKey);
85
108
  return client.readIndices(indexPattern);
@@ -138,7 +161,8 @@ class ElasticReportService {
138
161
  indexPattern,
139
162
  timeField,
140
163
  description: input.description ?? null,
141
- cachedFields: fields
164
+ cachedFields: fields,
165
+ ...input.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(input.allowedRoles) } : {}
142
166
  };
143
167
  if (input.id !== void 0 && input.id !== null && String(input.id).trim() !== "") {
144
168
  await repo.update({
@@ -147,6 +171,9 @@ class ElasticReportService {
147
171
  });
148
172
  return this.getDataView(input.id);
149
173
  }
174
+ if (values.allowedRoles === void 0) {
175
+ values.allowedRoles = [];
176
+ }
150
177
  if (userId !== void 0) {
151
178
  values.createdById = userId;
152
179
  }
@@ -170,16 +197,21 @@ class ElasticReportService {
170
197
  });
171
198
  return rows.map(serializeReport);
172
199
  }
173
- async getReport(reportId) {
200
+ async findReport(reportId, transaction) {
174
201
  const repo = this.app.db.getRepository(import_constants.REPORTS_COLLECTION);
175
202
  const row = await repo.findOne({
176
203
  filterByTk: reportId,
177
- appends: ["dataView"]
204
+ appends: ["dataView"],
205
+ transaction
178
206
  });
179
- if (!row) {
207
+ return row ? serializeReport(row) : null;
208
+ }
209
+ async getReport(reportId) {
210
+ const report = await this.findReport(reportId);
211
+ if (!report) {
180
212
  throw new Error(`Report "${String(reportId)}" was not found`);
181
213
  }
182
- return serializeReport(row);
214
+ return report;
183
215
  }
184
216
  async saveReport(input, userId) {
185
217
  var _a;
@@ -189,14 +221,18 @@ class ElasticReportService {
189
221
  }
190
222
  const dataView = await this.getDataView(input.dataViewId);
191
223
  const spec = (0, import_ReportQueryCompiler.normalizeReportSpec)(input.spec);
224
+ if (spec.queryMode !== "simple" && spec.query && spec.query.trim()) {
225
+ (0, import_ReportQueryCompiler.compileKqlToQueryDsl)(spec.query);
226
+ }
192
227
  const repo = this.app.db.getRepository(import_constants.REPORTS_COLLECTION);
193
228
  const values = {
194
229
  title,
195
- description: input.description ?? null,
230
+ ...input.description !== void 0 ? { description: input.description } : {},
196
231
  dataViewId: dataView.id,
197
232
  visualization: spec.visualization,
198
233
  spec,
199
- published: input.published !== false,
234
+ ...input.published !== void 0 ? { published: input.published } : {},
235
+ ...input.allowedRoles !== void 0 ? { allowedRoles: (0, import_acl_guard.normalizeRoleList)(input.allowedRoles) } : {},
200
236
  ...userId !== void 0 ? { updatedById: userId } : {}
201
237
  };
202
238
  if (input.id !== void 0 && input.id !== null && String(input.id).trim() !== "") {
@@ -206,6 +242,10 @@ class ElasticReportService {
206
242
  });
207
243
  return this.getReport(input.id);
208
244
  }
245
+ values.published ??= true;
246
+ if (values.allowedRoles === void 0) {
247
+ values.allowedRoles = [];
248
+ }
209
249
  if (userId !== void 0) {
210
250
  values.createdById = userId;
211
251
  }
@@ -214,39 +254,107 @@ class ElasticReportService {
214
254
  return this.getReport(plain.id);
215
255
  }
216
256
  async previewReport(params) {
257
+ var _a, _b, _c, _d, _e;
217
258
  const { dataView, fields } = await this.inspectDataViewFields(params.dataViewId, false);
218
259
  const normalizedSpec = (0, import_ReportQueryCompiler.normalizeReportSpec)(params.spec);
260
+ const client = await this.connections.getClient(dataView.dataSourceKey);
261
+ let activePitId = (_a = params.overrides) == null ? void 0 : _a.pitId;
262
+ const needsDeepCursor = normalizedSpec.visualization === "table" && !activePitId && ((((_b = params.overrides) == null ? void 0 : _b.page) ?? 1) * (((_c = params.overrides) == null ? void 0 : _c.pageSize) ?? normalizedSpec.pageSize ?? 20) > 1e4 || Boolean((_d = params.overrides) == null ? void 0 : _d.searchAfter));
263
+ if (needsDeepCursor && !((_e = params.overrides) == null ? void 0 : _e.searchAfter)) {
264
+ activePitId = await client.openPit(dataView.indexPattern, "1m") ?? void 0;
265
+ }
219
266
  const { body, effectiveSpec } = (0, import_ReportQueryCompiler.compileSearchRequest)({
220
267
  spec: normalizedSpec,
221
268
  overrides: params.overrides,
222
269
  timeField: dataView.timeField,
223
270
  fields,
224
- maxRowsCap: params.forMcp ? import_constants.MAX_MCP_PREVIEW_SIZE : import_constants.MAX_UI_PAGE_SIZE
271
+ maxRowsCap: params.forMcp ? import_constants.MAX_MCP_PREVIEW_SIZE : import_constants.MAX_UI_PAGE_SIZE,
272
+ userContext: params.userContext,
273
+ usePit: Boolean(activePitId)
225
274
  });
226
- const client = await this.connections.getClient(dataView.dataSourceKey);
227
- const rawSearch = await client.search(dataView.indexPattern, body);
275
+ const rawSearch = await client.search(
276
+ dataView.indexPattern,
277
+ body,
278
+ activePitId ? { pitId: activePitId } : void 0
279
+ );
228
280
  const result = (0, import_ReportQueryCompiler.parseSearchResponse)(rawSearch, body, effectiveSpec, dataView.timeField);
281
+ if (activePitId && !result.pitId) {
282
+ result.pitId = activePitId;
283
+ }
229
284
  return { dataView, result };
230
285
  }
231
286
  async runSavedReport(params) {
232
- var _a, _b, _c;
287
+ var _a, _b, _c, _d, _e, _f, _g;
233
288
  const report = await this.getReport(params.reportId);
234
289
  if (params.requirePublished && !report.published) {
235
290
  throw new Error(`Report "${report.title}" is not published`);
236
291
  }
237
292
  const runtimeOverrides = report.spec.allowInteractiveControls === false ? {
238
- page: (_a = params.overrides) == null ? void 0 : _a.page,
239
- pageSize: (_b = params.overrides) == null ? void 0 : _b.pageSize,
240
- searchAfter: (_c = params.overrides) == null ? void 0 : _c.searchAfter
293
+ contextFilters: (_a = params.overrides) == null ? void 0 : _a.contextFilters,
294
+ sharedFilters: (_b = params.overrides) == null ? void 0 : _b.sharedFilters,
295
+ timeZone: (_c = params.overrides) == null ? void 0 : _c.timeZone,
296
+ page: (_d = params.overrides) == null ? void 0 : _d.page,
297
+ pageSize: (_e = params.overrides) == null ? void 0 : _e.pageSize,
298
+ searchAfter: (_f = params.overrides) == null ? void 0 : _f.searchAfter,
299
+ pitId: (_g = params.overrides) == null ? void 0 : _g.pitId
241
300
  } : params.overrides;
242
301
  const { dataView, result } = await this.previewReport({
243
302
  dataViewId: report.dataViewId,
244
303
  spec: report.spec,
245
304
  overrides: runtimeOverrides,
246
- forMcp: params.forMcp
305
+ forMcp: params.forMcp,
306
+ userContext: params.userContext
247
307
  });
248
308
  return { report, dataView, result };
249
309
  }
310
+ async inspectFieldTopValues(params) {
311
+ const rawField = params.field.trim();
312
+ if (!rawField) {
313
+ throw new Error("field is required");
314
+ }
315
+ let baseSpec = (0, import_ReportQueryCompiler.normalizeReportSpec)({ visualization: "bar" });
316
+ let targetDataViewId = params.dataViewId;
317
+ if (params.reportId !== void 0 && params.reportId !== null && String(params.reportId).trim() !== "") {
318
+ const report = await this.getReport(params.reportId);
319
+ targetDataViewId = report.dataViewId;
320
+ baseSpec = report.spec;
321
+ }
322
+ const { dataView, fields } = await this.inspectDataViewFields(targetDataViewId, false);
323
+ const fieldMap = (0, import_ReportQueryCompiler.buildFieldCapabilityMap)(fields);
324
+ const resolvedField = (0, import_ReportQueryCompiler.resolveAggregatableField)(rawField, fieldMap);
325
+ const topSize = Math.max(1, Math.min(25, Math.trunc(params.size ?? 10)));
326
+ const probeSpec = (0, import_ReportQueryCompiler.normalizeReportSpec)({
327
+ ...baseSpec,
328
+ visualization: "bar",
329
+ chart: {
330
+ bucketType: "terms",
331
+ bucketField: resolvedField,
332
+ topN: topSize,
333
+ metricType: "count"
334
+ }
335
+ });
336
+ const { body, effectiveSpec } = (0, import_ReportQueryCompiler.compileSearchRequest)({
337
+ spec: probeSpec,
338
+ overrides: params.overrides,
339
+ timeField: dataView.timeField,
340
+ fields,
341
+ userContext: params.userContext
342
+ });
343
+ const client = await this.connections.getClient(dataView.dataSourceKey);
344
+ const rawSearch = await client.search(dataView.indexPattern, body);
345
+ const parsed = (0, import_ReportQueryCompiler.parseSearchResponse)(rawSearch, body, effectiveSpec, dataView.timeField);
346
+ const totalDocs = parsed.total;
347
+ return {
348
+ field: rawField,
349
+ resolvedField,
350
+ totalDocs,
351
+ buckets: parsed.series.map((pt) => ({
352
+ value: pt.label,
353
+ count: pt.count,
354
+ percentage: totalDocs > 0 ? Number((pt.count / totalDocs * 100).toFixed(1)) : 0
355
+ }))
356
+ };
357
+ }
250
358
  }
251
359
  function extractCurrentUserId(ctx) {
252
360
  var _a, _b, _c, _d;
@@ -256,8 +364,20 @@ function extractCurrentUserId(ctx) {
256
364
  if (authUser !== void 0 && authUser !== null) return authUser;
257
365
  return void 0;
258
366
  }
367
+ function extractServerUserContext(ctx) {
368
+ var _a;
369
+ const stateUser = (_a = ctx == null ? void 0 : ctx.state) == null ? void 0 : _a.currentUser;
370
+ const effectiveRole = (0, import_acl_guard.getEffectiveRoles)(ctx)[0];
371
+ return {
372
+ userId: extractCurrentUserId(ctx),
373
+ ...typeof (stateUser == null ? void 0 : stateUser.username) === "string" ? { username: stateUser.username } : {},
374
+ ...typeof (stateUser == null ? void 0 : stateUser.email) === "string" ? { email: stateUser.email } : {},
375
+ ...effectiveRole ? { role: effectiveRole } : {}
376
+ };
377
+ }
259
378
  // Annotate the CommonJS export names for ESM import in node:
260
379
  0 && (module.exports = {
261
380
  ElasticReportService,
262
- extractCurrentUserId
381
+ extractCurrentUserId,
382
+ extractServerUserContext
263
383
  });