Skip to content

Commit 3f83143

Browse files
committed
feat: added copilot instructions
1 parent 92acd40 commit 3f83143

1 file changed

Lines changed: 312 additions & 0 deletions

File tree

.github/copilot-instructions.md

Lines changed: 312 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,312 @@
1+
# Axios Library - GitHub Copilot Instructions
2+
3+
## Project Overview
4+
5+
Axios is a promise-based HTTP client for the browser and Node.js. It provides a simple, elegant API for making HTTP requests with features like interceptors, request/response transformation, automatic JSON data handling, and request cancellation.
6+
7+
## Core Architecture
8+
9+
### Module Structure
10+
11+
- **ES6 Modules**: The library uses ES6 import/export syntax throughout
12+
- **Platform Abstraction**: Code is organized to support both browser and Node.js environments via the `platform/` directory
13+
- **Adapter Pattern**: HTTP requests are handled through adapters (XHR, HTTP, Fetch) selected based on the environment
14+
15+
### Key Components
16+
17+
#### 1. Core Classes (`lib/core/`)
18+
19+
- **Axios**: Main class that manages request dispatching and interceptor chains
20+
- **AxiosError**: Custom error class with standardized error codes (ERR_NETWORK, ETIMEDOUT, etc.)
21+
- **AxiosHeaders**: Manages HTTP headers with case-insensitive access and normalization
22+
- **InterceptorManager**: Handles request/response interceptors with synchronous/asynchronous support
23+
24+
#### 2. Adapters (`lib/adapters/`)
25+
26+
- **xhr.js**: XMLHttpRequest adapter for browsers
27+
- **http.js**: Node.js HTTP/HTTPS adapter
28+
- **fetch.js**: Fetch API adapter
29+
- Adapters are selected automatically based on environment capabilities
30+
31+
#### 3. Utilities (`lib/utils.js`)
32+
33+
- Comprehensive type checking functions (isArray, isObject, isString, etc.)
34+
- Object manipulation utilities (merge, extend, forEach)
35+
- Platform-agnostic helper functions
36+
- Uses functional programming patterns with pure functions
37+
38+
#### 4. Helpers (`lib/helpers/`)
39+
40+
- URL building and parameter serialization
41+
- Form data handling and conversion
42+
- Progress event management
43+
- Request/response transformation utilities
44+
45+
## Coding Conventions
46+
47+
### Code Style
48+
49+
1. **Strict Mode**: Always use `'use strict';` at the top of files
50+
2. **Function Documentation**: Use JSDoc comments for all public functions with @param and @returns tags
51+
3. **Import Style**: Use named imports from relative paths with `.js` extension
52+
4. **Error Handling**: Always use AxiosError with appropriate error codes
53+
5. **Null Checks**: Use explicit checks (`=== null`, `!== undefined`) rather than truthy/falsy checks where precision matters
54+
55+
### Naming Conventions
56+
57+
- **Classes**: PascalCase (e.g., `Axios`, `AxiosError`, `InterceptorManager`)
58+
- **Functions**: camelCase (e.g., `buildURL`, `mergeConfig`, `dispatchRequest`)
59+
- **Constants**: UPPER_SNAKE_CASE for error codes (e.g., `ERR_NETWORK`, `ETIMEDOUT`)
60+
- **Private symbols**: Use Symbol for internal properties (e.g., `$internals`)
61+
- **Helper functions**: Prefix with underscore for internal helpers (e.g., `_request`)
62+
63+
### Error Handling Patterns
64+
65+
```javascript
66+
// Always use AxiosError for library errors
67+
throw new AxiosError(message, code, config, request, response);
68+
69+
// Predefined error codes
70+
AxiosError.ERR_BAD_REQUEST;
71+
AxiosError.ERR_NETWORK;
72+
AxiosError.ETIMEDOUT;
73+
AxiosError.ECONNABORTED;
74+
AxiosError.ERR_CANCELED;
75+
```
76+
77+
### Configuration Patterns
78+
79+
- Use `mergeConfig()` to combine configuration objects
80+
- Support both function and object forms for serializers
81+
- Validate options using the `validator` helper
82+
- Apply defaults from `lib/defaults/index.js`
83+
84+
## Important Design Patterns
85+
86+
### 1. Interceptor Chain Pattern
87+
88+
```javascript
89+
// Interceptors execute in a specific order:
90+
// Request interceptors (last registered -> first registered)
91+
// Actual request
92+
// Response interceptors (first registered -> last registered)
93+
94+
// Support both synchronous and asynchronous interceptors
95+
interceptors.request.use(onFulfilled, onRejected, {
96+
synchronous: false,
97+
runWhen: (config) => config.custom === true,
98+
});
99+
```
100+
101+
### 2. Adapter Selection
102+
103+
- Adapters are tried in order: ['xhr', 'http', 'fetch']
104+
- Use capability detection, not environment detection
105+
- Each adapter returns a Promise
106+
107+
### 3. Request/Response Transformation
108+
109+
```javascript
110+
// Transformations are applied in arrays
111+
transformRequest: [function(data, headers) {
112+
// Transform request data
113+
return data;
114+
}],
115+
transformResponse: [function(data) {
116+
// Transform response data
117+
return data;
118+
}]
119+
```
120+
121+
### 4. Config Merging Strategy
122+
123+
- Deep merge for nested objects
124+
- Header normalization and flattening
125+
- Method-specific headers override common headers
126+
127+
## Platform Abstraction
128+
129+
### Browser vs Node.js
130+
131+
- **Browser**: Uses XHR or Fetch adapter, includes XSRF protection
132+
- **Node.js**: Uses HTTP/HTTPS adapter, supports streams
133+
- Platform-specific classes in `lib/platform/browser/` and `lib/platform/node/`
134+
135+
### Environment Detection
136+
137+
```javascript
138+
// Check feature availability, not environment name
139+
const isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined";
140+
```
141+
142+
## Testing Considerations
143+
144+
- Functions should be pure and testable in isolation
145+
- Use dependency injection for platform-specific features
146+
- Mock adapters for unit tests
147+
- Support for cancellation should be tested thoroughly
148+
149+
## Common Pitfalls to Avoid
150+
151+
1. **Don't** use global variables or singletons
152+
2. **Don't** assume browser or Node.js specific APIs are available
153+
3. **Don't** mutate configuration objects - always return new objects
154+
4. **Don't** throw generic Error objects - use AxiosError
155+
5. **Don't** use `.bind()` without the helper function from `lib/helpers/bind.js`
156+
6. **Don't** add new dependencies without discussion
157+
158+
## Type Safety Notes
159+
160+
- The library includes TypeScript definitions (index.d.ts)
161+
- Maintain compatibility with existing type definitions
162+
- Use utils type checking functions consistently (utils.isArray, utils.isString, etc.)
163+
164+
## Performance Considerations
165+
166+
- Minimize object allocations in hot paths
167+
- Reuse headers objects when possible
168+
- Use efficient string operations
169+
- Avoid unnecessary array iterations
170+
- Cache compiled regular expressions
171+
172+
## Request Lifecycle
173+
174+
1. **Request Creation**: User calls `axios()` or `axios.get/post()` etc.
175+
2. **Config Merging**: Merge instance defaults with request config
176+
3. **Request Interceptors**: Execute in reverse order of registration
177+
4. **Adapter Selection**: Choose appropriate adapter for environment
178+
5. **Request Transformation**: Apply transformRequest functions
179+
6. **HTTP Request**: Adapter performs actual HTTP request
180+
7. **Response Transformation**: Apply transformResponse functions
181+
8. **Response Interceptors**: Execute in order of registration
182+
9. **Promise Resolution**: Return response or throw error
183+
184+
## Cancellation Patterns
185+
186+
- Support both CancelToken (legacy) and AbortSignal (modern)
187+
- Always cleanup listeners to prevent memory leaks
188+
- Cancel should work at any stage of the request
189+
190+
## Common Helper Usage
191+
192+
### URL Building
193+
194+
```javascript
195+
import buildURL from "./helpers/buildURL.js";
196+
const url = buildURL(baseURL, params, paramsSerializer);
197+
```
198+
199+
### Header Management
200+
201+
```javascript
202+
import AxiosHeaders from "./core/AxiosHeaders.js";
203+
const headers = AxiosHeaders.from(rawHeaders).normalize();
204+
```
205+
206+
### Type Checking
207+
208+
```javascript
209+
import utils from "./utils.js";
210+
if (utils.isObject(data) && !utils.isStream(data)) {
211+
// Handle object data
212+
}
213+
```
214+
215+
## When Adding New Features
216+
217+
1. Consider both browser and Node.js environments
218+
2. Add appropriate error codes if needed
219+
3. Update TypeScript definitions
220+
4. Maintain backward compatibility
221+
5. Add JSDoc documentation
222+
6. Consider performance implications
223+
7. Test with interceptors and transformations
224+
8. Validate configuration options properly
225+
226+
## Priority Guidelines
227+
228+
When suggesting code:
229+
230+
1. **Compatibility First**: Maintain backward compatibility
231+
2. **Platform Agnostic**: Work in both browser and Node.js
232+
3. **Error Handling**: Use AxiosError consistently
233+
4. **Documentation**: Include JSDoc comments
234+
5. **Performance**: Avoid unnecessary operations
235+
6. **Type Safety**: Use utils type checking consistently
236+
237+
## Code Examples to Follow
238+
239+
### Creating a New Helper
240+
241+
```javascript
242+
"use strict";
243+
244+
import utils from "../utils.js";
245+
246+
/**
247+
* Brief description of what this helper does
248+
*
249+
* @param {Type} paramName - Description
250+
* @returns {ReturnType} Description
251+
*/
252+
export default function helperName(paramName) {
253+
// Validate inputs
254+
if (!utils.isString(paramName)) {
255+
throw new TypeError("paramName must be a string");
256+
}
257+
258+
// Implementation
259+
return result;
260+
}
261+
```
262+
263+
### Creating a New Core Class
264+
265+
```javascript
266+
"use strict";
267+
268+
import utils from "../utils.js";
269+
270+
/**
271+
* Class description
272+
*/
273+
class ClassName {
274+
constructor(config) {
275+
this.config = config || {};
276+
}
277+
278+
/**
279+
* Method description
280+
*
281+
* @param {Type} param - Description
282+
* @returns {ReturnType} Description
283+
*/
284+
methodName(param) {
285+
// Implementation
286+
}
287+
}
288+
289+
export default ClassName;
290+
```
291+
292+
### Error Handling Pattern
293+
294+
```javascript
295+
import AxiosError from "../core/AxiosError.js";
296+
297+
// Throw with context
298+
throw new AxiosError(
299+
"Descriptive error message",
300+
AxiosError.ERR_APPROPRIATE_CODE,
301+
config,
302+
request,
303+
response
304+
);
305+
306+
// Create from existing error
307+
const axiosError = AxiosError.from(error, code, config, request, response);
308+
```
309+
310+
## Summary
311+
312+
When working with Axios code, prioritize compatibility, use the established patterns for error handling and configuration, leverage the utils library for type checking, and ensure code works across both browser and Node.js environments. Always document your code with JSDoc and maintain the functional programming style used throughout the library.

0 commit comments

Comments
 (0)