@symbo.ls/sdk 2.32.11 → 2.32.13

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 (50) hide show
  1. package/README.md +141 -0
  2. package/dist/cjs/config/environment.js +18 -7
  3. package/dist/cjs/index.js +38 -12
  4. package/dist/cjs/services/BaseService.js +46 -0
  5. package/dist/cjs/services/DnsService.js +6 -5
  6. package/dist/cjs/services/TrackingService.js +661 -0
  7. package/dist/cjs/services/index.js +5 -5
  8. package/dist/cjs/utils/changePreprocessor.js +8 -1
  9. package/dist/cjs/utils/services.js +27 -3
  10. package/dist/esm/config/environment.js +18 -7
  11. package/dist/esm/index.js +20747 -5912
  12. package/dist/esm/services/AdminService.js +64 -7
  13. package/dist/esm/services/AuthService.js +64 -7
  14. package/dist/esm/services/BaseService.js +64 -7
  15. package/dist/esm/services/BranchService.js +64 -7
  16. package/dist/esm/services/CollabService.js +72 -8
  17. package/dist/esm/services/DnsService.js +70 -12
  18. package/dist/esm/services/FileService.js +64 -7
  19. package/dist/esm/services/PaymentService.js +64 -7
  20. package/dist/esm/services/PlanService.js +64 -7
  21. package/dist/esm/services/ProjectService.js +72 -8
  22. package/dist/esm/services/PullRequestService.js +64 -7
  23. package/dist/esm/services/ScreenshotService.js +64 -7
  24. package/dist/esm/services/SubscriptionService.js +64 -7
  25. package/dist/esm/services/TrackingService.js +18321 -0
  26. package/dist/esm/services/index.js +20667 -5882
  27. package/dist/esm/utils/CollabClient.js +18 -7
  28. package/dist/esm/utils/changePreprocessor.js +8 -1
  29. package/dist/esm/utils/services.js +27 -3
  30. package/dist/node/config/environment.js +18 -7
  31. package/dist/node/index.js +42 -16
  32. package/dist/node/services/BaseService.js +46 -0
  33. package/dist/node/services/DnsService.js +6 -5
  34. package/dist/node/services/TrackingService.js +632 -0
  35. package/dist/node/services/index.js +5 -5
  36. package/dist/node/utils/changePreprocessor.js +8 -1
  37. package/dist/node/utils/services.js +27 -3
  38. package/package.json +8 -6
  39. package/src/config/environment.js +19 -11
  40. package/src/index.js +44 -14
  41. package/src/services/BaseService.js +43 -0
  42. package/src/services/DnsService.js +5 -5
  43. package/src/services/TrackingService.js +853 -0
  44. package/src/services/index.js +6 -5
  45. package/src/utils/changePreprocessor.js +25 -1
  46. package/src/utils/services.js +28 -4
  47. package/dist/cjs/services/CoreService.js +0 -2818
  48. package/dist/esm/services/CoreService.js +0 -3513
  49. package/dist/node/services/CoreService.js +0 -2789
  50. package/src/services/CoreService.js +0 -3208
@@ -1,2789 +0,0 @@
1
- import { BaseService } from "./BaseService.js";
2
- import environment from "../config/environment.js";
3
- import { getTokenManager } from "../utils/TokenManager.js";
4
- class CoreService extends BaseService {
5
- constructor(config) {
6
- super(config);
7
- this._client = null;
8
- this._initialized = false;
9
- this._apiUrl = null;
10
- this._tokenManager = null;
11
- }
12
- init({ context }) {
13
- try {
14
- const { appKey, authToken } = context || this._context;
15
- this._apiUrl = environment.apiUrl;
16
- if (!this._apiUrl) {
17
- throw new Error("Core service base URL not configured");
18
- }
19
- this._tokenManager = getTokenManager({
20
- apiUrl: this._apiUrl,
21
- onTokenRefresh: (tokens) => {
22
- this.updateContext({ authToken: tokens.accessToken });
23
- },
24
- onTokenExpired: () => {
25
- this.updateContext({ authToken: null });
26
- },
27
- onTokenError: (error) => {
28
- console.error("Token management error:", error);
29
- }
30
- });
31
- if (authToken && !this._tokenManager.hasTokens()) {
32
- this._tokenManager.setTokens({ access_token: authToken });
33
- }
34
- this._info = {
35
- config: {
36
- apiUrl: this._apiUrl,
37
- appKey: appKey ? `${appKey.substr(0, 4)}...${appKey.substr(-4)}` : null,
38
- hasToken: Boolean(authToken)
39
- }
40
- };
41
- this._initialized = true;
42
- this._setReady();
43
- } catch (error) {
44
- this._setError(error);
45
- throw error;
46
- }
47
- }
48
- // Helper to check if method requires initialization
49
- _requiresInit(methodName) {
50
- const noInitMethods = /* @__PURE__ */ new Set([
51
- "register",
52
- "login",
53
- "googleAuth",
54
- "googleAuthCallback",
55
- "githubAuth",
56
- "requestPasswordReset",
57
- "confirmPasswordReset",
58
- "confirmRegistration",
59
- "verifyEmail",
60
- "listPublicProjects",
61
- "getPublicProject",
62
- "getHealthStatus"
63
- ]);
64
- return !noInitMethods.has(methodName);
65
- }
66
- // Override _requireReady to be more flexible
67
- _requireReady(methodName) {
68
- if (this._requiresInit(methodName) && !this._initialized) {
69
- throw new Error("Core service not initialized");
70
- }
71
- }
72
- // Debug method to check token status
73
- getTokenDebugInfo() {
74
- if (!this._tokenManager) {
75
- return {
76
- tokenManagerExists: false,
77
- error: "TokenManager not initialized"
78
- };
79
- }
80
- const tokenStatus = this._tokenManager.getTokenStatus();
81
- const { tokens } = this._tokenManager;
82
- return {
83
- tokenManagerExists: true,
84
- tokenStatus,
85
- hasAccessToken: Boolean(tokens.accessToken),
86
- hasRefreshToken: Boolean(tokens.refreshToken),
87
- accessTokenPreview: tokens.accessToken ? `${tokens.accessToken.substring(0, 20)}...` : null,
88
- expiresAt: tokens.expiresAt,
89
- timeToExpiry: tokenStatus.timeToExpiry,
90
- authHeader: this._tokenManager.getAuthHeader()
91
- };
92
- }
93
- // Helper method to check if user is authenticated
94
- isAuthenticated() {
95
- if (!this._tokenManager) {
96
- return false;
97
- }
98
- return this._tokenManager.hasTokens();
99
- }
100
- // Helper method to check if user has valid tokens
101
- hasValidTokens() {
102
- if (!this._tokenManager) {
103
- return false;
104
- }
105
- return this._tokenManager.hasTokens() && this._tokenManager.isAccessTokenValid();
106
- }
107
- // Helper method to make HTTP requests
108
- async _request(endpoint, options = {}) {
109
- const url = `${this._apiUrl}/core${endpoint}`;
110
- const defaultHeaders = {};
111
- if (!(options.body instanceof FormData)) {
112
- defaultHeaders["Content-Type"] = "application/json";
113
- }
114
- if (this._requiresInit(options.methodName) && this._tokenManager) {
115
- try {
116
- const validToken = await this._tokenManager.ensureValidToken();
117
- if (validToken) {
118
- const authHeader = this._tokenManager.getAuthHeader();
119
- if (authHeader) {
120
- defaultHeaders.Authorization = authHeader;
121
- }
122
- }
123
- } catch (error) {
124
- console.warn(
125
- "Token management failed, proceeding without authentication:",
126
- error
127
- );
128
- }
129
- } else if (this._requiresInit(options.methodName)) {
130
- const { authToken } = this._context;
131
- if (authToken) {
132
- defaultHeaders.Authorization = `Bearer ${authToken}`;
133
- }
134
- }
135
- try {
136
- const response = await fetch(url, {
137
- ...options,
138
- headers: {
139
- ...defaultHeaders,
140
- ...options.headers
141
- }
142
- });
143
- if (!response.ok) {
144
- let error = {
145
- message: `HTTP ${response.status}: ${response.statusText}`
146
- };
147
- try {
148
- error = await response.json();
149
- } catch {
150
- }
151
- throw new Error(error.message || error.error || "Request failed", { cause: error });
152
- }
153
- return response.status === 204 ? null : response.json();
154
- } catch (error) {
155
- throw new Error(`Request failed: ${error.message}`, { cause: error });
156
- }
157
- }
158
- // ==================== AUTH METHODS ====================
159
- async register(userData) {
160
- try {
161
- const response = await this._request("/auth/register", {
162
- method: "POST",
163
- body: JSON.stringify(userData),
164
- methodName: "register"
165
- });
166
- if (response.success) {
167
- return response.data;
168
- }
169
- throw new Error(response.message);
170
- } catch (error) {
171
- throw new Error(`Registration failed: ${error.message}`, { cause: error });
172
- }
173
- }
174
- async login(email, password) {
175
- var _a;
176
- try {
177
- const response = await this._request("/auth/login", {
178
- method: "POST",
179
- body: JSON.stringify({ email, password }),
180
- methodName: "login"
181
- });
182
- if (response.success && response.data && response.data.tokens) {
183
- const { tokens } = response.data;
184
- const tokenData = {
185
- access_token: tokens.accessToken,
186
- refresh_token: tokens.refreshToken,
187
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
188
- token_type: "Bearer"
189
- };
190
- if (this._tokenManager) {
191
- this._tokenManager.setTokens(tokenData);
192
- }
193
- this.updateContext({ authToken: tokens.accessToken });
194
- }
195
- if (response.success) {
196
- return response.data;
197
- }
198
- throw new Error(response.message);
199
- } catch (error) {
200
- throw new Error(`Login failed: ${error.message}`, { cause: error });
201
- }
202
- }
203
- async logout() {
204
- this._requireReady("logout");
205
- try {
206
- await this._request("/auth/logout", {
207
- method: "POST",
208
- methodName: "logout"
209
- });
210
- if (this._tokenManager) {
211
- this._tokenManager.clearTokens();
212
- }
213
- this.updateContext({ authToken: null });
214
- } catch (error) {
215
- if (this._tokenManager) {
216
- this._tokenManager.clearTokens();
217
- }
218
- this.updateContext({ authToken: null });
219
- throw new Error(`Logout failed: ${error.message}`, { cause: error });
220
- }
221
- }
222
- async refreshToken(refreshToken) {
223
- try {
224
- const response = await this._request("/auth/refresh", {
225
- method: "POST",
226
- body: JSON.stringify({ refreshToken }),
227
- methodName: "refreshToken"
228
- });
229
- if (response.success) {
230
- return response.data;
231
- }
232
- throw new Error(response.message);
233
- } catch (error) {
234
- throw new Error(`Token refresh failed: ${error.message}`, { cause: error });
235
- }
236
- }
237
- async googleAuth(idToken, inviteToken = null) {
238
- var _a;
239
- try {
240
- const payload = { idToken };
241
- if (inviteToken) {
242
- payload.inviteToken = inviteToken;
243
- }
244
- const response = await this._request("/auth/google", {
245
- method: "POST",
246
- body: JSON.stringify(payload),
247
- methodName: "googleAuth"
248
- });
249
- if (response.success && response.data && response.data.tokens) {
250
- const { tokens } = response.data;
251
- const tokenData = {
252
- access_token: tokens.accessToken,
253
- refresh_token: tokens.refreshToken,
254
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
255
- token_type: "Bearer"
256
- };
257
- if (this._tokenManager) {
258
- this._tokenManager.setTokens(tokenData);
259
- }
260
- this.updateContext({ authToken: tokens.accessToken });
261
- }
262
- if (response.success) {
263
- return response.data;
264
- }
265
- throw new Error(response.message);
266
- } catch (error) {
267
- throw new Error(`Google auth failed: ${error.message}`, { cause: error });
268
- }
269
- }
270
- async githubAuth(code, inviteToken = null) {
271
- var _a;
272
- try {
273
- const payload = { code };
274
- if (inviteToken) {
275
- payload.inviteToken = inviteToken;
276
- }
277
- const response = await this._request("/auth/github", {
278
- method: "POST",
279
- body: JSON.stringify(payload),
280
- methodName: "githubAuth"
281
- });
282
- if (response.success && response.data && response.data.tokens) {
283
- const { tokens } = response.data;
284
- const tokenData = {
285
- access_token: tokens.accessToken,
286
- refresh_token: tokens.refreshToken,
287
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
288
- token_type: "Bearer"
289
- };
290
- if (this._tokenManager) {
291
- this._tokenManager.setTokens(tokenData);
292
- }
293
- this.updateContext({ authToken: tokens.accessToken });
294
- }
295
- if (response.success) {
296
- return response.data;
297
- }
298
- throw new Error(response.message);
299
- } catch (error) {
300
- throw new Error(`GitHub auth failed: ${error.message}`, { cause: error });
301
- }
302
- }
303
- async googleAuthCallback(code, redirectUri, inviteToken = null) {
304
- var _a;
305
- try {
306
- const body = { code, redirectUri };
307
- if (inviteToken) {
308
- body.inviteToken = inviteToken;
309
- }
310
- const response = await this._request("/auth/google/callback", {
311
- method: "POST",
312
- body: JSON.stringify(body),
313
- methodName: "googleAuthCallback"
314
- });
315
- if (response.success && response.data && response.data.tokens) {
316
- const { tokens } = response.data;
317
- const tokenData = {
318
- access_token: tokens.accessToken,
319
- refresh_token: tokens.refreshToken,
320
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
321
- token_type: "Bearer"
322
- };
323
- if (this._tokenManager) {
324
- this._tokenManager.setTokens(tokenData);
325
- }
326
- this.updateContext({ authToken: tokens.accessToken });
327
- }
328
- if (response.success) {
329
- return response.data;
330
- }
331
- throw new Error(response.message);
332
- } catch (error) {
333
- throw new Error(`Google auth callback failed: ${error.message}`, { cause: error });
334
- }
335
- }
336
- async requestPasswordReset(email) {
337
- try {
338
- const response = await this._request("/auth/request-password-reset", {
339
- method: "POST",
340
- body: JSON.stringify({ email }),
341
- methodName: "requestPasswordReset"
342
- });
343
- if (response.success) {
344
- return response.data;
345
- }
346
- throw new Error(response.message);
347
- } catch (error) {
348
- throw new Error(`Password reset request failed: ${error.message}`, { cause: error });
349
- }
350
- }
351
- async confirmPasswordReset(token, password) {
352
- try {
353
- const response = await this._request("/auth/reset-password-confirm", {
354
- method: "POST",
355
- body: JSON.stringify({ token, password }),
356
- methodName: "confirmPasswordReset"
357
- });
358
- if (response.success) {
359
- return response.data;
360
- }
361
- throw new Error(response.message);
362
- } catch (error) {
363
- throw new Error(`Password reset confirmation failed: ${error.message}`, { cause: error });
364
- }
365
- }
366
- async confirmRegistration(token) {
367
- try {
368
- const response = await this._request("/auth/register-confirmation", {
369
- method: "POST",
370
- body: JSON.stringify({ token }),
371
- methodName: "confirmRegistration"
372
- });
373
- if (response.success) {
374
- return response.data;
375
- }
376
- throw new Error(response.message);
377
- } catch (error) {
378
- throw new Error(`Registration confirmation failed: ${error.message}`, { cause: error });
379
- }
380
- }
381
- async requestPasswordChange() {
382
- this._requireReady("requestPasswordChange");
383
- try {
384
- const response = await this._request("/auth/request-password-change", {
385
- method: "POST",
386
- methodName: "requestPasswordChange"
387
- });
388
- if (response.success) {
389
- return response.data;
390
- }
391
- throw new Error(response.message);
392
- } catch (error) {
393
- throw new Error(`Password change request failed: ${error.message}`, { cause: error });
394
- }
395
- }
396
- async confirmPasswordChange(currentPassword, newPassword, code) {
397
- this._requireReady("confirmPasswordChange");
398
- try {
399
- const response = await this._request("/auth/confirm-password-change", {
400
- method: "POST",
401
- body: JSON.stringify({ currentPassword, newPassword, code }),
402
- methodName: "confirmPasswordChange"
403
- });
404
- if (response.success) {
405
- return response.data;
406
- }
407
- throw new Error(response.message);
408
- } catch (error) {
409
- throw new Error(`Password change confirmation failed: ${error.message}`, { cause: error });
410
- }
411
- }
412
- async getMe() {
413
- this._requireReady("getMe");
414
- try {
415
- const response = await this._request("/auth/me", {
416
- method: "GET",
417
- methodName: "getMe"
418
- });
419
- if (response.success) {
420
- return response.data;
421
- }
422
- throw new Error(response.message);
423
- } catch (error) {
424
- throw new Error(`Failed to get user profile: ${error.message}`, { cause: error });
425
- }
426
- }
427
- /**
428
- * Get stored authentication state (backward compatibility method)
429
- * Replaces AuthService.getStoredAuthState()
430
- */
431
- async getStoredAuthState() {
432
- try {
433
- if (!this._tokenManager) {
434
- return {
435
- userId: false,
436
- authToken: false
437
- };
438
- }
439
- const tokenStatus = this._tokenManager.getTokenStatus();
440
- if (!tokenStatus.hasTokens) {
441
- return {
442
- userId: false,
443
- authToken: false
444
- };
445
- }
446
- if (!tokenStatus.isValid && tokenStatus.hasRefreshToken) {
447
- try {
448
- await this._tokenManager.ensureValidToken();
449
- } catch (error) {
450
- console.warn("[CoreService] Token refresh failed:", error.message);
451
- if (error.message.includes("401") || error.message.includes("403") || error.message.includes("invalid") || error.message.includes("expired")) {
452
- this._tokenManager.clearTokens();
453
- return {
454
- userId: false,
455
- authToken: false,
456
- error: `Authentication failed: ${error.message}`
457
- };
458
- }
459
- return {
460
- userId: false,
461
- authToken: this._tokenManager.getAccessToken(),
462
- error: `Network error during token refresh: ${error.message}`,
463
- hasTokens: true
464
- };
465
- }
466
- }
467
- const currentAccessToken = this._tokenManager.getAccessToken();
468
- if (!currentAccessToken) {
469
- return {
470
- userId: false,
471
- authToken: false
472
- };
473
- }
474
- try {
475
- const currentUser = await this.getMe();
476
- return {
477
- userId: currentUser.user.id,
478
- authToken: currentAccessToken,
479
- ...currentUser,
480
- error: null
481
- };
482
- } catch (error) {
483
- console.warn("[CoreService] Failed to get user data:", error.message);
484
- if (error.message.includes("401") || error.message.includes("403")) {
485
- this._tokenManager.clearTokens();
486
- return {
487
- userId: false,
488
- authToken: false,
489
- error: `Authentication failed: ${error.message}`
490
- };
491
- }
492
- return {
493
- userId: false,
494
- authToken: currentAccessToken,
495
- error: `Failed to get user data: ${error.message}`,
496
- hasTokens: true
497
- };
498
- }
499
- } catch (error) {
500
- console.error(
501
- "[CoreService] Unexpected error in getStoredAuthState:",
502
- error
503
- );
504
- return {
505
- userId: false,
506
- authToken: false,
507
- error: `Failed to get stored auth state: ${error.message}`
508
- };
509
- }
510
- }
511
- // ==================== USER METHODS ====================
512
- async getUserProfile() {
513
- this._requireReady("getUserProfile");
514
- try {
515
- const response = await this._request("/users/profile", {
516
- method: "GET",
517
- methodName: "getUserProfile"
518
- });
519
- if (response.success) {
520
- return response.data;
521
- }
522
- throw new Error(response.message);
523
- } catch (error) {
524
- throw new Error(`Failed to get user profile: ${error.message}`);
525
- }
526
- }
527
- async updateUserProfile(profileData) {
528
- this._requireReady("updateUserProfile");
529
- try {
530
- const response = await this._request("/users/profile", {
531
- method: "PATCH",
532
- body: JSON.stringify(profileData),
533
- methodName: "updateUserProfile"
534
- });
535
- if (response.success) {
536
- return response.data;
537
- }
538
- throw new Error(response.message);
539
- } catch (error) {
540
- throw new Error(`Failed to update user profile: ${error.message}`, { cause: error });
541
- }
542
- }
543
- async getUserProjects() {
544
- this._requireReady("getUserProjects");
545
- try {
546
- const response = await this._request("/users/projects", {
547
- method: "GET",
548
- methodName: "getUserProjects"
549
- });
550
- if (response.success) {
551
- return response.data.map((project) => ({
552
- ...project,
553
- ...project.icon && {
554
- icon: {
555
- src: `${this._apiUrl}/core/files/public/${project.icon.id}/download`,
556
- ...project.icon
557
- }
558
- }
559
- }));
560
- }
561
- throw new Error(response.message);
562
- } catch (error) {
563
- throw new Error(`Failed to get user projects: ${error.message}`, { cause: error });
564
- }
565
- }
566
- async getUser(userId) {
567
- this._requireReady("getUser");
568
- if (!userId) {
569
- throw new Error("User ID is required");
570
- }
571
- try {
572
- const response = await this._request(`/users/${userId}`, {
573
- method: "GET",
574
- methodName: "getUser"
575
- });
576
- if (response.success) {
577
- return response.data;
578
- }
579
- throw new Error(response.message);
580
- } catch (error) {
581
- throw new Error(`Failed to get user: ${error.message}`, { cause: error });
582
- }
583
- }
584
- async getUserByEmail(email) {
585
- this._requireReady("getUserByEmail");
586
- if (!email) {
587
- throw new Error("Email is required");
588
- }
589
- try {
590
- const response = await this._request(`/auth/user?email=${email}`, {
591
- method: "GET",
592
- methodName: "getUserByEmail"
593
- });
594
- if (response.success) {
595
- return response.data.user;
596
- }
597
- throw new Error(response.message);
598
- } catch (error) {
599
- throw new Error(`Failed to get user by email: ${error.message}`, { cause: error });
600
- }
601
- }
602
- // ==================== PROJECT METHODS ====================
603
- async createProject(projectData) {
604
- this._requireReady("createProject");
605
- try {
606
- const response = await this._request("/projects", {
607
- method: "POST",
608
- body: JSON.stringify(projectData),
609
- methodName: "createProject"
610
- });
611
- if (response.success) {
612
- return response.data;
613
- }
614
- throw new Error(response.message);
615
- } catch (error) {
616
- throw new Error(`Failed to create project: ${error.message}`);
617
- }
618
- }
619
- async getProjects(params = {}) {
620
- this._requireReady("getProjects");
621
- try {
622
- const queryParams = new URLSearchParams();
623
- Object.keys(params).forEach((key) => {
624
- if (params[key] != null) {
625
- queryParams.append(key, params[key]);
626
- }
627
- });
628
- const queryString = queryParams.toString();
629
- const url = `/projects${queryString ? `?${queryString}` : ""}`;
630
- const response = await this._request(url, {
631
- method: "GET",
632
- methodName: "getProjects"
633
- });
634
- if (response.success) {
635
- return response;
636
- }
637
- throw new Error(response.message);
638
- } catch (error) {
639
- throw new Error(`Failed to get projects: ${error.message}`);
640
- }
641
- }
642
- /**
643
- * Alias for getProjects for consistency with API naming
644
- */
645
- async listProjects(params = {}) {
646
- return await this.getProjects(params);
647
- }
648
- /**
649
- * List only public projects (no authentication required)
650
- */
651
- async listPublicProjects(params = {}) {
652
- try {
653
- const queryParams = new URLSearchParams();
654
- Object.keys(params).forEach((key) => {
655
- if (params[key] != null) {
656
- queryParams.append(key, params[key]);
657
- }
658
- });
659
- const queryString = queryParams.toString();
660
- const url = `/projects/public${queryString ? `?${queryString}` : ""}`;
661
- const response = await this._request(url, {
662
- method: "GET",
663
- methodName: "listPublicProjects"
664
- });
665
- if (response.success) {
666
- return response.data;
667
- }
668
- throw new Error(response.message);
669
- } catch (error) {
670
- throw new Error(`Failed to list public projects: ${error.message}`);
671
- }
672
- }
673
- async getProject(projectId) {
674
- this._requireReady("getProject");
675
- if (!projectId) {
676
- throw new Error("Project ID is required");
677
- }
678
- try {
679
- const response = await this._request(`/projects/${projectId}`, {
680
- method: "GET",
681
- methodName: "getProject"
682
- });
683
- if (response.success) {
684
- const iconSrc = response.data.icon ? `${this._apiUrl}/core/files/public/${response.data.icon.id}/download` : null;
685
- return {
686
- ...response.data,
687
- icon: { src: iconSrc, ...response.data.icon }
688
- };
689
- }
690
- throw new Error(response.message);
691
- } catch (error) {
692
- throw new Error(`Failed to get project: ${error.message}`);
693
- }
694
- }
695
- /**
696
- * Get a public project by ID (no authentication required)
697
- * Corresponds to router.get('/public/:projectId', ProjectController.getPublicProject)
698
- */
699
- async getPublicProject(projectId) {
700
- if (!projectId) {
701
- throw new Error("Project ID is required");
702
- }
703
- try {
704
- const response = await this._request(`/projects/public/${projectId}`, {
705
- method: "GET",
706
- methodName: "getPublicProject"
707
- });
708
- if (response.success) {
709
- const iconSrc = response.data.icon ? `${this._apiUrl}/core/files/public/${response.data.icon.id}/download` : null;
710
- return {
711
- ...response.data,
712
- icon: { src: iconSrc, ...response.data.icon }
713
- };
714
- }
715
- throw new Error(response.message);
716
- } catch (error) {
717
- throw new Error(`Failed to get public project: ${error.message}`);
718
- }
719
- }
720
- async getProjectByKey(key) {
721
- this._requireReady("getProjectByKey");
722
- if (!key) {
723
- throw new Error("Project key is required");
724
- }
725
- try {
726
- const response = await this._request(`/projects/key/${key}`, {
727
- method: "GET",
728
- methodName: "getProjectByKey"
729
- });
730
- if (response.success) {
731
- const iconSrc = response.data.icon ? `${this._apiUrl}/core/files/public/${response.data.icon.id}/download` : null;
732
- return {
733
- ...response.data,
734
- icon: { src: iconSrc, ...response.data.icon }
735
- };
736
- }
737
- throw new Error(response.message);
738
- } catch (error) {
739
- throw new Error(`Failed to get project by key: ${error.message}`);
740
- }
741
- }
742
- /**
743
- * Get current project data by key (no project ID required)
744
- */
745
- async getProjectDataByKey(key, options = {}) {
746
- this._requireReady("getProjectDataByKey");
747
- if (!key) {
748
- throw new Error("Project key is required");
749
- }
750
- const {
751
- branch = "main",
752
- version = "latest",
753
- includeHistory = false
754
- } = options;
755
- const queryParams = new URLSearchParams({
756
- branch,
757
- version,
758
- includeHistory: includeHistory.toString()
759
- }).toString();
760
- try {
761
- const response = await this._request(
762
- `/projects/key/${key}/data?${queryParams}`,
763
- {
764
- method: "GET",
765
- methodName: "getProjectDataByKey"
766
- }
767
- );
768
- if (response.success) {
769
- return response.data;
770
- }
771
- throw new Error(response.message);
772
- } catch (error) {
773
- throw new Error(`Failed to get project data by key: ${error.message}`);
774
- }
775
- }
776
- async updateProject(projectId, data) {
777
- this._requireReady("updateProject");
778
- if (!projectId) {
779
- throw new Error("Project ID is required");
780
- }
781
- try {
782
- const response = await this._request(`/projects/${projectId}`, {
783
- method: "PATCH",
784
- body: JSON.stringify(data),
785
- methodName: "updateProject"
786
- });
787
- if (response.success) {
788
- return response.data;
789
- }
790
- throw new Error(response.message);
791
- } catch (error) {
792
- throw new Error(`Failed to update project: ${error.message}`);
793
- }
794
- }
795
- async updateProjectComponents(projectId, components) {
796
- this._requireReady("updateProjectComponents");
797
- if (!projectId) {
798
- throw new Error("Project ID is required");
799
- }
800
- try {
801
- const response = await this._request(
802
- `/projects/${projectId}/components`,
803
- {
804
- method: "PATCH",
805
- body: JSON.stringify({ components }),
806
- methodName: "updateProjectComponents"
807
- }
808
- );
809
- if (response.success) {
810
- return response.data;
811
- }
812
- throw new Error(response.message);
813
- } catch (error) {
814
- throw new Error(`Failed to update project components: ${error.message}`);
815
- }
816
- }
817
- async updateProjectSettings(projectId, settings) {
818
- this._requireReady("updateProjectSettings");
819
- if (!projectId) {
820
- throw new Error("Project ID is required");
821
- }
822
- try {
823
- const response = await this._request(`/projects/${projectId}/settings`, {
824
- method: "PATCH",
825
- body: JSON.stringify({ settings }),
826
- methodName: "updateProjectSettings"
827
- });
828
- if (response.success) {
829
- return response.data;
830
- }
831
- throw new Error(response.message);
832
- } catch (error) {
833
- throw new Error(`Failed to update project settings: ${error.message}`);
834
- }
835
- }
836
- async updateProjectName(projectId, name) {
837
- this._requireReady("updateProjectName");
838
- if (!projectId) {
839
- throw new Error("Project ID is required");
840
- }
841
- try {
842
- const response = await this._request(`/projects/${projectId}`, {
843
- method: "PATCH",
844
- body: JSON.stringify({ name }),
845
- methodName: "updateProjectName"
846
- });
847
- if (response.success) {
848
- return response.data;
849
- }
850
- throw new Error(response.message);
851
- } catch (error) {
852
- throw new Error(`Failed to update project name: ${error.message}`);
853
- }
854
- }
855
- async updateProjectPackage(projectId, pkg) {
856
- this._requireReady("updateProjectPackage");
857
- if (!projectId) {
858
- throw new Error("Project ID is required");
859
- }
860
- try {
861
- const response = await this._request(`/projects/${projectId}/package`, {
862
- method: "PATCH",
863
- body: JSON.stringify({ package: pkg }),
864
- methodName: "updateProjectPackage"
865
- });
866
- if (response.success) {
867
- return response.data;
868
- }
869
- throw new Error(response.message);
870
- } catch (error) {
871
- throw new Error(`Failed to update project package: ${error.message}`);
872
- }
873
- }
874
- async duplicateProject(projectId, newName, newKey, targetUserId) {
875
- this._requireReady("duplicateProject");
876
- if (!projectId) {
877
- throw new Error("Project ID is required");
878
- }
879
- try {
880
- const response = await this._request(`/projects/${projectId}/duplicate`, {
881
- method: "POST",
882
- body: JSON.stringify({ name: newName, key: newKey, targetUserId }),
883
- methodName: "duplicateProject"
884
- });
885
- if (response.success) {
886
- return response.data;
887
- }
888
- throw new Error(response.message);
889
- } catch (error) {
890
- throw new Error(`Failed to duplicate project: ${error.message}`);
891
- }
892
- }
893
- async removeProject(projectId) {
894
- this._requireReady("removeProject");
895
- if (!projectId) {
896
- throw new Error("Project ID is required");
897
- }
898
- try {
899
- const response = await this._request(`/projects/${projectId}`, {
900
- method: "DELETE",
901
- methodName: "removeProject"
902
- });
903
- if (response.success) {
904
- return response;
905
- }
906
- throw new Error(response.message);
907
- } catch (error) {
908
- throw new Error(`Failed to remove project: ${error.message}`);
909
- }
910
- }
911
- async checkProjectKeyAvailability(key) {
912
- this._requireReady("checkProjectKeyAvailability");
913
- if (!key) {
914
- throw new Error("Project key is required");
915
- }
916
- try {
917
- const response = await this._request(`/projects/check-key/${key}`, {
918
- method: "GET",
919
- methodName: "checkProjectKeyAvailability"
920
- });
921
- if (response.success) {
922
- return response.data;
923
- }
924
- throw new Error(response.message);
925
- } catch (error) {
926
- throw new Error(
927
- `Failed to check project key availability: ${error.message}`
928
- );
929
- }
930
- }
931
- // ==================== PROJECT MEMBER METHODS ====================
932
- async getProjectMembers(projectId) {
933
- this._requireReady("getProjectMembers");
934
- if (!projectId) {
935
- throw new Error("Project ID is required");
936
- }
937
- try {
938
- const response = await this._request(`/projects/${projectId}/members`, {
939
- method: "GET",
940
- methodName: "getProjectMembers"
941
- });
942
- if (response.success) {
943
- return response.data;
944
- }
945
- throw new Error(response.message);
946
- } catch (error) {
947
- throw new Error(`Failed to get project members: ${error.message}`);
948
- }
949
- }
950
- async inviteMember(projectId, email, role = "guest", options = {}) {
951
- this._requireReady("inviteMember");
952
- if (!projectId || !email || !role) {
953
- throw new Error("Project ID, email, and role are required");
954
- }
955
- const { name, callbackUrl } = options;
956
- const defaultCallbackUrl = typeof window === "undefined" ? "https://app.symbols.com/accept-invite" : `${window.location.origin}/accept-invite`;
957
- try {
958
- const requestBody = {
959
- email,
960
- role,
961
- callbackUrl: callbackUrl || defaultCallbackUrl
962
- };
963
- if (name) {
964
- requestBody.name = name;
965
- }
966
- const response = await this._request(`/projects/${projectId}/invite`, {
967
- method: "POST",
968
- body: JSON.stringify(requestBody),
969
- methodName: "inviteMember"
970
- });
971
- if (response.success) {
972
- return response.data;
973
- }
974
- throw new Error(response.message);
975
- } catch (error) {
976
- throw new Error(`Failed to invite member: ${error.message}`);
977
- }
978
- }
979
- async acceptInvite(token) {
980
- this._requireReady("acceptInvite");
981
- if (!token) {
982
- throw new Error("Invitation token is required");
983
- }
984
- try {
985
- const response = await this._request("/projects/accept-invite", {
986
- method: "POST",
987
- body: JSON.stringify({ token }),
988
- methodName: "acceptInvite"
989
- });
990
- if (response.success) {
991
- return response.data;
992
- }
993
- throw new Error(response.message);
994
- } catch (error) {
995
- throw new Error(`Failed to accept invite: ${error.message}`);
996
- }
997
- }
998
- async updateMemberRole(projectId, memberId, role) {
999
- this._requireReady("updateMemberRole");
1000
- if (!projectId || !memberId || !role) {
1001
- throw new Error("Project ID, member ID, and role are required");
1002
- }
1003
- try {
1004
- const response = await this._request(
1005
- `/projects/${projectId}/members/${memberId}`,
1006
- {
1007
- method: "PATCH",
1008
- body: JSON.stringify({ role }),
1009
- methodName: "updateMemberRole"
1010
- }
1011
- );
1012
- if (response.success) {
1013
- return response.data;
1014
- }
1015
- throw new Error(response.message);
1016
- } catch (error) {
1017
- throw new Error(`Failed to update member role: ${error.message}`);
1018
- }
1019
- }
1020
- async removeMember(projectId, memberId) {
1021
- this._requireReady("removeMember");
1022
- if (!projectId || !memberId) {
1023
- throw new Error("Project ID and member ID are required");
1024
- }
1025
- try {
1026
- const response = await this._request(
1027
- `/projects/${projectId}/members/${memberId}`,
1028
- {
1029
- method: "DELETE",
1030
- methodName: "removeMember"
1031
- }
1032
- );
1033
- if (response.success) {
1034
- return response.data;
1035
- }
1036
- throw new Error(response.message);
1037
- } catch (error) {
1038
- throw new Error(`Failed to remove member: ${error.message}`);
1039
- }
1040
- }
1041
- // ==================== PROJECT LIBRARY METHODS ====================
1042
- async getAvailableLibraries(params = {}) {
1043
- this._requireReady("getAvailableLibraries");
1044
- const queryParams = new URLSearchParams(params).toString();
1045
- try {
1046
- const response = await this._request(
1047
- `/projects/libraries/available?${queryParams}`,
1048
- {
1049
- method: "GET",
1050
- methodName: "getAvailableLibraries"
1051
- }
1052
- );
1053
- if (response.success) {
1054
- return response.data;
1055
- }
1056
- throw new Error(response.message);
1057
- } catch (error) {
1058
- throw new Error(`Failed to get available libraries: ${error.message}`);
1059
- }
1060
- }
1061
- async getProjectLibraries(projectId) {
1062
- this._requireReady("getProjectLibraries");
1063
- if (!projectId) {
1064
- throw new Error("Project ID is required");
1065
- }
1066
- try {
1067
- const response = await this._request(`/projects/${projectId}/libraries`, {
1068
- method: "GET",
1069
- methodName: "getProjectLibraries"
1070
- });
1071
- if (response.success) {
1072
- return response.data;
1073
- }
1074
- throw new Error(response.message);
1075
- } catch (error) {
1076
- throw new Error(`Failed to get project libraries: ${error.message}`);
1077
- }
1078
- }
1079
- async addProjectLibraries(projectId, libraryIds) {
1080
- this._requireReady("addProjectLibraries");
1081
- if (!projectId || !libraryIds) {
1082
- throw new Error("Project ID and library IDs are required");
1083
- }
1084
- try {
1085
- const response = await this._request(`/projects/${projectId}/libraries`, {
1086
- method: "POST",
1087
- body: JSON.stringify({ libraryIds }),
1088
- methodName: "addProjectLibraries"
1089
- });
1090
- if (response.success) {
1091
- return response.data;
1092
- }
1093
- throw new Error(response.message);
1094
- } catch (error) {
1095
- throw new Error(`Failed to add project libraries: ${error.message}`);
1096
- }
1097
- }
1098
- async removeProjectLibraries(projectId, libraryIds) {
1099
- this._requireReady("removeProjectLibraries");
1100
- if (!projectId || !libraryIds) {
1101
- throw new Error("Project ID and library IDs are required");
1102
- }
1103
- try {
1104
- const response = await this._request(`/projects/${projectId}/libraries`, {
1105
- method: "DELETE",
1106
- body: JSON.stringify({ libraryIds }),
1107
- methodName: "removeProjectLibraries"
1108
- });
1109
- if (response.success) {
1110
- return response;
1111
- }
1112
- throw new Error(response.message);
1113
- } catch (error) {
1114
- throw new Error(`Failed to remove project libraries: ${error.message}`);
1115
- }
1116
- }
1117
- // ==================== FILE METHODS ====================
1118
- async uploadFile(file, options = {}) {
1119
- this._requireReady("uploadFile");
1120
- if (!file) {
1121
- throw new Error("File is required for upload");
1122
- }
1123
- const formData = new FormData();
1124
- formData.append("file", file);
1125
- if (options.projectId) {
1126
- formData.append("projectId", options.projectId);
1127
- }
1128
- if (options.tags) {
1129
- formData.append("tags", JSON.stringify(options.tags));
1130
- }
1131
- if (options.visibility) {
1132
- formData.append("visibility", options.visibility || "public");
1133
- }
1134
- if (options.metadata) {
1135
- formData.append("metadata", JSON.stringify(options.metadata));
1136
- }
1137
- try {
1138
- const response = await this._request("/files/upload", {
1139
- method: "POST",
1140
- body: formData,
1141
- headers: {},
1142
- // Let browser set Content-Type for FormData
1143
- methodName: "uploadFile"
1144
- });
1145
- if (!response.success) {
1146
- throw new Error(response.message);
1147
- }
1148
- return {
1149
- id: response.data.id,
1150
- src: `${this._apiUrl}/core/files/public/${response.data.id}/download`,
1151
- success: true,
1152
- message: response.message
1153
- };
1154
- } catch (error) {
1155
- throw new Error(`File upload failed: ${error.message}`);
1156
- }
1157
- }
1158
- async updateProjectIcon(projectId, iconFile) {
1159
- this._requireReady("updateProjectIcon");
1160
- if (!projectId || !iconFile) {
1161
- throw new Error("Project ID and icon file are required");
1162
- }
1163
- const formData = new FormData();
1164
- formData.append("icon", iconFile);
1165
- formData.append("projectId", projectId);
1166
- try {
1167
- const response = await this._request("/files/upload-project-icon", {
1168
- method: "POST",
1169
- body: formData,
1170
- headers: {},
1171
- // Let browser set Content-Type for FormData
1172
- methodName: "updateProjectIcon"
1173
- });
1174
- if (response.success) {
1175
- return response.data;
1176
- }
1177
- throw new Error(response.message);
1178
- } catch (error) {
1179
- throw new Error(`Failed to update project icon: ${error.message}`);
1180
- }
1181
- }
1182
- // ==================== PAYMENT METHODS ====================
1183
- async checkout(options = {}) {
1184
- this._requireReady("checkout");
1185
- const {
1186
- projectId,
1187
- seats = 1,
1188
- price = "starter_monthly",
1189
- successUrl = `${window.location.origin}/success`,
1190
- cancelUrl = `${window.location.origin}/pricing`
1191
- } = options;
1192
- if (!projectId) {
1193
- throw new Error("Project ID is required for checkout");
1194
- }
1195
- try {
1196
- const response = await this._request("/payments/checkout", {
1197
- method: "POST",
1198
- body: JSON.stringify({
1199
- projectId,
1200
- seats,
1201
- price,
1202
- successUrl,
1203
- cancelUrl
1204
- }),
1205
- methodName: "checkout"
1206
- });
1207
- if (response.success) {
1208
- return response.data;
1209
- }
1210
- throw new Error(response.message);
1211
- } catch (error) {
1212
- throw new Error(`Failed to checkout: ${error.message}`);
1213
- }
1214
- }
1215
- async getSubscriptionStatus(projectId) {
1216
- this._requireReady("getSubscriptionStatus");
1217
- if (!projectId) {
1218
- throw new Error("Project ID is required");
1219
- }
1220
- try {
1221
- const response = await this._request(
1222
- `/payments/subscription/${projectId}`,
1223
- {
1224
- method: "GET",
1225
- methodName: "getSubscriptionStatus"
1226
- }
1227
- );
1228
- if (response.success) {
1229
- return response.data;
1230
- }
1231
- throw new Error(response.message);
1232
- } catch (error) {
1233
- throw new Error(`Failed to get subscription status: ${error.message}`);
1234
- }
1235
- }
1236
- // ==================== DNS METHODS ====================
1237
- async createDnsRecord(domain, options = {}) {
1238
- this._requireReady("createDnsRecord");
1239
- if (!domain) {
1240
- throw new Error("Domain is required");
1241
- }
1242
- try {
1243
- const response = await this._request("/dns/records", {
1244
- method: "POST",
1245
- body: JSON.stringify({ domain, ...options }),
1246
- methodName: "createDnsRecord"
1247
- });
1248
- if (response.success) {
1249
- return response.data;
1250
- }
1251
- throw new Error(response.message);
1252
- } catch (error) {
1253
- throw new Error(`Failed to create DNS record: ${error.message}`);
1254
- }
1255
- }
1256
- async getDnsRecord(domain) {
1257
- this._requireReady("getDnsRecord");
1258
- if (!domain) {
1259
- throw new Error("Domain is required");
1260
- }
1261
- try {
1262
- const response = await this._request(`/dns/records/${domain}`, {
1263
- method: "GET",
1264
- methodName: "getDnsRecord"
1265
- });
1266
- if (response.success) {
1267
- return response.data;
1268
- }
1269
- throw new Error(response.message);
1270
- } catch (error) {
1271
- throw new Error(`Failed to get DNS record: ${error.message}`);
1272
- }
1273
- }
1274
- async removeDnsRecord(domain) {
1275
- this._requireReady("removeDnsRecord");
1276
- if (!domain) {
1277
- throw new Error("Domain is required");
1278
- }
1279
- try {
1280
- const response = await this._request(`/dns/records/${domain}`, {
1281
- method: "DELETE",
1282
- methodName: "removeDnsRecord"
1283
- });
1284
- if (response.success) {
1285
- return response.data;
1286
- }
1287
- throw new Error(response.message);
1288
- } catch (error) {
1289
- throw new Error(`Failed to remove DNS record: ${error.message}`);
1290
- }
1291
- }
1292
- async setProjectDomains(projectKey, customDomain, hasCustomDomainAccess = false) {
1293
- this._requireReady("setProjectDomains");
1294
- if (!projectKey) {
1295
- throw new Error("Project key is required");
1296
- }
1297
- try {
1298
- const response = await this._request("/dns/project-domains", {
1299
- method: "POST",
1300
- body: JSON.stringify({
1301
- projectKey,
1302
- customDomain,
1303
- hasCustomDomainAccess
1304
- }),
1305
- methodName: "setProjectDomains"
1306
- });
1307
- if (response.success) {
1308
- return response.data;
1309
- }
1310
- throw new Error(response.message);
1311
- } catch (error) {
1312
- throw new Error(`Failed to set project domains: ${error.message}`);
1313
- }
1314
- }
1315
- async addProjectCustomDomains(projectId, customDomains) {
1316
- this._requireReady("addProjectCustomDomains");
1317
- if (!projectId) {
1318
- throw new Error("Project ID is required");
1319
- }
1320
- if (!customDomains || Array.isArray(customDomains) && !customDomains.length) {
1321
- throw new Error(
1322
- "customDomains is required and must be a non-empty string or array"
1323
- );
1324
- }
1325
- try {
1326
- const response = await this._request(`/projects/${projectId}/domains`, {
1327
- method: "PATCH",
1328
- body: JSON.stringify({ customDomains }),
1329
- methodName: "addProjectCustomDomains"
1330
- });
1331
- if (response.success) {
1332
- return response.data;
1333
- }
1334
- throw new Error(response.message);
1335
- } catch (error) {
1336
- throw new Error(
1337
- `Failed to update project custom domains: ${error.message}`
1338
- );
1339
- }
1340
- }
1341
- // ==================== UTILITY METHODS ====================
1342
- async getHealthStatus() {
1343
- try {
1344
- const response = await this._request("/health", {
1345
- method: "GET",
1346
- methodName: "getHealthStatus"
1347
- });
1348
- if (response.success) {
1349
- return response.data;
1350
- }
1351
- throw new Error(response.message);
1352
- } catch (error) {
1353
- throw new Error(`Failed to get health status: ${error.message}`);
1354
- }
1355
- }
1356
- // ==================== PROJECT DATA METHODS (SYMSTORY REPLACEMENT) ====================
1357
- /**
1358
- * Apply changes to a project, creating a new version
1359
- * Replaces: SymstoryService.updateData()
1360
- */
1361
- async applyProjectChanges(projectId, changes, options = {}) {
1362
- this._requireReady("applyProjectChanges");
1363
- if (!projectId) {
1364
- throw new Error("Project ID is required");
1365
- }
1366
- if (!Array.isArray(changes)) {
1367
- throw new Error("Changes must be an array");
1368
- }
1369
- const { message, branch = "main", type = "patch" } = options;
1370
- try {
1371
- const response = await this._request(`/projects/${projectId}/changes`, {
1372
- method: "POST",
1373
- body: JSON.stringify({
1374
- changes,
1375
- message,
1376
- branch,
1377
- type
1378
- }),
1379
- methodName: "applyProjectChanges"
1380
- });
1381
- if (response.success) {
1382
- return response.data;
1383
- }
1384
- throw new Error(response.message);
1385
- } catch (error) {
1386
- throw new Error(`Failed to apply project changes: ${error.message}`);
1387
- }
1388
- }
1389
- /**
1390
- * Get current project data for a specific branch
1391
- * Replaces: SymstoryService.getData()
1392
- */
1393
- async getProjectData(projectId, options = {}) {
1394
- this._requireReady("getProjectData");
1395
- if (!projectId) {
1396
- throw new Error("Project ID is required");
1397
- }
1398
- const {
1399
- branch = "main",
1400
- version = "latest",
1401
- includeHistory = false
1402
- } = options;
1403
- const queryParams = new URLSearchParams({
1404
- branch,
1405
- version,
1406
- includeHistory: includeHistory.toString()
1407
- }).toString();
1408
- try {
1409
- const response = await this._request(
1410
- `/projects/${projectId}/data?${queryParams}`,
1411
- {
1412
- method: "GET",
1413
- methodName: "getProjectData"
1414
- }
1415
- );
1416
- if (response.success) {
1417
- return response.data;
1418
- }
1419
- throw new Error(response.message);
1420
- } catch (error) {
1421
- throw new Error(`Failed to get project data: ${error.message}`);
1422
- }
1423
- }
1424
- /**
1425
- * Get project versions with pagination
1426
- */
1427
- async getProjectVersions(projectId, options = {}) {
1428
- this._requireReady("getProjectVersions");
1429
- if (!projectId) {
1430
- throw new Error("Project ID is required");
1431
- }
1432
- const { branch = "main", page = 1, limit = 50 } = options;
1433
- const queryParams = new URLSearchParams({
1434
- branch,
1435
- page: page.toString(),
1436
- limit: limit.toString()
1437
- }).toString();
1438
- try {
1439
- const response = await this._request(
1440
- `/projects/${projectId}/versions?${queryParams}`,
1441
- {
1442
- method: "GET",
1443
- methodName: "getProjectVersions"
1444
- }
1445
- );
1446
- if (response.success) {
1447
- return response.data;
1448
- }
1449
- throw new Error(response.message);
1450
- } catch (error) {
1451
- throw new Error(`Failed to get project versions: ${error.message}`);
1452
- }
1453
- }
1454
- /**
1455
- * Restore project to a previous version
1456
- * Replaces: SymstoryService.restoreVersion()
1457
- */
1458
- async restoreProjectVersion(projectId, version, options = {}) {
1459
- this._requireReady("restoreProjectVersion");
1460
- if (!projectId) {
1461
- throw new Error("Project ID is required");
1462
- }
1463
- if (!version) {
1464
- throw new Error("Version is required");
1465
- }
1466
- const { message, branch = "main", type = "patch" } = options;
1467
- try {
1468
- const response = await this._request(`/projects/${projectId}/restore`, {
1469
- method: "POST",
1470
- body: JSON.stringify({
1471
- version,
1472
- message,
1473
- branch,
1474
- type
1475
- }),
1476
- methodName: "restoreProjectVersion"
1477
- });
1478
- if (response.success) {
1479
- return response.data;
1480
- }
1481
- throw new Error(response.message);
1482
- } catch (error) {
1483
- throw new Error(`Failed to restore project version: ${error.message}`);
1484
- }
1485
- }
1486
- /**
1487
- * Helper method to update a single item in the project
1488
- * Convenience wrapper around applyProjectChanges
1489
- */
1490
- async updateProjectItem(projectId, path, value, options = {}) {
1491
- const changes = [["update", path, value]];
1492
- const message = options.message || `Updated ${Array.isArray(path) ? path.join(".") : path}`;
1493
- return await this.applyProjectChanges(projectId, changes, {
1494
- ...options,
1495
- message
1496
- });
1497
- }
1498
- /**
1499
- * Helper method to delete an item from the project
1500
- * Convenience wrapper around applyProjectChanges
1501
- */
1502
- async deleteProjectItem(projectId, path, options = {}) {
1503
- const changes = [["delete", path]];
1504
- const message = options.message || `Deleted ${Array.isArray(path) ? path.join(".") : path}`;
1505
- return await this.applyProjectChanges(projectId, changes, {
1506
- ...options,
1507
- message
1508
- });
1509
- }
1510
- /**
1511
- * Helper method to set a value in the project (alias for update)
1512
- * Convenience wrapper around applyProjectChanges
1513
- */
1514
- async setProjectValue(projectId, path, value, options = {}) {
1515
- const changes = [["set", path, value]];
1516
- const message = options.message || `Set ${Array.isArray(path) ? path.join(".") : path}`;
1517
- return await this.applyProjectChanges(projectId, changes, {
1518
- ...options,
1519
- message
1520
- });
1521
- }
1522
- /**
1523
- * Helper method to add multiple items to the project
1524
- * Convenience wrapper around applyProjectChanges
1525
- */
1526
- async addProjectItems(projectId, items, options = {}) {
1527
- const changes = items.map((item) => {
1528
- const [type, data] = item;
1529
- const { value, ...schema } = data;
1530
- return [
1531
- ["update", [type, data.key], value],
1532
- ["update", ["schema", type, data.key], schema]
1533
- ];
1534
- }).flat();
1535
- const message = options.message || `Added ${items.length} items`;
1536
- return await this.applyProjectChanges(projectId, changes, {
1537
- ...options,
1538
- message
1539
- });
1540
- }
1541
- /**
1542
- * Helper method to get specific data from project by path
1543
- * Convenience wrapper that gets project data and extracts specific path
1544
- */
1545
- async getProjectItemByPath(projectId, path, options = {}) {
1546
- const projectData = await this.getProjectData(projectId, options);
1547
- if (!(projectData == null ? void 0 : projectData.data)) {
1548
- return null;
1549
- }
1550
- let current = projectData.data;
1551
- const pathArray = Array.isArray(path) ? path : [path];
1552
- for (const segment of pathArray) {
1553
- if (current && typeof current === "object" && segment in current) {
1554
- current = current[segment];
1555
- } else {
1556
- return null;
1557
- }
1558
- }
1559
- return current;
1560
- }
1561
- // ==================== PULL REQUEST METHODS ====================
1562
- /**
1563
- * Create a new pull request
1564
- */
1565
- async createPullRequest(projectId, pullRequestData) {
1566
- this._requireReady("createPullRequest");
1567
- if (!projectId) {
1568
- throw new Error("Project ID is required");
1569
- }
1570
- if (!pullRequestData.source || !pullRequestData.target || !pullRequestData.title) {
1571
- throw new Error("Source branch, target branch, and title are required");
1572
- }
1573
- try {
1574
- const response = await this._request(
1575
- `/projects/${projectId}/pull-requests`,
1576
- {
1577
- method: "POST",
1578
- body: JSON.stringify(pullRequestData),
1579
- methodName: "createPullRequest"
1580
- }
1581
- );
1582
- if (response.success) {
1583
- return response.data;
1584
- }
1585
- throw new Error(response.message);
1586
- } catch (error) {
1587
- throw new Error(`Failed to create pull request: ${error.message}`);
1588
- }
1589
- }
1590
- /**
1591
- * List pull requests for a project with filtering options
1592
- */
1593
- async listPullRequests(projectId, options = {}) {
1594
- this._requireReady("listPullRequests");
1595
- if (!projectId) {
1596
- throw new Error("Project ID is required");
1597
- }
1598
- const { status = "open", source, target, page = 1, limit = 20 } = options;
1599
- const queryParams = new URLSearchParams({
1600
- status,
1601
- page: page.toString(),
1602
- limit: limit.toString()
1603
- });
1604
- if (source) {
1605
- queryParams.append("source", source);
1606
- }
1607
- if (target) {
1608
- queryParams.append("target", target);
1609
- }
1610
- try {
1611
- const response = await this._request(
1612
- `/projects/${projectId}/pull-requests?${queryParams.toString()}`,
1613
- {
1614
- method: "GET",
1615
- methodName: "listPullRequests"
1616
- }
1617
- );
1618
- if (response.success) {
1619
- return response.data;
1620
- }
1621
- throw new Error(response.message);
1622
- } catch (error) {
1623
- throw new Error(`Failed to list pull requests: ${error.message}`);
1624
- }
1625
- }
1626
- /**
1627
- * Get detailed information about a specific pull request
1628
- */
1629
- async getPullRequest(projectId, prId) {
1630
- this._requireReady("getPullRequest");
1631
- if (!projectId) {
1632
- throw new Error("Project ID is required");
1633
- }
1634
- if (!prId) {
1635
- throw new Error("Pull request ID is required");
1636
- }
1637
- try {
1638
- const response = await this._request(
1639
- `/projects/${projectId}/pull-requests/${prId}`,
1640
- {
1641
- method: "GET",
1642
- methodName: "getPullRequest"
1643
- }
1644
- );
1645
- if (response.success) {
1646
- return response.data;
1647
- }
1648
- throw new Error(response.message);
1649
- } catch (error) {
1650
- throw new Error(`Failed to get pull request: ${error.message}`);
1651
- }
1652
- }
1653
- /**
1654
- * Submit a review for a pull request
1655
- */
1656
- async reviewPullRequest(projectId, prId, reviewData) {
1657
- this._requireReady("reviewPullRequest");
1658
- if (!projectId) {
1659
- throw new Error("Project ID is required");
1660
- }
1661
- if (!prId) {
1662
- throw new Error("Pull request ID is required");
1663
- }
1664
- const validStatuses = ["approved", "requested_changes", "feedback"];
1665
- if (reviewData.status && !validStatuses.includes(reviewData.status)) {
1666
- throw new Error(
1667
- `Invalid review status. Must be one of: ${validStatuses.join(", ")}`
1668
- );
1669
- }
1670
- try {
1671
- const response = await this._request(
1672
- `/projects/${projectId}/pull-requests/${prId}/review`,
1673
- {
1674
- method: "POST",
1675
- body: JSON.stringify(reviewData),
1676
- methodName: "reviewPullRequest"
1677
- }
1678
- );
1679
- if (response.success) {
1680
- return response.data;
1681
- }
1682
- throw new Error(response.message);
1683
- } catch (error) {
1684
- throw new Error(`Failed to review pull request: ${error.message}`);
1685
- }
1686
- }
1687
- /**
1688
- * Add a comment to an existing review thread
1689
- */
1690
- async addPullRequestComment(projectId, prId, commentData) {
1691
- this._requireReady("addPullRequestComment");
1692
- if (!projectId) {
1693
- throw new Error("Project ID is required");
1694
- }
1695
- if (!prId) {
1696
- throw new Error("Pull request ID is required");
1697
- }
1698
- if (!commentData.value) {
1699
- throw new Error("Comment value is required");
1700
- }
1701
- try {
1702
- const response = await this._request(
1703
- `/projects/${projectId}/pull-requests/${prId}/comment`,
1704
- {
1705
- method: "POST",
1706
- body: JSON.stringify(commentData),
1707
- methodName: "addPullRequestComment"
1708
- }
1709
- );
1710
- if (response.success) {
1711
- return response.data;
1712
- }
1713
- throw new Error(response.message);
1714
- } catch (error) {
1715
- throw new Error(`Failed to add pull request comment: ${error.message}`);
1716
- }
1717
- }
1718
- /**
1719
- * Merge an approved pull request
1720
- */
1721
- async mergePullRequest(projectId, prId) {
1722
- this._requireReady("mergePullRequest");
1723
- if (!projectId) {
1724
- throw new Error("Project ID is required");
1725
- }
1726
- if (!prId) {
1727
- throw new Error("Pull request ID is required");
1728
- }
1729
- try {
1730
- const response = await this._request(
1731
- `/projects/${projectId}/pull-requests/${prId}/merge`,
1732
- {
1733
- method: "POST",
1734
- methodName: "mergePullRequest"
1735
- }
1736
- );
1737
- if (response.success) {
1738
- return response.data;
1739
- }
1740
- throw new Error(response.message);
1741
- } catch (error) {
1742
- if (error.message.includes("conflicts") || error.message.includes("409")) {
1743
- throw new Error(`Pull request has merge conflicts: ${error.message}`);
1744
- }
1745
- throw new Error(`Failed to merge pull request: ${error.message}`);
1746
- }
1747
- }
1748
- /**
1749
- * Get the diff/changes for a pull request
1750
- */
1751
- async getPullRequestDiff(projectId, prId) {
1752
- this._requireReady("getPullRequestDiff");
1753
- if (!projectId) {
1754
- throw new Error("Project ID is required");
1755
- }
1756
- if (!prId) {
1757
- throw new Error("Pull request ID is required");
1758
- }
1759
- try {
1760
- const response = await this._request(
1761
- `/projects/${projectId}/pull-requests/${prId}/diff`,
1762
- {
1763
- method: "GET",
1764
- methodName: "getPullRequestDiff"
1765
- }
1766
- );
1767
- if (response.success) {
1768
- return response.data;
1769
- }
1770
- throw new Error(response.message);
1771
- } catch (error) {
1772
- throw new Error(`Failed to get pull request diff: ${error.message}`);
1773
- }
1774
- }
1775
- /**
1776
- * Helper method to create a pull request with validation
1777
- */
1778
- async createPullRequestWithValidation(projectId, data) {
1779
- const { source, target, title, description, changes } = data;
1780
- if (source === target) {
1781
- throw new Error("Source and target branches cannot be the same");
1782
- }
1783
- if (!title || title.trim().length === 0) {
1784
- throw new Error("Pull request title cannot be empty");
1785
- }
1786
- if (title.length > 200) {
1787
- throw new Error("Pull request title cannot exceed 200 characters");
1788
- }
1789
- const pullRequestData = {
1790
- source: source.trim(),
1791
- target: target.trim(),
1792
- title: title.trim(),
1793
- ...description && { description: description.trim() },
1794
- ...changes && { changes }
1795
- };
1796
- return await this.createPullRequest(projectId, pullRequestData);
1797
- }
1798
- /**
1799
- * Helper method to approve a pull request
1800
- */
1801
- async approvePullRequest(projectId, prId, comment = "") {
1802
- const reviewData = {
1803
- status: "approved",
1804
- ...comment && {
1805
- threads: [
1806
- {
1807
- comment,
1808
- type: "praise"
1809
- }
1810
- ]
1811
- }
1812
- };
1813
- return await this.reviewPullRequest(projectId, prId, reviewData);
1814
- }
1815
- /**
1816
- * Helper method to request changes on a pull request
1817
- */
1818
- async requestPullRequestChanges(projectId, prId, threads = []) {
1819
- if (!threads || threads.length === 0) {
1820
- throw new Error("Must provide specific feedback when requesting changes");
1821
- }
1822
- const reviewData = {
1823
- status: "requested_changes",
1824
- threads
1825
- };
1826
- return await this.reviewPullRequest(projectId, prId, reviewData);
1827
- }
1828
- /**
1829
- * Helper method to get pull requests by status
1830
- */
1831
- async getOpenPullRequests(projectId, options = {}) {
1832
- return await this.listPullRequests(projectId, {
1833
- ...options,
1834
- status: "open"
1835
- });
1836
- }
1837
- async getClosedPullRequests(projectId, options = {}) {
1838
- return await this.listPullRequests(projectId, {
1839
- ...options,
1840
- status: "closed"
1841
- });
1842
- }
1843
- async getMergedPullRequests(projectId, options = {}) {
1844
- return await this.listPullRequests(projectId, {
1845
- ...options,
1846
- status: "merged"
1847
- });
1848
- }
1849
- /**
1850
- * Helper method to check if a pull request is canMerge
1851
- */
1852
- async isPullRequestMergeable(projectId, prId) {
1853
- var _a;
1854
- try {
1855
- const prData = await this.getPullRequest(projectId, prId);
1856
- return ((_a = prData == null ? void 0 : prData.data) == null ? void 0 : _a.canMerge) || false;
1857
- } catch (error) {
1858
- throw new Error(
1859
- `Failed to check pull request mergeability: ${error.message}`
1860
- );
1861
- }
1862
- }
1863
- /**
1864
- * Helper method to get pull request status summary
1865
- */
1866
- async getPullRequestStatusSummary(projectId, prId) {
1867
- var _a, _b, _c;
1868
- try {
1869
- const prData = await this.getPullRequest(projectId, prId);
1870
- const pr = prData == null ? void 0 : prData.data;
1871
- if (!pr) {
1872
- throw new Error("Pull request not found");
1873
- }
1874
- return {
1875
- status: pr.status,
1876
- reviewStatus: pr.reviewStatus,
1877
- canMerge: pr.canMerge,
1878
- hasConflicts: !pr.canMerge,
1879
- reviewCount: ((_a = pr.reviews) == null ? void 0 : _a.length) || 0,
1880
- approvedReviews: ((_b = pr.reviews) == null ? void 0 : _b.filter((r) => r.status === "approved").length) || 0,
1881
- changesRequested: ((_c = pr.reviews) == null ? void 0 : _c.filter((r) => r.status === "requested_changes").length) || 0
1882
- };
1883
- } catch (error) {
1884
- throw new Error(
1885
- `Failed to get pull request status summary: ${error.message}`
1886
- );
1887
- }
1888
- }
1889
- // ==================== BRANCH MANAGEMENT METHODS ====================
1890
- /**
1891
- * Get all branches for a project
1892
- */
1893
- async listBranches(projectId) {
1894
- this._requireReady("listBranches");
1895
- if (!projectId) {
1896
- throw new Error("Project ID is required");
1897
- }
1898
- try {
1899
- const response = await this._request(`/projects/${projectId}/branches`, {
1900
- method: "GET",
1901
- methodName: "listBranches"
1902
- });
1903
- if (response.success) {
1904
- return response.data;
1905
- }
1906
- throw new Error(response.message);
1907
- } catch (error) {
1908
- throw new Error(`Failed to list branches: ${error.message}`);
1909
- }
1910
- }
1911
- /**
1912
- * Create a new branch from an existing branch
1913
- */
1914
- async createBranch(projectId, branchData) {
1915
- this._requireReady("createBranch");
1916
- if (!projectId) {
1917
- throw new Error("Project ID is required");
1918
- }
1919
- if (!branchData.name) {
1920
- throw new Error("Branch name is required");
1921
- }
1922
- const { name, source = "main" } = branchData;
1923
- try {
1924
- const response = await this._request(`/projects/${projectId}/branches`, {
1925
- method: "POST",
1926
- body: JSON.stringify({ name, source }),
1927
- methodName: "createBranch"
1928
- });
1929
- if (response.success) {
1930
- return response.data;
1931
- }
1932
- throw new Error(response.message);
1933
- } catch (error) {
1934
- throw new Error(`Failed to create branch: ${error.message}`);
1935
- }
1936
- }
1937
- /**
1938
- * Delete a branch (cannot delete main branch)
1939
- */
1940
- async deleteBranch(projectId, branchName) {
1941
- this._requireReady("deleteBranch");
1942
- if (!projectId) {
1943
- throw new Error("Project ID is required");
1944
- }
1945
- if (!branchName) {
1946
- throw new Error("Branch name is required");
1947
- }
1948
- if (branchName === "main") {
1949
- throw new Error("Cannot delete main branch");
1950
- }
1951
- try {
1952
- const response = await this._request(
1953
- `/projects/${projectId}/branches/${encodeURIComponent(branchName)}`,
1954
- {
1955
- method: "DELETE",
1956
- methodName: "deleteBranch"
1957
- }
1958
- );
1959
- if (response.success) {
1960
- return response;
1961
- }
1962
- throw new Error(response.message);
1963
- } catch (error) {
1964
- throw new Error(`Failed to delete branch: ${error.message}`);
1965
- }
1966
- }
1967
- /**
1968
- * Rename a branch (cannot rename main branch)
1969
- */
1970
- async renameBranch(projectId, branchName, newName) {
1971
- this._requireReady("renameBranch");
1972
- if (!projectId) {
1973
- throw new Error("Project ID is required");
1974
- }
1975
- if (!branchName) {
1976
- throw new Error("Current branch name is required");
1977
- }
1978
- if (!newName) {
1979
- throw new Error("New branch name is required");
1980
- }
1981
- if (branchName === "main") {
1982
- throw new Error("Cannot rename main branch");
1983
- }
1984
- try {
1985
- const response = await this._request(
1986
- `/projects/${projectId}/branches/${encodeURIComponent(
1987
- branchName
1988
- )}/rename`,
1989
- {
1990
- method: "POST",
1991
- body: JSON.stringify({ newName }),
1992
- methodName: "renameBranch"
1993
- }
1994
- );
1995
- if (response.success) {
1996
- return response;
1997
- }
1998
- throw new Error(response.message);
1999
- } catch (error) {
2000
- throw new Error(`Failed to rename branch: ${error.message}`);
2001
- }
2002
- }
2003
- /**
2004
- * Get changes/diff for a branch compared to another version
2005
- */
2006
- async getBranchChanges(projectId, branchName = "main", options = {}) {
2007
- this._requireReady("getBranchChanges");
2008
- if (!projectId) {
2009
- throw new Error("Project ID is required");
2010
- }
2011
- if (!branchName) {
2012
- throw new Error("Branch name is required");
2013
- }
2014
- const { versionId, versionValue, target } = options;
2015
- const queryParams = new URLSearchParams();
2016
- if (versionId) {
2017
- queryParams.append("versionId", versionId);
2018
- }
2019
- if (versionValue) {
2020
- queryParams.append("versionValue", versionValue);
2021
- }
2022
- if (target) {
2023
- queryParams.append("target", target);
2024
- }
2025
- const queryString = queryParams.toString();
2026
- const url = `/projects/${projectId}/branches/${encodeURIComponent(
2027
- branchName
2028
- )}/changes${queryString ? `?${queryString}` : ""}`;
2029
- try {
2030
- const response = await this._request(url, {
2031
- method: "GET",
2032
- methodName: "getBranchChanges"
2033
- });
2034
- if (response.success) {
2035
- return response.data;
2036
- }
2037
- throw new Error(response.message);
2038
- } catch (error) {
2039
- throw new Error(`Failed to get branch changes: ${error.message}`);
2040
- }
2041
- }
2042
- /**
2043
- * Merge changes between branches (preview or commit)
2044
- */
2045
- async mergeBranch(projectId, branchName, mergeData = {}) {
2046
- this._requireReady("mergeBranch");
2047
- if (!projectId) {
2048
- throw new Error("Project ID is required");
2049
- }
2050
- if (!branchName) {
2051
- throw new Error("Source branch name is required");
2052
- }
2053
- const {
2054
- target = "main",
2055
- message,
2056
- type = "patch",
2057
- commit = false,
2058
- changes
2059
- } = mergeData;
2060
- const requestBody = {
2061
- target,
2062
- type,
2063
- commit,
2064
- ...message && { message },
2065
- ...changes && { changes }
2066
- };
2067
- try {
2068
- const response = await this._request(
2069
- `/projects/${projectId}/branches/${encodeURIComponent(
2070
- branchName
2071
- )}/merge`,
2072
- {
2073
- method: "POST",
2074
- body: JSON.stringify(requestBody),
2075
- methodName: "mergeBranch"
2076
- }
2077
- );
2078
- if (response.success) {
2079
- return response.data;
2080
- }
2081
- throw new Error(response.message);
2082
- } catch (error) {
2083
- if (error.message.includes("conflicts") || error.message.includes("409")) {
2084
- throw new Error(`Merge conflicts detected: ${error.message}`);
2085
- }
2086
- throw new Error(`Failed to merge branch: ${error.message}`);
2087
- }
2088
- }
2089
- /**
2090
- * Reset a branch to a clean state
2091
- */
2092
- async resetBranch(projectId, branchName) {
2093
- this._requireReady("resetBranch");
2094
- if (!projectId) {
2095
- throw new Error("Project ID is required");
2096
- }
2097
- if (!branchName) {
2098
- throw new Error("Branch name is required");
2099
- }
2100
- try {
2101
- const response = await this._request(
2102
- `/projects/${projectId}/branches/${encodeURIComponent(
2103
- branchName
2104
- )}/reset`,
2105
- {
2106
- method: "POST",
2107
- methodName: "resetBranch"
2108
- }
2109
- );
2110
- if (response.success) {
2111
- return response.data;
2112
- }
2113
- throw new Error(response.message);
2114
- } catch (error) {
2115
- throw new Error(`Failed to reset branch: ${error.message}`);
2116
- }
2117
- }
2118
- /**
2119
- * Publish a specific version as the live version
2120
- */
2121
- async publishVersion(projectId, publishData) {
2122
- this._requireReady("publishVersion");
2123
- if (!projectId) {
2124
- throw new Error("Project ID is required");
2125
- }
2126
- if (!publishData.version) {
2127
- throw new Error("Version is required");
2128
- }
2129
- const { version, branch = "main" } = publishData;
2130
- try {
2131
- const response = await this._request(`/projects/${projectId}/publish`, {
2132
- method: "POST",
2133
- body: JSON.stringify({ version, branch }),
2134
- methodName: "publishVersion"
2135
- });
2136
- if (response.success) {
2137
- return response.data;
2138
- }
2139
- throw new Error(response.message);
2140
- } catch (error) {
2141
- throw new Error(`Failed to publish version: ${error.message}`);
2142
- }
2143
- }
2144
- // ==================== BRANCH HELPER METHODS ====================
2145
- /**
2146
- * Helper method to create a branch with validation
2147
- */
2148
- async createBranchWithValidation(projectId, name, source = "main") {
2149
- if (!name || name.trim().length === 0) {
2150
- throw new Error("Branch name cannot be empty");
2151
- }
2152
- if (name.includes(" ")) {
2153
- throw new Error("Branch name cannot contain spaces");
2154
- }
2155
- if (name === "main") {
2156
- throw new Error('Cannot create a branch named "main"');
2157
- }
2158
- const sanitizedName = name.trim().toLowerCase().replace(/[^a-z0-9-_]/gu, "-");
2159
- return await this.createBranch(projectId, {
2160
- name: sanitizedName,
2161
- source
2162
- });
2163
- }
2164
- /**
2165
- * Helper method to check if a branch exists
2166
- */
2167
- async branchExists(projectId, branchName) {
2168
- var _a;
2169
- try {
2170
- const branches = await this.listBranches(projectId);
2171
- return ((_a = branches == null ? void 0 : branches.data) == null ? void 0 : _a.includes(branchName)) || false;
2172
- } catch (error) {
2173
- throw new Error(`Failed to check if branch exists: ${error.message}`);
2174
- }
2175
- }
2176
- /**
2177
- * Helper method to preview merge without committing
2178
- */
2179
- async previewMerge(projectId, sourceBranch, targetBranch = "main") {
2180
- return await this.mergeBranch(projectId, sourceBranch, {
2181
- target: targetBranch,
2182
- commit: false
2183
- });
2184
- }
2185
- /**
2186
- * Helper method to commit merge after preview
2187
- */
2188
- async commitMerge(projectId, sourceBranch, options = {}) {
2189
- const {
2190
- target = "main",
2191
- message = `Merge ${sourceBranch} into ${target}`,
2192
- type = "patch",
2193
- changes
2194
- } = options;
2195
- return await this.mergeBranch(projectId, sourceBranch, {
2196
- target,
2197
- message,
2198
- type,
2199
- commit: true,
2200
- changes
2201
- });
2202
- }
2203
- /**
2204
- * Helper method to create a feature branch from main
2205
- */
2206
- async createFeatureBranch(projectId, featureName) {
2207
- const branchName = `feature/${featureName.toLowerCase().replace(/[^a-z0-9-]/gu, "-")}`;
2208
- return await this.createBranch(projectId, {
2209
- name: branchName,
2210
- source: "main"
2211
- });
2212
- }
2213
- /**
2214
- * Helper method to create a hotfix branch from main
2215
- */
2216
- async createHotfixBranch(projectId, hotfixName) {
2217
- const branchName = `hotfix/${hotfixName.toLowerCase().replace(/[^a-z0-9-]/gu, "-")}`;
2218
- return await this.createBranch(projectId, {
2219
- name: branchName,
2220
- source: "main"
2221
- });
2222
- }
2223
- /**
2224
- * Helper method to get branch status summary
2225
- */
2226
- async getBranchStatus(projectId, branchName) {
2227
- var _a, _b, _c;
2228
- try {
2229
- const [branches, changes] = await Promise.all([
2230
- this.listBranches(projectId),
2231
- this.getBranchChanges(projectId, branchName).catch(() => null)
2232
- ]);
2233
- const exists = ((_a = branches == null ? void 0 : branches.data) == null ? void 0 : _a.includes(branchName)) || false;
2234
- const hasChanges = ((_b = changes == null ? void 0 : changes.data) == null ? void 0 : _b.length) > 0;
2235
- return {
2236
- exists,
2237
- hasChanges,
2238
- changeCount: ((_c = changes == null ? void 0 : changes.data) == null ? void 0 : _c.length) || 0,
2239
- canDelete: exists && branchName !== "main",
2240
- canRename: exists && branchName !== "main"
2241
- };
2242
- } catch (error) {
2243
- throw new Error(`Failed to get branch status: ${error.message}`);
2244
- }
2245
- }
2246
- /**
2247
- * Helper method to safely delete a branch with confirmation
2248
- */
2249
- async deleteBranchSafely(projectId, branchName, options = {}) {
2250
- const { force = false } = options;
2251
- if (!force) {
2252
- const status = await this.getBranchStatus(projectId, branchName);
2253
- if (!status.exists) {
2254
- throw new Error(`Branch '${branchName}' does not exist`);
2255
- }
2256
- if (!status.canDelete) {
2257
- throw new Error(`Branch '${branchName}' cannot be deleted`);
2258
- }
2259
- if (status.hasChanges) {
2260
- throw new Error(
2261
- `Branch '${branchName}' has uncommitted changes. Use force option to delete anyway.`
2262
- );
2263
- }
2264
- }
2265
- return await this.deleteBranch(projectId, branchName);
2266
- }
2267
- // ==================== ADMIN METHODS ====================
2268
- /**
2269
- * Get admin users list with comprehensive filtering and search capabilities
2270
- * Requires admin or super_admin global role
2271
- */
2272
- async getAdminUsers(params = {}) {
2273
- this._requireReady("getAdminUsers");
2274
- const {
2275
- emails,
2276
- ids,
2277
- query,
2278
- status,
2279
- page = 1,
2280
- limit = 50,
2281
- sort = { field: "createdAt", order: "desc" }
2282
- } = params;
2283
- const queryParams = new URLSearchParams();
2284
- if (emails) {
2285
- queryParams.append("emails", emails);
2286
- }
2287
- if (ids) {
2288
- queryParams.append("ids", ids);
2289
- }
2290
- if (query) {
2291
- queryParams.append("query", query);
2292
- }
2293
- if (status) {
2294
- queryParams.append("status", status);
2295
- }
2296
- if (page) {
2297
- queryParams.append("page", page.toString());
2298
- }
2299
- if (limit) {
2300
- queryParams.append("limit", limit.toString());
2301
- }
2302
- if (sort && sort.field) {
2303
- queryParams.append("sort[field]", sort.field);
2304
- queryParams.append("sort[order]", sort.order || "desc");
2305
- }
2306
- const queryString = queryParams.toString();
2307
- const url = `/users/admin/users${queryString ? `?${queryString}` : ""}`;
2308
- try {
2309
- const response = await this._request(url, {
2310
- method: "GET",
2311
- methodName: "getAdminUsers"
2312
- });
2313
- if (response.success) {
2314
- return response.data;
2315
- }
2316
- throw new Error(response.message);
2317
- } catch (error) {
2318
- throw new Error(`Failed to get admin users: ${error.message}`);
2319
- }
2320
- }
2321
- /**
2322
- * Assign projects to a specific user
2323
- * Requires admin or super_admin global role
2324
- */
2325
- async assignProjectsToUser(userId, options = {}) {
2326
- this._requireReady("assignProjectsToUser");
2327
- if (!userId) {
2328
- throw new Error("User ID is required");
2329
- }
2330
- const { projectIds, role = "guest" } = options;
2331
- const requestBody = {
2332
- userId,
2333
- role
2334
- };
2335
- if (projectIds && Array.isArray(projectIds)) {
2336
- requestBody.projectIds = projectIds;
2337
- }
2338
- try {
2339
- const response = await this._request("/assign-projects", {
2340
- method: "POST",
2341
- body: JSON.stringify(requestBody),
2342
- methodName: "assignProjectsToUser"
2343
- });
2344
- if (response.success) {
2345
- return response.data;
2346
- }
2347
- throw new Error(response.message);
2348
- } catch (error) {
2349
- throw new Error(`Failed to assign projects to user: ${error.message}`);
2350
- }
2351
- }
2352
- /**
2353
- * Helper method for admin users search
2354
- */
2355
- async searchAdminUsers(searchQuery, options = {}) {
2356
- return await this.getAdminUsers({
2357
- query: searchQuery,
2358
- ...options
2359
- });
2360
- }
2361
- /**
2362
- * Helper method to get admin users by email list
2363
- */
2364
- async getAdminUsersByEmails(emails, options = {}) {
2365
- const emailList = Array.isArray(emails) ? emails.join(",") : emails;
2366
- return await this.getAdminUsers({
2367
- emails: emailList,
2368
- ...options
2369
- });
2370
- }
2371
- /**
2372
- * Helper method to get admin users by ID list
2373
- */
2374
- async getAdminUsersByIds(ids, options = {}) {
2375
- const idList = Array.isArray(ids) ? ids.join(",") : ids;
2376
- return await this.getAdminUsers({
2377
- ids: idList,
2378
- ...options
2379
- });
2380
- }
2381
- /**
2382
- * Helper method to assign specific projects to a user with a specific role
2383
- */
2384
- async assignSpecificProjectsToUser(userId, projectIds, role = "guest") {
2385
- if (!Array.isArray(projectIds) || projectIds.length === 0) {
2386
- throw new Error("Project IDs must be a non-empty array");
2387
- }
2388
- return await this.assignProjectsToUser(userId, {
2389
- projectIds,
2390
- role
2391
- });
2392
- }
2393
- /**
2394
- * Helper method to assign all projects to a user with a specific role
2395
- */
2396
- async assignAllProjectsToUser(userId, role = "guest") {
2397
- return await this.assignProjectsToUser(userId, {
2398
- role
2399
- });
2400
- }
2401
- async updateUser(userId, userData) {
2402
- var _a;
2403
- this._requireReady("updateUser");
2404
- if (!userId) {
2405
- throw new Error("User ID is required");
2406
- }
2407
- if (!userData || typeof userData !== "object" || Object.keys(userData).length === 0) {
2408
- throw new Error("userData must be a non-empty object");
2409
- }
2410
- try {
2411
- const response = await this._request(`/users/${userId}`, {
2412
- method: "PATCH",
2413
- body: JSON.stringify(userData),
2414
- methodName: "updateUser"
2415
- });
2416
- if (response.success) {
2417
- return response.data;
2418
- }
2419
- throw new Error(response.message);
2420
- } catch (error) {
2421
- if ((_a = error.message) == null ? void 0 : _a.includes("Duplicate")) {
2422
- throw new Error("Username already exists");
2423
- }
2424
- throw new Error(`Failed to update user: ${error.message}`);
2425
- }
2426
- }
2427
- // Cleanup
2428
- destroy() {
2429
- if (this._tokenManager) {
2430
- this._tokenManager.destroy();
2431
- this._tokenManager = null;
2432
- }
2433
- this._client = null;
2434
- this._initialized = false;
2435
- this._setReady(false);
2436
- }
2437
- // ==================== FAVORITE PROJECT METHODS ====================
2438
- async getFavoriteProjects() {
2439
- this._requireReady("getFavoriteProjects");
2440
- try {
2441
- const response = await this._request("/users/favorites", {
2442
- method: "GET",
2443
- methodName: "getFavoriteProjects"
2444
- });
2445
- if (response.success) {
2446
- return (response.data || []).map((project) => ({
2447
- isFavorite: true,
2448
- ...project,
2449
- ...project.icon && {
2450
- icon: {
2451
- src: `${this._apiUrl}/core/files/public/${project.icon.id}/download`,
2452
- ...project.icon
2453
- }
2454
- }
2455
- }));
2456
- }
2457
- throw new Error(response.message);
2458
- } catch (error) {
2459
- throw new Error(`Failed to get favorite projects: ${error.message}`);
2460
- }
2461
- }
2462
- async addFavoriteProject(projectId) {
2463
- this._requireReady("addFavoriteProject");
2464
- if (!projectId) {
2465
- throw new Error("Project ID is required");
2466
- }
2467
- try {
2468
- const response = await this._request(`/users/favorites/${projectId}`, {
2469
- method: "POST",
2470
- methodName: "addFavoriteProject"
2471
- });
2472
- if (response.success) {
2473
- return response.data;
2474
- }
2475
- throw new Error(response.message);
2476
- } catch (error) {
2477
- throw new Error(`Failed to add favorite project: ${error.message}`);
2478
- }
2479
- }
2480
- async removeFavoriteProject(projectId) {
2481
- this._requireReady("removeFavoriteProject");
2482
- if (!projectId) {
2483
- throw new Error("Project ID is required");
2484
- }
2485
- try {
2486
- const response = await this._request(`/users/favorites/${projectId}`, {
2487
- method: "DELETE",
2488
- methodName: "removeFavoriteProject"
2489
- });
2490
- if (response.success) {
2491
- return response.message || "Project removed from favorites";
2492
- }
2493
- throw new Error(response.message);
2494
- } catch (error) {
2495
- throw new Error(`Failed to remove favorite project: ${error.message}`);
2496
- }
2497
- }
2498
- // ==================== RECENT PROJECT METHODS ====================
2499
- async getRecentProjects(options = {}) {
2500
- this._requireReady("getRecentProjects");
2501
- const { limit = 20 } = options;
2502
- const queryString = new URLSearchParams({
2503
- limit: limit.toString()
2504
- }).toString();
2505
- const url = `/users/projects/recent${queryString ? `?${queryString}` : ""}`;
2506
- try {
2507
- const response = await this._request(url, {
2508
- method: "GET",
2509
- methodName: "getRecentProjects"
2510
- });
2511
- if (response.success) {
2512
- return (response.data || []).map((item) => ({
2513
- ...item.project,
2514
- ...item.project && item.project.icon && {
2515
- icon: {
2516
- src: `${this._apiUrl}/core/files/public/${item.project.icon.id}/download`,
2517
- ...item.project.icon
2518
- }
2519
- }
2520
- }));
2521
- }
2522
- throw new Error(response.message);
2523
- } catch (error) {
2524
- throw new Error(`Failed to get recent projects: ${error.message}`);
2525
- }
2526
- }
2527
- // ==================== PLAN METHODS ====================
2528
- /**
2529
- * Get list of public plans (no authentication required)
2530
- */
2531
- async getPlans() {
2532
- try {
2533
- const response = await this._request("/plans", {
2534
- method: "GET",
2535
- methodName: "getPlans"
2536
- });
2537
- if (response.success) {
2538
- return response.data;
2539
- }
2540
- throw new Error(response.message);
2541
- } catch (error) {
2542
- throw new Error(`Failed to get plans: ${error.message}`);
2543
- }
2544
- }
2545
- /**
2546
- * Get a specific plan by ID (no authentication required)
2547
- */
2548
- async getPlan(planId) {
2549
- if (!planId) {
2550
- throw new Error("Plan ID is required");
2551
- }
2552
- try {
2553
- const response = await this._request(`/plans/${planId}`, {
2554
- method: "GET",
2555
- methodName: "getPlan"
2556
- });
2557
- if (response.success) {
2558
- return response.data;
2559
- }
2560
- throw new Error(response.message);
2561
- } catch (error) {
2562
- throw new Error(`Failed to get plan: ${error.message}`);
2563
- }
2564
- }
2565
- // ==================== ADMIN PLAN METHODS ====================
2566
- /**
2567
- * Get all plans including inactive ones (admin only)
2568
- */
2569
- async getAdminPlans() {
2570
- this._requireReady("getAdminPlans");
2571
- try {
2572
- const response = await this._request("/admin/plans", {
2573
- method: "GET",
2574
- methodName: "getAdminPlans"
2575
- });
2576
- if (response.success) {
2577
- return response.data;
2578
- }
2579
- throw new Error(response.message);
2580
- } catch (error) {
2581
- throw new Error(`Failed to get admin plans: ${error.message}`);
2582
- }
2583
- }
2584
- /**
2585
- * Create a new plan (admin only)
2586
- */
2587
- async createPlan(planData) {
2588
- this._requireReady("createPlan");
2589
- if (!planData || typeof planData !== "object") {
2590
- throw new Error("Plan data is required");
2591
- }
2592
- try {
2593
- const response = await this._request("/admin/plans", {
2594
- method: "POST",
2595
- body: JSON.stringify(planData),
2596
- methodName: "createPlan"
2597
- });
2598
- if (response.success) {
2599
- return response.data;
2600
- }
2601
- throw new Error(response.message);
2602
- } catch (error) {
2603
- throw new Error(`Failed to create plan: ${error.message}`);
2604
- }
2605
- }
2606
- /**
2607
- * Update an existing plan (admin only)
2608
- */
2609
- async updatePlan(planId, planData) {
2610
- this._requireReady("updatePlan");
2611
- if (!planId) {
2612
- throw new Error("Plan ID is required");
2613
- }
2614
- if (!planData || typeof planData !== "object") {
2615
- throw new Error("Plan data is required");
2616
- }
2617
- try {
2618
- const response = await this._request(`/admin/plans/${planId}`, {
2619
- method: "PATCH",
2620
- body: JSON.stringify(planData),
2621
- methodName: "updatePlan"
2622
- });
2623
- if (response.success) {
2624
- return response.data;
2625
- }
2626
- throw new Error(response.message);
2627
- } catch (error) {
2628
- throw new Error(`Failed to update plan: ${error.message}`);
2629
- }
2630
- }
2631
- /**
2632
- * Delete a plan (soft delete + archive Stripe product) (admin only)
2633
- */
2634
- async deletePlan(planId) {
2635
- this._requireReady("deletePlan");
2636
- if (!planId) {
2637
- throw new Error("Plan ID is required");
2638
- }
2639
- try {
2640
- const response = await this._request(`/admin/plans/${planId}`, {
2641
- method: "DELETE",
2642
- methodName: "deletePlan"
2643
- });
2644
- if (response.success) {
2645
- return response.data;
2646
- }
2647
- throw new Error(response.message);
2648
- } catch (error) {
2649
- throw new Error(`Failed to delete plan: ${error.message}`);
2650
- }
2651
- }
2652
- /**
2653
- * Initialize default plans (admin only)
2654
- */
2655
- async initializePlans() {
2656
- this._requireReady("initializePlans");
2657
- try {
2658
- const response = await this._request("/admin/plans/initialize", {
2659
- method: "POST",
2660
- methodName: "initializePlans"
2661
- });
2662
- if (response.success) {
2663
- return response;
2664
- }
2665
- throw new Error(response.message);
2666
- } catch (error) {
2667
- throw new Error(`Failed to initialize plans: ${error.message}`);
2668
- }
2669
- }
2670
- // ==================== PLAN HELPER METHODS ====================
2671
- /**
2672
- * Helper method to get plans with validation
2673
- */
2674
- async getPlansWithValidation() {
2675
- try {
2676
- const plans = await this.getPlans();
2677
- if (!Array.isArray(plans)) {
2678
- throw new Error("Invalid response format: plans should be an array");
2679
- }
2680
- return plans;
2681
- } catch (error) {
2682
- throw new Error(`Failed to get plans with validation: ${error.message}`);
2683
- }
2684
- }
2685
- /**
2686
- * Helper method to get a plan by ID with validation
2687
- */
2688
- async getPlanWithValidation(planId) {
2689
- if (!planId || typeof planId !== "string") {
2690
- throw new Error("Plan ID must be a valid string");
2691
- }
2692
- try {
2693
- const plan = await this.getPlan(planId);
2694
- if (!plan || typeof plan !== "object") {
2695
- throw new Error("Invalid plan data received");
2696
- }
2697
- return plan;
2698
- } catch (error) {
2699
- throw new Error(`Failed to get plan with validation: ${error.message}`);
2700
- }
2701
- }
2702
- /**
2703
- * Helper method to create a plan with validation (admin only)
2704
- */
2705
- async createPlanWithValidation(planData) {
2706
- if (!planData || typeof planData !== "object") {
2707
- throw new Error("Plan data must be a valid object");
2708
- }
2709
- const requiredFields = ["name", "key", "price"];
2710
- for (const field of requiredFields) {
2711
- if (!planData[field]) {
2712
- throw new Error(`Required field '${field}' is missing`);
2713
- }
2714
- }
2715
- if (typeof planData.price !== "number" || planData.price < 0) {
2716
- throw new Error("Price must be a positive number");
2717
- }
2718
- if (!/^[a-z0-9-]+$/u.test(planData.key)) {
2719
- throw new Error("Plan key must contain only lowercase letters, numbers, and hyphens");
2720
- }
2721
- return await this.createPlan(planData);
2722
- }
2723
- /**
2724
- * Helper method to update a plan with validation (admin only)
2725
- */
2726
- async updatePlanWithValidation(planId, planData) {
2727
- if (!planId || typeof planId !== "string") {
2728
- throw new Error("Plan ID must be a valid string");
2729
- }
2730
- if (!planData || typeof planData !== "object") {
2731
- throw new Error("Plan data must be a valid object");
2732
- }
2733
- if (planData.price != null) {
2734
- if (typeof planData.price !== "number" || planData.price < 0) {
2735
- throw new Error("Price must be a positive number");
2736
- }
2737
- }
2738
- if (planData.key && !/^[a-z0-9-]+$/u.test(planData.key)) {
2739
- throw new Error("Plan key must contain only lowercase letters, numbers, and hyphens");
2740
- }
2741
- return await this.updatePlan(planId, planData);
2742
- }
2743
- /**
2744
- * Helper method to get active plans only
2745
- */
2746
- async getActivePlans() {
2747
- try {
2748
- const plans = await this.getPlans();
2749
- return plans.filter((plan) => plan.active !== false);
2750
- } catch (error) {
2751
- throw new Error(`Failed to get active plans: ${error.message}`);
2752
- }
2753
- }
2754
- /**
2755
- * Helper method to get plans by price range
2756
- */
2757
- async getPlansByPriceRange(minPrice = 0, maxPrice = Infinity) {
2758
- try {
2759
- const plans = await this.getPlans();
2760
- return plans.filter((plan) => {
2761
- const price = plan.price || 0;
2762
- return price >= minPrice && price <= maxPrice;
2763
- });
2764
- } catch (error) {
2765
- throw new Error(`Failed to get plans by price range: ${error.message}`);
2766
- }
2767
- }
2768
- /**
2769
- * Helper method to find plan by key
2770
- */
2771
- async getPlanByKey(key) {
2772
- if (!key) {
2773
- throw new Error("Plan key is required");
2774
- }
2775
- try {
2776
- const plans = await this.getPlans();
2777
- const plan = plans.find((p) => p.key === key);
2778
- if (!plan) {
2779
- throw new Error(`Plan with key '${key}' not found`);
2780
- }
2781
- return plan;
2782
- } catch (error) {
2783
- throw new Error(`Failed to get plan by key: ${error.message}`);
2784
- }
2785
- }
2786
- }
2787
- export {
2788
- CoreService
2789
- };