@pakento/cms-sdk 4.3.1 → 4.3.2

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/dist/index.mjs CHANGED
@@ -1,15 +1,14 @@
1
- // src/services/api.ts
1
+ // src/api/core/apiClient.ts
2
2
  import axios, { AxiosError } from "axios";
3
+ import { z } from "zod";
3
4
 
4
- // src/services/cache.ts
5
+ // src/api/core/cache.ts
5
6
  import { Redis } from "@upstash/redis";
6
7
  import { createHash } from "crypto";
7
8
  var CacheService = class {
8
- isCacheEnvelope(value) {
9
- return typeof value === "object" && value !== null && "__pakento_cache_version" in value && "data" in value;
10
- }
11
- constructor(defaultTTL, apiKey) {
12
- this.defaultTTL = defaultTTL;
9
+ // 24 hours
10
+ constructor(apiKey) {
11
+ this.defaultTTL = 86400;
13
12
  this.apiKeyHash = createHash("sha256").update(apiKey).digest("hex").substring(0, 8);
14
13
  if (process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN) {
15
14
  this.redis = new Redis({
@@ -19,269 +18,51 @@ var CacheService = class {
19
18
  }
20
19
  }
21
20
  generateParamsHash(params) {
22
- const canonicalize = (value) => {
23
- if (value === void 0) return void 0;
24
- if (value === null) return null;
25
- if (Array.isArray(value)) {
26
- return value.map((v) => canonicalize(v));
27
- }
28
- if (typeof value === "object") {
29
- const obj = value;
30
- const result = {};
31
- Object.keys(obj).sort().forEach((key) => {
32
- const canon = canonicalize(obj[key]);
33
- if (canon !== void 0) {
34
- result[key] = canon;
35
- }
36
- });
37
- return result;
38
- }
39
- return value;
40
- };
41
- const canonicalParams = canonicalize(params);
42
- const paramsString = JSON.stringify(canonicalParams);
21
+ const paramsString = JSON.stringify(params, Object.keys(params).sort());
43
22
  return createHash("sha256").update(paramsString).digest("hex").substring(0, 16);
44
23
  }
45
24
  buildCacheKey(functionName, params = {}) {
46
25
  const paramsHash = this.generateParamsHash(params);
47
26
  return `pakento:${this.apiKeyHash}:${functionName}:${paramsHash}`;
48
27
  }
49
- safeJsonParse(data) {
50
- try {
51
- if (typeof data === "object" && data !== null) {
52
- return data;
53
- }
54
- if (typeof data === "string") {
55
- return JSON.parse(data);
56
- }
57
- return data;
58
- } catch (error) {
59
- console.warn("[PakentoSDK] Error en safeJsonParse:", error);
60
- console.warn("[PakentoSDK] Datos que causaron error:", {
61
- type: typeof data,
62
- isArray: Array.isArray(data),
63
- data
64
- });
65
- return null;
66
- }
67
- }
68
- serializeForCache(value) {
69
- try {
70
- const cacheData = {
71
- __pakento_cache_version: "2.0",
72
- __pakento_timestamp: Date.now(),
73
- data: value
74
- };
75
- return JSON.stringify(cacheData);
76
- } catch (error) {
77
- console.warn("[PakentoSDK] Error en serializeForCache:", error);
78
- return JSON.stringify(value);
79
- }
80
- }
81
- async getCachedOrFetch(key, fetcher, ttl, skipCache = false) {
82
- if (!this.redis || skipCache) {
28
+ async cacheWrap(key, fetcher) {
29
+ if (!this.redis) {
83
30
  return fetcher();
84
31
  }
32
+ let cached = null;
85
33
  try {
86
- const cached = await this.redis.get(key);
87
- if (cached !== null && cached !== void 0) {
88
- try {
89
- const parsed = this.safeJsonParse(cached);
90
- if (parsed !== null) {
91
- if (this.isCacheEnvelope(parsed)) {
92
- console.log("[PakentoSDK] Cache encontrado y devuelto");
93
- return parsed.data;
94
- } else {
95
- console.log("[PakentoSDK] Cache encontrado y devuelto");
96
- return parsed;
97
- }
98
- } else {
99
- console.warn(`[PakentoSDK] \u26A0\uFE0F Error parseando cache para: ${key}`);
100
- console.warn(`[PakentoSDK] Datos raw del cache:`, {
101
- type: typeof cached,
102
- value: cached
103
- });
104
- this.clearCorruptedCache(key).catch(
105
- (err) => console.warn(
106
- `[PakentoSDK] Error limpiando cache corrupto: ${err}`
107
- )
108
- );
109
- }
110
- } catch (parseError) {
111
- console.warn(
112
- `[PakentoSDK] \u26A0\uFE0F Excepci\xF3n parseando cache para: ${key}:`,
113
- parseError
114
- );
115
- this.clearCorruptedCache(key).catch(
116
- (err) => console.warn(`[PakentoSDK] Error limpiando cache corrupto: ${err}`)
117
- );
118
- }
34
+ cached = await this.redis.get(key);
35
+ if (typeof cached === "object" && cached !== null) {
36
+ console.log("[Cache] \u2705 Reading from cache:", key);
37
+ return cached;
38
+ }
39
+ if (cached) {
40
+ console.log("[Cache] \u2705 Reading from cache:", key);
41
+ return JSON.parse(cached);
119
42
  }
120
43
  } catch (err) {
121
- console.warn("[PakentoSDK] Error leyendo cache Redis", err);
44
+ console.warn("[Cache] \u274C Error reading from cache:", err);
45
+ console.log(`[Cache] \u274C Key: ${key}, type: ${typeof cached}`);
122
46
  }
123
47
  const result = await fetcher();
124
48
  try {
125
- const serializedData = this.serializeForCache(result);
126
- await this.redis.set(key, serializedData, {
127
- ex: ttl ?? this.defaultTTL
49
+ console.log("[Cache] \u2705 Writing to cache:", key);
50
+ await this.redis.set(key, JSON.stringify(result), {
51
+ ex: this.defaultTTL
128
52
  });
129
- console.log(
130
- "[PakentoSDK] Cache no encontrado, se guarda y se devuelve uno nuevo"
131
- );
132
53
  } catch (err) {
133
- console.warn("[PakentoSDK] Error escribiendo cache Redis", err);
134
- console.warn("[PakentoSDK] Detalles del error:", {
135
- error: err,
136
- key,
137
- resultType: typeof result,
138
- resultSize: JSON.stringify(result).length
139
- });
54
+ console.warn("[Cache] \u274C Error writing to cache:", err);
140
55
  }
141
56
  return result;
142
57
  }
143
- async hasCache(functionName, params = {}) {
144
- if (!this.redis) {
145
- console.warn("[PakentoSDK] Redis no configurado");
146
- return false;
147
- }
148
- try {
149
- const key = this.buildCacheKey(functionName, params);
150
- const cached = await this.redis.get(key);
151
- if (cached === null || cached === void 0) {
152
- return false;
153
- }
154
- const parsed = this.safeJsonParse(cached);
155
- return parsed !== null;
156
- } catch (err) {
157
- console.warn("[PakentoSDK] Error verificando cache", err);
158
- return false;
159
- }
160
- }
161
- /**
162
- * Limpia un cache específico si está corrupto
163
- */
164
- async clearCorruptedCache(key) {
165
- if (!this.redis) {
166
- return false;
167
- }
168
- try {
169
- await this.redis.del(key);
170
- return true;
171
- } catch (err) {
172
- console.warn("[PakentoSDK] Error limpiando cache corrupto", err);
173
- return false;
174
- }
175
- }
176
- getCacheKey(functionName, params = {}) {
177
- return this.buildCacheKey(functionName, params);
178
- }
179
- async clearCache(functionName, params = {}) {
180
- if (!this.redis) {
181
- console.warn("[PakentoSDK] Redis no configurado");
182
- return false;
183
- }
184
- try {
185
- const key = this.buildCacheKey(functionName, params);
186
- await this.redis.del(key);
187
- return true;
188
- } catch (err) {
189
- console.warn("[PakentoSDK] Error limpiando cache", err);
190
- return false;
191
- }
192
- }
193
- async clearAllCache() {
194
- if (!this.redis) {
195
- console.warn("[PakentoSDK] Redis no configurado");
196
- return false;
197
- }
198
- try {
199
- const pattern = `pakento:${this.apiKeyHash}:*`;
200
- const keys = await this.redis.keys(pattern);
201
- if (keys.length > 0) {
202
- await this.redis.del(...keys);
203
- }
204
- return true;
205
- } catch (err) {
206
- console.warn("[PakentoSDK] Error limpiando todo el cache", err);
207
- return false;
208
- }
209
- }
210
- async getCacheInfo(functionName, params = {}) {
211
- if (!this.redis) {
212
- console.warn("[PakentoSDK] Redis no configurado");
213
- return {
214
- exists: false,
215
- key: this.buildCacheKey(functionName, params)
216
- };
217
- }
218
- try {
219
- const key = this.buildCacheKey(functionName, params);
220
- const exists = await this.redis.exists(key);
221
- const ttl = exists ? await this.redis.ttl(key) : void 0;
222
- return {
223
- exists: exists === 1,
224
- key,
225
- ttl: ttl === -1 ? void 0 : ttl
226
- };
227
- } catch (err) {
228
- console.warn("[PakentoSDK] Error obteniendo info del cache", err);
229
- return {
230
- exists: false,
231
- key: this.buildCacheKey(functionName, params)
232
- };
233
- }
234
- }
235
58
  };
236
59
 
237
- // src/services/api.ts
238
- import { z } from "zod";
239
-
240
- // src/utils/itemParser.ts
241
- function parseRawItemToItem(rawItem) {
242
- const firstPrice = rawItem.item_prices.docs[0];
243
- const images = rawItem.images.map((img) => ({
244
- url: img.url,
245
- thumbnail_url: img.thumbnailURL
246
- }));
247
- const coverImageUrl = rawItem.coverImage?.url || rawItem.images[0]?.url || "";
248
- const coverImageThumbnailUrl = rawItem.coverImage?.thumbnailURL || rawItem.images[0]?.thumbnailURL || "";
249
- return {
250
- id: rawItem.id,
251
- name: rawItem.name,
252
- featured: rawItem.featured,
253
- url_safe_name: rawItem.url_safe_name,
254
- currency_prefix: "$",
255
- // Default currency prefix, could be made configurable
256
- description: rawItem.description,
257
- old_price: firstPrice?.old_price || 0,
258
- item_category_name: rawItem.item_category?.name || "",
259
- item_category_id: parseInt(rawItem.item_category?.id || "0"),
260
- price_text: firstPrice?.price_text || "",
261
- price_notes: firstPrice?.price_notes || "",
262
- // Not available in raw response
263
- price: firstPrice?.amount || 0,
264
- brand_id: parseInt(rawItem.brand?.id || "0"),
265
- brand_name: rawItem.brand?.name || "",
266
- cover_image_url: coverImageUrl,
267
- cover_image_thumbnail_url: coverImageThumbnailUrl,
268
- images
269
- };
270
- }
271
- function parseRawItemsToItems(rawItems) {
272
- return rawItems.map(parseRawItemToItem);
273
- }
274
-
275
- // src/services/api.ts
276
- var PakentoCMSAPI = class {
277
- constructor(config) {
278
- this.defaultTTL = 86400;
60
+ // src/api/core/apiClient.ts
61
+ var ApiClient = class {
62
+ constructor() {
279
63
  this.baseURL = process.env.PAKENTO_CMS_BASE_URL || "";
280
64
  this.apiKey = process.env.PAKENTO_API_KEY || "";
281
- if (config?.cacheTTL && typeof config.cacheTTL === "number") {
282
- this.defaultTTL = config.cacheTTL;
283
- }
284
- this.cache = new CacheService(this.defaultTTL, this.apiKey);
65
+ this.cache = new CacheService(this.apiKey);
285
66
  this.client = axios.create({
286
67
  baseURL: this.baseURL,
287
68
  headers: {
@@ -290,17 +71,14 @@ var PakentoCMSAPI = class {
290
71
  }
291
72
  });
292
73
  this.client.interceptors.request.use(
293
- (config2) => {
294
- const fullUrl = `${config2.baseURL}${config2.url}`;
295
- console.log(`\u{1F310} API Call: ${config2.method?.toUpperCase()} ${fullUrl}`);
296
- return config2;
74
+ (config) => {
75
+ const fullUrl = `${config.baseURL}${config.url}`;
76
+ console.log(`\u{1F310} API Call: ${config.method?.toUpperCase()} ${fullUrl}`);
77
+ return config;
297
78
  },
298
- (error) => {
299
- return Promise.reject(error);
300
- }
79
+ (error) => Promise.reject(error)
301
80
  );
302
81
  }
303
- // Centralized error handler
304
82
  handleApiError(error, context) {
305
83
  if (error instanceof AxiosError) {
306
84
  const status = error.response?.status;
@@ -316,7 +94,6 @@ var PakentoCMSAPI = class {
316
94
  }
317
95
  return "Error desconocido";
318
96
  }
319
- // Generic GraphQL fetcher
320
97
  async fetchGraphQL(query, variables, extractData) {
321
98
  try {
322
99
  const response = await this.client.post("/api/graphql", {
@@ -334,25 +111,64 @@ var PakentoCMSAPI = class {
334
111
  return { data: null, error: true, errorMessage };
335
112
  }
336
113
  }
114
+ };
115
+
116
+ // src/api/items/parsers.ts
117
+ function parseRawItemToItem(rawItem) {
118
+ const firstPrice = rawItem.item_prices.docs[0];
119
+ const images = rawItem.images.map((img) => ({
120
+ url: img.url,
121
+ thumbnail_url: img.thumbnailURL
122
+ }));
123
+ const coverImageUrl = rawItem.coverImage?.url || rawItem.images[0]?.url || "";
124
+ const coverImageThumbnailUrl = rawItem.coverImage?.thumbnailURL || rawItem.images[0]?.thumbnailURL || "";
125
+ return {
126
+ id: rawItem.id,
127
+ name: rawItem.name,
128
+ featured: rawItem.featured,
129
+ url_safe_name: rawItem.url_safe_name,
130
+ currency_prefix: "$",
131
+ // Default currency prefix, could be made configurable
132
+ description: rawItem.description,
133
+ old_price: firstPrice?.old_price || 0,
134
+ item_category_name: rawItem.item_category?.name || "",
135
+ item_category_id: parseInt(rawItem.item_category?.id || "0"),
136
+ price_text: firstPrice?.price_text || "",
137
+ price_notes: firstPrice?.price_notes || "",
138
+ price: firstPrice?.amount || 0,
139
+ brand_id: parseInt(rawItem.brand?.id || "0"),
140
+ brand_name: rawItem.brand?.name || "",
141
+ cover_image_url: coverImageUrl,
142
+ cover_image_thumbnail_url: coverImageThumbnailUrl,
143
+ images
144
+ };
145
+ }
146
+ function parseRawItemsToItems(rawItems) {
147
+ return rawItems.map(parseRawItemToItem);
148
+ }
149
+
150
+ // src/api/items/validators.ts
151
+ import { z as z2 } from "zod";
152
+ var itemsParamsSchema = z2.object({
153
+ where: z2.object({
154
+ item_category_id: z2.object({ equals: z2.string().optional() }).optional(),
155
+ item_super_category_id: z2.object({ equals: z2.string().optional() }).optional(),
156
+ brand_id: z2.object({ equals: z2.string().optional() }).optional(),
157
+ id: z2.object({ equals: z2.string().optional() }).optional()
158
+ }).optional(),
159
+ onlyOffers: z2.boolean().optional(),
160
+ limit: z2.coerce.number().optional(),
161
+ page: z2.coerce.number().optional(),
162
+ search: z2.string().optional(),
163
+ sort: z2.string().optional(),
164
+ minPrice: z2.coerce.number().optional(),
165
+ maxPrice: z2.coerce.number().optional()
166
+ });
167
+
168
+ // src/api/items/api.ts
169
+ var ItemsApi = class extends ApiClient {
337
170
  async getItems(params = {}) {
338
- const itemsSchema = z.object({
339
- where: z.object({
340
- item_category_id: z.object({ equals: z.string().optional() }).optional(),
341
- item_super_category_id: z.object({ equals: z.string().optional() }).optional(),
342
- brand_id: z.object({ equals: z.string().optional() }).optional(),
343
- id: z.object({ equals: z.string().optional() }).optional()
344
- }).optional(),
345
- onlyOffers: z.boolean().optional(),
346
- limit: z.coerce.number().optional(),
347
- page: z.coerce.number().optional(),
348
- search: z.string().optional(),
349
- sort: z.string().optional(),
350
- minPrice: z.coerce.number().optional(),
351
- maxPrice: z.coerce.number().optional(),
352
- skipCache: z.boolean().optional(),
353
- cacheTTL: z.number().optional()
354
- });
355
- const validatedParams = itemsSchema.safeParse(params);
171
+ const validatedParams = itemsParamsSchema.safeParse(params);
356
172
  if (!validatedParams.success) {
357
173
  const errorMessage = this.handleApiError(
358
174
  validatedParams.error,
@@ -368,25 +184,16 @@ var PakentoCMSAPI = class {
368
184
  errorMessage
369
185
  };
370
186
  }
371
- const { skipCache = false, cacheTTL, ...rest } = validatedParams.data;
372
- const cacheKey = this.cache.buildCacheKey("GetEcommerceItems", rest);
373
- const finalData = await this.cache.getCachedOrFetch(
187
+ const cacheKey = this.cache.buildCacheKey(
188
+ "GetEcommerceItems",
189
+ validatedParams.data
190
+ );
191
+ return this.cache.cacheWrap(
374
192
  cacheKey,
375
- () => this.fetchItemsFromAPI(rest),
376
- cacheTTL,
377
- skipCache
193
+ () => this.fetchItemsFromAPI(validatedParams.data)
378
194
  );
379
- return {
380
- data: finalData.data,
381
- totalDocs: finalData.totalDocs,
382
- totalPages: finalData.totalPages,
383
- prevPage: finalData.prevPage,
384
- nextPage: finalData.nextPage,
385
- error: false,
386
- errorMessage: null
387
- };
388
195
  }
389
- async fetchItemsFromAPI(params = {}) {
196
+ async fetchItemsFromAPI(params) {
390
197
  if (!this.baseURL || !this.apiKey) {
391
198
  return {
392
199
  data: null,
@@ -504,21 +311,42 @@ var PakentoCMSAPI = class {
504
311
  errorMessage: null
505
312
  };
506
313
  }
314
+ };
315
+ var itemsApi = new ItemsApi();
316
+
317
+ // src/api/categories/validators.ts
318
+ import { z as z3 } from "zod";
319
+ var categoriesParamsSchema = z3.object({
320
+ where: z3.object({
321
+ item_super_category_id: z3.object({ equals: z3.string().optional() }).optional(),
322
+ brand_id: z3.object({ equals: z3.string().optional() }).optional()
323
+ }).optional(),
324
+ limit: z3.coerce.number().optional(),
325
+ page: z3.coerce.number().optional(),
326
+ sort: z3.string().optional()
327
+ });
328
+
329
+ // src/api/categories/api.ts
330
+ var CategoriesApi = class extends ApiClient {
507
331
  async getCategories(params = {}) {
508
- const {
509
- skipCache = false,
510
- cacheTTL,
511
- ...rest
512
- } = params;
513
- const cacheKey = this.cache.buildCacheKey("GetEcommerceCategories", rest);
514
- return this.cache.getCachedOrFetch(
332
+ const validatedParams = categoriesParamsSchema.safeParse(params);
333
+ if (!validatedParams.success) {
334
+ const errorMessage = this.handleApiError(
335
+ validatedParams.error,
336
+ "getCategories validation"
337
+ );
338
+ return { data: null, categories: [], error: true, errorMessage };
339
+ }
340
+ const cacheKey = this.cache.buildCacheKey(
341
+ "GetEcommerceCategories",
342
+ validatedParams.data
343
+ );
344
+ return this.cache.cacheWrap(
515
345
  cacheKey,
516
- () => this.fetchCategoriesFromAPI(rest),
517
- cacheTTL,
518
- skipCache
346
+ () => this.fetchCategoriesFromAPI(validatedParams.data)
519
347
  );
520
348
  }
521
- async fetchCategoriesFromAPI(params = {}) {
349
+ async fetchCategoriesFromAPI(params) {
522
350
  if (!this.baseURL || !this.apiKey) {
523
351
  return {
524
352
  data: null,
@@ -554,12 +382,7 @@ var PakentoCMSAPI = class {
554
382
  (responseData) => responseData.GetEcommerceCategories
555
383
  );
556
384
  if (error) {
557
- return {
558
- data: null,
559
- categories: [],
560
- error: true,
561
- errorMessage
562
- };
385
+ return { data: null, categories: [], error: true, errorMessage };
563
386
  }
564
387
  return {
565
388
  data: data.docs,
@@ -568,17 +391,53 @@ var PakentoCMSAPI = class {
568
391
  errorMessage: null
569
392
  };
570
393
  }
394
+ };
395
+ var categoriesApi = new CategoriesApi();
396
+
397
+ // src/api/brands/validators.ts
398
+ import { z as z4 } from "zod";
399
+ var brandsParamsSchema = z4.object({
400
+ limit: z4.coerce.number().optional(),
401
+ page: z4.coerce.number().optional(),
402
+ sort: z4.string().optional()
403
+ });
404
+
405
+ // src/api/brands/api.ts
406
+ var BrandsApi = class extends ApiClient {
571
407
  async getBrands(params = {}) {
572
- const { skipCache = false, cacheTTL, ...rest } = params;
573
- const cacheKey = this.cache.buildCacheKey("GetEcommerceBrands", rest);
574
- return this.cache.getCachedOrFetch(
408
+ const validatedParams = brandsParamsSchema.safeParse(params);
409
+ if (!validatedParams.success) {
410
+ const errorMessage = this.handleApiError(
411
+ validatedParams.error,
412
+ "getBrands validation"
413
+ );
414
+ return {
415
+ data: null,
416
+ brands: [],
417
+ hasNextPage: false,
418
+ hasPrevPage: false,
419
+ limit: 0,
420
+ nextPage: 0,
421
+ offset: 0,
422
+ page: 0,
423
+ pagingCounter: 0,
424
+ prevPage: 0,
425
+ totalDocs: 0,
426
+ totalPages: 0,
427
+ error: true,
428
+ errorMessage
429
+ };
430
+ }
431
+ const cacheKey = this.cache.buildCacheKey(
432
+ "GetEcommerceBrands",
433
+ validatedParams.data
434
+ );
435
+ return this.cache.cacheWrap(
575
436
  cacheKey,
576
- () => this.fetchBrandsFromAPI(rest),
577
- cacheTTL,
578
- skipCache
437
+ () => this.fetchBrandsFromAPI(validatedParams.data)
579
438
  );
580
439
  }
581
- async fetchBrandsFromAPI(params = {}) {
440
+ async fetchBrandsFromAPI(params) {
582
441
  if (!this.baseURL || !this.apiKey) {
583
442
  return {
584
443
  data: null,
@@ -670,17 +529,19 @@ var PakentoCMSAPI = class {
670
529
  errorMessage: null
671
530
  };
672
531
  }
532
+ };
533
+ var brandsApi = new BrandsApi();
534
+
535
+ // src/api/entity/api.ts
536
+ var EntityApi = class extends ApiClient {
673
537
  async getEntity(params = {}) {
674
- const { skipCache = false, cacheTTL, ...rest } = params;
675
- const cacheKey = this.cache.buildCacheKey("GetEntity", rest);
676
- return this.cache.getCachedOrFetch(
538
+ const cacheKey = this.cache.buildCacheKey("GetEntity", params);
539
+ return this.cache.cacheWrap(
677
540
  cacheKey,
678
- () => this.fetchEntityFromAPI(rest),
679
- cacheTTL,
680
- skipCache
541
+ () => this.fetchEntityFromAPI(params)
681
542
  );
682
543
  }
683
- async fetchEntityFromAPI(params = {}) {
544
+ async fetchEntityFromAPI(params) {
684
545
  if (!this.baseURL || !this.apiKey) {
685
546
  return {
686
547
  data: null,
@@ -730,23 +591,39 @@ var PakentoCMSAPI = class {
730
591
  const { data, error, errorMessage } = await this.fetchGraphQL(
731
592
  query,
732
593
  params,
733
- (responseData) => responseData.GetEntity
594
+ (responseData) => responseData
734
595
  );
735
596
  if (error) {
736
- return {
737
- data: null,
738
- entity: null,
739
- error: true,
740
- errorMessage
741
- };
597
+ return { data: null, entity: null, error: true, errorMessage };
742
598
  }
743
599
  return {
744
- data,
745
- entity: data,
600
+ data: data.GetEntity,
601
+ entity: data.GetEntity,
746
602
  error: false,
747
603
  errorMessage: null
748
604
  };
749
605
  }
606
+ };
607
+ var entityApi = new EntityApi();
608
+
609
+ // src/api/orders/validators.ts
610
+ import { z as z5 } from "zod";
611
+ var orderSchema = z5.object({
612
+ name: z5.string().min(1),
613
+ email: z5.string().email(),
614
+ phone: z5.string().optional(),
615
+ notes: z5.string().optional(),
616
+ tin: z5.string().optional(),
617
+ items: z5.array(
618
+ z5.object({ id: z5.number().positive(), quantity: z5.number().positive() })
619
+ ).min(1),
620
+ delivery_address: z5.string().optional(),
621
+ delivery_instructions: z5.string().optional(),
622
+ payment_method: z5.enum(["cash", "transfer"]).optional()
623
+ });
624
+
625
+ // src/api/orders/api.ts
626
+ var OrdersApi = class extends ApiClient {
750
627
  async createEcommerceOrder(params) {
751
628
  if (!this.baseURL || !this.apiKey) {
752
629
  return {
@@ -755,22 +632,6 @@ var PakentoCMSAPI = class {
755
632
  errorMessage: "SDK no configurado"
756
633
  };
757
634
  }
758
- const orderSchema = z.object({
759
- name: z.string().min(1),
760
- email: z.string().email(),
761
- phone: z.string().optional(),
762
- notes: z.string().optional(),
763
- tin: z.string().optional(),
764
- items: z.array(
765
- z.object({
766
- id: z.number().positive(),
767
- quantity: z.number().positive()
768
- })
769
- ).min(1),
770
- delivery_address: z.string().optional(),
771
- delivery_instructions: z.string().optional(),
772
- payment_method: z.enum(["cash", "transfer"]).optional()
773
- });
774
635
  const validated = orderSchema.safeParse(params);
775
636
  if (!validated.success) {
776
637
  const errorMessage = this.handleApiError(
@@ -800,6 +661,62 @@ var PakentoCMSAPI = class {
800
661
  return { message: errorMessage, error: true, errorMessage };
801
662
  }
802
663
  }
664
+ };
665
+ var ordersApi = new OrdersApi();
666
+
667
+ // src/api/contact/validators.ts
668
+ import { z as z6 } from "zod";
669
+ var contactUsSchema = z6.object({
670
+ name: z6.string().min(1),
671
+ email: z6.string().email(),
672
+ phone: z6.string().optional(),
673
+ subject: z6.string().optional(),
674
+ notes: z6.string().min(1)
675
+ });
676
+
677
+ // src/api/contact/api.ts
678
+ var ContactApi = class extends ApiClient {
679
+ async sendContactUsEmail(params) {
680
+ if (!this.baseURL || !this.apiKey) {
681
+ return {
682
+ message: "SDK no configurado",
683
+ error: true,
684
+ errorMessage: "SDK no configurado"
685
+ };
686
+ }
687
+ const validated = contactUsSchema.safeParse(params);
688
+ if (!validated.success) {
689
+ const errorMessage = this.handleApiError(
690
+ validated.error,
691
+ "sendContactUsEmail validation"
692
+ );
693
+ return { message: errorMessage, error: true, errorMessage };
694
+ }
695
+ try {
696
+ const response = await this.client.post(
697
+ "/api/entities/send-contact-us-email",
698
+ validated.data
699
+ );
700
+ if (response.status === 200) {
701
+ return {
702
+ message: response.data.message || "Mensaje enviado exitosamente",
703
+ error: false,
704
+ errorMessage: null
705
+ };
706
+ } else {
707
+ const errorMessage = response.data.message || "Error al enviar el mensaje";
708
+ return { message: errorMessage, error: true, errorMessage };
709
+ }
710
+ } catch (error) {
711
+ const errorMessage = this.handleApiError(error, "sendContactUsEmail");
712
+ return { message: errorMessage, error: true, errorMessage };
713
+ }
714
+ }
715
+ };
716
+ var contactApi = new ContactApi();
717
+
718
+ // src/api/custom/api.ts
719
+ var CustomApi = class extends ApiClient {
803
720
  async executeCustomQuery(params) {
804
721
  if (!this.baseURL || !this.apiKey) {
805
722
  return {
@@ -834,116 +751,20 @@ var PakentoCMSAPI = class {
834
751
  errorMessage: null
835
752
  };
836
753
  } catch (error) {
837
- let errorMessage = "Error desconocido";
838
- if (error instanceof AxiosError) {
839
- const status = error.response?.status;
840
- if (status === 401) {
841
- errorMessage = "API Key inv\xE1lida o expirada";
842
- } else if (status === 404) {
843
- errorMessage = "Endpoint GraphQL no encontrado";
844
- } else if (status === 400) {
845
- errorMessage = "Query GraphQL inv\xE1lido o malformado";
846
- } else if (status && status >= 500) {
847
- errorMessage = "Error del servidor CMS";
848
- } else {
849
- errorMessage = `Error de conexi\xF3n: ${error.message}`;
850
- }
851
- } else if (error instanceof Error) {
852
- errorMessage = error.message;
853
- }
854
- return {
855
- data: null,
856
- error: true,
857
- errorMessage
858
- };
859
- }
860
- }
861
- async sendContactUsEmail(params) {
862
- if (!this.baseURL || !this.apiKey) {
863
- return {
864
- message: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes.",
865
- error: true,
866
- errorMessage: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes."
867
- };
868
- }
869
- const contactUsSchema = z.object({
870
- name: z.string().min(1),
871
- email: z.email(),
872
- phone: z.string().optional(),
873
- subject: z.string().optional(),
874
- message: z.string().min(1)
875
- });
876
- const validated = contactUsSchema.safeParse(params);
877
- if (!validated.success) {
878
- const errorMessage = this.handleApiError(
879
- validated.error,
880
- "sendContactUsEmail validation"
881
- );
882
- return { message: errorMessage, error: true, errorMessage };
883
- }
884
- try {
885
- const response = await this.client.post(
886
- "/api/entities/send-contact-us-email",
887
- validated.data
888
- );
889
- if (response.status === 200) {
890
- return {
891
- message: response.data.message || "Mensaje enviado exitosamente",
892
- error: false,
893
- errorMessage: null
894
- };
895
- } else {
896
- const errorMessage = response.data.message || "Error al enviar el mensaje";
897
- return { message: errorMessage, error: true, errorMessage };
898
- }
899
- } catch (error) {
900
- const errorMessage = this.handleApiError(error, "sendContactUsEmail");
901
- return { message: errorMessage, error: true, errorMessage };
754
+ const errorMessage = this.handleApiError(error, "Custom GraphQL");
755
+ return { data: null, error: true, errorMessage };
902
756
  }
903
757
  }
904
- /**
905
- * Verifica si existe cache para una función y parámetros específicos
906
- */
907
- async hasCache(functionName, params = {}) {
908
- return this.cache.hasCache(functionName, params);
909
- }
910
- /**
911
- * Obtiene la key de cache para una función y parámetros específicos
912
- */
913
- getCacheKey(functionName, params = {}) {
914
- return this.cache.getCacheKey(functionName, params);
915
- }
916
- /**
917
- * Limpia el cache para una función y parámetros específicos
918
- */
919
- async clearCache(functionName, params = {}) {
920
- return this.cache.clearCache(functionName, params);
921
- }
922
- /**
923
- * Limpia todo el cache relacionado con este API Key
924
- */
925
- async clearAllCache() {
926
- return this.cache.clearAllCache();
927
- }
928
- /**
929
- * Obtiene información del cache (útil para debugging)
930
- */
931
- async getCacheInfo(functionName, params = {}) {
932
- return this.cache.getCacheInfo(functionName, params);
933
- }
934
- /**
935
- * Limpia un cache específico que pueda estar corrupto
936
- */
937
- async clearCorruptedCache(functionName, params = {}) {
938
- const key = this.cache.getCacheKey(functionName, params);
939
- return this.cache.clearCorruptedCache(key);
940
- }
941
758
  };
942
- var pakentoCMSAPI = new PakentoCMSAPI();
759
+ var customApi = new CustomApi();
943
760
  export {
944
- CacheService,
945
- pakentoCMSAPI,
946
- parseRawItemToItem,
947
- parseRawItemsToItems
761
+ ApiClient,
762
+ brandsApi,
763
+ categoriesApi,
764
+ contactApi,
765
+ customApi,
766
+ entityApi,
767
+ itemsApi,
768
+ ordersApi
948
769
  };
949
770
  //# sourceMappingURL=index.mjs.map