@magemetrics/core 0.1.2 → 0.1.4

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.d.ts CHANGED
@@ -484,9 +484,11 @@ declare const inputSchema_7: z.ZodObject<{
484
484
  declare type InternalApiClient = Simplify<Client<NoAuthPaths, `${string}/${string}`>>;
485
485
 
486
486
  export declare class MageMetricsChatTransport extends DefaultChatTransport<MMChatUIMessage> {
487
- constructor(apiUrl: string, flowId: string, options?: Omit<HttpChatTransportInitOptions<MMChatUIMessage>, "api" | "headers" | "prepareSendMessagesRequest">);
487
+ constructor(apiUrl: string, flowId: string, options: MageMetricsChatTransportOptions);
488
488
  }
489
489
 
490
+ declare type MageMetricsChatTransportOptions = Omit<HttpChatTransportInitOptions<MMChatUIMessage>, "api" | "prepareSendMessagesRequest">;
491
+
490
492
  /**
491
493
  * Core MageMetrics client that handles authentication lifecycle and provides
492
494
  * a promise-based API that automatically waits for authentication to complete.
@@ -503,6 +505,7 @@ export declare class MageMetricsClient {
503
505
  private authApiResponse;
504
506
  private authPromise;
505
507
  private processedJwt;
508
+ private userId;
506
509
  private storageAdapter;
507
510
  private events;
508
511
  constructor(config: MageMetricsClientConfig);
@@ -544,22 +547,15 @@ export declare class MageMetricsClient {
544
547
  data: Blob | string;
545
548
  }>;
546
549
  generateContextualInsight: (payload: GenerateInsightParam) => Promise<ExtractInsightResponse>;
550
+ getChat: (flowId: string, options?: MageMetricsChatTransportOptions) => MageMetricsChatTransport;
547
551
  };
548
- /**
549
- * Initialize authentication flow
550
- */
551
- private initializeAuth;
552
552
  /**
553
553
  * Perform the complete authentication flow
554
554
  */
555
555
  private performAuthFlow;
556
556
  private getApiInformation;
557
557
  private initializeSupabaseClient;
558
- client(): Promise<InternalApiClient>;
559
- /**
560
- * Initialize the API client with Supabase headers
561
- */
562
- private initializeApiClient;
558
+ client(): InternalApiClient;
563
559
  /**
564
560
  * Handle the authentication logic (check session or exchange token)
565
561
  */
@@ -593,6 +589,11 @@ export declare interface MageMetricsClientConfig {
593
589
  export declare type MageMetricsEvent = {
594
590
  type: "authStateChange";
595
591
  detail: AuthState;
592
+ } | {
593
+ type: "userChange";
594
+ detail: {
595
+ id: string;
596
+ };
596
597
  };
597
598
 
598
599
  /**
@@ -1892,71 +1893,6 @@ declare interface operations {
1892
1893
  };
1893
1894
  };
1894
1895
  };
1895
- retrieveChatTimeline: {
1896
- parameters: {
1897
- query?: never;
1898
- header: {
1899
- "sp-access-token": string;
1900
- };
1901
- path: {
1902
- flowId: string;
1903
- };
1904
- cookie?: never;
1905
- };
1906
- requestBody?: never;
1907
- responses: {
1908
- /** @description The timeline of generated insights for the flow */
1909
- 200: {
1910
- headers: {
1911
- [name: string]: unknown;
1912
- };
1913
- content: {
1914
- "application/json": ({
1915
- /** @enum {string} */
1916
- type: "dataReport";
1917
- flowDataId: number;
1918
- flowId: string;
1919
- title: string;
1920
- bookmarked: boolean;
1921
- answer: string | null;
1922
- } | {
1923
- /** @enum {string} */
1924
- type: "visualization";
1925
- flowId: string;
1926
- flowDataId: number;
1927
- flowDataVisualizationId: number;
1928
- title: string;
1929
- bookmarked: boolean;
1930
- } | {
1931
- /** @enum {string} */
1932
- type: "message";
1933
- })[];
1934
- };
1935
- };
1936
- /** @description Unable to retrieve flow with this id */
1937
- 404: {
1938
- headers: {
1939
- [name: string]: unknown;
1940
- };
1941
- content: {
1942
- "application/json": {
1943
- error: string;
1944
- };
1945
- };
1946
- };
1947
- /** @description Something wrong happened */
1948
- 500: {
1949
- headers: {
1950
- [name: string]: unknown;
1951
- };
1952
- content: {
1953
- "application/json": {
1954
- error: string;
1955
- };
1956
- };
1957
- };
1958
- };
1959
- };
1960
1896
  retrieveChatMessages: {
1961
1897
  parameters: {
1962
1898
  query?: never;
@@ -3328,22 +3264,6 @@ declare interface paths {
3328
3264
  patch?: never;
3329
3265
  trace?: never;
3330
3266
  };
3331
- "/api/v1/chat/{flowId}/timeline": {
3332
- parameters: {
3333
- query?: never;
3334
- header?: never;
3335
- path?: never;
3336
- cookie?: never;
3337
- };
3338
- get: operations["retrieveChatTimeline"];
3339
- put?: never;
3340
- post?: never;
3341
- delete?: never;
3342
- options?: never;
3343
- head?: never;
3344
- patch?: never;
3345
- trace?: never;
3346
- };
3347
3267
  "/api/v1/chat/{flowId}/messages": {
3348
3268
  parameters: {
3349
3269
  query?: never;
package/dist/index.js CHANGED
@@ -2370,7 +2370,18 @@ var hashString = (value) => {
2370
2370
 
2371
2371
  // package.json
2372
2372
  var package_default = {
2373
- version: "0.1.2"};
2373
+ version: "0.1.4"};
2374
+ var MageMetricsChatTransport = class extends DefaultChatTransport {
2375
+ constructor(apiUrl, flowId, options) {
2376
+ super({
2377
+ ...options,
2378
+ api: `${apiUrl}/api/v1/chat/${flowId}`,
2379
+ prepareSendMessagesRequest({ messages, id: chatId }) {
2380
+ return { body: { message: messages.at(-1), id: chatId } };
2381
+ }
2382
+ });
2383
+ }
2384
+ };
2374
2385
 
2375
2386
  // src/core/MageMetricsEventEmitter.ts
2376
2387
  var MageMetricsEventEmitter = class {
@@ -2414,26 +2425,20 @@ var MageMetricsEventEmitter = class {
2414
2425
  }
2415
2426
  };
2416
2427
 
2428
+ // src/core/resolvable.ts
2429
+ var resolve = (value) => {
2430
+ if (typeof value === "function") {
2431
+ return Promise.resolve(value());
2432
+ }
2433
+ return Promise.resolve(value);
2434
+ };
2435
+
2417
2436
  // src/core/types.ts
2418
2437
  var TOKEN_STORAGE_KEY = "mm-ai-sp-token";
2419
2438
  var CHECK_KEY = "mm-ai-check-key";
2420
2439
 
2421
2440
  // src/core/MageMetricsClient.ts
2422
2441
  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
2442
  var getPublicApiClient = (apiUrl, apiKey) => {
2438
2443
  const client = createApiClient({ baseUrl: apiUrl });
2439
2444
  client.use(throwOnError);
@@ -2445,17 +2450,23 @@ var MageMetricsClient = class {
2445
2450
  config;
2446
2451
  authState = "initializing";
2447
2452
  supabaseClient = null;
2448
- internalApiClient = null;
2453
+ internalApiClient;
2449
2454
  noAuthApiClient = null;
2450
2455
  authApiResponse = null;
2451
2456
  authPromise = null;
2452
2457
  processedJwt = Symbol("initial");
2458
+ userId = null;
2453
2459
  storageAdapter;
2454
2460
  events = new MageMetricsEventEmitter();
2455
2461
  constructor(config) {
2456
2462
  this.config = config;
2457
2463
  this.storageAdapter = config.storageAdapter || createStorageAdapter();
2458
- void this.initializeAuth();
2464
+ this.internalApiClient = createApiClient({
2465
+ baseUrl: this.config.apiUrl
2466
+ });
2467
+ this.internalApiClient.use(throwOnError);
2468
+ this.internalApiClient.use(this.createSupabaseHeaderMiddleware());
2469
+ this.internalApiClient.use(addVersionHeader(MM_CLIENT_VERSION));
2459
2470
  }
2460
2471
  /**
2461
2472
  * Add an event listener for authentication state changes
@@ -2482,10 +2493,10 @@ var MageMetricsClient = class {
2482
2493
  if (this.authState === "error") {
2483
2494
  throw new Error("Authentication failed");
2484
2495
  }
2485
- if (this.authPromise) {
2486
- return this.authPromise;
2496
+ if (!this.authPromise) {
2497
+ this.authPromise = this.performAuthFlow();
2487
2498
  }
2488
- throw new Error("Authentication not initialized");
2499
+ return this.authPromise;
2489
2500
  }
2490
2501
  async updateExternalJwt(jwt) {
2491
2502
  if (this.config.externalJwt === jwt) return;
@@ -2506,11 +2517,9 @@ var MageMetricsClient = class {
2506
2517
  return {};
2507
2518
  }
2508
2519
  const { access_token } = session.data.session;
2509
- const headers = {};
2510
- if (access_token) {
2511
- headers["sp-access-token"] = access_token;
2512
- }
2513
- return headers;
2520
+ return {
2521
+ "sp-access-token": access_token
2522
+ };
2514
2523
  }
2515
2524
  async clearStorage() {
2516
2525
  try {
@@ -2531,7 +2540,6 @@ var MageMetricsClient = class {
2531
2540
  api = {
2532
2541
  getRecentFlows: async (params = {}) => {
2533
2542
  await this.waitForAuth();
2534
- if (!this.internalApiClient) throw new Error("API client not ready");
2535
2543
  const { data, error, response } = await this.internalApiClient.GET(
2536
2544
  RetrieveRecentFlows.path,
2537
2545
  {
@@ -2554,7 +2562,6 @@ var MageMetricsClient = class {
2554
2562
  },
2555
2563
  createFlow: async (request) => {
2556
2564
  await this.waitForAuth();
2557
- if (!this.internalApiClient) throw new Error("API client not ready");
2558
2565
  if ("query" in request) {
2559
2566
  const { data, error, response } = await this.internalApiClient.POST(
2560
2567
  CreateFlow.path,
@@ -2601,7 +2608,6 @@ var MageMetricsClient = class {
2601
2608
  },
2602
2609
  getDashboard: async (dashboardId) => {
2603
2610
  await this.waitForAuth();
2604
- if (!this.internalApiClient) throw new Error("API client not ready");
2605
2611
  const { data, error, response } = await this.internalApiClient.GET(
2606
2612
  RetrieveDashboard.path,
2607
2613
  {
@@ -2624,7 +2630,6 @@ var MageMetricsClient = class {
2624
2630
  },
2625
2631
  exportReportData: async (reportId, format = "blob") => {
2626
2632
  await this.waitForAuth();
2627
- if (!this.internalApiClient) throw new Error("API client not ready");
2628
2633
  const { data, error, response } = await this.internalApiClient.GET(
2629
2634
  ExportReportData.path,
2630
2635
  {
@@ -2650,7 +2655,6 @@ var MageMetricsClient = class {
2650
2655
  },
2651
2656
  generateContextualInsight: async (payload) => {
2652
2657
  await this.waitForAuth();
2653
- if (!this.internalApiClient) throw new Error("API client not ready");
2654
2658
  const { data, error, response } = await this.internalApiClient.POST(
2655
2659
  GenerateInsight.path,
2656
2660
  {
@@ -2669,19 +2673,22 @@ var MageMetricsClient = class {
2669
2673
  });
2670
2674
  }
2671
2675
  return data;
2676
+ },
2677
+ getChat: (flowId, options) => {
2678
+ return new MageMetricsChatTransport(this.config.apiUrl, flowId, {
2679
+ ...options,
2680
+ headers: async () => {
2681
+ const authHeaders = await this.getAuthHeaders();
2682
+ const headers = await resolve(options?.headers);
2683
+ return {
2684
+ ...headers,
2685
+ ...authHeaders,
2686
+ [HEADER_CLIENT_VERSION]: MM_CLIENT_VERSION
2687
+ };
2688
+ }
2689
+ });
2672
2690
  }
2673
2691
  };
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
2692
  /**
2686
2693
  * Perform the complete authentication flow
2687
2694
  */
@@ -2690,7 +2697,6 @@ var MageMetricsClient = class {
2690
2697
  this.setState("initializing");
2691
2698
  const apiInfo = await this.getApiInformation();
2692
2699
  this.initializeSupabaseClient(apiInfo.anonKey, apiInfo.apiUrl);
2693
- this.initializeApiClient();
2694
2700
  await this.handleAuthentication();
2695
2701
  if (this.config.externalJwt) {
2696
2702
  await this.saveCheckKey(this.config.externalJwt, this.config.apiKey);
@@ -2733,6 +2739,12 @@ var MageMetricsClient = class {
2733
2739
  });
2734
2740
  this.supabaseClient.onAuthStateChange((event, session) => {
2735
2741
  console.debug("Supabase auth state change:", event, !!session);
2742
+ if (event === "SIGNED_IN" && session?.user) {
2743
+ if (this.userId !== session.user.id && this.userId !== null) {
2744
+ this.events.dispatch("userChange", { id: session.user.id });
2745
+ }
2746
+ this.userId = session.user.id;
2747
+ }
2736
2748
  if (event === "TOKEN_REFRESHED" && session) {
2737
2749
  console.debug("Token refreshed successfully");
2738
2750
  this.setState("ready");
@@ -2744,27 +2756,8 @@ var MageMetricsClient = class {
2744
2756
  });
2745
2757
  }
2746
2758
  }
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));
2759
+ client() {
2760
+ return this.internalApiClient;
2768
2761
  }
2769
2762
  /**
2770
2763
  * Handle the authentication logic (check session or exchange token)
@@ -2834,19 +2827,18 @@ var MageMetricsClient = class {
2834
2827
  console.debug("Token exchange successful, session set");
2835
2828
  }
2836
2829
  createSupabaseHeaderMiddleware() {
2837
- const supabaseClient = this.supabaseClient;
2838
2830
  return {
2839
- async onRequest({ request }) {
2840
- if (!supabaseClient) {
2831
+ onRequest: async ({ request }) => {
2832
+ const headers = await this.getAuthHeaders();
2833
+ if (!this.supabaseClient) {
2841
2834
  return request;
2842
2835
  }
2843
- const session = await supabaseClient.getSession();
2836
+ const session = await this.supabaseClient.getSession();
2844
2837
  if (!session.data.session) {
2845
2838
  return request;
2846
2839
  }
2847
- const { access_token } = session.data.session;
2848
- if (access_token) {
2849
- request.headers.set("sp-access-token", access_token);
2840
+ for (const [key, value] of Object.entries(headers)) {
2841
+ request.headers.set(key, value);
2850
2842
  }
2851
2843
  return request;
2852
2844
  }
@@ -2879,6 +2871,6 @@ var MageMetricsClient = class {
2879
2871
  }
2880
2872
  };
2881
2873
 
2882
- export { BrowserStorageAdapter, CHECK_KEY, MageMetricsChatTransport, MageMetricsClient, MageMetricsEventEmitter, MemoryStorageAdapter, TOKEN_STORAGE_KEY, getPublicApiClient };
2874
+ export { BrowserStorageAdapter, CHECK_KEY, MageMetricsClient, MageMetricsEventEmitter, MemoryStorageAdapter, TOKEN_STORAGE_KEY, getPublicApiClient };
2883
2875
  //# sourceMappingURL=index.js.map
2884
2876
  //# sourceMappingURL=index.js.map