@http-forge/core 0.6.10 → 0.6.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -14,10 +14,9 @@
14
14
  - 📝 **JavaScript Scripting** - Pre-request and post-response scripts with full `pm.*` API (variables, assertions, execution flow, visualizer)
15
15
  - 🔄 **Dynamic Variables** - Built-in generators: `{{$randomInt}}`, `{{$timestamp}}`, `{{$uuid}}`, `{{$guid}}`, etc.
16
16
  - 🌍 **Environments** - Full variable scoping (globals, collection, environment, session, iterationData)
17
- - � **Cloud Secret Resolvers** - Resolve `{{secret:alias/path}}` from AWS Secrets Manager, Azure Key Vault, Google Secret Manager, HashiCorp Vault, 1Password, and Doppler; credentials read from the ambient environment, never from config
18
- - �👁️ **File Watching** - Automatic reload on collection/environment file changes with notification callbacks
17
+ - 👁️ **File Watching** - Automatic reload on collection/environment file changes with notification callbacks
19
18
  - 🍪 **Cookie Persistence** - Automatic cookie storage and reuse, `pm.cookies.jar()` and `.toObject()`
20
- - 📊 **Test Assertions** - BDD-style testing with `pm.test()` (sync/async), `pm.test.skip()` / `.fail()` / `.index()`, full Chai `expect()` chains (incl. `.contain()`), and JSON Schema validation via `pm.response.to.have.jsonSchema()`
19
+ - 📊 **Test Assertions** - BDD-style testing with `pm.test()` (sync/async) and full Chai `expect()` chains
21
20
  - 🔐 **CryptoJS** - Full crypto library: hash, HMAC, AES/DES/TripleDES, PBKDF2, encoding helpers
22
21
  - 🎯 **Execution Flow** - `pm.setNextRequest()`, `pm.execution.skipRequest()` for suite runner flow control
23
22
  - 📈 **Visualizer** - `pm.visualizer.set(template, data)` for custom Handlebars-based HTML output
@@ -43,129 +42,7 @@ Or using the tarball:
43
42
  npm install ./http-forge-core-0.1.0.tgz
44
43
  ```
45
44
 
46
- ## Runtime APIs (Headless + MCP)
47
-
48
- For current programmatic runtime APIs, see [RUNTIME-API.md](RUNTIME-API.md):
49
- - `runRequest(options)`
50
- - `runCollection(options)`
51
- - `runSuite(options)`
52
- - `createMcpRuntime(options)`
53
-
54
- This covers direct execution, embeddable MCP runtime lifecycle, response include options, and report behavior.
55
-
56
- ---
57
-
58
- ## 🤖 AI & Analysis APIs
59
-
60
- All AI features use the `IAiProvider` abstraction — bring any LLM (GitHub Copilot, OpenAI, Anthropic) without changing the core logic.
61
-
62
- ### `IAiProvider`
63
-
64
- ```typescript
65
- interface IAiProvider {
66
- complete(prompt: string): Promise<string>;
67
- }
68
- ```
69
-
70
- Implement this interface for any LLM backend. The package ships no concrete provider — callers supply one:
71
-
72
- | Package | Provider class |
73
- |---|---|
74
- | `http-forge` (VS Code extension) | `CopilotAiProvider` (wraps `vscode.lm`) |
75
- | `@http-forge/cli` | `OpenAiProvider`, `AnthropicProvider`, `createCliAiProvider()` |
76
-
77
- ### `enhanceCollection`
78
-
79
- Enhance a collection with AI-written example bodies and `pm.test()` assertion scripts.
80
-
81
- ```typescript
82
- import { enhanceCollection } from '@http-forge/core';
83
-
84
- await enhanceCollection(
85
- collection, // Collection to enhance
86
- collectionService, // ICollectionService
87
- aiProvider, // IAiProvider
88
- (msg, increment) => console.log(msg) // optional progress callback
89
- );
90
- ```
91
-
92
- Processes requests in batches of 10. Saves after each batch. Skips requests that already have a body and test script.
93
-
94
- ### `scanCollectionForEnvVarsWithAi`
95
-
96
- AI-powered scan for hardcoded values (API keys, tokens, base URLs, tenant IDs).
97
-
98
- ```typescript
99
- import { scanCollectionForEnvVarsWithAi } from '@http-forge/core';
100
-
101
- const suggestions = await scanCollectionForEnvVarsWithAi(collection, aiProvider);
102
- // Returns EnvSuggestion[] — same shape as detectEnvSuggestions,
103
- // so applyEnvSuggestionsToItems works for both.
104
- ```
105
-
106
- Returns `EnvSuggestion[]` sorted by occurrence count descending.
107
-
108
- ### `detectEnvSuggestions` (heuristic, no LLM)
109
-
110
- Rule-based detection — no AI dependency. Flags `Authorization` headers, common sensitive header/query names, shared base URLs, and long opaque strings.
111
-
112
- ```typescript
113
- import { detectEnvSuggestions, applyEnvSuggestionsToItems } from '@http-forge/core';
114
-
115
- const suggestions = detectEnvSuggestions(collection, /* minOccurrences */ 1);
116
- const counts = applyEnvSuggestionsToItems(collection.items, suggestions);
117
- await collectionService.saveCollection(collection);
118
- ```
119
-
120
- ### `parseCurlCommand`
121
-
122
- Parse a shell curl command string into a `ParsedCurlRequest` object ready to persist as a collection request.
123
-
124
- ```typescript
125
- import { parseCurlCommand } from '@http-forge/core';
126
-
127
- const parsed = parseCurlCommand(
128
- `curl -X POST https://api.example.com/users ` +
129
- `-H 'Authorization: Bearer sk-abc123' ` +
130
- `-d '{"name":"Alice"}'`
131
- );
132
- // parsed.name, .method, .url, .headers, .queryParams, .body, .suggestedVars
133
- ```
134
-
135
- `suggestedVars` contains heuristically-detected values that should become environment variables (e.g. the Bearer token above).
136
-
137
- ---
138
-
139
- ## 🔌 MCP Tools — AI Agent Integration
140
-
141
- When the MCP server is running, AI agents (Claude, Copilot, etc.) can call these tools in addition to the standard run/inspect tools:
142
-
143
- ### Agentic AI tools (no LLM config needed)
144
-
145
- These tools use the **calling AI as the analysis engine** — no API keys required on the server side.
146
-
147
- | Tool | Description |
148
- |---|---|
149
- | `ai_suggest_env_vars` | Returns request data + instructions; AI finds hardcoded values and calls `apply_env_vars`. One-shot. |
150
- | `ai_enhance_collection` | Returns paginated requests + instructions; AI writes bodies and test scripts and calls `apply_request_enhancements`. Self-continues. |
151
- | `ai_analyze_coverage` | Returns coverage gaps + instructions; AI calls `ai_enhance_collection` for unasserted requests and `generate_scenarios` for untested operations. |
152
- | `generate_request_from_intent` | Takes a plain-English intent; AI calls `create_request` + `set_request_script` in one shot. |
153
- | `generate_scenarios` | Returns request list + instructions; AI creates negative/edge-case variants (400/401/403/404/boundary) per request. Self-continues. |
154
- | `heal_assertions` | Returns current script + last run response; AI rewrites stale assertions and calls `set_request_script`. |
155
- | `generate_iteration_data` | Returns request schema + instructions; AI produces N varied test rows as a JSON array. |
156
-
157
- ### Data tools (read → you analyze → write)
158
-
159
- | Tool | Description |
160
- |---|---|
161
- | `suggest_env_vars` | Returns heuristic suggestions + full request summary for manual or AI review |
162
- | `apply_env_vars` | Replaces `{value, varName}[]` throughout the collection; optionally writes originals to env |
163
- | `get_requests_for_enhancement` | Returns paginated request details (body, test script, headers) |
164
- | `apply_request_enhancements` | Applies AI-written bodies and `pm.test()` scripts to the specified requests |
165
- | `analyze_coverage` | Per-request assertion count + collection-level %. Optional OpenAPI spec comparison. No LLM. |
166
- | `validate_against_spec` | Compares collection against an OpenAPI 3.0 spec: untested operations, unasserted requests, extra requests. No LLM. |
167
-
168
- ---
45
+ ## ⚡ Quick Start
169
46
 
170
47
  ### Basic Usage
171
48
 
@@ -364,75 +241,6 @@ if (pm.response.headers.has('Set-Cookie')) {
364
241
  }
365
242
  ```
366
243
 
367
- #### Response Body Type
368
-
369
- Like Postman, `pm.response.body` is the **raw response string** — it is not eagerly parsed. Parse JSON on demand:
370
-
371
- ```javascript
372
- const data = pm.response.json(); // parsed object (null if not JSON)
373
- const text = pm.response.text(); // raw string
374
- const obj = JSON.parse(pm.response.body); // body is a string
375
- ```
376
-
377
- `json()` tolerates an already-parsed object body for backward compatibility, but new code should treat `pm.response.body` as a string.
378
-
379
- #### Legacy Postman Globals
380
-
381
- Older Postman scripts and many Newman-exported collections rely on bare globals from the pre-`pm.*` sandbox. The core injects these so legacy scripts run unchanged.
382
-
383
- Available in **both** pre-request and test scripts: `request` (`{ id, name, description, url, method, headers, data }`), `environment` (read snapshot), `globals` (read snapshot), `data` (iteration row), `iteration` (index), and `tv4` (`tv4.validate(data, schema)` — when the optional `tv4` module is installed).
384
-
385
- Available in **test** scripts only: `responseBody` (raw string), `responseCode` (`{ code, name, detail }`), `responseHeaders`, `responseTime`, `responseCookies` (cookie objects with `name`, `value`, `domain`, `path`, `expires`, `maxAge`, `httpOnly`, `secure`, `sameSite`), `tests` (`tests['name'] = boolean`), plus `postman.getResponseHeader(name)` and `postman.getResponseCookie(name)` (case-insensitive; `getResponseCookie` returns the full cookie object, both return `null` if absent).
386
-
387
- ```javascript
388
- // Legacy-style test script — runs unmodified
389
- tests['status 200'] = responseCode.code === 200;
390
- tests['has token'] = JSON.parse(responseBody).token !== undefined;
391
- tests['is json'] = /application\/json/.test(postman.getResponseHeader('Content-Type'));
392
- ```
393
-
394
- > `environment` and `globals` are read snapshots — direct assignment was never persisted in legacy Postman either. Use `postman.setEnvironmentVariable()` / `postman.setGlobalVariable()` (or the modern `pm.environment.set()` / `pm.globals.set()`) to persist changes.
395
-
396
- #### Script Scope
397
-
398
- Control how script levels (collection → folder → request) and the pre-request/post-response phases share a JavaScript scope via `scripts.scope` in `http-forge.config.json` (or the `scriptScope` SDK option):
399
-
400
- | Mode | Behavior |
401
- |------|----------|
402
- | `'shared'` *(default)* | All levels and both phases run in one scope. `var`/`function` and global assignments leak across them; lowest overhead. Top-level `let`/`const` are scoped to a single phase. |
403
- | `'isolated'` | Each level runs in its own scope, matching Postman. Declarations cannot collide or leak; pass state through `pm.variables` / `pm.environment` / `pm.globals`. |
404
-
405
- ```typescript
406
- const forge = ForgeContainer.create({ scriptScope: 'isolated' });
407
- ```
408
-
409
- Use `'isolated'` when importing Postman collections whose scripts re-declare the same identifiers at multiple levels, which would otherwise throw `Identifier already declared` in shared mode.
410
-
411
- #### Async Script Execution (Event-Loop Draining)
412
-
413
- Like Postman, scripts do **not** end when their synchronous code returns. After the sync body completes, the core keeps the sandbox alive and drains pending timers (`setTimeout`/`setInterval`) and microtasks (un-awaited `Promise`s), then commits variable scopes — so deferred `pm.globals` / `pm.environment` / `pm.variables` writes are visible to the next request **without** `await`.
414
-
415
- ```typescript
416
- // Post-response script — committed for the next request, no await required
417
- setTimeout(() => pm.globals.set('authToken', generateToken()), 1500);
418
- ```
419
-
420
- The drain is bounded by `scripts.timeout` (the `scriptTimeout` SDK option), default **5000 ms**, which caps **both** synchronous CPU time and the async-drain window:
421
-
422
- ```typescript
423
- const forge = ForgeContainer.create({ scriptTimeout: 10000 });
424
- ```
425
-
426
- | Behavior | Notes |
427
- |----------|-------|
428
- | Sandbox kept alive after sync return | Pending timers/microtasks drained before the request advances |
429
- | Deferred `pm.*` writes committed | Visible to the next request without `await` |
430
- | Errors in timer/Promise callbacks | Reported as a console error, **non-fatal** — the request/test is not failed |
431
- | Runaway timers | A never-clearing `setInterval` or infinite timer loop is force-cancelled at the timeout, with a warning |
432
- | No async work | Returns immediately; draining adds no measurable latency |
433
-
434
- **Divergences from Postman:** uses real Node timers with a poll-based wall-clock drain (no exact pending-promise count, so pathological microtask recursion is bounded by the budget rather than a precise idle signal); a single `scripts.timeout` bounds both CPU time and the async window.
435
-
436
244
  ### Environment Management
437
245
 
438
246
  ```typescript
@@ -541,11 +349,6 @@ pm.response.cookies.forEach(cookie => {
541
349
  pm.cookies.set(cookie.name, cookie.value);
542
350
  });
543
351
 
544
- // Read a response cookie (Postman-compatible CookieList)
545
- const sid = pm.response.cookies.get('sessionId'); // value string
546
- const sidCookie = pm.response.cookies.one('sessionId'); // full object
547
- if (sidCookie?.secure && sidCookie.maxAge > 0) { /* ... */ }
548
-
549
352
  // List all active cookies
550
353
  const allCookies = pm.cookies.list(); // [{name, value}, ...]
551
354
 
@@ -602,7 +405,7 @@ interface ForgeContainerOptions {
602
405
 
603
406
  // Script Settings
604
407
  scriptRunner?: IScriptRunner; // Custom script runner
605
- scriptTimeout?: number; // Script budget (ms); caps CPU time + async-drain window. Default 5000
408
+ scriptTimeout?: number; // Script timeout (ms)
606
409
 
607
410
  // History
608
411
  enableHistory?: boolean; // Enable request history
@@ -717,46 +520,6 @@ interface PathParamEntry {
717
520
  }
718
521
  ```
719
522
 
720
- ### Postman Collection Import / Export
721
-
722
- `CollectionService` can import and export Postman Collection v2.1 JSON files, preserving all request body types, auth, scripts, and folder structure.
723
-
724
- **Import** (`importCollection(filePath)`):
725
-
726
- Detects Postman format by `info._postman_id` and converts all five body modes:
727
-
728
- | Postman `mode` | HTTP Forge `type` | Notes |
729
- |---|---|---|
730
- | `raw` | `raw` | `format` inferred from `options.raw.language` (json/xml/html/javascript/text) |
731
- | `urlencoded` | `x-www-form-urlencoded` | Fields mapped to `[{key, value, enabled}]` |
732
- | `formdata` | `form-data` | Fields mapped to `[{key, value, type, enabled}]` |
733
- | `graphql` | `graphql` | `variables` JSON string parsed to object |
734
- | `binary` | `binary` | File path not portable; imported with empty content |
735
-
736
- Auth types `bearer`, `basic`, and `apikey` are converted. Pre-request and test scripts (`prerequest`/`test` events) are imported as `scripts.preRequest`/`scripts.postResponse`. Folder hierarchy and item order are preserved.
737
-
738
- The whole collection is built in memory and persisted with a single `saveCollection()`
739
- call. `FolderCollectionStore.save()` writes sibling items and each request's
740
- independent files (body, docs, scripts, schemas) in parallel and writes each
741
- metadata file once; fresh imports skip stale-body cleanup and schema-existence
742
- probes. Loaders read JSON via a `readJsonFileSafe` helper that silently skips
743
- empty or half-written files, so a watcher reloading mid-import never throws
744
- `Unexpected end of JSON input`.
745
-
746
- **Export** (`exportCollection(collectionId, filePath)`):
747
-
748
- Converts back to Postman v2.1 JSON. All body types round-trip correctly: `x-www-form-urlencoded` exports as `mode: "urlencoded"`, `form-data` as `mode: "formdata"`, `graphql` as `mode: "graphql"`, and `binary` as `mode: "binary"`.
749
-
750
- ```typescript
751
- const service = container.getCollectionService();
752
-
753
- // Import
754
- const collection = await service.importCollection('./my-api.postman_collection.json');
755
-
756
- // Export
757
- await service.exportCollection(collection.id, './exported.postman_collection.json');
758
- ```
759
-
760
523
  ### OpenAPI Import / Export
761
524
 
762
525
  The core library includes full OpenAPI 3.0.3 import and export with constraint preservation.
@@ -768,59 +531,13 @@ The core library includes full OpenAPI 3.0.3 import and export with constraint p
768
531
 
769
532
  **Export** (`OpenApiExporter`):
770
533
  - Generates OpenAPI 3.0.3 specs from collections
771
- - **Host-variable server resolution** — Any `{{varName}}` that prefixes a request URL (e.g. `{{dcqHost}}/api/...`) is stripped from the path and resolved to a server URL entry. If the variable resolves in the active environment(s), a concrete `url` is added to `servers`. If unresolvable, an OAS server-variable entry is emitted: `url: '{varName}', variables: { varName: { default: '' } }`. This handles arbitrary host variables beyond `{{baseUrl}}`.
772
- - **Environment variable placeholder sanitization** — `{{varName}}` tokens in parameter examples (path, query, header) and request body examples are replaced with `<varName>` so the exported spec contains readable human placeholders rather than raw template syntax.
773
534
  - **Collision-aware merging**: When multiple requests normalize to the same path + HTTP method, they are merged into a single operation:
774
535
  - Descriptions are appended, tags are unioned
775
536
  - Parameters with the **same constraint kind** (both enum, both pattern, etc.) are merged in-place (union enum values, widen numeric ranges, alternation-join patterns)
776
537
  - Parameters with **different constraint kinds** are wrapped in `oneOf` — each variant keeps its self-consistent schema
777
538
  - All constraint fields round-trip without data loss
778
539
 
779
- ## � Exported Types
780
-
781
- ### Configuration
782
-
783
- `HttpForgeConfig` is the shape of `http-forge.config.json`. Key sub-interfaces:
784
-
785
- | Interface | Description |
786
- |---|---|
787
- | `StorageConfig` | Root/history/results paths |
788
- | `RequestConfig` | Timeout, redirects, SSL |
789
- | `ScriptsConfig` | Module search paths |
790
- | `RunnerConfig` | Retention, index page size |
791
- | `EnvironmentsConfig` | Default environment |
792
- | `RestClientExportConfig` | REST Client export path/merge settings |
793
- | `McpConfig` | MCP server project-level settings (see below) |
794
- | `ProxyConfig` | HTTP/HTTPS proxy URLs |
795
-
796
- **`McpConfig`** — controls what the HTTP Forge MCP server exposes to AI agents. All fields are optional; the service fills defaults automatically via `IConfigService.getMcpConfig()`.
797
-
798
- ```typescript
799
- interface McpConfig {
800
- excludedCollections: string[]; // IDs or names to hide (default: [] = expose all)
801
- excludedSuites: string[]; // IDs or names to hide (default: [] = expose all)
802
- toolPrefix: string; // Prefix for every tool name (default: "")
803
- maxRequestsPerCall: number; // Safety cap per collection/suite call (default: 500; min 1, max 10000)
804
- toolMode: 'flat' | 'drilldown' | 'auto'; // How tools are exposed (default: 'auto')
805
- drilldownThreshold: number; // 'auto' switches to drill-down above this request-tool count (default: 100; min 10, max 500)
806
- toolPageSize: number; // Max tools per tools/list page (default: 200; 0 = no pagination; min 10, max 1000)
807
- cors: {
808
- allowedOrigins: string[]; // CORS origins (default: ["http://localhost","http://127.0.0.1"])
809
- };
810
- }
811
- ```
812
-
813
- **`toolMode`** controls how collections/requests are surfaced as MCP tools:
814
-
815
- - `auto` (**default**) — uses `flat` below `drilldownThreshold` (100 requests), then switches to `drilldown`. Adapts automatically as the workspace grows.
816
- - `drilldown` — a small fixed set of generic tools (`list_collections`, `list_requests`, `run_request`, `run_folder`, `run_collection`, `run_suite`) whose arguments select the target. Keeps the tool list tiny regardless of scale.
817
- - `flat` — one tool per request, folder, collection, and suite. Only suitable for small, stable collections (<100 requests). **Avoid for large workspaces** — the tool list bloats the AI context window and degrades tool-selection accuracy.
818
-
819
- Use `IConfigService.getMcpConfig()` to read the resolved config with all defaults applied.
820
-
821
- ---
822
-
823
- ## �🛠️ Use Cases
540
+ ## 🛠️ Use Cases
824
541
 
825
542
  ### CLI Tool
826
543
 
@@ -1012,27 +729,12 @@ MIT © Henry Huang
1012
729
 
1013
730
  ## 📝 Changelog
1014
731
 
1015
- ### 0.7.0 (AI & Analysis)
1016
-
1017
- - ✅ **`IAiProvider`** — Platform-agnostic LLM interface; bring Copilot, OpenAI, Anthropic, or any other LLM
1018
- - ✅ **`enhanceCollection`** — Batch-enhances collection requests with AI-written example bodies and `pm.test()` scripts
1019
- - ✅ **`scanCollectionForEnvVarsWithAi`** — AI-powered scan for hardcoded values (keys, tokens, base URLs)
1020
- - ✅ **`detectEnvSuggestions`** / **`applyEnvSuggestionsToItems`** — Heuristic env var detection (no LLM)
1021
- - ✅ **`parseCurlCommand`** — Tokenising shell curl parser producing a ready-to-persist `ParsedCurlRequest`
1022
- - ✅ **MCP agentic tools** — `ai_suggest_env_vars`, `ai_enhance_collection`, `suggest_env_vars`, `apply_env_vars`, `get_requests_for_enhancement`, `apply_request_enhancements`
1023
- - ✅ **MCP gap-closure tools** — `analyze_coverage`, `ai_analyze_coverage`, `validate_against_spec`, `generate_request_from_intent`, `generate_scenarios`, `heal_assertions`, `generate_iteration_data`
1024
-
1025
732
  ### 0.2.16 (Duplicate Collection & Folder)
1026
733
 
1027
734
  - ✅ **`duplicateCollection(sourceId, newName)`** — Duplicates a collection including all nested folders, requests, scripts, and schemas
1028
735
  - ✅ **`duplicateFolder(collectionId, folderId, newName)`** — Duplicates a folder within a collection, preserving all nested request content
1029
736
  - ✅ **`getItemPath(collectionId, itemId)`** — Resolves the disk path of a folder or request within a collection
1030
737
 
1031
- ### 0.2.6 (OpenAPI Export — Environment Variable Handling)
1032
-
1033
- - ✅ **Host-variable URL stripping** — Any leading `{{varName}}` in a request URL (e.g. `{{dcqHost}}/DCQ/templates/GetEpg`) is now correctly stripped from the path. The variable name is resolved via `envConfigService.resolveVariables()` and the resulting URL is added to `servers`. When the variable cannot be resolved, an OAS server-variable entry (`url: '{varName}', variables: { varName: { default: '' } }`) is emitted instead. Previously, unknown host variables were converted to `/{varName}/...` path segments.
1034
- - ✅ **Example sanitization** — `{{varName}}` placeholders in parameter examples (path, query, header) and request body examples are replaced with `<varName>` so they render as readable human placeholders instead of raw template syntax in the exported spec.
1035
-
1036
738
  ### 0.2.5 (OpenAPI Constraint Round-Trip & Collision Merging)
1037
739
 
1038
740
  - ✅ **Full parameter constraint round-trip** — OpenAPI import/export now preserves all schema constraint fields: `pattern`, `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `minLength`, `maxLength`, and `oneOf` on both `KeyValueEntry` and `PathParamEntry`