@commercelayer/sdk 6.0.0-alfa.3 → 6.0.0-alfa.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/lib/esm/client.js CHANGED
@@ -1,9 +1,6 @@
1
- import axios from 'axios';
2
1
  import { SdkError, handleError } from './error';
3
2
  import config from './config';
4
- // import type { Agent as HttpAgent } from 'http'
5
- // import type { Agent as HttpsAgent } from 'https'
6
- // import { packageInfo } from './util'
3
+ import { fetchURL } from './fetch';
7
4
  import Debug from './debug';
8
5
  const debug = Debug('client');
9
6
  const baseURL = (organization, domain) => {
@@ -16,19 +13,18 @@ class ApiClient {
16
13
  throw new SdkError({ message: `Undefined '${attr}' parameter` });
17
14
  return new ApiClient(options);
18
15
  }
19
- baseUrl;
16
+ #baseUrl;
20
17
  #accessToken;
21
- #client;
22
- interceptors;
18
+ #clientConfig;
19
+ #interceptors;
23
20
  constructor(options) {
24
21
  debug('new client instance %O', options);
25
- this.baseUrl = baseURL(options.organization, options.domain);
22
+ this.#baseUrl = baseURL(options.organization, options.domain);
26
23
  this.#accessToken = options.accessToken;
27
- const axiosConfig = {
24
+ const fetchConfig = {
28
25
  timeout: options.timeout || config.client.timeout,
29
- proxy: options.proxy,
30
- httpAgent: options.httpAgent,
31
- httpsAgent: options.httpsAgent
26
+ // httpAgent: options.httpAgent,
27
+ // httpsAgent: options.httpsAgent
32
28
  };
33
29
  // Set custom headers
34
30
  const customHeaders = this.customHeaders(options.headers);
@@ -40,90 +36,81 @@ class ApiClient {
40
36
  'Authorization': 'Bearer ' + this.#accessToken
41
37
  };
42
38
  // Set User-Agent
43
- let userAgent = options.userAgent; // || `SDK-core axios/${axios.VERSION}`
44
- if (userAgent) {
45
- if (!userAgent.includes('axios/'))
46
- userAgent += ` axios/${axios.VERSION}`;
39
+ const userAgent = options.userAgent;
40
+ if (userAgent)
47
41
  headers['User-Agent'] = userAgent;
48
- }
49
- const axiosOptions = {
50
- baseURL: this.baseUrl,
51
- timeout: config.client.timeout,
52
- headers,
53
- ...axiosConfig
54
- };
55
- if (options.adapter)
56
- axiosOptions.adapter = options.adapter;
57
- debug('axios options: %O', axiosOptions);
58
- this.#client = axios.create(axiosOptions);
59
- this.interceptors = this.#client.interceptors;
42
+ fetchConfig.headers = headers;
43
+ this.#clientConfig = fetchConfig;
44
+ debug('fetch config: %O', fetchConfig);
45
+ // Interceptors
46
+ this.#interceptors = {};
47
+ }
48
+ get interceptors() { return this.#interceptors; }
49
+ get requestHeaders() {
50
+ if (!this.#clientConfig.headers)
51
+ this.#clientConfig.headers = {};
52
+ return this.#clientConfig.headers;
53
+ }
54
+ /*
55
+ set requestHeaders(headers: RequestHeaders) {
56
+ this.#clientConfig.headers = { ...this.#clientConfig.headers, ...headers }
60
57
  }
58
+ */
61
59
  config(config) {
62
60
  debug('config %o', config);
63
- const def = this.#client.defaults;
64
- // Axios config
61
+ const def = this.#clientConfig;
62
+ if (!def.headers)
63
+ def.headers = {};
64
+ // Client config
65
65
  if (config.timeout)
66
66
  def.timeout = config.timeout;
67
- if (config.proxy)
68
- def.proxy = config.proxy;
69
- if (config.httpAgent)
70
- def.httpAgent = config.httpAgent;
71
- if (config.httpsAgent)
72
- def.httpsAgent = config.httpsAgent;
73
- if (config.adapter)
74
- this.adapter(config.adapter);
67
+ // if (config.httpAgent) def.httpAgent = config.httpAgent
68
+ // if (config.httpsAgent) def.httpsAgent = config.httpsAgent
75
69
  if (config.userAgent)
76
70
  this.userAgent(config.userAgent);
77
71
  // API Client config
78
72
  if (config.organization)
79
- this.baseUrl = baseURL(config.organization, config.domain);
73
+ this.#baseUrl = baseURL(config.organization, config.domain);
80
74
  if (config.accessToken) {
81
75
  this.#accessToken = config.accessToken;
82
- def.headers.common.Authorization = 'Bearer ' + this.#accessToken;
76
+ def.headers.Authorization = 'Bearer ' + this.#accessToken;
83
77
  }
84
78
  if (config.headers)
85
- def.headers.common = this.customHeaders(config.headers);
79
+ def.headers = { ...def.headers, ...this.customHeaders(config.headers) };
86
80
  return this;
87
81
  }
88
82
  userAgent(userAgent) {
89
- if (userAgent) {
90
- let ua = userAgent;
91
- if (!ua.includes('axios/')) {
92
- // const axiosVer = packageInfo(['dependencies.axios'], { nestedName: true })
93
- if (axios.VERSION)
94
- ua += ` axios/${axios.VERSION}`;
95
- }
96
- this.#client.defaults.headers['User-Agent'] = ua;
97
- }
98
- return this;
99
- }
100
- adapter(adapter) {
101
- if (adapter)
102
- this.#client.defaults.adapter = adapter;
83
+ if (userAgent)
84
+ this.requestHeaders['User-Agent'] = userAgent;
103
85
  return this;
104
86
  }
105
87
  async request(method, path, body, options) {
106
88
  debug('request %s %s, %O, %O', method, path, body || {}, options || {});
107
- // Ignored params alerts (in debug mode)
108
- if (options?.adapter)
109
- debug('Adapter ignored in request config');
89
+ // Ignored params (in debug mode)
110
90
  if (options?.userAgent)
111
91
  debug('User-Agent header ignored in request config');
112
- const data = body ? { data: body } : undefined;
113
- const url = path;
114
- // Runtime request parameters
115
- const baseUrl = options?.organization ? baseURL(options.organization, options.domain) : undefined;
92
+ // URL
93
+ const baseUrl = options?.organization ? baseURL(options.organization, options.domain) : this.#baseUrl;
94
+ const url = new URL(`${baseUrl}/${path}`);
95
+ // Body
96
+ const bodyData = body ? JSON.stringify({ data: body }) : undefined;
97
+ // Headers
98
+ const headers = { ...this.requestHeaders, ...this.customHeaders(options?.headers) };
99
+ // Access token
116
100
  const accessToken = options?.accessToken || this.#accessToken;
117
- const headers = this.customHeaders(options?.headers);
118
101
  if (accessToken)
119
102
  headers.Authorization = 'Bearer ' + accessToken;
120
- const requestParams = { method, baseURL: baseUrl, url, data, ...options, headers };
121
- debug('request params: %O', requestParams);
103
+ const fetchOptions = { method, body: bodyData, headers };
104
+ // Timeout
105
+ const timeout = options?.timeout || this.#clientConfig.timeout;
106
+ if (timeout)
107
+ fetchOptions.signal = AbortSignal.timeout(timeout);
108
+ if (options?.params)
109
+ Object.entries(options?.params).forEach(([name, value]) => { url.searchParams.append(name, String(value)); });
122
110
  // const start = Date.now()
123
- return this.#client.request(requestParams)
124
- .then(response => response.data)
111
+ return await fetchURL(url, fetchOptions, this.interceptors)
125
112
  .catch((error) => handleError(error));
126
- // .finally(() => console.log(`<<-- ${method} ${path} ${Date.now() - start}`))
113
+ // .finally(() => { console.log(`<<-- ${method} ${path} ${Date.now() - start}`) })
127
114
  }
128
115
  customHeaders(headers) {
129
116
  const customHeaders = {};
@@ -10,142 +10,143 @@ type CommerceLayerConfig = Partial<CommerceLayerInitConfig>;
10
10
  declare class CommerceLayerClient {
11
11
  #private;
12
12
  readonly openApiSchemaVersion = "5.1.0";
13
- addresses: api.Addresses;
14
- adjustments: api.Adjustments;
15
- adyen_gateways: api.AdyenGateways;
16
- adyen_payments: api.AdyenPayments;
17
- application: api.Applications;
18
- attachments: api.Attachments;
19
- authorizations: api.Authorizations;
20
- avalara_accounts: api.AvalaraAccounts;
21
- axerve_gateways: api.AxerveGateways;
22
- axerve_payments: api.AxervePayments;
23
- billing_info_validation_rules: api.BillingInfoValidationRules;
24
- bing_geocoders: api.BingGeocoders;
25
- braintree_gateways: api.BraintreeGateways;
26
- braintree_payments: api.BraintreePayments;
27
- bundles: api.Bundles;
28
- buy_x_pay_y_promotions: api.BuyXPayYPromotions;
29
- captures: api.Captures;
30
- carrier_accounts: api.CarrierAccounts;
31
- checkout_com_gateways: api.CheckoutComGateways;
32
- checkout_com_payments: api.CheckoutComPayments;
33
- cleanups: api.Cleanups;
34
- coupon_codes_promotion_rules: api.CouponCodesPromotionRules;
35
- coupon_recipients: api.CouponRecipients;
36
- coupons: api.Coupons;
37
- custom_promotion_rules: api.CustomPromotionRules;
38
- customer_addresses: api.CustomerAddresses;
39
- customer_groups: api.CustomerGroups;
40
- customer_password_resets: api.CustomerPasswordResets;
41
- customer_payment_sources: api.CustomerPaymentSources;
42
- customer_subscriptions: api.CustomerSubscriptions;
43
- customers: api.Customers;
44
- delivery_lead_times: api.DeliveryLeadTimes;
45
- event_callbacks: api.EventCallbacks;
46
- events: api.Events;
47
- exports: api.Exports;
48
- external_gateways: api.ExternalGateways;
49
- external_payments: api.ExternalPayments;
50
- external_promotions: api.ExternalPromotions;
51
- external_tax_calculators: api.ExternalTaxCalculators;
52
- fixed_amount_promotions: api.FixedAmountPromotions;
53
- fixed_price_promotions: api.FixedPricePromotions;
54
- free_gift_promotions: api.FreeGiftPromotions;
55
- free_shipping_promotions: api.FreeShippingPromotions;
56
- geocoders: api.Geocoders;
57
- gift_card_recipients: api.GiftCardRecipients;
58
- gift_cards: api.GiftCards;
59
- google_geocoders: api.GoogleGeocoders;
60
- imports: api.Imports;
61
- in_stock_subscriptions: api.InStockSubscriptions;
62
- inventory_models: api.InventoryModels;
63
- inventory_return_locations: api.InventoryReturnLocations;
64
- inventory_stock_locations: api.InventoryStockLocations;
65
- klarna_gateways: api.KlarnaGateways;
66
- klarna_payments: api.KlarnaPayments;
67
- line_item_options: api.LineItemOptions;
68
- line_items: api.LineItems;
69
- manual_gateways: api.ManualGateways;
70
- manual_tax_calculators: api.ManualTaxCalculators;
71
- markets: api.Markets;
72
- merchants: api.Merchants;
73
- order_amount_promotion_rules: api.OrderAmountPromotionRules;
74
- order_copies: api.OrderCopies;
75
- order_factories: api.OrderFactories;
76
- order_subscription_items: api.OrderSubscriptionItems;
77
- order_subscriptions: api.OrderSubscriptions;
78
- order_validation_rules: api.OrderValidationRules;
79
- orders: api.Orders;
80
- organization: api.Organizations;
81
- packages: api.Packages;
82
- parcel_line_items: api.ParcelLineItems;
83
- parcels: api.Parcels;
84
- payment_gateways: api.PaymentGateways;
85
- payment_methods: api.PaymentMethods;
86
- payment_options: api.PaymentOptions;
87
- paypal_gateways: api.PaypalGateways;
88
- paypal_payments: api.PaypalPayments;
89
- percentage_discount_promotions: api.PercentageDiscountPromotions;
90
- price_frequency_tiers: api.PriceFrequencyTiers;
91
- price_lists: api.PriceLists;
92
- price_tiers: api.PriceTiers;
93
- price_volume_tiers: api.PriceVolumeTiers;
94
- prices: api.Prices;
95
- promotion_rules: api.PromotionRules;
96
- promotions: api.Promotions;
97
- recurring_order_copies: api.RecurringOrderCopies;
98
- refunds: api.Refunds;
99
- reserved_stocks: api.ReservedStocks;
100
- resource_errors: api.ResourceErrors;
101
- return_line_items: api.ReturnLineItems;
102
- returns: api.Returns;
103
- satispay_gateways: api.SatispayGateways;
104
- satispay_payments: api.SatispayPayments;
105
- shipments: api.Shipments;
106
- shipping_categories: api.ShippingCategories;
107
- shipping_method_tiers: api.ShippingMethodTiers;
108
- shipping_methods: api.ShippingMethods;
109
- shipping_weight_tiers: api.ShippingWeightTiers;
110
- shipping_zones: api.ShippingZones;
111
- sku_list_items: api.SkuListItems;
112
- sku_list_promotion_rules: api.SkuListPromotionRules;
113
- sku_lists: api.SkuLists;
114
- sku_options: api.SkuOptions;
115
- skus: api.Skus;
116
- stock_items: api.StockItems;
117
- stock_line_items: api.StockLineItems;
118
- stock_locations: api.StockLocations;
119
- stock_reservations: api.StockReservations;
120
- stock_transfers: api.StockTransfers;
121
- stripe_gateways: api.StripeGateways;
122
- stripe_payments: api.StripePayments;
123
- subscription_models: api.SubscriptionModels;
124
- tags: api.Tags;
125
- tax_calculators: api.TaxCalculators;
126
- tax_categories: api.TaxCategories;
127
- tax_rules: api.TaxRules;
128
- taxjar_accounts: api.TaxjarAccounts;
129
- transactions: api.Transactions;
130
- versions: api.Versions;
131
- voids: api.Voids;
132
- webhooks: api.Webhooks;
133
- wire_transfers: api.WireTransfers;
134
13
  constructor(config: CommerceLayerInitConfig);
14
+ get addresses(): api.Addresses;
15
+ get adjustments(): api.Adjustments;
16
+ get adyen_gateways(): api.AdyenGateways;
17
+ get adyen_payments(): api.AdyenPayments;
18
+ get application(): api.Applications;
19
+ get attachments(): api.Attachments;
20
+ get authorizations(): api.Authorizations;
21
+ get avalara_accounts(): api.AvalaraAccounts;
22
+ get axerve_gateways(): api.AxerveGateways;
23
+ get axerve_payments(): api.AxervePayments;
24
+ get billing_info_validation_rules(): api.BillingInfoValidationRules;
25
+ get bing_geocoders(): api.BingGeocoders;
26
+ get braintree_gateways(): api.BraintreeGateways;
27
+ get braintree_payments(): api.BraintreePayments;
28
+ get bundles(): api.Bundles;
29
+ get buy_x_pay_y_promotions(): api.BuyXPayYPromotions;
30
+ get captures(): api.Captures;
31
+ get carrier_accounts(): api.CarrierAccounts;
32
+ get checkout_com_gateways(): api.CheckoutComGateways;
33
+ get checkout_com_payments(): api.CheckoutComPayments;
34
+ get cleanups(): api.Cleanups;
35
+ get coupon_codes_promotion_rules(): api.CouponCodesPromotionRules;
36
+ get coupon_recipients(): api.CouponRecipients;
37
+ get coupons(): api.Coupons;
38
+ get custom_promotion_rules(): api.CustomPromotionRules;
39
+ get customer_addresses(): api.CustomerAddresses;
40
+ get customer_groups(): api.CustomerGroups;
41
+ get customer_password_resets(): api.CustomerPasswordResets;
42
+ get customer_payment_sources(): api.CustomerPaymentSources;
43
+ get customer_subscriptions(): api.CustomerSubscriptions;
44
+ get customers(): api.Customers;
45
+ get delivery_lead_times(): api.DeliveryLeadTimes;
46
+ get event_callbacks(): api.EventCallbacks;
47
+ get events(): api.Events;
48
+ get exports(): api.Exports;
49
+ get external_gateways(): api.ExternalGateways;
50
+ get external_payments(): api.ExternalPayments;
51
+ get external_promotions(): api.ExternalPromotions;
52
+ get external_tax_calculators(): api.ExternalTaxCalculators;
53
+ get fixed_amount_promotions(): api.FixedAmountPromotions;
54
+ get fixed_price_promotions(): api.FixedPricePromotions;
55
+ get free_gift_promotions(): api.FreeGiftPromotions;
56
+ get free_shipping_promotions(): api.FreeShippingPromotions;
57
+ get geocoders(): api.Geocoders;
58
+ get gift_card_recipients(): api.GiftCardRecipients;
59
+ get gift_cards(): api.GiftCards;
60
+ get google_geocoders(): api.GoogleGeocoders;
61
+ get imports(): api.Imports;
62
+ get in_stock_subscriptions(): api.InStockSubscriptions;
63
+ get inventory_models(): api.InventoryModels;
64
+ get inventory_return_locations(): api.InventoryReturnLocations;
65
+ get inventory_stock_locations(): api.InventoryStockLocations;
66
+ get klarna_gateways(): api.KlarnaGateways;
67
+ get klarna_payments(): api.KlarnaPayments;
68
+ get line_item_options(): api.LineItemOptions;
69
+ get line_items(): api.LineItems;
70
+ get manual_gateways(): api.ManualGateways;
71
+ get manual_tax_calculators(): api.ManualTaxCalculators;
72
+ get markets(): api.Markets;
73
+ get merchants(): api.Merchants;
74
+ get order_amount_promotion_rules(): api.OrderAmountPromotionRules;
75
+ get order_copies(): api.OrderCopies;
76
+ get order_factories(): api.OrderFactories;
77
+ get order_subscription_items(): api.OrderSubscriptionItems;
78
+ get order_subscriptions(): api.OrderSubscriptions;
79
+ get order_validation_rules(): api.OrderValidationRules;
80
+ get orders(): api.Orders;
81
+ get organization(): api.Organizations;
82
+ get packages(): api.Packages;
83
+ get parcel_line_items(): api.ParcelLineItems;
84
+ get parcels(): api.Parcels;
85
+ get payment_gateways(): api.PaymentGateways;
86
+ get payment_methods(): api.PaymentMethods;
87
+ get payment_options(): api.PaymentOptions;
88
+ get paypal_gateways(): api.PaypalGateways;
89
+ get paypal_payments(): api.PaypalPayments;
90
+ get percentage_discount_promotions(): api.PercentageDiscountPromotions;
91
+ get price_frequency_tiers(): api.PriceFrequencyTiers;
92
+ get price_lists(): api.PriceLists;
93
+ get price_tiers(): api.PriceTiers;
94
+ get price_volume_tiers(): api.PriceVolumeTiers;
95
+ get prices(): api.Prices;
96
+ get promotion_rules(): api.PromotionRules;
97
+ get promotions(): api.Promotions;
98
+ get recurring_order_copies(): api.RecurringOrderCopies;
99
+ get refunds(): api.Refunds;
100
+ get reserved_stocks(): api.ReservedStocks;
101
+ get resource_errors(): api.ResourceErrors;
102
+ get return_line_items(): api.ReturnLineItems;
103
+ get returns(): api.Returns;
104
+ get satispay_gateways(): api.SatispayGateways;
105
+ get satispay_payments(): api.SatispayPayments;
106
+ get shipments(): api.Shipments;
107
+ get shipping_categories(): api.ShippingCategories;
108
+ get shipping_method_tiers(): api.ShippingMethodTiers;
109
+ get shipping_methods(): api.ShippingMethods;
110
+ get shipping_weight_tiers(): api.ShippingWeightTiers;
111
+ get shipping_zones(): api.ShippingZones;
112
+ get sku_list_items(): api.SkuListItems;
113
+ get sku_list_promotion_rules(): api.SkuListPromotionRules;
114
+ get sku_lists(): api.SkuLists;
115
+ get sku_options(): api.SkuOptions;
116
+ get skus(): api.Skus;
117
+ get stock_items(): api.StockItems;
118
+ get stock_line_items(): api.StockLineItems;
119
+ get stock_locations(): api.StockLocations;
120
+ get stock_reservations(): api.StockReservations;
121
+ get stock_transfers(): api.StockTransfers;
122
+ get stripe_gateways(): api.StripeGateways;
123
+ get stripe_payments(): api.StripePayments;
124
+ get subscription_models(): api.SubscriptionModels;
125
+ get tags(): api.Tags;
126
+ get tax_calculators(): api.TaxCalculators;
127
+ get tax_categories(): api.TaxCategories;
128
+ get tax_rules(): api.TaxRules;
129
+ get taxjar_accounts(): api.TaxjarAccounts;
130
+ get transactions(): api.Transactions;
131
+ get versions(): api.Versions;
132
+ get voids(): api.Voids;
133
+ get webhooks(): api.Webhooks;
134
+ get wire_transfers(): api.WireTransfers;
135
135
  get currentOrganization(): string;
136
+ private get interceptors();
136
137
  private localConfig;
137
138
  config(config: CommerceLayerConfig): CommerceLayerClient;
138
139
  resources(): readonly string[];
139
140
  singletons(): readonly string[];
140
141
  isSingleton(resource: api.ResourceTypeLock): boolean;
141
142
  isApiError(error: any): error is ApiError;
142
- addRequestInterceptor(onFulfilled?: RequestInterceptor, onRejected?: ErrorInterceptor): number;
143
- addResponseInterceptor(onFulfilled?: ResponseInterceptor, onRejected?: ErrorInterceptor): number;
144
- removeInterceptor(type: InterceptorType, id: number): void;
143
+ addRequestInterceptor(onSuccess?: RequestInterceptor, onFailure?: ErrorInterceptor): void;
144
+ addResponseInterceptor(onSuccess?: ResponseInterceptor, onFailure?: ErrorInterceptor): void;
145
+ removeInterceptor(type: InterceptorType, id?: number): void;
145
146
  addRawResponseReader(options?: {
146
147
  headers: boolean;
147
148
  }): RawResponseReader;
148
- removeRawResponseReader(reader: number | RawResponseReader): void;
149
+ removeRawResponseReader(): void;
149
150
  }
150
151
  declare const CommerceLayer: (config: CommerceLayerInitConfig) => CommerceLayerClient;
151
152
  export default CommerceLayer;