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