pathao-merchant-sdk 2.0.1 → 2.0.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/CHANGELOG.md CHANGED
@@ -13,6 +13,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [2.0.2] - 2025-12-08
17
+
18
+ ### Added
19
+ - **Factory methods**: `PathaoApiService.fromEnv()` and `PathaoApiService.fromConfig()` for convenient initialization patterns
20
+ - **Debug logging**: Optional `debug` flag in constructor options to log all HTTP requests and responses
21
+ - **Configurable circuit breaker**: `circuitBreaker` option to customize failure threshold and timeout
22
+ - **Comprehensive error handling examples** in README with `PathaoApiError` usage patterns
23
+ - **Advanced options documentation** for factory methods and configuration
24
+
25
+ ### Changed
26
+ - **Breaking**: Deferred configuration validation to first API call instead of constructor throw. SDK now initializes successfully even without credentials, and throws `PathaoApiError` when attempting an API call with missing config.
27
+ - Removed config duplication in constructor (axios create config now uses resolved config values).
28
+ - Constructor now accepts optional `options` parameter: `new PathaoApiService(config, { debug?, circuitBreaker? })`
29
+ - Constructor no longer throws upfront, allowing graceful error handling at first API usage.
30
+
31
+ ### Fixed
32
+ - `ResolvedPathaoConfig` internal type ensures `timeout` is always a number.
33
+ - Tests updated to reflect deferred validation behavior.
34
+ - Circuit breaker now properly resets on successful requests and maintains configurable thresholds.
35
+
36
+ ### Verified
37
+ - `npm test` passes with 22/22 tests.
38
+ - Build succeeds (CJS/ESM/DTS).
39
+
16
40
  ## [2.0.1] - 2025-12-05
17
41
 
18
42
  ### Changed
package/README.md CHANGED
@@ -164,6 +164,56 @@ const pathao = new PathaoApiService({
164
164
  });
165
165
  ```
166
166
 
167
+ #### Factory Methods
168
+
169
+ The SDK provides convenient factory methods for common initialization patterns:
170
+
171
+ ```typescript
172
+ // Create from environment variables
173
+ const pathao = PathaoApiService.fromEnv();
174
+
175
+ // Create from environment with additional options
176
+ const pathao = PathaoApiService.fromEnv({
177
+ debug: true, // Enable debug logging
178
+ circuitBreaker: {
179
+ threshold: 10, // Number of failures before opening circuit (default: 5)
180
+ timeout: 120000 // Timeout before attempting to close circuit (default: 60000ms)
181
+ }
182
+ });
183
+
184
+ // Create from explicit config
185
+ const pathao = PathaoApiService.fromConfig({
186
+ baseURL: 'https://api-hermes.pathao.com',
187
+ clientId: 'client-id',
188
+ clientSecret: 'client-secret',
189
+ username: 'username',
190
+ password: 'password',
191
+ timeout: 5000
192
+ }, {
193
+ debug: true,
194
+ circuitBreaker: { threshold: 8 }
195
+ });
196
+ ```
197
+
198
+ #### Advanced Options
199
+
200
+ ```typescript
201
+ const pathao = new PathaoApiService(config, {
202
+ debug: false, // Enable detailed debug logging (default: false)
203
+ circuitBreaker: {
204
+ threshold: 5, // Failures before opening circuit (default: 5)
205
+ timeout: 60000 // Wait time before retry (default: 60000ms = 1 min)
206
+ }
207
+ });
208
+ ```
209
+
210
+ When `debug` is enabled, the SDK logs all HTTP requests and responses:
211
+
212
+ ```
213
+ [Pathao SDK] GET /aladdin/api/v1/stores { headers: {...}, data: {...} }
214
+ [Pathao SDK] Response 200 { url: '...', data: {...} }
215
+ ```
216
+
167
217
  ### Order Management
168
218
 
169
219
  #### Create Order
@@ -297,17 +347,61 @@ enum ItemType {
297
347
 
298
348
  ## Error Handling
299
349
 
300
- The SDK provides comprehensive error handling with detailed error messages:
350
+ The SDK provides comprehensive error handling through the `PathaoApiError` class, which extends Error with additional properties for detailed error information:
301
351
 
302
352
  ```typescript
353
+ import { PathaoApiService, PathaoApiError } from 'pathao-merchant-sdk';
354
+
355
+ const pathao = new PathaoApiService({
356
+ clientId: process.env.PATHAO_CLIENT_ID,
357
+ clientSecret: process.env.PATHAO_CLIENT_SECRET,
358
+ username: process.env.PATHAO_USERNAME,
359
+ password: process.env.PATHAO_PASSWORD
360
+ });
361
+
303
362
  try {
304
363
  const order = await pathao.createOrder(orderData);
364
+ console.log('Order created:', order.data.consignment_id);
365
+ } catch (error) {
366
+ // Check if it's a PathaoApiError (structured error from Pathao API)
367
+ if (error instanceof PathaoApiError) {
368
+ console.error('Pathao API Error:', {
369
+ status: error.status, // HTTP status code
370
+ code: error.code, // Pathao error code
371
+ type: error.type, // Error type (e.g., 'ValidationException')
372
+ message: error.message, // Error message
373
+ errors: error.errors, // Field-level errors
374
+ validation: error.validation // Validation errors
375
+ });
376
+ } else {
377
+ console.error('Unexpected error:', error.message);
378
+ }
379
+ }
380
+ ```
381
+
382
+ ### Error Properties
383
+
384
+ - **status**: HTTP status code (e.g., 400, 401, 422)
385
+ - **code**: Pathao API error code for programmatic handling
386
+ - **type**: Error type string (e.g., 'ValidationException', 'AuthenticationException')
387
+ - **errors**: Object with field-level error messages
388
+ - **validation**: Object with validation error messages
389
+ - **message**: Human-readable error message
390
+
391
+ ### Configuration Validation
392
+
393
+ Configuration validation is deferred until the first API call to allow gradual setup:
394
+
395
+ ```typescript
396
+ // This won't throw immediately
397
+ const pathao = new PathaoApiService({});
398
+
399
+ // This will throw PathaoApiError if credentials are missing
400
+ try {
401
+ await pathao.getStores();
305
402
  } catch (error) {
306
- console.error('Order creation failed:', error.message);
307
-
308
- // Check if it's a Pathao API error
309
- if (error.response?.data) {
310
- console.error('API Error:', error.response.data);
403
+ if (error instanceof PathaoApiError) {
404
+ console.error('Configuration error:', error.validation);
311
405
  }
312
406
  }
313
407
  ```
package/dist/index.d.mts CHANGED
@@ -221,6 +221,10 @@ declare class PathaoApiError extends Error {
221
221
  responseData?: unknown;
222
222
  });
223
223
  }
224
+ interface CircuitBreakerConfig {
225
+ threshold?: number;
226
+ timeout?: number;
227
+ }
224
228
  declare class PathaoApiService {
225
229
  private pathaoClient;
226
230
  private accessToken;
@@ -230,8 +234,14 @@ declare class PathaoApiService {
230
234
  private isAuthenticating;
231
235
  private authPromise;
232
236
  private requestQueue;
237
+ private hasValidated;
238
+ private debug;
233
239
  private circuitBreaker;
234
- constructor(config: PathaoConfig);
240
+ constructor(config: PathaoConfig, options?: {
241
+ debug?: boolean;
242
+ circuitBreaker?: CircuitBreakerConfig;
243
+ });
244
+ private validateConfiguration;
235
245
  private ensureAuthenticated;
236
246
  private performAuthentication;
237
247
  private processRequestQueue;
@@ -264,6 +274,14 @@ declare class PathaoApiService {
264
274
  static validateContactNumber(phone: string): boolean;
265
275
  static validateStoreAddress(address: string): boolean;
266
276
  clearAuth(): void;
277
+ static fromEnv(options?: {
278
+ debug?: boolean;
279
+ circuitBreaker?: CircuitBreakerConfig;
280
+ }): PathaoApiService;
281
+ static fromConfig(config: PathaoConfig, options?: {
282
+ debug?: boolean;
283
+ circuitBreaker?: CircuitBreakerConfig;
284
+ }): PathaoApiService;
267
285
  }
268
286
 
269
287
  export { DeliveryType, ItemType, PathaoApiError, PathaoApiService, type PathaoAreaResponse, type PathaoAuthResponse, type PathaoCityResponse, type PathaoConfig, type PathaoError, type PathaoOrderRequest, type PathaoOrderResponse, type PathaoOrderStatusResponse, type PathaoPriceRequest, type PathaoPriceResponse, type PathaoStore, type PathaoStoreCreateResponse, type PathaoStoreListResponse, type PathaoStoreRequest, type PathaoZoneResponse };
package/dist/index.d.ts CHANGED
@@ -221,6 +221,10 @@ declare class PathaoApiError extends Error {
221
221
  responseData?: unknown;
222
222
  });
223
223
  }
224
+ interface CircuitBreakerConfig {
225
+ threshold?: number;
226
+ timeout?: number;
227
+ }
224
228
  declare class PathaoApiService {
225
229
  private pathaoClient;
226
230
  private accessToken;
@@ -230,8 +234,14 @@ declare class PathaoApiService {
230
234
  private isAuthenticating;
231
235
  private authPromise;
232
236
  private requestQueue;
237
+ private hasValidated;
238
+ private debug;
233
239
  private circuitBreaker;
234
- constructor(config: PathaoConfig);
240
+ constructor(config: PathaoConfig, options?: {
241
+ debug?: boolean;
242
+ circuitBreaker?: CircuitBreakerConfig;
243
+ });
244
+ private validateConfiguration;
235
245
  private ensureAuthenticated;
236
246
  private performAuthentication;
237
247
  private processRequestQueue;
@@ -264,6 +274,14 @@ declare class PathaoApiService {
264
274
  static validateContactNumber(phone: string): boolean;
265
275
  static validateStoreAddress(address: string): boolean;
266
276
  clearAuth(): void;
277
+ static fromEnv(options?: {
278
+ debug?: boolean;
279
+ circuitBreaker?: CircuitBreakerConfig;
280
+ }): PathaoApiService;
281
+ static fromConfig(config: PathaoConfig, options?: {
282
+ debug?: boolean;
283
+ circuitBreaker?: CircuitBreakerConfig;
284
+ }): PathaoApiService;
267
285
  }
268
286
 
269
287
  export { DeliveryType, ItemType, PathaoApiError, PathaoApiService, type PathaoAreaResponse, type PathaoAuthResponse, type PathaoCityResponse, type PathaoConfig, type PathaoError, type PathaoOrderRequest, type PathaoOrderResponse, type PathaoOrderStatusResponse, type PathaoPriceRequest, type PathaoPriceResponse, type PathaoStore, type PathaoStoreCreateResponse, type PathaoStoreListResponse, type PathaoStoreRequest, type PathaoZoneResponse };
package/dist/index.js CHANGED
@@ -19,58 +19,68 @@ var PathaoApiError = class extends Error {
19
19
  this.responseData = options.responseData;
20
20
  }
21
21
  };
22
- var PathaoApiService = class {
23
- constructor(config) {
22
+ var PathaoApiService = class _PathaoApiService {
23
+ constructor(config, options) {
24
24
  this.accessToken = null;
25
25
  this.refreshToken = null;
26
26
  this.tokenExpiry = null;
27
27
  this.isAuthenticating = false;
28
28
  this.authPromise = null;
29
29
  this.requestQueue = [];
30
- this.circuitBreaker = {
31
- failures: 0,
32
- lastFailureTime: 0,
33
- threshold: 5,
34
- timeout: 6e4,
35
- // 1 minute
36
- isOpen: false
37
- };
30
+ this.hasValidated = false;
31
+ this.debug = false;
32
+ const timeout = config.timeout || parseInt(process.env.PATHAO_TIMEOUT || "30000", 10);
38
33
  this.config = {
39
34
  baseURL: config.baseURL || process.env.PATHAO_BASE_URL || "",
40
- timeout: config.timeout || parseInt(process.env.PATHAO_TIMEOUT || "30000", 10),
35
+ timeout,
41
36
  clientId: config.clientId || process.env.PATHAO_CLIENT_ID || "",
42
37
  clientSecret: config.clientSecret || process.env.PATHAO_CLIENT_SECRET || "",
43
38
  username: config.username || process.env.PATHAO_USERNAME || "",
44
39
  password: config.password || process.env.PATHAO_PASSWORD || ""
45
40
  };
41
+ this.debug = options?.debug || false;
42
+ this.circuitBreaker = {
43
+ failures: 0,
44
+ lastFailureTime: 0,
45
+ threshold: options?.circuitBreaker?.threshold ?? 5,
46
+ timeout: options?.circuitBreaker?.timeout ?? 6e4,
47
+ isOpen: false
48
+ };
46
49
  this.pathaoClient = axios__default.default.create({
47
- baseURL: this.config.baseURL || process.env.PATHAO_BASE_URL || "",
48
- timeout: this.config.timeout || parseInt(process.env.PATHAO_TIMEOUT || "30000", 10),
50
+ baseURL: this.config.baseURL,
51
+ timeout: this.config.timeout,
49
52
  headers: {
50
53
  "Content-Type": "application/json",
51
- "Accept": "application/json"
54
+ Accept: "application/json"
52
55
  }
53
56
  });
54
- if (!this.config.baseURL) {
55
- throw new Error("Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable");
56
- }
57
- if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {
58
- throw new Error("Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)");
59
- }
60
57
  this.pathaoClient.interceptors.request.use(async (config2) => {
61
58
  if (config2.url?.includes("/issue-token")) {
62
59
  return config2;
63
60
  }
61
+ this.validateConfiguration();
64
62
  await this.ensureAuthenticated();
65
63
  if (this.accessToken) {
66
64
  config2.headers.Authorization = `Bearer ${this.accessToken}`;
67
65
  }
66
+ if (this.debug) {
67
+ console.log(`[Pathao SDK] ${config2.method?.toUpperCase()} ${config2.url}`, {
68
+ headers: config2.headers,
69
+ data: config2.data
70
+ });
71
+ }
68
72
  return config2;
69
73
  });
70
74
  this.pathaoClient.interceptors.response.use(
71
75
  (response) => {
72
76
  this.circuitBreaker.failures = 0;
73
77
  this.circuitBreaker.isOpen = false;
78
+ if (this.debug) {
79
+ console.log(`[Pathao SDK] Response ${response.status}`, {
80
+ url: response.config.url,
81
+ data: response.data
82
+ });
83
+ }
74
84
  return response;
75
85
  },
76
86
  async (error) => {
@@ -92,13 +102,37 @@ var PathaoApiService = class {
92
102
  }
93
103
  );
94
104
  }
105
+ validateConfiguration() {
106
+ if (this.hasValidated) {
107
+ return;
108
+ }
109
+ if (!this.config.baseURL) {
110
+ throw this.toPathaoApiError(
111
+ new Error(
112
+ "Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable"
113
+ ),
114
+ "Configuration validation failed"
115
+ );
116
+ }
117
+ if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {
118
+ throw this.toPathaoApiError(
119
+ new Error(
120
+ "Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)"
121
+ ),
122
+ "Configuration validation failed"
123
+ );
124
+ }
125
+ this.hasValidated = true;
126
+ }
95
127
  async ensureAuthenticated() {
96
128
  if (this.circuitBreaker.isOpen) {
97
129
  if (Date.now() - this.circuitBreaker.lastFailureTime > this.circuitBreaker.timeout) {
98
130
  this.circuitBreaker.isOpen = false;
99
131
  this.circuitBreaker.failures = 0;
100
132
  } else {
101
- throw new Error("Circuit breaker is open. Too many authentication failures.");
133
+ throw new Error(
134
+ "Circuit breaker is open. Too many authentication failures."
135
+ );
102
136
  }
103
137
  }
104
138
  if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {
@@ -140,13 +174,16 @@ var PathaoApiService = class {
140
174
  }
141
175
  async authenticate() {
142
176
  try {
143
- const response = await this.pathaoClient.post("/aladdin/api/v1/issue-token", {
144
- client_id: this.config.clientId,
145
- client_secret: this.config.clientSecret,
146
- username: this.config.username,
147
- password: this.config.password,
148
- grant_type: "password"
149
- });
177
+ const response = await this.pathaoClient.post(
178
+ "/aladdin/api/v1/issue-token",
179
+ {
180
+ client_id: this.config.clientId,
181
+ client_secret: this.config.clientSecret,
182
+ username: this.config.username,
183
+ password: this.config.password,
184
+ grant_type: "password"
185
+ }
186
+ );
150
187
  this.accessToken = response.data.access_token;
151
188
  this.refreshToken = response.data.refresh_token;
152
189
  this.tokenExpiry = Date.now() + response.data.expires_in * 1e3 - 6e4;
@@ -162,12 +199,15 @@ var PathaoApiService = class {
162
199
  throw new Error("No refresh token available");
163
200
  }
164
201
  try {
165
- const response = await this.pathaoClient.post("/aladdin/api/v1/issue-token", {
166
- client_id: this.config.clientId,
167
- client_secret: this.config.clientSecret,
168
- refresh_token: this.refreshToken,
169
- grant_type: "refresh_token"
170
- });
202
+ const response = await this.pathaoClient.post(
203
+ "/aladdin/api/v1/issue-token",
204
+ {
205
+ client_id: this.config.clientId,
206
+ client_secret: this.config.clientSecret,
207
+ refresh_token: this.refreshToken,
208
+ grant_type: "refresh_token"
209
+ }
210
+ );
171
211
  this.accessToken = response.data.access_token;
172
212
  this.refreshToken = response.data.refresh_token;
173
213
  this.tokenExpiry = Date.now() + response.data.expires_in * 1e3 - 6e4;
@@ -196,14 +236,17 @@ var PathaoApiService = class {
196
236
  const axiosLike = error instanceof axios.AxiosError ? error : typeof error === "object" && error && "response" in error ? error : null;
197
237
  if (axiosLike) {
198
238
  const pathaoError = axiosLike.response?.data;
199
- return new PathaoApiError(`${context}: ${pathaoError?.message || messageFallback}`, {
200
- status: axiosLike.response?.status,
201
- code: pathaoError?.code ?? axiosLike.response?.status,
202
- type: pathaoError?.type,
203
- errors: pathaoError?.errors,
204
- validation: pathaoError?.validation,
205
- responseData: pathaoError ?? axiosLike.response?.data
206
- });
239
+ return new PathaoApiError(
240
+ `${context}: ${pathaoError?.message || messageFallback}`,
241
+ {
242
+ status: axiosLike.response?.status,
243
+ code: pathaoError?.code ?? axiosLike.response?.status,
244
+ type: pathaoError?.type,
245
+ errors: pathaoError?.errors,
246
+ validation: pathaoError?.validation,
247
+ responseData: pathaoError ?? axiosLike.response?.data
248
+ }
249
+ );
207
250
  }
208
251
  return new PathaoApiError(`${context}: ${messageFallback}`);
209
252
  }
@@ -217,7 +260,10 @@ var PathaoApiService = class {
217
260
  // Official Pathao API: Create Order
218
261
  async createOrder(orderData) {
219
262
  try {
220
- const response = await this.pathaoClient.post("/aladdin/api/v1/orders", orderData);
263
+ const response = await this.pathaoClient.post(
264
+ "/aladdin/api/v1/orders",
265
+ orderData
266
+ );
221
267
  return response.data;
222
268
  } catch (error) {
223
269
  throw this.toPathaoApiError(error, "Failed to create Pathao order");
@@ -226,7 +272,10 @@ var PathaoApiService = class {
226
272
  // Official Pathao API: Create Store
227
273
  async createStore(storeData) {
228
274
  try {
229
- const response = await this.pathaoClient.post("/aladdin/api/v1/stores", storeData);
275
+ const response = await this.pathaoClient.post(
276
+ "/aladdin/api/v1/stores",
277
+ storeData
278
+ );
230
279
  return response.data;
231
280
  } catch (error) {
232
281
  throw this.toPathaoApiError(error, "Failed to create Pathao store");
@@ -235,7 +284,9 @@ var PathaoApiService = class {
235
284
  // Official Pathao API: Get Store List
236
285
  async getStores() {
237
286
  try {
238
- const response = await this.pathaoClient.get("/aladdin/api/v1/stores");
287
+ const response = await this.pathaoClient.get(
288
+ "/aladdin/api/v1/stores"
289
+ );
239
290
  return response.data;
240
291
  } catch (error) {
241
292
  throw this.toPathaoApiError(error, "Failed to fetch Pathao stores");
@@ -244,7 +295,10 @@ var PathaoApiService = class {
244
295
  // Official Pathao API: Calculate Price
245
296
  async calculatePrice(priceData) {
246
297
  try {
247
- const response = await this.pathaoClient.post("/aladdin/api/v1/merchant/price-plan", priceData);
298
+ const response = await this.pathaoClient.post(
299
+ "/aladdin/api/v1/merchant/price-plan",
300
+ priceData
301
+ );
248
302
  return response.data;
249
303
  } catch (error) {
250
304
  throw this.toPathaoApiError(error, "Failed to calculate Pathao price");
@@ -253,7 +307,9 @@ var PathaoApiService = class {
253
307
  // Official Pathao API: Get Cities
254
308
  async getCities() {
255
309
  try {
256
- const response = await this.pathaoClient.get("/aladdin/api/v1/city-list");
310
+ const response = await this.pathaoClient.get(
311
+ "/aladdin/api/v1/city-list"
312
+ );
257
313
  return response.data;
258
314
  } catch (error) {
259
315
  throw this.toPathaoApiError(error, "Failed to fetch Pathao cities");
@@ -262,7 +318,9 @@ var PathaoApiService = class {
262
318
  // Official Pathao API: Get Zones for a City
263
319
  async getZones(cityId) {
264
320
  try {
265
- const response = await this.pathaoClient.get(`/aladdin/api/v1/cities/${cityId}/zone-list`);
321
+ const response = await this.pathaoClient.get(
322
+ `/aladdin/api/v1/cities/${cityId}/zone-list`
323
+ );
266
324
  return response.data;
267
325
  } catch (error) {
268
326
  throw this.toPathaoApiError(error, "Failed to fetch Pathao zones");
@@ -271,7 +329,9 @@ var PathaoApiService = class {
271
329
  // Official Pathao API: Get Areas for a Zone
272
330
  async getAreas(zoneId) {
273
331
  try {
274
- const response = await this.pathaoClient.get(`/aladdin/api/v1/zones/${zoneId}/area-list`);
332
+ const response = await this.pathaoClient.get(
333
+ `/aladdin/api/v1/zones/${zoneId}/area-list`
334
+ );
275
335
  return response.data;
276
336
  } catch (error) {
277
337
  throw this.toPathaoApiError(error, "Failed to fetch Pathao areas");
@@ -280,7 +340,9 @@ var PathaoApiService = class {
280
340
  // Official Pathao API: Get Order Status
281
341
  async getOrderStatus(consignmentId) {
282
342
  try {
283
- const response = await this.pathaoClient.get(`/aladdin/api/v1/orders/${consignmentId}/info`);
343
+ const response = await this.pathaoClient.get(
344
+ `/aladdin/api/v1/orders/${consignmentId}/info`
345
+ );
284
346
  return response.data;
285
347
  } catch (error) {
286
348
  throw this.toPathaoApiError(error, "Failed to fetch Pathao order status");
@@ -306,7 +368,9 @@ var PathaoApiService = class {
306
368
  if (cleanPhone.length === 11 && cleanPhone.startsWith("01")) {
307
369
  return cleanPhone;
308
370
  }
309
- throw new Error("Invalid phone number format. Must be 11 digits starting with 01");
371
+ throw new Error(
372
+ "Invalid phone number format. Must be 11 digits starting with 01"
373
+ );
310
374
  }
311
375
  // Helper method to validate address
312
376
  static validateAddress(address) {
@@ -350,13 +414,24 @@ var PathaoApiService = class {
350
414
  this.isAuthenticating = false;
351
415
  this.authPromise = null;
352
416
  this.requestQueue = [];
353
- this.circuitBreaker = {
354
- failures: 0,
355
- lastFailureTime: 0,
356
- threshold: 5,
357
- timeout: 6e4,
358
- isOpen: false
417
+ this.circuitBreaker.failures = 0;
418
+ this.circuitBreaker.isOpen = false;
419
+ this.circuitBreaker.lastFailureTime = 0;
420
+ }
421
+ // Static factory method to create instance from environment variables
422
+ static fromEnv(options) {
423
+ const config = {
424
+ clientId: "",
425
+ clientSecret: "",
426
+ username: "",
427
+ password: "",
428
+ baseURL: ""
359
429
  };
430
+ return new _PathaoApiService(config, options);
431
+ }
432
+ // Static factory method to create instance from configuration object
433
+ static fromConfig(config, options) {
434
+ return new _PathaoApiService(config, options);
360
435
  }
361
436
  };
362
437
 
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pathao-api.ts","../src/types.ts"],"names":["axios","config","AxiosError","DeliveryType","ItemType"],"mappings":";;;;;;;;;AAsCO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAQxC,WAAA,CAAY,OAAA,EAAiB,OAAA,GAOzB,EAAC,EAAG;AACN,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,UAAA;AAC1B,IAAA,IAAA,CAAK,eAAe,OAAA,CAAQ,YAAA;AAAA,EAC9B;AACF;AAEO,IAAM,mBAAN,MAAuB;AAAA,EAiB5B,YAAY,MAAA,EAAs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AAA,SAAAA,CAAA,cAAW,CAAA,CAAA,GAAX,UAAA;AACA,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,YAAS,CAAA,CAAA,GAAT,QAAA;AAFU,EAAA,OAAAA,SAAAA;AAAA,CAAA,EAAA,QAAA,IAAA,EAAA","file":"index.js","sourcesContent":["/**\n * Pathao Merchant API Service (Unofficial SDK)\n * \n * This is an unofficial SDK for the Pathao Merchant API.\n * \n * API Details (based on public documentation):\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n * \n * Features implemented:\n * - Token-based authentication with refresh token support\n * - Store management (create, list stores)\n * - Order creation (single and bulk)\n * - Order tracking and status\n * - Dynamic price calculation\n * - City, zone, and area management\n */\n\nimport axios, { AxiosError, AxiosInstance } from 'axios';\nimport {\n PathaoAreaResponse,\n PathaoAuthResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStoreCreateResponse,\n PathaoStoreListResponse,\n PathaoStoreRequest,\n PathaoZoneResponse,\n} from './types';\n\nexport class PathaoApiError extends Error {\n status: number | undefined;\n code: number | undefined;\n type: string | undefined;\n errors: Record<string, string[]> | undefined;\n validation: Record<string, string[]> | undefined;\n responseData: unknown;\n\n constructor(message: string, options: {\n status?: number | undefined;\n code?: number | undefined;\n type?: string | undefined;\n errors?: Record<string, string[]> | undefined;\n validation?: Record<string, string[]> | undefined;\n responseData?: unknown;\n } = {}) {\n super(message);\n this.name = 'PathaoApiError';\n this.status = options.status;\n this.code = options.code;\n this.type = options.type;\n this.errors = options.errors;\n this.validation = options.validation;\n this.responseData = options.responseData;\n }\n}\n\nexport class PathaoApiService {\n private pathaoClient: AxiosInstance;\n private accessToken: string | null = null;\n private refreshToken: string | null = null;\n private tokenExpiry: number | null = null;\n private config: PathaoConfig;\n private isAuthenticating: boolean = false;\n private authPromise: Promise<void> | null = null;\n private requestQueue: Array<{ resolve: () => void; reject: (error: Error) => void }> = [];\n private circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: 5,\n timeout: 60000, // 1 minute\n isOpen: false,\n };\n\n constructor(config: PathaoConfig) {\n this.config = {\n baseURL: config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout: config.timeout || parseInt(process.env.PATHAO_TIMEOUT || '30000', 10),\n clientId: config.clientId || process.env.PATHAO_CLIENT_ID || '',\n clientSecret: config.clientSecret || process.env.PATHAO_CLIENT_SECRET || '',\n username: config.username || process.env.PATHAO_USERNAME || '',\n password: config.password || process.env.PATHAO_PASSWORD || '',\n };\n\n this.pathaoClient = axios.create({\n baseURL: this.config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout: this.config.timeout || parseInt(process.env.PATHAO_TIMEOUT || '30000', 10),\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n });\n\n // Validate required configuration\n if (!this.config.baseURL) {\n throw new Error('Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable');\n }\n \n if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {\n throw new Error('Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)');\n }\n\n // Add request interceptor for authentication\n this.pathaoClient.interceptors.request.use(async (config) => {\n // Skip auth for token requests to prevent infinite loops\n if (config.url?.includes('/issue-token')) {\n return config;\n }\n \n await this.ensureAuthenticated();\n if (this.accessToken) {\n config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return config;\n });\n\n // Add response interceptor for error handling\n this.pathaoClient.interceptors.response.use(\n (response) => {\n // Reset circuit breaker on successful request\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n return response;\n },\n async (error) => {\n if (error.response?.status === 401) {\n // Token expired, clear tokens and retry\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n \n // Retry the request once\n if (error.config && !error.config._retry) {\n error.config._retry = true;\n await this.ensureAuthenticated();\n if (this.accessToken) {\n error.config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return this.pathaoClient.request(error.config);\n }\n }\n \n // Handle circuit breaker\n this.handleCircuitBreaker();\n return Promise.reject(error);\n },\n );\n }\n\n private async ensureAuthenticated(): Promise<void> {\n // Check circuit breaker\n if (this.circuitBreaker.isOpen) {\n if (Date.now() - this.circuitBreaker.lastFailureTime > this.circuitBreaker.timeout) {\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.failures = 0;\n } else {\n throw new Error('Circuit breaker is open. Too many authentication failures.');\n }\n }\n\n if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {\n return; // Token is still valid\n }\n\n // If already authenticating, wait for it to complete\n if (this.isAuthenticating && this.authPromise) {\n return this.authPromise;\n }\n\n // Start authentication process\n this.isAuthenticating = true;\n this.authPromise = this.performAuthentication();\n\n try {\n await this.authPromise;\n } finally {\n this.isAuthenticating = false;\n this.authPromise = null;\n // Process queued requests\n this.processRequestQueue();\n }\n }\n\n private async performAuthentication(): Promise<void> {\n if (this.refreshToken) {\n try {\n await this.refreshAccessToken();\n return;\n } catch (error) {\n // Refresh failed, try fresh authentication\n this.refreshToken = null;\n }\n }\n\n await this.authenticate();\n }\n\n private processRequestQueue(): void {\n const queue = [...this.requestQueue];\n this.requestQueue = [];\n \n queue.forEach(({ resolve }) => {\n try {\n resolve();\n } catch (error) {\n // Ignore errors in queued requests\n }\n });\n }\n\n private async authenticate(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>('/aladdin/api/v1/issue-token', {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n username: this.config.username,\n password: this.config.password,\n grant_type: 'password',\n });\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful auth\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw this.toPathaoApiError(error, 'Authentication failed');\n }\n }\n\n private async refreshAccessToken(): Promise<void> {\n if (!this.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>('/aladdin/api/v1/issue-token', {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n refresh_token: this.refreshToken,\n grant_type: 'refresh_token',\n });\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful refresh\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw this.toPathaoApiError(error, 'Token refresh failed');\n }\n }\n\n private getErrorMessage(error: unknown): string {\n if (error instanceof AxiosError) {\n const pathaoError = error.response?.data as PathaoError;\n if (pathaoError?.message) {\n return pathaoError.message;\n }\n return error.message;\n }\n return (error as Error).message || 'Unknown error';\n }\n\n private toPathaoApiError(error: unknown, context: string): PathaoApiError {\n if (error instanceof PathaoApiError) {\n return error;\n }\n\n const messageFallback = this.getErrorMessage(error);\n const axiosLike = (error instanceof AxiosError) ? error : (typeof error === 'object' && error && 'response' in (error as any) ? error as AxiosError : null);\n if (axiosLike) {\n const pathaoError = axiosLike.response?.data as PathaoError | undefined;\n return new PathaoApiError(`${context}: ${pathaoError?.message || messageFallback}`, {\n status: axiosLike.response?.status,\n code: pathaoError?.code ?? axiosLike.response?.status,\n type: pathaoError?.type,\n errors: pathaoError?.errors,\n validation: pathaoError?.validation,\n responseData: pathaoError ?? axiosLike.response?.data,\n });\n }\n\n return new PathaoApiError(`${context}: ${messageFallback}`);\n }\n\n private handleCircuitBreaker(): void {\n this.circuitBreaker.failures++;\n this.circuitBreaker.lastFailureTime = Date.now();\n \n if (this.circuitBreaker.failures >= this.circuitBreaker.threshold) {\n this.circuitBreaker.isOpen = true;\n }\n }\n\n // Official Pathao API: Create Order\n async createOrder(orderData: PathaoOrderRequest): Promise<PathaoOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoOrderResponse>('/aladdin/api/v1/orders', orderData);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create Pathao order');\n }\n }\n\n // Official Pathao API: Create Store\n async createStore(storeData: PathaoStoreRequest): Promise<PathaoStoreCreateResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoStoreCreateResponse>('/aladdin/api/v1/stores', storeData);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create Pathao store');\n }\n }\n\n // Official Pathao API: Get Store List\n async getStores(): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>('/aladdin/api/v1/stores');\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao stores');\n }\n }\n\n // Official Pathao API: Calculate Price\n async calculatePrice(priceData: PathaoPriceRequest): Promise<PathaoPriceResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoPriceResponse>('/aladdin/api/v1/merchant/price-plan', priceData);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to calculate Pathao price');\n }\n }\n\n // Official Pathao API: Get Cities\n async getCities(): Promise<PathaoCityResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoCityResponse>('/aladdin/api/v1/city-list');\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao cities');\n }\n }\n\n // Official Pathao API: Get Zones for a City\n async getZones(cityId: number): Promise<PathaoZoneResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoZoneResponse>(`/aladdin/api/v1/cities/${cityId}/zone-list`);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao zones');\n }\n }\n\n // Official Pathao API: Get Areas for a Zone\n async getAreas(zoneId: number): Promise<PathaoAreaResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoAreaResponse>(`/aladdin/api/v1/zones/${zoneId}/area-list`);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao areas');\n }\n }\n\n // Official Pathao API: Get Order Status\n async getOrderStatus(consignmentId: string): Promise<PathaoOrderStatusResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoOrderStatusResponse>(`/aladdin/api/v1/orders/${consignmentId}/info`);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao order status');\n }\n }\n\n // Official Pathao API: Create Bulk Order\n async createBulkOrder(\n orders: PathaoOrderRequest[],\n ): Promise<{ message: string; type: string; code: number; data: boolean }> {\n try {\n const response = await this.pathaoClient.post<{\n message: string;\n type: string;\n code: number;\n data: boolean;\n }>('/aladdin/api/v1/orders/bulk', { orders });\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create bulk Pathao orders');\n }\n }\n\n // Helper method to validate phone number\n static validatePhoneNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, '');\n return cleanPhone.length === 11 && cleanPhone.startsWith('01');\n }\n\n // Helper method to format phone number\n static formatPhoneNumber(phone: string): string {\n const cleanPhone = phone.replace(/\\D/g, '');\n if (cleanPhone.length === 11 && cleanPhone.startsWith('01')) {\n return cleanPhone;\n }\n throw new Error('Invalid phone number format. Must be 11 digits starting with 01');\n }\n\n // Helper method to validate address\n static validateAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 10 && trimmed.length <= 220;\n }\n\n // Helper method to validate weight\n static validateWeight(weight: number): boolean {\n return weight >= 0.5 && weight <= 10;\n }\n\n // Helper method to validate recipient name\n static validateRecipientName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 100;\n }\n\n // Helper method to validate store name\n static validateStoreName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact name\n static validateContactName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact number\n static validateContactNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, '');\n return cleanPhone.length === 11;\n }\n\n // Helper method to validate store address\n static validateStoreAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 15 && trimmed.length <= 120;\n }\n\n // Method to clear authentication state (useful for testing)\n clearAuth(): void {\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n this.isAuthenticating = false;\n this.authPromise = null;\n this.requestQueue = [];\n this.circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: 5,\n timeout: 60000,\n isOpen: false,\n };\n }\n}\n","/**\n * Pathao Courier API Types\n * \n * Official API Details:\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n */\n\n// Official Pathao API Authentication Response\nexport interface PathaoAuthResponse {\n token_type: string;\n expires_in: number;\n access_token: string;\n refresh_token: string;\n}\n\n// Official Pathao Order Creation Request\nexport interface PathaoOrderRequest {\n store_id: number;\n merchant_order_id?: string; // Optional - Your order tracking ID\n recipient_name: string; // Required - 3-100 characters\n recipient_phone: string; // Required - 11 characters\n recipient_secondary_phone?: string; // Optional - 11 characters\n recipient_address: string; // Required - 10-220 characters\n recipient_city?: number; // Optional - Auto-detected if not provided\n recipient_zone?: number; // Optional - Auto-detected if not provided\n recipient_area?: number; // Optional - Auto-detected if not provided\n delivery_type: number; // Required - 48 (Normal), 12 (On Demand)\n item_type: number; // Required - 1 (Document), 2 (Parcel)\n special_instruction?: string; // Optional\n item_quantity: number; // Required\n item_weight: number; // Required - 0.5-10 kg\n item_description?: string; // Optional\n amount_to_collect: number; // Required - COD amount (0 for non-COD)\n}\n\n// Official Pathao Store Creation Request\nexport interface PathaoStoreRequest {\n name: string; // 3-50 characters\n contact_name: string; // 3-50 characters\n contact_number: string; // 11 characters\n secondary_contact?: string; // Optional - 11 characters\n otp_number?: string; // Optional - OTP for orders\n address: string; // 15-120 characters\n city_id: number;\n zone_id: number;\n area_id: number;\n}\n\n// Official Pathao Order Response\nexport interface PathaoOrderResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n delivery_fee: number;\n };\n}\n\n// Official Pathao Store Creation Response\nexport interface PathaoStoreCreateResponse {\n type: string;\n code: number;\n message: string;\n data: {\n store_name: string; // Only store_name returned on creation\n };\n}\n\n// Official Pathao Store List Item (from GET /stores)\nexport interface PathaoStore {\n store_id: number;\n store_name: string;\n store_address: string;\n is_active: number; // 1 for active, 0 for deactivated\n city_id: number;\n zone_id: number;\n hub_id: number;\n is_default_store: boolean;\n is_default_return_store: boolean;\n}\n\n// Official Pathao Store List Response\nexport interface PathaoStoreListResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: PathaoStore[];\n total: number;\n current_page: number;\n per_page: number;\n total_in_page: number;\n last_page: number;\n path: string;\n to: number;\n from: number;\n last_page_url: string;\n first_page_url: string;\n };\n}\n\n// Official Pathao Price Calculation Request\nexport interface PathaoPriceRequest {\n store_id: number;\n item_type: number;\n item_weight: number;\n delivery_type: number;\n recipient_city: number;\n recipient_zone: number;\n}\n\n// Official Pathao Price Response\nexport interface PathaoPriceResponse {\n type: string;\n code: number;\n message: string;\n data: {\n price: number; // Calculated price for given item\n discount: number; // Discount for the given item\n promo_discount: number; // Promo discount for the given item\n plan_id: number; // Price plan id for the given item\n cod_enabled: number; // 1 if COD enabled, 0 if not\n cod_percentage: number; // Cash on delivery percentage\n additional_charge: number; // If there is any additional charge\n final_price: number; // Your final price for the given item\n };\n}\n\n// Official Pathao City Response\nexport interface PathaoCityResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n city_id: number;\n city_name: string;\n }>;\n };\n}\n\n// Official Pathao Order Status Response\nexport interface PathaoOrderStatusResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n order_status_slug: string;\n updated_at: string;\n invoice_id: string | null;\n };\n}\n\n// Official Pathao Zone Response\nexport interface PathaoZoneResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n zone_id: number;\n zone_name: string;\n }>;\n };\n}\n\n// Official Pathao Area Response\nexport interface PathaoAreaResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n area_id: number;\n area_name: string;\n home_delivery_available: boolean;\n pickup_available: boolean;\n }>;\n };\n}\n\n// Configuration options for PathaoApiService\nexport interface PathaoConfig {\n clientId: string;\n clientSecret: string;\n username: string;\n password: string;\n baseURL: string;\n timeout?: number;\n}\n\n// Error response from Pathao API\nexport interface PathaoError {\n type: string;\n code: number;\n message: string;\n errors?: Record<string, string[]>;\n validation?: Record<string, string[]>;\n}\n\n// Delivery types enum\nexport enum DeliveryType {\n NORMAL = 48,\n ON_DEMAND = 12\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2\n}\n\n// Store types enum (removed as not used in official API)\n// export enum StoreType {\n// PICKUP_POINT = 1,\n// SERVICE_POINT = 2\n// }\n"]}
1
+ {"version":3,"sources":["../src/pathao-api.ts","../src/types.ts"],"names":["axios","config","AxiosError","DeliveryType","ItemType"],"mappings":";;;;;;;;;AAsCO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAQxC,WAAA,CACE,OAAA,EACA,OAAA,GAOI,EAAC,EACL;AACA,IAAA,KAAA,CAAM,OAA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U,EAAA;AAAA,MACV,YAAA,EAAc,EAAA;AAAA,MACd,QAAA,EAAU,EAAA;AAAA,MACV,QAAA,EAAU,EAAA;AAAA,MACV,OAAA,EAAS;AAAA,KACX;AACA,IAAA,OAAO,IAAI,iBAAA,CAAiB,MAAA,EAAQ,OAAO,CAAA;AAAA,EAC7C;AAAA;AAAA,EAGA,OAAO,UAAA,CAAW,MAAA,EAAsB,OAAA,EAAwF;AAC9H,IAAA,OAAO,IAAI,iBAAA,CAAiB,MAAA,EAAQ,OAAO,CAAA;AAAA,EAC7C;AACF;;;AClZO,IAAK,YAAA,qBAAAC,aAAAA,KAAL;AACL,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,YAAS,EAAA,CAAA,GAAT,QAAA;AACA,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,eAAY,EAAA,CAAA,GAAZ,WAAA;AAFU,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAML,IAAK,QAAA,qBAAAC,SAAAA,KAAL;AACL,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,cAAW,CAAA,CAAA,GAAX,UAAA;AACA,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,YAAS,CAAA,CAAA,GAAT,QAAA;AAFU,EAAA,OAAAA,SAAAA;AAAA,CAAA,EAAA,QAAA,IAAA,EAAA","file":"index.js","sourcesContent":["/**\n * Pathao Merchant API Service (Unofficial SDK)\n *\n * This is an unofficial SDK for the Pathao Merchant API.\n *\n * API Details (based on public documentation):\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n *\n * Features implemented:\n * - Token-based authentication with refresh token support\n * - Store management (create, list stores)\n * - Order creation (single and bulk)\n * - Order tracking and status\n * - Dynamic price calculation\n * - City, zone, and area management\n */\n\nimport axios, { AxiosError, AxiosInstance } from 'axios';\nimport {\n PathaoAreaResponse,\n PathaoAuthResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStoreCreateResponse,\n PathaoStoreListResponse,\n PathaoStoreRequest,\n PathaoZoneResponse,\n} from './types';\n\nexport class PathaoApiError extends Error {\n status: number | undefined;\n code: number | undefined;\n type: string | undefined;\n errors: Record<string, string[]> | undefined;\n validation: Record<string, string[]> | undefined;\n responseData: unknown;\n\n constructor(\n message: string,\n options: {\n status?: number | undefined;\n code?: number | undefined;\n type?: string | undefined;\n errors?: Record<string, string[]> | undefined;\n validation?: Record<string, string[]> | undefined;\n responseData?: unknown;\n } = {},\n ) {\n super(message);\n this.name = 'PathaoApiError';\n this.status = options.status;\n this.code = options.code;\n this.type = options.type;\n this.errors = options.errors;\n this.validation = options.validation;\n this.responseData = options.responseData;\n }\n}\n\n// Internal resolved config with guaranteed timeout\ninterface ResolvedPathaoConfig extends PathaoConfig {\n timeout: number;\n}\n\n// Circuit breaker configuration\ninterface CircuitBreakerConfig {\n threshold?: number; // Default: 5\n timeout?: number; // Default: 60000ms\n}\n\nexport class PathaoApiService {\n private pathaoClient: AxiosInstance;\n private accessToken: string | null = null;\n private refreshToken: string | null = null;\n private tokenExpiry: number | null = null;\n private config: ResolvedPathaoConfig;\n private isAuthenticating: boolean = false;\n private authPromise: Promise<void> | null = null;\n private requestQueue: Array<{\n resolve: () => void;\n reject: (error: Error) => void;\n }> = [];\n private hasValidated: boolean = false;\n private debug: boolean = false;\n private circuitBreaker: {\n failures: number;\n lastFailureTime: number;\n threshold: number;\n timeout: number;\n isOpen: boolean;\n };\n\n constructor(config: PathaoConfig, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }) {\n const timeout: number =\n config.timeout || parseInt(process.env.PATHAO_TIMEOUT || '30000', 10);\n\n this.config = {\n baseURL: config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout,\n clientId: config.clientId || process.env.PATHAO_CLIENT_ID || '',\n clientSecret:\n config.clientSecret || process.env.PATHAO_CLIENT_SECRET || '',\n username: config.username || process.env.PATHAO_USERNAME || '',\n password: config.password || process.env.PATHAO_PASSWORD || '',\n };\n\n this.debug = options?.debug || false;\n this.circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: options?.circuitBreaker?.threshold ?? 5,\n timeout: options?.circuitBreaker?.timeout ?? 60000,\n isOpen: false,\n };\n\n this.pathaoClient = axios.create({\n baseURL: this.config.baseURL,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n });\n\n // Add request interceptor for authentication\n this.pathaoClient.interceptors.request.use(async (config) => {\n // Skip auth for token requests to prevent infinite loops\n if (config.url?.includes('/issue-token')) {\n return config;\n }\n\n // Validate configuration on first API call\n this.validateConfiguration();\n await this.ensureAuthenticated();\n if (this.accessToken) {\n config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n\n if (this.debug) {\n console.log(`[Pathao SDK] ${config.method?.toUpperCase()} ${config.url}`, {\n headers: config.headers,\n data: config.data,\n });\n }\n\n return config;\n });\n\n // Add response interceptor for error handling\n this.pathaoClient.interceptors.response.use(\n (response) => {\n // Reset circuit breaker on successful request\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n\n if (this.debug) {\n console.log(`[Pathao SDK] Response ${response.status}`, {\n url: response.config.url,\n data: response.data,\n });\n }\n\n return response;\n },\n async (error) => {\n if (error.response?.status === 401) {\n // Token expired, clear tokens and retry\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n\n // Retry the request once\n if (error.config && !error.config._retry) {\n error.config._retry = true;\n await this.ensureAuthenticated();\n if (this.accessToken) {\n error.config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return this.pathaoClient.request(error.config);\n }\n }\n\n // Handle circuit breaker\n this.handleCircuitBreaker();\n return Promise.reject(error);\n }\n );\n }\n\n private validateConfiguration(): void {\n // Only validate once\n if (this.hasValidated) {\n return;\n }\n\n if (!this.config.baseURL) {\n throw this.toPathaoApiError(\n new Error(\n \"Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable\"\n ),\n \"Configuration validation failed\"\n );\n }\n\n if (\n !this.config.clientId ||\n !this.config.clientSecret ||\n !this.config.username ||\n !this.config.password\n ) {\n throw this.toPathaoApiError(\n new Error(\n \"Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)\"\n ),\n \"Configuration validation failed\"\n );\n }\n\n this.hasValidated = true;\n }\n\n private async ensureAuthenticated(): Promise<void> {\n // Check circuit breaker\n if (this.circuitBreaker.isOpen) {\n if (\n Date.now() - this.circuitBreaker.lastFailureTime >\n this.circuitBreaker.timeout\n ) {\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.failures = 0;\n } else {\n throw new Error(\n \"Circuit breaker is open. Too many authentication failures.\"\n );\n }\n }\n\n if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {\n return; // Token is still valid\n }\n\n // If already authenticating, wait for it to complete\n if (this.isAuthenticating && this.authPromise) {\n return this.authPromise;\n }\n\n // Start authentication process\n this.isAuthenticating = true;\n this.authPromise = this.performAuthentication();\n\n try {\n await this.authPromise;\n } finally {\n this.isAuthenticating = false;\n this.authPromise = null;\n // Process queued requests\n this.processRequestQueue();\n }\n }\n\n private async performAuthentication(): Promise<void> {\n if (this.refreshToken) {\n try {\n await this.refreshAccessToken();\n return;\n } catch (error) {\n // Refresh failed, try fresh authentication\n this.refreshToken = null;\n }\n }\n\n await this.authenticate();\n }\n\n private processRequestQueue(): void {\n const queue = [...this.requestQueue];\n this.requestQueue = [];\n\n queue.forEach(({ resolve }) => {\n try {\n resolve();\n } catch (error) {\n // Ignore errors in queued requests\n }\n });\n }\n\n private async authenticate(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>(\n \"/aladdin/api/v1/issue-token\",\n {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n username: this.config.username,\n password: this.config.password,\n grant_type: \"password\",\n }\n );\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + response.data.expires_in * 1000 - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful auth\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw this.toPathaoApiError(error, \"Authentication failed\");\n }\n }\n\n private async refreshAccessToken(): Promise<void> {\n if (!this.refreshToken) {\n throw new Error(\"No refresh token available\");\n }\n\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>(\n \"/aladdin/api/v1/issue-token\",\n {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n refresh_token: this.refreshToken,\n grant_type: \"refresh_token\",\n }\n );\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + response.data.expires_in * 1000 - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful refresh\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw this.toPathaoApiError(error, \"Token refresh failed\");\n }\n }\n\n private getErrorMessage(error: unknown): string {\n if (error instanceof AxiosError) {\n const pathaoError = error.response?.data as PathaoError;\n if (pathaoError?.message) {\n return pathaoError.message;\n }\n return error.message;\n }\n return (error as Error).message || \"Unknown error\";\n }\n\n private toPathaoApiError(error: unknown, context: string): PathaoApiError {\n if (error instanceof PathaoApiError) {\n return error;\n }\n\n const messageFallback = this.getErrorMessage(error);\n const axiosLike =\n error instanceof AxiosError\n ? error\n : typeof error === \"object\" && error && \"response\" in (error as any)\n ? (error as AxiosError)\n : null;\n if (axiosLike) {\n const pathaoError = axiosLike.response?.data as PathaoError | undefined;\n return new PathaoApiError(\n `${context}: ${pathaoError?.message || messageFallback}`,\n {\n status: axiosLike.response?.status,\n code: pathaoError?.code ?? axiosLike.response?.status,\n type: pathaoError?.type,\n errors: pathaoError?.errors,\n validation: pathaoError?.validation,\n responseData: pathaoError ?? axiosLike.response?.data,\n }\n );\n }\n\n return new PathaoApiError(`${context}: ${messageFallback}`);\n }\n\n private handleCircuitBreaker(): void {\n this.circuitBreaker.failures++;\n this.circuitBreaker.lastFailureTime = Date.now();\n\n if (this.circuitBreaker.failures >= this.circuitBreaker.threshold) {\n this.circuitBreaker.isOpen = true;\n }\n }\n\n // Official Pathao API: Create Order\n async createOrder(\n orderData: PathaoOrderRequest\n ): Promise<PathaoOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoOrderResponse>(\n \"/aladdin/api/v1/orders\",\n orderData\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to create Pathao order\");\n }\n }\n\n // Official Pathao API: Create Store\n async createStore(\n storeData: PathaoStoreRequest\n ): Promise<PathaoStoreCreateResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoStoreCreateResponse>(\n \"/aladdin/api/v1/stores\",\n storeData\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to create Pathao store\");\n }\n }\n\n // Official Pathao API: Get Store List\n async getStores(): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>(\n \"/aladdin/api/v1/stores\"\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao stores\");\n }\n }\n\n // Official Pathao API: Calculate Price\n async calculatePrice(\n priceData: PathaoPriceRequest\n ): Promise<PathaoPriceResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoPriceResponse>(\n \"/aladdin/api/v1/merchant/price-plan\",\n priceData\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to calculate Pathao price\");\n }\n }\n\n // Official Pathao API: Get Cities\n async getCities(): Promise<PathaoCityResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoCityResponse>(\n \"/aladdin/api/v1/city-list\"\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao cities\");\n }\n }\n\n // Official Pathao API: Get Zones for a City\n async getZones(cityId: number): Promise<PathaoZoneResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoZoneResponse>(\n `/aladdin/api/v1/cities/${cityId}/zone-list`\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao zones\");\n }\n }\n\n // Official Pathao API: Get Areas for a Zone\n async getAreas(zoneId: number): Promise<PathaoAreaResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoAreaResponse>(\n `/aladdin/api/v1/zones/${zoneId}/area-list`\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao areas\");\n }\n }\n\n // Official Pathao API: Get Order Status\n async getOrderStatus(\n consignmentId: string\n ): Promise<PathaoOrderStatusResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoOrderStatusResponse>(\n `/aladdin/api/v1/orders/${consignmentId}/info`\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao order status\");\n }\n }\n\n // Official Pathao API: Create Bulk Order\n async createBulkOrder(\n orders: PathaoOrderRequest[]\n ): Promise<{ message: string; type: string; code: number; data: boolean }> {\n try {\n const response = await this.pathaoClient.post<{\n message: string;\n type: string;\n code: number;\n data: boolean;\n }>(\"/aladdin/api/v1/orders/bulk\", { orders });\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to create bulk Pathao orders\");\n }\n }\n\n // Helper method to validate phone number\n static validatePhoneNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, \"\");\n return cleanPhone.length === 11 && cleanPhone.startsWith(\"01\");\n }\n\n // Helper method to format phone number\n static formatPhoneNumber(phone: string): string {\n const cleanPhone = phone.replace(/\\D/g, \"\");\n if (cleanPhone.length === 11 && cleanPhone.startsWith(\"01\")) {\n return cleanPhone;\n }\n throw new Error(\n \"Invalid phone number format. Must be 11 digits starting with 01\"\n );\n }\n\n // Helper method to validate address\n static validateAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 10 && trimmed.length <= 220;\n }\n\n // Helper method to validate weight\n static validateWeight(weight: number): boolean {\n return weight >= 0.5 && weight <= 10;\n }\n\n // Helper method to validate recipient name\n static validateRecipientName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 100;\n }\n\n // Helper method to validate store name\n static validateStoreName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact name\n static validateContactName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact number\n static validateContactNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, \"\");\n return cleanPhone.length === 11;\n }\n\n // Helper method to validate store address\n static validateStoreAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 15 && trimmed.length <= 120;\n }\n\n // Method to clear authentication state (useful for testing)\n clearAuth(): void {\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n this.isAuthenticating = false;\n this.authPromise = null;\n this.requestQueue = [];\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.lastFailureTime = 0;\n }\n\n // Static factory method to create instance from environment variables\n static fromEnv(options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n const config: PathaoConfig = {\n clientId: \"\",\n clientSecret: \"\",\n username: \"\",\n password: \"\",\n baseURL: \"\",\n };\n return new PathaoApiService(config, options);\n }\n\n // Static factory method to create instance from configuration object\n static fromConfig(config: PathaoConfig, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n return new PathaoApiService(config, options);\n }\n}\n\n","/**\n * Pathao Courier API Types\n * \n * Official API Details:\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n */\n\n// Official Pathao API Authentication Response\nexport interface PathaoAuthResponse {\n token_type: string;\n expires_in: number;\n access_token: string;\n refresh_token: string;\n}\n\n// Official Pathao Order Creation Request\nexport interface PathaoOrderRequest {\n store_id: number;\n merchant_order_id?: string; // Optional - Your order tracking ID\n recipient_name: string; // Required - 3-100 characters\n recipient_phone: string; // Required - 11 characters\n recipient_secondary_phone?: string; // Optional - 11 characters\n recipient_address: string; // Required - 10-220 characters\n recipient_city?: number; // Optional - Auto-detected if not provided\n recipient_zone?: number; // Optional - Auto-detected if not provided\n recipient_area?: number; // Optional - Auto-detected if not provided\n delivery_type: number; // Required - 48 (Normal), 12 (On Demand)\n item_type: number; // Required - 1 (Document), 2 (Parcel)\n special_instruction?: string; // Optional\n item_quantity: number; // Required\n item_weight: number; // Required - 0.5-10 kg\n item_description?: string; // Optional\n amount_to_collect: number; // Required - COD amount (0 for non-COD)\n}\n\n// Official Pathao Store Creation Request\nexport interface PathaoStoreRequest {\n name: string; // 3-50 characters\n contact_name: string; // 3-50 characters\n contact_number: string; // 11 characters\n secondary_contact?: string; // Optional - 11 characters\n otp_number?: string; // Optional - OTP for orders\n address: string; // 15-120 characters\n city_id: number;\n zone_id: number;\n area_id: number;\n}\n\n// Official Pathao Order Response\nexport interface PathaoOrderResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n delivery_fee: number;\n };\n}\n\n// Official Pathao Store Creation Response\nexport interface PathaoStoreCreateResponse {\n type: string;\n code: number;\n message: string;\n data: {\n store_name: string; // Only store_name returned on creation\n };\n}\n\n// Official Pathao Store List Item (from GET /stores)\nexport interface PathaoStore {\n store_id: number;\n store_name: string;\n store_address: string;\n is_active: number; // 1 for active, 0 for deactivated\n city_id: number;\n zone_id: number;\n hub_id: number;\n is_default_store: boolean;\n is_default_return_store: boolean;\n}\n\n// Official Pathao Store List Response\nexport interface PathaoStoreListResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: PathaoStore[];\n total: number;\n current_page: number;\n per_page: number;\n total_in_page: number;\n last_page: number;\n path: string;\n to: number;\n from: number;\n last_page_url: string;\n first_page_url: string;\n };\n}\n\n// Official Pathao Price Calculation Request\nexport interface PathaoPriceRequest {\n store_id: number;\n item_type: number;\n item_weight: number;\n delivery_type: number;\n recipient_city: number;\n recipient_zone: number;\n}\n\n// Official Pathao Price Response\nexport interface PathaoPriceResponse {\n type: string;\n code: number;\n message: string;\n data: {\n price: number; // Calculated price for given item\n discount: number; // Discount for the given item\n promo_discount: number; // Promo discount for the given item\n plan_id: number; // Price plan id for the given item\n cod_enabled: number; // 1 if COD enabled, 0 if not\n cod_percentage: number; // Cash on delivery percentage\n additional_charge: number; // If there is any additional charge\n final_price: number; // Your final price for the given item\n };\n}\n\n// Official Pathao City Response\nexport interface PathaoCityResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n city_id: number;\n city_name: string;\n }>;\n };\n}\n\n// Official Pathao Order Status Response\nexport interface PathaoOrderStatusResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n order_status_slug: string;\n updated_at: string;\n invoice_id: string | null;\n };\n}\n\n// Official Pathao Zone Response\nexport interface PathaoZoneResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n zone_id: number;\n zone_name: string;\n }>;\n };\n}\n\n// Official Pathao Area Response\nexport interface PathaoAreaResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n area_id: number;\n area_name: string;\n home_delivery_available: boolean;\n pickup_available: boolean;\n }>;\n };\n}\n\n// Configuration options for PathaoApiService\nexport interface PathaoConfig {\n clientId: string;\n clientSecret: string;\n username: string;\n password: string;\n baseURL: string;\n timeout?: number; // Optional - defaults to 30000 if not provided\n}\n\n// Error response from Pathao API\nexport interface PathaoError {\n type: string;\n code: number;\n message: string;\n errors?: Record<string, string[]>;\n validation?: Record<string, string[]>;\n}\n\n// Delivery types enum\nexport enum DeliveryType {\n NORMAL = 48,\n ON_DEMAND = 12\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2\n}\n\n// Store types enum (removed as not used in official API)\n// export enum StoreType {\n// PICKUP_POINT = 1,\n// SERVICE_POINT = 2\n// }\n"]}
package/dist/index.mjs CHANGED
@@ -13,58 +13,68 @@ var PathaoApiError = class extends Error {
13
13
  this.responseData = options.responseData;
14
14
  }
15
15
  };
16
- var PathaoApiService = class {
17
- constructor(config) {
16
+ var PathaoApiService = class _PathaoApiService {
17
+ constructor(config, options) {
18
18
  this.accessToken = null;
19
19
  this.refreshToken = null;
20
20
  this.tokenExpiry = null;
21
21
  this.isAuthenticating = false;
22
22
  this.authPromise = null;
23
23
  this.requestQueue = [];
24
- this.circuitBreaker = {
25
- failures: 0,
26
- lastFailureTime: 0,
27
- threshold: 5,
28
- timeout: 6e4,
29
- // 1 minute
30
- isOpen: false
31
- };
24
+ this.hasValidated = false;
25
+ this.debug = false;
26
+ const timeout = config.timeout || parseInt(process.env.PATHAO_TIMEOUT || "30000", 10);
32
27
  this.config = {
33
28
  baseURL: config.baseURL || process.env.PATHAO_BASE_URL || "",
34
- timeout: config.timeout || parseInt(process.env.PATHAO_TIMEOUT || "30000", 10),
29
+ timeout,
35
30
  clientId: config.clientId || process.env.PATHAO_CLIENT_ID || "",
36
31
  clientSecret: config.clientSecret || process.env.PATHAO_CLIENT_SECRET || "",
37
32
  username: config.username || process.env.PATHAO_USERNAME || "",
38
33
  password: config.password || process.env.PATHAO_PASSWORD || ""
39
34
  };
35
+ this.debug = options?.debug || false;
36
+ this.circuitBreaker = {
37
+ failures: 0,
38
+ lastFailureTime: 0,
39
+ threshold: options?.circuitBreaker?.threshold ?? 5,
40
+ timeout: options?.circuitBreaker?.timeout ?? 6e4,
41
+ isOpen: false
42
+ };
40
43
  this.pathaoClient = axios.create({
41
- baseURL: this.config.baseURL || process.env.PATHAO_BASE_URL || "",
42
- timeout: this.config.timeout || parseInt(process.env.PATHAO_TIMEOUT || "30000", 10),
44
+ baseURL: this.config.baseURL,
45
+ timeout: this.config.timeout,
43
46
  headers: {
44
47
  "Content-Type": "application/json",
45
- "Accept": "application/json"
48
+ Accept: "application/json"
46
49
  }
47
50
  });
48
- if (!this.config.baseURL) {
49
- throw new Error("Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable");
50
- }
51
- if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {
52
- throw new Error("Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)");
53
- }
54
51
  this.pathaoClient.interceptors.request.use(async (config2) => {
55
52
  if (config2.url?.includes("/issue-token")) {
56
53
  return config2;
57
54
  }
55
+ this.validateConfiguration();
58
56
  await this.ensureAuthenticated();
59
57
  if (this.accessToken) {
60
58
  config2.headers.Authorization = `Bearer ${this.accessToken}`;
61
59
  }
60
+ if (this.debug) {
61
+ console.log(`[Pathao SDK] ${config2.method?.toUpperCase()} ${config2.url}`, {
62
+ headers: config2.headers,
63
+ data: config2.data
64
+ });
65
+ }
62
66
  return config2;
63
67
  });
64
68
  this.pathaoClient.interceptors.response.use(
65
69
  (response) => {
66
70
  this.circuitBreaker.failures = 0;
67
71
  this.circuitBreaker.isOpen = false;
72
+ if (this.debug) {
73
+ console.log(`[Pathao SDK] Response ${response.status}`, {
74
+ url: response.config.url,
75
+ data: response.data
76
+ });
77
+ }
68
78
  return response;
69
79
  },
70
80
  async (error) => {
@@ -86,13 +96,37 @@ var PathaoApiService = class {
86
96
  }
87
97
  );
88
98
  }
99
+ validateConfiguration() {
100
+ if (this.hasValidated) {
101
+ return;
102
+ }
103
+ if (!this.config.baseURL) {
104
+ throw this.toPathaoApiError(
105
+ new Error(
106
+ "Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable"
107
+ ),
108
+ "Configuration validation failed"
109
+ );
110
+ }
111
+ if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {
112
+ throw this.toPathaoApiError(
113
+ new Error(
114
+ "Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)"
115
+ ),
116
+ "Configuration validation failed"
117
+ );
118
+ }
119
+ this.hasValidated = true;
120
+ }
89
121
  async ensureAuthenticated() {
90
122
  if (this.circuitBreaker.isOpen) {
91
123
  if (Date.now() - this.circuitBreaker.lastFailureTime > this.circuitBreaker.timeout) {
92
124
  this.circuitBreaker.isOpen = false;
93
125
  this.circuitBreaker.failures = 0;
94
126
  } else {
95
- throw new Error("Circuit breaker is open. Too many authentication failures.");
127
+ throw new Error(
128
+ "Circuit breaker is open. Too many authentication failures."
129
+ );
96
130
  }
97
131
  }
98
132
  if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {
@@ -134,13 +168,16 @@ var PathaoApiService = class {
134
168
  }
135
169
  async authenticate() {
136
170
  try {
137
- const response = await this.pathaoClient.post("/aladdin/api/v1/issue-token", {
138
- client_id: this.config.clientId,
139
- client_secret: this.config.clientSecret,
140
- username: this.config.username,
141
- password: this.config.password,
142
- grant_type: "password"
143
- });
171
+ const response = await this.pathaoClient.post(
172
+ "/aladdin/api/v1/issue-token",
173
+ {
174
+ client_id: this.config.clientId,
175
+ client_secret: this.config.clientSecret,
176
+ username: this.config.username,
177
+ password: this.config.password,
178
+ grant_type: "password"
179
+ }
180
+ );
144
181
  this.accessToken = response.data.access_token;
145
182
  this.refreshToken = response.data.refresh_token;
146
183
  this.tokenExpiry = Date.now() + response.data.expires_in * 1e3 - 6e4;
@@ -156,12 +193,15 @@ var PathaoApiService = class {
156
193
  throw new Error("No refresh token available");
157
194
  }
158
195
  try {
159
- const response = await this.pathaoClient.post("/aladdin/api/v1/issue-token", {
160
- client_id: this.config.clientId,
161
- client_secret: this.config.clientSecret,
162
- refresh_token: this.refreshToken,
163
- grant_type: "refresh_token"
164
- });
196
+ const response = await this.pathaoClient.post(
197
+ "/aladdin/api/v1/issue-token",
198
+ {
199
+ client_id: this.config.clientId,
200
+ client_secret: this.config.clientSecret,
201
+ refresh_token: this.refreshToken,
202
+ grant_type: "refresh_token"
203
+ }
204
+ );
165
205
  this.accessToken = response.data.access_token;
166
206
  this.refreshToken = response.data.refresh_token;
167
207
  this.tokenExpiry = Date.now() + response.data.expires_in * 1e3 - 6e4;
@@ -190,14 +230,17 @@ var PathaoApiService = class {
190
230
  const axiosLike = error instanceof AxiosError ? error : typeof error === "object" && error && "response" in error ? error : null;
191
231
  if (axiosLike) {
192
232
  const pathaoError = axiosLike.response?.data;
193
- return new PathaoApiError(`${context}: ${pathaoError?.message || messageFallback}`, {
194
- status: axiosLike.response?.status,
195
- code: pathaoError?.code ?? axiosLike.response?.status,
196
- type: pathaoError?.type,
197
- errors: pathaoError?.errors,
198
- validation: pathaoError?.validation,
199
- responseData: pathaoError ?? axiosLike.response?.data
200
- });
233
+ return new PathaoApiError(
234
+ `${context}: ${pathaoError?.message || messageFallback}`,
235
+ {
236
+ status: axiosLike.response?.status,
237
+ code: pathaoError?.code ?? axiosLike.response?.status,
238
+ type: pathaoError?.type,
239
+ errors: pathaoError?.errors,
240
+ validation: pathaoError?.validation,
241
+ responseData: pathaoError ?? axiosLike.response?.data
242
+ }
243
+ );
201
244
  }
202
245
  return new PathaoApiError(`${context}: ${messageFallback}`);
203
246
  }
@@ -211,7 +254,10 @@ var PathaoApiService = class {
211
254
  // Official Pathao API: Create Order
212
255
  async createOrder(orderData) {
213
256
  try {
214
- const response = await this.pathaoClient.post("/aladdin/api/v1/orders", orderData);
257
+ const response = await this.pathaoClient.post(
258
+ "/aladdin/api/v1/orders",
259
+ orderData
260
+ );
215
261
  return response.data;
216
262
  } catch (error) {
217
263
  throw this.toPathaoApiError(error, "Failed to create Pathao order");
@@ -220,7 +266,10 @@ var PathaoApiService = class {
220
266
  // Official Pathao API: Create Store
221
267
  async createStore(storeData) {
222
268
  try {
223
- const response = await this.pathaoClient.post("/aladdin/api/v1/stores", storeData);
269
+ const response = await this.pathaoClient.post(
270
+ "/aladdin/api/v1/stores",
271
+ storeData
272
+ );
224
273
  return response.data;
225
274
  } catch (error) {
226
275
  throw this.toPathaoApiError(error, "Failed to create Pathao store");
@@ -229,7 +278,9 @@ var PathaoApiService = class {
229
278
  // Official Pathao API: Get Store List
230
279
  async getStores() {
231
280
  try {
232
- const response = await this.pathaoClient.get("/aladdin/api/v1/stores");
281
+ const response = await this.pathaoClient.get(
282
+ "/aladdin/api/v1/stores"
283
+ );
233
284
  return response.data;
234
285
  } catch (error) {
235
286
  throw this.toPathaoApiError(error, "Failed to fetch Pathao stores");
@@ -238,7 +289,10 @@ var PathaoApiService = class {
238
289
  // Official Pathao API: Calculate Price
239
290
  async calculatePrice(priceData) {
240
291
  try {
241
- const response = await this.pathaoClient.post("/aladdin/api/v1/merchant/price-plan", priceData);
292
+ const response = await this.pathaoClient.post(
293
+ "/aladdin/api/v1/merchant/price-plan",
294
+ priceData
295
+ );
242
296
  return response.data;
243
297
  } catch (error) {
244
298
  throw this.toPathaoApiError(error, "Failed to calculate Pathao price");
@@ -247,7 +301,9 @@ var PathaoApiService = class {
247
301
  // Official Pathao API: Get Cities
248
302
  async getCities() {
249
303
  try {
250
- const response = await this.pathaoClient.get("/aladdin/api/v1/city-list");
304
+ const response = await this.pathaoClient.get(
305
+ "/aladdin/api/v1/city-list"
306
+ );
251
307
  return response.data;
252
308
  } catch (error) {
253
309
  throw this.toPathaoApiError(error, "Failed to fetch Pathao cities");
@@ -256,7 +312,9 @@ var PathaoApiService = class {
256
312
  // Official Pathao API: Get Zones for a City
257
313
  async getZones(cityId) {
258
314
  try {
259
- const response = await this.pathaoClient.get(`/aladdin/api/v1/cities/${cityId}/zone-list`);
315
+ const response = await this.pathaoClient.get(
316
+ `/aladdin/api/v1/cities/${cityId}/zone-list`
317
+ );
260
318
  return response.data;
261
319
  } catch (error) {
262
320
  throw this.toPathaoApiError(error, "Failed to fetch Pathao zones");
@@ -265,7 +323,9 @@ var PathaoApiService = class {
265
323
  // Official Pathao API: Get Areas for a Zone
266
324
  async getAreas(zoneId) {
267
325
  try {
268
- const response = await this.pathaoClient.get(`/aladdin/api/v1/zones/${zoneId}/area-list`);
326
+ const response = await this.pathaoClient.get(
327
+ `/aladdin/api/v1/zones/${zoneId}/area-list`
328
+ );
269
329
  return response.data;
270
330
  } catch (error) {
271
331
  throw this.toPathaoApiError(error, "Failed to fetch Pathao areas");
@@ -274,7 +334,9 @@ var PathaoApiService = class {
274
334
  // Official Pathao API: Get Order Status
275
335
  async getOrderStatus(consignmentId) {
276
336
  try {
277
- const response = await this.pathaoClient.get(`/aladdin/api/v1/orders/${consignmentId}/info`);
337
+ const response = await this.pathaoClient.get(
338
+ `/aladdin/api/v1/orders/${consignmentId}/info`
339
+ );
278
340
  return response.data;
279
341
  } catch (error) {
280
342
  throw this.toPathaoApiError(error, "Failed to fetch Pathao order status");
@@ -300,7 +362,9 @@ var PathaoApiService = class {
300
362
  if (cleanPhone.length === 11 && cleanPhone.startsWith("01")) {
301
363
  return cleanPhone;
302
364
  }
303
- throw new Error("Invalid phone number format. Must be 11 digits starting with 01");
365
+ throw new Error(
366
+ "Invalid phone number format. Must be 11 digits starting with 01"
367
+ );
304
368
  }
305
369
  // Helper method to validate address
306
370
  static validateAddress(address) {
@@ -344,13 +408,24 @@ var PathaoApiService = class {
344
408
  this.isAuthenticating = false;
345
409
  this.authPromise = null;
346
410
  this.requestQueue = [];
347
- this.circuitBreaker = {
348
- failures: 0,
349
- lastFailureTime: 0,
350
- threshold: 5,
351
- timeout: 6e4,
352
- isOpen: false
411
+ this.circuitBreaker.failures = 0;
412
+ this.circuitBreaker.isOpen = false;
413
+ this.circuitBreaker.lastFailureTime = 0;
414
+ }
415
+ // Static factory method to create instance from environment variables
416
+ static fromEnv(options) {
417
+ const config = {
418
+ clientId: "",
419
+ clientSecret: "",
420
+ username: "",
421
+ password: "",
422
+ baseURL: ""
353
423
  };
424
+ return new _PathaoApiService(config, options);
425
+ }
426
+ // Static factory method to create instance from configuration object
427
+ static fromConfig(config, options) {
428
+ return new _PathaoApiService(config, options);
354
429
  }
355
430
  };
356
431
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pathao-api.ts","../src/types.ts"],"names":["config","DeliveryType","ItemType"],"mappings":";;;AAsCO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAQxC,WAAA,CAAY,OAAA,EAAiB,OAAA,GAOzB,EAAC,EAAG;AACN,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,aAAa,OAAA,CAAQ,UAAA;AAC1B,IAAA,IAAA,CAAK,eAAe,OAAA,CAAQ,YAAA;AAAA,EAC9B;AACF;AAEO,IAAM,mBAAN,MAAuB;AAAA,EAiB5B,YAAY,MAAA,EAAsB;AAflC,IAAA,IAAA,CAAQ,WAAA,GAA6B,IAAA;AACrC,IAAA,IAAA,CAAQ,YAAA,GAA8B,IAAA;AACtC,IAAA,IAAA,CAAQ,WAAA,GAA6B,IAAA;AAErC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A,CAAA,EAAA,QAAA,IAAA,EAAA","file":"index.mjs","sourcesContent":["/**\n * Pathao Merchant API Service (Unofficial SDK)\n * \n * This is an unofficial SDK for the Pathao Merchant API.\n * \n * API Details (based on public documentation):\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n * \n * Features implemented:\n * - Token-based authentication with refresh token support\n * - Store management (create, list stores)\n * - Order creation (single and bulk)\n * - Order tracking and status\n * - Dynamic price calculation\n * - City, zone, and area management\n */\n\nimport axios, { AxiosError, AxiosInstance } from 'axios';\nimport {\n PathaoAreaResponse,\n PathaoAuthResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStoreCreateResponse,\n PathaoStoreListResponse,\n PathaoStoreRequest,\n PathaoZoneResponse,\n} from './types';\n\nexport class PathaoApiError extends Error {\n status: number | undefined;\n code: number | undefined;\n type: string | undefined;\n errors: Record<string, string[]> | undefined;\n validation: Record<string, string[]> | undefined;\n responseData: unknown;\n\n constructor(message: string, options: {\n status?: number | undefined;\n code?: number | undefined;\n type?: string | undefined;\n errors?: Record<string, string[]> | undefined;\n validation?: Record<string, string[]> | undefined;\n responseData?: unknown;\n } = {}) {\n super(message);\n this.name = 'PathaoApiError';\n this.status = options.status;\n this.code = options.code;\n this.type = options.type;\n this.errors = options.errors;\n this.validation = options.validation;\n this.responseData = options.responseData;\n }\n}\n\nexport class PathaoApiService {\n private pathaoClient: AxiosInstance;\n private accessToken: string | null = null;\n private refreshToken: string | null = null;\n private tokenExpiry: number | null = null;\n private config: PathaoConfig;\n private isAuthenticating: boolean = false;\n private authPromise: Promise<void> | null = null;\n private requestQueue: Array<{ resolve: () => void; reject: (error: Error) => void }> = [];\n private circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: 5,\n timeout: 60000, // 1 minute\n isOpen: false,\n };\n\n constructor(config: PathaoConfig) {\n this.config = {\n baseURL: config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout: config.timeout || parseInt(process.env.PATHAO_TIMEOUT || '30000', 10),\n clientId: config.clientId || process.env.PATHAO_CLIENT_ID || '',\n clientSecret: config.clientSecret || process.env.PATHAO_CLIENT_SECRET || '',\n username: config.username || process.env.PATHAO_USERNAME || '',\n password: config.password || process.env.PATHAO_PASSWORD || '',\n };\n\n this.pathaoClient = axios.create({\n baseURL: this.config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout: this.config.timeout || parseInt(process.env.PATHAO_TIMEOUT || '30000', 10),\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n });\n\n // Validate required configuration\n if (!this.config.baseURL) {\n throw new Error('Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable');\n }\n \n if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {\n throw new Error('Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)');\n }\n\n // Add request interceptor for authentication\n this.pathaoClient.interceptors.request.use(async (config) => {\n // Skip auth for token requests to prevent infinite loops\n if (config.url?.includes('/issue-token')) {\n return config;\n }\n \n await this.ensureAuthenticated();\n if (this.accessToken) {\n config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return config;\n });\n\n // Add response interceptor for error handling\n this.pathaoClient.interceptors.response.use(\n (response) => {\n // Reset circuit breaker on successful request\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n return response;\n },\n async (error) => {\n if (error.response?.status === 401) {\n // Token expired, clear tokens and retry\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n \n // Retry the request once\n if (error.config && !error.config._retry) {\n error.config._retry = true;\n await this.ensureAuthenticated();\n if (this.accessToken) {\n error.config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return this.pathaoClient.request(error.config);\n }\n }\n \n // Handle circuit breaker\n this.handleCircuitBreaker();\n return Promise.reject(error);\n },\n );\n }\n\n private async ensureAuthenticated(): Promise<void> {\n // Check circuit breaker\n if (this.circuitBreaker.isOpen) {\n if (Date.now() - this.circuitBreaker.lastFailureTime > this.circuitBreaker.timeout) {\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.failures = 0;\n } else {\n throw new Error('Circuit breaker is open. Too many authentication failures.');\n }\n }\n\n if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {\n return; // Token is still valid\n }\n\n // If already authenticating, wait for it to complete\n if (this.isAuthenticating && this.authPromise) {\n return this.authPromise;\n }\n\n // Start authentication process\n this.isAuthenticating = true;\n this.authPromise = this.performAuthentication();\n\n try {\n await this.authPromise;\n } finally {\n this.isAuthenticating = false;\n this.authPromise = null;\n // Process queued requests\n this.processRequestQueue();\n }\n }\n\n private async performAuthentication(): Promise<void> {\n if (this.refreshToken) {\n try {\n await this.refreshAccessToken();\n return;\n } catch (error) {\n // Refresh failed, try fresh authentication\n this.refreshToken = null;\n }\n }\n\n await this.authenticate();\n }\n\n private processRequestQueue(): void {\n const queue = [...this.requestQueue];\n this.requestQueue = [];\n \n queue.forEach(({ resolve }) => {\n try {\n resolve();\n } catch (error) {\n // Ignore errors in queued requests\n }\n });\n }\n\n private async authenticate(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>('/aladdin/api/v1/issue-token', {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n username: this.config.username,\n password: this.config.password,\n grant_type: 'password',\n });\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful auth\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw this.toPathaoApiError(error, 'Authentication failed');\n }\n }\n\n private async refreshAccessToken(): Promise<void> {\n if (!this.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>('/aladdin/api/v1/issue-token', {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n refresh_token: this.refreshToken,\n grant_type: 'refresh_token',\n });\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful refresh\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw this.toPathaoApiError(error, 'Token refresh failed');\n }\n }\n\n private getErrorMessage(error: unknown): string {\n if (error instanceof AxiosError) {\n const pathaoError = error.response?.data as PathaoError;\n if (pathaoError?.message) {\n return pathaoError.message;\n }\n return error.message;\n }\n return (error as Error).message || 'Unknown error';\n }\n\n private toPathaoApiError(error: unknown, context: string): PathaoApiError {\n if (error instanceof PathaoApiError) {\n return error;\n }\n\n const messageFallback = this.getErrorMessage(error);\n const axiosLike = (error instanceof AxiosError) ? error : (typeof error === 'object' && error && 'response' in (error as any) ? error as AxiosError : null);\n if (axiosLike) {\n const pathaoError = axiosLike.response?.data as PathaoError | undefined;\n return new PathaoApiError(`${context}: ${pathaoError?.message || messageFallback}`, {\n status: axiosLike.response?.status,\n code: pathaoError?.code ?? axiosLike.response?.status,\n type: pathaoError?.type,\n errors: pathaoError?.errors,\n validation: pathaoError?.validation,\n responseData: pathaoError ?? axiosLike.response?.data,\n });\n }\n\n return new PathaoApiError(`${context}: ${messageFallback}`);\n }\n\n private handleCircuitBreaker(): void {\n this.circuitBreaker.failures++;\n this.circuitBreaker.lastFailureTime = Date.now();\n \n if (this.circuitBreaker.failures >= this.circuitBreaker.threshold) {\n this.circuitBreaker.isOpen = true;\n }\n }\n\n // Official Pathao API: Create Order\n async createOrder(orderData: PathaoOrderRequest): Promise<PathaoOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoOrderResponse>('/aladdin/api/v1/orders', orderData);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create Pathao order');\n }\n }\n\n // Official Pathao API: Create Store\n async createStore(storeData: PathaoStoreRequest): Promise<PathaoStoreCreateResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoStoreCreateResponse>('/aladdin/api/v1/stores', storeData);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create Pathao store');\n }\n }\n\n // Official Pathao API: Get Store List\n async getStores(): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>('/aladdin/api/v1/stores');\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao stores');\n }\n }\n\n // Official Pathao API: Calculate Price\n async calculatePrice(priceData: PathaoPriceRequest): Promise<PathaoPriceResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoPriceResponse>('/aladdin/api/v1/merchant/price-plan', priceData);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to calculate Pathao price');\n }\n }\n\n // Official Pathao API: Get Cities\n async getCities(): Promise<PathaoCityResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoCityResponse>('/aladdin/api/v1/city-list');\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao cities');\n }\n }\n\n // Official Pathao API: Get Zones for a City\n async getZones(cityId: number): Promise<PathaoZoneResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoZoneResponse>(`/aladdin/api/v1/cities/${cityId}/zone-list`);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao zones');\n }\n }\n\n // Official Pathao API: Get Areas for a Zone\n async getAreas(zoneId: number): Promise<PathaoAreaResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoAreaResponse>(`/aladdin/api/v1/zones/${zoneId}/area-list`);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao areas');\n }\n }\n\n // Official Pathao API: Get Order Status\n async getOrderStatus(consignmentId: string): Promise<PathaoOrderStatusResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoOrderStatusResponse>(`/aladdin/api/v1/orders/${consignmentId}/info`);\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao order status');\n }\n }\n\n // Official Pathao API: Create Bulk Order\n async createBulkOrder(\n orders: PathaoOrderRequest[],\n ): Promise<{ message: string; type: string; code: number; data: boolean }> {\n try {\n const response = await this.pathaoClient.post<{\n message: string;\n type: string;\n code: number;\n data: boolean;\n }>('/aladdin/api/v1/orders/bulk', { orders });\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create bulk Pathao orders');\n }\n }\n\n // Helper method to validate phone number\n static validatePhoneNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, '');\n return cleanPhone.length === 11 && cleanPhone.startsWith('01');\n }\n\n // Helper method to format phone number\n static formatPhoneNumber(phone: string): string {\n const cleanPhone = phone.replace(/\\D/g, '');\n if (cleanPhone.length === 11 && cleanPhone.startsWith('01')) {\n return cleanPhone;\n }\n throw new Error('Invalid phone number format. Must be 11 digits starting with 01');\n }\n\n // Helper method to validate address\n static validateAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 10 && trimmed.length <= 220;\n }\n\n // Helper method to validate weight\n static validateWeight(weight: number): boolean {\n return weight >= 0.5 && weight <= 10;\n }\n\n // Helper method to validate recipient name\n static validateRecipientName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 100;\n }\n\n // Helper method to validate store name\n static validateStoreName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact name\n static validateContactName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact number\n static validateContactNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, '');\n return cleanPhone.length === 11;\n }\n\n // Helper method to validate store address\n static validateStoreAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 15 && trimmed.length <= 120;\n }\n\n // Method to clear authentication state (useful for testing)\n clearAuth(): void {\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n this.isAuthenticating = false;\n this.authPromise = null;\n this.requestQueue = [];\n this.circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: 5,\n timeout: 60000,\n isOpen: false,\n };\n }\n}\n","/**\n * Pathao Courier API Types\n * \n * Official API Details:\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n */\n\n// Official Pathao API Authentication Response\nexport interface PathaoAuthResponse {\n token_type: string;\n expires_in: number;\n access_token: string;\n refresh_token: string;\n}\n\n// Official Pathao Order Creation Request\nexport interface PathaoOrderRequest {\n store_id: number;\n merchant_order_id?: string; // Optional - Your order tracking ID\n recipient_name: string; // Required - 3-100 characters\n recipient_phone: string; // Required - 11 characters\n recipient_secondary_phone?: string; // Optional - 11 characters\n recipient_address: string; // Required - 10-220 characters\n recipient_city?: number; // Optional - Auto-detected if not provided\n recipient_zone?: number; // Optional - Auto-detected if not provided\n recipient_area?: number; // Optional - Auto-detected if not provided\n delivery_type: number; // Required - 48 (Normal), 12 (On Demand)\n item_type: number; // Required - 1 (Document), 2 (Parcel)\n special_instruction?: string; // Optional\n item_quantity: number; // Required\n item_weight: number; // Required - 0.5-10 kg\n item_description?: string; // Optional\n amount_to_collect: number; // Required - COD amount (0 for non-COD)\n}\n\n// Official Pathao Store Creation Request\nexport interface PathaoStoreRequest {\n name: string; // 3-50 characters\n contact_name: string; // 3-50 characters\n contact_number: string; // 11 characters\n secondary_contact?: string; // Optional - 11 characters\n otp_number?: string; // Optional - OTP for orders\n address: string; // 15-120 characters\n city_id: number;\n zone_id: number;\n area_id: number;\n}\n\n// Official Pathao Order Response\nexport interface PathaoOrderResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n delivery_fee: number;\n };\n}\n\n// Official Pathao Store Creation Response\nexport interface PathaoStoreCreateResponse {\n type: string;\n code: number;\n message: string;\n data: {\n store_name: string; // Only store_name returned on creation\n };\n}\n\n// Official Pathao Store List Item (from GET /stores)\nexport interface PathaoStore {\n store_id: number;\n store_name: string;\n store_address: string;\n is_active: number; // 1 for active, 0 for deactivated\n city_id: number;\n zone_id: number;\n hub_id: number;\n is_default_store: boolean;\n is_default_return_store: boolean;\n}\n\n// Official Pathao Store List Response\nexport interface PathaoStoreListResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: PathaoStore[];\n total: number;\n current_page: number;\n per_page: number;\n total_in_page: number;\n last_page: number;\n path: string;\n to: number;\n from: number;\n last_page_url: string;\n first_page_url: string;\n };\n}\n\n// Official Pathao Price Calculation Request\nexport interface PathaoPriceRequest {\n store_id: number;\n item_type: number;\n item_weight: number;\n delivery_type: number;\n recipient_city: number;\n recipient_zone: number;\n}\n\n// Official Pathao Price Response\nexport interface PathaoPriceResponse {\n type: string;\n code: number;\n message: string;\n data: {\n price: number; // Calculated price for given item\n discount: number; // Discount for the given item\n promo_discount: number; // Promo discount for the given item\n plan_id: number; // Price plan id for the given item\n cod_enabled: number; // 1 if COD enabled, 0 if not\n cod_percentage: number; // Cash on delivery percentage\n additional_charge: number; // If there is any additional charge\n final_price: number; // Your final price for the given item\n };\n}\n\n// Official Pathao City Response\nexport interface PathaoCityResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n city_id: number;\n city_name: string;\n }>;\n };\n}\n\n// Official Pathao Order Status Response\nexport interface PathaoOrderStatusResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n order_status_slug: string;\n updated_at: string;\n invoice_id: string | null;\n };\n}\n\n// Official Pathao Zone Response\nexport interface PathaoZoneResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n zone_id: number;\n zone_name: string;\n }>;\n };\n}\n\n// Official Pathao Area Response\nexport interface PathaoAreaResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n area_id: number;\n area_name: string;\n home_delivery_available: boolean;\n pickup_available: boolean;\n }>;\n };\n}\n\n// Configuration options for PathaoApiService\nexport interface PathaoConfig {\n clientId: string;\n clientSecret: string;\n username: string;\n password: string;\n baseURL: string;\n timeout?: number;\n}\n\n// Error response from Pathao API\nexport interface PathaoError {\n type: string;\n code: number;\n message: string;\n errors?: Record<string, string[]>;\n validation?: Record<string, string[]>;\n}\n\n// Delivery types enum\nexport enum DeliveryType {\n NORMAL = 48,\n ON_DEMAND = 12\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2\n}\n\n// Store types enum (removed as not used in official API)\n// export enum StoreType {\n// PICKUP_POINT = 1,\n// SERVICE_POINT = 2\n// }\n"]}
1
+ {"version":3,"sources":["../src/pathao-api.ts","../src/types.ts"],"names":["config","DeliveryType","ItemType"],"mappings":";;;AAsCO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAQxC,WAAA,CACE,OAAA,EACA,OAAA,GAOI,EAAC,EACL;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,gBAAA;AACZ,IAAA,IAAA,CAAK,SAAS,OAAA,CAAQ,MAAA;AACtB,IAAA,IAAA,CAAK,OAAO,OAAA,CAAQ,IAAA;AACpB,IAAA,IA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,EAAQ,OAAO,CAAA;AAAA,EAC7C;AAAA;AAAA,EAGA,OAAO,UAAA,CAAW,MAAA,EAAsB,OAAA,EAAwF;AAC9H,IAAA,OAAO,IAAI,iBAAA,CAAiB,MAAA,EAAQ,OAAO,CAAA;AAAA,EAC7C;AACF;;;AClZO,IAAK,YAAA,qBAAAC,aAAAA,KAAL;AACL,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,YAAS,EAAA,CAAA,GAAT,QAAA;AACA,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,eAAY,EAAA,CAAA,GAAZ,WAAA;AAFU,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAML,IAAK,QAAA,qBAAAC,SAAAA,KAAL;AACL,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,cAAW,CAAA,CAAA,GAAX,UAAA;AACA,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,YAAS,CAAA,CAAA,GAAT,QAAA;AAFU,EAAA,OAAAA,SAAAA;AAAA,CAAA,EAAA,QAAA,IAAA,EAAA","file":"index.mjs","sourcesContent":["/**\n * Pathao Merchant API Service (Unofficial SDK)\n *\n * This is an unofficial SDK for the Pathao Merchant API.\n *\n * API Details (based on public documentation):\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n *\n * Features implemented:\n * - Token-based authentication with refresh token support\n * - Store management (create, list stores)\n * - Order creation (single and bulk)\n * - Order tracking and status\n * - Dynamic price calculation\n * - City, zone, and area management\n */\n\nimport axios, { AxiosError, AxiosInstance } from 'axios';\nimport {\n PathaoAreaResponse,\n PathaoAuthResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStoreCreateResponse,\n PathaoStoreListResponse,\n PathaoStoreRequest,\n PathaoZoneResponse,\n} from './types';\n\nexport class PathaoApiError extends Error {\n status: number | undefined;\n code: number | undefined;\n type: string | undefined;\n errors: Record<string, string[]> | undefined;\n validation: Record<string, string[]> | undefined;\n responseData: unknown;\n\n constructor(\n message: string,\n options: {\n status?: number | undefined;\n code?: number | undefined;\n type?: string | undefined;\n errors?: Record<string, string[]> | undefined;\n validation?: Record<string, string[]> | undefined;\n responseData?: unknown;\n } = {},\n ) {\n super(message);\n this.name = 'PathaoApiError';\n this.status = options.status;\n this.code = options.code;\n this.type = options.type;\n this.errors = options.errors;\n this.validation = options.validation;\n this.responseData = options.responseData;\n }\n}\n\n// Internal resolved config with guaranteed timeout\ninterface ResolvedPathaoConfig extends PathaoConfig {\n timeout: number;\n}\n\n// Circuit breaker configuration\ninterface CircuitBreakerConfig {\n threshold?: number; // Default: 5\n timeout?: number; // Default: 60000ms\n}\n\nexport class PathaoApiService {\n private pathaoClient: AxiosInstance;\n private accessToken: string | null = null;\n private refreshToken: string | null = null;\n private tokenExpiry: number | null = null;\n private config: ResolvedPathaoConfig;\n private isAuthenticating: boolean = false;\n private authPromise: Promise<void> | null = null;\n private requestQueue: Array<{\n resolve: () => void;\n reject: (error: Error) => void;\n }> = [];\n private hasValidated: boolean = false;\n private debug: boolean = false;\n private circuitBreaker: {\n failures: number;\n lastFailureTime: number;\n threshold: number;\n timeout: number;\n isOpen: boolean;\n };\n\n constructor(config: PathaoConfig, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }) {\n const timeout: number =\n config.timeout || parseInt(process.env.PATHAO_TIMEOUT || '30000', 10);\n\n this.config = {\n baseURL: config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout,\n clientId: config.clientId || process.env.PATHAO_CLIENT_ID || '',\n clientSecret:\n config.clientSecret || process.env.PATHAO_CLIENT_SECRET || '',\n username: config.username || process.env.PATHAO_USERNAME || '',\n password: config.password || process.env.PATHAO_PASSWORD || '',\n };\n\n this.debug = options?.debug || false;\n this.circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: options?.circuitBreaker?.threshold ?? 5,\n timeout: options?.circuitBreaker?.timeout ?? 60000,\n isOpen: false,\n };\n\n this.pathaoClient = axios.create({\n baseURL: this.config.baseURL,\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n },\n });\n\n // Add request interceptor for authentication\n this.pathaoClient.interceptors.request.use(async (config) => {\n // Skip auth for token requests to prevent infinite loops\n if (config.url?.includes('/issue-token')) {\n return config;\n }\n\n // Validate configuration on first API call\n this.validateConfiguration();\n await this.ensureAuthenticated();\n if (this.accessToken) {\n config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n\n if (this.debug) {\n console.log(`[Pathao SDK] ${config.method?.toUpperCase()} ${config.url}`, {\n headers: config.headers,\n data: config.data,\n });\n }\n\n return config;\n });\n\n // Add response interceptor for error handling\n this.pathaoClient.interceptors.response.use(\n (response) => {\n // Reset circuit breaker on successful request\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n\n if (this.debug) {\n console.log(`[Pathao SDK] Response ${response.status}`, {\n url: response.config.url,\n data: response.data,\n });\n }\n\n return response;\n },\n async (error) => {\n if (error.response?.status === 401) {\n // Token expired, clear tokens and retry\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n\n // Retry the request once\n if (error.config && !error.config._retry) {\n error.config._retry = true;\n await this.ensureAuthenticated();\n if (this.accessToken) {\n error.config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return this.pathaoClient.request(error.config);\n }\n }\n\n // Handle circuit breaker\n this.handleCircuitBreaker();\n return Promise.reject(error);\n }\n );\n }\n\n private validateConfiguration(): void {\n // Only validate once\n if (this.hasValidated) {\n return;\n }\n\n if (!this.config.baseURL) {\n throw this.toPathaoApiError(\n new Error(\n \"Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable\"\n ),\n \"Configuration validation failed\"\n );\n }\n\n if (\n !this.config.clientId ||\n !this.config.clientSecret ||\n !this.config.username ||\n !this.config.password\n ) {\n throw this.toPathaoApiError(\n new Error(\n \"Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)\"\n ),\n \"Configuration validation failed\"\n );\n }\n\n this.hasValidated = true;\n }\n\n private async ensureAuthenticated(): Promise<void> {\n // Check circuit breaker\n if (this.circuitBreaker.isOpen) {\n if (\n Date.now() - this.circuitBreaker.lastFailureTime >\n this.circuitBreaker.timeout\n ) {\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.failures = 0;\n } else {\n throw new Error(\n \"Circuit breaker is open. Too many authentication failures.\"\n );\n }\n }\n\n if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {\n return; // Token is still valid\n }\n\n // If already authenticating, wait for it to complete\n if (this.isAuthenticating && this.authPromise) {\n return this.authPromise;\n }\n\n // Start authentication process\n this.isAuthenticating = true;\n this.authPromise = this.performAuthentication();\n\n try {\n await this.authPromise;\n } finally {\n this.isAuthenticating = false;\n this.authPromise = null;\n // Process queued requests\n this.processRequestQueue();\n }\n }\n\n private async performAuthentication(): Promise<void> {\n if (this.refreshToken) {\n try {\n await this.refreshAccessToken();\n return;\n } catch (error) {\n // Refresh failed, try fresh authentication\n this.refreshToken = null;\n }\n }\n\n await this.authenticate();\n }\n\n private processRequestQueue(): void {\n const queue = [...this.requestQueue];\n this.requestQueue = [];\n\n queue.forEach(({ resolve }) => {\n try {\n resolve();\n } catch (error) {\n // Ignore errors in queued requests\n }\n });\n }\n\n private async authenticate(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>(\n \"/aladdin/api/v1/issue-token\",\n {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n username: this.config.username,\n password: this.config.password,\n grant_type: \"password\",\n }\n );\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + response.data.expires_in * 1000 - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful auth\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw this.toPathaoApiError(error, \"Authentication failed\");\n }\n }\n\n private async refreshAccessToken(): Promise<void> {\n if (!this.refreshToken) {\n throw new Error(\"No refresh token available\");\n }\n\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>(\n \"/aladdin/api/v1/issue-token\",\n {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n refresh_token: this.refreshToken,\n grant_type: \"refresh_token\",\n }\n );\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + response.data.expires_in * 1000 - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful refresh\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw this.toPathaoApiError(error, \"Token refresh failed\");\n }\n }\n\n private getErrorMessage(error: unknown): string {\n if (error instanceof AxiosError) {\n const pathaoError = error.response?.data as PathaoError;\n if (pathaoError?.message) {\n return pathaoError.message;\n }\n return error.message;\n }\n return (error as Error).message || \"Unknown error\";\n }\n\n private toPathaoApiError(error: unknown, context: string): PathaoApiError {\n if (error instanceof PathaoApiError) {\n return error;\n }\n\n const messageFallback = this.getErrorMessage(error);\n const axiosLike =\n error instanceof AxiosError\n ? error\n : typeof error === \"object\" && error && \"response\" in (error as any)\n ? (error as AxiosError)\n : null;\n if (axiosLike) {\n const pathaoError = axiosLike.response?.data as PathaoError | undefined;\n return new PathaoApiError(\n `${context}: ${pathaoError?.message || messageFallback}`,\n {\n status: axiosLike.response?.status,\n code: pathaoError?.code ?? axiosLike.response?.status,\n type: pathaoError?.type,\n errors: pathaoError?.errors,\n validation: pathaoError?.validation,\n responseData: pathaoError ?? axiosLike.response?.data,\n }\n );\n }\n\n return new PathaoApiError(`${context}: ${messageFallback}`);\n }\n\n private handleCircuitBreaker(): void {\n this.circuitBreaker.failures++;\n this.circuitBreaker.lastFailureTime = Date.now();\n\n if (this.circuitBreaker.failures >= this.circuitBreaker.threshold) {\n this.circuitBreaker.isOpen = true;\n }\n }\n\n // Official Pathao API: Create Order\n async createOrder(\n orderData: PathaoOrderRequest\n ): Promise<PathaoOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoOrderResponse>(\n \"/aladdin/api/v1/orders\",\n orderData\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to create Pathao order\");\n }\n }\n\n // Official Pathao API: Create Store\n async createStore(\n storeData: PathaoStoreRequest\n ): Promise<PathaoStoreCreateResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoStoreCreateResponse>(\n \"/aladdin/api/v1/stores\",\n storeData\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to create Pathao store\");\n }\n }\n\n // Official Pathao API: Get Store List\n async getStores(): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>(\n \"/aladdin/api/v1/stores\"\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao stores\");\n }\n }\n\n // Official Pathao API: Calculate Price\n async calculatePrice(\n priceData: PathaoPriceRequest\n ): Promise<PathaoPriceResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoPriceResponse>(\n \"/aladdin/api/v1/merchant/price-plan\",\n priceData\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to calculate Pathao price\");\n }\n }\n\n // Official Pathao API: Get Cities\n async getCities(): Promise<PathaoCityResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoCityResponse>(\n \"/aladdin/api/v1/city-list\"\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao cities\");\n }\n }\n\n // Official Pathao API: Get Zones for a City\n async getZones(cityId: number): Promise<PathaoZoneResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoZoneResponse>(\n `/aladdin/api/v1/cities/${cityId}/zone-list`\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao zones\");\n }\n }\n\n // Official Pathao API: Get Areas for a Zone\n async getAreas(zoneId: number): Promise<PathaoAreaResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoAreaResponse>(\n `/aladdin/api/v1/zones/${zoneId}/area-list`\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao areas\");\n }\n }\n\n // Official Pathao API: Get Order Status\n async getOrderStatus(\n consignmentId: string\n ): Promise<PathaoOrderStatusResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoOrderStatusResponse>(\n `/aladdin/api/v1/orders/${consignmentId}/info`\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to fetch Pathao order status\");\n }\n }\n\n // Official Pathao API: Create Bulk Order\n async createBulkOrder(\n orders: PathaoOrderRequest[]\n ): Promise<{ message: string; type: string; code: number; data: boolean }> {\n try {\n const response = await this.pathaoClient.post<{\n message: string;\n type: string;\n code: number;\n data: boolean;\n }>(\"/aladdin/api/v1/orders/bulk\", { orders });\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, \"Failed to create bulk Pathao orders\");\n }\n }\n\n // Helper method to validate phone number\n static validatePhoneNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, \"\");\n return cleanPhone.length === 11 && cleanPhone.startsWith(\"01\");\n }\n\n // Helper method to format phone number\n static formatPhoneNumber(phone: string): string {\n const cleanPhone = phone.replace(/\\D/g, \"\");\n if (cleanPhone.length === 11 && cleanPhone.startsWith(\"01\")) {\n return cleanPhone;\n }\n throw new Error(\n \"Invalid phone number format. Must be 11 digits starting with 01\"\n );\n }\n\n // Helper method to validate address\n static validateAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 10 && trimmed.length <= 220;\n }\n\n // Helper method to validate weight\n static validateWeight(weight: number): boolean {\n return weight >= 0.5 && weight <= 10;\n }\n\n // Helper method to validate recipient name\n static validateRecipientName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 100;\n }\n\n // Helper method to validate store name\n static validateStoreName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact name\n static validateContactName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact number\n static validateContactNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, \"\");\n return cleanPhone.length === 11;\n }\n\n // Helper method to validate store address\n static validateStoreAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 15 && trimmed.length <= 120;\n }\n\n // Method to clear authentication state (useful for testing)\n clearAuth(): void {\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n this.isAuthenticating = false;\n this.authPromise = null;\n this.requestQueue = [];\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.lastFailureTime = 0;\n }\n\n // Static factory method to create instance from environment variables\n static fromEnv(options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n const config: PathaoConfig = {\n clientId: \"\",\n clientSecret: \"\",\n username: \"\",\n password: \"\",\n baseURL: \"\",\n };\n return new PathaoApiService(config, options);\n }\n\n // Static factory method to create instance from configuration object\n static fromConfig(config: PathaoConfig, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n return new PathaoApiService(config, options);\n }\n}\n\n","/**\n * Pathao Courier API Types\n * \n * Official API Details:\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n */\n\n// Official Pathao API Authentication Response\nexport interface PathaoAuthResponse {\n token_type: string;\n expires_in: number;\n access_token: string;\n refresh_token: string;\n}\n\n// Official Pathao Order Creation Request\nexport interface PathaoOrderRequest {\n store_id: number;\n merchant_order_id?: string; // Optional - Your order tracking ID\n recipient_name: string; // Required - 3-100 characters\n recipient_phone: string; // Required - 11 characters\n recipient_secondary_phone?: string; // Optional - 11 characters\n recipient_address: string; // Required - 10-220 characters\n recipient_city?: number; // Optional - Auto-detected if not provided\n recipient_zone?: number; // Optional - Auto-detected if not provided\n recipient_area?: number; // Optional - Auto-detected if not provided\n delivery_type: number; // Required - 48 (Normal), 12 (On Demand)\n item_type: number; // Required - 1 (Document), 2 (Parcel)\n special_instruction?: string; // Optional\n item_quantity: number; // Required\n item_weight: number; // Required - 0.5-10 kg\n item_description?: string; // Optional\n amount_to_collect: number; // Required - COD amount (0 for non-COD)\n}\n\n// Official Pathao Store Creation Request\nexport interface PathaoStoreRequest {\n name: string; // 3-50 characters\n contact_name: string; // 3-50 characters\n contact_number: string; // 11 characters\n secondary_contact?: string; // Optional - 11 characters\n otp_number?: string; // Optional - OTP for orders\n address: string; // 15-120 characters\n city_id: number;\n zone_id: number;\n area_id: number;\n}\n\n// Official Pathao Order Response\nexport interface PathaoOrderResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n delivery_fee: number;\n };\n}\n\n// Official Pathao Store Creation Response\nexport interface PathaoStoreCreateResponse {\n type: string;\n code: number;\n message: string;\n data: {\n store_name: string; // Only store_name returned on creation\n };\n}\n\n// Official Pathao Store List Item (from GET /stores)\nexport interface PathaoStore {\n store_id: number;\n store_name: string;\n store_address: string;\n is_active: number; // 1 for active, 0 for deactivated\n city_id: number;\n zone_id: number;\n hub_id: number;\n is_default_store: boolean;\n is_default_return_store: boolean;\n}\n\n// Official Pathao Store List Response\nexport interface PathaoStoreListResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: PathaoStore[];\n total: number;\n current_page: number;\n per_page: number;\n total_in_page: number;\n last_page: number;\n path: string;\n to: number;\n from: number;\n last_page_url: string;\n first_page_url: string;\n };\n}\n\n// Official Pathao Price Calculation Request\nexport interface PathaoPriceRequest {\n store_id: number;\n item_type: number;\n item_weight: number;\n delivery_type: number;\n recipient_city: number;\n recipient_zone: number;\n}\n\n// Official Pathao Price Response\nexport interface PathaoPriceResponse {\n type: string;\n code: number;\n message: string;\n data: {\n price: number; // Calculated price for given item\n discount: number; // Discount for the given item\n promo_discount: number; // Promo discount for the given item\n plan_id: number; // Price plan id for the given item\n cod_enabled: number; // 1 if COD enabled, 0 if not\n cod_percentage: number; // Cash on delivery percentage\n additional_charge: number; // If there is any additional charge\n final_price: number; // Your final price for the given item\n };\n}\n\n// Official Pathao City Response\nexport interface PathaoCityResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n city_id: number;\n city_name: string;\n }>;\n };\n}\n\n// Official Pathao Order Status Response\nexport interface PathaoOrderStatusResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n order_status_slug: string;\n updated_at: string;\n invoice_id: string | null;\n };\n}\n\n// Official Pathao Zone Response\nexport interface PathaoZoneResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n zone_id: number;\n zone_name: string;\n }>;\n };\n}\n\n// Official Pathao Area Response\nexport interface PathaoAreaResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n area_id: number;\n area_name: string;\n home_delivery_available: boolean;\n pickup_available: boolean;\n }>;\n };\n}\n\n// Configuration options for PathaoApiService\nexport interface PathaoConfig {\n clientId: string;\n clientSecret: string;\n username: string;\n password: string;\n baseURL: string;\n timeout?: number; // Optional - defaults to 30000 if not provided\n}\n\n// Error response from Pathao API\nexport interface PathaoError {\n type: string;\n code: number;\n message: string;\n errors?: Record<string, string[]>;\n validation?: Record<string, string[]>;\n}\n\n// Delivery types enum\nexport enum DeliveryType {\n NORMAL = 48,\n ON_DEMAND = 12\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2\n}\n\n// Store types enum (removed as not used in official API)\n// export enum StoreType {\n// PICKUP_POINT = 1,\n// SERVICE_POINT = 2\n// }\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pathao-merchant-sdk",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "Unofficial Pathao Merchant API SDK for Node.js and TypeScript",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",