@gate-forge/pack-fastapi 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 UKD
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,171 @@
1
+ # @gate-forge/pack-fastapi — FastAPI server-route detector
2
+
3
+ Python-AST detector (stdlib only, no app import, no execution, no network)
4
+ served over GPP/3 using the pack-sqlalchemy two-tier structure (ADR 0002):
5
+ the in-process TypeScript wrapper spawns the SAME hardened python plugin
6
+ the subprocess transport runs, so one detector implementation serves both.
7
+
8
+ ## What it finds
9
+
10
+ - `FastAPI()` app instances and `APIRouter(prefix="…")` routers with
11
+ **literal** prefixes; computed prefixes emit a typed
12
+ `FASTAPI_PREFIX_UNRESOLVED` entry (blocking) — never a guess.
13
+ - Route decorators (`@app.get`, `@router.post`, `@router.api_route(
14
+ methods=[...])`, sync and `async` handlers) with **literal** paths;
15
+ computed paths emit `HTTP_PATH_DYNAMIC`.
16
+ - Cross-file mount trees: `include_router(...)` with literal prefixes,
17
+ resolved through scanned-file imports (absolute and relative), including
18
+ import-aliased router names (`from .routers import router as r`) whose
19
+ routes merge into the defining router, and module-import attribute
20
+ chains (`from api.v1 import endpoints` + `endpoints.health.router`).
21
+ Repeated mounts yield one fact per mount. Unresolvable or ambiguous
22
+ targets/aliases and include cycles emit `FASTAPI_PREFIX_UNRESOLVED`.
23
+ - Package-attribute imports: `from pkg import attr` where `pkg/attr.py`
24
+ does not exist resolves `attr` through the package's `__init__.py`
25
+ module-level bindings — an assignment (`router = APIRouter()`) or an
26
+ import re-export (`from .endpoints import router`), followed up to 8
27
+ hops. Ambiguity stays a typed `FASTAPI_PREFIX_UNRESOLVED` entry.
28
+ - **Registry functions** (the central-registrar pattern): a function
29
+ whose body calls `include_router` on one of its own parameters —
30
+ `def register_all_routers(app): app.include_router(r, prefix=...)` —
31
+ has those includes rewired onto whatever the call-site argument names
32
+ (details below).
33
+ - Verbs outside the supported set (e.g. `@router.trace`) emit
34
+ `HTTP_METHOD_DYNAMIC` — nothing disappears silently.
35
+ - Per fact: handler symbol, `isAsync`, `response_model`, request schema
36
+ symbols (non-primitive, non-path parameter annotations), `tags`,
37
+ `operationId`, and `mountProvenance` (`include-chain` | `standalone`).
38
+
39
+ ## Configuration: `.gateforge/fastapi.json`
40
+
41
+ Optional, JSON-only, read from the repo root (same precedent as
42
+ pack-http's `.gateforge/http-clients.json`): **absence is normal,
43
+ malformed documents throw.**
44
+
45
+ ```json
46
+ { "importRoots": ["backend"] }
47
+ ```
48
+
49
+ `importRoots` lists repo-root-relative directories that act as Python
50
+ import roots for ABSOLUTE imports — the central-router-registry pattern
51
+ where one module registers everything
52
+ (`from api.v1.endpoints import activities` /
53
+ `app.include_router(activities.router, prefix="/api/v1")`). With roots
54
+ configured:
55
+
56
+ - `from api.v1.endpoints import activities` binds the scanned file
57
+ `<importRoot>/api/v1/endpoints/activities.py` (or its package
58
+ `__init__.py`), so registry includes resolve and effective paths carry
59
+ their real prefixes (`/api/v1/activities/{id}`).
60
+ - `from api.v1 import activities` + `activities.router` (the imported
61
+ name is the module) and deeper chains
62
+ (`from api.v1 import endpoints` + `endpoints.health.router`) resolve
63
+ through the same roots.
64
+ - **Uniqueness is mandatory**: a dotted module matching MORE THAN ONE
65
+ scanned file across the roots is a typed blocking
66
+ `FASTAPI_PREFIX_UNRESOLVED` entry that names the conflicting files —
67
+ never a guess. Imports resolving to nothing scanned stay typed-
68
+ unresolved as usual (closed world: no scan hole is hidden). With roots
69
+ configured the absolute-import suffix heuristic is disabled (explicit
70
+ roots govern); relative imports and everything else are unchanged.
71
+ - Without the config file the detector behaves exactly as before.
72
+
73
+ The in-process wrapper passes the roots to the python scanner as an
74
+ explicit `--import-roots <json-array>` argv flag; the subprocess
75
+ transport can pass the same flag directly.
76
+
77
+ ## Registry functions: `include_router` through a function parameter
78
+
79
+ Real backends often register every router inside one function
80
+ (`backend/router_registry.py`):
81
+
82
+ ```python
83
+ def register_all_routers(app): # app is a PARAMETER
84
+ app.include_router(activities_router, prefix="/api/v1/activities")
85
+ ... # × 79 includes
86
+
87
+ # server.py
88
+ fastapi_app = FastAPI(...)
89
+ register_all_routers(fastapi_app) # module-level call site
90
+ ```
91
+
92
+ Without interprocedural support the parameter breaks the mount-graph
93
+ walk: the routers are provably included (so suppressed from standalone
94
+ emission) yet contribute ZERO endpoints. The detector closes that gap,
95
+ bounded and deterministic:
96
+
97
+ - **Collection**: a top-level function whose body calls
98
+ `include_router` on one of its own parameters collects those include
99
+ edges keyed by the parameter (nested functions count for the
100
+ enclosing top-level function; positional parameters only — call sites
101
+ bind positionally).
102
+ - **Materialization**: every call site of such a function whose argument
103
+ resolves to a known `FastAPI()`/`APIRouter()` instance variable — a
104
+ same-file assignment (module-level **or** factory-local:
105
+ `def create_app(): app = FastAPI(); register(app)` works because the
106
+ local instance is walked) or an import binding to another scanned
107
+ file's instance — receives the edges as ordinary includes on that
108
+ instance. Provenance is unchanged: `include-chain` at the include
109
+ call's own source location; repeated call sites duplicate mounts,
110
+ exactly like written includes.
111
+ - **Chaining**: a registry function may pass its parameter to another
112
+ helper (`def create_app(app): register_all_routers(app)`) up to
113
+ **8 helper hops** (`MAX_RESOLUTION_DEPTH`). Chains beyond the bound
114
+ yield one typed unresolved entry naming the function that would need
115
+ hop 9 — no silent drop, no guess.
116
+ - **Unresolvable arguments** (a name bound to no known instance, or a
117
+ computed expression): the honest outcome is a typed
118
+ `FASTAPI_PREFIX_UNRESOLVED` entry at the exact call site and **no
119
+ emission** — the routers are provably included somewhere and their
120
+ source carries prefixes, so prefix-less standalone paths would
121
+ fabricate routes. A never-called registry function mounts nothing and
122
+ stays silent (closed world: no scan hole is hidden, and no mount is
123
+ invented). A parameter name shadowing a same-file instance variable
124
+ keeps the module-level reading only (no double emission).
125
+
126
+ ## Output model (ADR 0004 D1)
127
+
128
+ One `http.contract` resource per (effective mounted path, concrete
129
+ method). These are **evidence-only**: the engine-owned graph excludes
130
+ them from business classification (no route/table collision) and the
131
+ endpoint compiler joins them against frontend-call facts
132
+ (`@gate-forge/http-contract`). The TypeScript wrapper fills the canonical
133
+ `normalizedPath` (single canonicalization implementation across
134
+ languages) and mints **no classification signals** (dogfood remediation
135
+ phase 4): the earlier `exposure: route` / `lifecycle.*` signals were
136
+ targeted at the path-derived business name — a guess that mostly names
137
+ no discovered resource (`/admin-bypasses` vs the real table), producing
138
+ `STALE_SIGNAL_TARGET` blockers while adding nothing, since unknown
139
+ exposure defaults `user-facing` and unknown lifecycle operations default
140
+ enabled (ADR 0003 D5). Route→resource linkage belongs to the CLI
141
+ endpoint compiler, which corroborates the candidate name against the
142
+ schema symbols (`requestSchemaSymbols`/`responseSchemaSymbols`) and
143
+ handler names these very facts carry, and blocks ambiguity with typed
144
+ `ENDPOINT_RESOURCE_LINK_UNRESOLVED`. Core's `STALE_SIGNAL_TARGET`
145
+ detection remains for genuinely stale authority signals (declaration
146
+ markers, adapter bindings, read-only declarations).
147
+
148
+ ## Setup
149
+
150
+ ```yaml
151
+ # .gateforge.yml
152
+ plugins:
153
+ - id: gateforge.pack-fastapi
154
+ version: 0.1.0
155
+ transport: in-process
156
+ module: '@gate-forge/pack-fastapi'
157
+ ```
158
+
159
+ Requires Node >= 20 and `python3` >= 3.11 on PATH; no network at any
160
+ point.
161
+
162
+ Subprocess transport (equivalent):
163
+
164
+ ```yaml
165
+ plugins:
166
+ - id: gateforge.pack-fastapi
167
+ version: 0.1.0
168
+ transport: subprocess
169
+ command: ['python3', '-m', 'gateforge_fastapi_detector']
170
+ # with PYTHONPATH=<pack>/python:<plugin-protocol>/python
171
+ ```
@@ -0,0 +1,73 @@
1
+ /** The subprocess command the in-process transport spawns (G4 surface). */
2
+ export declare const DEFAULT_COMMAND: string[];
3
+ /**
4
+ * The detector's config channel: a JSON document read from the repo root
5
+ * (same precedent as pack-http's `.gateforge/http-clients.json`). Absence
6
+ * is normal; a malformed document throws (fail closed).
7
+ */
8
+ export declare const FASTAPI_SCAN_CONFIG_PATH = ".gateforge/fastapi.json";
9
+ /** Parsed `.gateforge/fastapi.json` document (strict schema). */
10
+ export interface FastapiScanConfig {
11
+ /**
12
+ * Repo-root-relative directories that act as Python import roots for
13
+ * ABSOLUTE imports — the central-router-registry pattern
14
+ * (`from api.v1.endpoints import activities` +
15
+ * `app.include_router(activities.router, prefix=...)`). Resolution is
16
+ * unique or typed-unresolved: an import matching more than one scanned
17
+ * file across the roots never guesses.
18
+ */
19
+ importRoots?: readonly string[];
20
+ }
21
+ export declare const DEFAULT_FASTAPI_SCAN_CONFIG: FastapiScanConfig;
22
+ /**
23
+ * Reads a fastapi detector config document. Returns the default config
24
+ * when the file is absent; malformed documents throw (fail closed — the
25
+ * CLI surfaces the error instead of scanning with partial trust).
26
+ */
27
+ export declare function readFastapiScanConfigOrNull(path: string | null): FastapiScanConfig;
28
+ /**
29
+ * Builds the environment the python detector runs under: the host env
30
+ * plus a `PYTHONPATH` that makes both this pack's detector and the GPP/3
31
+ * client importable.
32
+ */
33
+ export declare function pythonEnvironment(extra?: readonly string[]): NodeJS.ProcessEnv;
34
+ /** Options for {@link createFastapiDetector}. */
35
+ export interface FastapiDetectorOptions {
36
+ /** Subprocess argv (default: `python3 -m gateforge_fastapi_detector`). */
37
+ command?: readonly string[];
38
+ /** Subprocess environment (default: {@link pythonEnvironment}). */
39
+ env?: NodeJS.ProcessEnv;
40
+ /** Working directory the repo-relative paths resolve against. */
41
+ cwd?: string;
42
+ /** Handshake-pinned plugin id (default: the pack id). */
43
+ pluginId?: string;
44
+ /** Handshake-pinned plugin version (default: the pack version). */
45
+ pluginVersion?: string;
46
+ /**
47
+ * Explicit import roots (repo-root-relative); overrides the config
48
+ * document entirely when given.
49
+ */
50
+ importRoots?: readonly string[];
51
+ /**
52
+ * Repo-relative path of a config document (JSON) read from `cwd` when
53
+ * `importRoots` is not given (default: `.gateforge/fastapi.json`;
54
+ * absence is normal, malformed throws).
55
+ */
56
+ importRootsConfigPath?: string;
57
+ }
58
+ /** The pinned in-process plugin contract: `{ discover(paths) }`. */
59
+ export interface FastapiDetector {
60
+ discover(paths: readonly string[]): Promise<{
61
+ resources: unknown[];
62
+ unresolved: unknown[];
63
+ findings: unknown[];
64
+ classificationSignals: unknown[];
65
+ scannedPaths?: string[];
66
+ }>;
67
+ }
68
+ /**
69
+ * Creates a discover-capable detector module. The default export of the
70
+ * pack is `createFastapiDetector()` — the CLI in-process contract.
71
+ */
72
+ export declare function createFastapiDetector(options?: FastapiDetectorOptions): FastapiDetector;
73
+ //# sourceMappingURL=detector.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detector.d.ts","sourceRoot":"","sources":["../src/detector.ts"],"names":[],"mappings":"AA4CA,2EAA2E;AAC3E,eAAO,MAAM,eAAe,UAAkD,CAAC;AAE/E;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,4BAA4B,CAAC;AAElE,iEAAiE;AACjE,MAAM,WAAW,iBAAiB;IAChC;;;;;;;OAOG;IACH,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACjC;AAED,eAAO,MAAM,2BAA2B,EAAE,iBAAsB,CAAC;AAsBjE;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,iBAAiB,CAkClF;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,GAAE,SAAS,MAAM,EAAO,GAAG,MAAM,CAAC,UAAU,CAGlF;AAED,iDAAiD;AACjD,MAAM,WAAW,sBAAsB;IACrC,0EAA0E;IAC1E,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC5B,mEAAmE;IACnE,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,iEAAiE;IACjE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,yDAAyD;IACzD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mEAAmE;IACnE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB;;;OAGG;IACH,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAChC;;;;OAIG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;CAChC;AAED,oEAAoE;AACpE,MAAM,WAAW,eAAe;IAC9B,QAAQ,CACN,KAAK,EAAE,SAAS,MAAM,EAAE,GACvB,OAAO,CAAC;QACT,SAAS,EAAE,OAAO,EAAE,CAAC;QACrB,UAAU,EAAE,OAAO,EAAE,CAAC;QACtB,QAAQ,EAAE,OAAO,EAAE,CAAC;QACpB,qBAAqB,EAAE,OAAO,EAAE,CAAC;QACjC,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;KACzB,CAAC,CAAC;CACJ;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,GAAE,sBAA2B,GAAG,eAAe,CAuC3F"}
@@ -0,0 +1,192 @@
1
+ /**
2
+ * The pack's discover entry: a thin TypeScript GPP/3 client over the
3
+ * Python AST detector, usable from BOTH CLI transports (the pack-sqlalchemy
4
+ * pattern; see ADR 0002 for the two-tier boundary).
5
+ *
6
+ * - **in-process**: `.gateforge.yml` declares
7
+ * `transport: in-process, module: "@gate-forge/pack-fastapi"`; the CLI
8
+ * imports this package's default export and calls `discover(paths)`.
9
+ * The implementation spawns the SAME python detector (GPP/3, hardened
10
+ * host) with a computed `PYTHONPATH`, so one detector implementation
11
+ * serves both transports.
12
+ * - **subprocess**: `.gateforge.yml` declares
13
+ * `transport: subprocess, command: ["python3","-m","gateforge_fastapi_detector"]`
14
+ * (with the pack's `python/` dir on `PYTHONPATH`); the CLI drives the
15
+ * plugin directly — see the README.
16
+ *
17
+ * Post-processing (`facts.ts`): effective paths are canonicalized with the
18
+ * shared `@gate-forge/http-contract` rules. The wrapper mints NO
19
+ * classification signals (dogfood remediation phase 4): a path-derived
20
+ * target is a guess that mostly names no discovered resource — route→resource
21
+ * linkage is the CLI endpoint compiler's exclusive job (schema-symbol/
22
+ * handler corroboration over the facts this pack emits).
23
+ *
24
+ * Determinism: the python scan is pure over (paths, file bytes). The
25
+ * optional `.gateforge/fastapi.json` config (import roots for absolute
26
+ * imports, the central-router-registry pattern) is read once at factory
27
+ * time and passed to the scanner as an explicit `--import-roots` argv
28
+ * flag — never environment state, never per-request mutation.
29
+ */
30
+ import { readFileSync } from 'node:fs';
31
+ import { delimiter, resolve } from 'node:path';
32
+ import { fileURLToPath } from 'node:url';
33
+ import { PluginSession } from '@gate-forge/plugin-protocol';
34
+ import { canonicalizeFacts } from './facts.js';
35
+ import { PACK_PLUGIN_ID, PACK_VERSION } from './version.js';
36
+ /** Absolute dir of this pack's `python/` tree (the detector package). */
37
+ const PACK_PYTHON_DIR = fileURLToPath(new URL('../python', import.meta.url));
38
+ /** Absolute dir of the sibling `@gate-forge/plugin-protocol` python client. */
39
+ const PROTOCOL_PYTHON_DIR = fileURLToPath(new URL('../../../plugin-protocol/python', import.meta.url));
40
+ /** The subprocess command the in-process transport spawns (G4 surface). */
41
+ export const DEFAULT_COMMAND = ['python3', '-m', 'gateforge_fastapi_detector'];
42
+ /**
43
+ * The detector's config channel: a JSON document read from the repo root
44
+ * (same precedent as pack-http's `.gateforge/http-clients.json`). Absence
45
+ * is normal; a malformed document throws (fail closed).
46
+ */
47
+ export const FASTAPI_SCAN_CONFIG_PATH = '.gateforge/fastapi.json';
48
+ export const DEFAULT_FASTAPI_SCAN_CONFIG = {};
49
+ /** One repo-relative import root, validated (fail closed on malformed). */
50
+ function normalizeImportRoot(raw, path) {
51
+ if (typeof raw !== 'string') {
52
+ throw new Error(`invalid fastapi detector config: import roots must be strings at ${path}`);
53
+ }
54
+ const stripped = raw.replace(/\\/g, '/').replace(/\/+$/, '');
55
+ let normalized = stripped;
56
+ while (normalized.startsWith('./'))
57
+ normalized = normalized.slice(2);
58
+ const segments = normalized.split('/');
59
+ if (normalized === '' || normalized.startsWith('/') || segments.includes('..')) {
60
+ throw new Error(`invalid fastapi detector config: import root must be a repo-root-relative ` +
61
+ `directory at ${path}: ${JSON.stringify(raw)}`);
62
+ }
63
+ return normalized;
64
+ }
65
+ /**
66
+ * Reads a fastapi detector config document. Returns the default config
67
+ * when the file is absent; malformed documents throw (fail closed — the
68
+ * CLI surfaces the error instead of scanning with partial trust).
69
+ */
70
+ export function readFastapiScanConfigOrNull(path) {
71
+ if (path === null)
72
+ return DEFAULT_FASTAPI_SCAN_CONFIG;
73
+ let text;
74
+ try {
75
+ text = readFileSync(path, 'utf8');
76
+ }
77
+ catch {
78
+ return DEFAULT_FASTAPI_SCAN_CONFIG; // absence is normal; malformed is not (below)
79
+ }
80
+ const parsed = JSON.parse(text);
81
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
82
+ throw new Error(`invalid fastapi detector config: expected an object at ${path}`);
83
+ }
84
+ const document = parsed;
85
+ const unknownKeys = Object.keys(document).filter((key) => key !== 'importRoots');
86
+ if (unknownKeys.length > 0) {
87
+ // Strict on purpose: a typo'd key would otherwise silently disable the
88
+ // import roots and hide exactly the routes they exist to expose.
89
+ throw new Error(`invalid fastapi detector config: unknown key(s) ` +
90
+ `${unknownKeys.sort().join(', ')} at ${path}`);
91
+ }
92
+ const config = {};
93
+ const roots = document['importRoots'];
94
+ if (roots !== undefined) {
95
+ if (!Array.isArray(roots)) {
96
+ throw new Error(`invalid fastapi detector config: 'importRoots' must be an array of ` +
97
+ `repo-root-relative directories at ${path}`);
98
+ }
99
+ config.importRoots = roots.map((root) => normalizeImportRoot(root, path));
100
+ }
101
+ return config;
102
+ }
103
+ /**
104
+ * Builds the environment the python detector runs under: the host env
105
+ * plus a `PYTHONPATH` that makes both this pack's detector and the GPP/3
106
+ * client importable.
107
+ */
108
+ export function pythonEnvironment(extra = []) {
109
+ const entries = [...extra, PACK_PYTHON_DIR, PROTOCOL_PYTHON_DIR];
110
+ return { ...process.env, PYTHONPATH: entries.join(delimiter) };
111
+ }
112
+ /**
113
+ * Creates a discover-capable detector module. The default export of the
114
+ * pack is `createFastapiDetector()` — the CLI in-process contract.
115
+ */
116
+ export function createFastapiDetector(options = {}) {
117
+ const command = options.command ?? DEFAULT_COMMAND;
118
+ const env = options.env ?? pythonEnvironment();
119
+ const cwd = options.cwd ?? process.cwd();
120
+ const pluginId = options.pluginId ?? PACK_PLUGIN_ID;
121
+ const pluginVersion = options.pluginVersion ?? PACK_VERSION;
122
+ // Explicit roots win; otherwise the config document (absence normal,
123
+ // malformed throws). With no roots at all the spawned command is
124
+ // byte-identical to the pre-config surface.
125
+ const importRoots = options.importRoots ??
126
+ readFastapiScanConfigOrNull(resolve(cwd, options.importRootsConfigPath ?? FASTAPI_SCAN_CONFIG_PATH))
127
+ .importRoots ??
128
+ [];
129
+ const argv = importRoots.length > 0 ? [...command, '--import-roots', JSON.stringify(importRoots)] : [...command];
130
+ return {
131
+ async discover(paths) {
132
+ if (paths.length === 0) {
133
+ return { resources: [], unresolved: [], findings: [], classificationSignals: [] };
134
+ }
135
+ const session = new PluginSession({
136
+ command: argv,
137
+ pluginId,
138
+ pluginVersion,
139
+ cwd,
140
+ env,
141
+ timeouts: { handshakeMs: 10_000, requestMs: 30_000, shutdownMs: 10_000 },
142
+ });
143
+ try {
144
+ await session.start();
145
+ const outcome = await session.discover([...paths]);
146
+ return postprocess(outcome);
147
+ }
148
+ finally {
149
+ await session.dispose();
150
+ }
151
+ },
152
+ };
153
+ }
154
+ /**
155
+ * Canonicalizes facts and merges the wrapper's unresolved entries with the
156
+ * python scanner's, keeping the whole outcome deterministic.
157
+ */
158
+ function postprocess(outcome) {
159
+ const canonical = canonicalizeFacts(outcome.resources);
160
+ const unresolved = [
161
+ ...outcome.unresolved,
162
+ ...canonical.unresolved,
163
+ ].sort((a, b) => {
164
+ const locationA = a['location'];
165
+ const locationB = b['location'];
166
+ const fileA = locationA?.['file'] ?? '';
167
+ const fileB = locationB?.['file'] ?? '';
168
+ if (fileA !== fileB)
169
+ return fileA < fileB ? -1 : 1;
170
+ const lineA = locationA?.['line'] ?? 0;
171
+ const lineB = locationB?.['line'] ?? 0;
172
+ if (lineA !== lineB)
173
+ return lineA - lineB;
174
+ const codeA = String(a['code'] ?? '');
175
+ const codeB = String(b['code'] ?? '');
176
+ if (codeA !== codeB)
177
+ return codeA < codeB ? -1 : 1;
178
+ const detailA = String(a['detail'] ?? '');
179
+ const detailB = String(b['detail'] ?? '');
180
+ if (detailA === detailB)
181
+ return 0;
182
+ return detailA < detailB ? -1 : 1;
183
+ });
184
+ return {
185
+ resources: canonical.resources,
186
+ unresolved,
187
+ findings: outcome.findings,
188
+ classificationSignals: canonical.classificationSignals,
189
+ ...(outcome.scannedPaths !== undefined ? { scannedPaths: outcome.scannedPaths } : {}),
190
+ };
191
+ }
192
+ //# sourceMappingURL=detector.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"detector.js","sourceRoot":"","sources":["../src/detector.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC/C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,aAAa,EAAyB,MAAM,6BAA6B,CAAC;AACnF,OAAO,EAAE,iBAAiB,EAAyB,MAAM,YAAY,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAE5D,yEAAyE;AACzE,MAAM,eAAe,GAAG,aAAa,CAAC,IAAI,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAE7E,+EAA+E;AAC/E,MAAM,mBAAmB,GAAG,aAAa,CACvC,IAAI,GAAG,CAAC,iCAAiC,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAC5D,CAAC;AAEF,2EAA2E;AAC3E,MAAM,C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