@symbo.ls/sdk 3.1.2 → 3.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/README.md +143 -2
  2. package/dist/cjs/config/environment.js +98 -30
  3. package/dist/cjs/index.js +144 -24
  4. package/dist/cjs/services/AdminService.js +351 -0
  5. package/dist/cjs/services/AuthService.js +738 -305
  6. package/dist/cjs/services/BaseService.js +158 -6
  7. package/dist/cjs/services/BranchService.js +484 -0
  8. package/dist/cjs/services/CollabService.js +743 -0
  9. package/dist/cjs/services/DnsService.js +340 -0
  10. package/dist/cjs/services/FeatureFlagService.js +175 -0
  11. package/dist/cjs/services/FileService.js +201 -0
  12. package/dist/cjs/services/IntegrationService.js +538 -0
  13. package/dist/cjs/services/MetricsService.js +62 -0
  14. package/dist/cjs/services/PaymentService.js +271 -0
  15. package/dist/cjs/services/PlanService.js +426 -0
  16. package/dist/cjs/services/ProjectService.js +1207 -0
  17. package/dist/cjs/services/PullRequestService.js +503 -0
  18. package/dist/cjs/services/ScreenshotService.js +304 -0
  19. package/dist/cjs/services/SubscriptionService.js +396 -0
  20. package/dist/cjs/services/TrackingService.js +661 -0
  21. package/dist/cjs/services/WaitlistService.js +148 -0
  22. package/dist/cjs/services/index.js +64 -16
  23. package/dist/cjs/state/RootStateManager.js +65 -0
  24. package/dist/cjs/state/rootEventBus.js +74 -0
  25. package/dist/cjs/utils/CollabClient.js +223 -0
  26. package/dist/cjs/utils/TokenManager.js +78 -30
  27. package/dist/cjs/utils/changePreprocessor.js +199 -0
  28. package/dist/cjs/utils/jsonDiff.js +145 -0
  29. package/dist/cjs/utils/ordering.js +309 -0
  30. package/dist/cjs/utils/services.js +301 -103
  31. package/dist/cjs/utils/validation.js +0 -3
  32. package/dist/esm/config/environment.js +98 -30
  33. package/dist/esm/index.js +49505 -8718
  34. package/dist/esm/services/AdminService.js +1132 -0
  35. package/dist/esm/services/AuthService.js +1493 -386
  36. package/dist/esm/services/BaseService.js +757 -6
  37. package/dist/esm/services/BranchService.js +1265 -0
  38. package/dist/esm/services/CollabService.js +26895 -0
  39. package/dist/esm/services/DnsService.js +1121 -0
  40. package/dist/esm/services/FeatureFlagService.js +956 -0
  41. package/dist/esm/services/FileService.js +982 -0
  42. package/dist/esm/services/IntegrationService.js +1319 -0
  43. package/dist/esm/services/MetricsService.js +843 -0
  44. package/dist/esm/services/PaymentService.js +1052 -0
  45. package/dist/esm/services/PlanService.js +1207 -0
  46. package/dist/esm/services/ProjectService.js +2526 -0
  47. package/dist/esm/services/PullRequestService.js +1284 -0
  48. package/dist/esm/services/ScreenshotService.js +1085 -0
  49. package/dist/esm/services/SubscriptionService.js +1177 -0
  50. package/dist/esm/services/TrackingService.js +18454 -0
  51. package/dist/esm/services/WaitlistService.js +929 -0
  52. package/dist/esm/services/index.js +49062 -8569
  53. package/dist/esm/state/RootStateManager.js +90 -0
  54. package/dist/esm/state/rootEventBus.js +56 -0
  55. package/dist/esm/utils/CollabClient.js +18889 -0
  56. package/dist/esm/utils/TokenManager.js +78 -30
  57. package/dist/esm/utils/changePreprocessor.js +542 -0
  58. package/dist/esm/utils/jsonDiff.js +7011 -0
  59. package/dist/esm/utils/ordering.js +291 -0
  60. package/dist/esm/utils/services.js +301 -103
  61. package/dist/esm/utils/validation.js +116 -50
  62. package/dist/node/config/environment.js +98 -30
  63. package/dist/node/index.js +175 -32
  64. package/dist/node/services/AdminService.js +332 -0
  65. package/dist/node/services/AuthService.js +742 -310
  66. package/dist/node/services/BaseService.js +148 -6
  67. package/dist/node/services/BranchService.js +465 -0
  68. package/dist/node/services/CollabService.js +724 -0
  69. package/dist/node/services/DnsService.js +321 -0
  70. package/dist/node/services/FeatureFlagService.js +156 -0
  71. package/dist/node/services/FileService.js +182 -0
  72. package/dist/node/services/IntegrationService.js +519 -0
  73. package/dist/node/services/MetricsService.js +43 -0
  74. package/dist/node/services/PaymentService.js +252 -0
  75. package/dist/node/services/PlanService.js +407 -0
  76. package/dist/node/services/ProjectService.js +1188 -0
  77. package/dist/node/services/PullRequestService.js +484 -0
  78. package/dist/node/services/ScreenshotService.js +285 -0
  79. package/dist/node/services/SubscriptionService.js +377 -0
  80. package/dist/node/services/TrackingService.js +632 -0
  81. package/dist/node/services/WaitlistService.js +129 -0
  82. package/dist/node/services/index.js +64 -16
  83. package/dist/node/state/RootStateManager.js +36 -0
  84. package/dist/node/state/rootEventBus.js +55 -0
  85. package/dist/node/utils/CollabClient.js +194 -0
  86. package/dist/node/utils/TokenManager.js +78 -30
  87. package/dist/node/utils/changePreprocessor.js +180 -0
  88. package/dist/node/utils/jsonDiff.js +116 -0
  89. package/dist/node/utils/ordering.js +290 -0
  90. package/dist/node/utils/services.js +301 -103
  91. package/dist/node/utils/validation.js +0 -3
  92. package/package.json +39 -21
  93. package/src/config/environment.js +99 -28
  94. package/src/index.js +181 -36
  95. package/src/services/AdminService.js +374 -0
  96. package/src/services/AuthService.js +874 -328
  97. package/src/services/BaseService.js +166 -6
  98. package/src/services/BranchService.js +536 -0
  99. package/src/services/CollabService.js +900 -0
  100. package/src/services/DnsService.js +366 -0
  101. package/src/services/FeatureFlagService.js +174 -0
  102. package/src/services/FileService.js +213 -0
  103. package/src/services/IntegrationService.js +548 -0
  104. package/src/services/MetricsService.js +40 -0
  105. package/src/services/PaymentService.js +287 -0
  106. package/src/services/PlanService.js +468 -0
  107. package/src/services/ProjectService.js +1366 -0
  108. package/src/services/PullRequestService.js +537 -0
  109. package/src/services/ScreenshotService.js +258 -0
  110. package/src/services/SubscriptionService.js +425 -0
  111. package/src/services/TrackingService.js +853 -0
  112. package/src/services/WaitlistService.js +130 -0
  113. package/src/services/index.js +80 -13
  114. package/src/services/tests/BranchService/createBranch.test.js +153 -0
  115. package/src/services/tests/BranchService/deleteBranch.test.js +173 -0
  116. package/src/services/tests/BranchService/getBranchChanges.test.js +146 -0
  117. package/src/services/tests/BranchService/listBranches.test.js +87 -0
  118. package/src/services/tests/BranchService/mergeBranch.test.js +210 -0
  119. package/src/services/tests/BranchService/publishVersion.test.js +183 -0
  120. package/src/services/tests/BranchService/renameBranch.test.js +240 -0
  121. package/src/services/tests/BranchService/resetBranch.test.js +152 -0
  122. package/src/services/tests/FeatureFlagService/adminFeatureFlags.test.js +67 -0
  123. package/src/services/tests/FeatureFlagService/getFeatureFlags.test.js +75 -0
  124. package/src/services/tests/FileService/createFileFormData.test.js +74 -0
  125. package/src/services/tests/FileService/getFileUrl.test.js +69 -0
  126. package/src/services/tests/FileService/updateProjectIcon.test.js +109 -0
  127. package/src/services/tests/FileService/uploadDocument.test.js +36 -0
  128. package/src/services/tests/FileService/uploadFile.test.js +78 -0
  129. package/src/services/tests/FileService/uploadFileWithValidation.test.js +114 -0
  130. package/src/services/tests/FileService/uploadImage.test.js +36 -0
  131. package/src/services/tests/FileService/uploadMultipleFiles.test.js +111 -0
  132. package/src/services/tests/FileService/validateFile.test.js +63 -0
  133. package/src/services/tests/PlanService/createPlan.test.js +104 -0
  134. package/src/services/tests/PlanService/createPlanWithValidation.test.js +523 -0
  135. package/src/services/tests/PlanService/deletePlan.test.js +92 -0
  136. package/src/services/tests/PlanService/getActivePlans.test.js +123 -0
  137. package/src/services/tests/PlanService/getAdminPlans.test.js +84 -0
  138. package/src/services/tests/PlanService/getPlan.test.js +50 -0
  139. package/src/services/tests/PlanService/getPlanByKey.test.js +109 -0
  140. package/src/services/tests/PlanService/getPlanWithValidation.test.js +85 -0
  141. package/src/services/tests/PlanService/getPlans.test.js +53 -0
  142. package/src/services/tests/PlanService/getPlansByPriceRange.test.js +109 -0
  143. package/src/services/tests/PlanService/getPlansWithValidation.test.js +48 -0
  144. package/src/services/tests/PlanService/initializePlans.test.js +75 -0
  145. package/src/services/tests/PlanService/updatePlan.test.js +111 -0
  146. package/src/services/tests/PlanService/updatePlanWithValidation.test.js +556 -0
  147. package/src/state/RootStateManager.js +76 -0
  148. package/src/state/rootEventBus.js +67 -0
  149. package/src/utils/CollabClient.js +248 -0
  150. package/src/utils/TokenManager.js +88 -33
  151. package/src/utils/changePreprocessor.js +239 -0
  152. package/src/utils/jsonDiff.js +144 -0
  153. package/src/utils/ordering.js +271 -0
  154. package/src/utils/services.js +326 -107
  155. package/src/utils/validation.js +0 -3
  156. package/dist/cjs/services/AIService.js +0 -155
  157. package/dist/cjs/services/BasedService.js +0 -1185
  158. package/dist/cjs/services/CoreService.js +0 -1751
  159. package/dist/cjs/services/SocketIOService.js +0 -307
  160. package/dist/cjs/services/SocketService.js +0 -161
  161. package/dist/cjs/services/SymstoryService.js +0 -571
  162. package/dist/cjs/utils/basedQuerys.js +0 -181
  163. package/dist/cjs/utils/symstoryClient.js +0 -259
  164. package/dist/esm/services/AIService.js +0 -185
  165. package/dist/esm/services/BasedService.js +0 -5278
  166. package/dist/esm/services/CoreService.js +0 -2264
  167. package/dist/esm/services/SocketIOService.js +0 -470
  168. package/dist/esm/services/SocketService.js +0 -191
  169. package/dist/esm/services/SymstoryService.js +0 -7041
  170. package/dist/esm/utils/basedQuerys.js +0 -163
  171. package/dist/esm/utils/symstoryClient.js +0 -370
  172. package/dist/node/services/AIService.js +0 -136
  173. package/dist/node/services/BasedService.js +0 -1156
  174. package/dist/node/services/CoreService.js +0 -1722
  175. package/dist/node/services/SocketIOService.js +0 -278
  176. package/dist/node/services/SocketService.js +0 -142
  177. package/dist/node/services/SymstoryService.js +0 -542
  178. package/dist/node/utils/basedQuerys.js +0 -162
  179. package/dist/node/utils/symstoryClient.js +0 -230
  180. package/src/services/AIService.js +0 -150
  181. package/src/services/BasedService.js +0 -1301
  182. package/src/services/CoreService.js +0 -1943
  183. package/src/services/SocketIOService.js +0 -334
  184. package/src/services/SocketService.js +0 -168
  185. package/src/services/SymstoryService.js +0 -649
  186. package/src/utils/basedQuerys.js +0 -164
  187. package/src/utils/symstoryClient.js +0 -252
@@ -1,1722 +0,0 @@
1
- import { BaseService } from "./BaseService.js";
2
- import environment from "../config/environment.js";
3
- import { getTokenManager } from "../utils/TokenManager.js";
4
- class CoreService extends BaseService {
5
- constructor(config) {
6
- super(config);
7
- this._client = null;
8
- this._initialized = false;
9
- this._baseUrl = null;
10
- this._tokenManager = null;
11
- }
12
- init({ context }) {
13
- try {
14
- const { appKey, authToken } = context || this._context;
15
- this._baseUrl = environment.apiUrl || environment.baseUrl;
16
- if (!this._baseUrl) {
17
- throw new Error("Core service base URL not configured");
18
- }
19
- this._tokenManager = getTokenManager({
20
- apiUrl: this._baseUrl,
21
- onTokenRefresh: (tokens) => {
22
- this.updateContext({ authToken: tokens.accessToken });
23
- },
24
- onTokenExpired: () => {
25
- this.updateContext({ authToken: null });
26
- },
27
- onTokenError: (error) => {
28
- console.error("Token management error:", error);
29
- }
30
- });
31
- if (authToken) {
32
- this._tokenManager.setTokens({ access_token: authToken });
33
- }
34
- this._info = {
35
- config: {
36
- baseUrl: this._baseUrl,
37
- appKey: appKey ? `${appKey.substr(0, 4)}...${appKey.substr(-4)}` : null,
38
- hasToken: Boolean(authToken)
39
- }
40
- };
41
- this._initialized = true;
42
- this._setReady();
43
- } catch (error) {
44
- this._setError(error);
45
- throw error;
46
- }
47
- }
48
- // Helper to check if method requires initialization
49
- _requiresInit(methodName) {
50
- const noInitMethods = /* @__PURE__ */ new Set([
51
- "register",
52
- "login",
53
- "googleAuth",
54
- "githubAuth",
55
- "requestPasswordReset",
56
- "confirmPasswordReset",
57
- "confirmRegistration",
58
- "verifyEmail"
59
- ]);
60
- return !noInitMethods.has(methodName);
61
- }
62
- // Override _requireReady to be more flexible
63
- _requireReady(methodName) {
64
- if (this._requiresInit(methodName) && !this._initialized) {
65
- throw new Error("Core service not initialized");
66
- }
67
- }
68
- // Debug method to check token status
69
- getTokenDebugInfo() {
70
- if (!this._tokenManager) {
71
- return {
72
- tokenManagerExists: false,
73
- error: "TokenManager not initialized"
74
- };
75
- }
76
- const tokenStatus = this._tokenManager.getTokenStatus();
77
- const { tokens } = this._tokenManager;
78
- return {
79
- tokenManagerExists: true,
80
- tokenStatus,
81
- hasAccessToken: Boolean(tokens.accessToken),
82
- hasRefreshToken: Boolean(tokens.refreshToken),
83
- accessTokenPreview: tokens.accessToken ? `${tokens.accessToken.substring(0, 20)}...` : null,
84
- expiresAt: tokens.expiresAt,
85
- timeToExpiry: tokenStatus.timeToExpiry,
86
- authHeader: this._tokenManager.getAuthHeader()
87
- };
88
- }
89
- // Helper method to make HTTP requests
90
- async _request(endpoint, options = {}) {
91
- const url = `${this._baseUrl}/core${endpoint}`;
92
- const defaultHeaders = {
93
- "Content-Type": "application/json"
94
- };
95
- if (this._requiresInit(options.methodName) && this._tokenManager) {
96
- try {
97
- const validToken = await this._tokenManager.ensureValidToken();
98
- console.log(`[CoreService] Token check for ${options.methodName}:`, {
99
- hasValidToken: Boolean(validToken),
100
- tokenPreview: validToken ? `${validToken.substring(0, 20)}...` : null
101
- });
102
- if (validToken) {
103
- const authHeader = this._tokenManager.getAuthHeader();
104
- if (authHeader) {
105
- defaultHeaders.Authorization = authHeader;
106
- console.log(`[CoreService] Added auth header for ${options.methodName}`);
107
- }
108
- }
109
- } catch (error) {
110
- console.warn("Token management failed, proceeding without authentication:", error);
111
- }
112
- } else if (this._requiresInit(options.methodName)) {
113
- const { authToken } = this._context;
114
- if (authToken) {
115
- defaultHeaders.Authorization = `Bearer ${authToken}`;
116
- console.log(`[CoreService] Using context token for ${options.methodName}`);
117
- }
118
- }
119
- try {
120
- const response = await fetch(url, {
121
- ...options,
122
- headers: {
123
- ...defaultHeaders,
124
- ...options.headers
125
- }
126
- });
127
- if (!response.ok) {
128
- let error = { message: `HTTP ${response.status}: ${response.statusText}` };
129
- try {
130
- error = await response.json();
131
- } catch {
132
- }
133
- throw new Error(error.message || error.error || "Request failed");
134
- }
135
- return response.status === 204 ? null : response.json();
136
- } catch (error) {
137
- throw new Error(`Request failed: ${error.message}`);
138
- }
139
- }
140
- // ==================== AUTH METHODS ====================
141
- async register(userData) {
142
- try {
143
- return await this._request("/auth/register", {
144
- method: "POST",
145
- body: JSON.stringify(userData),
146
- methodName: "register"
147
- });
148
- } catch (error) {
149
- throw new Error(`Registration failed: ${error.message}`);
150
- }
151
- }
152
- async login(email, password) {
153
- var _a;
154
- try {
155
- const response = await this._request("/auth/login", {
156
- method: "POST",
157
- body: JSON.stringify({ email, password }),
158
- methodName: "login"
159
- });
160
- if (response.success && response.data && response.data.tokens) {
161
- const { tokens } = response.data;
162
- const tokenData = {
163
- access_token: tokens.accessToken,
164
- refresh_token: tokens.refreshToken,
165
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
166
- token_type: "Bearer"
167
- };
168
- if (this._tokenManager) {
169
- this._tokenManager.setTokens(tokenData);
170
- }
171
- this.updateContext({ authToken: tokens.accessToken });
172
- }
173
- return response;
174
- } catch (error) {
175
- throw new Error(`Login failed: ${error.message}`);
176
- }
177
- }
178
- async logout() {
179
- this._requireReady("logout");
180
- try {
181
- await this._request("/auth/logout", {
182
- method: "POST",
183
- methodName: "logout"
184
- });
185
- if (this._tokenManager) {
186
- this._tokenManager.clearTokens();
187
- }
188
- this.updateContext({ authToken: null });
189
- } catch (error) {
190
- if (this._tokenManager) {
191
- this._tokenManager.clearTokens();
192
- }
193
- this.updateContext({ authToken: null });
194
- throw new Error(`Logout failed: ${error.message}`);
195
- }
196
- }
197
- async refreshToken(refreshToken) {
198
- try {
199
- return await this._request("/auth/refresh", {
200
- method: "POST",
201
- body: JSON.stringify({ refreshToken }),
202
- methodName: "refreshToken"
203
- });
204
- } catch (error) {
205
- throw new Error(`Token refresh failed: ${error.message}`);
206
- }
207
- }
208
- async googleAuth(idToken) {
209
- var _a;
210
- try {
211
- const response = await this._request("/auth/google", {
212
- method: "POST",
213
- body: JSON.stringify({ idToken }),
214
- methodName: "googleAuth"
215
- });
216
- if (response.success && response.data && response.data.tokens) {
217
- const { tokens } = response.data;
218
- const tokenData = {
219
- access_token: tokens.accessToken,
220
- refresh_token: tokens.refreshToken,
221
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
222
- token_type: "Bearer"
223
- };
224
- if (this._tokenManager) {
225
- this._tokenManager.setTokens(tokenData);
226
- }
227
- this.updateContext({ authToken: tokens.accessToken });
228
- }
229
- return response;
230
- } catch (error) {
231
- throw new Error(`Google auth failed: ${error.message}`);
232
- }
233
- }
234
- async githubAuth(code) {
235
- var _a;
236
- try {
237
- const response = await this._request("/auth/github", {
238
- method: "POST",
239
- body: JSON.stringify({ code }),
240
- methodName: "githubAuth"
241
- });
242
- if (response.success && response.data && response.data.tokens) {
243
- const { tokens } = response.data;
244
- const tokenData = {
245
- access_token: tokens.accessToken,
246
- refresh_token: tokens.refreshToken,
247
- expires_in: (_a = tokens.accessTokenExp) == null ? void 0 : _a.expiresIn,
248
- token_type: "Bearer"
249
- };
250
- if (this._tokenManager) {
251
- this._tokenManager.setTokens(tokenData);
252
- }
253
- this.updateContext({ authToken: tokens.accessToken });
254
- }
255
- return response;
256
- } catch (error) {
257
- throw new Error(`GitHub auth failed: ${error.message}`);
258
- }
259
- }
260
- async requestPasswordReset(email) {
261
- try {
262
- return await this._request("/auth/request-password-reset", {
263
- method: "POST",
264
- body: JSON.stringify({ email }),
265
- methodName: "requestPasswordReset"
266
- });
267
- } catch (error) {
268
- throw new Error(`Password reset request failed: ${error.message}`);
269
- }
270
- }
271
- async confirmPasswordReset(token, password) {
272
- try {
273
- return await this._request("/auth/reset-password-confirm", {
274
- method: "POST",
275
- body: JSON.stringify({ token, password }),
276
- methodName: "confirmPasswordReset"
277
- });
278
- } catch (error) {
279
- throw new Error(`Password reset confirmation failed: ${error.message}`);
280
- }
281
- }
282
- async confirmRegistration(token) {
283
- try {
284
- return await this._request("/auth/register-confirmation", {
285
- method: "POST",
286
- body: JSON.stringify({ token }),
287
- methodName: "confirmRegistration"
288
- });
289
- } catch (error) {
290
- throw new Error(`Registration confirmation failed: ${error.message}`);
291
- }
292
- }
293
- async requestPasswordChange() {
294
- this._requireReady("requestPasswordChange");
295
- try {
296
- return await this._request("/auth/request-password-change", {
297
- method: "POST",
298
- methodName: "requestPasswordChange"
299
- });
300
- } catch (error) {
301
- throw new Error(`Password change request failed: ${error.message}`);
302
- }
303
- }
304
- async confirmPasswordChange(currentPassword, newPassword, code) {
305
- this._requireReady("confirmPasswordChange");
306
- try {
307
- return await this._request("/auth/confirm-password-change", {
308
- method: "POST",
309
- body: JSON.stringify({ currentPassword, newPassword, code }),
310
- methodName: "confirmPasswordChange"
311
- });
312
- } catch (error) {
313
- throw new Error(`Password change confirmation failed: ${error.message}`);
314
- }
315
- }
316
- async getMe() {
317
- this._requireReady("getMe");
318
- try {
319
- return await this._request("/auth/me", {
320
- method: "GET",
321
- methodName: "getMe"
322
- });
323
- } catch (error) {
324
- throw new Error(`Failed to get user profile: ${error.message}`);
325
- }
326
- }
327
- /**
328
- * Get stored authentication state (backward compatibility method)
329
- * Replaces AuthService.getStoredAuthState()
330
- */
331
- async getStoredAuthState() {
332
- try {
333
- if (!this._tokenManager) {
334
- return {
335
- userId: false,
336
- authToken: false
337
- };
338
- }
339
- const tokenStatus = this._tokenManager.getTokenStatus();
340
- if (!tokenStatus.hasTokens) {
341
- return {
342
- userId: false,
343
- authToken: false
344
- };
345
- }
346
- if (!tokenStatus.isValid && tokenStatus.hasRefreshToken) {
347
- try {
348
- await this._tokenManager.ensureValidToken();
349
- } catch (error) {
350
- this._tokenManager.clearTokens();
351
- return {
352
- userId: false,
353
- authToken: false,
354
- error: `Token refresh failed: ${error.message}`
355
- };
356
- }
357
- }
358
- try {
359
- const currentUser = await this.getMe();
360
- const userProjects = await this.getUserProjects();
361
- return {
362
- userId: currentUser.data.id,
363
- authToken: this._tokenManager.getAccessToken(),
364
- user: {
365
- ...currentUser.data,
366
- projects: (userProjects == null ? void 0 : userProjects.data) || []
367
- },
368
- error: null
369
- };
370
- } catch (error) {
371
- this._tokenManager.clearTokens();
372
- return {
373
- userId: false,
374
- authToken: false,
375
- error: `Failed to get user data: ${error.message}`
376
- };
377
- }
378
- } catch (error) {
379
- return {
380
- userId: false,
381
- authToken: false,
382
- error: `Failed to get stored auth state: ${error.message}`
383
- };
384
- }
385
- }
386
- // ==================== USER METHODS ====================
387
- async getUserProfile() {
388
- this._requireReady("getUserProfile");
389
- try {
390
- return await this._request("/users/profile", {
391
- method: "GET",
392
- methodName: "getUserProfile"
393
- });
394
- } catch (error) {
395
- throw new Error(`Failed to get user profile: ${error.message}`);
396
- }
397
- }
398
- async updateUserProfile(profileData) {
399
- this._requireReady("updateUserProfile");
400
- try {
401
- return await this._request("/users/profile", {
402
- method: "PATCH",
403
- body: JSON.stringify(profileData),
404
- methodName: "updateUserProfile"
405
- });
406
- } catch (error) {
407
- throw new Error(`Failed to update user profile: ${error.message}`);
408
- }
409
- }
410
- async getUserProjects() {
411
- this._requireReady("getUserProjects");
412
- try {
413
- return await this._request("/users/projects", {
414
- method: "GET",
415
- methodName: "getUserProjects"
416
- });
417
- } catch (error) {
418
- throw new Error(`Failed to get user projects: ${error.message}`);
419
- }
420
- }
421
- async getUser(userId) {
422
- this._requireReady("getUser");
423
- if (!userId) {
424
- throw new Error("User ID is required");
425
- }
426
- try {
427
- return await this._request(`/users/${userId}`, {
428
- method: "GET",
429
- methodName: "getUser"
430
- });
431
- } catch (error) {
432
- throw new Error(`Failed to get user: ${error.message}`);
433
- }
434
- }
435
- async getUserByEmail(email) {
436
- this._requireReady("getUserByEmail");
437
- if (!email) {
438
- throw new Error("Email is required");
439
- }
440
- try {
441
- return await this._request("/auth/user", {
442
- method: "GET",
443
- headers: {
444
- "X-User-Email": email
445
- },
446
- methodName: "getUserByEmail"
447
- });
448
- } catch (error) {
449
- throw new Error(`Failed to get user by email: ${error.message}`);
450
- }
451
- }
452
- // ==================== PROJECT METHODS ====================
453
- async createProject(projectData) {
454
- this._requireReady("createProject");
455
- try {
456
- return await this._request("/projects", {
457
- method: "POST",
458
- body: JSON.stringify(projectData),
459
- methodName: "createProject"
460
- });
461
- } catch (error) {
462
- throw new Error(`Failed to create project: ${error.message}`);
463
- }
464
- }
465
- async getProjects() {
466
- this._requireReady("getProjects");
467
- try {
468
- return await this._request("/projects", {
469
- method: "GET",
470
- methodName: "getProjects"
471
- });
472
- } catch (error) {
473
- throw new Error(`Failed to get projects: ${error.message}`);
474
- }
475
- }
476
- async getProject(projectId) {
477
- this._requireReady("getProject");
478
- if (!projectId) {
479
- throw new Error("Project ID is required");
480
- }
481
- try {
482
- return await this._request(`/projects/${projectId}`, {
483
- method: "GET",
484
- methodName: "getProject"
485
- });
486
- } catch (error) {
487
- throw new Error(`Failed to get project: ${error.message}`);
488
- }
489
- }
490
- async getProjectByKey(key) {
491
- this._requireReady("getProjectByKey");
492
- if (!key) {
493
- throw new Error("Project key is required");
494
- }
495
- try {
496
- return await this._request(`/projects/check-key/${key}`, {
497
- method: "GET",
498
- methodName: "getProjectByKey"
499
- });
500
- } catch (error) {
501
- throw new Error(`Failed to get project by key: ${error.message}`);
502
- }
503
- }
504
- async updateProject(projectId, data) {
505
- this._requireReady("updateProject");
506
- if (!projectId) {
507
- throw new Error("Project ID is required");
508
- }
509
- try {
510
- return await this._request(`/projects/${projectId}`, {
511
- method: "PATCH",
512
- body: JSON.stringify(data),
513
- methodName: "updateProject"
514
- });
515
- } catch (error) {
516
- throw new Error(`Failed to update project: ${error.message}`);
517
- }
518
- }
519
- async updateProjectComponents(projectId, components) {
520
- this._requireReady("updateProjectComponents");
521
- if (!projectId) {
522
- throw new Error("Project ID is required");
523
- }
524
- try {
525
- return await this._request(`/projects/${projectId}/components`, {
526
- method: "PATCH",
527
- body: JSON.stringify({ components }),
528
- methodName: "updateProjectComponents"
529
- });
530
- } catch (error) {
531
- throw new Error(`Failed to update project components: ${error.message}`);
532
- }
533
- }
534
- async updateProjectSettings(projectId, settings) {
535
- this._requireReady("updateProjectSettings");
536
- if (!projectId) {
537
- throw new Error("Project ID is required");
538
- }
539
- try {
540
- return await this._request(`/projects/${projectId}/settings`, {
541
- method: "PATCH",
542
- body: JSON.stringify({ settings }),
543
- methodName: "updateProjectSettings"
544
- });
545
- } catch (error) {
546
- throw new Error(`Failed to update project settings: ${error.message}`);
547
- }
548
- }
549
- async updateProjectName(projectId, name) {
550
- this._requireReady("updateProjectName");
551
- if (!projectId) {
552
- throw new Error("Project ID is required");
553
- }
554
- try {
555
- return await this._request(`/projects/${projectId}`, {
556
- method: "PATCH",
557
- body: JSON.stringify({ name }),
558
- methodName: "updateProjectName"
559
- });
560
- } catch (error) {
561
- throw new Error(`Failed to update project name: ${error.message}`);
562
- }
563
- }
564
- async updateProjectPackage(projectId, pkg) {
565
- this._requireReady("updateProjectPackage");
566
- if (!projectId) {
567
- throw new Error("Project ID is required");
568
- }
569
- try {
570
- return await this._request(`/projects/${projectId}/tier`, {
571
- method: "PATCH",
572
- body: JSON.stringify({ tier: pkg }),
573
- methodName: "updateProjectPackage"
574
- });
575
- } catch (error) {
576
- throw new Error(`Failed to update project package: ${error.message}`);
577
- }
578
- }
579
- async duplicateProject(projectId, newName, newKey) {
580
- this._requireReady("duplicateProject");
581
- if (!projectId) {
582
- throw new Error("Project ID is required");
583
- }
584
- try {
585
- return await this._request(`/projects/${projectId}/duplicate`, {
586
- method: "POST",
587
- body: JSON.stringify({ name: newName, key: newKey }),
588
- methodName: "duplicateProject"
589
- });
590
- } catch (error) {
591
- throw new Error(`Failed to duplicate project: ${error.message}`);
592
- }
593
- }
594
- async removeProject(projectId) {
595
- this._requireReady("removeProject");
596
- if (!projectId) {
597
- throw new Error("Project ID is required");
598
- }
599
- try {
600
- return await this._request(`/projects/${projectId}`, {
601
- method: "DELETE",
602
- methodName: "removeProject"
603
- });
604
- } catch (error) {
605
- throw new Error(`Failed to remove project: ${error.message}`);
606
- }
607
- }
608
- async checkProjectKeyAvailability(key) {
609
- this._requireReady("checkProjectKeyAvailability");
610
- if (!key) {
611
- throw new Error("Project key is required");
612
- }
613
- try {
614
- return await this._request(`/projects/check-key/${key}`, {
615
- method: "GET",
616
- methodName: "checkProjectKeyAvailability"
617
- });
618
- } catch (error) {
619
- throw new Error(`Failed to check project key availability: ${error.message}`);
620
- }
621
- }
622
- // ==================== PROJECT MEMBER METHODS ====================
623
- async getProjectMembers(projectId) {
624
- this._requireReady("getProjectMembers");
625
- if (!projectId) {
626
- throw new Error("Project ID is required");
627
- }
628
- try {
629
- return await this._request(`/projects/${projectId}/members`, {
630
- method: "GET",
631
- methodName: "getProjectMembers"
632
- });
633
- } catch (error) {
634
- throw new Error(`Failed to get project members: ${error.message}`);
635
- }
636
- }
637
- async inviteMember(projectId, email, message, role = "guest") {
638
- this._requireReady("inviteMember");
639
- if (!projectId || !email) {
640
- throw new Error("Project ID and email are required");
641
- }
642
- try {
643
- return await this._request(`/projects/${projectId}/invite`, {
644
- method: "POST",
645
- body: JSON.stringify({ email, role, message }),
646
- methodName: "inviteMember"
647
- });
648
- } catch (error) {
649
- throw new Error(`Failed to invite member: ${error.message}`);
650
- }
651
- }
652
- async acceptInvite(projectId, token) {
653
- this._requireReady("acceptInvite");
654
- if (!projectId || !token) {
655
- throw new Error("Project ID and token are required");
656
- }
657
- try {
658
- return await this._request(`/projects/${projectId}/accept-invite`, {
659
- method: "POST",
660
- body: JSON.stringify({ token }),
661
- methodName: "acceptInvite"
662
- });
663
- } catch (error) {
664
- throw new Error(`Failed to accept invite: ${error.message}`);
665
- }
666
- }
667
- async updateMemberRole(projectId, memberId, role) {
668
- this._requireReady("updateMemberRole");
669
- if (!projectId || !memberId || !role) {
670
- throw new Error("Project ID, member ID, and role are required");
671
- }
672
- try {
673
- return await this._request(`/projects/${projectId}/members/${memberId}`, {
674
- method: "PATCH",
675
- body: JSON.stringify({ role }),
676
- methodName: "updateMemberRole"
677
- });
678
- } catch (error) {
679
- throw new Error(`Failed to update member role: ${error.message}`);
680
- }
681
- }
682
- async removeMember(projectId, memberId) {
683
- this._requireReady("removeMember");
684
- if (!projectId || !memberId) {
685
- throw new Error("Project ID and member ID are required");
686
- }
687
- try {
688
- return await this._request(`/projects/${projectId}/members/${memberId}`, {
689
- method: "DELETE",
690
- methodName: "removeMember"
691
- });
692
- } catch (error) {
693
- throw new Error(`Failed to remove member: ${error.message}`);
694
- }
695
- }
696
- // ==================== PROJECT LIBRARY METHODS ====================
697
- async getAvailableLibraries(params = {}) {
698
- this._requireReady("getAvailableLibraries");
699
- const queryParams = new URLSearchParams(params).toString();
700
- try {
701
- return await this._request(`/projects/libraries/available?${queryParams}`, {
702
- method: "GET",
703
- methodName: "getAvailableLibraries"
704
- });
705
- } catch (error) {
706
- throw new Error(`Failed to get available libraries: ${error.message}`);
707
- }
708
- }
709
- async getProjectLibraries(projectId) {
710
- this._requireReady("getProjectLibraries");
711
- if (!projectId) {
712
- throw new Error("Project ID is required");
713
- }
714
- try {
715
- return await this._request(`/projects/${projectId}/libraries`, {
716
- method: "GET",
717
- methodName: "getProjectLibraries"
718
- });
719
- } catch (error) {
720
- throw new Error(`Failed to get project libraries: ${error.message}`);
721
- }
722
- }
723
- async addProjectLibraries(projectId, libraryIds) {
724
- this._requireReady("addProjectLibraries");
725
- if (!projectId || !libraryIds) {
726
- throw new Error("Project ID and library IDs are required");
727
- }
728
- try {
729
- return await this._request(`/projects/${projectId}/libraries`, {
730
- method: "POST",
731
- body: JSON.stringify({ libraryIds }),
732
- methodName: "addProjectLibraries"
733
- });
734
- } catch (error) {
735
- throw new Error(`Failed to add project libraries: ${error.message}`);
736
- }
737
- }
738
- async removeProjectLibraries(projectId, libraryIds) {
739
- this._requireReady("removeProjectLibraries");
740
- if (!projectId || !libraryIds) {
741
- throw new Error("Project ID and library IDs are required");
742
- }
743
- try {
744
- return await this._request(`/projects/${projectId}/libraries`, {
745
- method: "DELETE",
746
- body: JSON.stringify({ libraryIds }),
747
- methodName: "removeProjectLibraries"
748
- });
749
- } catch (error) {
750
- throw new Error(`Failed to remove project libraries: ${error.message}`);
751
- }
752
- }
753
- // ==================== FILE METHODS ====================
754
- async uploadFile(file, options = {}) {
755
- this._requireReady("uploadFile");
756
- if (!file) {
757
- throw new Error("File is required for upload");
758
- }
759
- const formData = new FormData();
760
- formData.append("file", file);
761
- if (options.projectId) {
762
- formData.append("projectId", options.projectId);
763
- }
764
- if (options.tags) {
765
- formData.append("tags", JSON.stringify(options.tags));
766
- }
767
- if (options.visibility) {
768
- formData.append("visibility", options.visibility);
769
- }
770
- if (options.metadata) {
771
- formData.append("metadata", JSON.stringify(options.metadata));
772
- }
773
- try {
774
- return await this._request("/files/upload", {
775
- method: "POST",
776
- body: formData,
777
- headers: {},
778
- // Let browser set Content-Type for FormData
779
- methodName: "uploadFile"
780
- });
781
- } catch (error) {
782
- throw new Error(`File upload failed: ${error.message}`);
783
- }
784
- }
785
- async updateProjectIcon(projectId, iconFile) {
786
- this._requireReady("updateProjectIcon");
787
- if (!projectId || !iconFile) {
788
- throw new Error("Project ID and icon file are required");
789
- }
790
- const formData = new FormData();
791
- formData.append("icon", iconFile);
792
- formData.append("projectId", projectId);
793
- try {
794
- return await this._request("/files/upload-project-icon", {
795
- method: "POST",
796
- body: formData,
797
- headers: {},
798
- // Let browser set Content-Type for FormData
799
- methodName: "updateProjectIcon"
800
- });
801
- } catch (error) {
802
- throw new Error(`Failed to update project icon: ${error.message}`);
803
- }
804
- }
805
- // ==================== PAYMENT METHODS ====================
806
- async checkout(options = {}) {
807
- this._requireReady("checkout");
808
- const {
809
- projectId,
810
- seats = 1,
811
- price = "starter_monthly",
812
- successUrl = `${window.location.origin}/success`,
813
- cancelUrl = `${window.location.origin}/pricing`
814
- } = options;
815
- if (!projectId) {
816
- throw new Error("Project ID is required for checkout");
817
- }
818
- try {
819
- return await this._request("/payments/checkout", {
820
- method: "POST",
821
- body: JSON.stringify({
822
- projectId,
823
- seats,
824
- price,
825
- successUrl,
826
- cancelUrl
827
- }),
828
- methodName: "checkout"
829
- });
830
- } catch (error) {
831
- throw new Error(`Failed to checkout: ${error.message}`);
832
- }
833
- }
834
- async getSubscriptionStatus(projectId) {
835
- this._requireReady("getSubscriptionStatus");
836
- if (!projectId) {
837
- throw new Error("Project ID is required");
838
- }
839
- try {
840
- return await this._request(`/payments/subscription/${projectId}`, {
841
- method: "GET",
842
- methodName: "getSubscriptionStatus"
843
- });
844
- } catch (error) {
845
- throw new Error(`Failed to get subscription status: ${error.message}`);
846
- }
847
- }
848
- // ==================== DNS METHODS ====================
849
- async createDnsRecord(domain, options = {}) {
850
- this._requireReady("createDnsRecord");
851
- if (!domain) {
852
- throw new Error("Domain is required");
853
- }
854
- try {
855
- return await this._request("/dns/records", {
856
- method: "POST",
857
- body: JSON.stringify({ domain, ...options }),
858
- methodName: "createDnsRecord"
859
- });
860
- } catch (error) {
861
- throw new Error(`Failed to create DNS record: ${error.message}`);
862
- }
863
- }
864
- async getDnsRecord(domain) {
865
- this._requireReady("getDnsRecord");
866
- if (!domain) {
867
- throw new Error("Domain is required");
868
- }
869
- try {
870
- return await this._request(`/dns/records/${domain}`, {
871
- method: "GET",
872
- methodName: "getDnsRecord"
873
- });
874
- } catch (error) {
875
- throw new Error(`Failed to get DNS record: ${error.message}`);
876
- }
877
- }
878
- async removeDnsRecord(domain) {
879
- this._requireReady("removeDnsRecord");
880
- if (!domain) {
881
- throw new Error("Domain is required");
882
- }
883
- try {
884
- return await this._request(`/dns/records/${domain}`, {
885
- method: "DELETE",
886
- methodName: "removeDnsRecord"
887
- });
888
- } catch (error) {
889
- throw new Error(`Failed to remove DNS record: ${error.message}`);
890
- }
891
- }
892
- async setProjectDomains(projectKey, customDomain, hasCustomDomainAccess = false) {
893
- this._requireReady("setProjectDomains");
894
- if (!projectKey) {
895
- throw new Error("Project key is required");
896
- }
897
- try {
898
- return await this._request("/dns/project-domains", {
899
- method: "POST",
900
- body: JSON.stringify({
901
- projectKey,
902
- customDomain,
903
- hasCustomDomainAccess
904
- }),
905
- methodName: "setProjectDomains"
906
- });
907
- } catch (error) {
908
- throw new Error(`Failed to set project domains: ${error.message}`);
909
- }
910
- }
911
- // ==================== UTILITY METHODS ====================
912
- async getHealthStatus() {
913
- try {
914
- return await this._request("/health", {
915
- method: "GET",
916
- methodName: "getHealthStatus"
917
- });
918
- } catch (error) {
919
- throw new Error(`Failed to get health status: ${error.message}`);
920
- }
921
- }
922
- // ==================== PROJECT DATA METHODS (SYMSTORY REPLACEMENT) ====================
923
- /**
924
- * Apply changes to a project, creating a new version
925
- * Replaces: SymstoryService.updateData()
926
- */
927
- async applyProjectChanges(projectId, changes, options = {}) {
928
- this._requireReady("applyProjectChanges");
929
- if (!projectId) {
930
- throw new Error("Project ID is required");
931
- }
932
- if (!Array.isArray(changes)) {
933
- throw new Error("Changes must be an array");
934
- }
935
- const {
936
- message,
937
- branch = "main",
938
- type = "patch"
939
- } = options;
940
- try {
941
- const response = await this._request(`/projects/${projectId}/changes`, {
942
- method: "POST",
943
- body: JSON.stringify({
944
- changes,
945
- message,
946
- branch,
947
- type
948
- }),
949
- methodName: "applyProjectChanges"
950
- });
951
- return response;
952
- } catch (error) {
953
- throw new Error(`Failed to apply project changes: ${error.message}`);
954
- }
955
- }
956
- /**
957
- * Get current project data for a specific branch
958
- * Replaces: SymstoryService.getData()
959
- */
960
- async getProjectData(projectId, options = {}) {
961
- this._requireReady("getProjectData");
962
- if (!projectId) {
963
- throw new Error("Project ID is required");
964
- }
965
- const {
966
- branch = "main",
967
- includeHistory = false
968
- } = options;
969
- const queryParams = new URLSearchParams({
970
- branch,
971
- includeHistory: includeHistory.toString()
972
- }).toString();
973
- try {
974
- return await this._request(`/projects/${projectId}/data?${queryParams}`, {
975
- method: "GET",
976
- methodName: "getProjectData"
977
- });
978
- } catch (error) {
979
- throw new Error(`Failed to get project data: ${error.message}`);
980
- }
981
- }
982
- /**
983
- * Get project versions with pagination
984
- */
985
- async getProjectVersions(projectId, options = {}) {
986
- this._requireReady("getProjectVersions");
987
- if (!projectId) {
988
- throw new Error("Project ID is required");
989
- }
990
- const {
991
- branch = "main",
992
- page = 1,
993
- limit = 50
994
- } = options;
995
- const queryParams = new URLSearchParams({
996
- branch,
997
- page: page.toString(),
998
- limit: limit.toString()
999
- }).toString();
1000
- try {
1001
- return await this._request(`/projects/${projectId}/versions?${queryParams}`, {
1002
- method: "GET",
1003
- methodName: "getProjectVersions"
1004
- });
1005
- } catch (error) {
1006
- throw new Error(`Failed to get project versions: ${error.message}`);
1007
- }
1008
- }
1009
- /**
1010
- * Restore project to a previous version
1011
- * Replaces: SymstoryService.restoreVersion()
1012
- */
1013
- async restoreProjectVersion(projectId, version, options = {}) {
1014
- this._requireReady("restoreProjectVersion");
1015
- if (!projectId) {
1016
- throw new Error("Project ID is required");
1017
- }
1018
- if (!version) {
1019
- throw new Error("Version is required");
1020
- }
1021
- const {
1022
- message,
1023
- branch = "main",
1024
- type = "patch"
1025
- } = options;
1026
- try {
1027
- return await this._request(`/projects/${projectId}/restore`, {
1028
- method: "POST",
1029
- body: JSON.stringify({
1030
- version,
1031
- message,
1032
- branch,
1033
- type
1034
- }),
1035
- methodName: "restoreProjectVersion"
1036
- });
1037
- } catch (error) {
1038
- throw new Error(`Failed to restore project version: ${error.message}`);
1039
- }
1040
- }
1041
- /**
1042
- * Helper method to update a single item in the project
1043
- * Convenience wrapper around applyProjectChanges
1044
- */
1045
- async updateProjectItem(projectId, path, value, options = {}) {
1046
- const changes = [["update", path, value]];
1047
- const message = options.message || `Updated ${Array.isArray(path) ? path.join(".") : path}`;
1048
- return await this.applyProjectChanges(projectId, changes, {
1049
- ...options,
1050
- message
1051
- });
1052
- }
1053
- /**
1054
- * Helper method to delete an item from the project
1055
- * Convenience wrapper around applyProjectChanges
1056
- */
1057
- async deleteProjectItem(projectId, path, options = {}) {
1058
- const changes = [["delete", path]];
1059
- const message = options.message || `Deleted ${Array.isArray(path) ? path.join(".") : path}`;
1060
- return await this.applyProjectChanges(projectId, changes, {
1061
- ...options,
1062
- message
1063
- });
1064
- }
1065
- /**
1066
- * Helper method to set a value in the project (alias for update)
1067
- * Convenience wrapper around applyProjectChanges
1068
- */
1069
- async setProjectValue(projectId, path, value, options = {}) {
1070
- const changes = [["set", path, value]];
1071
- const message = options.message || `Set ${Array.isArray(path) ? path.join(".") : path}`;
1072
- return await this.applyProjectChanges(projectId, changes, {
1073
- ...options,
1074
- message
1075
- });
1076
- }
1077
- /**
1078
- * Helper method to add multiple items to the project
1079
- * Convenience wrapper around applyProjectChanges
1080
- */
1081
- async addProjectItems(projectId, items, options = {}) {
1082
- const changes = items.map((item) => {
1083
- const [type, data] = item;
1084
- const { value, ...schema } = data;
1085
- return [
1086
- ["update", [type, data.key], value],
1087
- ["update", ["schema", type, data.key], schema]
1088
- ];
1089
- }).flat();
1090
- const message = options.message || `Added ${items.length} items`;
1091
- return await this.applyProjectChanges(projectId, changes, {
1092
- ...options,
1093
- message
1094
- });
1095
- }
1096
- /**
1097
- * Helper method to get specific data from project by path
1098
- * Convenience wrapper that gets project data and extracts specific path
1099
- */
1100
- async getProjectItemByPath(projectId, path, options = {}) {
1101
- const projectData = await this.getProjectData(projectId, options);
1102
- if (!(projectData == null ? void 0 : projectData.data)) {
1103
- return null;
1104
- }
1105
- let current = projectData.data;
1106
- const pathArray = Array.isArray(path) ? path : [path];
1107
- for (const segment of pathArray) {
1108
- if (current && typeof current === "object" && segment in current) {
1109
- current = current[segment];
1110
- } else {
1111
- return null;
1112
- }
1113
- }
1114
- return current;
1115
- }
1116
- // ==================== PULL REQUEST METHODS ====================
1117
- /**
1118
- * Create a new pull request
1119
- */
1120
- async createPullRequest(projectId, pullRequestData) {
1121
- this._requireReady("createPullRequest");
1122
- if (!projectId) {
1123
- throw new Error("Project ID is required");
1124
- }
1125
- if (!pullRequestData.source || !pullRequestData.target || !pullRequestData.title) {
1126
- throw new Error("Source branch, target branch, and title are required");
1127
- }
1128
- try {
1129
- return await this._request(`/projects/${projectId}/pull-requests`, {
1130
- method: "POST",
1131
- body: JSON.stringify(pullRequestData),
1132
- methodName: "createPullRequest"
1133
- });
1134
- } catch (error) {
1135
- throw new Error(`Failed to create pull request: ${error.message}`);
1136
- }
1137
- }
1138
- /**
1139
- * List pull requests for a project with filtering options
1140
- */
1141
- async listPullRequests(projectId, options = {}) {
1142
- this._requireReady("listPullRequests");
1143
- if (!projectId) {
1144
- throw new Error("Project ID is required");
1145
- }
1146
- const {
1147
- status = "open",
1148
- source,
1149
- target,
1150
- page = 1,
1151
- limit = 20
1152
- } = options;
1153
- const queryParams = new URLSearchParams({
1154
- status,
1155
- page: page.toString(),
1156
- limit: limit.toString()
1157
- });
1158
- if (source) {
1159
- queryParams.append("source", source);
1160
- }
1161
- if (target) {
1162
- queryParams.append("target", target);
1163
- }
1164
- try {
1165
- return await this._request(`/projects/${projectId}/pull-requests?${queryParams.toString()}`, {
1166
- method: "GET",
1167
- methodName: "listPullRequests"
1168
- });
1169
- } catch (error) {
1170
- throw new Error(`Failed to list pull requests: ${error.message}`);
1171
- }
1172
- }
1173
- /**
1174
- * Get detailed information about a specific pull request
1175
- */
1176
- async getPullRequest(projectId, prId) {
1177
- this._requireReady("getPullRequest");
1178
- if (!projectId) {
1179
- throw new Error("Project ID is required");
1180
- }
1181
- if (!prId) {
1182
- throw new Error("Pull request ID is required");
1183
- }
1184
- try {
1185
- return await this._request(`/projects/${projectId}/pull-requests/${prId}`, {
1186
- method: "GET",
1187
- methodName: "getPullRequest"
1188
- });
1189
- } catch (error) {
1190
- throw new Error(`Failed to get pull request: ${error.message}`);
1191
- }
1192
- }
1193
- /**
1194
- * Submit a review for a pull request
1195
- */
1196
- async reviewPullRequest(projectId, prId, reviewData) {
1197
- this._requireReady("reviewPullRequest");
1198
- if (!projectId) {
1199
- throw new Error("Project ID is required");
1200
- }
1201
- if (!prId) {
1202
- throw new Error("Pull request ID is required");
1203
- }
1204
- const validStatuses = ["approved", "requested_changes", "feedback"];
1205
- if (reviewData.status && !validStatuses.includes(reviewData.status)) {
1206
- throw new Error(`Invalid review status. Must be one of: ${validStatuses.join(", ")}`);
1207
- }
1208
- try {
1209
- return await this._request(`/projects/${projectId}/pull-requests/${prId}/review`, {
1210
- method: "POST",
1211
- body: JSON.stringify(reviewData),
1212
- methodName: "reviewPullRequest"
1213
- });
1214
- } catch (error) {
1215
- throw new Error(`Failed to review pull request: ${error.message}`);
1216
- }
1217
- }
1218
- /**
1219
- * Add a comment to an existing review thread
1220
- */
1221
- async addPullRequestComment(projectId, prId, commentData) {
1222
- this._requireReady("addPullRequestComment");
1223
- if (!projectId) {
1224
- throw new Error("Project ID is required");
1225
- }
1226
- if (!prId) {
1227
- throw new Error("Pull request ID is required");
1228
- }
1229
- if (!commentData.value) {
1230
- throw new Error("Comment value is required");
1231
- }
1232
- try {
1233
- return await this._request(`/projects/${projectId}/pull-requests/${prId}/comment`, {
1234
- method: "POST",
1235
- body: JSON.stringify(commentData),
1236
- methodName: "addPullRequestComment"
1237
- });
1238
- } catch (error) {
1239
- throw new Error(`Failed to add pull request comment: ${error.message}`);
1240
- }
1241
- }
1242
- /**
1243
- * Merge an approved pull request
1244
- */
1245
- async mergePullRequest(projectId, prId) {
1246
- this._requireReady("mergePullRequest");
1247
- if (!projectId) {
1248
- throw new Error("Project ID is required");
1249
- }
1250
- if (!prId) {
1251
- throw new Error("Pull request ID is required");
1252
- }
1253
- try {
1254
- const response = await this._request(`/projects/${projectId}/pull-requests/${prId}/merge`, {
1255
- method: "POST",
1256
- methodName: "mergePullRequest"
1257
- });
1258
- return response;
1259
- } catch (error) {
1260
- if (error.message.includes("conflicts") || error.message.includes("409")) {
1261
- throw new Error(`Pull request has merge conflicts: ${error.message}`);
1262
- }
1263
- throw new Error(`Failed to merge pull request: ${error.message}`);
1264
- }
1265
- }
1266
- /**
1267
- * Get the diff/changes for a pull request
1268
- */
1269
- async getPullRequestDiff(projectId, prId) {
1270
- this._requireReady("getPullRequestDiff");
1271
- if (!projectId) {
1272
- throw new Error("Project ID is required");
1273
- }
1274
- if (!prId) {
1275
- throw new Error("Pull request ID is required");
1276
- }
1277
- try {
1278
- return await this._request(`/projects/${projectId}/pull-requests/${prId}/diff`, {
1279
- method: "GET",
1280
- methodName: "getPullRequestDiff"
1281
- });
1282
- } catch (error) {
1283
- throw new Error(`Failed to get pull request diff: ${error.message}`);
1284
- }
1285
- }
1286
- /**
1287
- * Helper method to create a pull request with validation
1288
- */
1289
- async createPullRequestWithValidation(projectId, data) {
1290
- const { source, target, title, description, changes } = data;
1291
- if (source === target) {
1292
- throw new Error("Source and target branches cannot be the same");
1293
- }
1294
- if (!title || title.trim().length === 0) {
1295
- throw new Error("Pull request title cannot be empty");
1296
- }
1297
- if (title.length > 200) {
1298
- throw new Error("Pull request title cannot exceed 200 characters");
1299
- }
1300
- const pullRequestData = {
1301
- source: source.trim(),
1302
- target: target.trim(),
1303
- title: title.trim(),
1304
- ...description && { description: description.trim() },
1305
- ...changes && { changes }
1306
- };
1307
- return await this.createPullRequest(projectId, pullRequestData);
1308
- }
1309
- /**
1310
- * Helper method to approve a pull request
1311
- */
1312
- async approvePullRequest(projectId, prId, comment = "") {
1313
- const reviewData = {
1314
- status: "approved",
1315
- ...comment && {
1316
- threads: [{
1317
- comment,
1318
- type: "praise"
1319
- }]
1320
- }
1321
- };
1322
- return await this.reviewPullRequest(projectId, prId, reviewData);
1323
- }
1324
- /**
1325
- * Helper method to request changes on a pull request
1326
- */
1327
- async requestPullRequestChanges(projectId, prId, threads = []) {
1328
- if (!threads || threads.length === 0) {
1329
- throw new Error("Must provide specific feedback when requesting changes");
1330
- }
1331
- const reviewData = {
1332
- status: "requested_changes",
1333
- threads
1334
- };
1335
- return await this.reviewPullRequest(projectId, prId, reviewData);
1336
- }
1337
- /**
1338
- * Helper method to get pull requests by status
1339
- */
1340
- async getOpenPullRequests(projectId, options = {}) {
1341
- return await this.listPullRequests(projectId, { ...options, status: "open" });
1342
- }
1343
- async getClosedPullRequests(projectId, options = {}) {
1344
- return await this.listPullRequests(projectId, { ...options, status: "closed" });
1345
- }
1346
- async getMergedPullRequests(projectId, options = {}) {
1347
- return await this.listPullRequests(projectId, { ...options, status: "merged" });
1348
- }
1349
- /**
1350
- * Helper method to check if a pull request is canMerge
1351
- */
1352
- async isPullRequestMergeable(projectId, prId) {
1353
- var _a;
1354
- try {
1355
- const prData = await this.getPullRequest(projectId, prId);
1356
- return ((_a = prData == null ? void 0 : prData.data) == null ? void 0 : _a.canMerge) || false;
1357
- } catch (error) {
1358
- throw new Error(`Failed to check pull request mergeability: ${error.message}`);
1359
- }
1360
- }
1361
- /**
1362
- * Helper method to get pull request status summary
1363
- */
1364
- async getPullRequestStatusSummary(projectId, prId) {
1365
- var _a, _b, _c;
1366
- try {
1367
- const prData = await this.getPullRequest(projectId, prId);
1368
- const pr = prData == null ? void 0 : prData.data;
1369
- if (!pr) {
1370
- throw new Error("Pull request not found");
1371
- }
1372
- return {
1373
- status: pr.status,
1374
- reviewStatus: pr.reviewStatus,
1375
- canMerge: pr.canMerge,
1376
- hasConflicts: !pr.canMerge,
1377
- reviewCount: ((_a = pr.reviews) == null ? void 0 : _a.length) || 0,
1378
- approvedReviews: ((_b = pr.reviews) == null ? void 0 : _b.filter((r) => r.status === "approved").length) || 0,
1379
- changesRequested: ((_c = pr.reviews) == null ? void 0 : _c.filter((r) => r.status === "requested_changes").length) || 0
1380
- };
1381
- } catch (error) {
1382
- throw new Error(`Failed to get pull request status summary: ${error.message}`);
1383
- }
1384
- }
1385
- // ==================== BRANCH MANAGEMENT METHODS ====================
1386
- /**
1387
- * Get all branches for a project
1388
- */
1389
- async listBranches(projectId) {
1390
- this._requireReady("listBranches");
1391
- if (!projectId) {
1392
- throw new Error("Project ID is required");
1393
- }
1394
- try {
1395
- return await this._request(`/projects/${projectId}/branches`, {
1396
- method: "GET",
1397
- methodName: "listBranches"
1398
- });
1399
- } catch (error) {
1400
- throw new Error(`Failed to list branches: ${error.message}`);
1401
- }
1402
- }
1403
- /**
1404
- * Create a new branch from an existing branch
1405
- */
1406
- async createBranch(projectId, branchData) {
1407
- this._requireReady("createBranch");
1408
- if (!projectId) {
1409
- throw new Error("Project ID is required");
1410
- }
1411
- if (!branchData.name) {
1412
- throw new Error("Branch name is required");
1413
- }
1414
- const { name, source = "main" } = branchData;
1415
- try {
1416
- return await this._request(`/projects/${projectId}/branches`, {
1417
- method: "POST",
1418
- body: JSON.stringify({ name, source }),
1419
- methodName: "createBranch"
1420
- });
1421
- } catch (error) {
1422
- throw new Error(`Failed to create branch: ${error.message}`);
1423
- }
1424
- }
1425
- /**
1426
- * Delete a branch (cannot delete main branch)
1427
- */
1428
- async deleteBranch(projectId, branchName) {
1429
- this._requireReady("deleteBranch");
1430
- if (!projectId) {
1431
- throw new Error("Project ID is required");
1432
- }
1433
- if (!branchName) {
1434
- throw new Error("Branch name is required");
1435
- }
1436
- if (branchName === "main") {
1437
- throw new Error("Cannot delete main branch");
1438
- }
1439
- try {
1440
- return await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}`, {
1441
- method: "DELETE",
1442
- methodName: "deleteBranch"
1443
- });
1444
- } catch (error) {
1445
- throw new Error(`Failed to delete branch: ${error.message}`);
1446
- }
1447
- }
1448
- /**
1449
- * Rename a branch (cannot rename main branch)
1450
- */
1451
- async renameBranch(projectId, branchName, newName) {
1452
- this._requireReady("renameBranch");
1453
- if (!projectId) {
1454
- throw new Error("Project ID is required");
1455
- }
1456
- if (!branchName) {
1457
- throw new Error("Current branch name is required");
1458
- }
1459
- if (!newName) {
1460
- throw new Error("New branch name is required");
1461
- }
1462
- if (branchName === "main") {
1463
- throw new Error("Cannot rename main branch");
1464
- }
1465
- try {
1466
- return await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/rename`, {
1467
- method: "POST",
1468
- body: JSON.stringify({ newName }),
1469
- methodName: "renameBranch"
1470
- });
1471
- } catch (error) {
1472
- throw new Error(`Failed to rename branch: ${error.message}`);
1473
- }
1474
- }
1475
- /**
1476
- * Get changes/diff for a branch compared to another version
1477
- */
1478
- async getBranchChanges(projectId, branchName, options = {}) {
1479
- this._requireReady("getBranchChanges");
1480
- if (!projectId) {
1481
- throw new Error("Project ID is required");
1482
- }
1483
- if (!branchName) {
1484
- throw new Error("Branch name is required");
1485
- }
1486
- const { versionId, versionValue, target } = options;
1487
- const queryParams = new URLSearchParams();
1488
- if (versionId) {
1489
- queryParams.append("versionId", versionId);
1490
- }
1491
- if (versionValue) {
1492
- queryParams.append("versionValue", versionValue);
1493
- }
1494
- if (target) {
1495
- queryParams.append("target", target);
1496
- }
1497
- const queryString = queryParams.toString();
1498
- const url = `/projects/${projectId}/branches/${encodeURIComponent(branchName)}/changes${queryString ? `?${queryString}` : ""}`;
1499
- try {
1500
- return await this._request(url, {
1501
- method: "GET",
1502
- methodName: "getBranchChanges"
1503
- });
1504
- } catch (error) {
1505
- throw new Error(`Failed to get branch changes: ${error.message}`);
1506
- }
1507
- }
1508
- /**
1509
- * Merge changes between branches (preview or commit)
1510
- */
1511
- async mergeBranch(projectId, branchName, mergeData = {}) {
1512
- this._requireReady("mergeBranch");
1513
- if (!projectId) {
1514
- throw new Error("Project ID is required");
1515
- }
1516
- if (!branchName) {
1517
- throw new Error("Source branch name is required");
1518
- }
1519
- const {
1520
- target = "main",
1521
- message,
1522
- type = "patch",
1523
- commit = false,
1524
- changes
1525
- } = mergeData;
1526
- const requestBody = {
1527
- target,
1528
- type,
1529
- commit,
1530
- ...message && { message },
1531
- ...changes && { changes }
1532
- };
1533
- try {
1534
- return await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/merge`, {
1535
- method: "POST",
1536
- body: JSON.stringify(requestBody),
1537
- methodName: "mergeBranch"
1538
- });
1539
- } catch (error) {
1540
- if (error.message.includes("conflicts") || error.message.includes("409")) {
1541
- throw new Error(`Merge conflicts detected: ${error.message}`);
1542
- }
1543
- throw new Error(`Failed to merge branch: ${error.message}`);
1544
- }
1545
- }
1546
- /**
1547
- * Reset a branch to a clean state
1548
- */
1549
- async resetBranch(projectId, branchName) {
1550
- this._requireReady("resetBranch");
1551
- if (!projectId) {
1552
- throw new Error("Project ID is required");
1553
- }
1554
- if (!branchName) {
1555
- throw new Error("Branch name is required");
1556
- }
1557
- try {
1558
- return await this._request(`/projects/${projectId}/branches/${encodeURIComponent(branchName)}/reset`, {
1559
- method: "POST",
1560
- methodName: "resetBranch"
1561
- });
1562
- } catch (error) {
1563
- throw new Error(`Failed to reset branch: ${error.message}`);
1564
- }
1565
- }
1566
- /**
1567
- * Publish a specific version as the live version
1568
- */
1569
- async publishVersion(projectId, publishData) {
1570
- this._requireReady("publishVersion");
1571
- if (!projectId) {
1572
- throw new Error("Project ID is required");
1573
- }
1574
- if (!publishData.version) {
1575
- throw new Error("Version is required");
1576
- }
1577
- const { version, branch = "main" } = publishData;
1578
- try {
1579
- return await this._request(`/projects/${projectId}/publish`, {
1580
- method: "POST",
1581
- body: JSON.stringify({ version, branch }),
1582
- methodName: "publishVersion"
1583
- });
1584
- } catch (error) {
1585
- throw new Error(`Failed to publish version: ${error.message}`);
1586
- }
1587
- }
1588
- // ==================== BRANCH HELPER METHODS ====================
1589
- /**
1590
- * Helper method to create a branch with validation
1591
- */
1592
- async createBranchWithValidation(projectId, name, source = "main") {
1593
- if (!name || name.trim().length === 0) {
1594
- throw new Error("Branch name cannot be empty");
1595
- }
1596
- if (name.includes(" ")) {
1597
- throw new Error("Branch name cannot contain spaces");
1598
- }
1599
- if (name === "main") {
1600
- throw new Error('Cannot create a branch named "main"');
1601
- }
1602
- const sanitizedName = name.trim().toLowerCase().replace(/[^a-z0-9-_]/gu, "-");
1603
- return await this.createBranch(projectId, {
1604
- name: sanitizedName,
1605
- source
1606
- });
1607
- }
1608
- /**
1609
- * Helper method to check if a branch exists
1610
- */
1611
- async branchExists(projectId, branchName) {
1612
- var _a;
1613
- try {
1614
- const branches = await this.listBranches(projectId);
1615
- return ((_a = branches == null ? void 0 : branches.data) == null ? void 0 : _a.includes(branchName)) || false;
1616
- } catch (error) {
1617
- throw new Error(`Failed to check if branch exists: ${error.message}`);
1618
- }
1619
- }
1620
- /**
1621
- * Helper method to preview merge without committing
1622
- */
1623
- async previewMerge(projectId, sourceBranch, targetBranch = "main") {
1624
- return await this.mergeBranch(projectId, sourceBranch, {
1625
- target: targetBranch,
1626
- commit: false
1627
- });
1628
- }
1629
- /**
1630
- * Helper method to commit merge after preview
1631
- */
1632
- async commitMerge(projectId, sourceBranch, options = {}) {
1633
- const {
1634
- target = "main",
1635
- message = `Merge ${sourceBranch} into ${target}`,
1636
- type = "patch",
1637
- changes
1638
- } = options;
1639
- return await this.mergeBranch(projectId, sourceBranch, {
1640
- target,
1641
- message,
1642
- type,
1643
- commit: true,
1644
- changes
1645
- });
1646
- }
1647
- /**
1648
- * Helper method to create a feature branch from main
1649
- */
1650
- async createFeatureBranch(projectId, featureName) {
1651
- const branchName = `feature/${featureName.toLowerCase().replace(/[^a-z0-9-]/gu, "-")}`;
1652
- return await this.createBranch(projectId, {
1653
- name: branchName,
1654
- source: "main"
1655
- });
1656
- }
1657
- /**
1658
- * Helper method to create a hotfix branch from main
1659
- */
1660
- async createHotfixBranch(projectId, hotfixName) {
1661
- const branchName = `hotfix/${hotfixName.toLowerCase().replace(/[^a-z0-9-]/gu, "-")}`;
1662
- return await this.createBranch(projectId, {
1663
- name: branchName,
1664
- source: "main"
1665
- });
1666
- }
1667
- /**
1668
- * Helper method to get branch status summary
1669
- */
1670
- async getBranchStatus(projectId, branchName) {
1671
- var _a, _b, _c;
1672
- try {
1673
- const [branches, changes] = await Promise.all([
1674
- this.listBranches(projectId),
1675
- this.getBranchChanges(projectId, branchName).catch(() => null)
1676
- ]);
1677
- const exists = ((_a = branches == null ? void 0 : branches.data) == null ? void 0 : _a.includes(branchName)) || false;
1678
- const hasChanges = ((_b = changes == null ? void 0 : changes.data) == null ? void 0 : _b.length) > 0;
1679
- return {
1680
- exists,
1681
- hasChanges,
1682
- changeCount: ((_c = changes == null ? void 0 : changes.data) == null ? void 0 : _c.length) || 0,
1683
- canDelete: exists && branchName !== "main",
1684
- canRename: exists && branchName !== "main"
1685
- };
1686
- } catch (error) {
1687
- throw new Error(`Failed to get branch status: ${error.message}`);
1688
- }
1689
- }
1690
- /**
1691
- * Helper method to safely delete a branch with confirmation
1692
- */
1693
- async deleteBranchSafely(projectId, branchName, options = {}) {
1694
- const { force = false } = options;
1695
- if (!force) {
1696
- const status = await this.getBranchStatus(projectId, branchName);
1697
- if (!status.exists) {
1698
- throw new Error(`Branch '${branchName}' does not exist`);
1699
- }
1700
- if (!status.canDelete) {
1701
- throw new Error(`Branch '${branchName}' cannot be deleted`);
1702
- }
1703
- if (status.hasChanges) {
1704
- throw new Error(`Branch '${branchName}' has uncommitted changes. Use force option to delete anyway.`);
1705
- }
1706
- }
1707
- return await this.deleteBranch(projectId, branchName);
1708
- }
1709
- // Cleanup
1710
- destroy() {
1711
- if (this._tokenManager) {
1712
- this._tokenManager.destroy();
1713
- this._tokenManager = null;
1714
- }
1715
- this._client = null;
1716
- this._initialized = false;
1717
- this._setReady(false);
1718
- }
1719
- }
1720
- export {
1721
- CoreService
1722
- };