@ihelpee/prumo-plugin-go-gin 0.0.0-stage → 0.8.3

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 [yyyy] [name of copyright owner]
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 CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @ihelpee/prumo-plugin-go-gin 🚦
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ <a href="https://www.npmjs.com/package/@ihelpee/prumo-plugin-go-gin"><img src="https://img.shields.io/npm/v/@ihelpee/prumo-plugin-go-gin?logo=npm&color=cb3837&label=npm" alt="npm version" /></a>
5
+ <a href="https://www.apache.org/licenses/LICENSE-2.0"><img src="https://img.shields.io/badge/license-Apache--2.0-blue?logo=apache&logoColor=white" alt="Apache 2.0 license" /></a>
6
+ <a href="https://go.dev/"><img src="https://img.shields.io/badge/go-%3E%3D1.21-00ADD8?logo=go&logoColor=white" alt="Go >= 1.21" /></a>
7
+ <a href="https://nodejs.org/"><img src="https://img.shields.io/badge/node-%3E%3D20.11-339933?logo=node.js&logoColor=white" alt="Node >= 20.11" /></a>
8
+ </p>
9
+
10
+ > Official **Go/Gin** architectural invariant plugin for [Prumo](https://www.npmjs.com/package/@ihelpee/prumo) — the deterministic gatekeeper and business guardrails for AI-assisted engineering.
11
+
12
+ Em Go, os três modos de falha que IA mais comete são estruturais: **rota de mutação sem auth** (Gin espalha middleware por três camadas — inline, `Group.Use`, `Engine.Use` — e a camada de grupo é onde o falso-negativo mora), **erro engolido** (`_ = err`, `x, _ := f()` — a falha silenciosa nativa da linguagem) e **binding sem validação** (`ShouldBindJSON` numa struct sem tags `binding:"..."`). Este plugin fiscaliza os três com AST estática pura — **sem boot do app, sem `go build` do alvo, sem rede**.
13
+
14
+ Go é também a única linguagem do ecossistema Prumo em que a lei do oráculo ("quem gera não especifica a correção") pode ser imposta pelo **próprio compilador**: implementação sob `internal/**` e oráculo num módulo separado (`oracle/go.mod`) tornam o import da implementação um erro de build, não um achado de lint. O plugin recomenda essa topologia como gold standard e tolera a de módulo único (coberta pela regra estática).
15
+
16
+ ## Instalação
17
+
18
+ ```bash
19
+ pnpm add -D @ihelpee/prumo-plugin-go-gin @ihelpee/prumo
20
+ ```
21
+
22
+ Configure em `prumo.config.ts` (o caminho real é `invariants:`, não `plugins:`):
23
+
24
+ ```ts
25
+ import { defineConfig } from '@ihelpee/prumo';
26
+ import { goGinPlugin } from '@ihelpee/prumo-plugin-go-gin';
27
+
28
+ export default defineConfig({
29
+ layout: {
30
+ src: ['internal', 'cmd', 'pkg'],
31
+ oracle: ['oracle'],
32
+ contract: ['.prumo/contract'],
33
+ invariants: ['.prumo/invariants'],
34
+ intent: ['.prumo/intent'],
35
+ waivers: ['.prumo/waivers'],
36
+ },
37
+ testFilePatterns: ['**/*_test.go'],
38
+ invariants: [goGinPlugin()],
39
+ });
40
+ ```
41
+
42
+ Ou em `.prumo/invariants/rules.ts` (onde vivem os waivers):
43
+
44
+ ```ts
45
+ import { goGinPreset } from '@ihelpee/prumo-plugin-go-gin';
46
+ export default goGinPreset;
47
+ ```
48
+
49
+ ## Invariantes
50
+
51
+ | id | sev. | o footgun | fronteira honesta (o que NÃO pega) |
52
+ |---|---|---|---|
53
+ | `mutation-routes-guarded` | error | rota de mutação (`POST`/`PUT`/`PATCH`/`DELETE`) sem auth em **nenhuma** camada — inline, `Group.Use`, `Engine.Use`, com herança **transitiva** de sub-grupos | `Recovery`/`Logger`/`CORS` não contam como auth; `NoAuth()` explícito marca público intencional; rotas de leitura nunca são alvo |
54
+ | `error-handling-enforced` | error | erro descartado deliberadamente: `_ = err`, `x, _ := f()` | `if err := f(); err != nil` não é achado |
55
+ | `error-handling-unchecked` | warn | chamada que retorna `error` usada como statement puro (`db.Save(o)`) | heurística sem type info: só funções em `knownErrReturning` ou vistas com `err` no mesmo arquivo; por isso `warn`, nunca bloqueia sem `--fail-on-warn` |
56
+ | `payload-validation-bound` | error | `ShouldBindJSON`/`Bind` numa struct com campo de dados sem tag `binding:"..."` | tipo não resolvível sintaticamente **não é reportado** (nunca adivinha); `binding:"-"` é ignorado |
57
+ | `payload-validation-query` | warn | binding de query/uri sem tag | validação de query é frequentemente opcional — `warn` |
58
+ | `oracle-no-src` | error | teste de oráculo importando pacote interno da aplicação (resolvido contra o `module` do `go.mod`) | alias, dot e blank import são todos arestas — burla por alias bloqueada |
59
+ | `oracle-whitebox-test` | error | `_test.go` dentro de `internal/**` declarando `package foo` — acessa símbolos não-exportados: espelho branco por construção | `package foo_test` é black-box e não viola |
60
+ | `src-no-oracle` | error | produção importando o diretório de oráculo (fixture vazando para produção) | — |
61
+ | `oracle-module-couples-app` | error | `oracle/go.mod` com `require`/`replace` do módulo da aplicação: a fronteira do compilador foi desativada de propósito | topologia de módulo único não tem `oracle/go.mod` e é coberta por `oracle-no-src` |
62
+ | `no-cross-feature-import` | warn | `internal/<A>/` importando `internal/<B>/` | layouts Go variam — `warn` no MVP |
63
+ | `monetary-is-integer` | warn | campo monetário como `float32`/`float64` | `int64` com sufixo `Cents` é limpo |
64
+ | `go-toolchain-missing` | warn | `go` ausente no host: invariantes Go **não avaliados** | nunca silencioso; `--fail-on-warn` promove a bloqueio |
65
+ | `go-parse-error` | error | arquivo `.go` que não parseia fica invisível às regras | corrigir/excluir o arquivo resolve |
66
+
67
+ ## Como funciona (e por que é seguro)
68
+
69
+ - **Extrator Go stdlib-only** (`go-extractor/`, módulo `ihelpee.dev/prumo-go-extractor`): `go/parser` + `go/ast` serializando a AST em **JSON canônico v1** no stdout. Zero dependência externa — qualquer `require` no `go.mod` do extrator é falha de build.
70
+ - **O extrator é parser, não implementador da lei.** A decisão "isto é violação?" vive 100% no core Node (`rules.ts`). Dois implementadores da mesma lei driftam — auto-refutação para uma ferramenta que caça drift.
71
+ - **Nunca executa o código analisado**: só `parser.ParseFile`. O `go run` do extrator roda de dentro do módulo isolado com `GOTOOLCHAIN=local` e `GOPROXY=off` — o grafo de dependências do alvo nunca é tocado, e a ausência de rede é mecânica, não acidental.
72
+ - **Timeout** (default 20s) no subprocesso; parse patológico não trava o gate.
73
+ - `go` ausente → achado `warn` nomeado, nunca skip mudo.
74
+
75
+ ## Opções
76
+
77
+ ```ts
78
+ goGinPlugin({
79
+ authSymbols: ['Auth', 'RequireAuth', 'JWTAuth'], // R3.5
80
+ publicSymbols: ['NoAuth'], // R3.6
81
+ knownErrReturning: ['Save', 'Exec', 'Do'], // R3.8
82
+ excludePatterns: ['**/gen/**'], // R1.7 (vendor/ e gerados já são default)
83
+ srcDirs: ['internal', 'pkg', 'cmd'], // R2.5/R2.7
84
+ oracleDirs: ['oracle', 'tests/oracle'], // R2.x
85
+ timeoutMs: 20_000, // R1.5
86
+ })
87
+ ```
88
+
89
+ ## Gold standard de oráculo em Go
90
+
91
+ ```
92
+ orders/ # go.mod: module github.com/acme/orders
93
+ internal/orders/handler.go # implementação — só importável neste módulo
94
+ cmd/server/main.go
95
+ oracle/ # módulo SEPARADO: go.mod próprio
96
+ go.mod # SEM require/replace do módulo da aplicação
97
+ orders_blackbox_test.go # HTTP black-box; expectativa do CONTRATO
98
+ ```
99
+
100
+ Nessa topologia o teste-espelho **não compila** — a lei é física, não opinativa. O Prumo vira verificador de intenção (`oracle-module-couples-app`).
101
+
102
+ ## License
103
+
104
+ Apache-2.0
package/dist/ast.d.ts ADDED
@@ -0,0 +1,154 @@
1
+ /**
2
+ * AST Extractor Go — ponte Node ↔ subprocesso Go (spec
3
+ * `docs/especificacao-prumo-go-gin.md` §1).
4
+ *
5
+ * DECISÃO §4.2 (anti-bifurcação da lei): este módulo é DADO do gate, não
6
+ * implementador da lei. O subprocesso Go (`go-extractor/`, stdlib-only)
7
+ * serializa fatos sintáticos em JSON canônico v1; a decisão "isto é
8
+ * violação?" vive 100% nas regras Node deste plugin, executadas pelo
9
+ * `engine.ts` do core.
10
+ *
11
+ * Mecânica (§1.3): `go run` roda DE DENTRO do módulo isolado
12
+ * (`go-extractor/`), nunca do diretório do alvo — o alvo pode não ter
13
+ * vendor nem cache. `GOTOOLCHAIN=local` + `GOPROXY=off` tornam a ausência
14
+ * de rede estrutural, não acidental. O extrator só faz `parser.ParseFile`:
15
+ * o app analisado nunca dá boot.
16
+ */
17
+ export interface GoImport {
18
+ path: string;
19
+ /** '' = sem alias; '_' = blank import; '.' = dot import (R2.3/R2.4). */
20
+ alias: string;
21
+ line: number;
22
+ }
23
+ export interface GoEngineRoot {
24
+ name: string;
25
+ line: number;
26
+ }
27
+ export interface GoRoute {
28
+ /** GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS/ANY */
29
+ method: string;
30
+ path: string;
31
+ handler: string;
32
+ receiver: string;
33
+ inlineGuards: string[];
34
+ line: number;
35
+ }
36
+ export interface GoGroupDef {
37
+ var: string;
38
+ parent: string;
39
+ path: string;
40
+ guards: string[];
41
+ line: number;
42
+ }
43
+ export interface GoUseCall {
44
+ receiver: string;
45
+ guards: string[];
46
+ line: number;
47
+ }
48
+ export interface GoBinding {
49
+ func: string;
50
+ argExpr: string;
51
+ varName: string;
52
+ line: number;
53
+ }
54
+ export interface GoField {
55
+ name: string;
56
+ type: string;
57
+ /** Valor da tag `binding` ('' quando ausente). */
58
+ bindingTag: string;
59
+ hasBinding: boolean;
60
+ }
61
+ export interface GoStruct {
62
+ name: string;
63
+ line: number;
64
+ fields: GoField[];
65
+ }
66
+ export interface GoVarType {
67
+ var: string;
68
+ type: string;
69
+ line: number;
70
+ }
71
+ export interface GoErrSite {
72
+ expr: string;
73
+ line: number;
74
+ }
75
+ export interface GoErrorHandling {
76
+ explicitDiscards: GoErrSite[];
77
+ uncheckedErrCalls: GoErrSite[];
78
+ }
79
+ export interface GoFile {
80
+ path: string;
81
+ package: string;
82
+ isTest: boolean;
83
+ isInternal: boolean;
84
+ imports: GoImport[];
85
+ dynamicImports: string[];
86
+ engineRoots: GoEngineRoot[];
87
+ routes: GoRoute[];
88
+ groupDefs: GoGroupDef[];
89
+ useCalls: GoUseCall[];
90
+ bindings: GoBinding[];
91
+ structs: GoStruct[];
92
+ varTypes: GoVarType[];
93
+ usesErr: boolean;
94
+ /** Fatos R3.8: chamadas que já aparecem com `err` neste arquivo. */
95
+ checkedCallees: string[];
96
+ errorHandling: GoErrorHandling;
97
+ /** R1.3: 'parse' quando o arquivo não parseia — nunca derruba o run. */
98
+ error?: string;
99
+ }
100
+ export interface GoModel {
101
+ version: number;
102
+ /** module path do go.mod do alvo; null se ausente. */
103
+ module: string | null;
104
+ files: GoFile[];
105
+ }
106
+ export type GoRunResult = {
107
+ status: 'ok';
108
+ model: GoModel;
109
+ } | {
110
+ status: 'missing-go';
111
+ } | {
112
+ status: 'timeout';
113
+ timeoutMs: number;
114
+ } | {
115
+ status: 'error';
116
+ message: string;
117
+ };
118
+ export interface GoGinOptions {
119
+ /** Símbolos que contam como auth/autorização (R3.5). */
120
+ authSymbols?: string[];
121
+ /** Convenção de rota pública intencional (R3.6). */
122
+ publicSymbols?: string[];
123
+ /** Whitelist de funções conhecidas por retornar error (R3.8). */
124
+ knownErrReturning?: string[];
125
+ /** Exclusões além das default vendor/ e gerados (R1.7). */
126
+ excludePatterns?: string[];
127
+ /** Diretórios de oráculo para as regras de fronteira (R2.x). */
128
+ oracleDirs?: string[];
129
+ /** Diretórios de implementação para fronteira reversa/white-box (R2.5/R2.7). Default: internal, pkg, cmd. */
130
+ srcDirs?: string[];
131
+ /** Timeout do subprocesso em ms (R1.5). Default 20s. */
132
+ timeoutMs?: number;
133
+ /** Binário do toolchain. Default 'go'. */
134
+ goCommand?: string;
135
+ }
136
+ export declare const DEFAULT_AUTH_SYMBOLS: readonly ["Auth", "Authentication", "Authorize", "RequireAuth", "JWT", "JWTAuth", "BasicAuth", "RequireAdmin", "Guard"];
137
+ export declare const DEFAULT_PUBLIC_SYMBOLS: readonly ["NoAuth"];
138
+ export declare const DEFAULT_KNOWN_ERR_RETURNING: readonly ["Save", "Create", "Update", "Delete", "Exec", "Query", "Close", "Send", "Write", "Marshal", "Unmarshal", "Do", "Scan", "Commit"];
139
+ export declare const DEFAULT_EXCLUDE_PATTERNS: readonly ["**/vendor/**", "**/*.pb.go", "**/*_gen.go", "**/wire_gen.go", "**/testdata/**"];
140
+ export declare const DEFAULT_ORACLE_DIRS: readonly ["oracle", "tests/oracle"];
141
+ export declare const DEFAULT_GO_TIMEOUT_MS = 20000;
142
+ /**
143
+ * `dist/ast.js` e `src/ast.ts` estão ambos a um nível da raiz do pacote,
144
+ * então o mesmo caminho vale em dev (tsx) e em produção (npm pack).
145
+ */
146
+ export declare function goExtractorDir(): string;
147
+ /** R1.6/R1.7: walk do core com `.go`, exclusões de vendor e gerados. */
148
+ export declare function collectGoFiles(root: string, excludePatterns?: readonly string[]): Promise<string[]>;
149
+ /**
150
+ * Executa o extrator Go sobre o alvo. Nunca lança: todo modo de falha é um
151
+ * status nomeado que as regras reportam de forma visível (R1.3/R1.4/R1.5).
152
+ */
153
+ export declare function runGoExtractor(root: string, opts?: GoGinOptions): Promise<GoRunResult>;
154
+ //# sourceMappingURL=ast.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../src/ast.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;;;;;;GAeG;AAMH,MAAM,WAAW,QAAQ;IACvB,IAAI,EAAE,MAAM,CAAC;IACb,wEAAwE;IACxE,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,OAAO;IACtB,iDAAiD;IACjD,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,CA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;IAC3B,gEAAgE;IAChE,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,6GAA6G;IAC7G,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,0CAA0C;IAC1C,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,eAAO,MAAM,oBAAoB,yHAUvB,CAAC;AAEX,eAAO,MAAM,sBAAsB,qBAAsB,CAAC;AAE1D,eAAO,MAAM,2BAA2B,4IAe9B,CAAC;AAEX,eAAO,MAAM,wBAAwB,4FAM3B,CAAC;AAEX,eAAO,MAAM,mBAAmB,qCAAsC,CAAC;AAEvE,eAAO,MAAM,qBAAqB,QAAS,CAAC;AAE5C;;;GAGG;AACH,wBAAgB,cAAc,IAAI,MAAM,CAGvC;AAED,wEAAwE;AACxE,wBAAsB,cAAc,CAClC,IAAI,EAAE,MAAM,EACZ,eAAe,GAAE,SAAS,MAAM,EAA6B,GAC5D,OAAO,CAAC,MAAM,EAAE,CAAC,CAkBnB;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,IAAI,EAAE,MAAM,EACZ,IAAI,GAAE,YAAiB,GACtB,OAAO,CAAC,WAAW,CAAC,CAwDtB"}
package/dist/ast.js ADDED
@@ -0,0 +1,123 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { dirname, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { walk } from '@ihelpee/prumo/core';
5
+ export const DEFAULT_AUTH_SYMBOLS = [
6
+ 'Auth',
7
+ 'Authentication',
8
+ 'Authorize',
9
+ 'RequireAuth',
10
+ 'JWT',
11
+ 'JWTAuth',
12
+ 'BasicAuth',
13
+ 'RequireAdmin',
14
+ 'Guard',
15
+ ];
16
+ export const DEFAULT_PUBLIC_SYMBOLS = ['NoAuth'];
17
+ export const DEFAULT_KNOWN_ERR_RETURNING = [
18
+ 'Save',
19
+ 'Create',
20
+ 'Update',
21
+ 'Delete',
22
+ 'Exec',
23
+ 'Query',
24
+ 'Close',
25
+ 'Send',
26
+ 'Write',
27
+ 'Marshal',
28
+ 'Unmarshal',
29
+ 'Do',
30
+ 'Scan',
31
+ 'Commit',
32
+ ];
33
+ export const DEFAULT_EXCLUDE_PATTERNS = [
34
+ '**/vendor/**',
35
+ '**/*.pb.go',
36
+ '**/*_gen.go',
37
+ '**/wire_gen.go',
38
+ '**/testdata/**',
39
+ ];
40
+ export const DEFAULT_ORACLE_DIRS = ['oracle', 'tests/oracle'];
41
+ export const DEFAULT_GO_TIMEOUT_MS = 20_000;
42
+ /**
43
+ * `dist/ast.js` e `src/ast.ts` estão ambos a um nível da raiz do pacote,
44
+ * então o mesmo caminho vale em dev (tsx) e em produção (npm pack).
45
+ */
46
+ export function goExtractorDir() {
47
+ const here = dirname(fileURLToPath(import.meta.url));
48
+ return resolve(here, '..', 'go-extractor');
49
+ }
50
+ /** R1.6/R1.7: walk do core com `.go`, exclusões de vendor e gerados. */
51
+ export async function collectGoFiles(root, excludePatterns = DEFAULT_EXCLUDE_PATTERNS) {
52
+ return walk(root, '.', {
53
+ extensions: ['.go'],
54
+ ignoreDirs: new Set([
55
+ 'node_modules',
56
+ 'dist',
57
+ 'build',
58
+ 'coverage',
59
+ '.git',
60
+ '.next',
61
+ '.turbo',
62
+ 'tmp',
63
+ '.cache',
64
+ 'vendor',
65
+ 'testdata',
66
+ ]),
67
+ ignorePatterns: [...excludePatterns],
68
+ });
69
+ }
70
+ /**
71
+ * Executa o extrator Go sobre o alvo. Nunca lança: todo modo de falha é um
72
+ * status nomeado que as regras reportam de forma visível (R1.3/R1.4/R1.5).
73
+ */
74
+ export async function runGoExtractor(root, opts = {}) {
75
+ const goCmd = opts.goCommand ?? 'go';
76
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_GO_TIMEOUT_MS;
77
+ const files = await collectGoFiles(root, opts.excludePatterns);
78
+ if (files.length === 0) {
79
+ // Nada .go: nada a fiscalizar — sem ruído de toolchain em repo não-Go.
80
+ return { status: 'ok', model: { version: 1, module: null, files: [] } };
81
+ }
82
+ // R1.4: `go` ausente → status nomeado; a regra vira achado `warn` visível,
83
+ // nunca um skip silencioso.
84
+ const probe = spawnSync(goCmd, ['version'], { encoding: 'utf8', timeout: 5_000 });
85
+ if (probe.error !== undefined || probe.status !== 0) {
86
+ return { status: 'missing-go' };
87
+ }
88
+ // §1.3: cwd = módulo isolado. O alvo nunca é o cwd do `go run`, e
89
+ // GOPROXY=off/GOTOOLCHAIN=local provam a ausência de rede mecanicamente.
90
+ const res = spawnSync(goCmd, ['run', './cmd/prumo-go-extractor', '--root', resolve(root), '--files', files.join(',')], {
91
+ cwd: goExtractorDir(),
92
+ encoding: 'utf8',
93
+ timeout: timeoutMs,
94
+ maxBuffer: 64 * 1024 * 1024,
95
+ env: { ...process.env, GOTOOLCHAIN: 'local', GOPROXY: 'off' },
96
+ });
97
+ if (res.error !== null && res.error !== undefined) {
98
+ const msg = res.error.message;
99
+ if (msg.includes('ETIMEDOUT'))
100
+ return { status: 'timeout', timeoutMs };
101
+ return { status: 'error', message: msg.slice(0, 400) };
102
+ }
103
+ if (res.signal === 'SIGTERM' || res.signal === 'SIGKILL') {
104
+ return { status: 'timeout', timeoutMs };
105
+ }
106
+ if (res.status !== 0) {
107
+ return {
108
+ status: 'error',
109
+ message: ((res.stderr ?? '').trim() || `go-extractor exit ${String(res.status)}`).slice(0, 400),
110
+ };
111
+ }
112
+ let model;
113
+ try {
114
+ model = JSON.parse(String(res.stdout));
115
+ }
116
+ catch {
117
+ return { status: 'error', message: 'stdout do go-extractor não é JSON canônico' };
118
+ }
119
+ if (model.version !== 1) {
120
+ return { status: 'error', message: `contrato v1 esperado; veio version=${String(model.version)}` };
121
+ }
122
+ return { status: 'ok', model };
123
+ }
@@ -0,0 +1,4 @@
1
+ export * from './ast.js';
2
+ export * from './rules.js';
3
+ export { goGinPlugin as default } from './rules.js';
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,UAAU,CAAC;AACzB,cAAc,YAAY,CAAC;AAC3B,OAAO,EAAE,WAAW,IAAI,OAAO,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export * from './ast.js';
2
+ export * from './rules.js';
3
+ export { goGinPlugin as default } from './rules.js';