@pakento/cms-sdk 4.3.0 → 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.js CHANGED
@@ -30,25 +30,28 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
- CacheService: () => CacheService,
34
- pakentoCMSAPI: () => pakentoCMSAPI,
35
- parseRawItemToItem: () => parseRawItemToItem,
36
- parseRawItemsToItems: () => parseRawItemsToItems
33
+ ApiClient: () => ApiClient,
34
+ brandsApi: () => brandsApi,
35
+ categoriesApi: () => categoriesApi,
36
+ contactApi: () => contactApi,
37
+ customApi: () => customApi,
38
+ entityApi: () => entityApi,
39
+ itemsApi: () => itemsApi,
40
+ ordersApi: () => ordersApi
37
41
  });
38
42
  module.exports = __toCommonJS(index_exports);
39
43
 
40
- // src/services/api.ts
44
+ // src/api/core/apiClient.ts
41
45
  var import_axios = __toESM(require("axios"));
46
+ var import_zod = require("zod");
42
47
 
43
- // src/services/cache.ts
48
+ // src/api/core/cache.ts
44
49
  var import_redis = require("@upstash/redis");
45
50
  var import_crypto = require("crypto");
46
51
  var CacheService = class {
47
- isCacheEnvelope(value) {
48
- return typeof value === "object" && value !== null && "__pakento_cache_version" in value && "data" in value;
49
- }
50
- constructor(defaultTTL, apiKey) {
51
- this.defaultTTL = defaultTTL;
52
+ // 24 hours
53
+ constructor(apiKey) {
54
+ this.defaultTTL = 86400;
52
55
  this.apiKeyHash = (0, import_crypto.createHash)("sha256").update(apiKey).digest("hex").substring(0, 8);
53
56
  if (process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN) {
54
57
  this.redis = new import_redis.Redis({
@@ -58,269 +61,51 @@ var CacheService = class {
58
61
  }
59
62
  }
60
63
  generateParamsHash(params) {
61
- const canonicalize = (value) => {
62
- if (value === void 0) return void 0;
63
- if (value === null) return null;
64
- if (Array.isArray(value)) {
65
- return value.map((v) => canonicalize(v));
66
- }
67
- if (typeof value === "object") {
68
- const obj = value;
69
- const result = {};
70
- Object.keys(obj).sort().forEach((key) => {
71
- const canon = canonicalize(obj[key]);
72
- if (canon !== void 0) {
73
- result[key] = canon;
74
- }
75
- });
76
- return result;
77
- }
78
- return value;
79
- };
80
- const canonicalParams = canonicalize(params);
81
- const paramsString = JSON.stringify(canonicalParams);
64
+ const paramsString = JSON.stringify(params, Object.keys(params).sort());
82
65
  return (0, import_crypto.createHash)("sha256").update(paramsString).digest("hex").substring(0, 16);
83
66
  }
84
67
  buildCacheKey(functionName, params = {}) {
85
68
  const paramsHash = this.generateParamsHash(params);
86
69
  return `pakento:${this.apiKeyHash}:${functionName}:${paramsHash}`;
87
70
  }
88
- safeJsonParse(data) {
89
- try {
90
- if (typeof data === "object" && data !== null) {
91
- return data;
92
- }
93
- if (typeof data === "string") {
94
- return JSON.parse(data);
95
- }
96
- return data;
97
- } catch (error) {
98
- console.warn("[PakentoSDK] Error en safeJsonParse:", error);
99
- console.warn("[PakentoSDK] Datos que causaron error:", {
100
- type: typeof data,
101
- isArray: Array.isArray(data),
102
- data
103
- });
104
- return null;
105
- }
106
- }
107
- serializeForCache(value) {
108
- try {
109
- const cacheData = {
110
- __pakento_cache_version: "2.0",
111
- __pakento_timestamp: Date.now(),
112
- data: value
113
- };
114
- return JSON.stringify(cacheData);
115
- } catch (error) {
116
- console.warn("[PakentoSDK] Error en serializeForCache:", error);
117
- return JSON.stringify(value);
118
- }
119
- }
120
- async getCachedOrFetch(key, fetcher, ttl, skipCache = false) {
121
- if (!this.redis || skipCache) {
71
+ async cacheWrap(key, fetcher) {
72
+ if (!this.redis) {
122
73
  return fetcher();
123
74
  }
75
+ let cached = null;
124
76
  try {
125
- const cached = await this.redis.get(key);
126
- if (cached !== null && cached !== void 0) {
127
- try {
128
- const parsed = this.safeJsonParse(cached);
129
- if (parsed !== null) {
130
- if (this.isCacheEnvelope(parsed)) {
131
- console.log("[PakentoSDK] Cache encontrado y devuelto");
132
- return parsed.data;
133
- } else {
134
- console.log("[PakentoSDK] Cache encontrado y devuelto");
135
- return parsed;
136
- }
137
- } else {
138
- console.warn(`[PakentoSDK] \u26A0\uFE0F Error parseando cache para: ${key}`);
139
- console.warn(`[PakentoSDK] Datos raw del cache:`, {
140
- type: typeof cached,
141
- value: cached
142
- });
143
- this.clearCorruptedCache(key).catch(
144
- (err) => console.warn(
145
- `[PakentoSDK] Error limpiando cache corrupto: ${err}`
146
- )
147
- );
148
- }
149
- } catch (parseError) {
150
- console.warn(
151
- `[PakentoSDK] \u26A0\uFE0F Excepci\xF3n parseando cache para: ${key}:`,
152
- parseError
153
- );
154
- this.clearCorruptedCache(key).catch(
155
- (err) => console.warn(`[PakentoSDK] Error limpiando cache corrupto: ${err}`)
156
- );
157
- }
77
+ cached = await this.redis.get(key);
78
+ if (typeof cached === "object" && cached !== null) {
79
+ console.log("[Cache] \u2705 Reading from cache:", key);
80
+ return cached;
81
+ }
82
+ if (cached) {
83
+ console.log("[Cache] \u2705 Reading from cache:", key);
84
+ return JSON.parse(cached);
158
85
  }
159
86
  } catch (err) {
160
- console.warn("[PakentoSDK] Error leyendo cache Redis", err);
87
+ console.warn("[Cache] \u274C Error reading from cache:", err);
88
+ console.log(`[Cache] \u274C Key: ${key}, type: ${typeof cached}`);
161
89
  }
162
90
  const result = await fetcher();
163
91
  try {
164
- const serializedData = this.serializeForCache(result);
165
- await this.redis.set(key, serializedData, {
166
- ex: ttl ?? this.defaultTTL
92
+ console.log("[Cache] \u2705 Writing to cache:", key);
93
+ await this.redis.set(key, JSON.stringify(result), {
94
+ ex: this.defaultTTL
167
95
  });
168
- console.log(
169
- "[PakentoSDK] Cache no encontrado, se guarda y se devuelve uno nuevo"
170
- );
171
96
  } catch (err) {
172
- console.warn("[PakentoSDK] Error escribiendo cache Redis", err);
173
- console.warn("[PakentoSDK] Detalles del error:", {
174
- error: err,
175
- key,
176
- resultType: typeof result,
177
- resultSize: JSON.stringify(result).length
178
- });
97
+ console.warn("[Cache] \u274C Error writing to cache:", err);
179
98
  }
180
99
  return result;
181
100
  }
182
- async hasCache(functionName, params = {}) {
183
- if (!this.redis) {
184
- console.warn("[PakentoSDK] Redis no configurado");
185
- return false;
186
- }
187
- try {
188
- const key = this.buildCacheKey(functionName, params);
189
- const cached = await this.redis.get(key);
190
- if (cached === null || cached === void 0) {
191
- return false;
192
- }
193
- const parsed = this.safeJsonParse(cached);
194
- return parsed !== null;
195
- } catch (err) {
196
- console.warn("[PakentoSDK] Error verificando cache", err);
197
- return false;
198
- }
199
- }
200
- /**
201
- * Limpia un cache específico si está corrupto
202
- */
203
- async clearCorruptedCache(key) {
204
- if (!this.redis) {
205
- return false;
206
- }
207
- try {
208
- await this.redis.del(key);
209
- return true;
210
- } catch (err) {
211
- console.warn("[PakentoSDK] Error limpiando cache corrupto", err);
212
- return false;
213
- }
214
- }
215
- getCacheKey(functionName, params = {}) {
216
- return this.buildCacheKey(functionName, params);
217
- }
218
- async clearCache(functionName, params = {}) {
219
- if (!this.redis) {
220
- console.warn("[PakentoSDK] Redis no configurado");
221
- return false;
222
- }
223
- try {
224
- const key = this.buildCacheKey(functionName, params);
225
- await this.redis.del(key);
226
- return true;
227
- } catch (err) {
228
- console.warn("[PakentoSDK] Error limpiando cache", err);
229
- return false;
230
- }
231
- }
232
- async clearAllCache() {
233
- if (!this.redis) {
234
- console.warn("[PakentoSDK] Redis no configurado");
235
- return false;
236
- }
237
- try {
238
- const pattern = `pakento:${this.apiKeyHash}:*`;
239
- const keys = await this.redis.keys(pattern);
240
- if (keys.length > 0) {
241
- await this.redis.del(...keys);
242
- }
243
- return true;
244
- } catch (err) {
245
- console.warn("[PakentoSDK] Error limpiando todo el cache", err);
246
- return false;
247
- }
248
- }
249
- async getCacheInfo(functionName, params = {}) {
250
- if (!this.redis) {
251
- console.warn("[PakentoSDK] Redis no configurado");
252
- return {
253
- exists: false,
254
- key: this.buildCacheKey(functionName, params)
255
- };
256
- }
257
- try {
258
- const key = this.buildCacheKey(functionName, params);
259
- const exists = await this.redis.exists(key);
260
- const ttl = exists ? await this.redis.ttl(key) : void 0;
261
- return {
262
- exists: exists === 1,
263
- key,
264
- ttl: ttl === -1 ? void 0 : ttl
265
- };
266
- } catch (err) {
267
- console.warn("[PakentoSDK] Error obteniendo info del cache", err);
268
- return {
269
- exists: false,
270
- key: this.buildCacheKey(functionName, params)
271
- };
272
- }
273
- }
274
101
  };
275
102
 
276
- // src/services/api.ts
277
- var import_zod = require("zod");
278
-
279
- // src/utils/itemParser.ts
280
- function parseRawItemToItem(rawItem) {
281
- const firstPrice = rawItem.item_prices.docs[0];
282
- const images = rawItem.images.map((img) => ({
283
- url: img.url,
284
- thumbnail_url: img.thumbnailURL
285
- }));
286
- const coverImageUrl = rawItem.coverImage?.url || rawItem.images[0]?.url || "";
287
- const coverImageThumbnailUrl = rawItem.coverImage?.thumbnailURL || rawItem.images[0]?.thumbnailURL || "";
288
- return {
289
- id: rawItem.id,
290
- name: rawItem.name,
291
- featured: rawItem.featured,
292
- url_safe_name: rawItem.url_safe_name,
293
- currency_prefix: "$",
294
- // Default currency prefix, could be made configurable
295
- description: rawItem.description,
296
- old_price: firstPrice?.old_price || 0,
297
- item_category_name: rawItem.item_category?.name || "",
298
- item_category_id: parseInt(rawItem.item_category?.id || "0"),
299
- price_text: firstPrice?.price_text || "",
300
- price_notes: firstPrice?.price_notes || "",
301
- // Not available in raw response
302
- price: firstPrice?.amount || 0,
303
- brand_id: parseInt(rawItem.brand?.id || "0"),
304
- brand_name: rawItem.brand?.name || "",
305
- cover_image_url: coverImageUrl,
306
- cover_image_thumbnail_url: coverImageThumbnailUrl,
307
- images
308
- };
309
- }
310
- function parseRawItemsToItems(rawItems) {
311
- return rawItems.map(parseRawItemToItem);
312
- }
313
-
314
- // src/services/api.ts
315
- var PakentoCMSAPI = class {
316
- constructor(config) {
317
- this.defaultTTL = 86400;
103
+ // src/api/core/apiClient.ts
104
+ var ApiClient = class {
105
+ constructor() {
318
106
  this.baseURL = process.env.PAKENTO_CMS_BASE_URL || "";
319
107
  this.apiKey = process.env.PAKENTO_API_KEY || "";
320
- if (config?.cacheTTL && typeof config.cacheTTL === "number") {
321
- this.defaultTTL = config.cacheTTL;
322
- }
323
- this.cache = new CacheService(this.defaultTTL, this.apiKey);
108
+ this.cache = new CacheService(this.apiKey);
324
109
  this.client = import_axios.default.create({
325
110
  baseURL: this.baseURL,
326
111
  headers: {
@@ -329,17 +114,14 @@ var PakentoCMSAPI = class {
329
114
  }
330
115
  });
331
116
  this.client.interceptors.request.use(
332
- (config2) => {
333
- const fullUrl = `${config2.baseURL}${config2.url}`;
334
- console.log(`\u{1F310} API Call: ${config2.method?.toUpperCase()} ${fullUrl}`);
335
- return config2;
117
+ (config) => {
118
+ const fullUrl = `${config.baseURL}${config.url}`;
119
+ console.log(`\u{1F310} API Call: ${config.method?.toUpperCase()} ${fullUrl}`);
120
+ return config;
336
121
  },
337
- (error) => {
338
- return Promise.reject(error);
339
- }
122
+ (error) => Promise.reject(error)
340
123
  );
341
124
  }
342
- // Centralized error handler
343
125
  handleApiError(error, context) {
344
126
  if (error instanceof import_axios.AxiosError) {
345
127
  const status = error.response?.status;
@@ -355,7 +137,6 @@ var PakentoCMSAPI = class {
355
137
  }
356
138
  return "Error desconocido";
357
139
  }
358
- // Generic GraphQL fetcher
359
140
  async fetchGraphQL(query, variables, extractData) {
360
141
  try {
361
142
  const response = await this.client.post("/api/graphql", {
@@ -373,25 +154,64 @@ var PakentoCMSAPI = class {
373
154
  return { data: null, error: true, errorMessage };
374
155
  }
375
156
  }
157
+ };
158
+
159
+ // src/api/items/parsers.ts
160
+ function parseRawItemToItem(rawItem) {
161
+ const firstPrice = rawItem.item_prices.docs[0];
162
+ const images = rawItem.images.map((img) => ({
163
+ url: img.url,
164
+ thumbnail_url: img.thumbnailURL
165
+ }));
166
+ const coverImageUrl = rawItem.coverImage?.url || rawItem.images[0]?.url || "";
167
+ const coverImageThumbnailUrl = rawItem.coverImage?.thumbnailURL || rawItem.images[0]?.thumbnailURL || "";
168
+ return {
169
+ id: rawItem.id,
170
+ name: rawItem.name,
171
+ featured: rawItem.featured,
172
+ url_safe_name: rawItem.url_safe_name,
173
+ currency_prefix: "$",
174
+ // Default currency prefix, could be made configurable
175
+ description: rawItem.description,
176
+ old_price: firstPrice?.old_price || 0,
177
+ item_category_name: rawItem.item_category?.name || "",
178
+ item_category_id: parseInt(rawItem.item_category?.id || "0"),
179
+ price_text: firstPrice?.price_text || "",
180
+ price_notes: firstPrice?.price_notes || "",
181
+ price: firstPrice?.amount || 0,
182
+ brand_id: parseInt(rawItem.brand?.id || "0"),
183
+ brand_name: rawItem.brand?.name || "",
184
+ cover_image_url: coverImageUrl,
185
+ cover_image_thumbnail_url: coverImageThumbnailUrl,
186
+ images
187
+ };
188
+ }
189
+ function parseRawItemsToItems(rawItems) {
190
+ return rawItems.map(parseRawItemToItem);
191
+ }
192
+
193
+ // src/api/items/validators.ts
194
+ var import_zod2 = require("zod");
195
+ var itemsParamsSchema = import_zod2.z.object({
196
+ where: import_zod2.z.object({
197
+ item_category_id: import_zod2.z.object({ equals: import_zod2.z.string().optional() }).optional(),
198
+ item_super_category_id: import_zod2.z.object({ equals: import_zod2.z.string().optional() }).optional(),
199
+ brand_id: import_zod2.z.object({ equals: import_zod2.z.string().optional() }).optional(),
200
+ id: import_zod2.z.object({ equals: import_zod2.z.string().optional() }).optional()
201
+ }).optional(),
202
+ onlyOffers: import_zod2.z.boolean().optional(),
203
+ limit: import_zod2.z.coerce.number().optional(),
204
+ page: import_zod2.z.coerce.number().optional(),
205
+ search: import_zod2.z.string().optional(),
206
+ sort: import_zod2.z.string().optional(),
207
+ minPrice: import_zod2.z.coerce.number().optional(),
208
+ maxPrice: import_zod2.z.coerce.number().optional()
209
+ });
210
+
211
+ // src/api/items/api.ts
212
+ var ItemsApi = class extends ApiClient {
376
213
  async getItems(params = {}) {
377
- const itemsSchema = import_zod.z.object({
378
- where: import_zod.z.object({
379
- item_category_id: import_zod.z.object({ equals: import_zod.z.string().optional() }).optional(),
380
- item_super_category_id: import_zod.z.object({ equals: import_zod.z.string().optional() }).optional(),
381
- brand_id: import_zod.z.object({ equals: import_zod.z.string().optional() }).optional(),
382
- id: import_zod.z.object({ equals: import_zod.z.string().optional() }).optional()
383
- }).optional(),
384
- onlyOffers: import_zod.z.boolean().optional(),
385
- limit: import_zod.z.coerce.number().optional(),
386
- page: import_zod.z.coerce.number().optional(),
387
- search: import_zod.z.string().optional(),
388
- sort: import_zod.z.string().optional(),
389
- minPrice: import_zod.z.coerce.number().optional(),
390
- maxPrice: import_zod.z.coerce.number().optional(),
391
- skipCache: import_zod.z.boolean().optional(),
392
- cacheTTL: import_zod.z.number().optional()
393
- });
394
- const validatedParams = itemsSchema.safeParse(params);
214
+ const validatedParams = itemsParamsSchema.safeParse(params);
395
215
  if (!validatedParams.success) {
396
216
  const errorMessage = this.handleApiError(
397
217
  validatedParams.error,
@@ -399,7 +219,6 @@ var PakentoCMSAPI = class {
399
219
  );
400
220
  return {
401
221
  data: null,
402
- items: [],
403
222
  totalDocs: 0,
404
223
  totalPages: 0,
405
224
  prevPage: null,
@@ -408,20 +227,19 @@ var PakentoCMSAPI = class {
408
227
  errorMessage
409
228
  };
410
229
  }
411
- const { skipCache = false, cacheTTL, ...rest } = validatedParams.data;
412
- const cacheKey = this.cache.buildCacheKey("GetEcommerceItems", rest);
413
- return this.cache.getCachedOrFetch(
230
+ const cacheKey = this.cache.buildCacheKey(
231
+ "GetEcommerceItems",
232
+ validatedParams.data
233
+ );
234
+ return this.cache.cacheWrap(
414
235
  cacheKey,
415
- () => this.fetchItemsFromAPI(rest),
416
- cacheTTL,
417
- skipCache
236
+ () => this.fetchItemsFromAPI(validatedParams.data)
418
237
  );
419
238
  }
420
- async fetchItemsFromAPI(params = {}) {
239
+ async fetchItemsFromAPI(params) {
421
240
  if (!this.baseURL || !this.apiKey) {
422
241
  return {
423
242
  data: null,
424
- items: [],
425
243
  totalDocs: 0,
426
244
  totalPages: 0,
427
245
  prevPage: null,
@@ -518,7 +336,6 @@ var PakentoCMSAPI = class {
518
336
  if (error) {
519
337
  return {
520
338
  data: null,
521
- items: [],
522
339
  totalDocs: 0,
523
340
  totalPages: 0,
524
341
  prevPage: null,
@@ -528,8 +345,7 @@ var PakentoCMSAPI = class {
528
345
  };
529
346
  }
530
347
  return {
531
- data,
532
- items: parseRawItemsToItems(data.docs),
348
+ data: parseRawItemsToItems(data.docs),
533
349
  totalDocs: data.totalDocs,
534
350
  totalPages: data.totalPages,
535
351
  prevPage: data.prevPage,
@@ -538,21 +354,42 @@ var PakentoCMSAPI = class {
538
354
  errorMessage: null
539
355
  };
540
356
  }
357
+ };
358
+ var itemsApi = new ItemsApi();
359
+
360
+ // src/api/categories/validators.ts
361
+ var import_zod3 = require("zod");
362
+ var categoriesParamsSchema = import_zod3.z.object({
363
+ where: import_zod3.z.object({
364
+ item_super_category_id: import_zod3.z.object({ equals: import_zod3.z.string().optional() }).optional(),
365
+ brand_id: import_zod3.z.object({ equals: import_zod3.z.string().optional() }).optional()
366
+ }).optional(),
367
+ limit: import_zod3.z.coerce.number().optional(),
368
+ page: import_zod3.z.coerce.number().optional(),
369
+ sort: import_zod3.z.string().optional()
370
+ });
371
+
372
+ // src/api/categories/api.ts
373
+ var CategoriesApi = class extends ApiClient {
541
374
  async getCategories(params = {}) {
542
- const {
543
- skipCache = false,
544
- cacheTTL,
545
- ...rest
546
- } = params;
547
- const cacheKey = this.cache.buildCacheKey("GetEcommerceCategories", rest);
548
- return this.cache.getCachedOrFetch(
375
+ const validatedParams = categoriesParamsSchema.safeParse(params);
376
+ if (!validatedParams.success) {
377
+ const errorMessage = this.handleApiError(
378
+ validatedParams.error,
379
+ "getCategories validation"
380
+ );
381
+ return { data: null, categories: [], error: true, errorMessage };
382
+ }
383
+ const cacheKey = this.cache.buildCacheKey(
384
+ "GetEcommerceCategories",
385
+ validatedParams.data
386
+ );
387
+ return this.cache.cacheWrap(
549
388
  cacheKey,
550
- () => this.fetchCategoriesFromAPI(rest),
551
- cacheTTL,
552
- skipCache
389
+ () => this.fetchCategoriesFromAPI(validatedParams.data)
553
390
  );
554
391
  }
555
- async fetchCategoriesFromAPI(params = {}) {
392
+ async fetchCategoriesFromAPI(params) {
556
393
  if (!this.baseURL || !this.apiKey) {
557
394
  return {
558
395
  data: null,
@@ -588,12 +425,7 @@ var PakentoCMSAPI = class {
588
425
  (responseData) => responseData.GetEcommerceCategories
589
426
  );
590
427
  if (error) {
591
- return {
592
- data: null,
593
- categories: [],
594
- error: true,
595
- errorMessage
596
- };
428
+ return { data: null, categories: [], error: true, errorMessage };
597
429
  }
598
430
  return {
599
431
  data: data.docs,
@@ -602,17 +434,53 @@ var PakentoCMSAPI = class {
602
434
  errorMessage: null
603
435
  };
604
436
  }
437
+ };
438
+ var categoriesApi = new CategoriesApi();
439
+
440
+ // src/api/brands/validators.ts
441
+ var import_zod4 = require("zod");
442
+ var brandsParamsSchema = import_zod4.z.object({
443
+ limit: import_zod4.z.coerce.number().optional(),
444
+ page: import_zod4.z.coerce.number().optional(),
445
+ sort: import_zod4.z.string().optional()
446
+ });
447
+
448
+ // src/api/brands/api.ts
449
+ var BrandsApi = class extends ApiClient {
605
450
  async getBrands(params = {}) {
606
- const { skipCache = false, cacheTTL, ...rest } = params;
607
- const cacheKey = this.cache.buildCacheKey("GetEcommerceBrands", rest);
608
- return this.cache.getCachedOrFetch(
451
+ const validatedParams = brandsParamsSchema.safeParse(params);
452
+ if (!validatedParams.success) {
453
+ const errorMessage = this.handleApiError(
454
+ validatedParams.error,
455
+ "getBrands validation"
456
+ );
457
+ return {
458
+ data: null,
459
+ brands: [],
460
+ hasNextPage: false,
461
+ hasPrevPage: false,
462
+ limit: 0,
463
+ nextPage: 0,
464
+ offset: 0,
465
+ page: 0,
466
+ pagingCounter: 0,
467
+ prevPage: 0,
468
+ totalDocs: 0,
469
+ totalPages: 0,
470
+ error: true,
471
+ errorMessage
472
+ };
473
+ }
474
+ const cacheKey = this.cache.buildCacheKey(
475
+ "GetEcommerceBrands",
476
+ validatedParams.data
477
+ );
478
+ return this.cache.cacheWrap(
609
479
  cacheKey,
610
- () => this.fetchBrandsFromAPI(rest),
611
- cacheTTL,
612
- skipCache
480
+ () => this.fetchBrandsFromAPI(validatedParams.data)
613
481
  );
614
482
  }
615
- async fetchBrandsFromAPI(params = {}) {
483
+ async fetchBrandsFromAPI(params) {
616
484
  if (!this.baseURL || !this.apiKey) {
617
485
  return {
618
486
  data: null,
@@ -704,17 +572,19 @@ var PakentoCMSAPI = class {
704
572
  errorMessage: null
705
573
  };
706
574
  }
575
+ };
576
+ var brandsApi = new BrandsApi();
577
+
578
+ // src/api/entity/api.ts
579
+ var EntityApi = class extends ApiClient {
707
580
  async getEntity(params = {}) {
708
- const { skipCache = false, cacheTTL, ...rest } = params;
709
- const cacheKey = this.cache.buildCacheKey("GetEntity", rest);
710
- return this.cache.getCachedOrFetch(
581
+ const cacheKey = this.cache.buildCacheKey("GetEntity", params);
582
+ return this.cache.cacheWrap(
711
583
  cacheKey,
712
- () => this.fetchEntityFromAPI(rest),
713
- cacheTTL,
714
- skipCache
584
+ () => this.fetchEntityFromAPI(params)
715
585
  );
716
586
  }
717
- async fetchEntityFromAPI(params = {}) {
587
+ async fetchEntityFromAPI(params) {
718
588
  if (!this.baseURL || !this.apiKey) {
719
589
  return {
720
590
  data: null,
@@ -764,23 +634,39 @@ var PakentoCMSAPI = class {
764
634
  const { data, error, errorMessage } = await this.fetchGraphQL(
765
635
  query,
766
636
  params,
767
- (responseData) => responseData.GetEntity
637
+ (responseData) => responseData
768
638
  );
769
639
  if (error) {
770
- return {
771
- data: null,
772
- entity: null,
773
- error: true,
774
- errorMessage
775
- };
640
+ return { data: null, entity: null, error: true, errorMessage };
776
641
  }
777
642
  return {
778
- data,
779
- entity: data,
643
+ data: data.GetEntity,
644
+ entity: data.GetEntity,
780
645
  error: false,
781
646
  errorMessage: null
782
647
  };
783
648
  }
649
+ };
650
+ var entityApi = new EntityApi();
651
+
652
+ // src/api/orders/validators.ts
653
+ var import_zod5 = require("zod");
654
+ var orderSchema = import_zod5.z.object({
655
+ name: import_zod5.z.string().min(1),
656
+ email: import_zod5.z.string().email(),
657
+ phone: import_zod5.z.string().optional(),
658
+ notes: import_zod5.z.string().optional(),
659
+ tin: import_zod5.z.string().optional(),
660
+ items: import_zod5.z.array(
661
+ import_zod5.z.object({ id: import_zod5.z.number().positive(), quantity: import_zod5.z.number().positive() })
662
+ ).min(1),
663
+ delivery_address: import_zod5.z.string().optional(),
664
+ delivery_instructions: import_zod5.z.string().optional(),
665
+ payment_method: import_zod5.z.enum(["cash", "transfer"]).optional()
666
+ });
667
+
668
+ // src/api/orders/api.ts
669
+ var OrdersApi = class extends ApiClient {
784
670
  async createEcommerceOrder(params) {
785
671
  if (!this.baseURL || !this.apiKey) {
786
672
  return {
@@ -789,22 +675,6 @@ var PakentoCMSAPI = class {
789
675
  errorMessage: "SDK no configurado"
790
676
  };
791
677
  }
792
- const orderSchema = import_zod.z.object({
793
- name: import_zod.z.string().min(1),
794
- email: import_zod.z.string().email(),
795
- phone: import_zod.z.string().optional(),
796
- notes: import_zod.z.string().optional(),
797
- tin: import_zod.z.string().optional(),
798
- items: import_zod.z.array(
799
- import_zod.z.object({
800
- id: import_zod.z.number().positive(),
801
- quantity: import_zod.z.number().positive()
802
- })
803
- ).min(1),
804
- delivery_address: import_zod.z.string().optional(),
805
- delivery_instructions: import_zod.z.string().optional(),
806
- payment_method: import_zod.z.enum(["cash", "transfer"]).optional()
807
- });
808
678
  const validated = orderSchema.safeParse(params);
809
679
  if (!validated.success) {
810
680
  const errorMessage = this.handleApiError(
@@ -834,6 +704,62 @@ var PakentoCMSAPI = class {
834
704
  return { message: errorMessage, error: true, errorMessage };
835
705
  }
836
706
  }
707
+ };
708
+ var ordersApi = new OrdersApi();
709
+
710
+ // src/api/contact/validators.ts
711
+ var import_zod6 = require("zod");
712
+ var contactUsSchema = import_zod6.z.object({
713
+ name: import_zod6.z.string().min(1),
714
+ email: import_zod6.z.string().email(),
715
+ phone: import_zod6.z.string().optional(),
716
+ subject: import_zod6.z.string().optional(),
717
+ notes: import_zod6.z.string().min(1)
718
+ });
719
+
720
+ // src/api/contact/api.ts
721
+ var ContactApi = class extends ApiClient {
722
+ async sendContactUsEmail(params) {
723
+ if (!this.baseURL || !this.apiKey) {
724
+ return {
725
+ message: "SDK no configurado",
726
+ error: true,
727
+ errorMessage: "SDK no configurado"
728
+ };
729
+ }
730
+ const validated = contactUsSchema.safeParse(params);
731
+ if (!validated.success) {
732
+ const errorMessage = this.handleApiError(
733
+ validated.error,
734
+ "sendContactUsEmail validation"
735
+ );
736
+ return { message: errorMessage, error: true, errorMessage };
737
+ }
738
+ try {
739
+ const response = await this.client.post(
740
+ "/api/entities/send-contact-us-email",
741
+ validated.data
742
+ );
743
+ if (response.status === 200) {
744
+ return {
745
+ message: response.data.message || "Mensaje enviado exitosamente",
746
+ error: false,
747
+ errorMessage: null
748
+ };
749
+ } else {
750
+ const errorMessage = response.data.message || "Error al enviar el mensaje";
751
+ return { message: errorMessage, error: true, errorMessage };
752
+ }
753
+ } catch (error) {
754
+ const errorMessage = this.handleApiError(error, "sendContactUsEmail");
755
+ return { message: errorMessage, error: true, errorMessage };
756
+ }
757
+ }
758
+ };
759
+ var contactApi = new ContactApi();
760
+
761
+ // src/api/custom/api.ts
762
+ var CustomApi = class extends ApiClient {
837
763
  async executeCustomQuery(params) {
838
764
  if (!this.baseURL || !this.apiKey) {
839
765
  return {
@@ -868,117 +794,21 @@ var PakentoCMSAPI = class {
868
794
  errorMessage: null
869
795
  };
870
796
  } catch (error) {
871
- let errorMessage = "Error desconocido";
872
- if (error instanceof import_axios.AxiosError) {
873
- const status = error.response?.status;
874
- if (status === 401) {
875
- errorMessage = "API Key inv\xE1lida o expirada";
876
- } else if (status === 404) {
877
- errorMessage = "Endpoint GraphQL no encontrado";
878
- } else if (status === 400) {
879
- errorMessage = "Query GraphQL inv\xE1lido o malformado";
880
- } else if (status && status >= 500) {
881
- errorMessage = "Error del servidor CMS";
882
- } else {
883
- errorMessage = `Error de conexi\xF3n: ${error.message}`;
884
- }
885
- } else if (error instanceof Error) {
886
- errorMessage = error.message;
887
- }
888
- return {
889
- data: null,
890
- error: true,
891
- errorMessage
892
- };
893
- }
894
- }
895
- async sendContactUsEmail(params) {
896
- if (!this.baseURL || !this.apiKey) {
897
- return {
898
- message: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes.",
899
- error: true,
900
- errorMessage: "SDK no configurado: PAKENTO_CMS_BASE_URL o PAKENTO_API_KEY faltantes."
901
- };
902
- }
903
- const contactUsSchema = import_zod.z.object({
904
- name: import_zod.z.string().min(1),
905
- email: import_zod.z.email(),
906
- phone: import_zod.z.string().optional(),
907
- subject: import_zod.z.string().optional(),
908
- message: import_zod.z.string().min(1)
909
- });
910
- const validated = contactUsSchema.safeParse(params);
911
- if (!validated.success) {
912
- const errorMessage = this.handleApiError(
913
- validated.error,
914
- "sendContactUsEmail validation"
915
- );
916
- return { message: errorMessage, error: true, errorMessage };
917
- }
918
- try {
919
- const response = await this.client.post(
920
- "/api/entities/send-contact-us-email",
921
- validated.data
922
- );
923
- if (response.status === 200) {
924
- return {
925
- message: response.data.message || "Mensaje enviado exitosamente",
926
- error: false,
927
- errorMessage: null
928
- };
929
- } else {
930
- const errorMessage = response.data.message || "Error al enviar el mensaje";
931
- return { message: errorMessage, error: true, errorMessage };
932
- }
933
- } catch (error) {
934
- const errorMessage = this.handleApiError(error, "sendContactUsEmail");
935
- return { message: errorMessage, error: true, errorMessage };
797
+ const errorMessage = this.handleApiError(error, "Custom GraphQL");
798
+ return { data: null, error: true, errorMessage };
936
799
  }
937
800
  }
938
- /**
939
- * Verifica si existe cache para una función y parámetros específicos
940
- */
941
- async hasCache(functionName, params = {}) {
942
- return this.cache.hasCache(functionName, params);
943
- }
944
- /**
945
- * Obtiene la key de cache para una función y parámetros específicos
946
- */
947
- getCacheKey(functionName, params = {}) {
948
- return this.cache.getCacheKey(functionName, params);
949
- }
950
- /**
951
- * Limpia el cache para una función y parámetros específicos
952
- */
953
- async clearCache(functionName, params = {}) {
954
- return this.cache.clearCache(functionName, params);
955
- }
956
- /**
957
- * Limpia todo el cache relacionado con este API Key
958
- */
959
- async clearAllCache() {
960
- return this.cache.clearAllCache();
961
- }
962
- /**
963
- * Obtiene información del cache (útil para debugging)
964
- */
965
- async getCacheInfo(functionName, params = {}) {
966
- return this.cache.getCacheInfo(functionName, params);
967
- }
968
- /**
969
- * Limpia un cache específico que pueda estar corrupto
970
- */
971
- async clearCorruptedCache(functionName, params = {}) {
972
- const key = this.cache.getCacheKey(functionName, params);
973
- return this.cache.clearCorruptedCache(key);
974
- }
975
801
  };
976
- var pakentoCMSAPI = new PakentoCMSAPI();
802
+ var customApi = new CustomApi();
977
803
  // Annotate the CommonJS export names for ESM import in node:
978
804
  0 && (module.exports = {
979
- CacheService,
980
- pakentoCMSAPI,
981
- parseRawItemToItem,
982
- parseRawItemsToItems
805
+ ApiClient,
806
+ brandsApi,
807
+ categoriesApi,
808
+ contactApi,
809
+ customApi,
810
+ entityApi,
811
+ itemsApi,
812
+ ordersApi
983
813
  });
984
814
  //# sourceMappingURL=index.js.map