@iblai/web-utils 1.2.5 → 1.2.7

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.esm.js CHANGED
@@ -2836,6 +2836,11 @@ function useAuthProvider({ middleware = new Map(), onAuthSuccess, onAuthFailure,
2836
2836
  * Skipped if enableStorageSync is false
2837
2837
  */
2838
2838
  useEffect(() => {
2839
+ console.log("[AuthProvider] cookie-sync effect running", {
2840
+ pathname,
2841
+ enableStorageSync,
2842
+ hasStorageService: !!storageService,
2843
+ });
2839
2844
  if (!storageService || !isWeb$1() || !enableStorageSync) {
2840
2845
  // If no storage service, not web, or sync disabled, mark sync as complete immediately
2841
2846
  setInitialSyncComplete(true);
@@ -2845,16 +2850,22 @@ function useAuthProvider({ middleware = new Map(), onAuthSuccess, onAuthFailure,
2845
2850
  isRedirectingRef.current = false;
2846
2851
  // Initial sync on mount
2847
2852
  async function initialSync() {
2853
+ console.log("[AuthProvider] initialSync starting");
2848
2854
  try {
2849
2855
  // Initialize last known logout timestamp
2850
2856
  lastLogoutTimestampRef.current = CookieUtils.get(COOKIE_KEYS.LOGOUT_TIMESTAMP);
2851
2857
  const { needsRefresh, userDataOutOfSync } = await syncCookiesToLocalStorage(storageService);
2858
+ console.log("[AuthProvider] initialSync result", {
2859
+ needsRefresh,
2860
+ userDataOutOfSync,
2861
+ });
2852
2862
  if (needsRefresh) {
2853
2863
  console.log("[auth-redirect] Cookie sync detected changes, refreshing page");
2854
2864
  // If user data is out of sync, trigger logout to force re-authentication
2855
2865
  safeRedirectToAuthSpa(undefined, undefined, userDataOutOfSync, false);
2856
2866
  }
2857
2867
  else {
2868
+ console.log("[AuthProvider] initialSync no changes, syncing auth to cookies");
2858
2869
  await syncAuthToCookies(storageService);
2859
2870
  }
2860
2871
  }
@@ -2867,8 +2878,10 @@ function useAuthProvider({ middleware = new Map(), onAuthSuccess, onAuthFailure,
2867
2878
  // Poll for cookie changes every 2 seconds to detect cross-SPA updates
2868
2879
  cookieCheckIntervalRef.current = setInterval(async () => {
2869
2880
  // If a redirect is already in progress, skip entirely
2870
- if (isRedirectingRef.current)
2881
+ if (isRedirectingRef.current) {
2882
+ console.log("[AuthProvider] interval: redirect already in progress, skipping");
2871
2883
  return;
2884
+ }
2872
2885
  // Skip cookie sync checks if user is completing SSO at /sso-login
2873
2886
  const completingSso = /^\/sso-login/.test(pathname);
2874
2887
  if (completingSso) {
@@ -2889,6 +2902,11 @@ function useAuthProvider({ middleware = new Map(), onAuthSuccess, onAuthFailure,
2889
2902
  return;
2890
2903
  }
2891
2904
  const { needsRefresh, userDataOutOfSync } = await syncCookiesToLocalStorage(storageService);
2905
+ console.log("[AuthProvider] interval poll result", {
2906
+ needsRefresh,
2907
+ userDataOutOfSync,
2908
+ pathname,
2909
+ });
2892
2910
  if (needsRefresh) {
2893
2911
  console.log("[auth-redirect] Cookie sync detected changes from another SPA, refreshing page");
2894
2912
  let cookieTenantKey;
@@ -2897,6 +2915,10 @@ function useAuthProvider({ middleware = new Map(), onAuthSuccess, onAuthFailure,
2897
2915
  cookieTenantKey = cookieCurrentTenant.key;
2898
2916
  }
2899
2917
  catch (_a) { }
2918
+ console.log("[AuthProvider] interval redirecting to auth spa", {
2919
+ cookieTenantKey,
2920
+ userDataOutOfSync,
2921
+ });
2900
2922
  // If user data is out of sync, trigger logout to force re-authentication
2901
2923
  safeRedirectToAuthSpa(undefined, cookieTenantKey, userDataOutOfSync, false);
2902
2924
  }
@@ -2906,6 +2928,7 @@ function useAuthProvider({ middleware = new Map(), onAuthSuccess, onAuthFailure,
2906
2928
  }, 2000);
2907
2929
  // Cleanup interval on unmount
2908
2930
  return () => {
2931
+ console.log("[AuthProvider] cookie-sync effect cleanup", { pathname });
2909
2932
  if (cookieCheckIntervalRef.current) {
2910
2933
  clearInterval(cookieCheckIntervalRef.current);
2911
2934
  }
@@ -5861,7 +5884,7 @@ const STREAMING_CONTENT_BUFFER_THRESHOLD = 300; // characters
5861
5884
  const STREAMING_CONTENT_FLUSH_INTERVAL = 300; // milliseconds
5862
5885
  const defaultSessionIds = Object.fromEntries(Object.keys(advancedTabsProperties).map((key) => [key, ""]));
5863
5886
  const defaultChatState = Object.fromEntries(Object.keys(advancedTabsProperties).map((key) => [key, []]));
5864
- const initialState$2 = {
5887
+ const initialState$3 = {
5865
5888
  chats: defaultChatState,
5866
5889
  isTyping: false,
5867
5890
  streaming: false,
@@ -5894,7 +5917,7 @@ const initialState$2 = {
5894
5917
  };
5895
5918
  const chatSlice = createSlice$1({
5896
5919
  name: "chatSliceShared",
5897
- initialState: initialState$2,
5920
+ initialState: initialState$3,
5898
5921
  reducers: {
5899
5922
  setChats: (state, action) => {
5900
5923
  state.chats = action.payload;
@@ -6558,12 +6581,12 @@ function useTimeTrackerNative(config) {
6558
6581
  };
6559
6582
  }
6560
6583
 
6561
- const initialState$1 = {
6584
+ const initialState$2 = {
6562
6585
  attachedFiles: [],
6563
6586
  };
6564
6587
  const filesSlice = createSlice$1({
6565
6588
  name: "files",
6566
- initialState: initialState$1,
6589
+ initialState: initialState$2,
6567
6590
  reducers: {
6568
6591
  addFiles: (state, action) => {
6569
6592
  state.attachedFiles = [...state.attachedFiles, ...action.payload];
@@ -6742,6 +6765,44 @@ function csvDataToText(data) {
6742
6765
  ].join("\n");
6743
6766
  }
6744
6767
 
6768
+ const initialState$1 = {
6769
+ displayMonetizationCheckoutModal: false,
6770
+ accessCheckResponse: null,
6771
+ paywallClosable: true,
6772
+ onClosePayload: undefined,
6773
+ };
6774
+ const monetizationSlice = createSlice$1({
6775
+ name: "monetization",
6776
+ initialState: initialState$1,
6777
+ reducers: {
6778
+ setDisplayMonetizationCheckoutModal(state, action) {
6779
+ state.displayMonetizationCheckoutModal = action.payload;
6780
+ if (!action.payload) {
6781
+ state.accessCheckResponse = null;
6782
+ }
6783
+ },
6784
+ setAccessCheckResponse(state, action) {
6785
+ state.accessCheckResponse = action.payload;
6786
+ },
6787
+ showMonetizationCheckoutModal(state, action) {
6788
+ var _a, _b, _c, _d, _e;
6789
+ state.displayMonetizationCheckoutModal =
6790
+ (_b = (_a = action.payload) === null || _a === void 0 ? void 0 : _a.showModal) !== null && _b !== void 0 ? _b : true;
6791
+ state.accessCheckResponse = action.payload;
6792
+ state.paywallClosable = (_d = (_c = action.payload) === null || _c === void 0 ? void 0 : _c.paywallClosable) !== null && _d !== void 0 ? _d : true;
6793
+ state.onClosePayload = (_e = action.payload) === null || _e === void 0 ? void 0 : _e.onClosePayload;
6794
+ },
6795
+ setAdvancedDisplayMonetizationCheckoutModal(state, action) {
6796
+ var _a, _b, _c, _d, _e;
6797
+ state.displayMonetizationCheckoutModal =
6798
+ (_b = (_a = action.payload) === null || _a === void 0 ? void 0 : _a.showModal) !== null && _b !== void 0 ? _b : true;
6799
+ state.paywallClosable = (_d = (_c = action.payload) === null || _c === void 0 ? void 0 : _c.paywallClosable) !== null && _d !== void 0 ? _d : true;
6800
+ state.onClosePayload = (_e = action.payload) === null || _e === void 0 ? void 0 : _e.onClosePayload;
6801
+ },
6802
+ },
6803
+ });
6804
+ const { setDisplayMonetizationCheckoutModal, setAccessCheckResponse, showMonetizationCheckoutModal, setAdvancedDisplayMonetizationCheckoutModal, } = monetizationSlice.actions;
6805
+
6745
6806
  /**
6746
6807
  * Ollama API client for local LLM chat
6747
6808
  *
@@ -13519,12 +13580,12 @@ const buildEndpointFromService = (service, serviceFn) => {
13519
13580
  }
13520
13581
  catch (err) {
13521
13582
  if (Object.prototype.hasOwnProperty.call(Config.httpErrorHandlers, err === null || err === void 0 ? void 0 : err.status)) {
13522
- Config.httpErrorHandlers[err === null || err === void 0 ? void 0 : err.status]();
13583
+ Config.httpErrorHandlers[err === null || err === void 0 ? void 0 : err.status]({ ...((err === null || err === void 0 ? void 0 : err.data) || {}) });
13523
13584
  }
13524
13585
  return {
13525
13586
  error: {
13526
13587
  status: (err === null || err === void 0 ? void 0 : err.status) || 500,
13527
- data: (err === null || err === void 0 ? void 0 : err.body) || (err === null || err === void 0 ? void 0 : err.message) || 'Unknown error',
13588
+ data: (err === null || err === void 0 ? void 0 : err.body) || (err === null || err === void 0 ? void 0 : err.data) || (err === null || err === void 0 ? void 0 : err.message) || 'Unknown error',
13528
13589
  },
13529
13590
  };
13530
13591
  }
@@ -13578,24 +13639,40 @@ const baseQuery = (service, jsonContentType = true, contentType, skipAuth = fals
13578
13639
  /**
13579
13640
  * Helper to invoke registered HTTP error handlers (e.g., logout on 401).
13580
13641
  */
13581
- const invokeHttpErrorHandler = (status) => {
13642
+ const invokeHttpErrorHandler = (status, error) => {
13582
13643
  const numericStatus = typeof status === 'number' ? status : parseInt(String(status), 10);
13644
+ console.log('[MONETIZATION error] ', { error });
13583
13645
  if (!isNaN(numericStatus) &&
13584
13646
  Object.prototype.hasOwnProperty.call(Config.httpErrorHandlers, numericStatus)) {
13585
- Config.httpErrorHandlers[numericStatus]();
13647
+ const err = error;
13648
+ Config.httpErrorHandlers[numericStatus]({ ...(err || {}) });
13586
13649
  }
13587
13650
  };
13651
+ /** HTTP status codes that should not be retried (e.g., 402 Payment Required). */
13652
+ const NON_RETRYABLE_STATUS_CODES = [402];
13653
+ /**
13654
+ * Wraps a base query to skip retries for non-retryable HTTP status codes.
13655
+ * Uses `retry.fail()` to immediately bail out of the retry loop.
13656
+ */
13657
+ const withNonRetryableErrors = (query) => async (args, api, extraOptions) => {
13658
+ const result = await query(args, api, extraOptions);
13659
+ if (result.error && NON_RETRYABLE_STATUS_CODES.includes(result.error.status)) {
13660
+ retry.fail(result.error);
13661
+ }
13662
+ return result;
13663
+ };
13588
13664
  const iblFetchBaseQuery = async (args, api, extraOptions) => {
13589
- var _a, _b;
13665
+ var _a, _b, _c;
13590
13666
  try {
13591
13667
  // Executing base query
13592
- const result = await retry(baseQuery(args.service, (_a = args === null || args === void 0 ? void 0 : args.isJson) !== null && _a !== void 0 ? _a : true, args === null || args === void 0 ? void 0 : args.contentType, args === null || args === void 0 ? void 0 : args.skipAuth), {
13668
+ const result = await retry(withNonRetryableErrors(baseQuery(args.service, (_a = args === null || args === void 0 ? void 0 : args.isJson) !== null && _a !== void 0 ? _a : true, args === null || args === void 0 ? void 0 : args.contentType, args === null || args === void 0 ? void 0 : args.skipAuth)), {
13593
13669
  maxRetries: 3,
13594
13670
  })(args, api, extraOptions);
13595
13671
  // Query completed
13596
13672
  if (result.error) {
13673
+ console.log('[MONETIZATION ERROR HANDLER]: ', { result });
13597
13674
  // Invoke registered HTTP error handlers (e.g., logout on 401)
13598
- invokeHttpErrorHandler(result.error.status);
13675
+ invokeHttpErrorHandler(result.error.status, (_b = result.error) === null || _b === void 0 ? void 0 : _b.data);
13599
13676
  // For profile image upload errors, preserve the original error structure
13600
13677
  if (args.url && args.url.includes('/profile_images/')) {
13601
13678
  throw result.error;
@@ -13613,7 +13690,7 @@ const iblFetchBaseQuery = async (args, api, extraOptions) => {
13613
13690
  // Ensure we throw a plain FetchBaseQueryError shape with enumerable fields
13614
13691
  throw {
13615
13692
  status: result.error.status,
13616
- data: (_b = result.error.data) !== null && _b !== void 0 ? _b : errorMessage,
13693
+ data: (_c = result.error.data) !== null && _c !== void 0 ? _c : errorMessage,
13617
13694
  };
13618
13695
  }
13619
13696
  return { data: result === null || result === void 0 ? void 0 : result.data };
@@ -13627,10 +13704,12 @@ const iblFetchBaseQuery = async (args, api, extraOptions) => {
13627
13704
  error: e,
13628
13705
  }));
13629
13706
  // Extract status from error and invoke HTTP error handlers
13707
+ console.log('[MONETIZATION e]', { e });
13708
+ const err = e;
13630
13709
  const errorStatus = typeof e === 'object' && e !== null && 'status' in e
13631
13710
  ? e.status
13632
13711
  : undefined;
13633
- invokeHttpErrorHandler(errorStatus);
13712
+ invokeHttpErrorHandler(errorStatus, err === null || err === void 0 ? void 0 : err.data);
13634
13713
  // Preserve original RTK error object for profile image uploads
13635
13714
  if (args.url &&
13636
13715
  args.url.includes('/profile_images/') &&
@@ -13667,7 +13746,11 @@ const buildEndpointFromServiceLegacy = (service, serviceFn) => {
13667
13746
  }
13668
13747
  catch (err) {
13669
13748
  if (Object.prototype.hasOwnProperty.call(Config.httpErrorHandlers, err === null || err === void 0 ? void 0 : err.status)) {
13670
- Config.httpErrorHandlers[err === null || err === void 0 ? void 0 : err.status]();
13749
+ Config.httpErrorHandlers[err === null || err === void 0 ? void 0 : err.status]({
13750
+ status: err === null || err === void 0 ? void 0 : err.status,
13751
+ body: err === null || err === void 0 ? void 0 : err.body,
13752
+ message: err === null || err === void 0 ? void 0 : err.message,
13753
+ });
13671
13754
  }
13672
13755
  return {
13673
13756
  error: {
@@ -15107,6 +15190,309 @@ createApi({
15107
15190
  }),
15108
15191
  });
15109
15192
 
15193
+ const MONETIZATION_REDUCER_PATH = 'monetizationApiSlice';
15194
+ const SERVICE_BASE = '/api/service/platforms';
15195
+ const BILLING_BASE = '/api/billing/platforms';
15196
+ const MONETIZATION_ENDPOINTS = {
15197
+ // Flow 1 — Stripe Connect Onboarding (Admin)
15198
+ STRIPE_CONNECT_STATUS: {
15199
+ path: (key) => `${SERVICE_BASE}/${key}/stripe/connect/status/`,
15200
+ service: SERVICES.DM,
15201
+ },
15202
+ STRIPE_CONNECT_ONBOARD: {
15203
+ path: (key) => `${SERVICE_BASE}/${key}/stripe/connect/onboard/`,
15204
+ service: SERVICES.DM,
15205
+ },
15206
+ STRIPE_CONNECT_DASHBOARD: {
15207
+ path: (key) => `${SERVICE_BASE}/${key}/stripe/connect/dashboard/`,
15208
+ service: SERVICES.DM,
15209
+ },
15210
+ // Flow 2 — Configure Paywall (Admin)
15211
+ PAYWALL_CONFIG: {
15212
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/paywall/`,
15213
+ service: SERVICES.DM,
15214
+ },
15215
+ // Flow 3 — Manage Prices (Admin)
15216
+ PAYWALL_PRICES: {
15217
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/paywall/prices/`,
15218
+ service: SERVICES.DM,
15219
+ },
15220
+ PAYWALL_PRICE_DETAIL: {
15221
+ path: (key, type, id, priceId) => `${BILLING_BASE}/${key}/items/${type}/${id}/paywall/prices/${priceId}/`,
15222
+ service: SERVICES.DM,
15223
+ },
15224
+ // Flow 4 — Public Pricing (No Auth)
15225
+ PUBLIC_PRICING: {
15226
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/pricing/`,
15227
+ service: SERVICES.DM,
15228
+ },
15229
+ // Flow 5 — Access Check
15230
+ ACCESS_CHECK: {
15231
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/access-check/`,
15232
+ service: SERVICES.DM,
15233
+ },
15234
+ ACCESS_CHECK_UNSCOPED: {
15235
+ path: (type, id) => `/api/billing/access-check/${type}/${id}/`,
15236
+ service: SERVICES.DM,
15237
+ },
15238
+ // Flow 6 — Checkout
15239
+ CHECKOUT: {
15240
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/checkout/`,
15241
+ service: SERVICES.DM,
15242
+ },
15243
+ CHECKOUT_GUEST: {
15244
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/checkout-guest/`,
15245
+ service: SERVICES.DM,
15246
+ },
15247
+ // Flow 7 — Cancel Subscription
15248
+ CANCEL_SUBSCRIPTION: {
15249
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/subscription/cancel/`,
15250
+ service: SERVICES.DM,
15251
+ },
15252
+ // Flow 8 — User Subscriptions
15253
+ MY_SUBSCRIPTIONS: {
15254
+ path: (key) => `${BILLING_BASE}/${key}/my-subscriptions/`,
15255
+ service: SERVICES.DM,
15256
+ },
15257
+ ITEM_SUBSCRIPTION: {
15258
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/subscription/`,
15259
+ service: SERVICES.DM,
15260
+ },
15261
+ // Flow 9 — Platform Analytics (Admin)
15262
+ LIST_PAYWALLS: {
15263
+ path: (key) => `${BILLING_BASE}/${key}/paywalls/`,
15264
+ service: SERVICES.DM,
15265
+ },
15266
+ LIST_SUBSCRIBERS: {
15267
+ path: (key) => `${BILLING_BASE}/${key}/subscribers/`,
15268
+ service: SERVICES.DM,
15269
+ },
15270
+ ITEM_SUBSCRIBERS: {
15271
+ path: (key, type, id) => `${BILLING_BASE}/${key}/items/${type}/${id}/subscribers/`,
15272
+ service: SERVICES.DM,
15273
+ },
15274
+ REVENUE: {
15275
+ path: (key) => `${BILLING_BASE}/${key}/revenue/`,
15276
+ service: SERVICES.DM,
15277
+ },
15278
+ };
15279
+
15280
+ createApi({
15281
+ reducerPath: MONETIZATION_REDUCER_PATH,
15282
+ baseQuery: iblFetchBaseQuery,
15283
+ tagTypes: [
15284
+ 'stripeConnectStatus',
15285
+ 'paywallConfig',
15286
+ 'paywallPrices',
15287
+ 'publicPricing',
15288
+ 'accessCheck',
15289
+ 'mySubscriptions',
15290
+ 'itemSubscription',
15291
+ 'paywalls',
15292
+ 'subscribers',
15293
+ 'revenue',
15294
+ ],
15295
+ endpoints: (builder) => ({
15296
+ // ── Flow 1: Stripe Connect ──
15297
+ getStripeConnectStatus: builder.query({
15298
+ query: ({ platform_key }) => ({
15299
+ url: MONETIZATION_ENDPOINTS.STRIPE_CONNECT_STATUS.path(platform_key),
15300
+ service: MONETIZATION_ENDPOINTS.STRIPE_CONNECT_STATUS.service,
15301
+ method: 'GET',
15302
+ }),
15303
+ providesTags: ['stripeConnectStatus'],
15304
+ }),
15305
+ startStripeConnectOnboarding: builder.mutation({
15306
+ query: ({ platform_key, ...body }) => ({
15307
+ url: MONETIZATION_ENDPOINTS.STRIPE_CONNECT_ONBOARD.path(platform_key),
15308
+ service: MONETIZATION_ENDPOINTS.STRIPE_CONNECT_ONBOARD.service,
15309
+ method: 'POST',
15310
+ body: JSON.stringify(body),
15311
+ }),
15312
+ invalidatesTags: ['stripeConnectStatus'],
15313
+ }),
15314
+ getStripeConnectDashboard: builder.query({
15315
+ query: ({ platform_key }) => ({
15316
+ url: MONETIZATION_ENDPOINTS.STRIPE_CONNECT_DASHBOARD.path(platform_key),
15317
+ service: MONETIZATION_ENDPOINTS.STRIPE_CONNECT_DASHBOARD.service,
15318
+ method: 'GET',
15319
+ }),
15320
+ }),
15321
+ // ── Flow 2: Paywall Config ──
15322
+ getPaywallConfig: builder.query({
15323
+ query: ({ platform_key, item_type, item_id }) => ({
15324
+ url: MONETIZATION_ENDPOINTS.PAYWALL_CONFIG.path(platform_key, item_type, item_id),
15325
+ service: MONETIZATION_ENDPOINTS.PAYWALL_CONFIG.service,
15326
+ method: 'GET',
15327
+ }),
15328
+ providesTags: ['paywallConfig'],
15329
+ }),
15330
+ enablePaywall: builder.mutation({
15331
+ query: ({ platform_key, item_type, item_id, ...body }) => ({
15332
+ url: MONETIZATION_ENDPOINTS.PAYWALL_CONFIG.path(platform_key, item_type, item_id),
15333
+ service: MONETIZATION_ENDPOINTS.PAYWALL_CONFIG.service,
15334
+ method: 'POST',
15335
+ body: JSON.stringify(body),
15336
+ }),
15337
+ invalidatesTags: ['paywallConfig', 'paywalls'],
15338
+ }),
15339
+ disablePaywall: builder.mutation({
15340
+ query: ({ platform_key, item_type, item_id }) => ({
15341
+ url: MONETIZATION_ENDPOINTS.PAYWALL_CONFIG.path(platform_key, item_type, item_id),
15342
+ service: MONETIZATION_ENDPOINTS.PAYWALL_CONFIG.service,
15343
+ method: 'DELETE',
15344
+ }),
15345
+ invalidatesTags: ['paywallConfig', 'paywalls'],
15346
+ }),
15347
+ // ── Flow 3: Manage Prices ──
15348
+ listPrices: builder.query({
15349
+ query: ({ platform_key, item_type, item_id }) => ({
15350
+ url: MONETIZATION_ENDPOINTS.PAYWALL_PRICES.path(platform_key, item_type, item_id),
15351
+ service: MONETIZATION_ENDPOINTS.PAYWALL_PRICES.service,
15352
+ method: 'GET',
15353
+ }),
15354
+ providesTags: ['paywallPrices'],
15355
+ }),
15356
+ createPrice: builder.mutation({
15357
+ query: ({ platform_key, item_type, item_id, ...body }) => ({
15358
+ url: MONETIZATION_ENDPOINTS.PAYWALL_PRICES.path(platform_key, item_type, item_id),
15359
+ service: MONETIZATION_ENDPOINTS.PAYWALL_PRICES.service,
15360
+ method: 'POST',
15361
+ body: JSON.stringify(body),
15362
+ }),
15363
+ invalidatesTags: ['paywallPrices', 'paywallConfig'],
15364
+ }),
15365
+ updatePrice: builder.mutation({
15366
+ query: ({ platform_key, item_type, item_id, price_unique_id, ...body }) => ({
15367
+ url: MONETIZATION_ENDPOINTS.PAYWALL_PRICE_DETAIL.path(platform_key, item_type, item_id, price_unique_id),
15368
+ service: MONETIZATION_ENDPOINTS.PAYWALL_PRICE_DETAIL.service,
15369
+ method: 'PUT',
15370
+ body: JSON.stringify(body),
15371
+ }),
15372
+ invalidatesTags: ['paywallPrices', 'paywallConfig'],
15373
+ }),
15374
+ deletePrice: builder.mutation({
15375
+ query: ({ platform_key, item_type, item_id, price_unique_id }) => ({
15376
+ url: MONETIZATION_ENDPOINTS.PAYWALL_PRICE_DETAIL.path(platform_key, item_type, item_id, price_unique_id),
15377
+ service: MONETIZATION_ENDPOINTS.PAYWALL_PRICE_DETAIL.service,
15378
+ method: 'DELETE',
15379
+ }),
15380
+ invalidatesTags: ['paywallPrices', 'paywallConfig'],
15381
+ }),
15382
+ // ── Flow 4: Public Pricing (No Auth) ──
15383
+ getPublicPricing: builder.query({
15384
+ query: ({ platform_key, item_type, item_id }) => ({
15385
+ url: MONETIZATION_ENDPOINTS.PUBLIC_PRICING.path(platform_key, item_type, item_id),
15386
+ service: MONETIZATION_ENDPOINTS.PUBLIC_PRICING.service,
15387
+ method: 'GET',
15388
+ skipAuth: true,
15389
+ }),
15390
+ providesTags: ['publicPricing'],
15391
+ }),
15392
+ // ── Flow 5: Access Check ──
15393
+ checkAccess: builder.query({
15394
+ query: ({ platform_key, item_type, item_id }) => ({
15395
+ url: MONETIZATION_ENDPOINTS.ACCESS_CHECK.path(platform_key, item_type, item_id),
15396
+ service: MONETIZATION_ENDPOINTS.ACCESS_CHECK.service,
15397
+ method: 'GET',
15398
+ }),
15399
+ providesTags: ['accessCheck'],
15400
+ }),
15401
+ checkAccessUnscoped: builder.query({
15402
+ query: ({ item_type, item_id, platform_key }) => ({
15403
+ url: MONETIZATION_ENDPOINTS.ACCESS_CHECK_UNSCOPED.path(item_type, item_id),
15404
+ service: MONETIZATION_ENDPOINTS.ACCESS_CHECK_UNSCOPED.service,
15405
+ method: 'GET',
15406
+ params: { platform_key },
15407
+ }),
15408
+ providesTags: ['accessCheck'],
15409
+ }),
15410
+ // ── Flow 6A/6B: Checkout (Subscription & One-Time) ──
15411
+ createCheckout: builder.mutation({
15412
+ query: ({ platform_key, item_type, item_id, ...body }) => ({
15413
+ url: MONETIZATION_ENDPOINTS.CHECKOUT.path(platform_key, item_type, item_id),
15414
+ service: MONETIZATION_ENDPOINTS.CHECKOUT.service,
15415
+ method: 'POST',
15416
+ body: JSON.stringify(body),
15417
+ }),
15418
+ }),
15419
+ // ── Flow 6C: Guest Checkout (No Auth) ──
15420
+ createGuestCheckout: builder.mutation({
15421
+ query: ({ platform_key, item_type, item_id, ...body }) => ({
15422
+ url: MONETIZATION_ENDPOINTS.CHECKOUT_GUEST.path(platform_key, item_type, item_id),
15423
+ service: MONETIZATION_ENDPOINTS.CHECKOUT_GUEST.service,
15424
+ method: 'POST',
15425
+ body: JSON.stringify(body),
15426
+ skipAuth: true,
15427
+ }),
15428
+ }),
15429
+ // ── Flow 7: Cancel Subscription ──
15430
+ cancelSubscription: builder.mutation({
15431
+ query: ({ platform_key, item_type, item_id, ...body }) => ({
15432
+ url: MONETIZATION_ENDPOINTS.CANCEL_SUBSCRIPTION.path(platform_key, item_type, item_id),
15433
+ service: MONETIZATION_ENDPOINTS.CANCEL_SUBSCRIPTION.service,
15434
+ method: 'POST',
15435
+ body: JSON.stringify(body),
15436
+ }),
15437
+ invalidatesTags: ['mySubscriptions', 'itemSubscription', 'accessCheck', 'subscribers'],
15438
+ }),
15439
+ // ── Flow 8: User Subscriptions ──
15440
+ getMySubscriptions: builder.query({
15441
+ query: ({ platform_key, ...params }) => ({
15442
+ url: MONETIZATION_ENDPOINTS.MY_SUBSCRIPTIONS.path(platform_key),
15443
+ service: MONETIZATION_ENDPOINTS.MY_SUBSCRIPTIONS.service,
15444
+ method: 'GET',
15445
+ params,
15446
+ }),
15447
+ providesTags: ['mySubscriptions'],
15448
+ }),
15449
+ getItemSubscription: builder.query({
15450
+ query: ({ platform_key, item_type, item_id }) => ({
15451
+ url: MONETIZATION_ENDPOINTS.ITEM_SUBSCRIPTION.path(platform_key, item_type, item_id),
15452
+ service: MONETIZATION_ENDPOINTS.ITEM_SUBSCRIPTION.service,
15453
+ method: 'GET',
15454
+ }),
15455
+ providesTags: ['itemSubscription'],
15456
+ }),
15457
+ // ── Flow 9: Platform Analytics (Admin) ──
15458
+ listPaywalls: builder.query({
15459
+ query: ({ platform_key, ...params }) => ({
15460
+ url: MONETIZATION_ENDPOINTS.LIST_PAYWALLS.path(platform_key),
15461
+ service: MONETIZATION_ENDPOINTS.LIST_PAYWALLS.service,
15462
+ method: 'GET',
15463
+ params,
15464
+ }),
15465
+ providesTags: ['paywalls'],
15466
+ }),
15467
+ listSubscribers: builder.query({
15468
+ query: ({ platform_key, ...params }) => ({
15469
+ url: MONETIZATION_ENDPOINTS.LIST_SUBSCRIBERS.path(platform_key),
15470
+ service: MONETIZATION_ENDPOINTS.LIST_SUBSCRIBERS.service,
15471
+ method: 'GET',
15472
+ params,
15473
+ }),
15474
+ providesTags: ['subscribers'],
15475
+ }),
15476
+ listItemSubscribers: builder.query({
15477
+ query: ({ platform_key, item_type, item_id, ...params }) => ({
15478
+ url: MONETIZATION_ENDPOINTS.ITEM_SUBSCRIBERS.path(platform_key, item_type, item_id),
15479
+ service: MONETIZATION_ENDPOINTS.ITEM_SUBSCRIBERS.service,
15480
+ method: 'GET',
15481
+ params,
15482
+ }),
15483
+ providesTags: ['subscribers'],
15484
+ }),
15485
+ getRevenue: builder.query({
15486
+ query: ({ platform_key }) => ({
15487
+ url: MONETIZATION_ENDPOINTS.REVENUE.path(platform_key),
15488
+ service: MONETIZATION_ENDPOINTS.REVENUE.service,
15489
+ method: 'GET',
15490
+ }),
15491
+ providesTags: ['revenue'],
15492
+ }),
15493
+ }),
15494
+ });
15495
+
15110
15496
  const STRIPE_ENDPOINTS = {
15111
15497
  GET_STRIPE_CONTEXT: {
15112
15498
  service: SERVICES.DM,
@@ -17919,11 +18305,18 @@ function useAdvancedChat({ tenantKey, mentorId, username = ANONYMOUS_USERNAME, t
17919
18305
  onStartNewChat === null || onStartNewChat === void 0 ? void 0 : onStartNewChat(response.session_id);
17920
18306
  }
17921
18307
  catch (error) {
18308
+ console.log("[MONETIZATION] session error", { error });
17922
18309
  if (mentorSettings.mentorVisibility !==
17923
18310
  MentorVisibilityEnum.VIEWABLE_BY_ANYONE) {
17924
- errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(`Failed to start new chat: ${JSON.stringify(error)}`);
17925
- console.log("[auth-redirect] Failed to start new chat", JSON.stringify({ error }));
17926
- redirectToAuthSpa(undefined, undefined, true);
18311
+ //only logging out if error code isn't 402
18312
+ if ((error === null || error === void 0 ? void 0 : error.status) === 402) {
18313
+ on402Error === null || on402Error === void 0 ? void 0 : on402Error(error === null || error === void 0 ? void 0 : error.data);
18314
+ }
18315
+ else {
18316
+ errorHandler === null || errorHandler === void 0 ? void 0 : errorHandler(`Failed to start new chat: ${JSON.stringify(error)}`);
18317
+ console.log("[auth-redirect] Failed to start new chat", JSON.stringify({ error }));
18318
+ redirectToAuthSpa(undefined, undefined, true);
18319
+ }
17927
18320
  }
17928
18321
  }
17929
18322
  }, [
@@ -22898,5 +23291,5 @@ const checkRbacPermission = (rbacPermissions, rbacResource, enableRBAC = true) =
22898
23291
  return checkRbacPermissionInternal(rbacPermissions, rbacResource);
22899
23292
  };
22900
23293
 
22901
- export { ALPHANUMERIC_32_REGEX, ANONYMOUS_USERNAME, AuthContext, AuthContextProvider, AuthProvider, CHAT_AREA_SIZE, LOCAL_STORAGE_KEYS, MAX_INITIAL_WEBSOCKET_CONNECTION_ATTEMPTS, MENTOR_CHAT_DOCUMENTS_EXTENSIONS, METADATAS, MentorProvider, STREAMING_CONTENT_BUFFER_THRESHOLD, STREAMING_CONTENT_FLUSH_INTERVAL, SUBSCRIPTION_MESSAGES, SUBSCRIPTION_PACKAGES, SUBSCRIPTION_PACKAGES_V2, SUBSCRIPTION_TRIGGERS, SUBSCRIPTION_V2_TRIGGERS, SubscriptionFlow, SubscriptionFlowV2, TOOLS, TenantContext, TenantContextProvider, TenantProvider, TimeTracker, WithFormPermissions, WithPermissions, addFiles, addProtocolToUrl, advancedTabs, advancedTabsProperties, chatActions, chatSliceReducerShared, checkModelAvailable, checkOllamaHealth, checkRbacPermission, clearAuthCookies, clearCookies, clearCurrentTenantCookie, clearFiles, combineCSVData, convertToOllamaMessages, createFileReference, createMultipleFileReferences, csvDataToText, defaultSessionIds, deleteCookie, deleteCookieOnAllDomains, filesReducer, filesSlice, formatRelativeTime, getAuthSpaJoinUrl, getDomainParts, getFileInfo, getInitials, getLocalLLMSystemPrompt, getNextNavigation, getParentDomain, getPlatform, getPlatformKey, getTimeAgo, getUserName, handleLogout, isAlphaNumeric32, isExpo, isInIframe, isJSON, isLoggedIn, isNode, isReactNative$1 as isReactNative, isTauri, isWeb$2 as isWeb, loadMetadataConfig, markdownToPlainText, parseCSV, redirectToAuthSpa, redirectToAuthSpaJoinTenant, removeFile, requestPresignedUrl, safeRequire, selectActiveChatMessages, selectActiveTab, selectArtifactsEnabled, selectChats, selectCurrentStreamingArtifact, selectCurrentStreamingMessage, selectDocumentFilter, selectIframeContext, selectIsError, selectIsPending, selectIsStopped, selectIsTyping, selectLastArtifactContentFlushTime, selectNumberOfActiveChatMessages, selectSessionId, selectSessionIds, selectShouldStartNewChat, selectShowingSharedChat, selectStatus, selectStreaming, selectStreamingArtifactContentBuffer, selectStreamingArtifactFullContent, selectToken, selectTokenEnabled, selectTools, sendMessageToParentWebsite, setCookieForAuth, streamOllamaChat, syncAuthToCookies, tenantKeySchema, tenantSchema, translatePrompt, updateFileMetadata, updateFileProgress, updateFileRetryCount, updateFileStatus, updateFileUrl, updateFileUrlFromWebSocket, uploadToS3, useAdvancedChat, useAuthContext, useAuthProvider, useChat, useDayJs, useExternalPricingPlan, useMentorSettings, useMentorTools, useProfileImageUpload, useSubscriptionHandler, useSubscriptionHandlerV2, useTenantContext, useTenantMetadata, useTimeTracker, useTimeTrackerNative, useUserProfileUpdate, userDataSchema, validateFile };
23294
+ export { ALPHANUMERIC_32_REGEX, ANONYMOUS_USERNAME, AuthContext, AuthContextProvider, AuthProvider, CHAT_AREA_SIZE, LOCAL_STORAGE_KEYS, MAX_INITIAL_WEBSOCKET_CONNECTION_ATTEMPTS, MENTOR_CHAT_DOCUMENTS_EXTENSIONS, METADATAS, MentorProvider, STREAMING_CONTENT_BUFFER_THRESHOLD, STREAMING_CONTENT_FLUSH_INTERVAL, SUBSCRIPTION_MESSAGES, SUBSCRIPTION_PACKAGES, SUBSCRIPTION_PACKAGES_V2, SUBSCRIPTION_TRIGGERS, SUBSCRIPTION_V2_TRIGGERS, SubscriptionFlow, SubscriptionFlowV2, TOOLS, TenantContext, TenantContextProvider, TenantProvider, TimeTracker, WithFormPermissions, WithPermissions, addFiles, addProtocolToUrl, advancedTabs, advancedTabsProperties, chatActions, chatSliceReducerShared, checkModelAvailable, checkOllamaHealth, checkRbacPermission, clearAuthCookies, clearCookies, clearCurrentTenantCookie, clearFiles, combineCSVData, convertToOllamaMessages, createFileReference, createMultipleFileReferences, csvDataToText, defaultSessionIds, deleteCookie, deleteCookieOnAllDomains, filesReducer, filesSlice, formatRelativeTime, getAuthSpaJoinUrl, getDomainParts, getFileInfo, getInitials, getLocalLLMSystemPrompt, getNextNavigation, getParentDomain, getPlatform, getPlatformKey, getTimeAgo, getUserName, handleLogout, isAlphaNumeric32, isExpo, isInIframe, isJSON, isLoggedIn, isNode, isReactNative$1 as isReactNative, isTauri, isWeb$2 as isWeb, loadMetadataConfig, markdownToPlainText, monetizationSlice, parseCSV, redirectToAuthSpa, redirectToAuthSpaJoinTenant, removeFile, requestPresignedUrl, safeRequire, selectActiveChatMessages, selectActiveTab, selectArtifactsEnabled, selectChats, selectCurrentStreamingArtifact, selectCurrentStreamingMessage, selectDocumentFilter, selectIframeContext, selectIsError, selectIsPending, selectIsStopped, selectIsTyping, selectLastArtifactContentFlushTime, selectNumberOfActiveChatMessages, selectSessionId, selectSessionIds, selectShouldStartNewChat, selectShowingSharedChat, selectStatus, selectStreaming, selectStreamingArtifactContentBuffer, selectStreamingArtifactFullContent, selectToken, selectTokenEnabled, selectTools, sendMessageToParentWebsite, setAccessCheckResponse, setAdvancedDisplayMonetizationCheckoutModal, setCookieForAuth, setDisplayMonetizationCheckoutModal, showMonetizationCheckoutModal, streamOllamaChat, syncAuthToCookies, tenantKeySchema, tenantSchema, translatePrompt, updateFileMetadata, updateFileProgress, updateFileRetryCount, updateFileStatus, updateFileUrl, updateFileUrlFromWebSocket, uploadToS3, useAdvancedChat, useAuthContext, useAuthProvider, useChat, useDayJs, useExternalPricingPlan, useMentorSettings, useMentorTools, useProfileImageUpload, useSubscriptionHandler, useSubscriptionHandlerV2, useTenantContext, useTenantMetadata, useTimeTracker, useTimeTrackerNative, useUserProfileUpdate, userDataSchema, validateFile };
22902
23295
  //# sourceMappingURL=index.esm.js.map