oneentry 1.0.156 → 1.0.157

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 (39) hide show
  1. package/changelog.md +89 -0
  2. package/dist/attribute-sets/attributeSetsApi.js +4 -4
  3. package/dist/attribute-sets/attributeSetsInterfaces.d.ts +1 -1
  4. package/dist/auth-provider/authProviderSchemas.d.ts +2 -0
  5. package/dist/auth-provider/authProviderSchemas.js +2 -0
  6. package/dist/auth-provider/authProvidersInterfaces.d.ts +4 -0
  7. package/dist/base/asyncModules.d.ts +18 -2
  8. package/dist/base/asyncModules.js +32 -8
  9. package/dist/base/syncModules.d.ts +36 -36
  10. package/dist/base/syncModules.js +60 -82
  11. package/dist/base/utils.d.ts +2 -2
  12. package/dist/forms/formsApi.js +2 -2
  13. package/dist/forms/formsInterfaces.d.ts +2 -2
  14. package/dist/forms-data/formsDataApi.js +2 -2
  15. package/dist/forms-data/formsDataInterfaces.d.ts +4 -4
  16. package/dist/integration-collections/integrationCollectionsApi.js +6 -6
  17. package/dist/integration-collections/integrationCollectionsInterfaces.d.ts +4 -0
  18. package/dist/integration-collections/integrationCollectionsSchemas.d.ts +4 -0
  19. package/dist/integration-collections/integrationCollectionsSchemas.js +2 -0
  20. package/dist/menus/menusApi.js +1 -1
  21. package/dist/orders/ordersInterfaces.d.ts +10 -0
  22. package/dist/orders/ordersSchemas.d.ts +10 -0
  23. package/dist/orders/ordersSchemas.js +12 -0
  24. package/dist/pages/pagesApi.d.ts +4 -4
  25. package/dist/pages/pagesApi.js +10 -9
  26. package/dist/pages/pagesInterfaces.d.ts +14 -4
  27. package/dist/pages/pagesSchemas.d.ts +15 -0
  28. package/dist/pages/pagesSchemas.js +13 -1
  29. package/dist/products/productsApi.d.ts +4 -4
  30. package/dist/products/productsApi.js +12 -10
  31. package/dist/products/productsInterfaces.d.ts +16 -4
  32. package/dist/products/productsSchemas.d.ts +17 -0
  33. package/dist/products/productsSchemas.js +14 -1
  34. package/dist/subscriptions/subscriptionsApi.d.ts +4 -4
  35. package/dist/subscriptions/subscriptionsApi.js +3 -3
  36. package/dist/subscriptions/subscriptionsInterfaces.d.ts +26 -5
  37. package/dist/subscriptions/subscriptionsSchemas.d.ts +27 -1
  38. package/dist/subscriptions/subscriptionsSchemas.js +20 -2
  39. package/package.json +1 -1
package/changelog.md CHANGED
@@ -1,5 +1,94 @@
1
1
  # SDK Change Log
2
2
 
3
+ ## v.1.0.157
4
+
5
+ ### What's New
6
+
7
+ - Subscriptions > `ISubscriptionEntity` — new exported type describing an available subscription: `id`, `identifier`, `localizeInfos` (`ILocalizeInfo`), `productIds`, `periodInDays`, `paymentAccountId`, `isUsed`. It backs the corrected return type of `getAllSubscriptions` (see below) and has a matching Zod schema (`SubscriptionEntitySchema` / `SubscriptionsListSchema`).
8
+
9
+ - Orders > `IOrderByMarkerEntity` — four fields the API already returns are now declared: `fulfillmentStatusIdentifier`, `fulfillmentStatusLocalizeInfos`, `paymentStatusIdentifier`, `paymentStatusLocalizeInfos` (each `null` until the corresponding status is assigned). Response validation drops every key its schema does not describe, so with `validation.enabled` these four were silently stripped from `getOrderByMarkerAndId` and `getAllOrdersByMarker` before reaching the consumer:
10
+
11
+ ```ts
12
+ const order = await Orders.getOrderByMarkerAndId('my_order', 179);
13
+ order.paymentStatusIdentifier; // "inProgress-payment"
14
+ order.paymentStatusLocalizeInfos; // { title: "In progress" }
15
+ ```
16
+
17
+ - Orders > `IBaseOrdersEntity` — `statusLocalizeInfos` (localized name of the status assigned to the order) is now declared on the `createOrder` / `updateOrderByMarkerAndId` response, which returned it but had it stripped by validation.
18
+
19
+ - IntegrationCollections > `ICollectionRow` — `langCode` and `formIdentifier` are now declared. Both are returned by the create/update row endpoints (`formIdentifier` on update) and were stripped by validation.
20
+
21
+ - AuthProvider > `ISignUpEntity` — `attributeSetId` and `attributesSets` are now declared on the `signUp` response, which returned them but had them stripped by validation.
22
+
23
+ - Products > `IProductSearchResult` and Pages > `IPageSearchResult` — new exported types describing the short card the quick search endpoints return: `{ id, title, pageId }` for products and `{ id, title }` for pages. Both have matching Zod schemas (`ProductSearchResultSchema` / `ProductSearchResponseSchema`, `PageSearchResultSchema` / `PageSearchResponseSchema`), so the quick search response is validated like every other response.
24
+
25
+ ### What's Changed
26
+
27
+ - **Breaking** — single-file `image` attributes are now unwrapped in **every** module, not only in the few that ran the extra post-processing step. When an `image` attribute holds exactly one file, its `value` is the file object itself (`[img]` → `img`); values with two or more files stay an array, as before.
28
+
29
+ Previously the unwrapping lived in `_clearArray`, which ran only after `_dataPostProcess` (products, menus, forms, forms-data, attribute-sets, integration-collections and `Pages.searchPage`) and only looked at the `attributeValues` key. Everywhere else — blocks, all other pages methods, `Products.getProductsEmptyPage`, `Products.getProductBlockById`, admins, discounts, templates, orders, users — the same attribute arrived as a one-element array, so consumers had to branch on the shape. Form `attributes`, form-data fields and nested `additionalFields` were never unwrapped at all.
30
+
31
+ The logic now lives in `_normalizeAttr`, which runs on every attribute of every response:
32
+
33
+ ```ts
34
+ const block = await Blocks.getBlockByMarker('promo');
35
+ // before: block.attributeValues.img.value[0].downloadLink
36
+ // now: block.attributeValues.img.value.downloadLink
37
+ ```
38
+
39
+ Code that reads `value[0]` from products or menus is unaffected — those modules already returned the object. Code that reads `value[0]` from blocks, pages, users or orders must drop the index.
40
+
41
+ - **Breaking** — a single-file `file` attribute is unwrapped like `image`: `value` is the file object itself, and an array only when several files are attached. `groupOfImages` is a collection by definition and always stays an array. `IBodyTypeFile.value` is widened to `IFileValue | IFileValue[]` accordingly.
42
+
43
+ - **Breaking** — `real` attributes are cast to a number. `integer` and `float` were already normalized, `real` was not, so the same numeric field reached the consumer as `10` or as `"10"` depending on which of the three types it was declared with:
44
+
45
+ ```ts
46
+ const page = await Pages.getPageByUrl('catalog');
47
+ // before: page.attributeValues.amount.value // "5"
48
+ // now: page.attributeValues.amount.value // 5
49
+ ```
50
+
51
+ - **Breaking** — numeric normalization now also runs on form attributes and on form-data fields, which were skipped entirely. A `rating` field of an `integer` form attribute is a `number`, not a string. `IBodyTypeStringNumberFloat.value` is widened to `string | number | null` (send a string; responses come back normalized).
52
+
53
+ - **Breaking** — an attribute with no value is always `null`. The API returns an empty localization map (`{}`) for an unset value, and the SDK passed it through for text-like types while numeric types became `null` — the same "no value" state had three representations. As a side effect, an unset `integer`/`float` no longer becomes `0`: `Number(null)` is `0`, so an explicit `null` from the API used to be reported as a real zero.
54
+
55
+ - **Breaking** — form `attributes` are sorted by `position`, the way `attributeValues` always were. The API returns form fields unordered (a field with `position: 10` could arrive after `position: 14`), so rendering a form in CMS order required sorting on the consumer side.
56
+
57
+ - **Breaking** — Subscriptions > `getAllSubscriptions` returns `ISubscriptionEntity[]` instead of `string[]`. The signature was taken from swagger, which declares `GET /api/content/subscriptions` as an array of markers; the endpoint actually returns full subscription objects, so response validation reported `expected string, received object` on every call and the declared type never matched the data. Callers that read markers should switch from the array element to its `identifier` field:
58
+
59
+ ```ts
60
+ const subscriptions = await Subscriptions.getAllSubscriptions();
61
+ // before: subscriptions // string[]
62
+ // now: subscriptions.map((s) => s.identifier)
63
+ ```
64
+
65
+ `getActiveSubscriptions` is unchanged (`string[]`).
66
+
67
+ - **Breaking (types only)** — `Products.searchProduct` returns `IProductsEntity[] | IProductSearchResult[] | IError` and `Pages.searchPage` returns `IPagesEntity[] | IPageSearchResult[] | IError`. With `traficLimit: true` both methods return the raw quick search response — a short card without `attributeValues`, `localizeInfos`, `blocks` and the rest of the entity — while the signature promised a full entity in both modes, so a consumer reading `attributeValues` in traficLimit mode got `undefined` with no type error. Runtime behaviour is unchanged; narrow by config or by field:
68
+
69
+ ```ts
70
+ const found = await Products.searchProduct('cos');
71
+ if (Array.isArray(found) && found.length && 'attributeValues' in found[0]) {
72
+ // IProductsEntity[] — traficLimit is off
73
+ }
74
+ ```
75
+
76
+ - `Pages.searchPage` no longer runs the template lookup over the traficLimit response. Short cards carry no `templateIdentifier`, so the step could never attach anything; the result is identical, minus the pointless pass.
77
+
78
+ ### Bug Fixes
79
+
80
+ - Methods whose result is just success-or-failure no longer report `true` when the API rejected the request: `Subscriptions.cancelSubscription`, `Subscriptions.recoverSubscriptions`, `Events.subscribeByMarker`, `Events.unsubscribeByMarker`, `Events.subscribeToForm`, `Events.unsubscribeFromForm`.
81
+
82
+ With `errors.isShell` enabled — the default — the SDK **returns** the API error instead of throwing it. The shared helper behind these six methods only had a `try/catch`, so nothing ever reached its `catch` and every failure was reported as a success: `cancelSubscription` answered `true` while the API replied `404 "Subscription already inactive"`, and the `IError` half of the declared `Promise<boolean | IError>` was unreachable. The helper now also inspects the returned value and passes the error through:
83
+
84
+ ```ts
85
+ const cancelled = await Subscriptions.cancelSubscription({ marker: 'premium' });
86
+ // before: true — on 404 and 403 alike
87
+ // now: { statusCode: 404, message: 'Subscription already inactive', ... }
88
+ ```
89
+
90
+ The success path is unchanged (`true`), and `isShell: false` still throws. Code that checks these results with `if (result)` must switch to `if (result === true)` — an error object is truthy.
91
+
3
92
  ## v.1.0.156
4
93
 
5
94
  ### What's New
@@ -50,7 +50,7 @@ class AttributesSetsApi extends asyncModules_1.default {
50
50
  const result = await this._fetchGet(`?` + this._queryParamsToString(query));
51
51
  // Validate response if validation is enabled
52
52
  const validated = this._validateResponse(result, attributeSetsSchemas_1.AttributeSetsResponseSchema);
53
- return this._dataPostProcess(validated, langCode);
53
+ return this._normalizeData(validated, langCode);
54
54
  }
55
55
  /**
56
56
  * Getting all attributes with data from the attribute set.
@@ -65,7 +65,7 @@ class AttributesSetsApi extends asyncModules_1.default {
65
65
  const result = await this._fetchGet(`/${marker}/attributes?langCode=${langCode}`);
66
66
  // Validate response if validation is enabled
67
67
  const validated = this._validateResponse(result, attributeSetsSchemas_1.AttributesArrayResponseSchema);
68
- return this._dataPostProcess(validated, langCode);
68
+ return this._normalizeData(validated, langCode);
69
69
  }
70
70
  /**
71
71
  * Get a single attribute with data from the attribute sets.
@@ -81,7 +81,7 @@ class AttributesSetsApi extends asyncModules_1.default {
81
81
  const result = await this._fetchGet(`/${setMarker}/attributes/${attributeMarker}?langCode=${langCode}`);
82
82
  // Validate response if validation is enabled
83
83
  const validated = this._validateResponse(result, attributeSetsSchemas_1.AttributeEntitySchema);
84
- return this._dataPostProcess(validated, langCode);
84
+ return this._normalizeData(validated, langCode);
85
85
  }
86
86
  /**
87
87
  * Getting a single object from a set of attributes by marker.
@@ -96,7 +96,7 @@ class AttributesSetsApi extends asyncModules_1.default {
96
96
  const result = await this._fetchGet(`/marker/${marker}?langCode=${langCode}`);
97
97
  // Validate response if validation is enabled
98
98
  const validated = this._validateResponse(result, attributeSetsSchemas_1.AttributeSetEntitySchema);
99
- return this._dataPostProcess(validated, langCode);
99
+ return this._normalizeData(validated, langCode);
100
100
  }
101
101
  }
102
102
  exports.default = AttributesSetsApi;
@@ -82,7 +82,7 @@ type AttributeType = 'string' | 'text' | 'textWithHeader' | 'integer' | 'real' |
82
82
  * Represents an attribute set entity.
83
83
  * @interface IAttributesSetsEntity
84
84
  * @property {AttributeType} type - Attribute type. Example: "string", "text", "integer", "etc".
85
- * @property {unknown} [value] - Value of the attribute, which can be of any type.
85
+ * @property {unknown} [value] - Value of the attribute, normalized the same way as an entity attribute value: `number | null` for numeric types, the file object itself for a single-file `image`/`file`, `null` when the attribute carries no value.
86
86
  * @property {unknown} initialValue - Initial value of the attribute.
87
87
  * @property {string} marker - Textual identifier of the attribute (marker). Example: "color", "size", "etc".
88
88
  * @property {number} position - Position number for sorting. Example: 1.
@@ -26,6 +26,8 @@ export declare const SignUpResponseSchema: z.ZodObject<{
26
26
  isDeleted: z.ZodOptional<z.ZodBoolean>;
27
27
  state: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
28
28
  rating: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
29
+ attributeSetId: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
30
+ attributesSets: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
29
31
  }, z.core.$strip>;
30
32
  /**
31
33
  * Auth response schema (login/refresh)
@@ -30,6 +30,8 @@ exports.SignUpResponseSchema = zod_1.z.object({
30
30
  isDeleted: zod_1.z.boolean().optional(),
31
31
  state: zod_1.z.record(zod_1.z.string(), zod_1.z.any()).optional(),
32
32
  rating: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()).optional(),
33
+ attributeSetId: zod_1.z.number().nullable().optional(),
34
+ attributesSets: zod_1.z.record(zod_1.z.string(), zod_1.z.unknown()).optional(),
33
35
  });
34
36
  /**
35
37
  * Auth response schema (login/refresh)
@@ -268,6 +268,8 @@ interface IOauthData {
268
268
  * @property {boolean} [isDeleted] - Whether the entity is deleted. Example: false.
269
269
  * @property {Record<string, unknown>} [state] - Additional state information. Example: {}.
270
270
  * @property {IRating} [rating] - Rating data.
271
+ * @property {number | null} [attributeSetId] - Identifier of the attribute set attached to the user, or null when none is attached. Example: null.
272
+ * @property {Record<string, unknown>} [attributesSets] - Attribute sets attached to the user, keyed by marker; empty object when none. Example: {}.
271
273
  * @description This interface defines the structure of a sign-up entity.
272
274
  */
273
275
  interface ISignUpEntity {
@@ -285,6 +287,8 @@ interface ISignUpEntity {
285
287
  isDeleted?: boolean;
286
288
  state?: Record<string, unknown>;
287
289
  rating?: IRating;
290
+ attributeSetId?: number | null;
291
+ attributesSets?: Record<string, unknown>;
288
292
  }
289
293
  /**
290
294
  * Interface representing a code entity used for user registration or verification processes.
@@ -15,6 +15,17 @@ export default abstract class AsyncModules extends SyncModules {
15
15
  * @description Constructor initializes the AsyncModules with a given state.
16
16
  */
17
17
  protected constructor(state: StateModule);
18
+ /**
19
+ * Detects an API error returned as a value instead of being thrown.
20
+ *
21
+ * With `isShell` enabled (the default) `browserResponse` returns the error
22
+ * body — and a caught exception — instead of throwing, so a failed request
23
+ * is indistinguishable from a successful one by control flow alone.
24
+ * @param {unknown} value - Value returned by a request.
25
+ * @returns {boolean} True when the value is an API error (statusCode >= 400) or a thrown error object.
26
+ * @description Recognizes both the OneEntry error body and errors caught by browserResponse (e.g. a network failure).
27
+ */
28
+ protected _isErrorResponse(value: unknown): value is IError;
18
29
  /**
19
30
  * Validates API response against a Zod schema (optional)
20
31
  * @param {unknown} data - The data to validate
@@ -59,8 +70,13 @@ export default abstract class AsyncModules extends SyncModules {
59
70
  *
60
71
  * Several endpoints (cancel/recover subscription, subscribe/unsubscribe to
61
72
  * events) return no useful body — callers only care whether the request
62
- * succeeded. This helper resolves to `true` on success and to the caught
63
- * error (as IError) on failure, centralizing the repeated try/catch.
73
+ * succeeded. This helper resolves to `true` on success and to the error
74
+ * (as IError) on failure, centralizing the repeated try/catch.
75
+ *
76
+ * The returned value has to be inspected as well: with `isShell` enabled
77
+ * (the default) browserResponse returns the API error instead of throwing
78
+ * it, so relying on the catch alone would report every failed call — a 404
79
+ * from cancelSubscription, a 403 from recoverSubscriptions — as a success.
64
80
  * @param {() => Promise<unknown>} request - Thunk performing the fetch call.
65
81
  * @returns {Promise<boolean | IError>} `true` on success, IError on failure.
66
82
  */
@@ -20,6 +20,26 @@ class AsyncModules extends syncModules_1.default {
20
20
  this.state = state;
21
21
  this._url = this.state.url;
22
22
  }
23
+ /**
24
+ * Detects an API error returned as a value instead of being thrown.
25
+ *
26
+ * With `isShell` enabled (the default) `browserResponse` returns the error
27
+ * body — and a caught exception — instead of throwing, so a failed request
28
+ * is indistinguishable from a successful one by control flow alone.
29
+ * @param {unknown} value - Value returned by a request.
30
+ * @returns {boolean} True when the value is an API error (statusCode >= 400) or a thrown error object.
31
+ * @description Recognizes both the OneEntry error body and errors caught by browserResponse (e.g. a network failure).
32
+ */
33
+ _isErrorResponse(value) {
34
+ if (value instanceof Error) {
35
+ return true;
36
+ }
37
+ return (value !== null &&
38
+ typeof value === 'object' &&
39
+ 'statusCode' in value &&
40
+ typeof value.statusCode === 'number' &&
41
+ value.statusCode >= 400);
42
+ }
23
43
  /**
24
44
  * Validates API response against a Zod schema (optional)
25
45
  * @param {unknown} data - The data to validate
@@ -33,11 +53,7 @@ class AsyncModules extends syncModules_1.default {
33
53
  return data;
34
54
  }
35
55
  // Skip validation for error responses (statusCode indicates API error)
36
- if (data !== null &&
37
- typeof data === 'object' &&
38
- 'statusCode' in data &&
39
- typeof data.statusCode === 'number' &&
40
- data.statusCode >= 400) {
56
+ if (this._isErrorResponse(data)) {
41
57
  return data;
42
58
  }
43
59
  // Use strict or safe validation based on config
@@ -109,14 +125,22 @@ class AsyncModules extends syncModules_1.default {
109
125
  *
110
126
  * Several endpoints (cancel/recover subscription, subscribe/unsubscribe to
111
127
  * events) return no useful body — callers only care whether the request
112
- * succeeded. This helper resolves to `true` on success and to the caught
113
- * error (as IError) on failure, centralizing the repeated try/catch.
128
+ * succeeded. This helper resolves to `true` on success and to the error
129
+ * (as IError) on failure, centralizing the repeated try/catch.
130
+ *
131
+ * The returned value has to be inspected as well: with `isShell` enabled
132
+ * (the default) browserResponse returns the API error instead of throwing
133
+ * it, so relying on the catch alone would report every failed call — a 404
134
+ * from cancelSubscription, a 403 from recoverSubscriptions — as a success.
114
135
  * @param {() => Promise<unknown>} request - Thunk performing the fetch call.
115
136
  * @returns {Promise<boolean | IError>} `true` on success, IError on failure.
116
137
  */
117
138
  async _fetchBoolean(request) {
118
139
  try {
119
- await request();
140
+ const result = await request();
141
+ if (this._isErrorResponse(result)) {
142
+ return result;
143
+ }
120
144
  return true;
121
145
  }
122
146
  catch (e) {
@@ -88,27 +88,33 @@ export default abstract class SyncModules {
88
88
  */
89
89
  protected _normalizePostBody(body: any, langCode?: string): any;
90
90
  /**
91
- * Clears arrays within the data structure.
91
+ * Normalizes the value of a single attribute in place.
92
92
  *
93
- * Traverses the data and fixes a specific edge case with image attributes:
94
- * when an `image` attribute has a single-element array in `value`,
95
- * the API returns an array but consumers expect a plain object.
96
- * In that case `value` is unwrapped: `[img]` → `img`.
93
+ * Applies the three type-driven fixes the API response needs, so that an
94
+ * attribute of a given type always reaches the consumer in the same shape,
95
+ * no matter which collection it arrived in:
97
96
  *
98
- * For all other keys the method recursively copies the structure unchanged.
99
- * @param {Record<string, any>} data - The data to clear.
100
- * @returns {any} Cleared data.
97
+ * 1. **Single-file values** (`image`, `file`) — the API always sends an array,
98
+ * even for one file: `[img]` → `img`. Multi-file values and `groupOfImages`
99
+ * (a collection by definition) stay an array.
100
+ * 2. **Empty values** — an attribute with no value comes back as an empty
101
+ * localization map `{}`; it is replaced with `null`, the same marker the
102
+ * numeric branch already produced.
103
+ * 3. **Numbers** (`integer`, `float`, `real`) — cast to a JS number; anything
104
+ * that is not a number (including an empty value) becomes `null`.
105
+ * @param {any} attr - The attribute object to normalize in place.
101
106
  */
102
- protected _clearArray(data: Record<string, any>): any;
107
+ private _normalizeAttrValue;
103
108
  /**
104
109
  * Sorts attributes by their positions.
105
110
  *
106
- * The API returns attributes as an object `{ marker: AttrObject }`.
107
- * Each attribute has a `position` field. The method rebuilds the object
108
- * with keys sorted by ascending `position` so that the display order
109
- * matches the order defined in the CMS.
110
- * @param {any} data - The data containing attributes.
111
- * @returns {any} Sorted attributes.
111
+ * Each attribute has a `position` field, and the API returns them in no
112
+ * particular order. The method rebuilds the collection sorted by ascending
113
+ * `position`, so the display order matches the order defined in the CMS.
114
+ * Both container shapes the API uses are handled: an object keyed by marker
115
+ * (`attributeValues`) and an array (form `attributes`).
116
+ * @param {any} data - The attributes collection to sort.
117
+ * @returns {any} Sorted attributes, in the same container shape.
112
118
  */
113
119
  protected _sortAttributes: (data: any) => any;
114
120
  /**
@@ -127,18 +133,23 @@ export default abstract class SyncModules {
127
133
  *
128
134
  * Handles three different attribute formats returned by the API:
129
135
  *
130
- * **1. `attributeValues`** attributes of pages, products and other entities.
131
- * Contains an object `{ marker: AttrObject }`. For each attribute:
132
- * - `_normalizeAdditionalFields` is called;
133
- * - numeric types (`integer`, `float`) are cast to a JS number (or `null`);
134
- * - the whole object is re-sorted by `position`.
136
+ * All three go through the same steps, so an attribute of a given type looks
137
+ * the same whichever collection it arrived in:
138
+ * - `_normalizeAdditionalFields` turns nested fields into a marker map;
139
+ * - `_normalizeAttrValue` unwraps single-file values, empties to `null` and
140
+ * casts numbers;
141
+ * - the collection is re-sorted by `position`.
135
142
  *
136
- * **2. `attributes`** — form attributes (different API structure).
137
- * Same `additionalFields` processing,
138
- * but numbers are not normalized here (commented out — logic differs).
143
+ * **1. `attributeValues`** — attributes of pages, products and other entities,
144
+ * an object `{ marker: AttrObject }`.
139
145
  *
140
- * **3. `type`** — a single attribute from an attribute set.
141
- * Same transformations as in case 1, but without sorting.
146
+ * **2. `attributes`** — form attributes, an array (or a marker map on some
147
+ * endpoints); form-only boolean flags (`isLogin`, `isSignUp`, notifications)
148
+ * are additionally coerced from `null` to `false`.
149
+ *
150
+ * **3. `type`** — a standalone attribute: an attribute-set entry, a form-data
151
+ * field or a nested `additionalFields` entry. Same transformations, but there
152
+ * is no collection to sort.
142
153
  *
143
154
  * `timeInterval` attributes are left exactly as the API returned them — a
144
155
  * compact recurrence rule. Resolving one into concrete slots is the caller's
@@ -150,17 +161,6 @@ export default abstract class SyncModules {
150
161
  * @returns {any} Normalized attributes.
151
162
  */
152
163
  protected _normalizeAttr(data: any): any;
153
- /**
154
- * Processes data after fetching or receiving it.
155
- *
156
- * Final post-processing of the API response: first unwraps localized fields
157
- * (`_normalizeData`), then fixes single-element image attributes
158
- * (`_clearArray`). Called at the end of every fetch method.
159
- * @param {any} data - The data to process.
160
- * @param {any} [langCode] - The language code for processing.
161
- * @returns {any} Processed data.
162
- */
163
- protected _dataPostProcess(data: any, langCode?: string): any;
164
164
  /**
165
165
  * Sets the access token in the state.
166
166
  * @param {string} accessToken - The access token to set.
@@ -91,14 +91,17 @@ class SyncModules {
91
91
  /**
92
92
  * Sorts attributes by their positions.
93
93
  *
94
- * The API returns attributes as an object `{ marker: AttrObject }`.
95
- * Each attribute has a `position` field. The method rebuilds the object
96
- * with keys sorted by ascending `position` so that the display order
97
- * matches the order defined in the CMS.
98
- * @param {any} data - The data containing attributes.
99
- * @returns {any} Sorted attributes.
94
+ * Each attribute has a `position` field, and the API returns them in no
95
+ * particular order. The method rebuilds the collection sorted by ascending
96
+ * `position`, so the display order matches the order defined in the CMS.
97
+ * Both container shapes the API uses are handled: an object keyed by marker
98
+ * (`attributeValues`) and an array (form `attributes`).
99
+ * @param {any} data - The attributes collection to sort.
100
+ * @returns {any} Sorted attributes, in the same container shape.
100
101
  */
101
- this._sortAttributes = (data) => Object.fromEntries(Object.entries(data).sort(([, a], [, b]) => a.position - b.position));
102
+ this._sortAttributes = (data) => Array.isArray(data)
103
+ ? [...data].sort((a, b) => a.position - b.position)
104
+ : Object.fromEntries(Object.entries(data).sort(([, a], [, b]) => a.position - b.position));
102
105
  this.state = state;
103
106
  this._url = state.url;
104
107
  this._nodeDeviceId = _generateId();
@@ -240,50 +243,42 @@ class SyncModules {
240
243
  return body;
241
244
  }
242
245
  /**
243
- * Clears arrays within the data structure.
246
+ * Normalizes the value of a single attribute in place.
244
247
  *
245
- * Traverses the data and fixes a specific edge case with image attributes:
246
- * when an `image` attribute has a single-element array in `value`,
247
- * the API returns an array but consumers expect a plain object.
248
- * In that case `value` is unwrapped: `[img]` → `img`.
248
+ * Applies the three type-driven fixes the API response needs, so that an
249
+ * attribute of a given type always reaches the consumer in the same shape,
250
+ * no matter which collection it arrived in:
249
251
  *
250
- * For all other keys the method recursively copies the structure unchanged.
251
- * @param {Record<string, any>} data - The data to clear.
252
- * @returns {any} Cleared data.
252
+ * 1. **Single-file values** (`image`, `file`) — the API always sends an array,
253
+ * even for one file: `[img]` → `img`. Multi-file values and `groupOfImages`
254
+ * (a collection by definition) stay an array.
255
+ * 2. **Empty values** — an attribute with no value comes back as an empty
256
+ * localization map `{}`; it is replaced with `null`, the same marker the
257
+ * numeric branch already produced.
258
+ * 3. **Numbers** (`integer`, `float`, `real`) — cast to a JS number; anything
259
+ * that is not a number (including an empty value) becomes `null`.
260
+ * @param {any} attr - The attribute object to normalize in place.
253
261
  */
254
- _clearArray(data) {
255
- if (Array.isArray(data)) {
256
- return data.map((item) => this._clearArray(item));
262
+ _normalizeAttrValue(attr) {
263
+ if ((attr.type === 'image' || attr.type === 'file') &&
264
+ Array.isArray(attr.value) &&
265
+ attr.value.length === 1) {
266
+ attr.value = attr.value[0];
257
267
  }
258
- else if (typeof data === 'object' && data) {
259
- const normalizeData = {};
260
- Object.keys(data).forEach((key) => {
261
- if (Array.isArray(data[key])) {
262
- normalizeData[key] = this._clearArray(data[key]);
263
- }
264
- else if (!data[key] || typeof data[key] !== 'object') {
265
- normalizeData[key] = data[key];
266
- }
267
- else if (key === 'attributeValues') {
268
- const attrs = data[key];
269
- Object.keys(attrs).forEach((attr) => {
270
- // If an image attribute has a single-element value array,
271
- // unwrap it to a plain object for consumer convenience.
272
- if (attrs[attr].type === 'image' &&
273
- attrs[attr].value.length === 1) {
274
- attrs[attr].value = attrs[attr].value[0];
275
- }
276
- });
277
- normalizeData[key] = data[key];
278
- }
279
- else {
280
- normalizeData[key] = this._clearArray(data[key]);
281
- }
282
- });
283
- return normalizeData;
268
+ // An attribute with no value arrives as an empty localization map.
269
+ if (attr.value &&
270
+ typeof attr.value === 'object' &&
271
+ !Array.isArray(attr.value) &&
272
+ Object.keys(attr.value).length === 0) {
273
+ attr.value = null;
284
274
  }
285
- else {
286
- return data;
275
+ if (attr.type === 'integer' ||
276
+ attr.type === 'float' ||
277
+ attr.type === 'real') {
278
+ // Number(null) is 0 and Number('') is 0 — an empty value must stay empty.
279
+ const isEmpty = attr.value === null || attr.value === undefined || attr.value === '';
280
+ const numValue = isEmpty ? NaN : Number(attr.value);
281
+ attr.value = isNaN(numValue) ? null : numValue;
287
282
  }
288
283
  }
289
284
  /**
@@ -306,18 +301,23 @@ class SyncModules {
306
301
  *
307
302
  * Handles three different attribute formats returned by the API:
308
303
  *
309
- * **1. `attributeValues`** attributes of pages, products and other entities.
310
- * Contains an object `{ marker: AttrObject }`. For each attribute:
311
- * - `_normalizeAdditionalFields` is called;
312
- * - numeric types (`integer`, `float`) are cast to a JS number (or `null`);
313
- * - the whole object is re-sorted by `position`.
304
+ * All three go through the same steps, so an attribute of a given type looks
305
+ * the same whichever collection it arrived in:
306
+ * - `_normalizeAdditionalFields` turns nested fields into a marker map;
307
+ * - `_normalizeAttrValue` unwraps single-file values, empties to `null` and
308
+ * casts numbers;
309
+ * - the collection is re-sorted by `position`.
314
310
  *
315
- * **2. `attributes`** — form attributes (different API structure).
316
- * Same `additionalFields` processing,
317
- * but numbers are not normalized here (commented out — logic differs).
311
+ * **1. `attributeValues`** — attributes of pages, products and other entities,
312
+ * an object `{ marker: AttrObject }`.
318
313
  *
319
- * **3. `type`** — a single attribute from an attribute set.
320
- * Same transformations as in case 1, but without sorting.
314
+ * **2. `attributes`** — form attributes, an array (or a marker map on some
315
+ * endpoints); form-only boolean flags (`isLogin`, `isSignUp`, notifications)
316
+ * are additionally coerced from `null` to `false`.
317
+ *
318
+ * **3. `type`** — a standalone attribute: an attribute-set entry, a form-data
319
+ * field or a nested `additionalFields` entry. Same transformations, but there
320
+ * is no collection to sort.
321
321
  *
322
322
  * `timeInterval` attributes are left exactly as the API returned them — a
323
323
  * compact recurrence rule. Resolving one into concrete slots is the caller's
@@ -334,11 +334,7 @@ class SyncModules {
334
334
  Object.keys(data.attributeValues).forEach((attr) => {
335
335
  const d = data.attributeValues[attr];
336
336
  this._normalizeAdditionalFields(d);
337
- // normalize numbers
338
- if (d.type === 'integer' || d.type === 'float') {
339
- const numValue = Number(d.value);
340
- d.value = isNaN(numValue) ? null : numValue;
341
- }
337
+ this._normalizeAttrValue(d);
342
338
  });
343
339
  return {
344
340
  ...data,
@@ -357,45 +353,27 @@ class SyncModules {
357
353
  const d = data.attributes;
358
354
  Object.keys(d).forEach((attr) => {
359
355
  this._normalizeAdditionalFields(d[attr]);
356
+ this._normalizeAttrValue(d[attr]);
360
357
  for (const field of booleanFields) {
361
358
  if (field in d[attr] && d[attr][field] === null) {
362
359
  d[attr][field] = false;
363
360
  }
364
361
  }
365
362
  });
366
- return data;
363
+ return { ...data, attributes: this._sortAttributes(d) };
367
364
  }
368
365
  // For single attribute - for attribute sets
369
366
  if ('type' in data) {
370
367
  this._normalizeAdditionalFields(data);
368
+ this._normalizeAttrValue(data);
371
369
  for (const field of booleanFields) {
372
370
  if (field in data && data[field] === null) {
373
371
  data[field] = false;
374
372
  }
375
373
  }
376
- // Normalize numbers
377
- if (data.type === 'integer' || data.type === 'float') {
378
- const numValue = Number(data.value);
379
- data.value = isNaN(numValue) ? null : numValue;
380
- }
381
374
  }
382
375
  return data;
383
376
  }
384
- /**
385
- * Processes data after fetching or receiving it.
386
- *
387
- * Final post-processing of the API response: first unwraps localized fields
388
- * (`_normalizeData`), then fixes single-element image attributes
389
- * (`_clearArray`). Called at the end of every fetch method.
390
- * @param {any} data - The data to process.
391
- * @param {any} [langCode] - The language code for processing.
392
- * @returns {any} Processed data.
393
- */
394
- _dataPostProcess(data, langCode = this.state.lang) {
395
- const normalize = this._normalizeData(data, langCode);
396
- const result = this._clearArray(normalize);
397
- return result;
398
- }
399
377
  /**
400
378
  * Sets the access token in the state.
401
379
  * @param {string} accessToken - The access token to set.
@@ -260,8 +260,8 @@ interface ITimeIntervalRange {
260
260
  /**
261
261
  * @interface IAttributeValue
262
262
  * @property {string} type - Attribute data type (e.g. "string", "integer", "list", "file", "image").
263
- * @property {unknown} value - Attribute value — actual TS type depends on `type` (string for "string"/"text", number for "integer", array for "list", etc.). Example: "Admins text".
264
- * @property {number} [position] - Sort position of the value inside its set. Example: 0.
263
+ * @property {unknown} value - Attribute value — actual TS type depends on `type`, and the SDK normalizes it to the same shape in every module: `string` for "string"/"text"; `number | null` for "integer"/"float"/"real"; the file object itself for a single-file "image"/"file" and an array of them for several; an array for "list" and "groupOfImages". An attribute with no value is always `null`. Example: "Admins text".
264
+ * @property {number} [position] - Sort position of the value inside its set; the containing collection is returned sorted by it. Example: 0.
265
265
  * @property {Record<string, IAttributeValue> | unknown[]} [additionalFields] - Nested attribute values keyed by marker; the API may also return an empty array when none are configured. Optional.
266
266
  * @property {boolean} [isIcon] - Block/preview attribute flag — whether the field is treated as an icon. Optional.
267
267
  * @property {boolean} [isProductPreview] - Block/preview attribute flag — whether the field is shown in product preview. Optional.
@@ -38,7 +38,7 @@ class FormsApi extends asyncModules_1.default {
38
38
  const result = await this._fetchGet(`?langCode=${langCode}&offset=${offset}&limit=${limit}`);
39
39
  // Validate response if validation is enabled
40
40
  const validated = this._validateResponse(result, formsSchemas_1.FormsResponseSchema);
41
- return this._dataPostProcess(validated, langCode);
41
+ return this._normalizeData(validated, langCode);
42
42
  }
43
43
  /**
44
44
  * Get one form by form marker.
@@ -53,7 +53,7 @@ class FormsApi extends asyncModules_1.default {
53
53
  const result = await this._fetchGet(`/marker/${marker}?langCode=${langCode}`);
54
54
  // Validate response if validation is enabled
55
55
  const validated = this._validateResponse(result, formsSchemas_1.FormEntitySchema);
56
- return this._dataPostProcess(validated, langCode);
56
+ return this._normalizeData(validated, langCode);
57
57
  }
58
58
  }
59
59
  exports.default = FormsApi;