@magemetrics/core 0.0.59 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/index.d.ts +4279 -0
  2. package/dist/index.js +2884 -0
  3. package/dist/index.js.map +1 -0
  4. package/package.json +12 -9
  5. package/dist/package.json +0 -59
  6. package/dist/src/adapters/storage/browser.d.ts +0 -11
  7. package/dist/src/adapters/storage/browser.d.ts.map +0 -1
  8. package/dist/src/adapters/storage/browser.js +0 -37
  9. package/dist/src/adapters/storage/browser.js.map +0 -1
  10. package/dist/src/adapters/storage/factory.d.ts +0 -8
  11. package/dist/src/adapters/storage/factory.d.ts.map +0 -1
  12. package/dist/src/adapters/storage/factory.js +0 -24
  13. package/dist/src/adapters/storage/factory.js.map +0 -1
  14. package/dist/src/adapters/storage/interface.d.ts +0 -26
  15. package/dist/src/adapters/storage/interface.d.ts.map +0 -1
  16. package/dist/src/adapters/storage/interface.js +0 -1
  17. package/dist/src/adapters/storage/interface.js.map +0 -1
  18. package/dist/src/adapters/storage/memory.d.ts +0 -11
  19. package/dist/src/adapters/storage/memory.d.ts.map +0 -1
  20. package/dist/src/adapters/storage/memory.js +0 -20
  21. package/dist/src/adapters/storage/memory.js.map +0 -1
  22. package/dist/src/core/MageMetricsClient.d.ts +0 -103
  23. package/dist/src/core/MageMetricsClient.d.ts.map +0 -1
  24. package/dist/src/core/MageMetricsClient.js +0 -509
  25. package/dist/src/core/MageMetricsClient.js.map +0 -1
  26. package/dist/src/core/MageMetricsEventEmitter.d.ts +0 -25
  27. package/dist/src/core/MageMetricsEventEmitter.d.ts.map +0 -1
  28. package/dist/src/core/MageMetricsEventEmitter.js +0 -48
  29. package/dist/src/core/MageMetricsEventEmitter.js.map +0 -1
  30. package/dist/src/core/types.d.ts +0 -37
  31. package/dist/src/core/types.d.ts.map +0 -1
  32. package/dist/src/core/types.js +0 -6
  33. package/dist/src/core/types.js.map +0 -1
  34. package/dist/src/index.d.ts +0 -8
  35. package/dist/src/index.d.ts.map +0 -1
  36. package/dist/src/index.js +0 -7
  37. package/dist/src/index.js.map +0 -1
  38. package/dist/src/utils/hash.d.ts +0 -8
  39. package/dist/src/utils/hash.d.ts.map +0 -1
  40. package/dist/src/utils/hash.js +0 -16
  41. package/dist/src/utils/hash.js.map +0 -1
  42. package/dist/src/utils/platform.d.ts +0 -10
  43. package/dist/src/utils/platform.d.ts.map +0 -1
  44. package/dist/src/utils/platform.js +0 -25
  45. package/dist/src/utils/platform.js.map +0 -1
  46. package/dist/tsconfig.tsbuildinfo +0 -1
package/dist/index.js ADDED
@@ -0,0 +1,2884 @@
1
+ import z5, { z } from 'zod';
2
+ import dayjs from 'dayjs';
3
+ import customParseFormat from 'dayjs/plugin/customParseFormat.js';
4
+ import relativeTime from 'dayjs/plugin/relativeTime.js';
5
+ import timezone from 'dayjs/plugin/timezone.js';
6
+ import utc from 'dayjs/plugin/utc.js';
7
+ import { GoTrueClient } from '@supabase/auth-js';
8
+ import createApiClient from 'openapi-fetch';
9
+ import { sha256 } from '@noble/hashes/sha2';
10
+ import { DefaultChatTransport } from 'ai';
11
+
12
+ // ../shared/dist/src/api/client/middleware.js
13
+ var HEADER_CLIENT_VERSION = "X-Client-Version";
14
+ var HEADER_API_KEY = "X-Api-Key";
15
+ var ApiError = class extends Error {
16
+ extra;
17
+ response;
18
+ constructor(message, response, extra) {
19
+ super(message);
20
+ this.name = "ApiError";
21
+ this.response = response;
22
+ this.extra = extra;
23
+ }
24
+ };
25
+ var throwOnError = {
26
+ async onResponse({ response, request }) {
27
+ if (response.status >= 400) {
28
+ const body = response.headers.get("content-type")?.includes("json") ? await response.clone().json() : await response.clone().text();
29
+ throw new ApiError(`[${response.status}] ${request.method} ${request.url}`, response, {
30
+ body,
31
+ status: response.status,
32
+ statusText: response.statusText,
33
+ url: request.url,
34
+ method: request.method
35
+ });
36
+ }
37
+ return void 0;
38
+ }
39
+ };
40
+ var addVersionHeader = (clientVersion) => {
41
+ return {
42
+ onRequest({ request }) {
43
+ request.headers.set(HEADER_CLIENT_VERSION, clientVersion);
44
+ return request;
45
+ }
46
+ };
47
+ };
48
+ var addApiKeyHeader = (apiKey) => {
49
+ return {
50
+ onRequest({ request }) {
51
+ request.headers.set(HEADER_API_KEY, apiKey);
52
+ return request;
53
+ }
54
+ };
55
+ };
56
+
57
+ // ../../node_modules/.pnpm/@asteasolutions+zod-to-openapi@7.3.4_zod@3.25.76/node_modules/@asteasolutions/zod-to-openapi/dist/index.mjs
58
+ function __rest(s, e) {
59
+ var t = {};
60
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
61
+ t[p] = s[p];
62
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
63
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
64
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
65
+ t[p[i]] = s[p[i]];
66
+ }
67
+ return t;
68
+ }
69
+ function isZodType(schema, typeName) {
70
+ var _a;
71
+ return ((_a = schema === null || schema === void 0 ? void 0 : schema._def) === null || _a === void 0 ? void 0 : _a.typeName) === typeName;
72
+ }
73
+ function preserveMetadataFromModifier(zod, modifier) {
74
+ const zodModifier = zod.ZodType.prototype[modifier];
75
+ zod.ZodType.prototype[modifier] = function(...args) {
76
+ const result = zodModifier.apply(this, args);
77
+ result._def.openapi = this._def.openapi;
78
+ return result;
79
+ };
80
+ }
81
+ function extendZodWithOpenApi(zod) {
82
+ if (typeof zod.ZodType.prototype.openapi !== "undefined") {
83
+ return;
84
+ }
85
+ zod.ZodType.prototype.openapi = function(refOrOpenapi, metadata) {
86
+ var _a, _b, _c, _d, _e, _f;
87
+ const openapi = typeof refOrOpenapi === "string" ? metadata : refOrOpenapi;
88
+ const _g = openapi !== null && openapi !== void 0 ? openapi : {}, { param } = _g, restOfOpenApi = __rest(_g, ["param"]);
89
+ const _internal = Object.assign(Object.assign({}, (_a = this._def.openapi) === null || _a === void 0 ? void 0 : _a._internal), typeof refOrOpenapi === "string" ? { refId: refOrOpenapi } : void 0);
90
+ const resultMetadata = Object.assign(Object.assign(Object.assign({}, (_b = this._def.openapi) === null || _b === void 0 ? void 0 : _b.metadata), restOfOpenApi), ((_d = (_c = this._def.openapi) === null || _c === void 0 ? void 0 : _c.metadata) === null || _d === void 0 ? void 0 : _d.param) || param ? {
91
+ param: Object.assign(Object.assign({}, (_f = (_e = this._def.openapi) === null || _e === void 0 ? void 0 : _e.metadata) === null || _f === void 0 ? void 0 : _f.param), param)
92
+ } : void 0);
93
+ const result = new this.constructor(Object.assign(Object.assign({}, this._def), { openapi: Object.assign(Object.assign({}, Object.keys(_internal).length > 0 ? { _internal } : void 0), Object.keys(resultMetadata).length > 0 ? { metadata: resultMetadata } : void 0) }));
94
+ if (isZodType(this, "ZodObject")) {
95
+ const originalExtend = this.extend;
96
+ result.extend = function(...args) {
97
+ var _a2, _b2, _c2, _d2, _e2, _f2, _g2;
98
+ const extendedResult = originalExtend.apply(this, args);
99
+ extendedResult._def.openapi = {
100
+ _internal: {
101
+ extendedFrom: ((_b2 = (_a2 = this._def.openapi) === null || _a2 === void 0 ? void 0 : _a2._internal) === null || _b2 === void 0 ? void 0 : _b2.refId) ? { refId: (_d2 = (_c2 = this._def.openapi) === null || _c2 === void 0 ? void 0 : _c2._internal) === null || _d2 === void 0 ? void 0 : _d2.refId, schema: this } : (_f2 = (_e2 = this._def.openapi) === null || _e2 === void 0 ? void 0 : _e2._internal) === null || _f2 === void 0 ? void 0 : _f2.extendedFrom
102
+ },
103
+ metadata: (_g2 = extendedResult._def.openapi) === null || _g2 === void 0 ? void 0 : _g2.metadata
104
+ };
105
+ return extendedResult;
106
+ };
107
+ }
108
+ return result;
109
+ };
110
+ preserveMetadataFromModifier(zod, "optional");
111
+ preserveMetadataFromModifier(zod, "nullable");
112
+ preserveMetadataFromModifier(zod, "default");
113
+ preserveMetadataFromModifier(zod, "transform");
114
+ preserveMetadataFromModifier(zod, "refine");
115
+ const zodDeepPartial = zod.ZodObject.prototype.deepPartial;
116
+ zod.ZodObject.prototype.deepPartial = function() {
117
+ const initialShape = this._def.shape();
118
+ const result = zodDeepPartial.apply(this);
119
+ const resultShape = result._def.shape();
120
+ Object.entries(resultShape).forEach(([key, value]) => {
121
+ var _a, _b;
122
+ value._def.openapi = (_b = (_a = initialShape[key]) === null || _a === void 0 ? void 0 : _a._def) === null || _b === void 0 ? void 0 : _b.openapi;
123
+ });
124
+ result._def.openapi = void 0;
125
+ return result;
126
+ };
127
+ const zodPick = zod.ZodObject.prototype.pick;
128
+ zod.ZodObject.prototype.pick = function(...args) {
129
+ const result = zodPick.apply(this, args);
130
+ result._def.openapi = void 0;
131
+ return result;
132
+ };
133
+ const zodOmit = zod.ZodObject.prototype.omit;
134
+ zod.ZodObject.prototype.omit = function(...args) {
135
+ const result = zodOmit.apply(this, args);
136
+ result._def.openapi = void 0;
137
+ return result;
138
+ };
139
+ }
140
+ new Set(".\\+*[^]$()");
141
+ var createRoute = (routeConfig) => {
142
+ const route = {
143
+ ...routeConfig,
144
+ getRoutingPath() {
145
+ return routeConfig.path.replaceAll(/\/{(.+?)}/g, "/:$1");
146
+ }
147
+ };
148
+ return Object.defineProperty(route, "getRoutingPath", { enumerable: false });
149
+ };
150
+ extendZodWithOpenApi(z);
151
+
152
+ // ../shared/dist/src/endpoints/admin-console/sqlPreview.routes.js
153
+ var TanStackColumnSchema = z.object({
154
+ id: z.string(),
155
+ accessorKey: z.string(),
156
+ header: z.string(),
157
+ cell: z.any().optional(),
158
+ meta: z.record(z.any()).optional()
159
+ });
160
+ var SqlPreviewResponseSchema = z.object({
161
+ columns: z.array(TanStackColumnSchema),
162
+ data: z.array(z.record(z.any())),
163
+ metadata: z.object({
164
+ wasSampled: z.boolean(),
165
+ originalCount: z.number(),
166
+ sampledCount: z.number()
167
+ }).optional()
168
+ });
169
+ var SqlPreviewErrorSchema = z.object({
170
+ error: z.string()
171
+ });
172
+ createRoute({
173
+ method: "post",
174
+ path: "/api/v1/admin-console/sql/preview",
175
+ operationId: "sqlPreview",
176
+ request: {
177
+ body: {
178
+ content: {
179
+ "application/json": {
180
+ schema: z.object({
181
+ sql: z.string().min(1, "SQL query is required")
182
+ })
183
+ }
184
+ }
185
+ }
186
+ },
187
+ responses: {
188
+ 200: {
189
+ description: "SQL query executed successfully",
190
+ content: {
191
+ "application/json": {
192
+ schema: SqlPreviewResponseSchema
193
+ }
194
+ }
195
+ },
196
+ 400: {
197
+ description: "Invalid SQL query or request",
198
+ content: {
199
+ "application/json": {
200
+ schema: SqlPreviewErrorSchema
201
+ }
202
+ }
203
+ },
204
+ 500: {
205
+ description: "Internal server error",
206
+ content: {
207
+ "application/json": {
208
+ schema: SqlPreviewErrorSchema
209
+ }
210
+ }
211
+ }
212
+ }
213
+ });
214
+
215
+ // ../shared/dist/src/endpoints/utils.js
216
+ var limitQueryParams = z.string().pipe(z.coerce.number()).optional().openapi({
217
+ param: {
218
+ required: false
219
+ },
220
+ type: "integer"
221
+ });
222
+ var orderQueryParams = z.string().transform((str) => {
223
+ if (!str)
224
+ return [];
225
+ return str.split(",").map((part) => {
226
+ const [column, direction = "ASC"] = part.split(":");
227
+ return {
228
+ column,
229
+ direction: direction.toUpperCase()
230
+ };
231
+ });
232
+ }).pipe(z.array(z.object({
233
+ column: z.string(),
234
+ direction: z.enum(["ASC", "DESC"])
235
+ }))).optional().openapi({
236
+ param: {
237
+ required: false,
238
+ example: "name:asc,date:desc"
239
+ },
240
+ type: "string"
241
+ });
242
+ var cursorParams = z.string().pipe(z.coerce.number()).optional().openapi({
243
+ param: {
244
+ required: false
245
+ },
246
+ type: "number"
247
+ });
248
+ var filterQueryParams = z.string().transform((str) => {
249
+ if (!str)
250
+ return [];
251
+ return str.split(",").map((part) => {
252
+ const [column, value = ""] = part.split(":").map(decodeURIComponent);
253
+ return { column, value };
254
+ });
255
+ }).pipe(z.array(z.object({
256
+ column: z.string(),
257
+ value: z.string()
258
+ }))).optional().openapi({
259
+ param: {
260
+ required: false,
261
+ example: "status:active,name:John%20Doe"
262
+ },
263
+ type: "string"
264
+ });
265
+ var columnsQueryParams = z.string().transform((str) => {
266
+ if (!str)
267
+ return [];
268
+ return str.split(",");
269
+ }).optional().openapi({
270
+ param: {
271
+ required: false,
272
+ example: "name,date"
273
+ },
274
+ type: "string"
275
+ });
276
+ var SupabaseUserHeaderSchema = z.object({
277
+ "sp-access-token": z.string()
278
+ });
279
+ var SupabaseHeaderSchema = SupabaseUserHeaderSchema;
280
+ var FEEDBACK_OPTIONS = [
281
+ { label: "Helpful", value: "helpful" },
282
+ { label: "Partially helpful", value: "partially helpful" },
283
+ { label: "Not helpful", value: "not helpful" },
284
+ { label: "Incorrect", value: "incorrect" }
285
+ ];
286
+ var FeedbackSchema = z.object({
287
+ created_at: z.string(),
288
+ flow_data_id: z.number(),
289
+ helpfulness: z.enum(FEEDBACK_OPTIONS.map((option) => option.value)),
290
+ id: z.number()
291
+ });
292
+ var Node3 = z.object({
293
+ id: z.string(),
294
+ type: z.enum([
295
+ "entity",
296
+ "attribute",
297
+ "filter",
298
+ "process",
299
+ "combine",
300
+ "result"
301
+ ]),
302
+ explanation: z.string()
303
+ });
304
+ var Edge = z.object({
305
+ source: z.string(),
306
+ target: z.string()
307
+ });
308
+ z.object({
309
+ score: z.number(),
310
+ reason: z.string()
311
+ });
312
+ var LLMColumnsLineageResponse = z.record(z.string(), z.object({
313
+ nodes: z.array(Node3),
314
+ edges: z.array(Edge)
315
+ }));
316
+ var SqlAnalysisChunkSchema = z.object({
317
+ chunk_title: z.string(),
318
+ chunk_explanation: z.string(),
319
+ lines: z.array(z.object({
320
+ sql: z.string(),
321
+ explanation: z.string()
322
+ }))
323
+ });
324
+ var BusinessExplanationSchema = z.object({
325
+ summary: z.string(),
326
+ implementation: z.array(z.string()),
327
+ assumptions: z.array(z.object({
328
+ type: z.enum([
329
+ "grain",
330
+ "completeness",
331
+ "transformation",
332
+ "relationship",
333
+ "other"
334
+ ]),
335
+ details: z.string(),
336
+ explanation: z.string()
337
+ }))
338
+ });
339
+
340
+ // ../shared/dist/src/schemas/flows.js
341
+ var FlowStepSchema = z.object({
342
+ name: z.string(),
343
+ status: z.enum(["running", "completed", "failed", "awaiting_input"]),
344
+ output: z.object({}).passthrough().or(z.unknown().array()).nullable()
345
+ });
346
+ var DatabaseFlowSchema = z.object({
347
+ created_at: z.string(),
348
+ id: z.string(),
349
+ request: z.string(),
350
+ user_id: z.string().nullable(),
351
+ flow_steps: z.array(FlowStepSchema),
352
+ flow_chat_messages: z.array(z.object({ count: z.number() }))
353
+ });
354
+ z.object({
355
+ table: z.string(),
356
+ schema: z.string(),
357
+ database: z.string()
358
+ });
359
+ var FrontendFlowSchema = DatabaseFlowSchema.omit({
360
+ flow_chat_messages: true,
361
+ flow_steps: true
362
+ }).extend({
363
+ user_friendly_goal: z.string().optional(),
364
+ has_chat_messages: z.boolean()
365
+ });
366
+ var FrontendRecentFlowsSchema = DatabaseFlowSchema.omit({
367
+ flow_steps: true,
368
+ flow_chat_messages: true
369
+ });
370
+ var ReportColumnSchema = z.object({
371
+ position: z.number().nonnegative().optional(),
372
+ data_type: z.string(),
373
+ null_count: z.number().nullable(),
374
+ unique_count: z.number().nullable(),
375
+ unique_percentage: z.number().nullable()
376
+ }).passthrough();
377
+ var ReportSchema = z.object({
378
+ created_at: z.string(),
379
+ flow_id: z.string(),
380
+ id: z.number(),
381
+ is_sample: z.boolean(),
382
+ schema: z.string(),
383
+ sql: z.string(),
384
+ table: z.string(),
385
+ title: z.string(),
386
+ request: z.string().nullable(),
387
+ data_sample: z.array(z.record(z.unknown())),
388
+ data_summary: z.object({
389
+ columns: z.record(z.string(), ReportColumnSchema)
390
+ }).passthrough(),
391
+ bookmarked: z.boolean(),
392
+ status: z.string().nullable()
393
+ });
394
+ var FrontendReportSchema = ReportSchema.omit({
395
+ sql: true,
396
+ table: true,
397
+ data_sample: true,
398
+ is_sample: true,
399
+ schema: true
400
+ });
401
+ var ReportDataSchema = z.object({}).passthrough().array().openapi("ReportData");
402
+ var ReportColumnsSchema = z.object({
403
+ name: z.string(),
404
+ data_type: z.string()
405
+ }).array();
406
+ z.object({
407
+ render_type: z.string().nullish(),
408
+ unit: z.string().nullish()
409
+ });
410
+ var FrontendReportColumnsSchema = ReportColumnsSchema.element.merge(z.object({
411
+ dataType: z.string(),
412
+ renderType: z.string().optional(),
413
+ unit: z.string().optional()
414
+ })).array().openapi("ReportColumns");
415
+ z.object({
416
+ goal: z.string(),
417
+ user_friendly_goal: z.string().optional()
418
+ });
419
+ var ReportExplainabilitySchema = z.object({
420
+ sql_explanation: z.array(SqlAnalysisChunkSchema).nullish(),
421
+ business_explanation: BusinessExplanationSchema.nullish(),
422
+ columns_lineage: LLMColumnsLineageResponse.nullish(),
423
+ confidence_score: z.number(),
424
+ confidence_score_reason: z.string(),
425
+ assumptions_score: z.number().optional(),
426
+ assumptions_score_reason: z.string().optional(),
427
+ friendliness_score: z.number().optional(),
428
+ friendliness_score_reason: z.string().optional(),
429
+ id: z.number(),
430
+ flow_data_id: z.number(),
431
+ created_at: z.string()
432
+ });
433
+ var FrontendReportExplainabilitySchema = ReportExplainabilitySchema.omit({
434
+ id: true,
435
+ created_at: true
436
+ });
437
+ dayjs.extend(relativeTime);
438
+ dayjs.extend(customParseFormat);
439
+ dayjs.extend(utc);
440
+ dayjs.extend(timezone);
441
+ var daysjs_default = dayjs;
442
+
443
+ // ../shared/dist/src/data/FormattedData.js
444
+ var formatWithAutoPrecision = (value, options = {}) => {
445
+ const { minPrecision = 0, maxPrecision = 6, trimZeros = true, useGrouping = true } = options;
446
+ if (typeof value !== "number" || isNaN(value)) {
447
+ return String(value);
448
+ }
449
+ if (value === 0) {
450
+ return "0";
451
+ }
452
+ const absValue = Math.abs(value);
453
+ let maximumFractionDigits;
454
+ if (absValue >= 1e3) {
455
+ maximumFractionDigits = 0;
456
+ } else if (absValue >= 100) {
457
+ maximumFractionDigits = 1;
458
+ } else if (absValue >= 10) {
459
+ maximumFractionDigits = 2;
460
+ } else if (absValue >= 1) {
461
+ maximumFractionDigits = 3;
462
+ } else if (absValue >= 0.1) {
463
+ maximumFractionDigits = 4;
464
+ } else if (absValue >= 0.01) {
465
+ maximumFractionDigits = 5;
466
+ } else {
467
+ maximumFractionDigits = maxPrecision;
468
+ if (absValue > 0) {
469
+ const exponent = Math.floor(Math.log10(absValue));
470
+ if (exponent < 0) {
471
+ maximumFractionDigits = Math.min(Math.abs(exponent) + 2, maxPrecision);
472
+ }
473
+ }
474
+ }
475
+ maximumFractionDigits = Math.max(maximumFractionDigits, minPrecision);
476
+ const formatter = new Intl.NumberFormat(void 0, {
477
+ minimumFractionDigits: trimZeros ? 0 : maximumFractionDigits,
478
+ maximumFractionDigits,
479
+ useGrouping
480
+ });
481
+ return formatter.format(value);
482
+ };
483
+ var MIN_VALID_YEAR = 1900;
484
+ var MAX_VALID_YEAR = 2200;
485
+ var zonedatetime = (format, zone) => ({ format, type: "zonedatetime", zone });
486
+ var datetime = (format) => ({ format, type: "datetime" });
487
+ var date = (format) => ({ format, type: "date" });
488
+ var DATE_FORMATS = [
489
+ // ISO 8601 formats
490
+ zonedatetime("YYYY-MM-DDTHH:mm:ss.SSSZ", "UTC"),
491
+ zonedatetime("YYYY-MM-DDTHH:mm:ssZ", "UTC"),
492
+ zonedatetime("YYYY-MM-DDTHH:mmZ", "UTC"),
493
+ datetime("YYYY-MM-DDTHH:mm:ss"),
494
+ datetime("YYYY-MM-DDTHH:mm"),
495
+ date("YYYY-MM-DDT"),
496
+ // Standard date formats
497
+ date("YYYY-MM-DD"),
498
+ date("YYYY/MM/DD"),
499
+ date("DD-MM-YYYY"),
500
+ date("DD/MM/YYYY"),
501
+ date("MM-DD-YYYY"),
502
+ date("MM/DD/YYYY"),
503
+ // Date time formats
504
+ datetime("YYYY-MM-DD HH:mm:ss"),
505
+ datetime("YYYY-MM-DD HH:mm"),
506
+ datetime("YYYY/MM/DD HH:mm:ss"),
507
+ datetime("YYYY/MM/DD HH:mm"),
508
+ datetime("DD-MM-YYYY HH:mm:ss"),
509
+ datetime("DD-MM-YYYY HH:mm"),
510
+ datetime("DD/MM/YYYY HH:mm:ss"),
511
+ datetime("DD/MM/YYYY HH:mm"),
512
+ datetime("MM-DD-YYYY HH:mm:ss"),
513
+ datetime("MM-DD-YYYY HH:mm"),
514
+ datetime("MM/DD/YYYY HH:mm:ss"),
515
+ datetime("MM/DD/YYYY HH:mm")
516
+ ];
517
+ var isDateString = (value) => {
518
+ if (typeof value !== "string")
519
+ return { isValid: false };
520
+ const stripped = value.replace(/[-/.:\s]/g, "");
521
+ if (/^\d+$/.test(stripped)) {
522
+ if (stripped.length < 6)
523
+ return { isValid: false };
524
+ if (value.length === stripped.length)
525
+ return { isValid: false };
526
+ }
527
+ if (stripped.length > "YYYY-MM-DDTHH:mm:ss.SSS+00:00".length) {
528
+ return { isValid: false };
529
+ }
530
+ for (const format of DATE_FORMATS) {
531
+ let date2;
532
+ try {
533
+ if (format.type === "zonedatetime") {
534
+ date2 = daysjs_default.tz(value, format.format, format.zone);
535
+ } else {
536
+ date2 = daysjs_default(value, format.format, true);
537
+ }
538
+ } catch {
539
+ continue;
540
+ }
541
+ if (date2.isValid()) {
542
+ const year = date2.year();
543
+ if (year < MIN_VALID_YEAR || year > MAX_VALID_YEAR)
544
+ continue;
545
+ const isDateTime = format.type === "zonedatetime" || format.type == "datetime";
546
+ return {
547
+ isValid: true,
548
+ parsedDate: date2,
549
+ isDateTime
550
+ };
551
+ }
552
+ }
553
+ return { isValid: false };
554
+ };
555
+ var formatDataValue = (value, { replaceNullValue } = {
556
+ replaceNullValue: true
557
+ }) => {
558
+ if (value === null || value === void 0) {
559
+ return {
560
+ display: replaceNullValue ? "empty" : null,
561
+ sortValue: null
562
+ };
563
+ }
564
+ let processedValue = value;
565
+ if (typeof processedValue === "string") {
566
+ try {
567
+ const parsed = JSON.parse(processedValue);
568
+ processedValue = parsed;
569
+ } catch {
570
+ }
571
+ }
572
+ if (processedValue && typeof processedValue === "object" && Object.keys(processedValue).length === 1 && "value" in processedValue) {
573
+ const extractedValue = processedValue.value;
574
+ const dateResult2 = isDateString(extractedValue);
575
+ if (dateResult2.isValid) {
576
+ return {
577
+ display: dateResult2.isDateTime ? dateResult2.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult2.parsedDate.format("YYYY-MM-DD"),
578
+ sortValue: dateResult2.parsedDate.valueOf()
579
+ };
580
+ }
581
+ return {
582
+ display: String(extractedValue),
583
+ sortValue: extractedValue
584
+ };
585
+ }
586
+ const dateResult = isDateString(processedValue);
587
+ if (dateResult.isValid) {
588
+ return {
589
+ display: dateResult.isDateTime ? dateResult.parsedDate.format("YYYY-MM-DD HH:mm:ss") : dateResult.parsedDate.format("YYYY-MM-DD"),
590
+ sortValue: dateResult.parsedDate.valueOf()
591
+ };
592
+ }
593
+ if (typeof processedValue === "object") {
594
+ const stringified = JSON.stringify(processedValue, null, 2);
595
+ return {
596
+ display: stringified,
597
+ sortValue: stringified
598
+ };
599
+ }
600
+ if (typeof processedValue === "boolean") {
601
+ return {
602
+ display: String(processedValue),
603
+ sortValue: processedValue ? 1 : 0
604
+ };
605
+ }
606
+ if (typeof processedValue === "number") {
607
+ return {
608
+ display: processedValue >= MIN_VALID_YEAR && processedValue <= MAX_VALID_YEAR && Number.isInteger(processedValue) ? String(processedValue) : formatWithAutoPrecision(processedValue),
609
+ sortValue: processedValue
610
+ };
611
+ }
612
+ return {
613
+ // eslint-disable-next-line @typescript-eslint/no-base-to-string
614
+ display: String(processedValue),
615
+ sortValue: processedValue
616
+ };
617
+ };
618
+
619
+ // ../shared/dist/src/schemas/visualizations.js
620
+ var commonConfigProperties = {
621
+ title: z.string()
622
+ };
623
+ var cartesianConfigProperties = {
624
+ xAxisLabel: z.string(),
625
+ yAxisLabel: z.string(),
626
+ xAxisDataKey: z.string().optional(),
627
+ yAxisDataKey: z.string().optional(),
628
+ dimensionDataKey: z.string().optional(),
629
+ valueColumns: z.array(z.string()).optional()
630
+ };
631
+ var V1VisualizationConfigurationSchema = z.discriminatedUnion("type", [
632
+ // Bar chart
633
+ z.object({
634
+ type: z.literal("bar"),
635
+ ...commonConfigProperties,
636
+ ...cartesianConfigProperties
637
+ }),
638
+ // Line/Area chart
639
+ z.object({
640
+ type: z.literal("line/area"),
641
+ ...commonConfigProperties,
642
+ ...cartesianConfigProperties
643
+ }),
644
+ // Scatter chart
645
+ z.object({
646
+ type: z.literal("scatter"),
647
+ ...commonConfigProperties,
648
+ ...cartesianConfigProperties
649
+ }),
650
+ // Pie chart
651
+ z.object({
652
+ type: z.literal("pie"),
653
+ ...commonConfigProperties,
654
+ nameKey: z.string(),
655
+ dataKey: z.string()
656
+ })
657
+ ]);
658
+ var VisualizationConfigurationSchema = z.discriminatedUnion("type", [
659
+ z.object({
660
+ type: z.literal("bar"),
661
+ ...commonConfigProperties,
662
+ config_version: z.literal(2),
663
+ xAxisLabel: z.string(),
664
+ yAxisLabel: z.string(),
665
+ categoryColumn: z.string(),
666
+ secondaryCategoryColumn: z.string().optional(),
667
+ valueColumn: z.string()
668
+ }),
669
+ // Line/Area chart - version 2: New format
670
+ z.object({
671
+ type: z.literal("line/area"),
672
+ config_version: z.literal(2),
673
+ ...commonConfigProperties,
674
+ xAxisColumn: z.string(),
675
+ valueColumns: z.array(z.string()),
676
+ yAxisLabels: z.array(z.string())
677
+ }),
678
+ // Line/Area chart - categorical format (requires pivoting)
679
+ z.object({
680
+ type: z.literal("line/area-categorical"),
681
+ ...commonConfigProperties,
682
+ config_version: z.literal(2),
683
+ valueColumn: z.string(),
684
+ xAxisColumn: z.string(),
685
+ xAxisLabel: z.string(),
686
+ yAxisLabel: z.string(),
687
+ categoryColumn: z.string()
688
+ }),
689
+ // Scatter chart - new format (v2)
690
+ z.object({
691
+ type: z.literal("scatter"),
692
+ ...commonConfigProperties,
693
+ config_version: z.literal(2),
694
+ xAxisLabel: z.string(),
695
+ yAxisLabel: z.string(),
696
+ xAxisValueColumn: z.string(),
697
+ yAxisValueColumn: z.string()
698
+ }),
699
+ // Pie chart - new format (v2)
700
+ z.object({
701
+ type: z.literal("pie"),
702
+ ...commonConfigProperties,
703
+ config_version: z.literal(2),
704
+ categoryColumn: z.string(),
705
+ valueColumn: z.string()
706
+ })
707
+ ]);
708
+ var BaseVisualizationSchema = z.object({
709
+ id: z.number(),
710
+ flow_data_id: z.number(),
711
+ created_at: z.string(),
712
+ sql: z.string(),
713
+ bookmarked: z.boolean(),
714
+ data_sample: z.array(z.record(z.unknown())),
715
+ is_sample: z.boolean(),
716
+ data_summary: z.record(z.unknown())
717
+ });
718
+ var V1VisualizationSchema = BaseVisualizationSchema.merge(z.object({
719
+ configuration: V1VisualizationConfigurationSchema
720
+ }));
721
+ var VisualizationSchema = BaseVisualizationSchema.merge(z.object({
722
+ configuration: VisualizationConfigurationSchema
723
+ }));
724
+ var VisualizationDataSchema = z.array(z.record(
725
+ z.string(),
726
+ // any key
727
+ z.union([
728
+ // Date objects FIRST
729
+ z.date(),
730
+ z.coerce.number(),
731
+ // Handle various data types including BigQueryDate
732
+ z.unknown().transform((val) => formatDataValue(val).display)
733
+ ])
734
+ )).openapi("VisualizationData");
735
+ var V1FrontendVisualizationSchema = V1VisualizationSchema.omit({
736
+ sql: true,
737
+ data_sample: true,
738
+ is_sample: true,
739
+ data_summary: true
740
+ });
741
+ var FrontendVisualizationSchema = VisualizationSchema.omit({
742
+ sql: true,
743
+ data_sample: true,
744
+ is_sample: true,
745
+ data_summary: true
746
+ });
747
+ var VisualizationMetadataSchema = z.object({
748
+ wasSampled: z.boolean(),
749
+ originalCount: z.number(),
750
+ sampledCount: z.number()
751
+ }).optional();
752
+ V1FrontendVisualizationSchema.extend({
753
+ data: VisualizationDataSchema,
754
+ _metadata: VisualizationMetadataSchema
755
+ });
756
+ FrontendVisualizationSchema.extend({
757
+ data: VisualizationDataSchema,
758
+ _metadata: VisualizationMetadataSchema
759
+ });
760
+
761
+ // ../shared/dist/src/endpoints/companion/flows.routes.js
762
+ var FlowIdParam = z.object({ flowId: z.string().uuid() }).openapi("FlowId", { type: "string" });
763
+ var FlowDataIdParam = z.object({ flowDataId: z.string().pipe(z.coerce.number()) }).openapi("FlowDataId", { type: "integer" });
764
+ var ReportId = z.string().pipe(z.coerce.number());
765
+ var ReportIdParam = z.object({ report_id: ReportId }).openapi("ReportId", { type: "integer" });
766
+ createRoute({
767
+ method: "get",
768
+ path: "/api/v1/flows/{flowId}/data-reports",
769
+ operationId: "retrieveFlowDataReports",
770
+ request: {
771
+ headers: SupabaseHeaderSchema,
772
+ params: FlowIdParam
773
+ },
774
+ responses: {
775
+ 200: {
776
+ description: "The data reports associated with the flow",
777
+ content: {
778
+ "application/json": {
779
+ schema: FrontendReportSchema.array()
780
+ }
781
+ }
782
+ },
783
+ 404: {
784
+ content: {
785
+ "application/json": {
786
+ schema: z.object({ error: z.string() })
787
+ }
788
+ },
789
+ description: "Unable to retrieve flow with this id"
790
+ },
791
+ 500: {
792
+ description: "Something wrong happened",
793
+ content: {
794
+ "application/json": {
795
+ schema: z.object({
796
+ error: z.string()
797
+ })
798
+ }
799
+ }
800
+ }
801
+ }
802
+ });
803
+ createRoute({
804
+ method: "get",
805
+ path: "/api/v1/flows/{flowId}/data-reports/last/status",
806
+ operationId: "retrieveLatestDataReportStatus",
807
+ request: {
808
+ headers: SupabaseHeaderSchema,
809
+ params: FlowIdParam
810
+ },
811
+ responses: {
812
+ 200: {
813
+ description: "The status of the latest flow data for a given flow",
814
+ content: {
815
+ "application/json": {
816
+ schema: z.object({ status: z.string().nullable() })
817
+ }
818
+ }
819
+ },
820
+ 404: {
821
+ content: {
822
+ "application/json": {
823
+ schema: z.object({ error: z.string() })
824
+ }
825
+ },
826
+ description: "Unable to retrieve status for latest flow data of flow with this id"
827
+ },
828
+ 500: {
829
+ description: "Something wrong happened",
830
+ content: {
831
+ "application/json": {
832
+ schema: z.object({
833
+ error: z.string()
834
+ })
835
+ }
836
+ }
837
+ }
838
+ }
839
+ });
840
+ createRoute({
841
+ // this endpoint is deprecated and will be removed in the future
842
+ hide: true,
843
+ method: "get",
844
+ path: "/api/v1/flows/{flowId}/insights",
845
+ operationId: "retrieveInsights",
846
+ request: {
847
+ headers: SupabaseHeaderSchema,
848
+ params: FlowIdParam,
849
+ query: z.object({
850
+ flowDataId: z.string().pipe(z.coerce.number()).optional().openapi({
851
+ param: {
852
+ required: false
853
+ },
854
+ type: "integer"
855
+ })
856
+ })
857
+ },
858
+ responses: {
859
+ 200: {
860
+ description: "The content of the flow",
861
+ content: {
862
+ "application/json": {
863
+ schema: z.object({
864
+ dataReports: FrontendReportSchema.array(),
865
+ visualizations: V1FrontendVisualizationSchema.array()
866
+ })
867
+ }
868
+ }
869
+ },
870
+ 404: {
871
+ content: {
872
+ "application/json": {
873
+ schema: z.object({ error: z.string() })
874
+ }
875
+ },
876
+ description: "Unable to retrieve flow with this id"
877
+ },
878
+ 500: {
879
+ description: "Something wrong happened",
880
+ content: {
881
+ "application/json": {
882
+ schema: z.object({
883
+ error: z.string()
884
+ })
885
+ }
886
+ }
887
+ }
888
+ }
889
+ });
890
+ createRoute({
891
+ // this endpoint is deprecated and will be removed in the future
892
+ hide: true,
893
+ method: "get",
894
+ path: "/api/v1/flows/{flowId}/columns",
895
+ operationId: "retrieveFlowColumns",
896
+ request: {
897
+ headers: SupabaseHeaderSchema,
898
+ params: FlowIdParam,
899
+ query: FlowDataIdParam
900
+ },
901
+ responses: {
902
+ 200: {
903
+ description: "A list containing the columns of the flow",
904
+ content: {
905
+ "application/json": {
906
+ schema: FrontendReportColumnsSchema
907
+ }
908
+ }
909
+ },
910
+ 404: {
911
+ content: {
912
+ "application/json": {
913
+ schema: z.object({ error: z.string() })
914
+ }
915
+ },
916
+ description: "Unable to retrieve flow with this id"
917
+ },
918
+ 500: {
919
+ description: "Something wrong happened",
920
+ content: {
921
+ "application/json": {
922
+ schema: z.object({
923
+ error: z.string()
924
+ })
925
+ }
926
+ }
927
+ }
928
+ }
929
+ });
930
+ createRoute({
931
+ method: "get",
932
+ path: "/api/v1/flows/{flowId}",
933
+ operationId: "retrieveFlow",
934
+ request: {
935
+ headers: SupabaseHeaderSchema,
936
+ params: FlowIdParam
937
+ },
938
+ responses: {
939
+ 200: {
940
+ description: "The flow with its steps",
941
+ content: {
942
+ "application/json": {
943
+ schema: FrontendFlowSchema
944
+ }
945
+ }
946
+ },
947
+ 404: {
948
+ content: {
949
+ "application/json": {
950
+ schema: z.object({ error: z.string() })
951
+ }
952
+ },
953
+ description: "Unable to retrieve flow with this id"
954
+ },
955
+ 500: {
956
+ description: "Something wrong happened",
957
+ content: {
958
+ "application/json": {
959
+ schema: z.object({
960
+ error: z.string()
961
+ })
962
+ }
963
+ }
964
+ }
965
+ }
966
+ });
967
+ var RetrieveRecentFlows = createRoute({
968
+ method: "get",
969
+ path: "/api/v1/recent-flows",
970
+ operationId: "retrieveRecentFlows",
971
+ request: {
972
+ headers: SupabaseHeaderSchema,
973
+ query: z.object({
974
+ limit: limitQueryParams
975
+ })
976
+ },
977
+ responses: {
978
+ 200: {
979
+ description: "A list of recent flows",
980
+ content: {
981
+ "application/json": {
982
+ schema: FrontendRecentFlowsSchema.array()
983
+ }
984
+ }
985
+ },
986
+ 500: {
987
+ description: "Something wrong happened",
988
+ content: {
989
+ "application/json": {
990
+ schema: z.object({
991
+ error: z.string()
992
+ })
993
+ }
994
+ }
995
+ }
996
+ }
997
+ });
998
+ createRoute({
999
+ method: "get",
1000
+ path: "/api/v1/data-reports/{report_id}/columns",
1001
+ operationId: "getDataReportColumns",
1002
+ request: {
1003
+ headers: SupabaseHeaderSchema,
1004
+ params: ReportIdParam
1005
+ },
1006
+ responses: {
1007
+ 200: {
1008
+ description: "A list containing the columns of the report",
1009
+ content: {
1010
+ "application/json": {
1011
+ schema: FrontendReportColumnsSchema
1012
+ }
1013
+ }
1014
+ },
1015
+ 404: {
1016
+ content: {
1017
+ "application/json": {
1018
+ schema: z.object({ error: z.string() })
1019
+ }
1020
+ },
1021
+ description: "Unable to retrieve report with this id"
1022
+ },
1023
+ 500: {
1024
+ description: "Something wrong happened",
1025
+ content: {
1026
+ "application/json": {
1027
+ schema: z.object({
1028
+ error: z.string()
1029
+ })
1030
+ }
1031
+ }
1032
+ }
1033
+ }
1034
+ });
1035
+ var ExportReportData = createRoute({
1036
+ method: "get",
1037
+ path: "/api/v1/data-reports/{report_id}/export",
1038
+ operationId: "exportReportData",
1039
+ request: {
1040
+ headers: SupabaseHeaderSchema,
1041
+ params: ReportIdParam
1042
+ },
1043
+ responses: {
1044
+ 200: {
1045
+ description: "The report data exported in CSV format",
1046
+ content: {
1047
+ "text/csv": {
1048
+ schema: z.string().describe("CSV formatted string of report data")
1049
+ }
1050
+ }
1051
+ },
1052
+ 404: {
1053
+ content: {
1054
+ "application/json": {
1055
+ schema: z.object({ error: z.string() })
1056
+ }
1057
+ },
1058
+ description: "Unable to retrieve flow with this id"
1059
+ },
1060
+ 500: {
1061
+ description: "Something wrong happened",
1062
+ content: {
1063
+ "application/json": {
1064
+ schema: z.object({
1065
+ error: z.string()
1066
+ })
1067
+ }
1068
+ }
1069
+ }
1070
+ }
1071
+ });
1072
+ createRoute({
1073
+ // this endpoint is deprecated and will be removed in the future
1074
+ hide: true,
1075
+ method: "get",
1076
+ path: "/api/v1/flows/{flowId}/data",
1077
+ operationId: "retrieveFlowData",
1078
+ request: {
1079
+ headers: SupabaseHeaderSchema,
1080
+ params: FlowIdParam,
1081
+ query: z.object({
1082
+ limit: limitQueryParams,
1083
+ order: orderQueryParams,
1084
+ cursor: cursorParams,
1085
+ filter: filterQueryParams,
1086
+ flowDataId: FlowDataIdParam.shape.flowDataId.openapi({
1087
+ type: "integer",
1088
+ param: { required: true }
1089
+ })
1090
+ })
1091
+ },
1092
+ responses: {
1093
+ 200: {
1094
+ description: "The content of the flow",
1095
+ content: {
1096
+ "application/json": {
1097
+ schema: ReportDataSchema
1098
+ }
1099
+ }
1100
+ },
1101
+ 404: {
1102
+ content: {
1103
+ "application/json": {
1104
+ schema: z.object({ error: z.string() })
1105
+ }
1106
+ },
1107
+ description: "Unable to retrieve flow with this id"
1108
+ },
1109
+ 500: {
1110
+ description: "Something wrong happened",
1111
+ content: {
1112
+ "application/json": {
1113
+ schema: z.object({
1114
+ error: z.string()
1115
+ })
1116
+ }
1117
+ }
1118
+ }
1119
+ }
1120
+ });
1121
+ createRoute({
1122
+ method: "get",
1123
+ path: "/api/v1/data-reports/{report_id}/data",
1124
+ operationId: "getDataReportData",
1125
+ request: {
1126
+ headers: SupabaseHeaderSchema,
1127
+ params: ReportIdParam,
1128
+ query: z.object({
1129
+ columns: columnsQueryParams,
1130
+ limit: limitQueryParams,
1131
+ order: orderQueryParams,
1132
+ cursor: cursorParams,
1133
+ filter: filterQueryParams
1134
+ })
1135
+ },
1136
+ responses: {
1137
+ 200: {
1138
+ description: "The content of the report",
1139
+ content: {
1140
+ "application/json": {
1141
+ schema: ReportDataSchema
1142
+ }
1143
+ }
1144
+ },
1145
+ 404: {
1146
+ content: {
1147
+ "application/json": {
1148
+ schema: z.object({ error: z.string() })
1149
+ }
1150
+ },
1151
+ description: "Unable to retrieve report with this id"
1152
+ },
1153
+ 500: {
1154
+ description: "Something wrong happened",
1155
+ content: {
1156
+ "application/json": {
1157
+ schema: z.object({
1158
+ error: z.string()
1159
+ })
1160
+ }
1161
+ }
1162
+ }
1163
+ }
1164
+ });
1165
+ createRoute({
1166
+ // this endpoint is deprecated and will be removed in the future
1167
+ hide: true,
1168
+ method: "get",
1169
+ path: "/api/v1/flows/{flowId}/count",
1170
+ operationId: "retrieveFlowDataCount",
1171
+ request: {
1172
+ headers: SupabaseHeaderSchema,
1173
+ params: FlowIdParam,
1174
+ query: z.object({
1175
+ flowDataId: z.string().pipe(z.coerce.number()).openapi({
1176
+ param: {
1177
+ required: false
1178
+ },
1179
+ type: "integer"
1180
+ })
1181
+ })
1182
+ },
1183
+ responses: {
1184
+ 200: {
1185
+ description: "The total count of rows in the flow",
1186
+ content: {
1187
+ "application/json": {
1188
+ schema: z.object({
1189
+ count: z.number().int().nonnegative().describe("Total number of rows in the flow")
1190
+ })
1191
+ }
1192
+ }
1193
+ },
1194
+ 404: {
1195
+ content: {
1196
+ "application/json": {
1197
+ schema: z.object({ error: z.string() })
1198
+ }
1199
+ },
1200
+ description: "Unable to retrieve flow with this id"
1201
+ },
1202
+ 500: {
1203
+ description: "Something wrong happened",
1204
+ content: {
1205
+ "application/json": {
1206
+ schema: z.object({
1207
+ error: z.string()
1208
+ })
1209
+ }
1210
+ }
1211
+ }
1212
+ }
1213
+ });
1214
+ createRoute({
1215
+ method: "get",
1216
+ path: "/api/v1/data-reports/{report_id}/count",
1217
+ operationId: "getDataReportRowCount",
1218
+ request: {
1219
+ headers: SupabaseHeaderSchema,
1220
+ params: ReportIdParam
1221
+ },
1222
+ responses: {
1223
+ 200: {
1224
+ description: "The total count of rows in the report",
1225
+ content: {
1226
+ "application/json": {
1227
+ schema: z.object({
1228
+ count: z.number().int().nonnegative().describe("Total number of rows in the report")
1229
+ })
1230
+ }
1231
+ }
1232
+ },
1233
+ 404: {
1234
+ content: {
1235
+ "application/json": {
1236
+ schema: z.object({ error: z.string() })
1237
+ }
1238
+ },
1239
+ description: "Unable to retrieve report with this id"
1240
+ },
1241
+ 500: {
1242
+ description: "Something wrong happened",
1243
+ content: {
1244
+ "application/json": {
1245
+ schema: z.object({
1246
+ error: z.string()
1247
+ })
1248
+ }
1249
+ }
1250
+ }
1251
+ }
1252
+ });
1253
+ createRoute({
1254
+ // this endpoint is deprecated and will be removed in the future
1255
+ hide: true,
1256
+ method: "get",
1257
+ path: "/api/v1/flow-data/{flowDataId}/feedback",
1258
+ operationId: "retrieveFeedback",
1259
+ request: {
1260
+ headers: SupabaseHeaderSchema,
1261
+ params: FlowDataIdParam
1262
+ },
1263
+ responses: {
1264
+ 200: {
1265
+ description: "The feedback for the flow data",
1266
+ content: {
1267
+ "application/json": {
1268
+ schema: FeedbackSchema.nullable()
1269
+ }
1270
+ }
1271
+ },
1272
+ 404: {
1273
+ content: {
1274
+ "application/json": {
1275
+ schema: z.object({ error: z.string() })
1276
+ }
1277
+ },
1278
+ description: "Unable to retrieve feedback"
1279
+ },
1280
+ 500: {
1281
+ description: "Something wrong happened",
1282
+ content: {
1283
+ "application/json": {
1284
+ schema: z.object({
1285
+ error: z.string()
1286
+ })
1287
+ }
1288
+ }
1289
+ }
1290
+ }
1291
+ });
1292
+ createRoute({
1293
+ method: "get",
1294
+ path: "/api/v1/data-reports/{report_id}/feedback",
1295
+ operationId: "getDataReportFeedback",
1296
+ request: {
1297
+ headers: SupabaseHeaderSchema,
1298
+ params: ReportIdParam
1299
+ },
1300
+ responses: {
1301
+ 200: {
1302
+ description: "The feedback for the report",
1303
+ content: {
1304
+ "application/json": {
1305
+ schema: FeedbackSchema.nullable()
1306
+ }
1307
+ }
1308
+ },
1309
+ 404: {
1310
+ content: {
1311
+ "application/json": {
1312
+ schema: z.object({ error: z.string() })
1313
+ }
1314
+ },
1315
+ description: "Unable to retrieve feedback"
1316
+ },
1317
+ 500: {
1318
+ description: "Something wrong happened",
1319
+ content: {
1320
+ "application/json": {
1321
+ schema: z.object({
1322
+ error: z.string()
1323
+ })
1324
+ }
1325
+ }
1326
+ }
1327
+ }
1328
+ });
1329
+ createRoute({
1330
+ // this endpoint is deprecated and will be removed in the future
1331
+ hide: true,
1332
+ method: "post",
1333
+ path: "/api/v1/flow-data/{flowDataId}/feedback",
1334
+ operationId: "upsertFeedback",
1335
+ request: {
1336
+ headers: SupabaseHeaderSchema,
1337
+ params: FlowDataIdParam,
1338
+ body: {
1339
+ description: "The feedback for the flow data",
1340
+ required: true,
1341
+ content: {
1342
+ "application/json": {
1343
+ schema: z.object({
1344
+ helpfulness: FeedbackSchema.shape.helpfulness
1345
+ })
1346
+ }
1347
+ }
1348
+ }
1349
+ },
1350
+ responses: {
1351
+ 200: {
1352
+ description: "Successfully upserted feedback"
1353
+ },
1354
+ 500: {
1355
+ description: "Something wrong happened",
1356
+ content: {
1357
+ "application/json": {
1358
+ schema: z.object({
1359
+ error: z.string()
1360
+ })
1361
+ }
1362
+ }
1363
+ }
1364
+ }
1365
+ });
1366
+ createRoute({
1367
+ method: "post",
1368
+ path: "/api/v1/data-reports/{report_id}/feedback",
1369
+ operationId: "upsertReportFeedback",
1370
+ request: {
1371
+ headers: SupabaseHeaderSchema,
1372
+ params: ReportIdParam,
1373
+ body: {
1374
+ description: "The feedback for the flow data",
1375
+ required: true,
1376
+ content: {
1377
+ "application/json": {
1378
+ schema: z.object({
1379
+ helpfulness: FeedbackSchema.shape.helpfulness
1380
+ })
1381
+ }
1382
+ }
1383
+ }
1384
+ },
1385
+ responses: {
1386
+ 200: {
1387
+ description: "Successfully upserted feedback"
1388
+ },
1389
+ 500: {
1390
+ description: "Something wrong happened",
1391
+ content: {
1392
+ "application/json": {
1393
+ schema: z.object({
1394
+ error: z.string()
1395
+ })
1396
+ }
1397
+ }
1398
+ }
1399
+ }
1400
+ });
1401
+ createRoute({
1402
+ // this endpoint is deprecated and will be removed in the future
1403
+ hide: true,
1404
+ method: "delete",
1405
+ path: "/api/v1/flow-data/{flowDataId}/feedback",
1406
+ operationId: "deleteFeedback",
1407
+ request: {
1408
+ headers: SupabaseHeaderSchema,
1409
+ params: FlowDataIdParam
1410
+ },
1411
+ responses: {
1412
+ 200: {
1413
+ description: "Successfully deleted feedback"
1414
+ },
1415
+ 404: {
1416
+ content: {
1417
+ "application/json": {
1418
+ schema: z.object({ error: z.string() })
1419
+ }
1420
+ },
1421
+ description: "Unable to retrieve feedback"
1422
+ },
1423
+ 500: {
1424
+ description: "Something wrong happened",
1425
+ content: {
1426
+ "application/json": {
1427
+ schema: z.object({
1428
+ error: z.string()
1429
+ })
1430
+ }
1431
+ }
1432
+ }
1433
+ }
1434
+ });
1435
+ createRoute({
1436
+ method: "delete",
1437
+ path: "/api/v1/data-reports/{report_id}/feedback",
1438
+ operationId: "deleteReportFeedback",
1439
+ request: {
1440
+ headers: SupabaseHeaderSchema,
1441
+ params: ReportIdParam
1442
+ },
1443
+ responses: {
1444
+ 200: {
1445
+ description: "Successfully deleted feedback"
1446
+ },
1447
+ 404: {
1448
+ content: {
1449
+ "application/json": {
1450
+ schema: z.object({ error: z.string() })
1451
+ }
1452
+ },
1453
+ description: "Unable to retrieve feedback"
1454
+ },
1455
+ 500: {
1456
+ description: "Something wrong happened",
1457
+ content: {
1458
+ "application/json": {
1459
+ schema: z.object({
1460
+ error: z.string()
1461
+ })
1462
+ }
1463
+ }
1464
+ }
1465
+ }
1466
+ });
1467
+ createRoute({
1468
+ // this endpoint is deprecated and will be removed in the future
1469
+ hide: true,
1470
+ method: "get",
1471
+ path: "/api/v1/flow-data/{flowDataId}/explainability",
1472
+ operationId: "retrieveFlowDataExplainability",
1473
+ request: {
1474
+ headers: SupabaseHeaderSchema,
1475
+ params: FlowDataIdParam
1476
+ },
1477
+ responses: {
1478
+ 200: {
1479
+ description: "The explainability of the flow data",
1480
+ content: {
1481
+ "application/json": {
1482
+ schema: FrontendReportExplainabilitySchema
1483
+ }
1484
+ }
1485
+ },
1486
+ 404: {
1487
+ content: {
1488
+ "application/json": {
1489
+ schema: z.object({ error: z.string() })
1490
+ }
1491
+ },
1492
+ description: "Unable to retrieve flow with this id"
1493
+ },
1494
+ 500: {
1495
+ description: "Something wrong happened",
1496
+ content: {
1497
+ "application/json": {
1498
+ schema: z.object({
1499
+ error: z.string()
1500
+ })
1501
+ }
1502
+ }
1503
+ }
1504
+ }
1505
+ });
1506
+ createRoute({
1507
+ method: "get",
1508
+ path: "/api/v1/data-reports/{report_id}/explainability",
1509
+ operationId: "getDataReportExplainability",
1510
+ request: {
1511
+ headers: SupabaseHeaderSchema,
1512
+ params: ReportIdParam
1513
+ },
1514
+ responses: {
1515
+ 200: {
1516
+ description: "The explainability of the report",
1517
+ content: {
1518
+ "application/json": {
1519
+ schema: FrontendReportExplainabilitySchema
1520
+ }
1521
+ }
1522
+ },
1523
+ 404: {
1524
+ content: {
1525
+ "application/json": {
1526
+ schema: z.object({ error: z.string() })
1527
+ }
1528
+ },
1529
+ description: "Unable to retrieve report with this id"
1530
+ },
1531
+ 500: {
1532
+ description: "Something wrong happened",
1533
+ content: {
1534
+ "application/json": {
1535
+ schema: z.object({
1536
+ error: z.string()
1537
+ })
1538
+ }
1539
+ }
1540
+ }
1541
+ }
1542
+ });
1543
+ createRoute({
1544
+ method: "get",
1545
+ path: "/api/v1/data-reports/{report_id}",
1546
+ operationId: "getDataReport",
1547
+ request: {
1548
+ headers: SupabaseHeaderSchema,
1549
+ params: ReportIdParam
1550
+ },
1551
+ responses: {
1552
+ 200: {
1553
+ description: "The visualizations for the report",
1554
+ content: {
1555
+ "application/json": {
1556
+ schema: FrontendReportSchema
1557
+ }
1558
+ }
1559
+ },
1560
+ 404: {
1561
+ content: {
1562
+ "application/json": {
1563
+ schema: z.object({ error: z.string() })
1564
+ }
1565
+ },
1566
+ description: "Unable to retrieve report with this id"
1567
+ },
1568
+ 500: {
1569
+ description: "Something wrong happened",
1570
+ content: {
1571
+ "application/json": {
1572
+ schema: z.object({
1573
+ error: z.string()
1574
+ })
1575
+ }
1576
+ }
1577
+ }
1578
+ }
1579
+ });
1580
+ createRoute({
1581
+ hide: true,
1582
+ method: "get",
1583
+ path: "/api/v1/data-reports/{report_id}/visualizations",
1584
+ operationId: "getDataReportVisualizations",
1585
+ request: {
1586
+ headers: SupabaseHeaderSchema,
1587
+ params: ReportIdParam
1588
+ },
1589
+ responses: {
1590
+ 200: {
1591
+ description: "The visualizations for the report",
1592
+ content: {
1593
+ "application/json": {
1594
+ schema: FrontendReportSchema.merge(z.object({
1595
+ visualizations: z.union([
1596
+ V1FrontendVisualizationSchema,
1597
+ FrontendVisualizationSchema
1598
+ ]).array()
1599
+ }))
1600
+ }
1601
+ }
1602
+ },
1603
+ 404: {
1604
+ content: {
1605
+ "application/json": {
1606
+ schema: z.object({ error: z.string() })
1607
+ }
1608
+ },
1609
+ description: "Unable to retrieve report with this id"
1610
+ },
1611
+ 500: {
1612
+ description: "Something wrong happened",
1613
+ content: {
1614
+ "application/json": {
1615
+ schema: z.object({
1616
+ error: z.string()
1617
+ })
1618
+ }
1619
+ }
1620
+ }
1621
+ }
1622
+ });
1623
+ var CreateFlow = createRoute({
1624
+ method: "post",
1625
+ path: "/api/v1/flows",
1626
+ operationId: "createFlow",
1627
+ request: {
1628
+ headers: SupabaseHeaderSchema,
1629
+ body: {
1630
+ required: true,
1631
+ content: {
1632
+ "application/json": {
1633
+ schema: z.object({
1634
+ userQuery: z.string()
1635
+ })
1636
+ }
1637
+ }
1638
+ }
1639
+ },
1640
+ responses: {
1641
+ 200: {
1642
+ description: "Create a new flow",
1643
+ content: {
1644
+ "application/json": {
1645
+ schema: z.object({
1646
+ status: z.literal("success"),
1647
+ flowId: z.string()
1648
+ })
1649
+ }
1650
+ }
1651
+ },
1652
+ 500: {
1653
+ description: "Something wrong happened",
1654
+ content: {
1655
+ "application/json": {
1656
+ schema: z.object({
1657
+ error: z.string()
1658
+ })
1659
+ }
1660
+ }
1661
+ }
1662
+ }
1663
+ });
1664
+
1665
+ // ../shared/dist/src/endpoints/admin-console/contextualInsights.routes.js
1666
+ var ExtractInsightResponseSchema = z.object({
1667
+ type: z.literal("text"),
1668
+ insight: z.string()
1669
+ }).or(z.object({
1670
+ type: z.literal("missing")
1671
+ }));
1672
+ createRoute({
1673
+ method: "post",
1674
+ path: "/api/v1/admin-console/contextual-insights/generate-template",
1675
+ operationId: "generateInsightTemplate",
1676
+ request: {
1677
+ body: {
1678
+ content: {
1679
+ "application/json": {
1680
+ schema: z.object({
1681
+ request: z.string(),
1682
+ insight_type: z.string(),
1683
+ additional_context: z.string().optional()
1684
+ })
1685
+ }
1686
+ }
1687
+ }
1688
+ },
1689
+ responses: {
1690
+ 200: {
1691
+ description: "Insight template generated successfully",
1692
+ content: {
1693
+ "application/json": {
1694
+ schema: z.object({
1695
+ expanded_request: z.string()
1696
+ })
1697
+ }
1698
+ }
1699
+ },
1700
+ 500: {
1701
+ description: "Something wrong happened",
1702
+ content: {
1703
+ "application/json": {
1704
+ schema: z.object({
1705
+ error: z.string()
1706
+ })
1707
+ }
1708
+ }
1709
+ }
1710
+ }
1711
+ });
1712
+ createRoute({
1713
+ method: "get",
1714
+ path: "/api/v1/admin-console/contextual-insights/preview/{report_id}/data",
1715
+ operationId: "getContextualInsightPreviewData",
1716
+ request: {
1717
+ params: ReportIdParam,
1718
+ query: z.object({
1719
+ limit: limitQueryParams,
1720
+ order: orderQueryParams,
1721
+ cursor: cursorParams,
1722
+ filter: filterQueryParams
1723
+ })
1724
+ },
1725
+ responses: {
1726
+ 200: {
1727
+ description: "The preview data for the contextual insight",
1728
+ content: {
1729
+ "application/json": {
1730
+ schema: SqlPreviewResponseSchema
1731
+ }
1732
+ }
1733
+ },
1734
+ 404: {
1735
+ content: {
1736
+ "application/json": {
1737
+ schema: z.object({ error: z.string() })
1738
+ }
1739
+ },
1740
+ description: "Unable to retrieve flow data with this id"
1741
+ },
1742
+ 500: {
1743
+ description: "Something wrong happened",
1744
+ content: {
1745
+ "application/json": {
1746
+ schema: z.object({
1747
+ error: z.string()
1748
+ })
1749
+ }
1750
+ }
1751
+ }
1752
+ }
1753
+ });
1754
+ createRoute({
1755
+ method: "get",
1756
+ path: "/api/v1/admin-console/contextual-insights/preview/{report_id}/sample-values",
1757
+ operationId: "getContextualInsightColumnSampleValues",
1758
+ request: {
1759
+ params: ReportIdParam,
1760
+ query: z.object({
1761
+ column_name: z.string().openapi({
1762
+ param: {
1763
+ required: true
1764
+ },
1765
+ type: "string",
1766
+ description: "The column name to get sample values for"
1767
+ })
1768
+ })
1769
+ },
1770
+ responses: {
1771
+ 200: {
1772
+ description: "Sample values for the specified column",
1773
+ content: {
1774
+ "application/json": {
1775
+ schema: z.object({
1776
+ options: z.array(z.unknown())
1777
+ })
1778
+ }
1779
+ }
1780
+ },
1781
+ 404: {
1782
+ content: {
1783
+ "application/json": {
1784
+ schema: z.object({ error: z.string() })
1785
+ }
1786
+ },
1787
+ description: "Unable to retrieve flow data with this id"
1788
+ },
1789
+ 500: {
1790
+ description: "Something wrong happened",
1791
+ content: {
1792
+ "application/json": {
1793
+ schema: z.object({
1794
+ error: z.string()
1795
+ })
1796
+ }
1797
+ }
1798
+ }
1799
+ }
1800
+ });
1801
+ var GenerateInsight = createRoute({
1802
+ method: "post",
1803
+ path: "/api/v1/contextual-insights/generate-insight",
1804
+ operationId: "generateInsight",
1805
+ request: {
1806
+ body: {
1807
+ content: {
1808
+ "application/json": {
1809
+ schema: z.object({
1810
+ selected_filter_value: z.string(),
1811
+ custom_id: z.string()
1812
+ })
1813
+ }
1814
+ }
1815
+ }
1816
+ },
1817
+ responses: {
1818
+ 200: {
1819
+ description: "Insight generated successfully",
1820
+ content: {
1821
+ "application/json": {
1822
+ schema: ExtractInsightResponseSchema
1823
+ }
1824
+ }
1825
+ },
1826
+ 404: {
1827
+ description: "Insight not found",
1828
+ content: {
1829
+ "application/json": {
1830
+ schema: z.object({
1831
+ error: z.string()
1832
+ })
1833
+ }
1834
+ }
1835
+ },
1836
+ 400: {
1837
+ description: "Invalid request",
1838
+ content: {
1839
+ "application/json": {
1840
+ schema: z.object({
1841
+ error: z.string()
1842
+ })
1843
+ }
1844
+ }
1845
+ },
1846
+ 500: {
1847
+ description: "Something wrong happened",
1848
+ content: {
1849
+ "application/json": {
1850
+ schema: z.object({
1851
+ error: z.string()
1852
+ })
1853
+ }
1854
+ }
1855
+ }
1856
+ }
1857
+ });
1858
+ createRoute({
1859
+ method: "post",
1860
+ path: "/api/v1/admin-console/contextual-insights/extract-insight",
1861
+ operationId: "extractInsight",
1862
+ request: {
1863
+ body: {
1864
+ content: {
1865
+ "application/json": {
1866
+ schema: z.object({
1867
+ flow_id: z.string(),
1868
+ report_id: z.number(),
1869
+ topic: z.string(),
1870
+ expanded_request: z.string(),
1871
+ insight_type: z.string(),
1872
+ selected_filter: z.string(),
1873
+ selected_filter_value: z.string(),
1874
+ additional_context: z.string().optional()
1875
+ })
1876
+ }
1877
+ }
1878
+ }
1879
+ },
1880
+ responses: {
1881
+ 200: {
1882
+ description: "Insight extracted successfully",
1883
+ content: {
1884
+ "application/json": {
1885
+ schema: ExtractInsightResponseSchema
1886
+ }
1887
+ }
1888
+ },
1889
+ 500: {
1890
+ description: "Something wrong happened",
1891
+ content: {
1892
+ "application/json": {
1893
+ schema: z.object({
1894
+ error: z.string()
1895
+ })
1896
+ }
1897
+ }
1898
+ }
1899
+ }
1900
+ });
1901
+ createRoute({
1902
+ method: "post",
1903
+ path: "/api/v1/admin-console/contextual-insights/suggest-filter-column",
1904
+ operationId: "suggestFilterColumn",
1905
+ request: {
1906
+ body: {
1907
+ content: {
1908
+ "application/json": {
1909
+ schema: z.object({
1910
+ report_id: z.number(),
1911
+ request: z.string(),
1912
+ insight_type: z.string(),
1913
+ additional_context: z.string().optional()
1914
+ })
1915
+ }
1916
+ }
1917
+ }
1918
+ },
1919
+ responses: {
1920
+ 200: {
1921
+ description: "Filter column suggestion generated successfully",
1922
+ content: {
1923
+ "application/json": {
1924
+ schema: z.object({
1925
+ recommended_column: z.string(),
1926
+ reasoning: z.string()
1927
+ })
1928
+ }
1929
+ }
1930
+ },
1931
+ 404: {
1932
+ description: "Report not found",
1933
+ content: {
1934
+ "application/json": {
1935
+ schema: z.object({
1936
+ error: z.string()
1937
+ })
1938
+ }
1939
+ }
1940
+ },
1941
+ 500: {
1942
+ description: "Something wrong happened",
1943
+ content: {
1944
+ "application/json": {
1945
+ schema: z.object({
1946
+ error: z.string()
1947
+ })
1948
+ }
1949
+ }
1950
+ }
1951
+ }
1952
+ });
1953
+
1954
+ // ../shared/dist/src/endpoints/auth.routes.js
1955
+ var GetApiInformationInputSchema = z.object({
1956
+ apiKey: z.string()
1957
+ });
1958
+ var GetApiInformationOutputSchema = z.object({
1959
+ apiUrl: z.string(),
1960
+ anonKey: z.string()
1961
+ });
1962
+ var GetApiInformation = createRoute({
1963
+ method: "get",
1964
+ path: "/api/v1/auth/apiInformation",
1965
+ operationId: "getApiInformation",
1966
+ request: {
1967
+ query: GetApiInformationInputSchema
1968
+ },
1969
+ responses: {
1970
+ 200: {
1971
+ content: {
1972
+ "application/json": {
1973
+ schema: GetApiInformationOutputSchema
1974
+ }
1975
+ },
1976
+ description: "Retrieve the API URL and anon key"
1977
+ },
1978
+ 400: {
1979
+ content: {
1980
+ "application/json": {
1981
+ schema: z.object({ error: z.string() })
1982
+ }
1983
+ },
1984
+ description: "Invalid input"
1985
+ },
1986
+ 500: {
1987
+ content: {
1988
+ "application/json": {
1989
+ schema: z.object({
1990
+ error: z.string()
1991
+ })
1992
+ }
1993
+ },
1994
+ description: "Unable to retrieve the API URL and anon key"
1995
+ }
1996
+ }
1997
+ });
1998
+ createRoute({
1999
+ hide: true,
2000
+ method: "get",
2001
+ path: "/api/auth/apiInformation",
2002
+ operationId: "getApiInformation",
2003
+ request: {
2004
+ query: GetApiInformationInputSchema
2005
+ },
2006
+ responses: {
2007
+ 200: {
2008
+ content: {
2009
+ "application/json": {
2010
+ schema: GetApiInformationOutputSchema
2011
+ }
2012
+ },
2013
+ description: "Retrieve the API URL and anon key"
2014
+ },
2015
+ 400: {
2016
+ content: {
2017
+ "application/json": {
2018
+ schema: z.object({ error: z.string() })
2019
+ }
2020
+ },
2021
+ description: "Invalid input"
2022
+ },
2023
+ 500: {
2024
+ content: {
2025
+ "application/json": {
2026
+ schema: z.object({
2027
+ error: z.string()
2028
+ })
2029
+ }
2030
+ },
2031
+ description: "Unable to retrieve the API URL and anon key"
2032
+ }
2033
+ }
2034
+ });
2035
+ var ExchangeExternalTokenInputSchema = z.object({
2036
+ apiKey: z.string(),
2037
+ externalJWT: z.string()
2038
+ });
2039
+ var ExchangeExternalTokenOutputSchema = z.object({
2040
+ accessToken: z.string(),
2041
+ refreshToken: z.string()
2042
+ });
2043
+ var ExchangeExternalToken = createRoute({
2044
+ method: "post",
2045
+ path: "/api/v1/auth/exchangeExternalToken",
2046
+ operationId: "exchangeExternalToken",
2047
+ request: {
2048
+ body: {
2049
+ required: true,
2050
+ content: {
2051
+ "application/json": {
2052
+ schema: ExchangeExternalTokenInputSchema
2053
+ }
2054
+ }
2055
+ }
2056
+ },
2057
+ responses: {
2058
+ 200: {
2059
+ content: {
2060
+ "application/json": {
2061
+ schema: ExchangeExternalTokenOutputSchema
2062
+ }
2063
+ },
2064
+ description: "Retrieve a JWT for an external user"
2065
+ },
2066
+ 400: {
2067
+ content: {
2068
+ "application/json": {
2069
+ schema: z.object({ error: z.string() })
2070
+ }
2071
+ },
2072
+ description: "Invalid input"
2073
+ },
2074
+ 500: {
2075
+ content: {
2076
+ "application/json": {
2077
+ schema: z.object({
2078
+ error: z.string()
2079
+ })
2080
+ }
2081
+ },
2082
+ description: "Unable to retrieve a JWT for an external user"
2083
+ }
2084
+ }
2085
+ });
2086
+
2087
+ // ../shared/dist/src/schemas/dashboard.js
2088
+ var DashboardTileSchema = z.discriminatedUnion("type", [
2089
+ z.object({
2090
+ type: z.literal("data-report"),
2091
+ flowId: z.string(),
2092
+ flowDataId: z.number(),
2093
+ title: z.string(),
2094
+ col: z.number(),
2095
+ colSpan: z.number(),
2096
+ rowSpan: z.number()
2097
+ }),
2098
+ z.object({
2099
+ type: z.literal("visualization"),
2100
+ visualizationId: z.number(),
2101
+ title: z.string(),
2102
+ col: z.number(),
2103
+ colSpan: z.number(),
2104
+ rowSpan: z.number()
2105
+ })
2106
+ ]);
2107
+ var DashboardSchema = z.object({
2108
+ company_id: z.number(),
2109
+ created_at: z.string(),
2110
+ description: z.string().nullable(),
2111
+ id: z.string().uuid(),
2112
+ name: z.string(),
2113
+ positions: z.array(DashboardTileSchema),
2114
+ updated_at: z.string(),
2115
+ is_removed: z.boolean(),
2116
+ is_public: z.boolean()
2117
+ });
2118
+ var DashboardIdParam = DashboardSchema.shape.id.openapi("DashboardId", {
2119
+ type: "string",
2120
+ format: "uuid"
2121
+ });
2122
+ var FrontendDashboardSchema = DashboardSchema.omit({
2123
+ company_id: true,
2124
+ created_at: true,
2125
+ updated_at: true,
2126
+ is_removed: true
2127
+ });
2128
+
2129
+ // ../shared/dist/src/endpoints/companion/dashboards.routes.js
2130
+ var RetrieveDashboard = createRoute({
2131
+ method: "get",
2132
+ path: "/api/v1/dashboard/{dashboard_id}",
2133
+ operationId: "retrieveDashboard",
2134
+ request: {
2135
+ headers: SupabaseHeaderSchema,
2136
+ params: z.object({
2137
+ dashboard_id: DashboardIdParam
2138
+ })
2139
+ },
2140
+ responses: {
2141
+ 200: {
2142
+ description: "The dashboard with the given id",
2143
+ content: {
2144
+ "application/json": {
2145
+ schema: FrontendDashboardSchema
2146
+ }
2147
+ }
2148
+ },
2149
+ 404: {
2150
+ content: {
2151
+ "application/json": {
2152
+ schema: z.object({ error: z.string() })
2153
+ }
2154
+ },
2155
+ description: "Unable to retrieve dashboard with this id"
2156
+ },
2157
+ 500: {
2158
+ description: "Something wrong happened",
2159
+ content: {
2160
+ "application/json": {
2161
+ schema: z.object({
2162
+ error: z.string()
2163
+ })
2164
+ }
2165
+ }
2166
+ }
2167
+ }
2168
+ });
2169
+
2170
+ // ../shared/dist/src/endpoints/end2end/run.routes.js
2171
+ var End2EndApiResponseSchema = z.discriminatedUnion("status", [
2172
+ z.object({
2173
+ status: z.literal("error"),
2174
+ error: z.string()
2175
+ }),
2176
+ z.object({
2177
+ status: z.literal("success"),
2178
+ flowId: z.string()
2179
+ })
2180
+ ]);
2181
+ createRoute({
2182
+ method: "post",
2183
+ path: "/api/v1/end2end",
2184
+ operationId: "runEnd2EndFlow",
2185
+ request: {
2186
+ headers: SupabaseHeaderSchema,
2187
+ body: {
2188
+ required: true,
2189
+ content: {
2190
+ "application/json": {
2191
+ schema: z.object({
2192
+ userQuery: z.string(),
2193
+ isNewAnalysisGoal: z.boolean().default(true),
2194
+ difficultyLevel: z.enum(["simple", "moderate", "complex"]).default("complex")
2195
+ })
2196
+ }
2197
+ }
2198
+ }
2199
+ },
2200
+ responses: {
2201
+ 200: {
2202
+ description: "Run the end2end flow",
2203
+ content: {
2204
+ "application/json": {
2205
+ schema: End2EndApiResponseSchema
2206
+ }
2207
+ }
2208
+ }
2209
+ }
2210
+ });
2211
+
2212
+ // ../shared/dist/src/endpoints/companion/triggers.routes.js
2213
+ var TriggerFlowBody = z5.object({
2214
+ triggerId: z5.string(),
2215
+ variables: z5.record(z5.string(), z5.string())
2216
+ });
2217
+ var TriggerFlow = createRoute({
2218
+ method: "post",
2219
+ path: "/api/v1/trigger-flow/",
2220
+ operationId: "triggerFlow",
2221
+ request: {
2222
+ headers: SupabaseHeaderSchema,
2223
+ body: {
2224
+ required: true,
2225
+ description: "Trigger flow request body",
2226
+ content: {
2227
+ "application/json": {
2228
+ schema: TriggerFlowBody
2229
+ }
2230
+ }
2231
+ }
2232
+ },
2233
+ responses: {
2234
+ 200: {
2235
+ description: "Flow id",
2236
+ content: {
2237
+ "application/json": {
2238
+ schema: End2EndApiResponseSchema
2239
+ }
2240
+ }
2241
+ },
2242
+ 400: {
2243
+ content: {
2244
+ "application/json": {
2245
+ schema: z5.object({ error: z5.string() })
2246
+ }
2247
+ },
2248
+ description: "Invalid template or variable values"
2249
+ },
2250
+ 404: {
2251
+ content: {
2252
+ "application/json": {
2253
+ schema: z5.object({ error: z5.string() })
2254
+ }
2255
+ },
2256
+ description: "Unable to retrieve trigger with this id"
2257
+ },
2258
+ 500: {
2259
+ description: "Something wrong happened",
2260
+ content: {
2261
+ "application/json": {
2262
+ schema: z5.object({
2263
+ error: z5.string()
2264
+ })
2265
+ }
2266
+ }
2267
+ }
2268
+ }
2269
+ });
2270
+
2271
+ // src/utils/platform.ts
2272
+ var isBrowser = () => {
2273
+ return typeof window !== "undefined" && typeof document !== "undefined";
2274
+ };
2275
+ var isNode = () => {
2276
+ return typeof process !== "undefined" && typeof process.versions === "object" && "node" in process.versions;
2277
+ };
2278
+ var isReactNative = () => {
2279
+ return typeof navigator !== "undefined" && navigator.product === "ReactNative";
2280
+ };
2281
+ var getPlatform = () => {
2282
+ if (isReactNative()) return "react-native";
2283
+ if (isBrowser()) return "browser";
2284
+ if (isNode()) return "node";
2285
+ return "unknown";
2286
+ };
2287
+
2288
+ // src/adapters/storage/browser.ts
2289
+ var BrowserStorageAdapter = class {
2290
+ // eslint-disable-next-line @typescript-eslint/require-await
2291
+ async getItem(key) {
2292
+ try {
2293
+ return localStorage.getItem(key);
2294
+ } catch (error) {
2295
+ console.warn(
2296
+ "BrowserStorageAdapter: Failed to get item from localStorage",
2297
+ error
2298
+ );
2299
+ return null;
2300
+ }
2301
+ }
2302
+ // eslint-disable-next-line @typescript-eslint/require-await
2303
+ async setItem(key, value) {
2304
+ try {
2305
+ localStorage.setItem(key, value);
2306
+ } catch (error) {
2307
+ console.warn(
2308
+ "BrowserStorageAdapter: Failed to set item in localStorage",
2309
+ error
2310
+ );
2311
+ throw error;
2312
+ }
2313
+ }
2314
+ // eslint-disable-next-line @typescript-eslint/require-await
2315
+ async removeItem(key) {
2316
+ try {
2317
+ localStorage.removeItem(key);
2318
+ } catch (error) {
2319
+ console.warn(
2320
+ "BrowserStorageAdapter: Failed to remove item from localStorage",
2321
+ error
2322
+ );
2323
+ throw error;
2324
+ }
2325
+ }
2326
+ };
2327
+
2328
+ // src/adapters/storage/memory.ts
2329
+ var MemoryStorageAdapter = class {
2330
+ storage = /* @__PURE__ */ new Map();
2331
+ // eslint-disable-next-line @typescript-eslint/require-await
2332
+ async getItem(key) {
2333
+ const value = this.storage.get(key);
2334
+ return value !== void 0 ? value : null;
2335
+ }
2336
+ // eslint-disable-next-line @typescript-eslint/require-await
2337
+ async setItem(key, value) {
2338
+ this.storage.set(key, value);
2339
+ }
2340
+ // eslint-disable-next-line @typescript-eslint/require-await
2341
+ async removeItem(key) {
2342
+ this.storage.delete(key);
2343
+ }
2344
+ };
2345
+
2346
+ // src/adapters/storage/factory.ts
2347
+ var createStorageAdapter = () => {
2348
+ const platform = getPlatform();
2349
+ switch (platform) {
2350
+ case "browser":
2351
+ return new BrowserStorageAdapter();
2352
+ case "node":
2353
+ return new MemoryStorageAdapter();
2354
+ case "react-native":
2355
+ throw new Error("Please provide AsyncStorage for React Native");
2356
+ case "unknown":
2357
+ default:
2358
+ console.warn(
2359
+ `Unknown platform detected: ${platform}. Defaulting to in memory storage.`
2360
+ );
2361
+ return new MemoryStorageAdapter();
2362
+ }
2363
+ };
2364
+ var hashString = (value) => {
2365
+ const encoder = new TextEncoder();
2366
+ const data = encoder.encode(value);
2367
+ const hash = sha256(data);
2368
+ return Array.from(hash).map((b) => b.toString(16).padStart(2, "0")).join("");
2369
+ };
2370
+
2371
+ // package.json
2372
+ var package_default = {
2373
+ version: "0.1.0"};
2374
+
2375
+ // src/core/MageMetricsEventEmitter.ts
2376
+ var MageMetricsEventEmitter = class {
2377
+ listeners = /* @__PURE__ */ new Map();
2378
+ addEventListener(type, listener, options) {
2379
+ if (!this.listeners.has(type)) {
2380
+ this.listeners.set(type, /* @__PURE__ */ new Set());
2381
+ }
2382
+ if (options?.signal) {
2383
+ if (options.signal.aborted) {
2384
+ return;
2385
+ }
2386
+ const abortHandler = () => {
2387
+ this.removeEventListener(type, listener);
2388
+ };
2389
+ options.signal.addEventListener("abort", abortHandler, { once: true });
2390
+ }
2391
+ this.listeners.get(type).add(listener);
2392
+ }
2393
+ removeEventListener(type, listener) {
2394
+ const typeListeners = this.listeners.get(type);
2395
+ if (typeListeners) {
2396
+ typeListeners.delete(listener);
2397
+ if (typeListeners.size === 0) {
2398
+ this.listeners.delete(type);
2399
+ }
2400
+ }
2401
+ }
2402
+ dispatch(type, detail) {
2403
+ const typeListeners = this.listeners.get(type);
2404
+ if (typeListeners) {
2405
+ const event = { type, detail };
2406
+ typeListeners.forEach((listener) => {
2407
+ try {
2408
+ listener(event);
2409
+ } catch (error) {
2410
+ console.error(`Error in event listener for "${type}":`, error);
2411
+ }
2412
+ });
2413
+ }
2414
+ }
2415
+ };
2416
+
2417
+ // src/core/types.ts
2418
+ var TOKEN_STORAGE_KEY = "mm-ai-sp-token";
2419
+ var CHECK_KEY = "mm-ai-check-key";
2420
+
2421
+ // src/core/MageMetricsClient.ts
2422
+ var MM_CLIENT_VERSION = package_default.version;
2423
+ var MageMetricsChatTransport = class extends DefaultChatTransport {
2424
+ constructor(apiUrl, flowId, options) {
2425
+ super({
2426
+ ...options,
2427
+ headers: {
2428
+ [HEADER_CLIENT_VERSION]: MM_CLIENT_VERSION
2429
+ },
2430
+ api: `${apiUrl}/api/v1/chat/${flowId}`,
2431
+ prepareSendMessagesRequest({ messages, id: chatId }) {
2432
+ return { body: { message: messages.at(-1), id: chatId } };
2433
+ }
2434
+ });
2435
+ }
2436
+ };
2437
+ var getPublicApiClient = (apiUrl, apiKey) => {
2438
+ const client = createApiClient({ baseUrl: apiUrl });
2439
+ client.use(throwOnError);
2440
+ client.use(addVersionHeader(MM_CLIENT_VERSION));
2441
+ client.use(addApiKeyHeader(apiKey));
2442
+ return client;
2443
+ };
2444
+ var MageMetricsClient = class {
2445
+ config;
2446
+ authState = "initializing";
2447
+ supabaseClient = null;
2448
+ internalApiClient = null;
2449
+ noAuthApiClient = null;
2450
+ authApiResponse = null;
2451
+ authPromise = null;
2452
+ processedJwt = Symbol("initial");
2453
+ storageAdapter;
2454
+ events = new MageMetricsEventEmitter();
2455
+ constructor(config) {
2456
+ this.config = config;
2457
+ this.storageAdapter = config.storageAdapter || createStorageAdapter();
2458
+ void this.initializeAuth();
2459
+ }
2460
+ /**
2461
+ * Add an event listener for authentication state changes
2462
+ * @param type the type of the event
2463
+ * @param listener the listener to add
2464
+ * @param options options for the event listener
2465
+ * @param options.signal an optional AbortSignal to abort the event listener
2466
+ */
2467
+ addEventListener(type, listener, options) {
2468
+ this.events.addEventListener(type, listener, options);
2469
+ }
2470
+ /**
2471
+ * Remove an event listener
2472
+ * @param type the type of the event
2473
+ * @param listener the listener to remove
2474
+ */
2475
+ removeEventListener(type, listener) {
2476
+ this.events.removeEventListener(type, listener);
2477
+ }
2478
+ async waitForAuth() {
2479
+ if (this.authState === "ready") {
2480
+ return Promise.resolve();
2481
+ }
2482
+ if (this.authState === "error") {
2483
+ throw new Error("Authentication failed");
2484
+ }
2485
+ if (this.authPromise) {
2486
+ return this.authPromise;
2487
+ }
2488
+ throw new Error("Authentication not initialized");
2489
+ }
2490
+ async updateExternalJwt(jwt) {
2491
+ if (this.config.externalJwt === jwt) return;
2492
+ this.config.externalJwt = jwt;
2493
+ this.processedJwt = Symbol("updating");
2494
+ await this.performAuthFlow();
2495
+ }
2496
+ get state() {
2497
+ return this.authState;
2498
+ }
2499
+ async getAuthHeaders() {
2500
+ await this.waitForAuth();
2501
+ if (!this.supabaseClient) {
2502
+ return {};
2503
+ }
2504
+ const session = await this.supabaseClient.getSession();
2505
+ if (!session.data.session) {
2506
+ return {};
2507
+ }
2508
+ const { access_token } = session.data.session;
2509
+ const headers = {};
2510
+ if (access_token) {
2511
+ headers["sp-access-token"] = access_token;
2512
+ }
2513
+ return headers;
2514
+ }
2515
+ async clearStorage() {
2516
+ try {
2517
+ await this.storageAdapter.removeItem(TOKEN_STORAGE_KEY);
2518
+ await this.storageAdapter.removeItem(CHECK_KEY);
2519
+ } catch {
2520
+ }
2521
+ }
2522
+ async logout() {
2523
+ if (this.supabaseClient) {
2524
+ await this.supabaseClient.signOut({ scope: "local" });
2525
+ }
2526
+ await this.clearStorage();
2527
+ }
2528
+ /**
2529
+ * Public API methods that automatically wait for authentication
2530
+ */
2531
+ api = {
2532
+ getRecentFlows: async (params = {}) => {
2533
+ await this.waitForAuth();
2534
+ if (!this.internalApiClient) throw new Error("API client not ready");
2535
+ const { data, error, response } = await this.internalApiClient.GET(
2536
+ RetrieveRecentFlows.path,
2537
+ {
2538
+ params: {
2539
+ query: {
2540
+ limit: params.limit ?? 10
2541
+ }
2542
+ }
2543
+ }
2544
+ );
2545
+ if (error) {
2546
+ throw new ApiError(error.error, response, {
2547
+ status: response.status,
2548
+ statusText: response.statusText,
2549
+ url: response.url,
2550
+ method: "GET"
2551
+ });
2552
+ }
2553
+ return data;
2554
+ },
2555
+ createFlow: async (request) => {
2556
+ await this.waitForAuth();
2557
+ if (!this.internalApiClient) throw new Error("API client not ready");
2558
+ if ("query" in request) {
2559
+ const { data, error, response } = await this.internalApiClient.POST(
2560
+ CreateFlow.path,
2561
+ {
2562
+ body: {
2563
+ userQuery: request.query
2564
+ }
2565
+ }
2566
+ );
2567
+ if (error) {
2568
+ throw new ApiError(error.error, response, {
2569
+ status: response.status,
2570
+ statusText: response.statusText,
2571
+ url: response.url,
2572
+ method: "POST"
2573
+ });
2574
+ }
2575
+ return { flowId: data.flowId };
2576
+ } else {
2577
+ const { triggerId, variables } = request;
2578
+ const { data, response } = await this.internalApiClient.POST(
2579
+ TriggerFlow.path,
2580
+ {
2581
+ body: {
2582
+ triggerId,
2583
+ variables
2584
+ }
2585
+ }
2586
+ );
2587
+ if (!data || data.status === "error") {
2588
+ throw new ApiError(
2589
+ data?.error ?? "Failed to trigger flow",
2590
+ response,
2591
+ {
2592
+ status: response.status,
2593
+ statusText: response.statusText,
2594
+ url: response.url,
2595
+ method: "POST"
2596
+ }
2597
+ );
2598
+ }
2599
+ return { flowId: data.flowId };
2600
+ }
2601
+ },
2602
+ getDashboard: async (dashboardId) => {
2603
+ await this.waitForAuth();
2604
+ if (!this.internalApiClient) throw new Error("API client not ready");
2605
+ const { data, error, response } = await this.internalApiClient.GET(
2606
+ RetrieveDashboard.path,
2607
+ {
2608
+ params: {
2609
+ path: {
2610
+ dashboard_id: dashboardId
2611
+ }
2612
+ }
2613
+ }
2614
+ );
2615
+ if (error) {
2616
+ throw new ApiError(error.error, response, {
2617
+ status: response.status,
2618
+ statusText: response.statusText,
2619
+ url: response.url,
2620
+ method: "GET"
2621
+ });
2622
+ }
2623
+ return data;
2624
+ },
2625
+ exportReportData: async (reportId, format = "blob") => {
2626
+ await this.waitForAuth();
2627
+ if (!this.internalApiClient) throw new Error("API client not ready");
2628
+ const { data, error, response } = await this.internalApiClient.GET(
2629
+ ExportReportData.path,
2630
+ {
2631
+ params: {
2632
+ path: {
2633
+ report_id: String(reportId)
2634
+ }
2635
+ },
2636
+ parseAs: format
2637
+ }
2638
+ );
2639
+ if (error) {
2640
+ throw new ApiError(error.error, response, {
2641
+ status: response.status,
2642
+ statusText: response.statusText,
2643
+ url: response.url,
2644
+ method: "GET"
2645
+ });
2646
+ }
2647
+ const contentDisposition = response.headers.get("content-disposition");
2648
+ const filename = contentDisposition ? contentDisposition.split("filename=")[1]?.replace(/"/g, "") || `mm-export-${reportId}.csv` : `mm-export-${reportId}.csv`;
2649
+ return { filename, data };
2650
+ },
2651
+ generateContextualInsight: async (payload) => {
2652
+ await this.waitForAuth();
2653
+ if (!this.internalApiClient) throw new Error("API client not ready");
2654
+ const { data, error, response } = await this.internalApiClient.POST(
2655
+ GenerateInsight.path,
2656
+ {
2657
+ body: {
2658
+ selected_filter_value: payload.selectedFilterValue,
2659
+ custom_id: payload.customId
2660
+ }
2661
+ }
2662
+ );
2663
+ if (error) {
2664
+ throw new ApiError(error.error, response, {
2665
+ status: response.status,
2666
+ statusText: response.statusText,
2667
+ url: response.url,
2668
+ method: "POST"
2669
+ });
2670
+ }
2671
+ return data;
2672
+ }
2673
+ };
2674
+ /**
2675
+ * Initialize authentication flow
2676
+ */
2677
+ async initializeAuth() {
2678
+ this.authPromise = this.performAuthFlow();
2679
+ try {
2680
+ await this.authPromise;
2681
+ } catch (error) {
2682
+ console.error("Failed to initialize authentication:", error);
2683
+ }
2684
+ }
2685
+ /**
2686
+ * Perform the complete authentication flow
2687
+ */
2688
+ async performAuthFlow() {
2689
+ try {
2690
+ this.setState("initializing");
2691
+ const apiInfo = await this.getApiInformation();
2692
+ this.initializeSupabaseClient(apiInfo.anonKey, apiInfo.apiUrl);
2693
+ this.initializeApiClient();
2694
+ await this.handleAuthentication();
2695
+ if (this.config.externalJwt) {
2696
+ await this.saveCheckKey(this.config.externalJwt, this.config.apiKey);
2697
+ }
2698
+ this.setState("ready");
2699
+ } catch (error) {
2700
+ console.error("Authentication flow failed:", error);
2701
+ this.setState("error");
2702
+ throw error;
2703
+ }
2704
+ }
2705
+ async getApiInformation() {
2706
+ if (!this.noAuthApiClient || !this.authApiResponse) {
2707
+ this.noAuthApiClient = getPublicApiClient(
2708
+ this.config.apiUrl,
2709
+ this.config.apiKey
2710
+ );
2711
+ const { data } = await this.noAuthApiClient.GET(GetApiInformation.path, {
2712
+ params: {
2713
+ query: {
2714
+ apiKey: this.config.apiKey
2715
+ }
2716
+ }
2717
+ });
2718
+ if (!data) {
2719
+ throw new Error("Failed to fetch API information");
2720
+ }
2721
+ this.authApiResponse = data;
2722
+ }
2723
+ return this.authApiResponse;
2724
+ }
2725
+ initializeSupabaseClient(anonKey, apiUrl) {
2726
+ if (!this.supabaseClient) {
2727
+ this.supabaseClient = new GoTrueClient({
2728
+ url: `${apiUrl}/auth/v1`,
2729
+ storageKey: TOKEN_STORAGE_KEY,
2730
+ headers: {
2731
+ apiKey: anonKey
2732
+ }
2733
+ });
2734
+ this.supabaseClient.onAuthStateChange((event, session) => {
2735
+ console.debug("Supabase auth state change:", event, !!session);
2736
+ if (event === "TOKEN_REFRESHED" && session) {
2737
+ console.debug("Token refreshed successfully");
2738
+ this.setState("ready");
2739
+ } else if (event === "SIGNED_OUT") {
2740
+ console.debug("User signed out");
2741
+ void this.clearStorage();
2742
+ this.setState("initializing");
2743
+ }
2744
+ });
2745
+ }
2746
+ }
2747
+ /* This method always waits for authentication to complete before returning the client */
2748
+ async client() {
2749
+ await this.waitForAuth();
2750
+ if (this.authState === "ready") {
2751
+ if (!this.internalApiClient) {
2752
+ throw new Error(
2753
+ "Client is ready but API client not available. This should never happen"
2754
+ );
2755
+ }
2756
+ return this.internalApiClient;
2757
+ }
2758
+ throw new Error(`Client is not available in auth state: ${this.authState}`);
2759
+ }
2760
+ /**
2761
+ * Initialize the API client with Supabase headers
2762
+ */
2763
+ initializeApiClient() {
2764
+ this.internalApiClient = createApiClient({ baseUrl: this.config.apiUrl });
2765
+ this.internalApiClient.use(throwOnError);
2766
+ this.internalApiClient.use(this.createSupabaseHeaderMiddleware());
2767
+ this.internalApiClient.use(addVersionHeader(MM_CLIENT_VERSION));
2768
+ }
2769
+ /**
2770
+ * Handle the authentication logic (check session or exchange token)
2771
+ */
2772
+ async handleAuthentication() {
2773
+ if (!this.supabaseClient) {
2774
+ throw new Error("Supabase client not initialized");
2775
+ }
2776
+ if (this.processedJwt === this.config.externalJwt) {
2777
+ return;
2778
+ }
2779
+ try {
2780
+ const { data, error } = await this.supabaseClient.getSession();
2781
+ if (error) {
2782
+ console.error("Error getting session:", error);
2783
+ this.processedJwt = this.config.externalJwt || "";
2784
+ return;
2785
+ }
2786
+ const isCheckValid = await this.compareCheckKey(
2787
+ this.config.externalJwt ?? "",
2788
+ this.config.apiKey
2789
+ );
2790
+ if (data.session && this.config.externalJwt && isCheckValid) {
2791
+ console.debug("Session found, authentication ready");
2792
+ this.processedJwt = this.config.externalJwt || "";
2793
+ } else if (this.config.externalJwt) {
2794
+ console.debug("No session found, exchanging external JWT");
2795
+ await this.clearCheckKey();
2796
+ await this.exchangeExternalToken();
2797
+ this.processedJwt = this.config.externalJwt;
2798
+ } else {
2799
+ console.debug("No session and no external JWT provided");
2800
+ this.processedJwt = this.config.externalJwt || "";
2801
+ }
2802
+ } catch (error) {
2803
+ console.error("Unhandled error during authentication:", error);
2804
+ this.processedJwt = this.config.externalJwt || "";
2805
+ throw error;
2806
+ }
2807
+ }
2808
+ /**
2809
+ * Exchange external JWT for Supabase tokens
2810
+ */
2811
+ async exchangeExternalToken() {
2812
+ if (!this.noAuthApiClient || !this.supabaseClient || !this.config.externalJwt) {
2813
+ throw new Error(
2814
+ "Required clients or JWT not available for token exchange"
2815
+ );
2816
+ }
2817
+ const { data } = await this.noAuthApiClient.POST(
2818
+ ExchangeExternalToken.path,
2819
+ {
2820
+ body: {
2821
+ apiKey: this.config.apiKey,
2822
+ externalJWT: this.config.externalJwt
2823
+ },
2824
+ headers: this.config.additionalHeaders || {}
2825
+ }
2826
+ );
2827
+ if (!data) {
2828
+ throw new Error("Failed to exchange tokens");
2829
+ }
2830
+ await this.supabaseClient.setSession({
2831
+ access_token: data.accessToken,
2832
+ refresh_token: data.refreshToken
2833
+ });
2834
+ console.debug("Token exchange successful, session set");
2835
+ }
2836
+ createSupabaseHeaderMiddleware() {
2837
+ const supabaseClient = this.supabaseClient;
2838
+ return {
2839
+ async onRequest({ request }) {
2840
+ if (!supabaseClient) {
2841
+ return request;
2842
+ }
2843
+ const session = await supabaseClient.getSession();
2844
+ if (!session.data.session) {
2845
+ return request;
2846
+ }
2847
+ const { access_token } = session.data.session;
2848
+ if (access_token) {
2849
+ request.headers.set("sp-access-token", access_token);
2850
+ }
2851
+ return request;
2852
+ }
2853
+ };
2854
+ }
2855
+ setState(state) {
2856
+ this.authState = state;
2857
+ this.events.dispatch("authStateChange", state);
2858
+ }
2859
+ encodeCheckKey(externalJwt, apiKey) {
2860
+ return hashString(
2861
+ JSON.stringify({
2862
+ externalJwt,
2863
+ apiKey
2864
+ })
2865
+ );
2866
+ }
2867
+ async saveCheckKey(externalJwt, apiKey) {
2868
+ const encodedKey = this.encodeCheckKey(externalJwt, apiKey);
2869
+ await this.storageAdapter.setItem(CHECK_KEY, encodedKey);
2870
+ }
2871
+ async compareCheckKey(externalJwt, apiKey) {
2872
+ const storedKey = await this.storageAdapter.getItem(CHECK_KEY);
2873
+ if (!storedKey) return false;
2874
+ const newValue = this.encodeCheckKey(externalJwt, apiKey);
2875
+ return storedKey === newValue;
2876
+ }
2877
+ async clearCheckKey() {
2878
+ await this.storageAdapter.removeItem(CHECK_KEY);
2879
+ }
2880
+ };
2881
+
2882
+ export { BrowserStorageAdapter, CHECK_KEY, MageMetricsChatTransport, MageMetricsClient, MageMetricsEventEmitter, MemoryStorageAdapter, TOKEN_STORAGE_KEY, getPublicApiClient };
2883
+ //# sourceMappingURL=index.js.map
2884
+ //# sourceMappingURL=index.js.map