@vorlaxen-labs/kargomucuz-sdk 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2026 Hakan Kaygusuz
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # βš“ Kargomucuz SDK
2
+
3
+ [![npm version](https://img.shields.io/badge/npm-v1.0.0-orange.svg)](https://www.npmjs.com/package/@vorlaxen-labs/kargomucuz-sdk)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-orange.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-orange?logo=typescript)](https://www.typescriptlang.org/)
6
+ [![API](https://img.shields.io/badge/API-REST-orange.svg)](https://kargomucuz.com)
7
+
8
+ **Official SDK for Kargomucuz. Unified cargo operations, shipment automation, and enterprise-grade logistics infrastructure.**
9
+
10
+ `@vorlaxen-labs/kargomucuz-sdk` provides a modern, strongly-typed, zero-hassle integration layer for accessing the Kargomucuz API platform.
11
+
12
+ Designed for scalable e-commerce systems, ERP infrastructures, marketplaces, warehouse management software, and modern backend services.
13
+
14
+ ---
15
+
16
+ # πŸ”₯ Why Kargomucuz SDK?
17
+
18
+ Cargo integrations in TΓΌrkiye are usually absolute chaos:
19
+
20
+ * Different authentication systems
21
+ * Different XML/SOAP nightmares
22
+ * Different tracking structures
23
+ * Different provider limitations
24
+ * Different error formats
25
+
26
+ `@vorlaxen-labs/kargomucuz-sdk` normalizes the entire experience into a single, predictable developer workflow.
27
+
28
+ * πŸš€ Unified API abstraction
29
+ * πŸ“¦ Multi-carrier shipment management
30
+ * πŸ”’ Secure token-based authentication
31
+ * ⚑ Fully typed TypeScript support
32
+ * 🌲 Tree-shakable architecture
33
+ * πŸ› οΈ Enterprise-ready infrastructure
34
+ * 🧩 Modular SDK structure
35
+ * πŸ“ˆ High-performance request handling
36
+
37
+ Because nobody wants to debug prehistoric cargo APIs at 3 AM while staring at cursed SOAP XML responses like forbidden ancient scrolls.
38
+
39
+ ---
40
+
41
+ # πŸ“¦ Installation
42
+
43
+ ```bash
44
+ pnpm add @vorlaxen-labs/kargomucuz-sdk
45
+ # or
46
+ npm install @vorlaxen-labs/kargomucuz-sdk
47
+ # or
48
+ yarn add @vorlaxen-labs/kargomucuz-sdk
49
+ ```
50
+
51
+ ---
52
+
53
+ # πŸš€ Quick Start
54
+
55
+ ```ts
56
+ import { Kargomucuz } from '@vorlaxen-labs/kargomucuz-sdk';
57
+
58
+ const km = new Kargomucuz({
59
+ auth: {
60
+ apiKey: process.env.KARGOMUCUZ_API_KEY
61
+ },
62
+
63
+ environment: 'production', // production or development
64
+
65
+ timeout: 10_000,
66
+
67
+ retry: {
68
+ retries: 3,
69
+ backoff: 'exponential'
70
+ },
71
+
72
+ logger: console
73
+ });
74
+ ```
75
+
76
+ ---
77
+
78
+ # πŸ› οΈ SDK Architecture
79
+
80
+ The SDK is built around modular service namespaces.
81
+
82
+ ### Core Modules
83
+
84
+ * Shipments
85
+ * Labels
86
+ * Orders
87
+
88
+ ---
89
+
90
+ # ⚑ Features
91
+
92
+ ### πŸ“¦ Shipment Management
93
+
94
+ Create, manage, cancel, and automate cargo operations from a single API layer.
95
+
96
+ ### πŸ”’ Secure by Default
97
+
98
+ Enterprise-focused authentication and request validation systems.
99
+
100
+ ---
101
+
102
+ # 🌍 Built For
103
+
104
+ * E-Commerce Platforms
105
+ * ERP Systems
106
+ * Warehouse Software
107
+ * Marketplace Infrastructure
108
+ * Logistics Automation
109
+ * Enterprise SaaS Products
110
+ * Modern Node.js Backends
111
+
112
+ ---
113
+
114
+ # 🌲 Tree-Shakable Imports
115
+
116
+ Import only what you use.
117
+
118
+ ```ts
119
+ import { Kargomucuz } from '@vorlaxen-labs/kargomucuz-sdk';
120
+ ```
121
+
122
+ ---
123
+
124
+ # πŸ“– Documentation
125
+
126
+ Full documentation, API references, examples, provider integrations, and advanced guides are available on the official documentation platform.
127
+
128
+ ### Official Links
129
+
130
+ * Website β†’ [https://kargomucuz.com](https://kargomucuz.com)
131
+ * Documentation β†’ [https://docs.vorlaxen.com/projects/kargomucuz-sdk](https://docs.vorlaxen.com/projects/kargomucuz-sdk)
132
+ * API Platform β†’ [https://api.kargomucuz.com](https://api.kargomucuz.com)
133
+
134
+ ---
135
+
136
+ # πŸ“ Design Philosophy
137
+
138
+ > **"Logistics infrastructure should feel invisible."**
139
+
140
+ `@vorlaxen-labs/kargomucuz-sdk` is designed to eliminate operational friction between your application and cargo providers.
141
+
142
+ Instead of forcing developers to deal with fragmented logistics ecosystems, the SDK provides a clean, stable, and scalable abstraction layer.
143
+
144
+ The goal is simple:
145
+
146
+ Write less integration code.
147
+ Ship more packages.
148
+ Lose less sanity.
149
+
150
+ ---
151
+
152
+ # βš–οΈ License
153
+
154
+ Distributed under the MIT License.
155
+
156
+ Built with precision by **Vorlaxen Labs**.
package/dist/index.cjs ADDED
@@ -0,0 +1,10 @@
1
+ "use strict";var R=Object.create;var m=Object.defineProperty;var I=Object.getOwnPropertyDescriptor;var S=Object.getOwnPropertyNames;var C=Object.getPrototypeOf,K=Object.prototype.hasOwnProperty;var T=(o,r)=>{for(var e in r)m(o,e,{get:r[e],enumerable:!0})},A=(o,r,e,s)=>{if(r&&typeof r=="object"||typeof r=="function")for(let t of S(r))!K.call(o,t)&&t!==e&&m(o,t,{get:()=>r[t],enumerable:!(s=I(r,t))||s.enumerable});return o};var _=(o,r,e)=>(e=o!=null?R(C(o)):{},A(r||!o||!o.__esModule?m(e,"default",{value:o,enumerable:!0}):e,o)),w=o=>A(m({},"__esModule",{value:!0}),o);var z={};T(z,{APIError:()=>c,AuthError:()=>d,Currency:()=>v,Kargomucuz:()=>f,KargomucuzError:()=>i,ProviderServiceCode:()=>b});module.exports=w(z);var x=_(require("axios"),1);var l=class{constructor(r){this.logger=null;r===console||r===!0?this.logger=console:typeof r=="object"&&r!==null&&"info"in r&&"error"in r&&(this.logger=r)}info(r,e){this.logger&&this.logger.info(`\x1B[36m[KM-SDK]\x1B[0m ${r}`,e??"")}error(r,e){this.logger&&this.logger.error(`\x1B[31m[KM-SDK-ERROR]\x1B[0m ${r}`,e??"")}};var i=class extends Error{constructor(r){super(r),this.name="KargomucuzError"}};var c=class extends i{constructor(e,s,t){super(e);this.statusCode=s;this.response=t;this.name="APIError"}};var d=class extends i{constructor(r="Authentication failed."){super(r),this.name="AuthError"}};var a=class{constructor(r){this.config=r;let e="https://api.kargomucuz.com";this.logger=new l(r.logger),this.instance=x.default.create({baseURL:e,timeout:r.timeout||1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.auth.apiKey}`,"X-SDK-Client":!0}}),this.initializeInterceptors()}initializeInterceptors(){this.instance.interceptors.request.use(r=>{if(this.config.environment!=="production"){let e=`${r.baseURL}${r.url||""}`;this.logger.info(`\x1B[36m[KM-SDK] ${r.method?.toUpperCase()} -> ${e}\x1B[0m`),r.params&&this.logger.info("Query Params:",JSON.stringify(r.params,null,2)),r.data&&this.logger.info("Body:",JSON.stringify(r.data,null,2))}return r}),this.instance.interceptors.response.use(r=>{let e=r.data;if(this.logger.info("Request Success",e),e.status===!1){let s=e.code||r.status;throw new c(e.message||"API Error",s,e)}return e},r=>{let e=r.response?.data,s=e?.code||r.response?.status;return this.logger.error("Request Failed",e||{message:r.message}),s===401||s===403?Promise.reject(new d(e?.message)):Promise.reject(new c(e?.message||r.message,s,e))})}async httpGet(r,e){return this.instance.get(r,e)}async httpPost(r,e,s){return this.instance.post(r,e,s)}};var g=class extends a{constructor(e){super(e.getConfig());this.client=e}async create(e){let s={type:e.role,title:e.title,location:{country:{id:e.location.countryId},city:{id:e.location.cityId},district:{id:e.location.districtId},address:{line1:e.location.addressLine1},postCode:e.location.postCode},by:{entity:e.contact.fullName,phone1:{phoneCountryCode:e.contact.phoneCountryCode,number:e.contact.phoneNumber},email:e.contact.email}},n=(await this.httpPost("/v1/addresses/0",s))?.payload?.data;if(!n)throw new Error("Address data missing in API response.");return this.mapAddress(n)}async list(){let e=this.client.getUserId(),t=(await this.httpGet(`/v1/addresses/${e}`))?.payload?.data;if(!Array.isArray(t))return{senders:[],receivers:[]};let n=t.map(u=>this.mapAddress(u));return{senders:n.filter(u=>u.role==="sender"),receivers:n.filter(u=>u.role==="receiver")}}async retrieve(e){let s=this.client.getUserId(),n=(await this.httpGet(`/v1/addresses/${s}/${e}`))?.payload?.data;if(!n)throw new Error(`Address with ID ${e} not found.`);return this.mapAddress(n)}async resolve(e){let t=(await this.httpPost("/others/convert-address-id",{id:e.toString()}))?.payload?.data;return Array.isArray(t)?t[0]||null:t||null}mapAddress(e){return{id:e._id,role:e.type,title:e.title,contact:{fullName:e.by?.entity,phone:{number:e.by?.phone1?.number??"",country:e.by?.phone1?.phoneCountryCode??""},email:e.by?.email},location:{country:e.location?.country?.title??"T\xFCrkiye",city:e.location?.city?.title,district:e.location?.district?.title,addressLine:e.location?.address?.line1,postCode:e.location?.postCode},createdAt:e.others?.created}}};var y=class extends a{constructor(e){super(e.getConfig());this.client=e}async get(e){let t=(await this.httpGet("/v1/shipments/desi-or-kgs",{params:{providerServiceCode:e.serviceCode,desiOrKg:e.weightOrDesi}}))?.payload?.data,n=Array.isArray(t)?t[0]:t;if(!n)throw new Error("Pricing data not found for the given parameters.");return{amount:Number(n.amount),currency:(n.currency||"TRY").toUpperCase(),providerCode:e.serviceCode}}};var h=class extends a{constructor(e){super(e.getConfig());this.client=e}async getDetail(e){let s=await this.httpGet(`/v1/shipments/0/${e}`);if(!s.payload?.data)throw new Error(s.message??`Shipment not found: ${e}`);let t=s.payload.data;return{id:t._id,providerServiceCode:t.shipmentInfo?.provider?.serviceCode,trackingNumber:t.shipmentInfo?.shipmentReferenceCode??t.labelData?.barcodeValue,status:t.shipmentInfo?.status,createdAt:t.others?.created,savedSenderAddress:null,savedReceiverAddress:null}}async create(e){let s={title:e.title??"Shipment",explanation:e.explanation??"",providerServiceCode:e.providerServiceCode,packageInfo:e.packageInfo,selectedSenderAddressId:e.sender.id,selectedReceiverAddressId:e.receiver.id,buyerPayShipping:e.buyerPayShipping??!1,buyerPayProduct:e.buyerPayProduct??!1},t=await this.httpPost("/v1/shipments/0",s);if(!t.payload)throw new Error(t.message??"Shipment could not be created.");let n=t.payload;return{id:n.shipmentTransactionId,providerServiceCode:n.providerServiceCode,trackingNumber:void 0,savedSenderAddress:n.savedSenderAddress,savedReceiverAddress:n.savedReceieverAddress}}};var f=class{constructor(r){this.userId="0";this.config=Object.freeze({environment:"production",timeout:1e4,...r})}asUser(r){return this.userId=r,this}getUserId(){return this.userId}getConfig(){return this.config}get addresses(){return new g(this)}get rates(){return new y(this)}get shipments(){return new h(this)}getBaseUrl(){return"https://api.kargomucuz.com/v1"}};var v=(s=>(s.TRY="try",s.USD="usd",s.EUR="eur",s))(v||{}),b=(p=>(p.PTT_FIXED_PRICE="ptt_fixed_price",p.PTT_STANDART_2="ptt_standart_2",p.HEPSIJET_STANDART_2="hepsijet_standart_2",p.SURAT_STANDART_2="surat_standart_2",p.UPS_STANDART_2="ups_standart_2",p.KOLAYGELSIN_STANDART_2="kolaygelsin_standart_2",p.YURTICI_STANDART_2="yurtici_standart_2",p))(b||{});0&&(module.exports={APIError,AuthError,Currency,Kargomucuz,KargomucuzError,ProviderServiceCode});
2
+ /**
3
+ * @file index.ts
4
+ * @description Official Kargomucuz SDK Entry Point
5
+ * @author Hakan Kaygusuz <hakankaygusuz@vorlaxen.com>
6
+ * @copyright (c) 2024 Vorlaxen Labs
7
+ * @license MIT
8
+ *
9
+ * "Building the bridge between modern web and legacy logistics."
10
+ */
@@ -0,0 +1,200 @@
1
+ import { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+
3
+ declare enum Currency {
4
+ TRY = "try",
5
+ USD = "usd",
6
+ EUR = "eur"
7
+ }
8
+ declare enum ProviderServiceCode {
9
+ PTT_FIXED_PRICE = "ptt_fixed_price",
10
+ PTT_STANDART_2 = "ptt_standart_2",
11
+ HEPSIJET_STANDART_2 = "hepsijet_standart_2",
12
+ SURAT_STANDART_2 = "surat_standart_2",
13
+ UPS_STANDART_2 = "ups_standart_2",
14
+ KOLAYGELSIN_STANDART_2 = "kolaygelsin_standart_2",
15
+ YURTICI_STANDART_2 = "yurtici_standart_2"
16
+ }
17
+
18
+ interface IKargomucuzLogger {
19
+ info(message: string, ...args: any[]): void;
20
+ error(message: string, ...args: any[]): void;
21
+ warn?(message: string, ...args: any[]): void;
22
+ debug?(message: string, ...args: any[]): void;
23
+ }
24
+ type IEnvironments = 'production' | 'development';
25
+ interface ApiResponse<T = any> {
26
+ status: boolean;
27
+ message: string;
28
+ payload?: T;
29
+ code?: number;
30
+ errors?: any;
31
+ }
32
+
33
+ declare class HttpClient {
34
+ private readonly config;
35
+ protected readonly instance: AxiosInstance;
36
+ private readonly logger;
37
+ constructor(config: KargomucuzConfig);
38
+ private initializeInterceptors;
39
+ protected httpGet<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
40
+ protected httpPost<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
41
+ }
42
+
43
+ interface AddressCreateOptions {
44
+ role: 'sender' | 'receiver';
45
+ title: string;
46
+ contact: {
47
+ fullName: string;
48
+ phoneCountryCode: string;
49
+ phoneNumber: string;
50
+ email: string;
51
+ };
52
+ location: {
53
+ countryId: string;
54
+ cityId: string | number;
55
+ districtId: string | number;
56
+ addressLine1: string;
57
+ postCode: string;
58
+ };
59
+ }
60
+ interface Address {
61
+ id: string;
62
+ role: "sender" | "receiver";
63
+ title: string;
64
+ contact: {
65
+ fullName: string;
66
+ phone: {
67
+ number: string;
68
+ country: string;
69
+ };
70
+ email: string;
71
+ };
72
+ location: {
73
+ country: string;
74
+ city: string;
75
+ district: string;
76
+ addressLine: string;
77
+ postCode: string;
78
+ };
79
+ createdAt: string;
80
+ }
81
+
82
+ declare class AddressesService extends HttpClient {
83
+ private client;
84
+ constructor(client: Kargomucuz);
85
+ create(options: AddressCreateOptions): Promise<Address>;
86
+ list(): Promise<{
87
+ senders: Address[];
88
+ receivers: Address[];
89
+ }>;
90
+ retrieve(id: string): Promise<Address>;
91
+ resolve(id: string | number): Promise<any | null>;
92
+ private mapAddress;
93
+ }
94
+
95
+ interface RateQueryOptions {
96
+ serviceCode: string;
97
+ weightOrDesi: string | number;
98
+ }
99
+ interface RateResult {
100
+ amount: number;
101
+ currency: string;
102
+ providerCode: string;
103
+ }
104
+
105
+ declare class RatesService extends HttpClient {
106
+ private client;
107
+ constructor(client: Kargomucuz);
108
+ get(params: RateQueryOptions): Promise<RateResult>;
109
+ }
110
+
111
+ interface ShipmentItem {
112
+ name: string;
113
+ quantity: number;
114
+ unitPrice: number;
115
+ }
116
+ interface ShipmentPackageInfo {
117
+ desiOrKg: string;
118
+ width: string;
119
+ height: string;
120
+ depth: string;
121
+ weight: string;
122
+ itemsAmountCurrency: Currency;
123
+ itemsTaxAmount: number;
124
+ itemsAmount: number;
125
+ items: ShipmentItem[];
126
+ }
127
+ interface ShipmentPackageInfo {
128
+ desiOrKg: string;
129
+ width: string;
130
+ height: string;
131
+ depth: string;
132
+ weight: string;
133
+ itemsAmountCurrency: Currency;
134
+ itemsTaxAmount: number;
135
+ itemsAmount: number;
136
+ items: ShipmentItem[];
137
+ }
138
+ interface CreateShipmentRequest {
139
+ sender: Address;
140
+ receiver: Address;
141
+ providerServiceCode: ProviderServiceCode;
142
+ packageInfo: ShipmentPackageInfo;
143
+ title?: string;
144
+ explanation?: string;
145
+ buyerPayShipping?: boolean;
146
+ buyerPayProduct?: boolean;
147
+ }
148
+ interface ShipmentResult {
149
+ id: string;
150
+ providerServiceCode: string;
151
+ trackingNumber?: string;
152
+ status?: string;
153
+ createdAt?: string;
154
+ savedSenderAddress: any | null;
155
+ savedReceiverAddress: any | null;
156
+ }
157
+
158
+ declare class ShipmentService extends HttpClient {
159
+ private readonly client;
160
+ constructor(client: Kargomucuz);
161
+ getDetail(shipmentId: string): Promise<ShipmentResult>;
162
+ create(request: CreateShipmentRequest): Promise<ShipmentResult>;
163
+ }
164
+
165
+ interface KargomucuzConfig {
166
+ auth: {
167
+ apiKey: string;
168
+ };
169
+ environment?: IEnvironments;
170
+ timeout?: number;
171
+ logger?: IKargomucuzLogger | boolean;
172
+ }
173
+ declare class Kargomucuz {
174
+ private readonly config;
175
+ private userId;
176
+ constructor(config: KargomucuzConfig);
177
+ asUser(id: string): this;
178
+ getUserId(): string;
179
+ getConfig(): KargomucuzConfig;
180
+ get addresses(): AddressesService;
181
+ get rates(): RatesService;
182
+ get shipments(): ShipmentService;
183
+ getBaseUrl(): string;
184
+ }
185
+
186
+ declare class KargomucuzError extends Error {
187
+ constructor(message: string);
188
+ }
189
+
190
+ declare class APIError extends KargomucuzError {
191
+ readonly statusCode?: number | undefined;
192
+ readonly response?: any | undefined;
193
+ constructor(message: string, statusCode?: number | undefined, response?: any | undefined);
194
+ }
195
+
196
+ declare class AuthError extends KargomucuzError {
197
+ constructor(message?: string);
198
+ }
199
+
200
+ export { APIError, type ApiResponse, AuthError, Currency, type IEnvironments, type IKargomucuzLogger, Kargomucuz, KargomucuzError, ProviderServiceCode };
@@ -0,0 +1,200 @@
1
+ import { AxiosInstance, AxiosRequestConfig } from 'axios';
2
+
3
+ declare enum Currency {
4
+ TRY = "try",
5
+ USD = "usd",
6
+ EUR = "eur"
7
+ }
8
+ declare enum ProviderServiceCode {
9
+ PTT_FIXED_PRICE = "ptt_fixed_price",
10
+ PTT_STANDART_2 = "ptt_standart_2",
11
+ HEPSIJET_STANDART_2 = "hepsijet_standart_2",
12
+ SURAT_STANDART_2 = "surat_standart_2",
13
+ UPS_STANDART_2 = "ups_standart_2",
14
+ KOLAYGELSIN_STANDART_2 = "kolaygelsin_standart_2",
15
+ YURTICI_STANDART_2 = "yurtici_standart_2"
16
+ }
17
+
18
+ interface IKargomucuzLogger {
19
+ info(message: string, ...args: any[]): void;
20
+ error(message: string, ...args: any[]): void;
21
+ warn?(message: string, ...args: any[]): void;
22
+ debug?(message: string, ...args: any[]): void;
23
+ }
24
+ type IEnvironments = 'production' | 'development';
25
+ interface ApiResponse<T = any> {
26
+ status: boolean;
27
+ message: string;
28
+ payload?: T;
29
+ code?: number;
30
+ errors?: any;
31
+ }
32
+
33
+ declare class HttpClient {
34
+ private readonly config;
35
+ protected readonly instance: AxiosInstance;
36
+ private readonly logger;
37
+ constructor(config: KargomucuzConfig);
38
+ private initializeInterceptors;
39
+ protected httpGet<T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
40
+ protected httpPost<T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>>;
41
+ }
42
+
43
+ interface AddressCreateOptions {
44
+ role: 'sender' | 'receiver';
45
+ title: string;
46
+ contact: {
47
+ fullName: string;
48
+ phoneCountryCode: string;
49
+ phoneNumber: string;
50
+ email: string;
51
+ };
52
+ location: {
53
+ countryId: string;
54
+ cityId: string | number;
55
+ districtId: string | number;
56
+ addressLine1: string;
57
+ postCode: string;
58
+ };
59
+ }
60
+ interface Address {
61
+ id: string;
62
+ role: "sender" | "receiver";
63
+ title: string;
64
+ contact: {
65
+ fullName: string;
66
+ phone: {
67
+ number: string;
68
+ country: string;
69
+ };
70
+ email: string;
71
+ };
72
+ location: {
73
+ country: string;
74
+ city: string;
75
+ district: string;
76
+ addressLine: string;
77
+ postCode: string;
78
+ };
79
+ createdAt: string;
80
+ }
81
+
82
+ declare class AddressesService extends HttpClient {
83
+ private client;
84
+ constructor(client: Kargomucuz);
85
+ create(options: AddressCreateOptions): Promise<Address>;
86
+ list(): Promise<{
87
+ senders: Address[];
88
+ receivers: Address[];
89
+ }>;
90
+ retrieve(id: string): Promise<Address>;
91
+ resolve(id: string | number): Promise<any | null>;
92
+ private mapAddress;
93
+ }
94
+
95
+ interface RateQueryOptions {
96
+ serviceCode: string;
97
+ weightOrDesi: string | number;
98
+ }
99
+ interface RateResult {
100
+ amount: number;
101
+ currency: string;
102
+ providerCode: string;
103
+ }
104
+
105
+ declare class RatesService extends HttpClient {
106
+ private client;
107
+ constructor(client: Kargomucuz);
108
+ get(params: RateQueryOptions): Promise<RateResult>;
109
+ }
110
+
111
+ interface ShipmentItem {
112
+ name: string;
113
+ quantity: number;
114
+ unitPrice: number;
115
+ }
116
+ interface ShipmentPackageInfo {
117
+ desiOrKg: string;
118
+ width: string;
119
+ height: string;
120
+ depth: string;
121
+ weight: string;
122
+ itemsAmountCurrency: Currency;
123
+ itemsTaxAmount: number;
124
+ itemsAmount: number;
125
+ items: ShipmentItem[];
126
+ }
127
+ interface ShipmentPackageInfo {
128
+ desiOrKg: string;
129
+ width: string;
130
+ height: string;
131
+ depth: string;
132
+ weight: string;
133
+ itemsAmountCurrency: Currency;
134
+ itemsTaxAmount: number;
135
+ itemsAmount: number;
136
+ items: ShipmentItem[];
137
+ }
138
+ interface CreateShipmentRequest {
139
+ sender: Address;
140
+ receiver: Address;
141
+ providerServiceCode: ProviderServiceCode;
142
+ packageInfo: ShipmentPackageInfo;
143
+ title?: string;
144
+ explanation?: string;
145
+ buyerPayShipping?: boolean;
146
+ buyerPayProduct?: boolean;
147
+ }
148
+ interface ShipmentResult {
149
+ id: string;
150
+ providerServiceCode: string;
151
+ trackingNumber?: string;
152
+ status?: string;
153
+ createdAt?: string;
154
+ savedSenderAddress: any | null;
155
+ savedReceiverAddress: any | null;
156
+ }
157
+
158
+ declare class ShipmentService extends HttpClient {
159
+ private readonly client;
160
+ constructor(client: Kargomucuz);
161
+ getDetail(shipmentId: string): Promise<ShipmentResult>;
162
+ create(request: CreateShipmentRequest): Promise<ShipmentResult>;
163
+ }
164
+
165
+ interface KargomucuzConfig {
166
+ auth: {
167
+ apiKey: string;
168
+ };
169
+ environment?: IEnvironments;
170
+ timeout?: number;
171
+ logger?: IKargomucuzLogger | boolean;
172
+ }
173
+ declare class Kargomucuz {
174
+ private readonly config;
175
+ private userId;
176
+ constructor(config: KargomucuzConfig);
177
+ asUser(id: string): this;
178
+ getUserId(): string;
179
+ getConfig(): KargomucuzConfig;
180
+ get addresses(): AddressesService;
181
+ get rates(): RatesService;
182
+ get shipments(): ShipmentService;
183
+ getBaseUrl(): string;
184
+ }
185
+
186
+ declare class KargomucuzError extends Error {
187
+ constructor(message: string);
188
+ }
189
+
190
+ declare class APIError extends KargomucuzError {
191
+ readonly statusCode?: number | undefined;
192
+ readonly response?: any | undefined;
193
+ constructor(message: string, statusCode?: number | undefined, response?: any | undefined);
194
+ }
195
+
196
+ declare class AuthError extends KargomucuzError {
197
+ constructor(message?: string);
198
+ }
199
+
200
+ export { APIError, type ApiResponse, AuthError, Currency, type IEnvironments, type IKargomucuzLogger, Kargomucuz, KargomucuzError, ProviderServiceCode };
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ import f from"axios";var m=class{constructor(r){this.logger=null;r===console||r===!0?this.logger=console:typeof r=="object"&&r!==null&&"info"in r&&"error"in r&&(this.logger=r)}info(r,e){this.logger&&this.logger.info(`\x1B[36m[KM-SDK]\x1B[0m ${r}`,e??"")}error(r,e){this.logger&&this.logger.error(`\x1B[31m[KM-SDK-ERROR]\x1B[0m ${r}`,e??"")}};var p=class extends Error{constructor(r){super(r),this.name="KargomucuzError"}};var c=class extends p{constructor(e,t,s){super(e);this.statusCode=t;this.response=s;this.name="APIError"}};var u=class extends p{constructor(r="Authentication failed."){super(r),this.name="AuthError"}};var i=class{constructor(r){this.config=r;let e="https://api.kargomucuz.com";this.logger=new m(r.logger),this.instance=f.create({baseURL:e,timeout:r.timeout||1e4,headers:{"Content-Type":"application/json",Authorization:`Bearer ${r.auth.apiKey}`,"X-SDK-Client":!0}}),this.initializeInterceptors()}initializeInterceptors(){this.instance.interceptors.request.use(r=>{if(this.config.environment!=="production"){let e=`${r.baseURL}${r.url||""}`;this.logger.info(`\x1B[36m[KM-SDK] ${r.method?.toUpperCase()} -> ${e}\x1B[0m`),r.params&&this.logger.info("Query Params:",JSON.stringify(r.params,null,2)),r.data&&this.logger.info("Body:",JSON.stringify(r.data,null,2))}return r}),this.instance.interceptors.response.use(r=>{let e=r.data;if(this.logger.info("Request Success",e),e.status===!1){let t=e.code||r.status;throw new c(e.message||"API Error",t,e)}return e},r=>{let e=r.response?.data,t=e?.code||r.response?.status;return this.logger.error("Request Failed",e||{message:r.message}),t===401||t===403?Promise.reject(new u(e?.message)):Promise.reject(new c(e?.message||r.message,t,e))})}async httpGet(r,e){return this.instance.get(r,e)}async httpPost(r,e,t){return this.instance.post(r,e,t)}};var l=class extends i{constructor(e){super(e.getConfig());this.client=e}async create(e){let t={type:e.role,title:e.title,location:{country:{id:e.location.countryId},city:{id:e.location.cityId},district:{id:e.location.districtId},address:{line1:e.location.addressLine1},postCode:e.location.postCode},by:{entity:e.contact.fullName,phone1:{phoneCountryCode:e.contact.phoneCountryCode,number:e.contact.phoneNumber},email:e.contact.email}},o=(await this.httpPost("/v1/addresses/0",t))?.payload?.data;if(!o)throw new Error("Address data missing in API response.");return this.mapAddress(o)}async list(){let e=this.client.getUserId(),s=(await this.httpGet(`/v1/addresses/${e}`))?.payload?.data;if(!Array.isArray(s))return{senders:[],receivers:[]};let o=s.map(d=>this.mapAddress(d));return{senders:o.filter(d=>d.role==="sender"),receivers:o.filter(d=>d.role==="receiver")}}async retrieve(e){let t=this.client.getUserId(),o=(await this.httpGet(`/v1/addresses/${t}/${e}`))?.payload?.data;if(!o)throw new Error(`Address with ID ${e} not found.`);return this.mapAddress(o)}async resolve(e){let s=(await this.httpPost("/others/convert-address-id",{id:e.toString()}))?.payload?.data;return Array.isArray(s)?s[0]||null:s||null}mapAddress(e){return{id:e._id,role:e.type,title:e.title,contact:{fullName:e.by?.entity,phone:{number:e.by?.phone1?.number??"",country:e.by?.phone1?.phoneCountryCode??""},email:e.by?.email},location:{country:e.location?.country?.title??"T\xFCrkiye",city:e.location?.city?.title,district:e.location?.district?.title,addressLine:e.location?.address?.line1,postCode:e.location?.postCode},createdAt:e.others?.created}}};var g=class extends i{constructor(e){super(e.getConfig());this.client=e}async get(e){let s=(await this.httpGet("/v1/shipments/desi-or-kgs",{params:{providerServiceCode:e.serviceCode,desiOrKg:e.weightOrDesi}}))?.payload?.data,o=Array.isArray(s)?s[0]:s;if(!o)throw new Error("Pricing data not found for the given parameters.");return{amount:Number(o.amount),currency:(o.currency||"TRY").toUpperCase(),providerCode:e.serviceCode}}};var y=class extends i{constructor(e){super(e.getConfig());this.client=e}async getDetail(e){let t=await this.httpGet(`/v1/shipments/0/${e}`);if(!t.payload?.data)throw new Error(t.message??`Shipment not found: ${e}`);let s=t.payload.data;return{id:s._id,providerServiceCode:s.shipmentInfo?.provider?.serviceCode,trackingNumber:s.shipmentInfo?.shipmentReferenceCode??s.labelData?.barcodeValue,status:s.shipmentInfo?.status,createdAt:s.others?.created,savedSenderAddress:null,savedReceiverAddress:null}}async create(e){let t={title:e.title??"Shipment",explanation:e.explanation??"",providerServiceCode:e.providerServiceCode,packageInfo:e.packageInfo,selectedSenderAddressId:e.sender.id,selectedReceiverAddressId:e.receiver.id,buyerPayShipping:e.buyerPayShipping??!1,buyerPayProduct:e.buyerPayProduct??!1},s=await this.httpPost("/v1/shipments/0",t);if(!s.payload)throw new Error(s.message??"Shipment could not be created.");let o=s.payload;return{id:o.shipmentTransactionId,providerServiceCode:o.providerServiceCode,trackingNumber:void 0,savedSenderAddress:o.savedSenderAddress,savedReceiverAddress:o.savedReceieverAddress}}};var h=class{constructor(r){this.userId="0";this.config=Object.freeze({environment:"production",timeout:1e4,...r})}asUser(r){return this.userId=r,this}getUserId(){return this.userId}getConfig(){return this.config}get addresses(){return new l(this)}get rates(){return new g(this)}get shipments(){return new y(this)}getBaseUrl(){return"https://api.kargomucuz.com/v1"}};var A=(t=>(t.TRY="try",t.USD="usd",t.EUR="eur",t))(A||{}),x=(a=>(a.PTT_FIXED_PRICE="ptt_fixed_price",a.PTT_STANDART_2="ptt_standart_2",a.HEPSIJET_STANDART_2="hepsijet_standart_2",a.SURAT_STANDART_2="surat_standart_2",a.UPS_STANDART_2="ups_standart_2",a.KOLAYGELSIN_STANDART_2="kolaygelsin_standart_2",a.YURTICI_STANDART_2="yurtici_standart_2",a))(x||{});export{c as APIError,u as AuthError,A as Currency,h as Kargomucuz,p as KargomucuzError,x as ProviderServiceCode};
2
+ /**
3
+ * @file index.ts
4
+ * @description Official Kargomucuz SDK Entry Point
5
+ * @author Hakan Kaygusuz <hakankaygusuz@vorlaxen.com>
6
+ * @copyright (c) 2024 Vorlaxen Labs
7
+ * @license MIT
8
+ *
9
+ * "Building the bridge between modern web and legacy logistics."
10
+ */
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "@vorlaxen-labs/kargomucuz-sdk",
3
+ "version": "1.0.1",
4
+ "description": "Official SDK for Kargomucuz. Unified cargo operations, shipment automation, and enterprise-grade logistics infrastructure.",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "type": "module",
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "scripts": {
16
+ "build": "tsup",
17
+ "local-build": "npm run build && yalc push --force",
18
+ "test": "jest --verbose --silent=false",
19
+ "lint": "eslint .",
20
+ "release": "standard-version",
21
+ "release:minor": "standard-version --release-as minor",
22
+ "release:major": "standard-version --release-as major",
23
+ "prepublishOnly": "npm run build"
24
+ },
25
+ "peerDependencies": {
26
+ "express": "^4.0.0 || ^5.0.0"
27
+ },
28
+ "devDependencies": {
29
+ "@eslint/js": "^10.0.1",
30
+ "@semantic-release/commit-analyzer": "^13.0.1",
31
+ "@semantic-release/github": "^12.0.6",
32
+ "@semantic-release/npm": "^13.1.5",
33
+ "@semantic-release/release-notes-generator": "^14.1.0",
34
+ "@swc/core": "^1.15.33",
35
+ "@swc/jest": "^0.2.39",
36
+ "@types/jest": "^29.5.14",
37
+ "@types/mocha": "^10.0.10",
38
+ "@types/node": "^25.6.0",
39
+ "@types/supertest": "^7.2.0",
40
+ "@typescript-eslint/eslint-plugin": "^8.59.1",
41
+ "@typescript-eslint/parser": "^8.59.1",
42
+ "dotenv": "^17.4.2",
43
+ "eslint": "^10.3.0",
44
+ "globals": "^17.6.0",
45
+ "jest": "^29.7.0",
46
+ "standard-version": "^9.5.0",
47
+ "supertest": "^7.2.2",
48
+ "tinyglobby": "^0.2.16",
49
+ "tsup": "^8.5.1",
50
+ "typescript": "^6.0.3",
51
+ "typescript-eslint": "^8.59.1"
52
+ },
53
+ "dependencies": {
54
+ "axios": "^1.16.0"
55
+ },
56
+ "pnpm": {
57
+ "onlyBuiltDependencies": [
58
+ "@swc/core",
59
+ "esbuild"
60
+ ]
61
+ }
62
+ }