plugin-elastic-report 0.7.0 → 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 (70) 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/{ai → dist/ai}/skills/elastic-report/SKILLS.md +52 -34
  6. package/dist/client-v2/851.35e416bfb3fb565f.js +10 -0
  7. package/dist/client-v2/877.81b10beb7b7f4bd7.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +2 -1
  10. package/dist/locale/en-US.json +213 -198
  11. package/dist/locale/vi-VN.json +213 -198
  12. package/dist/locale/zh-CN.json +213 -198
  13. package/dist/node_modules/@elastic/elasticsearch/package.json +1 -1
  14. package/dist/server/mcp/ElasticReportToolCatalog.js +6 -4
  15. package/dist/server/plugin.js +4 -4
  16. package/dist/server/report-block-tools.js +340 -0
  17. package/dist/server/services/ElasticReportService.js +12 -6
  18. package/dist/shared/constants.js +9 -0
  19. package/package.json +2 -3
  20. package/server.d.ts +2 -2
  21. package/server.js +1 -1
  22. package/src/ai/skills/elastic-report/SKILLS.md +52 -0
  23. package/src/client/index.tsx +34 -34
  24. package/src/client/workflow-instructions.tsx +44 -44
  25. package/src/client-v2/__tests__/elastic-report.test.tsx +879 -791
  26. package/src/client-v2/__tests__/kql-autocomplete.test.ts +178 -178
  27. package/src/client-v2/api.ts +320 -320
  28. package/src/client-v2/bus/DashboardFilterBus.ts +212 -212
  29. package/src/client-v2/components/ElasticBasicCharts.tsx +652 -652
  30. package/src/client-v2/components/ElasticFilterBar.tsx +372 -372
  31. package/src/client-v2/components/ElasticKqlInput.tsx +421 -421
  32. package/src/client-v2/components/ElasticReportBlock.tsx +306 -306
  33. package/src/client-v2/components/ElasticReportRenderer.tsx +1257 -1257
  34. package/src/client-v2/components/HighlightText.tsx +50 -50
  35. package/src/client-v2/components/ReportSelect.tsx +85 -85
  36. package/src/client-v2/index.tsx +14 -14
  37. package/src/client-v2/locale.ts +23 -23
  38. package/src/client-v2/models/ElasticFilterBarBlockModel.tsx +115 -115
  39. package/src/client-v2/models/ElasticReportBlockModel.tsx +118 -118
  40. package/src/client-v2/pages/ElasticReportManager.tsx +1453 -1453
  41. package/src/client-v2/plugin.tsx +107 -72
  42. package/src/client-v2/report-destination.tsx +126 -0
  43. package/src/client-v2/utils/kqlAutocomplete.ts +861 -861
  44. package/src/client-v2/workflow/instructions.tsx +149 -149
  45. package/src/index.ts +11 -11
  46. package/src/locale/en-US.json +213 -198
  47. package/src/locale/vi-VN.json +213 -198
  48. package/src/locale/zh-CN.json +213 -198
  49. package/src/server/__tests__/ai-blocks.integration.test.ts +292 -0
  50. package/src/server/__tests__/query-compiler.test.ts +620 -620
  51. package/src/server/__tests__/report-mcp-acl.integration.test.ts +645 -645
  52. package/src/server/acl-guard.ts +194 -194
  53. package/src/server/collections/es-report-data-views.ts +64 -64
  54. package/src/server/collections/es-reports.ts +80 -80
  55. package/src/server/index.ts +15 -15
  56. package/src/server/mcp/ElasticReportMcpServer.ts +391 -391
  57. package/src/server/mcp/ElasticReportToolCatalog.ts +667 -663
  58. package/src/server/plugin.ts +599 -599
  59. package/src/server/report-block-tools.ts +400 -0
  60. package/src/server/services/ElasticReportService.ts +494 -486
  61. package/src/server/services/ElasticsearchConnectionService.ts +728 -728
  62. package/src/server/services/ReportExportService.ts +282 -282
  63. package/src/server/services/ReportQueryCompiler.ts +1552 -1552
  64. package/src/server/workflow/ElasticReportQueryInstruction.ts +124 -124
  65. package/src/shared/constants.ts +39 -36
  66. package/src/shared/types.ts +272 -272
  67. package/dist/client-v2/851.142c93fc6d666b28.js +0 -10
  68. package/dist/client-v2/877.f4095a3dbcadf98f.js +0 -10
  69. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv +0 -15
  70. package/dist/node_modules/@elastic/elasticsearch/node_modules/.bin/arrow2csv.cmd +0 -7
@@ -1,282 +1,282 @@
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 { once } from 'events';
11
- import { PassThrough } from 'stream';
12
- import { DEFAULT_MAX_EXPORT_ROWS, EXPORT_BATCH_SIZE } from '../../shared/constants';
13
- import type { ExportFormat, ID, ReportRowHit, ReportRuntimeOverrides, ReportSpec } from '../../shared/types';
14
- import type { ElasticsearchConnectionService } from './ElasticsearchConnectionService';
15
- import type { ElasticReportService } from './ElasticReportService';
16
- import {
17
- type ServerUserTokenContext,
18
- compileSearchRequest,
19
- normalizeReportSpec,
20
- parseSearchResponse,
21
- } from './ReportQueryCompiler';
22
-
23
- function readNestedField(source: Record<string, unknown>, path: string): unknown {
24
- if (path in source) return source[path];
25
- const segments = path.split('.');
26
- let cur: unknown = source;
27
- for (const seg of segments) {
28
- if (cur && typeof cur === 'object' && !Array.isArray(cur) && seg in (cur as Record<string, unknown>)) {
29
- cur = (cur as Record<string, unknown>)[seg];
30
- } else {
31
- return undefined;
32
- }
33
- }
34
- return cur;
35
- }
36
-
37
- /**
38
- * Format and escape a CSV cell according to RFC-4180 while neutralizing
39
- * spreadsheet formula injection (`=`, `+`, `-`, `@`, `\t`, `\r` on non-numeric strings).
40
- */
41
- export function escapeCsvCell(value: unknown, options?: { allowAtIdentifier?: boolean }): string {
42
- if (value === null || value === undefined) return '';
43
- if (typeof value === 'number' || typeof value === 'boolean') return String(value);
44
-
45
- let str = typeof value === 'string' ? value : JSON.stringify(value);
46
- const isSafeAtFieldHeader = options?.allowAtIdentifier === true && /^@[A-Za-z0-9_.-]+$/.test(str);
47
- if (!isSafeAtFieldHeader && /^[=+\-@\t\r]/.test(str) && !/^-?\d+(\.\d+)?$/.test(str)) {
48
- str = `'${str}`;
49
- }
50
- if (/[",\r\n]/.test(str)) {
51
- return `"${str.replace(/"/g, '""')}"`;
52
- }
53
- return str;
54
- }
55
-
56
- function formatRowsAsCsv(rows: ReportRowHit[], columns: string[]): string {
57
- const lines: string[] = [];
58
- for (const row of rows) {
59
- const cells = columns.map((col) => {
60
- if (col === '_id') return escapeCsvCell(row._id);
61
- if (col === '_index') return escapeCsvCell(row._index);
62
- return escapeCsvCell(readNestedField(row.source, col));
63
- });
64
- lines.push(`${cells.join(',')}\r\n`);
65
- }
66
- return lines.join('');
67
- }
68
-
69
- function formatRowsAsNdjson(rows: ReportRowHit[]): string {
70
- return rows.map((row) => `${JSON.stringify({ _index: row._index, _id: row._id, ...row.source })}\n`).join('');
71
- }
72
-
73
- async function writeChunk(stream: PassThrough, chunk: string): Promise<void> {
74
- if (!chunk) return;
75
- if (!stream.write(chunk)) {
76
- await once(stream, 'drain');
77
- }
78
- }
79
-
80
- export class ReportExportService {
81
- constructor(
82
- private readonly connections: ElasticsearchConnectionService,
83
- private readonly reportService: ElasticReportService,
84
- ) {}
85
-
86
- private resolveMaxExportCap(requested?: number): number {
87
- const envCap = Number(process.env.ELASTIC_REPORT_MAX_EXPORT_ROWS);
88
- const hardCap = Number.isFinite(envCap) && envCap > 0 ? Math.trunc(envCap) : DEFAULT_MAX_EXPORT_ROWS;
89
- if (typeof requested === 'number' && Number.isFinite(requested) && requested > 0) {
90
- return Math.min(hardCap, Math.trunc(requested));
91
- }
92
- return hardCap;
93
- }
94
-
95
- async createExportStream(params: {
96
- reportId: ID;
97
- format: ExportFormat;
98
- overrides?: ReportRuntimeOverrides;
99
- columns?: string[];
100
- maxRows?: number;
101
- userContext?: ServerUserTokenContext;
102
- }): Promise<{
103
- stream: PassThrough;
104
- filename: string;
105
- contentType: string;
106
- }> {
107
- const report = await this.reportService.getReport(params.reportId);
108
- if (report.spec.allowExport === false) {
109
- const err = new Error('Data export is disabled for this report') as Error & { status?: number };
110
- err.status = 403;
111
- throw err;
112
- }
113
-
114
- const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
115
- const client = await this.connections.getClient(dataView.dataSourceKey);
116
-
117
- const maxRows = this.resolveMaxExportCap(params.maxRows);
118
- const batchSize = Math.min(EXPORT_BATCH_SIZE, maxRows);
119
-
120
- const exportSpec: ReportSpec = normalizeReportSpec({
121
- ...report.spec,
122
- visualization: 'table',
123
- ...(params.columns && params.columns.length > 0 ? { columns: params.columns } : {}),
124
- chart: { ...report.spec.chart, showHistogram: false },
125
- });
126
-
127
- const effectiveOverrides: ReportRuntimeOverrides | undefined =
128
- report.spec.allowInteractiveControls === false
129
- ? {
130
- contextFilters: params.overrides?.contextFilters,
131
- sharedFilters: params.overrides?.sharedFilters,
132
- timeZone: params.overrides?.timeZone,
133
- }
134
- : params.overrides;
135
-
136
- const pitId = await client.openPit(dataView.indexPattern, '1m');
137
-
138
- // Preflight batch 1 BEFORE returning HTTP 200 stream headers so ACL/KQL/ES errors throw cleanly.
139
- const firstCompile = compileSearchRequest({
140
- spec: exportSpec,
141
- overrides: {
142
- ...effectiveOverrides,
143
- page: 1,
144
- pageSize: batchSize,
145
- searchAfter: undefined,
146
- },
147
- timeField: dataView.timeField,
148
- fields,
149
- maxRowsCap: EXPORT_BATCH_SIZE,
150
- userContext: params.userContext,
151
- usePit: Boolean(pitId),
152
- });
153
- firstCompile.body.size = batchSize;
154
- delete firstCompile.body.from;
155
- delete firstCompile.body.highlight;
156
- delete firstCompile.body.aggs;
157
-
158
- let firstParsed;
159
- try {
160
- const firstRaw = await client.search(dataView.indexPattern, firstCompile.body, pitId ? { pitId } : undefined);
161
- firstParsed = parseSearchResponse(firstRaw, firstCompile.body, firstCompile.effectiveSpec, dataView.timeField);
162
- } catch (error) {
163
- if (pitId) {
164
- await client.closePit(pitId);
165
- }
166
- throw error;
167
- }
168
-
169
- const resolvedColumns =
170
- params.columns && params.columns.length > 0
171
- ? params.columns
172
- : firstParsed.columns.length > 0
173
- ? firstParsed.columns
174
- : ['@timestamp', '_index', '_id'];
175
-
176
- const safeSlug =
177
- report.title
178
- .toLowerCase()
179
- .replace(/[^a-z0-9_-]+/g, '-')
180
- .replace(/^-+|-+$/g, '')
181
- .slice(0, 48) || `report-${String(report.id)}`;
182
- const ext = params.format === 'ndjson' ? 'ndjson' : 'csv';
183
- const filename = `${safeSlug}.${ext}`;
184
- const contentType = params.format === 'ndjson' ? 'application/x-ndjson; charset=utf-8' : 'text/csv; charset=utf-8';
185
-
186
- const stream = new PassThrough();
187
-
188
- const pumpRemainingBatches = async () => {
189
- let exportedCount = 0;
190
- let activeCursor = firstParsed.nextSearchAfter;
191
- let activePit = firstParsed.pitId ?? pitId ?? undefined;
192
-
193
- try {
194
- if (params.format === 'csv') {
195
- await writeChunk(
196
- stream,
197
- `\uFEFF${resolvedColumns.map((col) => escapeCsvCell(col, { allowAtIdentifier: true })).join(',')}\r\n`,
198
- );
199
- await writeChunk(stream, formatRowsAsCsv(firstParsed.rows, resolvedColumns));
200
- } else {
201
- await writeChunk(stream, formatRowsAsNdjson(firstParsed.rows));
202
- }
203
- exportedCount += firstParsed.rows.length;
204
-
205
- while (
206
- exportedCount < maxRows &&
207
- firstParsed.rows.length === batchSize &&
208
- activeCursor &&
209
- activeCursor.length > 0
210
- ) {
211
- const remaining = maxRows - exportedCount;
212
- const nextSize = Math.min(EXPORT_BATCH_SIZE, remaining);
213
-
214
- const nextCompile = compileSearchRequest({
215
- spec: exportSpec,
216
- overrides: {
217
- ...effectiveOverrides,
218
- pageSize: nextSize,
219
- searchAfter: activeCursor,
220
- },
221
- timeField: dataView.timeField,
222
- fields,
223
- maxRowsCap: EXPORT_BATCH_SIZE,
224
- userContext: params.userContext,
225
- usePit: Boolean(activePit),
226
- });
227
- nextCompile.body.size = nextSize;
228
- nextCompile.body.search_after = activeCursor;
229
- delete nextCompile.body.from;
230
- delete nextCompile.body.highlight;
231
- delete nextCompile.body.aggs;
232
-
233
- const nextRaw = await client.search(
234
- dataView.indexPattern,
235
- nextCompile.body,
236
- activePit ? { pitId: activePit } : undefined,
237
- );
238
- const nextParsed = parseSearchResponse(
239
- nextRaw,
240
- nextCompile.body,
241
- nextCompile.effectiveSpec,
242
- dataView.timeField,
243
- );
244
- if (nextParsed.pitId) {
245
- activePit = nextParsed.pitId;
246
- }
247
- if (nextParsed.rows.length === 0) {
248
- break;
249
- }
250
-
251
- if (params.format === 'csv') {
252
- await writeChunk(stream, formatRowsAsCsv(nextParsed.rows, resolvedColumns));
253
- } else {
254
- await writeChunk(stream, formatRowsAsNdjson(nextParsed.rows));
255
- }
256
-
257
- exportedCount += nextParsed.rows.length;
258
- activeCursor = nextParsed.nextSearchAfter;
259
- if (nextParsed.rows.length < nextSize) {
260
- break;
261
- }
262
- }
263
-
264
- stream.end();
265
- } catch (err) {
266
- stream.destroy(err instanceof Error ? err : new Error(String(err)));
267
- } finally {
268
- if (activePit) {
269
- await client.closePit(activePit);
270
- }
271
- }
272
- };
273
-
274
- pumpRemainingBatches();
275
-
276
- return {
277
- stream,
278
- filename,
279
- contentType,
280
- };
281
- }
282
- }
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 { once } from 'events';
11
+ import { PassThrough } from 'stream';
12
+ import { DEFAULT_MAX_EXPORT_ROWS, EXPORT_BATCH_SIZE } from '../../shared/constants';
13
+ import type { ExportFormat, ID, ReportRowHit, ReportRuntimeOverrides, ReportSpec } from '../../shared/types';
14
+ import type { ElasticsearchConnectionService } from './ElasticsearchConnectionService';
15
+ import type { ElasticReportService } from './ElasticReportService';
16
+ import {
17
+ type ServerUserTokenContext,
18
+ compileSearchRequest,
19
+ normalizeReportSpec,
20
+ parseSearchResponse,
21
+ } from './ReportQueryCompiler';
22
+
23
+ function readNestedField(source: Record<string, unknown>, path: string): unknown {
24
+ if (path in source) return source[path];
25
+ const segments = path.split('.');
26
+ let cur: unknown = source;
27
+ for (const seg of segments) {
28
+ if (cur && typeof cur === 'object' && !Array.isArray(cur) && seg in (cur as Record<string, unknown>)) {
29
+ cur = (cur as Record<string, unknown>)[seg];
30
+ } else {
31
+ return undefined;
32
+ }
33
+ }
34
+ return cur;
35
+ }
36
+
37
+ /**
38
+ * Format and escape a CSV cell according to RFC-4180 while neutralizing
39
+ * spreadsheet formula injection (`=`, `+`, `-`, `@`, `\t`, `\r` on non-numeric strings).
40
+ */
41
+ export function escapeCsvCell(value: unknown, options?: { allowAtIdentifier?: boolean }): string {
42
+ if (value === null || value === undefined) return '';
43
+ if (typeof value === 'number' || typeof value === 'boolean') return String(value);
44
+
45
+ let str = typeof value === 'string' ? value : JSON.stringify(value);
46
+ const isSafeAtFieldHeader = options?.allowAtIdentifier === true && /^@[A-Za-z0-9_.-]+$/.test(str);
47
+ if (!isSafeAtFieldHeader && /^[=+\-@\t\r]/.test(str) && !/^-?\d+(\.\d+)?$/.test(str)) {
48
+ str = `'${str}`;
49
+ }
50
+ if (/[",\r\n]/.test(str)) {
51
+ return `"${str.replace(/"/g, '""')}"`;
52
+ }
53
+ return str;
54
+ }
55
+
56
+ function formatRowsAsCsv(rows: ReportRowHit[], columns: string[]): string {
57
+ const lines: string[] = [];
58
+ for (const row of rows) {
59
+ const cells = columns.map((col) => {
60
+ if (col === '_id') return escapeCsvCell(row._id);
61
+ if (col === '_index') return escapeCsvCell(row._index);
62
+ return escapeCsvCell(readNestedField(row.source, col));
63
+ });
64
+ lines.push(`${cells.join(',')}\r\n`);
65
+ }
66
+ return lines.join('');
67
+ }
68
+
69
+ function formatRowsAsNdjson(rows: ReportRowHit[]): string {
70
+ return rows.map((row) => `${JSON.stringify({ _index: row._index, _id: row._id, ...row.source })}\n`).join('');
71
+ }
72
+
73
+ async function writeChunk(stream: PassThrough, chunk: string): Promise<void> {
74
+ if (!chunk) return;
75
+ if (!stream.write(chunk)) {
76
+ await once(stream, 'drain');
77
+ }
78
+ }
79
+
80
+ export class ReportExportService {
81
+ constructor(
82
+ private readonly connections: ElasticsearchConnectionService,
83
+ private readonly reportService: ElasticReportService,
84
+ ) {}
85
+
86
+ private resolveMaxExportCap(requested?: number): number {
87
+ const envCap = Number(process.env.ELASTIC_REPORT_MAX_EXPORT_ROWS);
88
+ const hardCap = Number.isFinite(envCap) && envCap > 0 ? Math.trunc(envCap) : DEFAULT_MAX_EXPORT_ROWS;
89
+ if (typeof requested === 'number' && Number.isFinite(requested) && requested > 0) {
90
+ return Math.min(hardCap, Math.trunc(requested));
91
+ }
92
+ return hardCap;
93
+ }
94
+
95
+ async createExportStream(params: {
96
+ reportId: ID;
97
+ format: ExportFormat;
98
+ overrides?: ReportRuntimeOverrides;
99
+ columns?: string[];
100
+ maxRows?: number;
101
+ userContext?: ServerUserTokenContext;
102
+ }): Promise<{
103
+ stream: PassThrough;
104
+ filename: string;
105
+ contentType: string;
106
+ }> {
107
+ const report = await this.reportService.getReport(params.reportId);
108
+ if (report.spec.allowExport === false) {
109
+ const err = new Error('Data export is disabled for this report') as Error & { status?: number };
110
+ err.status = 403;
111
+ throw err;
112
+ }
113
+
114
+ const { dataView, fields } = await this.reportService.inspectDataViewFields(report.dataViewId, false);
115
+ const client = await this.connections.getClient(dataView.dataSourceKey);
116
+
117
+ const maxRows = this.resolveMaxExportCap(params.maxRows);
118
+ const batchSize = Math.min(EXPORT_BATCH_SIZE, maxRows);
119
+
120
+ const exportSpec: ReportSpec = normalizeReportSpec({
121
+ ...report.spec,
122
+ visualization: 'table',
123
+ ...(params.columns && params.columns.length > 0 ? { columns: params.columns } : {}),
124
+ chart: { ...report.spec.chart, showHistogram: false },
125
+ });
126
+
127
+ const effectiveOverrides: ReportRuntimeOverrides | undefined =
128
+ report.spec.allowInteractiveControls === false
129
+ ? {
130
+ contextFilters: params.overrides?.contextFilters,
131
+ sharedFilters: params.overrides?.sharedFilters,
132
+ timeZone: params.overrides?.timeZone,
133
+ }
134
+ : params.overrides;
135
+
136
+ const pitId = await client.openPit(dataView.indexPattern, '1m');
137
+
138
+ // Preflight batch 1 BEFORE returning HTTP 200 stream headers so ACL/KQL/ES errors throw cleanly.
139
+ const firstCompile = compileSearchRequest({
140
+ spec: exportSpec,
141
+ overrides: {
142
+ ...effectiveOverrides,
143
+ page: 1,
144
+ pageSize: batchSize,
145
+ searchAfter: undefined,
146
+ },
147
+ timeField: dataView.timeField,
148
+ fields,
149
+ maxRowsCap: EXPORT_BATCH_SIZE,
150
+ userContext: params.userContext,
151
+ usePit: Boolean(pitId),
152
+ });
153
+ firstCompile.body.size = batchSize;
154
+ delete firstCompile.body.from;
155
+ delete firstCompile.body.highlight;
156
+ delete firstCompile.body.aggs;
157
+
158
+ let firstParsed;
159
+ try {
160
+ const firstRaw = await client.search(dataView.indexPattern, firstCompile.body, pitId ? { pitId } : undefined);
161
+ firstParsed = parseSearchResponse(firstRaw, firstCompile.body, firstCompile.effectiveSpec, dataView.timeField);
162
+ } catch (error) {
163
+ if (pitId) {
164
+ await client.closePit(pitId);
165
+ }
166
+ throw error;
167
+ }
168
+
169
+ const resolvedColumns =
170
+ params.columns && params.columns.length > 0
171
+ ? params.columns
172
+ : firstParsed.columns.length > 0
173
+ ? firstParsed.columns
174
+ : ['@timestamp', '_index', '_id'];
175
+
176
+ const safeSlug =
177
+ report.title
178
+ .toLowerCase()
179
+ .replace(/[^a-z0-9_-]+/g, '-')
180
+ .replace(/^-+|-+$/g, '')
181
+ .slice(0, 48) || `report-${String(report.id)}`;
182
+ const ext = params.format === 'ndjson' ? 'ndjson' : 'csv';
183
+ const filename = `${safeSlug}.${ext}`;
184
+ const contentType = params.format === 'ndjson' ? 'application/x-ndjson; charset=utf-8' : 'text/csv; charset=utf-8';
185
+
186
+ const stream = new PassThrough();
187
+
188
+ const pumpRemainingBatches = async () => {
189
+ let exportedCount = 0;
190
+ let activeCursor = firstParsed.nextSearchAfter;
191
+ let activePit = firstParsed.pitId ?? pitId ?? undefined;
192
+
193
+ try {
194
+ if (params.format === 'csv') {
195
+ await writeChunk(
196
+ stream,
197
+ `\uFEFF${resolvedColumns.map((col) => escapeCsvCell(col, { allowAtIdentifier: true })).join(',')}\r\n`,
198
+ );
199
+ await writeChunk(stream, formatRowsAsCsv(firstParsed.rows, resolvedColumns));
200
+ } else {
201
+ await writeChunk(stream, formatRowsAsNdjson(firstParsed.rows));
202
+ }
203
+ exportedCount += firstParsed.rows.length;
204
+
205
+ while (
206
+ exportedCount < maxRows &&
207
+ firstParsed.rows.length === batchSize &&
208
+ activeCursor &&
209
+ activeCursor.length > 0
210
+ ) {
211
+ const remaining = maxRows - exportedCount;
212
+ const nextSize = Math.min(EXPORT_BATCH_SIZE, remaining);
213
+
214
+ const nextCompile = compileSearchRequest({
215
+ spec: exportSpec,
216
+ overrides: {
217
+ ...effectiveOverrides,
218
+ pageSize: nextSize,
219
+ searchAfter: activeCursor,
220
+ },
221
+ timeField: dataView.timeField,
222
+ fields,
223
+ maxRowsCap: EXPORT_BATCH_SIZE,
224
+ userContext: params.userContext,
225
+ usePit: Boolean(activePit),
226
+ });
227
+ nextCompile.body.size = nextSize;
228
+ nextCompile.body.search_after = activeCursor;
229
+ delete nextCompile.body.from;
230
+ delete nextCompile.body.highlight;
231
+ delete nextCompile.body.aggs;
232
+
233
+ const nextRaw = await client.search(
234
+ dataView.indexPattern,
235
+ nextCompile.body,
236
+ activePit ? { pitId: activePit } : undefined,
237
+ );
238
+ const nextParsed = parseSearchResponse(
239
+ nextRaw,
240
+ nextCompile.body,
241
+ nextCompile.effectiveSpec,
242
+ dataView.timeField,
243
+ );
244
+ if (nextParsed.pitId) {
245
+ activePit = nextParsed.pitId;
246
+ }
247
+ if (nextParsed.rows.length === 0) {
248
+ break;
249
+ }
250
+
251
+ if (params.format === 'csv') {
252
+ await writeChunk(stream, formatRowsAsCsv(nextParsed.rows, resolvedColumns));
253
+ } else {
254
+ await writeChunk(stream, formatRowsAsNdjson(nextParsed.rows));
255
+ }
256
+
257
+ exportedCount += nextParsed.rows.length;
258
+ activeCursor = nextParsed.nextSearchAfter;
259
+ if (nextParsed.rows.length < nextSize) {
260
+ break;
261
+ }
262
+ }
263
+
264
+ stream.end();
265
+ } catch (err) {
266
+ stream.destroy(err instanceof Error ? err : new Error(String(err)));
267
+ } finally {
268
+ if (activePit) {
269
+ await client.closePit(activePit);
270
+ }
271
+ }
272
+ };
273
+
274
+ pumpRemainingBatches();
275
+
276
+ return {
277
+ stream,
278
+ filename,
279
+ contentType,
280
+ };
281
+ }
282
+ }