@superatomai/sdk-node 0.0.8-s → 0.0.9-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.
- package/README.md +942 -942
- package/dist/index.d.mts +4949 -2021
- package/dist/index.d.ts +4949 -2021
- package/dist/index.js +21109 -11757
- package/dist/index.mjs +16979 -7681
- package/dist/userResponse/scripts/script-bootstrap.js +334 -76
- package/dist/userResponse/scripts/script-bootstrap.mjs +334 -76
- package/package.json +13 -6
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/userResponse/scripts/script-bootstrap.js.map +0 -1
- package/dist/userResponse/scripts/script-bootstrap.mjs.map +0 -1
|
@@ -48,8 +48,126 @@ var LineSplitter = class {
|
|
|
48
48
|
return rest;
|
|
49
49
|
}
|
|
50
50
|
};
|
|
51
|
-
|
|
52
|
-
|
|
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 };
|
|
53
171
|
}
|
|
54
172
|
|
|
55
173
|
// src/userResponse/scripts/script-bootstrap.ts
|
|
@@ -58,8 +176,28 @@ if (!SCRIPT_ARG) {
|
|
|
58
176
|
sendError("Bootstrap was invoked without a script path.", "compile");
|
|
59
177
|
process.exit(1);
|
|
60
178
|
}
|
|
61
|
-
var
|
|
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
|
+
});
|
|
62
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
|
+
}
|
|
63
201
|
var initResolve = null;
|
|
64
202
|
var initPromise = new Promise((resolve) => {
|
|
65
203
|
initResolve = resolve;
|
|
@@ -68,31 +206,87 @@ function buildCtx(init) {
|
|
|
68
206
|
return {
|
|
69
207
|
now: init.now,
|
|
70
208
|
async query(toolId, sql) {
|
|
71
|
-
|
|
209
|
+
if (!BRIDGE_URL) throw new Error("SCRIPT_BRIDGE_URL is not set \u2014 script bridge server is not running");
|
|
72
210
|
const startedAt = Date.now();
|
|
73
|
-
|
|
74
|
-
|
|
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 })
|
|
75
223
|
});
|
|
76
|
-
|
|
77
|
-
const result = await promise;
|
|
224
|
+
const json = await res.json();
|
|
78
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}`;
|
|
79
274
|
executedQueries.push({
|
|
80
|
-
sourceId
|
|
275
|
+
sourceId,
|
|
81
276
|
sourceName: toolId,
|
|
82
|
-
//
|
|
277
|
+
// enriched by runner after result arrives
|
|
83
278
|
sql,
|
|
84
|
-
data
|
|
85
|
-
count
|
|
86
|
-
|
|
87
|
-
|
|
279
|
+
data,
|
|
280
|
+
count,
|
|
281
|
+
executionTimeMs,
|
|
282
|
+
...json?.metadata?.appliedPolicies?.length ? { appliedPolicies: json.metadata.appliedPolicies } : {}
|
|
88
283
|
});
|
|
89
|
-
return { data
|
|
284
|
+
return { data, count, truncated, totalCount };
|
|
90
285
|
},
|
|
91
286
|
/**
|
|
92
287
|
* Call a tool with structured params (typically a direct tool whose
|
|
93
288
|
* fn(params) does not expect a SQL string). Returns whatever the tool
|
|
94
|
-
* returned — shape is up to the tool.
|
|
95
|
-
* against the authorized externalTools list before executing.
|
|
289
|
+
* returned — shape is up to the tool.
|
|
96
290
|
*
|
|
97
291
|
* Use this when you need a pre-built business-logic tool (e.g.,
|
|
98
292
|
* "Calculate Shelf Life") that takes structured input rather than SQL.
|
|
@@ -103,18 +297,15 @@ function buildCtx(init) {
|
|
|
103
297
|
* the array you want to chart.
|
|
104
298
|
*/
|
|
105
299
|
async runTool(toolId, params = {}) {
|
|
106
|
-
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
toolId,
|
|
112
|
-
sql: `-- runTool: ${toolId}`,
|
|
113
|
-
startedAt: Date.now()
|
|
114
|
-
});
|
|
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 })
|
|
115
305
|
});
|
|
116
|
-
|
|
117
|
-
|
|
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;
|
|
118
309
|
},
|
|
119
310
|
/**
|
|
120
311
|
* Register a computed dataset. Flows into executedQueries alongside
|
|
@@ -141,18 +332,37 @@ function buildCtx(init) {
|
|
|
141
332
|
}
|
|
142
333
|
};
|
|
143
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
|
+
}
|
|
144
360
|
function send(msg) {
|
|
145
|
-
process.stdout.write(encodeMessage(msg));
|
|
361
|
+
return process.stdout.write(encodeMessage(msg));
|
|
146
362
|
}
|
|
147
363
|
function sendError(message, phase, stack) {
|
|
148
364
|
send({ type: "error", message, stack, phase });
|
|
149
365
|
}
|
|
150
|
-
function rejectAllPending(reason) {
|
|
151
|
-
for (const [id, entry] of Array.from(pending.entries())) {
|
|
152
|
-
pending.delete(id);
|
|
153
|
-
entry.reject(new Error(reason));
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
366
|
var splitter = new LineSplitter();
|
|
157
367
|
process.stdin.setEncoding("utf-8");
|
|
158
368
|
process.stdin.on("data", (chunk) => {
|
|
@@ -161,7 +371,6 @@ process.stdin.on("data", (chunk) => {
|
|
|
161
371
|
lines = splitter.push(chunk);
|
|
162
372
|
} catch (err) {
|
|
163
373
|
const msg = err instanceof Error ? err.message : String(err);
|
|
164
|
-
rejectAllPending(msg);
|
|
165
374
|
sendError(msg, "runtime");
|
|
166
375
|
process.exit(1);
|
|
167
376
|
}
|
|
@@ -175,59 +384,71 @@ process.stdin.on("data", (chunk) => {
|
|
|
175
384
|
handleMessage(msg);
|
|
176
385
|
}
|
|
177
386
|
});
|
|
178
|
-
process.stdin.on("end", () => {
|
|
179
|
-
rejectAllPending("Parent closed the IPC channel (stdin end) before a query completed.");
|
|
180
|
-
});
|
|
181
|
-
process.stdin.on("error", (err) => {
|
|
182
|
-
rejectAllPending(`IPC channel error before a query completed: ${err.message}`);
|
|
183
|
-
});
|
|
184
387
|
function handleMessage(msg) {
|
|
185
388
|
switch (msg.type) {
|
|
186
389
|
case "init": {
|
|
187
390
|
if (initResolve) {
|
|
188
391
|
const now = new Date(msg.now || (/* @__PURE__ */ new Date()).toISOString());
|
|
189
392
|
const params = restoreParamTypes(msg.params || {}, msg.paramSchema);
|
|
190
|
-
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 });
|
|
191
394
|
initResolve = null;
|
|
192
395
|
}
|
|
193
396
|
break;
|
|
194
397
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
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;
|
|
202
405
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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" };
|
|
210
416
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
if (entry) {
|
|
214
|
-
pending.delete(msg.id);
|
|
215
|
-
entry.reject(new Error(msg.error));
|
|
216
|
-
}
|
|
217
|
-
break;
|
|
417
|
+
if (out.some((c) => !c || typeof c !== "object")) {
|
|
418
|
+
return { componentsError: "every entry getComponents returns must be a component spec object" };
|
|
218
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 }" };
|
|
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) };
|
|
219
444
|
}
|
|
220
445
|
}
|
|
221
446
|
(async () => {
|
|
447
|
+
let mod;
|
|
222
448
|
let getData;
|
|
223
449
|
try {
|
|
224
|
-
|
|
225
|
-
getData = mod.getData ?? mod.default;
|
|
226
|
-
if (typeof getData !== "function") {
|
|
227
|
-
throw new Error(
|
|
228
|
-
`Script at ${SCRIPT_ARG} does not export getData \u2014 expected \`export async function getData(ctx, params)\``
|
|
229
|
-
);
|
|
230
|
-
}
|
|
450
|
+
mod = await import((0, import_url.pathToFileURL)(SCRIPT_ARG).href);
|
|
451
|
+
getData = mod.getData ?? (typeof mod.default === "function" ? mod.default : mod.default?.getData);
|
|
231
452
|
} catch (err) {
|
|
232
453
|
const e = err;
|
|
233
454
|
sendError(e.message || String(err), "compile", e.stack);
|
|
@@ -235,7 +456,33 @@ function handleMessage(msg) {
|
|
|
235
456
|
return;
|
|
236
457
|
}
|
|
237
458
|
const init = await initPromise;
|
|
238
|
-
|
|
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));
|
|
239
486
|
const startedAt = Date.now();
|
|
240
487
|
try {
|
|
241
488
|
const raw = await getData(ctx, init.params);
|
|
@@ -243,17 +490,28 @@ function handleMessage(msg) {
|
|
|
243
490
|
const data = normalizeResultData(raw);
|
|
244
491
|
const count = typeof raw?.count === "number" ? raw.count : data.length;
|
|
245
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);
|
|
246
497
|
const result = {
|
|
247
498
|
type: "result",
|
|
248
499
|
data,
|
|
249
500
|
count,
|
|
250
501
|
executedQueries,
|
|
251
502
|
executionTimeMs,
|
|
252
|
-
sampleRows
|
|
503
|
+
sampleRows,
|
|
504
|
+
analysis,
|
|
505
|
+
analysisError,
|
|
506
|
+
components,
|
|
507
|
+
componentsError
|
|
253
508
|
};
|
|
254
|
-
send(result);
|
|
255
|
-
|
|
256
|
-
|
|
509
|
+
const flushed = send(result);
|
|
510
|
+
if (flushed) {
|
|
511
|
+
process.exit(0);
|
|
512
|
+
} else {
|
|
513
|
+
process.stdout.once("drain", () => process.exit(0));
|
|
514
|
+
}
|
|
257
515
|
} catch (err) {
|
|
258
516
|
const e = err;
|
|
259
517
|
sendError(e.message || String(err), "runtime", e.stack);
|