@winxs/wind 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 = 300,
99
+ //5 mins
100
+ retryOn = ["NETWORK", "TIMEOUT", "RATE_LIMIT", "SERVER"]
101
+ } = options;
102
+ let lastError;
103
+ for (let i = 0; i < attempts; i++) {
104
+ try {
105
+ return await fn();
106
+ } catch (err) {
107
+ let classified = classifyError(err);
108
+ lastError = classified;
109
+ if (!retryOn.includes(classified.type)) throw classified;
110
+ await new Promise((r) => setTimeout(r, backOffMs * (i + 1)));
111
+ }
112
+ }
113
+ throw lastError;
114
+ }
115
+
116
+ // src/Utility/CircuitBreaker.ts
117
+ var CircuitBreaker = class {
118
+ constructor(threshold = 5, timeoutMs = 1e4) {
119
+ this.threshold = threshold;
120
+ this.timeoutMs = timeoutMs;
121
+ this.failures = 0;
122
+ this.lastFailure = 0;
123
+ }
124
+ canRequest() {
125
+ if (this.failures < this.threshold) return true;
126
+ return Date.now() - this.lastFailure > this.timeoutMs;
127
+ }
128
+ success() {
129
+ this.failures = 0;
130
+ }
131
+ failure() {
132
+ this.failures++;
133
+ this.lastFailure = Date.now();
134
+ }
135
+ };
136
+
137
+ // src/Helper/Pagination.ts
138
+ async function* paginate(fetcher, path, body, config = {}) {
139
+ let FIXED_PARAMS = "";
140
+ if (config.FIXED_PARAMS) {
141
+ Object.entries(config.FIXED_PARAMS).forEach(
142
+ ([key, value]) => FIXED_PARAMS += `&${key}=${value}`
143
+ );
144
+ }
145
+ const pages = pagination(config.TOTAL_SIZE, config.CHUNK_SIZE);
146
+ const CHUNK_PAGINATION_KEY = config.PARAMS_KEY?.CHUNK_PAGINATION_KEY;
147
+ const CHUNK_SIZE_KEY = config.PARAMS_KEY?.CHUNK_SIZE_KEY;
148
+ if (Array.isArray(pages)) {
149
+ for (const page of pages) {
150
+ const paramsPath = `${CHUNK_PAGINATION_KEY}=${page.CHUNK_START}&${CHUNK_SIZE_KEY}=${page.CHUNK_SIZE}` + FIXED_PARAMS;
151
+ let args = {
152
+ ...config.options,
153
+ body
154
+ };
155
+ const data = await fetcher(`${path}?${paramsPath}`, args);
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,13 +66,13 @@ async function coreRequest(url, options) {
49
66
  // src/Utility/Retry.ts
50
67
  async function withRetry(fn, options) {
51
68
  const {
52
- attemps,
69
+ attempts,
53
70
  backOffMs = 300,
54
71
  //5 mins
55
72
  retryOn = ["NETWORK", "TIMEOUT", "RATE_LIMIT", "SERVER"]
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
77
  return await fn();
61
78
  } catch (err) {
@@ -90,19 +107,42 @@ var CircuitBreaker = class {
90
107
  };
91
108
 
92
109
  // 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
110
+ async function* paginate(fetcher, path, body, config = {}) {
111
+ let FIXED_PARAMS = "";
112
+ if (config.FIXED_PARAMS) {
113
+ Object.entries(config.FIXED_PARAMS).forEach(
114
+ ([key, value]) => FIXED_PARAMS += `&${key}=${value}`
100
115
  );
101
- if (config.stopOnEmpty !== false && (!data || Array.isArray(data) && data.length === 0)) {
102
- break;
116
+ }
117
+ const pages = pagination(config.TOTAL_SIZE, config.CHUNK_SIZE);
118
+ const CHUNK_PAGINATION_KEY = config.PARAMS_KEY?.CHUNK_PAGINATION_KEY;
119
+ const CHUNK_SIZE_KEY = config.PARAMS_KEY?.CHUNK_SIZE_KEY;
120
+ if (Array.isArray(pages)) {
121
+ for (const page of pages) {
122
+ const paramsPath = `${CHUNK_PAGINATION_KEY}=${page.CHUNK_START}&${CHUNK_SIZE_KEY}=${page.CHUNK_SIZE}` + FIXED_PARAMS;
123
+ let args = {
124
+ ...config.options,
125
+ body
126
+ };
127
+ const data = await fetcher(`${path}?${paramsPath}`, args);
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,44 +1,40 @@
1
- {
2
- "name": "@winxs/wind",
3
- "version": "0.1.1",
4
- "description": "Modern HTTP orchestration client for pagination, retries, batching, and failure-safe APIs",
5
- "license": "MIT",
6
- "author": "Winxs",
7
- "type": "module",
8
- "main": "dist/index.js",
9
- "types": "dist/index.d.ts",
10
- "exports": {
11
- ".": {
12
- "import": "./dist/index.js",
13
- "types": "./dist/index.d.ts"
14
- }
15
- },
16
- "files": [
17
- "dist",
18
- "README.md",
19
- "LICENSE"
20
- ],
21
- "scripts": {
22
- "build": "tsup src/index.ts --format esm --dts",
23
- "dev": "tsup src/index.ts --watch",
24
- "prepublishOnly": "npm run build"
25
- },
26
- "keywords": [
27
- "http",
28
- "fetch",
29
- "axios",
30
- "client",
31
- "pagination",
32
- "retry",
33
- "batch",
34
- "workers"
35
- ],
36
- "repository": {
37
- "type": "git",
38
- "url": "https://github.com/winxs/wind"
39
- },
40
- "devDependencies": {
41
- "tsup": "^8.5.1",
42
- "typescript": "^5.9.3"
43
- }
44
- }
1
+ {
2
+ "name": "@winxs/wind",
3
+ "version": "0.1.2",
4
+ "description": "Modern HTTP orchestration client for pagination, retries, batching, and failure-safe APIs",
5
+ "license": "MIT",
6
+ "author": "Winxs",
7
+ "main": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "type": "module",
10
+ "exports": {
11
+ "import": "./dist/esm/index.js",
12
+ "require": "./dist/cjs/index.cjs"
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsup"
21
+ },
22
+ "keywords": [
23
+ "http",
24
+ "fetch",
25
+ "axios",
26
+ "client",
27
+ "pagination",
28
+ "retry",
29
+ "batch",
30
+ "workers"
31
+ ],
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "https://github.com/adirathod1822/wind"
35
+ },
36
+ "devDependencies": {
37
+ "tsup": "^8.5.1",
38
+ "typescript": "^5.9.3"
39
+ }
40
+ }