oneentry 1.0.154 → 1.0.155

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
@@ -90,6 +90,8 @@ The second parameter of the constructor takes the 'config'. It contains the foll
90
90
 
91
91
  - 'guestId' - Optional guest identifier sent as the "x-guest-id" header on unauthenticated requests. It enables guest cart / wishlist / activity flows. In the browser, if you omit it, the SDK generates a stable id and persists it in localStorage. On the server you must pass a per-visitor "guestId" (or call "setGuestId"): the SDK never auto-generates a server id, to avoid sharing one guest across visitors. The header is omitted once a user is authenticated.
92
92
 
93
+ - 'deviceMetadata' - Optional device-metadata string sent as the "x-device-metadata" header instead of the fingerprint the SDK computes from the current environment. The API binds refresh tokens to this header, so a server that issues tokens on behalf of a browser (for example, an OAuth code exchange keeping the client secret server-side) must pass the browser's string here — otherwise the issued refresh token is bound to the server's fingerprint and cannot be refreshed from the browser. Obtain the string in the browser via "getDeviceMetadata()" and set/clear it at runtime via "setDeviceMetadata".
94
+
93
95
  - 'traficLimit' - Some methods use more than one request to the CMS so that the data you receive is complete and easy to work with. Pass the value "true" for this parameter to save traffic and decide for yourself what data you need. The default value "false".
94
96
 
95
97
  - 'auth' - An object with authorization settings. By default, the SDK is configured to work with tokens inside the user's session and does not require any additional work from you. At the same time, the SDK does not store the session state between sessions. If you are satisfied with such settings, do not pass the variable 'auth' at all.
package/changelog.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # SDK Change Log
2
2
 
3
+ ## v.1.0.155
4
+
5
+ ### What's New
6
+
7
+ - Config > `deviceMetadata` — new optional config parameter that overrides the `x-device-metadata` header (sent on POST requests and token refresh) instead of the fingerprint computed from the current environment. The API binds refresh tokens to this header, so a server issuing tokens on behalf of a browser (e.g. an OAuth code exchange that keeps the client secret server-side) can now stamp the browser's fingerprint and the issued refresh token stays refreshable from that browser. Previously this required bypassing the SDK with a raw `fetch`.
8
+ - `setDeviceMetadata(deviceMetadata)` — new public method on every module: sets the `x-device-metadata` override at runtime (empty string clears it and falls back to the computed fingerprint).
9
+ - `getDeviceMetadata()` — new public method on every module: returns the `x-device-metadata` string the SDK sends (the override when set, otherwise the environment-derived fingerprint). Use it in the browser to obtain the value that a server-side token-issuing flow must forward; previously this required reaching into the protected `_getDeviceMetadata`.
10
+
11
+ ### Bug Fixes
12
+
13
+ - `Blocks.getBlocks` — error responses no longer crash block enrichment. On an API error (e.g. `403` without list permission, or `422`) the normalized value is an `IError` without an `items` array; the method previously called `.items.map(...)` unconditionally and threw a `TypeError`. Enrichment now runs only when `items` is an array, and the error response is returned as-is.
14
+
15
+ - `Pages.getRootPages`, `getPages`, `getChildPagesByParentUrl`, `searchPage` — error responses no longer crash template enrichment. The shared `addTemplateToPages` helper called `.filter(...)` / `.map(...)` on its input; on an API error (e.g. `403` / `422`) that input is an `IError` object, not an array, which threw a `TypeError`. The helper now returns the error response as-is when the input is not an array.
16
+
17
+ - `Blocks.getProductsByBlockMarker` (used internally by block enrichment) — on an API error the method read `result.items` (which is `undefined` for an `IError`) and returned `undefined` instead of the error. It now returns the normalized error response when there is no `items` array.
18
+
19
+ ### What's Deleted
20
+
21
+ - AttributesSets > `IAttributeSetsEntity.typeId` and `IAttributeSetsEntity.properties` — removed: the API no longer returns these fields for `getAttributes` / `getAttributeSetByMarker`. The attribute set type is available via the `type` object (`type.id`, `type.type`). The Zod schema (`AttributeSetEntitySchema`) is updated accordingly. The `typeId` **query parameter** of `getAttributes` is unaffected.
22
+ - TemplatePreviews > `ITemplatesPreviewEntity.attributeValues` — removed: the API no longer returns this field for `getTemplatePreviews` / `getTemplatePreviewByMarker` (it was always an empty object). The Zod schema (`TemplatePreviewEntitySchema`) is updated accordingly.
23
+
3
24
  ## v.1.0.154
4
25
 
5
26
  ### What's New
@@ -206,7 +206,6 @@ interface IAttributeValidators {
206
206
  * @property {string} updatedDate - The date when the attribute set was last updated. Example: "2023-10-01T12:00:00Z".
207
207
  * @property {number} version - The version number of the attribute set, used for tracking changes or updates. Example: 1.
208
208
  * @property {string} identifier - A string that uniquely identifies the attribute set. Example: "attributeSet1".
209
- * @property {number} typeId - The numerical identifier representing the type of the attribute set. Example: 1.
210
209
  * @property {string} title - The title or name of the attribute set. Example: "Product Attributes".
211
210
  * @property {Record<string, IAttributeSchemaItem>} schema - Schema fields keyed by marker.
212
211
  * @example
@@ -223,12 +222,6 @@ interface IAttributeValidators {
223
222
  }
224
223
  }
225
224
  * @property {boolean} isVisible - Indicates whether the attribute set is visible or not. Example: true.
226
- * @property {Record<string, unknown>} properties - Additional properties associated with the attribute set; empty object when none.
227
- * @example
228
- {
229
- "color": "red",
230
- "size": "M"
231
- }
232
225
  * @property {string} type - The type of the attribute set, which could be a specific classification or category. Example: "product", "user", "etc".
233
226
  * @property {number} position - The position number for sorting the attribute set. Example: 1.
234
227
  * @description This interface defines the structure of an attribute set entity.
@@ -239,11 +232,9 @@ interface IAttributeSetsEntity {
239
232
  updatedDate: string;
240
233
  version: number;
241
234
  identifier: string;
242
- typeId: number;
243
235
  title: string;
244
236
  schema: Record<string, IAttributeSchemaItem>;
245
237
  isVisible: boolean;
246
- properties: Record<string, unknown>;
247
238
  type: IAttributeSetTypeRef;
248
239
  position: number;
249
240
  }
@@ -38,11 +38,9 @@ export declare const AttributeSetEntitySchema: z.ZodObject<{
38
38
  updatedDate: z.ZodString;
39
39
  version: z.ZodNumber;
40
40
  identifier: z.ZodString;
41
- typeId: z.ZodNumber;
42
41
  title: z.ZodString;
43
42
  schema: z.ZodObject<{}, z.core.$loose>;
44
43
  isVisible: z.ZodBoolean;
45
- properties: z.ZodObject<{}, z.core.$loose>;
46
44
  type: z.ZodObject<{
47
45
  id: z.ZodNumber;
48
46
  type: z.ZodString;
@@ -60,11 +58,9 @@ export declare const AttributeSetsResponseSchema: z.ZodObject<{
60
58
  updatedDate: z.ZodString;
61
59
  version: z.ZodNumber;
62
60
  identifier: z.ZodString;
63
- typeId: z.ZodNumber;
64
61
  title: z.ZodString;
65
62
  schema: z.ZodObject<{}, z.core.$loose>;
66
63
  isVisible: z.ZodBoolean;
67
- properties: z.ZodObject<{}, z.core.$loose>;
68
64
  type: z.ZodObject<{
69
65
  id: z.ZodNumber;
70
66
  type: z.ZodString;
@@ -47,11 +47,9 @@ exports.AttributeSetEntitySchema = zod_1.z.object({
47
47
  updatedDate: zod_1.z.string(),
48
48
  version: zod_1.z.number(),
49
49
  identifier: zod_1.z.string(),
50
- typeId: zod_1.z.number(),
51
50
  title: zod_1.z.string(),
52
51
  schema: zod_1.z.object({}).passthrough(),
53
52
  isVisible: zod_1.z.boolean(),
54
- properties: zod_1.z.object({}).passthrough(),
55
53
  type: zod_1.z.object({
56
54
  id: zod_1.z.number(),
57
55
  type: zod_1.z.string(),
@@ -10,6 +10,7 @@ export default class StateModule {
10
10
  lang: string | undefined;
11
11
  token: string | undefined;
12
12
  guestId: string | undefined;
13
+ deviceMetadata: string | undefined;
13
14
  accessToken: string | undefined;
14
15
  traficLimit: boolean;
15
16
  refreshToken: string | undefined;
@@ -27,6 +27,9 @@ class StateModule {
27
27
  // Normalize empty string to undefined: an explicit '' must not masquerade
28
28
  // as a set guest id (it would otherwise suppress id resolution).
29
29
  this.guestId = config.guestId || undefined;
30
+ // Same normalization as guestId: an explicit '' must not suppress the
31
+ // environment-derived fingerprint.
32
+ this.deviceMetadata = config.deviceMetadata || undefined;
30
33
  this.traficLimit = config.traficLimit || false;
31
34
  this.validationEnabled = (_c = (_b = config.validation) === null || _b === void 0 ? void 0 : _b.enabled) !== null && _c !== void 0 ? _c : false;
32
35
  this.validationStrictMode = (_e = (_d = config.validation) === null || _d === void 0 ? void 0 : _d.strictMode) !== null && _e !== void 0 ? _e : false;
@@ -287,6 +287,30 @@ export default abstract class SyncModules {
287
287
  * @returns {any} The instance of SyncModules for chaining.
288
288
  */
289
289
  setGuestId(guestId: string): any;
290
+ /**
291
+ * Sets the device-metadata override in the state.
292
+ *
293
+ * Once set, the string is sent as the `x-device-metadata` header on POST
294
+ * requests and token refresh instead of the environment-derived fingerprint.
295
+ * The API binds refresh tokens to this header, so server-side flows that issue
296
+ * tokens on behalf of a browser (e.g. an OAuth code exchange) must set the
297
+ * browser's string (obtained there via `getDeviceMetadata`). Pass an empty
298
+ * string to clear the override and fall back to the computed fingerprint.
299
+ * @param {string} deviceMetadata - The metadata string to send (empty string clears the override).
300
+ * @returns {any} The instance of SyncModules for chaining.
301
+ */
302
+ setDeviceMetadata(deviceMetadata: string): any;
303
+ /**
304
+ * Returns the device-metadata string the SDK sends as the `x-device-metadata` header.
305
+ *
306
+ * Public counterpart of `_getDeviceMetadata`: an explicit override (config or
307
+ * `setDeviceMetadata`) wins, otherwise the environment-derived fingerprint is
308
+ * computed. Use it in the browser to obtain the string that a server-side
309
+ * token-issuing flow (OAuth code exchange) must forward, so the issued refresh
310
+ * token stays refreshable from this browser.
311
+ * @returns {string} The metadata string sent with requests from this instance.
312
+ */
313
+ getDeviceMetadata(): string;
290
314
  /**
291
315
  * Get deviceMetadata
292
316
  *
@@ -313,6 +337,10 @@ export default abstract class SyncModules {
313
337
  * lives until the process restarts.
314
338
  *
315
339
  * In a Node.js environment (no `window`) returns a simplified object without screen/navigator.
340
+ *
341
+ * An explicitly provided string (`deviceMetadata` in config or `setDeviceMetadata`)
342
+ * takes precedence over the environment-derived fingerprint — this lets a server
343
+ * issue tokens bound to the browser's fingerprint (see `IConfig.deviceMetadata`).
316
344
  * @returns {string} - Returns an object containing device metadata.
317
345
  */
318
346
  protected _getDeviceMetadata(): string;
@@ -698,6 +698,35 @@ class SyncModules {
698
698
  this.state.guestId = guestId || undefined;
699
699
  return this;
700
700
  }
701
+ /**
702
+ * Sets the device-metadata override in the state.
703
+ *
704
+ * Once set, the string is sent as the `x-device-metadata` header on POST
705
+ * requests and token refresh instead of the environment-derived fingerprint.
706
+ * The API binds refresh tokens to this header, so server-side flows that issue
707
+ * tokens on behalf of a browser (e.g. an OAuth code exchange) must set the
708
+ * browser's string (obtained there via `getDeviceMetadata`). Pass an empty
709
+ * string to clear the override and fall back to the computed fingerprint.
710
+ * @param {string} deviceMetadata - The metadata string to send (empty string clears the override).
711
+ * @returns {any} The instance of SyncModules for chaining.
712
+ */
713
+ setDeviceMetadata(deviceMetadata) {
714
+ this.state.deviceMetadata = deviceMetadata || undefined;
715
+ return this;
716
+ }
717
+ /**
718
+ * Returns the device-metadata string the SDK sends as the `x-device-metadata` header.
719
+ *
720
+ * Public counterpart of `_getDeviceMetadata`: an explicit override (config or
721
+ * `setDeviceMetadata`) wins, otherwise the environment-derived fingerprint is
722
+ * computed. Use it in the browser to obtain the string that a server-side
723
+ * token-issuing flow (OAuth code exchange) must forward, so the issued refresh
724
+ * token stays refreshable from this browser.
725
+ * @returns {string} The metadata string sent with requests from this instance.
726
+ */
727
+ getDeviceMetadata() {
728
+ return this._getDeviceMetadata();
729
+ }
701
730
  /**
702
731
  * Get deviceMetadata
703
732
  *
@@ -724,10 +753,18 @@ class SyncModules {
724
753
  * lives until the process restarts.
725
754
  *
726
755
  * In a Node.js environment (no `window`) returns a simplified object without screen/navigator.
756
+ *
757
+ * An explicitly provided string (`deviceMetadata` in config or `setDeviceMetadata`)
758
+ * takes precedence over the environment-derived fingerprint — this lets a server
759
+ * issue tokens bound to the browser's fingerprint (see `IConfig.deviceMetadata`).
727
760
  * @returns {string} - Returns an object containing device metadata.
728
761
  */
729
762
  _getDeviceMetadata() {
730
763
  var _a;
764
+ // Explicit override wins: the API binds refresh tokens to this header, so
765
+ // server-side token issuance must be able to stamp the browser's string.
766
+ if (this.state.deviceMetadata)
767
+ return this.state.deviceMetadata;
731
768
  // Check if we're in a browser environment
732
769
  if (typeof globalThis === 'undefined') {
733
770
  return '';
@@ -2,6 +2,7 @@
2
2
  * @interface IConfig
3
3
  * @property {string} [token] - If your project is protected by a token, specify this token in this parameter.
4
4
  * @property {string} [guestId] - Guest identifier sent as the `x-guest-id` header on unauthenticated requests. Lets cart/wishlist/activity endpoints work for a guest. In the browser a stable id is auto-generated (localStorage) when omitted; on the server pass a per-visitor id. Can also be set later via `setGuestId`.
5
+ * @property {string} [deviceMetadata] - Device-metadata string sent as the `x-device-metadata` header on POST requests and token refresh, overriding the environment-derived fingerprint. The API binds refresh tokens to this header, so server-side flows that issue tokens on behalf of a browser (e.g. an OAuth code exchange) must pass the browser's string here — otherwise the token is bound to the server's fingerprint and cannot be refreshed from the browser. Obtain the string in the browser via `getDeviceMetadata()`. Can also be set later via `setDeviceMetadata`.
5
6
  * @property {string} [langCode] - specify the default language to avoid specifying it in every request.
6
7
  * @property {boolean} [traficLimit] - Some methods use multiple queries to make it easier to work with the API. Set this parameter to "false" to save traffic and decide for yourself what data you need.
7
8
  * @property {boolean} [rawData] - Set to true to receive raw API responses without any transformation.
@@ -44,6 +45,7 @@
44
45
  interface IConfig {
45
46
  token?: string;
46
47
  guestId?: string;
48
+ deviceMetadata?: string;
47
49
  langCode?: string;
48
50
  traficLimit?: boolean;
49
51
  rawData?: boolean;
@@ -43,7 +43,12 @@ class BlocksApi extends asyncModules_1.default {
43
43
  const validated = this._validateResponse(response, blocksSchemas_1.BlocksResponseSchema);
44
44
  if (!this.state.traficLimit) {
45
45
  const normalizeResponse = this._normalizeData(validated);
46
- await Promise.all(normalizeResponse.items.map((block) => this._enrichBlock(block, langCode, offset, limit, true)));
46
+ // On API error responses (e.g. 403 without list permission, 422) the
47
+ // normalized value is an IError without `items` — skip enrichment and
48
+ // return it as-is
49
+ if (Array.isArray(normalizeResponse.items)) {
50
+ await Promise.all(normalizeResponse.items.map((block) => this._enrichBlock(block, langCode, offset, limit, true)));
51
+ }
47
52
  return normalizeResponse;
48
53
  }
49
54
  return this._normalizeData(validated);
@@ -169,6 +174,11 @@ class BlocksApi extends asyncModules_1.default {
169
174
  signPrice,
170
175
  };
171
176
  const result = await this._fetchGet(`/${marker}/products?` + this._queryParamsToString(query));
177
+ // On API error responses there is no `items` array — return the (normalized)
178
+ // error as-is instead of producing `undefined` from `result.items`.
179
+ if (!Array.isArray(result === null || result === void 0 ? void 0 : result.items)) {
180
+ return this._normalizeData(result);
181
+ }
172
182
  return this._normalizeData(result.items);
173
183
  }
174
184
  /**
package/dist/index.d.ts CHANGED
@@ -123,6 +123,7 @@ interface IDefineApi {
123
123
  * @param {IConfig} config - Custom configuration settings
124
124
  * @param {string} [config.token] - Optional token parameter
125
125
  * @param {string} [config.guestId] - Optional guest identifier sent as the `x-guest-id` header for guest cart/wishlist/activity flows (only while unauthenticated). In the browser, if omitted, a stable per-device id is generated and persisted in localStorage. On the server you MUST pass a per-visitor `guestId` (or call `setGuestId`): the SDK never auto-generates a server id, to avoid sharing one guest across visitors.
126
+ * @param {string} [config.deviceMetadata] - Optional device-metadata string sent as the `x-device-metadata` header instead of the environment-derived fingerprint. Refresh tokens are bound to this header, so a server issuing tokens for a browser (OAuth code exchange) must pass the browser's string (from `getDeviceMetadata()`), or the token will not be refreshable from that browser.
126
127
  * @param {string} [config.langCode] - Optional langCode parameter
127
128
  * @param {boolean} [config.traficLimit] - Some methods use multiple queries to make it easier to work with the API. Set this parameter to "false" to save traffic and decide for yourself what data you need.
128
129
  * @param {string} [config.auth] - An object with authorization settings.
package/dist/index.js CHANGED
@@ -42,6 +42,7 @@ const wsApi_1 = __importDefault(require("./web-socket/wsApi"));
42
42
  * @param {IConfig} config - Custom configuration settings
43
43
  * @param {string} [config.token] - Optional token parameter
44
44
  * @param {string} [config.guestId] - Optional guest identifier sent as the `x-guest-id` header for guest cart/wishlist/activity flows (only while unauthenticated). In the browser, if omitted, a stable per-device id is generated and persisted in localStorage. On the server you MUST pass a per-visitor `guestId` (or call `setGuestId`): the SDK never auto-generates a server id, to avoid sharing one guest across visitors.
45
+ * @param {string} [config.deviceMetadata] - Optional device-metadata string sent as the `x-device-metadata` header instead of the environment-derived fingerprint. Refresh tokens are bound to this header, so a server issuing tokens for a browser (OAuth code exchange) must pass the browser's string (from `getDeviceMetadata()`), or the token will not be refreshable from that browser.
45
46
  * @param {string} [config.langCode] - Optional langCode parameter
46
47
  * @param {boolean} [config.traficLimit] - Some methods use multiple queries to make it easier to work with the API. Set this parameter to "false" to save traffic and decide for yourself what data you need.
47
48
  * @param {string} [config.auth] - An object with authorization settings.
@@ -277,6 +277,12 @@ class PagesApi extends asyncModules_1.default {
277
277
  * For example, if 100 pages use 3 different templates, this method makes 3 requests instead of 100.
278
278
  */
279
279
  async addTemplateToPages(data) {
280
+ // On API error responses (e.g. 403 without list permission, 422) the value
281
+ // is an IError, not an array — return it as-is instead of calling array
282
+ // methods (.filter/.map) on it and throwing a TypeError.
283
+ if (!Array.isArray(data)) {
284
+ return data;
285
+ }
280
286
  // Step 1: Collect unique templateIdentifiers from all pages
281
287
  const uniqueIdentifiers = [
282
288
  ...new Set(data
@@ -381,6 +387,11 @@ class StaffModule extends asyncModules_1.default {
381
387
  async getProductsByBlockMarker(marker, langCode = this.state.lang, offset = 0, limit = 30) {
382
388
  // Fetch products from the server
383
389
  const result = await this._fetchGet(`/${marker}/products?langCode=${langCode}&offset=${offset}&limit=${limit}`);
390
+ // On API error responses there is no `items` array — return the (normalized)
391
+ // error as-is instead of producing `undefined` from `result.items`.
392
+ if (!Array.isArray(result === null || result === void 0 ? void 0 : result.items)) {
393
+ return this._normalizeData(result);
394
+ }
384
395
  return this._normalizeData(result.items);
385
396
  }
386
397
  }
@@ -1,4 +1,4 @@
1
- import type { IAttributeValues, IError } from '../base/utils';
1
+ import type { IError } from '../base/utils';
2
2
  /**
3
3
  * @interface ITemplatesPreviewApi
4
4
  * @description This interface defines methods for retrieving template previews in the system, including fetching all previews, specific previews by marker.
@@ -69,7 +69,6 @@ interface ITemplatesPreviewApi {
69
69
  }
70
70
  * @property {string} identifier - The textual identifier for the record field. Example: "preview-templates"
71
71
  * @property {number} version - The version number of the object. Example: 1.
72
- * @property {IAttributeValues} attributeValues - Attribute values from index. Example: {}
73
72
  * @property {number} position - The position of the object. Example: 1.
74
73
  * @property {boolean} isUsed - Indicates whether the template preview is used. Example: true.
75
74
  * @property {string | null} [attributeSetIdentifier] - Text identifier used for a set of attributes. Example: "attribute_set_1".
@@ -81,7 +80,6 @@ interface ITemplatesPreviewEntity {
81
80
  proportions: ITemplatesPreviewProportions;
82
81
  identifier: string;
83
82
  version: number;
84
- attributeValues: IAttributeValues;
85
83
  position: number;
86
84
  isUsed: boolean;
87
85
  attributeSetIdentifier?: string | null;
@@ -45,7 +45,6 @@ export declare const TemplatePreviewEntitySchema: z.ZodObject<{
45
45
  }, z.core.$strip>;
46
46
  identifier: z.ZodString;
47
47
  version: z.ZodNumber;
48
- attributeValues: z.ZodRecord<z.ZodString, z.ZodAny>;
49
48
  position: z.ZodNumber;
50
49
  isUsed: z.ZodBoolean;
51
50
  attributeSetIdentifier: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -76,7 +75,6 @@ export declare const TemplatePreviewsResponseSchema: z.ZodArray<z.ZodObject<{
76
75
  }, z.core.$strip>;
77
76
  identifier: z.ZodString;
78
77
  version: z.ZodNumber;
79
- attributeValues: z.ZodRecord<z.ZodString, z.ZodAny>;
80
78
  position: z.ZodNumber;
81
79
  isUsed: z.ZodBoolean;
82
80
  attributeSetIdentifier: z.ZodOptional<z.ZodNullable<z.ZodString>>;
@@ -37,7 +37,6 @@ exports.TemplatePreviewEntitySchema = zod_1.z.object({
37
37
  }),
38
38
  identifier: zod_1.z.string(),
39
39
  version: zod_1.z.number(),
40
- attributeValues: zod_1.z.record(zod_1.z.string(), zod_1.z.any()),
41
40
  position: zod_1.z.number(),
42
41
  isUsed: zod_1.z.boolean(),
43
42
  attributeSetIdentifier: zod_1.z.string().nullable().optional(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "oneentry",
3
- "version": "1.0.154",
3
+ "version": "1.0.155",
4
4
  "description": "OneEntry NPM package",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,39 +0,0 @@
1
- /**
2
- * Result class for handling response data.
3
- * @description Result class for handling response data.
4
- */
5
- export default class Result {
6
- body: any;
7
- /**
8
- * Constructor that initializes the class with a given data.
9
- * @param {Response | string} data - Response or string data.
10
- * @description Constructor that initializes the class with a given data, which can be of type Response or string.
11
- */
12
- constructor(data: Response | string);
13
- /**
14
- * Asynchronously converts the body to a blob and returns the current instance.
15
- * @returns {Promise<Result>} Current instance.
16
- * @description Asynchronously converts the body to a blob and returns the current instance.
17
- */
18
- blob(): Promise<Result>;
19
- /**
20
- * Asynchronously parses the body as JSON and returns the current instance.
21
- * @returns {Promise<Result>} Current instance.
22
- * @description Asynchronously parses the body as JSON and returns the current instance.
23
- */
24
- json(): Promise<Result>;
25
- /**
26
- * Recursively removes language-specific data from the provided data or the body.
27
- * @param {string} langCode - Language code.
28
- * @param {any} [data] - Data to process.
29
- * @returns {any} Processed data.
30
- * @description Recursively removes language-specific data from the provided data or the body.
31
- */
32
- makeDataWithoutLang(langCode: string, data?: any): any;
33
- /**
34
- * Recursively simplifies arrays in the provided data or the body by removing single-element arrays.
35
- * @param {any} data - The data to simplify.
36
- * @returns {any} The simplified data.
37
- */
38
- makeDataWithoutArray(data?: any): any;
39
- }
@@ -1,154 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- /* eslint-disable jsdoc/reject-any-type */
4
- /* eslint-disable no-restricted-syntax */
5
- /* eslint-disable @typescript-eslint/no-explicit-any */
6
- /**
7
- * Result class for handling response data.
8
- * @description Result class for handling response data.
9
- */
10
- class Result {
11
- /**
12
- * Constructor that initializes the class with a given data.
13
- * @param {Response | string} data - Response or string data.
14
- * @description Constructor that initializes the class with a given data, which can be of type Response or string.
15
- */
16
- constructor(data) {
17
- this.body = data;
18
- }
19
- /**
20
- * Asynchronously converts the body to a blob and returns the current instance.
21
- * @returns {Promise<Result>} Current instance.
22
- * @description Asynchronously converts the body to a blob and returns the current instance.
23
- */
24
- async blob() {
25
- // Convert the body to a blob using the blob() method.
26
- this.body = await this.body.blob();
27
- return this;
28
- }
29
- /**
30
- * Asynchronously parses the body as JSON and returns the current instance.
31
- * @returns {Promise<Result>} Current instance.
32
- * @description Asynchronously parses the body as JSON and returns the current instance.
33
- */
34
- async json() {
35
- // Check if the body is a string, then parse it as JSON, otherwise call the json() method.
36
- this.body =
37
- (await typeof this.body) === 'string'
38
- ? JSON.parse(this.body)
39
- : this.body.json();
40
- return this;
41
- }
42
- /**
43
- * Recursively removes language-specific data from the provided data or the body.
44
- * @param {string} langCode - Language code.
45
- * @param {any} [data] - Data to process.
46
- * @returns {any} Processed data.
47
- * @description Recursively removes language-specific data from the provided data or the body.
48
- */
49
- makeDataWithoutLang(langCode, data) {
50
- if (data) {
51
- // If data is an array, recursively process each item.
52
- if (Array.isArray(data)) {
53
- return data.map((item) => this.makeDataWithoutLang(langCode, item));
54
- }
55
- else {
56
- // Iterate through each key in the data object.
57
- for (const key in data) {
58
- // If the value is an object containing the specified language code, replace it with the language-specific value.
59
- if (typeof data[key] === 'object' &&
60
- data[key] &&
61
- langCode in data[key]) {
62
- data[key] = data[key][langCode];
63
- }
64
- else if (typeof data[key] === 'object' && data[key] != null) {
65
- // If the value is an object, recursively process it.
66
- data[key] = this.makeDataWithoutLang(langCode, data[key]);
67
- }
68
- else if (Array.isArray(data[key])) {
69
- // If the value is an array, recursively process each item.
70
- data[key] = data.map((item) => this.makeDataWithoutLang(langCode, item));
71
- }
72
- }
73
- // Return the processed data.
74
- return data;
75
- }
76
- }
77
- else {
78
- // Process the body if no specific data is provided.
79
- if (Array.isArray(this.body)) {
80
- this.body = this.body.map((item) => this.makeDataWithoutLang(langCode, item));
81
- }
82
- else {
83
- // Iterate through each key in the body object.
84
- for (const key in this.body) {
85
- // Similar processing as above but applied to the body.
86
- if (typeof this.body[key] === 'object' &&
87
- this.body[key] &&
88
- langCode in this.body[key]) {
89
- this.body[key] = this.body[key][langCode];
90
- }
91
- else if (typeof this.body[key] === 'object' &&
92
- this.body[key] != null) {
93
- this.body[key] = this.makeDataWithoutLang(langCode, this.body[key]);
94
- }
95
- else if (Array.isArray(this.body[key])) {
96
- this.body[key] = this.body[key].map((item) => this.makeDataWithoutLang(langCode, item));
97
- }
98
- }
99
- }
100
- return this;
101
- }
102
- }
103
- /**
104
- * Recursively simplifies arrays in the provided data or the body by removing single-element arrays.
105
- * @param {any} data - The data to simplify.
106
- * @returns {any} The simplified data.
107
- */
108
- makeDataWithoutArray(data) {
109
- if (data) {
110
- // If data is an array, recursively process each item.
111
- if (Array.isArray(data)) {
112
- return data.map((item) => this.makeDataWithoutArray(item));
113
- }
114
- else {
115
- // Iterate through each key in the data object.
116
- for (const key in data) {
117
- // If the value is a single-element array, replace it with the element itself.
118
- if (Array.isArray(data[key]) && data[key].length === 1) {
119
- data[key] = data[key][0];
120
- }
121
- else if (typeof data[key] === 'object' &&
122
- data[key] &&
123
- !Array.isArray(data[key])) {
124
- // If the value is an object, recursively process it.
125
- data[key] = this.makeDataWithoutArray(data[key]);
126
- }
127
- }
128
- return data;
129
- }
130
- }
131
- else {
132
- // Process the body if no specific data is provided.
133
- if (Array.isArray(this.body)) {
134
- return this.body.map((item) => this.makeDataWithoutArray(item));
135
- }
136
- else {
137
- // Iterate through each key in the body object.
138
- for (const key in this.body) {
139
- // Similar processing as above but applied to the body.
140
- if (Array.isArray(this.body[key]) && this.body[key].length === 1) {
141
- this.body[key] = this.body[key][0];
142
- }
143
- else if (typeof this.body[key] === 'object' &&
144
- this.body[key] &&
145
- !Array.isArray(this.body[key])) {
146
- this.body[key] = this.makeDataWithoutArray(this.body[key]);
147
- }
148
- }
149
- return this;
150
- }
151
- }
152
- }
153
- }
154
- exports.default = Result;