@cimplify/sdk 0.3.4 → 0.3.5

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.d.mts CHANGED
@@ -1,3 +1,95 @@
1
+ /**
2
+ * Observability hooks for monitoring SDK behavior.
3
+ *
4
+ * These hooks allow you to plug in your own logging, metrics, and tracing
5
+ * without the SDK depending on any specific observability library.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const client = createCimplifyClient({
10
+ * hooks: {
11
+ * onRequestStart: ({ method, path }) => {
12
+ * console.log(`[SDK] ${method} ${path}`);
13
+ * },
14
+ * onRequestSuccess: ({ method, path, durationMs }) => {
15
+ * metrics.histogram('sdk.request.duration', durationMs, { method, path });
16
+ * },
17
+ * onRequestError: ({ method, path, error, retryCount }) => {
18
+ * Sentry.captureException(error, { extra: { method, path, retryCount } });
19
+ * },
20
+ * },
21
+ * });
22
+ * ```
23
+ */
24
+ /** Context passed to request lifecycle hooks */
25
+ interface RequestContext {
26
+ /** HTTP method */
27
+ method: "GET" | "POST" | "DELETE";
28
+ /** Request path (e.g., "/api/q", "/api/m") */
29
+ path: string;
30
+ /** Full URL */
31
+ url: string;
32
+ /** Request body (for POST requests) */
33
+ body?: unknown;
34
+ /** Timestamp when request started */
35
+ startTime: number;
36
+ }
37
+ /** Passed when a request starts */
38
+ interface RequestStartEvent extends RequestContext {
39
+ }
40
+ /** Passed when a request succeeds */
41
+ interface RequestSuccessEvent extends RequestContext {
42
+ /** HTTP status code */
43
+ status: number;
44
+ /** Duration in milliseconds */
45
+ durationMs: number;
46
+ }
47
+ /** Passed when a request fails */
48
+ interface RequestErrorEvent extends RequestContext {
49
+ /** The error that occurred */
50
+ error: Error;
51
+ /** Duration in milliseconds */
52
+ durationMs: number;
53
+ /** Number of retries attempted before giving up */
54
+ retryCount: number;
55
+ /** Whether the error is retryable */
56
+ retryable: boolean;
57
+ }
58
+ /** Passed when a retry is about to happen */
59
+ interface RetryEvent extends RequestContext {
60
+ /** Which retry attempt (1, 2, 3...) */
61
+ attempt: number;
62
+ /** Delay before retry in milliseconds */
63
+ delayMs: number;
64
+ /** The error that triggered the retry */
65
+ error: Error;
66
+ }
67
+ /** Passed when session token changes */
68
+ interface SessionChangeEvent {
69
+ /** Previous token (null if none) */
70
+ previousToken: string | null;
71
+ /** New token (null if cleared) */
72
+ newToken: string | null;
73
+ /** Source of the change */
74
+ source: "response" | "manual" | "clear";
75
+ }
76
+ /**
77
+ * Observability hooks configuration.
78
+ * All hooks are optional - only implement what you need.
79
+ */
80
+ interface ObservabilityHooks {
81
+ /** Called when a request is about to be sent */
82
+ onRequestStart?: (event: RequestStartEvent) => void;
83
+ /** Called when a request completes successfully */
84
+ onRequestSuccess?: (event: RequestSuccessEvent) => void;
85
+ /** Called when a request fails (after all retries exhausted) */
86
+ onRequestError?: (event: RequestErrorEvent) => void;
87
+ /** Called before each retry attempt */
88
+ onRetry?: (event: RetryEvent) => void;
89
+ /** Called when session token changes */
90
+ onSessionChange?: (event: SessionChangeEvent) => void;
91
+ }
92
+
1
93
  /** Decimal value represented as string for precision */
2
94
  type Money = string;
3
95
  /** Supported currencies */
@@ -2839,6 +2931,8 @@ interface CimplifyConfig {
2839
2931
  maxRetries?: number;
2840
2932
  /** Base delay between retries in milliseconds (default: 1000) */
2841
2933
  retryDelay?: number;
2934
+ /** Observability hooks for logging, metrics, and tracing */
2935
+ hooks?: ObservabilityHooks;
2842
2936
  }
2843
2937
  declare class CimplifyClient {
2844
2938
  private baseUrl;
@@ -2849,6 +2943,7 @@ declare class CimplifyClient {
2849
2943
  private timeout;
2850
2944
  private maxRetries;
2851
2945
  private retryDelay;
2946
+ private hooks;
2852
2947
  /** In-flight request deduplication map */
2853
2948
  private inflightRequests;
2854
2949
  private _catalogue?;
@@ -2870,7 +2965,7 @@ declare class CimplifyClient {
2870
2965
  private getHeaders;
2871
2966
  private updateSessionFromResponse;
2872
2967
  /**
2873
- * Resilient fetch with timeout and automatic retries for network errors.
2968
+ * Resilient fetch with timeout, automatic retries, and observability hooks.
2874
2969
  * Uses exponential backoff: 1s, 2s, 4s between retries.
2875
2970
  */
2876
2971
  private resilientFetch;
@@ -3435,4 +3530,4 @@ interface ApiResponse<T> {
3435
3530
  metadata?: ResponseMetadata;
3436
3531
  }
3437
3532
 
3438
- export { AUTHORIZATION_TYPE, AUTH_MUTATION, type AddOn, type AddOnDetails, type AddOnGroupDetails, type AddOnOption, type AddOnOptionDetails, type AddOnOptionPrice, type AddOnWithOptions, type AddToCartInput, type AddressData, type AdjustmentType, type AmountToPay, type ApiError, type ApiResponse, type AppliedDiscount, type AuthResponse, AuthService, type AuthStatus, type AuthorizationType, type AvailabilityCheck, type AvailabilityResult, type AvailableSlot, type BenefitType, type Booking, type BookingRequirementOverride, type BookingStatus, type BookingWithDetails, type BufferTimes, type Bundle, type BundleComponentData, type BundleComponentInfo, type BundlePriceType, type BundleProduct, type BundleSelectionData, type BundleSelectionInput, type BundleStoredSelection, type BundleSummary, type BundleWithDetails, type Business, type BusinessHours, type BusinessPreferences, BusinessService, type BusinessSettings, type BusinessType, type BusinessWithLocations, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, type CancelBookingInput, type CancelOrderInput, type CancellationPolicy, type Cart, type CartAddOn, type CartChannel, type CartItem, type CartItemDetails, CartOperations, type CartStatus, type CartSummary, type CartTotals, CatalogueQueries, type Category, type CategoryInfo, type CategorySummary, type ChangePasswordInput, type CheckSlotAvailabilityInput, type CheckoutAddressInfo, type CheckoutCustomerInfo, type CheckoutFormData, type CheckoutInput, type CheckoutMode, CheckoutService as CheckoutOperations, type CheckoutOrderType, type CheckoutPaymentMethod, type CheckoutResult, CheckoutService, type CheckoutStep, type ChosenPrice, CimplifyClient, type CimplifyConfig, CimplifyError, type Collection, type CollectionProduct, type CollectionSummary, type ComponentGroup, type ComponentGroupWithComponents, type ComponentPriceBreakdown, type ComponentSelectionInput, type ComponentSourceType, type Composite, type CompositeComponent, type CompositePriceBreakdown, type CompositePriceResult, type CompositePricingMode, type CompositeSelectionData, type ComponentSelectionInput as CompositeSelectionInput, type CompositeStoredSelection, type CompositeWithDetails, type ContactType, type CreateAddressInput, type CreateMobileMoneyInput, type Currency, type Customer, type CustomerAddress, type CustomerLinkPreferences, type CustomerMobileMoney, type CustomerServicePreferences, DEFAULT_COUNTRY, DEFAULT_CURRENCY, type DayAvailability, type DepositResult, type DepositType, type DeviceType, type DigitalProductType, type DiscountBreakdown, type DiscountDetails, type DisplayAddOn, type DisplayAddOnOption, type DisplayCart, type DisplayCartItem, type EnrollAndLinkOrderInput, type EnrollAndLinkOrderResult, type EnrollmentData, type Err, ErrorCode, type ErrorCodeType, type FeeBearerType, type FormatCompactOptions, type FormatPriceOptions, type FulfillmentLink, type FulfillmentStatus, type FulfillmentType, type GetAvailableSlotsInput, type GetOrdersOptions, type GetProductsOptions, type GroupPricingBehavior, type InitializePaymentResult, InventoryService, type InventorySummary, type InventoryType, type KitchenOrderItem, type KitchenOrderResult, LINK_MUTATION, LINK_QUERY, type LineConfiguration, type LineItem, type LineType, type LinkData, type LinkEnrollResult, LinkService, type LinkSession, type LinkStatusResult, type LiteBootstrap, LiteService, type Location, type LocationAppointment, type LocationProductPrice, type LocationStock, type LocationTaxBehavior, type LocationTaxOverrides, type LocationTimeProfile, type LocationWithDetails, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, type MobileMoneyData, type MobileMoneyDetails, type MobileMoneyProvider, type Money, type MutationRequest, ORDER_MUTATION, ORDER_TYPE, type Ok, type Order, type OrderChannel, type OrderFilter, type OrderFulfillmentSummary, type OrderGroup, type OrderGroupDetails, type OrderGroupPayment, type OrderGroupPaymentState, type OrderGroupPaymentSummary, type OrderHistory, type OrderLineState, type OrderLineStatus, type OrderPaymentEvent, OrderQueries, type OrderSplitDetail, type OrderStatus, type OtpResult, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, type Pagination, type PaginationParams, type ParsedPrice, type Payment, type PaymentErrorDetails, type PaymentMethod, type PaymentMethodType, type PaymentProcessingState, type PaymentProvider, type PaymentResponse, type PaymentState, type PaymentStatus, type PaymentStatusResponse, type PickupTime, type PickupTimeType, type Price, type PriceAdjustment, type PriceDecisionPath, type PriceEntryType, type PriceInfo, type PricePathTaxInfo, type PriceSource, type PricingOverrides, type Product, type ProductAddOn, type ProductAvailability, type ProductStock, type ProductTimeProfile, type ProductType, type ProductVariant, type ProductVariantValue, type ProductWithDetails, type ProductWithPrice, QueryBuilder, type QueryRequest, type RefundOrderInput, type ReminderMethod, type ReminderSettings, type RequestOtpInput, type RescheduleBookingInput, type ResourceAssignment, type ResourceAvailabilityException, type ResourceAvailabilityRule, type ResourceType, type ResponseMetadata, type Result, type RevokeAllSessionsResult, type RevokeSessionResult, type Room, type SalesChannel, type SchedulingMetadata, type SchedulingResult, SchedulingService, type SearchOptions, type SelectedAddOnOption, type Service, type ServiceAvailabilityException, type ServiceAvailabilityParams, type ServiceAvailabilityResult, type ServiceAvailabilityRule, type ServiceCharge, type ServiceNotes, type ServiceScheduleRequest, type ServiceStaffRequirement, type ServiceStatus, type ServiceWithStaff, type Staff, type StaffAssignment, type StaffAvailabilityException, type StaffAvailabilityRule, type StaffBookingProfile, type StaffRole, type StaffScheduleItem, type Stock, type StockLevel, type StockOwnershipType, type StockStatus, type StorefrontBootstrap, type SubmitAuthorizationInput, type Table, type TableInfo, type TaxComponent, type TaxInfo, type TaxPathComponent, type TimeRange, type TimeRanges, type TimeSlot, type UICart, type UICartBusiness, type UICartCustomer, type UICartLocation, type UICartPricing, type UpdateAddressInput, type UpdateCartItemInput, type UpdateOrderStatusInput, type UpdateProfileInput, type VariantAxis, type VariantAxisSelection, type VariantAxisValue, type VariantAxisWithValues, type VariantDetails, type VariantDetailsDTO, type VariantDisplayAttribute, type VariantLocationAvailability, type VariantStock, type VariantStrategy, type VerifyOtpInput, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
3533
+ export { AUTHORIZATION_TYPE, AUTH_MUTATION, type AddOn, type AddOnDetails, type AddOnGroupDetails, type AddOnOption, type AddOnOptionDetails, type AddOnOptionPrice, type AddOnWithOptions, type AddToCartInput, type AddressData, type AdjustmentType, type AmountToPay, type ApiError, type ApiResponse, type AppliedDiscount, type AuthResponse, AuthService, type AuthStatus, type AuthorizationType, type AvailabilityCheck, type AvailabilityResult, type AvailableSlot, type BenefitType, type Booking, type BookingRequirementOverride, type BookingStatus, type BookingWithDetails, type BufferTimes, type Bundle, type BundleComponentData, type BundleComponentInfo, type BundlePriceType, type BundleProduct, type BundleSelectionData, type BundleSelectionInput, type BundleStoredSelection, type BundleSummary, type BundleWithDetails, type Business, type BusinessHours, type BusinessPreferences, BusinessService, type BusinessSettings, type BusinessType, type BusinessWithLocations, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, type CancelBookingInput, type CancelOrderInput, type CancellationPolicy, type Cart, type CartAddOn, type CartChannel, type CartItem, type CartItemDetails, CartOperations, type CartStatus, type CartSummary, type CartTotals, CatalogueQueries, type Category, type CategoryInfo, type CategorySummary, type ChangePasswordInput, type CheckSlotAvailabilityInput, type CheckoutAddressInfo, type CheckoutCustomerInfo, type CheckoutFormData, type CheckoutInput, type CheckoutMode, CheckoutService as CheckoutOperations, type CheckoutOrderType, type CheckoutPaymentMethod, type CheckoutResult, CheckoutService, type CheckoutStep, type ChosenPrice, CimplifyClient, type CimplifyConfig, CimplifyError, type Collection, type CollectionProduct, type CollectionSummary, type ComponentGroup, type ComponentGroupWithComponents, type ComponentPriceBreakdown, type ComponentSelectionInput, type ComponentSourceType, type Composite, type CompositeComponent, type CompositePriceBreakdown, type CompositePriceResult, type CompositePricingMode, type CompositeSelectionData, type ComponentSelectionInput as CompositeSelectionInput, type CompositeStoredSelection, type CompositeWithDetails, type ContactType, type CreateAddressInput, type CreateMobileMoneyInput, type Currency, type Customer, type CustomerAddress, type CustomerLinkPreferences, type CustomerMobileMoney, type CustomerServicePreferences, DEFAULT_COUNTRY, DEFAULT_CURRENCY, type DayAvailability, type DepositResult, type DepositType, type DeviceType, type DigitalProductType, type DiscountBreakdown, type DiscountDetails, type DisplayAddOn, type DisplayAddOnOption, type DisplayCart, type DisplayCartItem, type EnrollAndLinkOrderInput, type EnrollAndLinkOrderResult, type EnrollmentData, type Err, ErrorCode, type ErrorCodeType, type FeeBearerType, type FormatCompactOptions, type FormatPriceOptions, type FulfillmentLink, type FulfillmentStatus, type FulfillmentType, type GetAvailableSlotsInput, type GetOrdersOptions, type GetProductsOptions, type GroupPricingBehavior, type InitializePaymentResult, InventoryService, type InventorySummary, type InventoryType, type KitchenOrderItem, type KitchenOrderResult, LINK_MUTATION, LINK_QUERY, type LineConfiguration, type LineItem, type LineType, type LinkData, type LinkEnrollResult, LinkService, type LinkSession, type LinkStatusResult, type LiteBootstrap, LiteService, type Location, type LocationAppointment, type LocationProductPrice, type LocationStock, type LocationTaxBehavior, type LocationTaxOverrides, type LocationTimeProfile, type LocationWithDetails, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, type MobileMoneyData, type MobileMoneyDetails, type MobileMoneyProvider, type Money, type MutationRequest, ORDER_MUTATION, ORDER_TYPE, type ObservabilityHooks, type Ok, type Order, type OrderChannel, type OrderFilter, type OrderFulfillmentSummary, type OrderGroup, type OrderGroupDetails, type OrderGroupPayment, type OrderGroupPaymentState, type OrderGroupPaymentSummary, type OrderHistory, type OrderLineState, type OrderLineStatus, type OrderPaymentEvent, OrderQueries, type OrderSplitDetail, type OrderStatus, type OtpResult, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, type Pagination, type PaginationParams, type ParsedPrice, type Payment, type PaymentErrorDetails, type PaymentMethod, type PaymentMethodType, type PaymentProcessingState, type PaymentProvider, type PaymentResponse, type PaymentState, type PaymentStatus, type PaymentStatusResponse, type PickupTime, type PickupTimeType, type Price, type PriceAdjustment, type PriceDecisionPath, type PriceEntryType, type PriceInfo, type PricePathTaxInfo, type PriceSource, type PricingOverrides, type Product, type ProductAddOn, type ProductAvailability, type ProductStock, type ProductTimeProfile, type ProductType, type ProductVariant, type ProductVariantValue, type ProductWithDetails, type ProductWithPrice, QueryBuilder, type QueryRequest, type RefundOrderInput, type ReminderMethod, type ReminderSettings, type RequestContext, type RequestErrorEvent, type RequestOtpInput, type RequestStartEvent, type RequestSuccessEvent, type RescheduleBookingInput, type ResourceAssignment, type ResourceAvailabilityException, type ResourceAvailabilityRule, type ResourceType, type ResponseMetadata, type Result, type RetryEvent, type RevokeAllSessionsResult, type RevokeSessionResult, type Room, type SalesChannel, type SchedulingMetadata, type SchedulingResult, SchedulingService, type SearchOptions, type SelectedAddOnOption, type Service, type ServiceAvailabilityException, type ServiceAvailabilityParams, type ServiceAvailabilityResult, type ServiceAvailabilityRule, type ServiceCharge, type ServiceNotes, type ServiceScheduleRequest, type ServiceStaffRequirement, type ServiceStatus, type ServiceWithStaff, type SessionChangeEvent, type Staff, type StaffAssignment, type StaffAvailabilityException, type StaffAvailabilityRule, type StaffBookingProfile, type StaffRole, type StaffScheduleItem, type Stock, type StockLevel, type StockOwnershipType, type StockStatus, type StorefrontBootstrap, type SubmitAuthorizationInput, type Table, type TableInfo, type TaxComponent, type TaxInfo, type TaxPathComponent, type TimeRange, type TimeRanges, type TimeSlot, type UICart, type UICartBusiness, type UICartCustomer, type UICartLocation, type UICartPricing, type UpdateAddressInput, type UpdateCartItemInput, type UpdateOrderStatusInput, type UpdateProfileInput, type VariantAxis, type VariantAxisSelection, type VariantAxisValue, type VariantAxisWithValues, type VariantDetails, type VariantDetailsDTO, type VariantDisplayAttribute, type VariantLocationAvailability, type VariantStock, type VariantStrategy, type VerifyOtpInput, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,95 @@
1
+ /**
2
+ * Observability hooks for monitoring SDK behavior.
3
+ *
4
+ * These hooks allow you to plug in your own logging, metrics, and tracing
5
+ * without the SDK depending on any specific observability library.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * const client = createCimplifyClient({
10
+ * hooks: {
11
+ * onRequestStart: ({ method, path }) => {
12
+ * console.log(`[SDK] ${method} ${path}`);
13
+ * },
14
+ * onRequestSuccess: ({ method, path, durationMs }) => {
15
+ * metrics.histogram('sdk.request.duration', durationMs, { method, path });
16
+ * },
17
+ * onRequestError: ({ method, path, error, retryCount }) => {
18
+ * Sentry.captureException(error, { extra: { method, path, retryCount } });
19
+ * },
20
+ * },
21
+ * });
22
+ * ```
23
+ */
24
+ /** Context passed to request lifecycle hooks */
25
+ interface RequestContext {
26
+ /** HTTP method */
27
+ method: "GET" | "POST" | "DELETE";
28
+ /** Request path (e.g., "/api/q", "/api/m") */
29
+ path: string;
30
+ /** Full URL */
31
+ url: string;
32
+ /** Request body (for POST requests) */
33
+ body?: unknown;
34
+ /** Timestamp when request started */
35
+ startTime: number;
36
+ }
37
+ /** Passed when a request starts */
38
+ interface RequestStartEvent extends RequestContext {
39
+ }
40
+ /** Passed when a request succeeds */
41
+ interface RequestSuccessEvent extends RequestContext {
42
+ /** HTTP status code */
43
+ status: number;
44
+ /** Duration in milliseconds */
45
+ durationMs: number;
46
+ }
47
+ /** Passed when a request fails */
48
+ interface RequestErrorEvent extends RequestContext {
49
+ /** The error that occurred */
50
+ error: Error;
51
+ /** Duration in milliseconds */
52
+ durationMs: number;
53
+ /** Number of retries attempted before giving up */
54
+ retryCount: number;
55
+ /** Whether the error is retryable */
56
+ retryable: boolean;
57
+ }
58
+ /** Passed when a retry is about to happen */
59
+ interface RetryEvent extends RequestContext {
60
+ /** Which retry attempt (1, 2, 3...) */
61
+ attempt: number;
62
+ /** Delay before retry in milliseconds */
63
+ delayMs: number;
64
+ /** The error that triggered the retry */
65
+ error: Error;
66
+ }
67
+ /** Passed when session token changes */
68
+ interface SessionChangeEvent {
69
+ /** Previous token (null if none) */
70
+ previousToken: string | null;
71
+ /** New token (null if cleared) */
72
+ newToken: string | null;
73
+ /** Source of the change */
74
+ source: "response" | "manual" | "clear";
75
+ }
76
+ /**
77
+ * Observability hooks configuration.
78
+ * All hooks are optional - only implement what you need.
79
+ */
80
+ interface ObservabilityHooks {
81
+ /** Called when a request is about to be sent */
82
+ onRequestStart?: (event: RequestStartEvent) => void;
83
+ /** Called when a request completes successfully */
84
+ onRequestSuccess?: (event: RequestSuccessEvent) => void;
85
+ /** Called when a request fails (after all retries exhausted) */
86
+ onRequestError?: (event: RequestErrorEvent) => void;
87
+ /** Called before each retry attempt */
88
+ onRetry?: (event: RetryEvent) => void;
89
+ /** Called when session token changes */
90
+ onSessionChange?: (event: SessionChangeEvent) => void;
91
+ }
92
+
1
93
  /** Decimal value represented as string for precision */
2
94
  type Money = string;
3
95
  /** Supported currencies */
@@ -2839,6 +2931,8 @@ interface CimplifyConfig {
2839
2931
  maxRetries?: number;
2840
2932
  /** Base delay between retries in milliseconds (default: 1000) */
2841
2933
  retryDelay?: number;
2934
+ /** Observability hooks for logging, metrics, and tracing */
2935
+ hooks?: ObservabilityHooks;
2842
2936
  }
2843
2937
  declare class CimplifyClient {
2844
2938
  private baseUrl;
@@ -2849,6 +2943,7 @@ declare class CimplifyClient {
2849
2943
  private timeout;
2850
2944
  private maxRetries;
2851
2945
  private retryDelay;
2946
+ private hooks;
2852
2947
  /** In-flight request deduplication map */
2853
2948
  private inflightRequests;
2854
2949
  private _catalogue?;
@@ -2870,7 +2965,7 @@ declare class CimplifyClient {
2870
2965
  private getHeaders;
2871
2966
  private updateSessionFromResponse;
2872
2967
  /**
2873
- * Resilient fetch with timeout and automatic retries for network errors.
2968
+ * Resilient fetch with timeout, automatic retries, and observability hooks.
2874
2969
  * Uses exponential backoff: 1s, 2s, 4s between retries.
2875
2970
  */
2876
2971
  private resilientFetch;
@@ -3435,4 +3530,4 @@ interface ApiResponse<T> {
3435
3530
  metadata?: ResponseMetadata;
3436
3531
  }
3437
3532
 
3438
- export { AUTHORIZATION_TYPE, AUTH_MUTATION, type AddOn, type AddOnDetails, type AddOnGroupDetails, type AddOnOption, type AddOnOptionDetails, type AddOnOptionPrice, type AddOnWithOptions, type AddToCartInput, type AddressData, type AdjustmentType, type AmountToPay, type ApiError, type ApiResponse, type AppliedDiscount, type AuthResponse, AuthService, type AuthStatus, type AuthorizationType, type AvailabilityCheck, type AvailabilityResult, type AvailableSlot, type BenefitType, type Booking, type BookingRequirementOverride, type BookingStatus, type BookingWithDetails, type BufferTimes, type Bundle, type BundleComponentData, type BundleComponentInfo, type BundlePriceType, type BundleProduct, type BundleSelectionData, type BundleSelectionInput, type BundleStoredSelection, type BundleSummary, type BundleWithDetails, type Business, type BusinessHours, type BusinessPreferences, BusinessService, type BusinessSettings, type BusinessType, type BusinessWithLocations, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, type CancelBookingInput, type CancelOrderInput, type CancellationPolicy, type Cart, type CartAddOn, type CartChannel, type CartItem, type CartItemDetails, CartOperations, type CartStatus, type CartSummary, type CartTotals, CatalogueQueries, type Category, type CategoryInfo, type CategorySummary, type ChangePasswordInput, type CheckSlotAvailabilityInput, type CheckoutAddressInfo, type CheckoutCustomerInfo, type CheckoutFormData, type CheckoutInput, type CheckoutMode, CheckoutService as CheckoutOperations, type CheckoutOrderType, type CheckoutPaymentMethod, type CheckoutResult, CheckoutService, type CheckoutStep, type ChosenPrice, CimplifyClient, type CimplifyConfig, CimplifyError, type Collection, type CollectionProduct, type CollectionSummary, type ComponentGroup, type ComponentGroupWithComponents, type ComponentPriceBreakdown, type ComponentSelectionInput, type ComponentSourceType, type Composite, type CompositeComponent, type CompositePriceBreakdown, type CompositePriceResult, type CompositePricingMode, type CompositeSelectionData, type ComponentSelectionInput as CompositeSelectionInput, type CompositeStoredSelection, type CompositeWithDetails, type ContactType, type CreateAddressInput, type CreateMobileMoneyInput, type Currency, type Customer, type CustomerAddress, type CustomerLinkPreferences, type CustomerMobileMoney, type CustomerServicePreferences, DEFAULT_COUNTRY, DEFAULT_CURRENCY, type DayAvailability, type DepositResult, type DepositType, type DeviceType, type DigitalProductType, type DiscountBreakdown, type DiscountDetails, type DisplayAddOn, type DisplayAddOnOption, type DisplayCart, type DisplayCartItem, type EnrollAndLinkOrderInput, type EnrollAndLinkOrderResult, type EnrollmentData, type Err, ErrorCode, type ErrorCodeType, type FeeBearerType, type FormatCompactOptions, type FormatPriceOptions, type FulfillmentLink, type FulfillmentStatus, type FulfillmentType, type GetAvailableSlotsInput, type GetOrdersOptions, type GetProductsOptions, type GroupPricingBehavior, type InitializePaymentResult, InventoryService, type InventorySummary, type InventoryType, type KitchenOrderItem, type KitchenOrderResult, LINK_MUTATION, LINK_QUERY, type LineConfiguration, type LineItem, type LineType, type LinkData, type LinkEnrollResult, LinkService, type LinkSession, type LinkStatusResult, type LiteBootstrap, LiteService, type Location, type LocationAppointment, type LocationProductPrice, type LocationStock, type LocationTaxBehavior, type LocationTaxOverrides, type LocationTimeProfile, type LocationWithDetails, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, type MobileMoneyData, type MobileMoneyDetails, type MobileMoneyProvider, type Money, type MutationRequest, ORDER_MUTATION, ORDER_TYPE, type Ok, type Order, type OrderChannel, type OrderFilter, type OrderFulfillmentSummary, type OrderGroup, type OrderGroupDetails, type OrderGroupPayment, type OrderGroupPaymentState, type OrderGroupPaymentSummary, type OrderHistory, type OrderLineState, type OrderLineStatus, type OrderPaymentEvent, OrderQueries, type OrderSplitDetail, type OrderStatus, type OtpResult, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, type Pagination, type PaginationParams, type ParsedPrice, type Payment, type PaymentErrorDetails, type PaymentMethod, type PaymentMethodType, type PaymentProcessingState, type PaymentProvider, type PaymentResponse, type PaymentState, type PaymentStatus, type PaymentStatusResponse, type PickupTime, type PickupTimeType, type Price, type PriceAdjustment, type PriceDecisionPath, type PriceEntryType, type PriceInfo, type PricePathTaxInfo, type PriceSource, type PricingOverrides, type Product, type ProductAddOn, type ProductAvailability, type ProductStock, type ProductTimeProfile, type ProductType, type ProductVariant, type ProductVariantValue, type ProductWithDetails, type ProductWithPrice, QueryBuilder, type QueryRequest, type RefundOrderInput, type ReminderMethod, type ReminderSettings, type RequestOtpInput, type RescheduleBookingInput, type ResourceAssignment, type ResourceAvailabilityException, type ResourceAvailabilityRule, type ResourceType, type ResponseMetadata, type Result, type RevokeAllSessionsResult, type RevokeSessionResult, type Room, type SalesChannel, type SchedulingMetadata, type SchedulingResult, SchedulingService, type SearchOptions, type SelectedAddOnOption, type Service, type ServiceAvailabilityException, type ServiceAvailabilityParams, type ServiceAvailabilityResult, type ServiceAvailabilityRule, type ServiceCharge, type ServiceNotes, type ServiceScheduleRequest, type ServiceStaffRequirement, type ServiceStatus, type ServiceWithStaff, type Staff, type StaffAssignment, type StaffAvailabilityException, type StaffAvailabilityRule, type StaffBookingProfile, type StaffRole, type StaffScheduleItem, type Stock, type StockLevel, type StockOwnershipType, type StockStatus, type StorefrontBootstrap, type SubmitAuthorizationInput, type Table, type TableInfo, type TaxComponent, type TaxInfo, type TaxPathComponent, type TimeRange, type TimeRanges, type TimeSlot, type UICart, type UICartBusiness, type UICartCustomer, type UICartLocation, type UICartPricing, type UpdateAddressInput, type UpdateCartItemInput, type UpdateOrderStatusInput, type UpdateProfileInput, type VariantAxis, type VariantAxisSelection, type VariantAxisValue, type VariantAxisWithValues, type VariantDetails, type VariantDetailsDTO, type VariantDisplayAttribute, type VariantLocationAvailability, type VariantStock, type VariantStrategy, type VerifyOtpInput, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
3533
+ export { AUTHORIZATION_TYPE, AUTH_MUTATION, type AddOn, type AddOnDetails, type AddOnGroupDetails, type AddOnOption, type AddOnOptionDetails, type AddOnOptionPrice, type AddOnWithOptions, type AddToCartInput, type AddressData, type AdjustmentType, type AmountToPay, type ApiError, type ApiResponse, type AppliedDiscount, type AuthResponse, AuthService, type AuthStatus, type AuthorizationType, type AvailabilityCheck, type AvailabilityResult, type AvailableSlot, type BenefitType, type Booking, type BookingRequirementOverride, type BookingStatus, type BookingWithDetails, type BufferTimes, type Bundle, type BundleComponentData, type BundleComponentInfo, type BundlePriceType, type BundleProduct, type BundleSelectionData, type BundleSelectionInput, type BundleStoredSelection, type BundleSummary, type BundleWithDetails, type Business, type BusinessHours, type BusinessPreferences, BusinessService, type BusinessSettings, type BusinessType, type BusinessWithLocations, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, type CancelBookingInput, type CancelOrderInput, type CancellationPolicy, type Cart, type CartAddOn, type CartChannel, type CartItem, type CartItemDetails, CartOperations, type CartStatus, type CartSummary, type CartTotals, CatalogueQueries, type Category, type CategoryInfo, type CategorySummary, type ChangePasswordInput, type CheckSlotAvailabilityInput, type CheckoutAddressInfo, type CheckoutCustomerInfo, type CheckoutFormData, type CheckoutInput, type CheckoutMode, CheckoutService as CheckoutOperations, type CheckoutOrderType, type CheckoutPaymentMethod, type CheckoutResult, CheckoutService, type CheckoutStep, type ChosenPrice, CimplifyClient, type CimplifyConfig, CimplifyError, type Collection, type CollectionProduct, type CollectionSummary, type ComponentGroup, type ComponentGroupWithComponents, type ComponentPriceBreakdown, type ComponentSelectionInput, type ComponentSourceType, type Composite, type CompositeComponent, type CompositePriceBreakdown, type CompositePriceResult, type CompositePricingMode, type CompositeSelectionData, type ComponentSelectionInput as CompositeSelectionInput, type CompositeStoredSelection, type CompositeWithDetails, type ContactType, type CreateAddressInput, type CreateMobileMoneyInput, type Currency, type Customer, type CustomerAddress, type CustomerLinkPreferences, type CustomerMobileMoney, type CustomerServicePreferences, DEFAULT_COUNTRY, DEFAULT_CURRENCY, type DayAvailability, type DepositResult, type DepositType, type DeviceType, type DigitalProductType, type DiscountBreakdown, type DiscountDetails, type DisplayAddOn, type DisplayAddOnOption, type DisplayCart, type DisplayCartItem, type EnrollAndLinkOrderInput, type EnrollAndLinkOrderResult, type EnrollmentData, type Err, ErrorCode, type ErrorCodeType, type FeeBearerType, type FormatCompactOptions, type FormatPriceOptions, type FulfillmentLink, type FulfillmentStatus, type FulfillmentType, type GetAvailableSlotsInput, type GetOrdersOptions, type GetProductsOptions, type GroupPricingBehavior, type InitializePaymentResult, InventoryService, type InventorySummary, type InventoryType, type KitchenOrderItem, type KitchenOrderResult, LINK_MUTATION, LINK_QUERY, type LineConfiguration, type LineItem, type LineType, type LinkData, type LinkEnrollResult, LinkService, type LinkSession, type LinkStatusResult, type LiteBootstrap, LiteService, type Location, type LocationAppointment, type LocationProductPrice, type LocationStock, type LocationTaxBehavior, type LocationTaxOverrides, type LocationTimeProfile, type LocationWithDetails, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, type MobileMoneyData, type MobileMoneyDetails, type MobileMoneyProvider, type Money, type MutationRequest, ORDER_MUTATION, ORDER_TYPE, type ObservabilityHooks, type Ok, type Order, type OrderChannel, type OrderFilter, type OrderFulfillmentSummary, type OrderGroup, type OrderGroupDetails, type OrderGroupPayment, type OrderGroupPaymentState, type OrderGroupPaymentSummary, type OrderHistory, type OrderLineState, type OrderLineStatus, type OrderPaymentEvent, OrderQueries, type OrderSplitDetail, type OrderStatus, type OtpResult, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, type Pagination, type PaginationParams, type ParsedPrice, type Payment, type PaymentErrorDetails, type PaymentMethod, type PaymentMethodType, type PaymentProcessingState, type PaymentProvider, type PaymentResponse, type PaymentState, type PaymentStatus, type PaymentStatusResponse, type PickupTime, type PickupTimeType, type Price, type PriceAdjustment, type PriceDecisionPath, type PriceEntryType, type PriceInfo, type PricePathTaxInfo, type PriceSource, type PricingOverrides, type Product, type ProductAddOn, type ProductAvailability, type ProductStock, type ProductTimeProfile, type ProductType, type ProductVariant, type ProductVariantValue, type ProductWithDetails, type ProductWithPrice, QueryBuilder, type QueryRequest, type RefundOrderInput, type ReminderMethod, type ReminderSettings, type RequestContext, type RequestErrorEvent, type RequestOtpInput, type RequestStartEvent, type RequestSuccessEvent, type RescheduleBookingInput, type ResourceAssignment, type ResourceAvailabilityException, type ResourceAvailabilityRule, type ResourceType, type ResponseMetadata, type Result, type RetryEvent, type RevokeAllSessionsResult, type RevokeSessionResult, type Room, type SalesChannel, type SchedulingMetadata, type SchedulingResult, SchedulingService, type SearchOptions, type SelectedAddOnOption, type Service, type ServiceAvailabilityException, type ServiceAvailabilityParams, type ServiceAvailabilityResult, type ServiceAvailabilityRule, type ServiceCharge, type ServiceNotes, type ServiceScheduleRequest, type ServiceStaffRequirement, type ServiceStatus, type ServiceWithStaff, type SessionChangeEvent, type Staff, type StaffAssignment, type StaffAvailabilityException, type StaffAvailabilityRule, type StaffBookingProfile, type StaffRole, type StaffScheduleItem, type Stock, type StockLevel, type StockOwnershipType, type StockStatus, type StorefrontBootstrap, type SubmitAuthorizationInput, type Table, type TableInfo, type TaxComponent, type TaxInfo, type TaxPathComponent, type TimeRange, type TimeRanges, type TimeSlot, type UICart, type UICartBusiness, type UICartCustomer, type UICartLocation, type UICartPricing, type UpdateAddressInput, type UpdateCartItemInput, type UpdateOrderStatusInput, type UpdateProfileInput, type VariantAxis, type VariantAxisSelection, type VariantAxisValue, type VariantAxisWithValues, type VariantDetails, type VariantDetailsDTO, type VariantDisplayAttribute, type VariantLocationAvailability, type VariantStock, type VariantStrategy, type VerifyOtpInput, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
package/dist/index.js CHANGED
@@ -1479,18 +1479,31 @@ var CimplifyClient = class {
1479
1479
  this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
1480
1480
  this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
1481
1481
  this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
1482
+ this.hooks = config.hooks ?? {};
1482
1483
  this.sessionToken = this.loadSessionToken();
1483
1484
  }
1484
1485
  getSessionToken() {
1485
1486
  return this.sessionToken;
1486
1487
  }
1487
1488
  setSessionToken(token) {
1489
+ const previous = this.sessionToken;
1488
1490
  this.sessionToken = token;
1489
1491
  this.saveSessionToken(token);
1492
+ this.hooks.onSessionChange?.({
1493
+ previousToken: previous,
1494
+ newToken: token,
1495
+ source: "manual"
1496
+ });
1490
1497
  }
1491
1498
  clearSession() {
1499
+ const previous = this.sessionToken;
1492
1500
  this.sessionToken = null;
1493
1501
  this.saveSessionToken(null);
1502
+ this.hooks.onSessionChange?.({
1503
+ previousToken: previous,
1504
+ newToken: null,
1505
+ source: "clear"
1506
+ });
1494
1507
  }
1495
1508
  loadSessionToken() {
1496
1509
  if (typeof window !== "undefined" && window.localStorage) {
@@ -1520,15 +1533,33 @@ var CimplifyClient = class {
1520
1533
  updateSessionFromResponse(response) {
1521
1534
  const newToken = response.headers.get(SESSION_TOKEN_HEADER);
1522
1535
  if (newToken && newToken !== this.sessionToken) {
1536
+ const previous = this.sessionToken;
1523
1537
  this.sessionToken = newToken;
1524
1538
  this.saveSessionToken(newToken);
1539
+ this.hooks.onSessionChange?.({
1540
+ previousToken: previous,
1541
+ newToken,
1542
+ source: "response"
1543
+ });
1525
1544
  }
1526
1545
  }
1527
1546
  /**
1528
- * Resilient fetch with timeout and automatic retries for network errors.
1547
+ * Resilient fetch with timeout, automatic retries, and observability hooks.
1529
1548
  * Uses exponential backoff: 1s, 2s, 4s between retries.
1530
1549
  */
1531
1550
  async resilientFetch(url, options) {
1551
+ const method = options.method || "GET";
1552
+ const path = url.replace(this.baseUrl, "").replace(this.linkApiUrl, "");
1553
+ const startTime = Date.now();
1554
+ let retryCount = 0;
1555
+ const context = {
1556
+ method,
1557
+ path,
1558
+ url,
1559
+ body: options.body ? JSON.parse(options.body) : void 0,
1560
+ startTime
1561
+ };
1562
+ this.hooks.onRequestStart?.(context);
1532
1563
  let lastError;
1533
1564
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1534
1565
  try {
@@ -1540,24 +1571,65 @@ var CimplifyClient = class {
1540
1571
  });
1541
1572
  clearTimeout(timeoutId);
1542
1573
  if (response.ok || response.status >= 400 && response.status < 500) {
1574
+ this.hooks.onRequestSuccess?.({
1575
+ ...context,
1576
+ status: response.status,
1577
+ durationMs: Date.now() - startTime
1578
+ });
1543
1579
  return response;
1544
1580
  }
1545
1581
  if (response.status >= 500 && attempt < this.maxRetries) {
1582
+ retryCount++;
1546
1583
  const delay = this.retryDelay * Math.pow(2, attempt);
1584
+ this.hooks.onRetry?.({
1585
+ ...context,
1586
+ attempt: retryCount,
1587
+ delayMs: delay,
1588
+ error: new Error(`Server error: ${response.status}`)
1589
+ });
1547
1590
  await sleep(delay);
1548
1591
  continue;
1549
1592
  }
1593
+ this.hooks.onRequestSuccess?.({
1594
+ ...context,
1595
+ status: response.status,
1596
+ durationMs: Date.now() - startTime
1597
+ });
1550
1598
  return response;
1551
1599
  } catch (error) {
1552
1600
  lastError = error;
1553
- if (!isRetryable(error) || attempt >= this.maxRetries) {
1554
- throw toNetworkError(error);
1601
+ const networkError = toNetworkError(error);
1602
+ const errorRetryable = isRetryable(error);
1603
+ if (!errorRetryable || attempt >= this.maxRetries) {
1604
+ this.hooks.onRequestError?.({
1605
+ ...context,
1606
+ error: networkError,
1607
+ durationMs: Date.now() - startTime,
1608
+ retryCount,
1609
+ retryable: errorRetryable
1610
+ });
1611
+ throw networkError;
1555
1612
  }
1613
+ retryCount++;
1556
1614
  const delay = this.retryDelay * Math.pow(2, attempt);
1615
+ this.hooks.onRetry?.({
1616
+ ...context,
1617
+ attempt: retryCount,
1618
+ delayMs: delay,
1619
+ error: networkError
1620
+ });
1557
1621
  await sleep(delay);
1558
1622
  }
1559
1623
  }
1560
- throw toNetworkError(lastError);
1624
+ const finalError = toNetworkError(lastError);
1625
+ this.hooks.onRequestError?.({
1626
+ ...context,
1627
+ error: finalError,
1628
+ durationMs: Date.now() - startTime,
1629
+ retryCount,
1630
+ retryable: false
1631
+ });
1632
+ throw finalError;
1561
1633
  }
1562
1634
  /**
1563
1635
  * Generate a deduplication key for a request.
package/dist/index.mjs CHANGED
@@ -1477,18 +1477,31 @@ var CimplifyClient = class {
1477
1477
  this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
1478
1478
  this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
1479
1479
  this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
1480
+ this.hooks = config.hooks ?? {};
1480
1481
  this.sessionToken = this.loadSessionToken();
1481
1482
  }
1482
1483
  getSessionToken() {
1483
1484
  return this.sessionToken;
1484
1485
  }
1485
1486
  setSessionToken(token) {
1487
+ const previous = this.sessionToken;
1486
1488
  this.sessionToken = token;
1487
1489
  this.saveSessionToken(token);
1490
+ this.hooks.onSessionChange?.({
1491
+ previousToken: previous,
1492
+ newToken: token,
1493
+ source: "manual"
1494
+ });
1488
1495
  }
1489
1496
  clearSession() {
1497
+ const previous = this.sessionToken;
1490
1498
  this.sessionToken = null;
1491
1499
  this.saveSessionToken(null);
1500
+ this.hooks.onSessionChange?.({
1501
+ previousToken: previous,
1502
+ newToken: null,
1503
+ source: "clear"
1504
+ });
1492
1505
  }
1493
1506
  loadSessionToken() {
1494
1507
  if (typeof window !== "undefined" && window.localStorage) {
@@ -1518,15 +1531,33 @@ var CimplifyClient = class {
1518
1531
  updateSessionFromResponse(response) {
1519
1532
  const newToken = response.headers.get(SESSION_TOKEN_HEADER);
1520
1533
  if (newToken && newToken !== this.sessionToken) {
1534
+ const previous = this.sessionToken;
1521
1535
  this.sessionToken = newToken;
1522
1536
  this.saveSessionToken(newToken);
1537
+ this.hooks.onSessionChange?.({
1538
+ previousToken: previous,
1539
+ newToken,
1540
+ source: "response"
1541
+ });
1523
1542
  }
1524
1543
  }
1525
1544
  /**
1526
- * Resilient fetch with timeout and automatic retries for network errors.
1545
+ * Resilient fetch with timeout, automatic retries, and observability hooks.
1527
1546
  * Uses exponential backoff: 1s, 2s, 4s between retries.
1528
1547
  */
1529
1548
  async resilientFetch(url, options) {
1549
+ const method = options.method || "GET";
1550
+ const path = url.replace(this.baseUrl, "").replace(this.linkApiUrl, "");
1551
+ const startTime = Date.now();
1552
+ let retryCount = 0;
1553
+ const context = {
1554
+ method,
1555
+ path,
1556
+ url,
1557
+ body: options.body ? JSON.parse(options.body) : void 0,
1558
+ startTime
1559
+ };
1560
+ this.hooks.onRequestStart?.(context);
1530
1561
  let lastError;
1531
1562
  for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1532
1563
  try {
@@ -1538,24 +1569,65 @@ var CimplifyClient = class {
1538
1569
  });
1539
1570
  clearTimeout(timeoutId);
1540
1571
  if (response.ok || response.status >= 400 && response.status < 500) {
1572
+ this.hooks.onRequestSuccess?.({
1573
+ ...context,
1574
+ status: response.status,
1575
+ durationMs: Date.now() - startTime
1576
+ });
1541
1577
  return response;
1542
1578
  }
1543
1579
  if (response.status >= 500 && attempt < this.maxRetries) {
1580
+ retryCount++;
1544
1581
  const delay = this.retryDelay * Math.pow(2, attempt);
1582
+ this.hooks.onRetry?.({
1583
+ ...context,
1584
+ attempt: retryCount,
1585
+ delayMs: delay,
1586
+ error: new Error(`Server error: ${response.status}`)
1587
+ });
1545
1588
  await sleep(delay);
1546
1589
  continue;
1547
1590
  }
1591
+ this.hooks.onRequestSuccess?.({
1592
+ ...context,
1593
+ status: response.status,
1594
+ durationMs: Date.now() - startTime
1595
+ });
1548
1596
  return response;
1549
1597
  } catch (error) {
1550
1598
  lastError = error;
1551
- if (!isRetryable(error) || attempt >= this.maxRetries) {
1552
- throw toNetworkError(error);
1599
+ const networkError = toNetworkError(error);
1600
+ const errorRetryable = isRetryable(error);
1601
+ if (!errorRetryable || attempt >= this.maxRetries) {
1602
+ this.hooks.onRequestError?.({
1603
+ ...context,
1604
+ error: networkError,
1605
+ durationMs: Date.now() - startTime,
1606
+ retryCount,
1607
+ retryable: errorRetryable
1608
+ });
1609
+ throw networkError;
1553
1610
  }
1611
+ retryCount++;
1554
1612
  const delay = this.retryDelay * Math.pow(2, attempt);
1613
+ this.hooks.onRetry?.({
1614
+ ...context,
1615
+ attempt: retryCount,
1616
+ delayMs: delay,
1617
+ error: networkError
1618
+ });
1555
1619
  await sleep(delay);
1556
1620
  }
1557
1621
  }
1558
- throw toNetworkError(lastError);
1622
+ const finalError = toNetworkError(lastError);
1623
+ this.hooks.onRequestError?.({
1624
+ ...context,
1625
+ error: finalError,
1626
+ durationMs: Date.now() - startTime,
1627
+ retryCount,
1628
+ retryable: false
1629
+ });
1630
+ throw finalError;
1559
1631
  }
1560
1632
  /**
1561
1633
  * Generate a deduplication key for a request.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cimplify/sdk",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
4
4
  "description": "Cimplify Commerce SDK for storefronts",
5
5
  "keywords": [
6
6
  "cimplify",