mirror of
https://github.com/foss42/apidash.git
synced 2025-07-03 06:27:26 +08:00
Merge branch 'main' into feat/better_networking
This commit is contained in:
@ -105,7 +105,7 @@ API Dash can be downloaded from the links below:
|
||||
| Insomnia | ✅ |
|
||||
| OpenAPI | https://github.com/foss42/apidash/issues/121 |
|
||||
| hurl | https://github.com/foss42/apidash/issues/123 |
|
||||
| HAR | https://github.com/foss42/apidash/issues/122 |
|
||||
| HAR | ✅ |
|
||||
|
||||
|
||||
**↗️ Create & Customize API Requests**
|
||||
|
545
doc/user_guide/scripting_user_guide.md
Normal file
545
doc/user_guide/scripting_user_guide.md
Normal file
@ -0,0 +1,545 @@
|
||||
# APIDash Scripting: Using the `ad` Object
|
||||
|
||||
APIDash allows you to write JavaScript code that runs either **before** a request is sent (pre-request script) or **after** a response is received (post-response script). These scripts give you powerful control over the request/response lifecycle and allow for automation, dynamic data manipulation, and basic testing.
|
||||
|
||||
The primary way to interact with APIDash data and functionality within these scripts is through the global `ad` object. This object provides structured access to request data, response data, environment variables, and logging utilities.
|
||||
|
||||
|
||||
## `ad.request` (Available in Pre-request Scripts Only)
|
||||
|
||||
Use `ad.request` to inspect and modify the request *before* it is sent.
|
||||
|
||||
### `ad.request.headers`
|
||||
|
||||
Manage request headers. Headers are stored internally as an array of objects: `[{name: "Header-Name", value: "HeaderValue"}, ...]`. Note that header name comparisons in these helper methods are **case-sensitive**.
|
||||
|
||||
* **`ad.request.headers.set(key: string, value: string)`**
|
||||
* Adds a new header or updates the value of the *first* existing header with the exact same `key`. Ensures the `value` is converted to a string.
|
||||
* Example:
|
||||
```javascript
|
||||
// Set an Authorization header
|
||||
let token = ad.environment.get("authToken");
|
||||
if (token) {
|
||||
ad.request.headers.set("Authorization", "Bearer " + token);
|
||||
}
|
||||
|
||||
// Update User-Agent
|
||||
ad.request.headers.set("User-Agent", "APIDash-Script/1.0");
|
||||
```
|
||||
|
||||
* **`ad.request.headers.get(key: string): string | undefined`**
|
||||
* Retrieves the value of the *first* header matching the `key`. Returns `undefined` if not found.
|
||||
* Example:
|
||||
```javascript
|
||||
let contentType = ad.request.headers.get("Content-Type");
|
||||
if (!contentType) {
|
||||
ad.console.log("Content-Type header is not set yet.");
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.request.headers.remove(key: string)`**
|
||||
* Removes *all* headers matching the exact `key`.
|
||||
* Example:
|
||||
```javascript
|
||||
// Remove default Accept header if it exists
|
||||
ad.request.headers.remove("Accept");
|
||||
```
|
||||
|
||||
* **`ad.request.headers.has(key: string): boolean`**
|
||||
* Checks if at least one header with the exact `key` exists.
|
||||
* Example:
|
||||
```javascript
|
||||
if (!ad.request.headers.has("X-Request-ID")) {
|
||||
ad.request.headers.set("X-Request-ID", Date.now()); // Simple example ID
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.request.headers.clear()`**
|
||||
* Removes all request headers.
|
||||
* Example:
|
||||
```javascript
|
||||
// Start with a clean slate for headers (use with caution)
|
||||
// ad.request.headers.clear();
|
||||
// ad.request.headers.set("Authorization", "..."); // Add back essential ones
|
||||
```
|
||||
|
||||
### `ad.request.params`
|
||||
|
||||
Manage URL query parameters. Parameters are stored internally as an array of objects: `[{name: "paramName", value: "paramValue"}, ...]`. Parameter name comparisons are **case-sensitive**.
|
||||
|
||||
* **`ad.request.params.set(key: string, value: string)`**
|
||||
* Adds a new query parameter or updates the value of the *first* existing parameter with the exact same `key`. Ensures the `value` is converted to a string.
|
||||
* *Note:* HTTP allows duplicate query parameter keys. This `set` method replaces the first match or adds a new one. If you need duplicates, you might need to manipulate the underlying `request.params` array directly (use with care) or call `set` multiple times if the backend handles updates correctly.
|
||||
* Example:
|
||||
```javascript
|
||||
// Add or update a timestamp parameter
|
||||
ad.request.params.set("ts", Date.now().toString());
|
||||
|
||||
// Set a user ID from the environment
|
||||
let userId = ad.environment.get("activeUserId");
|
||||
if (userId) {
|
||||
ad.request.params.set("userId", userId);
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.request.params.get(key: string): string | undefined`**
|
||||
* Retrieves the value of the *first* parameter matching the `key`. Returns `undefined` if not found.
|
||||
* Example:
|
||||
```javascript
|
||||
let existingFilter = ad.request.params.get("filter");
|
||||
ad.console.log("Current filter:", existingFilter);
|
||||
```
|
||||
|
||||
* **`ad.request.params.remove(key: string)`**
|
||||
* Removes *all* parameters matching the exact `key`.
|
||||
* Example:
|
||||
```javascript
|
||||
// Remove any debug flags before sending
|
||||
ad.request.params.remove("debug");
|
||||
```
|
||||
|
||||
* **`ad.request.params.has(key: string): boolean`**
|
||||
* Checks if at least one parameter with the exact `key` exists.
|
||||
* Example:
|
||||
```javascript
|
||||
if (!ad.request.params.has("page")) {
|
||||
ad.request.params.set("page", "1");
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.request.params.clear()`**
|
||||
* Removes all query parameters.
|
||||
* Example:
|
||||
```javascript
|
||||
// Clear existing params if rebuilding the query string
|
||||
// ad.request.params.clear();
|
||||
// ad.request.params.set("newParam", "value");
|
||||
```
|
||||
|
||||
### `ad.request.url`
|
||||
|
||||
Access or modify the entire request URL.
|
||||
|
||||
* **`ad.request.url.get(): string`**
|
||||
* Returns the current request URL string.
|
||||
* Example:
|
||||
```javascript
|
||||
let currentUrl = ad.request.url.get();
|
||||
ad.console.log("Request URL before modification:", currentUrl);
|
||||
```
|
||||
|
||||
* **`ad.request.url.set(newUrl: string)`**
|
||||
* Sets the request URL to the provided `newUrl` string.
|
||||
* Example:
|
||||
```javascript
|
||||
let baseUrl = ad.environment.get("apiBaseUrl");
|
||||
let resourcePath = "/users/me";
|
||||
if (baseUrl) {
|
||||
ad.request.url.set(baseUrl + resourcePath);
|
||||
}
|
||||
```
|
||||
|
||||
### `ad.request.body`
|
||||
|
||||
Access or modify the request body.
|
||||
|
||||
* **`ad.request.body.get(): string | null | undefined`**
|
||||
* Returns the current request body as a string. For `multipart/form-data`, this might return an empty or non-representative string; use `request.formData` (accessed directly for now, potential future `ad.request.formData` helpers) for structured form data.
|
||||
* Example:
|
||||
```javascript
|
||||
let bodyContent = ad.request.body.get();
|
||||
ad.console.log("Current body:", bodyContent);
|
||||
```
|
||||
|
||||
* **`ad.request.body.set(newBody: string | object, contentType?: string)`**
|
||||
* Sets the request body.
|
||||
* If `newBody` is an object, it's automatically `JSON.stringify`-ed.
|
||||
* If `newBody` is not an object, it's converted to a string.
|
||||
* **Content-Type Handling:**
|
||||
* If you provide the optional `contentType` argument (e.g., 'application/xml'), that value is used.
|
||||
* If `contentType` is *not* provided:
|
||||
* Defaults to `application/json` if `newBody` was an object.
|
||||
* Defaults to `text/plain` otherwise.
|
||||
* The calculated `Content-Type` is automatically added as a request header *unless* a `Content-Type` header already exists (case-insensitive check).
|
||||
* **Side Effect:** Setting the body via this method will clear any existing `request.formData` entries, as they are mutually exclusive with a raw string/JSON body in the APIDash model. It also updates the internal `request.bodyContentType`.
|
||||
* Example:
|
||||
```javascript
|
||||
// Set a JSON body
|
||||
let userData = { name: "Test User", email: "test@example.com" };
|
||||
ad.request.body.set(userData); // Automatically sets Content-Type: application/json if not already set
|
||||
|
||||
// Set a plain text body
|
||||
ad.request.body.set("This is plain text content.", "text/plain");
|
||||
|
||||
// Set an XML body (Content-Type needed)
|
||||
let xmlString = "<user><name>Test</name></user>";
|
||||
ad.request.body.set(xmlString, "application/xml");
|
||||
```
|
||||
### `ad.request.query`
|
||||
|
||||
* Access or modify the GraphQL query string. This applies specifically to GraphQL requests, where the body typically includes a `query`, `variables`, and optionally `operationName`.
|
||||
|
||||
* **`ad.request.query.get(): string`**
|
||||
|
||||
* Returns the current GraphQL query string (query, mutation, or subscription). If not set, returns an empty string.
|
||||
* Example:
|
||||
|
||||
```javascript
|
||||
let gqlQuery = ad.request.query.get();
|
||||
ad.console.log("Current GraphQL query:", gqlQuery);
|
||||
```
|
||||
|
||||
* **`ad.request.query.set(newQuery: string)`**
|
||||
|
||||
* Sets the GraphQL query string.
|
||||
* Automatically sets the `Content-Type` header to `application/json` unless it's already set, ensuring correct handling by GraphQL servers.
|
||||
* Does **not** set the entire request body, it is up to the user to include the full GraphQL payload inside the query. (e.g., `{ query, variables, operationName }`).
|
||||
* Example:
|
||||
|
||||
```javascript
|
||||
let newQuery = `
|
||||
query {
|
||||
user(id: 1) {
|
||||
id
|
||||
username
|
||||
email
|
||||
address {
|
||||
geo {
|
||||
lat
|
||||
lng
|
||||
}
|
||||
}
|
||||
}
|
||||
}`;
|
||||
ad.request.query.set(newQuery);
|
||||
```
|
||||
|
||||
* **`ad.request.query.clear()`**
|
||||
|
||||
* Clears the current GraphQL query string by setting it to an empty string.
|
||||
* Example:
|
||||
|
||||
```javascript
|
||||
ad.request.query.clear();
|
||||
```
|
||||
|
||||
### `ad.request.method`
|
||||
|
||||
Access or modify the HTTP request method (verb).
|
||||
|
||||
* **`ad.request.method.get(): string`**
|
||||
* Returns the current request method (e.g., "get", "post"). Usually lowercase.
|
||||
* Example:
|
||||
```javascript
|
||||
let method = ad.request.method.get();
|
||||
ad.console.log("Request method:", method);
|
||||
```
|
||||
|
||||
* **`ad.request.method.set(newMethod: string)`**
|
||||
* Sets the request method. The provided `newMethod` string will be converted to lowercase (e.g., "PUT" becomes "put").
|
||||
* Example:
|
||||
```javascript
|
||||
// Change method based on environment setting
|
||||
let usePatch = ad.environment.get("usePatchForUpdates");
|
||||
if (ad.request.method.get() === "put" && usePatch) {
|
||||
ad.request.method.set("PATCH");
|
||||
}
|
||||
```
|
||||
|
||||
## `ad.response` (Available in Post-response Scripts Only)
|
||||
|
||||
Use `ad.response` to access details of the response received from the server. This object is **read-only**.
|
||||
|
||||
* **`ad.response.status: number | undefined`**
|
||||
* The HTTP status code (e.g., `200`, `404`).
|
||||
* Example:
|
||||
```javascript
|
||||
if (ad.response.status === 201) {
|
||||
ad.console.log("Resource created successfully!");
|
||||
} else if (ad.response.status >= 400) {
|
||||
ad.console.error("Request failed with status:", ad.response.status);
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.response.body: string | undefined`**
|
||||
* The response body as a string. For binary responses, this might be decoded text or potentially garbled data depending on the Content-Type and encoding. Use `bodyBytes` for raw data.
|
||||
* Example:
|
||||
```javascript
|
||||
let responseText = ad.response.body;
|
||||
if (responseText && responseText.includes("error")) {
|
||||
ad.console.warn("Response body might contain an error message.");
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.response.formattedBody: string | undefined`**
|
||||
* The response body pre-formatted by APIDash (e.g., pretty-printed JSON). Useful for logging structured data clearly.
|
||||
* Example:
|
||||
```javascript
|
||||
ad.console.log("Formatted Response Body:\n", ad.response.formattedBody);
|
||||
```
|
||||
|
||||
* **`ad.response.bodyBytes: number[] | undefined`**
|
||||
* The raw response body as an array of byte values (integers 0-255). Useful for binary data, but be mindful of potential performance/memory impact for very large responses. Depends on Dart correctly serializing `Uint8List` to `List<int>`.
|
||||
* Example:
|
||||
```javascript
|
||||
let bytes = ad.response.bodyBytes;
|
||||
if (bytes) {
|
||||
ad.console.log(`Received ${bytes.length} bytes.`);
|
||||
// You might perform checks on byte sequences, e.g., magic numbers for file types
|
||||
// if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
|
||||
// ad.console.log("Looks like a PNG file.");
|
||||
// }
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.response.time: number | undefined`**
|
||||
* The approximate time taken for the request-response cycle, in **milliseconds**.
|
||||
* Example:
|
||||
```javascript
|
||||
let duration = ad.response.time;
|
||||
if (duration !== undefined) {
|
||||
ad.console.log(`Request took ${duration.toFixed(2)} ms.`);
|
||||
if (duration > 1000) {
|
||||
ad.console.warn("Request took longer than 1 second.");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.response.headers: object | undefined`**
|
||||
* An object containing the response headers. Header names are typically **lowercase** (due to processing by the underlying HTTP client). Values are strings.
|
||||
* Example:
|
||||
```javascript
|
||||
let headers = ad.response.headers;
|
||||
if (headers) {
|
||||
ad.console.log("Response Content-Type:", headers['content-type']); // Access using lowercase key
|
||||
ad.console.log("Response Date Header:", headers.date);
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.response.requestHeaders: object | undefined`**
|
||||
* An object containing the headers that were actually *sent* with the request. Useful for debugging or verification. Header names are typically **lowercase**.
|
||||
* Example:
|
||||
```javascript
|
||||
let sentHeaders = ad.response.requestHeaders;
|
||||
if (sentHeaders) {
|
||||
ad.console.log("Sent User-Agent:", sentHeaders['user-agent']);
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.response.json(): object | undefined`**
|
||||
* Attempts to parse the `ad.response.body` as JSON.
|
||||
* Returns the parsed JavaScript object/array if successful.
|
||||
* Returns `undefined` if the body is empty or parsing fails (an error message is automatically logged to the APIDash console via `ad.console.error` in case of failure).
|
||||
* Example:
|
||||
```javascript
|
||||
let jsonData = ad.response.json();
|
||||
if (jsonData && jsonData.data && jsonData.data.token) {
|
||||
ad.console.log("Found token in response.");
|
||||
ad.environment.set("sessionToken", jsonData.data.token);
|
||||
} else if (jsonData) {
|
||||
ad.console.log("Parsed JSON, but expected structure not found.");
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.response.getHeader(key: string): string | undefined`**
|
||||
* Retrieves a specific response header's value. The lookup is **case-insensitive**.
|
||||
* Example:
|
||||
```javascript
|
||||
// These are equivalent because of case-insensitivity:
|
||||
let contentType = ad.response.getHeader("Content-Type");
|
||||
let contentTypeLower = ad.response.getHeader("content-type");
|
||||
ad.console.log("Response Content-Type (case-insensitive get):", contentType);
|
||||
|
||||
let correlationId = ad.response.getHeader("X-Correlation-ID");
|
||||
if (correlationId) {
|
||||
ad.environment.set("lastCorrelationId", correlationId);
|
||||
}
|
||||
```
|
||||
|
||||
## `ad.environment` (Available in Pre & Post-response Scripts)
|
||||
|
||||
Use `ad.environment` to get, set, or remove variables within the currently active APIDash environment. Changes made here persist after the script runs and can be used by subsequent requests or other scripts using the same environment.
|
||||
|
||||
* **`ad.environment.get(key: string): any`**
|
||||
* Retrieves the value of the environment variable named `key`. Returns `undefined` if not found.
|
||||
* Example:
|
||||
```javascript
|
||||
let apiUrl = ad.environment.get("baseUrl");
|
||||
let apiKey = ad.environment.get("apiKey");
|
||||
ad.console.log("Using API URL:", apiUrl);
|
||||
```
|
||||
|
||||
* **`ad.environment.set(key: string, value: any)`**
|
||||
* Sets an environment variable named `key` to the given `value`. The `value` should be JSON-serializable (string, number, boolean, object, array, null).
|
||||
* Example:
|
||||
```javascript
|
||||
// In a post-response script after login:
|
||||
let responseData = ad.response.json();
|
||||
if (responseData && responseData.access_token) {
|
||||
ad.environment.set("oauthToken", responseData.access_token);
|
||||
ad.environment.set("tokenExpiry", Date.now() + (responseData.expires_in * 1000));
|
||||
ad.console.log("OAuth token saved to environment.");
|
||||
}
|
||||
|
||||
// Store complex object
|
||||
ad.environment.set("userProfile", { id: 123, name: "Default User"});
|
||||
```
|
||||
|
||||
* **`ad.environment.unset(key: string)`**
|
||||
* Removes the environment variable named `key`.
|
||||
* Example:
|
||||
```javascript
|
||||
// Clear temporary token after use or logout
|
||||
ad.environment.unset("sessionToken");
|
||||
ad.console.log("Session token cleared.");
|
||||
```
|
||||
|
||||
* **`ad.environment.has(key: string): boolean`**
|
||||
* Checks if an environment variable named `key` exists.
|
||||
* Example:
|
||||
```javascript
|
||||
if (!ad.environment.has("userId")) {
|
||||
ad.console.warn("Environment variable 'userId' is not set.");
|
||||
// Maybe set a default or fetch it?
|
||||
// ad.environment.set("userId", "default-001");
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.environment.clear()`**
|
||||
* Removes *all* variables from the active environment. Use with extreme caution!
|
||||
* Example:
|
||||
```javascript
|
||||
// Usually used for resetting state during testing, careful!
|
||||
// ad.environment.clear();
|
||||
// ad.console.warn("Cleared all variables in the active environment!");
|
||||
```
|
||||
|
||||
## `ad.console` (Available in Pre & Post-response Scripts)
|
||||
|
||||
Use `ad.console` to log messages to the APIDash console tab for the corresponding request. This is essential for debugging your scripts.
|
||||
|
||||
* **`ad.console.log(...args: any[])`**
|
||||
* Logs informational messages. Accepts multiple arguments, which will be JSON-stringified and displayed in the console.
|
||||
* Example:
|
||||
```javascript
|
||||
ad.console.log("Starting pre-request script...");
|
||||
let user = ad.environment.get("currentUser");
|
||||
ad.console.log("Current user from environment:", user);
|
||||
ad.console.log("Request URL is:", ad.request.url.get(), "Method:", ad.request.method.get());
|
||||
```
|
||||
|
||||
* **`ad.console.warn(...args: any[])`**
|
||||
* Logs warning messages. Typically displayed differently (e.g., yellow background) in the console.
|
||||
* Example:
|
||||
```javascript
|
||||
if (!ad.environment.has("apiKey")) {
|
||||
ad.console.warn("API Key environment variable is missing!");
|
||||
}
|
||||
let responseTime = ad.response.time;
|
||||
if (responseTime && responseTime > 2000) {
|
||||
ad.console.warn("Request took over 2 seconds:", responseTime, "ms");
|
||||
}
|
||||
```
|
||||
|
||||
* **`ad.console.error(...args: any[])`**
|
||||
* Logs error messages. Typically displayed prominently (e.g., red background) in the console. Also used internally by methods like `ad.response.json()` on failure.
|
||||
* Example:
|
||||
```javascript
|
||||
if (ad.response.status >= 500) {
|
||||
ad.console.error("Server error detected!", "Status:", ad.response.status);
|
||||
ad.console.error("Response Body:", ad.response.body);
|
||||
}
|
||||
try {
|
||||
// Some operation that might fail
|
||||
let criticalValue = ad.response.json().mustExist;
|
||||
} catch (e) {
|
||||
ad.console.error("Script failed to process response:", e.toString(), e.stack);
|
||||
}
|
||||
```
|
||||
|
||||
### Key Notes:
|
||||
1. **Pre/Post Script Context**
|
||||
- Request manipulation only works in pre-request scripts
|
||||
- Response access only works in post-response scripts
|
||||
|
||||
2. **Environment Variables**
|
||||
- Use `{{VAR_NAME}}` syntax in values for automatic substitution
|
||||
- Changes to environment variables persist for subsequent requests
|
||||
|
||||
3. **Data Types**
|
||||
- All values are converted to strings when set in headers/params
|
||||
- Use `ad.request.body.set()` with objects for proper JSON handling
|
||||
|
||||
4. **Error Handling**
|
||||
```javascript
|
||||
try {
|
||||
// Potentially error-prone operations
|
||||
} catch(e) {
|
||||
ad.console.error('Operation failed:', e.message)
|
||||
// Optionally re-throw to abort request
|
||||
throw e
|
||||
}
|
||||
```
|
||||
|
||||
5. **Best Practices**
|
||||
- Always check for existence before accessing values
|
||||
- Use environment variables for sensitive data
|
||||
- Clean up temporary variables with `ad.environment.unset()`
|
||||
- Use logging strategically to track script execution
|
||||
|
||||
### Example Workflow
|
||||
|
||||
### Example 1: Post-request - Extract Data and Check Status
|
||||
|
||||
```javascript
|
||||
// Post-response Script
|
||||
|
||||
// Set URL: https://api.apidash.dev/auth/login
|
||||
// 1. Check response status
|
||||
if (ad.response.status < 200 || ad.response.status >= 300) {
|
||||
ad.console.error(`Request failed with status ${ad.response.status}.`);
|
||||
ad.console.error("Response:", ad.response.body);
|
||||
// Optional: Could clear a related environment variable on failure
|
||||
// ad.environment.unset("last_successful_item_id");
|
||||
return; // Stop processing if status indicates failure
|
||||
}
|
||||
|
||||
ad.console.log(`Request successful with status ${ad.response.status}.`);
|
||||
ad.console.log(`Took ${ad.response.time} ms.`);
|
||||
|
||||
// 2. Try to parse JSON response
|
||||
const data = ad.response.json();
|
||||
|
||||
// 3. Extract and store data if available
|
||||
if (data && data.access_token) {
|
||||
ad.environment.set("current_session_id", data.access_token);
|
||||
ad.console.log("Session ID saved to environment.");
|
||||
} else {
|
||||
ad.console.warn("Could not find 'access_token' in the response JSON.");
|
||||
}
|
||||
```
|
||||
|
||||
### Example 2: Pre-request - Set Auth Header
|
||||
|
||||
```javascript
|
||||
// Pre-request Script
|
||||
|
||||
// Set URL : https://api.apidash.dev/profile
|
||||
// 1. Get Auth token from environment
|
||||
const token = ad.environment.get("access_token");
|
||||
if (token) {
|
||||
ad.request.headers.set("Authorization", `Bearer ${token}`);
|
||||
ad.console.log("Authorization header set.");
|
||||
} else {
|
||||
ad.console.warn("API token not found in environment!");
|
||||
}
|
||||
|
||||
// 2. Try to parse JSON response
|
||||
const data = ad.response.json();
|
||||
|
||||
// 3. Extract and store final User if available
|
||||
if (data && data.user && data.user.id) {
|
||||
ad.environment.set("logged_in_user_id", data.user.id);
|
||||
ad.console.log(`User ID ${data.user.id} saved to environment.`);
|
||||
}
|
||||
```
|
@ -6,6 +6,8 @@ import 'package:flutter/material.dart';
|
||||
|
||||
const kDiscordUrl = "https://bit.ly/heyfoss";
|
||||
const kGitUrl = "https://github.com/foss42/apidash";
|
||||
const kLearnScriptingUrl =
|
||||
"$kGitUrl/blob/main/doc/user_guide/scripting_user_guide.md";
|
||||
const kIssueUrl = "$kGitUrl/issues";
|
||||
const kDefaultUri = "api.apidash.dev";
|
||||
|
||||
@ -144,7 +146,8 @@ enum CodegenLanguage {
|
||||
enum ImportFormat {
|
||||
curl("cURL"),
|
||||
postman("Postman Collection v2.1"),
|
||||
insomnia("Insomnia v4");
|
||||
insomnia("Insomnia v4"),
|
||||
har("Har v1.2");
|
||||
|
||||
const ImportFormat(this.label);
|
||||
final String label;
|
||||
@ -441,9 +444,10 @@ const kUntitled = "untitled";
|
||||
const kLabelRequest = "Request";
|
||||
const kLabelHideCode = "Hide Code";
|
||||
const kLabelViewCode = "View Code";
|
||||
const kLabelURLParams = "URL Params";
|
||||
const kLabelURLParams = "Params";
|
||||
const kLabelHeaders = "Headers";
|
||||
const kLabelBody = "Body";
|
||||
const kLabelScripts = "Scripts";
|
||||
const kLabelQuery = "Query";
|
||||
const kNameCheckbox = "Checkbox";
|
||||
const kNameURLParam = "URL Parameter";
|
||||
@ -463,6 +467,8 @@ const kHintContent = "Enter content";
|
||||
const kHintText = "Enter text";
|
||||
const kHintJson = "Enter JSON";
|
||||
const kHintQuery = "Enter Query";
|
||||
// TODO: CodeField widget does not allow this hint. To be solved.
|
||||
const kHintScript = "// Use Javacript to modify this request dynamically";
|
||||
// Response Pane
|
||||
const kLabelNotSent = "Not Sent";
|
||||
const kLabelResponse = "Response";
|
||||
|
2
lib/dashbot/consts.dart
Normal file
2
lib/dashbot/consts.dart
Normal file
@ -0,0 +1,2 @@
|
||||
const kModel = 'llama3.2:3b';
|
||||
const kOllamaEndpoint = 'http://127.0.0.1:11434/api';
|
@ -1,6 +1,6 @@
|
||||
import 'dart:convert';
|
||||
import '../services/dashbot_service.dart';
|
||||
import 'package:apidash/models/request_model.dart';
|
||||
import '../services/services.dart';
|
||||
import '../../models/models.dart';
|
||||
|
||||
class DebugFeature {
|
||||
final DashBotService _service;
|
||||
|
66
lib/dashbot/features/documentation.dart
Normal file
66
lib/dashbot/features/documentation.dart
Normal file
@ -0,0 +1,66 @@
|
||||
import 'dart:convert';
|
||||
import '../services/services.dart';
|
||||
import '../../models/models.dart';
|
||||
|
||||
class DocumentationFeature {
|
||||
final DashBotService _service;
|
||||
|
||||
DocumentationFeature(this._service);
|
||||
|
||||
Future<String> generateApiDocumentation({
|
||||
required RequestModel? requestModel,
|
||||
required dynamic responseModel,
|
||||
}) async {
|
||||
if (requestModel == null || responseModel == null) {
|
||||
return "No recent API requests found.";
|
||||
}
|
||||
|
||||
final method = requestModel.httpRequestModel?.method
|
||||
.toString()
|
||||
.split('.')
|
||||
.last
|
||||
.toUpperCase() ??
|
||||
"GET";
|
||||
final endpoint = requestModel.httpRequestModel?.url ?? "Unknown Endpoint";
|
||||
final headers = requestModel.httpRequestModel?.enabledHeadersMap ?? {};
|
||||
final parameters = requestModel.httpRequestModel?.enabledParamsMap ?? {};
|
||||
final body = requestModel.httpRequestModel?.body;
|
||||
final rawResponse = responseModel.body;
|
||||
final responseBody =
|
||||
rawResponse is String ? rawResponse : jsonEncode(rawResponse);
|
||||
final statusCode = responseModel.statusCode ?? 0;
|
||||
|
||||
final prompt = """
|
||||
API DOCUMENTATION GENERATION
|
||||
|
||||
**API Details:**
|
||||
- Endpoint: $endpoint
|
||||
- Method: $method
|
||||
- Status Code: $statusCode
|
||||
|
||||
**Request Components:**
|
||||
- Headers: ${headers.isNotEmpty ? jsonEncode(headers) : "None"}
|
||||
- Query Parameters: ${parameters.isNotEmpty ? jsonEncode(parameters) : "None"}
|
||||
- Request Body: ${body != null && body.isNotEmpty ? body : "None"}
|
||||
|
||||
**Response Example:**
|
||||
```
|
||||
$responseBody
|
||||
```
|
||||
|
||||
**Documentation Instructions:**
|
||||
Create comprehensive API documentation that includes:
|
||||
|
||||
1. **Overview**: A clear, concise description of what this API endpoint does
|
||||
2. **Authentication**: Required authentication method based on headers
|
||||
3. **Request Details**: All required and optional parameters with descriptions
|
||||
4. **Response Structure**: Breakdown of response fields and their meanings
|
||||
5. **Error Handling**: Possible error codes and troubleshooting
|
||||
6. **Example Usage**: A complete code example showing how to call this API
|
||||
|
||||
Format in clean markdown with proper sections and code blocks where appropriate.
|
||||
""";
|
||||
|
||||
return _service.generateResponse(prompt);
|
||||
}
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
import '../services/dashbot_service.dart';
|
||||
import 'package:apidash/models/request_model.dart';
|
||||
import '../services/services.dart';
|
||||
import '../../models/models.dart';
|
||||
|
||||
class ExplainFeature {
|
||||
final DashBotService _service;
|
||||
|
5
lib/dashbot/features/features.dart
Normal file
5
lib/dashbot/features/features.dart
Normal file
@ -0,0 +1,5 @@
|
||||
export 'debug.dart';
|
||||
export 'documentation.dart';
|
||||
export 'explain.dart';
|
||||
export 'general_query.dart';
|
||||
export 'test_generator.dart';
|
54
lib/dashbot/features/general_query.dart
Normal file
54
lib/dashbot/features/general_query.dart
Normal file
@ -0,0 +1,54 @@
|
||||
import 'package:ollama_dart/ollama_dart.dart';
|
||||
import '../../models/models.dart';
|
||||
import '../consts.dart';
|
||||
|
||||
class GeneralQueryFeature {
|
||||
final OllamaClient _client;
|
||||
|
||||
GeneralQueryFeature(this._client);
|
||||
|
||||
Future<String> generateResponse(String prompt,
|
||||
{RequestModel? requestModel, dynamic responseModel}) async {
|
||||
String enhancedPrompt = prompt;
|
||||
|
||||
if (requestModel != null && responseModel != null) {
|
||||
final method = requestModel.httpRequestModel?.method
|
||||
.toString()
|
||||
.split('.')
|
||||
.last
|
||||
.toUpperCase() ??
|
||||
"GET";
|
||||
final endpoint = requestModel.httpRequestModel?.url ?? "Unknown Endpoint";
|
||||
final statusCode = responseModel.statusCode ?? 0;
|
||||
|
||||
enhancedPrompt = '''
|
||||
CONTEXT-AWARE RESPONSE
|
||||
|
||||
**User Question:**
|
||||
$prompt
|
||||
|
||||
**Related API Context:**
|
||||
- Endpoint: $endpoint
|
||||
- Method: $method
|
||||
- Status Code: $statusCode
|
||||
|
||||
**Instructions:**
|
||||
1. Directly address the user's specific question
|
||||
2. Provide relevant, concise information
|
||||
3. Reference the API context when helpful
|
||||
4. Focus on practical, actionable insights
|
||||
5. Avoid generic explanations or documentation
|
||||
|
||||
Respond in a helpful, direct manner that specifically answers what was asked.
|
||||
''';
|
||||
}
|
||||
|
||||
final response = await _client.generateCompletion(
|
||||
request: GenerateCompletionRequest(
|
||||
model: kModel,
|
||||
prompt: enhancedPrompt,
|
||||
),
|
||||
);
|
||||
return response.response.toString();
|
||||
}
|
||||
}
|
94
lib/dashbot/features/test_generator.dart
Normal file
94
lib/dashbot/features/test_generator.dart
Normal file
@ -0,0 +1,94 @@
|
||||
import 'dart:convert';
|
||||
import '../services/services.dart';
|
||||
import '../../models/models.dart';
|
||||
|
||||
class TestGeneratorFeature {
|
||||
final DashBotService _service;
|
||||
|
||||
TestGeneratorFeature(this._service);
|
||||
|
||||
Future<String> generateApiTests({
|
||||
required RequestModel? requestModel,
|
||||
required dynamic responseModel,
|
||||
}) async {
|
||||
if (requestModel == null || responseModel == null) {
|
||||
return "No recent API requests found.";
|
||||
}
|
||||
|
||||
final method = requestModel.httpRequestModel?.method
|
||||
.toString()
|
||||
.split('.')
|
||||
.last
|
||||
.toUpperCase() ??
|
||||
"GET";
|
||||
final endpoint = requestModel.httpRequestModel?.url ?? "Unknown Endpoint";
|
||||
final rawResponse = responseModel.body;
|
||||
final responseBody =
|
||||
rawResponse is String ? rawResponse : jsonEncode(rawResponse);
|
||||
final statusCode = responseModel.statusCode ?? 0;
|
||||
|
||||
Uri uri = Uri.parse(endpoint);
|
||||
final baseUrl = "${uri.scheme}://${uri.host}";
|
||||
final path = uri.path;
|
||||
|
||||
final parameterAnalysis = _analyzeParameters(uri.queryParameters);
|
||||
|
||||
final prompt = """
|
||||
EXECUTABLE API TEST CASES GENERATOR
|
||||
|
||||
**API Analysis:**
|
||||
- Base URL: $baseUrl
|
||||
- Endpoint: $path
|
||||
- Method: $method
|
||||
- Current Parameters: ${uri.queryParameters}
|
||||
- Current Response: $responseBody (Status: $statusCode)
|
||||
- Parameter Types: $parameterAnalysis
|
||||
|
||||
**Test Generation Task:**
|
||||
Generate practical, ready-to-use test cases for this API in cURL format. Each test should be executable immediately.
|
||||
|
||||
Include these test categories:
|
||||
1. **Valid Cases**: Different valid parameter values (use real-world examples like other country codes if this is a country API)
|
||||
2. **Invalid Parameter Tests**: Missing parameters, empty values, incorrect formats
|
||||
3. **Edge Cases**: Special characters, long values, unexpected inputs
|
||||
4. **Validation Tests**: Test input validation and error handling
|
||||
|
||||
For each test case:
|
||||
1. Provide a brief description of what the test verifies
|
||||
2. Include a complete, executable cURL command
|
||||
3. Show the expected outcome (status code and sample response)
|
||||
4. Organize tests in a way that's easy to copy and run
|
||||
|
||||
Focus on creating realistic test values based on the API context (e.g., for a country flag API, use real country codes, invalid codes, etc.)
|
||||
""";
|
||||
|
||||
final testCases = await _service.generateResponse(prompt);
|
||||
return "TEST_CASES_HIDDEN\n$testCases";
|
||||
}
|
||||
|
||||
String _analyzeParameters(Map<String, String> parameters) {
|
||||
if (parameters.isEmpty) {
|
||||
return "No parameters detected";
|
||||
}
|
||||
|
||||
Map<String, String> analysis = {};
|
||||
|
||||
parameters.forEach((key, value) {
|
||||
if (RegExp(r'^[A-Z]{3}$').hasMatch(value)) {
|
||||
analysis[key] =
|
||||
"Appears to be a 3-letter country code (ISO 3166-1 alpha-3)";
|
||||
} else if (RegExp(r'^[A-Z]{2}$').hasMatch(value)) {
|
||||
analysis[key] =
|
||||
"Appears to be a 2-letter country code (ISO 3166-1 alpha-2)";
|
||||
} else if (RegExp(r'^\d+$').hasMatch(value)) {
|
||||
analysis[key] = "Numeric value";
|
||||
} else if (RegExp(r'^[a-zA-Z]+$').hasMatch(value)) {
|
||||
analysis[key] = "Alphabetic string";
|
||||
} else {
|
||||
analysis[key] = "Unknown format: $value";
|
||||
}
|
||||
});
|
||||
|
||||
return jsonEncode(analysis);
|
||||
}
|
||||
}
|
@ -1,7 +1,11 @@
|
||||
import 'dart:convert';
|
||||
import 'package:apidash/services/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../services/dashbot_service.dart';
|
||||
import '../services/services.dart';
|
||||
|
||||
final dashBotMinimizedProvider = StateProvider<bool>((ref) {
|
||||
return true;
|
||||
});
|
||||
|
||||
final chatMessagesProvider =
|
||||
StateNotifierProvider<ChatMessagesNotifier, List<Map<String, dynamic>>>(
|
||||
@ -17,19 +21,16 @@ class ChatMessagesNotifier extends StateNotifier<List<Map<String, dynamic>>> {
|
||||
_loadMessages();
|
||||
}
|
||||
|
||||
static const _storageKey = 'chatMessages';
|
||||
|
||||
Future<void> _loadMessages() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final messages = prefs.getString(_storageKey);
|
||||
final messages = await hiveHandler.getDashbotMessages();
|
||||
if (messages != null) {
|
||||
state = List<Map<String, dynamic>>.from(json.decode(messages));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _saveMessages() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString(_storageKey, json.encode(state));
|
||||
final messages = json.encode(state);
|
||||
await hiveHandler.saveDashbotMessages(messages);
|
||||
}
|
||||
|
||||
void addMessage(Map<String, dynamic> message) {
|
||||
|
@ -1,36 +1,61 @@
|
||||
import 'package:apidash/dashbot/features/debug.dart';
|
||||
import 'package:ollama_dart/ollama_dart.dart';
|
||||
import '../features/explain.dart';
|
||||
import 'package:apidash/models/request_model.dart';
|
||||
import '../consts.dart';
|
||||
import '../features/features.dart';
|
||||
|
||||
class DashBotService {
|
||||
final OllamaClient _client;
|
||||
late final ExplainFeature _explainFeature;
|
||||
late final DebugFeature _debugFeature;
|
||||
late final DocumentationFeature _documentationFeature;
|
||||
late final TestGeneratorFeature _testGeneratorFeature;
|
||||
final GeneralQueryFeature _generalQueryFeature;
|
||||
|
||||
DashBotService()
|
||||
: _client = OllamaClient(baseUrl: 'http://127.0.0.1:11434/api') {
|
||||
: _client = OllamaClient(baseUrl: kOllamaEndpoint),
|
||||
_generalQueryFeature =
|
||||
GeneralQueryFeature(OllamaClient(baseUrl: kOllamaEndpoint)) {
|
||||
_explainFeature = ExplainFeature(this);
|
||||
_debugFeature = DebugFeature(this);
|
||||
_documentationFeature = DocumentationFeature(this);
|
||||
_testGeneratorFeature = TestGeneratorFeature(this);
|
||||
}
|
||||
|
||||
Future<String> generateResponse(String prompt) async {
|
||||
final response = await _client.generateCompletion(
|
||||
request: GenerateCompletionRequest(model: 'llama3.2:3b', prompt: prompt),
|
||||
);
|
||||
return response.response.toString();
|
||||
return _generalQueryFeature.generateResponse(prompt);
|
||||
}
|
||||
|
||||
Future<String> handleRequest(
|
||||
String input, RequestModel? requestModel, dynamic responseModel) async {
|
||||
String input,
|
||||
RequestModel? requestModel,
|
||||
dynamic responseModel,
|
||||
) async {
|
||||
if (input == "Explain API") {
|
||||
return _explainFeature.explainLatestApi(
|
||||
requestModel: requestModel, responseModel: responseModel);
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
} else if (input == "Debug API") {
|
||||
return _debugFeature.debugApi(
|
||||
requestModel: requestModel, responseModel: responseModel);
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
} else if (input == "Document API") {
|
||||
return _documentationFeature.generateApiDocumentation(
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
} else if (input == "Test API") {
|
||||
return _testGeneratorFeature.generateApiTests(
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
}
|
||||
|
||||
return generateResponse(input);
|
||||
return _generalQueryFeature.generateResponse(
|
||||
input,
|
||||
requestModel: requestModel,
|
||||
responseModel: responseModel,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
1
lib/dashbot/services/services.dart
Normal file
1
lib/dashbot/services/services.dart
Normal file
@ -0,0 +1 @@
|
||||
export 'dashbot_service.dart';
|
@ -7,7 +7,11 @@ class ChatBubble extends StatelessWidget {
|
||||
final String message;
|
||||
final bool isUser;
|
||||
|
||||
const ChatBubble({super.key, required this.message, this.isUser = false});
|
||||
const ChatBubble({
|
||||
super.key,
|
||||
required this.message,
|
||||
this.isUser = false,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
|
@ -1,16 +1,23 @@
|
||||
// lib/dashbot/widgets/content_renderer.dart
|
||||
import 'dart:convert';
|
||||
import 'package:apidash_design_system/apidash_design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_highlighter/flutter_highlighter.dart';
|
||||
import 'package:flutter_highlighter/themes/monokai-sublime.dart';
|
||||
import 'package:flutter_markdown/flutter_markdown.dart';
|
||||
|
||||
Widget renderContent(BuildContext context, String text) {
|
||||
Widget renderContent(
|
||||
BuildContext context,
|
||||
String text,
|
||||
) {
|
||||
if (text.isEmpty) {
|
||||
return const Text("No content to display.");
|
||||
}
|
||||
|
||||
final codeBlockPattern = RegExp(r'```(\w+)?\n([\s\S]*?)```', multiLine: true);
|
||||
final codeBlockPattern = RegExp(
|
||||
r'```(\w+)?\n([\s\S]*?)```',
|
||||
multiLine: true,
|
||||
);
|
||||
final matches = codeBlockPattern.allMatches(text);
|
||||
|
||||
if (matches.isEmpty) {
|
||||
@ -22,8 +29,10 @@ Widget renderContent(BuildContext context, String text) {
|
||||
|
||||
for (var match in matches) {
|
||||
if (match.start > lastEnd) {
|
||||
children
|
||||
.add(_renderMarkdown(context, text.substring(lastEnd, match.start)));
|
||||
children.add(_renderMarkdown(
|
||||
context,
|
||||
text.substring(lastEnd, match.start),
|
||||
));
|
||||
}
|
||||
|
||||
final language = match.group(1) ?? 'text';
|
||||
@ -43,7 +52,10 @@ Widget renderContent(BuildContext context, String text) {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _renderMarkdown(BuildContext context, String markdown) {
|
||||
Widget _renderMarkdown(
|
||||
BuildContext context,
|
||||
String markdown,
|
||||
) {
|
||||
return MarkdownBody(
|
||||
data: markdown,
|
||||
selectable: true,
|
||||
@ -53,7 +65,11 @@ Widget _renderMarkdown(BuildContext context, String markdown) {
|
||||
);
|
||||
}
|
||||
|
||||
Widget _renderCodeBlock(BuildContext context, String language, String code) {
|
||||
Widget _renderCodeBlock(
|
||||
BuildContext context,
|
||||
String language,
|
||||
String code,
|
||||
) {
|
||||
if (language == 'json') {
|
||||
try {
|
||||
final prettyJson =
|
||||
@ -63,7 +79,9 @@ Widget _renderCodeBlock(BuildContext context, String language, String code) {
|
||||
color: Theme.of(context).colorScheme.surfaceContainerLow,
|
||||
child: SelectableText(
|
||||
prettyJson,
|
||||
style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
|
||||
style: kCodeStyle.copyWith(
|
||||
fontSize: Theme.of(context).textTheme.bodyMedium?.fontSize,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
@ -78,7 +96,9 @@ Widget _renderCodeBlock(BuildContext context, String language, String code) {
|
||||
code,
|
||||
language: language,
|
||||
theme: monokaiSublimeTheme,
|
||||
textStyle: const TextStyle(fontFamily: 'monospace', fontSize: 12),
|
||||
textStyle: kCodeStyle.copyWith(
|
||||
fontSize: Theme.of(context).textTheme.bodyMedium?.fontSize,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
@ -87,14 +107,19 @@ Widget _renderCodeBlock(BuildContext context, String language, String code) {
|
||||
}
|
||||
}
|
||||
|
||||
Widget _renderFallbackCode(BuildContext context, String code) {
|
||||
Widget _renderFallbackCode(
|
||||
BuildContext context,
|
||||
String code,
|
||||
) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
color: Theme.of(context).colorScheme.surfaceContainerLow,
|
||||
child: SelectableText(
|
||||
code,
|
||||
style: const TextStyle(
|
||||
fontFamily: 'monospace', fontSize: 12, color: Colors.red),
|
||||
style: kCodeStyle.copyWith(
|
||||
fontSize: Theme.of(context).textTheme.bodyMedium?.fontSize,
|
||||
color: Colors.red,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
// lib/dashbot/widgets/dashbot_widget.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:apidash/dashbot/providers/dashbot_providers.dart';
|
||||
import 'package:apidash/providers/providers.dart';
|
||||
import 'test_runner_widget.dart';
|
||||
import 'chat_bubble.dart';
|
||||
|
||||
class DashBotWidget extends ConsumerStatefulWidget {
|
||||
@ -48,10 +48,21 @@ class _DashBotWidgetState extends ConsumerState<DashBotWidget> {
|
||||
try {
|
||||
final response = await dashBotService.handleRequest(
|
||||
message, requestModel, responseModel);
|
||||
ref.read(chatMessagesProvider.notifier).addMessage({
|
||||
'role': 'bot',
|
||||
'message': response,
|
||||
});
|
||||
if (response.startsWith("TEST_CASES_HIDDEN\n")) {
|
||||
final testCases = response.replaceFirst("TEST_CASES_HIDDEN\n", "");
|
||||
ref.read(chatMessagesProvider.notifier).addMessage({
|
||||
'role': 'bot',
|
||||
'message':
|
||||
"Test cases generated successfully. Click the button below to run them.",
|
||||
'testCases': testCases,
|
||||
'showTestButton': true,
|
||||
});
|
||||
} else {
|
||||
ref.read(chatMessagesProvider.notifier).addMessage({
|
||||
'role': 'bot',
|
||||
'message': response,
|
||||
});
|
||||
}
|
||||
} catch (error, stackTrace) {
|
||||
debugPrint('Error in _sendMessage: $error');
|
||||
debugPrint('StackTrace: $stackTrace');
|
||||
@ -63,7 +74,7 @@ class _DashBotWidgetState extends ConsumerState<DashBotWidget> {
|
||||
setState(() => _isLoading = false);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_scrollController.animateTo(
|
||||
0,
|
||||
_scrollController.position.minScrollExtent,
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
@ -71,111 +82,225 @@ class _DashBotWidgetState extends ConsumerState<DashBotWidget> {
|
||||
}
|
||||
}
|
||||
|
||||
void _showTestRunner(String testCases) {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => Dialog(
|
||||
child: SizedBox(
|
||||
width: MediaQuery.of(context).size.width * 0.8,
|
||||
height: 500,
|
||||
child: TestRunnerWidget(testCases: testCases),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final messages = ref.watch(chatMessagesProvider);
|
||||
final requestModel = ref.read(selectedRequestModelProvider);
|
||||
final statusCode = requestModel?.httpResponseModel?.statusCode;
|
||||
final showDebugButton = statusCode != null && statusCode >= 400;
|
||||
final isMinimized = ref.watch(dashBotMinimizedProvider);
|
||||
|
||||
return Container(
|
||||
height: 450,
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: const [
|
||||
BoxShadow(color: Colors.black12, blurRadius: 8, offset: Offset(0, 4))
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
child: isMinimized
|
||||
? _buildMinimizedView(context)
|
||||
: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildHeader(context),
|
||||
const SizedBox(height: 12),
|
||||
_buildQuickActions(showDebugButton),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(child: _buildChatArea(messages)),
|
||||
if (_isLoading) _buildLoadingIndicator(),
|
||||
const SizedBox(height: 10),
|
||||
_buildInputArea(context),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader(BuildContext context) {
|
||||
final isMinimized = ref.watch(dashBotMinimizedProvider);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 0),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
_buildHeader(context),
|
||||
const SizedBox(height: 12),
|
||||
_buildQuickActions(showDebugButton),
|
||||
const SizedBox(height: 12),
|
||||
Expanded(child: _buildChatArea(messages)),
|
||||
if (_isLoading) _buildLoadingIndicator(),
|
||||
const SizedBox(height: 10),
|
||||
_buildInputArea(context),
|
||||
const Text(
|
||||
'DashBot',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
IconButton(
|
||||
padding: const EdgeInsets.all(8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: Icon(
|
||||
isMinimized ? Icons.fullscreen : Icons.remove,
|
||||
size: 20,
|
||||
),
|
||||
tooltip: isMinimized ? 'Maximize' : 'Minimize',
|
||||
onPressed: () {
|
||||
ref.read(dashBotMinimizedProvider.notifier).state =
|
||||
!isMinimized;
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
padding: const EdgeInsets.all(8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.close, size: 20),
|
||||
tooltip: 'Close',
|
||||
onPressed: () {
|
||||
Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
padding: const EdgeInsets.all(8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
icon: const Icon(Icons.delete_sweep, size: 20),
|
||||
tooltip: 'Clear Chat',
|
||||
onPressed: () {
|
||||
ref.read(chatMessagesProvider.notifier).clearMessages();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
Widget _buildMinimizedView(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('DashBot',
|
||||
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.delete_sweep),
|
||||
tooltip: 'Clear Chat',
|
||||
onPressed: () =>
|
||||
ref.read(chatMessagesProvider.notifier).clearMessages(),
|
||||
_buildHeader(context),
|
||||
const SizedBox(height: 8),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: _buildInputArea(context),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildQuickActions(bool showDebugButton) {
|
||||
return Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Explain API"),
|
||||
icon: const Icon(Icons.info_outline),
|
||||
label: const Text("Explain"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
),
|
||||
),
|
||||
if (showDebugButton)
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Debug API"),
|
||||
icon: const Icon(Icons.bug_report_outlined),
|
||||
label: const Text("Debug"),
|
||||
onPressed: () => _sendMessage("Explain API"),
|
||||
icon: const Icon(Icons.info_outline, size: 16),
|
||||
label: const Text("Explain"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
],
|
||||
if (showDebugButton)
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Debug API"),
|
||||
icon: const Icon(Icons.bug_report_outlined, size: 16),
|
||||
label: const Text("Debug"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding:
|
||||
const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Document API"),
|
||||
icon: const Icon(Icons.description_outlined, size: 16),
|
||||
label: const Text("Document"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => _sendMessage("Test API"),
|
||||
icon: const Icon(Icons.science_outlined, size: 16),
|
||||
label: const Text("Test"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildChatArea(List<Map<String, dynamic>> messages) {
|
||||
return ListView.builder(
|
||||
controller: _scrollController,
|
||||
reverse: true,
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final message = messages.reversed.toList()[index];
|
||||
return ChatBubble(
|
||||
message: message['message'],
|
||||
isUser: message['role'] == 'user',
|
||||
);
|
||||
},
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: ListView.builder(
|
||||
controller: _scrollController,
|
||||
reverse: true,
|
||||
itemCount: messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final message = messages.reversed.toList()[index];
|
||||
final isBot = message['role'] == 'bot';
|
||||
final text = message['message'] as String;
|
||||
final showTestButton = message['showTestButton'] == true;
|
||||
final testCases = message['testCases'] as String?;
|
||||
|
||||
if (isBot && showTestButton && testCases != null) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
ChatBubble(message: text, isUser: false),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 12, top: 4, bottom: 4),
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: () => _showTestRunner(testCases),
|
||||
icon: const Icon(Icons.play_arrow, size: 16),
|
||||
label: const Text("Run Test Cases"),
|
||||
style: ElevatedButton.styleFrom(
|
||||
visualDensity: VisualDensity.compact,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return ChatBubble(
|
||||
message: text,
|
||||
isUser: message['role'] == 'user',
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLoadingIndicator() {
|
||||
return const Padding(
|
||||
padding: EdgeInsets.all(8.0),
|
||||
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
child: LinearProgressIndicator(),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInputArea(BuildContext context) {
|
||||
final isMinimized = ref.watch(dashBotMinimizedProvider);
|
||||
return Container(
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
color: Theme.of(context).colorScheme.surfaceContainer,
|
||||
),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
@ -184,14 +309,29 @@ class _DashBotWidgetState extends ConsumerState<DashBotWidget> {
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'Ask DashBot...',
|
||||
border: InputBorder.none,
|
||||
contentPadding: EdgeInsets.symmetric(vertical: 8),
|
||||
),
|
||||
onSubmitted: _sendMessage,
|
||||
onSubmitted: (value) {
|
||||
_sendMessage(value);
|
||||
_controller.clear();
|
||||
if (isMinimized) {
|
||||
ref.read(dashBotMinimizedProvider.notifier).state = false;
|
||||
}
|
||||
},
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.send),
|
||||
onPressed: () => _sendMessage(_controller.text),
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints(),
|
||||
icon: const Icon(Icons.send, size: 20),
|
||||
onPressed: () {
|
||||
_sendMessage(_controller.text);
|
||||
_controller.clear();
|
||||
if (isMinimized) {
|
||||
ref.read(dashBotMinimizedProvider.notifier).state = false;
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
|
328
lib/dashbot/widgets/test_runner_widget.dart
Normal file
328
lib/dashbot/widgets/test_runner_widget.dart
Normal file
@ -0,0 +1,328 @@
|
||||
import 'dart:convert';
|
||||
import 'package:apidash_core/apidash_core.dart' as http;
|
||||
import 'package:apidash_design_system/apidash_design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'content_renderer.dart';
|
||||
|
||||
class TestRunnerWidget extends ConsumerStatefulWidget {
|
||||
final String testCases;
|
||||
|
||||
const TestRunnerWidget({
|
||||
super.key,
|
||||
required this.testCases,
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<TestRunnerWidget> createState() => _TestRunnerWidgetState();
|
||||
}
|
||||
|
||||
class _TestRunnerWidgetState extends ConsumerState<TestRunnerWidget> {
|
||||
List<Map<String, dynamic>> _parsedTests = [];
|
||||
Map<int, Map<String, dynamic>> _results = {};
|
||||
bool _isRunning = false;
|
||||
int _currentTestIndex = -1;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_parseTestCases();
|
||||
}
|
||||
|
||||
void _parseTestCases() {
|
||||
final curlRegex = RegExp(r'```bash\ncurl\s+(.*?)\n```', dotAll: true);
|
||||
final descriptionRegex = RegExp(r'###\s*(.*?)\n', dotAll: true);
|
||||
|
||||
final curlMatches = curlRegex.allMatches(widget.testCases);
|
||||
final descMatches = descriptionRegex.allMatches(widget.testCases);
|
||||
|
||||
List<Map<String, dynamic>> tests = [];
|
||||
int index = 0;
|
||||
|
||||
for (var match in curlMatches) {
|
||||
String? description = "Test case ${index + 1}";
|
||||
if (index < descMatches.length) {
|
||||
description = descMatches.elementAt(index).group(1)?.trim();
|
||||
}
|
||||
|
||||
final curlCommand = match.group(1)?.trim() ?? "";
|
||||
|
||||
tests.add({
|
||||
'description': description,
|
||||
'command': curlCommand,
|
||||
'index': index,
|
||||
});
|
||||
|
||||
index++;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_parsedTests = tests;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _runTest(int index) async {
|
||||
if (_isRunning) return;
|
||||
|
||||
setState(() {
|
||||
_isRunning = true;
|
||||
_currentTestIndex = index;
|
||||
});
|
||||
|
||||
final test = _parsedTests[index];
|
||||
final command = test['command'];
|
||||
|
||||
try {
|
||||
final urlMatch = RegExp(r'"([^"]*)"').firstMatch(command) ??
|
||||
RegExp(r"'([^']*)'").firstMatch(command);
|
||||
final url = urlMatch?.group(1) ?? "";
|
||||
if (url.isEmpty) throw Exception("Could not parse URL from curl command");
|
||||
|
||||
String method = "GET";
|
||||
if (command.contains("-X POST") || command.contains("--request POST")) {
|
||||
method = "POST";
|
||||
} else if (command.contains("-X PUT") ||
|
||||
command.contains("--request PUT")) {
|
||||
method = "PUT";
|
||||
}
|
||||
|
||||
http.Response response;
|
||||
if (method == "GET") {
|
||||
response = await http.get(Uri.parse(url));
|
||||
} else if (method == "POST") {
|
||||
final bodyMatch = RegExp(r'-d\s+"([^"]*)"').firstMatch(command);
|
||||
final body = bodyMatch?.group(1) ?? "";
|
||||
response = await http.post(Uri.parse(url), body: body);
|
||||
} else {
|
||||
throw Exception("Unsupported HTTP method: $method");
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_results[index] = {
|
||||
'status': response.statusCode,
|
||||
'body': response.body,
|
||||
'headers': response.headers,
|
||||
'isSuccess': response.statusCode >= 200 && response.statusCode < 300,
|
||||
};
|
||||
});
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_results[index] = {
|
||||
'error': e.toString(),
|
||||
'isSuccess': false,
|
||||
};
|
||||
});
|
||||
} finally {
|
||||
setState(() {
|
||||
_isRunning = false;
|
||||
_currentTestIndex = -1;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _runAllTests() async {
|
||||
for (int i = 0; i < _parsedTests.length; i++) {
|
||||
if (!mounted) return;
|
||||
await _runTest(i);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('API Test Runner'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.help_outline),
|
||||
tooltip: 'How to use',
|
||||
onPressed: () {
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('API Test Runner'),
|
||||
content: const Text(
|
||||
'Run generated API tests:\n\n'
|
||||
'• "Run All" executes all tests\n'
|
||||
'• "Run" executes a single test\n'
|
||||
'• "Copy" copies the curl command',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: const Text('Close'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: _parsedTests.isEmpty
|
||||
? const Center(child: Text("No test cases found"))
|
||||
: _buildTestList(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_buildActionButtons(),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTestList() {
|
||||
return ListView.builder(
|
||||
itemCount: _parsedTests.length,
|
||||
itemBuilder: (context, index) {
|
||||
final test = _parsedTests[index];
|
||||
final result = _results[index];
|
||||
final bool hasResult = result != null;
|
||||
final bool isSuccess = hasResult && (result['isSuccess'] ?? false);
|
||||
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: ExpansionTile(
|
||||
title: Text(
|
||||
test['description'] ?? "Test case ${index + 1}",
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color:
|
||||
hasResult ? (isSuccess ? Colors.green : Colors.red) : null,
|
||||
),
|
||||
),
|
||||
subtitle: Text('Test ${index + 1} of ${_parsedTests.length}'),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.copy),
|
||||
tooltip: 'Copy command',
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: test['command']));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Command copied')),
|
||||
);
|
||||
},
|
||||
),
|
||||
if (_currentTestIndex == index && _isRunning)
|
||||
const SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
else
|
||||
IconButton(
|
||||
icon: Icon(hasResult
|
||||
? (isSuccess ? Icons.check_circle : Icons.error)
|
||||
: Icons.play_arrow),
|
||||
color: hasResult
|
||||
? (isSuccess ? Colors.green : Colors.red)
|
||||
: null,
|
||||
tooltip: hasResult ? 'Run again' : 'Run test',
|
||||
onPressed: () => _runTest(index),
|
||||
),
|
||||
],
|
||||
),
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Command:',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
margin: const EdgeInsets.only(top: 4, bottom: 16),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
Theme.of(context).colorScheme.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
width: double.infinity,
|
||||
child: SelectableText(
|
||||
test['command'],
|
||||
style: kCodeStyle,
|
||||
),
|
||||
),
|
||||
if (hasResult) ...[
|
||||
const Divider(),
|
||||
Text(
|
||||
'Result:',
|
||||
style: TextStyle(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: isSuccess ? Colors.green : Colors.red,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (result.containsKey('error'))
|
||||
Text(
|
||||
'Error: ${result['error']}',
|
||||
style: const TextStyle(color: Colors.red),
|
||||
)
|
||||
else ...[
|
||||
Text('Status: ${result['status']}'),
|
||||
const SizedBox(height: 8),
|
||||
const Text(
|
||||
'Response:',
|
||||
style: TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
margin: const EdgeInsets.only(top: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.surfaceContainerLow,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
width: double.infinity,
|
||||
child: renderContent(
|
||||
context, _tryFormatJson(result['body'])),
|
||||
),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildActionButtons() {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
onPressed: _isRunning ? null : _runAllTests,
|
||||
icon: const Icon(Icons.play_circle_outline),
|
||||
label: const Text("Run All Tests"),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
String _tryFormatJson(dynamic input) {
|
||||
if (input == null) return "null";
|
||||
if (input is! String) return input.toString();
|
||||
try {
|
||||
final decoded = json.decode(input);
|
||||
return JsonEncoder.withIndent(' ').convert(decoded);
|
||||
} catch (_) {
|
||||
return input;
|
||||
}
|
||||
}
|
||||
}
|
@ -13,6 +13,7 @@ class Importer {
|
||||
.toList(),
|
||||
ImportFormat.postman => PostmanIO().getHttpRequestModelList(content),
|
||||
ImportFormat.insomnia => InsomniaIO().getHttpRequestModelList(content),
|
||||
ImportFormat.har => HarParserIO().getHttpRequestModelList(content),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -11,6 +11,7 @@ void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
var settingsModel = await getSettingsFromSharedPrefs();
|
||||
var onboardingStatus = await getOnboardingStatusFromSharedPrefs();
|
||||
initializeJsRuntime();
|
||||
final initStatus = await initApp(
|
||||
kIsDesktop,
|
||||
settingsModel: settingsModel,
|
||||
|
@ -16,6 +16,8 @@ class HistoryRequestModel with _$HistoryRequestModel {
|
||||
required HistoryMetaModel metaData,
|
||||
required HttpRequestModel httpRequestModel,
|
||||
required HttpResponseModel httpResponseModel,
|
||||
String? preRequestScript,
|
||||
String? postRequestScript,
|
||||
}) = _HistoryRequestModel;
|
||||
|
||||
factory HistoryRequestModel.fromJson(Map<String, Object?> json) =>
|
||||
|
@ -24,6 +24,8 @@ mixin _$HistoryRequestModel {
|
||||
HistoryMetaModel get metaData => throw _privateConstructorUsedError;
|
||||
HttpRequestModel get httpRequestModel => throw _privateConstructorUsedError;
|
||||
HttpResponseModel get httpResponseModel => throw _privateConstructorUsedError;
|
||||
String? get preRequestScript => throw _privateConstructorUsedError;
|
||||
String? get postRequestScript => throw _privateConstructorUsedError;
|
||||
|
||||
/// Serializes this HistoryRequestModel to a JSON map.
|
||||
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
|
||||
@ -45,7 +47,9 @@ abstract class $HistoryRequestModelCopyWith<$Res> {
|
||||
{String historyId,
|
||||
HistoryMetaModel metaData,
|
||||
HttpRequestModel httpRequestModel,
|
||||
HttpResponseModel httpResponseModel});
|
||||
HttpResponseModel httpResponseModel,
|
||||
String? preRequestScript,
|
||||
String? postRequestScript});
|
||||
|
||||
$HistoryMetaModelCopyWith<$Res> get metaData;
|
||||
$HttpRequestModelCopyWith<$Res> get httpRequestModel;
|
||||
@ -71,6 +75,8 @@ class _$HistoryRequestModelCopyWithImpl<$Res, $Val extends HistoryRequestModel>
|
||||
Object? metaData = null,
|
||||
Object? httpRequestModel = null,
|
||||
Object? httpResponseModel = null,
|
||||
Object? preRequestScript = freezed,
|
||||
Object? postRequestScript = freezed,
|
||||
}) {
|
||||
return _then(_value.copyWith(
|
||||
historyId: null == historyId
|
||||
@ -89,6 +95,14 @@ class _$HistoryRequestModelCopyWithImpl<$Res, $Val extends HistoryRequestModel>
|
||||
? _value.httpResponseModel
|
||||
: httpResponseModel // ignore: cast_nullable_to_non_nullable
|
||||
as HttpResponseModel,
|
||||
preRequestScript: freezed == preRequestScript
|
||||
? _value.preRequestScript
|
||||
: preRequestScript // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
postRequestScript: freezed == postRequestScript
|
||||
? _value.postRequestScript
|
||||
: postRequestScript // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
) as $Val);
|
||||
}
|
||||
|
||||
@ -135,7 +149,9 @@ abstract class _$$HistoryRequestModelImplCopyWith<$Res>
|
||||
{String historyId,
|
||||
HistoryMetaModel metaData,
|
||||
HttpRequestModel httpRequestModel,
|
||||
HttpResponseModel httpResponseModel});
|
||||
HttpResponseModel httpResponseModel,
|
||||
String? preRequestScript,
|
||||
String? postRequestScript});
|
||||
|
||||
@override
|
||||
$HistoryMetaModelCopyWith<$Res> get metaData;
|
||||
@ -162,6 +178,8 @@ class __$$HistoryRequestModelImplCopyWithImpl<$Res>
|
||||
Object? metaData = null,
|
||||
Object? httpRequestModel = null,
|
||||
Object? httpResponseModel = null,
|
||||
Object? preRequestScript = freezed,
|
||||
Object? postRequestScript = freezed,
|
||||
}) {
|
||||
return _then(_$HistoryRequestModelImpl(
|
||||
historyId: null == historyId
|
||||
@ -180,6 +198,14 @@ class __$$HistoryRequestModelImplCopyWithImpl<$Res>
|
||||
? _value.httpResponseModel
|
||||
: httpResponseModel // ignore: cast_nullable_to_non_nullable
|
||||
as HttpResponseModel,
|
||||
preRequestScript: freezed == preRequestScript
|
||||
? _value.preRequestScript
|
||||
: preRequestScript // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
postRequestScript: freezed == postRequestScript
|
||||
? _value.postRequestScript
|
||||
: postRequestScript // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -192,7 +218,9 @@ class _$HistoryRequestModelImpl implements _HistoryRequestModel {
|
||||
{required this.historyId,
|
||||
required this.metaData,
|
||||
required this.httpRequestModel,
|
||||
required this.httpResponseModel});
|
||||
required this.httpResponseModel,
|
||||
this.preRequestScript,
|
||||
this.postRequestScript});
|
||||
|
||||
factory _$HistoryRequestModelImpl.fromJson(Map<String, dynamic> json) =>
|
||||
_$$HistoryRequestModelImplFromJson(json);
|
||||
@ -205,10 +233,14 @@ class _$HistoryRequestModelImpl implements _HistoryRequestModel {
|
||||
final HttpRequestModel httpRequestModel;
|
||||
@override
|
||||
final HttpResponseModel httpResponseModel;
|
||||
@override
|
||||
final String? preRequestScript;
|
||||
@override
|
||||
final String? postRequestScript;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'HistoryRequestModel(historyId: $historyId, metaData: $metaData, httpRequestModel: $httpRequestModel, httpResponseModel: $httpResponseModel)';
|
||||
return 'HistoryRequestModel(historyId: $historyId, metaData: $metaData, httpRequestModel: $httpRequestModel, httpResponseModel: $httpResponseModel, preRequestScript: $preRequestScript, postRequestScript: $postRequestScript)';
|
||||
}
|
||||
|
||||
@override
|
||||
@ -223,13 +255,17 @@ class _$HistoryRequestModelImpl implements _HistoryRequestModel {
|
||||
(identical(other.httpRequestModel, httpRequestModel) ||
|
||||
other.httpRequestModel == httpRequestModel) &&
|
||||
(identical(other.httpResponseModel, httpResponseModel) ||
|
||||
other.httpResponseModel == httpResponseModel));
|
||||
other.httpResponseModel == httpResponseModel) &&
|
||||
(identical(other.preRequestScript, preRequestScript) ||
|
||||
other.preRequestScript == preRequestScript) &&
|
||||
(identical(other.postRequestScript, postRequestScript) ||
|
||||
other.postRequestScript == postRequestScript));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
runtimeType, historyId, metaData, httpRequestModel, httpResponseModel);
|
||||
int get hashCode => Object.hash(runtimeType, historyId, metaData,
|
||||
httpRequestModel, httpResponseModel, preRequestScript, postRequestScript);
|
||||
|
||||
/// Create a copy of HistoryRequestModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@ -250,11 +286,12 @@ class _$HistoryRequestModelImpl implements _HistoryRequestModel {
|
||||
|
||||
abstract class _HistoryRequestModel implements HistoryRequestModel {
|
||||
const factory _HistoryRequestModel(
|
||||
{required final String historyId,
|
||||
required final HistoryMetaModel metaData,
|
||||
required final HttpRequestModel httpRequestModel,
|
||||
required final HttpResponseModel httpResponseModel}) =
|
||||
_$HistoryRequestModelImpl;
|
||||
{required final String historyId,
|
||||
required final HistoryMetaModel metaData,
|
||||
required final HttpRequestModel httpRequestModel,
|
||||
required final HttpResponseModel httpResponseModel,
|
||||
final String? preRequestScript,
|
||||
final String? postRequestScript}) = _$HistoryRequestModelImpl;
|
||||
|
||||
factory _HistoryRequestModel.fromJson(Map<String, dynamic> json) =
|
||||
_$HistoryRequestModelImpl.fromJson;
|
||||
@ -267,6 +304,10 @@ abstract class _HistoryRequestModel implements HistoryRequestModel {
|
||||
HttpRequestModel get httpRequestModel;
|
||||
@override
|
||||
HttpResponseModel get httpResponseModel;
|
||||
@override
|
||||
String? get preRequestScript;
|
||||
@override
|
||||
String? get postRequestScript;
|
||||
|
||||
/// Create a copy of HistoryRequestModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
|
@ -15,6 +15,8 @@ _$HistoryRequestModelImpl _$$HistoryRequestModelImplFromJson(Map json) =>
|
||||
Map<String, Object?>.from(json['httpRequestModel'] as Map)),
|
||||
httpResponseModel: HttpResponseModel.fromJson(
|
||||
Map<String, Object?>.from(json['httpResponseModel'] as Map)),
|
||||
preRequestScript: json['preRequestScript'] as String?,
|
||||
postRequestScript: json['postRequestScript'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$HistoryRequestModelImplToJson(
|
||||
@ -24,4 +26,6 @@ Map<String, dynamic> _$$HistoryRequestModelImplToJson(
|
||||
'metaData': instance.metaData.toJson(),
|
||||
'httpRequestModel': instance.httpRequestModel.toJson(),
|
||||
'httpResponseModel': instance.httpResponseModel.toJson(),
|
||||
'preRequestScript': instance.preRequestScript,
|
||||
'postRequestScript': instance.postRequestScript,
|
||||
};
|
||||
|
@ -22,6 +22,8 @@ class RequestModel with _$RequestModel {
|
||||
HttpResponseModel? httpResponseModel,
|
||||
@JsonKey(includeToJson: false) @Default(false) bool isWorking,
|
||||
@JsonKey(includeToJson: false) DateTime? sendingTime,
|
||||
String? preRequestScript,
|
||||
String? postRequestScript,
|
||||
}) = _RequestModel;
|
||||
|
||||
factory RequestModel.fromJson(Map<String, Object?> json) =>
|
||||
|
@ -35,6 +35,8 @@ mixin _$RequestModel {
|
||||
bool get isWorking => throw _privateConstructorUsedError;
|
||||
@JsonKey(includeToJson: false)
|
||||
DateTime? get sendingTime => throw _privateConstructorUsedError;
|
||||
String? get preRequestScript => throw _privateConstructorUsedError;
|
||||
String? get postRequestScript => throw _privateConstructorUsedError;
|
||||
|
||||
/// Serializes this RequestModel to a JSON map.
|
||||
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
|
||||
@ -63,7 +65,9 @@ abstract class $RequestModelCopyWith<$Res> {
|
||||
String? message,
|
||||
HttpResponseModel? httpResponseModel,
|
||||
@JsonKey(includeToJson: false) bool isWorking,
|
||||
@JsonKey(includeToJson: false) DateTime? sendingTime});
|
||||
@JsonKey(includeToJson: false) DateTime? sendingTime,
|
||||
String? preRequestScript,
|
||||
String? postRequestScript});
|
||||
|
||||
$HttpRequestModelCopyWith<$Res>? get httpRequestModel;
|
||||
$HttpResponseModelCopyWith<$Res>? get httpResponseModel;
|
||||
@ -95,6 +99,8 @@ class _$RequestModelCopyWithImpl<$Res, $Val extends RequestModel>
|
||||
Object? httpResponseModel = freezed,
|
||||
Object? isWorking = null,
|
||||
Object? sendingTime = freezed,
|
||||
Object? preRequestScript = freezed,
|
||||
Object? postRequestScript = freezed,
|
||||
}) {
|
||||
return _then(_value.copyWith(
|
||||
id: null == id
|
||||
@ -141,6 +147,14 @@ class _$RequestModelCopyWithImpl<$Res, $Val extends RequestModel>
|
||||
? _value.sendingTime
|
||||
: sendingTime // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime?,
|
||||
preRequestScript: freezed == preRequestScript
|
||||
? _value.preRequestScript
|
||||
: preRequestScript // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
postRequestScript: freezed == postRequestScript
|
||||
? _value.postRequestScript
|
||||
: postRequestScript // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
) as $Val);
|
||||
}
|
||||
|
||||
@ -192,7 +206,9 @@ abstract class _$$RequestModelImplCopyWith<$Res>
|
||||
String? message,
|
||||
HttpResponseModel? httpResponseModel,
|
||||
@JsonKey(includeToJson: false) bool isWorking,
|
||||
@JsonKey(includeToJson: false) DateTime? sendingTime});
|
||||
@JsonKey(includeToJson: false) DateTime? sendingTime,
|
||||
String? preRequestScript,
|
||||
String? postRequestScript});
|
||||
|
||||
@override
|
||||
$HttpRequestModelCopyWith<$Res>? get httpRequestModel;
|
||||
@ -224,6 +240,8 @@ class __$$RequestModelImplCopyWithImpl<$Res>
|
||||
Object? httpResponseModel = freezed,
|
||||
Object? isWorking = null,
|
||||
Object? sendingTime = freezed,
|
||||
Object? preRequestScript = freezed,
|
||||
Object? postRequestScript = freezed,
|
||||
}) {
|
||||
return _then(_$RequestModelImpl(
|
||||
id: null == id
|
||||
@ -269,6 +287,14 @@ class __$$RequestModelImplCopyWithImpl<$Res>
|
||||
? _value.sendingTime
|
||||
: sendingTime // ignore: cast_nullable_to_non_nullable
|
||||
as DateTime?,
|
||||
preRequestScript: freezed == preRequestScript
|
||||
? _value.preRequestScript
|
||||
: preRequestScript // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
postRequestScript: freezed == postRequestScript
|
||||
? _value.postRequestScript
|
||||
: postRequestScript // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
));
|
||||
}
|
||||
}
|
||||
@ -288,7 +314,9 @@ class _$RequestModelImpl implements _RequestModel {
|
||||
this.message,
|
||||
this.httpResponseModel,
|
||||
@JsonKey(includeToJson: false) this.isWorking = false,
|
||||
@JsonKey(includeToJson: false) this.sendingTime});
|
||||
@JsonKey(includeToJson: false) this.sendingTime,
|
||||
this.preRequestScript,
|
||||
this.postRequestScript});
|
||||
|
||||
factory _$RequestModelImpl.fromJson(Map<String, dynamic> json) =>
|
||||
_$$RequestModelImplFromJson(json);
|
||||
@ -321,10 +349,14 @@ class _$RequestModelImpl implements _RequestModel {
|
||||
@override
|
||||
@JsonKey(includeToJson: false)
|
||||
final DateTime? sendingTime;
|
||||
@override
|
||||
final String? preRequestScript;
|
||||
@override
|
||||
final String? postRequestScript;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'RequestModel(id: $id, apiType: $apiType, name: $name, description: $description, requestTabIndex: $requestTabIndex, httpRequestModel: $httpRequestModel, responseStatus: $responseStatus, message: $message, httpResponseModel: $httpResponseModel, isWorking: $isWorking, sendingTime: $sendingTime)';
|
||||
return 'RequestModel(id: $id, apiType: $apiType, name: $name, description: $description, requestTabIndex: $requestTabIndex, httpRequestModel: $httpRequestModel, responseStatus: $responseStatus, message: $message, httpResponseModel: $httpResponseModel, isWorking: $isWorking, sendingTime: $sendingTime, preRequestScript: $preRequestScript, postRequestScript: $postRequestScript)';
|
||||
}
|
||||
|
||||
@override
|
||||
@ -349,7 +381,11 @@ class _$RequestModelImpl implements _RequestModel {
|
||||
(identical(other.isWorking, isWorking) ||
|
||||
other.isWorking == isWorking) &&
|
||||
(identical(other.sendingTime, sendingTime) ||
|
||||
other.sendingTime == sendingTime));
|
||||
other.sendingTime == sendingTime) &&
|
||||
(identical(other.preRequestScript, preRequestScript) ||
|
||||
other.preRequestScript == preRequestScript) &&
|
||||
(identical(other.postRequestScript, postRequestScript) ||
|
||||
other.postRequestScript == postRequestScript));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@ -366,7 +402,9 @@ class _$RequestModelImpl implements _RequestModel {
|
||||
message,
|
||||
httpResponseModel,
|
||||
isWorking,
|
||||
sendingTime);
|
||||
sendingTime,
|
||||
preRequestScript,
|
||||
postRequestScript);
|
||||
|
||||
/// Create a copy of RequestModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@ -386,18 +424,19 @@ class _$RequestModelImpl implements _RequestModel {
|
||||
|
||||
abstract class _RequestModel implements RequestModel {
|
||||
const factory _RequestModel(
|
||||
{required final String id,
|
||||
final APIType apiType,
|
||||
final String name,
|
||||
final String description,
|
||||
@JsonKey(includeToJson: false) final dynamic requestTabIndex,
|
||||
final HttpRequestModel? httpRequestModel,
|
||||
final int? responseStatus,
|
||||
final String? message,
|
||||
final HttpResponseModel? httpResponseModel,
|
||||
@JsonKey(includeToJson: false) final bool isWorking,
|
||||
@JsonKey(includeToJson: false) final DateTime? sendingTime}) =
|
||||
_$RequestModelImpl;
|
||||
{required final String id,
|
||||
final APIType apiType,
|
||||
final String name,
|
||||
final String description,
|
||||
@JsonKey(includeToJson: false) final dynamic requestTabIndex,
|
||||
final HttpRequestModel? httpRequestModel,
|
||||
final int? responseStatus,
|
||||
final String? message,
|
||||
final HttpResponseModel? httpResponseModel,
|
||||
@JsonKey(includeToJson: false) final bool isWorking,
|
||||
@JsonKey(includeToJson: false) final DateTime? sendingTime,
|
||||
final String? preRequestScript,
|
||||
final String? postRequestScript}) = _$RequestModelImpl;
|
||||
|
||||
factory _RequestModel.fromJson(Map<String, dynamic> json) =
|
||||
_$RequestModelImpl.fromJson;
|
||||
@ -427,6 +466,10 @@ abstract class _RequestModel implements RequestModel {
|
||||
@override
|
||||
@JsonKey(includeToJson: false)
|
||||
DateTime? get sendingTime;
|
||||
@override
|
||||
String? get preRequestScript;
|
||||
@override
|
||||
String? get postRequestScript;
|
||||
|
||||
/// Create a copy of RequestModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
|
@ -27,6 +27,8 @@ _$RequestModelImpl _$$RequestModelImplFromJson(Map json) => _$RequestModelImpl(
|
||||
sendingTime: json['sendingTime'] == null
|
||||
? null
|
||||
: DateTime.parse(json['sendingTime'] as String),
|
||||
preRequestScript: json['preRequestScript'] as String?,
|
||||
postRequestScript: json['postRequestScript'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$RequestModelImplToJson(_$RequestModelImpl instance) =>
|
||||
@ -39,6 +41,8 @@ Map<String, dynamic> _$$RequestModelImplToJson(_$RequestModelImpl instance) =>
|
||||
'responseStatus': instance.responseStatus,
|
||||
'message': instance.message,
|
||||
'httpResponseModel': instance.httpResponseModel?.toJson(),
|
||||
'preRequestScript': instance.preRequestScript,
|
||||
'postRequestScript': instance.postRequestScript,
|
||||
};
|
||||
|
||||
const _$APITypeEnumMap = {
|
||||
|
@ -4,9 +4,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:apidash/consts.dart';
|
||||
import 'providers.dart';
|
||||
import '../models/models.dart';
|
||||
import '../services/services.dart' show hiveHandler, HiveHandler;
|
||||
import '../utils/utils.dart'
|
||||
show getNewUuid, collectionToHAR, substituteHttpRequestModel;
|
||||
import '../services/services.dart';
|
||||
import '../utils/utils.dart';
|
||||
|
||||
final selectedIdStateProvider = StateProvider<String?>((ref) => null);
|
||||
|
||||
@ -223,6 +222,8 @@ class CollectionStateNotifier
|
||||
int? responseStatus,
|
||||
String? message,
|
||||
HttpResponseModel? httpResponseModel,
|
||||
String? preRequestScript,
|
||||
String? postRequestScript,
|
||||
}) {
|
||||
final rId = id ?? ref.read(selectedIdStateProvider);
|
||||
if (rId == null) {
|
||||
@ -254,6 +255,8 @@ class CollectionStateNotifier
|
||||
responseStatus: responseStatus ?? currentModel.responseStatus,
|
||||
message: message ?? currentModel.message,
|
||||
httpResponseModel: httpResponseModel ?? currentModel.httpResponseModel,
|
||||
preRequestScript: preRequestScript ?? currentModel.preRequestScript,
|
||||
postRequestScript: postRequestScript ?? currentModel.postRequestScript,
|
||||
);
|
||||
|
||||
var map = {...state!};
|
||||
@ -266,6 +269,8 @@ class CollectionStateNotifier
|
||||
final requestId = ref.read(selectedIdStateProvider);
|
||||
ref.read(codePaneVisibleStateProvider.notifier).state = false;
|
||||
final defaultUriScheme = ref.read(settingsProvider).defaultUriScheme;
|
||||
final EnvironmentModel? originalEnvironmentModel =
|
||||
ref.read(selectedEnvironmentModelProvider);
|
||||
|
||||
if (requestId == null || state == null) {
|
||||
return;
|
||||
@ -276,6 +281,23 @@ class CollectionStateNotifier
|
||||
return;
|
||||
}
|
||||
|
||||
if (requestModel != null &&
|
||||
!requestModel.preRequestScript.isNullOrEmpty()) {
|
||||
requestModel = await handlePreRequestScript(
|
||||
requestModel,
|
||||
originalEnvironmentModel,
|
||||
(envModel, updatedValues) {
|
||||
ref
|
||||
.read(environmentsStateNotifierProvider.notifier)
|
||||
.updateEnvironment(
|
||||
envModel.id,
|
||||
name: envModel.name,
|
||||
values: updatedValues,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
APIType apiType = requestModel!.apiType;
|
||||
HttpRequestModel substitutedHttpRequestModel =
|
||||
getSubstitutedHttpRequestModel(requestModel.httpRequestModel!);
|
||||
@ -297,7 +319,7 @@ class CollectionStateNotifier
|
||||
noSSL: noSSL,
|
||||
);
|
||||
|
||||
late final RequestModel newRequestModel;
|
||||
late RequestModel newRequestModel;
|
||||
if (responseRec.$1 == null) {
|
||||
newRequestModel = requestModel.copyWith(
|
||||
responseStatus: -1,
|
||||
@ -331,7 +353,25 @@ class CollectionStateNotifier
|
||||
),
|
||||
httpRequestModel: substitutedHttpRequestModel,
|
||||
httpResponseModel: httpResponseModel,
|
||||
preRequestScript: requestModel.preRequestScript,
|
||||
postRequestScript: requestModel.postRequestScript,
|
||||
);
|
||||
|
||||
if (!requestModel.postRequestScript.isNullOrEmpty()) {
|
||||
newRequestModel = await handlePostResponseScript(
|
||||
newRequestModel,
|
||||
originalEnvironmentModel,
|
||||
(envModel, updatedValues) {
|
||||
ref
|
||||
.read(environmentsStateNotifierProvider.notifier)
|
||||
.updateEnvironment(
|
||||
envModel.id,
|
||||
name: envModel.name,
|
||||
values: updatedValues,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
ref.read(historyMetaStateNotifier.notifier).addHistoryRequest(model);
|
||||
}
|
||||
|
||||
|
@ -17,7 +17,8 @@ class Dashboard extends ConsumerWidget {
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final railIdx = ref.watch(navRailIndexStateProvider);
|
||||
final settings = ref.watch(settingsProvider);
|
||||
final isDashBotEnabled =
|
||||
ref.watch(settingsProvider.select((value) => value.isDashBotEnabled));
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: Row(
|
||||
@ -126,7 +127,7 @@ class Dashboard extends ConsumerWidget {
|
||||
],
|
||||
),
|
||||
),
|
||||
floatingActionButton: settings.isDashBotEnabled
|
||||
floatingActionButton: isDashBotEnabled
|
||||
? FloatingActionButton(
|
||||
onPressed: () => showModalBottomSheet(
|
||||
context: context,
|
||||
|
@ -5,6 +5,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:apidash/providers/providers.dart';
|
||||
import 'package:apidash/widgets/widgets.dart';
|
||||
import 'package:apidash/consts.dart';
|
||||
import 'his_scripts_tab.dart';
|
||||
|
||||
class HistoryRequestPane extends ConsumerWidget {
|
||||
const HistoryRequestPane({
|
||||
@ -38,6 +39,12 @@ class HistoryRequestPane extends ConsumerWidget {
|
||||
.select((value) => value?.httpRequestModel.hasQuery)) ??
|
||||
false;
|
||||
|
||||
final scriptsLength = ref.watch(selectedHistoryRequestModelProvider
|
||||
.select((value) => value?.preRequestScript?.length)) ??
|
||||
ref.watch(selectedHistoryRequestModelProvider
|
||||
.select((value) => value?.postRequestScript?.length)) ??
|
||||
0;
|
||||
|
||||
return switch (apiType) {
|
||||
APIType.rest => RequestPane(
|
||||
key: const Key("history-request-pane-rest"),
|
||||
@ -52,11 +59,13 @@ class HistoryRequestPane extends ConsumerWidget {
|
||||
paramLength > 0,
|
||||
headerLength > 0,
|
||||
hasBody,
|
||||
scriptsLength > 0
|
||||
],
|
||||
tabLabels: const [
|
||||
kLabelURLParams,
|
||||
kLabelHeaders,
|
||||
kLabelBody,
|
||||
kLabelScripts,
|
||||
],
|
||||
children: [
|
||||
RequestDataTable(
|
||||
@ -68,6 +77,7 @@ class HistoryRequestPane extends ConsumerWidget {
|
||||
keyName: kNameHeader,
|
||||
),
|
||||
const HisRequestBody(),
|
||||
const HistoryScriptsTab(),
|
||||
],
|
||||
),
|
||||
APIType.graphql => RequestPane(
|
||||
@ -79,13 +89,11 @@ class HistoryRequestPane extends ConsumerWidget {
|
||||
!codePaneVisible;
|
||||
},
|
||||
showViewCodeButton: !isCompact,
|
||||
showIndicators: [
|
||||
headerLength > 0,
|
||||
hasQuery,
|
||||
],
|
||||
showIndicators: [headerLength > 0, hasQuery, scriptsLength > 0],
|
||||
tabLabels: const [
|
||||
kLabelHeaders,
|
||||
kLabelQuery,
|
||||
kLabelScripts,
|
||||
],
|
||||
children: [
|
||||
RequestDataTable(
|
||||
@ -93,6 +101,7 @@ class HistoryRequestPane extends ConsumerWidget {
|
||||
keyName: kNameHeader,
|
||||
),
|
||||
const HisRequestBody(),
|
||||
const HistoryScriptsTab(),
|
||||
],
|
||||
),
|
||||
_ => kSizedBoxEmpty,
|
||||
|
83
lib/screens/history/history_widgets/his_scripts_tab.dart
Normal file
83
lib/screens/history/history_widgets/his_scripts_tab.dart
Normal file
@ -0,0 +1,83 @@
|
||||
import 'package:apidash_design_system/apidash_design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_code_editor/flutter_code_editor.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:highlight/languages/javascript.dart';
|
||||
import 'package:apidash/providers/providers.dart';
|
||||
import 'package:apidash/widgets/widgets.dart';
|
||||
|
||||
class HistoryScriptsTab extends ConsumerStatefulWidget {
|
||||
const HistoryScriptsTab({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<HistoryScriptsTab> createState() => _ScriptsCodePaneState();
|
||||
}
|
||||
|
||||
class _ScriptsCodePaneState extends ConsumerState<HistoryScriptsTab> {
|
||||
int _selectedTabIndex = 0;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hisRequestModel = ref.read(selectedHistoryRequestModelProvider);
|
||||
final isDarkMode =
|
||||
ref.watch(settingsProvider.select((value) => value.isDark));
|
||||
final preReqCodeController = CodeController(
|
||||
text: hisRequestModel?.preRequestScript,
|
||||
language: javascript,
|
||||
);
|
||||
|
||||
final postResCodeController = CodeController(
|
||||
text: hisRequestModel?.postRequestScript,
|
||||
language: javascript,
|
||||
);
|
||||
|
||||
preReqCodeController.addListener(() {
|
||||
ref.read(collectionStateNotifierProvider.notifier).update(
|
||||
preRequestScript: preReqCodeController.text,
|
||||
);
|
||||
});
|
||||
|
||||
postResCodeController.addListener(() {
|
||||
ref.read(collectionStateNotifierProvider.notifier).update(
|
||||
postRequestScript: postResCodeController.text,
|
||||
);
|
||||
});
|
||||
|
||||
final tabs = [(0, "Pre Request"), (1, "Post Response")];
|
||||
final content = [
|
||||
CodeEditor(
|
||||
controller: preReqCodeController,
|
||||
readOnly: true,
|
||||
isDark: isDarkMode,
|
||||
),
|
||||
CodeEditor(
|
||||
controller: postResCodeController,
|
||||
readOnly: true,
|
||||
isDark: isDarkMode,
|
||||
),
|
||||
];
|
||||
|
||||
return Column(
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: ADDropdownButton<int>(
|
||||
value: _selectedTabIndex,
|
||||
values: tabs,
|
||||
onChanged: (int? newValue) {
|
||||
if (newValue != null) {
|
||||
setState(() {
|
||||
_selectedTabIndex = newValue;
|
||||
});
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: content[_selectedTabIndex],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
@ -5,6 +5,7 @@ import 'package:apidash/providers/providers.dart';
|
||||
import 'package:apidash/widgets/widgets.dart';
|
||||
import 'request_headers.dart';
|
||||
import 'request_body.dart';
|
||||
import 'request_scripts.dart';
|
||||
|
||||
class EditGraphQLRequestPane extends ConsumerWidget {
|
||||
const EditGraphQLRequestPane({super.key});
|
||||
@ -21,7 +22,14 @@ class EditGraphQLRequestPane extends ConsumerWidget {
|
||||
final hasQuery = ref.watch(selectedRequestModelProvider
|
||||
.select((value) => value?.httpRequestModel?.hasQuery)) ??
|
||||
false;
|
||||
if (tabIndex >= 2) {
|
||||
|
||||
final scriptsLength = ref.watch(selectedRequestModelProvider
|
||||
.select((value) => value?.preRequestScript?.length)) ??
|
||||
ref.watch(selectedRequestModelProvider
|
||||
.select((value) => value?.postRequestScript?.length)) ??
|
||||
0;
|
||||
|
||||
if (tabIndex >= 3) {
|
||||
tabIndex = 0;
|
||||
}
|
||||
return RequestPane(
|
||||
@ -40,14 +48,17 @@ class EditGraphQLRequestPane extends ConsumerWidget {
|
||||
showIndicators: [
|
||||
headerLength > 0,
|
||||
hasQuery,
|
||||
scriptsLength > 0,
|
||||
],
|
||||
tabLabels: const [
|
||||
kLabelHeaders,
|
||||
kLabelQuery,
|
||||
kLabelScripts,
|
||||
],
|
||||
children: const [
|
||||
EditRequestHeaders(),
|
||||
EditRequestBody(),
|
||||
EditRequestScripts(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
@ -6,6 +6,7 @@ import 'package:apidash/widgets/widgets.dart';
|
||||
import 'request_headers.dart';
|
||||
import 'request_params.dart';
|
||||
import 'request_body.dart';
|
||||
import 'request_scripts.dart';
|
||||
|
||||
class EditRestRequestPane extends ConsumerWidget {
|
||||
const EditRestRequestPane({super.key});
|
||||
@ -27,6 +28,12 @@ class EditRestRequestPane extends ConsumerWidget {
|
||||
.select((value) => value?.httpRequestModel?.hasBody)) ??
|
||||
false;
|
||||
|
||||
final scriptsLength = ref.watch(selectedRequestModelProvider
|
||||
.select((value) => value?.preRequestScript?.length)) ??
|
||||
ref.watch(selectedRequestModelProvider
|
||||
.select((value) => value?.postRequestScript?.length)) ??
|
||||
0;
|
||||
|
||||
return RequestPane(
|
||||
selectedId: selectedId,
|
||||
codePaneVisible: codePaneVisible,
|
||||
@ -44,16 +51,19 @@ class EditRestRequestPane extends ConsumerWidget {
|
||||
paramLength > 0,
|
||||
headerLength > 0,
|
||||
hasBody,
|
||||
scriptsLength > 0,
|
||||
],
|
||||
tabLabels: const [
|
||||
kLabelURLParams,
|
||||
kLabelHeaders,
|
||||
kLabelBody,
|
||||
kLabelScripts,
|
||||
],
|
||||
children: const [
|
||||
EditRequestURLParams(),
|
||||
EditRequestHeaders(),
|
||||
EditRequestBody(),
|
||||
EditRequestScripts(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
@ -0,0 +1,94 @@
|
||||
import 'package:apidash_design_system/apidash_design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_code_editor/flutter_code_editor.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:highlight/languages/javascript.dart';
|
||||
import 'package:apidash/providers/providers.dart';
|
||||
import 'package:apidash/widgets/widgets.dart';
|
||||
import 'package:apidash/consts.dart';
|
||||
|
||||
class EditRequestScripts extends ConsumerStatefulWidget {
|
||||
const EditRequestScripts({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<EditRequestScripts> createState() => _EditRequestScriptsState();
|
||||
}
|
||||
|
||||
class _EditRequestScriptsState extends ConsumerState<EditRequestScripts> {
|
||||
int _selectedTabIndex = 0;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final requestModel = ref.read(selectedRequestModelProvider);
|
||||
final isDarkMode =
|
||||
ref.watch(settingsProvider.select((value) => value.isDark));
|
||||
final preReqCodeController = CodeController(
|
||||
text: requestModel?.preRequestScript,
|
||||
language: javascript,
|
||||
);
|
||||
|
||||
final postResCodeController = CodeController(
|
||||
text: requestModel?.postRequestScript,
|
||||
language: javascript,
|
||||
);
|
||||
|
||||
preReqCodeController.addListener(() {
|
||||
ref.read(collectionStateNotifierProvider.notifier).update(
|
||||
preRequestScript: preReqCodeController.text,
|
||||
);
|
||||
});
|
||||
|
||||
postResCodeController.addListener(() {
|
||||
ref.read(collectionStateNotifierProvider.notifier).update(
|
||||
postRequestScript: postResCodeController.text,
|
||||
);
|
||||
});
|
||||
|
||||
final tabs = [(0, "Pre Request"), (1, "Post Response")];
|
||||
final content = [
|
||||
CodeEditor(
|
||||
controller: preReqCodeController,
|
||||
isDark: isDarkMode,
|
||||
),
|
||||
CodeEditor(
|
||||
controller: postResCodeController,
|
||||
isDark: isDarkMode,
|
||||
),
|
||||
];
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
Padding(
|
||||
padding: kPh8b6,
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
ADDropdownButton<int>(
|
||||
isDense: true,
|
||||
iconSize: kButtonIconSizeMedium,
|
||||
value: _selectedTabIndex,
|
||||
values: tabs,
|
||||
onChanged: (int? newValue) {
|
||||
if (newValue != null) {
|
||||
setState(() {
|
||||
_selectedTabIndex = newValue;
|
||||
});
|
||||
}
|
||||
},
|
||||
),
|
||||
LearnButton(
|
||||
url: kLearnScriptingUrl,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: kPt5o10,
|
||||
child: content[_selectedTabIndex],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
275
lib/services/flutter_js_service.dart
Normal file
275
lib/services/flutter_js_service.dart
Normal file
@ -0,0 +1,275 @@
|
||||
// ignore_for_file: avoid_print
|
||||
|
||||
import 'dart:convert';
|
||||
import 'dart:developer';
|
||||
import 'package:apidash_core/apidash_core.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_js/flutter_js.dart';
|
||||
import '../models/models.dart';
|
||||
import '../utils/utils.dart';
|
||||
|
||||
late JavascriptRuntime jsRuntime;
|
||||
|
||||
void initializeJsRuntime() {
|
||||
jsRuntime = getJavascriptRuntime();
|
||||
setupJsBridge();
|
||||
}
|
||||
|
||||
void disposeJsRuntime() {
|
||||
jsRuntime.dispose();
|
||||
}
|
||||
|
||||
void evaluate(String code) {
|
||||
try {
|
||||
JsEvalResult jsResult = jsRuntime.evaluate(code);
|
||||
log(jsResult.stringResult);
|
||||
} on PlatformException catch (e) {
|
||||
log('ERROR: ${e.details}');
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: These log statements can be printed in a custom api dash terminal.
|
||||
void setupJsBridge() {
|
||||
jsRuntime.onMessage('consoleLog', (args) {
|
||||
try {
|
||||
if (args is List) {
|
||||
print('[JS LOG]: ${args.map((e) => e.toString()).join(' ')}');
|
||||
} else {
|
||||
print('[JS LOG]: $args');
|
||||
}
|
||||
} catch (e) {
|
||||
print('[JS LOG ERROR]: $args, Error: $e');
|
||||
}
|
||||
});
|
||||
|
||||
jsRuntime.onMessage('consoleWarn', (args) {
|
||||
try {
|
||||
if (args is List) {
|
||||
print('[JS WARN]: ${args.map((e) => e.toString()).join(' ')}');
|
||||
} else {
|
||||
print('[JS WARN]: $args');
|
||||
}
|
||||
} catch (e) {
|
||||
print('[JS WARN ERROR]: $args, Error: $e');
|
||||
}
|
||||
});
|
||||
|
||||
jsRuntime.onMessage('consoleError', (args) {
|
||||
try {
|
||||
if (args is List) {
|
||||
print('[JS ERROR]: ${args.map((e) => e.toString()).join(' ')}');
|
||||
} else {
|
||||
print('[JS ERROR]: $args');
|
||||
}
|
||||
} catch (e) {
|
||||
print('[JS ERROR ERROR]: $args, Error: $e');
|
||||
}
|
||||
});
|
||||
|
||||
jsRuntime.onMessage('fatalError', (args) {
|
||||
try {
|
||||
// 'fatalError' message is constructed as a JSON object in setupScript
|
||||
if (args is Map<String, dynamic>) {
|
||||
print('[JS FATAL ERROR]: ${args['message']}');
|
||||
if (args['error'] != null) print(' Error: ${args['error']}');
|
||||
if (args['stack'] != null) print(' Stack: ${args['stack']}');
|
||||
} else {
|
||||
print('[JS FATAL ERROR decoding error]: $args, Expected a Map.');
|
||||
}
|
||||
} catch (e) {
|
||||
print('[JS FATAL ERROR decoding error]: $args, Error: $e');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<
|
||||
({
|
||||
HttpRequestModel updatedRequest,
|
||||
Map<String, dynamic> updatedEnvironment
|
||||
})> executePreRequestScript({
|
||||
required RequestModel currentRequestModel,
|
||||
required Map<String, dynamic> activeEnvironment,
|
||||
}) async {
|
||||
if ((currentRequestModel.preRequestScript ?? "").trim().isEmpty) {
|
||||
// No script, return original data
|
||||
// return (
|
||||
// updatedRequest: currentRequestModel.httpRequestModel,
|
||||
// updatedEnvironment: activeEnvironment
|
||||
// );
|
||||
}
|
||||
|
||||
final httpRequest = currentRequestModel.httpRequestModel;
|
||||
final userScript = currentRequestModel.preRequestScript;
|
||||
|
||||
// Prepare Data
|
||||
final requestJson = jsonEncode(httpRequest?.toJson());
|
||||
final environmentJson = jsonEncode(activeEnvironment);
|
||||
|
||||
// Inject data as JS variables
|
||||
// Escape strings properly if embedding directly
|
||||
final dataInjection = """
|
||||
var injectedRequestJson = ${jsEscapeString(requestJson)};
|
||||
var injectedEnvironmentJson = ${jsEscapeString(environmentJson)};
|
||||
var injectedResponseJson = null; // Not needed for pre-request
|
||||
""";
|
||||
|
||||
// Concatenate & Add Return
|
||||
final fullScript = """
|
||||
(function() {
|
||||
// --- Data Injection (now constants within the IIFE scope) ---
|
||||
$dataInjection
|
||||
|
||||
// --- Setup Script (will declare variables within the IIFE scope) ---
|
||||
$kJSSetupScript
|
||||
|
||||
// --- User Script (will execute within the IIFE scope)---
|
||||
$userScript
|
||||
|
||||
// --- Return Result (accesses variables from the IIFE scope) ---
|
||||
// Ensure 'request' and 'environment' are accessible here
|
||||
return JSON.stringify({ request: request, environment: environment });
|
||||
})(); // Immediately invoke the function
|
||||
""";
|
||||
|
||||
// TODO: Do something better to avoid null check here.
|
||||
HttpRequestModel resultingRequest = httpRequest!;
|
||||
Map<String, dynamic> resultingEnvironment = Map.from(activeEnvironment);
|
||||
|
||||
try {
|
||||
// Execute
|
||||
final JsEvalResult result = jsRuntime.evaluate(fullScript);
|
||||
|
||||
// Process Results
|
||||
if (result.isError) {
|
||||
print("Pre-request script execution error: ${result.stringResult}");
|
||||
// Handle error - maybe show in UI, keep original request/env
|
||||
} else if (result.stringResult.isNotEmpty) {
|
||||
final resultMap = jsonDecode(result.stringResult);
|
||||
if (resultMap is Map<String, dynamic>) {
|
||||
// Deserialize Request
|
||||
if (resultMap.containsKey('request') && resultMap['request'] is Map) {
|
||||
try {
|
||||
resultingRequest = HttpRequestModel.fromJson(
|
||||
Map<String, Object?>.from(resultMap['request']));
|
||||
} catch (e) {
|
||||
print("Error deserializing modified request from script: $e");
|
||||
//TODO: Handle error - maybe keep original request?
|
||||
}
|
||||
}
|
||||
// Get Environment Modifications
|
||||
if (resultMap.containsKey('environment') &&
|
||||
resultMap['environment'] is Map) {
|
||||
resultingEnvironment =
|
||||
Map<String, dynamic>.from(resultMap['environment']);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print("Dart-level error during pre-request script execution: $e");
|
||||
}
|
||||
|
||||
return (
|
||||
updatedRequest: resultingRequest,
|
||||
updatedEnvironment: resultingEnvironment
|
||||
);
|
||||
}
|
||||
|
||||
Future<
|
||||
({
|
||||
HttpResponseModel updatedResponse,
|
||||
Map<String, dynamic> updatedEnvironment
|
||||
})> executePostResponseScript({
|
||||
required RequestModel currentRequestModel,
|
||||
required Map<String, dynamic> activeEnvironment,
|
||||
}) async {
|
||||
if ((currentRequestModel.postRequestScript ?? "").trim().isEmpty) {
|
||||
// No script, return original data
|
||||
// return (
|
||||
// updatedRequest: currentRequestModel.httpRequestModel,
|
||||
// updatedEnvironment: activeEnvironment
|
||||
// );
|
||||
}
|
||||
|
||||
final httpRequest = currentRequestModel.httpRequestModel;
|
||||
final httpResponse = currentRequestModel.httpResponseModel;
|
||||
final userScript = currentRequestModel.postRequestScript;
|
||||
|
||||
// Prepare Data
|
||||
final requestJson = jsonEncode(httpRequest?.toJson());
|
||||
final responseJson = jsonEncode(httpResponse?.toJson());
|
||||
final environmentJson = jsonEncode(activeEnvironment);
|
||||
|
||||
// Inject data as JS variables
|
||||
// Escape strings properly if embedding directly
|
||||
final dataInjection = """
|
||||
var injectedRequestJson = ${jsEscapeString(requestJson)};
|
||||
var injectedEnvironmentJson = ${jsEscapeString(environmentJson)};
|
||||
var injectedResponseJson = ${jsEscapeString(responseJson)};
|
||||
""";
|
||||
|
||||
// Concatenate & Add Return
|
||||
final fullScript = """
|
||||
(function() {
|
||||
// --- Data Injection (now constants within the IIFE scope) ---
|
||||
$dataInjection
|
||||
|
||||
// --- Setup Script (will declare variables within the IIFE scope) ---
|
||||
$kJSSetupScript
|
||||
|
||||
// --- User Script (will execute within the IIFE scope)---
|
||||
$userScript
|
||||
|
||||
// --- Return Result (accesses variables from the IIFE scope) ---
|
||||
return JSON.stringify({ response: response, environment: environment });
|
||||
})(); // Immediately invoke the function
|
||||
""";
|
||||
|
||||
// TODO: Do something better to avoid null check here.
|
||||
// HttpRequestModel resultingRequest = httpRequest!;
|
||||
HttpResponseModel resultingResponse = httpResponse!;
|
||||
Map<String, dynamic> resultingEnvironment = Map.from(activeEnvironment);
|
||||
|
||||
try {
|
||||
// Execute
|
||||
final JsEvalResult result = jsRuntime.evaluate(fullScript);
|
||||
|
||||
// Process Results
|
||||
if (result.isError) {
|
||||
print("Post-Response script execution error: ${result.stringResult}");
|
||||
// TODO: Handle error - maybe show in UI, keep original request/env
|
||||
} else if (result.stringResult.isNotEmpty) {
|
||||
final resultMap = jsonDecode(result.stringResult);
|
||||
if (resultMap is Map<String, dynamic>) {
|
||||
// Deserialize Request
|
||||
if (resultMap.containsKey('response') && resultMap['response'] is Map) {
|
||||
try {
|
||||
resultingResponse = HttpResponseModel.fromJson(
|
||||
Map<String, Object?>.from(resultMap['response']));
|
||||
} catch (e) {
|
||||
print("Error deserializing modified response from script: $e");
|
||||
//TODO: Handle error - maybe keep original response?
|
||||
}
|
||||
}
|
||||
// Get Environment Modifications
|
||||
if (resultMap.containsKey('environment') &&
|
||||
resultMap['environment'] is Map) {
|
||||
resultingEnvironment =
|
||||
Map<String, dynamic>.from(resultMap['environment']);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print("Dart-level error during post-response script execution: $e");
|
||||
}
|
||||
|
||||
return (
|
||||
updatedResponse: resultingResponse,
|
||||
updatedEnvironment: resultingEnvironment
|
||||
);
|
||||
}
|
||||
|
||||
// Helper to properly escape strings for JS embedding
|
||||
String jsEscapeString(String s) {
|
||||
return jsonEncode(
|
||||
s); // jsonEncode handles escaping correctly for JS string literals
|
||||
}
|
@ -1,6 +1,8 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:hive_flutter/hive_flutter.dart';
|
||||
|
||||
enum HiveBoxType { normal, lazy }
|
||||
|
||||
const String kDataBox = "apidash-data";
|
||||
const String kKeyDataBoxIds = "ids";
|
||||
|
||||
@ -11,6 +13,17 @@ const String kHistoryMetaBox = "apidash-history-meta";
|
||||
const String kHistoryBoxIds = "historyIds";
|
||||
const String kHistoryLazyBox = "apidash-history-lazy";
|
||||
|
||||
const String kDashBotBox = "apidash-dashbot-data";
|
||||
const String kKeyDashBotBoxIds = 'messages';
|
||||
|
||||
const kHiveBoxes = [
|
||||
(kDataBox, HiveBoxType.normal),
|
||||
(kEnvironmentBox, HiveBoxType.normal),
|
||||
(kHistoryMetaBox, HiveBoxType.normal),
|
||||
(kHistoryLazyBox, HiveBoxType.lazy),
|
||||
(kDashBotBox, HiveBoxType.lazy),
|
||||
];
|
||||
|
||||
Future<bool> initHiveBoxes(
|
||||
bool initializeUsingPath,
|
||||
String? workspaceFolderPath,
|
||||
@ -34,10 +47,13 @@ Future<bool> initHiveBoxes(
|
||||
|
||||
Future<bool> openHiveBoxes() async {
|
||||
try {
|
||||
await Hive.openBox(kDataBox);
|
||||
await Hive.openBox(kEnvironmentBox);
|
||||
await Hive.openBox(kHistoryMetaBox);
|
||||
await Hive.openLazyBox(kHistoryLazyBox);
|
||||
for (var box in kHiveBoxes) {
|
||||
if (box.$2 == HiveBoxType.normal) {
|
||||
await Hive.openBox(box.$1);
|
||||
} else if (box.$2 == HiveBoxType.lazy) {
|
||||
await Hive.openLazyBox(box.$1);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (e) {
|
||||
debugPrint("ERROR OPEN HIVE BOXES: $e");
|
||||
@ -47,17 +63,14 @@ Future<bool> openHiveBoxes() async {
|
||||
|
||||
Future<void> clearHiveBoxes() async {
|
||||
try {
|
||||
if (Hive.isBoxOpen(kDataBox)) {
|
||||
await Hive.box(kDataBox).clear();
|
||||
}
|
||||
if (Hive.isBoxOpen(kEnvironmentBox)) {
|
||||
await Hive.box(kEnvironmentBox).clear();
|
||||
}
|
||||
if (Hive.isBoxOpen(kHistoryMetaBox)) {
|
||||
await Hive.box(kHistoryMetaBox).clear();
|
||||
}
|
||||
if (Hive.isBoxOpen(kHistoryLazyBox)) {
|
||||
await Hive.lazyBox(kHistoryLazyBox).clear();
|
||||
for (var box in kHiveBoxes) {
|
||||
if (Hive.isBoxOpen(box.$1)) {
|
||||
if (box.$2 == HiveBoxType.normal) {
|
||||
await Hive.box(box.$1).clear();
|
||||
} else if (box.$2 == HiveBoxType.lazy) {
|
||||
await Hive.lazyBox(box.$1).clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint("ERROR CLEAR HIVE BOXES: $e");
|
||||
@ -66,17 +79,14 @@ Future<void> clearHiveBoxes() async {
|
||||
|
||||
Future<void> deleteHiveBoxes() async {
|
||||
try {
|
||||
if (Hive.isBoxOpen(kDataBox)) {
|
||||
await Hive.box(kDataBox).deleteFromDisk();
|
||||
}
|
||||
if (Hive.isBoxOpen(kEnvironmentBox)) {
|
||||
await Hive.box(kEnvironmentBox).deleteFromDisk();
|
||||
}
|
||||
if (Hive.isBoxOpen(kHistoryMetaBox)) {
|
||||
await Hive.box(kHistoryMetaBox).deleteFromDisk();
|
||||
}
|
||||
if (Hive.isBoxOpen(kHistoryLazyBox)) {
|
||||
await Hive.lazyBox(kHistoryLazyBox).deleteFromDisk();
|
||||
for (var box in kHiveBoxes) {
|
||||
if (Hive.isBoxOpen(box.$1)) {
|
||||
if (box.$2 == HiveBoxType.normal) {
|
||||
await Hive.box(box.$1).deleteFromDisk();
|
||||
} else if (box.$2 == HiveBoxType.lazy) {
|
||||
await Hive.lazyBox(box.$1).deleteFromDisk();
|
||||
}
|
||||
}
|
||||
}
|
||||
await Hive.close();
|
||||
} catch (e) {
|
||||
@ -91,6 +101,7 @@ class HiveHandler {
|
||||
late final Box environmentBox;
|
||||
late final Box historyMetaBox;
|
||||
late final LazyBox historyLazyBox;
|
||||
late final LazyBox dashBotBox;
|
||||
|
||||
HiveHandler() {
|
||||
debugPrint("Trying to open Hive boxes");
|
||||
@ -98,6 +109,7 @@ class HiveHandler {
|
||||
environmentBox = Hive.box(kEnvironmentBox);
|
||||
historyMetaBox = Hive.box(kHistoryMetaBox);
|
||||
historyLazyBox = Hive.lazyBox(kHistoryLazyBox);
|
||||
dashBotBox = Hive.lazyBox(kDashBotBox);
|
||||
}
|
||||
|
||||
dynamic getIds() => dataBox.get(kKeyDataBoxIds);
|
||||
@ -135,11 +147,16 @@ class HiveHandler {
|
||||
Future<dynamic> getHistoryRequest(String id) async =>
|
||||
await historyLazyBox.get(id);
|
||||
Future<void> setHistoryRequest(
|
||||
String id, Map<String, dynamic>? historyRequestJsoon) =>
|
||||
historyLazyBox.put(id, historyRequestJsoon);
|
||||
String id, Map<String, dynamic>? historyRequestJson) =>
|
||||
historyLazyBox.put(id, historyRequestJson);
|
||||
|
||||
Future<void> deleteHistoryRequest(String id) => historyLazyBox.delete(id);
|
||||
|
||||
Future<dynamic> getDashbotMessages() async =>
|
||||
await dashBotBox.get(kKeyDashBotBoxIds);
|
||||
Future<void> saveDashbotMessages(String messages) =>
|
||||
dashBotBox.put(kKeyDashBotBoxIds, messages);
|
||||
|
||||
Future clearAllHistory() async {
|
||||
await historyMetaBox.clear();
|
||||
await historyLazyBox.clear();
|
||||
@ -150,6 +167,7 @@ class HiveHandler {
|
||||
await environmentBox.clear();
|
||||
await historyMetaBox.clear();
|
||||
await historyLazyBox.clear();
|
||||
await dashBotBox.clear();
|
||||
}
|
||||
|
||||
Future<void> removeUnused() async {
|
||||
|
@ -1,3 +1,4 @@
|
||||
export 'flutter_js_service.dart';
|
||||
export 'hive_services.dart';
|
||||
export 'history_service.dart';
|
||||
export 'window_services.dart';
|
||||
|
616
lib/utils/js_utils.dart
Normal file
616
lib/utils/js_utils.dart
Normal file
@ -0,0 +1,616 @@
|
||||
const String kJSSetupScript = r"""
|
||||
// === APIDash Setup Script ===
|
||||
|
||||
// --- 1. Parse Injected Data ---
|
||||
// These variables are expected to be populated by Dart before this script runs.
|
||||
// Example: const injectedRequestJson = '{"method":"get", "url":"...", ...}';
|
||||
|
||||
let request = {}; // Will hold the RequestModel data
|
||||
let response = {}; // Will hold the ResponseModel data (only for post-request)
|
||||
let environment = {}; // Will hold the *active* environment variables as a simple {key: value} map
|
||||
|
||||
// Note: Using 'let' because environment might be completely cleared/reassigned by ad.environment.clear().
|
||||
|
||||
try {
|
||||
// 'injectedRequestJson' should always be provided
|
||||
if (typeof injectedRequestJson !== 'undefined' && injectedRequestJson) {
|
||||
request = JSON.parse(injectedRequestJson);
|
||||
// Ensure essential arrays exist if they are null/undefined after parsing
|
||||
request.headers = request.headers || [];
|
||||
request.params = request.params || [];
|
||||
request.formData = request.formData || [];
|
||||
} else {
|
||||
sendMessage('consoleError', JSON.stringify(['Setup Error: injectedRequestJson is missing or empty.']));
|
||||
}
|
||||
|
||||
// 'injectedResponseJson' is only for post-response scripts
|
||||
if (typeof injectedResponseJson !== 'undefined' && injectedResponseJson) {
|
||||
response = JSON.parse(injectedResponseJson);
|
||||
// Ensure response headers map exists
|
||||
response.headers = response.headers || {};
|
||||
response.requestHeaders = response.requestHeaders || {};
|
||||
}
|
||||
|
||||
// 'injectedEnvironmentJson' should always be provided
|
||||
if (typeof injectedEnvironmentJson !== 'undefined' && injectedEnvironmentJson) {
|
||||
const parsedEnvData = JSON.parse(injectedEnvironmentJson);
|
||||
|
||||
environment = {}; // Initialize the target simple map
|
||||
|
||||
if (parsedEnvData && Array.isArray(parsedEnvData.values)) {
|
||||
parsedEnvData.values.forEach(variable => {
|
||||
// Check if the variable object is valid and enabled
|
||||
if (variable && typeof variable === 'object' && variable.enabled === true && typeof variable.key === 'string') {
|
||||
// Add the key-value pair to our simplified 'environment' map
|
||||
environment[variable.key] = variable.value;
|
||||
}
|
||||
});
|
||||
// sendMessage('consoleLog', JSON.stringify(['Successfully parsed environment variables.']));
|
||||
} else {
|
||||
// Log a warning if the structure is not as expected, but continue with an empty env
|
||||
sendMessage('consoleWarn', JSON.stringify([
|
||||
'Setup Warning: injectedEnvironmentJson does not have the expected structure ({values: Array}). Using an empty environment.',
|
||||
'Received Data:', parsedEnvData // Log received data for debugging
|
||||
]));
|
||||
environment = {}; // Ensure it's an empty object
|
||||
}
|
||||
|
||||
} else {
|
||||
sendMessage('consoleError', JSON.stringify(['Setup Error: injectedEnvironmentJson is missing or empty.']));
|
||||
environment = {}; // Initialize to empty object to avoid errors later
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
// Send error back to Dart if parsing fails catastrophically
|
||||
sendMessage('fatalError', JSON.stringify({
|
||||
message: 'Failed to parse injected JSON data.',
|
||||
error: e.toString(),
|
||||
stack: e.stack
|
||||
}));
|
||||
// Optionally, re-throw to halt script execution immediately
|
||||
// throw new Error('Failed to parse injected JSON data: ' + e.toString());
|
||||
}
|
||||
|
||||
|
||||
// --- 2. Define APIDash Helper (`ad`) Object ---
|
||||
// This object provides functions to interact with the request, response,
|
||||
// environment, and the Dart host application.
|
||||
|
||||
const ad = {
|
||||
/**
|
||||
* Functions to modify the request object *before* it is sent.
|
||||
* Only available in pre-request scripts.
|
||||
* Changes are made directly to the 'request' JS object.
|
||||
*/
|
||||
request: {
|
||||
/**
|
||||
* Access and modify request headers. Remember header names are case-insensitive in HTTP,
|
||||
* but comparisons here might be case-sensitive unless handled carefully.
|
||||
* Headers are represented as an array of objects: [{name: string, value: string}, ...]
|
||||
*/
|
||||
headers: {
|
||||
/**
|
||||
* Adds or updates a header. If a header with the same name (case-sensitive)
|
||||
* already exists, it updates its value. Otherwise, adds a new header.
|
||||
* Also updates the isHeaderEnabledList to include {true} by default
|
||||
* @param {string} key The header name.
|
||||
* @param {string} value The header value.
|
||||
* @param {boolean} isHeaderEnabledList value.
|
||||
*/
|
||||
set: (key, value) => {
|
||||
if (!request || typeof request !== 'object' || !Array.isArray(request.headers)) return;
|
||||
if (typeof key !== 'string') return;
|
||||
|
||||
const stringValue = String(value);
|
||||
const existingHeaderIndex = request.headers.findIndex(
|
||||
h => typeof h === 'object' && h.name === key
|
||||
);
|
||||
|
||||
if (!Array.isArray(request.isHeaderEnabledList)) {
|
||||
request.isHeaderEnabledList = [];
|
||||
}
|
||||
|
||||
if (existingHeaderIndex > -1) {
|
||||
request.headers[existingHeaderIndex].value = stringValue;
|
||||
request.isHeaderEnabledList[existingHeaderIndex] = true;
|
||||
} else {
|
||||
request.headers.push({
|
||||
name: key,
|
||||
value: stringValue
|
||||
});
|
||||
request.isHeaderEnabledList.push(true);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Gets the value of the first header matching the key (case-sensitive).
|
||||
* @param {string} key The header name.
|
||||
* @returns {string|undefined} The header value or undefined if not found.
|
||||
*/
|
||||
|
||||
get: (key) => {
|
||||
if (!request || typeof request !== 'object' || !Array.isArray(request.headers)) return undefined;
|
||||
const header = request.headers.find(h => typeof h === 'object' && h.name === key);
|
||||
return header ? header.value : undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* Removes all headers with the given name (case-sensitive).
|
||||
* @param {string} key The header name to remove.
|
||||
*/
|
||||
|
||||
remove: (key) => {
|
||||
if (!request || typeof request !== 'object' || !Array.isArray(request.headers)) return;
|
||||
|
||||
if (!Array.isArray(request.isHeaderEnabledList)) {
|
||||
request.isHeaderEnabledList = [];
|
||||
}
|
||||
|
||||
const indicesToRemove = [];
|
||||
request.headers.forEach((h, index) => {
|
||||
if (typeof h === 'object' && h.name === key) {
|
||||
indicesToRemove.push(index);
|
||||
}
|
||||
});
|
||||
|
||||
// Remove from end to start to prevent index shifting
|
||||
for (let i = indicesToRemove.length - 1; i >= 0; i--) {
|
||||
const idx = indicesToRemove[i];
|
||||
request.headers.splice(idx, 1);
|
||||
request.isHeaderEnabledList.splice(idx, 1);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Checks if a header with the given name exists (case-sensitive).
|
||||
* @param {string} key The header name.
|
||||
* @returns {boolean} True if the header exists, false otherwise.
|
||||
*/
|
||||
|
||||
has: (key) => {
|
||||
if (!request || typeof request !== 'object' || !Array.isArray(request.headers)) return false;
|
||||
return request.headers.some(h => typeof h === 'object' && h.name === key);
|
||||
},
|
||||
/**
|
||||
* Clears all request headers along with isHeaderEnabledList.
|
||||
*/
|
||||
|
||||
clear: () => {
|
||||
if (!request || typeof request !== 'object') return;
|
||||
request.headers = [];
|
||||
request.isHeaderEnabledList = [];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Access and modify URL query parameters.
|
||||
* Params are represented as an array of objects: [{name: string, value: string}, ...]
|
||||
*/
|
||||
params: {
|
||||
/**
|
||||
* Adds or updates a query parameter. If a param with the same name (case-sensitive)
|
||||
* already exists, it updates its value. Use multiple times for duplicate keys if needed by server.
|
||||
* Consider URL encoding implications - values should likely be pre-encoded if necessary.
|
||||
* @param {string} key The parameter name.
|
||||
* @param {string} value The parameter value.
|
||||
*/
|
||||
set: (key, value) => {
|
||||
if (!request || typeof request !== 'object' || !Array.isArray(request.params)) return;
|
||||
if (typeof key !== 'string') return;
|
||||
|
||||
const stringValue = String(value);
|
||||
|
||||
if (!Array.isArray(request.isParamEnabledList)) {
|
||||
request.isParamEnabledList = [];
|
||||
}
|
||||
|
||||
const existingParamIndex = request.params.findIndex(p => typeof p === 'object' && p.name === key);
|
||||
|
||||
if (existingParamIndex > -1) {
|
||||
request.params[existingParamIndex].value = stringValue;
|
||||
request.isParamEnabledList[existingParamIndex] = true;
|
||||
} else {
|
||||
request.params.push({
|
||||
name: key,
|
||||
value: stringValue
|
||||
});
|
||||
request.isParamEnabledList.push(true);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Gets the value of the first query parameter matching the key (case-sensitive).
|
||||
* @param {string} key The parameter name.
|
||||
* @returns {string|undefined} The parameter value or undefined if not found.
|
||||
*/
|
||||
get: (key) => {
|
||||
if (!request || typeof request !== 'object' || !Array.isArray(request.params)) return undefined; // Safety check
|
||||
const param = request.params.find(p => typeof p === 'object' && p.name === key);
|
||||
return param ? param.value : undefined;
|
||||
},
|
||||
/**
|
||||
* Removes all query parameters with the given name (case-sensitive).
|
||||
* @param {string} key The parameter name to remove.
|
||||
*/
|
||||
remove: (key) => {
|
||||
if (!request || typeof request !== 'object' || !Array.isArray(request.params)) return;
|
||||
|
||||
if (!Array.isArray(request.isParamEnabledList)) {
|
||||
request.isParamEnabledList = [];
|
||||
}
|
||||
|
||||
const indicesToRemove = [];
|
||||
request.params.forEach((p, index) => {
|
||||
if (typeof p === 'object' && p.name === key) {
|
||||
indicesToRemove.push(index);
|
||||
}
|
||||
});
|
||||
|
||||
for (let i = indicesToRemove.length - 1; i >= 0; i--) {
|
||||
const idx = indicesToRemove[i];
|
||||
request.params.splice(idx, 1);
|
||||
request.isParamEnabledList.splice(idx, 1);
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Checks if a query parameter with the given name exists (case-sensitive).
|
||||
* @param {string} key The parameter name.
|
||||
* @returns {boolean} True if the parameter exists, false otherwise.
|
||||
*/
|
||||
has: (key) => {
|
||||
if (!request || typeof request !== 'object' || !Array.isArray(request.params)) return false; // Safety check
|
||||
return request.params.some(p => typeof p === 'object' && p.name === key);
|
||||
},
|
||||
/**
|
||||
* Clears all query parameters.
|
||||
*/
|
||||
clear: () => {
|
||||
if (!request || typeof request !== 'object') return;
|
||||
request.params = [];
|
||||
request.isParamEnabledList = [];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Access or modify the request URL.
|
||||
*/
|
||||
url: {
|
||||
/**
|
||||
* Gets the current request URL string.
|
||||
* @returns {string} The URL.
|
||||
*/
|
||||
get: () => {
|
||||
return (request && typeof request === 'object') ? request.url : '';
|
||||
},
|
||||
/**
|
||||
* Sets the request URL string.
|
||||
* @param {string} newUrl The new URL.
|
||||
*/
|
||||
set: (newUrl) => {
|
||||
if (request && typeof request === 'object' && typeof newUrl === 'string') {
|
||||
request.url = newUrl;
|
||||
}
|
||||
}
|
||||
// Future: Could add methods to manipulate parts (host, path, query) if needed
|
||||
},
|
||||
|
||||
/**
|
||||
* Access or modify the request body.
|
||||
*/
|
||||
body: {
|
||||
/**
|
||||
* Gets the current request body content (string).
|
||||
* Note: For form-data, this returns the raw string body (if any), not the structured data. Use `ad.request.formData` for that.
|
||||
* @returns {string|null|undefined} The request body string.
|
||||
*/
|
||||
get: () => {
|
||||
return (request && typeof request === 'object') ? request.body : undefined;
|
||||
},
|
||||
/**
|
||||
* Sets the request body content (string).
|
||||
* Important: Also updates the Content-Type if setting JSON/Text, unless a Content-Type header is already explicitly set.
|
||||
* Setting the body will clear form-data if the content type changes away from form-data.
|
||||
* @param {string|object} newBody The new body content. If an object is provided, it's stringified as JSON.
|
||||
* @param {string} [contentType] Optionally specify the Content-Type (e.g., 'application/json', 'text/plain'). If not set, defaults to 'text/plain' or 'application/json' if newBody is an object.
|
||||
*/
|
||||
set: (newBody, contentType) => {
|
||||
if (!request || typeof request !== 'object') return; // Safety check fix: check !request or typeof !== object
|
||||
|
||||
let finalBody = '';
|
||||
let finalContentType = contentType;
|
||||
|
||||
if (typeof newBody === 'object' && newBody !== null) {
|
||||
try {
|
||||
finalBody = JSON.stringify(newBody);
|
||||
finalContentType = contentType || 'application/json'; // Default to JSON if object
|
||||
request.bodyContentType = 'json'; // Update internal model type
|
||||
} catch (e) {
|
||||
sendMessage('consoleError', JSON.stringify(['Error stringifying object for request body:', e.toString()]));
|
||||
return; // Don't proceed if stringify fails
|
||||
}
|
||||
} else {
|
||||
finalBody = String(newBody); // Ensure it's a string
|
||||
finalContentType = contentType || 'text/plain'; // Default to text
|
||||
request.bodyContentType = 'text'; // Update internal model type
|
||||
}
|
||||
|
||||
request.body = finalBody;
|
||||
|
||||
// Clear form data if we are setting a string/json body
|
||||
request.formData = [];
|
||||
|
||||
// Set Content-Type header if not already set by user explicitly in headers
|
||||
// Use case-insensitive check for existing Content-Type
|
||||
const hasContentTypeHeader = request.headers.some(h => typeof h === 'object' && h.name.toLowerCase() === 'content-type');
|
||||
if (!hasContentTypeHeader && finalContentType) {
|
||||
ad.request.headers.set('Content-Type', finalContentType);
|
||||
}
|
||||
}
|
||||
// TODO: Add helpers for request.formData if needed (similar to headers/params)
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Access and modify GraphQL query string.
|
||||
* For GraphQL requests, this represents the query/mutation/subscription.
|
||||
*/
|
||||
query: {
|
||||
/**
|
||||
* Gets the current GraphQL query string.
|
||||
* @returns {string} The GraphQL query.
|
||||
*/
|
||||
get: () => {
|
||||
return (request && typeof request === 'object') ? (request.query || '') : '';
|
||||
},
|
||||
/**
|
||||
* Sets the GraphQL query string.
|
||||
* @param {string} newQuery The GraphQL query/mutation/subscription.
|
||||
*/
|
||||
set: (newQuery) => {
|
||||
if (request && typeof request === 'object' && typeof newQuery === 'string') {
|
||||
request.query = newQuery;
|
||||
ad.request.headers.set('Content-Type', 'application/json');
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Clears the GraphQL query.
|
||||
*/
|
||||
clear: () => {
|
||||
if (request && typeof request === 'object') {
|
||||
request.query = '';
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Access or modify the request method (e.g., 'GET', 'POST').
|
||||
*/
|
||||
method: {
|
||||
/**
|
||||
* Gets the current request method.
|
||||
* @returns {string} The HTTP method (e.g., "get", "post").
|
||||
*/
|
||||
get: () => {
|
||||
return (request && typeof request === 'object') ? request.method : '';
|
||||
},
|
||||
/**
|
||||
* Sets the request method.
|
||||
* @param {string} newMethod The new HTTP method (e.g., "POST", "put"). Case might matter for the Dart model enum.
|
||||
*/
|
||||
set: (newMethod) => {
|
||||
if (request && typeof request === 'object' && typeof newMethod === 'string') {
|
||||
// Consider converting to lowercase to match HTTPVerb enum likely usage
|
||||
request.method = newMethod.toLowerCase();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Read-only access to the response data.
|
||||
* Only available in post-response scripts.
|
||||
*/
|
||||
response: {
|
||||
/**
|
||||
* The HTTP status code of the response.
|
||||
* @type {number|undefined}
|
||||
*/
|
||||
get status() {
|
||||
return (response && typeof response === 'object') ? response.statusCode : undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* The response body as a string. If the response was binary, this might be decoded text
|
||||
* based on Content-Type or potentially garbled. Use `bodyBytes` for raw binary data access (if provided).
|
||||
* @type {string|undefined}
|
||||
*/
|
||||
get body() {
|
||||
return (response && typeof response === 'object') ? response.body : undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* The response body automatically formatted (e.g., pretty-printed JSON). Provided by Dart.
|
||||
* @type {string|undefined}
|
||||
*/
|
||||
get formattedBody() {
|
||||
return (response && typeof response === 'object') ? response.formattedBody : undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* The raw response body as an array of bytes (numbers).
|
||||
* Note: This relies on the Dart side serializing Uint8List correctly (e.g., as List<int>).
|
||||
* Accessing large byte arrays in JS might be memory-intensive.
|
||||
* @type {number[]|undefined}
|
||||
*/
|
||||
get bodyBytes() {
|
||||
return (response && typeof response === 'object') ? response.bodyBytes : undefined;
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* The approximate time taken for the request-response cycle. Provided by Dart.
|
||||
* Assumes Dart sends it as microseconds and converts it to milliseconds here.
|
||||
* @type {number|undefined} Time in milliseconds.
|
||||
*/
|
||||
get time() {
|
||||
// Assuming response.time is in microseconds from Dart's DurationConverter
|
||||
return (response && typeof response === 'object' && typeof response.time === 'number') ? response.time / 1000 : undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* An object containing the response headers (keys are header names, values are header values).
|
||||
* Header names are likely lowercase from the http package.
|
||||
* @type {object|undefined} e.g., {'content-type': 'application/json', ...}
|
||||
*/
|
||||
get headers() {
|
||||
return (response && typeof response === 'object') ? response.headers : undefined;
|
||||
},
|
||||
|
||||
/**
|
||||
* An object containing the request headers that were actually sent (useful for verification).
|
||||
* Header names are likely lowercase.
|
||||
* @type {object|undefined} e.g., {'user-agent': '...', ...}
|
||||
*/
|
||||
get requestHeaders() {
|
||||
return (response && typeof response === 'object') ? response.requestHeaders : undefined;
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* Attempts to parse the response body as JSON.
|
||||
* @returns {object|undefined} The parsed JSON object, or undefined if parsing fails or body is empty.
|
||||
*/
|
||||
json: () => {
|
||||
const bodyContent = ad.response.body; // Assign to variable first
|
||||
if (!bodyContent) { // Check the variable
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(bodyContent); // Parse the variable
|
||||
} catch (e) {
|
||||
ad.console.error("Failed to parse response body as JSON:", e.toString());
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Gets a specific response header value (case-insensitive key lookup).
|
||||
* @param {string} key The header name.
|
||||
* @returns {string|undefined} The header value or undefined if not found.
|
||||
*/
|
||||
getHeader: (key) => {
|
||||
const headers = ad.response.headers;
|
||||
if (!headers || typeof key !== 'string') return undefined;
|
||||
const lowerKey = key.toLowerCase();
|
||||
// Find the key in the headers object case-insensitively
|
||||
const headerKey = Object.keys(headers).find(k => k.toLowerCase() === lowerKey);
|
||||
return headerKey ? headers[headerKey] : undefined; // Return the value using the found key
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Access and modify environment variables for the active environment.
|
||||
* Changes are made to the 'environment' JS object (simple {key: value} map)
|
||||
* and sent back to Dart. Dart side will need to merge these changes back
|
||||
* into the original structured format if needed.
|
||||
*/
|
||||
environment: {
|
||||
/**
|
||||
* Gets the value of an environment variable from the simplified map.
|
||||
* @param {string} key The variable name.
|
||||
* @returns {any} The variable value or undefined if not found.
|
||||
*/
|
||||
get: (key) => {
|
||||
// Access the simplified 'environment' object directly
|
||||
return (environment && typeof environment === 'object') ? environment[key] : undefined;
|
||||
},
|
||||
/**
|
||||
* Sets the value of an environment variable in the simplified map.
|
||||
* @param {string} key The variable name.
|
||||
* @param {any} value The variable value. Should be JSON-serializable (string, number, boolean, object, array).
|
||||
*/
|
||||
set: (key, value) => {
|
||||
if (environment && typeof environment === 'object' && typeof key === 'string') {
|
||||
// Modify the simplified 'environment' object
|
||||
environment[key] = value;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Removes an environment variable from the simplified map.
|
||||
* @param {string} key The variable name to remove.
|
||||
*/
|
||||
unset: (key) => {
|
||||
if (environment && typeof environment === 'object') {
|
||||
// Modify the simplified 'environment' object
|
||||
delete environment[key];
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Checks if an environment variable exists in the simplified map.
|
||||
* @param {string} key The variable name.
|
||||
* @returns {boolean} True if the variable exists, false otherwise.
|
||||
*/
|
||||
has: (key) => {
|
||||
// Check the simplified 'environment' object
|
||||
return (environment && typeof environment === 'object') ? environment.hasOwnProperty(key) : false;
|
||||
},
|
||||
/**
|
||||
* Removes all variables from the simplified environment map scope.
|
||||
*/
|
||||
clear: () => {
|
||||
if (environment && typeof environment === 'object') {
|
||||
// Clear the simplified 'environment' object
|
||||
for (const key in environment) {
|
||||
if (environment.hasOwnProperty(key)) {
|
||||
delete environment[key];
|
||||
}
|
||||
}
|
||||
// Alternatively, just reassign: environment = {};
|
||||
}
|
||||
}
|
||||
// Note: A separate 'globals' object could be added here if global variables are implemented distinctly.
|
||||
},
|
||||
|
||||
/**
|
||||
* Provides logging capabilities. Messages are sent back to Dart via the bridge.
|
||||
*/
|
||||
console: {
|
||||
/**
|
||||
* Logs informational messages.
|
||||
* @param {...any} args Values to log. They will be JSON-stringified.
|
||||
*/
|
||||
log: (...args) => {
|
||||
try {
|
||||
sendMessage('consoleLog', JSON.stringify(args));
|
||||
} catch (e) {
|
||||
/* Ignore stringify errors for console? Or maybe log the error itself? */
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Logs warning messages.
|
||||
* @param {...any} args Values to log.
|
||||
*/
|
||||
warn: (...args) => {
|
||||
try {
|
||||
sendMessage('consoleWarn', JSON.stringify(args));
|
||||
} catch (e) {
|
||||
/* Ignore */
|
||||
}
|
||||
},
|
||||
/**
|
||||
* Logs error messages.
|
||||
* @param {...any} args Values to log.
|
||||
*/
|
||||
error: (...args) => {
|
||||
try {
|
||||
sendMessage('consoleError', JSON.stringify(args));
|
||||
} catch (e) {
|
||||
/* Ignore */
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
// --- End of APIDash Setup Script ---
|
||||
|
||||
// User's script will be appended below this line by Dart.
|
||||
// Dart will also append the final JSON.stringify() call to return results.
|
||||
""";
|
127
lib/utils/pre_post_script_utils.dart
Normal file
127
lib/utils/pre_post_script_utils.dart
Normal file
@ -0,0 +1,127 @@
|
||||
import 'package:apidash_core/apidash_core.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import '../models/models.dart';
|
||||
import '../services/services.dart';
|
||||
|
||||
Future<RequestModel> handlePreRequestScript(
|
||||
RequestModel requestModel,
|
||||
EnvironmentModel? originalEnvironmentModel,
|
||||
void Function(EnvironmentModel, List<EnvironmentVariableModel>)? updateEnv,
|
||||
) async {
|
||||
final scriptResult = await executePreRequestScript(
|
||||
currentRequestModel: requestModel,
|
||||
activeEnvironment: originalEnvironmentModel?.toJson() ?? {},
|
||||
);
|
||||
final newRequestModel =
|
||||
requestModel.copyWith(httpRequestModel: scriptResult.updatedRequest);
|
||||
if (originalEnvironmentModel != null) {
|
||||
final updatedEnvironmentMap = scriptResult.updatedEnvironment;
|
||||
|
||||
final List<EnvironmentVariableModel> newValues = [];
|
||||
final Map<String, dynamic> mutableUpdatedEnv =
|
||||
Map.from(updatedEnvironmentMap);
|
||||
|
||||
for (final originalVariable in originalEnvironmentModel.values) {
|
||||
if (mutableUpdatedEnv.containsKey(originalVariable.key)) {
|
||||
final dynamic newValue = mutableUpdatedEnv[originalVariable.key];
|
||||
newValues.add(
|
||||
originalVariable.copyWith(
|
||||
value: newValue == null ? '' : newValue.toString(),
|
||||
enabled: true,
|
||||
),
|
||||
);
|
||||
|
||||
mutableUpdatedEnv.remove(originalVariable.key);
|
||||
} else {
|
||||
// Variable was removed by the script (unset/clear), don't add it to newValues.
|
||||
// Alternatively, you could keep it but set enabled = false:
|
||||
// newValues.add(originalVariable.copyWith(enabled: false));
|
||||
}
|
||||
}
|
||||
|
||||
for (final entry in mutableUpdatedEnv.entries) {
|
||||
final dynamic newValue = entry.value;
|
||||
newValues.add(
|
||||
EnvironmentVariableModel(
|
||||
key: entry.key,
|
||||
value: newValue == null ? '' : newValue.toString(),
|
||||
enabled: true,
|
||||
type: EnvironmentVariableType.variable,
|
||||
),
|
||||
);
|
||||
}
|
||||
updateEnv?.call(originalEnvironmentModel, newValues);
|
||||
} else {
|
||||
debugPrint(
|
||||
"Skipped environment update as originalEnvironmentModel was null.");
|
||||
|
||||
if (scriptResult.updatedEnvironment.isNotEmpty) {
|
||||
debugPrint(
|
||||
"Warning: Pre-request script updated environment variables, but no active environment was selected to save them to.");
|
||||
}
|
||||
return requestModel;
|
||||
}
|
||||
return newRequestModel;
|
||||
}
|
||||
|
||||
Future<RequestModel> handlePostResponseScript(
|
||||
RequestModel requestModel,
|
||||
EnvironmentModel? originalEnvironmentModel,
|
||||
void Function(EnvironmentModel, List<EnvironmentVariableModel>)? updateEnv,
|
||||
) async {
|
||||
final scriptResult = await executePostResponseScript(
|
||||
currentRequestModel: requestModel,
|
||||
activeEnvironment: originalEnvironmentModel?.toJson() ?? {},
|
||||
);
|
||||
|
||||
final newRequestModel =
|
||||
requestModel.copyWith(httpResponseModel: scriptResult.updatedResponse);
|
||||
|
||||
if (originalEnvironmentModel != null) {
|
||||
final updatedEnvironmentMap = scriptResult.updatedEnvironment;
|
||||
|
||||
final List<EnvironmentVariableModel> newValues = [];
|
||||
final Map<String, dynamic> mutableUpdatedEnv =
|
||||
Map.from(updatedEnvironmentMap);
|
||||
|
||||
for (final originalVariable in originalEnvironmentModel.values) {
|
||||
if (mutableUpdatedEnv.containsKey(originalVariable.key)) {
|
||||
final dynamic newValue = mutableUpdatedEnv[originalVariable.key];
|
||||
newValues.add(
|
||||
originalVariable.copyWith(
|
||||
value: newValue == null ? '' : newValue.toString(),
|
||||
enabled: true,
|
||||
),
|
||||
);
|
||||
|
||||
mutableUpdatedEnv.remove(originalVariable.key);
|
||||
} else {
|
||||
// Variable was removed by the script (unset/clear), don't add it to newValues.
|
||||
// Alternatively, you could keep it but set enabled = false:
|
||||
// newValues.add(originalVariable.copyWith(enabled: false));
|
||||
}
|
||||
}
|
||||
|
||||
for (final entry in mutableUpdatedEnv.entries) {
|
||||
final dynamic newValue = entry.value;
|
||||
newValues.add(
|
||||
EnvironmentVariableModel(
|
||||
key: entry.key,
|
||||
value: newValue == null ? '' : newValue.toString(),
|
||||
enabled: true,
|
||||
type: EnvironmentVariableType.variable,
|
||||
),
|
||||
);
|
||||
}
|
||||
updateEnv?.call(originalEnvironmentModel, newValues);
|
||||
} else {
|
||||
debugPrint(
|
||||
"Skipped environment update as originalEnvironmentModel was null.");
|
||||
if (scriptResult.updatedEnvironment.isNotEmpty) {
|
||||
debugPrint(
|
||||
"Warning: Post-response script updated environment variables, but no active environment was selected to save them to.");
|
||||
}
|
||||
return requestModel;
|
||||
}
|
||||
return newRequestModel;
|
||||
}
|
@ -5,6 +5,8 @@ export 'har_utils.dart';
|
||||
export 'header_utils.dart';
|
||||
export 'history_utils.dart';
|
||||
export 'http_utils.dart';
|
||||
export 'js_utils.dart';
|
||||
export 'pre_post_script_utils.dart';
|
||||
export 'save_utils.dart';
|
||||
export 'ui_utils.dart';
|
||||
export 'window_utils.dart';
|
||||
|
38
lib/widgets/button_learn.dart
Normal file
38
lib/widgets/button_learn.dart
Normal file
@ -0,0 +1,38 @@
|
||||
import 'package:apidash_design_system/apidash_design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
class LearnButton extends StatelessWidget {
|
||||
const LearnButton({
|
||||
super.key,
|
||||
this.label,
|
||||
this.icon,
|
||||
this.url,
|
||||
});
|
||||
|
||||
final String? label;
|
||||
final IconData? icon;
|
||||
final String? url;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
var textLabel = label ?? 'Learn';
|
||||
return SizedBox(
|
||||
height: 24,
|
||||
child: ADFilledButton(
|
||||
icon: Icons.help,
|
||||
iconSize: kButtonIconSizeSmall,
|
||||
label: textLabel,
|
||||
isTonal: true,
|
||||
buttonStyle: ButtonStyle(
|
||||
padding: WidgetStatePropertyAll(kP10),
|
||||
),
|
||||
onPressed: () {
|
||||
if (url != null) {
|
||||
launchUrl(Uri.parse(url!));
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
53
lib/widgets/editor_code.dart
Normal file
53
lib/widgets/editor_code.dart
Normal file
@ -0,0 +1,53 @@
|
||||
import 'package:apidash_design_system/apidash_design_system.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_code_editor/flutter_code_editor.dart';
|
||||
import 'package:flutter_highlight/themes/monokai.dart';
|
||||
import 'package:flutter_highlight/themes/xcode.dart';
|
||||
|
||||
class CodeEditor extends StatelessWidget {
|
||||
const CodeEditor({
|
||||
super.key,
|
||||
required this.controller,
|
||||
this.readOnly = false,
|
||||
this.isDark = false,
|
||||
});
|
||||
|
||||
final bool readOnly;
|
||||
final CodeController controller;
|
||||
final bool isDark;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CodeTheme(
|
||||
data: CodeThemeData(
|
||||
styles: isDark ? monokaiTheme : xcodeTheme,
|
||||
),
|
||||
child: CodeField(
|
||||
expands: true,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: kBorderRadius8,
|
||||
border: BoxBorder.all(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
color: Theme.of(context).colorScheme.surfaceContainerLowest,
|
||||
),
|
||||
readOnly: readOnly,
|
||||
smartDashesType: SmartDashesType.enabled,
|
||||
smartQuotesType: SmartQuotesType.enabled,
|
||||
background: Theme.of(context).colorScheme.surfaceContainerLowest,
|
||||
gutterStyle: GutterStyle(
|
||||
width: 0, // TODO: Fix numbers size
|
||||
margin: 2,
|
||||
textAlign: TextAlign.left,
|
||||
showFoldingHandles: false,
|
||||
showLineNumbers: false,
|
||||
),
|
||||
cursorColor: Theme.of(context).colorScheme.primary,
|
||||
controller: controller,
|
||||
textStyle: kCodeStyle.copyWith(
|
||||
fontSize: Theme.of(context).textTheme.bodyMedium?.fontSize,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
@ -3,6 +3,7 @@ export 'button_copy.dart';
|
||||
export 'button_discord.dart';
|
||||
export 'button_form_data_file.dart';
|
||||
export 'button_group_filled.dart';
|
||||
export 'button_learn.dart';
|
||||
export 'button_repo.dart';
|
||||
export 'button_save_download.dart';
|
||||
export 'button_send.dart';
|
||||
@ -23,6 +24,7 @@ export 'dropdown_content_type.dart';
|
||||
export 'dropdown_formdata.dart';
|
||||
export 'dropdown_http_method.dart';
|
||||
export 'dropdown_import_format.dart';
|
||||
export 'editor_code.dart';
|
||||
export 'editor_json.dart';
|
||||
export 'editor.dart';
|
||||
export 'error_message.dart';
|
||||
|
135
packages/apidash_core/lib/import_export/har_io.dart
Normal file
135
packages/apidash_core/lib/import_export/har_io.dart
Normal file
@ -0,0 +1,135 @@
|
||||
import 'package:har/har.dart' as har;
|
||||
import 'package:seed/seed.dart';
|
||||
import '../consts.dart';
|
||||
import '../models/models.dart';
|
||||
import '../utils/utils.dart';
|
||||
|
||||
class HarParserIO {
|
||||
List<(String?, HttpRequestModel)>? getHttpRequestModelList(String content) {
|
||||
content = content.trim();
|
||||
try {
|
||||
final hl = har.harLogFromJsonStr(content);
|
||||
final requests = har.getRequestsFromHarLog(hl);
|
||||
return requests
|
||||
.map((req) => (req.$2.url, harRequestToHttpRequestModel(req.$2)))
|
||||
.toList();
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
HttpRequestModel harRequestToHttpRequestModel(har.Request request) {
|
||||
HTTPVerb method;
|
||||
|
||||
try {
|
||||
method = HTTPVerb.values.byName((request.method ?? "").toLowerCase());
|
||||
} catch (e) {
|
||||
method = kDefaultHttpMethod;
|
||||
}
|
||||
String url = stripUrlParams(request.url ?? "");
|
||||
List<NameValueModel> headers = [];
|
||||
List<bool> isHeaderEnabledList = [];
|
||||
|
||||
List<NameValueModel> params = [];
|
||||
List<bool> isParamEnabledList = [];
|
||||
|
||||
for (var header in request.headers ?? <har.Header>[]) {
|
||||
var name = header.name ?? "";
|
||||
var value = header.value;
|
||||
var activeHeader = header.disabled ?? false;
|
||||
headers.add(NameValueModel(name: name, value: value));
|
||||
isHeaderEnabledList.add(!activeHeader);
|
||||
}
|
||||
|
||||
for (var query in request.queryString ?? <har.Query>[]) {
|
||||
var name = query.name ?? "";
|
||||
var value = query.value;
|
||||
var activeQuery = query.disabled ?? false;
|
||||
params.add(NameValueModel(name: name, value: value));
|
||||
isParamEnabledList.add(!activeQuery);
|
||||
}
|
||||
|
||||
ContentType bodyContentType = kDefaultContentType;
|
||||
String? body;
|
||||
List<FormDataModel>? formData = [];
|
||||
|
||||
if (request.postData?.mimeType == "application/json") {
|
||||
bodyContentType = ContentType.json;
|
||||
body = request.postData?.text;
|
||||
}
|
||||
FormDataType formDataType = FormDataType.text;
|
||||
if (request.postData?.mimeType == "application/x-www-form-urlencoded") {
|
||||
bodyContentType = ContentType.formdata;
|
||||
var formDataStr = request.postData?.text;
|
||||
Map<String, String> parsedData = parseFormData(formDataStr);
|
||||
parsedData.forEach((key, value) {
|
||||
formDataType = FormDataType.text;
|
||||
var name = key;
|
||||
var val = value;
|
||||
formData.add(FormDataModel(
|
||||
name: name,
|
||||
value: val,
|
||||
type: formDataType,
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
if (request.postData?.mimeType == "multipart/form-data") {
|
||||
bodyContentType = ContentType.formdata;
|
||||
String? name, val;
|
||||
for (var fd in request.postData?.params ?? <har.Param>[]) {
|
||||
name = fd.name;
|
||||
if (fd.contentType == "text/plain") {
|
||||
formDataType = FormDataType.text;
|
||||
val = fd.value;
|
||||
} else {
|
||||
formDataType = FormDataType.file;
|
||||
val = fd.fileName;
|
||||
}
|
||||
formData.add(FormDataModel(
|
||||
name: name ?? "",
|
||||
value: val ?? "",
|
||||
type: formDataType,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
return HttpRequestModel(
|
||||
method: method,
|
||||
url: url,
|
||||
headers: headers,
|
||||
params: params,
|
||||
isHeaderEnabledList: isHeaderEnabledList,
|
||||
isParamEnabledList: isParamEnabledList,
|
||||
body: body,
|
||||
bodyContentType: bodyContentType,
|
||||
formData: formData);
|
||||
}
|
||||
|
||||
Map<String, String> parseFormData(String? data) {
|
||||
// Return an empty map if the input is null or empty
|
||||
if (data == null || data.isEmpty) {
|
||||
return {};
|
||||
}
|
||||
// Split the input string into individual key-value pairs
|
||||
var pairs = data.split('&');
|
||||
|
||||
// Create a Map to store key-value pairs
|
||||
Map<String, String> result = {};
|
||||
|
||||
// Loop through the pairs and split them into keys and values
|
||||
for (var pair in pairs) {
|
||||
var keyValue = pair.split('=');
|
||||
|
||||
// Ensure the pair contains both key and value
|
||||
if (keyValue.length == 2) {
|
||||
var key = Uri.decodeComponent(keyValue[0]);
|
||||
var value = Uri.decodeComponent(keyValue[1]);
|
||||
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
@ -1,3 +1,4 @@
|
||||
export 'curl_io.dart';
|
||||
export 'postman_io.dart';
|
||||
export 'insomnia_io.dart';
|
||||
export 'har_io.dart';
|
||||
|
@ -11,16 +11,20 @@ environment:
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
better_networking:
|
||||
path: ../better_networking
|
||||
collection: ^1.18.0
|
||||
curl_parser:
|
||||
path: ../curl_parser
|
||||
freezed_annotation: ^2.4.1
|
||||
har:
|
||||
path: ../har
|
||||
insomnia_collection:
|
||||
path: ../insomnia_collection
|
||||
postman:
|
||||
path: ../postman
|
||||
better_networking:
|
||||
path: ../better_networking
|
||||
seed: ^0.0.3
|
||||
xml: ^6.3.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
@ -1,7 +1,9 @@
|
||||
# melos_managed_dependency_overrides: curl_parser,insomnia_collection,postman,seed
|
||||
# melos_managed_dependency_overrides: curl_parser,insomnia_collection,postman,seed,har
|
||||
dependency_overrides:
|
||||
curl_parser:
|
||||
path: ../curl_parser
|
||||
har:
|
||||
path: ../har
|
||||
insomnia_collection:
|
||||
path: ../insomnia_collection
|
||||
postman:
|
||||
|
@ -69,6 +69,11 @@ const kPh6b12 = EdgeInsets.only(
|
||||
right: 6.0,
|
||||
bottom: 12.0,
|
||||
);
|
||||
const kPh8b6 = EdgeInsets.only(
|
||||
left: 8.0,
|
||||
right: 8.0,
|
||||
bottom: 6.0,
|
||||
);
|
||||
const kPh60 = EdgeInsets.symmetric(horizontal: 60);
|
||||
const kPh60v60 = EdgeInsets.symmetric(vertical: 60, horizontal: 60);
|
||||
const kPt24l4 = EdgeInsets.only(
|
||||
@ -88,6 +93,7 @@ const kPt20 = EdgeInsets.only(top: 20);
|
||||
const kPt24 = EdgeInsets.only(top: 24);
|
||||
const kPt28 = EdgeInsets.only(top: 28);
|
||||
const kPt32 = EdgeInsets.only(top: 32);
|
||||
const kPb6 = EdgeInsets.only(bottom: 6);
|
||||
const kPb10 = EdgeInsets.only(bottom: 10);
|
||||
const kPb15 = EdgeInsets.only(bottom: 15);
|
||||
const kPb70 = EdgeInsets.only(bottom: 70);
|
||||
|
32
packages/har/.gitignore
vendored
Normal file
32
packages/har/.gitignore
vendored
Normal file
@ -0,0 +1,32 @@
|
||||
# Miscellaneous
|
||||
*.class
|
||||
*.log
|
||||
*.pyc
|
||||
*.swp
|
||||
.DS_Store
|
||||
.atom/
|
||||
.buildlog/
|
||||
.history
|
||||
.svn/
|
||||
migrate_working_dir/
|
||||
|
||||
# IntelliJ related
|
||||
*.iml
|
||||
*.ipr
|
||||
*.iws
|
||||
.idea/
|
||||
|
||||
# The .vscode folder contains launch configuration and tasks you configure in
|
||||
# VS Code which you may wish to be included in version control, so this line
|
||||
# is commented out by default.
|
||||
#.vscode/
|
||||
|
||||
# Flutter/Dart/Pub related
|
||||
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
|
||||
/pubspec.lock
|
||||
**/doc/api/
|
||||
.dart_tool/
|
||||
.flutter-plugins
|
||||
.flutter-plugins-dependencies
|
||||
build/
|
||||
coverage/
|
3
packages/har/CHANGELOG.md
Normal file
3
packages/har/CHANGELOG.md
Normal file
@ -0,0 +1,3 @@
|
||||
## 0.0.1
|
||||
|
||||
* TODO: Describe initial release.
|
201
packages/har/LICENSE
Normal file
201
packages/har/LICENSE
Normal file
@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2025 Ashita Prasad, Ankit Mahato
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
340
packages/har/README.md
Normal file
340
packages/har/README.md
Normal file
@ -0,0 +1,340 @@
|
||||
# har
|
||||
|
||||
Seamlessly convert Har Collection Format v1.2 to Dart.
|
||||
|
||||
Helps you bring your APIs stored in Har to Dart and work with them.
|
||||
|
||||
Currently, this package is being used by [API Dash](https://github.com/foss42/apidash), a beautiful open-source cross-platform (macOS, Windows, Linux, Android & iOS) API Client built using Flutter which can help you easily create & customize your API requests, visually inspect responses and generate API integration code. A lightweight alternative to postman.
|
||||
|
||||
## Usage
|
||||
|
||||
### Example 1: Har collection JSON string to Har model
|
||||
|
||||
```dart
|
||||
import 'package:har/har.dart';
|
||||
|
||||
void main() {
|
||||
// Example 1: Har collection JSON string to Har model
|
||||
var collectionJsonStr = r'''
|
||||
{
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {"name": "Client Name", "version": "v8.x.x"},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "code", "value": "US"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url":
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "num", "value": "8700000"},
|
||||
{"name": "digits", "value": "3"},
|
||||
{"name": "system", "value": "SS"},
|
||||
{"name": "add_space", "value": "true"},
|
||||
{"name": "trailing_zeros", "value": "true"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{"name": "User-Agent", "value": "Test Agent"}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "text", "value": "API", "contentType": "text/plain"},
|
||||
{"name": "sep", "value": "|", "contentType": "text/plain"},
|
||||
{"name": "times", "value": "3", "contentType": "text/plain"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "token", "value": "xyz", "contentType": "text/plain"},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
var collection = harLogFromJsonStr(collectionJsonStr);
|
||||
|
||||
print(collection.log?.creator);
|
||||
print(collection.log?.entries?[0].startedDateTime);
|
||||
print(collection.log?.entries?[0].request?.url);
|
||||
}
|
||||
```
|
||||
|
||||
### Example 2: Har collection from JSON
|
||||
|
||||
```dart
|
||||
import 'package:har/har.dart';
|
||||
|
||||
void main() {
|
||||
// Example 2: Har collection from JSON
|
||||
var collectionJson = {
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {"name": "Client Name", "version": "v8.x.x"},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "code", "value": "US"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url":
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "num", "value": "8700000"},
|
||||
{"name": "digits", "value": "3"},
|
||||
{"name": "system", "value": "SS"},
|
||||
{"name": "add_space", "value": "true"},
|
||||
{"name": "trailing_zeros", "value": "true"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{"name": "User-Agent", "value": "Test Agent"}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "text", "value": "API", "contentType": "text/plain"},
|
||||
{"name": "sep", "value": "|", "contentType": "text/plain"},
|
||||
{"name": "times", "value": "3", "contentType": "text/plain"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "token", "value": "xyz", "contentType": "text/plain"},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
var collection1 = HarLog.fromJson(collectionJson);
|
||||
print(collection1.log?.creator?.name);
|
||||
print(collection1.log?.entries?[0].startedDateTime);
|
||||
print(collection1.log?.entries?[0].request?.url);
|
||||
|
||||
}
|
||||
```
|
||||
|
||||
## Maintainer
|
||||
|
||||
- Ashita Prasad ([GitHub](https://github.com/ashitaprasad), [LinkedIn](https://www.linkedin.com/in/ashitaprasad/), [X](https://x.com/ashitaprasad))
|
||||
- Mohammed Ayaan (contributor) ([GitHub](https://github.com/ayaan-md-blr))
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [Apache License 2.0](https://github.com/foss42/apidash/blob/main/packages/har/LICENSE).
|
6
packages/har/analysis_options.yaml
Normal file
6
packages/har/analysis_options.yaml
Normal file
@ -0,0 +1,6 @@
|
||||
analyzer:
|
||||
exclude:
|
||||
- "**/*.g.dart"
|
||||
- "**/*.freezed.dart"
|
||||
errors:
|
||||
invalid_annotation_target: ignore
|
312
packages/har/example/har_example.dart
Normal file
312
packages/har/example/har_example.dart
Normal file
@ -0,0 +1,312 @@
|
||||
import 'package:har/har.dart';
|
||||
|
||||
void main() {
|
||||
//Example 1
|
||||
var collectionJsonStr = r'''
|
||||
{
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {
|
||||
"name": "Client Name",
|
||||
"version": "v8.x.x"
|
||||
},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{
|
||||
"name": "code",
|
||||
"value": "US"
|
||||
}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{ "name": "num", "value": "8700000" },
|
||||
{ "name": "digits", "value": "3" },
|
||||
{ "name": "system", "value": "SS" },
|
||||
{ "name": "add_space", "value": "true" },
|
||||
{ "name": "trailing_zeros", "value": "true" }
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{
|
||||
"name": "User-Agent",
|
||||
"value": "Test Agent"
|
||||
}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{ "name": "text", "value": "API", "contentType":"text/plain" },
|
||||
{ "name": "sep", "value": "|", "contentType":"text/plain" },
|
||||
{ "name": "times", "value": "3", "contentType":"text/plain" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
,
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{ "name": "token", "value": "xyz", "contentType":"text/plain" },
|
||||
{ "name": "imfile", "fileName": "hire AI.jpeg", "contentType":"image/jpeg" }
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
var collection = harLogFromJsonStr(collectionJsonStr);
|
||||
|
||||
print(collection.log?.creator);
|
||||
print(collection.log?.entries?[0].startedDateTime);
|
||||
print(collection.log?.entries?[0].request?.url);
|
||||
|
||||
var collectionJson = {
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {"name": "Client Name", "version": "v8.x.x"},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "code", "value": "US"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url":
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "num", "value": "8700000"},
|
||||
{"name": "digits", "value": "3"},
|
||||
{"name": "system", "value": "SS"},
|
||||
{"name": "add_space", "value": "true"},
|
||||
{"name": "trailing_zeros", "value": "true"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{"name": "User-Agent", "value": "Test Agent"}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "text", "value": "API", "contentType": "text/plain"},
|
||||
{"name": "sep", "value": "|", "contentType": "text/plain"},
|
||||
{"name": "times", "value": "3", "contentType": "text/plain"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "token", "value": "xyz", "contentType": "text/plain"},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
var collection1 = HarLog.fromJson(collectionJson);
|
||||
print(collection1.log?.creator?.name);
|
||||
print(collection1.log?.entries?[0].startedDateTime);
|
||||
print(collection1.log?.entries?[0].request?.url);
|
||||
}
|
4
packages/har/lib/har.dart
Normal file
4
packages/har/lib/har.dart
Normal file
@ -0,0 +1,4 @@
|
||||
library har;
|
||||
|
||||
export 'models/models.dart';
|
||||
export 'utils/har_utils.dart';
|
174
packages/har/lib/models/har_log.dart
Normal file
174
packages/har/lib/models/har_log.dart
Normal file
@ -0,0 +1,174 @@
|
||||
import 'dart:convert';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'har_log.freezed.dart';
|
||||
part 'har_log.g.dart';
|
||||
|
||||
HarLog harLogFromJsonStr(String str) => HarLog.fromJson(json.decode(str));
|
||||
|
||||
String harLogToJsonStr(HarLog data) =>
|
||||
JsonEncoder.withIndent(' ').convert(data);
|
||||
|
||||
@freezed
|
||||
class HarLog with _$HarLog {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory HarLog({
|
||||
Log? log,
|
||||
}) = _HarLog;
|
||||
|
||||
factory HarLog.fromJson(Map<String, dynamic> json) => _$HarLogFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Log with _$Log {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Log({
|
||||
String? version,
|
||||
Creator? creator,
|
||||
List<Entry>? entries,
|
||||
}) = _Log;
|
||||
|
||||
factory Log.fromJson(Map<String, dynamic> json) => _$LogFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Creator with _$Creator {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Creator({
|
||||
String? name,
|
||||
String? version,
|
||||
}) = _Creator;
|
||||
|
||||
factory Creator.fromJson(Map<String, dynamic> json) =>
|
||||
_$CreatorFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Entry with _$Entry {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Entry({
|
||||
String? startedDateTime,
|
||||
int? time,
|
||||
Request? request,
|
||||
Response? response,
|
||||
}) = _Entry;
|
||||
|
||||
factory Entry.fromJson(Map<String, dynamic> json) => _$EntryFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Request with _$Request {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Request({
|
||||
String? method,
|
||||
String? url,
|
||||
String? httpVersion,
|
||||
List<dynamic>? cookies,
|
||||
List<Header>? headers,
|
||||
List<Query>? queryString,
|
||||
PostData? postData,
|
||||
int? headersSize,
|
||||
int? bodySize,
|
||||
}) = _Request;
|
||||
|
||||
factory Request.fromJson(Map<String, dynamic> json) =>
|
||||
_$RequestFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class PostData with _$PostData {
|
||||
@JsonSerializable(
|
||||
explicitToJson: true,
|
||||
anyMap: true,
|
||||
includeIfNull: false,
|
||||
)
|
||||
const factory PostData({
|
||||
String? mimeType,
|
||||
String? text,
|
||||
List<Param>? params, // for multipart/form-data params
|
||||
}) = _PostData;
|
||||
|
||||
factory PostData.fromJson(Map<String, dynamic> json) =>
|
||||
_$PostDataFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Param with _$Param {
|
||||
@JsonSerializable(
|
||||
explicitToJson: true,
|
||||
anyMap: true,
|
||||
includeIfNull: false,
|
||||
)
|
||||
const factory Param({
|
||||
String? name,
|
||||
String? value,
|
||||
String? fileName,
|
||||
String? contentType,
|
||||
bool? disabled,
|
||||
}) = _Param;
|
||||
|
||||
factory Param.fromJson(Map<String, dynamic> json) => _$ParamFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Query with _$Query {
|
||||
@JsonSerializable(
|
||||
explicitToJson: true,
|
||||
anyMap: true,
|
||||
includeIfNull: false,
|
||||
)
|
||||
const factory Query({
|
||||
String? name,
|
||||
String? value,
|
||||
bool? disabled,
|
||||
}) = _Query;
|
||||
|
||||
factory Query.fromJson(Map<String, dynamic> json) => _$QueryFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Header with _$Header {
|
||||
@JsonSerializable(
|
||||
explicitToJson: true,
|
||||
anyMap: true,
|
||||
includeIfNull: false,
|
||||
)
|
||||
const factory Header({
|
||||
String? name,
|
||||
String? value,
|
||||
bool? disabled,
|
||||
}) = _Header;
|
||||
|
||||
factory Header.fromJson(Map<String, dynamic> json) => _$HeaderFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Response with _$Response {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Response({
|
||||
int? status,
|
||||
String? statusText,
|
||||
String? httpVersion,
|
||||
List<dynamic>? cookies,
|
||||
List<dynamic>? headers,
|
||||
Content? content,
|
||||
String? redirectURL,
|
||||
int? headersSize,
|
||||
int? bodySize,
|
||||
}) = _Response;
|
||||
|
||||
factory Response.fromJson(Map<String, dynamic> json) =>
|
||||
_$ResponseFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
class Content with _$Content {
|
||||
@JsonSerializable(explicitToJson: true, anyMap: true, includeIfNull: false)
|
||||
const factory Content({
|
||||
int? size,
|
||||
String? mimeType,
|
||||
}) = _Content;
|
||||
|
||||
factory Content.fromJson(Map<String, dynamic> json) =>
|
||||
_$ContentFromJson(json);
|
||||
}
|
2482
packages/har/lib/models/har_log.freezed.dart
Normal file
2482
packages/har/lib/models/har_log.freezed.dart
Normal file
File diff suppressed because it is too large
Load Diff
198
packages/har/lib/models/har_log.g.dart
Normal file
198
packages/har/lib/models/har_log.g.dart
Normal file
@ -0,0 +1,198 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'har_log.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_$HarLogImpl _$$HarLogImplFromJson(Map json) => _$HarLogImpl(
|
||||
log: json['log'] == null
|
||||
? null
|
||||
: Log.fromJson(Map<String, dynamic>.from(json['log'] as Map)),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$HarLogImplToJson(_$HarLogImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.log?.toJson() case final value?) 'log': value,
|
||||
};
|
||||
|
||||
_$LogImpl _$$LogImplFromJson(Map json) => _$LogImpl(
|
||||
version: json['version'] as String?,
|
||||
creator: json['creator'] == null
|
||||
? null
|
||||
: Creator.fromJson(Map<String, dynamic>.from(json['creator'] as Map)),
|
||||
entries: (json['entries'] as List<dynamic>?)
|
||||
?.map((e) => Entry.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$LogImplToJson(_$LogImpl instance) => <String, dynamic>{
|
||||
if (instance.version case final value?) 'version': value,
|
||||
if (instance.creator?.toJson() case final value?) 'creator': value,
|
||||
if (instance.entries?.map((e) => e.toJson()).toList() case final value?)
|
||||
'entries': value,
|
||||
};
|
||||
|
||||
_$CreatorImpl _$$CreatorImplFromJson(Map json) => _$CreatorImpl(
|
||||
name: json['name'] as String?,
|
||||
version: json['version'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$CreatorImplToJson(_$CreatorImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.name case final value?) 'name': value,
|
||||
if (instance.version case final value?) 'version': value,
|
||||
};
|
||||
|
||||
_$EntryImpl _$$EntryImplFromJson(Map json) => _$EntryImpl(
|
||||
startedDateTime: json['startedDateTime'] as String?,
|
||||
time: (json['time'] as num?)?.toInt(),
|
||||
request: json['request'] == null
|
||||
? null
|
||||
: Request.fromJson(Map<String, dynamic>.from(json['request'] as Map)),
|
||||
response: json['response'] == null
|
||||
? null
|
||||
: Response.fromJson(
|
||||
Map<String, dynamic>.from(json['response'] as Map)),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$EntryImplToJson(_$EntryImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.startedDateTime case final value?) 'startedDateTime': value,
|
||||
if (instance.time case final value?) 'time': value,
|
||||
if (instance.request?.toJson() case final value?) 'request': value,
|
||||
if (instance.response?.toJson() case final value?) 'response': value,
|
||||
};
|
||||
|
||||
_$RequestImpl _$$RequestImplFromJson(Map json) => _$RequestImpl(
|
||||
method: json['method'] as String?,
|
||||
url: json['url'] as String?,
|
||||
httpVersion: json['httpVersion'] as String?,
|
||||
cookies: json['cookies'] as List<dynamic>?,
|
||||
headers: (json['headers'] as List<dynamic>?)
|
||||
?.map((e) => Header.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
queryString: (json['queryString'] as List<dynamic>?)
|
||||
?.map((e) => Query.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
postData: json['postData'] == null
|
||||
? null
|
||||
: PostData.fromJson(
|
||||
Map<String, dynamic>.from(json['postData'] as Map)),
|
||||
headersSize: (json['headersSize'] as num?)?.toInt(),
|
||||
bodySize: (json['bodySize'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$RequestImplToJson(_$RequestImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.method case final value?) 'method': value,
|
||||
if (instance.url case final value?) 'url': value,
|
||||
if (instance.httpVersion case final value?) 'httpVersion': value,
|
||||
if (instance.cookies case final value?) 'cookies': value,
|
||||
if (instance.headers?.map((e) => e.toJson()).toList() case final value?)
|
||||
'headers': value,
|
||||
if (instance.queryString?.map((e) => e.toJson()).toList()
|
||||
case final value?)
|
||||
'queryString': value,
|
||||
if (instance.postData?.toJson() case final value?) 'postData': value,
|
||||
if (instance.headersSize case final value?) 'headersSize': value,
|
||||
if (instance.bodySize case final value?) 'bodySize': value,
|
||||
};
|
||||
|
||||
_$PostDataImpl _$$PostDataImplFromJson(Map json) => _$PostDataImpl(
|
||||
mimeType: json['mimeType'] as String?,
|
||||
text: json['text'] as String?,
|
||||
params: (json['params'] as List<dynamic>?)
|
||||
?.map((e) => Param.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$PostDataImplToJson(_$PostDataImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.mimeType case final value?) 'mimeType': value,
|
||||
if (instance.text case final value?) 'text': value,
|
||||
if (instance.params?.map((e) => e.toJson()).toList() case final value?)
|
||||
'params': value,
|
||||
};
|
||||
|
||||
_$ParamImpl _$$ParamImplFromJson(Map json) => _$ParamImpl(
|
||||
name: json['name'] as String?,
|
||||
value: json['value'] as String?,
|
||||
fileName: json['fileName'] as String?,
|
||||
contentType: json['contentType'] as String?,
|
||||
disabled: json['disabled'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$ParamImplToJson(_$ParamImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.name case final value?) 'name': value,
|
||||
if (instance.value case final value?) 'value': value,
|
||||
if (instance.fileName case final value?) 'fileName': value,
|
||||
if (instance.contentType case final value?) 'contentType': value,
|
||||
if (instance.disabled case final value?) 'disabled': value,
|
||||
};
|
||||
|
||||
_$QueryImpl _$$QueryImplFromJson(Map json) => _$QueryImpl(
|
||||
name: json['name'] as String?,
|
||||
value: json['value'] as String?,
|
||||
disabled: json['disabled'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$QueryImplToJson(_$QueryImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.name case final value?) 'name': value,
|
||||
if (instance.value case final value?) 'value': value,
|
||||
if (instance.disabled case final value?) 'disabled': value,
|
||||
};
|
||||
|
||||
_$HeaderImpl _$$HeaderImplFromJson(Map json) => _$HeaderImpl(
|
||||
name: json['name'] as String?,
|
||||
value: json['value'] as String?,
|
||||
disabled: json['disabled'] as bool?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$HeaderImplToJson(_$HeaderImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.name case final value?) 'name': value,
|
||||
if (instance.value case final value?) 'value': value,
|
||||
if (instance.disabled case final value?) 'disabled': value,
|
||||
};
|
||||
|
||||
_$ResponseImpl _$$ResponseImplFromJson(Map json) => _$ResponseImpl(
|
||||
status: (json['status'] as num?)?.toInt(),
|
||||
statusText: json['statusText'] as String?,
|
||||
httpVersion: json['httpVersion'] as String?,
|
||||
cookies: json['cookies'] as List<dynamic>?,
|
||||
headers: json['headers'] as List<dynamic>?,
|
||||
content: json['content'] == null
|
||||
? null
|
||||
: Content.fromJson(Map<String, dynamic>.from(json['content'] as Map)),
|
||||
redirectURL: json['redirectURL'] as String?,
|
||||
headersSize: (json['headersSize'] as num?)?.toInt(),
|
||||
bodySize: (json['bodySize'] as num?)?.toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$ResponseImplToJson(_$ResponseImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.status case final value?) 'status': value,
|
||||
if (instance.statusText case final value?) 'statusText': value,
|
||||
if (instance.httpVersion case final value?) 'httpVersion': value,
|
||||
if (instance.cookies case final value?) 'cookies': value,
|
||||
if (instance.headers case final value?) 'headers': value,
|
||||
if (instance.content?.toJson() case final value?) 'content': value,
|
||||
if (instance.redirectURL case final value?) 'redirectURL': value,
|
||||
if (instance.headersSize case final value?) 'headersSize': value,
|
||||
if (instance.bodySize case final value?) 'bodySize': value,
|
||||
};
|
||||
|
||||
_$ContentImpl _$$ContentImplFromJson(Map json) => _$ContentImpl(
|
||||
size: (json['size'] as num?)?.toInt(),
|
||||
mimeType: json['mimeType'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$$ContentImplToJson(_$ContentImpl instance) =>
|
||||
<String, dynamic>{
|
||||
if (instance.size case final value?) 'size': value,
|
||||
if (instance.mimeType case final value?) 'mimeType': value,
|
||||
};
|
1
packages/har/lib/models/models.dart
Normal file
1
packages/har/lib/models/models.dart
Normal file
@ -0,0 +1 @@
|
||||
export 'har_log.dart';
|
24
packages/har/lib/utils/har_utils.dart
Normal file
24
packages/har/lib/utils/har_utils.dart
Normal file
@ -0,0 +1,24 @@
|
||||
import '../models/har_log.dart';
|
||||
|
||||
List<(String?, Request)> getRequestsFromHarLog(HarLog? hl) {
|
||||
if (hl == null || hl.log == null || hl.log?.entries == null) {
|
||||
return [];
|
||||
}
|
||||
List<(String?, Request)> requests = [];
|
||||
if (hl.log?.entries?.isNotEmpty ?? false)
|
||||
for (var entry in hl.log!.entries!) {
|
||||
requests.addAll(getRequestsFromHarLogEntry(entry));
|
||||
}
|
||||
return requests;
|
||||
}
|
||||
|
||||
List<(String?, Request)> getRequestsFromHarLogEntry(Entry? entry) {
|
||||
if (entry == null) {
|
||||
return [];
|
||||
}
|
||||
List<(String?, Request)> requests = [];
|
||||
if (entry.request != null) {
|
||||
requests.add((entry.startedDateTime, entry.request!));
|
||||
}
|
||||
return requests;
|
||||
}
|
25
packages/har/pubspec.yaml
Normal file
25
packages/har/pubspec.yaml
Normal file
@ -0,0 +1,25 @@
|
||||
name: har
|
||||
description: "Seamlessly convert har Format to Dart and vice versa."
|
||||
version: 0.0.1
|
||||
homepage: https://github.com/foss42/apidash
|
||||
|
||||
topics:
|
||||
- har
|
||||
- api
|
||||
- rest
|
||||
- http
|
||||
- network
|
||||
|
||||
environment:
|
||||
sdk: ">=3.0.0 <4.0.0"
|
||||
|
||||
dependencies:
|
||||
freezed_annotation: ^2.4.4
|
||||
json_annotation: ^4.9.0
|
||||
|
||||
dev_dependencies:
|
||||
build_runner: ^2.4.12
|
||||
freezed: ^2.5.7
|
||||
json_serializable: ^6.7.1
|
||||
lints: ^4.0.0
|
||||
test: ^1.24.0
|
329
packages/har/test/collection_examples/collection_apidash.dart
Normal file
329
packages/har/test/collection_examples/collection_apidash.dart
Normal file
@ -0,0 +1,329 @@
|
||||
var collectionJsonStr = r'''
|
||||
{
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {
|
||||
"name": "Client Name",
|
||||
"version": "v8.x.x"
|
||||
},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{
|
||||
"name": "code",
|
||||
"value": "US"
|
||||
}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{
|
||||
"name": "num",
|
||||
"value": "8700000"
|
||||
},
|
||||
{
|
||||
"name": "digits",
|
||||
"value": "3"
|
||||
},
|
||||
{
|
||||
"name": "system",
|
||||
"value": "SS"
|
||||
},
|
||||
{
|
||||
"name": "add_space",
|
||||
"value": "true"
|
||||
},
|
||||
{
|
||||
"name": "trailing_zeros",
|
||||
"value": "true"
|
||||
}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
},
|
||||
"bodySize": 50
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{
|
||||
"name": "User-Agent",
|
||||
"value": "Test Agent"
|
||||
}
|
||||
],
|
||||
"queryString": [],
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{
|
||||
"name": "text",
|
||||
"value": "API",
|
||||
"contentType": "text/plain"
|
||||
},
|
||||
{
|
||||
"name": "sep",
|
||||
"value": "|",
|
||||
"contentType": "text/plain"
|
||||
},
|
||||
{
|
||||
"name": "times",
|
||||
"value": "3",
|
||||
"contentType": "text/plain"
|
||||
}
|
||||
]
|
||||
},
|
||||
"bodySize": 100
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{
|
||||
"name": "token",
|
||||
"value": "xyz",
|
||||
"contentType": "text/plain"
|
||||
},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
},
|
||||
"bodySize": 150
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}''';
|
||||
|
||||
var collectionJson = {
|
||||
"log": {
|
||||
"version": "1.2",
|
||||
"creator": {"name": "Client Name", "version": "v8.x.x"},
|
||||
"entries": [
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:00:00.000Z",
|
||||
"time": 100,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:01:00.000Z",
|
||||
"time": 150,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url": "https://api.apidash.dev/country/data?code=US",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "code", "value": "US"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:02:00.000Z",
|
||||
"time": 200,
|
||||
"request": {
|
||||
"method": "GET",
|
||||
"url":
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
"headers": [],
|
||||
"queryString": [
|
||||
{"name": "num", "value": "8700000"},
|
||||
{"name": "digits", "value": "3"},
|
||||
{"name": "system", "value": "SS"},
|
||||
{"name": "add_space", "value": "true"},
|
||||
{"name": "trailing_zeros", "value": "true"}
|
||||
],
|
||||
"bodySize": 0
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:03:00.000Z",
|
||||
"time": 300,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/case/lower",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 50,
|
||||
"postData": {
|
||||
"mimeType": "application/json",
|
||||
"text": "{ \"text\": \"I LOVE Flutter\" }"
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:04:00.000Z",
|
||||
"time": 350,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/form",
|
||||
"headers": [
|
||||
{"name": "User-Agent", "value": "Test Agent"}
|
||||
],
|
||||
"queryString": [],
|
||||
"bodySize": 100,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "text", "value": "API", "contentType": "text/plain"},
|
||||
{"name": "sep", "value": "|", "contentType": "text/plain"},
|
||||
{"name": "times", "value": "3", "contentType": "text/plain"}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"startedDateTime": "2025-03-25T12:05:00.000Z",
|
||||
"time": 400,
|
||||
"request": {
|
||||
"method": "POST",
|
||||
"url": "https://api.apidash.dev/io/img",
|
||||
"headers": [],
|
||||
"queryString": [],
|
||||
"bodySize": 150,
|
||||
"postData": {
|
||||
"mimeType": "multipart/form-data",
|
||||
"params": [
|
||||
{"name": "token", "value": "xyz", "contentType": "text/plain"},
|
||||
{
|
||||
"name": "imfile",
|
||||
"fileName": "hire AI.jpeg",
|
||||
"contentType": "image/jpeg"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"response": {
|
||||
"status": 200,
|
||||
"statusText": "OK",
|
||||
"headers": [],
|
||||
"bodySize": 0
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
25
packages/har/test/har_test.dart
Normal file
25
packages/har/test/har_test.dart
Normal file
@ -0,0 +1,25 @@
|
||||
import 'package:har/har.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'collection_examples/collection_apidash.dart';
|
||||
import 'models/collection_apidash_model.dart';
|
||||
|
||||
void main() {
|
||||
group('Har tests', () {
|
||||
test('API Dash Har Requests from Json String', () {
|
||||
expect(harLogFromJsonStr(collectionJsonStr), collectionApiDashModel);
|
||||
});
|
||||
|
||||
test('API Dash Har Requests from Json', () {
|
||||
expect(HarLog.fromJson(collectionJson), collectionApiDashModel);
|
||||
});
|
||||
|
||||
test('API Dash Har Requests to Json String', () {
|
||||
expect(harLogToJsonStr(collectionApiDashModel), collectionJsonStr);
|
||||
});
|
||||
|
||||
test('API Dash Har Requests to Json', () {
|
||||
expect(collectionApiDashModel.toJson(), collectionJson);
|
||||
});
|
||||
});
|
||||
}
|
212
packages/har/test/models/collection_apidash_model.dart
Normal file
212
packages/har/test/models/collection_apidash_model.dart
Normal file
@ -0,0 +1,212 @@
|
||||
import 'package:har/models/models.dart';
|
||||
|
||||
var collectionApiDashModel = HarLog(
|
||||
log: Log(
|
||||
version: "1.2",
|
||||
creator: Creator(name: "Client Name", version: "v8.x.x"),
|
||||
entries: [
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:00:00.000Z",
|
||||
time: 100,
|
||||
request: Request(
|
||||
method: "GET",
|
||||
url: "https://api.apidash.dev",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
queryString: [],
|
||||
postData: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:01:00.000Z",
|
||||
time: 150,
|
||||
request: Request(
|
||||
method: "GET",
|
||||
url: "https://api.apidash.dev/country/data?code=US",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
queryString: [Query(name: "code", value: "US", disabled: null)],
|
||||
postData: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:02:00.000Z",
|
||||
time: 200,
|
||||
request: Request(
|
||||
method: "GET",
|
||||
url:
|
||||
"https://api.apidash.dev/humanize/social?num=8700000&digits=3&system=SS&add_space=true&trailing_zeros=true",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
queryString: [
|
||||
Query(name: "num", value: "8700000", disabled: null),
|
||||
Query(name: "digits", value: "3", disabled: null),
|
||||
Query(name: "system", value: "SS", disabled: null),
|
||||
Query(name: "add_space", value: "true", disabled: null),
|
||||
Query(name: "trailing_zeros", value: "true", disabled: null)
|
||||
],
|
||||
postData: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:03:00.000Z",
|
||||
time: 300,
|
||||
request: Request(
|
||||
method: "POST",
|
||||
url: "https://api.apidash.dev/case/lower",
|
||||
headers: [],
|
||||
queryString: [],
|
||||
postData: PostData(
|
||||
mimeType: "application/json",
|
||||
text: '{ "text": "I LOVE Flutter" }',
|
||||
params: null,
|
||||
),
|
||||
bodySize: 50,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:04:00.000Z",
|
||||
time: 350,
|
||||
request: Request(
|
||||
method: "POST",
|
||||
url: "https://api.apidash.dev/io/form",
|
||||
headers: [
|
||||
Header(name: "User-Agent", value: "Test Agent", disabled: null)
|
||||
],
|
||||
queryString: [],
|
||||
bodySize: 100,
|
||||
postData: PostData(
|
||||
mimeType: "multipart/form-data",
|
||||
params: [
|
||||
Param(
|
||||
name: "text",
|
||||
value: "API",
|
||||
fileName: null,
|
||||
contentType: "text/plain",
|
||||
disabled: null),
|
||||
Param(
|
||||
name: "sep",
|
||||
value: "|",
|
||||
fileName: null,
|
||||
contentType: "text/plain",
|
||||
disabled: null),
|
||||
Param(
|
||||
name: "times",
|
||||
value: "3",
|
||||
fileName: null,
|
||||
contentType: "text/plain",
|
||||
disabled: null)
|
||||
],
|
||||
),
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
Entry(
|
||||
startedDateTime: "2025-03-25T12:05:00.000Z",
|
||||
time: 400,
|
||||
request: Request(
|
||||
method: "POST",
|
||||
url: "https://api.apidash.dev/io/img",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
queryString: [],
|
||||
postData: PostData(
|
||||
mimeType: "multipart/form-data",
|
||||
text: null,
|
||||
params: [
|
||||
Param(
|
||||
name: "token",
|
||||
value: "xyz",
|
||||
fileName: null,
|
||||
contentType: "text/plain",
|
||||
disabled: null),
|
||||
Param(
|
||||
name: "imfile",
|
||||
value: null,
|
||||
fileName: "hire AI.jpeg",
|
||||
contentType: "image/jpeg",
|
||||
disabled: null)
|
||||
],
|
||||
),
|
||||
headersSize: null,
|
||||
bodySize: 150,
|
||||
),
|
||||
response: Response(
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
httpVersion: null,
|
||||
cookies: null,
|
||||
headers: [],
|
||||
content: null,
|
||||
redirectURL: null,
|
||||
headersSize: null,
|
||||
bodySize: 0,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
71
pubspec.lock
71
pubspec.lock
@ -79,6 +79,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.1.25"
|
||||
autotrie:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: autotrie
|
||||
sha256: "55da6faefb53cfcb0abb2f2ca8636123fb40e35286bb57440d2cf467568188f8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.0"
|
||||
barcode:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -530,11 +538,27 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_code_editor:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_code_editor
|
||||
sha256: "18cc1200e7481fcf144bc970fdec4e75b83e3f523da60bbf55810a4e8dd6f5fb"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.3"
|
||||
flutter_driver:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_highlight:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_highlight
|
||||
sha256: "7b96333867aa07e122e245c033b8ad622e4e3a42a1a2372cbb098a2541d8782c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.0"
|
||||
flutter_highlighter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@ -551,6 +575,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.21.2"
|
||||
flutter_js:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: flutter_js
|
||||
sha256: "6b777cd4e468546f046a2f114d078a4596143269f6fa6bad5c29611d5b896369"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.8.2"
|
||||
flutter_launcher_icons:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@ -678,6 +710,21 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
har:
|
||||
dependency: transitive
|
||||
description:
|
||||
path: "packages/har"
|
||||
relative: true
|
||||
source: path
|
||||
version: "0.0.1"
|
||||
highlight:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: highlight
|
||||
sha256: "5353a83ffe3e3eca7df0abfb72dcf3fa66cc56b953728e7113ad4ad88497cf21"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.0"
|
||||
highlighter:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@ -920,6 +967,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.1"
|
||||
linked_scroll_controller:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: linked_scroll_controller
|
||||
sha256: e6020062bcf4ffc907ee7fd090fa971e65d8dfaac3c62baf601a3ced0b37986a
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.2.0"
|
||||
lints:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -1000,6 +1055,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.0"
|
||||
mocktail:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: mocktail
|
||||
sha256: "890df3f9688106f25755f26b1c60589a92b3ab91a22b8b224947ad041bf172d8"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.4"
|
||||
mpv_dart:
|
||||
dependency: transitive
|
||||
description:
|
||||
@ -1643,6 +1706,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.2"
|
||||
tuple:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: tuple
|
||||
sha256: a97ce2013f240b2f3807bcbaf218765b6f301c3eff91092bcfa23a039e7dd151
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.2"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
@ -23,13 +23,17 @@ dependencies:
|
||||
extended_text_field: ^16.0.0
|
||||
file_selector: ^1.0.3
|
||||
flex_color_scheme: ^8.2.0
|
||||
flutter_code_editor: ^0.3.3
|
||||
flutter_highlight: ^0.7.0
|
||||
flutter_highlighter: ^0.1.0
|
||||
flutter_hooks: ^0.21.2
|
||||
flutter_js: ^0.8.2
|
||||
flutter_markdown: ^0.7.6+2
|
||||
flutter_portal: ^1.1.4
|
||||
flutter_riverpod: ^2.5.1
|
||||
flutter_svg: ^2.0.17
|
||||
fvp: ^0.30.0
|
||||
highlight: ^0.7.0
|
||||
highlighter: ^0.1.1
|
||||
hive_flutter: ^1.1.0
|
||||
hooks_riverpod: ^2.5.2
|
||||
|
@ -58,6 +58,8 @@ final Map<String, dynamic> historyRequestModelJson1 = {
|
||||
"metaData": historyMetaModelJson1,
|
||||
"httpRequestModel": httpRequestModelGet4Json,
|
||||
"httpResponseModel": responseModelJson,
|
||||
'preRequestScript': null,
|
||||
'postRequestScript': null
|
||||
};
|
||||
|
||||
final Map<String, dynamic> historyMetaModelJson2 = {
|
||||
|
@ -217,6 +217,8 @@ Map<String, dynamic> requestModelJson = {
|
||||
'responseStatus': 200,
|
||||
'message': null,
|
||||
'httpResponseModel': responseModelJson,
|
||||
'preRequestScript': null,
|
||||
'postRequestScript': null
|
||||
};
|
||||
|
||||
/// Basic GET request model for apidash.dev
|
||||
|
Reference in New Issue
Block a user