@topogram/cli 0.3.34

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 (257) hide show
  1. package/ARCHITECTURE.md +67 -0
  2. package/CHANGELOG.md +240 -0
  3. package/README.md +223 -0
  4. package/package.json +51 -0
  5. package/src/adoption/index.js +3 -0
  6. package/src/adoption/plan.js +702 -0
  7. package/src/adoption/reporting.js +464 -0
  8. package/src/adoption/review-groups.js +313 -0
  9. package/src/agent-ops/query-builders.js +5012 -0
  10. package/src/archive/archive.js +141 -0
  11. package/src/archive/compact.js +26 -0
  12. package/src/archive/jsonl.js +70 -0
  13. package/src/archive/resolver-bridge.js +82 -0
  14. package/src/archive/schema.js +87 -0
  15. package/src/archive/unarchive.js +108 -0
  16. package/src/catalog.js +752 -0
  17. package/src/cli/catalog-alias.js +166 -0
  18. package/src/cli.js +9738 -0
  19. package/src/component-behavior.js +173 -0
  20. package/src/example-implementation.js +91 -0
  21. package/src/format.js +19 -0
  22. package/src/generator/adapters.d.ts +4 -0
  23. package/src/generator/adapters.js +325 -0
  24. package/src/generator/api.d.ts +1 -0
  25. package/src/generator/api.js +1196 -0
  26. package/src/generator/check.js +355 -0
  27. package/src/generator/component-conformance.js +767 -0
  28. package/src/generator/components.js +39 -0
  29. package/src/generator/context/bundle.js +291 -0
  30. package/src/generator/context/diff.js +256 -0
  31. package/src/generator/context/digest.js +182 -0
  32. package/src/generator/context/domain-coverage.js +94 -0
  33. package/src/generator/context/domain-page.js +137 -0
  34. package/src/generator/context/index.js +42 -0
  35. package/src/generator/context/report.js +121 -0
  36. package/src/generator/context/shared.js +1397 -0
  37. package/src/generator/context/slice.js +703 -0
  38. package/src/generator/context/task-mode.js +466 -0
  39. package/src/generator/docs.js +327 -0
  40. package/src/generator/index.js +161 -0
  41. package/src/generator/native/parity-bundle.js +311 -0
  42. package/src/generator/output.js +300 -0
  43. package/src/generator/registry.js +482 -0
  44. package/src/generator/runtime/app-bundle.js +456 -0
  45. package/src/generator/runtime/bundle-shared.js +166 -0
  46. package/src/generator/runtime/compile-check.js +163 -0
  47. package/src/generator/runtime/deployment.js +287 -0
  48. package/src/generator/runtime/environment.js +635 -0
  49. package/src/generator/runtime/index.js +32 -0
  50. package/src/generator/runtime/runtime-check.js +554 -0
  51. package/src/generator/runtime/shared.js +515 -0
  52. package/src/generator/runtime/smoke.js +219 -0
  53. package/src/generator/schema.js +204 -0
  54. package/src/generator/sdlc/board.js +66 -0
  55. package/src/generator/sdlc/doc-page.js +53 -0
  56. package/src/generator/sdlc/index.js +23 -0
  57. package/src/generator/sdlc/release-notes.js +62 -0
  58. package/src/generator/sdlc/traceability-matrix.js +65 -0
  59. package/src/generator/shared.js +29 -0
  60. package/src/generator/surfaces/contracts.js +146 -0
  61. package/src/generator/surfaces/databases/contract.js +40 -0
  62. package/src/generator/surfaces/databases/index.js +84 -0
  63. package/src/generator/surfaces/databases/lifecycle-shared.d.ts +1 -0
  64. package/src/generator/surfaces/databases/lifecycle-shared.js +612 -0
  65. package/src/generator/surfaces/databases/migration-plan.js +281 -0
  66. package/src/generator/surfaces/databases/postgres/capabilities.js +14 -0
  67. package/src/generator/surfaces/databases/postgres/drizzle.js +99 -0
  68. package/src/generator/surfaces/databases/postgres/index.js +9 -0
  69. package/src/generator/surfaces/databases/postgres/lifecycle.js +16 -0
  70. package/src/generator/surfaces/databases/postgres/prisma.js +159 -0
  71. package/src/generator/surfaces/databases/postgres/sql-migration.js +102 -0
  72. package/src/generator/surfaces/databases/postgres/sql-schema.js +34 -0
  73. package/src/generator/surfaces/databases/shared.d.ts +1 -0
  74. package/src/generator/surfaces/databases/shared.js +350 -0
  75. package/src/generator/surfaces/databases/snapshot.js +96 -0
  76. package/src/generator/surfaces/databases/sqlite/capabilities.js +14 -0
  77. package/src/generator/surfaces/databases/sqlite/index.js +8 -0
  78. package/src/generator/surfaces/databases/sqlite/lifecycle.js +16 -0
  79. package/src/generator/surfaces/databases/sqlite/prisma.js +143 -0
  80. package/src/generator/surfaces/databases/sqlite/sql-migration.js +65 -0
  81. package/src/generator/surfaces/databases/sqlite/sql-schema.js +27 -0
  82. package/src/generator/surfaces/index.js +25 -0
  83. package/src/generator/surfaces/native/swiftui-app.js +38 -0
  84. package/src/generator/surfaces/native/swiftui-templates/Package.swift.txt +20 -0
  85. package/src/generator/surfaces/native/swiftui-templates/README.generated.md +26 -0
  86. package/src/generator/surfaces/native/swiftui-templates/runtime/DynamicScreens.swift +682 -0
  87. package/src/generator/surfaces/native/swiftui-templates/runtime/TodoAPIClient.swift +156 -0
  88. package/src/generator/surfaces/native/swiftui-templates/runtime/TodoSwiftUIApp.swift +44 -0
  89. package/src/generator/surfaces/native/swiftui-templates/runtime/Visibility.swift +183 -0
  90. package/src/generator/surfaces/services/express.d.ts +1 -0
  91. package/src/generator/surfaces/services/express.js +766 -0
  92. package/src/generator/surfaces/services/hono.d.ts +1 -0
  93. package/src/generator/surfaces/services/hono.js +204 -0
  94. package/src/generator/surfaces/services/index.js +42 -0
  95. package/src/generator/surfaces/services/persistence-wiring.js +240 -0
  96. package/src/generator/surfaces/services/runtime-helpers.js +631 -0
  97. package/src/generator/surfaces/services/server-contract.js +80 -0
  98. package/src/generator/surfaces/services/stateless.d.ts +1 -0
  99. package/src/generator/surfaces/services/stateless.js +97 -0
  100. package/src/generator/surfaces/shared.js +64 -0
  101. package/src/generator/surfaces/web/api-client.js +1 -0
  102. package/src/generator/surfaces/web/forms.js +1 -0
  103. package/src/generator/surfaces/web/index.d.ts +2 -0
  104. package/src/generator/surfaces/web/index.js +53 -0
  105. package/src/generator/surfaces/web/react-components.js +248 -0
  106. package/src/generator/surfaces/web/react.js +538 -0
  107. package/src/generator/surfaces/web/routes.js +1 -0
  108. package/src/generator/surfaces/web/screens.js +1 -0
  109. package/src/generator/surfaces/web/shared.js +369 -0
  110. package/src/generator/surfaces/web/sveltekit-actions.js +28 -0
  111. package/src/generator/surfaces/web/sveltekit-components.js +234 -0
  112. package/src/generator/surfaces/web/sveltekit.js +426 -0
  113. package/src/generator/surfaces/web/ui-web-contract.js +65 -0
  114. package/src/generator/surfaces/web/vanilla.js +239 -0
  115. package/src/generator/verification.js +84 -0
  116. package/src/generator.js +1 -0
  117. package/src/import/core/context.js +52 -0
  118. package/src/import/core/contracts.js +23 -0
  119. package/src/import/core/registry.js +81 -0
  120. package/src/import/core/runner.js +646 -0
  121. package/src/import/core/shared.js +910 -0
  122. package/src/import/enrichers/auth-session.js +18 -0
  123. package/src/import/enrichers/django-rest.js +226 -0
  124. package/src/import/enrichers/doc-linking.js +20 -0
  125. package/src/import/enrichers/rails-controllers.js +246 -0
  126. package/src/import/enrichers/rails-models.js +130 -0
  127. package/src/import/enrichers/workflow-target-state.js +10 -0
  128. package/src/import/extractors/api/aspnet-core.js +304 -0
  129. package/src/import/extractors/api/django-routes.js +318 -0
  130. package/src/import/extractors/api/express.js +154 -0
  131. package/src/import/extractors/api/fastify.js +371 -0
  132. package/src/import/extractors/api/flutter-dio.js +135 -0
  133. package/src/import/extractors/api/generic-route-fallback.js +90 -0
  134. package/src/import/extractors/api/graphql-code-first.js +565 -0
  135. package/src/import/extractors/api/graphql-sdl.js +309 -0
  136. package/src/import/extractors/api/jaxrs.js +303 -0
  137. package/src/import/extractors/api/micronaut.js +213 -0
  138. package/src/import/extractors/api/next-route.js +50 -0
  139. package/src/import/extractors/api/next-server-action.js +51 -0
  140. package/src/import/extractors/api/nextauth.js +52 -0
  141. package/src/import/extractors/api/openapi-code.js +242 -0
  142. package/src/import/extractors/api/openapi.js +232 -0
  143. package/src/import/extractors/api/rails-routes.js +230 -0
  144. package/src/import/extractors/api/react-native-repository.js +128 -0
  145. package/src/import/extractors/api/retrofit.js +103 -0
  146. package/src/import/extractors/api/spring-web.js +372 -0
  147. package/src/import/extractors/api/swift-webapi.js +116 -0
  148. package/src/import/extractors/api/trpc.js +212 -0
  149. package/src/import/extractors/db/django-models.js +232 -0
  150. package/src/import/extractors/db/dotnet-models.js +93 -0
  151. package/src/import/extractors/db/drizzle.js +242 -0
  152. package/src/import/extractors/db/ef-core.js +221 -0
  153. package/src/import/extractors/db/flutter-entities.js +120 -0
  154. package/src/import/extractors/db/jpa.js +120 -0
  155. package/src/import/extractors/db/liquibase.js +180 -0
  156. package/src/import/extractors/db/mybatis-xml.js +145 -0
  157. package/src/import/extractors/db/prisma.js +185 -0
  158. package/src/import/extractors/db/rails-schema.js +175 -0
  159. package/src/import/extractors/db/react-native-entities.js +95 -0
  160. package/src/import/extractors/db/room.js +193 -0
  161. package/src/import/extractors/db/snapshot.js +112 -0
  162. package/src/import/extractors/db/sql.js +180 -0
  163. package/src/import/extractors/db/swiftdata.js +137 -0
  164. package/src/import/extractors/ui/android-compose.js +230 -0
  165. package/src/import/extractors/ui/backend-only.js +70 -0
  166. package/src/import/extractors/ui/blazor.js +227 -0
  167. package/src/import/extractors/ui/flutter-screens.js +152 -0
  168. package/src/import/extractors/ui/maui-xaml.js +135 -0
  169. package/src/import/extractors/ui/next-app-router.js +83 -0
  170. package/src/import/extractors/ui/next-pages-router.js +141 -0
  171. package/src/import/extractors/ui/razor-pages.js +181 -0
  172. package/src/import/extractors/ui/react-native-screens.js +166 -0
  173. package/src/import/extractors/ui/react-router.js +139 -0
  174. package/src/import/extractors/ui/sveltekit.js +123 -0
  175. package/src/import/extractors/ui/swiftui.js +193 -0
  176. package/src/import/extractors/ui/uikit.js +175 -0
  177. package/src/import/extractors/verification/generic.js +290 -0
  178. package/src/import/extractors/workflows/generic.js +137 -0
  179. package/src/import/index.js +7 -0
  180. package/src/import/provenance.js +158 -0
  181. package/src/new-project.js +2107 -0
  182. package/src/parser.js +439 -0
  183. package/src/policy/review-boundaries.js +165 -0
  184. package/src/project-config.js +535 -0
  185. package/src/proofs/backend-parity.js +19 -0
  186. package/src/proofs/contract-audit.js +220 -0
  187. package/src/proofs/ios-parity.js +7 -0
  188. package/src/proofs/issues-parity.js +10 -0
  189. package/src/proofs/web-parity.js +50 -0
  190. package/src/realization/api/build-api-realization.js +5 -0
  191. package/src/realization/api/index.js +1 -0
  192. package/src/realization/backend/build-backend-runtime-realization.js +82 -0
  193. package/src/realization/backend/index.d.ts +1 -0
  194. package/src/realization/backend/index.js +4 -0
  195. package/src/realization/db/build-db-realization.js +17 -0
  196. package/src/realization/db/index.js +3 -0
  197. package/src/realization/db/migration-plan.js +5 -0
  198. package/src/realization/db/snapshot.js +5 -0
  199. package/src/realization/ui/build-ui-shared-realization.js +305 -0
  200. package/src/realization/ui/build-web-realization.js +189 -0
  201. package/src/realization/ui/index.js +2 -0
  202. package/src/reconcile/docs.js +280 -0
  203. package/src/reconcile/index.js +3 -0
  204. package/src/reconcile/journeys.js +441 -0
  205. package/src/resolver/docs.js +1 -0
  206. package/src/resolver/enrich/acceptance-criterion.js +14 -0
  207. package/src/resolver/enrich/bug.js +12 -0
  208. package/src/resolver/enrich/component.js +2 -0
  209. package/src/resolver/enrich/index.js +1 -0
  210. package/src/resolver/enrich/pitch.js +18 -0
  211. package/src/resolver/enrich/requirement.js +20 -0
  212. package/src/resolver/enrich/task.js +16 -0
  213. package/src/resolver/expressions.js +1 -0
  214. package/src/resolver/index.js +2422 -0
  215. package/src/resolver/normalize.js +1 -0
  216. package/src/resolver.js +1 -0
  217. package/src/sdlc/adopt.js +65 -0
  218. package/src/sdlc/check.js +86 -0
  219. package/src/sdlc/dod/acceptance-criterion.js +22 -0
  220. package/src/sdlc/dod/bug.js +26 -0
  221. package/src/sdlc/dod/document.js +23 -0
  222. package/src/sdlc/dod/index.js +25 -0
  223. package/src/sdlc/dod/pitch.js +23 -0
  224. package/src/sdlc/dod/requirement.js +34 -0
  225. package/src/sdlc/dod/task.js +39 -0
  226. package/src/sdlc/explain.js +116 -0
  227. package/src/sdlc/history.js +80 -0
  228. package/src/sdlc/paths.js +11 -0
  229. package/src/sdlc/release.js +106 -0
  230. package/src/sdlc/scaffold.js +89 -0
  231. package/src/sdlc/status-filter.js +54 -0
  232. package/src/sdlc/transition.js +112 -0
  233. package/src/sdlc/transitions/acceptance-criterion.js +28 -0
  234. package/src/sdlc/transitions/bug.js +31 -0
  235. package/src/sdlc/transitions/document.js +29 -0
  236. package/src/sdlc/transitions/index.js +56 -0
  237. package/src/sdlc/transitions/pitch.js +34 -0
  238. package/src/sdlc/transitions/requirement.js +31 -0
  239. package/src/sdlc/transitions/task.js +34 -0
  240. package/src/template-trust.js +597 -0
  241. package/src/validator/expressions.js +1 -0
  242. package/src/validator/index.js +3424 -0
  243. package/src/validator/kinds.js +346 -0
  244. package/src/validator/per-kind/acceptance-criterion.js +91 -0
  245. package/src/validator/per-kind/bug.js +77 -0
  246. package/src/validator/per-kind/component.js +274 -0
  247. package/src/validator/per-kind/domain.js +205 -0
  248. package/src/validator/per-kind/pitch.js +101 -0
  249. package/src/validator/per-kind/requirement.js +75 -0
  250. package/src/validator/per-kind/task.js +96 -0
  251. package/src/validator/registry.js +1 -0
  252. package/src/validator/utils.js +12 -0
  253. package/src/validator.js +1 -0
  254. package/src/workflows.js +7597 -0
  255. package/src/workspace-docs.js +265 -0
  256. package/template-helpers/react.js +5 -0
  257. package/template-helpers/sveltekit.js +5 -0
@@ -0,0 +1,103 @@
1
+ import {
2
+ canonicalCandidateTerm,
3
+ dedupeCandidateRecords,
4
+ findImportFiles,
5
+ makeCandidateRecord,
6
+ relativeTo,
7
+ titleCase
8
+ } from "../../core/shared.js";
9
+
10
+ function inferRetrofitCapabilityId(resource, methodName, httpMethod, routePath) {
11
+ const stem = canonicalCandidateTerm(resource);
12
+ const normalizedMethod = String(methodName || "").toLowerCase();
13
+ if (httpMethod === "GET" && /list|fetch.*list/.test(normalizedMethod)) return `cap_list_${stem}s`;
14
+ if (httpMethod === "GET" && /info|detail|get/.test(normalizedMethod)) return `cap_get_${stem}`;
15
+ if (httpMethod === "POST" && /create|add/.test(normalizedMethod)) return `cap_create_${stem}`;
16
+ if (httpMethod === "PATCH" || httpMethod === "PUT") return `cap_update_${stem}`;
17
+ if (httpMethod === "DELETE") return `cap_delete_${stem}`;
18
+ const routeStem = canonicalCandidateTerm((routePath.split("/").filter(Boolean)[0] || stem).replace(/[{}]/g, ""));
19
+ if (httpMethod === "GET" && /\{/.test(routePath)) return `cap_get_${routeStem}`;
20
+ if (httpMethod === "GET") return `cap_list_${routeStem}s`;
21
+ return `cap_${httpMethod.toLowerCase()}_${routeStem}`;
22
+ }
23
+
24
+ function parseRetrofitInterface(text, provenance) {
25
+ const ifaceMatch = String(text || "").match(/interface\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{/m);
26
+ if (!ifaceMatch) return [];
27
+ const interfaceName = ifaceMatch[1];
28
+ const resource = canonicalCandidateTerm(interfaceName.replace(/Service$/, "").replace(/Client$/, ""));
29
+ const capabilities = [];
30
+ for (const match of String(text || "").matchAll(/@(GET|POST|PUT|PATCH|DELETE)\("([^"]+)"\)[\s\S]*?suspend\s+fun\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(([\s\S]*?)\)\s*:\s*([A-Za-z0-9_<>,?. ]+)/g)) {
31
+ const [, httpMethod, rawPath, methodName, params, returnType] = match;
32
+ const endpointPath = `/${rawPath.replace(/^\/+/, "")}`;
33
+ const pathParams = [...String(params || "").matchAll(/@Path\("([^"]+)"\)\s+([A-Za-z_][A-Za-z0-9_]*)\s*:/g)]
34
+ .map((entry) => ({ name: entry[1], required: true, type: null }));
35
+ const queryParams = [...String(params || "").matchAll(/@Query\("([^"]+)"\)\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([A-Za-z0-9_<>,?.]+)/g)]
36
+ .map((entry) => ({ name: entry[1], required: !entry[3].includes("?"), type: entry[3] }));
37
+ const returnStem = String(returnType || "").match(/<([^>]+)>/)?.[1] || String(returnType || "");
38
+ const outputFields = /^List</.test(String(returnType || "")) ? [canonicalCandidateTerm(returnStem), `${canonicalCandidateTerm(returnStem)}s`] : [canonicalCandidateTerm(returnStem)];
39
+ const routeResource = canonicalCandidateTerm(endpointPath.split("/").filter(Boolean)[0] || resource);
40
+ const capabilityId = inferRetrofitCapabilityId(routeResource, methodName, httpMethod, endpointPath);
41
+ const entityStem = canonicalCandidateTerm(routeResource === "pokemon" ? "pokemon" : routeResource);
42
+ capabilities.push(makeCandidateRecord({
43
+ kind: "capability",
44
+ idHint: capabilityId,
45
+ label: titleCase(capabilityId.replace(/^cap_/, "")),
46
+ confidence: "high",
47
+ sourceKind: "route_code",
48
+ provenance: `${provenance}#${httpMethod} ${endpointPath}`,
49
+ endpoint: { method: httpMethod, path: endpointPath },
50
+ path_params: pathParams,
51
+ query_params: queryParams,
52
+ header_params: [],
53
+ input_fields: [],
54
+ output_fields: [...new Set(outputFields.filter(Boolean))],
55
+ auth_hint: "public",
56
+ entity_id: `entity_${entityStem}`,
57
+ retrofit_interface: interfaceName,
58
+ track: "api"
59
+ }));
60
+ }
61
+
62
+ return capabilities;
63
+ }
64
+
65
+ export const retrofitExtractor = {
66
+ id: "api.retrofit",
67
+ track: "api",
68
+ detect(context) {
69
+ const serviceFiles = findImportFiles(context.paths, (filePath) => /Service\.kt$/i.test(filePath) || /retrofit\/.+\.kt$/i.test(filePath));
70
+ const score = serviceFiles.some((filePath) => /@GET|@POST|@PUT|@PATCH|@DELETE/.test(context.helpers.readTextIfExists(filePath) || "")) ? 87 : 0;
71
+ return {
72
+ score,
73
+ reasons: score > 0 ? ["Found Retrofit service or API interfaces"] : []
74
+ };
75
+ },
76
+ extract(context) {
77
+ const serviceFiles = findImportFiles(context.paths, (filePath) => /Service\.kt$/i.test(filePath) || /retrofit\/.+\.kt$/i.test(filePath));
78
+ const capabilities = [];
79
+ for (const filePath of serviceFiles) {
80
+ const provenance = relativeTo(context.paths.repoRoot, filePath);
81
+ capabilities.push(...parseRetrofitInterface(context.helpers.readTextIfExists(filePath) || "", provenance));
82
+ }
83
+ const findings = capabilities.length > 0 ? [{
84
+ kind: "android_retrofit",
85
+ files: [...new Set(capabilities.flatMap((entry) => entry.provenance || []).map((entry) => String(entry).split("#")[0]))],
86
+ capability_count: capabilities.length
87
+ }] : [];
88
+ return {
89
+ findings,
90
+ candidates: {
91
+ capabilities: dedupeCandidateRecords(capabilities, (record) => record.id_hint),
92
+ routes: capabilities.map((entry) => ({
93
+ path: entry.endpoint.path,
94
+ method: entry.endpoint.method,
95
+ confidence: entry.confidence,
96
+ source_kind: entry.source_kind,
97
+ provenance: entry.provenance?.[0] || null
98
+ })),
99
+ stacks: capabilities.length > 0 ? ["retrofit"] : []
100
+ }
101
+ };
102
+ }
103
+ };
@@ -0,0 +1,372 @@
1
+ import {
2
+ dedupeCandidateRecords,
3
+ findImportFiles,
4
+ inferApiEntityIdFromPath,
5
+ inferRouteCapabilityId,
6
+ makeCandidateRecord,
7
+ normalizeOpenApiPath,
8
+ readTextIfExists,
9
+ relativeTo,
10
+ titleCase
11
+ } from "../../core/shared.js";
12
+
13
+ const JAVA_ANNOTATION_PATTERN = String.raw`@[\w.]+(?:\((?:[^()]|\([^)]*\))*\))?`;
14
+
15
+ function buildJavaFileIndex(paths) {
16
+ const files = findImportFiles(paths, (filePath) => /\.java$/i.test(filePath));
17
+ return files.map((filePath) => ({
18
+ filePath,
19
+ relativePath: relativeTo(paths.repoRoot, filePath),
20
+ text: readTextIfExists(filePath) || ""
21
+ }));
22
+ }
23
+
24
+ function escapeRegExp(value) {
25
+ return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
26
+ }
27
+
28
+ function explicitHandlerHint(methodName, routePath, httpMethod) {
29
+ const low = String(methodName || "").toLowerCase();
30
+ if (httpMethod === "GET" && /\/articles\/feed$/.test(routePath)) return "feed_article";
31
+ if (httpMethod === "POST" && /\/articles\/\{slug\}\/favorite$/.test(routePath)) return "favorite_article";
32
+ if (httpMethod === "DELETE" && /\/articles\/\{slug\}\/favorite$/.test(routePath)) return "unfavorite_article";
33
+ if (httpMethod === "GET" && /\/articles\/\{slug\}\/comments$/.test(routePath)) return "list_comments";
34
+ if (httpMethod === "POST" && /\/articles\/\{slug\}\/comments$/.test(routePath)) return "create_comment";
35
+ if (httpMethod === "DELETE" && /\/articles\/\{slug\}\/comments\/\{id\}$/.test(routePath)) return "delete_comment";
36
+ if (httpMethod === "GET" && /\/profiles\/\{username\}$/.test(routePath)) return "get_profile";
37
+ if (httpMethod === "POST" && /\/profiles\/\{username\}\/follow$/.test(routePath)) return "follow_profile";
38
+ if (httpMethod === "DELETE" && /\/profiles\/\{username\}\/follow$/.test(routePath)) return "unfollow_profile";
39
+ if (httpMethod === "POST" && /\/users\/login$/.test(routePath)) return "sign_in_account";
40
+ if (httpMethod === "POST" && routePath === "/users") return "create_user";
41
+ if (httpMethod === "GET" && routePath === "/user") return "get_user";
42
+ if ((httpMethod === "PUT" || httpMethod === "PATCH") && routePath === "/user") return "update_user";
43
+ if (httpMethod === "GET" && routePath === "/tags") return "list_tags";
44
+ if (httpMethod === "GET" && /\/articles\/\{slug\}$/.test(routePath)) return "get_article";
45
+ if (httpMethod === "GET" && routePath === "/articles") return "list_articles";
46
+ if (httpMethod === "POST" && routePath === "/articles") return "create_article";
47
+ if ((httpMethod === "PUT" || httpMethod === "PATCH") && /\/articles\/\{slug\}$/.test(routePath)) return "update_article";
48
+ if (httpMethod === "DELETE" && /\/articles\/\{slug\}$/.test(routePath)) return "delete_article";
49
+ if (httpMethod === "POST" && routePath === "/Customer") return "create_customer";
50
+ if (httpMethod === "POST" && /\/Customer\/auth$/.test(routePath)) return "sign_in_account";
51
+ if (httpMethod === "GET" && routePath === "/Store") return "list_stores";
52
+ if (httpMethod === "GET" && /\/Store\/search\/\{text\}$/.test(routePath)) return "search_stores";
53
+ if (httpMethod === "GET" && /\/Store\/\{id\}$/.test(routePath)) return "get_store";
54
+ if (httpMethod === "GET" && /\/Store\/\{id\}\/products$/.test(routePath)) return "list_products";
55
+ if (httpMethod === "GET" && routePath === "/Product") return "list_products";
56
+ if (httpMethod === "GET" && /\/Product\/search\/\{text\}$/.test(routePath)) return "search_products";
57
+ if (httpMethod === "GET" && /\/Product\/\{id\}$/.test(routePath)) return "get_product";
58
+ if (httpMethod === "GET" && routePath === "/Cousine") return "list_cousines";
59
+ if (httpMethod === "GET" && /\/Cousine\/search\/\{text\}$/.test(routePath)) return "search_cousines";
60
+ if (httpMethod === "GET" && /\/Cousine\/\{id\}\/stores$/.test(routePath)) return "list_stores";
61
+ if (httpMethod === "POST" && routePath === "/Order") return "create_order";
62
+ if (httpMethod === "GET" && /\/Order\/\{id\}$/.test(routePath)) return "get_order";
63
+ if (httpMethod === "GET" && /\/Order\/\{id\}\/customer$/.test(routePath)) return "get_customer";
64
+ if (httpMethod === "DELETE" && /\/Order\/\{id\}$/.test(routePath)) return "delete_order";
65
+ if (httpMethod === "POST" && /\/Order\/\{id\}\/payment$/.test(routePath)) return "pay_order";
66
+ if (httpMethod === "POST" && /\/Order\/\{id\}\/delivery$/.test(routePath)) return "delivery_order";
67
+ if (low === "feed" || low === "getfeed") return "feed_article";
68
+ if (low.includes("favorite")) return low.startsWith("un") ? "unfavorite_article" : "favorite_article";
69
+ if (low.includes("comment")) {
70
+ if (low.startsWith("delete")) return "delete_comment";
71
+ if (low.startsWith("create") || low.startsWith("add")) return "create_comment";
72
+ return "list_comments";
73
+ }
74
+ if ((low === "findbyusername" || low === "getprofile") && /\/profiles\/\{username\}$/.test(routePath)) return "get_profile";
75
+ if (low.includes("follow")) return low.startsWith("un") ? "unfollow_profile" : "follow_profile";
76
+ if (low === "login" || low === "userlogin" || /\/users\/login$/.test(routePath)) return "sign_in_account";
77
+ if (low === "register" || low === "createuser" || (routePath === "/users" && httpMethod === "POST")) return "create_user";
78
+ if (low === "current" || low === "currentuser") return "get_user";
79
+ if ((low === "update" || low === "updateprofile") && routePath === "/user") return "update_user";
80
+ if (low === "findall" || low === "gettags") return "list_tags";
81
+ if ((low === "findbyslug" || low === "article") && httpMethod === "GET") return "get_article";
82
+ if ((low === "findbyfilters" || low === "getarticles") && httpMethod === "GET") return "list_articles";
83
+ if ((low === "create" || low === "createarticle") && routePath === "/articles") return "create_article";
84
+ if (low === "updatebyslug" || low === "updatearticle") return "update_article";
85
+ if (low === "deletebyslug" || low === "deletearticle") return "delete_article";
86
+ if (low === "signup") return "create_customer";
87
+ if (low === "signin" || /\/auth$/.test(routePath)) return "sign_in_account";
88
+ if (low === "getallstores") return "list_stores";
89
+ if (low === "getallproducts") return "list_products";
90
+ if (low === "getallcousines") return "list_cousines";
91
+ if (low.includes("search")) {
92
+ if (low.includes("store")) return "search_stores";
93
+ if (low.includes("product")) return "search_products";
94
+ if (low.includes("cousine")) return "search_cousines";
95
+ }
96
+ if (low === "create") {
97
+ return null;
98
+ }
99
+ return null;
100
+ }
101
+
102
+ function parseRecordFields(recordText) {
103
+ const ctorMatch = String(recordText || "").match(/record\s+[A-Za-z_][A-Za-z0-9_]*\s*\(([\s\S]*?)\)\s*(?:implements[^{]+)?\{/);
104
+ if (!ctorMatch) return [];
105
+ return ctorMatch[1]
106
+ .split(",")
107
+ .map((part) => part.trim())
108
+ .filter(Boolean)
109
+ .map((part) => {
110
+ const cleaned = part.replace(new RegExp(`${JAVA_ANNOTATION_PATTERN}\\s*`, "g"), "").trim();
111
+ const match = cleaned.match(/([A-Za-z0-9_<>\[\]\?\.]+)\s+([A-Za-z_][A-Za-z0-9_]*)$/);
112
+ return match ? { type: match[1], name: match[2] } : null;
113
+ })
114
+ .filter(Boolean);
115
+ }
116
+
117
+ function parseClassFields(classText) {
118
+ return [...String(classText || "").matchAll(new RegExp(`((?:\\s*${JAVA_ANNOTATION_PATTERN}\\s*)*)\\s*private\\s+([A-Za-z0-9_<>\\[\\]\\?\\.]+)\\s+([A-Za-z_][A-Za-z0-9_]*)\\s*;`, "g"))]
119
+ .map((entry) => ({
120
+ annotations: entry[1] || "",
121
+ type: entry[2],
122
+ name: entry[3]
123
+ }));
124
+ }
125
+
126
+ function findJavaTypeBlock(typeName, files, preferredFile = null) {
127
+ const bare = String(typeName || "").split(".").pop();
128
+ if (!bare) return null;
129
+ const patterns = [
130
+ new RegExp(`(?:public\\s+)?record\\s+${escapeRegExp(bare)}\\b[\\s\\S]{0,2400}?\\n\\}`, "m"),
131
+ new RegExp(`(?:public\\s+)?class\\s+${escapeRegExp(bare)}\\b[\\s\\S]{0,3600}?\\n\\}`, "m"),
132
+ new RegExp(`(?:public\\s+)?interface\\s+${escapeRegExp(bare)}\\b[\\s\\S]{0,2400}?\\n\\}`, "m")
133
+ ];
134
+ const orderedFiles = preferredFile
135
+ ? [...files.filter((file) => file.filePath === preferredFile), ...files.filter((file) => file.filePath !== preferredFile)]
136
+ : files;
137
+ for (const file of orderedFiles) {
138
+ for (const pattern of patterns) {
139
+ const match = file.text.match(pattern);
140
+ if (match) {
141
+ return { filePath: file.filePath, text: match[0] };
142
+ }
143
+ }
144
+ }
145
+ return null;
146
+ }
147
+
148
+ function flattenFieldsFromType(typeName, files, seen = new Set(), preferredFile = null) {
149
+ const bare = String(typeName || "").split(".").pop();
150
+ const key = `${preferredFile || ""}:${bare}`;
151
+ if (!bare || seen.has(key)) return [];
152
+ seen.add(key);
153
+ const block = findJavaTypeBlock(typeName, files, preferredFile);
154
+ if (!block) return [];
155
+ const fields = [];
156
+ const recordFields = parseRecordFields(block.text);
157
+ if (recordFields.length > 0) {
158
+ for (const field of recordFields) {
159
+ const nested = flattenFieldsFromType(field.type, files, seen, block.filePath);
160
+ if (nested.length > 0 && ["article", "user", "data", "comment", "profile", "request", "orderrequest"].includes(field.name.toLowerCase())) {
161
+ fields.push(...nested);
162
+ } else {
163
+ fields.push(field.name);
164
+ }
165
+ }
166
+ return [...new Set(fields)];
167
+ }
168
+ for (const field of parseClassFields(block.text)) {
169
+ if (/static\s+final/i.test(field.annotations || "")) continue;
170
+ fields.push(field.name);
171
+ }
172
+ return [...new Set(fields)];
173
+ }
174
+
175
+ function flattenOutputFieldsFromType(typeName, files, preferredFile = null) {
176
+ const block = findJavaTypeBlock(typeName, files, preferredFile);
177
+ if (!block) return [];
178
+ const recordFields = parseRecordFields(block.text);
179
+ if (recordFields.length > 0) return recordFields.map((field) => field.name);
180
+ return parseClassFields(block.text).map((field) => field.name);
181
+ }
182
+
183
+ function parseRequestParams(parameters) {
184
+ return [...String(parameters || "").matchAll(/@RequestParam(?:\(([^)]*)\))?\s+(?:@[A-Za-z_][A-Za-z0-9_.]*(?:\([^)]*\))?\s+)*([A-Za-z0-9_<>\[\]\?\.]+)\s+([A-Za-z_][A-Za-z0-9_]*)/g)]
185
+ .map((entry) => ({
186
+ name: entry[3],
187
+ required: !/required\s*=\s*false/.test(entry[1] || ""),
188
+ type: entry[2] || null
189
+ }));
190
+ }
191
+
192
+ function parsePathParams(parameters) {
193
+ return [...String(parameters || "").matchAll(/@PathVariable(?:\("([^"]+)"\))?\s+(?:@[A-Za-z_][A-Za-z0-9_.]*(?:\([^)]*\))?\s+)*([A-Za-z0-9_<>\[\]\?\.]+)\s+([A-Za-z_][A-Za-z0-9_]*)/g)]
194
+ .map((entry) => ({
195
+ name: entry[1] || entry[3],
196
+ required: true,
197
+ type: entry[2] || null
198
+ }));
199
+ }
200
+
201
+ function parseHeaderParams(parameters) {
202
+ return [...String(parameters || "").matchAll(/@RequestHeader(?:\(([^)]*)\))?\s+(?:@[A-Za-z_][A-Za-z0-9_.]*(?:\([^)]*\))?\s+)*([A-Za-z0-9_<>\[\]\?\.]+)\s+([A-Za-z_][A-Za-z0-9_]*)/g)]
203
+ .map((entry) => ({
204
+ name: entry[3],
205
+ required: !/required\s*=\s*false/.test(entry[1] || ""),
206
+ type: entry[2] || null
207
+ }));
208
+ }
209
+
210
+ function parseBodyType(parameters) {
211
+ const match = String(parameters || "").match(/@RequestBody\s+([A-Za-z0-9_<>\[\]\?\.]+)\s+([A-Za-z_][A-Za-z0-9_]*)/);
212
+ return match ? match[1] : null;
213
+ }
214
+
215
+ function normalizeJoinedPath(basePath, childPath = "") {
216
+ return normalizeOpenApiPath(`/${[String(basePath || "").replace(/^\/+/, ""), String(childPath || "").replace(/^\/+/, "")].filter(Boolean).join("/")}`);
217
+ }
218
+
219
+ function inferAuthHint(pathValue, methodName, parameters = "", annotations = "") {
220
+ if (/@PreAuthorize/.test(annotations) || /AuthenticationPrincipal|CurrentUser/.test(parameters) || /RequestHeader\([^)]*Authorization/.test(parameters)) return "secured";
221
+ if (pathValue === "/users/login" || pathValue === "/Customer/auth") return "public";
222
+ if ((pathValue === "/users" && /create|register|signup/i.test(methodName)) || pathValue === "/Customer") return "public";
223
+ if ((pathValue === "/articles" || pathValue === "/tags") || /^\/articles\/\{slug\}(?:\/comments)?$/.test(pathValue) || /^\/profiles\/\{username\}$/.test(pathValue)) {
224
+ return "public";
225
+ }
226
+ return "unknown";
227
+ }
228
+
229
+ function inferOutputFieldsFromBody(methodBody, returnType, files, preferredFile = null) {
230
+ const keys = [...String(methodBody || "").matchAll(/put\("([^"]+)"/g)].map((entry) => entry[1]);
231
+ if (keys.length > 0) return [...new Set(keys)];
232
+ const typeFields = flattenOutputFieldsFromType(returnType, files, preferredFile);
233
+ if (typeFields.length > 0) return typeFields;
234
+ return [];
235
+ }
236
+
237
+ function parseOperationInterfaces(files, repoRoot) {
238
+ const operationFiles = files.filter((file) => /\/api\/operation\/.+Operations\.java$/.test(file.relativePath));
239
+ const routes = [];
240
+ for (const file of operationFiles) {
241
+ for (const match of file.text.matchAll(/@((?:Get|Post|Put|Patch|Delete)Exchange)\("([^"]+)"\)\s+([A-Za-z0-9_<>\[\]\?\.]+)\s+([A-Za-z_][A-Za-z0-9_]*)\(([\s\S]*?)\);/g)) {
242
+ const [, exchangeType, routePathRaw, returnType, methodName, parameters] = match;
243
+ const method = exchangeType.replace("Exchange", "").toUpperCase();
244
+ const pathValue = normalizeOpenApiPath(routePathRaw);
245
+ const bodyType = parseBodyType(parameters);
246
+ routes.push({
247
+ method,
248
+ path: pathValue,
249
+ handler_hint: explicitHandlerHint(methodName, pathValue, method),
250
+ controller: file.relativePath.split("/").pop()?.replace(/\.java$/, "") || "SpringOperation",
251
+ action: methodName,
252
+ auth_hint: inferAuthHint(pathValue, methodName, parameters, ""),
253
+ path_params: parsePathParams(parameters),
254
+ query_params: parseRequestParams(parameters),
255
+ header_params: parseHeaderParams(parameters),
256
+ input_fields: bodyType ? flattenFieldsFromType(bodyType, files, new Set(), file.filePath) : [],
257
+ output_fields: flattenOutputFieldsFromType(returnType, files, file.filePath),
258
+ provenance: `${relativeTo(repoRoot, file.filePath)}#${method} ${pathValue}`
259
+ });
260
+ }
261
+ }
262
+ return routes;
263
+ }
264
+
265
+ function parseSpringMvcRoutes(files, repoRoot) {
266
+ const springFiles = files.filter((file) => /@(RestController|Controller)\b/.test(file.text));
267
+ const routes = [];
268
+ const methodPattern = new RegExp(`((?:\\s*${JAVA_ANNOTATION_PATTERN}\\s*)+)\\s*(?:public\\s+)?(?:default\\s+)?([A-Za-z0-9_<>\\[\\]\\?., ]+)\\s+([A-Za-z_][A-Za-z0-9_]*)\\(([\\s\\S]*?)\\)\\s*(\\{|;)`, "g");
269
+ for (const file of springFiles) {
270
+ const classMapping = file.text.match(/@RequestMapping\(([^)]*)\)/);
271
+ const basePath = classMapping?.[1].match(/path\s*=\s*"([^"]+)"|"([^"]+)"/)?.[1] || classMapping?.[1].match(/path\s*=\s*"([^"]+)"|"([^"]+)"/)?.[2] || "";
272
+ for (const match of file.text.matchAll(methodPattern)) {
273
+ const [, annotations, returnTypeRaw, methodName, parameters, terminator] = match;
274
+ const mappingMatch = annotations.match(/@(GetMapping|PostMapping|PutMapping|PatchMapping|DeleteMapping|RequestMapping)\(([^)]*)\)|@(GetMapping|PostMapping|PutMapping|PatchMapping|DeleteMapping)\b/g);
275
+ if (!mappingMatch) continue;
276
+ let method = null;
277
+ let childPath = "";
278
+ let rawArgs = "";
279
+ const first = mappingMatch[0];
280
+ const detailed = first.match(/@(GetMapping|PostMapping|PutMapping|PatchMapping|DeleteMapping|RequestMapping)\(([^)]*)\)/);
281
+ if (detailed) {
282
+ const mappingType = detailed[1];
283
+ rawArgs = detailed[2] || "";
284
+ method = mappingType === "RequestMapping"
285
+ ? (rawArgs.match(/RequestMethod\.([A-Z]+)/)?.[1] || rawArgs.match(/method\s*=\s*([A-Z]+)/)?.[1] || null)
286
+ : mappingType.replace("Mapping", "").toUpperCase();
287
+ childPath = rawArgs.match(/path\s*=\s*"([^"]+)"|"([^"]+)"/)?.[1] || rawArgs.match(/path\s*=\s*"([^"]+)"|"([^"]+)"/)?.[2] || "";
288
+ } else {
289
+ const simple = first.match(/@(GetMapping|PostMapping|PutMapping|PatchMapping|DeleteMapping)\b/);
290
+ if (simple) method = simple[1].replace("Mapping", "").toUpperCase();
291
+ }
292
+ if (!method) continue;
293
+ const pathValue = normalizeJoinedPath(basePath, childPath);
294
+ const bodyType = parseBodyType(parameters);
295
+ const returnType = String(returnTypeRaw || "").trim().replace(/^CompletableFuture\s*</, "").replace(/^ResponseEntity\s*</, "").replace(/>\s*$/, "").replace(/>\s*$/, "").trim();
296
+ const bodyStart = match.index + match[0].length;
297
+ const nextChunk = terminator === "{" ? file.text.slice(bodyStart, bodyStart + 1600) : "";
298
+ routes.push({
299
+ method,
300
+ path: pathValue,
301
+ handler_hint: explicitHandlerHint(methodName, pathValue, method),
302
+ controller: file.relativePath.split("/").pop()?.replace(/\.java$/, "") || "SpringController",
303
+ action: methodName,
304
+ auth_hint: inferAuthHint(pathValue, methodName, parameters, annotations),
305
+ path_params: parsePathParams(parameters),
306
+ query_params: parseRequestParams(parameters),
307
+ header_params: parseHeaderParams(parameters),
308
+ input_fields: bodyType ? flattenFieldsFromType(bodyType, files, new Set(), file.filePath) : [],
309
+ output_fields: inferOutputFieldsFromBody(nextChunk, returnType, files, file.filePath),
310
+ provenance: `${relativeTo(repoRoot, file.filePath)}#${method} ${pathValue}`
311
+ });
312
+ }
313
+ }
314
+ return routes;
315
+ }
316
+
317
+ export const springWebExtractor = {
318
+ id: "api.spring-web",
319
+ track: "api",
320
+ detect(context) {
321
+ const javaFiles = findImportFiles(context.paths, (filePath) => /\.java$/i.test(filePath));
322
+ const springCount = javaFiles.filter((filePath) => /@(RestController|Controller)|@(?:Get|Post|Put|Patch|Delete)Exchange|@(GetMapping|PostMapping|PutMapping|PatchMapping|DeleteMapping)|@RequestMapping/.test(readTextIfExists(filePath) || "")).length;
323
+ return {
324
+ score: springCount > 0 ? 90 : 0,
325
+ reasons: springCount > 0 ? ["Found Spring web contracts or controllers"] : []
326
+ };
327
+ },
328
+ extract(context) {
329
+ const javaFiles = buildJavaFileIndex(context.paths);
330
+ const routes = [...parseOperationInterfaces(javaFiles, context.paths.repoRoot), ...parseSpringMvcRoutes(javaFiles, context.paths.repoRoot)];
331
+ const findings = [];
332
+ const candidates = { capabilities: [], routes: [], stacks: [] };
333
+ if (routes.length > 0) {
334
+ findings.push({
335
+ kind: "spring_web",
336
+ route_count: routes.length,
337
+ files: [...new Set(routes.map((route) => route.provenance.split("#")[0]))]
338
+ });
339
+ }
340
+ candidates.capabilities.push(...routes.map((route) => makeCandidateRecord({
341
+ kind: "capability",
342
+ idHint: inferRouteCapabilityId(route),
343
+ label: route.handler_hint ? titleCase(route.handler_hint) : `${route.method} ${route.path}`,
344
+ confidence: "high",
345
+ sourceKind: "route_code",
346
+ provenance: route.provenance,
347
+ endpoint: { method: route.method, path: route.path },
348
+ path_params: route.path_params,
349
+ query_params: route.query_params,
350
+ header_params: route.header_params,
351
+ input_fields: route.input_fields,
352
+ output_fields: route.output_fields,
353
+ auth_hint: route.auth_hint,
354
+ entity_id: route.handler_hint === "sign_in_account" ? "entity_account" : inferApiEntityIdFromPath(route.path),
355
+ track: "api"
356
+ })));
357
+ candidates.routes.push(...routes.map((route) => ({
358
+ path: route.path,
359
+ method: route.method,
360
+ confidence: "high",
361
+ source_kind: "route_code",
362
+ provenance: route.provenance
363
+ })));
364
+ candidates.capabilities = dedupeCandidateRecords(candidates.capabilities, (record) => record.id_hint);
365
+ candidates.routes = dedupeCandidateRecords(
366
+ candidates.routes.map((route) => ({ ...route, id_hint: `${route.method}_${route.path}` })),
367
+ (record) => `${record.method}:${record.path}:${record.source_kind}`
368
+ ).map(({ id_hint, ...route }) => route);
369
+ candidates.stacks = routes.length > 0 ? ["spring"] : [];
370
+ return { findings, candidates };
371
+ }
372
+ };
@@ -0,0 +1,116 @@
1
+ import {
2
+ canonicalCandidateTerm,
3
+ dedupeCandidateRecords,
4
+ findImportFiles,
5
+ idHintify,
6
+ makeCandidateRecord,
7
+ relativeTo,
8
+ titleCase
9
+ } from "../../core/shared.js";
10
+
11
+ function inferSwiftCapabilityId(methodName, pathValue, returnTypeHint) {
12
+ const normalizedMethod = String(methodName || "").toLowerCase();
13
+ const pathStem = canonicalCandidateTerm(idHintify((pathValue || "").replace(/[/?=&{}().]+/g, "_")));
14
+ if (/countries/.test(normalizedMethod) || /allcountries/.test(pathValue || "")) return "cap_list_countries";
15
+ if (/details/.test(normalizedMethod) || /countrydetails/.test(pathValue || "")) return "cap_get_country_details";
16
+ if (/image/.test(normalizedMethod) || /push/.test(normalizedMethod)) return `cap_get_${canonicalCandidateTerm(idHintify(returnTypeHint || pathStem || "resource"))}`;
17
+ return `cap_get_${pathStem || canonicalCandidateTerm(idHintify(returnTypeHint || "resource"))}`;
18
+ }
19
+
20
+ function inferEntityId(capabilityId) {
21
+ if (capabilityId === "cap_list_countries") return "entity_country";
22
+ if (capabilityId === "cap_get_country_details") return "entity_country_details";
23
+ const stem = capabilityId.replace(/^cap_(get|list|create|update|delete)_/, "");
24
+ return `entity_${canonicalCandidateTerm(stem)}`;
25
+ }
26
+
27
+ function parseRepositoryFile(text, provenance) {
28
+ const repoMatch = String(text || "").match(/struct\s+Real([A-Za-z_][A-Za-z0-9_]*)\s*:\s*([A-Za-z_][A-Za-z0-9_]*)/m);
29
+ if (!repoMatch) return [];
30
+ const repositoryName = repoMatch[1];
31
+ if (/Image|PushToken/i.test(repositoryName)) {
32
+ return [];
33
+ }
34
+ const capabilities = [];
35
+ const methods = [...String(text || "").matchAll(/func\s+([A-Za-z_][A-Za-z0-9_]*)\(([\s\S]*?)\)\s+async\s+throws\s+->\s+([A-Za-z0-9_<>\[\].?]+)\s*\{([\s\S]*?)\n\s*\}/g)];
36
+ const pathSwitch = [...String(text || "").matchAll(/case\s+(?:let\s+)?\.([A-Za-z_][A-Za-z0-9_]*)(?:\([^)]+\))?:\s*return\s+"([^"]+)"/g)]
37
+ .reduce((acc, match) => acc.set(match[1], match[2]), new Map());
38
+ const methodSwitch = [...String(text || "").matchAll(/case\s+(?:let\s+)?\.([A-Za-z_][A-Za-z0-9_]*)(?:\([^)]+\))?:\s*return\s+"(GET|POST|PUT|PATCH|DELETE)"/g)]
39
+ .reduce((acc, match) => acc.set(match[1], match[2]), new Map());
40
+
41
+ for (const match of methods) {
42
+ const [, methodName, params, returnType, body] = match;
43
+ const endpointCase =
44
+ body.match(/endpoint:\s*API\.([A-Za-z_][A-Za-z0-9_]*)/)?.[1]
45
+ || (methodName === "countries" ? "allCountries" : methodName);
46
+ let pathValue = pathSwitch.get(endpointCase) || `/${endpointCase}`;
47
+ if (/countryName:/.test(body) && /\/name\//.test(pathValue)) {
48
+ pathValue = "/name/{countryName}";
49
+ }
50
+ const httpMethod = methodSwitch.get(endpointCase) || "GET";
51
+ const capabilityId = inferSwiftCapabilityId(methodName, pathValue, returnType);
52
+ const queryParams = [...String(pathValue).matchAll(/[?&]([^=]+)=/g)].map((entry) => ({ name: entry[1], required: false, type: null }));
53
+ const pathParams = [...String(pathValue).matchAll(/\{([^}]+)\}/g)].map((entry) => ({ name: entry[1], required: true, type: null }));
54
+ const outputStem = canonicalCandidateTerm(idHintify(String(returnType || "").replace(/[\[\]?]/g, "").split(".").pop() || ""));
55
+ capabilities.push(makeCandidateRecord({
56
+ kind: "capability",
57
+ idHint: capabilityId,
58
+ label: titleCase(capabilityId.replace(/^cap_/, "")),
59
+ confidence: "high",
60
+ sourceKind: "route_code",
61
+ provenance: `${provenance}#${methodName}`,
62
+ endpoint: { method: httpMethod, path: pathValue.replace(/\\\([^)]*\)/g, "{id}") },
63
+ path_params: pathParams,
64
+ query_params: queryParams,
65
+ header_params: [],
66
+ input_fields: [],
67
+ output_fields: httpMethod === "GET" ? [outputStem] : [],
68
+ auth_hint: "public",
69
+ entity_id: inferEntityId(capabilityId),
70
+ repository: repositoryName,
71
+ track: "api"
72
+ }));
73
+ }
74
+ return capabilities;
75
+ }
76
+
77
+ export const swiftWebApiExtractor = {
78
+ id: "api.swift-webapi",
79
+ track: "api",
80
+ detect(context) {
81
+ const files = findImportFiles(context.paths, (filePath) => /WebRepository\.swift$/i.test(filePath) || /WebAPI\/.+\.swift$/i.test(filePath));
82
+ const score = files.some((filePath) => /APICall|URLSession/.test(context.helpers.readTextIfExists(filePath) || "")) ? 85 : 0;
83
+ return {
84
+ score,
85
+ reasons: score > 0 ? ["Found Swift web repositories using APICall/URLSession"] : []
86
+ };
87
+ },
88
+ extract(context) {
89
+ const files = findImportFiles(context.paths, (filePath) => /WebAPI\/.+\.swift$/i.test(filePath))
90
+ .filter((filePath) => /struct\s+Real/.test(context.helpers.readTextIfExists(filePath) || ""));
91
+ const capabilities = [];
92
+ for (const filePath of files) {
93
+ const provenance = relativeTo(context.paths.repoRoot, filePath);
94
+ capabilities.push(...parseRepositoryFile(context.helpers.readTextIfExists(filePath) || "", provenance));
95
+ }
96
+ const findings = capabilities.length > 0 ? [{
97
+ kind: "swift_webapi",
98
+ files: [...new Set(capabilities.flatMap((entry) => entry.provenance || []).map((entry) => String(entry).split("#")[0]))],
99
+ capability_count: capabilities.length
100
+ }] : [];
101
+ return {
102
+ findings,
103
+ candidates: {
104
+ capabilities: dedupeCandidateRecords(capabilities, (record) => `${record.id_hint}:${record.endpoint?.path || ""}`),
105
+ routes: capabilities.map((entry) => ({
106
+ path: entry.endpoint.path,
107
+ method: entry.endpoint.method,
108
+ confidence: entry.confidence,
109
+ source_kind: entry.source_kind,
110
+ provenance: entry.provenance?.[0] || null
111
+ })),
112
+ stacks: capabilities.length > 0 ? ["swift_webapi"] : []
113
+ }
114
+ };
115
+ }
116
+ };