@oxy-hq/sdk 2.3.0 → 2.4.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.
package/dist/index.cjs CHANGED
@@ -1,35 +1,6 @@
1
1
  // @oxy/sdk - TypeScript SDK for Oxy data platform
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
- //#region \0rolldown/runtime.js
4
- var __create = Object.create;
5
- var __defProp = Object.defineProperty;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __getProtoOf = Object.getPrototypeOf;
9
- var __hasOwnProp = Object.prototype.hasOwnProperty;
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
13
- key = keys[i];
14
- if (!__hasOwnProp.call(to, key) && key !== except) {
15
- __defProp(to, key, {
16
- get: ((k) => from[k]).bind(null, key),
17
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
- });
19
- }
20
- }
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
25
- value: mod,
26
- enumerable: true
27
- }) : target, mod));
28
-
29
- //#endregion
30
- let react = require("react");
31
- react = __toESM(react, 1);
32
- let react_jsx_runtime = require("react/jsx-runtime");
3
+ const require_react = require('./react-B7Blpmt7.cjs');
33
4
 
34
5
  //#region src/anomalies.ts
35
6
  /**
@@ -111,46 +82,6 @@ var AnomaliesClient = class {
111
82
  }
112
83
  };
113
84
 
114
- //#endregion
115
- //#region src/customer-app/logger.ts
116
- let activeLogger = createConsoleLogger();
117
- /** Replace the global logger. Pass `null` to silence everything. */
118
- function setOxyAppLogger(logger) {
119
- activeLogger = logger ?? silentLogger();
120
- }
121
- /** Used by the SDK internals; not part of the public surface. */
122
- function getOxyAppLogger() {
123
- return activeLogger;
124
- }
125
- function createConsoleLogger() {
126
- return { log(level, msg, ctx) {
127
- if (typeof console === "undefined") return;
128
- const prefix = "[oxy-app]";
129
- const args = ctx ? [
130
- prefix,
131
- msg,
132
- ctx
133
- ] : [prefix, msg];
134
- switch (level) {
135
- case "debug":
136
- console.debug(...args);
137
- break;
138
- case "info":
139
- console.info(...args);
140
- break;
141
- case "warn":
142
- console.warn(...args);
143
- break;
144
- case "error":
145
- console.error(...args);
146
- break;
147
- }
148
- } };
149
- }
150
- function silentLogger() {
151
- return { log() {} };
152
- }
153
-
154
85
  //#endregion
155
86
  //#region src/customer-app/debug.ts
156
87
  /**
@@ -160,7 +91,7 @@ function silentLogger() {
160
91
  * console at info level.
161
92
  */
162
93
  async function getCustomerAppDebug(resolved) {
163
- const log = getOxyAppLogger();
94
+ const log = require_react.getOxyAppLogger();
164
95
  const { apiBaseUrl, orgSlug, appSlug } = resolved;
165
96
  const url = `${apiBaseUrl}/api/customer-apps/${encodeURIComponent(orgSlug)}/${encodeURIComponent(appSlug)}/debug`;
166
97
  log.log("debug", "fetching debug snapshot", { url });
@@ -174,2065 +105,6 @@ async function getCustomerAppDebug(resolved) {
174
105
  return snapshot;
175
106
  }
176
107
 
177
- //#endregion
178
- //#region src/customer-app/errors.ts
179
- /**
180
- * Error thrown by all customer-app hooks when an API call returns a
181
- * non-2xx response. Carries the structured `code` + `hint` the server
182
- * emits so bundle UIs can render an actionable message instead of
183
- * "404: { ...json... }".
184
- */
185
- var OxyApiError = class extends Error {
186
- constructor(opts) {
187
- const base = opts.message || `HTTP ${opts.status}`;
188
- const code = opts.code ? ` [${opts.code}]` : "";
189
- const hint = opts.hint ? `\n\n${opts.hint}` : "";
190
- super(`${base}${code}${hint}`);
191
- this.name = "OxyApiError";
192
- this.status = opts.status;
193
- this.code = opts.code ?? null;
194
- this.hint = opts.hint ?? null;
195
- }
196
- };
197
- /**
198
- * Read a non-2xx response from oxy and return an `OxyApiError`.
199
- * Parses the JSON envelope when present; falls back to raw text
200
- * (truncated to 240 chars so a runaway HTML error page doesn't
201
- * dominate the bundle UI).
202
- */
203
- async function apiErrorFromResponse(resp) {
204
- let body;
205
- let raw = "";
206
- try {
207
- raw = await resp.text();
208
- body = raw ? JSON.parse(raw) : void 0;
209
- } catch {}
210
- if (body && typeof body === "object") {
211
- const b = body;
212
- return new OxyApiError({
213
- status: resp.status,
214
- message: typeof b.message === "string" ? b.message : `HTTP ${resp.status}`,
215
- code: typeof b.code === "string" ? b.code : null,
216
- hint: typeof b.hint === "string" ? b.hint : null
217
- });
218
- }
219
- const snippet = raw.length > 240 ? `${raw.slice(0, 237)}…` : raw;
220
- return new OxyApiError({
221
- status: resp.status,
222
- message: snippet || `HTTP ${resp.status}`
223
- });
224
- }
225
- const ARCH_DOC = "internal-docs/customer-apps.md";
226
- /** Interpret a thrown error as a structured report for UI display. */
227
- function interpretCustomerAppError(err) {
228
- const message = err instanceof Error ? err.message : String(err);
229
- if (/Failed to load oxy-app\.json.*HTTP 404/.test(message)) return {
230
- title: "Manifest not found",
231
- message,
232
- hint: "The bundle is being served, but oxy-app.json was not. Check that public/oxy-app.json is committed in the customer-app repo and that the build copied it into the static output. If you're using Next.js, anything under public/ is auto-copied to out/.",
233
- docs: ARCH_DOC
234
- };
235
- if (/Failed to load oxy-app\.json/.test(message)) return {
236
- title: "Manifest could not be loaded",
237
- message,
238
- hint: "Network error fetching the manifest. Confirm the bundle is being served from a path that matches OXY_APP_BASE_PATH at build time — a mismatch causes assets and the manifest to 404.",
239
- docs: ARCH_DOC
240
- };
241
- if (/schemaVersion/i.test(message)) return {
242
- title: "Manifest schema mismatch",
243
- message,
244
- hint: "This bundle was built against a different version of the data-product contract than the SDK it ships. Rebuild the bundle with a compatible @oxy-hq/sdk version.",
245
- docs: ARCH_DOC
246
- };
247
- if (/^401:/m.test(message)) return {
248
- title: "Session expired",
249
- message,
250
- hint: "Reload the page to re-authenticate via oxy's session cookie.",
251
- docs: ARCH_DOC
252
- };
253
- if (/^403:.*origin not allowed/im.test(message)) return {
254
- title: "Request origin not allowed",
255
- message,
256
- hint: "The bundle's host isn't in oxy's OXY_ALLOWED_ORIGINS. Production: add the bundle's serving origin to the env var. Local dev: oxy auto-allows http://localhost:5173 and :5174.",
257
- docs: ARCH_DOC
258
- };
259
- if (/^403:.*not a member/im.test(message)) return {
260
- title: "Access denied",
261
- message,
262
- hint: "Your account isn't a member of the org that owns this project. Ask an org owner to add you.",
263
- docs: ARCH_DOC
264
- };
265
- if (/^403:.*SELECT.*WITH/im.test(message)) return {
266
- title: "Query rejected — read-only endpoint",
267
- message,
268
- hint: "This proxy only runs SELECT or WITH queries. Mutations (INSERT/UPDATE/DELETE/DROP) are not allowed from customer-app bundles.",
269
- docs: ARCH_DOC
270
- };
271
- if (/^403:/m.test(message)) return {
272
- title: "Access denied",
273
- message,
274
- hint: "The request was rejected by the server. Check the oxy server logs for details.",
275
- docs: ARCH_DOC
276
- };
277
- if (/^404:/m.test(message) && /project/i.test(message)) return {
278
- title: "Project not found",
279
- message,
280
- hint: "The projectId in oxy-app.json doesn't match any registered project. Confirm the manifest's projectId is a real UUID for this deployment.",
281
- docs: ARCH_DOC
282
- };
283
- if (/^400:.*sql.*must be non-empty/im.test(message)) return {
284
- title: "Empty SQL",
285
- message,
286
- hint: "useQuery was called with an empty or whitespace-only `sql`. Pass a real query, or set `enabled: false` to skip the call.",
287
- docs: ARCH_DOC
288
- };
289
- if (/^400:/m.test(message) && /query failed/i.test(message)) return {
290
- title: "Query failed",
291
- message,
292
- hint: "The SQL ran but the warehouse rejected it. Full error in the oxy server logs (look for the projects::query span).",
293
- docs: ARCH_DOC
294
- };
295
- if (/^502:/m.test(message)) return {
296
- title: "Warehouse unreachable",
297
- message,
298
- hint: "Oxy couldn't reach the configured database. Check connector config + warehouse health.",
299
- docs: ARCH_DOC
300
- };
301
- if (/Unexpected token '<'|<!doctype/i.test(message)) return {
302
- title: "Fetched HTML where JSON was expected",
303
- message,
304
- hint: "Most likely the built bundle is stale — built against an old SDK whose endpoints no longer exist on the server. Rebuild the bundle (vite build) with @oxy-hq/sdk@^2.0.0 and reload. If the bundle is current, check that OXY_APP_BASE_PATH matches the path the customer-app row is served at.",
305
- docs: ARCH_DOC
306
- };
307
- return {
308
- title: "Unexpected error loading the dashboard",
309
- message,
310
- hint: "Check the browser console for the full stack trace, and the oxy server logs for the corresponding request.",
311
- docs: ARCH_DOC
312
- };
313
- }
314
-
315
- //#endregion
316
- //#region src/customer-app/inject.ts
317
- /**
318
- * Read the runtime app-config oxy injected at serve time. Returns
319
- * `undefined` outside the browser or when the global isn't set
320
- * (`pnpm dev` against a non-oxy server, etc. — manifest hints are
321
- * the fallback).
322
- */
323
- function readInjectedAppConfig() {
324
- if (typeof window === "undefined") return void 0;
325
- return window.__OXY_APP__;
326
- }
327
-
328
- //#endregion
329
- //#region src/customer-app/manifest.ts
330
- let cached = null;
331
- /**
332
- * Load + validate the manifest. Cached after the first call so callers
333
- * can invoke this from every component without coordinating.
334
- */
335
- function loadCustomerAppManifest(options = {}) {
336
- if (!cached) cached = fetchAndValidate(options);
337
- return cached;
338
- }
339
- /** For tests: reset the cache between runs. */
340
- function _resetCustomerAppManifestCacheForTest() {
341
- cached = null;
342
- }
343
- async function fetchAndValidate(options) {
344
- const log = getOxyAppLogger();
345
- const injected = readInjectedAppConfig();
346
- const manifestUrl = options.manifestUrl ?? defaultManifestUrl(injected);
347
- log.log("info", "loading manifest", {
348
- manifestUrl,
349
- injectionPresent: !!injected,
350
- orgSlug: injected?.orgSlug,
351
- appSlug: injected?.slug,
352
- appId: injected?.appId
353
- });
354
- const startedAt = Date.now();
355
- const res = await fetch(manifestUrl, { credentials: "same-origin" });
356
- if (!res.ok) {
357
- log.log("error", "manifest fetch failed", {
358
- manifestUrl,
359
- status: res.status,
360
- statusText: res.statusText
361
- });
362
- throw new Error(`Failed to load oxy-app.json from ${manifestUrl} (HTTP ${res.status}). The customer-app repo must commit this file alongside the bundle.`);
363
- }
364
- const manifest = validateManifest(await res.json(), manifestUrl);
365
- const resolved = {
366
- manifest,
367
- productNames: [],
368
- orgSlug: injected?.orgSlug ?? "",
369
- appSlug: injected?.slug ?? "",
370
- apiBaseUrl: injected?.apiBaseUrl || "",
371
- appId: injected?.appId,
372
- projectId: injected?.projectId ?? manifest.projectId
373
- };
374
- log.log("info", "manifest ready", {
375
- durationMs: Date.now() - startedAt,
376
- schemaVersion: manifest.schemaVersion,
377
- slug: manifest.slug
378
- });
379
- return resolved;
380
- }
381
- /**
382
- * Default manifest URL.
383
- *
384
- * Resolution order (bundler-agnostic):
385
- * 1. `window.__OXY_APP__.orgSlug`/`slug` injection → the canonical
386
- * `/customer-apps/<org>/<app>/oxy-app.json`. Works for every
387
- * bundle oxy serves regardless of how it was built.
388
- * 2. `NEXT_PUBLIC_APP_BASE_PATH` env var — kept for backward compat
389
- * with Next.js bundles that bake basePath at build time.
390
- * 3. Empty basePath → `/oxy-app.json` (only matches when running in
391
- * a `vite dev` / `next dev` root mount; will 404 under oxy).
392
- */
393
- function defaultManifestUrl(injected) {
394
- if (injected?.orgSlug && injected?.slug) return `/customer-apps/${encodeURIComponent(injected.orgSlug)}/${encodeURIComponent(injected.slug)}/oxy-app.json`;
395
- return "/oxy-app.json";
396
- }
397
- /**
398
- * Validate a v2 manifest. Required: schemaVersion === 2, slug (non-empty).
399
- * Optional: name (display), orgSlug (dev-time hint for the admin dialog),
400
- * projectId (dev-time hint when there's no server-side injection).
401
- *
402
- * At serve time, oxy's identity injection (window.__OXY_APP__) overrides
403
- * the manifest's orgSlug/projectId — the manifest fields are advisory.
404
- */
405
- function validateManifest(raw, url) {
406
- if (!isRecord(raw)) throw new Error(`Manifest at ${url} is not a JSON object`);
407
- if (raw.schemaVersion !== 2) throw new Error(`oxy-app.json: schemaVersion must be 2 (got ${JSON.stringify(raw.schemaVersion)}). v1 manifests are no longer supported — upgrade to the identity-only shape.`);
408
- if (raw.products !== void 0 || raw.writers !== void 0) throw new Error(`oxy-app.json is schemaVersion 2 (identity-only); \`products\` and \`writers\` are no longer supported`);
409
- if (typeof raw.slug !== "string" || !raw.slug.trim()) throw new Error("oxy-app.json: `slug` is required and must be a non-empty string");
410
- return {
411
- schemaVersion: 2,
412
- name: typeof raw.name === "string" ? raw.name : void 0,
413
- slug: raw.slug,
414
- orgSlug: typeof raw.orgSlug === "string" ? raw.orgSlug : void 0,
415
- projectId: typeof raw.projectId === "string" ? raw.projectId : void 0,
416
- functions: raw.functions !== void 0 ? validateFunctions(raw.functions) : void 0
417
- };
418
- }
419
- const FUNCTION_NAME_RE = /^[a-z][a-z0-9-]{0,63}$/;
420
- /**
421
- * Validate the optional `functions` map. Each key is a function name;
422
- * each value declares how the function is invoked. Mirrors the
423
- * server-side validation in `customer_apps_publish.rs` so a bad
424
- * manifest fails at build, not at publish.
425
- */
426
- function validateFunctions(raw) {
427
- if (!isRecord(raw)) throw new Error("oxy-app.json: `functions` must be an object keyed by function name");
428
- const out = {};
429
- for (const [fnName, value] of Object.entries(raw)) {
430
- if (!FUNCTION_NAME_RE.test(fnName)) throw new Error(`oxy-app.json: function name "${fnName}" must match ^[a-z][a-z0-9-]{0,63}$`);
431
- if (!isRecord(value)) throw new Error(`oxy-app.json: function "${fnName}" must be an object`);
432
- const fn = {};
433
- if (value.entry !== void 0) {
434
- if (typeof value.entry !== "string" || !value.entry.trim()) throw new Error(`oxy-app.json: function "${fnName}" \`entry\` must be a non-empty string`);
435
- fn.entry = value.entry;
436
- }
437
- if (value.schedule !== void 0) {
438
- if (typeof value.schedule !== "string" || !value.schedule.trim()) throw new Error(`oxy-app.json: function "${fnName}" \`schedule\` must be a cron string`);
439
- fn.schedule = value.schedule;
440
- }
441
- if (value.timezone !== void 0) {
442
- if (typeof value.timezone !== "string") throw new Error(`oxy-app.json: function "${fnName}" \`timezone\` must be a string`);
443
- fn.timezone = value.timezone;
444
- }
445
- if (value.route !== void 0) {
446
- if (typeof value.route !== "boolean") throw new Error(`oxy-app.json: function "${fnName}" \`route\` must be a boolean`);
447
- fn.route = value.route;
448
- }
449
- if (value.airwayStep !== void 0) {
450
- const step = value.airwayStep;
451
- if (!isRecord(step) || typeof step.pipeline !== "string" || typeof step.resource !== "string") throw new Error(`oxy-app.json: function "${fnName}" \`airwayStep\` must be { pipeline, resource }`);
452
- fn.airwayStep = {
453
- pipeline: step.pipeline,
454
- resource: step.resource
455
- };
456
- }
457
- if (value.timeoutSeconds !== void 0) {
458
- const t = value.timeoutSeconds;
459
- if (typeof t !== "number" || !Number.isInteger(t) || t < 1 || t > 300) throw new Error(`oxy-app.json: function "${fnName}" \`timeoutSeconds\` must be an integer in [1, 300]`);
460
- fn.timeoutSeconds = t;
461
- }
462
- if (value.cache !== void 0) {
463
- const c = value.cache;
464
- if (!isRecord(c)) throw new Error(`oxy-app.json: function "${fnName}" \`cache\` must be an object`);
465
- if (c.ttlSeconds !== void 0) {
466
- const ttl = c.ttlSeconds;
467
- if (typeof ttl !== "number" || !Number.isInteger(ttl) || ttl < 1) throw new Error(`oxy-app.json: function "${fnName}" \`cache.ttlSeconds\` must be a positive integer`);
468
- fn.cache = { ttlSeconds: ttl };
469
- }
470
- }
471
- if (value.retries !== void 0) {
472
- const r = value.retries;
473
- if (!isRecord(r)) throw new Error(`oxy-app.json: function "${fnName}" \`retries\` must be an object`);
474
- const retries = {};
475
- for (const key of [
476
- "maxAttempts",
477
- "minTimeoutMs",
478
- "maxTimeoutMs"
479
- ]) {
480
- const n = r[key];
481
- if (n !== void 0) {
482
- if (typeof n !== "number" || !Number.isInteger(n) || n < 1) throw new Error(`oxy-app.json: function "${fnName}" \`retries.${key}\` must be a positive integer`);
483
- retries[key] = n;
484
- }
485
- }
486
- fn.retries = retries;
487
- }
488
- if (value.inputExample !== void 0) fn.inputExample = value.inputExample;
489
- const hasSchedule = fn.schedule !== void 0;
490
- const hasAirway = fn.airwayStep !== void 0;
491
- if (!(fn.route ?? !(hasSchedule || hasAirway)) && !hasSchedule && !hasAirway) throw new Error(`oxy-app.json: function "${fnName}" must enable at least one of route/schedule/airwayStep`);
492
- out[fnName] = fn;
493
- }
494
- return out;
495
- }
496
- function isRecord(v) {
497
- return typeof v === "object" && v !== null && !Array.isArray(v);
498
- }
499
-
500
- //#endregion
501
- //#region src/customer-app/function-invoke.ts
502
- const inflight$1 = /* @__PURE__ */ new Map();
503
- /**
504
- * Dedup key for an invocation: function name + its (stable-serialized) body,
505
- * joined by a newline. Function names are `[a-z][a-z0-9-]*` (no newline), so
506
- * the separator can never collide with a name.
507
- */
508
- function functionInvokeKey(name, body) {
509
- return `${name}\n${JSON.stringify(body ?? {})}`;
510
- }
511
- /**
512
- * Run `run()` unless an identical invocation is already in flight, in which
513
- * case share its promise. The entry is removed once the promise settles — so
514
- * this dedups concurrency only, it does NOT memoize the result.
515
- */
516
- function sharedFunctionInvoke(key, run) {
517
- const existing = inflight$1.get(key);
518
- if (existing) return existing;
519
- const p = run().finally(() => {
520
- inflight$1.delete(key);
521
- });
522
- inflight$1.set(key, p);
523
- return p;
524
- }
525
-
526
- //#endregion
527
- //#region src/customer-app/function-sse.ts
528
- /**
529
- * Read a `text/event-stream` function response to completion. Resolves with the
530
- * decoded result + captured logs, or rejects (with `.logs` attached) on an
531
- * `event: error` frame / a stream that ends without a terminal event.
532
- */
533
- async function readFunctionSseStream(resp) {
534
- const reader = resp.body?.getReader();
535
- if (!reader) throw new Error("function response has no body stream");
536
- const decoder = new TextDecoder();
537
- let buffer = "";
538
- let dataPayload = "";
539
- const logs = [];
540
- const handleFrame = (frame) => {
541
- let event = "message";
542
- let data = "";
543
- for (const line of frame.split("\n")) if (line.startsWith("event:")) event = line.slice(6).trim();
544
- else if (line.startsWith("data:")) data += line.slice(5).trim();
545
- if (event === "log") try {
546
- const l = JSON.parse(data);
547
- logs.push({
548
- level: String(l.level ?? "info"),
549
- message: String(l.message ?? "")
550
- });
551
- } catch {}
552
- else if (event === "data") dataPayload = data;
553
- else if (event === "done") return {
554
- done: true,
555
- value: dataPayload ? JSON.parse(dataPayload) : null
556
- };
557
- else if (event === "error") {
558
- const payload = data ? JSON.parse(data) : {};
559
- const err = new Error(payload.message || payload.error || "function invocation failed");
560
- err.name = payload.error || "FunctionError";
561
- err.logs = logs;
562
- throw err;
563
- }
564
- };
565
- for (;;) {
566
- const { done, value } = await reader.read();
567
- if (done) break;
568
- buffer += decoder.decode(value, { stream: true });
569
- let sep;
570
- while ((sep = buffer.indexOf("\n\n")) !== -1) {
571
- const frame = buffer.slice(0, sep);
572
- buffer = buffer.slice(sep + 2);
573
- const result = handleFrame(frame);
574
- if (result) return {
575
- value: result.value,
576
- logs
577
- };
578
- }
579
- }
580
- throw new Error("function stream ended without a terminal event");
581
- }
582
-
583
- //#endregion
584
- //#region src/customer-app/interpolate.ts
585
- /**
586
- * Interpolate `{{ params.X }}` and `{{ params.X | sqlquote }}` placeholders
587
- * in a SQL template.
588
- *
589
- * - `{{ params.X | sqlquote }}` — quote strings ('foo'), pass numbers and
590
- * booleans raw, nullish becomes NULL. Mirrors the server's Jinja sqlquote
591
- * filter.
592
- * - `{{ params.X }}` — raw pass-through. Used for already-trusted values
593
- * (numbers, identifiers the caller has validated). Caller is responsible
594
- * for safety.
595
- *
596
- * Not a security boundary. The server still gates SQL execution by
597
- * project membership. Bundles that accept untrusted user input should
598
- * use `| sqlquote` or validate/coerce before passing.
599
- */
600
- function interpolateSqlParams(sql, params) {
601
- return sql.replace(/\{\{\s*params\.([a-zA-Z0-9_]+)(\s*\|\s*sqlquote)?\s*\}\}/g, (_match, key, sqlquote) => {
602
- const v = params[key];
603
- if (v === null || v === void 0) return "NULL";
604
- if (sqlquote) {
605
- if (typeof v === "number" || typeof v === "boolean") return String(v);
606
- return `'${String(v).replace(/'/g, "''")}'`;
607
- }
608
- return String(v);
609
- });
610
- }
611
-
612
- //#endregion
613
- //#region src/customer-app/markdown.ts
614
- /**
615
- * Allowlist for `[text](url)` href values in agent-emitted markdown.
616
- * Markdown comes from an LLM, which sits across an external trust
617
- * boundary — without this filter, a `javascript:` URL produced by
618
- * the model would render as a clickable XSS in the bundle's origin.
619
- *
620
- * Accepts:
621
- * - http(s):// absolute URLs
622
- * - mailto: addresses
623
- * - root-relative paths (`/foo`)
624
- * - same-page fragments (`#section`)
625
- *
626
- * Rejects everything else, including `javascript:`, `data:`,
627
- * protocol-relative `//evil.com`, and any other scheme. Comparison
628
- * is case-insensitive after stripping leading whitespace + ASCII
629
- * control bytes (browsers strip these before scheme resolution, so
630
- * `java\tscript:` would otherwise slip past a naive prefix check).
631
- */
632
- function isSafeLinkHref(raw) {
633
- let cleaned = "";
634
- for (let i = 0; i < raw.length; i++) {
635
- const cc = raw.charCodeAt(i);
636
- if (cc > 32 && cc !== 127) cleaned += raw[i];
637
- }
638
- if (cleaned === "") return false;
639
- if (cleaned.startsWith("#") || cleaned.startsWith("/")) {
640
- if (cleaned.startsWith("//")) return false;
641
- return true;
642
- }
643
- const lower = cleaned.toLowerCase();
644
- return lower.startsWith("http://") || lower.startsWith("https://") || lower.startsWith("mailto:");
645
- }
646
-
647
- //#endregion
648
- //#region src/customer-app/query-cache.ts
649
- const SWR_TTL_MS = 3e4;
650
- const inflight = /* @__PURE__ */ new Map();
651
- const cache = /* @__PURE__ */ new Map();
652
- function queryKey(projectId, db, sql) {
653
- return `${projectId} ${db ?? ""} ${sql}`;
654
- }
655
- function getCached(projectId, sql, db) {
656
- const e = cache.get(queryKey(projectId, db, sql));
657
- return e && Date.now() - e.at < SWR_TTL_MS ? e.data : void 0;
658
- }
659
- /** Fetch with in-flight dedup + cache. `force` bypasses the fresh-cache
660
- * short-circuit (used by refetch) but still dedupes a concurrent in-flight. */
661
- async function sharedQuery(fetcher, projectId, sql, db, opts = {}) {
662
- const key = queryKey(projectId, db, sql);
663
- if (!opts.force) {
664
- const fresh = getCached(projectId, sql, db);
665
- if (fresh) return fresh;
666
- }
667
- const existing = inflight.get(key);
668
- if (existing) return existing;
669
- const body = JSON.stringify({
670
- sql,
671
- ...db ? { database: db } : {}
672
- });
673
- const p = (async () => {
674
- const resp = await fetcher(`/api/projects/${projectId}/query`, {
675
- method: "POST",
676
- headers: { "content-type": "application/json" },
677
- body
678
- });
679
- if (!resp.ok) throw await apiErrorFromResponse(resp);
680
- const data = await resp.json();
681
- cache.set(key, {
682
- at: Date.now(),
683
- data
684
- });
685
- return data;
686
- })().finally(() => inflight.delete(key));
687
- inflight.set(key, p);
688
- return p;
689
- }
690
-
691
- //#endregion
692
- //#region src/customer-app/react.tsx
693
- function defaultFetcher(input, init) {
694
- return fetch(input, {
695
- credentials: "include",
696
- ...init
697
- });
698
- }
699
- const OxyAppContext = react.createContext(void 0);
700
- /**
701
- * Top-level provider. Loads the manifest once on mount; children only
702
- * render after the manifest is ready (or the error fallback fires).
703
- */
704
- function OxyAppProvider(props) {
705
- const { manifestOptions, fallback, errorFallback, fetcher: fetcherProp, children } = props;
706
- const fetcher = fetcherProp ?? defaultFetcher;
707
- const [state, setState] = react.useState({
708
- status: "loading",
709
- fetcher
710
- });
711
- react.useEffect(() => {
712
- let cancelled = false;
713
- loadCustomerAppManifest(manifestOptions).then((resolved) => {
714
- if (!cancelled) setState({
715
- status: "ready",
716
- resolved,
717
- fetcher
718
- });
719
- }).catch((e) => {
720
- if (!cancelled) setState({
721
- status: "error",
722
- error: interpretCustomerAppError(e),
723
- fetcher
724
- });
725
- });
726
- return () => {
727
- cancelled = true;
728
- };
729
- }, [manifestOptions, fetcher]);
730
- if (state.status === "error" && state.error) {
731
- const err = state.error;
732
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OxyAppContext.Provider, {
733
- value: state,
734
- children: errorFallback ? errorFallback(err) : defaultErrorFallback(err)
735
- });
736
- }
737
- if (state.status === "loading") return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OxyAppContext.Provider, {
738
- value: state,
739
- children: fallback ?? null
740
- });
741
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OxyAppContext.Provider, {
742
- value: state,
743
- children
744
- });
745
- }
746
- function defaultErrorFallback(err) {
747
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
748
- style: {
749
- margin: "2rem auto",
750
- maxWidth: "640px",
751
- padding: "1rem",
752
- border: "1px solid #fca5a5",
753
- background: "#fee2e2",
754
- color: "#991b1b",
755
- borderRadius: "8px",
756
- fontFamily: "system-ui, -apple-system, sans-serif",
757
- fontSize: "14px"
758
- },
759
- children: [
760
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
761
- style: { fontWeight: 600 },
762
- children: err.title
763
- }),
764
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
765
- style: {
766
- fontSize: "12px",
767
- marginTop: "4px"
768
- },
769
- children: err.message
770
- }),
771
- /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
772
- style: { marginTop: "12px" },
773
- children: [
774
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "What to try:" }),
775
- " ",
776
- err.hint
777
- ]
778
- })
779
- ]
780
- });
781
- }
782
- /**
783
- * Emit a one-time `console.warn` the first time a beta hook is
784
- * used in a given page load. Bundles upgrading from a future GA
785
- * release won't see the warning; the message lets us flag rough
786
- * edges without breaking the build.
787
- */
788
- const _warnedBeta = /* @__PURE__ */ new Set();
789
- function warnBetaOnce(name) {
790
- if (_warnedBeta.has(name)) return;
791
- _warnedBeta.add(name);
792
- if (typeof console !== "undefined" && typeof console.warn === "function") console.warn(`[@oxy-hq/sdk] \`${name}\` is in beta — interface and behavior may change. See https://github.com/oxy-hq/customer-apps for caveats and the migration guide.`);
793
- }
794
- /**
795
- * Read the resolved manifest from context. Throws if called outside
796
- * `<OxyAppProvider>` — that's a programmer error worth surfacing
797
- * loudly, not silently swallowing.
798
- */
799
- function useResolvedManifest() {
800
- const ctx = react.useContext(OxyAppContext);
801
- if (!ctx) throw new Error("useResolvedManifest must be called inside <OxyAppProvider>");
802
- if (ctx.status !== "ready" || !ctx.resolved) throw new Error("useResolvedManifest called before manifest finished loading. Use the provider's `fallback` prop to render while loading.");
803
- return ctx.resolved;
804
- }
805
- /**
806
- * Low-level hook that returns the raw context value (including the
807
- * fetcher). Prefer `useResolvedManifest` for manifest access; use
808
- * this only when you need the fetcher or projectId without requiring
809
- * the manifest to be ready (e.g. inside `useQuery`).
810
- */
811
- function useOxyApp() {
812
- const ctx = react.useContext(OxyAppContext);
813
- if (!ctx) throw new Error("useOxyApp must be called inside <OxyAppProvider>");
814
- return {
815
- projectId: ctx.resolved?.projectId,
816
- fetcher: ctx.fetcher
817
- };
818
- }
819
- /**
820
- * Execute an ad-hoc SQL query against the project linked to this
821
- * customer app. The query is specified inline by the caller; no
822
- * manifest declaration is involved.
823
- *
824
- * Re-runs whenever `input` or enabled `params` change. Use the
825
- * `enabled` option to defer the first fetch until required data is
826
- * available (e.g. a user-supplied filter value).
827
- */
828
- function useQuery(input, opts = {}) {
829
- const { projectId, fetcher } = useOxyApp();
830
- const enabled = opts.enabled !== false;
831
- const paramsKey = JSON.stringify(opts.params);
832
- const sqlWithParams = react.useMemo(() => interpolateSqlParams(input.sql, opts.params ?? {}), [input.sql, paramsKey]);
833
- const [state, setState] = react.useState({
834
- rows: [],
835
- columns: [],
836
- loading: enabled && !!projectId,
837
- error: null
838
- });
839
- const [nonce, setNonce] = react.useState(0);
840
- react.useEffect(() => {
841
- if (!enabled || !projectId) {
842
- setState((s) => s.loading ? {
843
- ...s,
844
- loading: false
845
- } : s);
846
- return;
847
- }
848
- let cancelled = false;
849
- const cached = getCached(projectId, sqlWithParams, input.database);
850
- if (cached && nonce === 0) {
851
- const { columns, rows } = cached;
852
- const objects = rows.map((r) => Object.fromEntries(columns.map((c, i) => [c, r[i]])));
853
- setState({
854
- rows: objects,
855
- columns,
856
- loading: false,
857
- error: null
858
- });
859
- return;
860
- }
861
- setState((s) => ({
862
- ...s,
863
- loading: true,
864
- error: null
865
- }));
866
- sharedQuery(fetcher, projectId, sqlWithParams, input.database, { force: nonce > 0 }).then(({ columns, rows }) => {
867
- if (cancelled) return;
868
- const objects = rows.map((r) => Object.fromEntries(columns.map((c, i) => [c, r[i]])));
869
- setState({
870
- rows: objects,
871
- columns,
872
- loading: false,
873
- error: null
874
- });
875
- }).catch((err) => {
876
- if (cancelled) return;
877
- setState((s) => ({
878
- ...s,
879
- loading: false,
880
- error: err instanceof Error ? err : new Error(String(err))
881
- }));
882
- });
883
- return () => {
884
- cancelled = true;
885
- };
886
- }, [
887
- enabled,
888
- projectId,
889
- sqlWithParams,
890
- input.database,
891
- nonce,
892
- fetcher
893
- ]);
894
- return {
895
- rows: state.rows,
896
- columns: state.columns,
897
- loading: state.loading,
898
- error: state.error,
899
- refetch: () => setNonce((n) => n + 1)
900
- };
901
- }
902
- /**
903
- * Imperative hook for invoking an Oxy Function by name.
904
- *
905
- * ```tsx
906
- * const refresh = useFunction("refresh-sales");
907
- * <button disabled={refresh.isLoading} onClick={() => refresh.invoke({ full: true })}>
908
- * Refresh
909
- * </button>
910
- * ```
911
- */
912
- function useFunction(name) {
913
- const ctx = react.useContext(OxyAppContext);
914
- if (!ctx) throw new Error("useFunction must be called inside <OxyAppProvider>");
915
- const fetcher = ctx.fetcher;
916
- const resolved = ctx.resolved;
917
- const [state, setState] = react.useState({
918
- data: null,
919
- isLoading: false,
920
- error: null,
921
- logs: []
922
- });
923
- return {
924
- invoke: react.useCallback(async (body, opts) => {
925
- if (!resolved) throw new Error("useFunction.invoke called before the manifest finished loading. Render behind the provider's `fallback` until ready.");
926
- const { orgSlug, appSlug, apiBaseUrl } = resolved;
927
- const url = `${apiBaseUrl || ""}/customer-apps/${encodeURIComponent(orgSlug)}/${encodeURIComponent(appSlug)}/fn/${encodeURIComponent(name)}`;
928
- setState((s) => ({
929
- ...s,
930
- isLoading: true,
931
- error: null
932
- }));
933
- try {
934
- const headers = {
935
- "content-type": "application/json",
936
- accept: "text/event-stream"
937
- };
938
- if (opts?.idempotencyKey) headers["idempotency-key"] = opts.idempotencyKey;
939
- const result = await sharedFunctionInvoke(functionInvokeKey(name, body), async () => {
940
- const resp = await fetcher(url, {
941
- method: "POST",
942
- headers,
943
- body: JSON.stringify(body ?? {})
944
- });
945
- if (!resp.ok && resp.status !== 200) throw await apiErrorFromResponse(resp);
946
- return readFunctionSseStream(resp);
947
- });
948
- setState({
949
- data: result.value,
950
- isLoading: false,
951
- error: null,
952
- logs: result.logs
953
- });
954
- return result.value;
955
- } catch (err) {
956
- const e = err instanceof Error ? err : new Error(String(err));
957
- const logs = e.logs ?? [];
958
- setState((s) => ({
959
- ...s,
960
- isLoading: false,
961
- error: e,
962
- logs
963
- }));
964
- throw e;
965
- }
966
- }, [
967
- resolved,
968
- fetcher,
969
- name
970
- ]),
971
- data: state.data,
972
- isLoading: state.isLoading,
973
- error: state.error,
974
- logs: state.logs
975
- };
976
- }
977
- /**
978
- * Run a semantic-layer query against the project's `.view.yml` /
979
- * `.topic.yml` definitions. The server compiles to SQL and executes
980
- * through the same connector path as `useQuery`, so result shape
981
- * matches.
982
- *
983
- * Re-runs whenever the input shape changes (deep-compared via JSON).
984
- * Use `opts.enabled = false` to defer the first fetch until required
985
- * inputs (e.g. a user-picked filter value) are available.
986
- */
987
- function useSemanticQuery(input, opts = {}) {
988
- const { projectId, fetcher } = useOxyApp();
989
- const enabled = opts.enabled !== false;
990
- const debug = opts.debug === true;
991
- const inputKey = react.useMemo(() => JSON.stringify(input), [input]);
992
- const [state, setState] = react.useState({
993
- rows: [],
994
- columns: [],
995
- truncated: false,
996
- sql: null,
997
- loading: enabled && !!projectId,
998
- error: null
999
- });
1000
- const [nonce, setNonce] = react.useState(0);
1001
- react.useEffect(() => {
1002
- if (!enabled || !projectId) {
1003
- setState((s) => s.loading ? {
1004
- ...s,
1005
- loading: false
1006
- } : s);
1007
- return;
1008
- }
1009
- const ctrl = new AbortController();
1010
- let cancelled = false;
1011
- setState((s) => ({
1012
- ...s,
1013
- loading: true,
1014
- error: null
1015
- }));
1016
- const body = JSON.stringify({
1017
- v: 1,
1018
- topic: input.topic,
1019
- dimensions: input.dimensions ?? [],
1020
- measures: input.measures ?? [],
1021
- time_dimensions: input.time_dimensions ?? [],
1022
- filters: input.filters ?? [],
1023
- ...input.limit != null ? { limit: input.limit } : {}
1024
- });
1025
- const url = `/api/projects/${projectId}/semantic-query${debug ? "?debug=1" : ""}`;
1026
- fetcher(url, {
1027
- method: "POST",
1028
- headers: { "content-type": "application/json" },
1029
- body,
1030
- signal: ctrl.signal
1031
- }).then(async (resp) => {
1032
- if (!resp.ok) throw await apiErrorFromResponse(resp);
1033
- return resp.json();
1034
- }).then(({ columns, rows, truncated, sql }) => {
1035
- if (cancelled) return;
1036
- const objects = rows.map((r) => Object.fromEntries(columns.map((c, i) => [c, r[i]])));
1037
- setState({
1038
- rows: objects,
1039
- columns,
1040
- truncated,
1041
- sql: sql ?? null,
1042
- loading: false,
1043
- error: null
1044
- });
1045
- }).catch((err) => {
1046
- if (cancelled) return;
1047
- if (err instanceof DOMException && err.name === "AbortError") return;
1048
- setState((s) => ({
1049
- ...s,
1050
- loading: false,
1051
- error: err instanceof Error ? err : new Error(String(err))
1052
- }));
1053
- });
1054
- return () => {
1055
- cancelled = true;
1056
- ctrl.abort();
1057
- };
1058
- }, [
1059
- enabled,
1060
- projectId,
1061
- inputKey,
1062
- debug,
1063
- nonce,
1064
- fetcher
1065
- ]);
1066
- return {
1067
- rows: state.rows,
1068
- columns: state.columns,
1069
- truncated: state.truncated,
1070
- sql: state.sql,
1071
- loading: state.loading,
1072
- error: state.error,
1073
- refetch: () => setNonce((n) => n + 1)
1074
- };
1075
- }
1076
- const PROCEDURE_POLL_MS = 2e3;
1077
- const PROCEDURE_BACKOFF_MS = 5e3;
1078
- const PROCEDURE_MAX_WAIT_MS = 3600 * 1e3;
1079
- /**
1080
- * @beta Long-running procedure runner. The wire shape works end-to-end
1081
- * (start → poll → cancel; runs survive server restarts via the
1082
- * `customer_app_procedure_runs` table) but a few rough edges remain
1083
- * before this is GA-ready:
1084
- *
1085
- * - Hint surfaces for `procedure_not_found` are correct but the
1086
- * procedure-discovery rules (which directories the server scans,
1087
- * case-sensitivity, branch awareness) aren't documented yet.
1088
- * - Cancellation across multi-instance deployments leans on a
1089
- * periodic sweep — fine for now, but expect occasional latency
1090
- * between `cancel()` and the run actually stopping.
1091
- * - Progress reporting requires the procedure to emit named
1092
- * steps; bundles get `progress: null` until that lands.
1093
- *
1094
- * The API surface is stable; expect breaking changes only if the
1095
- * server-side `customer_app_procedure_runs` schema changes.
1096
- */
1097
- function useProcedureRun(input, opts = {}) {
1098
- warnBetaOnce("useProcedureRun");
1099
- const { projectId, fetcher } = useOxyApp();
1100
- const pollMs = opts.pollIntervalMs ?? PROCEDURE_POLL_MS;
1101
- const backoffMs = opts.pollIntervalBackoffMs ?? PROCEDURE_BACKOFF_MS;
1102
- const maxWaitMs = opts.maxWaitMs ?? PROCEDURE_MAX_WAIT_MS;
1103
- const [state, setState] = react.useState({
1104
- state: "idle",
1105
- progress: null,
1106
- result: null,
1107
- error: null
1108
- });
1109
- const inflight = react.useRef({});
1110
- const cancel = react.useCallback(() => {
1111
- const runId = inflight.current.runId;
1112
- if (!projectId || !runId) return;
1113
- inflight.current.abort?.abort();
1114
- inflight.current.runId = void 0;
1115
- fetcher(`/api/projects/${projectId}/procedures/runs/${encodeURIComponent(runId)}/cancel`, { method: "POST" }).catch(() => {});
1116
- setState({
1117
- state: "failed",
1118
- progress: null,
1119
- result: null,
1120
- error: /* @__PURE__ */ new Error("procedure cancelled by user")
1121
- });
1122
- }, [projectId, fetcher]);
1123
- const run = react.useCallback((params) => {
1124
- if (!projectId) {
1125
- setState((s) => ({
1126
- ...s,
1127
- state: "failed",
1128
- error: /* @__PURE__ */ new Error("project not configured")
1129
- }));
1130
- return;
1131
- }
1132
- inflight.current.abort?.abort();
1133
- const ctrl = new AbortController();
1134
- inflight.current = { abort: ctrl };
1135
- setState({
1136
- state: "running",
1137
- progress: null,
1138
- result: null,
1139
- error: null
1140
- });
1141
- (async () => {
1142
- try {
1143
- const body = JSON.stringify({
1144
- v: 1,
1145
- ...params ? { params } : {}
1146
- });
1147
- const startResp = await fetcher(`/api/projects/${projectId}/procedures/${encodeURIComponent(input.procedureId)}/runs`, {
1148
- method: "POST",
1149
- headers: { "content-type": "application/json" },
1150
- body,
1151
- signal: ctrl.signal
1152
- });
1153
- if (!startResp.ok) throw await apiErrorFromResponse(startResp);
1154
- const { run_id } = await startResp.json();
1155
- inflight.current.runId = run_id;
1156
- const startedAt = Date.now();
1157
- let pollCount = 0;
1158
- while (true) {
1159
- if (ctrl.signal.aborted) return;
1160
- if (Date.now() - startedAt > maxWaitMs) throw new Error("procedure run timed out client-side");
1161
- await sleep(pollCount < 6 ? pollMs : backoffMs, ctrl.signal);
1162
- if (ctrl.signal.aborted) return;
1163
- pollCount += 1;
1164
- const pollResp = await fetcher(`/api/projects/${projectId}/procedures/runs/${encodeURIComponent(run_id)}`, {
1165
- method: "GET",
1166
- signal: ctrl.signal
1167
- });
1168
- if (!pollResp.ok) throw await apiErrorFromResponse(pollResp);
1169
- const poll = await pollResp.json();
1170
- if (poll.status === "running") {
1171
- if (poll.progress) setState((s) => ({
1172
- ...s,
1173
- progress: poll.progress ?? null
1174
- }));
1175
- continue;
1176
- }
1177
- if (poll.status === "done") {
1178
- inflight.current.runId = void 0;
1179
- setState({
1180
- state: "done",
1181
- progress: null,
1182
- result: poll.result,
1183
- error: null
1184
- });
1185
- return;
1186
- }
1187
- if (poll.status === "cancelled") {
1188
- inflight.current.runId = void 0;
1189
- setState({
1190
- state: "failed",
1191
- progress: null,
1192
- result: null,
1193
- error: /* @__PURE__ */ new Error("procedure cancelled")
1194
- });
1195
- return;
1196
- }
1197
- inflight.current.runId = void 0;
1198
- setState({
1199
- state: "failed",
1200
- progress: null,
1201
- result: null,
1202
- error: new Error(poll.error.message)
1203
- });
1204
- return;
1205
- }
1206
- } catch (e) {
1207
- if (e instanceof DOMException && e.name === "AbortError") return;
1208
- inflight.current.runId = void 0;
1209
- setState({
1210
- state: "failed",
1211
- progress: null,
1212
- result: null,
1213
- error: e instanceof Error ? e : new Error(String(e))
1214
- });
1215
- }
1216
- })();
1217
- }, [
1218
- projectId,
1219
- fetcher,
1220
- input.procedureId,
1221
- pollMs,
1222
- backoffMs,
1223
- maxWaitMs
1224
- ]);
1225
- react.useEffect(() => {
1226
- return () => {
1227
- inflight.current.abort?.abort();
1228
- };
1229
- }, []);
1230
- return {
1231
- state: state.state,
1232
- run,
1233
- cancel,
1234
- progress: state.progress,
1235
- result: state.result,
1236
- error: state.error
1237
- };
1238
- }
1239
- function useAgentRun(input) {
1240
- const { projectId, fetcher } = useOxyApp();
1241
- const [state, setState] = react.useState({
1242
- state: "idle",
1243
- events: [],
1244
- artifacts: [],
1245
- answer: null,
1246
- clarification: null,
1247
- threadId: null,
1248
- threadUrl: null,
1249
- error: null
1250
- });
1251
- const inflight = react.useRef({});
1252
- const cancel = react.useCallback(() => {
1253
- const runId = inflight.current.runId;
1254
- if (!projectId || !runId) return;
1255
- inflight.current.abort?.abort();
1256
- inflight.current.runId = void 0;
1257
- fetcher(`/api/projects/${projectId}/agents/asks/${encodeURIComponent(runId)}/cancel`, { method: "POST" }).catch(() => {});
1258
- setState((s) => ({
1259
- ...s,
1260
- state: "failed",
1261
- error: /* @__PURE__ */ new Error("agent run cancelled by user")
1262
- }));
1263
- }, [projectId, fetcher]);
1264
- const ask = react.useCallback((question, opts = {}) => {
1265
- if (!projectId) {
1266
- setState((s) => ({
1267
- ...s,
1268
- state: "failed",
1269
- error: /* @__PURE__ */ new Error("project not configured")
1270
- }));
1271
- return;
1272
- }
1273
- inflight.current.abort?.abort();
1274
- const ctrl = new AbortController();
1275
- inflight.current = { abort: ctrl };
1276
- setState({
1277
- state: "running",
1278
- events: [],
1279
- artifacts: [],
1280
- answer: null,
1281
- clarification: null,
1282
- threadId: opts.threadId ?? null,
1283
- threadUrl: opts.threadId ? `/threads/${opts.threadId}` : null,
1284
- error: null
1285
- });
1286
- (async () => {
1287
- try {
1288
- const body = JSON.stringify({
1289
- v: 1,
1290
- question,
1291
- ...opts.threadId ? { thread_id: opts.threadId } : {}
1292
- });
1293
- const startResp = await fetcher(`/api/projects/${projectId}/agents/${encodeURIComponent(input.agentId)}/asks`, {
1294
- method: "POST",
1295
- headers: { "content-type": "application/json" },
1296
- body,
1297
- signal: ctrl.signal
1298
- });
1299
- if (!startResp.ok) throw await apiErrorFromResponse(startResp);
1300
- const { run_id, thread_id, thread_url } = await startResp.json();
1301
- inflight.current.runId = run_id;
1302
- setState((s) => ({
1303
- ...s,
1304
- threadId: thread_id,
1305
- threadUrl: thread_url ?? `/threads/${thread_id}`
1306
- }));
1307
- let lastEventId = "";
1308
- let attempts = 0;
1309
- let terminated = false;
1310
- while (true) {
1311
- if (ctrl.signal.aborted) return;
1312
- if (terminated) return;
1313
- attempts += 1;
1314
- try {
1315
- await consumeSseStream({
1316
- url: `/api/projects/${projectId}/agents/runs/${encodeURIComponent(run_id)}/events`,
1317
- fetcher,
1318
- signal: ctrl.signal,
1319
- lastEventId,
1320
- onEvent: (ev) => {
1321
- if (ev.id) lastEventId = ev.id;
1322
- const data = parseSseData(ev.data);
1323
- const eventType = ev.event || "message";
1324
- const artifact = extractSqlArtifact(eventType, ev.id, data);
1325
- const token = eventType === "text_delta" && typeof data === "object" && data !== null && "token" in data ? String(data.token) : null;
1326
- setState((s) => ({
1327
- ...s,
1328
- events: [...s.events, {
1329
- type: eventType,
1330
- data
1331
- }],
1332
- artifacts: artifact ? [...s.artifacts, artifact] : s.artifacts,
1333
- answer: token !== null ? (s.answer ?? "") + token : s.answer
1334
- }));
1335
- if (ev.event === "done") {
1336
- terminated = true;
1337
- inflight.current.runId = void 0;
1338
- setState((s) => ({
1339
- ...s,
1340
- state: "done"
1341
- }));
1342
- } else if (ev.event === "failed" || ev.event === "error" || ev.event === "cancelled") {
1343
- terminated = true;
1344
- inflight.current.runId = void 0;
1345
- const message = typeof data === "object" && data !== null && "message" in data ? String(data.message) : `agent run ${ev.event}`;
1346
- setState((s) => ({
1347
- ...s,
1348
- state: "failed",
1349
- error: new Error(message)
1350
- }));
1351
- } else if (ev.event === "ask_user") {
1352
- terminated = true;
1353
- const clarification = typeof data === "object" && data !== null && "question" in data ? String(data.question) : "Agent needs clarification.";
1354
- setState((s) => ({
1355
- ...s,
1356
- state: "needs_clarification",
1357
- clarification
1358
- }));
1359
- }
1360
- }
1361
- });
1362
- } catch (err) {
1363
- if (err instanceof DOMException && err.name === "AbortError") return;
1364
- if (attempts >= 5) {
1365
- inflight.current.runId = void 0;
1366
- setState((s) => ({
1367
- ...s,
1368
- state: "failed",
1369
- error: err instanceof Error ? err : new Error(String(err))
1370
- }));
1371
- return;
1372
- }
1373
- }
1374
- if (terminated) return;
1375
- await sleep(1e3, ctrl.signal);
1376
- }
1377
- } catch (e) {
1378
- if (e instanceof DOMException && e.name === "AbortError") return;
1379
- inflight.current.runId = void 0;
1380
- setState((s) => ({
1381
- ...s,
1382
- state: "failed",
1383
- error: e instanceof Error ? e : new Error(String(e))
1384
- }));
1385
- }
1386
- })();
1387
- }, [
1388
- projectId,
1389
- fetcher,
1390
- input.agentId
1391
- ]);
1392
- react.useEffect(() => {
1393
- return () => {
1394
- inflight.current.abort?.abort();
1395
- };
1396
- }, []);
1397
- return {
1398
- state: state.state,
1399
- ask,
1400
- cancel,
1401
- events: state.events,
1402
- artifacts: state.artifacts,
1403
- answer: state.answer,
1404
- clarification: state.clarification,
1405
- threadId: state.threadId,
1406
- threadUrl: state.threadUrl,
1407
- error: state.error
1408
- };
1409
- }
1410
- /** Parsed JSON payload of an SSE `data:` line, falling back to raw
1411
- * string on parse failure. */
1412
- function parseSseData(raw) {
1413
- try {
1414
- return JSON.parse(raw);
1415
- } catch {
1416
- return raw;
1417
- }
1418
- }
1419
- /** UI event types in the analytics taxonomy that carry SQL the bundle
1420
- * may want to render alongside the answer. Each carries the same
1421
- * shape (`query` / `columns` / `rows` / `success`) so we can parse
1422
- * uniformly. New types added upstream don't surface as artifacts
1423
- * until added here — that's intentional, the renderer needs to
1424
- * know how to display each. */
1425
- const SQL_EVENT_TYPES = /* @__PURE__ */ new Set([
1426
- "query_executed",
1427
- "query_generated",
1428
- "verified_sql",
1429
- "semantic_query",
1430
- "omni_query"
1431
- ]);
1432
- /** Extract a SQL artifact from a single SSE event when the type +
1433
- * payload shape match. Returns `null` for events that aren't SQL
1434
- * carriers or whose payload doesn't include the expected fields. */
1435
- function extractSqlArtifact(eventType, eventId, data) {
1436
- if (!SQL_EVENT_TYPES.has(eventType)) return null;
1437
- if (typeof data !== "object" || data === null) return null;
1438
- const obj = data;
1439
- const sql = typeof obj.query === "string" ? obj.query : typeof obj.sql === "string" ? obj.sql : null;
1440
- if (!sql) return null;
1441
- const columns = Array.isArray(obj.columns) ? obj.columns.map(String) : void 0;
1442
- const rows = Array.isArray(obj.rows) ? obj.rows : void 0;
1443
- const rowCount = typeof obj.row_count === "number" ? obj.row_count : typeof obj.rowCount === "number" ? obj.rowCount : rows?.length;
1444
- const artifact = {
1445
- type: "sql",
1446
- id: eventId || `${eventType}-${sql.slice(0, 32)}`,
1447
- source: eventType,
1448
- sql
1449
- };
1450
- if (columns && rows) artifact.results = {
1451
- columns,
1452
- rows,
1453
- rowCount: rowCount ?? rows.length
1454
- };
1455
- const errMsg = typeof obj.error === "string" ? obj.error : obj.success === false && typeof obj.message === "string" ? obj.message : void 0;
1456
- if (errMsg) artifact.error = errMsg;
1457
- return artifact;
1458
- }
1459
- /**
1460
- * Hand-rolled SSE consumer using `fetch` + `ReadableStream`. We use
1461
- * this in place of `EventSource` because:
1462
- * 1. EventSource doesn't expose the connection's `Last-Event-ID`
1463
- * header in a way you can control. The browser tracks it
1464
- * internally but you can't pass a starting value, so a hook
1465
- * that wants to resume after a tab switch / network blip has
1466
- * no way to ask the server to replay from a known point.
1467
- * 2. EventSource can't pass `Authorization` / other custom
1468
- * headers — only `withCredentials` for cookies. Fine today,
1469
- * but couples us to cookie auth forever.
1470
- *
1471
- * The parser handles the message-block model from the SSE spec
1472
- * verbatim: lines split by `\n` (or `\r\n` / `\r`), event blocks
1473
- * separated by blank lines, `id:` / `event:` / `data:` fields
1474
- * accumulated per block. Multiple `data:` lines concatenate with
1475
- * `\n` (per spec) — we honor that even though the server emits
1476
- * single-line data today.
1477
- *
1478
- * Throws on network error or non-2xx. Returns when the stream ends
1479
- * normally (server closed connection cleanly).
1480
- */
1481
- async function consumeSseStream(opts) {
1482
- const headers = {
1483
- accept: "text/event-stream",
1484
- "cache-control": "no-cache"
1485
- };
1486
- if (opts.lastEventId) headers["Last-Event-ID"] = opts.lastEventId;
1487
- const resp = await opts.fetcher(opts.url, {
1488
- method: "GET",
1489
- headers,
1490
- signal: opts.signal
1491
- });
1492
- if (!resp.ok) throw await apiErrorFromResponse(resp);
1493
- if (!resp.body) throw new Error("SSE response has no body");
1494
- const reader = resp.body.getReader();
1495
- const decoder = new TextDecoder();
1496
- let buffer = "";
1497
- let currentId = "";
1498
- let currentEvent = "message";
1499
- let currentData = [];
1500
- const dispatch = () => {
1501
- if (currentData.length === 0 && currentEvent === "message" && !currentId) return;
1502
- opts.onEvent({
1503
- id: currentId,
1504
- event: currentEvent,
1505
- data: currentData.join("\n")
1506
- });
1507
- currentEvent = "message";
1508
- currentData = [];
1509
- };
1510
- while (true) {
1511
- const { value, done } = await reader.read();
1512
- if (done) break;
1513
- buffer += decoder.decode(value, { stream: true });
1514
- let nlIndex;
1515
- while ((nlIndex = buffer.search(/\r\n|\r|\n/)) !== -1) {
1516
- if (nlIndex === buffer.length - 1 && buffer[nlIndex] === "\r") break;
1517
- const line = buffer.slice(0, nlIndex);
1518
- const sep = buffer.slice(nlIndex, nlIndex + 2);
1519
- buffer = buffer.slice(nlIndex + (sep === "\r\n" ? 2 : 1));
1520
- if (line === "") {
1521
- dispatch();
1522
- continue;
1523
- }
1524
- if (line.startsWith(":")) continue;
1525
- const colonAt = line.indexOf(":");
1526
- const field = colonAt === -1 ? line : line.slice(0, colonAt);
1527
- let value = colonAt === -1 ? "" : line.slice(colonAt + 1);
1528
- if (value.startsWith(" ")) value = value.slice(1);
1529
- switch (field) {
1530
- case "id":
1531
- currentId = value;
1532
- break;
1533
- case "event":
1534
- currentEvent = value;
1535
- break;
1536
- case "data":
1537
- currentData.push(value);
1538
- break;
1539
- }
1540
- }
1541
- }
1542
- if (currentData.length > 0) dispatch();
1543
- }
1544
- function sleep(ms, signal) {
1545
- return new Promise((resolve, reject) => {
1546
- const t = setTimeout(resolve, ms);
1547
- signal?.addEventListener("abort", () => {
1548
- clearTimeout(t);
1549
- reject(new DOMException("aborted", "AbortError"));
1550
- }, { once: true });
1551
- });
1552
- }
1553
- /**
1554
- * Engineer-tagged usage event. Free-form `event_name` (≤ 64 chars,
1555
- * `[a-z][a-z0-9-]*` validated server-side) + optional JSON `payload`
1556
- * (object, ≤ 4 KiB serialized). Surfaces in the admin Activity tab
1557
- * grouped by name, with drill-down into recent occurrences.
1558
- *
1559
- * The handler returned by [`useTrackEvent`] is **fire-and-forget**:
1560
- * it enqueues the event into an in-memory batch flushed every second
1561
- * (and on `pagehide` so a navigation away doesn't drop the tail).
1562
- * No await semantics — call it inline from a click handler without
1563
- * awaiting it. Server-side validation errors are logged to the
1564
- * console; the call site doesn't need to handle them.
1565
- *
1566
- * Example:
1567
- * ```tsx
1568
- * const track = useTrackEvent();
1569
- * <button
1570
- * onClick={() => {
1571
- * track("export-clicked", { format: "csv", rowCount });
1572
- * doExport();
1573
- * }}
1574
- * >Export</button>
1575
- * ```
1576
- *
1577
- * Rate-limited at 60/min per (user, app) on the server. A burst that
1578
- * trips the limit drops the excess events with a console warning;
1579
- * within-limit events are unaffected.
1580
- */
1581
- function useTrackEvent() {
1582
- const { projectId, fetcher } = useOxyApp();
1583
- const queueRef = react.useRef([]);
1584
- const flushTimerRef = react.useRef(null);
1585
- const flush = react.useCallback(() => {
1586
- flushTimerRef.current = null;
1587
- if (!projectId) return;
1588
- const batch = queueRef.current;
1589
- if (batch.length === 0) return;
1590
- queueRef.current = [];
1591
- for (const evt of batch) {
1592
- const url = `/api/customer-apps/${projectId}/events`;
1593
- const body = JSON.stringify(evt);
1594
- try {
1595
- if (typeof navigator !== "undefined" && typeof navigator.sendBeacon === "function" && document.visibilityState === "hidden") navigator.sendBeacon(url, new Blob([body], { type: "application/json" }));
1596
- else fetcher(url, {
1597
- method: "POST",
1598
- headers: { "content-type": "application/json" },
1599
- body
1600
- }).catch((e) => {
1601
- console.warn("[oxy] useTrackEvent flush failed:", e);
1602
- });
1603
- } catch (e) {
1604
- console.warn("[oxy] useTrackEvent enqueue failed:", e);
1605
- }
1606
- }
1607
- }, [projectId, fetcher]);
1608
- react.useEffect(() => {
1609
- if (typeof window === "undefined") return;
1610
- const onHide = () => flush();
1611
- window.addEventListener("pagehide", onHide);
1612
- return () => {
1613
- window.removeEventListener("pagehide", onHide);
1614
- flush();
1615
- if (flushTimerRef.current !== null) {
1616
- clearTimeout(flushTimerRef.current);
1617
- flushTimerRef.current = null;
1618
- }
1619
- };
1620
- }, [flush]);
1621
- return react.useCallback((name, payload) => {
1622
- queueRef.current.push({
1623
- event_name: name,
1624
- payload: payload ?? {}
1625
- });
1626
- if (flushTimerRef.current === null) flushTimerRef.current = setTimeout(flush, 1e3);
1627
- }, [flush]);
1628
- }
1629
- /**
1630
- * Renders an agent run's answer + artifacts + thread link as a
1631
- * single block. The default styling is intentionally neutral
1632
- * (system fonts, gray surfaces) so it blends into any bundle.
1633
- *
1634
- * Designed to be paired with `useAgentRun`:
1635
- *
1636
- * ```tsx
1637
- * const run = useAgentRun({ agentId: "analyst" });
1638
- * return (
1639
- * <>
1640
- * <button onClick={() => run.ask("how many users last week?")}>Ask</button>
1641
- * <OxyAnswer {...run} />
1642
- * </>
1643
- * );
1644
- * ```
1645
- */
1646
- function OxyAnswer(props) {
1647
- const { answer, artifacts = [], state, clarification, error, threadUrl, threadLinkLabel = "Continue this thread in Oxy", maxArtifactRows = 10, className } = props;
1648
- const isRunning = state === "running";
1649
- const isFailed = state === "failed";
1650
- const needsClarification = state === "needs_clarification";
1651
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1652
- className,
1653
- style: styles.answerWrap,
1654
- children: [
1655
- isRunning && answer === null ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1656
- style: styles.statusRow,
1657
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1658
- style: styles.spinner,
1659
- "aria-hidden": "true"
1660
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1661
- style: styles.statusText,
1662
- children: "Thinking…"
1663
- })]
1664
- }) : null,
1665
- artifacts.length > 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1666
- style: styles.artifactList,
1667
- children: artifacts.map((a) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(SqlArtifactBlock, {
1668
- artifact: a,
1669
- maxRows: maxArtifactRows
1670
- }, a.id))
1671
- }) : null,
1672
- answer ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1673
- style: styles.markdown,
1674
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(MarkdownText, { text: answer })
1675
- }) : null,
1676
- needsClarification && clarification ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1677
- style: styles.clarification,
1678
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "Agent needs clarification:" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1679
- style: { marginTop: 4 },
1680
- children: clarification
1681
- })]
1682
- }) : null,
1683
- isFailed && error ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ErrorBlock, { error }) : null,
1684
- threadUrl && (answer || artifacts.length > 0) ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1685
- style: styles.threadLinkRow,
1686
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("a", {
1687
- href: threadUrl,
1688
- target: "_blank",
1689
- rel: "noreferrer noopener",
1690
- style: styles.threadLink,
1691
- children: [threadLinkLabel, " →"]
1692
- }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1693
- style: styles.betaBadge,
1694
- title: "Thread linking is in beta — see docs",
1695
- children: "beta"
1696
- })]
1697
- }) : null
1698
- ]
1699
- });
1700
- }
1701
- /**
1702
- * Complete drop-in chat surface. One agent, one input, one answer
1703
- * view. The chat is single-turn by default — each new question
1704
- * cancels the previous run and clears the answer. Bundles that
1705
- * want a multi-turn conversation history compose their own UI
1706
- * using `useAgentRun` directly.
1707
- *
1708
- * Single-turn keeps the surface dead simple: bundles use this for
1709
- * the "ask anything about your data" widget that sits next to
1710
- * structured panels. Multi-turn is rare in those contexts and
1711
- * better expressed by the bundle.
1712
- */
1713
- function OxyChat(props) {
1714
- const { agentId, placeholder = "Ask a question about your data…", submitLabel = "Ask", emptyState, maxArtifactRows, className } = props;
1715
- const run = useAgentRun({ agentId });
1716
- const [question, setQuestion] = react.useState("");
1717
- const submit = react.useCallback((e) => {
1718
- e?.preventDefault();
1719
- const q = question.trim();
1720
- if (!q || run.state === "running") return;
1721
- run.ask(q);
1722
- }, [question, run]);
1723
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1724
- className,
1725
- style: styles.chatWrap,
1726
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
1727
- onSubmit: submit,
1728
- style: styles.chatForm,
1729
- children: [
1730
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("input", {
1731
- type: "text",
1732
- value: question,
1733
- onChange: (e) => setQuestion(e.target.value),
1734
- placeholder,
1735
- disabled: run.state === "running",
1736
- style: styles.chatInput,
1737
- "aria-label": "Question"
1738
- }),
1739
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1740
- type: "submit",
1741
- disabled: run.state === "running" || question.trim() === "",
1742
- style: styles.chatSubmit,
1743
- children: run.state === "running" ? "…" : submitLabel
1744
- }),
1745
- run.state === "running" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("button", {
1746
- type: "button",
1747
- onClick: run.cancel,
1748
- style: styles.chatCancel,
1749
- children: "Stop"
1750
- }) : null
1751
- ]
1752
- }), run.state === "idle" ? emptyState ?? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1753
- style: styles.emptyState,
1754
- children: "Ask a question to get started."
1755
- }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(OxyAnswer, {
1756
- answer: run.answer,
1757
- artifacts: run.artifacts,
1758
- state: run.state,
1759
- clarification: run.clarification,
1760
- error: run.error,
1761
- threadUrl: run.threadUrl,
1762
- maxArtifactRows
1763
- })]
1764
- });
1765
- }
1766
- function SqlArtifactBlock(props) {
1767
- const { artifact, maxRows } = props;
1768
- const [open, setOpen] = react.useState(false);
1769
- const results = artifact.results;
1770
- const truncated = results ? results.rows.length > maxRows : false;
1771
- const visibleRows = results ? results.rows.slice(0, maxRows) : [];
1772
- const sourceLabel = artifact.source === "verified_sql" ? "Verified query" : artifact.source === "semantic_query" ? "Semantic query" : artifact.source === "omni_query" ? "Omni query" : "Query";
1773
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1774
- style: styles.artifact,
1775
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
1776
- type: "button",
1777
- onClick: () => setOpen((o) => !o),
1778
- style: styles.artifactHeader,
1779
- children: [
1780
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1781
- style: styles.artifactBadge,
1782
- children: sourceLabel
1783
- }),
1784
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1785
- style: styles.artifactSummary,
1786
- children: results ? `${results.rowCount} row${results.rowCount === 1 ? "" : "s"}` : artifact.error ? "execution failed" : "SQL only"
1787
- }),
1788
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1789
- style: styles.artifactToggle,
1790
- children: open ? "Hide" : "Show"
1791
- })
1792
- ]
1793
- }), open ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
1794
- style: styles.sqlBlock,
1795
- children: artifact.sql
1796
- }), artifact.error ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1797
- style: styles.error,
1798
- children: artifact.error
1799
- }) : results ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1800
- style: styles.resultsWrap,
1801
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("table", {
1802
- style: styles.resultsTable,
1803
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("thead", { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tr", { children: results.columns.map((c) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("th", {
1804
- style: styles.resultsTh,
1805
- children: c
1806
- }, c)) }) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tbody", { children: visibleRows.map((row, i) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("tr", { children: row.map((cell, j) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("td", {
1807
- style: styles.resultsTd,
1808
- children: formatCell(cell)
1809
- }, j)) }, i)) })]
1810
- }), truncated ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1811
- style: styles.truncatedNote,
1812
- children: [
1813
- "+",
1814
- results.rows.length - maxRows,
1815
- " more rows. Open the thread in Oxy to see all."
1816
- ]
1817
- }) : null]
1818
- }) : null] }) : null]
1819
- });
1820
- }
1821
- function formatCell(value) {
1822
- if (value === null || value === void 0) return "—";
1823
- if (typeof value === "object") return JSON.stringify(value);
1824
- return String(value);
1825
- }
1826
- /**
1827
- * Renders a thrown Error with the server's `hint` line broken out
1828
- * if the error is an `OxyApiError`. Falls back to `error.message`
1829
- * for plain Errors. Whitespace-preserving so multi-line hints from
1830
- * the server land readably.
1831
- */
1832
- function ErrorBlock(props) {
1833
- const { error } = props;
1834
- if (error instanceof OxyApiError) return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1835
- style: styles.error,
1836
- children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", { children: [
1837
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "Run failed:" }),
1838
- " ",
1839
- error.message.split("\n\n")[0]
1840
- ] }), error.hint ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1841
- style: {
1842
- marginTop: 6,
1843
- fontWeight: 400,
1844
- whiteSpace: "pre-wrap"
1845
- },
1846
- children: [
1847
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "Hint:" }),
1848
- " ",
1849
- error.hint
1850
- ]
1851
- }) : null]
1852
- });
1853
- return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1854
- style: styles.error,
1855
- children: [
1856
- /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: "Run failed:" }),
1857
- " ",
1858
- error.message
1859
- ]
1860
- });
1861
- }
1862
- function MarkdownText(props) {
1863
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: react.useMemo(() => parseMarkdown(props.text), [props.text]) });
1864
- }
1865
- function parseMarkdown(text) {
1866
- const lines = text.replace(/\r\n/g, "\n").split("\n");
1867
- const blocks = [];
1868
- let i = 0;
1869
- while (i < lines.length) {
1870
- const line = lines[i];
1871
- if (line === void 0) {
1872
- i++;
1873
- continue;
1874
- }
1875
- const fence = line.match(/^```(\w*)\s*$/);
1876
- if (fence) {
1877
- const lang = fence[1] ?? "";
1878
- const buf = [];
1879
- i++;
1880
- while (i < lines.length && !/^```\s*$/.test(lines[i] ?? "")) {
1881
- buf.push(lines[i] ?? "");
1882
- i++;
1883
- }
1884
- i++;
1885
- blocks.push({
1886
- kind: "code",
1887
- lang,
1888
- code: buf.join("\n")
1889
- });
1890
- continue;
1891
- }
1892
- const h = line.match(/^(#{1,3})\s+(.+)$/);
1893
- if (h) {
1894
- blocks.push({
1895
- kind: "h",
1896
- level: h[1]?.length,
1897
- text: h[2]
1898
- });
1899
- i++;
1900
- continue;
1901
- }
1902
- if (/^\s*[-*]\s+/.test(line)) {
1903
- const items = [];
1904
- while (i < lines.length && /^\s*[-*]\s+/.test(lines[i] ?? "")) {
1905
- items.push((lines[i] ?? "").replace(/^\s*[-*]\s+/, ""));
1906
- i++;
1907
- }
1908
- blocks.push({
1909
- kind: "list",
1910
- items
1911
- });
1912
- continue;
1913
- }
1914
- if (line.trim() === "") {
1915
- i++;
1916
- continue;
1917
- }
1918
- const buf = [line];
1919
- i++;
1920
- while (i < lines.length) {
1921
- const next = lines[i] ?? "";
1922
- if (next.trim() === "" || /^#{1,3}\s+/.test(next) || /^```/.test(next) || /^\s*[-*]\s+/.test(next)) break;
1923
- buf.push(next);
1924
- i++;
1925
- }
1926
- blocks.push({
1927
- kind: "p",
1928
- text: buf.join(" ")
1929
- });
1930
- }
1931
- return blocks.map((b, idx) => {
1932
- switch (b.kind) {
1933
- case "h": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(`h${b.level}`, {
1934
- style: b.level === 1 ? styles.h1 : b.level === 2 ? styles.h2 : styles.h3,
1935
- children: renderInline(b.text)
1936
- }, idx);
1937
- case "code": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("pre", {
1938
- style: styles.codeBlock,
1939
- "data-lang": b.lang || void 0,
1940
- children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", { children: b.code })
1941
- }, idx);
1942
- case "list": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("ul", {
1943
- style: styles.list,
1944
- children: b.items.map((item, i) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("li", { children: renderInline(item) }, i))
1945
- }, idx);
1946
- case "p": return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1947
- style: styles.paragraph,
1948
- children: renderInline(b.text)
1949
- }, idx);
1950
- }
1951
- });
1952
- }
1953
- /**
1954
- * Inline tokenizer for **bold**, *italic*, `code`, and [text](url).
1955
- * Lazy: scan once, split into segments. The patterns are matched in
1956
- * priority order (code first so backticks don't get eaten by bold).
1957
- */
1958
- function renderInline(text) {
1959
- const segments = [];
1960
- let remaining = text;
1961
- let key = 0;
1962
- const patterns = [
1963
- {
1964
- re: /`([^`]+)`/,
1965
- render: (m) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
1966
- style: styles.inlineCode,
1967
- children: m[1]
1968
- })
1969
- },
1970
- {
1971
- re: /\[([^\]]+)\]\(([^)]+)\)/,
1972
- render: (m) => {
1973
- if (isSafeLinkHref(m[2])) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("a", {
1974
- href: m[2],
1975
- target: "_blank",
1976
- rel: "noreferrer noopener",
1977
- style: styles.link,
1978
- children: m[1]
1979
- });
1980
- return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(react_jsx_runtime.Fragment, { children: m[1] });
1981
- }
1982
- },
1983
- {
1984
- re: /\*\*([^*]+)\*\*/,
1985
- render: (m) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("strong", { children: m[1] })
1986
- },
1987
- {
1988
- re: /\*([^*]+)\*/,
1989
- render: (m) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)("em", { children: m[1] })
1990
- }
1991
- ];
1992
- while (remaining.length > 0) {
1993
- let earliest = null;
1994
- for (const { re, render } of patterns) {
1995
- const m = re.exec(remaining);
1996
- if (m && (earliest === null || m.index < earliest.idx)) earliest = {
1997
- idx: m.index,
1998
- len: m[0].length,
1999
- node: render(m)
2000
- };
2001
- }
2002
- if (earliest === null) {
2003
- segments.push(remaining);
2004
- break;
2005
- }
2006
- if (earliest.idx > 0) segments.push(remaining.slice(0, earliest.idx));
2007
- segments.push(/* @__PURE__ */ (0, react_jsx_runtime.jsx)(react.Fragment, { children: earliest.node }, key++));
2008
- remaining = remaining.slice(earliest.idx + earliest.len);
2009
- }
2010
- return segments;
2011
- }
2012
- const SANS = "-apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif";
2013
- const MONO = "ui-monospace, SFMono-Regular, \"SF Mono\", Menlo, Consolas, monospace";
2014
- const styles = {
2015
- answerWrap: {
2016
- fontFamily: SANS,
2017
- fontSize: 14,
2018
- lineHeight: 1.5,
2019
- color: "#1f2937"
2020
- },
2021
- statusRow: {
2022
- display: "flex",
2023
- alignItems: "center",
2024
- gap: 8,
2025
- padding: "8px 0"
2026
- },
2027
- spinner: {
2028
- display: "inline-block",
2029
- width: 12,
2030
- height: 12,
2031
- borderRadius: "50%",
2032
- border: "2px solid #d1d5db",
2033
- borderTopColor: "#6b7280",
2034
- animation: "oxy-spin 0.8s linear infinite"
2035
- },
2036
- statusText: { color: "#6b7280" },
2037
- markdown: { marginTop: 8 },
2038
- h1: {
2039
- fontSize: 20,
2040
- fontWeight: 600,
2041
- margin: "16px 0 8px"
2042
- },
2043
- h2: {
2044
- fontSize: 17,
2045
- fontWeight: 600,
2046
- margin: "14px 0 6px"
2047
- },
2048
- h3: {
2049
- fontSize: 15,
2050
- fontWeight: 600,
2051
- margin: "12px 0 4px"
2052
- },
2053
- paragraph: { margin: "0 0 8px" },
2054
- list: {
2055
- margin: "0 0 8px",
2056
- paddingLeft: 20
2057
- },
2058
- codeBlock: {
2059
- fontFamily: MONO,
2060
- fontSize: 12,
2061
- background: "#f3f4f6",
2062
- border: "1px solid #e5e7eb",
2063
- borderRadius: 6,
2064
- padding: "8px 10px",
2065
- overflowX: "auto",
2066
- margin: "8px 0"
2067
- },
2068
- inlineCode: {
2069
- fontFamily: MONO,
2070
- fontSize: "0.92em",
2071
- background: "#f3f4f6",
2072
- padding: "1px 4px",
2073
- borderRadius: 3
2074
- },
2075
- link: {
2076
- color: "#2563eb",
2077
- textDecoration: "underline"
2078
- },
2079
- clarification: {
2080
- marginTop: 12,
2081
- padding: "10px 12px",
2082
- background: "#fef3c7",
2083
- border: "1px solid #fcd34d",
2084
- borderRadius: 6,
2085
- color: "#78350f"
2086
- },
2087
- error: {
2088
- marginTop: 12,
2089
- padding: "10px 12px",
2090
- background: "#fee2e2",
2091
- border: "1px solid #fca5a5",
2092
- borderRadius: 6,
2093
- color: "#991b1b"
2094
- },
2095
- threadLinkRow: {
2096
- marginTop: 12,
2097
- textAlign: "right",
2098
- display: "flex",
2099
- justifyContent: "flex-end",
2100
- alignItems: "center",
2101
- gap: 6
2102
- },
2103
- threadLink: {
2104
- fontSize: 12,
2105
- color: "#6b7280",
2106
- textDecoration: "none"
2107
- },
2108
- betaBadge: {
2109
- fontSize: 9,
2110
- fontWeight: 600,
2111
- letterSpacing: .5,
2112
- textTransform: "uppercase",
2113
- padding: "1px 5px",
2114
- borderRadius: 3,
2115
- background: "#fef3c7",
2116
- color: "#92400e",
2117
- border: "1px solid #fcd34d"
2118
- },
2119
- artifactList: {
2120
- display: "flex",
2121
- flexDirection: "column",
2122
- gap: 8,
2123
- marginBottom: 8
2124
- },
2125
- artifact: {
2126
- border: "1px solid #e5e7eb",
2127
- borderRadius: 6,
2128
- background: "#fafafa",
2129
- overflow: "hidden"
2130
- },
2131
- artifactHeader: {
2132
- display: "flex",
2133
- alignItems: "center",
2134
- gap: 10,
2135
- width: "100%",
2136
- padding: "6px 10px",
2137
- background: "transparent",
2138
- border: "none",
2139
- borderBottom: "1px solid transparent",
2140
- cursor: "pointer",
2141
- fontFamily: SANS,
2142
- fontSize: 12,
2143
- color: "#374151"
2144
- },
2145
- artifactBadge: {
2146
- fontWeight: 600,
2147
- fontSize: 11,
2148
- textTransform: "uppercase",
2149
- letterSpacing: .4,
2150
- color: "#4b5563"
2151
- },
2152
- artifactSummary: {
2153
- color: "#6b7280",
2154
- flex: 1
2155
- },
2156
- artifactToggle: { color: "#2563eb" },
2157
- sqlBlock: {
2158
- fontFamily: MONO,
2159
- fontSize: 12,
2160
- margin: 0,
2161
- padding: "8px 10px",
2162
- background: "#0f172a",
2163
- color: "#e2e8f0",
2164
- overflowX: "auto"
2165
- },
2166
- resultsWrap: {
2167
- padding: 8,
2168
- overflowX: "auto"
2169
- },
2170
- resultsTable: {
2171
- width: "100%",
2172
- borderCollapse: "collapse",
2173
- fontSize: 12
2174
- },
2175
- resultsTh: {
2176
- textAlign: "left",
2177
- padding: "4px 8px",
2178
- borderBottom: "1px solid #e5e7eb",
2179
- fontWeight: 600,
2180
- color: "#374151"
2181
- },
2182
- resultsTd: {
2183
- padding: "4px 8px",
2184
- borderBottom: "1px solid #f3f4f6",
2185
- color: "#1f2937"
2186
- },
2187
- truncatedNote: {
2188
- fontSize: 11,
2189
- color: "#6b7280",
2190
- padding: "6px 8px"
2191
- },
2192
- chatWrap: {
2193
- fontFamily: SANS,
2194
- fontSize: 14,
2195
- color: "#1f2937"
2196
- },
2197
- chatForm: {
2198
- display: "flex",
2199
- gap: 8,
2200
- marginBottom: 12
2201
- },
2202
- chatInput: {
2203
- flex: 1,
2204
- padding: "8px 12px",
2205
- border: "1px solid #d1d5db",
2206
- borderRadius: 6,
2207
- fontSize: 14,
2208
- fontFamily: SANS
2209
- },
2210
- chatSubmit: {
2211
- padding: "8px 16px",
2212
- border: "none",
2213
- borderRadius: 6,
2214
- background: "#2563eb",
2215
- color: "#ffffff",
2216
- fontSize: 14,
2217
- fontWeight: 500,
2218
- cursor: "pointer"
2219
- },
2220
- chatCancel: {
2221
- padding: "8px 12px",
2222
- border: "1px solid #d1d5db",
2223
- borderRadius: 6,
2224
- background: "#ffffff",
2225
- color: "#374151",
2226
- fontSize: 14,
2227
- cursor: "pointer"
2228
- },
2229
- emptyState: {
2230
- padding: "12px 0",
2231
- color: "#9ca3af",
2232
- fontStyle: "italic"
2233
- }
2234
- };
2235
-
2236
108
  //#endregion
2237
109
  //#region src/metricTree.ts
2238
110
  /**
@@ -2364,23 +236,24 @@ var MetricTreeClient = class {
2364
236
  //#endregion
2365
237
  exports.AnomaliesClient = AnomaliesClient;
2366
238
  exports.MetricTreeClient = MetricTreeClient;
2367
- exports.OxyAnswer = OxyAnswer;
2368
- exports.OxyApiError = OxyApiError;
2369
- exports.OxyAppProvider = OxyAppProvider;
2370
- exports.OxyChat = OxyChat;
2371
- exports._resetCustomerAppManifestCacheForTest = _resetCustomerAppManifestCacheForTest;
2372
- exports.apiErrorFromResponse = apiErrorFromResponse;
239
+ exports.OxyAnswer = require_react.OxyAnswer;
240
+ exports.OxyApiError = require_react.OxyApiError;
241
+ exports.OxyAppProvider = require_react.OxyAppProvider;
242
+ exports.OxyChat = require_react.OxyChat;
243
+ exports._resetCustomerAppManifestCacheForTest = require_react._resetCustomerAppManifestCacheForTest;
244
+ exports.apiErrorFromResponse = require_react.apiErrorFromResponse;
2373
245
  exports.getCustomerAppDebug = getCustomerAppDebug;
2374
- exports.getOxyAppLogger = getOxyAppLogger;
2375
- exports.interpretCustomerAppError = interpretCustomerAppError;
2376
- exports.loadCustomerAppManifest = loadCustomerAppManifest;
2377
- exports.readInjectedAppConfig = readInjectedAppConfig;
2378
- exports.setOxyAppLogger = setOxyAppLogger;
2379
- exports.useAgentRun = useAgentRun;
2380
- exports.useFunction = useFunction;
2381
- exports.useProcedureRun = useProcedureRun;
2382
- exports.useQuery = useQuery;
2383
- exports.useResolvedManifest = useResolvedManifest;
2384
- exports.useSemanticQuery = useSemanticQuery;
2385
- exports.useTrackEvent = useTrackEvent;
246
+ exports.getOxyAppLogger = require_react.getOxyAppLogger;
247
+ exports.interpretCustomerAppError = require_react.interpretCustomerAppError;
248
+ exports.loadCustomerAppManifest = require_react.loadCustomerAppManifest;
249
+ exports.readInjectedAppConfig = require_react.readInjectedAppConfig;
250
+ exports.setOxyAppLogger = require_react.setOxyAppLogger;
251
+ exports.useAgentRun = require_react.useAgentRun;
252
+ exports.useFunction = require_react.useFunction;
253
+ exports.useOxyApp = require_react.useOxyApp;
254
+ exports.useProcedureRun = require_react.useProcedureRun;
255
+ exports.useQuery = require_react.useQuery;
256
+ exports.useResolvedManifest = require_react.useResolvedManifest;
257
+ exports.useSemanticQuery = require_react.useSemanticQuery;
258
+ exports.useTrackEvent = require_react.useTrackEvent;
2386
259
  //# sourceMappingURL=index.cjs.map