@winxs/wind 0.1.1 → 0.1.6

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 CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Winxs
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Winxs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
package/README.md CHANGED
@@ -1,187 +1,205 @@
1
- # 🌬️ Wind — @winxs/wind
2
-
3
- [![npm version](https://img.shields.io/npm/v/@winxs/wind)](https://www.npmjs.com/package/@winxs/wind)
4
- [![npm downloads](https://img.shields.io/npm/dm/@winxs/wind)](https://www.npmjs.com/package/@winxs/wind)
5
- [![license](https://img.shields.io/npm/l/@winxs/wind)](LICENSE)
6
- [![TypeScript](https://img.shields.io/badge/TypeScript-ready-blue)](https://www.typescriptlang.org/)
7
- [![npm bundle size](https://img.shields.io/bundlephobia/minzip/@winxs/wind)](https://bundlephobia.com/package/@winxs/wind)
8
-
9
- **Modern HTTP orchestration client for JavaScript & TypeScript**
10
-
11
- > Axios helps you make requests.
12
- > **Wind helps you manage flows.**
13
-
14
- **Wind** is a modern HTTP orchestration client for JavaScript and TypeScript.
15
-
16
- > Axios helps you make requests.
17
- > **Wind helps you manage flows.**
18
-
19
- Wind is built for **real-world APIs** — pagination, retries, batching, circuit breakers, and failure-safe third-party integrations.
20
-
21
- ---
22
-
23
- ## ✨ Why Wind?
24
-
25
- Most HTTP clients stop at `request → response`.
26
-
27
- In real systems you also need:
28
-
29
- - Pagination without writing loops
30
- - Safe retries
31
- - Partial-failure batch calls
32
- - Protection against unstable third-party APIs
33
- - Worker & SSR-friendly (no global state, isolated clients)
34
- > ⚠️ For SSR or workers, always create a new client using `wind()` or `windClient`.
35
-
36
-
37
- **Wind provides these as first-class primitives.**
38
-
39
- ---
40
-
41
- ## 🚀 Features
42
-
43
- - ⚡ **Simple API** (Axios-style defaults)
44
- - 🔁 **Built-in retry support**
45
- - 🔌 **Circuit breaker** for failing APIs
46
- - 📄 **Pagination as async iterators**
47
- - 📦 **Batch requests with partial failures**
48
- - 🧵 **Worker & SSR safe** (no global mutation)
49
- - 🪶 **Lightweight & dependency-minimal**
50
-
51
- ### 🌍 Runtime Environments
52
-
53
- Wind is designed to run in:
54
-
55
- - Browsers
56
- - Node.js (18+)
57
- - Workers / Edge runtimes
58
-
59
- > Wind does not rely on global mutable state,
60
- making it safe for concurrent and isolated environments.
61
-
62
- ---
63
-
64
- ## 📦 Installation
65
-
66
- ```bash
67
- npm install @winxs/wind
68
- ```
69
- ## 🧩 Usage
70
- ### 1️⃣ Quick (Axios-style)
71
- ```ts
72
-
73
- import wind from "@winxs/wind";
74
- const users = await wind.get("/users");
75
- The default wind client is shared.
76
- For production, workers, or multiple APIs — prefer the factory or class.
77
- ```
78
-
79
- ### 2️⃣ Recommended: Factory API
80
- ```ts
81
- import { wind } from "@winxs/wind";
82
-
83
- const api = wind({
84
- baseURL: "https://api.example.com",
85
- });
86
-
87
- const users = await api.get("/users");
88
- ```
89
- ### 3️⃣ Advanced: Isolated Client
90
- ```ts
91
- import { windClient } from "@winxs/wind";
92
-
93
- const github = new windClient("https://api.github.com");
94
-
95
- const repos = await github.get("/users/octocat/repos");
96
- ```
97
- ### 🔁 Pagination (No Loops)
98
- #### ❌ Traditional approach
99
- ```ts
100
- let page = 1;
101
- while (true) {
102
- const res = await fetch(`/users?page=${page}`);
103
- if (!res.length) break;
104
- page++;
105
- }
106
- ```
107
- ### Wind way
108
- ```ts
109
- for await (const page of api.paginate("/users")) {
110
- console.log(page);
111
- }
112
- ```
113
- * Lazy
114
- * Memory-safe
115
- * Failure-aware
116
-
117
- ### 📦 Batch Requests (Promise.all++)
118
- #### ❌ Traditional
119
- ```ts
120
- await Promise.all([
121
- fetch("/a"),
122
- fetch("/b"),
123
- ]);
124
- ```
125
- #### ✅ Wind
126
- ```ts
127
- const { results, errors } = await api.batch(
128
- [
129
- () => api.get("/a"),
130
- () => api.get("/b"),
131
- ],
132
- { concurrency: 2 }
133
- );
134
- ```
135
- * Controlled concurrency
136
- * Partial success support
137
- * No global failures
138
-
139
- ### 🔌 Circuit Breaker
140
- 1. Wind protects your system from unstable APIs.
141
- 2. Trips on network failures
142
- 3. Trips on 5xx responses
143
- 4. Trips on rate-limits (429)
144
- 5. Ignores 4xx & validation errors
145
-
146
- ```ts
147
- await api.get("/third-party"); // auto-protected
148
- ```
149
- * When the circuit is open, requests fail fast instead of cascading failures.
150
-
151
- ### 🔁 Retry Support
152
- ```ts
153
- await api.get("/unstable", {
154
- retry: {
155
- attempts: 3,
156
- },
157
- });
158
- ```
159
- * Retry happens before circuit breaker evaluation.
160
-
161
- ### 🔄 Axios Wind Migration
162
- #### Axios
163
- ```ts
164
- import axios from "axios";
165
- axios.get("/users");
166
- ```
167
- #### Wind
168
- ```ts
169
- import wind from "@winxs/wind";
170
- wind.get("/users");
171
- ```
172
- #### Axios Instance
173
- ```ts
174
- const api = axios.create({ baseURL });
175
- ```
176
- #### Wind Factory
177
- ```ts
178
- const api = wind({ baseURL });
179
- ```
180
- #### Axios Pagination
181
- ```ts
182
- // manual looping
183
- ```
184
- #### Wind Pagination
185
- ```ts
186
- for await (const page of api.paginate("/users")) {}
1
+ # 🌬️ Wind — @winxs/wind
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@winxs/wind)](https://www.npmjs.com/package/@winxs/wind)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@winxs/wind)](https://www.npmjs.com/package/@winxs/wind)
5
+ [![license](https://img.shields.io/npm/l/@winxs/wind)](LICENSE)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-ready-blue)](https://www.typescriptlang.org/)
7
+ [![npm bundle size](https://img.shields.io/bundlephobia/minzip/@winxs/wind)](https://bundlephobia.com/package/@winxs/wind)
8
+
9
+ **Modern HTTP orchestration client for JavaScript & TypeScript**
10
+
11
+ > Axios helps you make requests.
12
+ > **Wind helps you manage flows.**
13
+
14
+ **Wind** is a modern HTTP orchestration client for JavaScript and TypeScript.
15
+
16
+ > Axios helps you make requests.
17
+ > **Wind helps you manage flows.**
18
+
19
+ Wind is built for **real-world APIs** — pagination, retries, batching, circuit breakers, and failure-safe third-party integrations.
20
+
21
+ ---
22
+
23
+ ## ✨ Why Wind?
24
+
25
+ Most HTTP clients stop at `request → response`.
26
+
27
+ In real systems you also need:
28
+
29
+ - Pagination without writing loops
30
+ - Safe retries
31
+ - Partial-failure batch calls
32
+ - Protection against unstable third-party APIs
33
+ - Worker & SSR-friendly (no global state, isolated clients)
34
+ > ⚠️ For SSR or workers, always create a new client using `wind()` or `windClient`.
35
+
36
+
37
+ **Wind provides these as first-class primitives.**
38
+
39
+ ---
40
+
41
+ ## 🚀 Features
42
+
43
+ - ⚡ **Simple API** (Axios-style defaults)
44
+ - 🔁 **Built-in retry support**
45
+ - 🔌 **Circuit breaker** for failing APIs
46
+ - 📄 **Pagination as async iterators**
47
+ - 📦 **Batch requests with partial failures**
48
+ - 🧵 **Worker & SSR safe** (no global mutation)
49
+ - 🪶 **Lightweight & dependency-minimal**
50
+
51
+ ### 🌍 Runtime Environments
52
+
53
+ Wind is designed to run in:
54
+
55
+ - Browsers
56
+ - Node.js (18+)
57
+ - Workers / Edge runtimes
58
+
59
+ > Wind does not rely on global mutable state,
60
+ making it safe for concurrent and isolated environments.
61
+
62
+ ---
63
+
64
+ ## 📦 Installation
65
+
66
+ ```bash
67
+ npm install @winxs/wind
68
+ ```
69
+ ## 🧩 Usage
70
+ ### 1️⃣ Quick (Axios-style)
71
+ ```ts
72
+ import wind from "@winxs/wind";
73
+ const users = await wind.get("/users");
74
+ ```
75
+ * The default wind client is shared.
76
+ * For production, workers, or multiple APIs — prefer the factory or class.
77
+
78
+ ### 2️⃣ Recommended: Factory API
79
+ ```ts
80
+ import { wind } from "@winxs/wind";
81
+
82
+ const api = wind({
83
+ baseURL: "https://api.example.com",
84
+ });
85
+
86
+ const users = await api.get("/users");
87
+ ```
88
+ ### 3️⃣ Advanced: Isolated Client
89
+ ```ts
90
+ import { windClient } from "@winxs/wind";
91
+
92
+ const github = new windClient("https://api.github.com");
93
+
94
+ const repos = await github.get("/users/octocat/repos");
95
+ ```
96
+ ### 🔁 Pagination (No Loops)
97
+ #### Traditional approach
98
+ ```ts
99
+ let page = 1;
100
+ while (true) {
101
+ const res = await fetch(`/users?page=${page}`);
102
+ if (!res.length) break;
103
+ page++;
104
+ }
105
+ ```
106
+ ### ✅ Wind way
107
+ #### Config :
108
+ ```ts
109
+ let config ={
110
+ FIXED_PARAMS : {'Env' : 'Prod'},
111
+ TOTAL_SIZE : 10000,
112
+ CHUNK_SIZE : 200,
113
+ stopOnEmpty : true,
114
+ options : {
115
+ method : "POST"
116
+ headers : {authorization : 'Bearer eyeacuh'}
117
+ body: {}
118
+ },
119
+ PARAMS_KEY?: {
120
+ CHUNK_PAGINATION_KEY: 'Start',
121
+ CHUNK_SIZE_KEY: 'Size'
122
+ };
123
+ }
124
+ ```
125
+ ```ts
126
+
127
+ for await (const page of api.paginate("/users", body, config)) {
128
+ console.log(page);
129
+ }
130
+ ```
131
+ * Lazy
132
+ * Memory-safe
133
+ * Failure-aware
134
+
135
+ ### 📦 Batch Requests (Promise.all++)
136
+ #### Traditional
137
+ ```ts
138
+ await Promise.all([
139
+ fetch("/a"),
140
+ fetch("/b"),
141
+ ]);
142
+ ```
143
+ #### Wind
144
+ ```ts
145
+ const { results, errors } = await api.batch(
146
+ [
147
+ () => api.get("/a"),
148
+ () => api.get("/b"),
149
+ ],
150
+ { concurrency: 2 }
151
+ );
152
+ ```
153
+ * Controlled concurrency
154
+ * Partial success support
155
+ * No global failures
156
+
157
+ ### 🔌 Circuit Breaker
158
+ 1. Wind protects your system from unstable APIs.
159
+ 2. Trips on network failures
160
+ 3. Trips on 5xx responses
161
+ 4. Trips on rate-limits (429)
162
+ 5. Ignores 4xx & validation errors
163
+
164
+ ```ts
165
+ await api.get("/third-party"); // auto-protected
166
+ ```
167
+ * When the circuit is open, requests fail fast instead of cascading failures.
168
+
169
+ ### 🔁 Retry Support
170
+ ```ts
171
+ await api.get("/unstable", {
172
+ retry: {
173
+ attempts: 3,
174
+ },
175
+ });
176
+ ```
177
+ * Retry happens before circuit breaker evaluation.
178
+
179
+ ### 🔄 Axios → Wind Migration
180
+ #### Axios
181
+ ```ts
182
+ import axios from "axios";
183
+ axios.get("/users");
184
+ ```
185
+ #### Wind
186
+ ```ts
187
+ import wind from "@winxs/wind";
188
+ wind.get("/users");
189
+ ```
190
+ #### Axios Instance
191
+ ```ts
192
+ const api = axios.create({ baseURL });
193
+ ```
194
+ #### Wind Factory
195
+ ```ts
196
+ const api = wind({ baseURL });
197
+ ```
198
+ #### Axios Pagination
199
+ ```ts
200
+ // manual looping
201
+ ```
202
+ #### Wind Pagination
203
+ ```ts
204
+ for await (const page of api.paginate("/users", body, config)) {}
187
205
  ```
@@ -0,0 +1,254 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ default: () => index_default,
24
+ wind: () => wind,
25
+ windClient: () => windClient
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+
29
+ // src/Utility/HttpError.ts
30
+ var HttpError = class extends Error {
31
+ constructor(message, type, status, response) {
32
+ super(message);
33
+ this.type = type;
34
+ this.status = status;
35
+ this.response = response;
36
+ }
37
+ };
38
+ function classifyError(err) {
39
+ if (err instanceof HttpError) return err;
40
+ if (err.name === "AbortError") return new HttpError("Request Timed Out", "TIMEOUT");
41
+ if (err.status) {
42
+ if (err.status === 429) return new HttpError("Rate limited", "RATE_LIMIT", 429);
43
+ if (err.status >= 500) return new HttpError("Server error", "SERVER", err.status);
44
+ if (err.status >= 400) return new HttpError("Client error", "CLIENT", err.status);
45
+ }
46
+ return new HttpError(err.message || "Unknown error", "UNKNOWN");
47
+ }
48
+
49
+ // src/Utility/coreRequest.ts
50
+ async function coreRequest(url, options) {
51
+ const controller = new AbortController();
52
+ if (options.timeoutMS) {
53
+ setTimeout(() => controller.abort(), options.timeoutMS);
54
+ }
55
+ let finalUrl = url;
56
+ if (options.params) {
57
+ const searchParams = new URLSearchParams(
58
+ Object.entries(options.params).map(([key, value]) => [
59
+ key,
60
+ String(value)
61
+ ])
62
+ );
63
+ finalUrl += `?${searchParams.toString()}`;
64
+ }
65
+ const res = await fetch(finalUrl, {
66
+ method: options.method ?? "GET",
67
+ headers: {
68
+ "Content-Type": "application/json",
69
+ ...options.headers
70
+ },
71
+ body: options.body ? JSON.stringify(options.body) : void 0,
72
+ signal: controller.signal
73
+ });
74
+ let text;
75
+ try {
76
+ text = await res.text();
77
+ } catch {
78
+ throw new HttpError("Failed to read response", "NETWORK", res.status);
79
+ }
80
+ let data = null;
81
+ if (text) {
82
+ try {
83
+ data = JSON.parse(text);
84
+ } catch {
85
+ throw new HttpError("Invalid JSON Response", "SCHEMA", res.status, text);
86
+ }
87
+ }
88
+ if (!res.ok) {
89
+ throw new HttpError("HTTP Error", "CLIENT", res.status, data);
90
+ }
91
+ return data;
92
+ }
93
+
94
+ // src/Utility/Retry.ts
95
+ async function withRetry(fn, options) {
96
+ const {
97
+ attempts,
98
+ backOffMs = 3e4,
99
+ //5 mins
100
+ retryOn = ["NETWORK", "TIMEOUT", "RATE_LIMIT", "SERVER", "UNKNOWN"]
101
+ } = options;
102
+ let lastError;
103
+ for (let i = 0; i < attempts; i++) {
104
+ try {
105
+ let { data, error } = await fn();
106
+ if (!!error) {
107
+ throw error;
108
+ }
109
+ return { data, error };
110
+ } catch (err) {
111
+ let classified = classifyError(err);
112
+ lastError = classified;
113
+ if (!retryOn.includes(classified.type)) throw classified;
114
+ await new Promise((r) => setTimeout(r, backOffMs * (i + 1)));
115
+ }
116
+ }
117
+ throw lastError;
118
+ }
119
+
120
+ // src/Utility/CircuitBreaker.ts
121
+ var CircuitBreaker = class {
122
+ constructor(threshold = 5, timeoutMs = 1e4) {
123
+ this.threshold = threshold;
124
+ this.timeoutMs = timeoutMs;
125
+ this.failures = 0;
126
+ this.lastFailure = 0;
127
+ }
128
+ canRequest() {
129
+ if (this.failures < this.threshold) return true;
130
+ return Date.now() - this.lastFailure > this.timeoutMs;
131
+ }
132
+ success() {
133
+ this.failures = 0;
134
+ }
135
+ failure() {
136
+ this.failures++;
137
+ this.lastFailure = Date.now();
138
+ }
139
+ };
140
+
141
+ // src/Helper/Pagination.ts
142
+ async function* paginate(fetcher, path, body, config = {}) {
143
+ let FIXED_PARAMS = "";
144
+ if (config.FIXED_PARAMS) {
145
+ Object.entries(config.FIXED_PARAMS).forEach(
146
+ ([key, value]) => FIXED_PARAMS += `&${key}=${value}`
147
+ );
148
+ }
149
+ const pages = pagination(config.TOTAL_SIZE, config.CHUNK_SIZE);
150
+ const CHUNK_PAGINATION_KEY = config.PARAMS_KEY?.CHUNK_PAGINATION_KEY;
151
+ const CHUNK_SIZE_KEY = config.PARAMS_KEY?.CHUNK_SIZE_KEY;
152
+ if (Array.isArray(pages)) {
153
+ for (const page of pages) {
154
+ const paramsPath = `${CHUNK_PAGINATION_KEY}=${page.CHUNK_START}&${CHUNK_SIZE_KEY}=${page.CHUNK_SIZE}` + FIXED_PARAMS;
155
+ const data = await fetcher(`${path}?${paramsPath}`, body, { ...config.options });
156
+ if (config.stopOnEmpty !== false && (!data || Array.isArray(data) && data.length === 0)) {
157
+ break;
158
+ }
159
+ yield data;
160
+ }
161
+ }
162
+ }
163
+ function pagination(TOTAL_SIZE = 2e3, CHUNK_SIZE = 2e3, start = 1) {
164
+ try {
165
+ const totalChunks = Math.ceil(TOTAL_SIZE / CHUNK_SIZE);
166
+ CHUNK_SIZE = TOTAL_SIZE < CHUNK_SIZE ? TOTAL_SIZE : CHUNK_SIZE;
167
+ const requests = Array.from({ length: totalChunks }, (_, index) => {
168
+ const CHUNK_START = start + index * CHUNK_SIZE;
169
+ return { CHUNK_START, CHUNK_SIZE };
170
+ });
171
+ return requests;
172
+ } catch (error) {
173
+ throw error;
174
+ }
175
+ }
176
+
177
+ // src/Helper/Batch.ts
178
+ async function batch(tasks, options = {}) {
179
+ const concurrency = options.concurrency ?? tasks.length;
180
+ const failFast = options.failFast ?? false;
181
+ const results = [];
182
+ const errors = [];
183
+ let index = 0;
184
+ async function worker() {
185
+ while (index < tasks.length) {
186
+ const i = index++;
187
+ try {
188
+ results[i] = await tasks[i]();
189
+ } catch (err) {
190
+ errors[i] = err;
191
+ if (failFast) throw err;
192
+ }
193
+ }
194
+ }
195
+ await Promise.all(
196
+ Array.from({ length: concurrency }, worker)
197
+ );
198
+ return { results, errors };
199
+ }
200
+
201
+ // src/index.ts
202
+ var windClient = class {
203
+ constructor(baseURL = "") {
204
+ this.baseURL = baseURL;
205
+ this.breaker = new CircuitBreaker();
206
+ }
207
+ async request(path, options = {}) {
208
+ if (!this.breaker.canRequest()) {
209
+ throw new Error("Circuit breaker is open");
210
+ }
211
+ const exec = async () => {
212
+ return await coreRequest(this.baseURL + path, options);
213
+ };
214
+ try {
215
+ const result = options.retry ? await withRetry(exec, options.retry) : await exec();
216
+ this.breaker.success();
217
+ return result;
218
+ } catch (err) {
219
+ if (this.shouldTripBreaker(err)) {
220
+ this.breaker.failure();
221
+ }
222
+ throw err;
223
+ }
224
+ }
225
+ get(path, options) {
226
+ return this.request(path, { ...options, method: "GET" });
227
+ }
228
+ post(path, body, options) {
229
+ return this.request(path, { ...options, method: "POST", body });
230
+ }
231
+ paginate(path, body, config) {
232
+ return paginate(this.post.bind(this), path, body, config);
233
+ }
234
+ batch(tasks, options) {
235
+ return batch(tasks, options);
236
+ }
237
+ shouldTripBreaker(err) {
238
+ const status = err?.status;
239
+ if (!status) return true;
240
+ if (status >= 500) return true;
241
+ if (status === 429) return true;
242
+ return false;
243
+ }
244
+ };
245
+ function wind(config = {}) {
246
+ return new windClient(config.baseURL ?? "");
247
+ }
248
+ var defaultWind = new windClient();
249
+ var index_default = defaultWind;
250
+ // Annotate the CommonJS export names for ESM import in node:
251
+ 0 && (module.exports = {
252
+ wind,
253
+ windClient
254
+ });
@@ -8,7 +8,7 @@ declare class HttpError extends Error {
8
8
  }
9
9
 
10
10
  interface RetryOptions {
11
- attemps: number;
11
+ attempts: number;
12
12
  backOffMs?: number;
13
13
  retryOn?: ErrorType[];
14
14
  }
@@ -18,14 +18,20 @@ interface RequestOptions {
18
18
  headers?: Record<string, string>;
19
19
  body?: any;
20
20
  timeoutMS?: number;
21
+ params?: any;
21
22
  retry?: RetryOptions;
22
23
  }
23
24
 
24
25
  interface PaginationConfig {
25
- pageParam?: string;
26
- startPage?: number;
26
+ FIXED_PARAMS?: Record<string, string | number>;
27
+ TOTAL_SIZE?: number;
28
+ CHUNK_SIZE?: number;
27
29
  stopOnEmpty?: boolean;
28
30
  options?: RequestOptions;
31
+ PARAMS_KEY?: {
32
+ CHUNK_PAGINATION_KEY?: string;
33
+ CHUNK_SIZE_KEY?: string;
34
+ };
29
35
  }
30
36
 
31
37
  interface BatchOptions {
@@ -40,7 +46,7 @@ declare class windClient {
40
46
  request<T>(path: string, options?: RequestOptions): Promise<T>;
41
47
  get<T>(path: string, options?: RequestOptions): Promise<T>;
42
48
  post<T>(path: string, body: any, options?: RequestOptions): Promise<T>;
43
- paginate<T>(path: string, config?: PaginationConfig): AsyncGenerator<T, any, any>;
49
+ paginate<T>(path: string, body: any, config?: PaginationConfig): AsyncGenerator<T, any, any>;
44
50
  batch<T>(tasks: (() => Promise<T>)[], options?: BatchOptions): Promise<{
45
51
  results: T[];
46
52
  errors: HttpError[];
@@ -24,21 +24,38 @@ async function coreRequest(url, options) {
24
24
  if (options.timeoutMS) {
25
25
  setTimeout(() => controller.abort(), options.timeoutMS);
26
26
  }
27
- const res = await fetch(url, {
28
- method: options.method || "GET",
27
+ let finalUrl = url;
28
+ if (options.params) {
29
+ const searchParams = new URLSearchParams(
30
+ Object.entries(options.params).map(([key, value]) => [
31
+ key,
32
+ String(value)
33
+ ])
34
+ );
35
+ finalUrl += `?${searchParams.toString()}`;
36
+ }
37
+ const res = await fetch(finalUrl, {
38
+ method: options.method ?? "GET",
29
39
  headers: {
40
+ "Content-Type": "application/json",
30
41
  ...options.headers
31
42
  },
32
43
  body: options.body ? JSON.stringify(options.body) : void 0,
33
44
  signal: controller.signal
34
45
  });
35
- let data = null;
36
- let text = null;
46
+ let text;
37
47
  try {
38
48
  text = await res.text();
39
- data = text ? JSON.parse(text) : null;
40
49
  } catch {
41
- throw new HttpError("Invalid JSON Response", "SCHEMA", res.status, text);
50
+ throw new HttpError("Failed to read response", "NETWORK", res.status);
51
+ }
52
+ let data = null;
53
+ if (text) {
54
+ try {
55
+ data = JSON.parse(text);
56
+ } catch {
57
+ throw new HttpError("Invalid JSON Response", "SCHEMA", res.status, text);
58
+ }
42
59
  }
43
60
  if (!res.ok) {
44
61
  throw new HttpError("HTTP Error", "CLIENT", res.status, data);
@@ -49,15 +66,19 @@ async function coreRequest(url, options) {
49
66
  // src/Utility/Retry.ts
50
67
  async function withRetry(fn, options) {
51
68
  const {
52
- attemps,
53
- backOffMs = 300,
69
+ attempts,
70
+ backOffMs = 3e4,
54
71
  //5 mins
55
- retryOn = ["NETWORK", "TIMEOUT", "RATE_LIMIT", "SERVER"]
72
+ retryOn = ["NETWORK", "TIMEOUT", "RATE_LIMIT", "SERVER", "UNKNOWN"]
56
73
  } = options;
57
74
  let lastError;
58
- for (let i = 0; i < attemps; i++) {
75
+ for (let i = 0; i < attempts; i++) {
59
76
  try {
60
- return await fn();
77
+ let { data, error } = await fn();
78
+ if (!!error) {
79
+ throw error;
80
+ }
81
+ return { data, error };
61
82
  } catch (err) {
62
83
  let classified = classifyError(err);
63
84
  lastError = classified;
@@ -90,19 +111,38 @@ var CircuitBreaker = class {
90
111
  };
91
112
 
92
113
  // src/Helper/Pagination.ts
93
- async function* paginate(fetcher, path, config = {}) {
94
- const pageParam = config.pageParam ?? "page";
95
- let page = config.startPage ?? 1;
96
- while (true) {
97
- const data = await fetcher(
98
- `${path}?${pageParam}=${page}`,
99
- config.options
114
+ async function* paginate(fetcher, path, body, config = {}) {
115
+ let FIXED_PARAMS = "";
116
+ if (config.FIXED_PARAMS) {
117
+ Object.entries(config.FIXED_PARAMS).forEach(
118
+ ([key, value]) => FIXED_PARAMS += `&${key}=${value}`
100
119
  );
101
- if (config.stopOnEmpty !== false && (!data || Array.isArray(data) && data.length === 0)) {
102
- break;
120
+ }
121
+ const pages = pagination(config.TOTAL_SIZE, config.CHUNK_SIZE);
122
+ const CHUNK_PAGINATION_KEY = config.PARAMS_KEY?.CHUNK_PAGINATION_KEY;
123
+ const CHUNK_SIZE_KEY = config.PARAMS_KEY?.CHUNK_SIZE_KEY;
124
+ if (Array.isArray(pages)) {
125
+ for (const page of pages) {
126
+ const paramsPath = `${CHUNK_PAGINATION_KEY}=${page.CHUNK_START}&${CHUNK_SIZE_KEY}=${page.CHUNK_SIZE}` + FIXED_PARAMS;
127
+ const data = await fetcher(`${path}?${paramsPath}`, body, { ...config.options });
128
+ if (config.stopOnEmpty !== false && (!data || Array.isArray(data) && data.length === 0)) {
129
+ break;
130
+ }
131
+ yield data;
103
132
  }
104
- yield data;
105
- page++;
133
+ }
134
+ }
135
+ function pagination(TOTAL_SIZE = 2e3, CHUNK_SIZE = 2e3, start = 1) {
136
+ try {
137
+ const totalChunks = Math.ceil(TOTAL_SIZE / CHUNK_SIZE);
138
+ CHUNK_SIZE = TOTAL_SIZE < CHUNK_SIZE ? TOTAL_SIZE : CHUNK_SIZE;
139
+ const requests = Array.from({ length: totalChunks }, (_, index) => {
140
+ const CHUNK_START = start + index * CHUNK_SIZE;
141
+ return { CHUNK_START, CHUNK_SIZE };
142
+ });
143
+ return requests;
144
+ } catch (error) {
145
+ throw error;
106
146
  }
107
147
  }
108
148
 
@@ -141,7 +181,7 @@ var windClient = class {
141
181
  throw new Error("Circuit breaker is open");
142
182
  }
143
183
  const exec = async () => {
144
- return coreRequest(this.baseURL + path, options);
184
+ return await coreRequest(this.baseURL + path, options);
145
185
  };
146
186
  try {
147
187
  const result = options.retry ? await withRetry(exec, options.retry) : await exec();
@@ -160,8 +200,8 @@ var windClient = class {
160
200
  post(path, body, options) {
161
201
  return this.request(path, { ...options, method: "POST", body });
162
202
  }
163
- paginate(path, config) {
164
- return paginate(this.get.bind(this), path, config);
203
+ paginate(path, body, config) {
204
+ return paginate(this.post.bind(this), path, body, config);
165
205
  }
166
206
  batch(tasks, options) {
167
207
  return batch(tasks, options);
package/package.json CHANGED
@@ -1,17 +1,15 @@
1
1
  {
2
2
  "name": "@winxs/wind",
3
- "version": "0.1.1",
3
+ "version": "0.1.6",
4
4
  "description": "Modern HTTP orchestration client for pagination, retries, batching, and failure-safe APIs",
5
5
  "license": "MIT",
6
6
  "author": "Winxs",
7
- "type": "module",
8
7
  "main": "dist/index.js",
9
8
  "types": "dist/index.d.ts",
9
+ "type": "module",
10
10
  "exports": {
11
- ".": {
12
- "import": "./dist/index.js",
13
- "types": "./dist/index.d.ts"
14
- }
11
+ "import": "./dist/esm/index.js",
12
+ "require": "./dist/cjs/index.cjs"
15
13
  },
16
14
  "files": [
17
15
  "dist",
@@ -19,9 +17,7 @@
19
17
  "LICENSE"
20
18
  ],
21
19
  "scripts": {
22
- "build": "tsup src/index.ts --format esm --dts",
23
- "dev": "tsup src/index.ts --watch",
24
- "prepublishOnly": "npm run build"
20
+ "build": "tsup"
25
21
  },
26
22
  "keywords": [
27
23
  "http",
@@ -35,7 +31,7 @@
35
31
  ],
36
32
  "repository": {
37
33
  "type": "git",
38
- "url": "https://github.com/winxs/wind"
34
+ "url": "https://github.com/adirathod1822/wind"
39
35
  },
40
36
  "devDependencies": {
41
37
  "tsup": "^8.5.1",