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