musora-content-services 2.167.2 → 2.167.3

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 (131) hide show
  1. package/.agent/decisions/2026-07-20-mu2-1724-songs-lessons-counts.md +33 -0
  2. package/.agent/decisions/2026-07-20-query-builder-tostring.md +37 -0
  3. package/CHANGELOG.md +8 -0
  4. package/package.json +2 -1
  5. package/src/contentTypeConfig.js +1 -0
  6. package/src/lib/sanity/query.ts +5 -0
  7. package/src/services/config.js +15 -0
  8. package/src/services/content/artist.ts +1 -3
  9. package/src/services/content/counts.ts +47 -0
  10. package/src/services/content/genre.ts +1 -3
  11. package/src/services/content/instructor.ts +1 -3
  12. package/src/services/userActivity.js +2 -0
  13. package/src/version-info.js +1 -0
  14. package/.claude/settings.local.json +0 -53
  15. package/test/initializeTests.js +0 -60
  16. package/test/integration/awards/award-exclusion-handling.test.ts +0 -275
  17. package/test/integration/awards/internal/image-utils.test.ts +0 -86
  18. package/test/integration/content-progress/__mocks__/mocks.ts +0 -104
  19. package/test/integration/content-progress/contentProgress.test.ts +0 -335
  20. package/test/integration/content-progress/e2eOfflineProgress.test.ts +0 -352
  21. package/test/integration/content-progress/e2eProgress.test.ts +0 -612
  22. package/test/integration/content-progress/getters.test.ts +0 -334
  23. package/test/integration/content-progress/helpers.test.ts +0 -263
  24. package/test/integration/content-progress/offlineContentProgress.test.ts +0 -226
  25. package/test/integration/forums.test.ts +0 -209
  26. package/test/integration/infrastructure/FetchRequestExecutor.test.ts +0 -88
  27. package/test/integration/initializeTestDB.ts +0 -80
  28. package/test/integration/learning-paths.test.ts +0 -854
  29. package/test/integration/notifications.test.ts +0 -178
  30. package/test/integration/progress-row/content-card.test.ts +0 -283
  31. package/test/integration/sync/adapters/idb-errors.test.ts +0 -144
  32. package/test/integration/sync/adapters/sqlite-errors.test.ts +0 -173
  33. package/test/integration/sync/fetch.test.ts +0 -224
  34. package/test/integration/sync/repositories/content-likes.test.ts +0 -99
  35. package/test/integration/sync/repositories/practices.test.ts +0 -179
  36. package/test/integration/sync/repositories/progress.test.ts +0 -245
  37. package/test/integration/sync/repositories/user-award-progress.static.test.ts +0 -68
  38. package/test/integration/sync/repositories/user-award-progress.test.ts +0 -387
  39. package/test/integration/sync/store/cross-user-protection.test.ts +0 -217
  40. package/test/integration/sync/store/store-idb.test.ts +0 -180
  41. package/test/integration/sync/store/store.test.ts +0 -361
  42. package/test/integration/user/permissions.test.js +0 -20
  43. package/test/integration/userActivity.test.ts +0 -102
  44. package/test/live/README.md +0 -29
  45. package/test/live/content.test.js +0 -116
  46. package/test/localStorageMock.js +0 -21
  47. package/test/log.js +0 -5
  48. package/test/mockData/award-definitions.js +0 -171
  49. package/test/mockData/mockData_fetchByRailContentIds_one_content.json +0 -35
  50. package/test/mockData/mockData_progress_content.json +0 -182
  51. package/test/mockData/mockData_sanity_progress_content.json +0 -1451
  52. package/test/mockData/mockData_user_practices.json +0 -9
  53. package/test/setupConsole.js +0 -6
  54. package/test/setupNetworkGuard.js +0 -3
  55. package/test/setupTimers.js +0 -13
  56. package/test/unit/HttpClient.test.ts +0 -267
  57. package/test/unit/awards/award-alacarte-observer.test.ts +0 -199
  58. package/test/unit/awards/award-auto-refresh.test.ts +0 -84
  59. package/test/unit/awards/award-calculations.test.ts +0 -34
  60. package/test/unit/awards/award-callbacks.test.ts +0 -144
  61. package/test/unit/awards/award-certificate-display.test.ts +0 -330
  62. package/test/unit/awards/award-collection-edge-cases.test.ts +0 -212
  63. package/test/unit/awards/award-collection-filtering.test.ts +0 -287
  64. package/test/unit/awards/award-completion-flow.test.ts +0 -306
  65. package/test/unit/awards/award-multi-lesson.test.ts +0 -243
  66. package/test/unit/awards/award-observer-integration.test.ts +0 -327
  67. package/test/unit/awards/award-query-messages.test.ts +0 -448
  68. package/test/unit/awards/award-user-collection.test.ts +0 -416
  69. package/test/unit/awards/duplicate-prevention.test.ts +0 -120
  70. package/test/unit/awards/helpers/completion-mock.ts +0 -56
  71. package/test/unit/awards/helpers/index.ts +0 -3
  72. package/test/unit/awards/helpers/mock-setup.ts +0 -79
  73. package/test/unit/awards/helpers/progress-emitter.ts +0 -45
  74. package/test/unit/awards/message-generator.test.ts +0 -162
  75. package/test/unit/content-progress/bubbleTrickle.test.ts +0 -322
  76. package/test/unit/content-progress/helpers.test.ts +0 -329
  77. package/test/unit/content-progress/navigateTo.test.ts +0 -392
  78. package/test/unit/contentLikes.test.ts +0 -62
  79. package/test/unit/contentMetaData.test.ts +0 -58
  80. package/test/unit/dataContext.test.ts +0 -38
  81. package/test/unit/dateUtils.test.ts +0 -188
  82. package/test/unit/endScreen.test.js +0 -712
  83. package/test/unit/eventsAPI.test.ts +0 -159
  84. package/test/unit/imageSRCBuilder.test.ts +0 -37
  85. package/test/unit/imageSRCVerify.test.ts +0 -155
  86. package/test/unit/infrastructure/DefaultHeaderProvider.test.ts +0 -39
  87. package/test/unit/infrastructure/sanity/ContentClient.test.ts +0 -168
  88. package/test/unit/infrastructure/sanity/DefaultConfigProvider.test.ts +0 -93
  89. package/test/unit/infrastructure/sanity/FetchQueryExecutor.test.ts +0 -174
  90. package/test/unit/infrastructure/sanity/SanityClient.test.ts +0 -140
  91. package/test/unit/lib/__snapshots__/filter.test.ts.snap +0 -5
  92. package/test/unit/lib/filter.test.ts +0 -1154
  93. package/test/unit/lib/lastUpdated.test.ts +0 -21
  94. package/test/unit/lib/query.test.ts +0 -1469
  95. package/test/unit/lib/sanity/decorators/base.test.ts +0 -368
  96. package/test/unit/lib/sanity/decorators/navigate-to.test.ts +0 -361
  97. package/test/unit/lib/sanity/decorators/need-access.test.ts +0 -89
  98. package/test/unit/lib/sanity/decorators/need-lifetime-upgrade.test.ts +0 -85
  99. package/test/unit/lib/sanity/decorators/page-type.test.ts +0 -81
  100. package/test/unit/playerSettings.test.ts +0 -73
  101. package/test/unit/progress-row/content-card.test.ts +0 -314
  102. package/test/unit/progress-row/playlist-card.test.ts +0 -104
  103. package/test/unit/progressRows.test.ts +0 -243
  104. package/test/unit/recommendations.test.js +0 -47
  105. package/test/unit/sanityQueryService.test.ts +0 -200
  106. package/test/unit/search.test.ts +0 -44
  107. package/test/unit/sentry.test.ts +0 -62
  108. package/test/unit/services/progress-internal/bubble.test.ts +0 -279
  109. package/test/unit/services/progress.test.ts +0 -396
  110. package/test/unit/streakMessage.test.ts +0 -251
  111. package/test/unit/sync/context.test.ts +0 -51
  112. package/test/unit/sync/effects/logout-warning.test.ts +0 -158
  113. package/test/unit/sync/effects/push-failure-notification.test.ts +0 -196
  114. package/test/unit/sync/errors/sync-errors.test.ts +0 -106
  115. package/test/unit/sync/errors/validators.test.ts +0 -61
  116. package/test/unit/sync/helpers/TestModel.ts +0 -44
  117. package/test/unit/sync/helpers/index.ts +0 -172
  118. package/test/unit/sync/manager.test.ts +0 -303
  119. package/test/unit/sync/models/user-award-progress.test.ts +0 -82
  120. package/test/unit/sync/resolver.test.ts +0 -229
  121. package/test/unit/sync/retry.test.ts +0 -314
  122. package/test/unit/sync/run-scope.test.ts +0 -23
  123. package/test/unit/sync/stale-record-cleanup.test.ts +0 -107
  124. package/test/unit/sync/store/push-coalescer.test.ts +0 -156
  125. package/test/unit/sync/store-configs.test.ts +0 -37
  126. package/test/unit/sync/telemetry/sync-telemetry.test.ts +0 -118
  127. package/test/unit/sync/utils/event-emitter.test.ts +0 -64
  128. package/test/unit/sync/utils/throttle.test.ts +0 -245
  129. package/test/unit/url-builder.test.ts +0 -72
  130. package/test/unit/user/account.test.ts +0 -66
  131. package/test/unit/user/permissions.test.js +0 -191
@@ -1,226 +0,0 @@
1
- import { initializeTestDB } from '../initializeTestDB'
2
- import {
3
- contentStatusCompletedManyOffline,
4
- contentStatusCompletedOffline,
5
- contentStatusResetOffline,
6
- contentStatusStartedOffline,
7
- duplicateProgressToALaCarteOffline,
8
- recordWatchSessionOffline,
9
- } from '../../../src/services/offline/progress'
10
- import { getProgressState } from '../../../src/services/contentProgress.js'
11
- import { COLLECTION_ID_SELF, COLLECTION_TYPE } from '../../../src/services/sync/models/ContentProgress'
12
- import db from '../../../src/services/sync/repository-proxy'
13
-
14
- jest.mock('../../../src/services/sanity.js', () => require('./__mocks__/mocks').mockSanity())
15
- jest.mock('../../../src/services/content-org/learning-paths.ts', () => require('./__mocks__/mocks').mockLearningPaths())
16
- jest.mock('../../../src/services/awards/internal/content-progress-observer', () => require('./__mocks__/mocks').mockContentProgressObserver())
17
- jest.mock('../../../src/services/progress-events', () => require('./__mocks__/mocks').mockProgressEvents())
18
-
19
- jest.mock('../../../src/services/userActivity', () => ({
20
- trackUserPractice: jest.fn().mockResolvedValue(undefined),
21
- }))
22
-
23
- const meta = { brand: 'drumeo', type: 'lesson', parent_id: 0 }
24
- const collectionSelf = { type: COLLECTION_TYPE.SELF, id: COLLECTION_ID_SELF }
25
- const collectionLP = (id: number) => ({ type: COLLECTION_TYPE.LEARNING_PATH, id })
26
-
27
- const flushPromises = async () => {
28
- for (let i = 0; i < 200; i++) {
29
- await new Promise(resolve => setImmediate(resolve))
30
- }
31
- }
32
-
33
- const hierarchyFor = (contentId: number) => ({
34
- topLevelId: contentId,
35
- parents: {},
36
- children: {},
37
- metadata: { [contentId]: meta },
38
- })
39
-
40
- const ctx = initializeTestDB()
41
-
42
- // ─── contentStatusCompletedOffline ────────────────────────────────────────────
43
-
44
- describe('contentStatusCompletedOffline', () => {
45
- test('sets state to completed in DB', async () => {
46
- await contentStatusCompletedOffline(500, null, hierarchyFor(500))
47
- expect(await getProgressState(500)).toBe('completed')
48
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('save-content-progress')
49
- })
50
-
51
- test('sets progress_percent to 100 in DB', async () => {
52
- await contentStatusCompletedOffline(500, null, hierarchyFor(500))
53
- const record = await db.contentProgress.getOneProgressByContentId(500, null)
54
- expect(record.data?.progress_percent).toBe(100)
55
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('save-content-progress')
56
- })
57
-
58
- test('defaults to SELF collection when null is passed', async () => {
59
- await contentStatusCompletedOffline(500, null, hierarchyFor(500))
60
- const record = await db.contentProgress.getOneProgressByContentId(500, null)
61
- expect(record.data?.collection_type).toBe(COLLECTION_TYPE.SELF)
62
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('save-content-progress')
63
- })
64
- })
65
-
66
- // ─── contentStatusCompletedManyOffline ────────────────────────────────────────
67
-
68
- describe('contentStatusCompletedManyOffline', () => {
69
- test('sets all ids to completed state in DB', async () => {
70
- const hierarchy = {
71
- topLevelId: 501,
72
- parents: {},
73
- children: {},
74
- metadata: { 501: meta, 502: meta, 503: meta },
75
- }
76
- await contentStatusCompletedManyOffline([501, 502, 503], null, hierarchy)
77
- expect(await getProgressState(501)).toBe('completed')
78
- expect(await getProgressState(502)).toBe('completed')
79
- expect(await getProgressState(503)).toBe('completed')
80
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('save-content-progress')
81
- })
82
-
83
- test('each record has progress_percent of 100', async () => {
84
- const hierarchy = {
85
- topLevelId: 501,
86
- parents: {},
87
- children: {},
88
- metadata: { 501: meta, 502: meta },
89
- }
90
- await contentStatusCompletedManyOffline([501, 502], null, hierarchy)
91
- const r1 = await db.contentProgress.getOneProgressByContentId(501, null)
92
- const r2 = await db.contentProgress.getOneProgressByContentId(502, null)
93
- expect(r1.data?.progress_percent).toBe(100)
94
- expect(r2.data?.progress_percent).toBe(100)
95
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('save-content-progress')
96
- })
97
- })
98
-
99
- // ─── contentStatusStartedOffline ──────────────────────────────────────────────
100
-
101
- describe('contentStatusStartedOffline', () => {
102
- test('sets state to started in DB', async () => {
103
- await contentStatusStartedOffline(600, null, hierarchyFor(600))
104
- expect(await getProgressState(600)).toBe('started')
105
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('save-content-progress')
106
- })
107
-
108
- test('sets progress_percent to 0 in DB', async () => {
109
- await contentStatusStartedOffline(600, null, hierarchyFor(600))
110
- const record = await db.contentProgress.getOneProgressByContentId(600, null)
111
- expect(record.data?.progress_percent).toBe(0)
112
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('save-content-progress')
113
- })
114
- })
115
-
116
- // ─── contentStatusResetOffline ────────────────────────────────────────────────
117
-
118
- describe('contentStatusResetOffline', () => {
119
- test('removes record from DB so getProgressState returns empty string', async () => {
120
- await contentStatusCompletedOffline(700, null, hierarchyFor(700))
121
- expect(await getProgressState(700)).toBe('completed')
122
- await contentStatusResetOffline(700)
123
- expect(await getProgressState(700)).toBe('')
124
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('save-content-progress')
125
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('reset-status')
126
- })
127
-
128
- test('defaults to SELF collection when called without collection', async () => {
129
- await db.contentProgress.recordProgress(701, null, 80, meta, undefined, { skipPush: true })
130
- await contentStatusResetOffline(701)
131
- expect(await getProgressState(701)).toBe('')
132
- expect(ctx.pushSpies.contentProgress).toHaveBeenCalledWith('reset-status')
133
- })
134
- })
135
-
136
- // ─── recordWatchSessionOffline ────────────────────────────────────────────────
137
-
138
- describe('recordWatchSessionOffline', () => {
139
- const mockUserActivity = jest.requireMock('../../../src/services/userActivity')
140
-
141
- beforeEach(() => {
142
- jest.clearAllMocks()
143
- })
144
-
145
- test('writes progress to DB and calls trackUserPractice', async () => {
146
- await recordWatchSessionOffline(234, 200, 100, 30, hierarchyFor(234))
147
- const record = await db.contentProgress.getOneProgressByContentId(234, null)
148
- expect(record.data?.progress_percent).toBe(50)
149
- expect(mockUserActivity.trackUserPractice).toHaveBeenCalledWith(234, 30, expect.any(Object))
150
- expect(ctx.pushSpies.contentProgress).not.toHaveBeenCalled()
151
- })
152
-
153
- test('normalizes string contentId to number in DB', async () => {
154
- await recordWatchSessionOffline('234' as any, 200, 100, 30, hierarchyFor(234))
155
- const record = await db.contentProgress.getOneProgressByContentId(234, null)
156
- expect(record.data?.content_id).toBe(234)
157
- expect(ctx.pushSpies.contentProgress).not.toHaveBeenCalled()
158
- })
159
-
160
- test('full duration (200/200) clamps to 99 — never reaches 100 via watch', async () => {
161
- await recordWatchSessionOffline(234, 200, 200, 60, hierarchyFor(234))
162
- const record = await db.contentProgress.getOneProgressByContentId(234, null)
163
- expect(record.data?.progress_percent).toBe(99)
164
- expect(ctx.pushSpies.contentProgress).not.toHaveBeenCalled()
165
- })
166
-
167
- test('passes instrumentId and categoryId through to trackUserPractice', async () => {
168
- await recordWatchSessionOffline(234, 200, 100, 30, hierarchyFor(234), {
169
- instrumentId: 7,
170
- categoryId: 9,
171
- })
172
- expect(mockUserActivity.trackUserPractice).toHaveBeenCalledWith(
173
- 234,
174
- 30,
175
- expect.objectContaining({ instrumentId: 7, categoryId: 9 }),
176
- )
177
- })
178
- })
179
-
180
- // ─── duplicateProgressToALaCarteOffline ───────────────────────────────────────
181
-
182
- describe('duplicateProgressToALaCarteOffline', () => {
183
- test('writes SELF records for a-la-carte collection', async () => {
184
- await duplicateProgressToALaCarteOffline({ 101: 50 }, { 101: meta }, collectionSelf)
185
- await flushPromises()
186
- const record = await db.contentProgress.getOneProgressByContentId(101, null)
187
- expect(record.data?.collection_type).toBe(COLLECTION_TYPE.SELF)
188
- expect(ctx.pushSpies.contentProgress).not.toHaveBeenCalled()
189
- })
190
-
191
- test('LP collection excludes the LP id itself from duplication', async () => {
192
- await duplicateProgressToALaCarteOffline({ 200: 50, 101: 75 }, { 200: meta, 101: meta }, collectionLP(200))
193
- await flushPromises()
194
- const lpRecord = await db.contentProgress.getOneProgressByContentId(200, null)
195
- const lessonRecord = await db.contentProgress.getOneProgressByContentId(101, null)
196
- expect(lpRecord.data).toBeNull()
197
- expect(lessonRecord.data?.progress_percent).toBe(75)
198
- expect(ctx.pushSpies.contentProgress).not.toHaveBeenCalled()
199
- })
200
-
201
- test('lower progress than existing is filtered — existing stays unchanged', async () => {
202
- await db.contentProgress.recordProgress(101, null, 80, meta, undefined, { skipPush: true })
203
- await duplicateProgressToALaCarteOffline({ 101: 50 }, { 101: meta }, collectionSelf)
204
- await flushPromises()
205
- const record = await db.contentProgress.getOneProgressByContentId(101, null)
206
- expect(record.data?.progress_percent).toBe(80)
207
- expect(ctx.pushSpies.contentProgress).not.toHaveBeenCalled()
208
- })
209
-
210
- test('equal progress passes and record is updated', async () => {
211
- await db.contentProgress.recordProgress(101, null, 50, meta, undefined, { skipPush: true })
212
- await duplicateProgressToALaCarteOffline({ 101: 50 }, { 101: meta }, collectionSelf)
213
- await flushPromises()
214
- const record = await db.contentProgress.getOneProgressByContentId(101, null)
215
- expect(record.data?.progress_percent).toBe(50)
216
- expect(ctx.pushSpies.contentProgress).not.toHaveBeenCalled()
217
- })
218
-
219
- test('empty progresses results in no new records', async () => {
220
- await duplicateProgressToALaCarteOffline({}, {}, collectionSelf)
221
- await flushPromises()
222
- const record = await db.contentProgress.getOneProgressByContentId(101, null)
223
- expect(record.data).toBeNull()
224
- expect(ctx.pushSpies.contentProgress).not.toHaveBeenCalled()
225
- })
226
- })
@@ -1,209 +0,0 @@
1
- import { getActiveDiscussions } from '@/services/forums/forums'
2
-
3
- const mockGet = jest.fn()
4
-
5
- jest.mock('@/infrastructure/http/HttpClient', () => ({
6
- HttpClient: jest.fn().mockImplementation(() => ({
7
- get: mockGet,
8
- })),
9
- }))
10
-
11
- function makeThread(overrides = {}) {
12
- return {
13
- id: 1,
14
- slug: 'test-thread',
15
- title: 'Test Thread',
16
- locked: false,
17
- pinned: false,
18
- state: 'open',
19
- category_id: 10,
20
- post_count: 1,
21
- is_read: false,
22
- author: {
23
- id: 100,
24
- display_name: 'Jane Doe',
25
- profile_picture_url: 'https://example.com/avatar.jpg',
26
- access_level: 'member',
27
- signature: null,
28
- },
29
- last_post: {
30
- id: 200,
31
- content: 'Hello world',
32
- created_at: '2024-01-01T00:00:00Z',
33
- created_at_human: '1 day ago',
34
- author: null,
35
- like_count: 0,
36
- is_liked: false,
37
- },
38
- ...overrides,
39
- }
40
- }
41
-
42
- function makePaginatedResponse(threads = [makeThread()]) {
43
- return {
44
- data: threads,
45
- meta: {
46
- current_page: 1,
47
- per_page: 10,
48
- total: threads.length,
49
- last_page: 1,
50
- },
51
- }
52
- }
53
-
54
- describe('getActiveDiscussions', () => {
55
- test('returns transformed data and meta', async () => {
56
- mockGet.mockResolvedValue(makePaginatedResponse())
57
-
58
- const result = await getActiveDiscussions('drumeo')
59
-
60
- expect(result.data).toHaveLength(1)
61
- expect(result.meta).toBeDefined()
62
- expect(result.meta.current_page).toBe(1)
63
- })
64
-
65
- test('maps thread fields correctly', async () => {
66
- mockGet.mockResolvedValue(makePaginatedResponse())
67
-
68
- const result = await getActiveDiscussions('drumeo')
69
- const thread = result.data[0]
70
-
71
- expect(thread.id).toBe(1)
72
- expect(thread.url).toBe('forums/threads/10/1')
73
- expect(thread.title).toBe('Test Thread')
74
- expect(thread.post).toBe('Hello world')
75
- expect(thread.author.id).toBe(100)
76
- expect(thread.author.name).toBe('Jane Doe')
77
- expect(thread.author.avatar).toBe('https://example.com/avatar.jpg')
78
- })
79
-
80
- test('maps author avatar to empty string when profile_picture_url is null', async () => {
81
- const thread = makeThread({
82
- author: { id: 1, display_name: 'No Avatar', profile_picture_url: null, access_level: 'member', signature: null },
83
- })
84
- mockGet.mockResolvedValue(makePaginatedResponse([thread]))
85
-
86
- const result = await getActiveDiscussions('drumeo')
87
-
88
- expect(result.data[0].author.avatar).toBe('')
89
- })
90
-
91
- test('filters out threads with null last_post', async () => {
92
- const threads = [makeThread({ last_post: null }), makeThread({ id: 2 })]
93
- mockGet.mockResolvedValue(makePaginatedResponse(threads))
94
-
95
- const result = await getActiveDiscussions('drumeo')
96
-
97
- expect(result.data).toHaveLength(1)
98
- expect(result.data[0].id).toBe(2)
99
- })
100
-
101
- test('filters out threads with null author', async () => {
102
- const threads = [makeThread({ author: null }), makeThread({ id: 2 })]
103
- mockGet.mockResolvedValue(makePaginatedResponse(threads))
104
-
105
- const result = await getActiveDiscussions('drumeo')
106
-
107
- expect(result.data).toHaveLength(1)
108
- expect(result.data[0].id).toBe(2)
109
- })
110
-
111
- test('passes brand, page and limit to the HTTP call', async () => {
112
- mockGet.mockResolvedValue(makePaginatedResponse())
113
-
114
- await getActiveDiscussions('pianote', { page: 3, limit: 25 })
115
-
116
- expect(mockGet).toHaveBeenCalledWith(
117
- '/api/forums/v1/threads/latest?brand=pianote&page=3&limit=25'
118
- )
119
- })
120
-
121
- test('defaults page to 1 and limit to 10', async () => {
122
- mockGet.mockResolvedValue(makePaginatedResponse())
123
-
124
- await getActiveDiscussions('drumeo')
125
-
126
- expect(mockGet).toHaveBeenCalledWith(
127
- '/api/forums/v1/threads/latest?brand=drumeo&page=1&limit=10'
128
- )
129
- })
130
-
131
- describe('stripHtml', () => {
132
- test('removes blockquote and its content', async () => {
133
- const thread = makeThread({
134
- last_post: { id: 1, content: 'Before<blockquote>quoted text</blockquote>After', created_at: '', created_at_human: '', author: null, like_count: 0, is_liked: false },
135
- })
136
- mockGet.mockResolvedValue(makePaginatedResponse([thread]))
137
-
138
- const result = await getActiveDiscussions('drumeo')
139
-
140
- expect(result.data[0].post).toBe('BeforeAfter')
141
- })
142
-
143
- test('removes iframes and their content', async () => {
144
- const thread = makeThread({
145
- last_post: { id: 1, content: 'Before<iframe src="x">content</iframe>After', created_at: '', created_at_human: '', author: null, like_count: 0, is_liked: false },
146
- })
147
- mockGet.mockResolvedValue(makePaginatedResponse([thread]))
148
-
149
- const result = await getActiveDiscussions('drumeo')
150
-
151
- expect(result.data[0].post).toBe('BeforeAfter')
152
- })
153
-
154
- test('converts <br> to space to prevent word concatenation', async () => {
155
- const thread = makeThread({
156
- last_post: { id: 1, content: 'word1<br>word2<br/>word3', created_at: '', created_at_human: '', author: null, like_count: 0, is_liked: false },
157
- })
158
- mockGet.mockResolvedValue(makePaginatedResponse([thread]))
159
-
160
- const result = await getActiveDiscussions('drumeo')
161
-
162
- expect(result.data[0].post).toBe('word1 word2 word3')
163
- })
164
-
165
- test('converts closing block-level tags to spaces', async () => {
166
- const thread = makeThread({
167
- last_post: { id: 1, content: '<p>word1</p><div>word2</div>', created_at: '', created_at_human: '', author: null, like_count: 0, is_liked: false },
168
- })
169
- mockGet.mockResolvedValue(makePaginatedResponse([thread]))
170
-
171
- const result = await getActiveDiscussions('drumeo')
172
-
173
- expect(result.data[0].post).toBe('word1 word2')
174
- })
175
-
176
- test('decodes HTML entities', async () => {
177
- const thread = makeThread({
178
- last_post: { id: 1, content: 'a &amp; b &lt;c&gt; &quot;d&quot; &#39;e&#39; f&nbsp;g', created_at: '', created_at_human: '', author: null, like_count: 0, is_liked: false },
179
- })
180
- mockGet.mockResolvedValue(makePaginatedResponse([thread]))
181
-
182
- const result = await getActiveDiscussions('drumeo')
183
-
184
- expect(result.data[0].post).toBe("a & b <c> \"d\" 'e' f g")
185
- })
186
-
187
- test('removes remaining HTML tags', async () => {
188
- const thread = makeThread({
189
- last_post: { id: 1, content: '<strong>bold</strong> and <em>italic</em>', created_at: '', created_at_human: '', author: null, like_count: 0, is_liked: false },
190
- })
191
- mockGet.mockResolvedValue(makePaginatedResponse([thread]))
192
-
193
- const result = await getActiveDiscussions('drumeo')
194
-
195
- expect(result.data[0].post).toBe('bold and italic')
196
- })
197
-
198
- test('replaces img tags with spaces', async () => {
199
- const thread = makeThread({
200
- last_post: { id: 1, content: 'word1<img src="x.jpg">word2', created_at: '', created_at_human: '', author: null, like_count: 0, is_liked: false },
201
- })
202
- mockGet.mockResolvedValue(makePaginatedResponse([thread]))
203
-
204
- const result = await getActiveDiscussions('drumeo')
205
-
206
- expect(result.data[0].post).toBe('word1 word2')
207
- })
208
- })
209
- })
@@ -1,88 +0,0 @@
1
- import { FetchRequestExecutor } from '../../../src/infrastructure/http'
2
- describe('FetchRequestExecutor', () => {
3
- let executor: FetchRequestExecutor
4
- beforeEach(() => {
5
- executor = new FetchRequestExecutor()
6
- })
7
- afterEach(() => {
8
- jest.restoreAllMocks()
9
- })
10
- describe('successful responses', () => {
11
- test('returns parsed JSON when content-type is application/json', async () => {
12
- const mockData = { id: 1, name: 'test' }
13
- global.fetch = jest.fn().mockResolvedValue({
14
- ok: true,
15
- headers: { get: jest.fn().mockReturnValue('application/json') },
16
- json: jest.fn().mockResolvedValue(mockData),
17
- text: jest.fn(),
18
- })
19
- const result = await executor.execute('https://api.example.com/test', { method: 'GET', headers: {} })
20
- expect(result).toEqual(mockData)
21
- })
22
- test('returns text when content-type is not application/json', async () => {
23
- global.fetch = jest.fn().mockResolvedValue({
24
- ok: true,
25
- headers: { get: jest.fn().mockReturnValue('text/plain') },
26
- json: jest.fn(),
27
- text: jest.fn().mockResolvedValue('plain text response'),
28
- })
29
- const result = await executor.execute('https://api.example.com/test', { method: 'GET', headers: {} })
30
- expect(result).toBe('plain text response')
31
- })
32
- })
33
- describe('error responses', () => {
34
- test('throws HttpError with correct shape when response is not ok', async () => {
35
- global.fetch = jest.fn().mockResolvedValue({
36
- ok: false,
37
- status: 404,
38
- statusText: 'Not Found',
39
- headers: { get: jest.fn().mockReturnValue('application/json') },
40
- json: jest.fn().mockResolvedValue({ message: 'not found' }),
41
- text: jest.fn(),
42
- })
43
- await expect(
44
- executor.execute('https://api.example.com/test', { method: 'GET', headers: {} })
45
- ).rejects.toMatchObject({
46
- status: 404,
47
- statusText: 'Not Found',
48
- url: 'https://api.example.com/test',
49
- method: 'GET',
50
- body: { message: 'not found' },
51
- })
52
- })
53
- test('error body is parsed as JSON when response body is valid JSON', async () => {
54
- const errorBody = { message: 'validation failed', code: 422 }
55
- global.fetch = jest.fn().mockResolvedValue({
56
- ok: false,
57
- status: 422,
58
- statusText: 'Unprocessable Entity',
59
- headers: { get: jest.fn() },
60
- json: jest.fn().mockResolvedValue(errorBody),
61
- text: jest.fn(),
62
- })
63
- await expect(
64
- executor.execute('https://api.example.com/test', { method: 'POST', headers: {} })
65
- ).rejects.toMatchObject({
66
- body: errorBody,
67
- })
68
- })
69
- test('error body falls back to text when response body is not JSON', async () => {
70
- global.fetch = jest.fn().mockResolvedValue({
71
- ok: false,
72
- status: 500,
73
- statusText: 'Internal Server Error',
74
- headers: { get: jest.fn() },
75
- json: jest.fn().mockRejectedValue(new Error('invalid json')),
76
- text: jest.fn().mockResolvedValue('Internal Server Error'),
77
- })
78
- await expect(
79
- executor.execute('https://api.example.com/test', { method: 'GET', headers: {} })
80
- ).rejects.toMatchObject({
81
- body: 'Internal Server Error',
82
- })
83
- })
84
- })
85
- })
86
-
87
-
88
-
@@ -1,80 +0,0 @@
1
- import { initializeTestService } from '../initializeTests.js'
2
- import SyncManager from '@/services/sync/manager'
3
- import { SyncTelemetry } from '@/services/sync/telemetry'
4
- import { makeContext, makeDatabase, makeTelemetry, makeUserScope } from '../unit/sync/helpers'
5
- import db from '@/services/sync/repository-proxy'
6
-
7
- export interface PushSpies {
8
- contentProgress: jest.SpyInstance
9
- practices: jest.SpyInstance
10
- likes: jest.SpyInstance
11
- userAwardProgress: jest.SpyInstance
12
- practiceDayNotes: jest.SpyInstance
13
- }
14
-
15
- export interface TestDBContext {
16
- pushSpies: PushSpies
17
- }
18
-
19
- export const waitForPushCall = async (
20
- spy: jest.SpyInstance,
21
- cause: string,
22
- timeoutMs = 2000,
23
- ): Promise<void> => {
24
- const start = Date.now()
25
- while (Date.now() - start < timeoutMs) {
26
- if (spy.mock.calls.some(c => c[0] === cause)) return
27
- await new Promise(resolve => setImmediate(resolve))
28
- }
29
- }
30
-
31
- export function initializeMockPushes(): PushSpies {
32
- return {
33
- contentProgress: jest.spyOn(db.contentProgress, 'requestPushUnsynced').mockImplementation(() => {
34
- }),
35
- practices: jest.spyOn(db.practices, 'requestPushUnsynced').mockImplementation(() => {
36
- }),
37
- likes: jest.spyOn(db.likes, 'requestPushUnsynced').mockImplementation(() => {
38
- }),
39
- userAwardProgress: jest.spyOn(db.userAwardProgress, 'requestPushUnsynced').mockImplementation(() => {
40
- }),
41
- practiceDayNotes: jest.spyOn(db.practiceDayNotes, 'requestPushUnsynced').mockImplementation(() => {
42
- }),
43
- }
44
- }
45
-
46
- export function initializeTestDB(): TestDBContext {
47
- const ctx: TestDBContext = { pushSpies: {} as PushSpies }
48
-
49
- beforeAll(() => {
50
- global.fetch = jest.fn().mockResolvedValue({
51
- ok: true,
52
- headers: { get: (key: string) => key === 'X-Sync-Intended-User-Id' ? '1' : null },
53
- json: () => Promise.resolve({
54
- meta: { since: null, max_updated_at: Date.now(), timestamp: Date.now() },
55
- entries: [],
56
- }),
57
- } as any)
58
- })
59
-
60
- let teardown: ((mode?: any) => Promise<void>) | null = null
61
-
62
- beforeEach(() => {
63
- initializeTestService()
64
- const userScope = makeUserScope()
65
- SyncTelemetry.setInstance(makeTelemetry(userScope))
66
- const manager = new SyncManager(userScope, makeContext(), () => makeDatabase())
67
- teardown = SyncManager.assignAndSetupInstance(manager)
68
- ctx.pushSpies = initializeMockPushes()
69
- })
70
-
71
- afterEach(async () => {
72
- for (let i = 0; i < 200; i++) await new Promise(resolve => setImmediate(resolve))
73
- await teardown?.('reset')
74
- teardown = null
75
- SyncTelemetry.clearInstance()
76
- ;(SyncManager as any).instance = null
77
- })
78
-
79
- return ctx
80
- }