@nordhavnhq/runner 0.0.0-stage → 0.96.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 (338) hide show
  1. package/bin/cliclick +0 -0
  2. package/dist/brand.d.ts +5 -0
  3. package/dist/brand.js +18 -0
  4. package/dist/cli/agent.d.ts +9 -0
  5. package/dist/cli/agent.js +39 -0
  6. package/dist/cli/folder.d.ts +2 -0
  7. package/dist/cli/folder.js +103 -0
  8. package/dist/cli/init.d.ts +2 -0
  9. package/dist/cli/init.js +67 -0
  10. package/dist/cli/lifecycle.d.ts +3 -0
  11. package/dist/cli/lifecycle.js +149 -0
  12. package/dist/cli/link.d.ts +20 -0
  13. package/dist/cli/link.js +312 -0
  14. package/dist/cli/logs.d.ts +2 -0
  15. package/dist/cli/logs.js +144 -0
  16. package/dist/cli/prompts.d.ts +7 -0
  17. package/dist/cli/prompts.js +13 -0
  18. package/dist/cli/ps.d.ts +2 -0
  19. package/dist/cli/ps.js +80 -0
  20. package/dist/cli/relay.d.ts +4 -0
  21. package/dist/cli/relay.js +29 -0
  22. package/dist/cli/update.d.ts +6 -0
  23. package/dist/cli/update.js +131 -0
  24. package/dist/config.d.ts +166 -0
  25. package/dist/config.js +383 -0
  26. package/dist/index.d.ts +2 -0
  27. package/dist/index.js +135 -0
  28. package/dist/legacy-env.d.ts +4 -0
  29. package/dist/legacy-env.js +32 -0
  30. package/dist/paths.d.ts +37 -0
  31. package/dist/paths.js +92 -0
  32. package/dist/runtime/daemon.d.ts +57 -0
  33. package/dist/runtime/daemon.js +159 -0
  34. package/dist/runtime/dev-start.d.ts +31 -0
  35. package/dist/runtime/dev-start.js +110 -0
  36. package/dist/runtime/file-claims.d.ts +58 -0
  37. package/dist/runtime/file-claims.js +174 -0
  38. package/dist/runtime/fs-browse.d.ts +18 -0
  39. package/dist/runtime/fs-browse.js +104 -0
  40. package/dist/runtime/fs-checkout.d.ts +154 -0
  41. package/dist/runtime/fs-checkout.js +1049 -0
  42. package/dist/runtime/fs-git-index.d.ts +22 -0
  43. package/dist/runtime/fs-git-index.js +133 -0
  44. package/dist/runtime/fs-git.d.ts +16 -0
  45. package/dist/runtime/fs-git.js +424 -0
  46. package/dist/runtime/git-relay.d.ts +46 -0
  47. package/dist/runtime/git-relay.js +259 -0
  48. package/dist/runtime/git-unpushed.d.ts +36 -0
  49. package/dist/runtime/git-unpushed.js +93 -0
  50. package/dist/runtime/node-version.d.ts +12 -0
  51. package/dist/runtime/node-version.js +39 -0
  52. package/dist/runtime/preview-tunnel.d.ts +16 -0
  53. package/dist/runtime/preview-tunnel.js +135 -0
  54. package/dist/runtime/processes.d.ts +61 -0
  55. package/dist/runtime/processes.js +408 -0
  56. package/dist/runtime/project-node-download.d.ts +17 -0
  57. package/dist/runtime/project-node-download.js +137 -0
  58. package/dist/runtime/project-node.d.ts +65 -0
  59. package/dist/runtime/project-node.js +223 -0
  60. package/dist/runtime/reap-scratch.d.ts +22 -0
  61. package/dist/runtime/reap-scratch.js +112 -0
  62. package/dist/runtime/spill-tool-output.d.ts +14 -0
  63. package/dist/runtime/spill-tool-output.js +84 -0
  64. package/dist/runtime/up.d.ts +6 -0
  65. package/dist/runtime/up.js +1324 -0
  66. package/dist/tools/_coerce.d.ts +2 -0
  67. package/dist/tools/_coerce.js +26 -0
  68. package/dist/tools/_commit-scope.d.ts +14 -0
  69. package/dist/tools/_commit-scope.js +70 -0
  70. package/dist/tools/_jail.d.ts +68 -0
  71. package/dist/tools/_jail.js +209 -0
  72. package/dist/tools/_output.d.ts +24 -0
  73. package/dist/tools/_output.js +48 -0
  74. package/dist/tools/_ripgrep.d.ts +46 -0
  75. package/dist/tools/_ripgrep.js +148 -0
  76. package/dist/tools/_run-worktree.d.ts +10 -0
  77. package/dist/tools/_run-worktree.js +27 -0
  78. package/dist/tools/_shell-words.d.ts +15 -0
  79. package/dist/tools/_shell-words.js +43 -0
  80. package/dist/tools/_sonar/astro.d.ts +6 -0
  81. package/dist/tools/_sonar/astro.js +45 -0
  82. package/dist/tools/_sonar/blade.d.ts +3 -0
  83. package/dist/tools/_sonar/blade.js +53 -0
  84. package/dist/tools/_sonar/build.d.ts +44 -0
  85. package/dist/tools/_sonar/build.js +147 -0
  86. package/dist/tools/_sonar/changed.d.ts +21 -0
  87. package/dist/tools/_sonar/changed.js +230 -0
  88. package/dist/tools/_sonar/diagnose/delta.d.ts +27 -0
  89. package/dist/tools/_sonar/diagnose/delta.js +64 -0
  90. package/dist/tools/_sonar/diagnose/detect.d.ts +39 -0
  91. package/dist/tools/_sonar/diagnose/detect.js +117 -0
  92. package/dist/tools/_sonar/diagnose/index.d.ts +13 -0
  93. package/dist/tools/_sonar/diagnose/index.js +217 -0
  94. package/dist/tools/_sonar/diagnose/lint-worker.d.ts +1 -0
  95. package/dist/tools/_sonar/diagnose/lint-worker.js +48 -0
  96. package/dist/tools/_sonar/diagnose/pool.d.ts +22 -0
  97. package/dist/tools/_sonar/diagnose/pool.js +149 -0
  98. package/dist/tools/_sonar/diagnose/rules.d.ts +23 -0
  99. package/dist/tools/_sonar/diagnose/rules.js +131 -0
  100. package/dist/tools/_sonar/diagnose/types-worker.d.ts +1 -0
  101. package/dist/tools/_sonar/diagnose/types-worker.js +183 -0
  102. package/dist/tools/_sonar/files.d.ts +14 -0
  103. package/dist/tools/_sonar/files.js +121 -0
  104. package/dist/tools/_sonar/graph.d.ts +34 -0
  105. package/dist/tools/_sonar/graph.js +164 -0
  106. package/dist/tools/_sonar/hints.d.ts +116 -0
  107. package/dist/tools/_sonar/hints.js +545 -0
  108. package/dist/tools/_sonar/imports.d.ts +38 -0
  109. package/dist/tools/_sonar/imports.js +275 -0
  110. package/dist/tools/_sonar/index.d.ts +79 -0
  111. package/dist/tools/_sonar/index.js +462 -0
  112. package/dist/tools/_sonar/keys.d.ts +5 -0
  113. package/dist/tools/_sonar/keys.js +248 -0
  114. package/dist/tools/_sonar/laravel-routes.d.ts +15 -0
  115. package/dist/tools/_sonar/laravel-routes.js +263 -0
  116. package/dist/tools/_sonar/laravel.d.ts +64 -0
  117. package/dist/tools/_sonar/laravel.js +326 -0
  118. package/dist/tools/_sonar/location.d.ts +33 -0
  119. package/dist/tools/_sonar/location.js +137 -0
  120. package/dist/tools/_sonar/map.d.ts +43 -0
  121. package/dist/tools/_sonar/map.js +212 -0
  122. package/dist/tools/_sonar/parse.d.ts +3 -0
  123. package/dist/tools/_sonar/parse.js +76 -0
  124. package/dist/tools/_sonar/prewarm.d.ts +9 -0
  125. package/dist/tools/_sonar/prewarm.js +96 -0
  126. package/dist/tools/_sonar/prisma.d.ts +9 -0
  127. package/dist/tools/_sonar/prisma.js +51 -0
  128. package/dist/tools/_sonar/refs.d.ts +7 -0
  129. package/dist/tools/_sonar/refs.js +273 -0
  130. package/dist/tools/_sonar/render.d.ts +66 -0
  131. package/dist/tools/_sonar/render.js +498 -0
  132. package/dist/tools/_sonar/resolve.d.ts +63 -0
  133. package/dist/tools/_sonar/resolve.js +402 -0
  134. package/dist/tools/_sonar/roots.d.ts +4 -0
  135. package/dist/tools/_sonar/roots.js +42 -0
  136. package/dist/tools/_sonar/routes.d.ts +5 -0
  137. package/dist/tools/_sonar/routes.js +247 -0
  138. package/dist/tools/_sonar/serve.d.ts +12 -0
  139. package/dist/tools/_sonar/serve.js +104 -0
  140. package/dist/tools/_sonar/suggest.d.ts +23 -0
  141. package/dist/tools/_sonar/suggest.js +114 -0
  142. package/dist/tools/_sonar/tests.d.ts +21 -0
  143. package/dist/tools/_sonar/tests.js +134 -0
  144. package/dist/tools/_sonar/tsconfig.d.ts +34 -0
  145. package/dist/tools/_sonar/tsconfig.js +188 -0
  146. package/dist/tools/_sonar/types.d.ts +81 -0
  147. package/dist/tools/_sonar/types.js +6 -0
  148. package/dist/tools/_symbols.d.ts +27 -0
  149. package/dist/tools/_symbols.js +461 -0
  150. package/dist/tools/_test-report.d.ts +47 -0
  151. package/dist/tools/_test-report.js +203 -0
  152. package/dist/tools/_touched.d.ts +44 -0
  153. package/dist/tools/_touched.js +195 -0
  154. package/dist/tools/_upload.d.ts +26 -0
  155. package/dist/tools/_upload.js +132 -0
  156. package/dist/tools/_worktree-setup.d.ts +29 -0
  157. package/dist/tools/_worktree-setup.js +204 -0
  158. package/dist/tools/browser.d.ts +2 -0
  159. package/dist/tools/browser.js +8 -0
  160. package/dist/tools/commit-guard.d.ts +44 -0
  161. package/dist/tools/commit-guard.js +165 -0
  162. package/dist/tools/computer.d.ts +13 -0
  163. package/dist/tools/computer.js +952 -0
  164. package/dist/tools/console.d.ts +44 -0
  165. package/dist/tools/console.js +739 -0
  166. package/dist/tools/database.d.ts +28 -0
  167. package/dist/tools/database.js +152 -0
  168. package/dist/tools/filesystem.d.ts +36 -0
  169. package/dist/tools/filesystem.js +506 -0
  170. package/dist/tools/git-tag.d.ts +10 -0
  171. package/dist/tools/git-tag.js +164 -0
  172. package/dist/tools/git.d.ts +52 -0
  173. package/dist/tools/git.js +1272 -0
  174. package/dist/tools/http.d.ts +12 -0
  175. package/dist/tools/http.js +119 -0
  176. package/dist/tools/image.d.ts +8 -0
  177. package/dist/tools/image.js +551 -0
  178. package/dist/tools/index.d.ts +13 -0
  179. package/dist/tools/index.js +58 -0
  180. package/dist/tools/outline.d.ts +20 -0
  181. package/dist/tools/outline.js +98 -0
  182. package/dist/tools/search.d.ts +17 -0
  183. package/dist/tools/search.js +391 -0
  184. package/dist/tools/sonar.d.ts +17 -0
  185. package/dist/tools/sonar.js +231 -0
  186. package/dist/tools/testing.d.ts +36 -0
  187. package/dist/tools/testing.js +273 -0
  188. package/dist/tools/upload.d.ts +8 -0
  189. package/dist/tools/upload.js +106 -0
  190. package/dist/tools/webcam.d.ts +28 -0
  191. package/dist/tools/webcam.js +967 -0
  192. package/dist/update/install-kind.d.ts +35 -0
  193. package/dist/update/install-kind.js +109 -0
  194. package/dist/update/install.d.ts +32 -0
  195. package/dist/update/install.js +187 -0
  196. package/dist/update/manifest.d.ts +18 -0
  197. package/dist/update/manifest.js +73 -0
  198. package/dist/update/peers.d.ts +18 -0
  199. package/dist/update/peers.js +43 -0
  200. package/dist/update/policy.d.ts +20 -0
  201. package/dist/update/policy.js +49 -0
  202. package/dist/update/supervisor.d.ts +25 -0
  203. package/dist/update/supervisor.js +83 -0
  204. package/dist/update/updater.d.ts +44 -0
  205. package/dist/update/updater.js +116 -0
  206. package/dist/utils/format.d.ts +50 -0
  207. package/dist/utils/format.js +190 -0
  208. package/dist/version.d.ts +17 -0
  209. package/dist/version.js +63 -0
  210. package/dist/version.json +5 -0
  211. package/node_modules/@nordhavnhq/runner-browser/dist/act-tools.d.ts +15 -0
  212. package/node_modules/@nordhavnhq/runner-browser/dist/act-tools.js +541 -0
  213. package/node_modules/@nordhavnhq/runner-browser/dist/cast-hub.d.ts +25 -0
  214. package/node_modules/@nordhavnhq/runner-browser/dist/cast-hub.js +137 -0
  215. package/node_modules/@nordhavnhq/runner-browser/dist/guard.d.ts +21 -0
  216. package/node_modules/@nordhavnhq/runner-browser/dist/guard.js +104 -0
  217. package/node_modules/@nordhavnhq/runner-browser/dist/host-protocol.d.ts +47 -0
  218. package/node_modules/@nordhavnhq/runner-browser/dist/host-protocol.js +41 -0
  219. package/node_modules/@nordhavnhq/runner-browser/dist/host.d.ts +18 -0
  220. package/node_modules/@nordhavnhq/runner-browser/dist/host.js +15 -0
  221. package/node_modules/@nordhavnhq/runner-browser/dist/index.d.ts +13 -0
  222. package/node_modules/@nordhavnhq/runner-browser/dist/index.js +28 -0
  223. package/node_modules/@nordhavnhq/runner-browser/dist/live-input.d.ts +74 -0
  224. package/node_modules/@nordhavnhq/runner-browser/dist/live-input.js +93 -0
  225. package/node_modules/@nordhavnhq/runner-browser/dist/live-open.d.ts +4 -0
  226. package/node_modules/@nordhavnhq/runner-browser/dist/live-open.js +57 -0
  227. package/node_modules/@nordhavnhq/runner-browser/dist/live.d.ts +148 -0
  228. package/node_modules/@nordhavnhq/runner-browser/dist/live.js +179 -0
  229. package/node_modules/@nordhavnhq/runner-browser/dist/local-live.d.ts +31 -0
  230. package/node_modules/@nordhavnhq/runner-browser/dist/local-live.js +262 -0
  231. package/node_modules/@nordhavnhq/runner-browser/dist/marks.d.ts +36 -0
  232. package/node_modules/@nordhavnhq/runner-browser/dist/marks.js +173 -0
  233. package/node_modules/@nordhavnhq/runner-browser/dist/page-events.d.ts +27 -0
  234. package/node_modules/@nordhavnhq/runner-browser/dist/page-events.js +82 -0
  235. package/node_modules/@nordhavnhq/runner-browser/dist/page-tools.d.ts +13 -0
  236. package/node_modules/@nordhavnhq/runner-browser/dist/page-tools.js +526 -0
  237. package/node_modules/@nordhavnhq/runner-browser/dist/params.d.ts +12 -0
  238. package/node_modules/@nordhavnhq/runner-browser/dist/params.js +32 -0
  239. package/node_modules/@nordhavnhq/runner-browser/dist/pick.d.ts +24 -0
  240. package/node_modules/@nordhavnhq/runner-browser/dist/pick.js +76 -0
  241. package/node_modules/@nordhavnhq/runner-browser/dist/session.d.ts +225 -0
  242. package/node_modules/@nordhavnhq/runner-browser/dist/session.js +507 -0
  243. package/node_modules/@nordhavnhq/runner-browser/dist/shots.d.ts +11 -0
  244. package/node_modules/@nordhavnhq/runner-browser/dist/shots.js +103 -0
  245. package/node_modules/@nordhavnhq/runner-browser/dist/show.d.ts +10 -0
  246. package/node_modules/@nordhavnhq/runner-browser/dist/show.js +190 -0
  247. package/node_modules/@nordhavnhq/runner-browser/dist/target.d.ts +37 -0
  248. package/node_modules/@nordhavnhq/runner-browser/dist/target.js +82 -0
  249. package/node_modules/@nordhavnhq/runner-browser/dist/tour.d.ts +19 -0
  250. package/node_modules/@nordhavnhq/runner-browser/dist/tour.js +178 -0
  251. package/node_modules/@nordhavnhq/runner-browser/package.json +18 -0
  252. package/node_modules/@nordhavnhq/runner-runtime/dist/config.d.ts +96 -0
  253. package/node_modules/@nordhavnhq/runner-runtime/dist/config.js +25 -0
  254. package/node_modules/@nordhavnhq/runner-runtime/dist/connection.d.ts +276 -0
  255. package/node_modules/@nordhavnhq/runner-runtime/dist/connection.js +507 -0
  256. package/node_modules/@nordhavnhq/runner-runtime/dist/constants.d.ts +48 -0
  257. package/node_modules/@nordhavnhq/runner-runtime/dist/constants.js +95 -0
  258. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/batch.d.ts +94 -0
  259. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/batch.js +219 -0
  260. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/calls.d.ts +136 -0
  261. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/calls.js +214 -0
  262. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/fs.d.ts +735 -0
  263. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/fs.js +40 -0
  264. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/loop.d.ts +362 -0
  265. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/loop.js +703 -0
  266. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/own-files.d.ts +105 -0
  267. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/own-files.js +202 -0
  268. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/phases.d.ts +204 -0
  269. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/phases.js +497 -0
  270. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/pins.d.ts +45 -0
  271. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/pins.js +176 -0
  272. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/processes.d.ts +74 -0
  273. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/processes.js +72 -0
  274. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/release-tag.d.ts +59 -0
  275. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/release-tag.js +117 -0
  276. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/replay.d.ts +62 -0
  277. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/replay.js +84 -0
  278. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/tool-names.d.ts +27 -0
  279. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/tool-names.js +80 -0
  280. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/version.d.ts +22 -0
  281. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/version.js +22 -0
  282. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/wire.d.ts +595 -0
  283. package/node_modules/@nordhavnhq/runner-runtime/dist/contract/wire.js +85 -0
  284. package/node_modules/@nordhavnhq/runner-runtime/dist/index.d.ts +43 -0
  285. package/node_modules/@nordhavnhq/runner-runtime/dist/index.js +50 -0
  286. package/node_modules/@nordhavnhq/runner-runtime/dist/inference.d.ts +135 -0
  287. package/node_modules/@nordhavnhq/runner-runtime/dist/inference.js +945 -0
  288. package/node_modules/@nordhavnhq/runner-runtime/dist/mcp.d.ts +67 -0
  289. package/node_modules/@nordhavnhq/runner-runtime/dist/mcp.js +47 -0
  290. package/node_modules/@nordhavnhq/runner-runtime/dist/platform.d.ts +21 -0
  291. package/node_modules/@nordhavnhq/runner-runtime/dist/platform.js +25 -0
  292. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/auto-load.d.ts +39 -0
  293. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/auto-load.js +67 -0
  294. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/background-commands.d.ts +61 -0
  295. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/background-commands.js +58 -0
  296. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/chat-run-ends.d.ts +23 -0
  297. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/chat-run-ends.js +42 -0
  298. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/duration.d.ts +6 -0
  299. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/duration.js +12 -0
  300. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/events.d.ts +150 -0
  301. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/events.js +36 -0
  302. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/extract-json.d.ts +14 -0
  303. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/extract-json.js +49 -0
  304. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-chat.d.ts +109 -0
  305. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-chat.js +894 -0
  306. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-task.d.ts +73 -0
  307. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/handle-task.js +765 -0
  308. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/loop.d.ts +246 -0
  309. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/loop.js +621 -0
  310. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/messages.d.ts +88 -0
  311. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/messages.js +188 -0
  312. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/pending-steers.d.ts +15 -0
  313. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/pending-steers.js +10 -0
  314. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/phased-loop.d.ts +16 -0
  315. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/phased-loop.js +97 -0
  316. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/project-instructions.d.ts +22 -0
  317. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/project-instructions.js +47 -0
  318. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/run-tools.d.ts +26 -0
  319. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/run-tools.js +48 -0
  320. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/scratch-prompt.d.ts +8 -0
  321. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/scratch-prompt.js +19 -0
  322. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/side-question.d.ts +76 -0
  323. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/side-question.js +155 -0
  324. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/task-validation.d.ts +43 -0
  325. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/task-validation.js +37 -0
  326. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/unload-toolset.d.ts +49 -0
  327. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/unload-toolset.js +104 -0
  328. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/write-scope.d.ts +16 -0
  329. package/node_modules/@nordhavnhq/runner-runtime/dist/runtime/write-scope.js +6 -0
  330. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/delegate.d.ts +86 -0
  331. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/delegate.js +141 -0
  332. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/index.d.ts +179 -0
  333. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/index.js +35 -0
  334. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/mcp.d.ts +21 -0
  335. package/node_modules/@nordhavnhq/runner-runtime/dist/tools/mcp.js +179 -0
  336. package/node_modules/@nordhavnhq/runner-runtime/package.json +18 -0
  337. package/package.json +33 -4
  338. package/README.md +0 -3
@@ -0,0 +1,1049 @@
1
+ import { execFile, spawnSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { appendFileSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { FS_BYTES_CHUNK, FS_LOG_LIMIT, FS_PATCH_FILE_BYTES, FS_PATCH_TOTAL_BYTES, FS_PATHS_LIMIT, FS_REPOS_DEPTH, FS_REPOS_LIMIT, FS_UPLOAD_MAX_BYTES, } from '@nordhavnhq/runner-runtime';
6
+ import { isInsideRoot } from '../tools/_jail.js';
7
+ import { nearestTag, unpushedAnnotatedTags, unpushedCommits } from './git-unpushed.js';
8
+ // ─── A project's checkout for the code app ─────────────────────────
9
+ //
10
+ // The studio's code app shows the files of a project as they are on this
11
+ // machine: the tree one folder at a time (`fs:list`), every file's path for
12
+ // the quick open (`fs:paths`), one file at a time (`fs:read`, or a slice of
13
+ // its bytes with `fs:bytes`, for a picture or a video), what git says
14
+ // changed (`fs:status`), saves what somebody edited there (`fs:write`), and
15
+ // makes, renames and deletes files and folders from its tree (`fs:entry`).
16
+ // Its git too: the repositories in it (`fs:repos`, a checkout may hold
17
+ // several), the branches and remotes (`fs:branches`), the commits
18
+ // (`fs:log`), one commit with its diff (`fs:show`), what changed in the
19
+ // working tree (`fs:diff`), who wrote a line (`fs:blame`). What a person
20
+ // does from there (`fs:git`) is fs-git.ts. Git runs asynchronously, so a
21
+ // slow one never stalls the agents on this runner. The studio keeps none of it; every request comes
22
+ // here and goes back raw. `root` is the project's checkout and must lie inside one of the
23
+ // runner's folder roots (`config.projectsRoots`, its access scope); `path` is
24
+ // relative to it and may not leave it. What git ignores is in the tree, marked
25
+ // so, as an editor shows it; the quick open's paths leave it out, bar a
26
+ // sensitive file (`.env`, a key), which a person needs to edit exactly
27
+ // because it is not in the repo. A sensitive file goes out marked
28
+ // `sensitive`: this is a person's window, never an agent's, and the studio
29
+ // hands it only to who may save files in the project.
30
+ /** Past this a file comes back without its content. */
31
+ const MAX_FILE_BYTES = 512 * 1024;
32
+ /** Past this an edited file is not saved: room to grow past what was shown. */
33
+ const MAX_WRITE_BYTES = 2 * MAX_FILE_BYTES;
34
+ /** Changed paths reported at most: past this the tree marks only these. */
35
+ const MAX_CHANGES = 5000;
36
+ /** Bytes looked at to tell a binary file. */
37
+ const SNIFF_BYTES = 8192;
38
+ /** Secrets: shown to a person who may edit the checkout, never to an agent. */
39
+ const SENSITIVE = [
40
+ /^\.env$/,
41
+ /^\.env\.(?!example$|sample$|template$|dist$).+/,
42
+ /\.(pem|key|p12|pfx|crt|cer|der|keystore|jks)$/i,
43
+ /^id_(rsa|dsa|ecdsa|ed25519)(\.pub)?$/,
44
+ /^\.npmrc$/,
45
+ /^\.netrc$/,
46
+ ];
47
+ const isSensitive = (name) => SENSITIVE.some(re => re.test(name));
48
+ /** `root` resolved, once it lies inside the runner's folder roots and exists. Exported for `proc:start`. */
49
+ export function checkout(config, root) {
50
+ const resolved = resolve(root);
51
+ const roots = (config.projectsRoots ?? []).map(r => resolve(r));
52
+ if (!roots.some(r => isInsideRoot(resolved, r)))
53
+ throw new Error('The checkout is outside the runner\'s allowed roots');
54
+ if (!existsSync(resolved) || !statSync(resolved).isDirectory())
55
+ throw new Error('The checkout does not exist on this runner');
56
+ return resolved;
57
+ }
58
+ /** `path` inside the checkout, or an error when it leaves it, by its name or
59
+ * through a symlink (an existing path is compared by its real location). */
60
+ export function inside(base, path) {
61
+ if (isAbsolute(path))
62
+ throw new Error('A path in the checkout is relative');
63
+ const target = resolve(base, path);
64
+ if (!isInsideRoot(target, base))
65
+ throw new Error('The path leaves the checkout');
66
+ if (existsSync(target) && !isInsideRoot(realpathSync(target), realpathSync(base)))
67
+ throw new Error('The path leaves the checkout');
68
+ return target;
69
+ }
70
+ /** What a checkout that is no git repo leaves out of its tree anyway:
71
+ * dependencies, builds and caches, which nobody reads by hand. */
72
+ const NOT_A_REPO_IGNORED = new Set([
73
+ 'node_modules', 'dist', 'build', 'out', 'coverage', 'vendor',
74
+ '.nuxt', '.output', '.next', '.astro', '.svelte-kit', '.turbo', '.cache', '.parcel-cache', '.vercel',
75
+ ]);
76
+ /**
77
+ * The names among `names` (relative to the checkout) that git ignores, or
78
+ * null when the checkout is no git repo (or git is missing).
79
+ */
80
+ function gitIgnored(base, names) {
81
+ if (!names.length)
82
+ return new Set();
83
+ const run = spawnSync('git', ['-C', base, 'check-ignore', '--stdin'], { input: names.join('\n'), encoding: 'utf8', timeout: 5000 });
84
+ // 0: some ignored, 1: none, anything else: not a repo or no git.
85
+ if (run.status === 1)
86
+ return new Set();
87
+ if (run.status !== 0)
88
+ return null;
89
+ return new Set(run.stdout.split('\n').filter(Boolean));
90
+ }
91
+ /** One folder of the checkout: folders first, then files, what git ignores
92
+ * marked `ignored` (outside a repo: dependencies, builds and caches), the way
93
+ * an editor greys it out. */
94
+ export function listCheckout(config, root, path) {
95
+ const base = checkout(config, root);
96
+ const dir = inside(base, path);
97
+ if (!existsSync(dir) || !statSync(dir).isDirectory())
98
+ throw new Error('Folder does not exist');
99
+ const entries = [];
100
+ for (const d of readdirSync(dir, { withFileTypes: true })) {
101
+ if (d.name === '.git' || d.name === '.DS_Store')
102
+ continue;
103
+ const full = join(dir, d.name);
104
+ const rel = relative(base, full).split(sep).join('/');
105
+ if (d.isDirectory())
106
+ entries.push({ name: d.name, path: rel, kind: 'dir' });
107
+ else if (d.isFile()) {
108
+ let size;
109
+ try {
110
+ size = statSync(full).size;
111
+ }
112
+ catch { /* gone or unreadable: listed without a size */ }
113
+ entries.push({ name: d.name, path: rel, kind: 'file', size });
114
+ }
115
+ }
116
+ const ignored = gitIgnored(base, entries.map(e => (e.kind === 'dir' ? `${e.path}/` : e.path)));
117
+ const isIgnored = (e) => ignored
118
+ ? ignored.has(e.kind === 'dir' ? `${e.path}/` : e.path) || ignored.has(e.path)
119
+ : e.kind === 'dir' && NOT_A_REPO_IGNORED.has(e.name);
120
+ return entries
121
+ .map(e => (isIgnored(e) ? { ...e, ignored: true } : e))
122
+ .sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'dir' ? -1 : 1));
123
+ }
124
+ /** NUL-separated output of git in the checkout, or null when it fails. */
125
+ function gitList(base, args) {
126
+ const run = spawnSync('git', ['-C', base, ...args], { encoding: 'utf8', timeout: 10_000, maxBuffer: 64 * 1024 * 1024 });
127
+ return run.status === 0 ? run.stdout.split('\0').filter(Boolean) : null;
128
+ }
129
+ /**
130
+ * Every file of the checkout by its path, as the tree has them: in a repo
131
+ * what git tracks and what it does not ignore (paths relative to the
132
+ * checkout, which may be a folder inside the repo), plus an ignored secret
133
+ * in a folder git keeps; outside one a walk that leaves out dependencies,
134
+ * builds and caches. At most `FS_PATHS_LIMIT`, sorted.
135
+ */
136
+ export function checkoutPaths(config, root) {
137
+ const base = checkout(config, root);
138
+ const listed = gitList(base, ['ls-files', '-z', '--cached', '--others', '--exclude-standard']);
139
+ let paths;
140
+ if (listed) {
141
+ const deleted = new Set(gitList(base, ['ls-files', '-z', '--deleted']) ?? []);
142
+ // An ignored folder comes back as one `dir/`: only files in kept folders.
143
+ const secrets = (gitList(base, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory']) ?? [])
144
+ .filter(p => !p.endsWith('/') && isSensitive(basename(p)));
145
+ paths = [...new Set([...listed.filter(p => !deleted.has(p)), ...secrets])];
146
+ }
147
+ else {
148
+ paths = [];
149
+ const walk = (dir) => {
150
+ for (const d of readdirSync(dir, { withFileTypes: true })) {
151
+ if (paths.length > FS_PATHS_LIMIT)
152
+ return;
153
+ if (d.name === '.git' || d.name === '.DS_Store')
154
+ continue;
155
+ const full = join(dir, d.name);
156
+ if (d.isDirectory() && !NOT_A_REPO_IGNORED.has(d.name))
157
+ walk(full);
158
+ else if (d.isFile())
159
+ paths.push(relative(base, full).split(sep).join('/'));
160
+ }
161
+ };
162
+ walk(base);
163
+ }
164
+ paths.sort();
165
+ return { paths: paths.slice(0, FS_PATHS_LIMIT), truncated: paths.length > FS_PATHS_LIMIT };
166
+ }
167
+ /** One file of the checkout as text, unless it is binary or too large; a
168
+ * sensitive one marked so. */
169
+ export function readCheckoutFile(config, root, path) {
170
+ const base = checkout(config, root);
171
+ const file = inside(base, path);
172
+ if (!existsSync(file) || !statSync(file).isFile())
173
+ throw new Error('File does not exist');
174
+ const rel = relative(base, file).split(sep).join('/');
175
+ const size = statSync(file).size;
176
+ const sensitive = isSensitive(basename(file)) ? { sensitive: true } : {};
177
+ const fd = openSync(file, 'r');
178
+ try {
179
+ const head = Buffer.alloc(Math.min(size, SNIFF_BYTES));
180
+ readSync(fd, head, 0, head.length, 0);
181
+ if (head.includes(0))
182
+ return { path: rel, size, content: null, binary: true, ...sensitive };
183
+ if (size > MAX_FILE_BYTES)
184
+ return { path: rel, size, content: null, truncated: true, ...sensitive };
185
+ const all = Buffer.alloc(size);
186
+ readSync(fd, all, 0, size, 0);
187
+ const hash = hashOf(all);
188
+ try {
189
+ return { path: rel, size, content: new TextDecoder('utf-8', { fatal: true }).decode(all), hash, ...sensitive };
190
+ }
191
+ catch {
192
+ // Saving this back as UTF-8 would rewrite every byte that is not.
193
+ return { path: rel, size, content: all.toString('utf8'), hash, readOnly: 'Not UTF-8 text, so it is not saved from here.', ...sensitive };
194
+ }
195
+ }
196
+ finally {
197
+ closeSync(fd);
198
+ }
199
+ }
200
+ /** A slice of one file of the checkout as bytes, read off disk on its own
201
+ * (a video is never read whole); a sensitive one marked so. */
202
+ export function readCheckoutBytes(config, root, path, offset, length) {
203
+ const base = checkout(config, root);
204
+ const file = inside(base, path);
205
+ if (!existsSync(file) || !statSync(file).isFile())
206
+ throw new Error('File does not exist');
207
+ const rel = relative(base, file).split(sep).join('/');
208
+ const size = statSync(file).size;
209
+ const sensitive = isSensitive(basename(file)) ? { sensitive: true } : {};
210
+ const start = Math.max(0, Math.min(offset, size));
211
+ const bytes = Buffer.alloc(Math.max(0, Math.min(length, FS_BYTES_CHUNK, size - start)));
212
+ const fd = openSync(file, 'r');
213
+ try {
214
+ const read = bytes.length ? readSync(fd, bytes, 0, bytes.length, start) : 0;
215
+ return { path: rel, size, offset: start, data: bytes.subarray(0, read).toString('base64'), ...sensitive };
216
+ }
217
+ finally {
218
+ closeSync(fd);
219
+ }
220
+ }
221
+ const hashOf = (bytes) => createHash('sha256').update(bytes).digest('hex');
222
+ /** The file on disk is not the version the editor started from. */
223
+ export class CheckoutConflictError extends Error {
224
+ constructor() {
225
+ super('The file changed on the runner since it was opened');
226
+ }
227
+ }
228
+ /**
229
+ * Save one existing file of the checkout as UTF-8, unless it is inside
230
+ * `.git` or too large (a sensitive one too: a person edits its secrets). With `baseHash`, only while the file on disk is
231
+ * still that version (else `CheckoutConflictError`): an agent may have written
232
+ * it meanwhile, and its work must not vanish under somebody's save. Written
233
+ * in place, so the file keeps its mode. Returns the file as saved.
234
+ */
235
+ export function writeCheckoutFile(config, root, path, content, baseHash) {
236
+ const base = checkout(config, root);
237
+ const file = inside(base, path);
238
+ if (!existsSync(file) || !statSync(file).isFile())
239
+ throw new Error('File does not exist');
240
+ const rel = relative(base, file).split(sep).join('/');
241
+ if (rel.split('/').includes('.git'))
242
+ throw new Error('Git\'s own files are not saved from here.');
243
+ const bytes = Buffer.from(content, 'utf8');
244
+ if (bytes.length > MAX_WRITE_BYTES)
245
+ throw new Error('Too large to save from here.');
246
+ if (baseHash) {
247
+ const current = readCheckoutFile(config, root, path);
248
+ if (current.hash !== baseHash)
249
+ throw new CheckoutConflictError();
250
+ }
251
+ writeFileSync(file, bytes);
252
+ return readCheckoutFile(config, root, path);
253
+ }
254
+ /** `path` relative to the checkout, with forward slashes. */
255
+ const relOf = (base, path) => relative(base, path).split(sep).join('/');
256
+ /** A path of the checkout that `fs:entry` may touch: inside it (an existing
257
+ * one by its real location), not the checkout itself and nothing in `.git`. */
258
+ function entryTarget(base, path) {
259
+ if (path.includes('\0'))
260
+ throw new Error('A path has no NUL in it');
261
+ const target = inside(base, path);
262
+ const rel = relOf(base, target);
263
+ if (!rel)
264
+ throw new Error('Not the checkout itself');
265
+ if (rel.split('/').includes('.git'))
266
+ throw new Error('Git\'s own files are not changed from here.');
267
+ return target;
268
+ }
269
+ /** A path `fs:entry` makes: free, and its nearest folder that exists is in
270
+ * the checkout by its real location too (a symlinked folder may not lead out). */
271
+ function newTarget(base, path, same) {
272
+ const target = entryTarget(base, path);
273
+ if (existsSync(target) && !(same && sameEntry(same, target)))
274
+ throw new Error(`${relOf(base, target)} already exists`);
275
+ let parent = dirname(target);
276
+ while (!existsSync(parent))
277
+ parent = dirname(parent);
278
+ if (!isInsideRoot(realpathSync(parent), realpathSync(base)))
279
+ throw new Error('The path leaves the checkout');
280
+ if (!statSync(parent).isDirectory())
281
+ throw new Error(`${relOf(base, parent)} is a file, not a folder`);
282
+ return target;
283
+ }
284
+ /** Two paths that are one entry on disk (a rename of only a letter's case,
285
+ * on a disk that does not tell them apart). */
286
+ function sameEntry(a, b) {
287
+ const x = lstatSync(a);
288
+ const y = lstatSync(b);
289
+ return x.ino === y.ino && x.dev === y.dev;
290
+ }
291
+ /**
292
+ * Make a file (empty) or a folder in the checkout, rename one, or delete
293
+ * several, from the code app's tree. Every path is checked before anything
294
+ * changes: inside the checkout, not `.git`, a new one free (nothing is
295
+ * overwritten), its missing folders made with it. A delete is for good, a
296
+ * folder with all it holds. An upload comes in pieces: the first makes the
297
+ * file (never over one), each next one appends only when the file is exactly
298
+ * as long as its `offset` says, so a piece twice or out of order is refused.
299
+ * Returns the new path of a create, a rename or an upload.
300
+ */
301
+ export function checkoutEntry(config, root, action) {
302
+ const base = checkout(config, root);
303
+ switch (action.kind) {
304
+ case 'create-file': {
305
+ const file = newTarget(base, action.path);
306
+ mkdirSync(dirname(file), { recursive: true });
307
+ writeFileSync(file, '', { flag: 'wx' });
308
+ return { created: relOf(base, file) };
309
+ }
310
+ case 'create-folder': {
311
+ const dir = newTarget(base, action.path);
312
+ mkdirSync(dir, { recursive: true });
313
+ return { created: relOf(base, dir) };
314
+ }
315
+ case 'rename': {
316
+ const from = entryTarget(base, action.path);
317
+ if (!existsSync(from))
318
+ throw new Error(`${action.path} does not exist`);
319
+ const to = newTarget(base, action.to, from);
320
+ if (isInsideRoot(to, from) && to !== from)
321
+ throw new Error('A folder does not go inside itself');
322
+ mkdirSync(dirname(to), { recursive: true });
323
+ renameSync(from, to);
324
+ return { created: relOf(base, to) };
325
+ }
326
+ case 'delete': {
327
+ const targets = action.paths.map((path) => {
328
+ const target = entryTarget(base, path);
329
+ if (!existsSync(target))
330
+ throw new Error(`${path} does not exist`);
331
+ return target;
332
+ });
333
+ // A folder and something in it: the folder takes it along.
334
+ const outer = targets.filter(t => !targets.some(o => o !== t && isInsideRoot(t, o)));
335
+ for (const target of outer)
336
+ rmSync(target, { recursive: true });
337
+ return {};
338
+ }
339
+ case 'upload':
340
+ return { created: uploadPiece(base, action.path, action.offset, action.data) };
341
+ }
342
+ }
343
+ /** One piece of an upload: the first makes the file (never over one), each
344
+ * next one appends only when the file is exactly `offset` bytes long. */
345
+ function uploadPiece(base, path, offset, data) {
346
+ const bytes = Buffer.from(data, 'base64');
347
+ if (bytes.length > FS_BYTES_CHUNK)
348
+ throw new Error('An upload piece is too large');
349
+ if (!Number.isSafeInteger(offset) || offset < 0)
350
+ throw new Error('An upload offset is a whole number');
351
+ if (offset + bytes.length > FS_UPLOAD_MAX_BYTES)
352
+ throw new Error('Too large to upload');
353
+ if (offset === 0) {
354
+ const file = newTarget(base, path);
355
+ mkdirSync(dirname(file), { recursive: true });
356
+ writeFileSync(file, bytes, { flag: 'wx' });
357
+ return relOf(base, file);
358
+ }
359
+ const file = entryTarget(base, path);
360
+ const stat = existsSync(file) ? lstatSync(file) : null;
361
+ if (!stat?.isFile())
362
+ throw new Error(`${path} is not an upload in progress`);
363
+ if (stat.size !== offset)
364
+ throw new Error(`${path} is ${stat.size} bytes, not ${offset}`);
365
+ appendFileSync(file, bytes);
366
+ return relOf(base, file);
367
+ }
368
+ /** What git's two status letters (index, worktree) mean in an editor's tree. */
369
+ function gitState(xy) {
370
+ if (xy === '??')
371
+ return 'untracked';
372
+ if (xy.includes('U') || xy === 'AA' || xy === 'DD')
373
+ return 'conflicted';
374
+ if (xy.includes('D'))
375
+ return 'deleted';
376
+ if (xy.includes('R'))
377
+ return 'renamed';
378
+ if (xy[0] === 'A')
379
+ return 'added';
380
+ return 'modified';
381
+ }
382
+ /**
383
+ * What git says changed in the checkout, staged or not, untracked files one
384
+ * by one: paths relative to the checkout, which may be a folder inside the
385
+ * repo (git answers relative to the repo's root, so its prefix is cut off and
386
+ * what lies outside the checkout is left out). Throws when it is no repo.
387
+ */
388
+ export function checkoutGitStatus(config, root) {
389
+ const base = checkout(config, root);
390
+ const prefix = spawnSync('git', ['-C', base, 'rev-parse', '--show-prefix'], { encoding: 'utf8', timeout: 5000 });
391
+ if (prefix.status !== 0)
392
+ throw new Error('The checkout is no git repository');
393
+ const inRepo = prefix.stdout.trim();
394
+ const run = spawnSync('git', ['-C', base, 'status', '--porcelain=v1', '-z', '--untracked-files=all', '--', '.'], { encoding: 'utf8', timeout: 10_000, maxBuffer: 16 * 1024 * 1024 });
395
+ if (run.status !== 0)
396
+ throw new Error(run.stderr.trim() || 'git status failed');
397
+ const changes = [];
398
+ const parts = run.stdout.split('\0');
399
+ for (let i = 0; i < parts.length && changes.length < MAX_CHANGES; i++) {
400
+ const entry = parts[i];
401
+ if (entry.length < 4)
402
+ continue;
403
+ const xy = entry.slice(0, 2);
404
+ const path = entry.slice(3);
405
+ // A rename or copy is followed by the path it came from.
406
+ if (xy[0] === 'R' || xy[0] === 'C')
407
+ i++;
408
+ if (!path.startsWith(inRepo))
409
+ continue;
410
+ changes.push({ path: path.slice(inRepo.length).replace(/\/$/, ''), state: gitState(xy) });
411
+ }
412
+ return changes;
413
+ }
414
+ /** git in the checkout, without blocking the runner. It never prompts: a
415
+ * remote that wants a password nobody stored fails instead of hanging. */
416
+ export function git(base, args, opts = {}) {
417
+ return new Promise((done) => {
418
+ execFile('git', ['-C', base, '-c', 'core.quotePath=false', ...args], {
419
+ encoding: 'utf8',
420
+ timeout: opts.timeout ?? 15_000,
421
+ maxBuffer: 64 * 1024 * 1024,
422
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', ...opts.env },
423
+ }, (err, stdout, stderr) => done({ ok: !err, stdout: String(stdout), stderr: String(stderr) }));
424
+ });
425
+ }
426
+ /** What git said, without a user or password of a url in it: an error of a
427
+ * push names the remote it could not reach, token and all. */
428
+ const scrub = (text) => text.replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@]+@/gi, '$1').trim().slice(0, 4000);
429
+ /** What git said when it failed, for the person who asked. */
430
+ export const failure = (run, fallback) => scrub(run.stderr || run.stdout) || fallback;
431
+ export const said = (run) => scrub(`${run.stdout}${run.stderr}`);
432
+ /** The checkout, failing like `checkoutGitStatus` when it is no repo. */
433
+ export async function repo(config, root) {
434
+ const base = checkout(config, root);
435
+ if (!(await git(base, ['rev-parse', '--git-dir'])).ok)
436
+ throw new Error('The checkout is no git repository');
437
+ return base;
438
+ }
439
+ /** Folders `fs:repos` never looks into, besides hidden ones: dependencies,
440
+ * builds and caches, and the worktrees of a repository. */
441
+ const REPO_SKIP = new Set([...NOT_A_REPO_IGNORED, '.worktrees']);
442
+ /** Folders `fs:repos` reads at most, so a checkout that holds a whole disk
443
+ * still answers. */
444
+ const REPO_SCAN_FOLDERS = 5000;
445
+ /**
446
+ * The folders below `base` that hold a `.git` (a folder, or a file for a
447
+ * submodule or a worktree), relative to it with `/`, sorted: level by level,
448
+ * at most `depth` deep, into a repository too (one can hold another). Hidden
449
+ * folders and `REPO_SKIP` are passed over, a symlink is never followed.
450
+ */
451
+ export function findRepos(base, depth = FS_REPOS_DEPTH, limit = FS_REPOS_LIMIT) {
452
+ const found = [];
453
+ let level = [''];
454
+ let read = 0;
455
+ for (let d = 1; d <= depth && level.length; d++) {
456
+ const next = [];
457
+ for (const folder of level) {
458
+ if (++read > REPO_SCAN_FOLDERS)
459
+ return found.sort();
460
+ let entries;
461
+ try {
462
+ entries = readdirSync(join(base, folder), { withFileTypes: true });
463
+ }
464
+ catch {
465
+ continue;
466
+ }
467
+ for (const entry of entries) {
468
+ // A Dirent of a symlink is no directory: it is never followed.
469
+ if (!entry.isDirectory() || entry.name.startsWith('.') || REPO_SKIP.has(entry.name))
470
+ continue;
471
+ const rel = folder ? `${folder}/${entry.name}` : entry.name;
472
+ if (existsSync(join(base, rel, '.git'))) {
473
+ found.push(rel);
474
+ if (found.length >= limit)
475
+ return found.sort();
476
+ }
477
+ next.push(rel);
478
+ }
479
+ }
480
+ level = next;
481
+ }
482
+ return found.sort();
483
+ }
484
+ /** What is checked out in the repository at `dir` (null: a detached head)
485
+ * and how many paths changed in it; null when git does not take it for one. */
486
+ async function repoSummary(dir) {
487
+ const run = await git(dir, ['status', '--porcelain=v2', '--branch', '-z', '--untracked-files=normal', '--', '.'], { timeout: 10_000 });
488
+ if (!run.ok)
489
+ return null;
490
+ let branch = null;
491
+ let changes = 0;
492
+ const parts = run.stdout.split('\0');
493
+ for (let i = 0; i < parts.length; i++) {
494
+ const part = parts[i];
495
+ if (part.startsWith('# branch.head ')) {
496
+ const head = part.slice('# branch.head '.length);
497
+ branch = head === '(detached)' ? null : head;
498
+ }
499
+ else if (/^[12u?] /.test(part)) {
500
+ changes++;
501
+ // A rename or a copy is followed by the path it came from.
502
+ if (part.startsWith('2 '))
503
+ i++;
504
+ }
505
+ }
506
+ return { branch, changes };
507
+ }
508
+ /**
509
+ * The git repositories in the checkout, for the code app's Git view to pick
510
+ * one: the checkout itself first when it is (or lies in) one, then every
511
+ * folder below it that holds one (`findRepos`), each with its branch and
512
+ * how many paths changed in it. None when there is no repository at all.
513
+ */
514
+ export async function checkoutRepos(config, root) {
515
+ const base = checkout(config, root);
516
+ const isRepo = (await git(base, ['rev-parse', '--git-dir'])).ok;
517
+ const paths = [...(isRepo ? [''] : []), ...findRepos(base)];
518
+ const states = await Promise.all(paths.map(path => repoSummary(path ? join(base, path) : base)));
519
+ return paths.flatMap((path, i) => states[i] ? [{ path, ...states[i] }] : []);
520
+ }
521
+ /** `ahead 2, behind 1` (git's track of an upstream) as numbers. */
522
+ function track(text) {
523
+ const ahead = /ahead (\d+)/.exec(text);
524
+ const behind = /behind (\d+)/.exec(text);
525
+ return { ...(ahead ? { ahead: Number(ahead[1]) } : {}), ...(behind ? { behind: Number(behind[1]) } : {}) };
526
+ }
527
+ /** A remote's url without a user or password in it (a token often is one);
528
+ * `git@host:path` keeps its `git`, which is no secret. */
529
+ export function publicRemoteUrl(url) {
530
+ if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(url))
531
+ return url;
532
+ try {
533
+ const parsed = new URL(url);
534
+ if (parsed.protocol === 'ssh:' && !parsed.password)
535
+ return url;
536
+ parsed.username = '';
537
+ parsed.password = '';
538
+ return parsed.toString();
539
+ }
540
+ catch {
541
+ return url.replace(/\/\/[^@/]*@/, '//');
542
+ }
543
+ }
544
+ export async function remotesOf(base) {
545
+ const run = await git(base, ['config', '--get-regexp', '^remote\\..*\\.url$']);
546
+ return run.stdout.split('\n').flatMap((line) => {
547
+ const m = /^remote\.(.+)\.url (.*)$/.exec(line);
548
+ return m ? [{ name: m[1], url: publicRemoteUrl(m[2]) }] : [];
549
+ });
550
+ }
551
+ /**
552
+ * The checkout's branches, the one checked out first, then the other local
553
+ * ones, then the remote ones, each group the most recently committed first:
554
+ * with its last commit and how far it is from the branch it follows. And its
555
+ * remotes. Throws when it is no repo.
556
+ */
557
+ export async function checkoutBranches(config, root) {
558
+ const base = await repo(config, root);
559
+ const remotes = await remotesOf(base);
560
+ const format = ['%(refname)', '%(refname:short)', '%(HEAD)', '%(upstream:short)', '%(upstream:track,nobracket)', '%(objectname)', '%(contents:subject)', '%(committerdate:iso-strict)', '%(symref)'].join('%00');
561
+ const run = await git(base, ['for-each-ref', '--sort=-committerdate', `--format=${format}`, 'refs/heads', 'refs/remotes']);
562
+ if (!run.ok)
563
+ throw new Error(failure(run, 'git for-each-ref failed'));
564
+ const branches = [];
565
+ for (const line of run.stdout.split('\n')) {
566
+ if (!line)
567
+ continue;
568
+ const [ref, name, head, upstream, tracking, sha, subject, date, symref] = line.split('\0');
569
+ // `origin/HEAD` only points at another remote branch.
570
+ if (symref)
571
+ continue;
572
+ const remote = ref.startsWith('refs/remotes/') ? remotes.find(r => ref.startsWith(`refs/remotes/${r.name}/`))?.name ?? ref.split('/')[2] : undefined;
573
+ branches.push({
574
+ ref: ref,
575
+ name: name,
576
+ ...(remote ? { remote } : {}),
577
+ current: head === '*',
578
+ ...(upstream ? { upstream, ...track(tracking ?? '') } : {}),
579
+ sha: sha,
580
+ subject: subject ?? '',
581
+ date: date ?? '',
582
+ });
583
+ }
584
+ const rank = (b) => (b.current ? 0 : b.remote ? 2 : 1);
585
+ const [state, tags] = await Promise.all([repoState(base), tagsOf(base)]);
586
+ return { branches: branches.sort((a, b) => rank(a) - rank(b)), remotes, repo: state, tags };
587
+ }
588
+ /** The most tags an `fs:branches` reply carries, the newest first. */
589
+ const TAGS_LIMIT = 300;
590
+ /** The checkout's tags, the newest first, each with the commit it points at. */
591
+ async function tagsOf(base) {
592
+ const format = ['%(refname:short)', '%(objectname)', '%(*objectname)', '%(objecttype)', '%(contents:subject)', '%(creatordate:iso-strict)'].join('%00');
593
+ const run = await git(base, ['for-each-ref', '--sort=-creatordate', `--count=${TAGS_LIMIT}`, `--format=${format}`, 'refs/tags']);
594
+ if (!run.ok)
595
+ return [];
596
+ return run.stdout.split('\n').flatMap((line) => {
597
+ if (!line)
598
+ return [];
599
+ const [name, sha, peeled, type, subject, date] = line.split('\0');
600
+ return [{ name: name, sha: peeled || sha, subject: subject ?? '', date: date ?? '', annotated: type === 'tag' }];
601
+ });
602
+ }
603
+ /** The merge, rebase, cherry-pick or revert the checkout is in the middle of. */
604
+ export async function operationOf(base) {
605
+ const dir = (await git(base, ['rev-parse', '--absolute-git-dir'])).stdout.trim();
606
+ if (!dir)
607
+ return null;
608
+ if (existsSync(join(dir, 'rebase-merge')) || existsSync(join(dir, 'rebase-apply')))
609
+ return 'rebase';
610
+ if (existsSync(join(dir, 'MERGE_HEAD')))
611
+ return 'merge';
612
+ if (existsSync(join(dir, 'CHERRY_PICK_HEAD')))
613
+ return 'cherry-pick';
614
+ if (existsSync(join(dir, 'REVERT_HEAD')))
615
+ return 'revert';
616
+ return null;
617
+ }
618
+ /** The files with a conflict, relative to the checkout. */
619
+ export async function conflictsOf(base) {
620
+ const run = await git(base, ['diff', '--name-only', '--diff-filter=U', '--relative', '-z']);
621
+ return run.stdout.split('\0').filter(Boolean);
622
+ }
623
+ /** Whether a remote branch holds the commit: then it is not undone. */
624
+ export async function isPushed(base, rev) {
625
+ return !!(await git(base, ['branch', '-r', '--contains', rev])).stdout.trim();
626
+ }
627
+ async function repoState(base) {
628
+ const [operation, conflicts, stashed, last, symbolic, tag, unpushedTags] = await Promise.all([
629
+ operationOf(base),
630
+ conflictsOf(base),
631
+ git(base, ['stash', 'list', '--format=%gd%x1f%gs%x1f%cI%x1f%H']),
632
+ git(base, ['log', '-1', '--format=%H%x1f%s', 'HEAD']),
633
+ git(base, ['symbolic-ref', '--quiet', 'HEAD']),
634
+ nearestTag(base),
635
+ unpushedAnnotatedTags(base),
636
+ ]);
637
+ const stashes = stashed.stdout.split('\n').flatMap((line) => {
638
+ const [ref, message, date, id] = line.split('\x1f');
639
+ const index = /^stash@\{(\d+)\}$/.exec(ref ?? '')?.[1];
640
+ return index === undefined ? [] : [{ index: Number(index), message: message ?? '', date: date ?? '', ...(id ? { sha: id } : {}) }];
641
+ });
642
+ const [sha, subject] = last.ok ? last.stdout.trim().split('\x1f') : [];
643
+ return {
644
+ operation,
645
+ conflicts,
646
+ stashes,
647
+ last: sha ? { sha, subject: subject ?? '', pushed: await isPushed(base, sha) } : null,
648
+ ...(sha && !symbolic.ok ? { detached: sha } : {}),
649
+ tag,
650
+ unpushedTags,
651
+ };
652
+ }
653
+ /** `HEAD -> refs/heads/main, refs/remotes/origin/main, tag: refs/tags/v1`
654
+ * (git's full decoration) as what points at a commit. */
655
+ function decoration(text) {
656
+ const refs = [];
657
+ let head = false;
658
+ for (let part of text.split(', ')) {
659
+ if (!part)
660
+ continue;
661
+ if (part === 'HEAD') {
662
+ head = true;
663
+ continue;
664
+ }
665
+ const isHead = part.startsWith('HEAD -> ');
666
+ if (isHead)
667
+ part = part.slice('HEAD -> '.length);
668
+ if (part.startsWith('tag: refs/tags/'))
669
+ refs.push({ name: part.slice('tag: refs/tags/'.length), kind: 'tag' });
670
+ else if (part.startsWith('refs/heads/'))
671
+ refs.push({ name: part.slice('refs/heads/'.length), kind: 'branch', ...(isHead ? { head: true } : {}) });
672
+ else if (part.startsWith('refs/remotes/') && !part.endsWith('/HEAD'))
673
+ refs.push({ name: part.slice('refs/remotes/'.length), kind: 'remote' });
674
+ }
675
+ return { refs, head };
676
+ }
677
+ export const exists = async (base, rev) => (await git(base, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`])).ok;
678
+ /**
679
+ * The latest commits of the checkout, newest first and each before its
680
+ * parents (what a graph needs), at most `FS_LOG_LIMIT`: on `ref` (a full ref
681
+ * of a local or remote branch), on what is checked out when it is null, or
682
+ * with `all` on every branch, remote branch and tag. Only the commits that
683
+ * touch the checkout, which may be a folder inside the repo, their parents
684
+ * the nearest that do. A repo without commits has none. Throws when it is no
685
+ * repo or `ref` is no branch.
686
+ */
687
+ export async function checkoutLog(config, root, ref, all = false, opts = {}) {
688
+ const base = await repo(config, root);
689
+ let revs;
690
+ if (all) {
691
+ revs = ['--branches', '--remotes', '--tags'];
692
+ if (await exists(base, 'HEAD'))
693
+ revs.push('HEAD');
694
+ }
695
+ else if (ref !== null) {
696
+ // A full ref name, so nothing in it reads as an option or a range.
697
+ const known = /^refs\/(heads|remotes)\//.test(ref)
698
+ && spawnSync('git', ['check-ref-format', ref], { timeout: 5000 }).status === 0
699
+ && await exists(base, ref);
700
+ if (!known)
701
+ throw new Error('No such branch in the checkout');
702
+ revs = [ref];
703
+ }
704
+ else {
705
+ if (!(await exists(base, 'HEAD')))
706
+ return [];
707
+ revs = ['HEAD'];
708
+ }
709
+ const skip = Math.max(0, Math.floor(opts.skip ?? 0));
710
+ const search = opts.search?.trim().slice(0, 200) ?? '';
711
+ // One file or folder: its own path, renames of a file followed.
712
+ let spec = ['--', '.'];
713
+ let follow = [];
714
+ if (opts.path) {
715
+ const file = inside(base, opts.path);
716
+ const rel = relative(base, file).split(sep).join('/');
717
+ if (rel) {
718
+ spec = ['--', `:(literal)${rel}`];
719
+ if (existsSync(file) && statSync(file).isFile())
720
+ follow = ['--follow'];
721
+ }
722
+ }
723
+ const format = ['--format=%H%x1f%P%x1f%s%x1f%an%x1f%cI%x1f%D'];
724
+ const logOf = (filter, count, from) => git(base, [
725
+ 'log', '-z', '--date-order', '--parents', '--decorate=full', `--max-count=${count}`, ...(from ? [`--skip=${from}`] : []),
726
+ ...filter, ...follow, ...format, ...revs, ...spec,
727
+ ], { timeout: 30_000 });
728
+ let records;
729
+ if (!search) {
730
+ const run = await logOf([], FS_LOG_LIMIT, skip);
731
+ if (!run.ok) {
732
+ // Every ref of `all` may be gone at once (a repo without commits).
733
+ if (all)
734
+ return [];
735
+ throw new Error(failure(run, 'git log failed'));
736
+ }
737
+ records = run.stdout.split('\0').filter(Boolean);
738
+ }
739
+ else {
740
+ // git ands --grep with --author: the message and the author apart, then
741
+ // joined newest first; an id as itself.
742
+ const window = skip + FS_LOG_LIMIT;
743
+ const literal = ['--regexp-ignore-case', '--fixed-strings'];
744
+ const runs = await Promise.all([
745
+ logOf([...literal, `--grep=${search}`], window, 0),
746
+ logOf([...literal, `--author=${search}`], window, 0),
747
+ ]);
748
+ if (runs.every(r => !r.ok)) {
749
+ if (all)
750
+ return [];
751
+ throw new Error(failure(runs[0], 'git log failed'));
752
+ }
753
+ const seen = new Map();
754
+ if (/^[0-9a-f]{4,64}$/i.test(search)) {
755
+ const one = await git(base, ['log', '-z', '-1', '--parents', '--decorate=full', ...format, `${search}^{commit}`, '--']);
756
+ if (one.ok)
757
+ for (const r of one.stdout.split('\0').filter(Boolean))
758
+ seen.set(r.split('\x1f')[0], r);
759
+ }
760
+ for (const run of runs)
761
+ for (const r of run.stdout.split('\0').filter(Boolean))
762
+ seen.set(r.split('\x1f')[0], r);
763
+ records = [...seen.values()]
764
+ .sort((a, b) => Date.parse(b.split('\x1f')[4]) - Date.parse(a.split('\x1f')[4]))
765
+ .slice(skip, skip + FS_LOG_LIMIT);
766
+ }
767
+ return records.map((record) => {
768
+ const [sha, parents, subject, author, date, decorated] = record.split('\x1f');
769
+ const { refs, head } = decoration(decorated ?? '');
770
+ return {
771
+ sha: sha,
772
+ parents: (parents ?? '').split(' ').filter(Boolean),
773
+ subject: subject ?? '',
774
+ author: author ?? '',
775
+ date: date ?? '',
776
+ ...(refs.length ? { refs } : {}),
777
+ ...(head ? { head } : {}),
778
+ };
779
+ });
780
+ }
781
+ /** `fs:log` with `unpushed`: the commits on HEAD no remote branch holds, each
782
+ * with its body and stat: what a tag of the unpushed work covers (the whole
783
+ * repo, not just the checkout's folder, as the tag is). Throws when it is no repo. */
784
+ export async function checkoutUnpushedLog(config, root) {
785
+ const commits = await unpushedCommits(await repo(config, root));
786
+ return commits.map((c) => {
787
+ const { refs, head } = decoration(c.decorated);
788
+ return {
789
+ sha: c.sha,
790
+ parents: c.parents,
791
+ subject: c.subject,
792
+ author: c.author,
793
+ date: c.date,
794
+ ...(refs.length ? { refs } : {}),
795
+ ...(head ? { head } : {}),
796
+ body: c.body,
797
+ stat: c.stat,
798
+ };
799
+ });
800
+ }
801
+ /** The commit `sha` names, in full, or an error when it is no commit here. */
802
+ export async function commitOf(base, sha) {
803
+ if (!/^[0-9a-f]{4,64}$/i.test(sha))
804
+ throw new Error('No such commit in the checkout');
805
+ const run = await git(base, ['rev-parse', '--verify', '--quiet', `${sha}^{commit}`]);
806
+ if (!run.ok)
807
+ throw new Error('No such commit in the checkout');
808
+ return run.stdout.trim();
809
+ }
810
+ /** `diff --git a/x b/x` with no `---`/`+++` (a binary file): the path. */
811
+ function pathOfHeader(line) {
812
+ const rest = line.slice('diff --git '.length);
813
+ // `a/<p> b/<p>`: the same path twice, so its length is known.
814
+ return rest.slice(2, 2 + (rest.length - 5) / 2);
815
+ }
816
+ /** A unified diff of several files, file by file. */
817
+ function splitPatch(text) {
818
+ const files = [];
819
+ let total = 0;
820
+ const chunks = text.split(/^(?=diff --git )/m).filter(c => c.startsWith('diff --git '));
821
+ for (const chunk of chunks) {
822
+ const lines = chunk.split('\n');
823
+ let path = pathOfHeader(lines[0]);
824
+ let from;
825
+ let state = 'modified';
826
+ let binary = false;
827
+ let i = 1;
828
+ for (; i < lines.length && !lines[i].startsWith('@@'); i++) {
829
+ const line = lines[i];
830
+ if (line.startsWith('new file mode'))
831
+ state = 'added';
832
+ else if (line.startsWith('deleted file mode'))
833
+ state = 'deleted';
834
+ else if (line.startsWith('rename from ')) {
835
+ from = line.slice('rename from '.length);
836
+ state = 'renamed';
837
+ }
838
+ else if (line.startsWith('rename to '))
839
+ path = line.slice('rename to '.length);
840
+ else if (line.startsWith('Binary files ') || line === 'GIT binary patch')
841
+ binary = true;
842
+ else if (line.startsWith('+++ ') && line !== '+++ /dev/null')
843
+ path = line.slice('+++ b/'.length);
844
+ else if (line.startsWith('--- ') && line !== '--- /dev/null' && state === 'deleted')
845
+ path = line.slice('--- a/'.length);
846
+ }
847
+ const hunks = lines.slice(i);
848
+ while (hunks.length && hunks[hunks.length - 1] === '')
849
+ hunks.pop();
850
+ let additions = 0;
851
+ let deletions = 0;
852
+ for (const line of hunks) {
853
+ if (line.startsWith('+'))
854
+ additions++;
855
+ else if (line.startsWith('-'))
856
+ deletions++;
857
+ }
858
+ const patch = hunks.join('\n');
859
+ const bytes = Buffer.byteLength(patch);
860
+ const tooLarge = !binary && (bytes > FS_PATCH_FILE_BYTES || total + bytes > FS_PATCH_TOTAL_BYTES);
861
+ if (!binary && !tooLarge)
862
+ total += bytes;
863
+ files.push({
864
+ path,
865
+ ...(from ? { from } : {}),
866
+ state,
867
+ additions,
868
+ deletions,
869
+ ...(binary ? { binary } : {}),
870
+ ...(tooLarge ? { tooLarge } : {}),
871
+ patch: binary || tooLarge || !patch ? null : patch,
872
+ });
873
+ }
874
+ return files;
875
+ }
876
+ /**
877
+ * One commit with its whole message and what it changed against its first
878
+ * parent (a merge: what it brought in), file by file, only inside the
879
+ * checkout, paths relative to it.
880
+ */
881
+ export async function checkoutShow(config, root, sha, against) {
882
+ const base = await repo(config, root);
883
+ const full = await revOf(base, sha);
884
+ const from = against ? await revOf(base, against) : null;
885
+ const meta = await git(base, ['show', '-s', '--decorate=full', '--format=%H%x1f%P%x1f%an%x1f%ae%x1f%cI%x1f%D%x1f%s%x1f%b', full]);
886
+ if (!meta.ok)
887
+ throw new Error(failure(meta, 'git show failed'));
888
+ const [, parents, author, email, date, decorated, subject, ...body] = meta.stdout.split('\x1f');
889
+ const parentList = (parents ?? '').split(' ').filter(Boolean);
890
+ const range = from ? [from, full] : parentList[0] ? [parentList[0], full] : ['--root', full];
891
+ const diff = await git(base, ['diff-tree', '-p', '-r', '-M', '--relative', '--no-color', '--no-ext-diff', ...range, '--', '.'], { timeout: 30_000 });
892
+ if (!diff.ok)
893
+ throw new Error(failure(diff, 'git diff-tree failed'));
894
+ // `--root` prints the commit's id first.
895
+ const patch = diff.stdout.slice(Math.max(0, diff.stdout.indexOf('diff --git ')));
896
+ const { refs, head } = decoration(decorated ?? '');
897
+ return {
898
+ sha: full,
899
+ parents: parentList,
900
+ subject: subject ?? '',
901
+ author: author ?? '',
902
+ email: email ?? '',
903
+ date: date ?? '',
904
+ body: body.join('\x1f').trim(),
905
+ ...(refs.length ? { refs } : {}),
906
+ ...(head ? { head } : {}),
907
+ files: patch.startsWith('diff --git ') ? splitPatch(patch) : [],
908
+ };
909
+ }
910
+ /** A commit by its id (an ancestor with `^` or `~N`: a stash against its
911
+ * parent), or by a full ref of a branch, remote branch or tag (what a
912
+ * compare names), in full; an error when it is neither. */
913
+ async function revOf(base, rev) {
914
+ const ancestor = /^([0-9a-f]{4,64})(\^|~\d{1,4})$/i.exec(rev);
915
+ if (ancestor) {
916
+ const run = await git(base, ['rev-parse', '--verify', '--quiet', `${await commitOf(base, ancestor[1])}${ancestor[2]}^{commit}`]);
917
+ if (!run.ok)
918
+ throw new Error('No such commit in the checkout');
919
+ return run.stdout.trim();
920
+ }
921
+ if (!rev.startsWith('refs/'))
922
+ return commitOf(base, rev);
923
+ const known = /^refs\/(heads|remotes|tags)\//.test(rev) && spawnSync('git', ['check-ref-format', rev], { timeout: 5000 }).status === 0;
924
+ const run = known ? await git(base, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`]) : null;
925
+ if (!run?.ok)
926
+ throw new Error('No such branch or tag in the checkout');
927
+ return run.stdout.trim();
928
+ }
929
+ const UNCOMMITTED = /^0+$/;
930
+ /** Takes the author, time and summary of one `git blame --porcelain` header line into `pending`. */
931
+ function readBlameMeta(line, pending) {
932
+ if (line.startsWith('author '))
933
+ pending.author = line.slice('author '.length);
934
+ else if (line.startsWith('author-time '))
935
+ pending.time = Number(line.slice('author-time '.length));
936
+ else if (line.startsWith('summary '))
937
+ pending.subject = line.slice('summary '.length);
938
+ }
939
+ /**
940
+ * Who last changed each line of one file of the checkout, as it is on disk:
941
+ * per line the commit, null for a line not committed yet, and per commit who,
942
+ * when and why. Throws when git does not track the file.
943
+ */
944
+ export async function checkoutBlame(config, root, path) {
945
+ const base = await repo(config, root);
946
+ const file = inside(base, path);
947
+ if (!existsSync(file) || !statSync(file).isFile())
948
+ throw new Error('File does not exist');
949
+ const rel = relative(base, file).split(sep).join('/');
950
+ const run = await git(base, ['blame', '--porcelain', '--', rel], { timeout: 30_000 });
951
+ if (!run.ok)
952
+ throw new Error(failure(run, 'git blame failed'));
953
+ const lines = [];
954
+ const commits = {};
955
+ let sha = '';
956
+ let pending = {};
957
+ for (const line of run.stdout.split('\n')) {
958
+ const header = /^([0-9a-f]{40,64}) \d+ (\d+)/.exec(line);
959
+ if (header) {
960
+ sha = header[1];
961
+ pending = {};
962
+ continue;
963
+ }
964
+ if (line.startsWith('\t')) {
965
+ const uncommitted = UNCOMMITTED.test(sha);
966
+ if (!uncommitted && !commits[sha] && pending.time !== undefined) {
967
+ commits[sha] = { author: pending.author ?? '', date: new Date(pending.time * 1000).toISOString(), subject: pending.subject ?? '' };
968
+ }
969
+ lines.push(uncommitted ? null : sha);
970
+ continue;
971
+ }
972
+ readBlameMeta(line, pending);
973
+ }
974
+ return { lines, commits };
975
+ }
976
+ /** An untracked file as a patch that adds it, within the same limits as a
977
+ * commit's (binary or too large: no text). */
978
+ function addedFile(base, rel) {
979
+ const full = join(base, rel);
980
+ let bytes;
981
+ try {
982
+ bytes = readFileSync(full);
983
+ }
984
+ catch {
985
+ return { path: rel, state: 'added', additions: 0, deletions: 0, patch: null };
986
+ }
987
+ if (bytes.subarray(0, SNIFF_BYTES).includes(0))
988
+ return { path: rel, state: 'added', additions: 0, deletions: 0, binary: true, patch: null };
989
+ const text = bytes.toString('utf8');
990
+ const lines = text.split('\n');
991
+ if (lines[lines.length - 1] === '')
992
+ lines.pop();
993
+ if (bytes.length > FS_PATCH_FILE_BYTES)
994
+ return { path: rel, state: 'added', additions: lines.length, deletions: 0, tooLarge: true, patch: null };
995
+ const patch = lines.length
996
+ ? [`@@ -0,0 +1,${lines.length} @@`, ...lines.map(l => `+${l}`), ...(text.endsWith('\n') ? [] : ['\'])].join('\n')
997
+ : null;
998
+ return { path: rel, state: 'added', additions: lines.length, deletions: 0, patch };
999
+ }
1000
+ /**
1001
+ * What `git diff` compares against for a side. Staged: the index against the
1002
+ * last commit (against nothing before the first one); unstaged: the files on
1003
+ * disk against the index; neither: the files on disk against the last commit
1004
+ * (null before the first one: nothing to diff).
1005
+ */
1006
+ function diffAgainst(side, born) {
1007
+ if (side === 'staged')
1008
+ return ['--cached', ...(born ? ['HEAD'] : [])];
1009
+ if (side === 'unstaged')
1010
+ return [];
1011
+ return born ? ['HEAD'] : null;
1012
+ }
1013
+ /**
1014
+ * What changed in the checkout against what is committed, staged or not,
1015
+ * file by file with its patch (`path`: that one file): tracked files as git
1016
+ * diffs them, untracked ones as added. Only inside the checkout, paths
1017
+ * relative to it. A repo without commits has every file added.
1018
+ */
1019
+ export async function checkoutDiff(config, root, path, side) {
1020
+ const base = await repo(config, root);
1021
+ const spec = path === null ? '.' : relative(base, inside(base, path)).split(sep).join('/');
1022
+ const literal = path === null ? [] : ['--literal-pathspecs'];
1023
+ const files = [];
1024
+ const born = await exists(base, 'HEAD');
1025
+ const against = diffAgainst(side, born);
1026
+ if (against) {
1027
+ const run = await git(base, [...literal, 'diff', ...against, '-M', '--relative', '--no-color', '--no-ext-diff', '--', spec], { timeout: 30_000 });
1028
+ if (!run.ok)
1029
+ throw new Error(failure(run, 'git diff failed'));
1030
+ if (run.stdout.startsWith('diff --git '))
1031
+ files.push(...splitPatch(run.stdout));
1032
+ }
1033
+ if (side === 'staged')
1034
+ return files.sort((a, b) => a.path.localeCompare(b.path));
1035
+ // What the index holds counts as staged once a side is asked for.
1036
+ const listed = await git(base, [...literal, 'ls-files', '-z', '--others', '--exclude-standard', ...(born || side ? [] : ['--cached']), '--', spec]);
1037
+ let budget = files.reduce((n, f) => n + Buffer.byteLength(f.patch ?? ''), 0);
1038
+ for (const rel of listed.stdout.split('\0').filter(Boolean)) {
1039
+ const added = addedFile(base, rel);
1040
+ const bytes = Buffer.byteLength(added.patch ?? '');
1041
+ if (added.patch && budget + bytes > FS_PATCH_TOTAL_BYTES)
1042
+ files.push({ ...added, tooLarge: true, patch: null });
1043
+ else {
1044
+ budget += bytes;
1045
+ files.push(added);
1046
+ }
1047
+ }
1048
+ return files.sort((a, b) => a.path.localeCompare(b.path));
1049
+ }