@symbo.ls/sdk 2.34.35 → 3.1.2

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 (187) hide show
  1. package/README.md +2 -143
  2. package/dist/cjs/config/environment.js +30 -98
  3. package/dist/cjs/index.js +24 -144
  4. package/dist/cjs/services/AIService.js +155 -0
  5. package/dist/cjs/services/AuthService.js +305 -738
  6. package/dist/cjs/services/BaseService.js +6 -158
  7. package/dist/cjs/services/BasedService.js +1185 -0
  8. package/dist/cjs/services/CoreService.js +1751 -0
  9. package/dist/cjs/services/SocketIOService.js +307 -0
  10. package/dist/cjs/services/SocketService.js +161 -0
  11. package/dist/cjs/services/SymstoryService.js +571 -0
  12. package/dist/cjs/services/index.js +16 -64
  13. package/dist/cjs/utils/TokenManager.js +30 -78
  14. package/dist/cjs/utils/basedQuerys.js +181 -0
  15. package/dist/cjs/utils/services.js +103 -301
  16. package/dist/cjs/utils/symstoryClient.js +259 -0
  17. package/dist/cjs/utils/validation.js +3 -0
  18. package/dist/esm/config/environment.js +30 -98
  19. package/dist/esm/index.js +8797 -49416
  20. package/dist/esm/services/AIService.js +185 -0
  21. package/dist/esm/services/AuthService.js +386 -1493
  22. package/dist/esm/services/BaseService.js +6 -757
  23. package/dist/esm/services/BasedService.js +5278 -0
  24. package/dist/esm/services/CoreService.js +2264 -0
  25. package/dist/esm/services/SocketIOService.js +470 -0
  26. package/dist/esm/services/SocketService.js +191 -0
  27. package/dist/esm/services/SymstoryService.js +7041 -0
  28. package/dist/esm/services/index.js +8690 -49015
  29. package/dist/esm/utils/TokenManager.js +30 -78
  30. package/dist/esm/utils/basedQuerys.js +163 -0
  31. package/dist/esm/utils/services.js +103 -301
  32. package/dist/esm/utils/symstoryClient.js +370 -0
  33. package/dist/esm/utils/validation.js +7 -4
  34. package/dist/node/config/environment.js +30 -98
  35. package/dist/node/index.js +32 -175
  36. package/dist/node/services/AIService.js +136 -0
  37. package/dist/node/services/AuthService.js +310 -742
  38. package/dist/node/services/BaseService.js +6 -148
  39. package/dist/node/services/BasedService.js +1156 -0
  40. package/dist/node/services/CoreService.js +1722 -0
  41. package/dist/node/services/SocketIOService.js +278 -0
  42. package/dist/node/services/SocketService.js +142 -0
  43. package/dist/node/services/SymstoryService.js +542 -0
  44. package/dist/node/services/index.js +16 -64
  45. package/dist/node/utils/TokenManager.js +30 -78
  46. package/dist/node/utils/basedQuerys.js +162 -0
  47. package/dist/node/utils/services.js +103 -301
  48. package/dist/node/utils/symstoryClient.js +230 -0
  49. package/dist/node/utils/validation.js +3 -0
  50. package/package.json +16 -35
  51. package/src/config/environment.js +28 -99
  52. package/src/index.js +36 -181
  53. package/src/services/AIService.js +150 -0
  54. package/src/services/AuthService.js +328 -874
  55. package/src/services/BaseService.js +6 -166
  56. package/src/services/BasedService.js +1301 -0
  57. package/src/services/CoreService.js +1943 -0
  58. package/src/services/SocketIOService.js +334 -0
  59. package/src/services/SocketService.js +168 -0
  60. package/src/services/SymstoryService.js +649 -0
  61. package/src/services/index.js +13 -80
  62. package/src/utils/TokenManager.js +33 -88
  63. package/src/utils/basedQuerys.js +164 -0
  64. package/src/utils/services.js +107 -326
  65. package/src/utils/symstoryClient.js +252 -0
  66. package/src/utils/validation.js +3 -0
  67. package/dist/cjs/services/AdminService.js +0 -351
  68. package/dist/cjs/services/BranchService.js +0 -484
  69. package/dist/cjs/services/CollabService.js +0 -743
  70. package/dist/cjs/services/DnsService.js +0 -340
  71. package/dist/cjs/services/FeatureFlagService.js +0 -175
  72. package/dist/cjs/services/FileService.js +0 -201
  73. package/dist/cjs/services/IntegrationService.js +0 -538
  74. package/dist/cjs/services/MetricsService.js +0 -62
  75. package/dist/cjs/services/PaymentService.js +0 -271
  76. package/dist/cjs/services/PlanService.js +0 -426
  77. package/dist/cjs/services/ProjectService.js +0 -1207
  78. package/dist/cjs/services/PullRequestService.js +0 -503
  79. package/dist/cjs/services/ScreenshotService.js +0 -304
  80. package/dist/cjs/services/SubscriptionService.js +0 -396
  81. package/dist/cjs/services/TrackingService.js +0 -661
  82. package/dist/cjs/services/WaitlistService.js +0 -148
  83. package/dist/cjs/state/RootStateManager.js +0 -65
  84. package/dist/cjs/state/rootEventBus.js +0 -74
  85. package/dist/cjs/utils/CollabClient.js +0 -223
  86. package/dist/cjs/utils/changePreprocessor.js +0 -199
  87. package/dist/cjs/utils/jsonDiff.js +0 -145
  88. package/dist/cjs/utils/ordering.js +0 -309
  89. package/dist/esm/services/AdminService.js +0 -1132
  90. package/dist/esm/services/BranchService.js +0 -1265
  91. package/dist/esm/services/CollabService.js +0 -26838
  92. package/dist/esm/services/DnsService.js +0 -1121
  93. package/dist/esm/services/FeatureFlagService.js +0 -956
  94. package/dist/esm/services/FileService.js +0 -982
  95. package/dist/esm/services/IntegrationService.js +0 -1319
  96. package/dist/esm/services/MetricsService.js +0 -843
  97. package/dist/esm/services/PaymentService.js +0 -1052
  98. package/dist/esm/services/PlanService.js +0 -1207
  99. package/dist/esm/services/ProjectService.js +0 -2526
  100. package/dist/esm/services/PullRequestService.js +0 -1284
  101. package/dist/esm/services/ScreenshotService.js +0 -1085
  102. package/dist/esm/services/SubscriptionService.js +0 -1177
  103. package/dist/esm/services/TrackingService.js +0 -18343
  104. package/dist/esm/services/WaitlistService.js +0 -929
  105. package/dist/esm/state/RootStateManager.js +0 -90
  106. package/dist/esm/state/rootEventBus.js +0 -56
  107. package/dist/esm/utils/CollabClient.js +0 -18901
  108. package/dist/esm/utils/changePreprocessor.js +0 -542
  109. package/dist/esm/utils/jsonDiff.js +0 -7011
  110. package/dist/esm/utils/ordering.js +0 -291
  111. package/dist/node/services/AdminService.js +0 -332
  112. package/dist/node/services/BranchService.js +0 -465
  113. package/dist/node/services/CollabService.js +0 -724
  114. package/dist/node/services/DnsService.js +0 -321
  115. package/dist/node/services/FeatureFlagService.js +0 -156
  116. package/dist/node/services/FileService.js +0 -182
  117. package/dist/node/services/IntegrationService.js +0 -519
  118. package/dist/node/services/MetricsService.js +0 -43
  119. package/dist/node/services/PaymentService.js +0 -252
  120. package/dist/node/services/PlanService.js +0 -407
  121. package/dist/node/services/ProjectService.js +0 -1188
  122. package/dist/node/services/PullRequestService.js +0 -484
  123. package/dist/node/services/ScreenshotService.js +0 -285
  124. package/dist/node/services/SubscriptionService.js +0 -377
  125. package/dist/node/services/TrackingService.js +0 -632
  126. package/dist/node/services/WaitlistService.js +0 -129
  127. package/dist/node/state/RootStateManager.js +0 -36
  128. package/dist/node/state/rootEventBus.js +0 -55
  129. package/dist/node/utils/CollabClient.js +0 -194
  130. package/dist/node/utils/changePreprocessor.js +0 -180
  131. package/dist/node/utils/jsonDiff.js +0 -116
  132. package/dist/node/utils/ordering.js +0 -290
  133. package/src/services/AdminService.js +0 -374
  134. package/src/services/BranchService.js +0 -536
  135. package/src/services/CollabService.js +0 -900
  136. package/src/services/DnsService.js +0 -366
  137. package/src/services/FeatureFlagService.js +0 -174
  138. package/src/services/FileService.js +0 -213
  139. package/src/services/IntegrationService.js +0 -548
  140. package/src/services/MetricsService.js +0 -40
  141. package/src/services/PaymentService.js +0 -287
  142. package/src/services/PlanService.js +0 -468
  143. package/src/services/ProjectService.js +0 -1366
  144. package/src/services/PullRequestService.js +0 -537
  145. package/src/services/ScreenshotService.js +0 -258
  146. package/src/services/SubscriptionService.js +0 -425
  147. package/src/services/TrackingService.js +0 -853
  148. package/src/services/WaitlistService.js +0 -130
  149. package/src/services/tests/BranchService/createBranch.test.js +0 -153
  150. package/src/services/tests/BranchService/deleteBranch.test.js +0 -173
  151. package/src/services/tests/BranchService/getBranchChanges.test.js +0 -146
  152. package/src/services/tests/BranchService/listBranches.test.js +0 -87
  153. package/src/services/tests/BranchService/mergeBranch.test.js +0 -210
  154. package/src/services/tests/BranchService/publishVersion.test.js +0 -183
  155. package/src/services/tests/BranchService/renameBranch.test.js +0 -240
  156. package/src/services/tests/BranchService/resetBranch.test.js +0 -152
  157. package/src/services/tests/FeatureFlagService/adminFeatureFlags.test.js +0 -67
  158. package/src/services/tests/FeatureFlagService/getFeatureFlags.test.js +0 -75
  159. package/src/services/tests/FileService/createFileFormData.test.js +0 -74
  160. package/src/services/tests/FileService/getFileUrl.test.js +0 -69
  161. package/src/services/tests/FileService/updateProjectIcon.test.js +0 -109
  162. package/src/services/tests/FileService/uploadDocument.test.js +0 -36
  163. package/src/services/tests/FileService/uploadFile.test.js +0 -78
  164. package/src/services/tests/FileService/uploadFileWithValidation.test.js +0 -114
  165. package/src/services/tests/FileService/uploadImage.test.js +0 -36
  166. package/src/services/tests/FileService/uploadMultipleFiles.test.js +0 -111
  167. package/src/services/tests/FileService/validateFile.test.js +0 -63
  168. package/src/services/tests/PlanService/createPlan.test.js +0 -104
  169. package/src/services/tests/PlanService/createPlanWithValidation.test.js +0 -523
  170. package/src/services/tests/PlanService/deletePlan.test.js +0 -92
  171. package/src/services/tests/PlanService/getActivePlans.test.js +0 -123
  172. package/src/services/tests/PlanService/getAdminPlans.test.js +0 -84
  173. package/src/services/tests/PlanService/getPlan.test.js +0 -50
  174. package/src/services/tests/PlanService/getPlanByKey.test.js +0 -109
  175. package/src/services/tests/PlanService/getPlanWithValidation.test.js +0 -85
  176. package/src/services/tests/PlanService/getPlans.test.js +0 -53
  177. package/src/services/tests/PlanService/getPlansByPriceRange.test.js +0 -109
  178. package/src/services/tests/PlanService/getPlansWithValidation.test.js +0 -48
  179. package/src/services/tests/PlanService/initializePlans.test.js +0 -75
  180. package/src/services/tests/PlanService/updatePlan.test.js +0 -111
  181. package/src/services/tests/PlanService/updatePlanWithValidation.test.js +0 -556
  182. package/src/state/RootStateManager.js +0 -76
  183. package/src/state/rootEventBus.js +0 -67
  184. package/src/utils/CollabClient.js +0 -248
  185. package/src/utils/changePreprocessor.js +0 -239
  186. package/src/utils/jsonDiff.js +0 -144
  187. package/src/utils/ordering.js +0 -271
@@ -1,290 +0,0 @@
1
- function isObjectLike(val) {
2
- return val && typeof val === "object" && !Array.isArray(val);
3
- }
4
- function normalizePath(path) {
5
- if (Array.isArray(path)) {
6
- return path;
7
- }
8
- if (typeof path === "string") {
9
- return [path];
10
- }
11
- return [];
12
- }
13
- function getParentPathsFromTuples(tuples = []) {
14
- const seen = /* @__PURE__ */ new Set();
15
- const parents = [];
16
- const META_KEYS = /* @__PURE__ */ new Set([
17
- "style",
18
- "class",
19
- "text",
20
- "html",
21
- "content",
22
- "data",
23
- "attr",
24
- "state",
25
- "scope",
26
- "define",
27
- "on",
28
- "extend",
29
- "extends",
30
- "childExtend",
31
- "childExtends",
32
- "children",
33
- "component",
34
- "context",
35
- "tag",
36
- "key",
37
- "__order",
38
- "if"
39
- ]);
40
- for (let i = 0; i < tuples.length; i++) {
41
- const tuple = tuples[i];
42
- if (!Array.isArray(tuple) || tuple.length < 2) {
43
- continue;
44
- }
45
- const path = normalizePath(tuple[1]);
46
- if (!path.length) {
47
- continue;
48
- }
49
- if (path[0] === "schema") {
50
- continue;
51
- }
52
- const immediateParent = path.slice(0, -1);
53
- if (immediateParent.length) {
54
- const key = JSON.stringify(immediateParent);
55
- if (!seen.has(key)) {
56
- seen.add(key);
57
- parents.push(immediateParent);
58
- }
59
- }
60
- const last = path[path.length - 1];
61
- if (META_KEYS.has(last) && path.length >= 2) {
62
- const containerParent = path.slice(0, -2);
63
- if (containerParent.length) {
64
- const key2 = JSON.stringify(containerParent);
65
- if (!seen.has(key2)) {
66
- seen.add(key2);
67
- parents.push(containerParent);
68
- }
69
- }
70
- }
71
- for (let j = 0; j < path.length; j++) {
72
- const seg = path[j];
73
- if (!META_KEYS.has(seg)) {
74
- continue;
75
- }
76
- const containerParent2 = path.slice(0, j);
77
- if (!containerParent2.length) {
78
- continue;
79
- }
80
- const key3 = JSON.stringify(containerParent2);
81
- if (!seen.has(key3)) {
82
- seen.add(key3);
83
- parents.push(containerParent2);
84
- }
85
- }
86
- }
87
- return parents;
88
- }
89
- function computeOrdersFromState(root, parentPaths = []) {
90
- if (!root || typeof root.getByPath !== "function") {
91
- return [];
92
- }
93
- const orders = [];
94
- const EXCLUDE_KEYS = /* @__PURE__ */ new Set(["__order"]);
95
- for (let i = 0; i < parentPaths.length; i++) {
96
- const parentPath = parentPaths[i];
97
- const obj = (() => {
98
- try {
99
- return root.getByPath(parentPath);
100
- } catch {
101
- return null;
102
- }
103
- })();
104
- if (!isObjectLike(obj)) {
105
- continue;
106
- }
107
- const keys = Object.keys(obj).filter((k) => !EXCLUDE_KEYS.has(k));
108
- orders.push({ path: parentPath, keys });
109
- }
110
- return orders;
111
- }
112
- function normaliseSchemaCode(code) {
113
- if (typeof code !== "string" || !code.length) {
114
- return "";
115
- }
116
- return code.replaceAll("/////n", "\n").replaceAll("/////tilde", "`");
117
- }
118
- function parseExportedObject(code) {
119
- const src = normaliseSchemaCode(code);
120
- if (!src) {
121
- return null;
122
- }
123
- const body = src.replace(/^\s*export\s+default\s*/u, "return ");
124
- try {
125
- return new Function(body)();
126
- } catch {
127
- return null;
128
- }
129
- }
130
- function extractTopLevelKeysFromCode(code) {
131
- const obj = parseExportedObject(code);
132
- if (!obj || typeof obj !== "object") {
133
- return [];
134
- }
135
- return Object.keys(obj);
136
- }
137
- function computeOrdersForTuples(root, tuples = []) {
138
- const pendingChildrenByContainer = /* @__PURE__ */ new Map();
139
- for (let i = 0; i < tuples.length; i++) {
140
- const t = tuples[i];
141
- if (!Array.isArray(t)) {
142
- continue;
143
- }
144
- const [action, path] = t;
145
- const p = normalizePath(path);
146
- if (!Array.isArray(p) || p.length < 2) {
147
- continue;
148
- }
149
- if (p[0] === "schema") {
150
- continue;
151
- }
152
- const containerPath = p.slice(0, -1);
153
- const childKey = p[p.length - 1];
154
- const key = JSON.stringify(containerPath);
155
- if (!pendingChildrenByContainer.has(key)) {
156
- pendingChildrenByContainer.set(key, /* @__PURE__ */ new Set());
157
- }
158
- if (action === "update" || action === "set") {
159
- pendingChildrenByContainer.get(key).add(childKey);
160
- }
161
- }
162
- const preferredOrderMap = /* @__PURE__ */ new Map();
163
- for (let i = 0; i < tuples.length; i++) {
164
- const t = tuples[i];
165
- if (!Array.isArray(t)) {
166
- continue;
167
- }
168
- const [action, path, value] = t;
169
- const p = normalizePath(path);
170
- if (action !== "update" || !Array.isArray(p) || p.length < 3) {
171
- continue;
172
- }
173
- if (p[0] !== "schema") {
174
- continue;
175
- }
176
- const [, type, key] = p;
177
- const containerPath = [type, key];
178
- const uses = value && Array.isArray(value.uses) ? value.uses : null;
179
- const code = value && value.code;
180
- const obj = (() => {
181
- try {
182
- return root && typeof root.getByPath === "function" ? root.getByPath(containerPath) : null;
183
- } catch {
184
- return null;
185
- }
186
- })();
187
- if (!obj) {
188
- continue;
189
- }
190
- const present = new Set(Object.keys(obj));
191
- const EXCLUDE_KEYS = /* @__PURE__ */ new Set(["__order"]);
192
- const codeKeys = extractTopLevelKeysFromCode(code);
193
- let resolved = [];
194
- const pendingKey = JSON.stringify(containerPath);
195
- const pendingChildren = pendingChildrenByContainer.get(pendingKey) || /* @__PURE__ */ new Set();
196
- const eligible = /* @__PURE__ */ new Set([...present, ...pendingChildren]);
197
- if (Array.isArray(codeKeys) && codeKeys.length) {
198
- resolved = codeKeys.filter((k) => eligible.has(k) && !EXCLUDE_KEYS.has(k));
199
- }
200
- if (Array.isArray(uses) && uses.length) {
201
- for (let u = 0; u < uses.length; u++) {
202
- const keyName = uses[u];
203
- if (eligible.has(keyName) && !EXCLUDE_KEYS.has(keyName) && !resolved.includes(keyName)) {
204
- resolved.push(keyName);
205
- }
206
- }
207
- }
208
- if (pendingChildren.size) {
209
- for (const child of pendingChildren) {
210
- if (!EXCLUDE_KEYS.has(child) && !resolved.includes(child)) {
211
- resolved.push(child);
212
- }
213
- }
214
- }
215
- if (resolved.length) {
216
- preferredOrderMap.set(JSON.stringify(containerPath), { path: containerPath, keys: resolved });
217
- }
218
- }
219
- const parents = getParentPathsFromTuples(tuples);
220
- const orders = [];
221
- const seen = /* @__PURE__ */ new Set();
222
- preferredOrderMap.forEach((v) => {
223
- const k = JSON.stringify(v.path);
224
- if (!seen.has(k)) {
225
- seen.add(k);
226
- orders.push(v);
227
- }
228
- });
229
- const fallbackOrders = computeOrdersFromState(root, parents);
230
- for (let i = 0; i < fallbackOrders.length; i++) {
231
- const v = fallbackOrders[i];
232
- const k = JSON.stringify(v.path);
233
- if (seen.has(k)) {
234
- continue;
235
- }
236
- const pending = pendingChildrenByContainer.get(k);
237
- if (pending && pending.size) {
238
- const existingKeys = v.keys;
239
- const existingSet = new Set(existingKeys);
240
- const META_KEYS = /* @__PURE__ */ new Set([
241
- "style",
242
- "class",
243
- "text",
244
- "html",
245
- "content",
246
- "data",
247
- "attr",
248
- "state",
249
- "scope",
250
- "define",
251
- "on",
252
- "extend",
253
- "extends",
254
- "childExtend",
255
- "childExtends",
256
- "children",
257
- "component",
258
- "context",
259
- "tag",
260
- "key",
261
- "__order",
262
- "if"
263
- ]);
264
- let firstMetaIndex = existingKeys.length;
265
- for (let j = 0; j < existingKeys.length; j++) {
266
- if (META_KEYS.has(existingKeys[j])) {
267
- firstMetaIndex = j;
268
- break;
269
- }
270
- }
271
- for (const child of pending) {
272
- if (existingSet.has(child)) {
273
- continue;
274
- }
275
- const insertIndex = firstMetaIndex;
276
- existingKeys.splice(insertIndex, 0, child);
277
- existingSet.add(child);
278
- firstMetaIndex++;
279
- }
280
- }
281
- seen.add(k);
282
- orders.push(v);
283
- }
284
- return orders;
285
- }
286
- export {
287
- computeOrdersForTuples,
288
- computeOrdersFromState,
289
- getParentPathsFromTuples
290
- };
@@ -1,374 +0,0 @@
1
- import { BaseService } from './BaseService.js'
2
-
3
- export class AdminService extends BaseService {
4
- // ==================== ADMIN METHODS ====================
5
-
6
- /**
7
- * Get admin users list with comprehensive filtering and search capabilities
8
- * Requires admin or super_admin global role
9
- */
10
- async getAdminUsers (params = {}) {
11
- this._requireReady('getAdminUsers')
12
-
13
- const {
14
- emails,
15
- ids,
16
- query,
17
- status,
18
- page = 1,
19
- limit = 50,
20
- sort = { field: 'createdAt', order: 'desc' }
21
- } = params
22
-
23
- const queryParams = new URLSearchParams()
24
-
25
- // Add query parameters
26
- if (emails) {
27
- queryParams.append('emails', emails)
28
- }
29
- if (ids) {
30
- queryParams.append('ids', ids)
31
- }
32
- if (query) {
33
- queryParams.append('query', query)
34
- }
35
- if (status) {
36
- queryParams.append('status', status)
37
- }
38
- if (page) {
39
- queryParams.append('page', page.toString())
40
- }
41
- if (limit) {
42
- queryParams.append('limit', limit.toString())
43
- }
44
- if (sort && sort.field) {
45
- queryParams.append('sort[field]', sort.field)
46
- queryParams.append('sort[order]', sort.order || 'desc')
47
- }
48
-
49
- const queryString = queryParams.toString()
50
- const url = `/users/admin/users${queryString ? `?${queryString}` : ''}`
51
-
52
- try {
53
- const response = await this._request(url, {
54
- method: 'GET',
55
- methodName: 'getAdminUsers'
56
- })
57
- if (response.success) {
58
- return response.data
59
- }
60
- throw new Error(response.message)
61
- } catch (error) {
62
- throw new Error(`Failed to get admin users: ${error.message}`, { cause: error })
63
- }
64
- }
65
-
66
- /**
67
- * Assign projects to a specific user
68
- * Requires admin or super_admin global role
69
- */
70
- async assignProjectsToUser (userId, options = {}) {
71
- this._requireReady('assignProjectsToUser')
72
-
73
- if (!userId) {
74
- throw new Error('User ID is required')
75
- }
76
-
77
- const { projectIds, role = 'guest' } = options
78
-
79
- const requestBody = {
80
- userId,
81
- role
82
- }
83
-
84
- // Only include projectIds if provided (otherwise assigns all projects)
85
- if (projectIds && Array.isArray(projectIds)) {
86
- requestBody.projectIds = projectIds
87
- }
88
-
89
- try {
90
- const response = await this._request('/assign-projects', {
91
- method: 'POST',
92
- body: JSON.stringify(requestBody),
93
- methodName: 'assignProjectsToUser'
94
- })
95
- if (response.success) {
96
- return response.data
97
- }
98
- throw new Error(response.message)
99
- } catch (error) {
100
- throw new Error(`Failed to assign projects to user: ${error.message}`, { cause: error })
101
- }
102
- }
103
-
104
- /**
105
- * Update user information (admin only)
106
- */
107
- async updateUser (userId, userData) {
108
- this._requireReady('updateUser')
109
- if (!userId) {
110
- throw new Error('User ID is required')
111
- }
112
- if (
113
- !userData ||
114
- typeof userData !== 'object' ||
115
- Object.keys(userData).length === 0
116
- ) {
117
- throw new Error('userData must be a non-empty object')
118
- }
119
-
120
- try {
121
- const response = await this._request(`/users/${userId}`, {
122
- method: 'PATCH',
123
- body: JSON.stringify(userData),
124
- methodName: 'updateUser'
125
- })
126
- if (response.success) {
127
- return response.data
128
- }
129
- throw new Error(response.message)
130
- } catch (error) {
131
- // Surface duplicate username conflict nicely
132
- if (error.message?.includes('Duplicate')) {
133
- throw new Error('Username already exists')
134
- }
135
- throw new Error(`Failed to update user: ${error.message}`, { cause: error })
136
- }
137
- }
138
-
139
- // ==================== ADMIN HELPER METHODS ====================
140
-
141
- /**
142
- * Helper method for admin users search
143
- */
144
- async searchAdminUsers (searchQuery, options = {}) {
145
- return await this.getAdminUsers({
146
- query: searchQuery,
147
- ...options
148
- })
149
- }
150
-
151
- /**
152
- * Helper method to get admin users by email list
153
- */
154
- async getAdminUsersByEmails (emails, options = {}) {
155
- const emailList = Array.isArray(emails) ? emails.join(',') : emails
156
- return await this.getAdminUsers({
157
- emails: emailList,
158
- ...options
159
- })
160
- }
161
-
162
- /**
163
- * Helper method to get admin users by ID list
164
- */
165
- async getAdminUsersByIds (ids, options = {}) {
166
- const idList = Array.isArray(ids) ? ids.join(',') : ids
167
- return await this.getAdminUsers({
168
- ids: idList,
169
- ...options
170
- })
171
- }
172
-
173
- /**
174
- * Helper method to assign specific projects to a user with a specific role
175
- */
176
- async assignSpecificProjectsToUser (userId, projectIds, role = 'guest') {
177
- if (!Array.isArray(projectIds) || projectIds.length === 0) {
178
- throw new Error('Project IDs must be a non-empty array')
179
- }
180
-
181
- return await this.assignProjectsToUser(userId, {
182
- projectIds,
183
- role
184
- })
185
- }
186
-
187
- /**
188
- * Helper method to assign all projects to a user with a specific role
189
- */
190
- async assignAllProjectsToUser (userId, role = 'guest') {
191
- return await this.assignProjectsToUser(userId, {
192
- role
193
- })
194
- }
195
-
196
- /**
197
- * Helper method to validate user data for updates
198
- */
199
- validateUserData (userData) {
200
- const errors = []
201
-
202
- if (!userData || typeof userData !== 'object') {
203
- errors.push('User data must be an object')
204
- return { isValid: false, errors }
205
- }
206
-
207
- // Validate email if provided
208
- if (userData.email && typeof userData.email !== 'string') {
209
- errors.push('Email must be a string')
210
- } else if (userData.email && !this._isValidEmail(userData.email)) {
211
- errors.push('Email must be a valid email address')
212
- }
213
-
214
- // Validate username if provided
215
- if (userData.username && typeof userData.username !== 'string') {
216
- errors.push('Username must be a string')
217
- } else if (userData.username && userData.username.length < 3) {
218
- errors.push('Username must be at least 3 characters long')
219
- }
220
-
221
- // Validate role if provided
222
- if (userData.role && !['admin', 'user', 'guest'].includes(userData.role)) {
223
- errors.push('Role must be one of: admin, user, guest')
224
- }
225
-
226
- // Validate status if provided
227
- if (userData.status && !['active', 'inactive', 'suspended'].includes(userData.status)) {
228
- errors.push('Status must be one of: active, inactive, suspended')
229
- }
230
-
231
- return {
232
- isValid: errors.length === 0,
233
- errors
234
- }
235
- }
236
-
237
- /**
238
- * Helper method to update user with validation
239
- */
240
- async updateUserWithValidation (userId, userData) {
241
- const validation = this.validateUserData(userData)
242
- if (!validation.isValid) {
243
- throw new Error(`Validation failed: ${validation.errors.join(', ')}`)
244
- }
245
-
246
- return await this.updateUser(userId, userData)
247
- }
248
-
249
- /**
250
- * Helper method to get user statistics
251
- */
252
- async getUserStats () {
253
- try {
254
- const users = await this.getAdminUsers({ limit: 1000 })
255
-
256
- const stats = {
257
- total: users.length,
258
- active: 0,
259
- inactive: 0,
260
- suspended: 0,
261
- admins: 0,
262
- users: 0,
263
- guests: 0
264
- }
265
-
266
- users.forEach(user => {
267
- if (user.status === 'active') {stats.active++}
268
- if (user.status === 'inactive') {stats.inactive++}
269
- if (user.status === 'suspended') {stats.suspended++}
270
- if (user.role === 'admin') {stats.admins++}
271
- if (user.role === 'user') {stats.users++}
272
- if (user.role === 'guest') {stats.guests++}
273
- })
274
-
275
- return stats
276
- } catch (error) {
277
- throw new Error(`Failed to get user stats: ${error.message}`, { cause: error })
278
- }
279
- }
280
-
281
- /**
282
- * Helper method to bulk update users
283
- */
284
- async bulkUpdateUsers (userUpdates) {
285
- if (!Array.isArray(userUpdates) || userUpdates.length === 0) {
286
- throw new Error('User updates must be a non-empty array')
287
- }
288
-
289
- const updatePromises = userUpdates.map(async update => {
290
- try {
291
- const result = await this.updateUser(update.userId, update.userData)
292
- return {
293
- userId: update.userId,
294
- success: true,
295
- data: result
296
- }
297
- } catch (error) {
298
- return {
299
- userId: update.userId,
300
- success: false,
301
- error: error.message
302
- }
303
- }
304
- })
305
-
306
- const results = await Promise.all(updatePromises)
307
-
308
- return {
309
- total: results.length,
310
- successful: results.filter(r => r.success).length,
311
- failed: results.filter(r => !r.success).length,
312
- results
313
- }
314
- }
315
-
316
- /**
317
- * Helper method to get users by role
318
- */
319
- async getUsersByRole (role, options = {}) {
320
- const users = await this.getAdminUsers(options)
321
- return users.filter(user => user.role === role)
322
- }
323
-
324
- /**
325
- * Helper method to get users by status
326
- */
327
- async getUsersByStatus (status, options = {}) {
328
- const users = await this.getAdminUsers(options)
329
- return users.filter(user => user.status === status)
330
- }
331
-
332
- /**
333
- * Helper method to activate a user
334
- */
335
- async activateUser (userId) {
336
- return await this.updateUser(userId, { status: 'active' })
337
- }
338
-
339
- /**
340
- * Helper method to deactivate a user
341
- */
342
- async deactivateUser (userId) {
343
- return await this.updateUser(userId, { status: 'inactive' })
344
- }
345
-
346
- /**
347
- * Helper method to suspend a user
348
- */
349
- async suspendUser (userId) {
350
- return await this.updateUser(userId, { status: 'suspended' })
351
- }
352
-
353
- /**
354
- * Helper method to promote user to admin
355
- */
356
- async promoteToAdmin (userId) {
357
- return await this.updateUser(userId, { role: 'admin' })
358
- }
359
-
360
- /**
361
- * Helper method to demote user from admin
362
- */
363
- async demoteFromAdmin (userId) {
364
- return await this.updateUser(userId, { role: 'user' })
365
- }
366
-
367
- /**
368
- * Private helper to validate email format
369
- */
370
- _isValidEmail (email) {
371
- const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/u
372
- return emailRegex.test(email)
373
- }
374
- }