@superatomai/sdk-node 0.0.7-s → 0.0.8-cp

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.
@@ -7,8 +7,21 @@ var import_url = require("url");
7
7
  function encodeMessage(msg) {
8
8
  return JSON.stringify(msg) + "\n";
9
9
  }
10
+ var LineOverflowError = class extends Error {
11
+ constructor(buffered, limit) {
12
+ super(`IPC message exceeded ${limit} bytes without a newline (${buffered} buffered) \u2014 aborting to avoid unbounded memory.`);
13
+ this.buffered = buffered;
14
+ this.limit = limit;
15
+ this.name = "LineOverflowError";
16
+ }
17
+ };
18
+ var DEFAULT_MAX_IPC_BYTES = (() => {
19
+ const envVal = Number(process.env.SCRIPT_MAX_IPC_BYTES);
20
+ return Number.isFinite(envVal) && envVal > 0 ? Math.floor(envVal) : 64 * 1024 * 1024;
21
+ })();
10
22
  var LineSplitter = class {
11
- constructor() {
23
+ constructor(maxBytes = DEFAULT_MAX_IPC_BYTES) {
24
+ this.maxBytes = maxBytes;
12
25
  this.buffer = "";
13
26
  }
14
27
  push(chunk) {
@@ -20,6 +33,11 @@ var LineSplitter = class {
20
33
  this.buffer = this.buffer.slice(idx + 1);
21
34
  if (line.length > 0) lines.push(line);
22
35
  }
36
+ if (this.buffer.length > this.maxBytes) {
37
+ const buffered = this.buffer.length;
38
+ this.buffer = "";
39
+ throw new LineOverflowError(buffered, this.maxBytes);
40
+ }
23
41
  return lines;
24
42
  }
25
43
  /** Flush any remaining partial data (useful on stream close) */
@@ -30,8 +48,126 @@ var LineSplitter = class {
30
48
  return rest;
31
49
  }
32
50
  };
33
- function shortId() {
34
- return Math.random().toString(36).slice(2, 10);
51
+
52
+ // src/userResponse/scripts/fmt.ts
53
+ var DASH = "\u2014";
54
+ var DEFAULT_FMT_CONFIG = { locale: "en-IN", currency: "INR" };
55
+ var MONEY_TIERS = {
56
+ "en-IN": [[1e7, "Cr"], [1e5, "L"]],
57
+ "hi-IN": [[1e7, "Cr"], [1e5, "L"]]
58
+ };
59
+ var DEFAULT_MONEY_TIERS = [[1e9, "B"], [1e6, "M"]];
60
+ function moneyTiers(locale) {
61
+ return MONEY_TIERS[locale] ?? DEFAULT_MONEY_TIERS;
62
+ }
63
+ var COUNT_SCALE_MIN = 1e7;
64
+ function toNum(v) {
65
+ if (v === null || v === void 0 || v === "") return null;
66
+ const n = typeof v === "number" ? v : Number(v);
67
+ return Number.isFinite(n) ? n : null;
68
+ }
69
+ var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
70
+ var ISO_DATE = /^\d{4}-\d{2}-\d{2}([T ]|$)/;
71
+ function toDate(v) {
72
+ if (v === null || v === void 0 || v === "") return null;
73
+ if (v instanceof Date) return Number.isNaN(v.getTime()) ? null : v;
74
+ if (typeof v === "number") {
75
+ const d = new Date(v);
76
+ return Number.isNaN(d.getTime()) ? null : d;
77
+ }
78
+ if (typeof v === "string" && ISO_DATE.test(v.trim())) {
79
+ const d = new Date(v.trim());
80
+ return Number.isNaN(d.getTime()) ? null : d;
81
+ }
82
+ return null;
83
+ }
84
+ function makeFmt(cfg = {}) {
85
+ const locale = cfg.locale || DEFAULT_FMT_CONFIG.locale;
86
+ const currency = cfg.currency || DEFAULT_FMT_CONFIG.currency;
87
+ const group = (n, decimals = 0) => n.toLocaleString(locale, { minimumFractionDigits: decimals, maximumFractionDigits: decimals });
88
+ const symbol = (() => {
89
+ try {
90
+ const parts = new Intl.NumberFormat(locale, { style: "currency", currency }).formatToParts(0);
91
+ return parts.find((p) => p.type === "currency")?.value ?? "";
92
+ } catch {
93
+ return "";
94
+ }
95
+ })();
96
+ const scaled = (abs, tiers, decimals) => {
97
+ for (const [threshold, unit] of tiers) {
98
+ if (abs >= threshold) return `${group(abs / threshold, decimals)} ${unit}`;
99
+ }
100
+ return null;
101
+ };
102
+ function money(v, decimals = 2) {
103
+ const n = toNum(v);
104
+ if (n === null) return DASH;
105
+ const sign = n < 0 ? "-" : "";
106
+ const abs = Math.abs(n);
107
+ const tiers = moneyTiers(locale);
108
+ for (let i = 0; i < tiers.length; i++) {
109
+ const [threshold, unit] = tiers[i];
110
+ if (abs < threshold) continue;
111
+ const value = Number((abs / threshold).toFixed(decimals));
112
+ const higher = tiers[i - 1];
113
+ if (higher && value * threshold >= higher[0]) {
114
+ return `${sign}${symbol}${group(abs / higher[0], decimals)} ${higher[1]}`;
115
+ }
116
+ return `${sign}${symbol}${group(abs / threshold, decimals)} ${unit}`;
117
+ }
118
+ try {
119
+ return new Intl.NumberFormat(locale, {
120
+ style: "currency",
121
+ currency,
122
+ minimumFractionDigits: Number.isInteger(n) ? 0 : decimals,
123
+ maximumFractionDigits: decimals
124
+ }).format(n);
125
+ } catch {
126
+ return `${sign}${symbol}${group(abs, Number.isInteger(abs) ? 0 : decimals)}`;
127
+ }
128
+ }
129
+ function num(v, decimals) {
130
+ const n = toNum(v);
131
+ if (n === null) return DASH;
132
+ return group(n, decimals ?? (Number.isInteger(n) ? 0 : 2));
133
+ }
134
+ function count(v, decimals = 2) {
135
+ const n = toNum(v);
136
+ if (n === null) return DASH;
137
+ const abs = Math.abs(n);
138
+ const s = abs >= COUNT_SCALE_MIN ? scaled(abs, moneyTiers(locale), decimals) : null;
139
+ if (s) return `${n < 0 ? "-" : ""}${s}`;
140
+ return group(n, Number.isInteger(n) ? 0 : decimals);
141
+ }
142
+ function pct(part, whole, decimals = 1) {
143
+ const p = toNum(part), w = toNum(whole);
144
+ if (p === null || w === null || w === 0) return DASH;
145
+ return `${group(p / w * 100, decimals)}%`;
146
+ }
147
+ function delta(current, previous, decimals = 1) {
148
+ const c = toNum(current), p = toNum(previous);
149
+ if (c === null || p === null || p === 0) return DASH;
150
+ const change = (c - p) / Math.abs(p) * 100;
151
+ return `${change >= 0 ? "+" : "-"}${group(Math.abs(change), decimals)}%`;
152
+ }
153
+ function date(v) {
154
+ const d = toDate(v);
155
+ if (!d) return DASH;
156
+ return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;
157
+ }
158
+ function range(from, to) {
159
+ const a = toDate(from), b = toDate(to);
160
+ if (!a || !b) return DASH;
161
+ const left = a.getUTCFullYear() === b.getUTCFullYear() ? `${a.getUTCDate()} ${MONTHS[a.getUTCMonth()]}` : date(a);
162
+ return `${left} \u2013 ${date(b)}`;
163
+ }
164
+ function list(items, conjunction = "and") {
165
+ const parts = (items || []).map((i) => String(i ?? "").trim()).filter(Boolean);
166
+ if (!parts.length) return DASH;
167
+ if (parts.length === 1) return parts[0];
168
+ return `${parts.slice(0, -1).join(", ")} ${conjunction} ${parts[parts.length - 1]}`;
169
+ }
170
+ return { money, num, count, pct, delta, date, range, list };
35
171
  }
36
172
 
37
173
  // src/userResponse/scripts/script-bootstrap.ts
@@ -40,8 +176,28 @@ if (!SCRIPT_ARG) {
40
176
  sendError("Bootstrap was invoked without a script path.", "compile");
41
177
  process.exit(1);
42
178
  }
43
- var pending = /* @__PURE__ */ new Map();
179
+ var BRIDGE_URL = process.env.SCRIPT_BRIDGE_URL;
180
+ var CONTEXT_TOKEN = process.env.SA_CONTEXT_TOKEN;
181
+ var observedPolicies = /* @__PURE__ */ new Set();
182
+ var bridgeHeaders = () => ({
183
+ "content-type": "application/json",
184
+ ...CONTEXT_TOKEN ? { "x-sa-context": CONTEXT_TOKEN } : {}
185
+ });
44
186
  var executedQueries = [];
187
+ var toolIdCallCounts = {};
188
+ var PREVIEW_MAX_ROWS = 10;
189
+ var PREVIEW_MAX_CHARS = 200;
190
+ var QUERY_ROW_CAP = 250;
191
+ function previewRows(data) {
192
+ return data.slice(0, PREVIEW_MAX_ROWS).map((row) => {
193
+ if (!row || typeof row !== "object") return row;
194
+ const out = {};
195
+ for (const [k, v] of Object.entries(row)) {
196
+ out[k] = typeof v === "string" && v.length > PREVIEW_MAX_CHARS ? v.slice(0, PREVIEW_MAX_CHARS) + "\u2026" : v;
197
+ }
198
+ return out;
199
+ });
200
+ }
45
201
  var initResolve = null;
46
202
  var initPromise = new Promise((resolve) => {
47
203
  initResolve = resolve;
@@ -50,31 +206,87 @@ function buildCtx(init) {
50
206
  return {
51
207
  now: init.now,
52
208
  async query(toolId, sql) {
53
- const id = shortId();
209
+ if (!BRIDGE_URL) throw new Error("SCRIPT_BRIDGE_URL is not set \u2014 script bridge server is not running");
54
210
  const startedAt = Date.now();
55
- const promise = new Promise((resolve, reject) => {
56
- pending.set(id, { resolve, reject, toolId, sql, startedAt });
211
+ send({ type: "stream", chunk: `
212
+ \u{1F4DD} **Querying ${toolId}:**
213
+ \`\`\`sql
214
+ ${sql}
215
+ \`\`\`
216
+
217
+ ` });
218
+ send({ type: "stream", chunk: `__QUERY_TIMER_START_Executing query__` });
219
+ const res = await fetch(`${BRIDGE_URL}/query`, {
220
+ method: "POST",
221
+ headers: bridgeHeaders(),
222
+ body: JSON.stringify({ toolId, sql, limit: QUERY_ROW_CAP })
57
223
  });
58
- send({ type: "query", id, toolId, sql });
59
- const result = await promise;
224
+ const json = await res.json();
60
225
  const executionTimeMs = Date.now() - startedAt;
226
+ for (const p of json?.metadata?.appliedPolicies ?? []) observedPolicies.add(p);
227
+ send({ type: "stream", chunk: `__QUERY_TIMER_DONE_${(executionTimeMs / 1e3).toFixed(1)}__
228
+
229
+ ` });
230
+ if (!res.ok || !json.success) {
231
+ const errMsg = json.error || `Bridge query failed (${res.status})`;
232
+ send({ type: "stream", chunk: `\u274C **Query failed on ${toolId}:** ${errMsg}
233
+
234
+ ` });
235
+ throw new Error(errMsg);
236
+ }
237
+ let truncated = false;
238
+ let totalCount;
239
+ if (json.metadata?.truncated) {
240
+ truncated = true;
241
+ totalCount = typeof json.metadata.totalCount === "number" ? json.metadata.totalCount : void 0;
242
+ const total = json.metadata.totalCount ?? "more";
243
+ const hasGroupBy = /\bGROUP\s+BY\b/i.test(sql);
244
+ const explicitLimitMatch = sql.match(/\bLIMIT\s+(\d+)/i);
245
+ const hasDeliberateLimit = explicitLimitMatch != null && Number(explicitLimitMatch[1]) < QUERY_ROW_CAP;
246
+ if (hasGroupBy) {
247
+ send({ type: "stream", chunk: `\u2139\uFE0F Only the top ${QUERY_ROW_CAP} of ${total} grouped rows are returned (query is already aggregated via GROUP BY) \u2014 expected for a top-N request.
248
+
249
+ ` });
250
+ } else if (hasDeliberateLimit) {
251
+ send({ type: "stream", chunk: `\u2139\uFE0F Only the ${explicitLimitMatch[1]} rows requested (of ${total} matching) are returned \u2014 expected for a top-N request with an explicit LIMIT.
252
+
253
+ ` });
254
+ } else {
255
+ const msg = `ctx.query truncated the result of this query to ${QUERY_ROW_CAP} rows (it matched ${total}). Do NOT compute over raw rows \u2014 AGGREGATE IN SQL (GROUP BY / mode() / mode(...) FILTER (WHERE \u2026) / COUNT(...) FILTER (\u2026) / CASE) so the query returns the final, already-reduced rows, then have getData return those.`;
256
+ send({ type: "stream", chunk: `\u274C **Result truncated on ${toolId}:** ${msg}
257
+
258
+ ` });
259
+ throw new Error(msg);
260
+ }
261
+ }
262
+ const data = json.data ?? [];
263
+ const count = json.count ?? data.length;
264
+ send({ type: "stream", chunk: `\u2705 **${count} rows from ${toolId}**
265
+
266
+ ` });
267
+ if (data.length > 0) {
268
+ send({ type: "stream", chunk: `<DataTable>${JSON.stringify(previewRows(data))}</DataTable>
269
+
270
+ ` });
271
+ }
272
+ const callNumber = toolIdCallCounts[toolId] = (toolIdCallCounts[toolId] ?? 0) + 1;
273
+ const sourceId = callNumber === 1 ? toolId : `${toolId}#${callNumber}`;
61
274
  executedQueries.push({
62
- sourceId: toolId,
275
+ sourceId,
63
276
  sourceName: toolId,
64
- // parent overwrites with the real name
277
+ // enriched by runner after result arrives
65
278
  sql,
66
- data: result.data,
67
- count: result.count,
68
- totalCount: result.metadata?.totalCount,
69
- executionTimeMs
279
+ data,
280
+ count,
281
+ executionTimeMs,
282
+ ...json?.metadata?.appliedPolicies?.length ? { appliedPolicies: json.metadata.appliedPolicies } : {}
70
283
  });
71
- return { data: result.data, count: result.count };
284
+ return { data, count, truncated, totalCount };
72
285
  },
73
286
  /**
74
287
  * Call a tool with structured params (typically a direct tool whose
75
288
  * fn(params) does not expect a SQL string). Returns whatever the tool
76
- * returned — shape is up to the tool. The parent verifies toolId
77
- * against the authorized externalTools list before executing.
289
+ * returned — shape is up to the tool.
78
290
  *
79
291
  * Use this when you need a pre-built business-logic tool (e.g.,
80
292
  * "Calculate Shelf Life") that takes structured input rather than SQL.
@@ -85,18 +297,15 @@ function buildCtx(init) {
85
297
  * the array you want to chart.
86
298
  */
87
299
  async runTool(toolId, params = {}) {
88
- const id = shortId();
89
- const promise = new Promise((resolveResult, rejectResult) => {
90
- pending.set(id, {
91
- resolve: (payload) => resolveResult(payload?.result ?? payload),
92
- reject: rejectResult,
93
- toolId,
94
- sql: `-- runTool: ${toolId}`,
95
- startedAt: Date.now()
96
- });
300
+ if (!BRIDGE_URL) throw new Error("SCRIPT_BRIDGE_URL is not set \u2014 script bridge server is not running");
301
+ const res = await fetch(`${BRIDGE_URL}/run-tool`, {
302
+ method: "POST",
303
+ headers: bridgeHeaders(),
304
+ body: JSON.stringify({ toolId, params })
97
305
  });
98
- send({ type: "run_tool", id, toolId, params });
99
- return promise;
306
+ const json = await res.json();
307
+ if (!res.ok || !json.success) throw new Error(json.error || `Bridge run-tool failed (${res.status})`);
308
+ return json.result;
100
309
  },
101
310
  /**
102
311
  * Register a computed dataset. Flows into executedQueries alongside
@@ -123,8 +332,33 @@ function buildCtx(init) {
123
332
  }
124
333
  };
125
334
  }
335
+ function guardCtx(ctx) {
336
+ const PASSTHROUGH = /* @__PURE__ */ new Set([
337
+ "then",
338
+ "catch",
339
+ "finally",
340
+ "constructor",
341
+ "toJSON",
342
+ "inspect",
343
+ "valueOf",
344
+ "toString",
345
+ "hasOwnProperty",
346
+ "nodeType"
347
+ ]);
348
+ return new Proxy(ctx, {
349
+ get(target, prop, receiver) {
350
+ if (typeof prop === "symbol" || prop in target || PASSTHROUGH.has(prop)) {
351
+ return Reflect.get(target, prop, receiver);
352
+ }
353
+ const available = Reflect.ownKeys(target).filter((k) => typeof k === "string").join(", ");
354
+ throw new TypeError(
355
+ `ctx.${String(prop)} does not exist. ctx has exactly: ${available}. There are no formatting/parsing/date helpers on ctx \u2014 interpolate ISO date strings straight into the SQL and do date arithmetic in SQL.`
356
+ );
357
+ }
358
+ });
359
+ }
126
360
  function send(msg) {
127
- process.stdout.write(encodeMessage(msg));
361
+ return process.stdout.write(encodeMessage(msg));
128
362
  }
129
363
  function sendError(message, phase, stack) {
130
364
  send({ type: "error", message, stack, phase });
@@ -132,7 +366,15 @@ function sendError(message, phase, stack) {
132
366
  var splitter = new LineSplitter();
133
367
  process.stdin.setEncoding("utf-8");
134
368
  process.stdin.on("data", (chunk) => {
135
- for (const line of splitter.push(chunk)) {
369
+ let lines;
370
+ try {
371
+ lines = splitter.push(chunk);
372
+ } catch (err) {
373
+ const msg = err instanceof Error ? err.message : String(err);
374
+ sendError(msg, "runtime");
375
+ process.exit(1);
376
+ }
377
+ for (const line of lines) {
136
378
  let msg;
137
379
  try {
138
380
  msg = JSON.parse(line);
@@ -142,55 +384,71 @@ process.stdin.on("data", (chunk) => {
142
384
  handleMessage(msg);
143
385
  }
144
386
  });
145
- process.stdin.on("end", () => {
146
- });
147
387
  function handleMessage(msg) {
148
388
  switch (msg.type) {
149
389
  case "init": {
150
390
  if (initResolve) {
151
391
  const now = new Date(msg.now || (/* @__PURE__ */ new Date()).toISOString());
152
392
  const params = restoreParamTypes(msg.params || {}, msg.paramSchema);
153
- initResolve({ params, now });
393
+ initResolve({ params, now, mode: msg.mode, data: msg.data, datasets: msg.datasets, fmt: msg.fmt, entities: msg.entities, appliedPolicies: msg.appliedPolicies });
154
394
  initResolve = null;
155
395
  }
156
396
  break;
157
397
  }
158
- case "query_result": {
159
- const entry = pending.get(msg.id);
160
- if (entry) {
161
- pending.delete(msg.id);
162
- entry.resolve({ data: msg.data, count: msg.count, metadata: msg.metadata });
163
- }
164
- break;
398
+ }
399
+ }
400
+ function collectDatasets(queries) {
401
+ const out = {};
402
+ for (const q of queries) {
403
+ if (q.virtual && q.sourceId.startsWith("computed:")) {
404
+ out[q.sourceId.slice("computed:".length)] = q.data;
165
405
  }
166
- case "run_tool_result": {
167
- const entry = pending.get(msg.id);
168
- if (entry) {
169
- pending.delete(msg.id);
170
- entry.resolve({ result: msg.result });
171
- }
172
- break;
406
+ }
407
+ return out;
408
+ }
409
+ async function runComponents(mod, data, params, fmtCfg, datasets = {}, entities = [], scope = []) {
410
+ const getComponents = mod?.getComponents ?? mod?.default?.getComponents;
411
+ if (typeof getComponents !== "function") return {};
412
+ try {
413
+ const out = await getComponents(data, params, makeFmt(fmtCfg), datasets, entities, scope);
414
+ if (!Array.isArray(out)) {
415
+ return { componentsError: "getComponents must return an ARRAY of component specs" };
173
416
  }
174
- case "query_error": {
175
- const entry = pending.get(msg.id);
176
- if (entry) {
177
- pending.delete(msg.id);
178
- entry.reject(new Error(msg.error));
179
- }
180
- break;
417
+ if (out.some((c) => !c || typeof c !== "object")) {
418
+ return { componentsError: "every entry getComponents returns must be a component spec object" };
419
+ }
420
+ return { components: out };
421
+ } catch (err) {
422
+ const e = err;
423
+ return { componentsError: e?.message || String(err) };
424
+ }
425
+ }
426
+ async function runAnalysis(mod, data, params, fmtCfg, datasets = {}, entities = [], scope = []) {
427
+ const getAnalysis = mod?.getAnalysis ?? mod?.default?.getAnalysis;
428
+ if (typeof getAnalysis !== "function") return {};
429
+ try {
430
+ const out = await getAnalysis(data, params, makeFmt(fmtCfg), datasets, entities, scope);
431
+ if (!out || typeof out !== "object") {
432
+ return { analysisError: "getAnalysis must return an object with { analysis, summary, method }" };
181
433
  }
434
+ return {
435
+ analysis: {
436
+ analysis: typeof out.analysis === "string" ? out.analysis : void 0,
437
+ summary: Array.isArray(out.summary) ? out.summary.map((s) => String(s)) : void 0,
438
+ method: typeof out.method === "string" ? out.method : void 0
439
+ }
440
+ };
441
+ } catch (err) {
442
+ const e = err;
443
+ return { analysisError: e?.message || String(err) };
182
444
  }
183
445
  }
184
446
  (async () => {
447
+ let mod;
185
448
  let getData;
186
449
  try {
187
- const mod = await import((0, import_url.pathToFileURL)(SCRIPT_ARG).href);
188
- getData = mod.getData ?? mod.default;
189
- if (typeof getData !== "function") {
190
- throw new Error(
191
- `Script at ${SCRIPT_ARG} does not export getData \u2014 expected \`export async function getData(ctx, params)\``
192
- );
193
- }
450
+ mod = await import((0, import_url.pathToFileURL)(SCRIPT_ARG).href);
451
+ getData = mod.getData ?? (typeof mod.default === "function" ? mod.default : mod.default?.getData);
194
452
  } catch (err) {
195
453
  const e = err;
196
454
  sendError(e.message || String(err), "compile", e.stack);
@@ -198,7 +456,33 @@ function handleMessage(msg) {
198
456
  return;
199
457
  }
200
458
  const init = await initPromise;
201
- const ctx = buildCtx(init);
459
+ if (init.mode === "analysis" || init.mode === "components") {
460
+ const started = Date.now();
461
+ const rows = Array.isArray(init.data) ? init.data : [];
462
+ const ds = init.datasets ?? {};
463
+ const authored = init.mode === "analysis" ? await runAnalysis(mod, rows, init.params, init.fmt, ds, init.entities, init.appliedPolicies ?? []) : await runComponents(mod, rows, init.params, init.fmt, ds, init.entities, init.appliedPolicies ?? []);
464
+ const flushedAuthored = send({
465
+ type: "result",
466
+ data: [],
467
+ count: rows.length,
468
+ executedQueries: [],
469
+ executionTimeMs: Date.now() - started,
470
+ sampleRows: [],
471
+ ...authored
472
+ });
473
+ if (flushedAuthored) process.exit(0);
474
+ else process.stdout.once("drain", () => process.exit(0));
475
+ return;
476
+ }
477
+ if (typeof getData !== "function") {
478
+ sendError(
479
+ `Script at ${SCRIPT_ARG} does not export getData \u2014 expected \`export async function getData(ctx, params)\``,
480
+ "compile"
481
+ );
482
+ process.exit(1);
483
+ return;
484
+ }
485
+ const ctx = guardCtx(buildCtx(init));
202
486
  const startedAt = Date.now();
203
487
  try {
204
488
  const raw = await getData(ctx, init.params);
@@ -206,17 +490,28 @@ function handleMessage(msg) {
206
490
  const data = normalizeResultData(raw);
207
491
  const count = typeof raw?.count === "number" ? raw.count : data.length;
208
492
  const sampleRows = data.slice(0, 5);
493
+ const ds = collectDatasets(executedQueries);
494
+ const observed = [...observedPolicies];
495
+ const { analysis, analysisError } = await runAnalysis(mod, data, init.params, init.fmt, ds, init.entities, observed);
496
+ const { components, componentsError } = await runComponents(mod, data, init.params, init.fmt, ds, init.entities, observed);
209
497
  const result = {
210
498
  type: "result",
211
499
  data,
212
500
  count,
213
501
  executedQueries,
214
502
  executionTimeMs,
215
- sampleRows
503
+ sampleRows,
504
+ analysis,
505
+ analysisError,
506
+ components,
507
+ componentsError
216
508
  };
217
- send(result);
218
- process.stdout.once("drain", () => process.exit(0));
219
- setImmediate(() => process.exit(0));
509
+ const flushed = send(result);
510
+ if (flushed) {
511
+ process.exit(0);
512
+ } else {
513
+ process.stdout.once("drain", () => process.exit(0));
514
+ }
220
515
  } catch (err) {
221
516
  const e = err;
222
517
  sendError(e.message || String(err), "runtime", e.stack);