@techstuff-dev/foundation-api-utils 2.3.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/cjs/chunks/{shared-CdwWllrh.js → shared-DVGP3iZ0.js} +2 -2
  2. package/dist/cjs/chunks/{shared-CdwWllrh.js.map → shared-DVGP3iZ0.js.map} +1 -1
  3. package/dist/cjs/chunks/{slice-Dpwqdz65.js → slice-C4MKCa5N.js} +276 -745
  4. package/dist/cjs/chunks/slice-C4MKCa5N.js.map +1 -0
  5. package/dist/cjs/chunks/useAuth-BVyDLl6H.js +25 -0
  6. package/dist/cjs/chunks/useAuth-BVyDLl6H.js.map +1 -0
  7. package/dist/cjs/hooks/index.native.js +1 -1
  8. package/dist/cjs/hooks/index.web.js +1 -1
  9. package/dist/cjs/index.js +644 -31
  10. package/dist/cjs/index.js.map +1 -1
  11. package/dist/cjs/store/index.native.js +2 -4
  12. package/dist/cjs/store/index.native.js.map +1 -1
  13. package/dist/cjs/store/index.web.js +2 -4
  14. package/dist/cjs/store/index.web.js.map +1 -1
  15. package/dist/esm/chunks/{shared-PYY2b9oT.js → shared-DvU_DUT_.js} +2 -2
  16. package/dist/esm/chunks/{shared-PYY2b9oT.js.map → shared-DvU_DUT_.js.map} +1 -1
  17. package/dist/esm/chunks/{slice-BD3oWPrI.js → slice-B2f63n1v.js} +265 -721
  18. package/dist/esm/chunks/slice-B2f63n1v.js.map +1 -0
  19. package/dist/esm/chunks/useAuth-CTcqsTAS.js +23 -0
  20. package/dist/esm/chunks/useAuth-CTcqsTAS.js.map +1 -0
  21. package/dist/esm/hooks/index.native.js +1 -1
  22. package/dist/esm/hooks/index.web.js +1 -1
  23. package/dist/esm/index.js +609 -4
  24. package/dist/esm/index.js.map +1 -1
  25. package/dist/esm/store/index.native.js +2 -4
  26. package/dist/esm/store/index.native.js.map +1 -1
  27. package/dist/esm/store/index.web.js +2 -4
  28. package/dist/esm/store/index.web.js.map +1 -1
  29. package/dist/types/hooks/index.d.ts +1 -1
  30. package/dist/types/{index-CNDW7aai.d.ts → index-UGRVwFLD.d.ts} +108 -38
  31. package/dist/types/index.d.ts +2897 -140
  32. package/dist/types/store/index.d.ts +1 -1
  33. package/package.json +2 -3
  34. package/dist/cjs/chunks/slice-Dpwqdz65.js.map +0 -1
  35. package/dist/cjs/chunks/useAuth-DKhvUX_r.js +0 -13
  36. package/dist/cjs/chunks/useAuth-DKhvUX_r.js.map +0 -1
  37. package/dist/esm/chunks/slice-BD3oWPrI.js.map +0 -1
  38. package/dist/esm/chunks/useAuth-8d6DlERn.js +0 -11
  39. package/dist/esm/chunks/useAuth-8d6DlERn.js.map +0 -1
@@ -1,9 +1,7 @@
1
- import { Auth } from 'aws-amplify';
2
- import { r as resetCreating, s as setCredentials, l as logout } from './slice-ChJ8ZvmP.js';
1
+ import { r as resetCreating, l as logout, s as setCredentials } from './slice-ChJ8ZvmP.js';
3
2
  import { nanoid, formatProdErrorMessage, createAction, createSelector as createSelector$1, isPlainObject as isPlainObject$1, createNextState, createAsyncThunk, createSlice, prepareAutoBatched, isAnyOf, isFulfilled, isRejectedWithValue, combineReducers, SHOULD_AUTOBATCH, isAllOf, isRejected, isPending, isAction, isAsyncThunkAction } from '@reduxjs/toolkit';
4
3
  import { useStore, useSelector, useDispatch, batch, shallowEqual } from 'react-redux';
5
4
  import { useCallback, useDebugValue, useMemo, useState, useEffect, useRef, useLayoutEffect } from 'react';
6
- import { jwtDecode } from 'jwt-decode';
7
5
 
8
6
  // src/utils/env.ts
9
7
  var NOTHING = Symbol.for("immer-nothing");
@@ -5095,641 +5093,17 @@ function createUnwrappingBaseQuery(baseQueryOptions) {
5095
5093
  };
5096
5094
  }
5097
5095
 
5098
- function onlyUnique(value, index, self) {
5099
- return self.indexOf(value) === index;
5100
- }
5101
- function applyCoupon(coupon, netTotal) {
5102
- const discountedAmount = netTotal * (Number(coupon.discount) / 100);
5103
- const discountedTotal = netTotal - discountedAmount;
5104
- const data = {
5105
- ...coupon,
5106
- discountedTotal,
5107
- discountedAmount,
5108
- };
5109
- return data;
5110
- }
5111
- function applyTax(taxRate, netTotal) {
5112
- const taxAmount = netTotal * (taxRate.percentage / 100);
5113
- return taxAmount;
5114
- }
5115
- function toCamelCaseObject(obj) {
5116
- const toCamelCase = (str) => {
5117
- return str.replace(/([-_][a-z])/gi, (match) => {
5118
- return match.toUpperCase().replace(/[-_]/, '');
5119
- });
5120
- };
5121
- const camelCaseObject = {};
5122
- for (const key in obj) {
5123
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
5124
- const camelKey = toCamelCase(key);
5125
- camelCaseObject[camelKey] = obj[key];
5126
- }
5127
- }
5128
- return camelCaseObject;
5129
- }
5130
-
5131
- // TODO: typing.
5132
- const formatUserPayload = (payload) => {
5133
- const { email: userEmail, given_name: firstName, family_name: lastName, birthdate: dateOfBirth, picture: picture, 'cognito:username': uuid, 'custom:termsAccepted': termsAccepted, 'custom:subscriptionId': subscriptionId, 'custom:contactPreferences': contactPreference, 'custom:customerId': customerId, } = payload;
5134
- const parsedTermsAccepted = termsAccepted ? JSON.parse(termsAccepted) : null;
5135
- const parsedContactPreference = contactPreference
5136
- ? JSON.parse(contactPreference)
5137
- : null;
5138
- const data = {
5139
- userEmail,
5140
- lastName,
5141
- firstName,
5142
- dateOfBirth,
5143
- /** Handles the auth micro service/Cognito serving boolean options as a string. */
5144
- termsAccepted: parsedTermsAccepted,
5145
- contactPreference: parsedContactPreference,
5146
- uuid,
5147
- subscription: subscriptionId || null,
5148
- customerId,
5149
- picture,
5150
- };
5151
- return data;
5152
- };
5153
- function formatPromos(data) {
5154
- return data.map((item) => {
5155
- return {
5156
- uuid: item?._source?.uuid?.[0],
5157
- id: item?._source?.uuid?.[0],
5158
- title: item?._source?.title?.[0],
5159
- image: item?._source?.image?.[0],
5160
- imageFormatted: item?._source?.image_formatted?.[0],
5161
- description: item?._source?.description?.[0],
5162
- created: item?._source?.created?.[0],
5163
- updated: item?._source?.updated?.[0],
5164
- weight: item?._source?.weight?.[0],
5165
- buttonText: item?._source?.button_text?.[0],
5166
- link: item?._source?.link?.[0],
5167
- linkMobile: item?._source?.link_mobile?.[0],
5168
- term: item?._source?.term?.[0],
5169
- // video: item?._source?.video?.[0],
5170
- // align: item?._source?.align?.[0],
5171
- // section: item?._source?.section?.[0],
5172
- // backgroundImage: item?._source?.background_image?.[0],
5173
- // backgroundVideo: item?._source?.background_video?.[0],
5174
- // backgroundImageFormatted: item?._source?.background_image_formatted?.[0],
5175
- // langcode: item?._source?.langcode?.[0],
5176
- // authPanel: item?._source?.auth_panel?.[0],
5177
- };
5178
- });
5179
- }
5180
- function formatWorkout(data) {
5181
- return data.map((item) => {
5182
- return {
5183
- changed: item?._source?.changed?.[0],
5184
- created: item?._source?.created?.[0],
5185
- uuid: item?._source?.uuid?.[0],
5186
- description: item?._source?.description?.[0],
5187
- duration: item?._source?.duration_filter?.[0],
5188
- // duration_filter: item?._source?.duration_filter?.[0],
5189
- level: item?._source?.level?.[0],
5190
- published: item?._source?.published?.[0],
5191
- targeted_section: item?._source?.targeted_section?.[0],
5192
- uid: item?._source?.uid?.[0],
5193
- imageStyled: item?._source?.image_16_9?.[0],
5194
- image: item?._source?.image?.[0],
5195
- title: item?._source?.title?.[0],
5196
- video: item?._source?.video_url?.[0],
5197
- videoDownload: item?._source?.video_download?.[0],
5198
- videoPoster: item?._source?.video_poster?.[0],
5199
- workoutCategory: item?._source?.workout_category?.[0],
5200
- workoutType: item?._source?.workout_type?.[0],
5201
- livestreamSection: item?._source?.livestream_section?.[0],
5202
- };
5203
- });
5204
- }
5205
- // export function formatSeries(data: Series[], channel: string) {
5206
- // const formattedSeriesSelection = data.map((series) => {
5207
- // return {
5208
- // uuid: series.uuid,
5209
- // id: series.uuid,
5210
- // title: series.title,
5211
- // subtitle: series.subtitle,
5212
- // thumb: series.imageThumbnailURL,
5213
- // mainImage: series.imageURL,
5214
- // description: series.summary.value,
5215
- // body: series.body.value,
5216
- // nid: series.nid,
5217
- // seasonList: series.season,
5218
- // channel,
5219
- // };
5220
- // });
5221
- // return formattedSeriesSelection;
5222
- // }
5223
- function formatShortform(data) {
5224
- return data.map((item) => {
5225
- const { _source } = item;
5226
- return {
5227
- uuid: _source.uuid && _source.uuid[0],
5228
- id: _source.uuid && _source.uuid[0],
5229
- nid: _source.nid && _source.nid[0],
5230
- title: _source.title && _source.title[0],
5231
- thumb: _source.field_image_thumb && _source.field_image_thumb[0],
5232
- mainImage: _source.field_image_poster && _source.field_image_poster[0],
5233
- description: _source.field_short_synopsis && _source.field_short_synopsis[0],
5234
- body: _source.field_body && _source.field_body[0],
5235
- channel: _source.field_channel && _source.field_channel[0],
5236
- updated: _source.revision_timestamp && _source.revision_timestamp[0],
5237
- langcode: _source.langcode && _source.langcode[0],
5238
- video: _source.field_videomanifest && _source.field_videomanifest[0],
5239
- duration: _source.field_duration && _source.field_duration[0],
5240
- category: _source.field_category && _source.field_category[0],
5241
- };
5242
- });
5243
- }
5244
- // export function formatLongform(data: ESLongForm[]) {
5245
- // return data.map((item) => {
5246
- // const { _source } = item;
5247
- // return {
5248
- // uuid: _source.uuid && _source.uuid[0],
5249
- // id: _source.uuid && _source.uuid[0],
5250
- // nid: _source.nid && _source.nid[0],
5251
- // title: _source.title && _source.title[0],
5252
- // image: _source.image && _source.image[0],
5253
- // image_promo: _source.image_promo && _source.image_promo[0],
5254
- // image_promo_large:
5255
- // _source.image_promo_large && _source.image_promo_large[0],
5256
- // image_poster: _source.image_poster && _source.image_poster[0],
5257
- // summary: _source.summary && _source.summary[0],
5258
- // created: _source.created && _source.created[0],
5259
- // updated: _source.revision_timestamp && _source.revision_timestamp[0],
5260
- // video: _source.video_manifest && _source.video_manifest[0],
5261
- // rating: _source.rating && _source.rating[0],
5262
- // released: _source.released_date && _source.released_date[0],
5263
- // source_id: _source.source_id && _source.source_id[0],
5264
- // director: _source.director && _source.director[0],
5265
- // duration: _source.duration && _source.duration[0],
5266
- // path: _source.path && _source.path[0],
5267
- // genres: _source.genres,
5268
- // actors: _source.actors,
5269
- // writers: _source.writers,
5270
- // };
5271
- // });
5272
- // }
5273
- function formatFaqs(data) {
5274
- return data.map((item) => {
5275
- const { _source } = item;
5276
- return {
5277
- uuid: _source.uuid && _source.uuid[0],
5278
- id: _source.uuid && _source.uuid[0],
5279
- title: _source.title && _source.title[0],
5280
- answer: _source.answer && _source.answer[0],
5281
- created: _source.created && _source.created[0],
5282
- updated: _source.updated && _source.updated[0],
5283
- };
5284
- });
5285
- }
5286
- function formatPages(data) {
5287
- return data.map((item) => {
5288
- return {
5289
- uuid: item?._source?.uuid?.[0],
5290
- id: item?._source?.uuid?.[0],
5291
- title: item?._source?.title?.[0],
5292
- body: item?._source?.body?.[0],
5293
- created: item?._source?.created?.[0],
5294
- updated: item?._source?.updated?.[0],
5295
- langcode: item?._source?.langcode?.[0],
5296
- url: item?._source?.url?.[0],
5297
- };
5298
- });
5299
- }
5300
- function formatSettings(data) {
5301
- return data.map((item) => {
5302
- const { _source } = item;
5303
- const fieldset = _source.fieldset && _source.fieldset[0].toLowerCase();
5304
- return {
5305
- uuid: _source.uuid && _source.uuid[0],
5306
- created: _source.created && _source.created[0],
5307
- updated: _source.updated && _source.updated[0],
5308
- status: _source.status && _source.status[0],
5309
- type: _source.type && _source.type[0],
5310
- video: _source.video && _source.video[0],
5311
- number: _source.number && _source.number[0],
5312
- pass: _source.pass && _source.pass[0],
5313
- fieldset,
5314
- };
5315
- });
5316
- }
5317
- function formatPress(data) {
5318
- return data.map((item) => {
5319
- const { _source } = item;
5320
- return {
5321
- uuid: _source.uuid && _source.uuid[0],
5322
- created: _source.created && _source.created[0],
5323
- updated: _source.updated && _source.updated[0],
5324
- image: _source.image && _source.image[0],
5325
- title: _source.title && _source.title[0],
5326
- };
5327
- });
5328
- }
5329
- function formatGuests(data) {
5330
- return data.map((item) => {
5331
- const { _source } = item;
5332
- return {
5333
- uuid: _source.uuid && _source.uuid[0],
5334
- id: _source.id && _source.id[0],
5335
- title: _source.title && _source.title[0],
5336
- updated: _source.updated && _source.updated[0],
5337
- description: _source.description && _source.description[0],
5338
- image: _source.image_16_9 && _source.image_16_9[0],
5339
- display: _source.display && _source.display[0],
5340
- };
5341
- });
5342
- }
5343
- function formatVideos(data) {
5344
- return data.map((item) => {
5345
- return {
5346
- uuid: item?._source?.uuid?.[0],
5347
- title: item?._source?.title?.[0],
5348
- created: item?._source?.created?.[0],
5349
- updated: item?._source?.updated?.[0],
5350
- description: item?._source?.description?.[0],
5351
- image: item?._source?.image?.[0],
5352
- duration: item?._source?.duration?.[0],
5353
- section: item?._source?.section?.[0],
5354
- videoPoster: item?._source?.video_poster?.[0],
5355
- video: item?._source?.video_url?.[0],
5356
- videoDownload: item?._source?.video_download?.[0],
5357
- sectionId: item?._source?.section_id?.[0],
5358
- };
5359
- });
5360
- }
5361
- function formatSections(data) {
5362
- return data.map((item) => {
5363
- const { _source } = item;
5364
- return {
5365
- uuid: _source.uuid && _source.uuid[0],
5366
- title: _source.title && _source.title[0],
5367
- description: _source.description && _source.description[0],
5368
- image: _source.image && _source.image[0],
5369
- challenge: _source.challenge && _source.challenge[0],
5370
- display: _source.display && _source.display[0],
5371
- id: _source.id && _source.id[0],
5372
- };
5373
- });
5374
- }
5375
- function formatSchedule(data) {
5376
- return data.map((item) => {
5377
- return {
5378
- uuid: item?._source?.uuid?.[0],
5379
- created: item?._source?.created?.[0],
5380
- langcode: item?._source?.langcode?.[0],
5381
- updated: item?._source?.updated?.[0],
5382
- days: [
5383
- {
5384
- monday: item?._source?.monday_title?.map((title, index) => {
5385
- return {
5386
- end: item?._source?.monday_end?.[index],
5387
- start: item?._source?.monday_start?.[index],
5388
- title,
5389
- video: item?._source?.monday_video?.[index],
5390
- live: item?._source?.monday_live?.[index],
5391
- };
5392
- }),
5393
- },
5394
- {
5395
- tuesday: item?._source?.tuesday_title?.map((title, index) => {
5396
- return {
5397
- end: item?._source?.tuesday_end?.[index],
5398
- start: item?._source?.tuesday_start?.[index],
5399
- title,
5400
- video: item?._source?.tuesday_video?.[index],
5401
- live: item?._source?.tuesday_live?.[index],
5402
- };
5403
- }),
5404
- },
5405
- {
5406
- wednesday: item?._source?.wednesday_title?.map((title, index) => {
5407
- return {
5408
- end: item?._source?.wednesday_end?.[index],
5409
- start: item?._source?.wednesday_start?.[index],
5410
- title,
5411
- video: item?._source?.wednesday_video?.[index],
5412
- live: item?._source?.wednesday_live?.[index],
5413
- };
5414
- }),
5415
- },
5416
- {
5417
- thursday: item?._source?.thursday_title?.map((title, index) => {
5418
- return {
5419
- end: item?._source?.thursday_end?.[index],
5420
- start: item?._source?.thursday_start?.[index],
5421
- title,
5422
- video: item?._source?.thursday_video?.[index],
5423
- live: item?._source?.thursday_live?.[index],
5424
- };
5425
- }),
5426
- },
5427
- {
5428
- friday: item?._source?.friday_title?.map((title, index) => {
5429
- return {
5430
- end: item?._source?.friday_end?.[index],
5431
- start: item?._source?.friday_start?.[index],
5432
- title,
5433
- video: item?._source?.friday_video?.[index],
5434
- live: item?._source?.friday_live?.[index],
5435
- };
5436
- }),
5437
- },
5438
- {
5439
- saturday: item?._source?.saturday_title?.map((title, index) => {
5440
- return {
5441
- end: item?._source?.saturday_end?.[index],
5442
- start: item?._source?.saturday_start?.[index],
5443
- title,
5444
- video: item?._source?.saturday_video?.[index],
5445
- live: item?._source?.saturday_live?.[index],
5446
- };
5447
- }),
5448
- },
5449
- {
5450
- sunday: item?._source?.sunday_title?.map((title, index) => {
5451
- return {
5452
- end: item?._source?.sunday_end?.[index],
5453
- start: item?._source?.sunday_start?.[index],
5454
- title,
5455
- video: item?._source?.sunday_video?.[index],
5456
- live: item?._source?.sunday_live?.[index],
5457
- };
5458
- }),
5459
- },
5460
- ],
5461
- };
5462
- });
5463
- }
5464
- function formatChallenges(data) {
5465
- return data.map((item) => {
5466
- const { _source } = item;
5467
- return {
5468
- uuid: _source?.uuid?.[0],
5469
- title: _source.title && _source.title[0],
5470
- body: _source.body && _source.body[0],
5471
- image: _source.image && _source.image[0],
5472
- challengeKey: _source.challenge_key && _source.challenge_key[0],
5473
- created: _source.created && _source.created[0],
5474
- days: _source.days,
5475
- updated: _source.updated && _source.updated[0],
5476
- purchaseButtonLabel: _source.purchase_button_label && _source.purchase_button_label[0],
5477
- price: _source.price && _source.price[0],
5478
- };
5479
- });
5480
- }
5481
- function formatChallengeDays(data) {
5482
- return data.map((item) => {
5483
- return {
5484
- uuid: item?._source?.uuid?.[0],
5485
- title: item?._source?.title?.[0],
5486
- body: item?._source?.body?.[0],
5487
- image: item?._source?.image?.[0],
5488
- created: item?._source?.created?.[0],
5489
- updated: item?._source?.updated?.[0],
5490
- video: item?._source?.video?.[0],
5491
- workout: item?._source?.workout?.[0],
5492
- };
5493
- });
5494
- }
5495
- function formatSecondsToISO8601Duration(seconds) {
5496
- if (!seconds)
5497
- return '';
5498
- // Calculate hours, minutes, and remaining seconds
5499
- const hours = Math.floor(seconds / 3600);
5500
- const minutes = Math.floor((seconds % 3600) / 60);
5501
- const remainingSeconds = seconds % 60;
5502
- // Build the ISO 8601 duration string
5503
- let duration = 'PT';
5504
- if (hours > 0) {
5505
- duration += `${hours}H`;
5506
- }
5507
- if (minutes > 0) {
5508
- duration += `${minutes}M`;
5509
- }
5510
- if (remainingSeconds > 0 || duration === 'PT') {
5511
- duration += `${remainingSeconds}S`;
5512
- }
5513
- return duration;
5514
- }
5515
- function formatAuthSession(session) {
5516
- return {
5517
- accessToken: session?.tokens?.accessToken.toString(),
5518
- idToken: session?.tokens?.idToken?.toString(),
5519
- refreshToken: undefined,
5520
- accessTokenExpiry: session?.tokens?.idToken?.payload?.exp,
5521
- expires: session?.tokens?.idToken?.payload?.exp,
5522
- sub: session?.tokens?.idToken?.payload?.['cognito:username']?.toString(),
5523
- details: {
5524
- userEmail: session?.tokens?.idToken?.payload?.email?.toString(),
5525
- firstName: session?.tokens?.idToken?.payload?.given_name?.toString(),
5526
- lastName: session?.tokens?.idToken?.payload?.family_name?.toString(),
5527
- dateOfBirth: session?.tokens?.idToken?.payload?.birthdate?.toString(),
5528
- 'cognito:username': session?.tokens?.idToken?.payload?.['cognito:username']?.toString(),
5529
- 'custom:termsAccepted': session?.tokens?.idToken?.payload?.['custom:termsAccepted']?.toString(),
5530
- 'custom:subscriptionId': session?.tokens?.idToken?.payload?.['custom:subscriptionId']?.toString(),
5531
- 'custom:contactPreferences': session?.tokens?.idToken?.payload?.['custom:contactPreferences']?.toString(),
5532
- 'custom:customerId': session?.tokens?.idToken?.payload?.['custom:customerId']?.toString(),
5533
- picture: session?.tokens?.idToken?.payload?.picture?.toString(),
5534
- },
5535
- };
5536
- }
5537
- function formatFedaratedSession(session) {
5538
- return {
5539
- accessToken: session?.accessToken?.jwtToken,
5540
- idToken: session?.idToken?.jwtToken,
5541
- refreshToken: session?.refreshToken?.token,
5542
- accessTokenExpiry: session?.accessToken?.payload?.exp,
5543
- expires: session?.accessToken?.payload?.exp,
5544
- sub: session?.idToken?.payload?.sub,
5545
- details: {
5546
- userEmail: session?.idToken?.payload?.email,
5547
- firstName: session?.idToken?.payload?.given_name,
5548
- lastName: session?.idToken?.payload?.family_name,
5549
- dateOfBirth: session?.idToken?.payload?.birthdate,
5550
- 'cognito:username': session?.idToken?.payload?.sub,
5551
- 'custom:termsAccepted': session?.idToken?.payload?.['custom:termsAccepted'],
5552
- 'custom:subscriptionId': session?.idToken?.payload?.['custom:subscriptionId'],
5553
- 'custom:contactPreferences': session?.idToken?.payload?.['custom:contactPreferences'],
5554
- 'custom:customerId': session?.idToken?.payload?.['custom:customerId'],
5555
- picture: session?.idToken?.payload?.picture,
5556
- id: toCamelCaseObject(session?.idToken?.payload),
5557
- },
5558
- };
5559
- }
5560
- function formatSocialAuthSession(tokens) {
5561
- const idToken = jwtDecode(tokens.idToken);
5562
- return {
5563
- socialSignin: true,
5564
- accessToken: tokens.accessToken,
5565
- idToken: tokens.idToken,
5566
- refreshToken: tokens.refreshToken,
5567
- accessTokenExpiry: idToken?.exp,
5568
- expires: idToken?.exp,
5569
- sub: idToken.sub,
5570
- details: {
5571
- userEmail: idToken.email,
5572
- firstName: idToken.given_name,
5573
- lastName: idToken.family_name,
5574
- dateOfBirth: idToken?.birthdate,
5575
- 'cognito:username': idToken?.['cognito:username'],
5576
- 'custom:termsAccepted': idToken?.['custom:termsAccepted'],
5577
- 'custom:subscriptionId': idToken?.['custom:subscriptionId'],
5578
- 'custom:contactPreferences': idToken?.['custom:contactPreferences'],
5579
- 'custom:customerId': idToken?.['custom:customerId'],
5580
- picture: idToken?.picture,
5581
- },
5582
- };
5583
- }
5584
- function formatConfig(data) {
5585
- return data.map((item) => {
5586
- return {
5587
- uuid: item?._source?.uuid?.[0],
5588
- id: item?._source?.uuid?.[0],
5589
- created: item?._source?.created?.[0],
5590
- updated: item?._source?.updated?.[0],
5591
- type: item?._source?.type?.[0],
5592
- cla: item?._source?.cla?.[0],
5593
- enabled: item?._source?.enabled?.[0],
5594
- name: item?._source?.name?.[0],
5595
- price: item?._source?.price?.[0],
5596
- video: item?._source?.video?.[0],
5597
- imageHomepage: item?._source?.image_homepage?.[0],
5598
- imageSectionBanner: item?._source?.image_section_banner?.[0],
5599
- };
5600
- });
5601
- }
5602
- function formatSectionPanels(data) {
5603
- return data.map((item) => {
5604
- return {
5605
- uuid: item?._source?.uuid?.[0],
5606
- id: item?._source?.uuid?.[0],
5607
- title: item?._source?.title?.[0],
5608
- created: item?._source?.created?.[0],
5609
- updated: item?._source?.updated?.[0],
5610
- weight: item?._source?.weight?.[0],
5611
- items: item?._source?.item_uuid,
5612
- type: item?._source?.type?.[0],
5613
- };
5614
- });
5615
- }
5616
- function formatSectionItems(data) {
5617
- return data.map((item) => {
5618
- return {
5619
- uuid: item?._source?.uuid?.[0],
5620
- id: item?._source?.uuid?.[0],
5621
- title: item?._source?.title?.[0],
5622
- created: item?._source?.created?.[0],
5623
- updated: item?._source?.updated?.[0],
5624
- type: item?._source?.type?.[0],
5625
- term: item?._source?.term?.[0],
5626
- image: item?._source?.custom_image_formatted?.[0],
5627
- bannerImage: item?._source?.banner_image_formatted?.[0],
5628
- };
5629
- });
5096
+ /**
5097
+ * Shared helper to extract auth tokens from the Redux store.
5098
+ * Used by all RTK Query services to attach tokens to request headers
5099
+ * without depending on aws-amplify's Auth.currentSession().
5100
+ */
5101
+ function getAuthHeaders(getState) {
5102
+ const state = getState();
5103
+ const accessToken = state?.auth?.user?.accessToken;
5104
+ const idToken = state?.auth?.user?.idToken;
5105
+ return { accessToken, idToken };
5630
5106
  }
5631
- const formatTaxonomies = (data) => {
5632
- return data.map((item) => {
5633
- return {
5634
- uuid: item?._source?.uuid?.[0],
5635
- id: item?._source?.uuid?.[0],
5636
- updated: item?._source?.updated?.[0],
5637
- vocabulary: item?._source?.vocabulary?.[0],
5638
- name: item?._source?.name?.[0],
5639
- description: item?._source?.description?.[0],
5640
- image: item?._source?.image?.[0],
5641
- imageBanner: item?._source?.image_banner?.[0],
5642
- imageBannerTaxonomy: item?._source?.image_banner_taxonomy?.[0],
5643
- imageLarge: item?._source?.image_large_16_9?.[0],
5644
- weight: item?._source?.weight?.[0],
5645
- parentName: item?._source?.parent_name?.[0],
5646
- color: item?._source?.color?.[0],
5647
- };
5648
- });
5649
- };
5650
- const formatSeries = (data) => {
5651
- return data.map((item) => {
5652
- return {
5653
- uuid: item?._source?.uuid?.[0],
5654
- id: item?._source?.uuid?.[0],
5655
- created: item?._source?.created?.[0],
5656
- updated: item?._source?.updated?.[0],
5657
- title: item?._source?.display_title?.[0],
5658
- synopsis: item?._source?.synopsis?.[0],
5659
- imagePoster: item?._source?.image_style_poster?.[0],
5660
- imageThumb: item?._source?.image_style_thumb?.[0],
5661
- category: item?._source?.category?.[0],
5662
- categoryId: item?._source?.category_id?.[0],
5663
- seasons: item?._source?.seasons || [],
5664
- };
5665
- });
5666
- };
5667
- const formatSeasons = (data) => {
5668
- return data.map((item) => {
5669
- return {
5670
- uuid: item?._source?.uuid?.[0],
5671
- id: item?._source?.uuid?.[0],
5672
- created: item?._source?.created?.[0],
5673
- updated: item?._source?.updated?.[0],
5674
- title: item?._source?.display_title?.[0],
5675
- synopsis: item?._source?.synopsis?.[0],
5676
- imagePoster: item?._source?.image_style_poster?.[0],
5677
- imageThumb: item?._source?.image_style_thumb?.[0],
5678
- episodes: item?._source?.episodes || [],
5679
- seasonNumber: item?._source?.season_number?.[0],
5680
- showId: item?._source?.show?.[0],
5681
- };
5682
- });
5683
- };
5684
- const formatLongform = (data) => {
5685
- return data.map((item) => {
5686
- return {
5687
- uuid: item?._source?.uuid?.[0],
5688
- id: item?._source?.uuid?.[0],
5689
- created: item?._source?.created?.[0],
5690
- updated: item?._source?.updated?.[0],
5691
- title: item?._source?.display_title?.[0],
5692
- synopsis: item?._source?.synopsis?.[0],
5693
- imagePoster: item?._source?.image_style_poster?.[0],
5694
- imageThumb: item?._source?.image_style_thumb?.[0],
5695
- duration: item?._source?.duration?.[0],
5696
- releaseDate: item?._source?.release_date?.[0],
5697
- video: item?._source?.video?.[0],
5698
- imageUrl: item?._source?.image_url?.[0],
5699
- episodeNumber: item?._source?.episode_number?.[0],
5700
- };
5701
- });
5702
- };
5703
- const formatMediaItem = (data) => {
5704
- return data.map((item) => {
5705
- return {
5706
- changed: item?._source?.changed?.[0],
5707
- created: item?._source?.created?.[0],
5708
- image: item?._source?.image?.[0],
5709
- customThumbnail: item?._source?.custom_thumbnail?.[0],
5710
- price: item?._source?.price?.[0],
5711
- priceTwoYear: item?._source?.price_2_year?.[0],
5712
- revisionTimestamp: item?._source?.revision_timestamp?.[0],
5713
- sku: item?._source?.sku?.[0],
5714
- status: item?._source?.status?.[0],
5715
- uuid: item?._source?.uuid?.[0],
5716
- description: item?._source?.description?.[0],
5717
- transcript: item?._source?.transcript?.[0],
5718
- entities: item?._source?.entities,
5719
- phrases: item?._source?.phrases,
5720
- video: item?._source?.video?.[0],
5721
- title: item?._source?.title?.[0],
5722
- generatedTitle: item?._source?.generated_title?.[0],
5723
- projectPricing: item?._source?.project_pricing?.[0],
5724
- related_items: item?._source?.related_uuids,
5725
- franchises: item?._source?.franchise_name,
5726
- franchisesIds: item?._source?.franchise_tid,
5727
- original: item?._source?.original?.[0],
5728
- script: item?._source?.script?.[0],
5729
- hideThumbnailTitle: item?._source?.hide_thumbnail_title?.[0],
5730
- };
5731
- });
5732
- };
5733
5107
 
5734
5108
  /**
5735
5109
  * Platform detection utilities for cross-platform React/React Native applications
@@ -5971,55 +5345,146 @@ const createAuthBaseQuery = () => {
5971
5345
  const baseUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_AUTH_PREFIX
5972
5346
  ? process.env.NEXT_PUBLIC_API_AUTH_PREFIX
5973
5347
  : (API_AUTH_PREFIX || '');
5974
- console.log('[authApi] Resolved baseUrl:', baseUrl);
5975
5348
  return createUnwrappingBaseQuery({
5976
5349
  baseUrl,
5977
- prepareHeaders: async (headers) => {
5350
+ prepareHeaders: (headers, { getState }) => {
5978
5351
  headers.set('Content-Type', 'application/json');
5979
- try {
5980
- // add accessToken to headers from slice using selectAccessToken selector
5981
- const session = await Auth.currentSession();
5982
- const idToken = session.getIdToken().getJwtToken(); // ID token
5983
- const accessToken = session.getAccessToken().getJwtToken(); // Access token
5984
- if (accessToken && idToken) {
5985
- headers.set('accesstoken', accessToken);
5986
- headers.set('idtoken', idToken);
5987
- // headers.set('refreshtoken', tokens.refreshToken);
5988
- }
5989
- return headers;
5990
- }
5991
- catch (error) {
5992
- // eslint-disable-next-line no-console
5993
- console.error('authDataBaseQuery: ', error);
5994
- return headers;
5352
+ const { accessToken, idToken } = getAuthHeaders(getState);
5353
+ if (accessToken && idToken) {
5354
+ headers.set('accesstoken', accessToken);
5355
+ headers.set('idtoken', idToken);
5995
5356
  }
5357
+ return headers;
5996
5358
  },
5997
5359
  credentials: 'include',
5998
5360
  });
5999
5361
  };
6000
5362
  const authDataBaseQuery = createAuthBaseQuery();
6001
5363
  /**
6002
- * This function is used to retry a request if we get a 401 error.
5364
+ * Mutex to prevent multiple concurrent refresh attempts
5365
+ */
5366
+ let isRefreshing = false;
5367
+ let refreshPromise = null;
5368
+ /**
5369
+ * Attempt to refresh the auth token using the refresh token from Redux state.
5370
+ * Returns true if refresh succeeded and tokens were updated.
5371
+ */
5372
+ async function attemptTokenRefresh(api) {
5373
+ const state = api.getState();
5374
+ const refreshToken = state?.auth?.user?.refreshToken;
5375
+ console.debug('[TokenRefresh] Attempting refresh', {
5376
+ hasRefreshToken: !!refreshToken,
5377
+ refreshTokenPreview: refreshToken ? `${refreshToken.substring(0, 20)}...` : 'none',
5378
+ });
5379
+ if (!refreshToken) {
5380
+ console.warn('[TokenRefresh] No refresh token in Redux store — cannot refresh');
5381
+ return false;
5382
+ }
5383
+ // Use the Next.js API route for refresh (proxies to auth microservice)
5384
+ // Falls back to direct auth API if NEXT_PUBLIC_API_PREFIX is not available
5385
+ const refreshUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_PREFIX
5386
+ ? `${process.env.NEXT_PUBLIC_API_PREFIX}/auth/refresh-token`
5387
+ : `${API_AUTH_PREFIX || ''}/user/refreshtoken`;
5388
+ try {
5389
+ const response = await fetch(refreshUrl, {
5390
+ method: 'POST',
5391
+ headers: { 'Content-Type': 'application/json' },
5392
+ credentials: 'include',
5393
+ body: JSON.stringify({ refreshtoken: refreshToken }),
5394
+ });
5395
+ if (!response.ok) {
5396
+ const errorBody = await response.text().catch(() => 'unable to read body');
5397
+ console.error('[TokenRefresh] Refresh request failed', {
5398
+ status: response.status,
5399
+ body: errorBody,
5400
+ url: refreshUrl,
5401
+ });
5402
+ return false;
5403
+ }
5404
+ const data = await response.json();
5405
+ // The response may be wrapped in { success: true, data: {...} } or direct
5406
+ const tokenData = data?.data || data;
5407
+ const accessToken = tokenData?.accessToken || tokenData?.AccessToken;
5408
+ const idToken = tokenData?.idToken || tokenData?.IdToken;
5409
+ console.debug('[TokenRefresh] Refresh response parsed', {
5410
+ hasAccessToken: !!accessToken,
5411
+ hasIdToken: !!idToken,
5412
+ dataKeys: Object.keys(tokenData || {}),
5413
+ });
5414
+ if (accessToken && idToken) {
5415
+ console.debug('[TokenRefresh] SUCCESS — dispatching new credentials + syncing cookies');
5416
+ api.dispatch(setCredentials({
5417
+ accessToken,
5418
+ idToken,
5419
+ refreshToken,
5420
+ }));
5421
+ // Sync refreshed tokens to Cognito-format cookies so Next.js middleware sees valid tokens
5422
+ if (typeof window !== 'undefined') {
5423
+ try {
5424
+ const clientId = process.env?.NEXT_PUBLIC_AWS_COGNITO_CLIENT_ID || '';
5425
+ const lastAuthCookie = `CognitoIdentityServiceProvider.${clientId}.LastAuthUser`;
5426
+ const match = document.cookie.match(new RegExp(`(?:^|; )${lastAuthCookie.replace(/\./g, '\\.')}=([^;]*)`));
5427
+ const username = match ? decodeURIComponent(match[1]) : null;
5428
+ if (username && clientId) {
5429
+ const prefix = `CognitoIdentityServiceProvider.${clientId}.${username}`;
5430
+ const setCookie = (name, value) => {
5431
+ document.cookie = `${name}=${encodeURIComponent(value)}; path=/; max-age=${30 * 86400}; SameSite=Lax`;
5432
+ };
5433
+ setCookie(`${prefix}.accessToken`, accessToken);
5434
+ setCookie(`${prefix}.idToken`, idToken);
5435
+ }
5436
+ }
5437
+ catch {
5438
+ // Cookie sync is best-effort
5439
+ }
5440
+ }
5441
+ return true;
5442
+ }
5443
+ console.error('[TokenRefresh] Refresh response missing accessToken or idToken');
5444
+ return false;
5445
+ }
5446
+ catch (err) {
5447
+ console.error('[TokenRefresh] Exception during refresh', err);
5448
+ return false;
5449
+ }
5450
+ }
5451
+ /**
5452
+ * This function retries the request after refreshing the token on 401.
5453
+ * If the refresh fails, it dispatches logout.
6003
5454
  */
6004
5455
  const authDataBaseQueryWithReauth = async (args, api, extraOptions) => {
6005
5456
  let result = await authDataBaseQuery(args, api, extraOptions);
6006
- // If we get a 401 error
5457
+ if (result?.error) {
5458
+ const requestUrl = typeof args === 'string' ? args : args?.url;
5459
+ console.debug('[AuthQuery] Request error', {
5460
+ url: requestUrl,
5461
+ status: result.error.status,
5462
+ data: result.error?.data,
5463
+ });
5464
+ }
6007
5465
  if (result?.error?.status === 401) {
6008
- const authSession = await Auth.currentAuthenticatedUser({
6009
- bypassCache: true, // Ensures that the user is refreshed from the server
5466
+ const requestUrl = typeof args === 'string' ? args : args?.url;
5467
+ console.warn('[TokenRefresh] 401 received, attempting token refresh', {
5468
+ url: requestUrl,
5469
+ errorStatus: result.error.status,
5470
+ isAlreadyRefreshing: isRefreshing,
6010
5471
  });
6011
- const user = formatAuthSession(authSession);
6012
- api.dispatch(setCredentials(user));
6013
- if (authSession?.tokens) {
6014
- // If we get a new access token, retry the original request.
5472
+ // Use mutex to prevent concurrent refreshes
5473
+ if (!isRefreshing) {
5474
+ isRefreshing = true;
5475
+ refreshPromise = attemptTokenRefresh(api).finally(() => {
5476
+ isRefreshing = false;
5477
+ refreshPromise = null;
5478
+ });
5479
+ }
5480
+ const refreshed = await (refreshPromise || attemptTokenRefresh(api));
5481
+ if (refreshed) {
5482
+ console.debug('[TokenRefresh] Refresh succeeded — retrying original request');
6015
5483
  result = await authDataBaseQuery(args, api, extraOptions);
6016
5484
  }
6017
5485
  else {
6018
- // TODO; require full data reset?
6019
- await Auth.signOut();
5486
+ console.error('[TokenRefresh] Refresh FAILED dispatching logout');
6020
5487
  api.dispatch(logout());
6021
- // If no access token throw error.
6022
- throw new Error('No access token found');
6023
5488
  }
6024
5489
  }
6025
5490
  return result;
@@ -6027,8 +5492,8 @@ const authDataBaseQueryWithReauth = async (args, api, extraOptions) => {
6027
5492
  const authApi = createApi({
6028
5493
  reducerPath: 'authApi',
6029
5494
  baseQuery: authDataBaseQueryWithReauth,
6030
- tagTypes: ['UserToken', 'UserData'],
6031
- // keepUnusedDataFor: 300,
5495
+ tagTypes: ['UserToken', 'UserData', 'Streak', 'WeeklyProgress', 'WatchProgress', 'Recommendations', 'ActivityStats'],
5496
+ keepUnusedDataFor: 300,
6032
5497
  endpoints: (builder) => ({
6033
5498
  resetPassword: builder.mutation({
6034
5499
  query: (data) => ({
@@ -6166,6 +5631,80 @@ const authApi = createApi({
6166
5631
  }),
6167
5632
  invalidatesTags: ['UserData'],
6168
5633
  }),
5634
+ // Dashboard data endpoints
5635
+ getStreak: builder.query({
5636
+ query: (sub) => ({
5637
+ url: `/user/streak?sub=${sub}`,
5638
+ method: 'GET',
5639
+ }),
5640
+ providesTags: ['Streak'],
5641
+ }),
5642
+ getWeeklyProgress: builder.query({
5643
+ query: (sub) => ({
5644
+ url: `/user/weekly-progress?sub=${sub}`,
5645
+ method: 'GET',
5646
+ }),
5647
+ providesTags: ['WeeklyProgress'],
5648
+ }),
5649
+ getWatchProgress: builder.query({
5650
+ query: ({ sub, limit = 1 }) => ({
5651
+ url: `/user/watch-progress?sub=${sub}&limit=${limit}`,
5652
+ method: 'GET',
5653
+ }),
5654
+ providesTags: ['WatchProgress'],
5655
+ }),
5656
+ getRecommendations: builder.query({
5657
+ query: ({ sub, limit = 8 }) => ({
5658
+ url: `/user/recommendations?sub=${sub}&limit=${limit}`,
5659
+ method: 'GET',
5660
+ }),
5661
+ providesTags: ['Recommendations'],
5662
+ }),
5663
+ getActivityStats: builder.query({
5664
+ query: ({ sub, period = 'this-month' }) => ({
5665
+ url: `/user/activity-stats?sub=${sub}&period=${period}`,
5666
+ method: 'GET',
5667
+ }),
5668
+ providesTags: ['ActivityStats'],
5669
+ }),
5670
+ getActiveChallenges: builder.query({
5671
+ query: (sub) => ({
5672
+ url: `/user/active-challenges?sub=${sub}`,
5673
+ method: 'GET',
5674
+ }),
5675
+ providesTags: ['UserData'],
5676
+ }),
5677
+ getChallengeProgress: builder.query({
5678
+ query: ({ sub, challengeId }) => ({
5679
+ url: `/user/challenge-progress/${challengeId}?sub=${sub}`,
5680
+ method: 'GET',
5681
+ }),
5682
+ providesTags: ['UserData'],
5683
+ }),
5684
+ // Activity logging — invalidates dashboard caches
5685
+ logActivity: builder.mutation({
5686
+ query: (data) => ({
5687
+ url: '/activity',
5688
+ method: 'POST',
5689
+ body: data,
5690
+ }),
5691
+ invalidatesTags: (result, error, arg) => {
5692
+ const tags = [];
5693
+ if (arg.type === 'workout_completed') {
5694
+ tags.push('Streak', 'WeeklyProgress', 'Recommendations', 'ActivityStats', 'UserData');
5695
+ }
5696
+ if (arg.type === 'watch_progress') {
5697
+ tags.push('WatchProgress');
5698
+ }
5699
+ if (arg.type === 'workout_liked' || arg.type === 'workout_unliked') {
5700
+ tags.push('Recommendations', 'UserData');
5701
+ }
5702
+ if (arg.type === 'challenge_joined') {
5703
+ tags.push('UserData');
5704
+ }
5705
+ return tags;
5706
+ },
5707
+ }),
6169
5708
  }),
6170
5709
  });
6171
5710
  // Export hooks for usage in functional components.
@@ -6177,7 +5716,7 @@ const {
6177
5716
  // useLogoutQuery,
6178
5717
  // useLazyLogoutQuery,
6179
5718
  useResetPasswordMutation, // Use this for mobile app.
6180
- useResetPasswordAuthMutation, useRegisterMutation, useVerifyUserQuery, useLazyVerifyUserQuery, useGetUserInfoQuery, useLazyGetUserInfoQuery, useUpdateUserInfoMutation, useForgottenPasswordMutation, useVerifyUserAttributesQuery, useLazyVerifyUserAttributesQuery, useVerifyUserResendQuery, useLazyVerifyUserResendQuery, useUpdateUserMutation, } = authApi;
5719
+ useResetPasswordAuthMutation, useRegisterMutation, useVerifyUserQuery, useLazyVerifyUserQuery, useGetUserInfoQuery, useLazyGetUserInfoQuery, useUpdateUserInfoMutation, useForgottenPasswordMutation, useVerifyUserAttributesQuery, useLazyVerifyUserAttributesQuery, useVerifyUserResendQuery, useLazyVerifyUserResendQuery, useUpdateUserMutation, useGetStreakQuery, useLazyGetStreakQuery, useGetWeeklyProgressQuery, useLazyGetWeeklyProgressQuery, useGetWatchProgressQuery, useLazyGetWatchProgressQuery, useGetRecommendationsQuery, useLazyGetRecommendationsQuery, useGetActivityStatsQuery, useLazyGetActivityStatsQuery, useLogActivityMutation, useGetActiveChallengesQuery, useGetChallengeProgressQuery, } = authApi;
6181
5720
 
6182
5721
  // Create dynamic baseQuery that resolves URL at request time
6183
5722
  const createContentBaseQuery = () => {
@@ -6250,16 +5789,12 @@ const dynamicBaseQuery$1 = async (args, api, extraOptions) => {
6250
5789
  : (API_PAYMENTS_PREFIX || '');
6251
5790
  const baseQuery = createUnwrappingBaseQuery({
6252
5791
  baseUrl,
6253
- prepareHeaders: async (headers) => {
5792
+ prepareHeaders: (headers, { getState }) => {
6254
5793
  headers.set('Content-Type', 'application/json');
6255
- // add accessToken to headers from slice using selectAccessToken selector
6256
- const session = await Auth.currentSession();
6257
- const idToken = session.getIdToken().getJwtToken(); // ID token
6258
- const accessToken = session.getAccessToken().getJwtToken(); // Access token
5794
+ const { accessToken, idToken } = getAuthHeaders(getState);
6259
5795
  if (accessToken && idToken) {
6260
5796
  headers.set('accesstoken', accessToken);
6261
5797
  headers.set('idtoken', idToken);
6262
- // headers.set('refreshtoken', tokens.refreshToken);
6263
5798
  }
6264
5799
  return headers;
6265
5800
  },
@@ -6319,21 +5854,12 @@ const dynamicBaseQuery = async (args, api, extraOptions) => {
6319
5854
  : (API_PAYMENTS_PREFIX || '');
6320
5855
  const baseQuery = createUnwrappingBaseQuery({
6321
5856
  baseUrl,
6322
- prepareHeaders: async (headers) => {
5857
+ prepareHeaders: (headers, { getState }) => {
6323
5858
  headers.set('Content-Type', 'application/json');
6324
- // Try to add accessToken to headers, but don't fail if unavailable
6325
- try {
6326
- const session = await Auth.currentSession();
6327
- const idToken = session.getIdToken().getJwtToken(); // ID token
6328
- const accessToken = session.getAccessToken().getJwtToken(); // Access token
6329
- if (accessToken && idToken) {
6330
- headers.set('accesstoken', accessToken);
6331
- headers.set('idtoken', idToken);
6332
- }
6333
- }
6334
- catch (error) {
6335
- // Authentication not available - this is OK for public endpoints like getProducts
6336
- console.log('Auth not available for products API request');
5859
+ const { accessToken, idToken } = getAuthHeaders(getState);
5860
+ if (accessToken && idToken) {
5861
+ headers.set('accesstoken', accessToken);
5862
+ headers.set('idtoken', idToken);
6337
5863
  }
6338
5864
  return headers;
6339
5865
  },
@@ -6385,16 +5911,12 @@ const createOrdersBaseQuery = () => {
6385
5911
  : (API_ORDERS_PREFIX || '');
6386
5912
  return fetchBaseQuery({
6387
5913
  baseUrl,
6388
- prepareHeaders: async (headers) => {
5914
+ prepareHeaders: (headers, { getState }) => {
6389
5915
  headers.set('Content-Type', 'application/json');
6390
- // add accessToken to headers from slice using selectAccessToken selector
6391
- const session = await Auth.currentSession();
6392
- const idToken = session.getIdToken().getJwtToken(); // ID token
6393
- const accessToken = session.getAccessToken().getJwtToken(); // Access token
5916
+ const { accessToken, idToken } = getAuthHeaders(getState);
6394
5917
  if (accessToken && idToken) {
6395
5918
  headers.set('accesstoken', accessToken);
6396
5919
  headers.set('idtoken', idToken);
6397
- // headers.set('refreshtoken', tokens.refreshToken);
6398
5920
  }
6399
5921
  return headers;
6400
5922
  },
@@ -6406,25 +5928,9 @@ const dataBaseQuery = createOrdersBaseQuery();
6406
5928
  * This function is used to retry a request if we get a 401 error.
6407
5929
  */
6408
5930
  const dataBaseQueryWithReauth = async (args, api, extraOptions) => {
6409
- let result = await dataBaseQuery(args, api, extraOptions);
6410
- // If we get a 401 error
5931
+ const result = await dataBaseQuery(args, api, extraOptions);
6411
5932
  if (result?.error?.status === 401) {
6412
- const authSession = await Auth.currentAuthenticatedUser({
6413
- bypassCache: true, // Ensures that the user is refreshed from the server
6414
- });
6415
- const user = formatAuthSession(authSession);
6416
- api.dispatch(setCredentials(user));
6417
- if (authSession?.tokens) {
6418
- // If we get a new access token, retry the original request.
6419
- result = await dataBaseQuery(args, api, extraOptions);
6420
- }
6421
- else {
6422
- // TODO; require full data reset?
6423
- await Auth.signOut();
6424
- api.dispatch(logout());
6425
- // If no access token throw error.
6426
- throw new Error('No access token found');
6427
- }
5933
+ api.dispatch(logout());
6428
5934
  }
6429
5935
  return result;
6430
5936
  };
@@ -6451,7 +5957,7 @@ const ordersApi = createApi({
6451
5957
  */
6452
5958
  getOrders: builder.query({
6453
5959
  query: ({ customerId }) => ({
6454
- url: `${process.env.NEXT_PUBLIC_PAYMENTS_URL}/v1/payment/orders`,
5960
+ url: `/payment/orders`,
6455
5961
  params: { customerId },
6456
5962
  }),
6457
5963
  providesTags: ['Orders'],
@@ -6460,7 +5966,7 @@ const ordersApi = createApi({
6460
5966
  * Get a single partnership order by ID from Stripe.
6461
5967
  */
6462
5968
  getOrder: builder.query({
6463
- query: (orderId) => `${process.env.NEXT_PUBLIC_PAYMENTS_URL}/v1/payment/orders/${orderId}`,
5969
+ query: (orderId) => `/payment/orders/${orderId}`,
6464
5970
  providesTags: (_result, _error, orderId) => [{ type: 'Orders', id: orderId }],
6465
5971
  }),
6466
5972
  }),
@@ -6468,6 +5974,39 @@ const ordersApi = createApi({
6468
5974
  // Export hooks for usage in functional components.
6469
5975
  const { useFetchOrdersQuery, useLazyFetchOrdersQuery, useGetOrdersQuery, useGetOrderQuery, } = ordersApi;
6470
5976
 
5977
+ function onlyUnique(value, index, self) {
5978
+ return self.indexOf(value) === index;
5979
+ }
5980
+ function applyCoupon(coupon, netTotal) {
5981
+ const discountedAmount = netTotal * (Number(coupon.discount) / 100);
5982
+ const discountedTotal = netTotal - discountedAmount;
5983
+ const data = {
5984
+ ...coupon,
5985
+ discountedTotal,
5986
+ discountedAmount,
5987
+ };
5988
+ return data;
5989
+ }
5990
+ function applyTax(taxRate, netTotal) {
5991
+ const taxAmount = netTotal * (taxRate.percentage / 100);
5992
+ return taxAmount;
5993
+ }
5994
+ function toCamelCaseObject(obj) {
5995
+ const toCamelCase = (str) => {
5996
+ return str.replace(/([-_][a-z])/gi, (match) => {
5997
+ return match.toUpperCase().replace(/[-_]/, '');
5998
+ });
5999
+ };
6000
+ const camelCaseObject = {};
6001
+ for (const key in obj) {
6002
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
6003
+ const camelKey = toCamelCase(key);
6004
+ camelCaseObject[camelKey] = obj[key];
6005
+ }
6006
+ }
6007
+ return camelCaseObject;
6008
+ }
6009
+
6471
6010
  const initialState = {
6472
6011
  addedItems: [],
6473
6012
  netTotal: 0,
@@ -6547,10 +6086,13 @@ const cartSlice = createSlice({
6547
6086
  },
6548
6087
  addToCart: (state, action) => {
6549
6088
  const { options, item } = action.payload;
6550
- const newTotal = state.netTotal + options.selectedPrice;
6089
+ const price = Number(options?.selectedPrice) || 0;
6090
+ const currentNetTotal = Number(state.netTotal) || 0;
6091
+ const newTotal = currentNetTotal + price;
6551
6092
  const taxAmount = newTotal * (state.taxRate.percentage / 100);
6552
6093
  const grossTotal = newTotal + taxAmount;
6553
- const addItem = item ? { ...item, options } : null;
6094
+ const sanitizedOptions = { ...options, selectedPrice: price };
6095
+ const addItem = item ? { ...item, options: sanitizedOptions } : null;
6554
6096
  if (!addItem) {
6555
6097
  return state;
6556
6098
  }
@@ -6574,7 +6116,9 @@ const cartSlice = createSlice({
6574
6116
  },
6575
6117
  removeFromCart: (state, action) => {
6576
6118
  const { id, price } = action.payload;
6577
- const newTotal = state.netTotal - price;
6119
+ const sanitizedPrice = Number(price) || 0;
6120
+ const currentNetTotal = Number(state.netTotal) || 0;
6121
+ const newTotal = currentNetTotal - sanitizedPrice;
6578
6122
  const taxAmount = newTotal * (state.taxRate.percentage / 100);
6579
6123
  const grossTotal = newTotal + taxAmount;
6580
6124
  return {
@@ -6620,5 +6164,5 @@ const selectCartItemsIds = createSelector$1([selectMediaInCart], (items) => {
6620
6164
  });
6621
6165
  cartSlice.reducer;
6622
6166
 
6623
- export { formatPress as $, cartSlice as A, setTaxRate as B, resetTaxRate as C, setPromoCode as D, removePromoCode as E, addToCart as F, updateCart as G, removeFromCart as H, emptyCart as I, toggleCart as J, selectMediaInCart as K, selectCartTotal as L, selectCartNetTotal as M, selectCartTaxRate as N, selectCartTaxAmount as O, selectCartCount as P, selectCartStatus as Q, selectPromoCode as R, selectCartItems as S, selectCartItemsIds as T, formatUserPayload as U, formatPromos as V, formatWorkout as W, formatShortform as X, formatFaqs as Y, formatPages as Z, formatSettings as _, authApi as a, formatGuests as a0, formatVideos as a1, formatSections as a2, formatSchedule as a3, formatChallenges as a4, formatChallengeDays as a5, formatSecondsToISO8601Duration as a6, formatAuthSession as a7, formatFedaratedSession as a8, formatSocialAuthSession as a9, formatConfig as aa, formatSectionPanels as ab, formatSectionItems as ac, formatTaxonomies as ad, formatSeries as ae, formatSeasons as af, formatLongform as ag, formatMediaItem as ah, isWeb as ai, isReactNative as aj, getPlatform as ak, runOnPlatform as al, onlyUnique as am, applyCoupon as an, applyTax as ao, toCamelCaseObject as ap, createUnwrappingBaseQuery as aq, productsApi as b, contentApi as c, useResetPasswordAuthMutation as d, useRegisterMutation as e, useVerifyUserQuery as f, useLazyVerifyUserQuery as g, useGetUserInfoQuery as h, useLazyGetUserInfoQuery as i, useUpdateUserInfoMutation as j, useForgottenPasswordMutation as k, useVerifyUserAttributesQuery as l, useLazyVerifyUserAttributesQuery as m, useVerifyUserResendQuery as n, ordersApi as o, paymentApi as p, useLazyVerifyUserResendQuery as q, useUpdateUserMutation as r, useGetProductsQuery as s, useLazyGetProductsQuery as t, useResetPasswordMutation as u, usePurchaseProductMutation as v, useFetchOrdersQuery as w, useLazyFetchOrdersQuery as x, useGetOrdersQuery as y, useGetOrderQuery as z };
6624
- //# sourceMappingURL=slice-BD3oWPrI.js.map
6167
+ export { selectCartTaxRate as $, useGetRecommendationsQuery as A, useLazyGetRecommendationsQuery as B, useGetActivityStatsQuery as C, useLazyGetActivityStatsQuery as D, useLogActivityMutation as E, useGetActiveChallengesQuery as F, useGetChallengeProgressQuery as G, useGetProductsQuery as H, useLazyGetProductsQuery as I, usePurchaseProductMutation as J, useFetchOrdersQuery as K, useLazyFetchOrdersQuery as L, useGetOrdersQuery as M, useGetOrderQuery as N, cartSlice as O, setTaxRate as P, resetTaxRate as Q, setPromoCode as R, removePromoCode as S, addToCart as T, updateCart as U, removeFromCart as V, emptyCart as W, toggleCart as X, selectMediaInCart as Y, selectCartTotal as Z, selectCartNetTotal as _, authApi as a, selectCartTaxAmount as a0, selectCartCount as a1, selectCartStatus as a2, selectPromoCode as a3, selectCartItems as a4, selectCartItemsIds as a5, isWeb as a6, isReactNative as a7, getPlatform as a8, runOnPlatform as a9, onlyUnique as aa, applyCoupon as ab, applyTax as ac, createUnwrappingBaseQuery as ad, productsApi as b, contentApi as c, useResetPasswordAuthMutation as d, useRegisterMutation as e, useVerifyUserQuery as f, useLazyVerifyUserQuery as g, useGetUserInfoQuery as h, useLazyGetUserInfoQuery as i, useUpdateUserInfoMutation as j, useForgottenPasswordMutation as k, useVerifyUserAttributesQuery as l, useLazyVerifyUserAttributesQuery as m, useVerifyUserResendQuery as n, ordersApi as o, paymentApi as p, useLazyVerifyUserResendQuery as q, useUpdateUserMutation as r, useGetStreakQuery as s, toCamelCaseObject as t, useResetPasswordMutation as u, useLazyGetStreakQuery as v, useGetWeeklyProgressQuery as w, useLazyGetWeeklyProgressQuery as x, useGetWatchProgressQuery as y, useLazyGetWatchProgressQuery as z };
6168
+ //# sourceMappingURL=slice-B2f63n1v.js.map