@flexbe/sdk 0.2.34 → 0.2.37

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.
package/README.md CHANGED
@@ -19,7 +19,7 @@ const client = new FlexbeClient({
19
19
  baseUrl: 'https://api.flexbe.com', // optional
20
20
  timeout: 30000, // optional, defaults to 30 seconds
21
21
  });
22
- const siteApi = client.getSiteApi(SITE_ID)
22
+ const siteApi = client.getSiteApi(SITE_ID);
23
23
 
24
24
  // Using the Pages API for a specific site
25
25
  try {
@@ -28,14 +28,15 @@ try {
28
28
  limit: 10,
29
29
  offset: 0,
30
30
  type: 'page',
31
- status: 'published'
31
+ status: 'published',
32
32
  });
33
33
  console.log(pages.pages);
34
34
 
35
35
  // Get a single page from site
36
36
  const page = await siteApi.pages.getPage(123);
37
37
  console.log(page);
38
- } catch (error) {
38
+ }
39
+ catch (error) {
39
40
  console.error(error.message);
40
41
  }
41
42
 
@@ -58,6 +59,7 @@ try {
58
59
  ## Environment Variables
59
60
 
60
61
  The SDK supports the following environment variables:
62
+
61
63
  - `FLEXBE_API_KEY`: Your API key (required for API Key authentication)
62
64
  - `FLEXBE_API_URL`: Base URL (defaults to 'https://api.flexbe.com')
63
65
 
@@ -79,4 +81,4 @@ npm run lint
79
81
 
80
82
  ## License
81
83
 
82
- MIT
84
+ MIT
@@ -7,7 +7,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
7
7
  step((generator = generator.apply(thisArg, _arguments || [])).next());
8
8
  });
9
9
  };
10
- import { NotFoundException, ForbiddenException, BadRequestException, UnauthorizedException, ServerException, TimeoutException, FlexbeAuthType } from '../types';
10
+ import { BadRequestException, FlexbeAuthType, ForbiddenException, NotFoundException, ServerException, TimeoutException, UnauthorizedException } from '../types';
11
11
  import { TokenManager } from './token-manager';
12
12
  export class ApiClient {
13
13
  constructor(config) {
@@ -29,7 +29,7 @@ export class ApiClient {
29
29
  if (!token) {
30
30
  throw new Error('No valid bearer token available');
31
31
  }
32
- headers['Authorization'] = `Bearer ${token}`;
32
+ headers.Authorization = `Bearer ${token}`;
33
33
  }
34
34
  return headers;
35
35
  });
@@ -59,7 +59,7 @@ export class ApiClient {
59
59
  const defaultError = {
60
60
  message: response.statusText,
61
61
  error: response.statusText,
62
- statusCode: response.status
62
+ statusCode: response.status,
63
63
  };
64
64
  const errorData = yield response.json().catch(() => defaultError);
65
65
  switch (errorData.statusCode) {
@@ -81,7 +81,7 @@ export class ApiClient {
81
81
  message: errorData.message,
82
82
  error: errorData.error,
83
83
  statusCode: errorData.statusCode,
84
- errors: errorData.errors
84
+ errors: errorData.errors,
85
85
  };
86
86
  }
87
87
  }
@@ -112,18 +112,28 @@ export class ApiClient {
112
112
  });
113
113
  }
114
114
  get(url, config) {
115
- return this.request(Object.assign(Object.assign({}, config), { url, method: 'GET' }));
115
+ return __awaiter(this, void 0, void 0, function* () {
116
+ return this.request(Object.assign(Object.assign({}, config), { url, method: 'GET' }));
117
+ });
116
118
  }
117
119
  post(url, data, config) {
118
- return this.request(Object.assign(Object.assign({}, config), { url, method: 'POST', body: JSON.stringify(data) }));
120
+ return __awaiter(this, void 0, void 0, function* () {
121
+ return this.request(Object.assign(Object.assign({}, config), { url, method: 'POST', body: JSON.stringify(data) }));
122
+ });
119
123
  }
120
124
  put(url, data, config) {
121
- return this.request(Object.assign(Object.assign({}, config), { url, method: 'PUT', body: JSON.stringify(data) }));
125
+ return __awaiter(this, void 0, void 0, function* () {
126
+ return this.request(Object.assign(Object.assign({}, config), { url, method: 'PUT', body: JSON.stringify(data) }));
127
+ });
122
128
  }
123
129
  patch(url, data, config) {
124
- return this.request(Object.assign(Object.assign({}, config), { url, method: 'PATCH', body: JSON.stringify(data) }));
130
+ return __awaiter(this, void 0, void 0, function* () {
131
+ return this.request(Object.assign(Object.assign({}, config), { url, method: 'PATCH', body: JSON.stringify(data) }));
132
+ });
125
133
  }
126
134
  delete(url, config) {
127
- return this.request(Object.assign(Object.assign({}, config), { url, method: 'DELETE' }));
135
+ return __awaiter(this, void 0, void 0, function* () {
136
+ return this.request(Object.assign(Object.assign({}, config), { url, method: 'DELETE' }));
137
+ });
128
138
  }
129
139
  }
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { FlexbeAuthType } from '../types';
11
11
  import { ApiClient } from './api-client';
12
- import { SiteApi } from './site-api';
13
12
  import { MetaApi } from './meta-api';
13
+ import { SiteApi } from './site-api';
14
14
  import { TokenManager } from './token-manager';
15
15
  export class FlexbeClient {
16
16
  constructor(config) {
@@ -18,7 +18,7 @@ export class MetaApi {
18
18
  getSiteLanguages() {
19
19
  return __awaiter(this, void 0, void 0, function* () {
20
20
  const response = yield this.api.get('/meta/site-languages', {
21
- headers: { 'Authorization': '' }
21
+ headers: { Authorization: '' },
22
22
  });
23
23
  return response.data;
24
24
  });
@@ -30,7 +30,7 @@ export class MetaApi {
30
30
  getUserLanguages() {
31
31
  return __awaiter(this, void 0, void 0, function* () {
32
32
  const response = yield this.api.get('/meta/user-languages', {
33
- headers: { 'Authorization': '' }
33
+ headers: { Authorization: '' },
34
34
  });
35
35
  return response.data;
36
36
  });
@@ -42,7 +42,7 @@ export class MetaApi {
42
42
  getSiteCurrencies() {
43
43
  return __awaiter(this, void 0, void 0, function* () {
44
44
  const response = yield this.api.get('/meta/site-currencies', {
45
- headers: { 'Authorization': '' }
45
+ headers: { Authorization: '' },
46
46
  });
47
47
  return response.data;
48
48
  });
@@ -30,7 +30,8 @@ export class Pages {
30
30
  */
31
31
  getPages(params) {
32
32
  return __awaiter(this, void 0, void 0, function* () {
33
- const processedParams = params ? Object.assign(Object.assign({}, params), { type: Array.isArray(params.type) ? params.type.join(',') : params.type, status: Array.isArray(params.status) ? params.status.join(',') : params.status }) : undefined;
33
+ const processedParams = params
34
+ ? Object.assign(Object.assign({}, params), { type: Array.isArray(params.type) ? params.type.join(',') : params.type, status: Array.isArray(params.status) ? params.status.join(',') : params.status }) : undefined;
34
35
  const response = yield this.api.get(`/sites/${this.siteId}/pages`, { params: processedParams });
35
36
  return response.data;
36
37
  });
@@ -233,7 +234,7 @@ export class Pages {
233
234
  bulkDeletePages(ids) {
234
235
  return __awaiter(this, void 0, void 0, function* () {
235
236
  const response = yield this.api.delete(`/sites/${this.siteId}/pages`, {
236
- body: JSON.stringify({ ids })
237
+ body: JSON.stringify({ ids }),
237
238
  });
238
239
  return response.data;
239
240
  });
@@ -338,4 +339,25 @@ export class Pages {
338
339
  return response.data;
339
340
  });
340
341
  }
342
+ /**
343
+ * Create a new page version
344
+ * @param pageId - ID of the page to create version for
345
+ * @param data - Version data including:
346
+ * - data: Page data structure containing blocks, modals, widgets, etc.
347
+ * - assets: Optional page assets (images, files, screenshot)
348
+ * - publish: Whether to publish this version immediately (default: true)
349
+ * @returns The created page version with data
350
+ * @throws {UnauthorizedException} When the API key is invalid or expired
351
+ * @throws {NotFoundException} When the page is not found
352
+ * @throws {ForbiddenException} When the page does not belong to the site
353
+ * @throws {BadRequestException} When the version data is invalid
354
+ * @throws {ServerException} When the server encounters an error
355
+ * @throws {TimeoutException} When the request times out
356
+ */
357
+ createVersion(pageId, data) {
358
+ return __awaiter(this, void 0, void 0, function* () {
359
+ const response = yield this.api.post(`/sites/${this.siteId}/pages/${pageId}/versions`, data);
360
+ return response.data;
361
+ });
362
+ }
341
363
  }
@@ -13,6 +13,7 @@ const TOKEN_REFRESH_THRESHOLD = 5 * 60 * 1000; // update token 5 minutes before
13
13
  export class TokenManager {
14
14
  constructor() {
15
15
  this.tokenPromise = null;
16
+ this.isRevoking = false;
16
17
  }
17
18
  static getInstance() {
18
19
  if (!TokenManager.instance) {
@@ -29,6 +30,9 @@ export class TokenManager {
29
30
  getToken() {
30
31
  return __awaiter(this, void 0, void 0, function* () {
31
32
  var _a;
33
+ if (this.isRevoking) {
34
+ return null;
35
+ }
32
36
  const token = this.getStoredToken();
33
37
  if (token && token.expiresAt > Date.now()) {
34
38
  // TODO check if token expire less that 1 minute
@@ -45,10 +49,14 @@ export class TokenManager {
45
49
  }
46
50
  revokeToken() {
47
51
  return __awaiter(this, void 0, void 0, function* () {
52
+ this.isRevoking = true;
48
53
  const token = this.getStoredToken();
49
- this.clearToken();
50
- if (!token)
54
+ if (!token) {
55
+ this.isRevoking = false;
51
56
  return;
57
+ }
58
+ // Optimistic token cleanup
59
+ this.clearToken();
52
60
  try {
53
61
  const controller = new AbortController();
54
62
  const timeoutId = setTimeout(() => controller.abort(), 30000);
@@ -56,7 +64,7 @@ export class TokenManager {
56
64
  method: 'POST',
57
65
  headers: {
58
66
  'Content-Type': 'application/json',
59
- 'Authorization': `Bearer ${token.accessToken}`
67
+ Authorization: `Bearer ${token.accessToken}`,
60
68
  },
61
69
  body: JSON.stringify({ token: token.accessToken }),
62
70
  credentials: 'include',
@@ -67,11 +75,17 @@ export class TokenManager {
67
75
  catch (error) {
68
76
  console.error('Failed to revoke token:', error);
69
77
  }
78
+ finally {
79
+ // Finally cleanup the token
80
+ this.clearToken();
81
+ this.isRevoking = false;
82
+ }
70
83
  });
71
84
  }
72
85
  getStoredToken() {
73
- if (typeof window === 'undefined')
86
+ if (typeof window === 'undefined') {
74
87
  return null;
88
+ }
75
89
  const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
76
90
  if (!storedToken) {
77
91
  return null;
@@ -104,28 +118,23 @@ export class TokenManager {
104
118
  return __awaiter(this, void 0, void 0, function* () {
105
119
  const controller = new AbortController();
106
120
  const timeoutId = setTimeout(() => controller.abort(), 30000);
107
- try {
108
- const response = yield fetch('/oauth/token', {
109
- method: 'POST',
110
- headers: { 'Content-Type': 'application/json' },
111
- body: JSON.stringify({ grant_type: 'client_credentials' }),
112
- credentials: 'include',
113
- signal: controller.signal,
114
- });
115
- clearTimeout(timeoutId);
116
- if (!response.ok) {
117
- const errorData = yield response.json().catch(() => ({ message: response.statusText }));
118
- if (response.status === 401) {
119
- throw new UnauthorizedException(errorData.message || response.statusText);
120
- }
121
- throw new Error(errorData.message || response.statusText);
121
+ const response = yield fetch('/oauth/token', {
122
+ method: 'POST',
123
+ headers: { 'Content-Type': 'application/json' },
124
+ body: JSON.stringify({ grant_type: 'client_credentials' }),
125
+ credentials: 'include',
126
+ signal: controller.signal,
127
+ });
128
+ clearTimeout(timeoutId);
129
+ if (!response.ok) {
130
+ const errorData = yield response.json().catch(() => ({ message: response.statusText }));
131
+ if (response.status === 401) {
132
+ throw new UnauthorizedException(errorData.message || response.statusText);
122
133
  }
123
- const data = yield response.json();
124
- this.setToken(data);
125
- }
126
- catch (error) {
127
- throw error;
134
+ throw new Error(errorData.message || response.statusText);
128
135
  }
136
+ const data = yield response.json();
137
+ this.setToken(data);
129
138
  });
130
139
  }
131
140
  setToken(tokenResponse) {
@@ -22,7 +22,7 @@ class ApiClient {
22
22
  if (!token) {
23
23
  throw new Error('No valid bearer token available');
24
24
  }
25
- headers['Authorization'] = `Bearer ${token}`;
25
+ headers.Authorization = `Bearer ${token}`;
26
26
  }
27
27
  return headers;
28
28
  }
@@ -57,7 +57,7 @@ class ApiClient {
57
57
  const defaultError = {
58
58
  message: response.statusText,
59
59
  error: response.statusText,
60
- statusCode: response.status
60
+ statusCode: response.status,
61
61
  };
62
62
  const errorData = await response.json().catch(() => defaultError);
63
63
  switch (errorData.statusCode) {
@@ -79,7 +79,7 @@ class ApiClient {
79
79
  message: errorData.message,
80
80
  error: errorData.error,
81
81
  statusCode: errorData.statusCode,
82
- errors: errorData.errors
82
+ errors: errorData.errors,
83
83
  };
84
84
  }
85
85
  }
@@ -108,19 +108,19 @@ class ApiClient {
108
108
  throw error;
109
109
  }
110
110
  }
111
- get(url, config) {
111
+ async get(url, config) {
112
112
  return this.request({ ...config, url, method: 'GET' });
113
113
  }
114
- post(url, data, config) {
114
+ async post(url, data, config) {
115
115
  return this.request({ ...config, url, method: 'POST', body: JSON.stringify(data) });
116
116
  }
117
- put(url, data, config) {
117
+ async put(url, data, config) {
118
118
  return this.request({ ...config, url, method: 'PUT', body: JSON.stringify(data) });
119
119
  }
120
- patch(url, data, config) {
120
+ async patch(url, data, config) {
121
121
  return this.request({ ...config, url, method: 'PATCH', body: JSON.stringify(data) });
122
122
  }
123
- delete(url, config) {
123
+ async delete(url, config) {
124
124
  return this.request({ ...config, url, method: 'DELETE' });
125
125
  }
126
126
  }
@@ -3,8 +3,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.FlexbeClient = void 0;
4
4
  const types_1 = require("../types");
5
5
  const api_client_1 = require("./api-client");
6
- const site_api_1 = require("./site-api");
7
6
  const meta_api_1 = require("./meta-api");
7
+ const site_api_1 = require("./site-api");
8
8
  const token_manager_1 = require("./token-manager");
9
9
  class FlexbeClient {
10
10
  constructor(config) {
@@ -11,7 +11,7 @@ class MetaApi {
11
11
  */
12
12
  async getSiteLanguages() {
13
13
  const response = await this.api.get('/meta/site-languages', {
14
- headers: { 'Authorization': '' }
14
+ headers: { Authorization: '' },
15
15
  });
16
16
  return response.data;
17
17
  }
@@ -21,7 +21,7 @@ class MetaApi {
21
21
  */
22
22
  async getUserLanguages() {
23
23
  const response = await this.api.get('/meta/user-languages', {
24
- headers: { 'Authorization': '' }
24
+ headers: { Authorization: '' },
25
25
  });
26
26
  return response.data;
27
27
  }
@@ -31,7 +31,7 @@ class MetaApi {
31
31
  */
32
32
  async getSiteCurrencies() {
33
33
  const response = await this.api.get('/meta/site-currencies', {
34
- headers: { 'Authorization': '' }
34
+ headers: { Authorization: '' },
35
35
  });
36
36
  return response.data;
37
37
  }
@@ -23,11 +23,13 @@ class Pages {
23
23
  * @throws {TimeoutException} When the request times out
24
24
  */
25
25
  async getPages(params) {
26
- const processedParams = params ? {
27
- ...params,
28
- type: Array.isArray(params.type) ? params.type.join(',') : params.type,
29
- status: Array.isArray(params.status) ? params.status.join(',') : params.status
30
- } : undefined;
26
+ const processedParams = params
27
+ ? {
28
+ ...params,
29
+ type: Array.isArray(params.type) ? params.type.join(',') : params.type,
30
+ status: Array.isArray(params.status) ? params.status.join(',') : params.status,
31
+ }
32
+ : undefined;
31
33
  const response = await this.api.get(`/sites/${this.siteId}/pages`, { params: processedParams });
32
34
  return response.data;
33
35
  }
@@ -208,7 +210,7 @@ class Pages {
208
210
  */
209
211
  async bulkDeletePages(ids) {
210
212
  const response = await this.api.delete(`/sites/${this.siteId}/pages`, {
211
- body: JSON.stringify({ ids })
213
+ body: JSON.stringify({ ids }),
212
214
  });
213
215
  return response.data;
214
216
  }
@@ -300,5 +302,24 @@ class Pages {
300
302
  const response = await this.api.get(`/sites/${this.siteId}/pages/${pageId}/versions/${versionId}`);
301
303
  return response.data;
302
304
  }
305
+ /**
306
+ * Create a new page version
307
+ * @param pageId - ID of the page to create version for
308
+ * @param data - Version data including:
309
+ * - data: Page data structure containing blocks, modals, widgets, etc.
310
+ * - assets: Optional page assets (images, files, screenshot)
311
+ * - publish: Whether to publish this version immediately (default: true)
312
+ * @returns The created page version with data
313
+ * @throws {UnauthorizedException} When the API key is invalid or expired
314
+ * @throws {NotFoundException} When the page is not found
315
+ * @throws {ForbiddenException} When the page does not belong to the site
316
+ * @throws {BadRequestException} When the version data is invalid
317
+ * @throws {ServerException} When the server encounters an error
318
+ * @throws {TimeoutException} When the request times out
319
+ */
320
+ async createVersion(pageId, data) {
321
+ const response = await this.api.post(`/sites/${this.siteId}/pages/${pageId}/versions`, data);
322
+ return response.data;
323
+ }
303
324
  }
304
325
  exports.Pages = Pages;
@@ -7,6 +7,7 @@ const TOKEN_REFRESH_THRESHOLD = 5 * 60 * 1000; // update token 5 minutes before
7
7
  class TokenManager {
8
8
  constructor() {
9
9
  this.tokenPromise = null;
10
+ this.isRevoking = false;
10
11
  }
11
12
  static getInstance() {
12
13
  if (!TokenManager.instance) {
@@ -21,6 +22,9 @@ class TokenManager {
21
22
  return TokenManager.instance;
22
23
  }
23
24
  async getToken() {
25
+ if (this.isRevoking) {
26
+ return null;
27
+ }
24
28
  const token = this.getStoredToken();
25
29
  if (token && token.expiresAt > Date.now()) {
26
30
  // TODO check if token expire less that 1 minute
@@ -35,10 +39,14 @@ class TokenManager {
35
39
  return retrievedToken?.accessToken ?? null;
36
40
  }
37
41
  async revokeToken() {
42
+ this.isRevoking = true;
38
43
  const token = this.getStoredToken();
39
- this.clearToken();
40
- if (!token)
44
+ if (!token) {
45
+ this.isRevoking = false;
41
46
  return;
47
+ }
48
+ // Optimistic token cleanup
49
+ this.clearToken();
42
50
  try {
43
51
  const controller = new AbortController();
44
52
  const timeoutId = setTimeout(() => controller.abort(), 30000);
@@ -46,7 +54,7 @@ class TokenManager {
46
54
  method: 'POST',
47
55
  headers: {
48
56
  'Content-Type': 'application/json',
49
- 'Authorization': `Bearer ${token.accessToken}`
57
+ Authorization: `Bearer ${token.accessToken}`,
50
58
  },
51
59
  body: JSON.stringify({ token: token.accessToken }),
52
60
  credentials: 'include',
@@ -57,10 +65,16 @@ class TokenManager {
57
65
  catch (error) {
58
66
  console.error('Failed to revoke token:', error);
59
67
  }
68
+ finally {
69
+ // Finally cleanup the token
70
+ this.clearToken();
71
+ this.isRevoking = false;
72
+ }
60
73
  }
61
74
  getStoredToken() {
62
- if (typeof window === 'undefined')
75
+ if (typeof window === 'undefined') {
63
76
  return null;
77
+ }
64
78
  const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
65
79
  if (!storedToken) {
66
80
  return null;
@@ -90,28 +104,23 @@ class TokenManager {
90
104
  async doRetrieveToken() {
91
105
  const controller = new AbortController();
92
106
  const timeoutId = setTimeout(() => controller.abort(), 30000);
93
- try {
94
- const response = await fetch('/oauth/token', {
95
- method: 'POST',
96
- headers: { 'Content-Type': 'application/json' },
97
- body: JSON.stringify({ grant_type: 'client_credentials' }),
98
- credentials: 'include',
99
- signal: controller.signal,
100
- });
101
- clearTimeout(timeoutId);
102
- if (!response.ok) {
103
- const errorData = await response.json().catch(() => ({ message: response.statusText }));
104
- if (response.status === 401) {
105
- throw new types_1.UnauthorizedException(errorData.message || response.statusText);
106
- }
107
- throw new Error(errorData.message || response.statusText);
107
+ const response = await fetch('/oauth/token', {
108
+ method: 'POST',
109
+ headers: { 'Content-Type': 'application/json' },
110
+ body: JSON.stringify({ grant_type: 'client_credentials' }),
111
+ credentials: 'include',
112
+ signal: controller.signal,
113
+ });
114
+ clearTimeout(timeoutId);
115
+ if (!response.ok) {
116
+ const errorData = await response.json().catch(() => ({ message: response.statusText }));
117
+ if (response.status === 401) {
118
+ throw new types_1.UnauthorizedException(errorData.message || response.statusText);
108
119
  }
109
- const data = await response.json();
110
- this.setToken(data);
111
- }
112
- catch (error) {
113
- throw error;
120
+ throw new Error(errorData.message || response.statusText);
114
121
  }
122
+ const data = await response.json();
123
+ this.setToken(data);
115
124
  }
116
125
  setToken(tokenResponse) {
117
126
  const expiresAt = this.getExpirationFromToken(tokenResponse.accessToken);
@@ -1,4 +1,4 @@
1
- import { NotFoundException, ForbiddenException, BadRequestException, UnauthorizedException, ServerException, TimeoutException, FlexbeAuthType } from '../types';
1
+ import { BadRequestException, FlexbeAuthType, ForbiddenException, NotFoundException, ServerException, TimeoutException, UnauthorizedException } from '../types';
2
2
  import { TokenManager } from './token-manager';
3
3
  export class ApiClient {
4
4
  constructor(config) {
@@ -19,7 +19,7 @@ export class ApiClient {
19
19
  if (!token) {
20
20
  throw new Error('No valid bearer token available');
21
21
  }
22
- headers['Authorization'] = `Bearer ${token}`;
22
+ headers.Authorization = `Bearer ${token}`;
23
23
  }
24
24
  return headers;
25
25
  }
@@ -54,7 +54,7 @@ export class ApiClient {
54
54
  const defaultError = {
55
55
  message: response.statusText,
56
56
  error: response.statusText,
57
- statusCode: response.status
57
+ statusCode: response.status,
58
58
  };
59
59
  const errorData = await response.json().catch(() => defaultError);
60
60
  switch (errorData.statusCode) {
@@ -76,7 +76,7 @@ export class ApiClient {
76
76
  message: errorData.message,
77
77
  error: errorData.error,
78
78
  statusCode: errorData.statusCode,
79
- errors: errorData.errors
79
+ errors: errorData.errors,
80
80
  };
81
81
  }
82
82
  }
@@ -105,19 +105,19 @@ export class ApiClient {
105
105
  throw error;
106
106
  }
107
107
  }
108
- get(url, config) {
108
+ async get(url, config) {
109
109
  return this.request({ ...config, url, method: 'GET' });
110
110
  }
111
- post(url, data, config) {
111
+ async post(url, data, config) {
112
112
  return this.request({ ...config, url, method: 'POST', body: JSON.stringify(data) });
113
113
  }
114
- put(url, data, config) {
114
+ async put(url, data, config) {
115
115
  return this.request({ ...config, url, method: 'PUT', body: JSON.stringify(data) });
116
116
  }
117
- patch(url, data, config) {
117
+ async patch(url, data, config) {
118
118
  return this.request({ ...config, url, method: 'PATCH', body: JSON.stringify(data) });
119
119
  }
120
- delete(url, config) {
120
+ async delete(url, config) {
121
121
  return this.request({ ...config, url, method: 'DELETE' });
122
122
  }
123
123
  }
@@ -1,7 +1,7 @@
1
1
  import { FlexbeAuthType } from '../types';
2
2
  import { ApiClient } from './api-client';
3
- import { SiteApi } from './site-api';
4
3
  import { MetaApi } from './meta-api';
4
+ import { SiteApi } from './site-api';
5
5
  import { TokenManager } from './token-manager';
6
6
  export class FlexbeClient {
7
7
  constructor(config) {
@@ -8,7 +8,7 @@ export class MetaApi {
8
8
  */
9
9
  async getSiteLanguages() {
10
10
  const response = await this.api.get('/meta/site-languages', {
11
- headers: { 'Authorization': '' }
11
+ headers: { Authorization: '' },
12
12
  });
13
13
  return response.data;
14
14
  }
@@ -18,7 +18,7 @@ export class MetaApi {
18
18
  */
19
19
  async getUserLanguages() {
20
20
  const response = await this.api.get('/meta/user-languages', {
21
- headers: { 'Authorization': '' }
21
+ headers: { Authorization: '' },
22
22
  });
23
23
  return response.data;
24
24
  }
@@ -28,7 +28,7 @@ export class MetaApi {
28
28
  */
29
29
  async getSiteCurrencies() {
30
30
  const response = await this.api.get('/meta/site-currencies', {
31
- headers: { 'Authorization': '' }
31
+ headers: { Authorization: '' },
32
32
  });
33
33
  return response.data;
34
34
  }
@@ -20,11 +20,13 @@ export class Pages {
20
20
  * @throws {TimeoutException} When the request times out
21
21
  */
22
22
  async getPages(params) {
23
- const processedParams = params ? {
24
- ...params,
25
- type: Array.isArray(params.type) ? params.type.join(',') : params.type,
26
- status: Array.isArray(params.status) ? params.status.join(',') : params.status
27
- } : undefined;
23
+ const processedParams = params
24
+ ? {
25
+ ...params,
26
+ type: Array.isArray(params.type) ? params.type.join(',') : params.type,
27
+ status: Array.isArray(params.status) ? params.status.join(',') : params.status,
28
+ }
29
+ : undefined;
28
30
  const response = await this.api.get(`/sites/${this.siteId}/pages`, { params: processedParams });
29
31
  return response.data;
30
32
  }
@@ -205,7 +207,7 @@ export class Pages {
205
207
  */
206
208
  async bulkDeletePages(ids) {
207
209
  const response = await this.api.delete(`/sites/${this.siteId}/pages`, {
208
- body: JSON.stringify({ ids })
210
+ body: JSON.stringify({ ids }),
209
211
  });
210
212
  return response.data;
211
213
  }
@@ -297,4 +299,23 @@ export class Pages {
297
299
  const response = await this.api.get(`/sites/${this.siteId}/pages/${pageId}/versions/${versionId}`);
298
300
  return response.data;
299
301
  }
302
+ /**
303
+ * Create a new page version
304
+ * @param pageId - ID of the page to create version for
305
+ * @param data - Version data including:
306
+ * - data: Page data structure containing blocks, modals, widgets, etc.
307
+ * - assets: Optional page assets (images, files, screenshot)
308
+ * - publish: Whether to publish this version immediately (default: true)
309
+ * @returns The created page version with data
310
+ * @throws {UnauthorizedException} When the API key is invalid or expired
311
+ * @throws {NotFoundException} When the page is not found
312
+ * @throws {ForbiddenException} When the page does not belong to the site
313
+ * @throws {BadRequestException} When the version data is invalid
314
+ * @throws {ServerException} When the server encounters an error
315
+ * @throws {TimeoutException} When the request times out
316
+ */
317
+ async createVersion(pageId, data) {
318
+ const response = await this.api.post(`/sites/${this.siteId}/pages/${pageId}/versions`, data);
319
+ return response.data;
320
+ }
300
321
  }
@@ -4,6 +4,7 @@ const TOKEN_REFRESH_THRESHOLD = 5 * 60 * 1000; // update token 5 minutes before
4
4
  export class TokenManager {
5
5
  constructor() {
6
6
  this.tokenPromise = null;
7
+ this.isRevoking = false;
7
8
  }
8
9
  static getInstance() {
9
10
  if (!TokenManager.instance) {
@@ -18,6 +19,9 @@ export class TokenManager {
18
19
  return TokenManager.instance;
19
20
  }
20
21
  async getToken() {
22
+ if (this.isRevoking) {
23
+ return null;
24
+ }
21
25
  const token = this.getStoredToken();
22
26
  if (token && token.expiresAt > Date.now()) {
23
27
  // TODO check if token expire less that 1 minute
@@ -32,10 +36,14 @@ export class TokenManager {
32
36
  return retrievedToken?.accessToken ?? null;
33
37
  }
34
38
  async revokeToken() {
39
+ this.isRevoking = true;
35
40
  const token = this.getStoredToken();
36
- this.clearToken();
37
- if (!token)
41
+ if (!token) {
42
+ this.isRevoking = false;
38
43
  return;
44
+ }
45
+ // Optimistic token cleanup
46
+ this.clearToken();
39
47
  try {
40
48
  const controller = new AbortController();
41
49
  const timeoutId = setTimeout(() => controller.abort(), 30000);
@@ -43,7 +51,7 @@ export class TokenManager {
43
51
  method: 'POST',
44
52
  headers: {
45
53
  'Content-Type': 'application/json',
46
- 'Authorization': `Bearer ${token.accessToken}`
54
+ Authorization: `Bearer ${token.accessToken}`,
47
55
  },
48
56
  body: JSON.stringify({ token: token.accessToken }),
49
57
  credentials: 'include',
@@ -54,10 +62,16 @@ export class TokenManager {
54
62
  catch (error) {
55
63
  console.error('Failed to revoke token:', error);
56
64
  }
65
+ finally {
66
+ // Finally cleanup the token
67
+ this.clearToken();
68
+ this.isRevoking = false;
69
+ }
57
70
  }
58
71
  getStoredToken() {
59
- if (typeof window === 'undefined')
72
+ if (typeof window === 'undefined') {
60
73
  return null;
74
+ }
61
75
  const storedToken = localStorage.getItem(TOKEN_STORAGE_KEY);
62
76
  if (!storedToken) {
63
77
  return null;
@@ -87,28 +101,23 @@ export class TokenManager {
87
101
  async doRetrieveToken() {
88
102
  const controller = new AbortController();
89
103
  const timeoutId = setTimeout(() => controller.abort(), 30000);
90
- try {
91
- const response = await fetch('/oauth/token', {
92
- method: 'POST',
93
- headers: { 'Content-Type': 'application/json' },
94
- body: JSON.stringify({ grant_type: 'client_credentials' }),
95
- credentials: 'include',
96
- signal: controller.signal,
97
- });
98
- clearTimeout(timeoutId);
99
- if (!response.ok) {
100
- const errorData = await response.json().catch(() => ({ message: response.statusText }));
101
- if (response.status === 401) {
102
- throw new UnauthorizedException(errorData.message || response.statusText);
103
- }
104
- throw new Error(errorData.message || response.statusText);
104
+ const response = await fetch('/oauth/token', {
105
+ method: 'POST',
106
+ headers: { 'Content-Type': 'application/json' },
107
+ body: JSON.stringify({ grant_type: 'client_credentials' }),
108
+ credentials: 'include',
109
+ signal: controller.signal,
110
+ });
111
+ clearTimeout(timeoutId);
112
+ if (!response.ok) {
113
+ const errorData = await response.json().catch(() => ({ message: response.statusText }));
114
+ if (response.status === 401) {
115
+ throw new UnauthorizedException(errorData.message || response.statusText);
105
116
  }
106
- const data = await response.json();
107
- this.setToken(data);
108
- }
109
- catch (error) {
110
- throw error;
117
+ throw new Error(errorData.message || response.statusText);
111
118
  }
119
+ const data = await response.json();
120
+ this.setToken(data);
112
121
  }
113
122
  setToken(tokenResponse) {
114
123
  const expiresAt = this.getExpirationFromToken(tokenResponse.accessToken);
@@ -1,4 +1,4 @@
1
- import { FlexbeConfig, FlexbeResponse } from '../types';
1
+ import type { FlexbeConfig, FlexbeResponse } from '../types';
2
2
  export declare class ApiClient {
3
3
  private readonly config;
4
4
  private readonly tokenManager;
@@ -1,6 +1,6 @@
1
- import { FlexbeConfig } from '../types';
2
- import { SiteApi } from './site-api';
3
1
  import { MetaApi } from './meta-api';
2
+ import { SiteApi } from './site-api';
3
+ import type { FlexbeConfig } from '../types';
4
4
  export declare class FlexbeClient {
5
5
  private readonly config;
6
6
  private readonly api;
@@ -1,5 +1,5 @@
1
- import { ApiClient } from './api-client';
2
- import { SiteCurrency, SiteLanguage, UserLanguage } from '../types/meta';
1
+ import type { ApiClient } from './api-client';
2
+ import type { SiteCurrency, SiteLanguage, UserLanguage } from '../types/meta';
3
3
  export declare class MetaApi {
4
4
  private readonly api;
5
5
  constructor(api: ApiClient);
@@ -1,5 +1,5 @@
1
- import { Page, GetPagesParams, PageListResponse, PageFolder, PageFolderListResponse, UpdateFolderParams, CreateFolderParams, UpdatePageParams, BulkUpdatePageItem, BulkUpdateResponse, BulkUpdateFolderItem, BulkUpdateFolderResponse, BulkDeleteResponse, PageContent, UpdatePageContentParams, PageHistoryListResponse, PageHistoryItemData, PageVersionListResponse, PageVersionDataResponse } from '../types/pages';
2
1
  import { ApiClient } from './api-client';
2
+ import { BulkDeleteResponse, BulkUpdateFolderItem, BulkUpdateFolderResponse, BulkUpdatePageItem, BulkUpdateResponse, CreateFolderParams, CreatePageVersionParams, GetPagesParams, Page, PageContent, PageFolder, PageFolderListResponse, PageHistoryItemData, PageHistoryListResponse, PageListResponse, PageVersionDataResponse, PageVersionListResponse, UpdateFolderParams, UpdatePageContentParams, UpdatePageParams } from '../types/pages';
3
3
  export declare class Pages {
4
4
  private readonly api;
5
5
  private readonly siteId;
@@ -239,4 +239,20 @@ export declare class Pages {
239
239
  * @throws {TimeoutException} When the request times out
240
240
  */
241
241
  getPageVersion(pageId: number, versionId: number): Promise<PageVersionDataResponse>;
242
+ /**
243
+ * Create a new page version
244
+ * @param pageId - ID of the page to create version for
245
+ * @param data - Version data including:
246
+ * - data: Page data structure containing blocks, modals, widgets, etc.
247
+ * - assets: Optional page assets (images, files, screenshot)
248
+ * - publish: Whether to publish this version immediately (default: true)
249
+ * @returns The created page version with data
250
+ * @throws {UnauthorizedException} When the API key is invalid or expired
251
+ * @throws {NotFoundException} When the page is not found
252
+ * @throws {ForbiddenException} When the page does not belong to the site
253
+ * @throws {BadRequestException} When the version data is invalid
254
+ * @throws {ServerException} When the server encounters an error
255
+ * @throws {TimeoutException} When the request times out
256
+ */
257
+ createVersion(pageId: number, data: CreatePageVersionParams): Promise<PageVersionDataResponse>;
242
258
  }
@@ -1,6 +1,6 @@
1
- import { ApiClient } from './api-client';
2
1
  import { Pages } from './pages';
3
2
  import { Stat } from './stat';
3
+ import type { ApiClient } from './api-client';
4
4
  export declare class SiteApi {
5
5
  readonly pages: Pages;
6
6
  readonly stat: Stat;
@@ -1,5 +1,5 @@
1
- import { ApiClient } from './api-client';
2
- import { AbTest } from '../types/stat';
1
+ import type { ApiClient } from './api-client';
2
+ import type { AbTest } from '../types/stat';
3
3
  export declare class Stat {
4
4
  private readonly api;
5
5
  private readonly siteId;
@@ -1,6 +1,7 @@
1
1
  export declare class TokenManager {
2
2
  private static instance;
3
3
  private tokenPromise;
4
+ private isRevoking;
4
5
  static getInstance(): TokenManager;
5
6
  getToken(): Promise<string | null>;
6
7
  revokeToken(): Promise<void>;
@@ -1,4 +1,4 @@
1
- import { FlexbeBulkError, Pagination } from './index';
1
+ import type { FlexbeBulkError, Pagination } from './index';
2
2
  export interface GridConfig {
3
3
  color?: string;
4
4
  desktop?: {
@@ -98,6 +98,15 @@ export interface UpdatePageParams {
98
98
  sortIndex?: number;
99
99
  meta?: Partial<PageMeta>;
100
100
  }
101
+ export interface CreatePageVersionParams {
102
+ data: PageDataStructure;
103
+ assets?: {
104
+ images: number[];
105
+ files: string[];
106
+ screenshot?: number | null;
107
+ };
108
+ publish?: boolean;
109
+ }
101
110
  export interface BulkUpdatePageItem extends UpdatePageParams {
102
111
  id: number;
103
112
  }
@@ -307,7 +316,19 @@ export interface PageVersionItem {
307
316
  export interface PageVersionListResponse {
308
317
  list: PageVersionItem[];
309
318
  }
310
- export interface PageVersionDataResponse {
311
- data: PageContent;
319
+ export interface PageDataStructure {
320
+ is: string;
321
+ template_id: string;
322
+ blocks: PageBlock[];
323
+ modals: PageModal[];
324
+ widgets: PageWidget[];
325
+ codes: string[];
326
+ abtests: PageABTest[];
327
+ background: PageBackground;
328
+ textStyles: TextStyleItem[];
329
+ responsive: string | boolean;
330
+ }
331
+ export interface PageVersionDataResponse extends PageVersionItem {
332
+ data: PageDataStructure;
312
333
  }
313
334
  export {};
package/package.json CHANGED
@@ -1,67 +1,64 @@
1
1
  {
2
- "name": "@flexbe/sdk",
3
- "version": "0.2.34",
4
- "description": "TypeScript SDK for Flexbe API",
5
- "main": "dist/cjs/index.js",
6
- "module": "dist/esm/index.js",
7
- "types": "dist/types/index.d.ts",
8
- "browser": "dist/browser/index.js",
9
- "exports": {
10
- ".": {
11
- "import": "./dist/esm/index.js",
12
- "require": "./dist/cjs/index.js",
13
- "types": "./dist/types/index.d.ts"
14
- }
15
- },
16
- "scripts": {
17
- "build": "npm run build:esm && npm run build:cjs && npm run build:browser",
18
- "build:esm": "tsc -p tsconfig.esm.json",
19
- "build:cjs": "tsc -p tsconfig.cjs.json",
20
- "build:browser": "tsc -p tsconfig.browser.json",
21
- "dev": "tsc -p tsconfig.esm.json --watch",
22
- "test": "dotenv -e test/.env.test jest",
23
- "lint": "eslint src --ext .ts",
24
- "format": "prettier --write \"src/**/*.ts\"",
25
- "prepare": "npm run build",
26
- "prepublishOnly": "npm test && npm run lint"
27
- },
28
- "keywords": [
29
- "flexbe",
30
- "sdk",
31
- "typescript",
32
- "api-client"
33
- ],
34
- "author": "Flexbe",
35
- "license": "MIT",
36
- "repository": {
37
- "type": "git",
38
- "url": "git+https://github.com/flexbe/sdk-ts.git"
39
- },
40
- "bugs": {
41
- "url": "https://github.com/flexbe/sdk-ts/issues"
42
- },
43
- "homepage": "https://github.com/flexbe/sdk-ts#readme",
44
- "dependencies": {},
45
- "devDependencies": {
46
- "@types/jest": "^29.5.12",
47
- "@types/node": "^20.11.19",
48
- "@typescript-eslint/eslint-plugin": "^7.0.1",
49
- "@typescript-eslint/parser": "^7.0.1",
50
- "dotenv-cli": "^7.4.1",
51
- "eslint": "^8.56.0",
52
- "jest": "^29.7.0",
53
- "prettier": "^3.2.5",
54
- "ts-jest": "^29.1.2",
55
- "typescript": "~5.5.0"
56
- },
57
- "files": [
58
- "dist",
59
- "README.md"
60
- ],
61
- "engines": {
62
- "node": ">=16.0.0"
63
- },
64
- "publishConfig": {
65
- "access": "public"
2
+ "name": "@flexbe/sdk",
3
+ "version": "0.2.37",
4
+ "description": "TypeScript SDK for Flexbe API",
5
+ "main": "dist/cjs/index.js",
6
+ "module": "dist/esm/index.js",
7
+ "types": "dist/types/index.d.ts",
8
+ "browser": "dist/browser/index.js",
9
+ "exports": {
10
+ ".": {
11
+ "import": "./dist/esm/index.js",
12
+ "require": "./dist/cjs/index.js",
13
+ "types": "./dist/types/index.d.ts"
66
14
  }
15
+ },
16
+ "scripts": {
17
+ "build": "npm run build:esm && npm run build:cjs && npm run build:browser",
18
+ "build:esm": "tsc -p tsconfig.esm.json",
19
+ "build:cjs": "tsc -p tsconfig.cjs.json",
20
+ "build:browser": "tsc -p tsconfig.browser.json",
21
+ "dev": "tsc -p tsconfig.esm.json --watch",
22
+ "test": "dotenv -e test/.env.test jest",
23
+ "lint": "eslint src --ext .ts",
24
+ "format": "prettier --write \"src/**/*.ts\"",
25
+ "prepare": "npm run build",
26
+ "prepublishOnly": "npm test && npm run lint"
27
+ },
28
+ "keywords": [
29
+ "flexbe",
30
+ "sdk",
31
+ "typescript",
32
+ "api-client"
33
+ ],
34
+ "author": "Flexbe",
35
+ "license": "MIT",
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/flexbe/sdk-ts.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/flexbe/sdk-ts/issues"
42
+ },
43
+ "homepage": "https://github.com/flexbe/sdk-ts#readme",
44
+ "devDependencies": {
45
+ "@flexbe/eslint-config": "^1.0.7",
46
+ "@types/jest": "^29.5.12",
47
+ "@types/node": "^20.11.19",
48
+ "dotenv-cli": "^7.4.1",
49
+ "eslint": "^9.26.0",
50
+ "jest": "^29.7.0",
51
+ "ts-jest": "^29.1.2",
52
+ "typescript": "~5.5.0"
53
+ },
54
+ "files": [
55
+ "dist",
56
+ "README.md"
57
+ ],
58
+ "engines": {
59
+ "node": ">=16.0.0"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ }
67
64
  }