@memberjunction/actions-bizapps-lms 5.3.1 → 5.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 (194) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +16 -0
  3. package/LEARNWORLDS_SIDECAR_PLAN.md +845 -0
  4. package/dist/base/base-lms.action.d.ts +26 -4
  5. package/dist/base/base-lms.action.d.ts.map +1 -1
  6. package/dist/base/base-lms.action.js +73 -17
  7. package/dist/base/base-lms.action.js.map +1 -1
  8. package/dist/providers/learnworlds/actions/attach-tags.action.d.ts +26 -0
  9. package/dist/providers/learnworlds/actions/attach-tags.action.d.ts.map +1 -0
  10. package/dist/providers/learnworlds/actions/attach-tags.action.js +79 -0
  11. package/dist/providers/learnworlds/actions/attach-tags.action.js.map +1 -0
  12. package/dist/providers/learnworlds/actions/create-user.action.d.ts +24 -1
  13. package/dist/providers/learnworlds/actions/create-user.action.d.ts.map +1 -1
  14. package/dist/providers/learnworlds/actions/create-user.action.js +166 -142
  15. package/dist/providers/learnworlds/actions/create-user.action.js.map +1 -1
  16. package/dist/providers/learnworlds/actions/detach-tags.action.d.ts +26 -0
  17. package/dist/providers/learnworlds/actions/detach-tags.action.d.ts.map +1 -0
  18. package/dist/providers/learnworlds/actions/detach-tags.action.js +79 -0
  19. package/dist/providers/learnworlds/actions/detach-tags.action.js.map +1 -0
  20. package/dist/providers/learnworlds/actions/enroll-user.action.d.ts +31 -3
  21. package/dist/providers/learnworlds/actions/enroll-user.action.d.ts.map +1 -1
  22. package/dist/providers/learnworlds/actions/enroll-user.action.js +179 -125
  23. package/dist/providers/learnworlds/actions/enroll-user.action.js.map +1 -1
  24. package/dist/providers/learnworlds/actions/get-bulk-data.action.d.ts +79 -0
  25. package/dist/providers/learnworlds/actions/get-bulk-data.action.d.ts.map +1 -0
  26. package/dist/providers/learnworlds/actions/get-bulk-data.action.js +359 -0
  27. package/dist/providers/learnworlds/actions/get-bulk-data.action.js.map +1 -0
  28. package/dist/providers/learnworlds/actions/get-bundles.action.d.ts +34 -0
  29. package/dist/providers/learnworlds/actions/get-bundles.action.d.ts.map +1 -0
  30. package/dist/providers/learnworlds/actions/get-bundles.action.js +107 -0
  31. package/dist/providers/learnworlds/actions/get-bundles.action.js.map +1 -0
  32. package/dist/providers/learnworlds/actions/get-certificates.action.d.ts +33 -2
  33. package/dist/providers/learnworlds/actions/get-certificates.action.d.ts.map +1 -1
  34. package/dist/providers/learnworlds/actions/get-certificates.action.js +311 -244
  35. package/dist/providers/learnworlds/actions/get-certificates.action.js.map +1 -1
  36. package/dist/providers/learnworlds/actions/get-course-analytics.action.d.ts +14 -14
  37. package/dist/providers/learnworlds/actions/get-course-analytics.action.d.ts.map +1 -1
  38. package/dist/providers/learnworlds/actions/get-course-analytics.action.js +234 -226
  39. package/dist/providers/learnworlds/actions/get-course-analytics.action.js.map +1 -1
  40. package/dist/providers/learnworlds/actions/get-course-details.action.d.ts +42 -6
  41. package/dist/providers/learnworlds/actions/get-course-details.action.d.ts.map +1 -1
  42. package/dist/providers/learnworlds/actions/get-course-details.action.js +182 -148
  43. package/dist/providers/learnworlds/actions/get-course-details.action.js.map +1 -1
  44. package/dist/providers/learnworlds/actions/get-courses.action.d.ts +29 -82
  45. package/dist/providers/learnworlds/actions/get-courses.action.d.ts.map +1 -1
  46. package/dist/providers/learnworlds/actions/get-courses.action.js +188 -207
  47. package/dist/providers/learnworlds/actions/get-courses.action.js.map +1 -1
  48. package/dist/providers/learnworlds/actions/get-quiz-results.action.d.ts +22 -2
  49. package/dist/providers/learnworlds/actions/get-quiz-results.action.d.ts.map +1 -1
  50. package/dist/providers/learnworlds/actions/get-quiz-results.action.js +316 -294
  51. package/dist/providers/learnworlds/actions/get-quiz-results.action.js.map +1 -1
  52. package/dist/providers/learnworlds/actions/get-user-details.action.d.ts +23 -59
  53. package/dist/providers/learnworlds/actions/get-user-details.action.d.ts.map +1 -1
  54. package/dist/providers/learnworlds/actions/get-user-details.action.js +113 -114
  55. package/dist/providers/learnworlds/actions/get-user-details.action.js.map +1 -1
  56. package/dist/providers/learnworlds/actions/get-user-enrollments.action.d.ts +43 -5
  57. package/dist/providers/learnworlds/actions/get-user-enrollments.action.d.ts.map +1 -1
  58. package/dist/providers/learnworlds/actions/get-user-enrollments.action.js +191 -147
  59. package/dist/providers/learnworlds/actions/get-user-enrollments.action.js.map +1 -1
  60. package/dist/providers/learnworlds/actions/get-user-progress.action.d.ts +21 -92
  61. package/dist/providers/learnworlds/actions/get-user-progress.action.d.ts.map +1 -1
  62. package/dist/providers/learnworlds/actions/get-user-progress.action.js +145 -166
  63. package/dist/providers/learnworlds/actions/get-user-progress.action.js.map +1 -1
  64. package/dist/providers/learnworlds/actions/get-users.action.d.ts +14 -28
  65. package/dist/providers/learnworlds/actions/get-users.action.d.ts.map +1 -1
  66. package/dist/providers/learnworlds/actions/get-users.action.js +122 -143
  67. package/dist/providers/learnworlds/actions/get-users.action.js.map +1 -1
  68. package/dist/providers/learnworlds/actions/index.d.ts +7 -0
  69. package/dist/providers/learnworlds/actions/index.d.ts.map +1 -1
  70. package/dist/providers/learnworlds/actions/index.js +7 -0
  71. package/dist/providers/learnworlds/actions/index.js.map +1 -1
  72. package/dist/providers/learnworlds/actions/onboard-learner.action.d.ts +53 -0
  73. package/dist/providers/learnworlds/actions/onboard-learner.action.d.ts.map +1 -0
  74. package/dist/providers/learnworlds/actions/onboard-learner.action.js +236 -0
  75. package/dist/providers/learnworlds/actions/onboard-learner.action.js.map +1 -0
  76. package/dist/providers/learnworlds/actions/sso-login.action.d.ts +35 -0
  77. package/dist/providers/learnworlds/actions/sso-login.action.d.ts.map +1 -0
  78. package/dist/providers/learnworlds/actions/sso-login.action.js +101 -0
  79. package/dist/providers/learnworlds/actions/sso-login.action.js.map +1 -0
  80. package/dist/providers/learnworlds/actions/update-user-progress.action.d.ts +12 -1
  81. package/dist/providers/learnworlds/actions/update-user-progress.action.d.ts.map +1 -1
  82. package/dist/providers/learnworlds/actions/update-user-progress.action.js +167 -210
  83. package/dist/providers/learnworlds/actions/update-user-progress.action.js.map +1 -1
  84. package/dist/providers/learnworlds/actions/update-user.action.d.ts +39 -0
  85. package/dist/providers/learnworlds/actions/update-user.action.d.ts.map +1 -0
  86. package/dist/providers/learnworlds/actions/update-user.action.js +168 -0
  87. package/dist/providers/learnworlds/actions/update-user.action.js.map +1 -0
  88. package/dist/providers/learnworlds/index.d.ts +1 -0
  89. package/dist/providers/learnworlds/index.d.ts.map +1 -1
  90. package/dist/providers/learnworlds/index.js +2 -0
  91. package/dist/providers/learnworlds/index.js.map +1 -1
  92. package/dist/providers/learnworlds/interfaces/bundle.types.d.ts +16 -0
  93. package/dist/providers/learnworlds/interfaces/bundle.types.d.ts.map +1 -0
  94. package/dist/providers/learnworlds/interfaces/bundle.types.js +2 -0
  95. package/dist/providers/learnworlds/interfaces/bundle.types.js.map +1 -0
  96. package/dist/providers/learnworlds/interfaces/certificate.types.d.ts +66 -0
  97. package/dist/providers/learnworlds/interfaces/certificate.types.d.ts.map +1 -0
  98. package/dist/providers/learnworlds/interfaces/certificate.types.js +2 -0
  99. package/dist/providers/learnworlds/interfaces/certificate.types.js.map +1 -0
  100. package/dist/providers/learnworlds/interfaces/common.types.d.ts +221 -0
  101. package/dist/providers/learnworlds/interfaces/common.types.d.ts.map +1 -0
  102. package/dist/providers/learnworlds/interfaces/common.types.js +2 -0
  103. package/dist/providers/learnworlds/interfaces/common.types.js.map +1 -0
  104. package/dist/providers/learnworlds/interfaces/course.types.d.ts +393 -0
  105. package/dist/providers/learnworlds/interfaces/course.types.d.ts.map +1 -0
  106. package/dist/providers/learnworlds/interfaces/course.types.js +2 -0
  107. package/dist/providers/learnworlds/interfaces/course.types.js.map +1 -0
  108. package/dist/providers/learnworlds/interfaces/enrollment.types.d.ts +165 -0
  109. package/dist/providers/learnworlds/interfaces/enrollment.types.d.ts.map +1 -0
  110. package/dist/providers/learnworlds/interfaces/enrollment.types.js +2 -0
  111. package/dist/providers/learnworlds/interfaces/enrollment.types.js.map +1 -0
  112. package/dist/providers/learnworlds/interfaces/index.d.ts +12 -0
  113. package/dist/providers/learnworlds/interfaces/index.d.ts.map +1 -0
  114. package/dist/providers/learnworlds/interfaces/index.js +13 -0
  115. package/dist/providers/learnworlds/interfaces/index.js.map +1 -0
  116. package/dist/providers/learnworlds/interfaces/onboarding.types.d.ts +39 -0
  117. package/dist/providers/learnworlds/interfaces/onboarding.types.d.ts.map +1 -0
  118. package/dist/providers/learnworlds/interfaces/onboarding.types.js +2 -0
  119. package/dist/providers/learnworlds/interfaces/onboarding.types.js.map +1 -0
  120. package/dist/providers/learnworlds/interfaces/quiz.types.d.ts +108 -0
  121. package/dist/providers/learnworlds/interfaces/quiz.types.d.ts.map +1 -0
  122. package/dist/providers/learnworlds/interfaces/quiz.types.js +2 -0
  123. package/dist/providers/learnworlds/interfaces/quiz.types.js.map +1 -0
  124. package/dist/providers/learnworlds/interfaces/sso.types.d.ts +18 -0
  125. package/dist/providers/learnworlds/interfaces/sso.types.d.ts.map +1 -0
  126. package/dist/providers/learnworlds/interfaces/sso.types.js +2 -0
  127. package/dist/providers/learnworlds/interfaces/sso.types.js.map +1 -0
  128. package/dist/providers/learnworlds/interfaces/sync.types.d.ts +44 -0
  129. package/dist/providers/learnworlds/interfaces/sync.types.d.ts.map +1 -0
  130. package/dist/providers/learnworlds/interfaces/sync.types.js +2 -0
  131. package/dist/providers/learnworlds/interfaces/sync.types.js.map +1 -0
  132. package/dist/providers/learnworlds/interfaces/tag.types.d.ts +17 -0
  133. package/dist/providers/learnworlds/interfaces/tag.types.d.ts.map +1 -0
  134. package/dist/providers/learnworlds/interfaces/tag.types.js +2 -0
  135. package/dist/providers/learnworlds/interfaces/tag.types.js.map +1 -0
  136. package/dist/providers/learnworlds/interfaces/user.types.d.ts +198 -0
  137. package/dist/providers/learnworlds/interfaces/user.types.d.ts.map +1 -0
  138. package/dist/providers/learnworlds/interfaces/user.types.js +2 -0
  139. package/dist/providers/learnworlds/interfaces/user.types.js.map +1 -0
  140. package/dist/providers/learnworlds/learnworlds-base.action.d.ts +111 -7
  141. package/dist/providers/learnworlds/learnworlds-base.action.d.ts.map +1 -1
  142. package/dist/providers/learnworlds/learnworlds-base.action.js +293 -56
  143. package/dist/providers/learnworlds/learnworlds-base.action.js.map +1 -1
  144. package/package.json +8 -7
  145. package/src/__tests__/attach-tags.action.test.ts +137 -0
  146. package/src/__tests__/create-user.action.test.ts +311 -0
  147. package/src/__tests__/detach-tags.action.test.ts +136 -0
  148. package/src/__tests__/enroll-user.action.test.ts +283 -0
  149. package/src/__tests__/get-bulk-data.action.test.ts +649 -0
  150. package/src/__tests__/get-bundles.action.test.ts +215 -0
  151. package/src/__tests__/lms.test.ts +275 -184
  152. package/src/__tests__/onboard-learner.action.test.ts +455 -0
  153. package/src/__tests__/sso-login.action.test.ts +256 -0
  154. package/src/__tests__/update-user.action.test.ts +350 -0
  155. package/src/base/base-lms.action.ts +226 -163
  156. package/src/providers/learnworlds/actions/attach-tags.action.ts +90 -0
  157. package/src/providers/learnworlds/actions/create-user.action.ts +291 -235
  158. package/src/providers/learnworlds/actions/detach-tags.action.ts +90 -0
  159. package/src/providers/learnworlds/actions/enroll-user.action.ts +326 -220
  160. package/src/providers/learnworlds/actions/get-bulk-data.action.ts +438 -0
  161. package/src/providers/learnworlds/actions/get-bundles.action.ts +139 -0
  162. package/src/providers/learnworlds/actions/get-certificates.action.ts +499 -309
  163. package/src/providers/learnworlds/actions/get-course-analytics.action.ts +470 -337
  164. package/src/providers/learnworlds/actions/get-course-details.action.ts +395 -249
  165. package/src/providers/learnworlds/actions/get-courses.action.ts +508 -565
  166. package/src/providers/learnworlds/actions/get-quiz-results.action.ts +606 -381
  167. package/src/providers/learnworlds/actions/get-user-details.action.ts +335 -349
  168. package/src/providers/learnworlds/actions/get-user-enrollments.action.ts +328 -228
  169. package/src/providers/learnworlds/actions/get-user-progress.action.ts +522 -571
  170. package/src/providers/learnworlds/actions/get-users.action.ts +231 -282
  171. package/src/providers/learnworlds/actions/index.ts +8 -1
  172. package/src/providers/learnworlds/actions/onboard-learner.action.ts +286 -0
  173. package/src/providers/learnworlds/actions/sso-login.action.ts +116 -0
  174. package/src/providers/learnworlds/actions/update-user-progress.action.ts +301 -263
  175. package/src/providers/learnworlds/actions/update-user.action.ts +181 -0
  176. package/src/providers/learnworlds/index.ts +4 -1
  177. package/src/providers/learnworlds/interfaces/bundle.types.ts +17 -0
  178. package/src/providers/learnworlds/interfaces/certificate.types.ts +69 -0
  179. package/src/providers/learnworlds/interfaces/common.types.ts +233 -0
  180. package/src/providers/learnworlds/interfaces/course.types.ts +411 -0
  181. package/src/providers/learnworlds/interfaces/enrollment.types.ts +176 -0
  182. package/src/providers/learnworlds/interfaces/index.ts +12 -0
  183. package/src/providers/learnworlds/interfaces/onboarding.types.ts +41 -0
  184. package/src/providers/learnworlds/interfaces/quiz.types.ts +118 -0
  185. package/src/providers/learnworlds/interfaces/sso.types.ts +19 -0
  186. package/src/providers/learnworlds/interfaces/sync.types.ts +46 -0
  187. package/src/providers/learnworlds/interfaces/tag.types.ts +18 -0
  188. package/src/providers/learnworlds/interfaces/user.types.ts +204 -0
  189. package/src/providers/learnworlds/learnworlds-base.action.ts +468 -210
  190. package/tsconfig.json +1 -1
  191. package/dist/__tests__/lms.test.d.ts +0 -2
  192. package/dist/__tests__/lms.test.d.ts.map +0 -1
  193. package/dist/__tests__/lms.test.js +0 -232
  194. package/dist/__tests__/lms.test.js.map +0 -1
@@ -3,6 +3,8 @@ import { BaseLMSAction } from '../../base/base-lms.action';
3
3
  import { UserInfo } from '@memberjunction/core';
4
4
  import { MJCompanyIntegrationEntity } from '@memberjunction/core-entities';
5
5
  import { BaseAction } from '@memberjunction/actions';
6
+ import { ActionParam } from '@memberjunction/actions-base';
7
+ import { LWApiEnrollmentStatus, LWApiProgressData, LWApiUser, LearnWorldsUser, LearnWorldsPaginatedResponse } from './interfaces';
6
8
 
7
9
  /**
8
10
  * Base class for all LearnWorlds LMS actions.
@@ -10,213 +12,469 @@ import { BaseAction } from '@memberjunction/actions';
10
12
  */
11
13
  @RegisterClass(BaseAction, 'LearnWorldsBaseAction')
12
14
  export abstract class LearnWorldsBaseAction extends BaseLMSAction {
13
- protected lmsProvider = 'LearnWorlds';
14
- protected integrationName = 'LearnWorlds';
15
-
16
- /**
17
- * LearnWorlds API version
18
- */
19
- protected apiVersion = 'v2';
20
-
21
- /**
22
- * Current action parameters (set by the framework)
23
- */
24
- protected params: any;
25
-
26
- /**
27
- * Makes an authenticated request to LearnWorlds API
28
- */
29
- protected async makeLearnWorldsRequest<T = any>(
30
- endpoint: string,
31
- method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',
32
- body?: any,
33
- contextUser?: UserInfo
34
- ): Promise<T> {
35
- if (!contextUser) {
36
- throw new Error('Context user is required for LearnWorlds API calls');
37
- }
38
-
39
- // Get company ID from action params
40
- const companyId = this.getParamValue(this.params, 'CompanyID');
41
- if (!companyId) {
42
- throw new Error('CompanyID parameter is required');
43
- }
44
-
45
- // Get the integration credentials
46
- const integration = await this.getCompanyIntegration(companyId, contextUser);
47
-
48
- // Get API credentials (from env vars or database)
49
- const credentials = await this.getAPICredentials(integration);
50
-
51
- if (!credentials.apiKey) {
52
- throw new Error('API Key is required for LearnWorlds integration');
53
- }
54
-
55
- // Get the school domain from ExternalSystemID or environment
56
- const schoolDomain = integration.ExternalSystemID || this.getCredentialFromEnv(companyId, 'SCHOOL_DOMAIN');
57
- if (!schoolDomain) {
58
- throw new Error('School domain not found. Set in CompanyIntegration.ExternalSystemID or environment variable');
59
- }
60
-
61
- // Build the full URL
62
- const baseUrl = `https://${schoolDomain}/api/${this.apiVersion}`;
63
- const fullUrl = `${baseUrl}/${endpoint}`;
64
-
65
- // Prepare headers
66
- const headers: Record<string, string> = {
67
- 'Authorization': `Bearer ${credentials.apiKey}`,
68
- 'Accept': 'application/json',
69
- 'Content-Type': 'application/json',
70
- 'Lw-Client': 'MemberJunction'
71
- };
72
-
73
- try {
74
- const response = await fetch(fullUrl, {
75
- method,
76
- headers,
77
- body: body ? JSON.stringify(body) : undefined
78
- });
79
-
80
- if (!response.ok) {
81
- const errorText = await response.text();
82
- let errorMessage = `LearnWorlds API error: ${response.status} ${response.statusText}`;
83
-
84
- try {
85
- const errorJson = JSON.parse(errorText);
86
- if (errorJson.error) {
87
- errorMessage = `LearnWorlds API error: ${errorJson.error.message || errorJson.error}`;
88
- } else if (errorJson.message) {
89
- errorMessage = `LearnWorlds API error: ${errorJson.message}`;
90
- }
91
- } catch {
92
- errorMessage += ` - ${errorText}`;
93
- }
94
-
95
- throw new Error(errorMessage);
96
- }
97
-
98
- const result = await response.json();
99
- return result as T;
100
- } catch (error) {
101
- if (error instanceof Error) {
102
- throw error;
103
- }
104
- throw new Error(`LearnWorlds API request failed: ${error}`);
105
- }
106
- }
107
-
108
- /**
109
- * Makes a paginated request to LearnWorlds API
110
- */
111
- protected async makeLearnWorldsPaginatedRequest<T = any>(
112
- endpoint: string,
113
- params: Record<string, any> = {},
114
- contextUser?: UserInfo
115
- ): Promise<T[]> {
116
- const results: T[] = [];
117
- let page = 1;
118
- let hasMore = true;
119
- const limit = params.limit || 50;
120
-
121
- while (hasMore) {
122
- const queryParams = new URLSearchParams({
123
- ...params,
124
- page: page.toString(),
125
- limit: limit.toString()
126
- });
127
-
128
- const response = await this.makeLearnWorldsRequest<{
129
- data: T[];
130
- meta?: {
131
- page: number;
132
- totalPages: number;
133
- totalItems: number;
134
- };
135
- }>(`${endpoint}?${queryParams}`, 'GET', undefined, contextUser);
136
-
137
- if (response.data && Array.isArray(response.data)) {
138
- results.push(...response.data);
139
- }
140
-
141
- // Check if there are more pages
142
- if (response.meta && response.meta.page < response.meta.totalPages) {
143
- page++;
144
- } else {
145
- hasMore = false;
146
- }
147
-
148
- // Respect max results if specified
149
- const maxResults = this.getParamValue(this.params, 'MaxResults');
150
- if (maxResults && results.length >= maxResults) {
151
- return results.slice(0, maxResults);
152
- }
153
- }
154
-
155
- return results;
156
- }
157
-
158
- /**
159
- * Convert LearnWorlds date format to Date object
160
- */
161
- protected parseLearnWorldsDate(dateString: string | number): Date {
162
- // LearnWorlds sometimes returns timestamps as seconds since epoch
163
- if (typeof dateString === 'number') {
164
- return new Date(dateString * 1000);
165
- }
166
- return new Date(dateString);
167
- }
168
-
169
- /**
170
- * Format date for LearnWorlds API (ISO 8601)
171
- */
172
- protected formatLearnWorldsDate(date: Date): string {
173
- return date.toISOString();
174
- }
175
-
176
- /**
177
- * Map LearnWorlds user status to standard status
178
- */
179
- protected mapUserStatus(status: string): 'active' | 'inactive' | 'suspended' {
180
- const statusMap: Record<string, 'active' | 'inactive' | 'suspended'> = {
181
- 'active': 'active',
182
- 'inactive': 'inactive',
183
- 'suspended': 'suspended',
184
- 'blocked': 'suspended'
185
- };
186
-
187
- return statusMap[status.toLowerCase()] || 'inactive';
188
- }
189
-
190
- /**
191
- * Map LearnWorlds enrollment status
192
- */
193
- protected mapLearnWorldsEnrollmentStatus(enrollment: any): 'active' | 'completed' | 'expired' | 'suspended' {
194
- if (enrollment.completed) {
195
- return 'completed';
196
- }
197
- if (enrollment.expired) {
198
- return 'expired';
199
- }
200
- if (enrollment.suspended || !enrollment.active) {
201
- return 'suspended';
202
- }
203
- return 'active';
204
- }
205
-
206
- /**
207
- * Calculate progress from LearnWorlds data
208
- */
209
- protected calculateProgress(progressData: any): {
210
- percentage: number;
211
- completedUnits: number;
212
- totalUnits: number;
213
- timeSpent: number;
214
- } {
215
- return {
216
- percentage: progressData.percentage || 0,
217
- completedUnits: progressData.completed_units || 0,
218
- totalUnits: progressData.total_units || 0,
219
- timeSpent: progressData.time_spent || 0
220
- };
221
- }
222
- }
15
+ protected lmsProvider = 'LearnWorlds';
16
+ protected integrationName = 'LearnWorlds';
17
+
18
+ /**
19
+ * LearnWorlds API version
20
+ */
21
+ protected apiVersion = 'v2';
22
+
23
+ /**
24
+ * Concurrency limit for parallel API calls to avoid overwhelming the API.
25
+ */
26
+ protected static readonly CONCURRENCY_LIMIT = 5;
27
+
28
+ /**
29
+ * Allowed user roles in LearnWorlds.
30
+ */
31
+ protected static readonly ALLOWED_ROLES: readonly string[] = ['student', 'observer', 'instructor'] as const;
32
+
33
+ /**
34
+ * Maximum number of items per page supported by the LearnWorlds API
35
+ */
36
+ protected static readonly LW_MAX_PAGE_SIZE = 100;
37
+
38
+ /**
39
+ * Current action parameters (set by the framework or by SetCompanyContext)
40
+ */
41
+ protected params: ActionParam[] = [];
42
+
43
+ /**
44
+ * Tracks the number of actual HTTP requests made since last reset.
45
+ * Useful for callers that need accurate API call counts (e.g., bulk data).
46
+ */
47
+ protected apiCallCount = 0;
48
+
49
+ /**
50
+ * Public accessor for the running API call count.
51
+ */
52
+ public get ApiCallCount(): number {
53
+ return this.apiCallCount;
54
+ }
55
+
56
+ /**
57
+ * Set the company context for direct (non-framework) calls.
58
+ * This populates `this.params` so that `makeLearnWorldsRequest` can find the CompanyID.
59
+ */
60
+ public SetCompanyContext(companyId: string): void {
61
+ this.params = [{ Name: 'CompanyID', Type: 'Input', Value: companyId }];
62
+ }
63
+
64
+ /**
65
+ * Makes an authenticated request to LearnWorlds API.
66
+ * The body parameter accepts any object that will be JSON-serialized.
67
+ */
68
+ protected async makeLearnWorldsRequest<T = Record<string, unknown>>(
69
+ endpoint: string,
70
+ method: 'GET' | 'POST' | 'PUT' | 'DELETE' = 'GET',
71
+ body?: object | null,
72
+ contextUser?: UserInfo,
73
+ ): Promise<T> {
74
+ if (!contextUser) {
75
+ throw new Error('Context user is required for LearnWorlds API calls');
76
+ }
77
+
78
+ const { fullUrl, headers } = await this.buildRequestConfig(contextUser);
79
+ const requestUrl = `${fullUrl}/${endpoint}`;
80
+
81
+ try {
82
+ this.apiCallCount++;
83
+ const response = await fetch(requestUrl, {
84
+ method,
85
+ headers,
86
+ body: body ? JSON.stringify(body) : undefined,
87
+ });
88
+
89
+ if (!response.ok) {
90
+ throw new Error(await this.buildErrorMessage(response));
91
+ }
92
+
93
+ return (await response.json()) as T;
94
+ } catch (error) {
95
+ if (error instanceof Error) {
96
+ throw error;
97
+ }
98
+ throw new Error(`LearnWorlds API request failed: ${error}`);
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Resolves integration credentials and builds the base URL and headers.
104
+ */
105
+ private async buildRequestConfig(contextUser: UserInfo): Promise<{ fullUrl: string; headers: Record<string, string> }> {
106
+ const companyId = this.getParamValue(this.params, 'CompanyID') as string | undefined;
107
+ if (!companyId) {
108
+ throw new Error('CompanyID parameter is required');
109
+ }
110
+
111
+ const integration = await this.getCompanyIntegration(companyId, contextUser);
112
+ const credentials = await this.getAPICredentials(integration);
113
+
114
+ if (!credentials.apiKey) {
115
+ throw new Error('API Key is required for LearnWorlds integration');
116
+ }
117
+
118
+ const schoolDomain = integration.ExternalSystemID || this.getCredentialFromEnv(companyId, 'SCHOOL_DOMAIN');
119
+ if (!schoolDomain) {
120
+ throw new Error('School domain not found. Set in CompanyIntegration.ExternalSystemID or environment variable');
121
+ }
122
+
123
+ this.validateSchoolDomain(schoolDomain);
124
+
125
+ return {
126
+ fullUrl: `https://${schoolDomain}/api/${this.apiVersion}`,
127
+ headers: {
128
+ Authorization: `Bearer ${credentials.apiKey}`,
129
+ Accept: 'application/json',
130
+ 'Content-Type': 'application/json',
131
+ 'Lw-Client': 'MemberJunction',
132
+ },
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Parses error details from a non-OK API response.
138
+ */
139
+ private async buildErrorMessage(response: Response): Promise<string> {
140
+ const errorText = await response.text();
141
+ let errorMessage = `LearnWorlds API error: ${response.status} ${response.statusText}`;
142
+
143
+ try {
144
+ const errorJson = JSON.parse(errorText) as { error?: { message?: string }; message?: string };
145
+ if (errorJson.error) {
146
+ errorMessage = `LearnWorlds API error: ${errorJson.error.message || String(errorJson.error)}`;
147
+ } else if (errorJson.message) {
148
+ errorMessage = `LearnWorlds API error: ${errorJson.message}`;
149
+ }
150
+ } catch {
151
+ errorMessage += ` - ${errorText}`;
152
+ }
153
+
154
+ return errorMessage;
155
+ }
156
+
157
+ /**
158
+ * Makes a paginated request to LearnWorlds API
159
+ */
160
+ protected async makeLearnWorldsPaginatedRequest<T = Record<string, unknown>>(
161
+ endpoint: string,
162
+ queryParams: Record<string, string | number | boolean> = {},
163
+ contextUser?: UserInfo,
164
+ ): Promise<T[]> {
165
+ const results: T[] = [];
166
+ let page = 1;
167
+ let hasMore = true;
168
+ const limit = (queryParams.limit as number) || LearnWorldsBaseAction.LW_MAX_PAGE_SIZE;
169
+
170
+ while (hasMore) {
171
+ const paginatedParams: Record<string, string> = {};
172
+ for (const [key, val] of Object.entries(queryParams)) {
173
+ paginatedParams[key] = String(val);
174
+ }
175
+ paginatedParams.page = page.toString();
176
+ paginatedParams.limit = limit.toString();
177
+
178
+ const qs = new URLSearchParams(paginatedParams);
179
+
180
+ const response = await this.makeLearnWorldsRequest<LearnWorldsPaginatedResponse<T>>(`${endpoint}?${qs}`, 'GET', undefined, contextUser);
181
+
182
+ if (response.data && Array.isArray(response.data)) {
183
+ results.push(...response.data);
184
+ }
185
+
186
+ // Check if there are more pages
187
+ if (response.meta && response.meta.page < response.meta.totalPages) {
188
+ page++;
189
+ } else {
190
+ hasMore = false;
191
+ }
192
+
193
+ // Respect max results if specified
194
+ const maxResults = this.getParamValue(this.params, 'MaxResults') as number | undefined;
195
+ if (maxResults && results.length >= maxResults) {
196
+ return results.slice(0, maxResults);
197
+ }
198
+ }
199
+
200
+ return results;
201
+ }
202
+
203
+ /**
204
+ * Convert LearnWorlds date format to Date object
205
+ */
206
+ protected parseLearnWorldsDate(dateString: string | number): Date {
207
+ // LearnWorlds sometimes returns timestamps as seconds since epoch
208
+ if (typeof dateString === 'number') {
209
+ return new Date(dateString * 1000);
210
+ }
211
+ return new Date(dateString);
212
+ }
213
+
214
+ /**
215
+ * Format date for LearnWorlds API (ISO 8601)
216
+ */
217
+ protected formatLearnWorldsDate(date: Date): string {
218
+ return date.toISOString();
219
+ }
220
+
221
+ /**
222
+ * Map LearnWorlds user status to standard status
223
+ */
224
+ protected mapUserStatus(status: string): 'active' | 'inactive' | 'suspended' {
225
+ const statusMap: Record<string, 'active' | 'inactive' | 'suspended'> = {
226
+ active: 'active',
227
+ inactive: 'inactive',
228
+ suspended: 'suspended',
229
+ blocked: 'suspended',
230
+ };
231
+
232
+ return statusMap[status.toLowerCase()] || 'inactive';
233
+ }
234
+
235
+ /**
236
+ * Map LearnWorlds enrollment status
237
+ */
238
+ protected mapLearnWorldsEnrollmentStatus(enrollment: LWApiEnrollmentStatus): 'active' | 'completed' | 'expired' | 'suspended' {
239
+ if (enrollment.completed) {
240
+ return 'completed';
241
+ }
242
+ if (enrollment.expired) {
243
+ return 'expired';
244
+ }
245
+ if (enrollment.suspended || !enrollment.active) {
246
+ return 'suspended';
247
+ }
248
+ return 'active';
249
+ }
250
+
251
+ /**
252
+ * Calculate progress from LearnWorlds data
253
+ */
254
+ protected calculateProgress(progressData: LWApiProgressData): {
255
+ percentage: number;
256
+ completedUnits: number;
257
+ totalUnits: number;
258
+ timeSpent: number;
259
+ } {
260
+ return {
261
+ percentage: progressData.percentage || 0,
262
+ completedUnits: progressData.completed_units || 0,
263
+ totalUnits: progressData.total_units || 0,
264
+ timeSpent: progressData.time_spent || 0,
265
+ };
266
+ }
267
+
268
+ /**
269
+ * Safely parses a date string to ISO format.
270
+ * Returns undefined if the input is falsy or produces an invalid date.
271
+ */
272
+ protected safeParseDateToISO(dateString: string | undefined): string | undefined {
273
+ if (!dateString) return undefined;
274
+ const parsed = new Date(dateString);
275
+ if (isNaN(parsed.getTime())) {
276
+ console.warn(`Invalid date string "${dateString}" — skipping date filter`);
277
+ return undefined;
278
+ }
279
+ return parsed.toISOString();
280
+ }
281
+
282
+ // ----------------------------------------------------------------
283
+ // Validation helpers
284
+ // ----------------------------------------------------------------
285
+
286
+ /**
287
+ * Validates that a value is safe to use as a URL path segment.
288
+ * Rejects values containing path traversal or URL manipulation characters.
289
+ */
290
+ protected validatePathSegment(value: string, paramName: string): string {
291
+ if (value.length === 0) {
292
+ throw new Error(`${paramName} must not be empty`);
293
+ }
294
+ if (/[\/\\?#@%]|\.\./.test(value)) {
295
+ throw new Error(`Invalid ${paramName}: contains forbidden characters`);
296
+ }
297
+ return value;
298
+ }
299
+
300
+ /**
301
+ * Validates that a school domain is safe to use in URL construction.
302
+ * Must look like a hostname (alphanumeric + hyphens + dots).
303
+ */
304
+ private validateSchoolDomain(domain: string): string {
305
+ if (/[\/\\?#@\s]/.test(domain)) {
306
+ throw new Error('Invalid school domain: contains URL-unsafe characters');
307
+ }
308
+ if (!/^[a-zA-Z0-9]([a-zA-Z0-9.-]*[a-zA-Z0-9])?$/.test(domain)) {
309
+ throw new Error('Invalid school domain format');
310
+ }
311
+ return domain;
312
+ }
313
+
314
+ /**
315
+ * Validates that a role is in the allowed set.
316
+ */
317
+ protected validateRole(role: string): string {
318
+ const normalizedRole = role.toLowerCase();
319
+ if (!LearnWorldsBaseAction.ALLOWED_ROLES.includes(normalizedRole)) {
320
+ throw new Error(`Invalid role '${role}'. Allowed roles: ${LearnWorldsBaseAction.ALLOWED_ROLES.join(', ')}`);
321
+ }
322
+ return normalizedRole;
323
+ }
324
+
325
+ /**
326
+ * Validates that a string is a plausible email address.
327
+ */
328
+ protected validateEmail(email: string, paramName: string = 'Email'): string {
329
+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
330
+ if (!emailRegex.test(email)) {
331
+ throw new Error(`Invalid ${paramName} format: '${email}'`);
332
+ }
333
+ return email;
334
+ }
335
+
336
+ /**
337
+ * Validates that a redirect URL is either a relative path or an absolute URL
338
+ * that belongs to the LearnWorlds school domain and uses http(s).
339
+ */
340
+ protected validateRedirectTo(redirectTo: string, schoolDomain?: string): string {
341
+ // Allow relative paths
342
+ if (redirectTo.startsWith('/')) {
343
+ return redirectTo;
344
+ }
345
+ // If absolute URL, parse and check against school domain
346
+ let url: URL;
347
+ try {
348
+ url = new URL(redirectTo);
349
+ } catch {
350
+ throw new Error('RedirectTo is not a valid URL or relative path');
351
+ }
352
+ // Block dangerous protocols
353
+ if (!['http:', 'https:'].includes(url.protocol)) {
354
+ throw new Error('RedirectTo must use http or https protocol');
355
+ }
356
+ if (schoolDomain && !url.hostname.endsWith('.learnworlds.com') && url.hostname !== schoolDomain) {
357
+ throw new Error('RedirectTo must be a relative path or a LearnWorlds domain URL');
358
+ }
359
+ return redirectTo;
360
+ }
361
+
362
+ // ----------------------------------------------------------------
363
+ // Batch concurrency helper
364
+ // ----------------------------------------------------------------
365
+
366
+ /**
367
+ * Processes items in batches with controlled concurrency.
368
+ * Prevents unbounded parallel API calls from overwhelming the target API.
369
+ */
370
+ protected async processInBatches<TItem, TResult>(
371
+ items: TItem[],
372
+ processFn: (item: TItem) => Promise<TResult>,
373
+ batchSize: number = LearnWorldsBaseAction.CONCURRENCY_LIMIT,
374
+ ): Promise<TResult[]> {
375
+ const results: TResult[] = [];
376
+ for (let i = 0; i < items.length; i += batchSize) {
377
+ const batch = items.slice(i, i + batchSize);
378
+ const batchResults = await Promise.all(batch.map(processFn));
379
+ results.push(...batchResults);
380
+ }
381
+ return results;
382
+ }
383
+
384
+ // ----------------------------------------------------------------
385
+ // Parameter extraction helpers
386
+ // ----------------------------------------------------------------
387
+
388
+ /**
389
+ * Gets a required string parameter, throwing if missing or empty.
390
+ */
391
+ protected getRequiredStringParam(params: ActionParam[], name: string): string {
392
+ const value = this.getParamValue(params, name);
393
+ if (typeof value !== 'string' || !value) {
394
+ throw new Error(`Required string parameter '${name}' is missing or invalid`);
395
+ }
396
+ return value;
397
+ }
398
+
399
+ /**
400
+ * Gets an optional string parameter.
401
+ */
402
+ protected getOptionalStringParam(params: ActionParam[], name: string): string | undefined {
403
+ const value = this.getParamValue(params, name);
404
+ if (value === undefined || value === null) return undefined;
405
+ return typeof value === 'string' ? value : String(value);
406
+ }
407
+
408
+ /**
409
+ * Gets an optional boolean parameter with a default value.
410
+ * When defaultValue is undefined, returns undefined if the parameter is missing.
411
+ */
412
+ protected getOptionalBooleanParam(params: ActionParam[], name: string, defaultValue: boolean): boolean;
413
+ protected getOptionalBooleanParam(params: ActionParam[], name: string, defaultValue: boolean | undefined): boolean | undefined;
414
+ protected getOptionalBooleanParam(params: ActionParam[], name: string, defaultValue: boolean | undefined): boolean | undefined {
415
+ const value = this.getParamValue(params, name);
416
+ if (value === undefined || value === null) return defaultValue;
417
+ if (typeof value === 'boolean') return value;
418
+ const strVal = String(value).toLowerCase();
419
+ if (strVal === 'true' || strVal === '1') return true;
420
+ if (strVal === 'false' || strVal === '0') return false;
421
+ return defaultValue;
422
+ }
423
+
424
+ /**
425
+ * Gets an optional number parameter with a default value.
426
+ * When defaultValue is undefined, returns undefined if the parameter is missing.
427
+ */
428
+ protected getOptionalNumberParam(params: ActionParam[], name: string, defaultValue: number): number;
429
+ protected getOptionalNumberParam(params: ActionParam[], name: string, defaultValue: number | undefined): number | undefined;
430
+ protected getOptionalNumberParam(params: ActionParam[], name: string, defaultValue: number | undefined): number | undefined {
431
+ const value = this.getParamValue(params, name);
432
+ if (value === undefined || value === null) return defaultValue;
433
+ const parsed = Number(value);
434
+ return isNaN(parsed) ? defaultValue : parsed;
435
+ }
436
+
437
+ /**
438
+ * Gets an optional string array parameter.
439
+ */
440
+ protected getOptionalStringArrayParam(params: ActionParam[], name: string): string[] | undefined {
441
+ const value = this.getParamValue(params, name);
442
+ if (value === undefined || value === null) return undefined;
443
+ if (Array.isArray(value)) return value.map(String);
444
+ return undefined;
445
+ }
446
+
447
+ /**
448
+ * Shared utility: find a LearnWorlds user by email.
449
+ * Returns the user if found, null if not found (empty results).
450
+ * Re-throws errors for network failures, auth errors, rate limiting, etc.
451
+ */
452
+ public async FindUserByEmail(email: string, contextUser: UserInfo): Promise<LearnWorldsUser | null> {
453
+ const response = await this.makeLearnWorldsPaginatedRequest<LWApiUser>('users', { search: email, limit: 5 }, contextUser);
454
+
455
+ const match = response.find((u) => u.email.toLowerCase() === email.toLowerCase());
456
+ if (!match) return null;
457
+
458
+ return this.mapLWApiUserToLearnWorldsUser(match);
459
+ }
460
+
461
+ /**
462
+ * Maps a raw LW API user to the normalized LearnWorldsUser shape.
463
+ */
464
+ private mapLWApiUserToLearnWorldsUser(user: LWApiUser): LearnWorldsUser {
465
+ return {
466
+ id: user.id || user._id || '',
467
+ email: user.email,
468
+ username: user.username || user.email,
469
+ firstName: user.first_name,
470
+ lastName: user.last_name,
471
+ fullName: user.full_name || `${user.first_name || ''} ${user.last_name || ''}`.trim(),
472
+ status: this.mapUserStatus(user.status || 'active'),
473
+ role: user.role || 'student',
474
+ createdAt: this.parseLearnWorldsDate(user.created || user.created_at || ''),
475
+ lastLoginAt: user.last_login ? this.parseLearnWorldsDate(user.last_login) : undefined,
476
+ tags: user.tags || [],
477
+ customFields: user.custom_fields || {},
478
+ };
479
+ }
480
+ }