repometry 0.0.0-dev.0 → 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.
Files changed (281) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +24 -1
  3. package/package.json +48 -7
  4. package/target/main/resources/report/json/compact-json-v1.schema.json +24 -0
  5. package/target/main/resources/report/json/comparison-v1.schema.json +65 -0
  6. package/target/main/resources/report/json/config-v1.schema.json +34 -0
  7. package/target/main/resources/report/json/diff-coverage-v1.schema.json +55 -0
  8. package/target/main/resources/report/json/file-metrics-v1.schema.json +134 -0
  9. package/target/main/resources/report/json/inspection-context-v1.schema.json +172 -0
  10. package/target/main/resources/report/json/metabranch-v1.schema.json +9 -0
  11. package/target/main/resources/report/json/metric-catalog-v1.schema.json +31 -0
  12. package/target/main/resources/report/json/public-history-v1.schema.json +50 -0
  13. package/target/main/resources/report/json/pull-review-v1.schema.json +97 -0
  14. package/target/main/resources/report/json/quality-history-v1.schema.json +51 -0
  15. package/target/main/resources/report/json/report-v1.schema.json +65 -0
  16. package/target/main/resources/report/json/report-v2.schema.json +238 -0
  17. package/target/main/resources/report/json/repository-summary-v1.schema.json +181 -0
  18. package/target/main/resources/report/json/viewer-details-v1.schema.json +343 -0
  19. package/target/main/resources/report/json/viewer-inspection-v1.schema.json +13 -0
  20. package/target/main/resources/viewer/files.css +578 -0
  21. package/target/main/resources/viewer/index.html +130 -0
  22. package/target/main/resources/viewer/projects.html +52 -0
  23. package/target/main/resources/viewer/styles.css +586 -0
  24. package/target/main/resources/viewer/viewer-pulls.css +64 -0
  25. package/target/main/ts/api/gh/github-pr-comment.d.ts +4 -0
  26. package/target/main/ts/api/gh/github-pr-comment.js +107 -0
  27. package/target/main/ts/api/gh/github.d.ts +6 -0
  28. package/target/main/ts/api/gh/github.js +91 -0
  29. package/target/main/ts/api/git/blob-batch.d.ts +10 -0
  30. package/target/main/ts/api/git/blob-batch.js +105 -0
  31. package/target/main/ts/api/git/changes.d.ts +22 -0
  32. package/target/main/ts/api/git/changes.js +107 -0
  33. package/target/main/ts/api/git/commit-metadata.d.ts +3 -0
  34. package/target/main/ts/api/git/commit-metadata.js +54 -0
  35. package/target/main/ts/api/git/git-churn.d.ts +9 -0
  36. package/target/main/ts/api/git/git-churn.js +70 -0
  37. package/target/main/ts/api/git/git-reader.d.ts +16 -0
  38. package/target/main/ts/api/git/git-reader.js +73 -0
  39. package/target/main/ts/api/git/git.d.ts +21 -0
  40. package/target/main/ts/api/git/git.js +152 -0
  41. package/target/main/ts/api/git/inspection-source.d.ts +15 -0
  42. package/target/main/ts/api/git/inspection-source.js +30 -0
  43. package/target/main/ts/api/git/local-sources.d.ts +5 -0
  44. package/target/main/ts/api/git/local-sources.js +46 -0
  45. package/target/main/ts/api/git/local.d.ts +3 -0
  46. package/target/main/ts/api/git/local.js +35 -0
  47. package/target/main/ts/api/git/metabranch-worktree.d.ts +1 -0
  48. package/target/main/ts/api/git/metabranch-worktree.js +34 -0
  49. package/target/main/ts/api/git/source-cache.d.ts +3 -0
  50. package/target/main/ts/api/git/source-cache.js +56 -0
  51. package/target/main/ts/api/import/finding-import.d.ts +9 -0
  52. package/target/main/ts/api/import/finding-import.js +226 -0
  53. package/target/main/ts/api/import/lcov-files.d.ts +5 -0
  54. package/target/main/ts/api/import/lcov-files.js +13 -0
  55. package/target/main/ts/api/import/profile-file.d.ts +4 -0
  56. package/target/main/ts/api/import/profile-file.js +16 -0
  57. package/target/main/ts/api/worker/remote-executor.d.ts +2 -0
  58. package/target/main/ts/api/worker/remote-executor.js +45 -0
  59. package/target/main/ts/api/worker/worker-protocol.d.ts +7 -0
  60. package/target/main/ts/api/worker/worker-protocol.js +101 -0
  61. package/target/main/ts/api/worker/worker.d.ts +5 -0
  62. package/target/main/ts/api/worker/worker.js +85 -0
  63. package/target/main/ts/cli/arguments.d.ts +28 -0
  64. package/target/main/ts/cli/arguments.js +110 -0
  65. package/target/main/ts/cli/config.d.ts +14 -0
  66. package/target/main/ts/cli/config.js +60 -0
  67. package/target/main/ts/cli/github-pr-comment.d.ts +1 -0
  68. package/target/main/ts/cli/github-pr-comment.js +12 -0
  69. package/target/main/ts/cli/imports.d.ts +7 -0
  70. package/target/main/ts/cli/imports.js +29 -0
  71. package/target/main/ts/cli/main.d.ts +2 -0
  72. package/target/main/ts/cli/main.js +343 -284
  73. package/target/main/ts/cli/reporting.d.ts +18 -0
  74. package/target/main/ts/cli/reporting.js +108 -0
  75. package/target/main/ts/cli/revisions.d.ts +6 -0
  76. package/target/main/ts/cli/revisions.js +15 -0
  77. package/target/main/ts/cli/store.d.ts +13 -0
  78. package/target/main/ts/cli/store.js +38 -0
  79. package/target/main/ts/compose/analyze-snapshot.d.ts +4 -0
  80. package/target/main/ts/compose/analyze-snapshot.js +163 -0
  81. package/target/main/ts/compose/attach-churn.d.ts +2 -0
  82. package/target/main/ts/compose/attach-churn.js +37 -0
  83. package/target/main/ts/compose/diff-coverage.d.ts +20 -0
  84. package/target/main/ts/compose/diff-coverage.js +56 -0
  85. package/target/main/ts/compose/inspect.d.ts +23 -0
  86. package/target/main/ts/compose/inspect.js +44 -0
  87. package/target/main/ts/compose/plugin-list.d.ts +6 -0
  88. package/target/main/ts/compose/plugin-list.js +9 -0
  89. package/target/main/ts/compose/prepare-metabranch.d.ts +9 -0
  90. package/target/main/ts/compose/prepare-metabranch.js +16 -0
  91. package/target/main/ts/compose/review.d.ts +16 -0
  92. package/target/main/ts/compose/review.js +38 -0
  93. package/target/main/ts/compose/sources.d.ts +3 -0
  94. package/target/main/ts/compose/sources.js +29 -0
  95. package/target/main/ts/core/engine/execute.d.ts +10 -0
  96. package/target/main/ts/core/engine/execute.js +49 -0
  97. package/target/main/ts/core/engine/manifest.d.ts +4 -0
  98. package/target/main/ts/core/engine/manifest.js +104 -0
  99. package/target/main/ts/core/engine/plan.d.ts +22 -0
  100. package/target/main/ts/core/engine/plan.js +106 -0
  101. package/target/main/ts/core/engine/plugin.d.ts +59 -0
  102. package/target/main/ts/core/engine/plugin.js +4 -0
  103. package/target/main/ts/core/engine/report-products.d.ts +16 -0
  104. package/target/main/ts/core/engine/report-products.js +85 -0
  105. package/target/main/ts/core/model/changes.d.ts +8 -0
  106. package/target/main/ts/core/model/changes.js +1 -0
  107. package/target/main/ts/core/model/churn.d.ts +11 -0
  108. package/target/main/ts/core/model/churn.js +5 -0
  109. package/target/main/ts/core/model/clone-source.d.ts +16 -0
  110. package/target/main/ts/core/model/clone-source.js +14 -0
  111. package/target/main/ts/core/model/code-structure.d.ts +30 -0
  112. package/target/main/ts/core/model/code-structure.js +31 -0
  113. package/target/main/ts/core/model/comparison.d.ts +24 -0
  114. package/target/main/ts/core/model/comparison.js +1 -0
  115. package/target/main/ts/core/model/diff-coverage.d.ts +23 -0
  116. package/target/main/ts/core/model/diff-coverage.js +1 -0
  117. package/target/main/ts/core/model/finding-ignore.d.ts +8 -0
  118. package/target/main/ts/core/model/finding-ignore.js +35 -0
  119. package/target/main/ts/core/model/finding.d.ts +28 -0
  120. package/target/main/ts/core/model/finding.js +29 -0
  121. package/target/main/ts/core/model/ignore-rule.d.ts +11 -0
  122. package/target/main/ts/core/model/ignore-rule.js +1 -0
  123. package/target/main/ts/core/model/measurement.d.ts +27 -0
  124. package/target/main/ts/core/model/measurement.js +24 -0
  125. package/target/main/ts/core/model/metric-descriptor.d.ts +17 -0
  126. package/target/main/ts/core/model/metric-descriptor.js +1 -0
  127. package/target/main/ts/core/model/plugin-data.d.ts +25 -0
  128. package/target/main/ts/core/model/plugin-data.js +1 -0
  129. package/target/main/ts/core/model/pull-review.d.ts +48 -0
  130. package/target/main/ts/core/model/pull-review.js +1 -0
  131. package/target/main/ts/core/model/quality-summary.d.ts +42 -0
  132. package/target/main/ts/core/model/quality-summary.js +64 -0
  133. package/target/main/ts/core/model/report.d.ts +32 -0
  134. package/target/main/ts/core/model/report.js +5 -0
  135. package/target/main/ts/core/model/scanner-import.d.ts +39 -0
  136. package/target/main/ts/core/model/scanner-import.js +28 -0
  137. package/target/main/ts/core/model/snapshot.d.ts +15 -0
  138. package/target/main/ts/core/model/snapshot.js +50 -0
  139. package/target/main/ts/core/model/source-locator.d.ts +7 -0
  140. package/target/main/ts/core/model/source-locator.js +1 -0
  141. package/target/main/ts/core/model/source.d.ts +23 -0
  142. package/target/main/ts/core/model/source.js +1 -0
  143. package/target/main/ts/core/ports/report.d.ts +9 -0
  144. package/target/main/ts/core/ports/report.js +1 -0
  145. package/target/main/ts/core/ports/source-provider.d.ts +14 -0
  146. package/target/main/ts/core/ports/source-provider.js +4 -0
  147. package/target/main/ts/core/profile/exclusions.d.ts +11 -0
  148. package/target/main/ts/core/profile/exclusions.js +57 -0
  149. package/target/main/ts/core/profile/maintainability.d.ts +31 -0
  150. package/target/main/ts/core/profile/maintainability.js +9 -0
  151. package/target/main/ts/core/profile/profile.d.ts +4 -0
  152. package/target/main/ts/core/profile/profile.js +10 -0
  153. package/target/main/ts/core/usecases/compare.d.ts +6 -0
  154. package/target/main/ts/core/usecases/compare.js +145 -0
  155. package/target/main/ts/core/usecases/diff-coverage-policy.d.ts +6 -0
  156. package/target/main/ts/core/usecases/diff-coverage-policy.js +10 -0
  157. package/target/main/ts/core/usecases/diff-coverage.d.ts +40 -0
  158. package/target/main/ts/core/usecases/diff-coverage.js +15 -0
  159. package/target/main/ts/core/usecases/inspect.d.ts +38 -0
  160. package/target/main/ts/core/usecases/inspect.js +41 -0
  161. package/target/main/ts/core/usecases/review.d.ts +31 -0
  162. package/target/main/ts/core/usecases/review.js +128 -0
  163. package/target/main/ts/index.d.ts +35 -0
  164. package/target/main/ts/index.js +17 -13
  165. package/target/main/ts/plugin.d.ts +14 -0
  166. package/target/main/ts/plugin.js +5 -0
  167. package/target/main/ts/plugins/coverage/coverage.d.ts +23 -0
  168. package/target/main/ts/plugins/coverage/coverage.js +120 -0
  169. package/target/main/ts/plugins/coverage/diff-coverage.d.ts +7 -0
  170. package/target/main/ts/plugins/coverage/diff-coverage.js +89 -0
  171. package/target/main/ts/plugins/duplication/duplication.d.ts +4 -0
  172. package/target/main/ts/plugins/duplication/duplication.js +93 -0
  173. package/target/main/ts/plugins/language-js/babel-provider.d.ts +10 -0
  174. package/target/main/ts/plugins/language-js/babel-provider.js +46 -0
  175. package/target/main/ts/plugins/language-js/clone-candidates.d.ts +3 -0
  176. package/target/main/ts/plugins/language-js/clone-candidates.js +64 -0
  177. package/target/main/ts/plugins/language-js/code-lines.d.ts +6 -0
  178. package/target/main/ts/plugins/language-js/code-lines.js +35 -0
  179. package/target/main/ts/plugins/language-js/function-facts.d.ts +8 -0
  180. package/target/main/ts/plugins/language-js/function-facts.js +60 -0
  181. package/target/main/ts/plugins/language-js/structural-observations.d.ts +8 -0
  182. package/target/main/ts/plugins/language-js/structural-observations.js +79 -0
  183. package/target/main/ts/plugins/maintainability/maintainability.d.ts +9 -0
  184. package/target/main/ts/plugins/maintainability/maintainability.js +42 -0
  185. package/target/main/ts/plugins/maintainability/structural-smells.d.ts +3 -0
  186. package/target/main/ts/plugins/maintainability/structural-smells.js +15 -0
  187. package/target/main/ts/plugins/source/forges.d.ts +4 -0
  188. package/target/main/ts/plugins/source/forges.js +79 -0
  189. package/target/main/ts/plugins/structure/structure.d.ts +2 -0
  190. package/target/main/ts/plugins/structure/structure.js +37 -0
  191. package/target/main/ts/report/html/app/viewer-access.d.ts +19 -0
  192. package/target/main/ts/report/html/app/viewer-access.js +25 -0
  193. package/target/main/ts/report/html/app/viewer-chart.d.ts +101 -0
  194. package/target/main/ts/report/html/app/viewer-chart.js +711 -0
  195. package/target/main/ts/report/html/app/viewer-commits.d.ts +36 -0
  196. package/target/main/ts/report/html/app/viewer-commits.js +280 -0
  197. package/target/main/ts/report/html/app/viewer-data.d.ts +23 -0
  198. package/target/main/ts/report/html/app/viewer-data.js +105 -0
  199. package/target/main/ts/report/html/app/viewer-files.d.ts +117 -0
  200. package/target/main/ts/report/html/app/viewer-files.js +2087 -0
  201. package/target/main/ts/report/html/app/viewer-filter.d.ts +113 -0
  202. package/target/main/ts/report/html/app/viewer-filter.js +492 -0
  203. package/target/main/ts/report/html/app/viewer-metric-registry.d.ts +68 -0
  204. package/target/main/ts/report/html/app/viewer-metric-registry.js +206 -0
  205. package/target/main/ts/report/html/app/viewer-metrics.d.ts +44 -0
  206. package/target/main/ts/report/html/app/viewer-metrics.js +172 -0
  207. package/target/main/ts/report/html/app/viewer-profile.d.ts +17 -0
  208. package/target/main/ts/report/html/app/viewer-profile.js +401 -0
  209. package/target/main/ts/report/html/app/viewer-projects.d.ts +1 -0
  210. package/target/main/ts/report/html/app/viewer-projects.js +90 -0
  211. package/target/main/ts/report/html/app/viewer-pulls.d.ts +3 -0
  212. package/target/main/ts/report/html/app/viewer-pulls.js +242 -0
  213. package/target/main/ts/report/html/app/viewer-source.d.ts +75 -0
  214. package/target/main/ts/report/html/app/viewer-source.js +313 -0
  215. package/target/main/ts/report/html/app/viewer-trends.d.ts +74 -0
  216. package/target/main/ts/report/html/app/viewer-trends.js +413 -0
  217. package/target/main/ts/report/html/app/viewer.d.ts +1 -0
  218. package/target/main/ts/report/html/app/viewer.js +794 -0
  219. package/target/main/ts/report/html/site/badges.d.ts +14 -0
  220. package/target/main/ts/report/html/site/badges.js +39 -0
  221. package/target/main/ts/report/html/site/export-site.d.ts +21 -0
  222. package/target/main/ts/report/html/site/export-site.js +157 -0
  223. package/target/main/ts/report/html/site/exported-server.d.ts +6 -0
  224. package/target/main/ts/report/html/site/exported-server.js +70 -0
  225. package/target/main/ts/report/html/site/local-server.d.ts +7 -0
  226. package/target/main/ts/report/html/site/local-server.js +64 -0
  227. package/target/main/ts/report/html/site/projects.d.ts +3 -0
  228. package/target/main/ts/report/html/site/projects.js +79 -0
  229. package/target/main/ts/report/html/site/server.d.ts +4 -0
  230. package/target/main/ts/report/html/site/server.js +64 -0
  231. package/target/main/ts/report/html/site/source-route.d.ts +6 -0
  232. package/target/main/ts/report/html/site/source-route.js +22 -0
  233. package/target/main/ts/report/json/projections/commit-summary.d.ts +11 -0
  234. package/target/main/ts/report/json/projections/commit-summary.js +118 -0
  235. package/target/main/ts/report/json/projections/components.d.ts +4 -0
  236. package/target/main/ts/report/json/projections/components.js +29 -0
  237. package/target/main/ts/report/json/projections/file-metrics.d.ts +5 -0
  238. package/target/main/ts/report/json/projections/file-metrics.js +243 -0
  239. package/target/main/ts/report/json/projections/inspection-context.d.ts +6 -0
  240. package/target/main/ts/report/json/projections/inspection-context.js +92 -0
  241. package/target/main/ts/report/json/projections/inspection-details.d.ts +11 -0
  242. package/target/main/ts/report/json/projections/inspection-details.js +69 -0
  243. package/target/main/ts/report/json/projections/metric-values.d.ts +7 -0
  244. package/target/main/ts/report/json/projections/metric-values.js +57 -0
  245. package/target/main/ts/report/json/projections/public-history.d.ts +4 -0
  246. package/target/main/ts/report/json/projections/public-history.js +16 -0
  247. package/target/main/ts/report/json/store/components.d.ts +2 -0
  248. package/target/main/ts/report/json/store/components.js +31 -0
  249. package/target/main/ts/report/json/store/local-store.d.ts +13 -0
  250. package/target/main/ts/report/json/store/local-store.js +179 -0
  251. package/target/main/ts/report/json/store/pull-review-store.d.ts +3 -0
  252. package/target/main/ts/report/json/store/pull-review-store.js +51 -0
  253. package/target/main/ts/report/json/validation/metabranch.d.ts +4 -0
  254. package/target/main/ts/report/json/validation/metabranch.js +7 -0
  255. package/target/main/ts/report/json/validation/report.d.ts +15 -0
  256. package/target/main/ts/report/json/validation/report.js +64 -0
  257. package/target/main/ts/report/json/validation/summary-validation.d.ts +4 -0
  258. package/target/main/ts/report/json/validation/summary-validation.js +27 -0
  259. package/target/main/ts/report/json/wire/compact-json.d.ts +11 -0
  260. package/target/main/ts/report/json/wire/compact-json.js +76 -0
  261. package/target/main/ts/report/json/wire/component-model.d.ts +9 -0
  262. package/target/main/ts/report/json/wire/component-model.js +1 -0
  263. package/target/main/ts/report/json/wire/domain-types.d.ts +2 -0
  264. package/target/main/ts/report/json/wire/domain-types.js +1 -0
  265. package/target/main/ts/report/json/wire/file-metrics-model.d.ts +77 -0
  266. package/target/main/ts/report/json/wire/file-metrics-model.js +1 -0
  267. package/target/main/ts/report/json/wire/inspection-context-model.d.ts +26 -0
  268. package/target/main/ts/report/json/wire/inspection-context-model.js +1 -0
  269. package/target/main/ts/report/json/wire/inspection-details-model.d.ts +82 -0
  270. package/target/main/ts/report/json/wire/inspection-details-model.js +1 -0
  271. package/target/main/ts/report/json/wire/project-model.d.ts +7 -0
  272. package/target/main/ts/report/json/wire/project-model.js +1 -0
  273. package/target/main/ts/report/json/wire/public-history-model.d.ts +42 -0
  274. package/target/main/ts/report/json/wire/public-history-model.js +6 -0
  275. package/target/main/ts/report/json/wire/pull-review-model.d.ts +7 -0
  276. package/target/main/ts/report/json/wire/pull-review-model.js +1 -0
  277. package/target/main/ts/report/json/wire/summary-model.d.ts +45 -0
  278. package/target/main/ts/report/json/wire/summary-model.js +1 -0
  279. package/target/main/ts/report.d.ts +11 -0
  280. package/target/main/ts/report.js +5 -0
  281. package/index.js +0 -1
@@ -0,0 +1,226 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { isRecord } from '../../core/engine/plugin.js';
5
+ import { digest } from '../../core/model/snapshot.js';
6
+ import { uniqueScanners, scannerText as text } from '../../core/model/scanner-import.js';
7
+ export { findingImportMethods } from '../../core/model/scanner-import.js';
8
+ export async function importFindings(input, root, excludes, knownPaths) {
9
+ const bytes = await readFile(input.file);
10
+ let parsed;
11
+ try {
12
+ const value = JSON.parse(bytes.toString('utf8'));
13
+ const map = (path) => repositoryPath(root, path);
14
+ parsed = input.format === 'sarif' ? parseSarif(value, input.category, root)
15
+ : input.format === 'eslint' ? parseESLint(value, map) : parseOSV(value, map);
16
+ }
17
+ catch {
18
+ throw new Error(`Invalid ${input.format.toUpperCase()} finding input (${input.category})`);
19
+ }
20
+ const { toolVersion, settingsDigest = null, scope = null } = input;
21
+ if (toolVersion !== undefined && (parsed.tools.length !== 1 || !text(toolVersion)))
22
+ throw new Error('A tool version override requires one scanner');
23
+ if (settingsDigest !== null && !/^[a-f0-9]{64}$/.test(settingsDigest))
24
+ throw new Error('Invalid scanner settings digest');
25
+ const tools = toolVersion === undefined ? parsed.tools : [{ name: parsed.tools[0].name, version: toolVersion }];
26
+ const findings = [];
27
+ let unmapped = 0;
28
+ for (const item of parsed.items) {
29
+ if (item?.path && excludes(item.path))
30
+ continue;
31
+ if (item === null || (item.path && knownPaths && !knownPaths.has(item.path))) {
32
+ unmapped++;
33
+ continue;
34
+ }
35
+ const related = item.related?.filter(location => !excludes(location.path) && (!knownPaths || knownPaths.has(location.path)));
36
+ findings.push({ ...item, related: related?.length ? related : undefined });
37
+ }
38
+ return { findings, metadata: { format: input.format, category: input.category, inputDigest: digest(bytes), tools, settingsDigest, scope,
39
+ imported: findings.length, reported: parsed.items.length, unmapped, units: parsed.units } };
40
+ }
41
+ function parseSarif(value, category, root) {
42
+ const report = object(value);
43
+ if (report.version !== '2.1.0')
44
+ throw new Error('Unknown SARIF version');
45
+ const runs = array(report.runs);
46
+ const tools = [];
47
+ const items = [];
48
+ for (const value of runs) {
49
+ const run = object(value);
50
+ const driver = object(object(run.tool).driver);
51
+ const tool = requiredText(driver.name);
52
+ tools.push({ name: tool, version: text(driver.semanticVersion) ?? text(driver.version) ?? null });
53
+ const rules = optionalArray(driver.rules);
54
+ const rulesById = new Map(rules.filter(isRecord).map(rule => [text(rule.id), rule]));
55
+ const artifacts = optionalArray(run.artifacts);
56
+ const bases = isRecord(run.originalUriBaseIds) ? run.originalUriBaseIds : {};
57
+ if (optionalArray(run.invocations).some(invocation => object(invocation).executionSuccessful === false)) {
58
+ throw new Error('SARIF run reports an execution failure');
59
+ }
60
+ for (const candidate of optionalArray(run.results)) {
61
+ const result = object(candidate);
62
+ if (result.kind !== undefined && result.kind !== 'fail' || optionalArray(result.suppressions).some(suppression => object(suppression).status === undefined || object(suppression).status === 'accepted'))
63
+ continue;
64
+ const id = text(result.ruleId);
65
+ const descriptor = safeIndex(result.ruleIndex) ? rules[result.ruleIndex] : id ? rulesById.get(id) : undefined;
66
+ const rule = isRecord(descriptor) ? descriptor : {};
67
+ const defaultConfiguration = isRecord(rule.defaultConfiguration) ? rule.defaultConfiguration : {};
68
+ const level = lookupLevel(result.level ?? defaultConfiguration.level);
69
+ const ruleId = id ?? text(rule.id) ?? '(unclassified)';
70
+ const message = category === 'secret' ? 'Potential secret reported by a scanner' : sarifMessage(result.message);
71
+ const locations = optionalArray(result.locations).map(location => sarifLocation(location, artifacts, bases, root));
72
+ const primary = locations.find(location => location && location.path !== null);
73
+ const related = locations.filter((location) => location !== primary && location !== undefined && location.path !== null && location.line !== undefined && location.endLine !== undefined);
74
+ items.push(locations.some(location => location?.path === null) && !primary ? null : {
75
+ tool, rule: ruleId, category, level, message, ...(primary?.path && { ...primary, path: primary.path }), related,
76
+ });
77
+ }
78
+ }
79
+ return { tools: uniqueScanners(tools), items, units: runs.length };
80
+ }
81
+ function sarifMessage(value) {
82
+ const message = object(value);
83
+ return text(message.text) ?? text(message.markdown) ?? text(message.id) ?? '(missing message)';
84
+ }
85
+ function sarifLocation(value, artifacts, bases, root) {
86
+ const location = object(value);
87
+ const physical = location.physicalLocation;
88
+ if (!isRecord(physical) || !isRecord(physical.artifactLocation))
89
+ return;
90
+ const artifact = physical.artifactLocation;
91
+ const stored = safeIndex(artifact.index) ? artifacts[artifact.index] : undefined;
92
+ const fallback = isRecord(stored) && isRecord(stored.location) ? stored.location : {};
93
+ const uri = text(artifact.uri) ?? text(fallback.uri);
94
+ if (!uri)
95
+ return { path: null };
96
+ const baseId = text(artifact.uriBaseId) ?? text(fallback.uriBaseId);
97
+ const base = pathToFileURL(`${root}${sep}`);
98
+ const resolvedBase = baseId ? sarifBase(baseId, bases, base, new Set()) : base;
99
+ const file = fileLocation(uri, resolvedBase);
100
+ const path = file === null ? null : repositoryPath(root, file);
101
+ const source = isRecord(physical.region) ? physical.region : {};
102
+ return { path, ...range(source.startLine, source.endLine) };
103
+ }
104
+ function sarifBase(id, bases, fallback, visited) {
105
+ if (visited.has(id))
106
+ return null;
107
+ if (!Object.hasOwn(bases, id))
108
+ return id === '%SRCROOT%' ? fallback : null;
109
+ visited.add(id);
110
+ const item = object(bases[id]);
111
+ const uri = text(item.uri);
112
+ const parent = text(item.uriBaseId);
113
+ const base = parent ? sarifBase(parent, bases, fallback, visited) : fallback;
114
+ const file = uri && fileLocation(uri, base);
115
+ return file ? pathToFileURL(file) : null;
116
+ }
117
+ function fileLocation(uri, base) {
118
+ try {
119
+ const url = base === null ? new URL(uri) : new URL(uri, base);
120
+ if (url.protocol !== 'file:' || url.search !== '' || url.hash !== '')
121
+ return null;
122
+ return fileURLToPath(url);
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ }
128
+ function parseESLint(value, map) {
129
+ const files = array(isRecord(value) ? value.results : value);
130
+ const items = [];
131
+ for (const candidate of files) {
132
+ const file = object(candidate);
133
+ const path = map(requiredText(file.filePath));
134
+ for (const value of array(file.messages)) {
135
+ const message = object(value);
136
+ items.push(path === null ? null : { tool: 'eslint', rule: text(message.ruleId) ?? (message.fatal === true ? 'parse-error' : '(unclassified)'),
137
+ category: 'lint', level: message.severity === 2 ? 'high' : message.severity === 1 ? 'medium' : 'unknown',
138
+ message: requiredText(message.message), path, ...range(message.line, message.endLine) });
139
+ }
140
+ }
141
+ return { tools: [{ name: 'eslint', version: null }], items, units: files.length };
142
+ }
143
+ function parseOSV(value, map) {
144
+ const report = object(value);
145
+ const sources = report.results === null ? [] : array(report.results);
146
+ const items = [];
147
+ let units = 0;
148
+ for (const value of sources) {
149
+ const source = object(value);
150
+ const pathValue = isRecord(source.source) ? text(source.source.path) : undefined;
151
+ const path = pathValue === undefined ? undefined : map(pathValue);
152
+ for (const candidate of array(source.packages)) {
153
+ units++;
154
+ const listed = object(candidate);
155
+ const pkg = object(listed.package);
156
+ const name = requiredText(pkg.name);
157
+ const version = text(pkg.version) ?? text(pkg.commit);
158
+ const advisories = new Set(optionalArray(listed.vulnerabilities).map(value => requiredText(object(value).id)));
159
+ for (const entry of optionalArray(listed.groups)) {
160
+ const group = object(entry);
161
+ const identifiers = array(group.ids).map(requiredText);
162
+ if (advisories.size > 0 && identifiers.some(id => advisories.has(id))) {
163
+ const canonical = advisoryId([...identifiers, ...optionalArray(group.aliases).map(requiredText)]);
164
+ add(canonical, scoreLevel(group.max_severity));
165
+ for (const id of identifiers)
166
+ advisories.delete(id);
167
+ }
168
+ }
169
+ for (const advisory of advisories)
170
+ add(advisory, 'unknown');
171
+ function add(rule, level) {
172
+ items.push(path === null ? null : { tool: 'osv-scanner', rule, category: 'dependency', level, path,
173
+ message: `Advisory for ${name}${version ? `@${version}` : ''}` });
174
+ }
175
+ }
176
+ }
177
+ return { tools: [{ name: 'osv-scanner', version: null }], items, units };
178
+ }
179
+ function advisoryId(ids) {
180
+ const sorted = [...ids].sort();
181
+ return sorted.find(id => id.startsWith('CVE-')) ?? sorted.find(id => id.startsWith('GHSA-')) ?? sorted[0];
182
+ }
183
+ function scoreLevel(value) {
184
+ const numeric = typeof value === 'string' && /^(?:\d+|\d+\.\d+)$/.test(value) ? Number(value) : value;
185
+ if (typeof numeric !== 'number' || !Number.isFinite(numeric) || numeric <= 0 || numeric > 10)
186
+ return 'unknown';
187
+ return numeric >= 7 ? 'high' : numeric >= 4 ? 'medium' : 'low';
188
+ }
189
+ function lookupLevel(value) {
190
+ return value === 'error' ? 'high' : value === 'warning' ? 'medium' : value === 'note' ? 'low' : 'unknown';
191
+ }
192
+ function range(first, last) {
193
+ if (!safeIndex(first) || first === 0)
194
+ return {};
195
+ return { line: first, endLine: safeIndex(last) && last >= first ? last : first };
196
+ }
197
+ function repositoryPath(root, path) {
198
+ if (/[\0\r\n]/.test(path))
199
+ return null;
200
+ const result = relative(root, resolve(root, path));
201
+ if (result === '' || isAbsolute(result) || result === '..' || result.startsWith(`..${sep}`))
202
+ return null;
203
+ return result.split(sep).join('/');
204
+ }
205
+ function requiredText(value) {
206
+ const result = text(value);
207
+ if (result === undefined)
208
+ throw new Error('Invalid scanner field');
209
+ return result;
210
+ }
211
+ function object(value) {
212
+ if (!isRecord(value))
213
+ throw new Error('Expected scanner object');
214
+ return value;
215
+ }
216
+ function array(value) {
217
+ if (!Array.isArray(value))
218
+ throw new Error('Expected scanner array');
219
+ return value;
220
+ }
221
+ function optionalArray(value) {
222
+ return value === undefined ? [] : array(value);
223
+ }
224
+ function safeIndex(value) {
225
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
226
+ }
@@ -0,0 +1,5 @@
1
+ export type LcovFiles = string | readonly string[];
2
+ export declare function readLcovFiles(input: LcovFiles): Promise<{
3
+ text: string;
4
+ inputDigests: string[];
5
+ }>;
@@ -0,0 +1,13 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { comparePaths, digest, utf8 } from '../../core/model/snapshot.js';
3
+ export async function readLcovFiles(input) {
4
+ const paths = typeof input === 'string' ? [input] : input;
5
+ if (paths.length === 0)
6
+ throw new Error('Provide at least one LCOV file');
7
+ const sources = await Promise.all(paths.map(async (path) => {
8
+ const text = utf8(await readFile(path));
9
+ return { text, digest: digest(text) };
10
+ }));
11
+ sources.sort((a, b) => comparePaths(a.digest, b.digest));
12
+ return { text: sources.map(source => source.text).join('\n'), inputDigests: sources.map(source => source.digest) };
13
+ }
@@ -0,0 +1,4 @@
1
+ export declare function readProfile(file: string | undefined, optional?: boolean): Promise<{
2
+ exclude: readonly string[];
3
+ ignore: readonly import("../../index.js").FindingIgnoreRule[];
4
+ }>;
@@ -0,0 +1,16 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { normalizeProfile } from '../../core/profile/profile.js';
3
+ export async function readProfile(file, optional = false) {
4
+ if (file === undefined)
5
+ return { exclude: [], ignore: [] };
6
+ let text;
7
+ try {
8
+ text = await readFile(file, 'utf8');
9
+ }
10
+ catch (error) {
11
+ if (optional && error instanceof Error && 'code' in error && error.code === 'ENOENT')
12
+ return { exclude: [], ignore: [] };
13
+ throw error;
14
+ }
15
+ return normalizeProfile(JSON.parse(text));
16
+ }
@@ -0,0 +1,2 @@
1
+ import type { AnalysisExecutor } from '../../core/usecases/inspect.js';
2
+ export declare function remoteExecutor(endpoint: string, token: string): AnalysisExecutor;
@@ -0,0 +1,45 @@
1
+ import { readReport } from '../../report/json/validation/report.js';
2
+ import { encodeWorkerInput, maxWorkerInput, maxWorkerResult, workerRoute } from './worker-protocol.js';
3
+ export function remoteExecutor(endpoint, token) {
4
+ const base = new URL(endpoint);
5
+ const local = ['127.0.0.1', '[::1]', 'localhost'].includes(base.hostname);
6
+ if (base.protocol !== 'https:' && !(base.protocol === 'http:' && local)) {
7
+ throw new Error('Use HTTPS for a remote worker or HTTP over loopback');
8
+ }
9
+ if (base.username || base.password || base.search || base.hash)
10
+ throw new Error('Invalid worker base URL');
11
+ base.pathname = base.pathname.replace(/\/+$/, '') + workerRoute;
12
+ return async (input) => {
13
+ const body = encodeWorkerInput(input);
14
+ if (Buffer.byteLength(body) > maxWorkerInput)
15
+ throw new Error('Worker input exceeds 16 MiB');
16
+ const response = await fetch(base, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
17
+ body, signal: AbortSignal.timeout(60_000), redirect: 'error' });
18
+ if (!response.ok) {
19
+ await response.body?.cancel();
20
+ throw new Error(`Worker request failed (HTTP ${response.status})`);
21
+ }
22
+ if (!response.body)
23
+ throw new Error('Missing worker response');
24
+ const reader = response.body.getReader();
25
+ const parts = [];
26
+ let size = 0;
27
+ try {
28
+ for (;;) {
29
+ const part = await reader.read();
30
+ if (part.done)
31
+ break;
32
+ size += part.value.byteLength;
33
+ if (size > maxWorkerResult) {
34
+ await reader.cancel();
35
+ throw new Error('Worker response exceeds 64 MiB');
36
+ }
37
+ parts.push(part.value);
38
+ }
39
+ }
40
+ finally {
41
+ reader.releaseLock();
42
+ }
43
+ return readReport(JSON.parse(Buffer.concat(parts).toString('utf8')));
44
+ };
45
+ }
@@ -0,0 +1,7 @@
1
+ import type { AnalysisInput } from '../../core/usecases/inspect.js';
2
+ export declare const workerRoute = "/v1/inspect";
3
+ export declare const maxWorkerInput: number;
4
+ export declare const maxWorkerResult: number;
5
+ export declare function workerToken(value?: string | undefined): string;
6
+ export declare function encodeWorkerInput(input: AnalysisInput): string;
7
+ export declare function decodeWorkerInput(value: unknown): AnalysisInput;
@@ -0,0 +1,101 @@
1
+ import { isRecord } from '../../core/engine/plugin.js';
2
+ import { validSubjectId } from '../../report/json/validation/report.js';
3
+ import { exclusionMatcher, normalizeExclusions } from '../../core/profile/exclusions.js';
4
+ import { comparePaths, isSourcePath, workingSnapshot } from '../../core/model/snapshot.js';
5
+ const schemaV1 = 'urn:repometry:schema:worker-input:1';
6
+ const schemaV2 = 'urn:repometry:schema:worker-input:2';
7
+ export const workerRoute = '/v1/inspect';
8
+ export const maxWorkerInput = 16 * 1024 * 1024;
9
+ export const maxWorkerResult = 64 * 1024 * 1024;
10
+ export function workerToken(value = process.env.REPOMETRY_WORKER_TOKEN) {
11
+ if (!value || !/^[A-Za-z0-9._~-]+$/.test(value))
12
+ throw new Error('Set REPOMETRY_WORKER_TOKEN before using the worker');
13
+ return value;
14
+ }
15
+ export function encodeWorkerInput(input) {
16
+ const { subject, files, inventory, generatedExcluded } = input.snapshot;
17
+ const excludedPaths = input.excludedPaths ?? [];
18
+ const profile = excludedPaths.length === 0 ? { schema: schemaV1 } : { schema: schemaV2, excludedPaths };
19
+ return JSON.stringify({ ...profile, subject, excludedOutput: input.excludedOutput, coverage: input.coverage ?? null,
20
+ files: files.map(({ path, bytes }) => ({ path, base64: Buffer.from(bytes).toString('base64') })),
21
+ ...(inventory === undefined ? {} : { inventory }), ...(generatedExcluded?.length ? { generatedExcluded } : {}) });
22
+ }
23
+ export function decodeWorkerInput(value) {
24
+ if (!isRecord(value) || (value.schema !== schemaV1 && value.schema !== schemaV2) || !isSubject(value.subject) || !Array.isArray(value.files)) {
25
+ throw new Error('Invalid worker input envelope');
26
+ }
27
+ const { subject, excludedOutput } = value;
28
+ const excludedPaths = value.schema === schemaV2 ? normalizeExclusions(value.excludedPaths) : [];
29
+ const excludes = exclusionMatcher(excludedPaths);
30
+ if (excludedOutput !== null && (typeof excludedOutput !== 'string' || !safePath(excludedOutput)))
31
+ throw new Error('Invalid excluded output');
32
+ if (subject.kind === 'commit' && excludedOutput !== null)
33
+ throw new Error('Invalid excluded output for the Git snapshot');
34
+ const files = [];
35
+ const paths = new Set();
36
+ for (const item of value.files) {
37
+ if (!isRecord(item) || typeof item.path !== 'string' || !safePath(item.path) || !isSourcePath(item.path) || excludes(item.path)
38
+ || typeof item.base64 !== 'string') {
39
+ throw new Error('Invalid worker source file');
40
+ }
41
+ if (paths.has(item.path))
42
+ throw new Error('Duplicate worker source path');
43
+ const bytes = Buffer.from(item.base64, 'base64');
44
+ if (bytes.toString('base64') !== item.base64)
45
+ throw new Error('Invalid worker source encoding');
46
+ paths.add(item.path);
47
+ files.push({ path: item.path, bytes });
48
+ }
49
+ if (subject.kind === 'working-tree' && workingSnapshot(files).subject.id !== subject.id) {
50
+ throw new Error('Invalid working snapshot digest');
51
+ }
52
+ files.sort((a, b) => comparePaths(a.path, b.path));
53
+ const inventory = readInventory(value.inventory, excludes);
54
+ const generatedExcluded = readGeneratedExclusions(value.generatedExcluded, paths, inventory);
55
+ return { snapshot: { subject, files, ...(inventory === undefined ? {} : { inventory }), generatedExcluded },
56
+ excludedOutput, excludedPaths, coverage: readCoverage(value.coverage) };
57
+ }
58
+ function readGeneratedExclusions(value, sourcePaths, inventory) {
59
+ if (value === undefined)
60
+ return [];
61
+ if (!Array.isArray(value))
62
+ throw new Error('Invalid worker generated exclusions');
63
+ const listed = new Set([...sourcePaths, ...(inventory ?? []).map(file => file.path)]);
64
+ const excluded = new Set();
65
+ for (const path of value) {
66
+ if (typeof path !== 'string' || !safePath(path) || !isSourcePath(path) || listed.has(path) || excluded.has(path)) {
67
+ throw new Error('Invalid worker generated exclusion');
68
+ }
69
+ excluded.add(path);
70
+ }
71
+ return [...excluded].sort(comparePaths);
72
+ }
73
+ function readInventory(value, excludes) {
74
+ if (value === undefined)
75
+ return undefined;
76
+ if (!Array.isArray(value))
77
+ throw new Error('Invalid worker file inventory');
78
+ const inventory = new Map();
79
+ for (const item of value) {
80
+ if (!isRecord(item) || typeof item.path !== 'string' || !safePath(item.path) || excludes(item.path) || inventory.has(item.path)
81
+ || (item.lines !== null && (typeof item.lines !== 'number' || !Number.isSafeInteger(item.lines) || item.lines < 0))
82
+ || (item.bytes !== undefined && (typeof item.bytes !== 'number' || !Number.isSafeInteger(item.bytes) || item.bytes < 0))) {
83
+ throw new Error('Invalid worker inventory file');
84
+ }
85
+ inventory.set(item.path, { path: item.path, lines: item.lines, ...(item.bytes === undefined ? {} : { bytes: item.bytes }) });
86
+ }
87
+ return [...inventory.values()];
88
+ }
89
+ function isSubject(value) {
90
+ return isRecord(value) && (value.kind === 'commit' || value.kind === 'working-tree') && typeof value.id === 'string' && validSubjectId(value.kind, value.id);
91
+ }
92
+ function safePath(path) {
93
+ return !path.includes('\0') && !path.split('/').some(part => part === '' || part === '.' || part === '..');
94
+ }
95
+ function readCoverage(value) {
96
+ if (value === null)
97
+ return undefined;
98
+ if (!isRecord(value) || typeof value.text !== 'string' || typeof value.sourceRoot !== 'string')
99
+ throw new Error('Invalid worker LCOV input');
100
+ return { text: value.text, sourceRoot: value.sourceRoot };
101
+ }
@@ -0,0 +1,5 @@
1
+ import type { AnalysisExecutor } from '../../core/usecases/inspect.js';
2
+ export declare function serveWorker(host: '127.0.0.1' | '0.0.0.0', port: number, token: string, analyze: AnalysisExecutor): Promise<{
3
+ url: string;
4
+ close: () => void;
5
+ }>;
@@ -0,0 +1,85 @@
1
+ import { timingSafeEqual } from 'node:crypto';
2
+ import { createServer } from 'node:http';
3
+ import { utf8 } from '../../core/model/snapshot.js';
4
+ import { decodeWorkerInput, maxWorkerInput, maxWorkerResult, workerRoute } from './worker-protocol.js';
5
+ export async function serveWorker(host, port, token, analyze) {
6
+ let busy = false;
7
+ const server = createServer({ headersTimeout: 10_000, requestTimeout: 30_000, connectionsCheckingInterval: 5_000 }, (request, response) => {
8
+ if (request.url !== workerRoute) {
9
+ reply(response, 404, 'Unknown worker route');
10
+ return;
11
+ }
12
+ if (request.method !== 'POST') {
13
+ reply(response, 405, 'Use POST');
14
+ return;
15
+ }
16
+ if (!authorized(request, token)) {
17
+ reply(response, 401, 'Invalid token');
18
+ return;
19
+ }
20
+ if (busy) {
21
+ reply(response, 503, 'Worker is busy');
22
+ return;
23
+ }
24
+ busy = true;
25
+ void handle(request, response, analyze).finally(() => { busy = false; });
26
+ });
27
+ await new Promise((resolve, reject) => {
28
+ server.once('error', reject);
29
+ server.listen(port, host, () => { server.removeListener('error', reject); resolve(); });
30
+ });
31
+ const address = server.address();
32
+ if (!address || typeof address === 'string') {
33
+ server.close();
34
+ throw new Error('Cannot determine the worker address');
35
+ }
36
+ return { url: `http://${host}:${address.port}/`, close: () => server.close() };
37
+ }
38
+ async function handle(request, response, analyze) {
39
+ const declared = Number(request.headers['content-length']);
40
+ if (declared > maxWorkerInput) {
41
+ reply(response, 413, 'Worker input exceeds 16 MiB');
42
+ return;
43
+ }
44
+ const parts = [];
45
+ let size = 0;
46
+ let payload;
47
+ try {
48
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
49
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
50
+ size += bytes.length;
51
+ if (size > maxWorkerInput) {
52
+ reply(response, 413, 'Worker input exceeds 16 MiB');
53
+ return;
54
+ }
55
+ parts.push(bytes);
56
+ }
57
+ payload = decodeWorkerInput(JSON.parse(utf8(Buffer.concat(parts))));
58
+ }
59
+ catch {
60
+ reply(response, 400, 'Invalid worker input');
61
+ return;
62
+ }
63
+ try {
64
+ const result = JSON.stringify(await analyze(payload));
65
+ if (Buffer.byteLength(result) > maxWorkerResult) {
66
+ reply(response, 422, 'Report exceeds 64 MiB');
67
+ return;
68
+ }
69
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }).end(result);
70
+ }
71
+ catch {
72
+ reply(response, 500, 'Worker analysis failed');
73
+ }
74
+ }
75
+ function authorized(request, token) {
76
+ const actual = Buffer.from(request.headers.authorization ?? '');
77
+ const expected = Buffer.from(`Bearer ${token}`);
78
+ return actual.length === expected.length && timingSafeEqual(actual, expected);
79
+ }
80
+ function reply(response, status, error) {
81
+ if (response.destroyed)
82
+ return;
83
+ response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', Connection: 'close' });
84
+ response.end(JSON.stringify({ error }));
85
+ }
@@ -0,0 +1,28 @@
1
+ interface Option {
2
+ readonly type: 'string' | 'boolean';
3
+ readonly description: string;
4
+ readonly value?: string;
5
+ readonly short?: string;
6
+ readonly multiple?: boolean;
7
+ }
8
+ export interface Invocation {
9
+ readonly args: readonly string[];
10
+ text(name: string): string | undefined;
11
+ flag(name: string): boolean;
12
+ many(name: string): readonly string[];
13
+ }
14
+ export interface Command {
15
+ readonly description: string;
16
+ readonly parameters?: string;
17
+ readonly min?: number;
18
+ readonly max?: number;
19
+ readonly options?: Readonly<Record<string, Option>>;
20
+ run(input: Invocation): Promise<number | void> | number | void;
21
+ }
22
+ export declare function option(value: string, description: string, props?: {
23
+ short?: string;
24
+ multiple?: boolean;
25
+ }): Option;
26
+ export declare function flag(description: string, short?: string): Option;
27
+ export declare function dispatch(commands: Readonly<Record<string, Command>>, input: readonly string[], version: string): Promise<number>;
28
+ export {};
@@ -0,0 +1,110 @@
1
+ import { parseArgs } from 'node:util';
2
+ export function option(value, description, props = {}) {
3
+ return { type: 'string', value, description, ...props };
4
+ }
5
+ export function flag(description, short) {
6
+ return { type: 'boolean', description, short };
7
+ }
8
+ const globals = {
9
+ help: flag('Show command help.', 'h'),
10
+ version: flag('Show the installed version.', 'V'),
11
+ repo: option('DIR', 'Run in the given repository.', { short: 'C' }),
12
+ store: option('PATH|git:REF', 'Select a report store.'),
13
+ };
14
+ export async function dispatch(commands, input, version) {
15
+ const [name, ...rest] = placeGlobalOptions(input);
16
+ if (name === '--version' || name === '-V') {
17
+ process.stdout.write(version + '\n');
18
+ return 0;
19
+ }
20
+ if (name === undefined || name === '--help' || name === '-h' || name === 'help') {
21
+ showHelp(commands, name === 'help' ? rest[0] : undefined);
22
+ return 0;
23
+ }
24
+ const command = Object.hasOwn(commands, name) ? commands[name] : undefined;
25
+ if (!command)
26
+ throw new Error(`Unknown command: ${name}.${suggest(name, Object.keys(commands))}`);
27
+ const options = { ...globals, ...command.options };
28
+ const config = Object.fromEntries(Object.entries(options).map(([key, { type, short, multiple }]) => [key,
29
+ { type, ...(short === undefined ? {} : { short }), ...(multiple === undefined ? {} : { multiple }) }]));
30
+ let parsed;
31
+ try {
32
+ parsed = parseArgs({ args: rest, options: config, allowPositionals: true });
33
+ }
34
+ catch (error) {
35
+ if (error instanceof Error && 'code' in error && error.code === 'ERR_PARSE_ARGS_UNKNOWN_OPTION') {
36
+ const unknown = /'([^']+)'/.exec(error.message)?.[1] ?? '';
37
+ const choices = Object.keys(options).map(value => '--' + value);
38
+ throw new Error(`${unknown || 'Unknown option'} is not an option of ${name}.${suggest(unknown, choices)}`);
39
+ }
40
+ throw error;
41
+ }
42
+ if (parsed.values.version) {
43
+ process.stdout.write(version + '\n');
44
+ return 0;
45
+ }
46
+ if (parsed.values.help) {
47
+ showHelp(commands, name);
48
+ return 0;
49
+ }
50
+ const args = parsed.positionals;
51
+ if (args.length < (command.min ?? 0) || args.length > (command.max ?? 0)) {
52
+ throw new Error(`Usage: repometry ${name}${command.parameters ? ' ' + command.parameters : ''}`);
53
+ }
54
+ const result = await command.run({
55
+ args,
56
+ text: key => typeof parsed.values[key] === 'string' ? parsed.values[key] : undefined,
57
+ flag: key => parsed.values[key] === true,
58
+ many: key => Array.isArray(parsed.values[key]) ? parsed.values[key] : [],
59
+ });
60
+ return result ?? 0;
61
+ }
62
+ function placeGlobalOptions(input) {
63
+ const leading = [];
64
+ let index = 0;
65
+ while (index < input.length) {
66
+ const next = input[index];
67
+ if (/^(?:--repo|--store)=/.test(next))
68
+ leading.push(next);
69
+ else if (next === '-C' || next === '--repo' || next === '--store') {
70
+ if (input[index + 1] === undefined)
71
+ throw new Error(`${next} needs a value`);
72
+ leading.push(next, input[++index]);
73
+ }
74
+ else
75
+ break;
76
+ index++;
77
+ }
78
+ return input[index] === undefined ? [] : [input[index], ...leading, ...input.slice(index + 1)];
79
+ }
80
+ function showHelp(commands, name) {
81
+ if (name === undefined) {
82
+ process.stdout.write(['Usage: repometry <command> [options]', '', ...Object.entries(commands)
83
+ .map(([id, command]) => ` ${id.padEnd(15)} ${command.description}`), ' help Show help for any command.', ''].join('\n'));
84
+ return;
85
+ }
86
+ const command = Object.hasOwn(commands, name) ? commands[name] : undefined;
87
+ if (!command)
88
+ throw new Error(`Unknown command: ${name}.${suggest(name, Object.keys(commands))}`);
89
+ const usage = `Usage: repometry ${name}${command.parameters ? ' ' + command.parameters : ''}`;
90
+ const help = Object.entries({ ...globals, ...command.options }).map(([key, setting]) => {
91
+ const flags = (setting.short ? `-${setting.short}, ` : '') + `--${key}` + (setting.value ? ' ' + setting.value : '');
92
+ return ` ${flags.padEnd(28)} ${setting.description}`;
93
+ });
94
+ process.stdout.write([usage, '', command.description, '', ...help, ''].join('\n'));
95
+ }
96
+ function suggest(name, candidates) {
97
+ const ranked = candidates.map(value => ({ value, score: distance(name, value) })).sort((a, b) => a.score - b.score);
98
+ const nearest = ranked[0];
99
+ return nearest && nearest.score <= Math.max(2, Math.floor(name.length / 3)) ? ` Did you mean ${nearest.value}?` : '';
100
+ }
101
+ function distance(a, b) {
102
+ let row = Array.from({ length: b.length + 1 }, (_, index) => index);
103
+ for (let i = 0; i < a.length; i++) {
104
+ const next = [i + 1];
105
+ for (let j = 0; j < b.length; j++)
106
+ next.push(Math.min(row[j + 1] + 1, next[j] + 1, row[j] + Number(a[i] !== b[j])));
107
+ row = next;
108
+ }
109
+ return row[b.length];
110
+ }