@atomic-solutions/woocommerce-api-client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +124 -0
  3. package/dist/client/index.d.mts +9 -0
  4. package/dist/client/index.d.ts +9 -0
  5. package/dist/client/index.js +1461 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/index.mjs +1455 -0
  8. package/dist/client/index.mjs.map +1 -0
  9. package/dist/http/index.d.mts +11 -0
  10. package/dist/http/index.d.ts +11 -0
  11. package/dist/http/index.js +638 -0
  12. package/dist/http/index.js.map +1 -0
  13. package/dist/http/index.mjs +631 -0
  14. package/dist/http/index.mjs.map +1 -0
  15. package/dist/index.d.mts +29 -0
  16. package/dist/index.d.ts +29 -0
  17. package/dist/index.js +2152 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/index.mjs +2105 -0
  20. package/dist/index.mjs.map +1 -0
  21. package/dist/pagination.schema-CdjWGZJr.d.mts +190 -0
  22. package/dist/pagination.schema-CdjWGZJr.d.ts +190 -0
  23. package/dist/products-Cxl54crz.d.mts +3412 -0
  24. package/dist/products-Cxl54crz.d.ts +3412 -0
  25. package/dist/schemas/admin-api/index.d.mts +5340 -0
  26. package/dist/schemas/admin-api/index.d.ts +5340 -0
  27. package/dist/schemas/admin-api/index.js +584 -0
  28. package/dist/schemas/admin-api/index.js.map +1 -0
  29. package/dist/schemas/admin-api/index.mjs +545 -0
  30. package/dist/schemas/admin-api/index.mjs.map +1 -0
  31. package/dist/schemas/index.d.mts +4 -0
  32. package/dist/schemas/index.d.ts +4 -0
  33. package/dist/schemas/index.js +887 -0
  34. package/dist/schemas/index.js.map +1 -0
  35. package/dist/schemas/index.mjs +844 -0
  36. package/dist/schemas/index.mjs.map +1 -0
  37. package/dist/schemas/store-api/index.d.mts +1076 -0
  38. package/dist/schemas/store-api/index.d.ts +1076 -0
  39. package/dist/schemas/store-api/index.js +887 -0
  40. package/dist/schemas/store-api/index.js.map +1 -0
  41. package/dist/schemas/store-api/index.mjs +844 -0
  42. package/dist/schemas/store-api/index.mjs.map +1 -0
  43. package/dist/types-B-zy1xrP.d.mts +183 -0
  44. package/dist/types-qKWtrw7A.d.ts +183 -0
  45. package/dist/utils/index.d.mts +17 -0
  46. package/dist/utils/index.d.ts +17 -0
  47. package/dist/utils/index.js +316 -0
  48. package/dist/utils/index.js.map +1 -0
  49. package/dist/utils/index.mjs +308 -0
  50. package/dist/utils/index.mjs.map +1 -0
  51. package/package.json +117 -0
@@ -0,0 +1,638 @@
1
+ 'use strict';
2
+
3
+ var axios = require('axios');
4
+
5
+ // src/errors/classes/BaseError.ts
6
+ var BaseError = class extends Error {
7
+ constructor(options) {
8
+ super(options.message);
9
+ this.options = options;
10
+ Object.setPrototypeOf(this, new.target.prototype);
11
+ this.name = this.constructor.name;
12
+ if (Error.captureStackTrace) {
13
+ Error.captureStackTrace(this, this.constructor);
14
+ }
15
+ if (this.options.cause instanceof Error && this.options.cause.stack) {
16
+ this.stack = `${this.stack}
17
+ Caused by: ${this.options.cause.stack}`;
18
+ }
19
+ }
20
+ /**
21
+ * Get reportable data for error tracking/logging
22
+ * Subclasses should override this to add their own reportable fields
23
+ */
24
+ getReportableData() {
25
+ const { code, operation, userMessage, retryable } = this.options;
26
+ return {
27
+ code,
28
+ operation,
29
+ userMessage,
30
+ retryable
31
+ };
32
+ }
33
+ /**
34
+ * Custom JSON serialization
35
+ * Makes the error properly serializable for logging/reporting
36
+ */
37
+ toJSON() {
38
+ return {
39
+ ...this.getReportableData(),
40
+ name: this.name,
41
+ message: this.message,
42
+ stack: this.stack
43
+ };
44
+ }
45
+ };
46
+
47
+ // src/errors/mapping/mapWooCommerceCode.ts
48
+ var mapWooCommerceCode = (apiCode) => {
49
+ const directMatches = {
50
+ woocommerce_rest_cart_empty: "cart_empty",
51
+ woocommerce_rest_cart_coupon_error: "invalid_coupon",
52
+ woocommerce_rest_missing_nonce: "missing_nonce",
53
+ woocommerce_rest_invalid_nonce: "invalid_nonce",
54
+ rest_invalid_param: "invalid_params",
55
+ woocommerce_rest_product_invalid_id: "product_not_found",
56
+ woocommerce_rest_product_out_of_stock: "out_of_stock",
57
+ woocommerce_rest_product_not_enough_stock: "insufficient_stock",
58
+ woocommerce_rest_checkout_invalid_payment_method: "invalid_payment_method"
59
+ };
60
+ if (directMatches[apiCode]) {
61
+ return directMatches[apiCode];
62
+ }
63
+ if (apiCode.includes("nonce")) return "invalid_nonce";
64
+ if (apiCode.includes("coupon")) return "invalid_coupon";
65
+ if (apiCode.includes("stock")) return "insufficient_stock";
66
+ if (apiCode.includes("checkout")) return "checkout_error";
67
+ if (apiCode.includes("payment")) return "invalid_payment_method";
68
+ return "unknown_error";
69
+ };
70
+
71
+ // src/errors/mapping/constants.ts
72
+ var WOOCOMMERCE_ERROR_METADATA = {
73
+ cart_empty: {
74
+ operation: "get_cart",
75
+ retryable: false,
76
+ userMessage: "Your cart is empty"
77
+ },
78
+ invalid_coupon: {
79
+ operation: "apply_coupon",
80
+ retryable: false,
81
+ userMessage: "Invalid coupon code"
82
+ },
83
+ missing_nonce: {
84
+ operation: "cart_request",
85
+ retryable: true
86
+ // Auto-retry with new nonce
87
+ },
88
+ invalid_nonce: {
89
+ operation: "cart_request",
90
+ retryable: true
91
+ // Auto-retry with new nonce
92
+ },
93
+ invalid_params: {
94
+ operation: "api_request",
95
+ retryable: false,
96
+ userMessage: "Invalid request parameters"
97
+ },
98
+ product_not_found: {
99
+ operation: "get_product",
100
+ retryable: false,
101
+ userMessage: "Product not found"
102
+ },
103
+ out_of_stock: {
104
+ operation: "add_to_cart",
105
+ retryable: false,
106
+ userMessage: "This product is out of stock"
107
+ },
108
+ insufficient_stock: {
109
+ operation: "add_to_cart",
110
+ retryable: false,
111
+ userMessage: "Not enough stock available"
112
+ },
113
+ invalid_payment_method: {
114
+ operation: "process_checkout",
115
+ retryable: false,
116
+ userMessage: "Invalid payment method"
117
+ },
118
+ checkout_error: {
119
+ operation: "process_checkout",
120
+ retryable: false
121
+ },
122
+ network_error: {
123
+ operation: "network_request",
124
+ retryable: true
125
+ },
126
+ unknown_error: {
127
+ operation: "unknown",
128
+ retryable: false
129
+ }
130
+ };
131
+
132
+ // src/errors/classes/WooCommerceApiError.ts
133
+ var WooCommerceApiError = class extends BaseError {
134
+ constructor(options) {
135
+ const metadata = WOOCOMMERCE_ERROR_METADATA[options.code] ?? {
136
+ operation: "woocommerce_api_request",
137
+ retryable: false
138
+ };
139
+ const enrichedOptions = {
140
+ ...options,
141
+ operation: options.operation || metadata.operation,
142
+ userMessage: options.userMessage || metadata.userMessage,
143
+ retryable: options.retryable ?? metadata.retryable
144
+ };
145
+ super(enrichedOptions);
146
+ }
147
+ // Convenient getters for frequently accessed fields (no duplication)
148
+ get wooCode() {
149
+ return this.options.code;
150
+ }
151
+ get originalCode() {
152
+ return this.options.originalCode;
153
+ }
154
+ get statusCode() {
155
+ return this.options.statusCode;
156
+ }
157
+ get url() {
158
+ return this.options.url;
159
+ }
160
+ get method() {
161
+ return this.options.method;
162
+ }
163
+ get requestBody() {
164
+ return this.options.requestBody;
165
+ }
166
+ get responseBody() {
167
+ return this.options.responseBody;
168
+ }
169
+ get data() {
170
+ return this.options.data;
171
+ }
172
+ /**
173
+ * Get reportable data for error tracking/logging
174
+ * Includes HTTP context and WooCommerce-specific fields
175
+ */
176
+ getReportableData() {
177
+ return {
178
+ code: this.options.code,
179
+ operation: this.options.operation,
180
+ userMessage: this.options.userMessage,
181
+ retryable: this.options.retryable,
182
+ statusCode: this.options.statusCode,
183
+ url: this.options.url,
184
+ method: this.options.method,
185
+ wooCode: this.options.code,
186
+ originalCode: this.options.originalCode
187
+ };
188
+ }
189
+ };
190
+
191
+ // src/errors/classes/WooCommerceDataValidationError.ts
192
+ var WooCommerceDataValidationError = class _WooCommerceDataValidationError extends BaseError {
193
+ constructor(options) {
194
+ const fieldErrors = options.zodError ? _WooCommerceDataValidationError.extractFieldErrorsFromZod(options.zodError) : void 0;
195
+ super({
196
+ code: "validation_error",
197
+ message: options.message,
198
+ operation: options.operation,
199
+ userMessage: options.userMessage || "Received unexpected data from WooCommerce",
200
+ retryable: false,
201
+ cause: options.cause,
202
+ url: options.url,
203
+ zodError: options.zodError,
204
+ value: options.value,
205
+ fieldErrors
206
+ });
207
+ }
208
+ // Convenient getters for validation-specific fields (no duplication)
209
+ get url() {
210
+ return this.options.url;
211
+ }
212
+ get zodError() {
213
+ return this.options.zodError;
214
+ }
215
+ get invalidValue() {
216
+ return this.options.value;
217
+ }
218
+ get fieldErrors() {
219
+ return this.options.fieldErrors;
220
+ }
221
+ /**
222
+ * Get reportable data for error tracking/logging
223
+ * Includes validation-specific fields
224
+ */
225
+ getReportableData() {
226
+ return {
227
+ code: this.options.code,
228
+ operation: this.options.operation,
229
+ userMessage: this.options.userMessage,
230
+ retryable: false,
231
+ fieldErrors: this.options.fieldErrors,
232
+ url: this.options.url
233
+ };
234
+ }
235
+ /**
236
+ * Extract field errors from Zod error
237
+ */
238
+ static extractFieldErrorsFromZod(zodError) {
239
+ if (!zodError?.errors) {
240
+ return void 0;
241
+ }
242
+ const fieldErrors = {};
243
+ for (const issue of zodError.errors) {
244
+ const path = issue.path.join(".");
245
+ if (!fieldErrors[path]) {
246
+ fieldErrors[path] = [];
247
+ }
248
+ fieldErrors[path].push(issue.message);
249
+ }
250
+ return fieldErrors;
251
+ }
252
+ /**
253
+ * Get all error messages as a flat array
254
+ */
255
+ getMessages() {
256
+ if (!this.fieldErrors) {
257
+ return [this.message];
258
+ }
259
+ const messages = [];
260
+ for (const fieldMessages of Object.values(this.fieldErrors)) {
261
+ messages.push(...fieldMessages);
262
+ }
263
+ return messages;
264
+ }
265
+ /**
266
+ * Check if a specific field has errors
267
+ */
268
+ hasFieldError(field) {
269
+ return this.fieldErrors ? field in this.fieldErrors : false;
270
+ }
271
+ /**
272
+ * Get error messages for a specific field
273
+ */
274
+ getFieldError(field) {
275
+ return this.fieldErrors?.[field];
276
+ }
277
+ };
278
+
279
+ // src/http/handleApiResponse.ts
280
+ var handleApiResponse = (response, schema, options) => {
281
+ const validationMode = options?.validationMode ?? "strict";
282
+ if (validationMode === "warn") {
283
+ const result = schema.safeParse(response.data);
284
+ if (!result.success) {
285
+ const validationError = new WooCommerceDataValidationError({
286
+ message: `WooCommerce API response validation failed for ${response.config.url || "unknown endpoint"}`,
287
+ url: response.config.url,
288
+ zodError: result.error,
289
+ value: response.data,
290
+ userMessage: "Received unexpected data from WooCommerce"
291
+ });
292
+ options?.onValidationError?.(validationError);
293
+ options?.errorReporter?.(validationError);
294
+ console.warn("[woocommerce-utils] Validation warning:", validationError.message);
295
+ return response.data;
296
+ }
297
+ return result.data;
298
+ }
299
+ try {
300
+ return schema.parse(response.data);
301
+ } catch (error2) {
302
+ if (error2 && typeof error2 === "object" && "issues" in error2) {
303
+ const validationError = new WooCommerceDataValidationError({
304
+ message: `WooCommerce API response validation failed for ${response.config.url || "unknown endpoint"}`,
305
+ url: response.config.url,
306
+ zodError: error2,
307
+ value: response.data,
308
+ userMessage: "Received unexpected data from WooCommerce"
309
+ });
310
+ options?.onValidationError?.(validationError);
311
+ options?.errorReporter?.(validationError);
312
+ throw validationError;
313
+ }
314
+ throw error2;
315
+ }
316
+ };
317
+ var isZodError = (error2) => {
318
+ return error2 instanceof Error && error2.name === "ZodError";
319
+ };
320
+
321
+ // src/utils/calculatePagination.ts
322
+ var calculatePagination = (input) => {
323
+ const { page, perPage, total, totalPages } = input;
324
+ const hasNextPage = page < totalPages;
325
+ const hasPrevPage = page > 1;
326
+ return {
327
+ page,
328
+ perPage,
329
+ total,
330
+ totalPages,
331
+ hasNextPage,
332
+ hasPrevPage,
333
+ nextPage: hasNextPage ? page + 1 : null,
334
+ prevPage: hasPrevPage ? page - 1 : null
335
+ };
336
+ };
337
+
338
+ // src/utils/getPaginationMeta.ts
339
+ var getPaginationMeta = (headers) => {
340
+ if (!headers) {
341
+ return {
342
+ total: 0,
343
+ totalPages: 0
344
+ };
345
+ }
346
+ const wpTotal = headers["x-wp-total"];
347
+ const wpTotalPages = headers["x-wp-totalpages"];
348
+ if (!wpTotal || !wpTotalPages) {
349
+ return {
350
+ total: 0,
351
+ totalPages: 0
352
+ };
353
+ }
354
+ const total = parseInt(wpTotal, 10);
355
+ const totalPages = parseInt(wpTotalPages, 10);
356
+ return {
357
+ total,
358
+ totalPages
359
+ };
360
+ };
361
+
362
+ // src/http/handlePaginatedApiResponse.ts
363
+ var handlePaginatedApiResponse = (response, schema, params = {}, options) => {
364
+ const validationMode = options?.validationMode ?? "strict";
365
+ let data;
366
+ if (validationMode === "warn") {
367
+ const result = schema.safeParse(response.data);
368
+ if (!result.success) {
369
+ const validationError = new WooCommerceDataValidationError({
370
+ message: `WooCommerce API response validation failed for ${response.config.url || "unknown endpoint"}`,
371
+ url: response.config.url,
372
+ zodError: result.error,
373
+ value: response.data,
374
+ userMessage: "Received unexpected data from WooCommerce"
375
+ });
376
+ options?.onValidationError?.(validationError);
377
+ options?.errorReporter?.(validationError);
378
+ console.warn("[woocommerce-utils] Validation warning:", validationError.message);
379
+ data = Array.isArray(response.data) ? response.data : [];
380
+ } else {
381
+ data = result.data;
382
+ }
383
+ } else {
384
+ try {
385
+ data = schema.parse(response.data);
386
+ } catch (error2) {
387
+ if (error2 && typeof error2 === "object" && "issues" in error2) {
388
+ const validationError = new WooCommerceDataValidationError({
389
+ message: `WooCommerce API response validation failed for ${response.config.url || "unknown endpoint"}`,
390
+ url: response.config.url,
391
+ zodError: error2,
392
+ value: response.data,
393
+ userMessage: "Received unexpected data from WooCommerce"
394
+ });
395
+ options?.onValidationError?.(validationError);
396
+ options?.errorReporter?.(validationError);
397
+ throw validationError;
398
+ }
399
+ throw error2;
400
+ }
401
+ }
402
+ const { total, totalPages } = getPaginationMeta(response.headers);
403
+ const page = params.page || 1;
404
+ const perPage = params.per_page || 10;
405
+ const pagination = calculatePagination({
406
+ page,
407
+ perPage,
408
+ total,
409
+ totalPages
410
+ });
411
+ return {
412
+ data,
413
+ pagination
414
+ };
415
+ };
416
+
417
+ // src/logging/logger.ts
418
+ var DEBUG_PREFIX = "[woocommerce-utils]";
419
+ var isDebugEnabled = () => {
420
+ if (typeof process !== "undefined" && process.env) {
421
+ return process.env.DEBUG === "true" || process.env.DEBUG === "1";
422
+ }
423
+ return false;
424
+ };
425
+ var debug = (...args) => {
426
+ if (isDebugEnabled()) {
427
+ console.log(DEBUG_PREFIX, ...args);
428
+ }
429
+ };
430
+ var error = (...args) => {
431
+ console.error(DEBUG_PREFIX, ...args);
432
+ };
433
+
434
+ // src/http/interceptors/request.ts
435
+ var requiresAuth = (url) => {
436
+ if (!url) return false;
437
+ const authEndpoints = ["/jwt-auth/", "/customers/me", "/wp/v2/users/me"];
438
+ return authEndpoints.some((endpoint) => url.includes(endpoint));
439
+ };
440
+ var requiresCartAuth = (url) => {
441
+ if (!url) return false;
442
+ return /\/wc\/store\/(v\d+\/)?cart/.test(url) || /\/wc\/store\/(v\d+\/)?checkout/.test(url);
443
+ };
444
+ var setupRequestInterceptor = (axiosInstance, config, client) => {
445
+ axiosInstance.interceptors.request.use(
446
+ async (requestConfig) => {
447
+ const url = requestConfig.url;
448
+ if (requiresAuth(url) && config.jwtToken) {
449
+ const token = await config.jwtToken.get();
450
+ if (token) {
451
+ requestConfig.headers.Authorization = `Bearer ${token}`;
452
+ if (config.debug) {
453
+ debug("Injected JWT token for", url);
454
+ }
455
+ }
456
+ }
457
+ if (requiresCartAuth(url)) {
458
+ const headers = await config.cartHeaders.get();
459
+ if (headers.nonce) {
460
+ requestConfig.headers.Nonce = headers.nonce;
461
+ }
462
+ if (headers.cartToken) {
463
+ requestConfig.headers["Cart-Token"] = headers.cartToken;
464
+ }
465
+ requestConfig.headers["Cache-Control"] = "no-cache, no-store, must-revalidate";
466
+ requestConfig.headers.Pragma = "no-cache";
467
+ requestConfig.headers.Expires = "0";
468
+ if (config.debug) {
469
+ debug("Injected cart headers for", url, {
470
+ hasNonce: !!headers.nonce,
471
+ hasCartToken: !!headers.cartToken
472
+ });
473
+ }
474
+ }
475
+ if (config.debug) {
476
+ debug(
477
+ `${requestConfig.method?.toUpperCase()} ${requestConfig.url}`,
478
+ requestConfig.params || requestConfig.data
479
+ );
480
+ }
481
+ if (config.onRequest) {
482
+ return config.onRequest(requestConfig, client);
483
+ }
484
+ return requestConfig;
485
+ },
486
+ (error2) => {
487
+ return Promise.reject(error2);
488
+ }
489
+ );
490
+ };
491
+
492
+ // src/http/interceptors/response.ts
493
+ var isCartResponse = (url) => {
494
+ if (!url) return false;
495
+ return /\/wc\/store\/(v\d+\/)?cart/.test(url) || /\/wc\/store\/(v\d+\/)?checkout/.test(url);
496
+ };
497
+ var setupResponseInterceptor = (axiosInstance, config, client) => {
498
+ axiosInstance.interceptors.response.use(
499
+ async (response) => {
500
+ if (isCartResponse(response.config.url)) {
501
+ const nonce = response.headers["nonce"] || response.headers["Nonce"];
502
+ const cartToken = response.headers["cart-token"] || response.headers["Cart-Token"];
503
+ if (nonce || cartToken) {
504
+ await config.cartHeaders.save({
505
+ nonce: nonce || void 0,
506
+ cartToken: cartToken || void 0
507
+ });
508
+ if (config.debug) {
509
+ debug(
510
+ "Saved updated cart headers:",
511
+ response.config.url,
512
+ "nonce:",
513
+ !!nonce,
514
+ "cartToken:",
515
+ !!cartToken
516
+ );
517
+ }
518
+ }
519
+ }
520
+ if (config.debug) {
521
+ debug("Response:", response.config.url, response.status);
522
+ }
523
+ if (config.onResponse) {
524
+ return config.onResponse(response, client);
525
+ }
526
+ return response;
527
+ },
528
+ (error2) => {
529
+ return Promise.reject(error2);
530
+ }
531
+ );
532
+ };
533
+
534
+ // src/utils/initializeCartSession.ts
535
+ var initializeCartSession = async (client, cartHeaders) => {
536
+ try {
537
+ debug("session", "Initializing cart session");
538
+ const response = await client.get("/wc/store/v1/cart");
539
+ const nonce = response.headers["nonce"] || response.headers["Nonce"];
540
+ const cartToken = response.headers["cart-token"] || response.headers["Cart-Token"];
541
+ if (nonce || cartToken) {
542
+ await cartHeaders.save({
543
+ nonce: nonce || void 0,
544
+ cartToken: cartToken || void 0
545
+ });
546
+ debug("session", "Cart session initialized", {
547
+ hasNonce: !!nonce,
548
+ hasCartToken: !!cartToken
549
+ });
550
+ }
551
+ } catch (error2) {
552
+ debug("session", "Failed to initialize cart session", error2);
553
+ throw error2;
554
+ }
555
+ };
556
+
557
+ // src/http/interceptors/error.ts
558
+ var setupErrorInterceptor = (axiosInstance, config, client) => {
559
+ axiosInstance.interceptors.response.use(
560
+ (response) => response,
561
+ async (axiosError) => {
562
+ const status = axiosError.response?.status || 500;
563
+ const errorData = axiosError.response?.data;
564
+ const apiCode = errorData?.code || "unknown_error";
565
+ const wpMessage = errorData?.message || axiosError.message || "Unknown error";
566
+ const errorCode = mapWooCommerceCode(apiCode);
567
+ const errorMetadata = WOOCOMMERCE_ERROR_METADATA[errorCode];
568
+ const wcError = new WooCommerceApiError({
569
+ message: wpMessage,
570
+ statusCode: status,
571
+ code: errorCode,
572
+ // Transformed app-level code
573
+ originalCode: apiCode,
574
+ // Original WooCommerce API code
575
+ retryable: errorMetadata.retryable,
576
+ userMessage: errorMetadata.userMessage,
577
+ operation: errorMetadata.operation,
578
+ url: axiosError.config?.url || "",
579
+ method: axiosError.config?.method?.toUpperCase() || "GET",
580
+ requestBody: axiosError.config?.data,
581
+ responseBody: errorData,
582
+ data: errorData?.data,
583
+ cause: axiosError
584
+ });
585
+ if (config.debug) {
586
+ debug("WooCommerce error:", apiCode, status, wpMessage);
587
+ error(wcError);
588
+ }
589
+ if ((status === 401 || status === 403) && config.onAuthError && axios.isAxiosError(axiosError) && !axiosError.config?._retry) {
590
+ if (config.debug) {
591
+ debug("Auth error detected, calling onAuthError handler");
592
+ }
593
+ try {
594
+ const shouldRetry = await config.onAuthError(wcError, client);
595
+ if (shouldRetry) {
596
+ if (config.debug) {
597
+ debug("Retrying request after auth error");
598
+ }
599
+ axiosError.config._retry = true;
600
+ return axiosInstance.request(axiosError.config);
601
+ }
602
+ } catch (authErrorHandlerError) {
603
+ if (config.debug) {
604
+ debug("onAuthError handler threw error", authErrorHandlerError);
605
+ }
606
+ }
607
+ }
608
+ if (config.onError) {
609
+ config.onError(wcError, client);
610
+ }
611
+ const isNonceError = errorCode === "missing_nonce" || errorCode === "invalid_nonce";
612
+ if (isNonceError && axios.isAxiosError(axiosError) && !axiosError.config?._retry) {
613
+ if (config.debug) {
614
+ debug("Nonce error detected, retrying with new session");
615
+ }
616
+ try {
617
+ await initializeCartSession(axiosInstance, config.cartHeaders);
618
+ axiosError.config._retry = true;
619
+ return axiosInstance.request(axiosError.config);
620
+ } catch (_retryError) {
621
+ config.errorReporter?.report(wcError);
622
+ return Promise.reject(wcError);
623
+ }
624
+ }
625
+ config.errorReporter?.report(wcError);
626
+ return Promise.reject(wcError);
627
+ }
628
+ );
629
+ };
630
+
631
+ exports.handleApiResponse = handleApiResponse;
632
+ exports.handlePaginatedApiResponse = handlePaginatedApiResponse;
633
+ exports.isZodError = isZodError;
634
+ exports.setupErrorInterceptor = setupErrorInterceptor;
635
+ exports.setupRequestInterceptor = setupRequestInterceptor;
636
+ exports.setupResponseInterceptor = setupResponseInterceptor;
637
+ //# sourceMappingURL=index.js.map
638
+ //# sourceMappingURL=index.js.map