@ahoo-wang/fetcher 0.3.2 → 0.3.5

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/README.md CHANGED
@@ -78,6 +78,55 @@ fetcher
78
78
  });
79
79
  ```
80
80
 
81
+ ### Named Fetcher Usage
82
+
83
+ NamedFetcher is an extension of the Fetcher class that automatically registers itself with a global registrar. This is
84
+ useful when you need to manage multiple fetcher instances throughout your application.
85
+
86
+ ```typescript
87
+ import { NamedFetcher, fetcherRegistrar } from '@ahoo-wang/fetcher';
88
+
89
+ // Create a named fetcher that automatically registers itself
90
+ const apiFetcher = new NamedFetcher('api', {
91
+ baseURL: 'https://api.example.com',
92
+ timeout: 5000,
93
+ headers: {
94
+ 'Content-Type': 'application/json',
95
+ Authorization: 'Bearer token',
96
+ },
97
+ });
98
+
99
+ // Create another named fetcher for a different service
100
+ const authFetcher = new NamedFetcher('auth', {
101
+ baseURL: 'https://auth.example.com',
102
+ timeout: 3000,
103
+ });
104
+
105
+ // Use the fetcher normally
106
+ apiFetcher
107
+ .get('/users/123')
108
+ .then(response => response.json())
109
+ .then(data => console.log(data));
110
+
111
+ // Retrieve a named fetcher from the registrar
112
+ const retrievedFetcher = fetcherRegistrar.get('api');
113
+ if (retrievedFetcher) {
114
+ retrievedFetcher.post('/users', {
115
+ body: { name: 'Jane Doe' },
116
+ });
117
+ }
118
+
119
+ // Use requiredGet to retrieve a fetcher (throws error if not found)
120
+ try {
121
+ const authFetcher = fetcherRegistrar.requiredGet('auth');
122
+ authFetcher.post('/login', {
123
+ body: { username: 'user', password: 'pass' },
124
+ });
125
+ } catch (error) {
126
+ console.error('Fetcher not found:', error.message);
127
+ }
128
+ ```
129
+
81
130
  ### Interceptor Usage
82
131
 
83
132
  ```typescript
@@ -149,6 +198,43 @@ new Fetcher(options: FetcherOptions = defaultOptions)
149
198
  - `head(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>` - HEAD request
150
199
  - `options(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>` - OPTIONS request
151
200
 
201
+ ### NamedFetcher Class
202
+
203
+ An extension of the Fetcher class that automatically registers itself with the global fetcherRegistrar using a provided
204
+ name.
205
+
206
+ #### Constructor
207
+
208
+ ```typescript
209
+ new NamedFetcher(name
210
+ :
211
+ string, options
212
+ :
213
+ FetcherOptions = defaultOptions
214
+ )
215
+ ```
216
+
217
+ **Parameters:**
218
+
219
+ - `name`: The name to register this fetcher under
220
+ - `options`: Same as Fetcher constructor options
221
+
222
+ ### FetcherRegistrar
223
+
224
+ Global instance for managing multiple Fetcher instances by name.
225
+
226
+ #### Properties
227
+
228
+ - `default`: Get or set the default fetcher instance
229
+
230
+ #### Methods
231
+
232
+ - `register(name: string, fetcher: Fetcher): void` - Register a fetcher with a name
233
+ - `unregister(name: string): boolean` - Unregister a fetcher by name
234
+ - `get(name: string): Fetcher | undefined` - Get a fetcher by name
235
+ - `requiredGet(name: string): Fetcher` - Get a fetcher by name, throws if not found
236
+ - `fetchers: Map<string, Fetcher>` - Get all registered fetchers
237
+
152
238
  ### UrlBuilder Class
153
239
 
154
240
  URL builder for constructing complete URLs with parameters.
package/README.zh-CN.md CHANGED
@@ -78,6 +78,55 @@ fetcher
78
78
  });
79
79
  ```
80
80
 
81
+ ### 命名 Fetcher 用法
82
+
83
+ NamedFetcher 是 Fetcher 类的扩展,它会自动使用提供的名称在全局注册器中注册自己。当您需要在应用程序中管理多个 fetcher
84
+ 实例时,这很有用。
85
+
86
+ ```typescript
87
+ import { NamedFetcher, fetcherRegistrar } from '@ahoo-wang/fetcher';
88
+
89
+ // 创建一个自动注册自己的命名 fetcher
90
+ const apiFetcher = new NamedFetcher('api', {
91
+ baseURL: 'https://api.example.com',
92
+ timeout: 5000,
93
+ headers: {
94
+ 'Content-Type': 'application/json',
95
+ Authorization: 'Bearer token',
96
+ },
97
+ });
98
+
99
+ // 为不同的服务创建另一个命名 fetcher
100
+ const authFetcher = new NamedFetcher('auth', {
101
+ baseURL: 'https://auth.example.com',
102
+ timeout: 3000,
103
+ });
104
+
105
+ // 正常使用 fetcher
106
+ apiFetcher
107
+ .get('/users/123')
108
+ .then(response => response.json())
109
+ .then(data => console.log(data));
110
+
111
+ // 从注册器中检索命名 fetcher
112
+ const retrievedFetcher = fetcherRegistrar.get('api');
113
+ if (retrievedFetcher) {
114
+ retrievedFetcher.post('/users', {
115
+ body: { name: 'Jane Doe' },
116
+ });
117
+ }
118
+
119
+ // 使用 requiredGet 检索 fetcher(如果未找到则抛出错误)
120
+ try {
121
+ const authFetcher = fetcherRegistrar.requiredGet('auth');
122
+ authFetcher.post('/login', {
123
+ body: { username: 'user', password: 'pass' },
124
+ });
125
+ } catch (error) {
126
+ console.error('未找到 Fetcher:', error.message);
127
+ }
128
+ ```
129
+
81
130
  ### 拦截器用法
82
131
 
83
132
  ```typescript
@@ -149,6 +198,40 @@ new Fetcher(options?: FetcherOptions)
149
198
  - `head(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>` - HEAD 请求
150
199
  - `options(url: string, request?: Omit<FetcherRequest, 'method' | 'body'>): Promise<Response>` - OPTIONS 请求
151
200
 
201
+ ### NamedFetcher 类
202
+
203
+ Fetcher 类的扩展,它会自动使用提供的名称在全局 fetcherRegistrar 中注册自己。
204
+
205
+ #### 构造函数
206
+
207
+ ```typescript
208
+ new NamedFetcher(name
209
+ :
210
+ string, options ? : FetcherOptions
211
+ )
212
+ ```
213
+
214
+ **参数:**
215
+
216
+ - `name`:注册此 fetcher 的名称
217
+ - `options`:与 Fetcher 构造函数相同的选项
218
+
219
+ ### FetcherRegistrar
220
+
221
+ 用于按名称管理多个 Fetcher 实例的全局实例。
222
+
223
+ #### 属性
224
+
225
+ - `default`:获取或设置默认 fetcher 实例
226
+
227
+ #### 方法
228
+
229
+ - `register(name: string, fetcher: Fetcher): void` - 使用名称注册 fetcher
230
+ - `unregister(name: string): boolean` - 按名称注销 fetcher
231
+ - `get(name: string): Fetcher | undefined` - 按名称获取 fetcher
232
+ - `requiredGet(name: string): Fetcher` - 按名称获取 fetcher,如果未找到则抛出错误
233
+ - `fetchers: Map<string, Fetcher>` - 获取所有已注册的 fetcher
234
+
152
235
  ### UrlBuilder 类
153
236
 
154
237
  用于构建带参数的完整 URL 的 URL 构建器。
package/dist/fetcher.d.ts CHANGED
@@ -6,6 +6,7 @@ import { FetcherInterceptors, FetchExchange } from './interceptor';
6
6
  */
7
7
  export interface FetcherOptions extends BaseURLCapable, HeadersCapable, TimeoutCapable {
8
8
  }
9
+ export declare const defaultOptions: FetcherOptions;
9
10
  /**
10
11
  * Fetcher request options interface
11
12
  */
@@ -1 +1 @@
1
- {"version":3,"file":"fetcher.d.ts","sourceRoot":"","sources":["../src/fetcher.ts"],"names":[],"mappings":"AAcA,OAAO,EAAqC,cAAc,EAAE,MAAM,WAAW,CAAC;AAC9E,OAAO,EACL,cAAc,EAGd,cAAc,EAEd,YAAY,EACb,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,mBAAmB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAGnE;;GAEG;AACH,MAAM,WAAW,cACf,SAAQ,cAAc,EACpB,cAAc,EACd,cAAc;CACjB;AAWD;;GAEG;AACH,MAAM,WAAW,cACf,SAAQ,cAAc,EACpB,IAAI,CAAC,WAAW,EAAE,MAAM,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IACjC,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAClC,IAAI,CAAC,EAAE,QAAQ,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC;CAC9C;AAED;;;;;;;;;;GAUG;AACH,qBAAa,OAAQ,YAAW,cAAc,EAAE,cAAc;IAC5D,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAkB;IAClD,OAAO,CAAC,EA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AAY,CAAC,IAAI,CAAM,GAC1E,OAAO,CAAC,QAAQ,CAAC;IAIpB;;;;;;OAMG;IACG,OAAO,CACX,GAAG,EAAE,MAAM,EACX,OAAO,GAAE,IAAI,CAAC,cAAc,EAAE,YAAY,CAAC,MAAM,GAAG,YAAY,CAAC,IAAI,CAAM,GAC1E,OAAO,CAAC,QAAQ,CAAC;CAGrB"}
@@ -0,0 +1,126 @@
1
+ import { Fetcher } from './fetcher';
2
+ /**
3
+ * Default fetcher name used when no name is specified
4
+ */
5
+ export declare const defaultFetcherName = "default";
6
+ /**
7
+ * FetcherRegistrar is a registry for managing multiple Fetcher instances.
8
+ * It allows registering, retrieving, and unregistering Fetcher instances by name.
9
+ * This is useful for applications that need to manage multiple HTTP clients
10
+ * with different configurations.
11
+ *
12
+ * @example
13
+ * // Register a fetcher
14
+ * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
15
+ * fetcherRegistrar.register('api', fetcher);
16
+ *
17
+ * // Retrieve a fetcher
18
+ * const apiFetcher = fetcherRegistrar.get('api');
19
+ *
20
+ * // Use the default fetcher
21
+ * const defaultFetcher = fetcherRegistrar.default;
22
+ *
23
+ * // Unregister a fetcher
24
+ * fetcherRegistrar.unregister('api');
25
+ */
26
+ export declare class FetcherRegistrar {
27
+ /**
28
+ * Internal map for storing registered fetchers
29
+ * @private
30
+ */
31
+ private registrar;
32
+ /**
33
+ * Register a Fetcher instance with a given name
34
+ *
35
+ * @param name - The name to register the fetcher under
36
+ * @param fetcher - The Fetcher instance to register
37
+ * @example
38
+ * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
39
+ * fetcherRegistrar.register('api', fetcher);
40
+ */
41
+ register(name: string, fetcher: Fetcher): void;
42
+ /**
43
+ * Unregister a Fetcher instance by name
44
+ *
45
+ * @param name - The name of the fetcher to unregister
46
+ * @returns boolean - True if the fetcher was successfully unregistered, false otherwise
47
+ * @example
48
+ * const success = fetcherRegistrar.unregister('api');
49
+ * if (success) {
50
+ * console.log('Fetcher unregistered successfully');
51
+ * }
52
+ */
53
+ unregister(name: string): boolean;
54
+ /**
55
+ * Get a Fetcher instance by name
56
+ *
57
+ * @param name - The name of the fetcher to retrieve
58
+ * @returns Fetcher | undefined - The Fetcher instance if found, undefined otherwise
59
+ * @example
60
+ * const fetcher = fetcherRegistrar.get('api');
61
+ * if (fetcher) {
62
+ * // Use the fetcher
63
+ * }
64
+ */
65
+ get(name: string): Fetcher | undefined;
66
+ /**
67
+ * Get a Fetcher instance by name, throwing an error if not found
68
+ *
69
+ * @param name - The name of the fetcher to retrieve
70
+ * @returns Fetcher - The Fetcher instance
71
+ * @throws Error - If no fetcher is registered with the given name
72
+ * @example
73
+ * try {
74
+ * const fetcher = fetcherRegistrar.requiredGet('api');
75
+ * // Use the fetcher
76
+ * } catch (error) {
77
+ * console.error('Fetcher not found:', error.message);
78
+ * }
79
+ */
80
+ requiredGet(name: string): Fetcher;
81
+ /**
82
+ * Get the default Fetcher instance
83
+ *
84
+ * @returns Fetcher - The default Fetcher instance
85
+ * @throws Error - If no default fetcher is registered
86
+ * @example
87
+ * const defaultFetcher = fetcherRegistrar.default;
88
+ */
89
+ get default(): Fetcher;
90
+ /**
91
+ * Set the default Fetcher instance
92
+ *
93
+ * @param fetcher - The Fetcher instance to set as default
94
+ * @example
95
+ * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
96
+ * fetcherRegistrar.default = fetcher;
97
+ */
98
+ set default(fetcher: Fetcher);
99
+ /**
100
+ * Get a copy of all registered fetchers
101
+ *
102
+ * @returns Map<string, Fetcher> - A copy of the internal registrar map
103
+ * @example
104
+ * const allFetchers = fetcherRegistrar.fetchers;
105
+ * for (const [name, fetcher] of allFetchers) {
106
+ * console.log(`Fetcher ${name}:`, fetcher);
107
+ * }
108
+ */
109
+ get fetchers(): Map<string, Fetcher>;
110
+ }
111
+ /**
112
+ * Global instance of FetcherRegistrar
113
+ * This is the default registrar used throughout the application
114
+ *
115
+ * @example
116
+ * import { fetcherRegistrar } from '@ahoo-wang/fetcher';
117
+ *
118
+ * // Register a fetcher
119
+ * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
120
+ * fetcherRegistrar.register('api', fetcher);
121
+ *
122
+ * // Retrieve a fetcher
123
+ * const apiFetcher = fetcherRegistrar.get('api');
124
+ */
125
+ export declare const fetcherRegistrar: FetcherRegistrar;
126
+ //# sourceMappingURL=fetcherRegistrar.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetcherRegistrar.d.ts","sourceRoot":"","sources":["../src/fetcherRegistrar.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAEpC;;GAEG;AACH,eAAO,MAAM,kBAAkB,YAAY,CAAC;AAE5C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,gBAAgB;IAC3B;;;OAGG;IACH,OAAO,CAAC,SAAS,CAAmC;IAEpD;;;;;;;;OAQG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI;IAI9C;;;;;;;;;;OAUG;IACH,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAIjC;;;;;;;;;;OAUG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,GAAG,SAAS;IAItC;;;;;;;;;;;;;OAaG;IACH,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAQlC;;;;;;;OAOG;IACH,IAAI,OAAO,IAAI,OAAO,CAErB;IAED;;;;;;;OAOG;IACH,IAAI,OAAO,CAAC,OAAO,EAAE,OAAO,EAE3B;IAED;;;;;;;;;OASG;IACH,IAAI,QAAQ,IAAI,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAEnC;CACF;AAED;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,gBAAgB,kBAAyB,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export * from './fetcher';
2
+ export * from './fetcherRegistrar';
2
3
  export * from './interceptor';
4
+ export * from './namedFetcher';
3
5
  export * from './timeout';
4
6
  export * from './types';
5
7
  export * from './urlBuilder';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,WAAW,CAAC;AAC1B,cAAc,eAAe,CAAC;AAC9B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,QAAQ,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,WAAW,CAAC;AAC1B,cAAc,oBAAoB,CAAC;AACnC,cAAc,eAAe,CAAC;AAC9B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,SAAS,CAAC;AACxB,cAAc,cAAc,CAAC;AAC7B,cAAc,QAAQ,CAAC"}
package/dist/index.es.js CHANGED
@@ -1,10 +1,10 @@
1
1
  function b(r) {
2
2
  return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(r);
3
3
  }
4
- function E(r, e) {
4
+ function g(r, e) {
5
5
  return b(e) ? e : e ? r.replace(/\/?\/$/, "") + "/" + e.replace(/^\/+/, "") : r;
6
6
  }
7
- class w {
7
+ class P {
8
8
  /**
9
9
  * 创建UrlBuilder实例
10
10
  *
@@ -23,12 +23,12 @@ class w {
23
23
  * @throws 当路径参数中缺少必需的占位符时抛出错误
24
24
  */
25
25
  build(e, t, s) {
26
- let o = E(this.baseURL, e), i = this.interpolateUrl(o, t);
26
+ let i = g(this.baseURL, e), o = this.interpolateUrl(i, t);
27
27
  if (s) {
28
28
  const n = new URLSearchParams(s).toString();
29
- n && (i += "?" + n);
29
+ n && (o += "?" + n);
30
30
  }
31
- return i;
31
+ return o;
32
32
  }
33
33
  /**
34
34
  * 替换url中的占位符参数
@@ -39,24 +39,24 @@ class w {
39
39
  * @throws 当路径参数中缺少必需的占位符时抛出错误
40
40
  */
41
41
  interpolateUrl(e, t) {
42
- return t ? e.replace(/{([^}]+)}/g, (s, o) => {
43
- const i = t[o];
44
- if (i === void 0)
45
- throw new Error(`Missing required path parameter: ${o}`);
46
- return String(i);
42
+ return t ? e.replace(/{([^}]+)}/g, (s, i) => {
43
+ const o = t[i];
44
+ if (o === void 0)
45
+ throw new Error(`Missing required path parameter: ${i}`);
46
+ return String(o);
47
47
  }) : e;
48
48
  }
49
49
  }
50
- function P(r, e) {
50
+ function O(r, e) {
51
51
  return typeof r < "u" ? r : e;
52
52
  }
53
53
  class l extends Error {
54
54
  constructor(e, t) {
55
- const s = e.request?.method || "GET", o = `Request timeout of ${t}ms exceeded for ${s} ${e.url}`;
56
- super(o), this.name = "FetchTimeoutError", this.exchange = e, Object.setPrototypeOf(this, l.prototype);
55
+ const s = e.request?.method || "GET", i = `Request timeout of ${t}ms exceeded for ${s} ${e.url}`;
56
+ super(i), this.name = "FetchTimeoutError", this.exchange = e, Object.setPrototypeOf(this, l.prototype);
57
57
  }
58
58
  }
59
- var c = /* @__PURE__ */ ((r) => (r.GET = "GET", r.POST = "POST", r.PUT = "PUT", r.DELETE = "DELETE", r.PATCH = "PATCH", r.HEAD = "HEAD", r.OPTIONS = "OPTIONS", r))(c || {}), O = /* @__PURE__ */ ((r) => (r.METHOD = "method", r.BODY = "body", r))(O || {});
59
+ var c = /* @__PURE__ */ ((r) => (r.GET = "GET", r.POST = "POST", r.PUT = "PUT", r.DELETE = "DELETE", r.PATCH = "PATCH", r.HEAD = "HEAD", r.OPTIONS = "OPTIONS", r))(c || {}), q = /* @__PURE__ */ ((r) => (r.METHOD = "method", r.BODY = "body", r))(q || {});
60
60
  const d = "Content-Type";
61
61
  var f = /* @__PURE__ */ ((r) => (r.APPLICATION_JSON = "application/json", r.TEXT_EVENT_STREAM = "text/event-stream", r))(f || {});
62
62
  class h {
@@ -97,7 +97,7 @@ class h {
97
97
  return t;
98
98
  }
99
99
  }
100
- class q {
100
+ class F {
101
101
  constructor() {
102
102
  this.request = new h(), this.response = new h(), this.error = new h();
103
103
  }
@@ -132,24 +132,24 @@ class A {
132
132
  return e;
133
133
  const s = { ...t };
134
134
  s.body = JSON.stringify(t.body), s.headers || (s.headers = {});
135
- const o = s.headers;
136
- return o[d] || (o[d] = f.APPLICATION_JSON), { ...e, request: s };
135
+ const i = s.headers;
136
+ return i[d] || (i[d] = f.APPLICATION_JSON), { ...e, request: s };
137
137
  }
138
138
  }
139
- const m = {
139
+ const y = {
140
140
  [d]: f.APPLICATION_JSON
141
- }, S = {
141
+ }, T = {
142
142
  baseURL: "",
143
- headers: m
143
+ headers: y
144
144
  };
145
- class I {
145
+ class S {
146
146
  /**
147
147
  * Create a Fetcher instance
148
148
  *
149
149
  * @param options - Fetcher configuration options
150
150
  */
151
- constructor(e = S) {
152
- this.headers = m, this.interceptors = new q(), this.urlBuilder = new w(e.baseURL), e.headers !== void 0 && (this.headers = e.headers), this.timeout = e.timeout, this.interceptors.request.use(new A());
151
+ constructor(e = T) {
152
+ this.headers = y, this.interceptors = new F(), this.urlBuilder = new P(e.baseURL), e.headers !== void 0 && (this.headers = e.headers), this.timeout = e.timeout, this.interceptors.request.use(new A());
153
153
  }
154
154
  /**
155
155
  * Make an HTTP request
@@ -177,18 +177,18 @@ class I {
177
177
  const s = {
178
178
  ...this.headers || {},
179
179
  ...t.headers || {}
180
- }, o = {
180
+ }, i = {
181
181
  ...t,
182
182
  headers: Object.keys(s).length > 0 ? s : void 0
183
- }, i = this.urlBuilder.build(
183
+ }, o = this.urlBuilder.build(
184
184
  e,
185
185
  t.pathParams,
186
186
  t.queryParams
187
187
  );
188
188
  let n = {
189
189
  fetcher: this,
190
- url: i,
191
- request: o,
190
+ url: o,
191
+ request: i,
192
192
  response: void 0,
193
193
  error: void 0
194
194
  };
@@ -219,25 +219,25 @@ class I {
219
219
  * @throws FetchTimeoutError Thrown when the request times out
220
220
  */
221
221
  async timeoutFetch(e) {
222
- const t = e.url, s = e.request, o = s.timeout, i = P(o, this.timeout);
223
- if (!i)
222
+ const t = e.url, s = e.request, i = s.timeout, o = O(i, this.timeout);
223
+ if (!o)
224
224
  return fetch(t, s);
225
225
  const n = new AbortController(), u = {
226
226
  ...s,
227
227
  signal: n.signal
228
228
  };
229
229
  let a = null;
230
- const y = new Promise((F, T) => {
230
+ const w = new Promise((N, E) => {
231
231
  a = setTimeout(() => {
232
232
  a && clearTimeout(a);
233
- const p = new l(e, i);
234
- n.abort(p), T(p);
235
- }, i);
233
+ const p = new l(e, o);
234
+ n.abort(p), E(p);
235
+ }, o);
236
236
  });
237
237
  try {
238
238
  return await Promise.race([
239
239
  fetch(t, u),
240
- y
240
+ w
241
241
  ]);
242
242
  } finally {
243
243
  a && clearTimeout(a);
@@ -328,17 +328,146 @@ class I {
328
328
  return this.methodFetch(c.OPTIONS, e, t);
329
329
  }
330
330
  }
331
+ const m = "default";
332
+ class R {
333
+ constructor() {
334
+ this.registrar = /* @__PURE__ */ new Map();
335
+ }
336
+ /**
337
+ * Register a Fetcher instance with a given name
338
+ *
339
+ * @param name - The name to register the fetcher under
340
+ * @param fetcher - The Fetcher instance to register
341
+ * @example
342
+ * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
343
+ * fetcherRegistrar.register('api', fetcher);
344
+ */
345
+ register(e, t) {
346
+ this.registrar.set(e, t);
347
+ }
348
+ /**
349
+ * Unregister a Fetcher instance by name
350
+ *
351
+ * @param name - The name of the fetcher to unregister
352
+ * @returns boolean - True if the fetcher was successfully unregistered, false otherwise
353
+ * @example
354
+ * const success = fetcherRegistrar.unregister('api');
355
+ * if (success) {
356
+ * console.log('Fetcher unregistered successfully');
357
+ * }
358
+ */
359
+ unregister(e) {
360
+ return this.registrar.delete(e);
361
+ }
362
+ /**
363
+ * Get a Fetcher instance by name
364
+ *
365
+ * @param name - The name of the fetcher to retrieve
366
+ * @returns Fetcher | undefined - The Fetcher instance if found, undefined otherwise
367
+ * @example
368
+ * const fetcher = fetcherRegistrar.get('api');
369
+ * if (fetcher) {
370
+ * // Use the fetcher
371
+ * }
372
+ */
373
+ get(e) {
374
+ return this.registrar.get(e);
375
+ }
376
+ /**
377
+ * Get a Fetcher instance by name, throwing an error if not found
378
+ *
379
+ * @param name - The name of the fetcher to retrieve
380
+ * @returns Fetcher - The Fetcher instance
381
+ * @throws Error - If no fetcher is registered with the given name
382
+ * @example
383
+ * try {
384
+ * const fetcher = fetcherRegistrar.requiredGet('api');
385
+ * // Use the fetcher
386
+ * } catch (error) {
387
+ * console.error('Fetcher not found:', error.message);
388
+ * }
389
+ */
390
+ requiredGet(e) {
391
+ const t = this.get(e);
392
+ if (!t)
393
+ throw new Error(`Fetcher ${e} not found`);
394
+ return t;
395
+ }
396
+ /**
397
+ * Get the default Fetcher instance
398
+ *
399
+ * @returns Fetcher - The default Fetcher instance
400
+ * @throws Error - If no default fetcher is registered
401
+ * @example
402
+ * const defaultFetcher = fetcherRegistrar.default;
403
+ */
404
+ get default() {
405
+ return this.requiredGet(m);
406
+ }
407
+ /**
408
+ * Set the default Fetcher instance
409
+ *
410
+ * @param fetcher - The Fetcher instance to set as default
411
+ * @example
412
+ * const fetcher = new Fetcher({ baseURL: 'https://api.example.com' });
413
+ * fetcherRegistrar.default = fetcher;
414
+ */
415
+ set default(e) {
416
+ this.register(m, e);
417
+ }
418
+ /**
419
+ * Get a copy of all registered fetchers
420
+ *
421
+ * @returns Map<string, Fetcher> - A copy of the internal registrar map
422
+ * @example
423
+ * const allFetchers = fetcherRegistrar.fetchers;
424
+ * for (const [name, fetcher] of allFetchers) {
425
+ * console.log(`Fetcher ${name}:`, fetcher);
426
+ * }
427
+ */
428
+ get fetchers() {
429
+ return new Map(this.registrar);
430
+ }
431
+ }
432
+ const I = new R();
433
+ class U extends S {
434
+ /**
435
+ * Create a NamedFetcher instance and automatically register it with the global fetcherRegistrar
436
+ *
437
+ * @param name - The name to register this fetcher under
438
+ * @param options - Fetcher configuration options (same as Fetcher constructor)
439
+ *
440
+ * @example
441
+ * // Create with default options
442
+ * const fetcher1 = new NamedFetcher('default');
443
+ *
444
+ * // Create with custom options
445
+ * const fetcher2 = new NamedFetcher('api', {
446
+ * baseURL: 'https://api.example.com',
447
+ * timeout: 5000,
448
+ * headers: { 'Authorization': 'Bearer token' }
449
+ * });
450
+ */
451
+ constructor(e, t = T) {
452
+ super(t), this.name = e, I.register(e, this);
453
+ }
454
+ }
331
455
  export {
332
456
  d as ContentTypeHeader,
333
457
  f as ContentTypeValues,
334
458
  l as FetchTimeoutError,
335
- I as Fetcher,
336
- q as FetcherInterceptors,
459
+ S as Fetcher,
460
+ F as FetcherInterceptors,
461
+ R as FetcherRegistrar,
337
462
  c as HttpMethod,
338
463
  h as InterceptorManager,
339
- O as RequestField,
340
- w as UrlBuilder,
341
- E as combineURLs,
464
+ U as NamedFetcher,
465
+ q as RequestField,
466
+ P as UrlBuilder,
467
+ g as combineURLs,
468
+ m as defaultFetcherName,
469
+ T as defaultOptions,
470
+ I as fetcherRegistrar,
342
471
  b as isAbsoluteURL,
343
- P as resolveTimeout
472
+ O as resolveTimeout
344
473
  };
package/dist/index.umd.js CHANGED
@@ -1 +1 @@
1
- (function(o,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(o=typeof globalThis<"u"?globalThis:o||self,h(o.Fetcher={}))})(this,(function(o){"use strict";function h(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function y(r,e){return h(e)?e:e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}class T{constructor(e){this.baseURL=e}build(e,t,s){let i=y(this.baseURL,e),c=this.interpolateUrl(i,t);if(s){const n=new URLSearchParams(s).toString();n&&(c+="?"+n)}return c}interpolateUrl(e,t){return t?e.replace(/{([^}]+)}/g,(s,i)=>{const c=t[i];if(c===void 0)throw new Error(`Missing required path parameter: ${i}`);return String(c)}):e}}function b(r,e){return typeof r<"u"?r:e}class l extends Error{constructor(e,t){const s=e.request?.method||"GET",i=`Request timeout of ${t}ms exceeded for ${s} ${e.url}`;super(i),this.name="FetchTimeoutError",this.exchange=e,Object.setPrototypeOf(this,l.prototype)}}var u=(r=>(r.GET="GET",r.POST="POST",r.PUT="PUT",r.DELETE="DELETE",r.PATCH="PATCH",r.HEAD="HEAD",r.OPTIONS="OPTIONS",r))(u||{}),E=(r=>(r.METHOD="method",r.BODY="body",r))(E||{});const f="Content-Type";var m=(r=>(r.APPLICATION_JSON="application/json",r.TEXT_EVENT_STREAM="text/event-stream",r))(m||{});class p{constructor(){this.interceptors=[]}use(e){const t=this.interceptors.length;return this.interceptors.push(e),t}eject(e){this.interceptors[e]&&(this.interceptors[e]=null)}clear(){this.interceptors=[]}async intercept(e){let t=e;for(let s of this.interceptors)s&&(t=await s.intercept(t));return t}}class P{constructor(){this.request=new p,this.response=new p,this.error=new p}}class F{intercept(e){const t=e.request;if(t.body===void 0||t.body===null||typeof t.body!="object"||t.body instanceof ArrayBuffer||ArrayBuffer.isView(t.body)||t.body instanceof Blob||t.body instanceof File||t.body instanceof URLSearchParams||t.body instanceof FormData||t.body instanceof ReadableStream)return e;const s={...t};s.body=JSON.stringify(t.body),s.headers||(s.headers={});const i=s.headers;return i[f]||(i[f]=m.APPLICATION_JSON),{...e,request:s}}}const w={[f]:m.APPLICATION_JSON},S={baseURL:"",headers:w};class q{constructor(e=S){this.headers=w,this.interceptors=new P,this.urlBuilder=new T(e.baseURL),e.headers!==void 0&&(this.headers=e.headers),this.timeout=e.timeout,this.interceptors.request.use(new F)}async fetch(e,t={}){const s=await this.request(e,t);if(!s.response)throw new Error(`Request to ${s.url} failed with no response`);return s.response}async request(e,t={}){const s={...this.headers||{},...t.headers||{}},i={...t,headers:Object.keys(s).length>0?s:void 0},c=this.urlBuilder.build(e,t.pathParams,t.queryParams);let n={fetcher:this,url:c,request:i,response:void 0,error:void 0};try{const d={...n};n=await this.interceptors.request.intercept(d),n.response=await this.timeoutFetch(n);const a={...n};return n=await this.interceptors.response.intercept(a),n}catch(d){if(n.error=d,n=await this.interceptors.error.intercept(n),n.response)return n;throw n.error}}async timeoutFetch(e){const t=e.url,s=e.request,i=s.timeout,c=b(i,this.timeout);if(!c)return fetch(t,s);const n=new AbortController,d={...s,signal:n.signal};let a=null;const A=new Promise((g,U)=>{a=setTimeout(()=>{a&&clearTimeout(a);const O=new l(e,c);n.abort(O),U(O)},c)});try{return await Promise.race([fetch(t,d),A])}finally{a&&clearTimeout(a)}}async methodFetch(e,t,s={}){return this.fetch(t,{...s,method:e})}async get(e,t={}){return this.methodFetch(u.GET,e,t)}async post(e,t={}){return this.methodFetch(u.POST,e,t)}async put(e,t={}){return this.methodFetch(u.PUT,e,t)}async delete(e,t={}){return this.methodFetch(u.DELETE,e,t)}async patch(e,t={}){return this.methodFetch(u.PATCH,e,t)}async head(e,t={}){return this.methodFetch(u.HEAD,e,t)}async options(e,t={}){return this.methodFetch(u.OPTIONS,e,t)}}o.ContentTypeHeader=f,o.ContentTypeValues=m,o.FetchTimeoutError=l,o.Fetcher=q,o.FetcherInterceptors=P,o.HttpMethod=u,o.InterceptorManager=p,o.RequestField=E,o.UrlBuilder=T,o.combineURLs=y,o.isAbsoluteURL=h,o.resolveTimeout=b,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(n,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(n=typeof globalThis<"u"?globalThis:n||self,h(n.Fetcher={}))})(this,(function(n){"use strict";function h(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function b(r,e){return h(e)?e:e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}class g{constructor(e){this.baseURL=e}build(e,t,s){let o=b(this.baseURL,e),c=this.interpolateUrl(o,t);if(s){const i=new URLSearchParams(s).toString();i&&(c+="?"+i)}return c}interpolateUrl(e,t){return t?e.replace(/{([^}]+)}/g,(s,o)=>{const c=t[o];if(c===void 0)throw new Error(`Missing required path parameter: ${o}`);return String(c)}):e}}function E(r,e){return typeof r<"u"?r:e}class l extends Error{constructor(e,t){const s=e.request?.method||"GET",o=`Request timeout of ${t}ms exceeded for ${s} ${e.url}`;super(o),this.name="FetchTimeoutError",this.exchange=e,Object.setPrototypeOf(this,l.prototype)}}var u=(r=>(r.GET="GET",r.POST="POST",r.PUT="PUT",r.DELETE="DELETE",r.PATCH="PATCH",r.HEAD="HEAD",r.OPTIONS="OPTIONS",r))(u||{}),w=(r=>(r.METHOD="method",r.BODY="body",r))(w||{});const f="Content-Type";var m=(r=>(r.APPLICATION_JSON="application/json",r.TEXT_EVENT_STREAM="text/event-stream",r))(m||{});class p{constructor(){this.interceptors=[]}use(e){const t=this.interceptors.length;return this.interceptors.push(e),t}eject(e){this.interceptors[e]&&(this.interceptors[e]=null)}clear(){this.interceptors=[]}async intercept(e){let t=e;for(let s of this.interceptors)s&&(t=await s.intercept(t));return t}}class F{constructor(){this.request=new p,this.response=new p,this.error=new p}}class A{intercept(e){const t=e.request;if(t.body===void 0||t.body===null||typeof t.body!="object"||t.body instanceof ArrayBuffer||ArrayBuffer.isView(t.body)||t.body instanceof Blob||t.body instanceof File||t.body instanceof URLSearchParams||t.body instanceof FormData||t.body instanceof ReadableStream)return e;const s={...t};s.body=JSON.stringify(t.body),s.headers||(s.headers={});const o=s.headers;return o[f]||(o[f]=m.APPLICATION_JSON),{...e,request:s}}}const P={[f]:m.APPLICATION_JSON},y={baseURL:"",headers:P};class O{constructor(e=y){this.headers=P,this.interceptors=new F,this.urlBuilder=new g(e.baseURL),e.headers!==void 0&&(this.headers=e.headers),this.timeout=e.timeout,this.interceptors.request.use(new A)}async fetch(e,t={}){const s=await this.request(e,t);if(!s.response)throw new Error(`Request to ${s.url} failed with no response`);return s.response}async request(e,t={}){const s={...this.headers||{},...t.headers||{}},o={...t,headers:Object.keys(s).length>0?s:void 0},c=this.urlBuilder.build(e,t.pathParams,t.queryParams);let i={fetcher:this,url:c,request:o,response:void 0,error:void 0};try{const d={...i};i=await this.interceptors.request.intercept(d),i.response=await this.timeoutFetch(i);const a={...i};return i=await this.interceptors.response.intercept(a),i}catch(d){if(i.error=d,i=await this.interceptors.error.intercept(i),i.response)return i;throw i.error}}async timeoutFetch(e){const t=e.url,s=e.request,o=s.timeout,c=E(o,this.timeout);if(!c)return fetch(t,s);const i=new AbortController,d={...s,signal:i.signal};let a=null;const I=new Promise((L,N)=>{a=setTimeout(()=>{a&&clearTimeout(a);const S=new l(e,c);i.abort(S),N(S)},c)});try{return await Promise.race([fetch(t,d),I])}finally{a&&clearTimeout(a)}}async methodFetch(e,t,s={}){return this.fetch(t,{...s,method:e})}async get(e,t={}){return this.methodFetch(u.GET,e,t)}async post(e,t={}){return this.methodFetch(u.POST,e,t)}async put(e,t={}){return this.methodFetch(u.PUT,e,t)}async delete(e,t={}){return this.methodFetch(u.DELETE,e,t)}async patch(e,t={}){return this.methodFetch(u.PATCH,e,t)}async head(e,t={}){return this.methodFetch(u.HEAD,e,t)}async options(e,t={}){return this.methodFetch(u.OPTIONS,e,t)}}const T="default";class q{constructor(){this.registrar=new Map}register(e,t){this.registrar.set(e,t)}unregister(e){return this.registrar.delete(e)}get(e){return this.registrar.get(e)}requiredGet(e){const t=this.get(e);if(!t)throw new Error(`Fetcher ${e} not found`);return t}get default(){return this.requiredGet(T)}set default(e){this.register(T,e)}get fetchers(){return new Map(this.registrar)}}const R=new q;class U extends O{constructor(e,t=y){super(t),this.name=e,R.register(e,this)}}n.ContentTypeHeader=f,n.ContentTypeValues=m,n.FetchTimeoutError=l,n.Fetcher=O,n.FetcherInterceptors=F,n.FetcherRegistrar=q,n.HttpMethod=u,n.InterceptorManager=p,n.NamedFetcher=U,n.RequestField=w,n.UrlBuilder=g,n.combineURLs=b,n.defaultFetcherName=T,n.defaultOptions=y,n.fetcherRegistrar=R,n.isAbsoluteURL=h,n.resolveTimeout=E,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}));
@@ -0,0 +1,47 @@
1
+ import { NamedCapable } from './types';
2
+ import { Fetcher, FetcherOptions } from './fetcher';
3
+ /**
4
+ * NamedFetcher is an extension of the Fetcher class that automatically registers
5
+ * itself with the global fetcherRegistrar using a provided name.
6
+ * This allows for easy management and retrieval of multiple fetcher instances
7
+ * throughout an application by name.
8
+ *
9
+ * @example
10
+ * // Create a named fetcher that automatically registers itself
11
+ * const apiFetcher = new NamedFetcher('api', {
12
+ * baseURL: 'https://api.example.com',
13
+ * timeout: 5000
14
+ * });
15
+ *
16
+ * // Retrieve the fetcher later by name
17
+ * const sameFetcher = fetcherRegistrar.get('api');
18
+ * console.log(apiFetcher === sameFetcher); // true
19
+ *
20
+ * // Use the fetcher normally
21
+ * const response = await apiFetcher.get('/users');
22
+ */
23
+ export declare class NamedFetcher extends Fetcher implements NamedCapable {
24
+ /**
25
+ * The name of this fetcher instance, used for registration and retrieval
26
+ */
27
+ name: string;
28
+ /**
29
+ * Create a NamedFetcher instance and automatically register it with the global fetcherRegistrar
30
+ *
31
+ * @param name - The name to register this fetcher under
32
+ * @param options - Fetcher configuration options (same as Fetcher constructor)
33
+ *
34
+ * @example
35
+ * // Create with default options
36
+ * const fetcher1 = new NamedFetcher('default');
37
+ *
38
+ * // Create with custom options
39
+ * const fetcher2 = new NamedFetcher('api', {
40
+ * baseURL: 'https://api.example.com',
41
+ * timeout: 5000,
42
+ * headers: { 'Authorization': 'Bearer token' }
43
+ * });
44
+ */
45
+ constructor(name: string, options?: FetcherOptions);
46
+ }
47
+ //# sourceMappingURL=namedFetcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"namedFetcher.d.ts","sourceRoot":"","sources":["../src/namedFetcher.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAkB,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAGpE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,YAAa,SAAQ,OAAQ,YAAW,YAAY;IAC/D;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;;;;;;;;;;;;;;OAgBG;gBACS,IAAI,EAAE,MAAM,EAAE,OAAO,GAAE,cAA+B;CAKnE"}
@@ -1 +1 @@
1
- {"version":3,"file":"timeout.d.ts","sourceRoot":"","sources":["../src/timeout.ts"],"names":[],"mappings":"AAcA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,cAAc,CAAC,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,MAAM,GACtB,MAAM,GAAG,SAAS,CAKpB;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,EAAE,aAAa,CAAC;gBAEZ,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM;CAUrD"}
1
+ {"version":3,"file":"timeout.d.ts","sourceRoot":"","sources":["../src/timeout.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAE9C;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,cAAc,CAAC,EAAE,MAAM,EACvB,cAAc,CAAC,EAAE,MAAM,GACtB,MAAM,GAAG,SAAS,CAKpB;AAED;;;GAGG;AACH,qBAAa,iBAAkB,SAAQ,KAAK;IAC1C,QAAQ,EAAE,aAAa,CAAC;gBAEZ,QAAQ,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM;CAUrD"}
package/dist/types.d.ts CHANGED
@@ -32,4 +32,7 @@ export declare enum ContentTypeValues {
32
32
  APPLICATION_JSON = "application/json",
33
33
  TEXT_EVENT_STREAM = "text/event-stream"
34
34
  }
35
+ export interface NamedCapable {
36
+ name: string;
37
+ }
35
38
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,oBAAY,UAAU;IACpB,GAAG,QAAQ;IACX,IAAI,SAAS;IACb,GAAG,QAAQ;IACX,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,IAAI,SAAS;IACb,OAAO,YAAY;CACpB;AAED,oBAAY,YAAY;IACtB,MAAM,WAAW;IACjB,IAAI,SAAS;CACd;AAED,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAEhD,oBAAY,iBAAiB;IAC3B,gBAAgB,qBAAqB;IACrC,iBAAiB,sBAAsB;CACxC"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC7B;;OAEG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAClC;AAED;;GAEG;AACH,oBAAY,UAAU;IACpB,GAAG,QAAQ;IACX,IAAI,SAAS;IACb,GAAG,QAAQ;IACX,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,IAAI,SAAS;IACb,OAAO,YAAY;CACpB;AAED,oBAAY,YAAY;IACtB,MAAM,WAAW;IACjB,IAAI,SAAS;CACd;AAED,eAAO,MAAM,iBAAiB,iBAAiB,CAAC;AAEhD,oBAAY,iBAAiB;IAC3B,gBAAgB,qBAAqB;IACrC,iBAAiB,sBAAsB;CACxC;AAGD,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;CACd"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher",
3
- "version": "0.3.2",
3
+ "version": "0.3.5",
4
4
  "description": "Core library providing basic HTTP client functionality for Fetcher",
5
5
  "keywords": [
6
6
  "fetch",