pathao-merchant-sdk 2.1.0 → 2.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +35 -7
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +35 -7
- package/dist/index.mjs.map +1 -1
- package/dist/webhooks.d.mts +88 -93
- package/dist/webhooks.d.ts +88 -93
- package/dist/webhooks.js +80 -72
- package/dist/webhooks.js.map +1 -1
- package/dist/webhooks.mjs +80 -71
- package/dist/webhooks.mjs.map +1 -1
- package/package.json +3 -2
package/dist/index.d.mts
CHANGED
|
@@ -166,7 +166,7 @@ interface PathaoConfig {
|
|
|
166
166
|
clientSecret: string;
|
|
167
167
|
username: string;
|
|
168
168
|
password: string;
|
|
169
|
-
baseURL
|
|
169
|
+
baseURL?: string;
|
|
170
170
|
timeout?: number;
|
|
171
171
|
}
|
|
172
172
|
interface PathaoError {
|
|
@@ -265,6 +265,7 @@ declare class PathaoApiService {
|
|
|
265
265
|
createOrder(orderData: PathaoOrderRequest): Promise<PathaoOrderResponse>;
|
|
266
266
|
createStore(storeData: PathaoStoreRequest): Promise<PathaoStoreCreateResponse>;
|
|
267
267
|
getStores(page?: number): Promise<PathaoStoreListResponse>;
|
|
268
|
+
getStoresAll(): Promise<PathaoStore[]>;
|
|
268
269
|
calculatePrice(priceData: PathaoPriceRequest): Promise<PathaoPriceResponse>;
|
|
269
270
|
getCities(): Promise<PathaoCityResponse>;
|
|
270
271
|
getZones(cityId: number): Promise<PathaoZoneResponse>;
|
package/dist/index.d.ts
CHANGED
|
@@ -166,7 +166,7 @@ interface PathaoConfig {
|
|
|
166
166
|
clientSecret: string;
|
|
167
167
|
username: string;
|
|
168
168
|
password: string;
|
|
169
|
-
baseURL
|
|
169
|
+
baseURL?: string;
|
|
170
170
|
timeout?: number;
|
|
171
171
|
}
|
|
172
172
|
interface PathaoError {
|
|
@@ -265,6 +265,7 @@ declare class PathaoApiService {
|
|
|
265
265
|
createOrder(orderData: PathaoOrderRequest): Promise<PathaoOrderResponse>;
|
|
266
266
|
createStore(storeData: PathaoStoreRequest): Promise<PathaoStoreCreateResponse>;
|
|
267
267
|
getStores(page?: number): Promise<PathaoStoreListResponse>;
|
|
268
|
+
getStoresAll(): Promise<PathaoStore[]>;
|
|
268
269
|
calculatePrice(priceData: PathaoPriceRequest): Promise<PathaoPriceResponse>;
|
|
269
270
|
getCities(): Promise<PathaoCityResponse>;
|
|
270
271
|
getZones(cityId: number): Promise<PathaoZoneResponse>;
|
package/dist/index.js
CHANGED
|
@@ -48,7 +48,7 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
48
48
|
isOpen: false
|
|
49
49
|
};
|
|
50
50
|
this.pathaoClient = axios__default.default.create({
|
|
51
|
-
baseURL: this.config.baseURL,
|
|
51
|
+
...this.config.baseURL ? { baseURL: this.config.baseURL } : {},
|
|
52
52
|
timeout: this.config.timeout,
|
|
53
53
|
headers: {
|
|
54
54
|
"Content-Type": "application/json",
|
|
@@ -117,7 +117,10 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
117
117
|
return this.pathaoClient.request(error.config);
|
|
118
118
|
}
|
|
119
119
|
}
|
|
120
|
-
|
|
120
|
+
const isUserError = status !== void 0 && status >= 400 && status < 500 && status !== 401 && status !== 429;
|
|
121
|
+
if (!isUserError) {
|
|
122
|
+
this.handleCircuitBreaker();
|
|
123
|
+
}
|
|
121
124
|
return Promise.reject(error);
|
|
122
125
|
}
|
|
123
126
|
);
|
|
@@ -278,6 +281,12 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
278
281
|
// Official Pathao API: Create Order
|
|
279
282
|
async createOrder(orderData) {
|
|
280
283
|
try {
|
|
284
|
+
if (!_PathaoApiService.validatePhoneNumber(orderData.recipient_phone)) {
|
|
285
|
+
throw new PathaoApiError("Validation failed: Invalid recipient_phone format", { code: 400 });
|
|
286
|
+
}
|
|
287
|
+
if (!_PathaoApiService.validateWeight(orderData.item_weight)) {
|
|
288
|
+
throw new PathaoApiError("Validation failed: Invalid item_weight (must be 0.5 to 10)", { code: 400 });
|
|
289
|
+
}
|
|
281
290
|
const response = await this.pathaoClient.post(
|
|
282
291
|
"/aladdin/api/v1/orders",
|
|
283
292
|
orderData
|
|
@@ -311,6 +320,25 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
311
320
|
throw this.toPathaoApiError(error, "Failed to fetch Pathao stores");
|
|
312
321
|
}
|
|
313
322
|
}
|
|
323
|
+
// Official Pathao API: Get All Stores (Auto-paginating helper)
|
|
324
|
+
async getStoresAll() {
|
|
325
|
+
try {
|
|
326
|
+
let currentPage = 1;
|
|
327
|
+
let lastPage = 1;
|
|
328
|
+
const allStores = [];
|
|
329
|
+
do {
|
|
330
|
+
const response = await this.getStores(currentPage);
|
|
331
|
+
if (response.data?.data) {
|
|
332
|
+
allStores.push(...response.data.data);
|
|
333
|
+
}
|
|
334
|
+
lastPage = response.data?.last_page || 1;
|
|
335
|
+
currentPage++;
|
|
336
|
+
} while (currentPage <= lastPage);
|
|
337
|
+
return allStores;
|
|
338
|
+
} catch (error) {
|
|
339
|
+
throw this.toPathaoApiError(error, "Failed to fetch all Pathao stores");
|
|
340
|
+
}
|
|
341
|
+
}
|
|
314
342
|
// Official Pathao API: Calculate Price
|
|
315
343
|
async calculatePrice(priceData) {
|
|
316
344
|
try {
|
|
@@ -442,11 +470,11 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
442
470
|
// Static factory method to create instance from environment variables
|
|
443
471
|
static fromEnv(options) {
|
|
444
472
|
const config = {
|
|
445
|
-
clientId: "",
|
|
446
|
-
clientSecret: "",
|
|
447
|
-
username: "",
|
|
448
|
-
password: "",
|
|
449
|
-
baseURL: ""
|
|
473
|
+
clientId: process.env.PATHAO_CLIENT_ID || "",
|
|
474
|
+
clientSecret: process.env.PATHAO_CLIENT_SECRET || "",
|
|
475
|
+
username: process.env.PATHAO_USERNAME || "",
|
|
476
|
+
password: process.env.PATHAO_PASSWORD || "",
|
|
477
|
+
baseURL: process.env.PATHAO_BASE_URL || ""
|
|
450
478
|
};
|
|
451
479
|
return new _PathaoApiService(config, options);
|
|
452
480
|
}
|
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":";;;;;;;;;AAuCO,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,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;AAaO,IAAM,gBAAA,GAAN,MAAM,iBAAA,CAAiB;AAAA,EAkB5B,WAAA,CAAY,QAAsB,OAAA,EAAsE;AAhBxG,IAAA,IAAA,CAAQ,WAAA,GAA6B,IAAA;AACrC,IAAA,IAAA,CAAQ,YAAA,GAA8B,IAAA;AACtC,IAAA,IAAA,CAAQ,WAAA,GAA6B,IAAA;AAErC,IAAA,IAAA,CAAQ,gBAAA,GAA4B,KAAA;AACpC,IAAA,IAAA,CAAQ,WAAA,GAAoC,IAAA;AAC5C,IAAA,IAAA,CAAQ,YAAA,GAAwB,KAAA;AAChC,IAAA,IAAA,CAAQ,KAAA,GAAiB,KAAA;AAUvB,IAAA,MAAM,gBAAgB,QAAA,CAAS,OAAA,CAAQ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,EACF;AAAA;AAAA,EAGA,OAAO,UAAA,CAAW,WAAA,EAA4C,OAAA,EAAwF;AACpJ,IAAA,OAAO,IAAI,iBAAA;AAAA,MACT,EAAE,GAAG,WAAA,EAAa,OAAA,EAAS,+BAAA,EAAgC;AAAA,MAC3D;AAAA,KACF;AAAA,EACF;AACF;;;AC7aO,IAAK,YAAA,qBAAAC,aAAAA,KAAL;AAEL,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,YAAS,EAAA,CAAA,GAAT,QAAA;AAEA,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,eAAY,EAAA,CAAA,GAAZ,WAAA;AAJU,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAQL,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 PathaoBulkOrderResponse,\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\nexport interface 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 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 parsedTimeout = parseInt(process.env.PATHAO_TIMEOUT || '', 10);\n const envTimeout = Number.isNaN(parsedTimeout) || parsedTimeout <= 0 ? 30000 : parsedTimeout;\n const timeout: number = config.timeout ?? envTimeout;\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 'User-Agent': `pathao-merchant-sdk node/${ process.version}`,\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 const safeHeaders = { ...config.headers } as Record<string, unknown>;\n if (safeHeaders['Authorization']) safeHeaders['Authorization'] = 'Bearer [REDACTED]';\n console.log(`[Pathao SDK] ${config.method?.toUpperCase()} ${config.url}`, {\n headers: safeHeaders,\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 once\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n\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 // Respect Retry-After on 429 (rate limit), retry once\n if (error.response?.status === 429 && error.config && !error.config._rateLimitRetry) {\n error.config._rateLimitRetry = true;\n const retryAfterHeader = error.response.headers['retry-after'] as string | undefined;\n const delayMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1000 : 1000;\n await this.delay(delayMs);\n return this.pathaoClient.request(error.config);\n }\n\n // Retry transient 5xx errors with exponential backoff (max 2 retries)\n const status: number | undefined = error.response?.status;\n if (status !== undefined && status >= 500 && error.config) {\n const retryCount: number = (error.config._retryCount as number | undefined) ?? 0;\n if (retryCount < 2) {\n error.config._retryCount = retryCount + 1;\n await this.delay(Math.min(500 * 2 ** retryCount, 4000));\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 (!this.config.baseURL.startsWith('https://')) {\n throw this.toPathaoApiError(\n new Error('Pathao API baseURL must use HTTPS (https://)'),\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 PathaoApiError(\n 'Circuit breaker is open. Too many authentication failures. Try again later.',\n { code: 503 },\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 }\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 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 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 if (error instanceof Error) return error.message;\n return '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 hasResponse = (e: unknown): e is { response?: AxiosError['response'] } =>\n typeof e === 'object' && e !== null && 'response' in e;\n const axiosLike =\n error instanceof AxiosError\n ? error\n : hasResponse(error)\n ? error\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 private delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\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(page?: number): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>(\n '/aladdin/api/v1/stores',\n page !== undefined ? { params: { page } } : undefined,\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/${encodeURIComponent(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<PathaoBulkOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoBulkOrderResponse>(\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 && cleanPhone.startsWith('01');\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.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(\n config: PathaoConfig,\n options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig },\n ): PathaoApiService {\n return new PathaoApiService(config, options);\n }\n\n // Named constructor for sandbox environment\n static sandbox(credentials: Omit<PathaoConfig, 'baseURL'>, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n return new PathaoApiService(\n { ...credentials, baseURL: 'https://courier-api-sandbox.pathao.com' },\n options,\n );\n }\n\n // Named constructor for production environment\n static production(credentials: Omit<PathaoConfig, 'baseURL'>, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n return new PathaoApiService(\n { ...credentials, baseURL: 'https://api-hermes.pathao.com' },\n options,\n );\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: 0 | 1; // 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: 0 | 1; // 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/**\n * Delivery type codes defined by the Pathao API.\n * Values correspond to Pathao's internal delivery_type IDs.\n * @see https://developers.pathao.com - Order Creation endpoint\n */\nexport enum DeliveryType {\n /** Standard delivery (API value: 48) */\n NORMAL = 48,\n /** Same-day on-demand delivery (API value: 12) */\n ON_DEMAND = 12\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2\n}\n\n// Official Pathao Bulk Order Response\nexport interface PathaoBulkOrderResponse {\n message: string;\n type: string;\n code: number;\n data: boolean;\n}\n\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/pathao-api.ts","../src/types.ts"],"names":["axios","config","AxiosError","DeliveryType","ItemType"],"mappings":";;;;;;;;;AAwCO,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,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;AAaO,IAAM,gBAAA,GAAN,MAAM,iBAAA,CAAiB;AAAA,EAkB5B,WAAA,CAAY,QAAsB,OAAA,EAAsE;AAhBxG,IAAA,IAAA,CAAQ,WAAA,GAA6B,IAAA;AACrC,IAAA,IAAA,CAAQ,YAAA,GAA8B,IAAA;AACtC,IAAA,IAAA,CAAQ,WAAA,GAA6B,IAAA;AAErC,IAAA,IAAA,CAAQ,gBAAA,GAA4B,KAAA;AACpC,IAAA,IAAA,CAAQ,WAAA,GAAoC,IAAA;AAC5C,IAAA,IAAA,CAAQ,YAAA,GAAwB,KAAA;AAChC,IAAA,IAAA,CAAQ,KAAA,GAAiB,KAAA;AAUvB,IAAA,MAAM,gBAAgB,QAAA,CAAS,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A,CAAiB,MAAA,EAAQ,OAAO,CAAA;AAAA,EAC7C;AAAA;AAAA,EAGA,OAAO,OAAA,CAAQ,WAAA,EAA4C,OAAA,EAAwF;AACjJ,IAAA,OAAO,IAAI,iBAAA;AAAA,MACT,EAAE,GAAG,WAAA,EAAa,OAAA,EAAS,wCAAA,EAAyC;AAAA,MACpE;AAAA,KACF;AAAA,EACF;AAAA;AAAA,EAGA,OAAO,UAAA,CAAW,WAAA,EAA4C,OAAA,EAAwF;AACpJ,IAAA,OAAO,IAAI,iBAAA;AAAA,MACT,EAAE,GAAG,WAAA,EAAa,OAAA,EAAS,+BAAA,EAAgC;AAAA,MAC3D;AAAA,KACF;AAAA,EACF;AACF;;;AC9cO,IAAK,YAAA,qBAAAC,aAAAA,KAAL;AAEL,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,YAAS,EAAA,CAAA,GAAT,QAAA;AAEA,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,eAAY,EAAA,CAAA,GAAZ,WAAA;AAJU,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAQL,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 PathaoBulkOrderResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStore,\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\nexport interface 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 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 parsedTimeout = parseInt(process.env.PATHAO_TIMEOUT || '', 10);\n const envTimeout = Number.isNaN(parsedTimeout) || parsedTimeout <= 0 ? 30000 : parsedTimeout;\n const timeout: number = config.timeout ?? envTimeout;\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 ...(this.config.baseURL ? { baseURL: this.config.baseURL } : {}),\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': `pathao-merchant-sdk node/${process.version}`,\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 const safeHeaders = { ...config.headers } as Record<string, unknown>;\n if (safeHeaders['Authorization']) safeHeaders['Authorization'] = 'Bearer [REDACTED]';\n console.log(`[Pathao SDK] ${config.method?.toUpperCase()} ${config.url}`, {\n headers: safeHeaders,\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 once\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n\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 // Respect Retry-After on 429 (rate limit), retry once\n if (error.response?.status === 429 && error.config && !error.config._rateLimitRetry) {\n error.config._rateLimitRetry = true;\n const retryAfterHeader = error.response.headers['retry-after'] as string | undefined;\n const delayMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1000 : 1000;\n await this.delay(delayMs);\n return this.pathaoClient.request(error.config);\n }\n\n // Retry transient 5xx errors with exponential backoff (max 2 retries)\n const status: number | undefined = error.response?.status;\n if (status !== undefined && status >= 500 && error.config) {\n const retryCount: number = (error.config._retryCount as number | undefined) ?? 0;\n if (retryCount < 2) {\n error.config._retryCount = retryCount + 1;\n await this.delay(Math.min(500 * 2 ** retryCount, 4000));\n return this.pathaoClient.request(error.config);\n }\n }\n\n // Handle circuit breaker for network, 5xx, or specific auth/rate-limit failures\n const isUserError = status !== undefined && status >= 400 && status < 500 && status !== 401 && status !== 429;\n if (!isUserError) {\n this.handleCircuitBreaker();\n }\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 (!this.config.baseURL.startsWith('https://')) {\n throw this.toPathaoApiError(\n new Error('Pathao API baseURL must use HTTPS (https://)'),\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 PathaoApiError(\n 'Circuit breaker is open. Too many authentication failures. Try again later.',\n { code: 503 },\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 }\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 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 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 if (error instanceof Error) return error.message;\n return '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 hasResponse = (e: unknown): e is { response?: AxiosError['response'] } =>\n typeof e === 'object' && e !== null && 'response' in e;\n const axiosLike =\n error instanceof AxiosError\n ? error\n : hasResponse(error)\n ? error\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 private delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n // Official Pathao API: Create Order\n async createOrder(\n orderData: PathaoOrderRequest,\n ): Promise<PathaoOrderResponse> {\n try {\n if (!PathaoApiService.validatePhoneNumber(orderData.recipient_phone)) {\n throw new PathaoApiError('Validation failed: Invalid recipient_phone format', { code: 400 });\n }\n if (!PathaoApiService.validateWeight(orderData.item_weight)) {\n throw new PathaoApiError('Validation failed: Invalid item_weight (must be 0.5 to 10)', { code: 400 });\n }\n\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(page?: number): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>(\n '/aladdin/api/v1/stores',\n page !== undefined ? { params: { page } } : undefined,\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: Get All Stores (Auto-paginating helper)\n async getStoresAll(): Promise<PathaoStore[]> {\n try {\n let currentPage = 1;\n let lastPage = 1;\n const allStores: PathaoStore[] = [];\n\n do {\n const response = await this.getStores(currentPage);\n if (response.data?.data) {\n allStores.push(...response.data.data);\n }\n lastPage = response.data?.last_page || 1;\n currentPage++;\n } while (currentPage <= lastPage);\n\n return allStores;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch all 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/${encodeURIComponent(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<PathaoBulkOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoBulkOrderResponse>(\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 && cleanPhone.startsWith('01');\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.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: process.env.PATHAO_CLIENT_ID || '',\n clientSecret: process.env.PATHAO_CLIENT_SECRET || '',\n username: process.env.PATHAO_USERNAME || '',\n password: process.env.PATHAO_PASSWORD || '',\n baseURL: process.env.PATHAO_BASE_URL || '',\n };\n return new PathaoApiService(config, options);\n }\n\n // Static factory method to create instance from configuration object\n static fromConfig(\n config: PathaoConfig,\n options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig },\n ): PathaoApiService {\n return new PathaoApiService(config, options);\n }\n\n // Named constructor for sandbox environment\n static sandbox(credentials: Omit<PathaoConfig, 'baseURL'>, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n return new PathaoApiService(\n { ...credentials, baseURL: 'https://courier-api-sandbox.pathao.com' },\n options,\n );\n }\n\n // Named constructor for production environment\n static production(credentials: Omit<PathaoConfig, 'baseURL'>, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n return new PathaoApiService(\n { ...credentials, baseURL: 'https://api-hermes.pathao.com' },\n options,\n );\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: 0 | 1; // 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: 0 | 1; // 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/**\n * Delivery type codes defined by the Pathao API.\n * Values correspond to Pathao's internal delivery_type IDs.\n * @see https://developers.pathao.com - Order Creation endpoint\n */\nexport enum DeliveryType {\n /** Standard delivery (API value: 48) */\n NORMAL = 48,\n /** Same-day on-demand delivery (API value: 12) */\n ON_DEMAND = 12\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2\n}\n\n// Official Pathao Bulk Order Response\nexport interface PathaoBulkOrderResponse {\n message: string;\n type: string;\n code: number;\n data: boolean;\n}\n\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -42,7 +42,7 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
42
42
|
isOpen: false
|
|
43
43
|
};
|
|
44
44
|
this.pathaoClient = axios.create({
|
|
45
|
-
baseURL: this.config.baseURL,
|
|
45
|
+
...this.config.baseURL ? { baseURL: this.config.baseURL } : {},
|
|
46
46
|
timeout: this.config.timeout,
|
|
47
47
|
headers: {
|
|
48
48
|
"Content-Type": "application/json",
|
|
@@ -111,7 +111,10 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
111
111
|
return this.pathaoClient.request(error.config);
|
|
112
112
|
}
|
|
113
113
|
}
|
|
114
|
-
|
|
114
|
+
const isUserError = status !== void 0 && status >= 400 && status < 500 && status !== 401 && status !== 429;
|
|
115
|
+
if (!isUserError) {
|
|
116
|
+
this.handleCircuitBreaker();
|
|
117
|
+
}
|
|
115
118
|
return Promise.reject(error);
|
|
116
119
|
}
|
|
117
120
|
);
|
|
@@ -272,6 +275,12 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
272
275
|
// Official Pathao API: Create Order
|
|
273
276
|
async createOrder(orderData) {
|
|
274
277
|
try {
|
|
278
|
+
if (!_PathaoApiService.validatePhoneNumber(orderData.recipient_phone)) {
|
|
279
|
+
throw new PathaoApiError("Validation failed: Invalid recipient_phone format", { code: 400 });
|
|
280
|
+
}
|
|
281
|
+
if (!_PathaoApiService.validateWeight(orderData.item_weight)) {
|
|
282
|
+
throw new PathaoApiError("Validation failed: Invalid item_weight (must be 0.5 to 10)", { code: 400 });
|
|
283
|
+
}
|
|
275
284
|
const response = await this.pathaoClient.post(
|
|
276
285
|
"/aladdin/api/v1/orders",
|
|
277
286
|
orderData
|
|
@@ -305,6 +314,25 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
305
314
|
throw this.toPathaoApiError(error, "Failed to fetch Pathao stores");
|
|
306
315
|
}
|
|
307
316
|
}
|
|
317
|
+
// Official Pathao API: Get All Stores (Auto-paginating helper)
|
|
318
|
+
async getStoresAll() {
|
|
319
|
+
try {
|
|
320
|
+
let currentPage = 1;
|
|
321
|
+
let lastPage = 1;
|
|
322
|
+
const allStores = [];
|
|
323
|
+
do {
|
|
324
|
+
const response = await this.getStores(currentPage);
|
|
325
|
+
if (response.data?.data) {
|
|
326
|
+
allStores.push(...response.data.data);
|
|
327
|
+
}
|
|
328
|
+
lastPage = response.data?.last_page || 1;
|
|
329
|
+
currentPage++;
|
|
330
|
+
} while (currentPage <= lastPage);
|
|
331
|
+
return allStores;
|
|
332
|
+
} catch (error) {
|
|
333
|
+
throw this.toPathaoApiError(error, "Failed to fetch all Pathao stores");
|
|
334
|
+
}
|
|
335
|
+
}
|
|
308
336
|
// Official Pathao API: Calculate Price
|
|
309
337
|
async calculatePrice(priceData) {
|
|
310
338
|
try {
|
|
@@ -436,11 +464,11 @@ var PathaoApiService = class _PathaoApiService {
|
|
|
436
464
|
// Static factory method to create instance from environment variables
|
|
437
465
|
static fromEnv(options) {
|
|
438
466
|
const config = {
|
|
439
|
-
clientId: "",
|
|
440
|
-
clientSecret: "",
|
|
441
|
-
username: "",
|
|
442
|
-
password: "",
|
|
443
|
-
baseURL: ""
|
|
467
|
+
clientId: process.env.PATHAO_CLIENT_ID || "",
|
|
468
|
+
clientSecret: process.env.PATHAO_CLIENT_SECRET || "",
|
|
469
|
+
username: process.env.PATHAO_USERNAME || "",
|
|
470
|
+
password: process.env.PATHAO_PASSWORD || "",
|
|
471
|
+
baseURL: process.env.PATHAO_BASE_URL || ""
|
|
444
472
|
};
|
|
445
473
|
return new _PathaoApiService(config, options);
|
|
446
474
|
}
|