@http-forge/core 0.6.35 → 0.6.36-beta.1

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.
Files changed (98) hide show
  1. package/README.md +51 -0
  2. package/dist/__tests__/api-discovery/golden-utils.d.ts +10 -0
  3. package/dist/index.d.ts +49 -22
  4. package/dist/index.js +456 -480
  5. package/dist/index.mjs +456 -480
  6. package/dist/infrastructure/ai/ai-context.d.ts +109 -0
  7. package/dist/infrastructure/ai/ai-provider.d.ts +1 -1
  8. package/dist/infrastructure/ai/ai-utils.d.ts +38 -0
  9. package/dist/infrastructure/ai/http-providers.d.ts +34 -0
  10. package/dist/infrastructure/api-discovery/analyzer/component-analyzer.d.ts +60 -0
  11. package/dist/infrastructure/api-discovery/analyzer/express-component-analyzer.d.ts +14 -0
  12. package/dist/infrastructure/api-discovery/analyzer/fastify-component-analyzer.d.ts +14 -0
  13. package/dist/infrastructure/api-discovery/analyzer/index.d.ts +11 -0
  14. package/dist/infrastructure/api-discovery/analyzer/lambda-component-analyzer.d.ts +18 -0
  15. package/dist/infrastructure/api-discovery/api-discovery-service.d.ts +49 -0
  16. package/dist/infrastructure/api-discovery/auth-validation.d.ts +34 -0
  17. package/dist/infrastructure/api-discovery/drift-engine.d.ts +139 -0
  18. package/dist/infrastructure/api-discovery/fastapi/fastapi-discovery-provider.d.ts +19 -0
  19. package/dist/infrastructure/api-discovery/fastapi/fastapi-parser.d.ts +60 -0
  20. package/dist/infrastructure/api-discovery/framework-detector.d.ts +8 -0
  21. package/dist/infrastructure/api-discovery/index.d.ts +29 -0
  22. package/dist/infrastructure/api-discovery/path-utils.d.ts +17 -0
  23. package/dist/infrastructure/api-discovery/project-name.d.ts +2 -0
  24. package/dist/infrastructure/api-discovery/provider.d.ts +29 -0
  25. package/dist/infrastructure/api-discovery/providers/express-discovery-provider.d.ts +13 -0
  26. package/dist/infrastructure/api-discovery/providers/fastify-discovery-provider.d.ts +13 -0
  27. package/dist/infrastructure/api-discovery/providers/lambda-discovery-provider.d.ts +19 -0
  28. package/dist/infrastructure/api-discovery/providers/nest-discovery-provider.d.ts +12 -0
  29. package/dist/infrastructure/api-discovery/seed-loader.d.ts +11 -0
  30. package/dist/infrastructure/api-discovery/source-files.d.ts +1 -0
  31. package/dist/infrastructure/api-discovery/spring/controller-visitor.d.ts +141 -0
  32. package/dist/infrastructure/api-discovery/spring/endpoint-parser.d.ts +51 -0
  33. package/dist/infrastructure/api-discovery/spring/file-utils.d.ts +28 -0
  34. package/dist/infrastructure/api-discovery/spring/model.d.ts +84 -0
  35. package/dist/infrastructure/api-discovery/spring/schema-generator.d.ts +65 -0
  36. package/dist/infrastructure/api-discovery/spring/spring-discovery-provider.d.ts +30 -0
  37. package/dist/infrastructure/api-discovery/spring/spring-types.d.ts +27 -0
  38. package/dist/infrastructure/api-discovery/test-generator.d.ts +69 -0
  39. package/dist/infrastructure/api-discovery/types.d.ts +154 -0
  40. package/dist/infrastructure/api-discovery/workflow-discovery.d.ts +55 -0
  41. package/dist/infrastructure/architect/api-architect-service.d.ts +85 -0
  42. package/dist/infrastructure/architect/architect-prompt.d.ts +22 -0
  43. package/dist/infrastructure/architect/collection-to-endpoints.d.ts +13 -0
  44. package/dist/infrastructure/architect/index.d.ts +10 -0
  45. package/dist/infrastructure/collection/collection-service.d.ts +1 -5
  46. package/dist/infrastructure/collection/json-collection-loader.d.ts +0 -8
  47. package/dist/infrastructure/cookie/cookie-service.d.ts +2 -13
  48. package/dist/infrastructure/cookie/cookie-utils.d.ts +5 -0
  49. package/dist/infrastructure/docs/index.d.ts +5 -0
  50. package/dist/infrastructure/docs/release-notes.d.ts +51 -0
  51. package/dist/infrastructure/environment/environment-config-service.d.ts +0 -1
  52. package/dist/infrastructure/environment/variable-interpolator.d.ts +9 -0
  53. package/dist/infrastructure/http/header-utils.d.ts +13 -0
  54. package/dist/infrastructure/http/http-request-service.d.ts +3 -3
  55. package/dist/infrastructure/http/interceptor-chain.d.ts +35 -16
  56. package/dist/infrastructure/http/native-http-client.d.ts +0 -10
  57. package/dist/infrastructure/openapi/interfaces.d.ts +14 -0
  58. package/dist/infrastructure/openapi/openapi-exporter.d.ts +11 -91
  59. package/dist/infrastructure/openapi/openapi-importer.d.ts +19 -0
  60. package/dist/infrastructure/openapi/openapi-operation-builder.d.ts +36 -0
  61. package/dist/infrastructure/openapi/openapi-schema-merger.d.ts +33 -0
  62. package/dist/infrastructure/openapi/openapi-spec-writer.d.ts +27 -0
  63. package/dist/infrastructure/openapi/openapi-utils.d.ts +62 -0
  64. package/dist/infrastructure/parsers/har-parser.d.ts +63 -0
  65. package/dist/infrastructure/parsers/index.d.ts +2 -0
  66. package/dist/infrastructure/review/index.d.ts +5 -0
  67. package/dist/infrastructure/review/review-engine.d.ts +95 -0
  68. package/dist/infrastructure/script/crypto-js-compat.d.ts +123 -0
  69. package/dist/infrastructure/script/request-object-factory.d.ts +54 -0
  70. package/dist/infrastructure/script/request-script-session.d.ts +0 -5
  71. package/dist/infrastructure/script/script-executor.d.ts +4 -33
  72. package/dist/infrastructure/script/script-factories.d.ts +13 -0
  73. package/dist/infrastructure/script/variable-scopes.d.ts +101 -0
  74. package/dist/infrastructure/test-suite/interfaces.d.ts +6 -0
  75. package/dist/runtime/collection-traversal.d.ts +32 -0
  76. package/dist/runtime/direct-execution.d.ts +7 -0
  77. package/dist/runtime/execution-helpers.d.ts +30 -0
  78. package/dist/runtime/mcp-dispatcher.d.ts +10 -34
  79. package/dist/runtime/mcp-handlers/ai.d.ts +6 -0
  80. package/dist/runtime/mcp-handlers/collection.d.ts +5 -0
  81. package/dist/runtime/mcp-handlers/discovery.d.ts +12 -0
  82. package/dist/runtime/mcp-handlers/environment-management.d.ts +6 -0
  83. package/dist/runtime/mcp-handlers/environment.d.ts +5 -0
  84. package/dist/runtime/mcp-handlers/execution.d.ts +6 -0
  85. package/dist/runtime/mcp-handlers/helpers.d.ts +43 -0
  86. package/dist/runtime/mcp-handlers/inspection.d.ts +5 -0
  87. package/dist/runtime/mcp-handlers/registry.d.ts +12 -0
  88. package/dist/runtime/mcp-handlers/request.d.ts +5 -0
  89. package/dist/runtime/mcp-handlers/review.d.ts +10 -0
  90. package/dist/runtime/mcp-handlers/run-status.d.ts +5 -0
  91. package/dist/runtime/mcp-handlers/suite.d.ts +6 -0
  92. package/dist/runtime/mcp-handlers/types.d.ts +59 -0
  93. package/dist/runtime/mcp-prompts.d.ts +16 -2
  94. package/dist/runtime/mcp-tool-schemas.d.ts +8 -0
  95. package/dist/runtime/suite-executor.d.ts +20 -0
  96. package/dist/types/types.d.ts +0 -9
  97. package/dist/utils/env-hints.d.ts +17 -0
  98. package/package.json +16 -6
@@ -0,0 +1,109 @@
1
+ /**
2
+ * AI Context Assemblers
3
+ *
4
+ * Turn everything HTTP Forge knows about a workspace — collection structure,
5
+ * per-request business docs (`doc.md`), descriptions, OpenAPI metadata,
6
+ * workspace knowledge files, and test-run results — into compact, bounded
7
+ * "business context" blocks that get injected into AI prompts and MCP task
8
+ * payloads. This gives every AI feature the same grounding: the calling LLM
9
+ * no longer has to guess what an endpoint does or why a test failed.
10
+ *
11
+ * Platform-independent except the optional workspace-knowledge reader, which
12
+ * is guarded so it no-ops when no workspace folder is available.
13
+ */
14
+ import type { Collection, CollectionRequestItem } from '../../types/collection';
15
+ import type { McpRunStore } from '../../runtime/mcp-run-store';
16
+ /**
17
+ * Kinds of knowledge a source can provide. Adding a new source = one file
18
+ * implementing `ApiKnowledgeSource` + one `registerKnowledgeSource` call.
19
+ */
20
+ export type ApiKnowledgeKind = 'collection' | 'openapi' | 'discovered-code' | 'workspace-knowledge' | 'run-results';
21
+ /**
22
+ * A bounded, token-budgeted snapshot of a knowledge source — the same
23
+ * discipline as the builders above, but packaged as a self-describing block so
24
+ * `assembleBusinessContext` can render it without knowing the source type.
25
+ */
26
+ export interface ApiKnowledgeSnapshot {
27
+ kind: ApiKnowledgeKind;
28
+ /** Display heading used when this snapshot is assembled into a context block. */
29
+ heading: string;
30
+ /** Bounded body (never unbounded — each source caps its own output). */
31
+ body: string;
32
+ /** When the snapshot was produced. */
33
+ generatedAt: number;
34
+ }
35
+ /**
36
+ * The pluggable "understanding" contract every AI feature reads from. One
37
+ * implementation per source; registration is the only wiring needed.
38
+ */
39
+ export interface ApiKnowledgeSource {
40
+ kind: ApiKnowledgeKind;
41
+ /** Produce a bounded context block. Cheap enough to call on demand. */
42
+ snapshot(): ApiKnowledgeSnapshot;
43
+ /** Drives auto-maintain + watch: 'fresh' when the source's data is current. */
44
+ freshness(): 'fresh' | 'stale';
45
+ }
46
+ /** Collection-structure context (description, vars, auth, folder tree, methods). */
47
+ export declare function collectionKnowledgeSource(collection: Collection): ApiKnowledgeSource;
48
+ /** Single-request business context (docs, OpenAPI metadata, schema, body). */
49
+ export declare function requestKnowledgeSource(request: CollectionRequestItem, folderPath?: string): ApiKnowledgeSource;
50
+ /** Workspace business knowledge (`.http-forge/knowledge/**`, README, AGENTS). */
51
+ export declare function workspaceKnowledgeSource(workspaceFolder?: string): ApiKnowledgeSource;
52
+ /** Test-run results context from the shared run store. */
53
+ export declare function runResultsKnowledgeSource(runStore: McpRunStore, runId?: string): ApiKnowledgeSource;
54
+ /** Register a custom knowledge source; every assemble call picks it up. */
55
+ export declare function registerKnowledgeSource(source: ApiKnowledgeSource): void;
56
+ /** Drop all registered sources (test teardown). */
57
+ export declare function clearRegisteredKnowledgeSources(): void;
58
+ /** Current registered sources (read-only snapshot). */
59
+ export declare function getRegisteredKnowledgeSources(): ApiKnowledgeSource[];
60
+ /**
61
+ * Compact business context for a single request: what it does, its docs,
62
+ * OpenAPI contract metadata, schema, and body. Skips empty fields.
63
+ */
64
+ export declare function buildRequestBusinessContext(req: CollectionRequestItem, folderPath?: string): string;
65
+ /**
66
+ * Collection-level business context: name, description, variables, auth,
67
+ * folder tree and request inventory.
68
+ */
69
+ export declare function buildCollectionBusinessContext(collection: Collection): string;
70
+ /**
71
+ * Read workspace business knowledge into a bounded block. Sources (in priority
72
+ * order):
73
+ * - `.http-forge/knowledge/` — user-dropped business docs: Confluence page
74
+ * exports, Jira ticket summaries, ADRs, API design notes (any *.md)
75
+ * - workspace-root `README.md` and `AGENTS.md`
76
+ * Returns '' when no workspace folder is available or nothing was found.
77
+ */
78
+ export declare function gatherWorkspaceKnowledge(workspaceFolder?: string): string;
79
+ /**
80
+ * Compact run-results context from the shared run store: outcome, failures,
81
+ * and assertion messages — the test-result grounding for failure tools.
82
+ */
83
+ export declare function buildRunResultsContext(runStore: McpRunStore, runId?: string): string;
84
+ /**
85
+ * Options form of the legacy context assembler. Maps to the default source set
86
+ * via {@link createDefaultKnowledgeSources} — kept for callers that don't need
87
+ * to compose sources themselves.
88
+ */
89
+ export interface AssembleContextOptions {
90
+ collection: Collection;
91
+ request?: CollectionRequestItem;
92
+ requestFolderPath?: string;
93
+ workspaceFolder?: string;
94
+ runStore?: McpRunStore;
95
+ runId?: string;
96
+ }
97
+ /**
98
+ * Build the default set of knowledge sources from the legacy options shape.
99
+ * Order matches the pre-seam assembler: Collection, Request, Business
100
+ * Knowledge, Test Results — so assembled output is byte-for-byte unchanged.
101
+ */
102
+ export declare function createDefaultKnowledgeSources(options: AssembleContextOptions): ApiKnowledgeSource[];
103
+ /**
104
+ * Assemble one labeled business-context block from knowledge sources. Empty
105
+ * sources are omitted. This is the single injection point for every AI feature
106
+ * (plan §3.1) — passing `[]` still picks up registered sources.
107
+ */
108
+ export declare function assembleBusinessContext(sources: ApiKnowledgeSource[]): string;
109
+ export declare function assembleBusinessContext(options: AssembleContextOptions): string;
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * Platform-agnostic abstraction for text-completion AI.
5
5
  * Implementations:
6
+ * - http-providers.ts: OpenAiProvider / AnthropicProvider (plain HTTP fetch)
6
7
  * - VS Code extension: CopilotAiProvider (wraps vscode.lm)
7
- * - CLI: OpenAiProvider / AnthropicProvider (plain HTTP)
8
8
  */
9
9
  /** Minimal interface required by all AI-powered core utilities. */
10
10
  export interface IAiProvider {
@@ -0,0 +1,38 @@
1
+ /**
2
+ * AI Utility Helpers
3
+ *
4
+ * Shared reliability helpers for every AI-backed core utility:
5
+ * - extractJsonFromLlm: robustly extract a JSON value from a free-form LLM
6
+ * completion (markdown fences, trailing prose, or stray brackets).
7
+ * - withAiRetry: retry an IAiProvider.complete() call with exponential backoff
8
+ * so a single transient provider error doesn't abort a whole batch.
9
+ *
10
+ * Platform-independent — no VS Code or Node.js-specific dependency.
11
+ */
12
+ /**
13
+ * Extract the first parseable JSON value (object or array) from an LLM
14
+ * completion. LLMs frequently wrap JSON in json fences or append prose;
15
+ * this scans for the first `[`/`{` and takes its balanced span, respecting
16
+ * strings and escapes, then JSON.parses exactly that region.
17
+ *
18
+ * @param raw The raw completion text.
19
+ * @returns The parsed JSON value, or null if nothing parseable was found.
20
+ */
21
+ export declare function extractJsonFromLlm<T = unknown>(raw: string): T | null;
22
+ export interface AiRetryOptions {
23
+ /** Maximum attempts including the first call (default 3). */
24
+ attempts?: number;
25
+ /** Base backoff delay in ms, doubled per retry (default 250). */
26
+ baseDelayMs?: number;
27
+ /** Predicate deciding whether an error is worth retrying (default: all). */
28
+ isRetryable?: (error: unknown) => boolean;
29
+ }
30
+ /**
31
+ * Retry an async operation (typically an IAiProvider.complete call) with
32
+ * exponential backoff. Non-retryable errors propagate immediately.
33
+ *
34
+ * @param fn The operation to retry.
35
+ * @param options Backoff/attempt configuration.
36
+ * @returns The first successful result.
37
+ */
38
+ export declare function withAiRetry<T>(fn: () => Promise<T>, options?: AiRetryOptions): Promise<T>;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * HTTP AI Providers
3
+ *
4
+ * IAiProvider implementations that talk to OpenAI / Anthropic over plain HTTPS
5
+ * using native `fetch` (Node 20+, browsers, and the VS Code extension host) —
6
+ * no SDK dependency required.
7
+ *
8
+ * Auto-detection (createEnvAiProvider):
9
+ * 1. OPENAI_API_KEY → OpenAiProvider (model: gpt-4o-mini by default)
10
+ * 2. ANTHROPIC_API_KEY → AnthropicProvider (model: claude-3-5-haiku-20241022)
11
+ */
12
+ import type { IAiProvider } from './ai-provider';
13
+ export declare class OpenAiProvider implements IAiProvider {
14
+ private readonly apiKey;
15
+ private readonly model;
16
+ constructor(apiKey: string, model?: string);
17
+ complete(prompt: string): Promise<string>;
18
+ }
19
+ export declare class AnthropicProvider implements IAiProvider {
20
+ private readonly apiKey;
21
+ private readonly model;
22
+ constructor(apiKey: string, model?: string);
23
+ complete(prompt: string): Promise<string>;
24
+ }
25
+ /**
26
+ * Create the best available AI provider from environment variables.
27
+ * Returns null if no provider is configured.
28
+ *
29
+ * Respects:
30
+ * OPENAI_API_KEY → OpenAI (override model with OPENAI_MODEL)
31
+ * ANTHROPIC_API_KEY → Anthropic (override model with ANTHROPIC_MODEL)
32
+ * HTTP_FORGE_AI_PROVIDER=openai|anthropic to force a specific provider
33
+ */
34
+ export declare function createEnvAiProvider(): IAiProvider | null;
@@ -0,0 +1,60 @@
1
+ import * as ts from 'typescript';
2
+ import { DiscoveredApiCookie, DiscoveredApi, DiscoveredApiMiddleware, DiscoveredApiParameter, DiscoveredApiBody, DiscoveredApiResponse, DiscoveryContext, EndpointConfidence, FrameworkFingerprint } from '../types';
3
+ /**
4
+ * Shared interface for framework-specific component analyzers.
5
+ *
6
+ * Each framework (Express, Fastify, NestJS) implements this interface
7
+ * to provide consistent route discovery while handling framework-specific logic.
8
+ */
9
+ export interface ComponentAnalyzer {
10
+ /**
11
+ * Analyze a source file and extract API endpoints.
12
+ *
13
+ * @param filePath - absolute path to the source file
14
+ * @param content - file contents
15
+ * @param fingerprint - framework fingerprint
16
+ * @param context - discovery context with environment overrides
17
+ * @returns array of discovered endpoints, may be empty
18
+ */
19
+ analyzeFile(filePath: string, content: string, fingerprint: FrameworkFingerprint, context: DiscoveryContext): Promise<DiscoveredApi[]>;
20
+ }
21
+ export interface RouteDefinitionBase {
22
+ method: string;
23
+ pathExpression: string;
24
+ resolvedPath?: string;
25
+ confidence: EndpointConfidence;
26
+ source: DiscoveredApi['source'];
27
+ middleware: DiscoveredApiMiddleware[];
28
+ }
29
+ export interface PrefixState {
30
+ pathExpression: string;
31
+ resolvedPath?: string;
32
+ confidence: EndpointConfidence;
33
+ }
34
+ export interface EndpointMetadata {
35
+ parameters: DiscoveredApiParameter[];
36
+ requestBody: DiscoveredApiBody | undefined;
37
+ cookies: DiscoveredApiCookie[];
38
+ responses: DiscoveredApiResponse[];
39
+ }
40
+ interface TraversalState {
41
+ visitedSymbols: Set<string>;
42
+ }
43
+ interface RootAliasHints {
44
+ requestAliases?: Set<string>;
45
+ responseAliases?: Set<string>;
46
+ }
47
+ export declare function combineConfidence(a: EndpointConfidence, b: EndpointConfidence): EndpointConfidence;
48
+ /**
49
+ * Extract path parameters from a route pattern.
50
+ * Supports Express (`:id`) and Fastify (`{id}`) style parameters.
51
+ */
52
+ export declare function extractPathParameters(pathPattern: string, source?: ts.SourceFile, location?: any): DiscoveredApiParameter[];
53
+ /**
54
+ * Analyze handler function to extract request/response metadata.
55
+ * Detects usage of req.query, req.body, req.headers, req.cookies, res.locals, res.header(), res.cookie().
56
+ */
57
+ export declare function analyzeHandlerMetadata(handlerNode: ts.Node, source: ts.SourceFile, filePath: string, method: string, traversalState?: TraversalState, rootAliasHints?: RootAliasHints, contextProperties?: string[]): EndpointMetadata;
58
+ export declare function analyzeComponentChainMetadata(componentNodes: ts.Node[], source: ts.SourceFile, filePath: string, method: string, contextProperties?: string[]): EndpointMetadata;
59
+ export declare function dedupeDiscoveredApiParameters(parameters: DiscoveredApiParameter[]): DiscoveredApiParameter[];
60
+ export {};
@@ -0,0 +1,14 @@
1
+ import { DiscoveredApi, DiscoveryContext, FrameworkFingerprint } from '../types';
2
+ import { ComponentAnalyzer } from './component-analyzer';
3
+ /**
4
+ * Analyzes Express applications for API endpoints.
5
+ *
6
+ * Handles:
7
+ * - app.get/post/put/delete/patch routes
8
+ * - nested router mounts via app.use(prefix, router)
9
+ * - route() chains
10
+ * - middleware extraction
11
+ */
12
+ export declare class ExpressComponentAnalyzer implements ComponentAnalyzer {
13
+ analyzeFile(filePath: string, content: string, fingerprint: FrameworkFingerprint, context: DiscoveryContext): Promise<DiscoveredApi[]>;
14
+ }
@@ -0,0 +1,14 @@
1
+ import { DiscoveredApi, DiscoveryContext, FrameworkFingerprint } from '../types';
2
+ import { ComponentAnalyzer } from './component-analyzer';
3
+ /**
4
+ * Analyzes Fastify applications for API endpoints.
5
+ *
6
+ * Handles:
7
+ * - fastify.get/post/put/delete/patch routes
8
+ * - nested plugins via fastify.register()
9
+ * - route() config objects
10
+ * - preHandler middleware
11
+ */
12
+ export declare class FastifyComponentAnalyzer implements ComponentAnalyzer {
13
+ analyzeFile(filePath: string, content: string, fingerprint: FrameworkFingerprint, context: DiscoveryContext): Promise<DiscoveredApi[]>;
14
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Analyzer barrel — ported subset of `node-api-forge/src/discovery/analyzer`.
3
+ *
4
+ * Express is the first ported framework (Phase 1 vertical slice). Fastify,
5
+ * Lambda and external-call analysis are ported in a later pass.
6
+ */
7
+ export { analyzeComponentChainMetadata, analyzeHandlerMetadata, combineConfidence, dedupeDiscoveredApiParameters, extractPathParameters, } from './component-analyzer';
8
+ export type { ComponentAnalyzer, PrefixState, RouteDefinitionBase, } from './component-analyzer';
9
+ export { ExpressComponentAnalyzer } from './express-component-analyzer';
10
+ export { FastifyComponentAnalyzer } from './fastify-component-analyzer';
11
+ export { LambdaComponentAnalyzer } from './lambda-component-analyzer';
@@ -0,0 +1,18 @@
1
+ import { DiscoveredApi, DiscoveryContext, FrameworkFingerprint } from '../types';
2
+ import { ComponentAnalyzer } from './component-analyzer';
3
+ /**
4
+ * Analyzes AWS Lambda handler files for exported handler functions.
5
+ *
6
+ * Handles:
7
+ * - exports.handler / exports.<name> = async (event) => { ... }
8
+ * - module.exports = async (event) => { ... }
9
+ * - export const handler: APIGatewayProxyHandler = async (event) => { ... }
10
+ * - export async function handler(event: APIGatewayProxyEvent) { ... }
11
+ * - Middy: exports.handler = middy(baseHandler).use(plugin)
12
+ *
13
+ * Extracts parameters from event.pathParameters, event.queryStringParameters,
14
+ * event.headers, event.body, event.multiValueQueryStringParameters.
15
+ */
16
+ export declare class LambdaComponentAnalyzer implements ComponentAnalyzer {
17
+ analyzeFile(filePath: string, content: string, _fingerprint: FrameworkFingerprint, _context: DiscoveryContext): Promise<DiscoveredApi[]>;
18
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * API Discovery — Service Orchestrator
3
+ *
4
+ * Single entry point for source-code discovery across all frameworks (plan §3.3).
5
+ * Depends only on the `ApiDiscoveryProvider` abstraction and `IFileSystem`
6
+ * (dependency inversion). Providers are injected — the service never constructs
7
+ * them and never special-cases a framework (Open/Closed).
8
+ *
9
+ * Orchestration mirrors `node-api-forge/src/discovery/discovery-engine.ts`
10
+ * (Phase 1 port): fingerprint → framework detection → eligible providers →
11
+ * parallel discovery → seed merge → deterministic path-parameter enrichment →
12
+ * dedupe + sort → git-native index (DECISIONS D12).
13
+ */
14
+ import type { IFileSystem } from '../../types/platform';
15
+ import { FrameworkDetector } from './framework-detector';
16
+ import { ApiDiscoveryProvider } from './provider';
17
+ import { DiscoveryContext, DiscoveryResult, DiscoveredApi, DiscoveredApiIndex } from './types';
18
+ export interface IApiDiscoveryService {
19
+ discover(context: DiscoveryContext): Promise<DiscoveryResult>;
20
+ getIndex(): DiscoveredApiIndex | undefined;
21
+ getEndpoint(id: string): DiscoveredApi | undefined;
22
+ invalidate(projectRoots?: string[]): void;
23
+ persistIndex(index: DiscoveredApiIndex): Promise<void>;
24
+ }
25
+ export interface ApiDiscoveryServiceOptions {
26
+ providers?: ApiDiscoveryProvider[];
27
+ fileSystem?: IFileSystem;
28
+ indexFilePath?: string;
29
+ indexVersion?: string;
30
+ detector?: FrameworkDetector;
31
+ }
32
+ export declare class ApiDiscoveryService implements IApiDiscoveryService {
33
+ private readonly providers;
34
+ private readonly fileSystem?;
35
+ private readonly indexFilePath?;
36
+ private readonly indexVersion;
37
+ private readonly detector;
38
+ private index?;
39
+ constructor(options?: ApiDiscoveryServiceOptions);
40
+ discover(context: DiscoveryContext): Promise<DiscoveryResult>;
41
+ getIndex(): DiscoveredApiIndex | undefined;
42
+ getEndpoint(id: string): DiscoveredApi | undefined;
43
+ invalidate(projectRoots?: string[]): void;
44
+ persistIndex(index: DiscoveredApiIndex): Promise<void>;
45
+ private endpointKey;
46
+ private mergeSeedIntoEndpoint;
47
+ private buildIndex;
48
+ private dedupeAndSort;
49
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Auth + validation enrichment for discovered endpoints.
3
+ *
4
+ * Phase 1 convergence gap (plan §2): the ported node providers captured
5
+ * middleware names but never emitted the structured `auth` / `validation`
6
+ * fields on DiscoveredApi. These helpers derive both from data the providers
7
+ * already collect, deterministically:
8
+ *
9
+ * - `auth` from middleware names (jwt/passport/guard/authenticate/…)
10
+ * - `validation` from middleware names (zod/joi/validat/schema/…)
11
+ * and from JSON Schema constraint keywords (FastAPI/Pydantic).
12
+ *
13
+ * Applied centrally in ApiDiscoveryService so every provider converges on one
14
+ * implementation. Metadata-only — never affects run_request execution.
15
+ */
16
+ import type { DiscoveredApi, DiscoveredApiAuth, DiscoveredApiMiddleware } from './types';
17
+ export type JsonSchema = Record<string, unknown>;
18
+ /**
19
+ * Derive auth metadata from middleware names. Returns undefined when no
20
+ * middleware reads as auth-related so callers keep the field unset.
21
+ */
22
+ export declare function inferAuthFromMiddleware(middleware?: DiscoveredApiMiddleware[]): DiscoveredApiAuth | undefined;
23
+ /**
24
+ * Derive summarized validation rules from middleware names (Nest ValidationPipe,
25
+ * Express validator chains, Fastify schema options, Lambda middy validators).
26
+ */
27
+ export declare function inferValidationFromMiddleware(middleware?: DiscoveredApiMiddleware[]): string[] | undefined;
28
+ /**
29
+ * Derive summarized validation rules from a JSON Schema's constraint keywords
30
+ * (Pydantic → JSON Schema in FastAPI). Returns undefined when no constraints.
31
+ */
32
+ export declare function inferValidationFromJsonSchema(schema: JsonSchema | undefined): string[] | undefined;
33
+ /** Combined enrichment applied to every merged endpoint. */
34
+ export declare function enrichEndpointAuthAndValidation(endpoint: DiscoveredApi): void;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Phase 2b — Self-maintenance / drift engine.
3
+ *
4
+ * Design rules (plan §Phase 2b):
5
+ * 1. Regenerate, don't patch — on source change, re-derive the artifact and
6
+ * present a 3-way diff; never diff-patch arbitrary code in place.
7
+ * 2. User-override preservation — only `ai_generated` regions are regenerable.
8
+ * The 3-way diff surfaces which hunks are user edits vs regenerated.
9
+ * 3. Freshness — git hash + source mtime compare; in git-less workspaces,
10
+ * degrade to mtime-only (no git, no drift claims).
11
+ *
12
+ * Deterministic and pure where possible: no timestamps inside records beyond
13
+ * the explicit freshness fields.
14
+ */
15
+ import type { DiscoveredApiIndex } from './types';
16
+ /** A project's source freshness fingerprint. */
17
+ export interface ProjectFreshness {
18
+ gitHash?: string;
19
+ /** Max mtime (ms) of any scanned source file under the project root. */
20
+ maxSourceMtime: number;
21
+ }
22
+ /** Drift status for one project. */
23
+ export type DriftStatus = 'current' | 'stale' | 'unknown';
24
+ /** Result of a drift check for a single project. */
25
+ export interface ProjectDrift {
26
+ projectRoot: string;
27
+ status: DriftStatus;
28
+ storedFreshness?: ProjectFreshness;
29
+ currentFreshness: ProjectFreshness;
30
+ /** Human-readable reason for the status. */
31
+ reason?: string;
32
+ }
33
+ /** Drift check across an index. */
34
+ export interface DriftReport {
35
+ projects: ProjectDrift[];
36
+ /** Number of stale projects (needs regeneration). */
37
+ staleCount: number;
38
+ checkedAt: string;
39
+ }
40
+ /**
41
+ * Compute the freshness fingerprint of a project: git HEAD hash (when in a git
42
+ * work tree) and the newest mtime across its source files.
43
+ */
44
+ export declare function computeProjectFreshness(projectRoot: string): ProjectFreshness;
45
+ /**
46
+ * Detect drift for a single project against an existing index.
47
+ *
48
+ * In git work trees, drift is keyed on the git hash (revision changed since the
49
+ * index was built). In git-less workspaces, fall back to the max source mtime —
50
+ * a source file newer than `scannedAt` marks the project stale.
51
+ */
52
+ export declare function detectProjectDrift(projectRoot: string, stored: {
53
+ gitHash?: string;
54
+ scannedAt: string;
55
+ } | undefined): ProjectDrift;
56
+ /** Run drift detection across every project in an index. */
57
+ export declare function detectIndexDrift(index: DiscoveredApiIndex): DriftReport;
58
+ export type DiffLineType = 'same' | 'removed' | 'added';
59
+ export interface DiffHunk {
60
+ type: DiffLineType;
61
+ /** 1-based line number in the relevant version (base for same/removed, target for added). */
62
+ line: number;
63
+ text: string;
64
+ }
65
+ /**
66
+ * A minimal LCS-based line diff between two texts. Returns unified-style hunks
67
+ * in document order (removed lines from `a`, added lines from `b`).
68
+ */
69
+ export declare function diffLines(a: string, b: string): DiffHunk[];
70
+ /**
71
+ * A 3-way diff over a generated artifact:
72
+ * - `base` — the last generated version (ground truth from previous scan)
73
+ * - `current` — what's on disk now (may include user edits)
74
+ * - `regenerated` — freshly re-derived from current source
75
+ *
76
+ * This is the "regenerate, don't patch" surface: the caller shows the user
77
+ * which hunks differ, and only `ai_generated` regions are safe to overwrite.
78
+ */
79
+ export interface ThreeWayDiff {
80
+ /** Line hunks: base → current (what the user changed since generation). */
81
+ userChanges: DiffHunk[];
82
+ /** Line hunks: base → regenerated (what source drift would change). */
83
+ regeneratedChanges: DiffHunk[];
84
+ /** Whether regeneration would change the artifact at all. */
85
+ changed: boolean;
86
+ /** Number of user-edited lines (never auto-overwritten). */
87
+ userEditedLineCount: number;
88
+ }
89
+ export declare function threeWayDiff(base: string, current: string, regenerated: string): ThreeWayDiff;
90
+ /**
91
+ * Given a current artifact and its freshly regenerated version, compute what
92
+ * should be written: regenerate the `ai_generated` regions, preserving user
93
+ * edits. Conflict lines (same region edited both ways) are NOT auto-resolved —
94
+ * they are surfaced in `conflicts` for the developer.
95
+ */
96
+ export declare function resolveRegenerated(current: string, regenerated: string, base: string): {
97
+ merged: string;
98
+ conflicts: DiffHunk[];
99
+ };
100
+ /** A suite artifact that was generated from discovery (carries derived_from). */
101
+ export interface GeneratedSuite {
102
+ id: string;
103
+ name: string;
104
+ /** Serialized suite content currently on disk (may include user edits). */
105
+ currentContent: string;
106
+ /** Endpoint ids this suite was derived from (Phase 2a drift hook). */
107
+ derivedFrom: string[];
108
+ }
109
+ /** Proposed regeneration for one affected suite. */
110
+ export interface SuiteUpdateProposal {
111
+ suiteId: string;
112
+ suiteName: string;
113
+ /** Endpoint ids in this suite that map to a drifted source file. */
114
+ affectedEndpointIds: string[];
115
+ /** 3-way diff: base → current (user edits) vs base → regenerated. */
116
+ diff: ThreeWayDiff;
117
+ /** Whether user edits overlap regeneration (needs developer approval). */
118
+ hasConflicts: boolean;
119
+ }
120
+ /**
121
+ * Map drifted source files → affected endpoints → affected suites, and produce
122
+ * a regeneration proposal (3-way diff) for each affected suite.
123
+ *
124
+ * `storedContent` is the last-generated (base) content for each suite; the
125
+ * caller passes current on-disk content and freshly regenerated content.
126
+ */
127
+ export declare function proposeSuiteUpdates(staleEndpointIds: string[], suites: GeneratedSuite[], baseContent: Record<string, string>, regeneratedContent: Record<string, string>): SuiteUpdateProposal[];
128
+ /**
129
+ * Apply a regeneration proposal for one suite: compute the merged content with
130
+ * user-override preservation (`resolveRegenerated`). When the proposal has no
131
+ * conflicts and the regeneration actually changed something, the caller may
132
+ * write `merged` to disk — the "Developer approves" step. Conflicting proposals
133
+ * are never auto-applied.
134
+ */
135
+ export declare function applyRegenerated(proposal: SuiteUpdateProposal, currentContent: string, regeneratedContent: string, baseContent: string): {
136
+ canApply: boolean;
137
+ merged: string;
138
+ conflicts: number;
139
+ };
@@ -0,0 +1,19 @@
1
+ /**
2
+ * API Discovery — FastAPI Provider
3
+ *
4
+ * NEW provider (no legacy engine to port). Parses FastAPI apps/routers with
5
+ * the pure-JS line parser in `fastapi-parser.ts` (no runtime deps — python3 is
6
+ * never spawned, matching the core "node-only" constraint).
7
+ */
8
+ import { ApiDiscoveryProvider, ProviderSupport } from '../provider';
9
+ import type { DiscoveryContext, DiscoveryResult, FrameworkFingerprint } from '../types';
10
+ export declare class FastApiDiscoveryProvider implements ApiDiscoveryProvider {
11
+ readonly id = "provider.fastapi";
12
+ readonly framework: 'fastapi';
13
+ supports(fingerprint: FrameworkFingerprint): ProviderSupport;
14
+ discover(context: DiscoveryContext, fingerprint: FrameworkFingerprint): Promise<DiscoveryResult>;
15
+ private endpointToDiscoveredApi;
16
+ private paramToDiscovered;
17
+ private buildRequestBody;
18
+ private buildResponses;
19
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * FastAPI source parser — line-oriented, pure JS, no runtime deps.
3
+ *
4
+ * FastAPI's decorator syntax is extremely regular, so we parse it with a
5
+ * balance-aware line walker instead of a heavyweight Python parser:
6
+ *
7
+ * - `app = FastAPI(...)` / `router = APIRouter(prefix=...)` object detection
8
+ * - `@<obj>.<method>(...)` decorators (get/post/put/patch/delete/options/head,
9
+ * plus `api_route` with explicit methods)
10
+ * - path params from `{name}` braces, function-signature param locations via
11
+ * `Path/Query/Header/Cookie/Body/File/Form(...)` wrappers
12
+ * - Pydantic `class X(BaseModel)` → JSON Schema
13
+ * - `include_router(router, prefix=...)` prefix resolution (project-wide)
14
+ *
15
+ * Determinism: endpoints are emitted in file-scan order; the provider sorts.
16
+ * Trust floor: paths built from f-strings/expressions or with an unresolvable
17
+ * router prefix are marked `confidence: 'low'` by the provider.
18
+ */
19
+ import { JsonSchema } from '../types';
20
+ export type ParamLocation = 'path' | 'query' | 'header' | 'cookie' | 'body' | 'form';
21
+ export interface FastApiModelField {
22
+ name: string;
23
+ type: string;
24
+ required: boolean;
25
+ description?: string;
26
+ }
27
+ export interface FastApiModel {
28
+ name: string;
29
+ fields: FastApiModelField[];
30
+ }
31
+ export interface FastApiParam {
32
+ name: string;
33
+ location: ParamLocation;
34
+ type: string;
35
+ required: boolean;
36
+ }
37
+ export interface FastApiEndpoint {
38
+ methods: string[];
39
+ path: string;
40
+ file: string;
41
+ line: number;
42
+ functionName: string;
43
+ statusCode?: number;
44
+ responseModel?: string;
45
+ tags?: string[];
46
+ deprecated?: boolean;
47
+ summary?: string;
48
+ params: FastApiParam[];
49
+ security: string[];
50
+ /** True when the decorator path is an f-string / expression that cannot be trusted. */
51
+ pathUnresolved: boolean;
52
+ }
53
+ export interface FastApiParseResult {
54
+ endpoints: FastApiEndpoint[];
55
+ models: Map<string, FastApiModel>;
56
+ warnings: string[];
57
+ }
58
+ export declare function collectPythonFiles(projectRoot: string): string[];
59
+ export declare function parseFastApiProject(projectRoot: string): FastApiParseResult;
60
+ export declare function buildJsonSchema(typeText: string, models: Map<string, FastApiModel>): JsonSchema | undefined;
@@ -0,0 +1,8 @@
1
+ import { ApiFramework, FrameworkFingerprint } from './types';
2
+ export declare class FrameworkDetector {
3
+ buildFingerprint(projectRoot: string): FrameworkFingerprint;
4
+ detectFrameworks(fingerprint: FrameworkFingerprint): ApiFramework[];
5
+ private hasDependency;
6
+ private hasBuildFile;
7
+ private hasSourceHint;
8
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * API Discovery — public barrel.
3
+ *
4
+ * Phase 1 port target. The unified `DiscoveredApi` model and the
5
+ * `ApiDiscoveryProvider` contract are the seam every framework provider
6
+ * implements and every upstream layer (workflow, tests, maintenance, review)
7
+ * consumes.
8
+ */
9
+ export * from './types';
10
+ export * from './provider';
11
+ export { FrameworkDetector } from './framework-detector';
12
+ export { collectSourceFiles } from './source-files';
13
+ export { loadHybridSeedEndpoints } from './seed-loader';
14
+ export { resolveProjectName } from './project-name';
15
+ export { ExpressDiscoveryProvider } from './providers/express-discovery-provider';
16
+ export { FastifyDiscoveryProvider } from './providers/fastify-discovery-provider';
17
+ export { NestDiscoveryProvider } from './providers/nest-discovery-provider';
18
+ export { LambdaDiscoveryProvider, parseYamlToObject } from './providers/lambda-discovery-provider';
19
+ export { SpringDiscoveryProvider } from './spring/spring-discovery-provider';
20
+ export { FastApiDiscoveryProvider } from './fastapi/fastapi-discovery-provider';
21
+ export * from './analyzer';
22
+ export { generateSuiteFromEndpoints, suiteIdFromName, generateFlowFromEndpoints, } from './test-generator';
23
+ export type { GenerateSuiteOptions, GenerateSuiteResult, GenerateFlowOptions, } from './test-generator';
24
+ export { discoverWorkflows, } from './workflow-discovery';
25
+ export type { WorkflowChain, WorkflowDiscoveryOptions, WorkflowDependent, WorkflowProducer, } from './workflow-discovery';
26
+ export { applyRegenerated, computeProjectFreshness, detectIndexDrift, detectProjectDrift, diffLines, proposeSuiteUpdates, resolveRegenerated, threeWayDiff, } from './drift-engine';
27
+ export type { DiffHunk, DiffLineType, DriftReport, DriftStatus, GeneratedSuite, ProjectDrift, ProjectFreshness, SuiteUpdateProposal, ThreeWayDiff, } from './drift-engine';
28
+ export { ApiDiscoveryService, } from './api-discovery-service';
29
+ export type { IApiDiscoveryService, ApiDiscoveryServiceOptions, } from './api-discovery-service';