@hyperfrontend/versioning 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 (353) hide show
  1. package/ARCHITECTURE.md +593 -0
  2. package/CHANGELOG.md +35 -0
  3. package/FUNDING.md +141 -0
  4. package/LICENSE.md +21 -0
  5. package/README.md +195 -0
  6. package/SECURITY.md +82 -0
  7. package/changelog/compare/diff.d.ts +128 -0
  8. package/changelog/compare/diff.d.ts.map +1 -0
  9. package/changelog/compare/index.cjs.js +628 -0
  10. package/changelog/compare/index.cjs.js.map +1 -0
  11. package/changelog/compare/index.d.ts +4 -0
  12. package/changelog/compare/index.d.ts.map +1 -0
  13. package/changelog/compare/index.esm.js +612 -0
  14. package/changelog/compare/index.esm.js.map +1 -0
  15. package/changelog/compare/is-equal.d.ts +114 -0
  16. package/changelog/compare/is-equal.d.ts.map +1 -0
  17. package/changelog/index.cjs.js +6448 -0
  18. package/changelog/index.cjs.js.map +1 -0
  19. package/changelog/index.d.ts +6 -0
  20. package/changelog/index.d.ts.map +1 -0
  21. package/changelog/index.esm.js +6358 -0
  22. package/changelog/index.esm.js.map +1 -0
  23. package/changelog/models/changelog.d.ts +86 -0
  24. package/changelog/models/changelog.d.ts.map +1 -0
  25. package/changelog/models/commit-ref.d.ts +51 -0
  26. package/changelog/models/commit-ref.d.ts.map +1 -0
  27. package/changelog/models/entry.d.ts +84 -0
  28. package/changelog/models/entry.d.ts.map +1 -0
  29. package/changelog/models/index.cjs.js +2043 -0
  30. package/changelog/models/index.cjs.js.map +1 -0
  31. package/changelog/models/index.d.ts +11 -0
  32. package/changelog/models/index.d.ts.map +1 -0
  33. package/changelog/models/index.esm.js +2026 -0
  34. package/changelog/models/index.esm.js.map +1 -0
  35. package/changelog/models/schema.d.ts +68 -0
  36. package/changelog/models/schema.d.ts.map +1 -0
  37. package/changelog/models/section.d.ts +25 -0
  38. package/changelog/models/section.d.ts.map +1 -0
  39. package/changelog/operations/add-entry.d.ts +56 -0
  40. package/changelog/operations/add-entry.d.ts.map +1 -0
  41. package/changelog/operations/add-item.d.ts +18 -0
  42. package/changelog/operations/add-item.d.ts.map +1 -0
  43. package/changelog/operations/filter-by-predicate.d.ts +81 -0
  44. package/changelog/operations/filter-by-predicate.d.ts.map +1 -0
  45. package/changelog/operations/filter-by-range.d.ts +63 -0
  46. package/changelog/operations/filter-by-range.d.ts.map +1 -0
  47. package/changelog/operations/filter-entries.d.ts +9 -0
  48. package/changelog/operations/filter-entries.d.ts.map +1 -0
  49. package/changelog/operations/index.cjs.js +2455 -0
  50. package/changelog/operations/index.cjs.js.map +1 -0
  51. package/changelog/operations/index.d.ts +15 -0
  52. package/changelog/operations/index.d.ts.map +1 -0
  53. package/changelog/operations/index.esm.js +2411 -0
  54. package/changelog/operations/index.esm.js.map +1 -0
  55. package/changelog/operations/merge.d.ts +88 -0
  56. package/changelog/operations/merge.d.ts.map +1 -0
  57. package/changelog/operations/remove-entry.d.ts +45 -0
  58. package/changelog/operations/remove-entry.d.ts.map +1 -0
  59. package/changelog/operations/remove-section.d.ts +50 -0
  60. package/changelog/operations/remove-section.d.ts.map +1 -0
  61. package/changelog/operations/transform.d.ts +143 -0
  62. package/changelog/operations/transform.d.ts.map +1 -0
  63. package/changelog/parse/index.cjs.js +1282 -0
  64. package/changelog/parse/index.cjs.js.map +1 -0
  65. package/changelog/parse/index.d.ts +5 -0
  66. package/changelog/parse/index.d.ts.map +1 -0
  67. package/changelog/parse/index.esm.js +1275 -0
  68. package/changelog/parse/index.esm.js.map +1 -0
  69. package/changelog/parse/line.d.ts +48 -0
  70. package/changelog/parse/line.d.ts.map +1 -0
  71. package/changelog/parse/parser.d.ts +16 -0
  72. package/changelog/parse/parser.d.ts.map +1 -0
  73. package/changelog/parse/tokenizer.d.ts +49 -0
  74. package/changelog/parse/tokenizer.d.ts.map +1 -0
  75. package/changelog/serialize/index.cjs.js +574 -0
  76. package/changelog/serialize/index.cjs.js.map +1 -0
  77. package/changelog/serialize/index.d.ts +6 -0
  78. package/changelog/serialize/index.d.ts.map +1 -0
  79. package/changelog/serialize/index.esm.js +564 -0
  80. package/changelog/serialize/index.esm.js.map +1 -0
  81. package/changelog/serialize/templates.d.ts +81 -0
  82. package/changelog/serialize/templates.d.ts.map +1 -0
  83. package/changelog/serialize/to-json.d.ts +57 -0
  84. package/changelog/serialize/to-json.d.ts.map +1 -0
  85. package/changelog/serialize/to-string.d.ts +30 -0
  86. package/changelog/serialize/to-string.d.ts.map +1 -0
  87. package/commits/index.cjs.js +648 -0
  88. package/commits/index.cjs.js.map +1 -0
  89. package/commits/index.d.ts +3 -0
  90. package/commits/index.d.ts.map +1 -0
  91. package/commits/index.esm.js +629 -0
  92. package/commits/index.esm.js.map +1 -0
  93. package/commits/models/breaking.d.ts +39 -0
  94. package/commits/models/breaking.d.ts.map +1 -0
  95. package/commits/models/commit-type.d.ts +32 -0
  96. package/commits/models/commit-type.d.ts.map +1 -0
  97. package/commits/models/conventional.d.ts +49 -0
  98. package/commits/models/conventional.d.ts.map +1 -0
  99. package/commits/models/index.cjs.js +207 -0
  100. package/commits/models/index.cjs.js.map +1 -0
  101. package/commits/models/index.d.ts +7 -0
  102. package/commits/models/index.d.ts.map +1 -0
  103. package/commits/models/index.esm.js +193 -0
  104. package/commits/models/index.esm.js.map +1 -0
  105. package/commits/parse/body.d.ts +18 -0
  106. package/commits/parse/body.d.ts.map +1 -0
  107. package/commits/parse/footer.d.ts +16 -0
  108. package/commits/parse/footer.d.ts.map +1 -0
  109. package/commits/parse/header.d.ts +15 -0
  110. package/commits/parse/header.d.ts.map +1 -0
  111. package/commits/parse/index.cjs.js +505 -0
  112. package/commits/parse/index.cjs.js.map +1 -0
  113. package/commits/parse/index.d.ts +5 -0
  114. package/commits/parse/index.d.ts.map +1 -0
  115. package/commits/parse/index.esm.js +499 -0
  116. package/commits/parse/index.esm.js.map +1 -0
  117. package/commits/parse/message.d.ts +17 -0
  118. package/commits/parse/message.d.ts.map +1 -0
  119. package/commits/utils/replace-char.d.ts +19 -0
  120. package/commits/utils/replace-char.d.ts.map +1 -0
  121. package/flow/executor/execute.d.ts +72 -0
  122. package/flow/executor/execute.d.ts.map +1 -0
  123. package/flow/executor/index.cjs.js +4402 -0
  124. package/flow/executor/index.cjs.js.map +1 -0
  125. package/flow/executor/index.d.ts +3 -0
  126. package/flow/executor/index.d.ts.map +1 -0
  127. package/flow/executor/index.esm.js +4398 -0
  128. package/flow/executor/index.esm.js.map +1 -0
  129. package/flow/factory.d.ts +58 -0
  130. package/flow/factory.d.ts.map +1 -0
  131. package/flow/index.cjs.js +8506 -0
  132. package/flow/index.cjs.js.map +1 -0
  133. package/flow/index.d.ts +7 -0
  134. package/flow/index.d.ts.map +1 -0
  135. package/flow/index.esm.js +8451 -0
  136. package/flow/index.esm.js.map +1 -0
  137. package/flow/models/flow.d.ts +130 -0
  138. package/flow/models/flow.d.ts.map +1 -0
  139. package/flow/models/index.cjs.js +285 -0
  140. package/flow/models/index.cjs.js.map +1 -0
  141. package/flow/models/index.d.ts +7 -0
  142. package/flow/models/index.d.ts.map +1 -0
  143. package/flow/models/index.esm.js +268 -0
  144. package/flow/models/index.esm.js.map +1 -0
  145. package/flow/models/step.d.ts +108 -0
  146. package/flow/models/step.d.ts.map +1 -0
  147. package/flow/models/types.d.ts +150 -0
  148. package/flow/models/types.d.ts.map +1 -0
  149. package/flow/presets/conventional.d.ts +59 -0
  150. package/flow/presets/conventional.d.ts.map +1 -0
  151. package/flow/presets/independent.d.ts +61 -0
  152. package/flow/presets/independent.d.ts.map +1 -0
  153. package/flow/presets/index.cjs.js +3903 -0
  154. package/flow/presets/index.cjs.js.map +1 -0
  155. package/flow/presets/index.d.ts +4 -0
  156. package/flow/presets/index.d.ts.map +1 -0
  157. package/flow/presets/index.esm.js +3889 -0
  158. package/flow/presets/index.esm.js.map +1 -0
  159. package/flow/presets/synced.d.ts +65 -0
  160. package/flow/presets/synced.d.ts.map +1 -0
  161. package/flow/steps/analyze-commits.d.ts +19 -0
  162. package/flow/steps/analyze-commits.d.ts.map +1 -0
  163. package/flow/steps/calculate-bump.d.ts +27 -0
  164. package/flow/steps/calculate-bump.d.ts.map +1 -0
  165. package/flow/steps/create-commit.d.ts +16 -0
  166. package/flow/steps/create-commit.d.ts.map +1 -0
  167. package/flow/steps/create-tag.d.ts +22 -0
  168. package/flow/steps/create-tag.d.ts.map +1 -0
  169. package/flow/steps/fetch-registry.d.ts +19 -0
  170. package/flow/steps/fetch-registry.d.ts.map +1 -0
  171. package/flow/steps/generate-changelog.d.ts +25 -0
  172. package/flow/steps/generate-changelog.d.ts.map +1 -0
  173. package/flow/steps/index.cjs.js +3523 -0
  174. package/flow/steps/index.cjs.js.map +1 -0
  175. package/flow/steps/index.d.ts +8 -0
  176. package/flow/steps/index.d.ts.map +1 -0
  177. package/flow/steps/index.esm.js +3504 -0
  178. package/flow/steps/index.esm.js.map +1 -0
  179. package/flow/steps/update-packages.d.ts +25 -0
  180. package/flow/steps/update-packages.d.ts.map +1 -0
  181. package/flow/utils/interpolate.d.ts +11 -0
  182. package/flow/utils/interpolate.d.ts.map +1 -0
  183. package/git/factory.d.ts +233 -0
  184. package/git/factory.d.ts.map +1 -0
  185. package/git/index.cjs.js +2863 -0
  186. package/git/index.cjs.js.map +1 -0
  187. package/git/index.d.ts +5 -0
  188. package/git/index.d.ts.map +1 -0
  189. package/git/index.esm.js +2785 -0
  190. package/git/index.esm.js.map +1 -0
  191. package/git/models/commit.d.ts +129 -0
  192. package/git/models/commit.d.ts.map +1 -0
  193. package/git/models/index.cjs.js +755 -0
  194. package/git/models/index.cjs.js.map +1 -0
  195. package/git/models/index.d.ts +7 -0
  196. package/git/models/index.d.ts.map +1 -0
  197. package/git/models/index.esm.js +729 -0
  198. package/git/models/index.esm.js.map +1 -0
  199. package/git/models/ref.d.ts +120 -0
  200. package/git/models/ref.d.ts.map +1 -0
  201. package/git/models/tag.d.ts +141 -0
  202. package/git/models/tag.d.ts.map +1 -0
  203. package/git/operations/commit.d.ts +97 -0
  204. package/git/operations/commit.d.ts.map +1 -0
  205. package/git/operations/head-info.d.ts +29 -0
  206. package/git/operations/head-info.d.ts.map +1 -0
  207. package/git/operations/index.cjs.js +1954 -0
  208. package/git/operations/index.cjs.js.map +1 -0
  209. package/git/operations/index.d.ts +14 -0
  210. package/git/operations/index.d.ts.map +1 -0
  211. package/git/operations/index.esm.js +1903 -0
  212. package/git/operations/index.esm.js.map +1 -0
  213. package/git/operations/log.d.ts +104 -0
  214. package/git/operations/log.d.ts.map +1 -0
  215. package/git/operations/manage-tags.d.ts +60 -0
  216. package/git/operations/manage-tags.d.ts.map +1 -0
  217. package/git/operations/query-tags.d.ts +88 -0
  218. package/git/operations/query-tags.d.ts.map +1 -0
  219. package/git/operations/stage.d.ts +66 -0
  220. package/git/operations/stage.d.ts.map +1 -0
  221. package/git/operations/status.d.ts +173 -0
  222. package/git/operations/status.d.ts.map +1 -0
  223. package/index.cjs.js +16761 -0
  224. package/index.cjs.js.map +1 -0
  225. package/index.d.ts +102 -0
  226. package/index.d.ts.map +1 -0
  227. package/index.esm.js +16427 -0
  228. package/index.esm.js.map +1 -0
  229. package/package.json +200 -0
  230. package/registry/factory.d.ts +18 -0
  231. package/registry/factory.d.ts.map +1 -0
  232. package/registry/index.cjs.js +543 -0
  233. package/registry/index.cjs.js.map +1 -0
  234. package/registry/index.d.ts +5 -0
  235. package/registry/index.d.ts.map +1 -0
  236. package/registry/index.esm.js +535 -0
  237. package/registry/index.esm.js.map +1 -0
  238. package/registry/models/index.cjs.js +69 -0
  239. package/registry/models/index.cjs.js.map +1 -0
  240. package/registry/models/index.d.ts +6 -0
  241. package/registry/models/index.d.ts.map +1 -0
  242. package/registry/models/index.esm.js +66 -0
  243. package/registry/models/index.esm.js.map +1 -0
  244. package/registry/models/package-info.d.ts +55 -0
  245. package/registry/models/package-info.d.ts.map +1 -0
  246. package/registry/models/registry.d.ts +62 -0
  247. package/registry/models/registry.d.ts.map +1 -0
  248. package/registry/models/version-info.d.ts +67 -0
  249. package/registry/models/version-info.d.ts.map +1 -0
  250. package/registry/npm/cache.d.ts +50 -0
  251. package/registry/npm/cache.d.ts.map +1 -0
  252. package/registry/npm/client.d.ts +30 -0
  253. package/registry/npm/client.d.ts.map +1 -0
  254. package/registry/npm/index.cjs.js +456 -0
  255. package/registry/npm/index.cjs.js.map +1 -0
  256. package/registry/npm/index.d.ts +4 -0
  257. package/registry/npm/index.d.ts.map +1 -0
  258. package/registry/npm/index.esm.js +451 -0
  259. package/registry/npm/index.esm.js.map +1 -0
  260. package/semver/compare/compare.d.ts +100 -0
  261. package/semver/compare/compare.d.ts.map +1 -0
  262. package/semver/compare/index.cjs.js +386 -0
  263. package/semver/compare/index.cjs.js.map +1 -0
  264. package/semver/compare/index.d.ts +3 -0
  265. package/semver/compare/index.d.ts.map +1 -0
  266. package/semver/compare/index.esm.js +370 -0
  267. package/semver/compare/index.esm.js.map +1 -0
  268. package/semver/compare/sort.d.ts +36 -0
  269. package/semver/compare/sort.d.ts.map +1 -0
  270. package/semver/format/index.cjs.js +58 -0
  271. package/semver/format/index.cjs.js.map +1 -0
  272. package/semver/format/index.d.ts +2 -0
  273. package/semver/format/index.d.ts.map +1 -0
  274. package/semver/format/index.esm.js +53 -0
  275. package/semver/format/index.esm.js.map +1 -0
  276. package/semver/format/to-string.d.ts +31 -0
  277. package/semver/format/to-string.d.ts.map +1 -0
  278. package/semver/increment/bump.d.ts +37 -0
  279. package/semver/increment/bump.d.ts.map +1 -0
  280. package/semver/increment/index.cjs.js +223 -0
  281. package/semver/increment/index.cjs.js.map +1 -0
  282. package/semver/increment/index.d.ts +2 -0
  283. package/semver/increment/index.d.ts.map +1 -0
  284. package/semver/increment/index.esm.js +219 -0
  285. package/semver/increment/index.esm.js.map +1 -0
  286. package/semver/index.cjs.js +1499 -0
  287. package/semver/index.cjs.js.map +1 -0
  288. package/semver/index.d.ts +6 -0
  289. package/semver/index.d.ts.map +1 -0
  290. package/semver/index.esm.js +1458 -0
  291. package/semver/index.esm.js.map +1 -0
  292. package/semver/models/index.cjs.js +153 -0
  293. package/semver/models/index.cjs.js.map +1 -0
  294. package/semver/models/index.d.ts +5 -0
  295. package/semver/models/index.d.ts.map +1 -0
  296. package/semver/models/index.esm.js +139 -0
  297. package/semver/models/index.esm.js.map +1 -0
  298. package/semver/models/range.d.ts +83 -0
  299. package/semver/models/range.d.ts.map +1 -0
  300. package/semver/models/version.d.ts +78 -0
  301. package/semver/models/version.d.ts.map +1 -0
  302. package/semver/parse/index.cjs.js +799 -0
  303. package/semver/parse/index.cjs.js.map +1 -0
  304. package/semver/parse/index.d.ts +5 -0
  305. package/semver/parse/index.d.ts.map +1 -0
  306. package/semver/parse/index.esm.js +793 -0
  307. package/semver/parse/index.esm.js.map +1 -0
  308. package/semver/parse/range.d.ts +38 -0
  309. package/semver/parse/range.d.ts.map +1 -0
  310. package/semver/parse/version.d.ts +49 -0
  311. package/semver/parse/version.d.ts.map +1 -0
  312. package/workspace/discovery/changelog-path.d.ts +21 -0
  313. package/workspace/discovery/changelog-path.d.ts.map +1 -0
  314. package/workspace/discovery/dependencies.d.ts +145 -0
  315. package/workspace/discovery/dependencies.d.ts.map +1 -0
  316. package/workspace/discovery/discover-changelogs.d.ts +76 -0
  317. package/workspace/discovery/discover-changelogs.d.ts.map +1 -0
  318. package/workspace/discovery/index.cjs.js +2300 -0
  319. package/workspace/discovery/index.cjs.js.map +1 -0
  320. package/workspace/discovery/index.d.ts +13 -0
  321. package/workspace/discovery/index.d.ts.map +1 -0
  322. package/workspace/discovery/index.esm.js +2283 -0
  323. package/workspace/discovery/index.esm.js.map +1 -0
  324. package/workspace/discovery/packages.d.ts +83 -0
  325. package/workspace/discovery/packages.d.ts.map +1 -0
  326. package/workspace/index.cjs.js +4445 -0
  327. package/workspace/index.cjs.js.map +1 -0
  328. package/workspace/index.d.ts +52 -0
  329. package/workspace/index.d.ts.map +1 -0
  330. package/workspace/index.esm.js +4394 -0
  331. package/workspace/index.esm.js.map +1 -0
  332. package/workspace/models/index.cjs.js +284 -0
  333. package/workspace/models/index.cjs.js.map +1 -0
  334. package/workspace/models/index.d.ts +10 -0
  335. package/workspace/models/index.d.ts.map +1 -0
  336. package/workspace/models/index.esm.js +261 -0
  337. package/workspace/models/index.esm.js.map +1 -0
  338. package/workspace/models/project.d.ts +118 -0
  339. package/workspace/models/project.d.ts.map +1 -0
  340. package/workspace/models/workspace.d.ts +139 -0
  341. package/workspace/models/workspace.d.ts.map +1 -0
  342. package/workspace/operations/batch-update.d.ts +99 -0
  343. package/workspace/operations/batch-update.d.ts.map +1 -0
  344. package/workspace/operations/cascade-bump.d.ts +125 -0
  345. package/workspace/operations/cascade-bump.d.ts.map +1 -0
  346. package/workspace/operations/index.cjs.js +2675 -0
  347. package/workspace/operations/index.cjs.js.map +1 -0
  348. package/workspace/operations/index.d.ts +12 -0
  349. package/workspace/operations/index.d.ts.map +1 -0
  350. package/workspace/operations/index.esm.js +2663 -0
  351. package/workspace/operations/index.esm.js.map +1 -0
  352. package/workspace/operations/validate.d.ts +85 -0
  353. package/workspace/operations/validate.d.ts.map +1 -0
@@ -0,0 +1,4402 @@
1
+ 'use strict';
2
+
3
+ require('node:util');
4
+ var node_path = require('node:path');
5
+ var node_fs = require('node:fs');
6
+ require('node:os');
7
+ var node_child_process = require('node:child_process');
8
+
9
+ /**
10
+ * Safe copies of Date built-in via factory function and static methods.
11
+ *
12
+ * Since constructors cannot be safely captured via Object.assign, this module
13
+ * provides a factory function that uses Reflect.construct internally.
14
+ *
15
+ * These references are captured at module initialization time to protect against
16
+ * prototype pollution attacks. Import only what you need for tree-shaking.
17
+ *
18
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/date
19
+ */
20
+ // Capture references at module initialization time
21
+ const _Date = globalThis.Date;
22
+ const _Reflect$3 = globalThis.Reflect;
23
+ function createDate(...args) {
24
+ return _Reflect$3.construct(_Date, args);
25
+ }
26
+ /**
27
+ * (Safe copy) Returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
28
+ */
29
+ const dateNow = _Date.now;
30
+
31
+ /**
32
+ * Safe copies of Error built-ins via factory functions.
33
+ *
34
+ * Since constructors cannot be safely captured via Object.assign, this module
35
+ * provides factory functions that use Reflect.construct internally.
36
+ *
37
+ * These references are captured at module initialization time to protect against
38
+ * prototype pollution attacks. Import only what you need for tree-shaking.
39
+ *
40
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
41
+ */
42
+ // Capture references at module initialization time
43
+ const _Error = globalThis.Error;
44
+ const _Reflect$2 = globalThis.Reflect;
45
+ /**
46
+ * (Safe copy) Creates a new Error using the captured Error constructor.
47
+ * Use this instead of `new Error()`.
48
+ *
49
+ * @param message - Optional error message.
50
+ * @param options - Optional error options.
51
+ * @returns A new Error instance.
52
+ */
53
+ const createError = (message, options) => _Reflect$2.construct(_Error, [message, options]);
54
+
55
+ /**
56
+ * Safe copies of JSON built-in methods.
57
+ *
58
+ * These references are captured at module initialization time to protect against
59
+ * prototype pollution attacks. Import only what you need for tree-shaking.
60
+ *
61
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/json
62
+ */
63
+ // Capture references at module initialization time
64
+ const _JSON = globalThis.JSON;
65
+ /**
66
+ * (Safe copy) Converts a JavaScript Object Notation (JSON) string into an object.
67
+ */
68
+ const parse = _JSON.parse;
69
+ /**
70
+ * (Safe copy) Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
71
+ */
72
+ const stringify = _JSON.stringify;
73
+
74
+ /**
75
+ * Safe copies of Set built-in via factory function.
76
+ *
77
+ * Since constructors cannot be safely captured via Object.assign, this module
78
+ * provides a factory function that uses Reflect.construct internally.
79
+ *
80
+ * These references are captured at module initialization time to protect against
81
+ * prototype pollution attacks. Import only what you need for tree-shaking.
82
+ *
83
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/set
84
+ */
85
+ // Capture references at module initialization time
86
+ const _Set = globalThis.Set;
87
+ const _Reflect$1 = globalThis.Reflect;
88
+ /**
89
+ * (Safe copy) Creates a new Set using the captured Set constructor.
90
+ * Use this instead of `new Set()`.
91
+ *
92
+ * @param iterable - Optional iterable of values.
93
+ * @returns A new Set instance.
94
+ */
95
+ const createSet = (iterable) => _Reflect$1.construct(_Set, iterable ? [iterable] : []);
96
+
97
+ /**
98
+ * Safe copies of Object built-in methods.
99
+ *
100
+ * These references are captured at module initialization time to protect against
101
+ * prototype pollution attacks. Import only what you need for tree-shaking.
102
+ *
103
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
104
+ */
105
+ // Capture references at module initialization time
106
+ const _Object = globalThis.Object;
107
+ /**
108
+ * (Safe copy) Prevents modification of existing property attributes and values,
109
+ * and prevents the addition of new properties.
110
+ */
111
+ const freeze = _Object.freeze;
112
+ /**
113
+ * (Safe copy) Returns the names of the enumerable string properties and methods of an object.
114
+ */
115
+ const keys = _Object.keys;
116
+ /**
117
+ * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
118
+ */
119
+ const entries = _Object.entries;
120
+ /**
121
+ * (Safe copy) Adds one or more properties to an object, and/or modifies attributes of existing properties.
122
+ */
123
+ const defineProperties = _Object.defineProperties;
124
+
125
+ const registeredClasses = [];
126
+
127
+ /**
128
+ * Safe copies of Array built-in static methods.
129
+ *
130
+ * These references are captured at module initialization time to protect against
131
+ * prototype pollution attacks. Import only what you need for tree-shaking.
132
+ *
133
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/array
134
+ */
135
+ // Capture references at module initialization time
136
+ const _Array = globalThis.Array;
137
+ /**
138
+ * (Safe copy) Determines whether the passed value is an Array.
139
+ */
140
+ const isArray = _Array.isArray;
141
+ /**
142
+ * (Safe copy) Creates an array from an array-like or iterable object.
143
+ */
144
+ const from = _Array.from;
145
+
146
+ /**
147
+ * Returns the data type of the target.
148
+ * Uses native `typeof` operator, however, makes distinction between `null`, `array`, and `object`.
149
+ * Also, when classes are registered via `registerClass`, it checks if objects are instance of any known registered class.
150
+ *
151
+ * @param target - The target to get the data type of.
152
+ * @returns The data type of the target.
153
+ */
154
+ const getType = (target) => {
155
+ if (target === null)
156
+ return 'null';
157
+ const nativeDataType = typeof target;
158
+ if (nativeDataType === 'object') {
159
+ if (isArray(target))
160
+ return 'array';
161
+ for (const registeredClass of registeredClasses) {
162
+ if (target instanceof registeredClass)
163
+ return registeredClass.name;
164
+ }
165
+ }
166
+ return nativeDataType;
167
+ };
168
+
169
+ /**
170
+ * Safe copies of Map built-in via factory function.
171
+ *
172
+ * Since constructors cannot be safely captured via Object.assign, this module
173
+ * provides a factory function that uses Reflect.construct internally.
174
+ *
175
+ * These references are captured at module initialization time to protect against
176
+ * prototype pollution attacks. Import only what you need for tree-shaking.
177
+ *
178
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
179
+ */
180
+ // Capture references at module initialization time
181
+ const _Map = globalThis.Map;
182
+ const _Reflect = globalThis.Reflect;
183
+ /**
184
+ * (Safe copy) Creates a new Map using the captured Map constructor.
185
+ * Use this instead of `new Map()`.
186
+ *
187
+ * @param iterable - Optional iterable of key-value pairs.
188
+ * @returns A new Map instance.
189
+ */
190
+ const createMap = (iterable) => _Reflect.construct(_Map, iterable ? [iterable] : []);
191
+
192
+ /* eslint-disable @typescript-eslint/no-explicit-any */
193
+ /**
194
+ * Creates a wrapper function that only executes the wrapped function if the condition function returns true.
195
+ *
196
+ * @param func - The function to be conditionally executed.
197
+ * @param conditionFunc - A function that returns a boolean, determining if `func` should be executed.
198
+ * @returns A wrapped version of `func` that executes conditionally.
199
+ */
200
+ function createConditionalExecutionFunction(func, conditionFunc) {
201
+ return function (...args) {
202
+ if (conditionFunc()) {
203
+ return func(...args);
204
+ }
205
+ };
206
+ }
207
+
208
+ /* eslint-disable @typescript-eslint/no-explicit-any */
209
+ /**
210
+ * Creates a wrapper function that silently ignores any errors thrown by the wrapped void function.
211
+ * This function is specifically for wrapping functions that do not return a value (void functions).
212
+ * Exceptions are swallowed without any logging or handling.
213
+ *
214
+ * @param func - The void function to be wrapped.
215
+ * @returns A wrapped version of the input function that ignores errors.
216
+ */
217
+ function createErrorIgnoringFunction(func) {
218
+ return function (...args) {
219
+ try {
220
+ func(...args);
221
+ }
222
+ catch {
223
+ // Deliberately swallowing/ignoring the exception
224
+ }
225
+ };
226
+ }
227
+
228
+ /* eslint-disable @typescript-eslint/no-unused-vars */
229
+ /**
230
+ * A no-operation function (noop) that does nothing regardless of the arguments passed.
231
+ * It is designed to be as permissive as possible in its typing without using the `Function` keyword.
232
+ *
233
+ * @param args - Any arguments passed to the function (ignored)
234
+ */
235
+ const noop = (...args) => {
236
+ // Intentionally does nothing
237
+ };
238
+
239
+ const logLevels = ['none', 'error', 'warn', 'log', 'info', 'debug'];
240
+ const priority = {
241
+ error: 4,
242
+ warn: 3,
243
+ log: 2,
244
+ info: 1,
245
+ debug: 0,
246
+ };
247
+ /**
248
+ * Validates whether a given string is a valid log level.
249
+ *
250
+ * @param level - The log level to validate
251
+ * @returns True if the level is valid, false otherwise
252
+ */
253
+ function isValidLogLevel(level) {
254
+ return logLevels.includes(level);
255
+ }
256
+ /**
257
+ * Creates a log level configuration manager for controlling logging behavior.
258
+ * Provides methods to get, set, and evaluate log levels based on priority.
259
+ *
260
+ * @param level - The initial log level (defaults to 'error')
261
+ * @returns A configuration object with log level management methods
262
+ * @throws {Error} When the provided level is not a valid log level
263
+ */
264
+ function createLogLevelConfig(level = 'error') {
265
+ if (!isValidLogLevel(level)) {
266
+ throw createError('Cannot create log level configuration with a valid default log level');
267
+ }
268
+ const state = { level };
269
+ const getLogLevel = () => state.level;
270
+ const setLogLevel = (level) => {
271
+ if (!isValidLogLevel(level)) {
272
+ throw createError(`Cannot set value '${level}' level. Expected levels are ${logLevels}.`);
273
+ }
274
+ state.level = level;
275
+ };
276
+ const shouldLog = (level) => {
277
+ if (state.level === 'none' || level === 'none' || !isValidLogLevel(level)) {
278
+ return false;
279
+ }
280
+ return priority[level] >= priority[state.level];
281
+ };
282
+ return freeze({
283
+ getLogLevel,
284
+ setLogLevel,
285
+ shouldLog,
286
+ });
287
+ }
288
+
289
+ /**
290
+ * Creates a logger instance with configurable log level filtering.
291
+ * Each log function is wrapped to respect the current log level setting.
292
+ *
293
+ * @param error - Function to handle error-level logs (required)
294
+ * @param warn - Function to handle warning-level logs (optional, defaults to noop)
295
+ * @param log - Function to handle standard logs (optional, defaults to noop)
296
+ * @param info - Function to handle info-level logs (optional, defaults to noop)
297
+ * @param debug - Function to handle debug-level logs (optional, defaults to noop)
298
+ * @returns A frozen logger object with log methods and level control
299
+ * @throws {ErrorLevelFn} When any provided log function is invalid
300
+ */
301
+ function createLogger(error, warn = noop, log = noop, info = noop, debug = noop) {
302
+ if (notValidLogFn(error)) {
303
+ throw createError(notFnMsg('error'));
304
+ }
305
+ if (notValidLogFn(warn)) {
306
+ throw createError(notFnMsg('warn'));
307
+ }
308
+ if (notValidLogFn(log)) {
309
+ throw createError(notFnMsg('log'));
310
+ }
311
+ if (notValidLogFn(info)) {
312
+ throw createError(notFnMsg('info'));
313
+ }
314
+ if (notValidLogFn(debug)) {
315
+ throw createError(notFnMsg('debug'));
316
+ }
317
+ const { setLogLevel, getLogLevel, shouldLog } = createLogLevelConfig();
318
+ const wrapLogFn = (fn, level) => {
319
+ if (fn === noop)
320
+ return fn;
321
+ const condition = () => shouldLog(level);
322
+ return createConditionalExecutionFunction(createErrorIgnoringFunction(fn), condition);
323
+ };
324
+ return freeze({
325
+ error: wrapLogFn(error, 'error'),
326
+ warn: wrapLogFn(warn, 'warn'),
327
+ log: wrapLogFn(log, 'log'),
328
+ info: wrapLogFn(info, 'info'),
329
+ debug: wrapLogFn(debug, 'debug'),
330
+ setLogLevel,
331
+ getLogLevel,
332
+ });
333
+ }
334
+ /**
335
+ * Validates whether a given value is a valid log function.
336
+ *
337
+ * @param fn - The value to validate
338
+ * @returns True if the value is not a function (invalid), false if it is valid
339
+ */
340
+ function notValidLogFn(fn) {
341
+ return getType(fn) !== 'function' && fn !== noop;
342
+ }
343
+ /**
344
+ * Generates an error message for invalid log function parameters.
345
+ *
346
+ * @param label - The name of the log function that failed validation
347
+ * @returns A formatted error message string
348
+ */
349
+ function notFnMsg(label) {
350
+ return `Cannot create a logger when ${label} is not a function`;
351
+ }
352
+
353
+ /**
354
+ * Safe copies of Console built-in methods.
355
+ *
356
+ * These references are captured at module initialization time to protect against
357
+ * prototype pollution attacks. Import only what you need for tree-shaking.
358
+ *
359
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/console
360
+ */
361
+ // Capture references at module initialization time
362
+ const _console = globalThis.console;
363
+ /**
364
+ * (Safe copy) Outputs a message to the console.
365
+ */
366
+ const log = _console.log.bind(_console);
367
+ /**
368
+ * (Safe copy) Outputs a warning message to the console.
369
+ */
370
+ const warn = _console.warn.bind(_console);
371
+ /**
372
+ * (Safe copy) Outputs an error message to the console.
373
+ */
374
+ const error = _console.error.bind(_console);
375
+ /**
376
+ * (Safe copy) Outputs an informational message to the console.
377
+ */
378
+ const info = _console.info.bind(_console);
379
+ /**
380
+ * (Safe copy) Outputs a debug message to the console.
381
+ */
382
+ const debug = _console.debug.bind(_console);
383
+ /**
384
+ * (Safe copy) Outputs a stack trace to the console.
385
+ */
386
+ _console.trace.bind(_console);
387
+ /**
388
+ * (Safe copy) Displays an interactive listing of the properties of a specified object.
389
+ */
390
+ _console.dir.bind(_console);
391
+ /**
392
+ * (Safe copy) Displays tabular data as a table.
393
+ */
394
+ _console.table.bind(_console);
395
+ /**
396
+ * (Safe copy) Writes an error message to the console if the assertion is false.
397
+ */
398
+ _console.assert.bind(_console);
399
+ /**
400
+ * (Safe copy) Clears the console.
401
+ */
402
+ _console.clear.bind(_console);
403
+ /**
404
+ * (Safe copy) Logs the number of times that this particular call to count() has been called.
405
+ */
406
+ _console.count.bind(_console);
407
+ /**
408
+ * (Safe copy) Resets the counter used with console.count().
409
+ */
410
+ _console.countReset.bind(_console);
411
+ /**
412
+ * (Safe copy) Creates a new inline group in the console.
413
+ */
414
+ _console.group.bind(_console);
415
+ /**
416
+ * (Safe copy) Creates a new inline group in the console that is initially collapsed.
417
+ */
418
+ _console.groupCollapsed.bind(_console);
419
+ /**
420
+ * (Safe copy) Exits the current inline group.
421
+ */
422
+ _console.groupEnd.bind(_console);
423
+ /**
424
+ * (Safe copy) Starts a timer with a name specified as an input parameter.
425
+ */
426
+ _console.time.bind(_console);
427
+ /**
428
+ * (Safe copy) Stops a timer that was previously started.
429
+ */
430
+ _console.timeEnd.bind(_console);
431
+ /**
432
+ * (Safe copy) Logs the current value of a timer that was previously started.
433
+ */
434
+ _console.timeLog.bind(_console);
435
+
436
+ const logger = createLogger(error, warn, log, info, debug);
437
+
438
+ /**
439
+ * Global log level registry.
440
+ * Tracks all created scoped loggers to allow global log level changes.
441
+ */
442
+ const loggerRegistry = createSet();
443
+ /** Redacted placeholder for sensitive values */
444
+ const REDACTED = '[REDACTED]';
445
+ /**
446
+ * Patterns that indicate a sensitive key name.
447
+ * Keys containing these patterns will have their values sanitized.
448
+ */
449
+ const SENSITIVE_KEY_PATTERNS = [
450
+ /token/i,
451
+ /key/i,
452
+ /password/i,
453
+ /secret/i,
454
+ /credential/i,
455
+ /auth/i,
456
+ /bearer/i,
457
+ /api[_-]?key/i,
458
+ /private/i,
459
+ /passphrase/i,
460
+ ];
461
+ /**
462
+ * Checks if a key name indicates sensitive data.
463
+ *
464
+ * @param key - Key name to check
465
+ * @returns True if the key indicates sensitive data
466
+ */
467
+ function isSensitiveKey(key) {
468
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
469
+ }
470
+ /**
471
+ * Sanitizes an object by replacing sensitive values with REDACTED.
472
+ * This function recursively processes nested objects and arrays.
473
+ *
474
+ * @param obj - Object to sanitize
475
+ * @returns New object with sensitive values redacted
476
+ */
477
+ function sanitize(obj) {
478
+ if (obj === null || obj === undefined) {
479
+ return obj;
480
+ }
481
+ if (isArray(obj)) {
482
+ return obj.map((item) => sanitize(item));
483
+ }
484
+ if (typeof obj === 'object') {
485
+ const result = {};
486
+ for (const [key, value] of entries(obj)) {
487
+ if (isSensitiveKey(key)) {
488
+ result[key] = REDACTED;
489
+ }
490
+ else if (typeof value === 'object' && value !== null) {
491
+ result[key] = sanitize(value);
492
+ }
493
+ else {
494
+ result[key] = value;
495
+ }
496
+ }
497
+ return result;
498
+ }
499
+ return obj;
500
+ }
501
+ /**
502
+ * Formats a log message with optional metadata.
503
+ *
504
+ * @param namespace - Logger namespace prefix
505
+ * @param message - Log message
506
+ * @param meta - Optional metadata object
507
+ * @returns Formatted log string
508
+ */
509
+ function formatMessage(namespace, message, meta) {
510
+ const prefix = `[${namespace}]`;
511
+ if (meta && keys(meta).length > 0) {
512
+ const sanitizedMeta = sanitize(meta);
513
+ return `${prefix} ${message} ${stringify(sanitizedMeta)}`;
514
+ }
515
+ return `${prefix} ${message}`;
516
+ }
517
+ /**
518
+ * Creates a scoped logger with namespace prefix and optional secret sanitization.
519
+ * All log messages will be prefixed with [namespace] and sensitive metadata
520
+ * values will be automatically redacted.
521
+ *
522
+ * @param namespace - Logger namespace (e.g., 'project-scope', 'analyze')
523
+ * @param options - Logger configuration options
524
+ * @returns A configured scoped logger instance
525
+ *
526
+ * @example
527
+ * ```typescript
528
+ * const logger = createScopedLogger('project-scope')
529
+ * logger.setLogLevel('debug')
530
+ *
531
+ * // Basic logging
532
+ * logger.info('Starting analysis', { path: './project' })
533
+ *
534
+ * // Sensitive data is automatically redacted
535
+ * logger.debug('Config loaded', { apiKey: 'secret123' })
536
+ * // Output: [project-scope] Config loaded {"apiKey":"[REDACTED]"}
537
+ * ```
538
+ */
539
+ function createScopedLogger(namespace, options = {}) {
540
+ const { level = 'error', sanitizeSecrets = true } = options;
541
+ // Create wrapper functions that add namespace prefix and sanitization
542
+ const createLogFn = (baseFn) => (message, meta) => {
543
+ const processedMeta = sanitizeSecrets && meta ? sanitize(meta) : meta;
544
+ baseFn(formatMessage(namespace, message, processedMeta));
545
+ };
546
+ // Create base logger with wrapped functions
547
+ const baseLogger = createLogger(createLogFn(error), createLogFn(warn), createLogFn(log), createLogFn(info), createLogFn(debug));
548
+ // Set initial log level (use global override if set)
549
+ baseLogger.setLogLevel(level);
550
+ const scopedLogger = freeze({
551
+ error: (message, meta) => baseLogger.error(message, meta),
552
+ warn: (message, meta) => baseLogger.warn(message, meta),
553
+ log: (message, meta) => baseLogger.log(message, meta),
554
+ info: (message, meta) => baseLogger.info(message, meta),
555
+ debug: (message, meta) => baseLogger.debug(message, meta),
556
+ setLogLevel: baseLogger.setLogLevel,
557
+ getLogLevel: baseLogger.getLogLevel,
558
+ });
559
+ // Register logger for global level management
560
+ loggerRegistry.add(scopedLogger);
561
+ return scopedLogger;
562
+ }
563
+ /**
564
+ * Default logger instance for the project-scope library.
565
+ * Use this for general logging within the library.
566
+ *
567
+ * @example
568
+ * ```typescript
569
+ * import { logger } from '@hyperfrontend/project-scope/core'
570
+ *
571
+ * logger.setLogLevel('debug')
572
+ * logger.debug('Analyzing project', { path: './src' })
573
+ * ```
574
+ */
575
+ createScopedLogger('project-scope');
576
+
577
+ createScopedLogger('project-scope:fs');
578
+ /**
579
+ * Create a file system error with code and context.
580
+ *
581
+ * @param message - The error message describing what went wrong
582
+ * @param code - The category code for this type of filesystem failure
583
+ * @param context - Additional context including path, operation, and cause
584
+ * @returns A configured Error object with code and context properties
585
+ */
586
+ function createFileSystemError(message, code, context) {
587
+ const error = createError(message);
588
+ defineProperties(error, {
589
+ code: { value: code, enumerable: true },
590
+ context: { value: context, enumerable: true },
591
+ });
592
+ return error;
593
+ }
594
+
595
+ const fsWriteLogger = createScopedLogger('project-scope:fs:write');
596
+ /**
597
+ * Ensure directory exists, create recursively if not.
598
+ *
599
+ * @param dirPath - Directory path to ensure exists
600
+ */
601
+ function ensureDir(dirPath) {
602
+ if (!node_fs.existsSync(dirPath)) {
603
+ fsWriteLogger.debug('Creating directory recursively', { path: dirPath });
604
+ node_fs.mkdirSync(dirPath, { recursive: true });
605
+ }
606
+ }
607
+
608
+ /**
609
+ * Get file stats with error handling.
610
+ *
611
+ * @param filePath - Path to file
612
+ * @param followSymlinks - Whether to follow symlinks (default: true)
613
+ * @returns File stats or null if path doesn't exist
614
+ */
615
+ function getFileStat(filePath, followSymlinks = true) {
616
+ if (!node_fs.existsSync(filePath)) {
617
+ return null;
618
+ }
619
+ try {
620
+ const stat = followSymlinks ? node_fs.statSync(filePath) : node_fs.lstatSync(filePath);
621
+ return {
622
+ isFile: stat.isFile(),
623
+ isDirectory: stat.isDirectory(),
624
+ isSymlink: stat.isSymbolicLink(),
625
+ size: stat.size,
626
+ created: stat.birthtime,
627
+ modified: stat.mtime,
628
+ accessed: stat.atime,
629
+ mode: stat.mode,
630
+ };
631
+ }
632
+ catch {
633
+ return null;
634
+ }
635
+ }
636
+ /**
637
+ * Check if path is a file.
638
+ *
639
+ * @param filePath - Path to check
640
+ * @returns True if path is a file
641
+ */
642
+ function isFile(filePath) {
643
+ const stats = getFileStat(filePath);
644
+ return stats?.isFile ?? false;
645
+ }
646
+ /**
647
+ * Check if path is a directory.
648
+ *
649
+ * @param dirPath - Path to check
650
+ * @returns True if path is a directory
651
+ */
652
+ function isDirectory(dirPath) {
653
+ const stats = getFileStat(dirPath);
654
+ return stats?.isDirectory ?? false;
655
+ }
656
+ /**
657
+ * Check if path exists.
658
+ *
659
+ * @param filePath - Path to check
660
+ * @returns True if path exists
661
+ */
662
+ function exists(filePath) {
663
+ return node_fs.existsSync(filePath);
664
+ }
665
+
666
+ const fsDirLogger = createScopedLogger('project-scope:fs:dir');
667
+ /**
668
+ * List immediate contents of a directory.
669
+ *
670
+ * @param dirPath - Absolute or relative path to the directory
671
+ * @returns Array of entries with metadata for each file/directory
672
+ * @throws {Error} If directory doesn't exist or isn't a directory
673
+ *
674
+ * @example
675
+ * ```typescript
676
+ * import { readDirectory } from '@hyperfrontend/project-scope'
677
+ *
678
+ * const entries = readDirectory('./src')
679
+ * for (const entry of entries) {
680
+ * console.log(entry.name, entry.isFile ? 'file' : 'directory')
681
+ * }
682
+ * ```
683
+ */
684
+ function readDirectory(dirPath) {
685
+ fsDirLogger.debug('Reading directory', { path: dirPath });
686
+ if (!node_fs.existsSync(dirPath)) {
687
+ fsDirLogger.debug('Directory not found', { path: dirPath });
688
+ throw createFileSystemError(`Directory not found: ${dirPath}`, 'FS_NOT_FOUND', { path: dirPath, operation: 'readdir' });
689
+ }
690
+ if (!isDirectory(dirPath)) {
691
+ fsDirLogger.debug('Path is not a directory', { path: dirPath });
692
+ throw createFileSystemError(`Not a directory: ${dirPath}`, 'FS_NOT_A_DIRECTORY', { path: dirPath, operation: 'readdir' });
693
+ }
694
+ try {
695
+ const entries = node_fs.readdirSync(dirPath, { withFileTypes: true });
696
+ fsDirLogger.debug('Directory read complete', { path: dirPath, entryCount: entries.length });
697
+ return entries.map((entry) => ({
698
+ name: entry.name,
699
+ path: node_path.join(dirPath, entry.name),
700
+ isFile: entry.isFile(),
701
+ isDirectory: entry.isDirectory(),
702
+ isSymlink: entry.isSymbolicLink(),
703
+ }));
704
+ }
705
+ catch (error) {
706
+ fsDirLogger.warn('Failed to read directory', { path: dirPath, error: error instanceof Error ? error.message : String(error) });
707
+ throw createFileSystemError(`Failed to read directory: ${dirPath}`, 'FS_READ_ERROR', {
708
+ path: dirPath,
709
+ operation: 'readdir',
710
+ cause: error,
711
+ });
712
+ }
713
+ }
714
+
715
+ /**
716
+ * Normalize path separators to forward slashes.
717
+ *
718
+ * @param filePath - Path to normalize
719
+ * @returns Normalized path with forward slashes
720
+ */
721
+ function normalizePath(filePath) {
722
+ if (!filePath)
723
+ return '';
724
+ // Normalize path and convert backslashes to forward slashes
725
+ const normalized = node_path.normalize(filePath);
726
+ return node_path.sep === '\\' ? normalized.replace(/\\/g, '/') : normalized;
727
+ }
728
+ /**
729
+ * Strip any trailing forward or back slashes from a path.
730
+ *
731
+ * @param filePath - Path that may have trailing slashes
732
+ * @returns Path with trailing slashes removed
733
+ */
734
+ function removeTrailingSlash(filePath) {
735
+ let i = filePath.length;
736
+ while (i > 0 && (filePath[i - 1] === '/' || filePath[i - 1] === '\\')) {
737
+ i--;
738
+ }
739
+ return filePath.slice(0, i);
740
+ }
741
+
742
+ /**
743
+ * Resolve path segments to an absolute path.
744
+ *
745
+ * @param segments - Path segments to resolve
746
+ * @returns Resolved absolute path with normalized separators
747
+ */
748
+ function resolvePath(...segments) {
749
+ return normalizePath(node_path.resolve(...segments));
750
+ }
751
+ /**
752
+ * Compute the normalized path from source directory to target.
753
+ *
754
+ * @param from - Source path (base directory)
755
+ * @param to - Target path to reach
756
+ * @returns Relative path from source to target with forward slashes
757
+ */
758
+ function relativePath(from, to) {
759
+ return normalizePath(node_path.relative(from, to));
760
+ }
761
+ /**
762
+ * Join path segments.
763
+ *
764
+ * @param segments - Path segments to join
765
+ * @returns Joined path with normalized separators
766
+ */
767
+ function joinPath(...segments) {
768
+ return normalizePath(node_path.join(...segments));
769
+ }
770
+ /**
771
+ * Check if path is absolute.
772
+ *
773
+ * @param filePath - Path to check
774
+ * @returns True if path is absolute
775
+ */
776
+ function isAbsolute(filePath) {
777
+ return node_path.isAbsolute(filePath);
778
+ }
779
+
780
+ /**
781
+ * Get directory name of path.
782
+ *
783
+ * @param filePath - Path to extract directory from
784
+ * @returns Directory name
785
+ */
786
+ function getDirname(filePath) {
787
+ return normalizePath(node_path.dirname(filePath));
788
+ }
789
+
790
+ createScopedLogger('project-scope:fs:traversal');
791
+
792
+ createScopedLogger('project-scope:project:package');
793
+
794
+ createScopedLogger('project-scope:heuristics:deps');
795
+
796
+ /**
797
+ * Global registry of all caches for bulk operations.
798
+ */
799
+ const cacheRegistry = createSet();
800
+ /**
801
+ * Create a cache with optional TTL and size limits.
802
+ *
803
+ * The cache provides a simple key-value store with:
804
+ * - Optional TTL (time-to-live) for automatic expiration
805
+ * - Optional maxSize for limiting cache size with FIFO eviction
806
+ * - Lazy expiration (entries are checked on access)
807
+ *
808
+ * @param options - Cache configuration options
809
+ * @returns Cache instance
810
+ *
811
+ * @example
812
+ * ```typescript
813
+ * // Basic cache
814
+ * const cache = createCache<string, number>()
815
+ * cache.set('answer', 42)
816
+ * cache.get('answer') // 42
817
+ *
818
+ * // Cache with TTL (expires after 60 seconds)
819
+ * const ttlCache = createCache<string, object>({ ttl: 60000 })
820
+ *
821
+ * // Cache with max size (evicts oldest when full)
822
+ * const lruCache = createCache<string, object>({ maxSize: 100 })
823
+ *
824
+ * // Combined options
825
+ * const configCache = createCache<string, object>({
826
+ * ttl: 30000,
827
+ * maxSize: 50
828
+ * })
829
+ * ```
830
+ */
831
+ function createCache$1(options) {
832
+ const { ttl, maxSize } = options ?? {};
833
+ const store = createMap();
834
+ // Track insertion order for FIFO eviction
835
+ const insertionOrder = [];
836
+ /**
837
+ * Check if an entry is expired.
838
+ *
839
+ * @param entry - Cache entry to check
840
+ * @returns True if entry is expired
841
+ */
842
+ function isExpired(entry) {
843
+ if (ttl === undefined)
844
+ return false;
845
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
846
+ return Date.now() - entry.timestamp > ttl;
847
+ }
848
+ /**
849
+ * Evict oldest entries to make room for new ones.
850
+ */
851
+ function evictIfNeeded() {
852
+ if (maxSize === undefined)
853
+ return;
854
+ while (store.size >= maxSize && insertionOrder.length > 0) {
855
+ const oldestKey = insertionOrder.shift();
856
+ if (oldestKey !== undefined) {
857
+ store.delete(oldestKey);
858
+ }
859
+ }
860
+ }
861
+ /**
862
+ * Remove key from insertion order tracking.
863
+ *
864
+ * @param key - Key to remove from order tracking
865
+ */
866
+ function removeFromOrder(key) {
867
+ const index = insertionOrder.indexOf(key);
868
+ if (index !== -1) {
869
+ insertionOrder.splice(index, 1);
870
+ }
871
+ }
872
+ const cache = {
873
+ get(key) {
874
+ const entry = store.get(key);
875
+ if (!entry)
876
+ return undefined;
877
+ if (isExpired(entry)) {
878
+ store.delete(key);
879
+ removeFromOrder(key);
880
+ return undefined;
881
+ }
882
+ return entry.value;
883
+ },
884
+ set(key, value) {
885
+ // If key exists, remove from order first
886
+ if (store.has(key)) {
887
+ removeFromOrder(key);
888
+ }
889
+ else {
890
+ // Evict if needed before adding new entry
891
+ evictIfNeeded();
892
+ }
893
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
894
+ store.set(key, { value, timestamp: Date.now() });
895
+ insertionOrder.push(key);
896
+ },
897
+ has(key) {
898
+ const entry = store.get(key);
899
+ if (!entry)
900
+ return false;
901
+ if (isExpired(entry)) {
902
+ store.delete(key);
903
+ removeFromOrder(key);
904
+ return false;
905
+ }
906
+ return true;
907
+ },
908
+ delete(key) {
909
+ removeFromOrder(key);
910
+ return store.delete(key);
911
+ },
912
+ clear() {
913
+ store.clear();
914
+ insertionOrder.length = 0;
915
+ },
916
+ size() {
917
+ return store.size;
918
+ },
919
+ keys() {
920
+ return [...insertionOrder];
921
+ },
922
+ };
923
+ // Register cache for global operations
924
+ cacheRegistry.add(cache);
925
+ return freeze(cache);
926
+ }
927
+
928
+ createScopedLogger('project-scope:project:walk');
929
+
930
+ createScopedLogger('project-scope:project:search');
931
+
932
+ createScopedLogger('project-scope:heuristics:entry-points');
933
+ /**
934
+ * Cache for entry point discovery results.
935
+ * TTL: 60 seconds (entry points are relatively stable)
936
+ */
937
+ createCache$1({ ttl: 60000, maxSize: 50 });
938
+
939
+ createScopedLogger('project-scope:tech');
940
+ /**
941
+ * Cache for tech detection results.
942
+ * TTL: 60 seconds (tech stack can change during active development)
943
+ */
944
+ createCache$1({ ttl: 60000, maxSize: 50 });
945
+
946
+ createScopedLogger('project-scope:heuristics:project-type');
947
+
948
+ createScopedLogger('project-scope:root');
949
+
950
+ createScopedLogger('project-scope:nx');
951
+
952
+ createScopedLogger('project-scope:nx:devkit');
953
+
954
+ createScopedLogger('project-scope:nx:config');
955
+
956
+ createScopedLogger('project-scope:config');
957
+ /**
958
+ * Cache for config detection results.
959
+ * TTL: 30 seconds (configs can change frequently during setup)
960
+ */
961
+ createCache$1({ ttl: 30000, maxSize: 50 });
962
+
963
+ /**
964
+ * Safe copies of Number built-in methods and constants.
965
+ *
966
+ * These references are captured at module initialization time to protect against
967
+ * prototype pollution attacks. Import only what you need for tree-shaking.
968
+ *
969
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/number
970
+ */
971
+ // Capture references at module initialization time
972
+ const _parseInt = globalThis.parseInt;
973
+ const _isNaN = globalThis.isNaN;
974
+ // ============================================================================
975
+ // Parsing
976
+ // ============================================================================
977
+ /**
978
+ * (Safe copy) Parses a string and returns an integer.
979
+ */
980
+ const parseInt = _parseInt;
981
+ // ============================================================================
982
+ // Global Type Checking (legacy, less strict)
983
+ // ============================================================================
984
+ /**
985
+ * (Safe copy) Global isNaN function (coerces to number first, less strict than Number.isNaN).
986
+ */
987
+ const globalIsNaN = _isNaN;
988
+
989
+ /** Logger for analysis operations */
990
+ createScopedLogger('project-scope:analyze');
991
+
992
+ /** Logger for CLI operations */
993
+ createScopedLogger('project-scope:cli');
994
+
995
+ createScopedLogger('project-scope:encoding');
996
+
997
+ createScopedLogger('project-scope:encoding:convert');
998
+
999
+ createScopedLogger('project-scope:heuristics:framework');
1000
+ /**
1001
+ * Cache for framework identification results.
1002
+ * TTL: 60 seconds (frameworks are stable but can change during development)
1003
+ */
1004
+ createCache$1({ ttl: 60000, maxSize: 50 });
1005
+
1006
+ /**
1007
+ * Write mode for file operations.
1008
+ */
1009
+ const Mode = freeze({
1010
+ /** Overwrite existing files */
1011
+ Overwrite: 'overwrite',
1012
+ /** Fail if file exists */
1013
+ ExclusiveCreate: 'exclusive',
1014
+ /** Skip if file exists */
1015
+ SkipIfExists: 'skip',
1016
+ });
1017
+
1018
+ const fsTreeLogger = createScopedLogger('project-scope:vfs:tree');
1019
+ /**
1020
+ * Create a file system-backed tree implementation.
1021
+ *
1022
+ * Supports transactional modifications - all changes are buffered
1023
+ * in memory and can be committed atomically or rolled back.
1024
+ *
1025
+ * @param root - Absolute path to the workspace root directory
1026
+ * @param options - Configuration for verbose logging
1027
+ * @returns A Tree instance
1028
+ */
1029
+ function createFsTree(root, options) {
1030
+ const _root = removeTrailingSlash(normalizePath(root));
1031
+ const _changes = createMap();
1032
+ const _isVerbose = false;
1033
+ const _followSymlinks = true;
1034
+ fsTreeLogger.debug('Creating VFS tree', { root: _root, verbose: _isVerbose, followSymlinks: _followSymlinks });
1035
+ /**
1036
+ * Normalize path to be relative from root.
1037
+ *
1038
+ * @param filePath - Path to normalize
1039
+ * @returns Normalized relative path
1040
+ * @throws {Error} if path traverses outside the tree root
1041
+ */
1042
+ function normalizeFilePath(filePath) {
1043
+ const normalized = isAbsolute(filePath) ? relativePath(_root, filePath) : normalizePath(filePath);
1044
+ const absoluteResolved = resolvePath(_root, normalized);
1045
+ if (!absoluteResolved.startsWith(_root + '/') && absoluteResolved !== _root) {
1046
+ throw createError(`Path escapes tree root: ${filePath}`);
1047
+ }
1048
+ return normalized;
1049
+ }
1050
+ /**
1051
+ * Get absolute path on disk.
1052
+ *
1053
+ * @param filePath - Relative path from root
1054
+ * @returns Absolute path on disk
1055
+ */
1056
+ function absolutePath(filePath) {
1057
+ return joinPath(_root, normalizeFilePath(filePath));
1058
+ }
1059
+ /**
1060
+ * Check if a normalized path is a symbolic link.
1061
+ *
1062
+ * @param normalPath - Already normalized path
1063
+ * @returns True if path is a symlink
1064
+ */
1065
+ function isSymlinkNormalizedPath(normalPath) {
1066
+ const absPath = absolutePath(normalPath);
1067
+ try {
1068
+ const stats = node_fs.lstatSync(absPath);
1069
+ return stats.isSymbolicLink();
1070
+ }
1071
+ catch {
1072
+ return false;
1073
+ }
1074
+ }
1075
+ /**
1076
+ * Validate that a symlink target stays within tree bounds.
1077
+ *
1078
+ * @param normalPath - Already normalized path to symlink
1079
+ * @throws {Error} If symlink target escapes tree root or followSymlinks is disabled
1080
+ */
1081
+ function validateSymlink(normalPath) {
1082
+ const absPath = absolutePath(normalPath);
1083
+ if (!isSymlinkNormalizedPath(normalPath)) {
1084
+ return;
1085
+ }
1086
+ try {
1087
+ const target = node_fs.readlinkSync(absPath);
1088
+ let targetAbsolute;
1089
+ if (isAbsolute(target)) {
1090
+ targetAbsolute = target;
1091
+ }
1092
+ else {
1093
+ const symlinkDir = getDirname(absPath);
1094
+ targetAbsolute = resolvePath(symlinkDir, target);
1095
+ }
1096
+ const normalizedTarget = normalizePath(targetAbsolute);
1097
+ if (!normalizedTarget.startsWith(_root + '/') && normalizedTarget !== _root) {
1098
+ throw createError(`Symlink target escapes tree root: ${normalPath} -> ${target}`);
1099
+ }
1100
+ }
1101
+ catch (error) {
1102
+ /* istanbul ignore else -- other errors are rare edge cases (e.g., permission denied) */
1103
+ if (error instanceof Error && error.message.includes('Symlink target escapes')) {
1104
+ throw error;
1105
+ }
1106
+ if (error instanceof Error && error.message.includes('followSymlinks is disabled')) {
1107
+ throw error;
1108
+ }
1109
+ throw createError(`Failed to validate symlink: ${normalPath}`);
1110
+ }
1111
+ }
1112
+ /**
1113
+ * Check if path exists on disk (not considering buffered changes).
1114
+ *
1115
+ * @param normalPath - Normalized path to check
1116
+ * @returns True if exists on disk
1117
+ */
1118
+ function existsOnDisk(normalPath) {
1119
+ const absPath = absolutePath(normalPath);
1120
+ return exists(absPath);
1121
+ }
1122
+ /**
1123
+ * Read from disk (not considering buffered changes).
1124
+ *
1125
+ * @param normalPath - Normalized path to read
1126
+ * @returns File content or null
1127
+ */
1128
+ function readFromDisk(normalPath) {
1129
+ validateSymlink(normalPath);
1130
+ const absPath = absolutePath(normalPath);
1131
+ if (!isFile(absPath)) {
1132
+ return null;
1133
+ }
1134
+ try {
1135
+ return node_fs.readFileSync(absPath);
1136
+ }
1137
+ catch {
1138
+ return null;
1139
+ }
1140
+ }
1141
+ const tree = {
1142
+ get root() {
1143
+ return _root;
1144
+ },
1145
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1146
+ read(filePath, encoding) {
1147
+ const normalPath = normalizeFilePath(filePath);
1148
+ const change = _changes.get(normalPath);
1149
+ if (change) {
1150
+ if (change.type === 'DELETE') {
1151
+ return null;
1152
+ }
1153
+ if (change.content !== null) {
1154
+ return encoding ? change.content.toString(encoding) : change.content;
1155
+ }
1156
+ }
1157
+ validateSymlink(normalPath);
1158
+ const absPath = absolutePath(normalPath);
1159
+ if (!exists(absPath)) {
1160
+ return null;
1161
+ }
1162
+ if (!isFile(absPath)) {
1163
+ return null;
1164
+ }
1165
+ try {
1166
+ const content = node_fs.readFileSync(absPath);
1167
+ return encoding ? content.toString(encoding) : content;
1168
+ }
1169
+ catch {
1170
+ return null;
1171
+ }
1172
+ },
1173
+ write(filePath, content, options) {
1174
+ const normalPath = normalizeFilePath(filePath);
1175
+ const buffer = typeof content === 'string' ? Buffer.from(content, 'utf-8') : content;
1176
+ fsTreeLogger.debug('write', { path: normalPath, size: buffer.length, mode: options?.mode ?? 'Overwrite' });
1177
+ const mode = options?.mode ?? Mode.Overwrite;
1178
+ if (mode === Mode.ExclusiveCreate && this.exists(normalPath)) {
1179
+ throw createError(`File already exists: ${normalPath}`);
1180
+ }
1181
+ if (mode === Mode.SkipIfExists && this.exists(normalPath)) {
1182
+ return;
1183
+ }
1184
+ const existingChange = _changes.get(normalPath);
1185
+ const diskExists = existsOnDisk(normalPath);
1186
+ let changeType;
1187
+ let originalContent = null;
1188
+ if (existingChange?.type === 'CREATE' || (!diskExists && !existingChange)) {
1189
+ changeType = 'CREATE';
1190
+ }
1191
+ else {
1192
+ changeType = 'UPDATE';
1193
+ originalContent = existingChange?.originalContent ?? readFromDisk(normalPath);
1194
+ }
1195
+ _changes.set(normalPath, {
1196
+ type: changeType,
1197
+ content: buffer,
1198
+ originalContent,
1199
+ permissions: options?.permissions,
1200
+ });
1201
+ },
1202
+ exists(filePath) {
1203
+ const normalPath = normalizeFilePath(filePath);
1204
+ const change = _changes.get(normalPath);
1205
+ if (change) {
1206
+ return change.type !== 'DELETE';
1207
+ }
1208
+ for (const [changedPath, record] of _changes) {
1209
+ if (record.type !== 'DELETE' && changedPath.startsWith(normalPath + '/')) {
1210
+ return true;
1211
+ }
1212
+ }
1213
+ return existsOnDisk(normalPath);
1214
+ },
1215
+ delete(filePath) {
1216
+ const normalPath = normalizeFilePath(filePath);
1217
+ fsTreeLogger.debug('delete', { path: normalPath });
1218
+ const existingChange = _changes.get(normalPath);
1219
+ if (existingChange?.type === 'CREATE') {
1220
+ _changes.delete(normalPath);
1221
+ return;
1222
+ }
1223
+ if (!existsOnDisk(normalPath)) {
1224
+ return;
1225
+ }
1226
+ _changes.set(normalPath, {
1227
+ type: 'DELETE',
1228
+ content: null,
1229
+ originalContent: readFromDisk(normalPath),
1230
+ });
1231
+ },
1232
+ rename(from, to) {
1233
+ const content = this.read(from);
1234
+ if (content === null) {
1235
+ throw createError(`Source file not found: ${from}`);
1236
+ }
1237
+ this.write(to, content);
1238
+ this.delete(from);
1239
+ },
1240
+ isFile(filePath) {
1241
+ const normalPath = normalizeFilePath(filePath);
1242
+ const change = _changes.get(normalPath);
1243
+ if (change) {
1244
+ return change.type !== 'DELETE';
1245
+ }
1246
+ const absPath = absolutePath(normalPath);
1247
+ return isFile(absPath);
1248
+ },
1249
+ isDirectory(filePath) {
1250
+ const normalPath = normalizeFilePath(filePath);
1251
+ for (const [changedPath, change] of _changes) {
1252
+ if (change.type !== 'DELETE' && changedPath.startsWith(normalPath + '/')) {
1253
+ return true;
1254
+ }
1255
+ }
1256
+ const absPath = absolutePath(normalPath);
1257
+ return isDirectory(absPath);
1258
+ },
1259
+ isSymlink(filePath) {
1260
+ const normalPath = normalizeFilePath(filePath);
1261
+ return isSymlinkNormalizedPath(normalPath);
1262
+ },
1263
+ children(dirPath) {
1264
+ const normalPath = normalizeFilePath(dirPath);
1265
+ const childSet = createSet();
1266
+ const absPath = absolutePath(normalPath);
1267
+ try {
1268
+ if (exists(absPath) && isDirectory(absPath)) {
1269
+ const entries = readDirectory(absPath);
1270
+ for (const entry of entries) {
1271
+ childSet.add(entry.name);
1272
+ }
1273
+ }
1274
+ }
1275
+ catch {
1276
+ // Directory doesn't exist on disk
1277
+ }
1278
+ const prefix = normalPath === '.' || normalPath === '' ? '' : normalPath + '/';
1279
+ for (const [changedPath, change] of _changes) {
1280
+ // Handle root-level files
1281
+ if (prefix === '') {
1282
+ const childName = changedPath.split('/')[0];
1283
+ if (change.type === 'DELETE' && !changedPath.includes('/')) {
1284
+ childSet.delete(childName);
1285
+ }
1286
+ else if (change.type !== 'DELETE') {
1287
+ childSet.add(childName);
1288
+ }
1289
+ continue;
1290
+ }
1291
+ if (!changedPath.startsWith(prefix)) {
1292
+ continue;
1293
+ }
1294
+ const relativePath = changedPath.slice(prefix.length);
1295
+ const childName = relativePath.split('/')[0];
1296
+ if (change.type === 'DELETE') {
1297
+ // Only remove if it's a direct child being deleted
1298
+ if (!relativePath.includes('/')) {
1299
+ childSet.delete(childName);
1300
+ }
1301
+ }
1302
+ else {
1303
+ childSet.add(childName);
1304
+ }
1305
+ }
1306
+ return from(childSet).sort();
1307
+ },
1308
+ listChanges() {
1309
+ const changes = [];
1310
+ for (const [path, record] of _changes) {
1311
+ changes.push({
1312
+ path,
1313
+ type: record.type,
1314
+ content: record.content ?? undefined,
1315
+ originalContent: record.originalContent ?? undefined,
1316
+ mode: record.permissions,
1317
+ });
1318
+ }
1319
+ return changes.sort((a, b) => a.path.localeCompare(b.path));
1320
+ },
1321
+ changePermissions(filePath, mode) {
1322
+ const normalPath = normalizeFilePath(filePath);
1323
+ if (!this.exists(normalPath)) {
1324
+ throw createError(`File not found: ${normalPath}`);
1325
+ }
1326
+ const existingChange = _changes.get(normalPath);
1327
+ if (existingChange) {
1328
+ existingChange.permissions = mode;
1329
+ }
1330
+ else {
1331
+ const content = readFromDisk(normalPath);
1332
+ _changes.set(normalPath, {
1333
+ type: 'UPDATE',
1334
+ content,
1335
+ originalContent: content,
1336
+ permissions: mode,
1337
+ });
1338
+ }
1339
+ },
1340
+ changeFile(filePath, transform) {
1341
+ const content = this.read(filePath);
1342
+ if (content === null) {
1343
+ throw createError(`File not found: ${filePath}`);
1344
+ }
1345
+ const newContent = transform(content);
1346
+ this.write(filePath, newContent);
1347
+ },
1348
+ clearChanges() {
1349
+ _changes.clear();
1350
+ },
1351
+ };
1352
+ return tree;
1353
+ }
1354
+
1355
+ const factoryLogger = createScopedLogger('project-scope:vfs:factory');
1356
+ /**
1357
+ * Create a virtual file system tree.
1358
+ *
1359
+ * @param root - Root directory path
1360
+ * @param options - Tree creation options
1361
+ * @returns A new Tree instance
1362
+ * @throws {Error} If root doesn't exist or isn't a directory
1363
+ *
1364
+ * @example
1365
+ * ```typescript
1366
+ * import { createTree } from '@hyperfrontend/project-scope'
1367
+ *
1368
+ * const tree = createTree('./my-project')
1369
+ *
1370
+ * // Read files from tree
1371
+ * const content = tree.read('src/index.ts', 'utf-8')
1372
+ *
1373
+ * // Make changes (buffered in memory)
1374
+ * tree.write('src/new-file.ts', 'export const x = 1')
1375
+ *
1376
+ * // List pending changes
1377
+ * console.log(tree.listChanges())
1378
+ * ```
1379
+ */
1380
+ function createTree(root, options) {
1381
+ const normalizedRoot = normalizePath(root);
1382
+ factoryLogger.debug('createTree', { root: normalizedRoot });
1383
+ // Validate root exists
1384
+ if (!exists(normalizedRoot)) {
1385
+ factoryLogger.warn('createTree failed: root does not exist', { root: normalizedRoot });
1386
+ throw createError(`Root directory does not exist: ${normalizedRoot}`);
1387
+ }
1388
+ // Validate root is a directory
1389
+ if (!isDirectory(normalizedRoot)) {
1390
+ factoryLogger.warn('createTree failed: root is not a directory', { root: normalizedRoot });
1391
+ throw createError(`Root path is not a directory: ${normalizedRoot}`);
1392
+ }
1393
+ return createFsTree(normalizedRoot);
1394
+ }
1395
+
1396
+ const vfsLogger = createScopedLogger('project-scope:vfs');
1397
+ /**
1398
+ * Commit buffered changes to disk.
1399
+ *
1400
+ * @param tree - Virtual file system tree with pending modifications
1401
+ * @param options - Configuration for dry-run and verbosity
1402
+ * @returns Result of the commit operation
1403
+ *
1404
+ * @example
1405
+ * ```typescript
1406
+ * import { createTree, commitChanges } from '@hyperfrontend/project-scope'
1407
+ *
1408
+ * const tree = createTree('./my-project')
1409
+ * tree.write('src/new-file.ts', 'export const hello = "world"')
1410
+ *
1411
+ * // Preview changes without writing
1412
+ * const preview = commitChanges(tree, { dryRun: true })
1413
+ * console.log('Would create:', preview.created, 'files')
1414
+ *
1415
+ * // Actually commit changes
1416
+ * const result = commitChanges(tree)
1417
+ * console.log('Created:', result.created, 'Updated:', result.updated)
1418
+ * ```
1419
+ */
1420
+ function commitChanges(tree, options) {
1421
+ const changes = tree.listChanges();
1422
+ const appliedChanges = [];
1423
+ // Set log level based on verbose option
1424
+ if (options?.verbose) {
1425
+ vfsLogger.setLogLevel('debug');
1426
+ }
1427
+ vfsLogger.debug('Committing changes', { changeCount: changes.length, dryRun: options?.dryRun });
1428
+ const result = {
1429
+ created: 0,
1430
+ updated: 0,
1431
+ deleted: 0,
1432
+ changes: [],
1433
+ dryRun: options?.dryRun ?? false,
1434
+ };
1435
+ // Dry run - just count changes without writing
1436
+ if (options?.dryRun) {
1437
+ for (const change of changes) {
1438
+ switch (change.type) {
1439
+ case 'CREATE':
1440
+ result.created++;
1441
+ break;
1442
+ case 'UPDATE':
1443
+ result.updated++;
1444
+ break;
1445
+ case 'DELETE':
1446
+ result.deleted++;
1447
+ break;
1448
+ }
1449
+ }
1450
+ result.changes = changes;
1451
+ return result;
1452
+ }
1453
+ // Sort changes: deletes first (to free names), then creates, then updates
1454
+ const sortedChanges = [...changes].sort((a, b) => {
1455
+ const order = { DELETE: 0, CREATE: 1, UPDATE: 2 };
1456
+ return order[a.type] - order[b.type];
1457
+ });
1458
+ for (const change of sortedChanges) {
1459
+ const absPath = node_path.join(tree.root, change.path);
1460
+ try {
1461
+ switch (change.type) {
1462
+ case 'CREATE':
1463
+ case 'UPDATE':
1464
+ /* istanbul ignore if -- content is always defined for CREATE/UPDATE from tree.write() */
1465
+ if (change.content !== undefined) {
1466
+ // Ensure directory exists
1467
+ const dir = node_path.dirname(absPath);
1468
+ ensureDir(dir);
1469
+ node_fs.writeFileSync(absPath, change.content);
1470
+ // Apply permissions if specified
1471
+ if (change.mode !== undefined) {
1472
+ node_fs.chmodSync(absPath, change.mode);
1473
+ }
1474
+ if (change.type === 'CREATE') {
1475
+ result.created++;
1476
+ }
1477
+ else {
1478
+ result.updated++;
1479
+ }
1480
+ }
1481
+ break;
1482
+ case 'DELETE':
1483
+ if (exists(absPath)) {
1484
+ try {
1485
+ node_fs.unlinkSync(absPath);
1486
+ }
1487
+ catch {
1488
+ // Try recursive delete for directories
1489
+ node_fs.rmSync(absPath, { recursive: true });
1490
+ }
1491
+ }
1492
+ result.deleted++;
1493
+ break;
1494
+ }
1495
+ appliedChanges.push(change);
1496
+ if (options?.verbose) {
1497
+ const prefix = change.type === 'CREATE' ? '+' : change.type === 'DELETE' ? '-' : '~';
1498
+ vfsLogger.info(`${prefix} ${change.path}`);
1499
+ }
1500
+ }
1501
+ catch (error) {
1502
+ // On error, throw with context
1503
+ vfsLogger.error('Commit failed', { path: change.path, type: change.type });
1504
+ const message = error instanceof Error
1505
+ ? `Failed to ${change.type.toLowerCase()} ${change.path}: ${error.message}`
1506
+ : `Failed to ${change.type.toLowerCase()} ${change.path}`;
1507
+ throw createError(message);
1508
+ }
1509
+ }
1510
+ result.changes = appliedChanges;
1511
+ // Clear the tree's pending changes after successful commit
1512
+ tree.clearChanges();
1513
+ return result;
1514
+ }
1515
+
1516
+ createScopedLogger('project-scope:vfs:diff');
1517
+
1518
+ /**
1519
+ * Creates a git reference from full name.
1520
+ * Parses the reference type from the full name.
1521
+ *
1522
+ * @param options - Reference creation options
1523
+ * @returns A new GitRef object
1524
+ *
1525
+ * @example
1526
+ * const ref = createGitRef({
1527
+ * fullName: 'refs/heads/main',
1528
+ * commitHash: 'abc123...',
1529
+ * })
1530
+ */
1531
+ function createGitRef(options) {
1532
+ const { type, name, remote } = parseRefName(options.fullName);
1533
+ return {
1534
+ fullName: options.fullName,
1535
+ name,
1536
+ type,
1537
+ commitHash: options.commitHash,
1538
+ remote,
1539
+ isHead: options.isHead,
1540
+ };
1541
+ }
1542
+ /**
1543
+ * Parses a full reference name into its components.
1544
+ * Uses character-by-character parsing (no regex).
1545
+ *
1546
+ * @param fullName - Full reference name
1547
+ * @returns Parsed components
1548
+ *
1549
+ * @example
1550
+ * parseRefName('refs/heads/main') // { type: 'branch', name: 'main' }
1551
+ * parseRefName('refs/remotes/origin/main') // { type: 'remote', name: 'main', remote: 'origin' }
1552
+ */
1553
+ function parseRefName(fullName) {
1554
+ // Handle HEAD specially
1555
+ if (fullName === 'HEAD') {
1556
+ return { type: 'head', name: 'HEAD' };
1557
+ }
1558
+ // Split by '/' character
1559
+ const parts = splitByChar(fullName, '/');
1560
+ // refs/heads/... -> branch
1561
+ if (parts.length >= 3 && parts[0] === 'refs' && parts[1] === 'heads') {
1562
+ return {
1563
+ type: 'branch',
1564
+ name: parts.slice(2).join('/'),
1565
+ };
1566
+ }
1567
+ // refs/tags/... -> tag
1568
+ if (parts.length >= 3 && parts[0] === 'refs' && parts[1] === 'tags') {
1569
+ return {
1570
+ type: 'tag',
1571
+ name: parts.slice(2).join('/'),
1572
+ };
1573
+ }
1574
+ // refs/remotes/origin/... -> remote
1575
+ if (parts.length >= 4 && parts[0] === 'refs' && parts[1] === 'remotes') {
1576
+ return {
1577
+ type: 'remote',
1578
+ name: parts.slice(3).join('/'),
1579
+ remote: parts[2],
1580
+ };
1581
+ }
1582
+ // refs/stash -> stash
1583
+ if (parts.length >= 2 && parts[0] === 'refs' && parts[1] === 'stash') {
1584
+ return {
1585
+ type: 'stash',
1586
+ name: parts.slice(1).join('/'),
1587
+ };
1588
+ }
1589
+ // Default to branch for unknown patterns
1590
+ return {
1591
+ type: 'branch',
1592
+ name: fullName,
1593
+ };
1594
+ }
1595
+ /**
1596
+ * Splits a string by a character.
1597
+ * Character-by-character implementation (no regex).
1598
+ *
1599
+ * @param str - String to split
1600
+ * @param char - Character to split by
1601
+ * @returns Array of parts
1602
+ */
1603
+ function splitByChar(str, char) {
1604
+ const parts = [];
1605
+ let current = '';
1606
+ for (let i = 0; i < str.length; i++) {
1607
+ if (str[i] === char) {
1608
+ parts.push(current);
1609
+ current = '';
1610
+ }
1611
+ else {
1612
+ current += str[i];
1613
+ }
1614
+ }
1615
+ parts.push(current);
1616
+ return parts;
1617
+ }
1618
+
1619
+ /**
1620
+ * Creates a git commit model.
1621
+ *
1622
+ * @param options - Commit creation options
1623
+ * @returns A new GitCommit object
1624
+ *
1625
+ * @example
1626
+ * const commit = createGitCommit({
1627
+ * hash: 'abc123...',
1628
+ * authorName: 'John Doe',
1629
+ * authorEmail: 'john@example.com',
1630
+ * authorDate: '2026-03-12T10:00:00Z',
1631
+ * subject: 'feat: add new feature',
1632
+ * })
1633
+ */
1634
+ function createGitCommit(options) {
1635
+ const body = options.body ?? '';
1636
+ const subject = options.subject;
1637
+ return {
1638
+ hash: options.hash,
1639
+ shortHash: getShortHash(options.hash),
1640
+ authorName: options.authorName,
1641
+ authorEmail: options.authorEmail,
1642
+ authorDate: options.authorDate,
1643
+ committerName: options.committerName ?? options.authorName,
1644
+ committerEmail: options.committerEmail ?? options.authorEmail,
1645
+ commitDate: options.commitDate ?? options.authorDate,
1646
+ subject,
1647
+ body,
1648
+ message: body ? `${subject}\n\n${body}` : subject,
1649
+ parents: options.parents ?? [],
1650
+ refs: options.refs ?? [],
1651
+ };
1652
+ }
1653
+ /**
1654
+ * Gets a short hash (7 characters) from a full commit hash.
1655
+ *
1656
+ * @param hash - Full commit hash
1657
+ * @returns Short hash (7 characters)
1658
+ */
1659
+ function getShortHash(hash) {
1660
+ return hash.slice(0, 7);
1661
+ }
1662
+
1663
+ /**
1664
+ * Default log options.
1665
+ */
1666
+ const DEFAULT_LOG_OPTIONS = {
1667
+ maxCount: 100,
1668
+ includeMerges: true,
1669
+ timeout: 30000,
1670
+ };
1671
+ /**
1672
+ * Git log format string for structured output.
1673
+ * Uses ASCII delimiters that won't appear in commit messages.
1674
+ */
1675
+ const LOG_FORMAT = [
1676
+ '%H', // full hash
1677
+ '%an', // author name
1678
+ '%ae', // author email
1679
+ '%aI', // author date (ISO 8601)
1680
+ '%cn', // committer name
1681
+ '%ce', // committer email
1682
+ '%cI', // commit date (ISO 8601)
1683
+ '%s', // subject
1684
+ '%b', // body
1685
+ '%P', // parent hashes
1686
+ '%D', // refs
1687
+ ].join('%x00'); // NUL separator
1688
+ /**
1689
+ * Record separator for commit entries.
1690
+ */
1691
+ const RECORD_SEPARATOR = '\x1e'; // ASCII Record Separator
1692
+ /**
1693
+ * Gets the commit log from a git repository.
1694
+ *
1695
+ * @param options - Configuration for retrieving the commit log
1696
+ * @returns Array of GitCommit objects
1697
+ *
1698
+ * @example
1699
+ * const commits = getCommitLog({ maxCount: 10 })
1700
+ * const recentChanges = getCommitLog({ from: 'v1.0.0', to: 'HEAD' })
1701
+ */
1702
+ function getCommitLog(options = {}) {
1703
+ const opts = { ...DEFAULT_LOG_OPTIONS, ...options };
1704
+ const args = ['log', `--format=${RECORD_SEPARATOR}${LOG_FORMAT}`];
1705
+ // Add options
1706
+ if (opts.maxCount !== undefined && opts.maxCount > 0) {
1707
+ args.push(`-n${opts.maxCount}`);
1708
+ }
1709
+ if (!opts.includeMerges) {
1710
+ args.push('--no-merges');
1711
+ }
1712
+ if (opts.author) {
1713
+ const safeAuthor = escapeGitArg(opts.author);
1714
+ args.push(`--author=${safeAuthor}`);
1715
+ }
1716
+ // Add range
1717
+ if (opts.from && opts.to) {
1718
+ const safeFrom = escapeGitRef(opts.from);
1719
+ const safeTo = escapeGitRef(opts.to);
1720
+ args.push(`${safeFrom}..${safeTo}`);
1721
+ }
1722
+ else if (opts.from) {
1723
+ const safeFrom = escapeGitRef(opts.from);
1724
+ args.push(`${safeFrom}..HEAD`);
1725
+ }
1726
+ else if (opts.to) {
1727
+ const safeTo = escapeGitRef(opts.to);
1728
+ args.push(safeTo);
1729
+ }
1730
+ // Add path filter
1731
+ if (opts.path) {
1732
+ const safePath = escapeGitPath(opts.path);
1733
+ args.push('--', safePath);
1734
+ }
1735
+ try {
1736
+ const output = node_child_process.execSync(`git ${args.join(' ')}`, {
1737
+ encoding: 'utf-8',
1738
+ cwd: opts.cwd,
1739
+ timeout: opts.timeout,
1740
+ stdio: ['pipe', 'pipe', 'pipe'],
1741
+ maxBuffer: 50 * 1024 * 1024, // 50MB
1742
+ });
1743
+ return parseCommitLog(output);
1744
+ }
1745
+ catch (error) {
1746
+ // Check if error is due to no commits
1747
+ if (error instanceof Error && error.message.includes('does not have any commits')) {
1748
+ return [];
1749
+ }
1750
+ throw error;
1751
+ }
1752
+ }
1753
+ /**
1754
+ * Gets commits between two references.
1755
+ *
1756
+ * @param from - Starting reference (exclusive)
1757
+ * @param to - Ending reference (inclusive, default: HEAD)
1758
+ * @param options - Additional options
1759
+ * @returns Array of GitCommit objects
1760
+ *
1761
+ * @example
1762
+ * const commits = getCommitsBetween('v1.0.0', 'v1.1.0')
1763
+ */
1764
+ function getCommitsBetween(from, to = 'HEAD', options = {}) {
1765
+ return getCommitLog({ ...options, from, to });
1766
+ }
1767
+ /**
1768
+ * Gets commits since a specific tag or reference.
1769
+ *
1770
+ * @param since - Reference to start from (exclusive)
1771
+ * @param options - Additional options
1772
+ * @returns Array of GitCommit objects
1773
+ *
1774
+ * @example
1775
+ * const commits = getCommitsSince('v1.0.0')
1776
+ */
1777
+ function getCommitsSince(since, options = {}) {
1778
+ return getCommitLog({ ...options, from: since });
1779
+ }
1780
+ /**
1781
+ * Gets a single commit by its hash.
1782
+ *
1783
+ * @param hash - Commit hash (full or short)
1784
+ * @param options - Additional options
1785
+ * @returns GitCommit or null if not found
1786
+ *
1787
+ * @example
1788
+ * const commit = getCommit('abc1234')
1789
+ */
1790
+ function getCommit(hash, options = {}) {
1791
+ const safeHash = escapeGitRef(hash);
1792
+ try {
1793
+ const commits = getCommitLog({
1794
+ ...options,
1795
+ to: safeHash,
1796
+ maxCount: 1,
1797
+ });
1798
+ return commits[0] ?? null;
1799
+ }
1800
+ catch {
1801
+ return null;
1802
+ }
1803
+ }
1804
+ /**
1805
+ * Checks if a commit exists in the repository.
1806
+ *
1807
+ * @param hash - Commit hash to check
1808
+ * @param options - Additional options
1809
+ * @returns True if commit exists
1810
+ */
1811
+ function commitExists(hash, options = {}) {
1812
+ const safeHash = escapeGitRef(hash);
1813
+ try {
1814
+ node_child_process.execSync(`git cat-file -t ${safeHash}`, {
1815
+ encoding: 'utf-8',
1816
+ cwd: options.cwd,
1817
+ timeout: options.timeout ?? 5000,
1818
+ stdio: ['pipe', 'pipe', 'pipe'],
1819
+ });
1820
+ return true;
1821
+ }
1822
+ catch {
1823
+ return false;
1824
+ }
1825
+ }
1826
+ /**
1827
+ * Parses raw git log output into GitCommit objects.
1828
+ *
1829
+ * @param output - Raw git log output
1830
+ * @returns Array of GitCommit objects
1831
+ */
1832
+ function parseCommitLog(output) {
1833
+ const commits = [];
1834
+ if (!output.trim()) {
1835
+ return commits;
1836
+ }
1837
+ // Split by record separator
1838
+ const records = splitByDelimiter(output, RECORD_SEPARATOR);
1839
+ for (const record of records) {
1840
+ const trimmed = record.trim();
1841
+ if (!trimmed)
1842
+ continue;
1843
+ // Split by NUL character
1844
+ const fields = splitByDelimiter(trimmed, '\x00');
1845
+ if (fields.length < 10)
1846
+ continue;
1847
+ const [hash, authorName, authorEmail, authorDate, committerName, committerEmail, commitDate, subject, body, parentsStr, refsStr] = fields;
1848
+ // Parse parents (space-separated hashes)
1849
+ const parents = parentsStr ? splitByDelimiter(parentsStr, ' ').filter((p) => p.trim()) : [];
1850
+ // Parse refs (comma-separated, may have prefixes like 'HEAD -> ')
1851
+ const refs = parseRefs(refsStr || '');
1852
+ commits.push(createGitCommit({
1853
+ hash,
1854
+ authorName,
1855
+ authorEmail,
1856
+ authorDate,
1857
+ committerName,
1858
+ committerEmail,
1859
+ commitDate,
1860
+ subject,
1861
+ body: body || undefined,
1862
+ parents,
1863
+ refs,
1864
+ }));
1865
+ }
1866
+ return commits;
1867
+ }
1868
+ /**
1869
+ * Parses ref string from git log.
1870
+ *
1871
+ * @param refsStr - Raw refs string from git log
1872
+ * @returns Array of ref names
1873
+ */
1874
+ function parseRefs(refsStr) {
1875
+ if (!refsStr.trim()) {
1876
+ return [];
1877
+ }
1878
+ const refs = [];
1879
+ const parts = splitByDelimiter(refsStr, ',');
1880
+ for (const part of parts) {
1881
+ let ref = part.trim();
1882
+ // Handle 'HEAD -> branch' format
1883
+ const arrowIndex = findSubstring(ref, ' -> ');
1884
+ if (arrowIndex !== -1) {
1885
+ refs.push('HEAD');
1886
+ ref = ref.slice(arrowIndex + 4);
1887
+ }
1888
+ // Handle 'tag: tagname' format
1889
+ if (startsWithPrefix$2(ref, 'tag: ')) {
1890
+ ref = ref.slice(5);
1891
+ }
1892
+ if (ref) {
1893
+ refs.push(ref);
1894
+ }
1895
+ }
1896
+ return refs;
1897
+ }
1898
+ /**
1899
+ * Splits string by delimiter (no regex).
1900
+ *
1901
+ * @param str - String to split
1902
+ * @param delimiter - Delimiter to split by
1903
+ * @returns Array of parts
1904
+ */
1905
+ function splitByDelimiter(str, delimiter) {
1906
+ const parts = [];
1907
+ let current = '';
1908
+ let i = 0;
1909
+ while (i < str.length) {
1910
+ if (matchesAt(str, i, delimiter)) {
1911
+ parts.push(current);
1912
+ current = '';
1913
+ i += delimiter.length;
1914
+ }
1915
+ else {
1916
+ current += str[i];
1917
+ i++;
1918
+ }
1919
+ }
1920
+ parts.push(current);
1921
+ return parts;
1922
+ }
1923
+ /**
1924
+ * Checks if string matches at position.
1925
+ *
1926
+ * @param str - String to check
1927
+ * @param pos - Position to check at
1928
+ * @param pattern - Pattern to match
1929
+ * @returns True if matches
1930
+ */
1931
+ function matchesAt(str, pos, pattern) {
1932
+ if (pos + pattern.length > str.length)
1933
+ return false;
1934
+ for (let i = 0; i < pattern.length; i++) {
1935
+ if (str[pos + i] !== pattern[i])
1936
+ return false;
1937
+ }
1938
+ return true;
1939
+ }
1940
+ /**
1941
+ * Finds substring position (no regex).
1942
+ *
1943
+ * @param str - String to search
1944
+ * @param pattern - Pattern to find
1945
+ * @returns Position or -1 if not found
1946
+ */
1947
+ function findSubstring(str, pattern) {
1948
+ for (let i = 0; i <= str.length - pattern.length; i++) {
1949
+ if (matchesAt(str, i, pattern)) {
1950
+ return i;
1951
+ }
1952
+ }
1953
+ return -1;
1954
+ }
1955
+ /**
1956
+ * Checks if string starts with prefix (no regex).
1957
+ *
1958
+ * @param str - String to check
1959
+ * @param prefix - Prefix to check for
1960
+ * @returns True if starts with prefix
1961
+ */
1962
+ function startsWithPrefix$2(str, prefix) {
1963
+ return matchesAt(str, 0, prefix);
1964
+ }
1965
+ // ============================================================================
1966
+ // Security helpers - character-by-character validation (no regex)
1967
+ // ============================================================================
1968
+ /**
1969
+ * Maximum allowed git reference length.
1970
+ */
1971
+ const MAX_REF_LENGTH = 256;
1972
+ /**
1973
+ * Escapes a git reference for safe use in shell commands.
1974
+ *
1975
+ * @param ref - Reference to escape
1976
+ * @returns Safe reference string
1977
+ * @throws {Error} If reference contains invalid characters
1978
+ */
1979
+ function escapeGitRef(ref) {
1980
+ if (!ref || typeof ref !== 'string') {
1981
+ throw createError('Git reference is required');
1982
+ }
1983
+ if (ref.length > MAX_REF_LENGTH) {
1984
+ throw createError(`Git reference exceeds maximum length of ${MAX_REF_LENGTH}`);
1985
+ }
1986
+ const safe = [];
1987
+ for (let i = 0; i < ref.length; i++) {
1988
+ const code = ref.charCodeAt(i);
1989
+ // Allow: a-z, A-Z, 0-9, /, -, _, ., ~, ^, @, {, }
1990
+ if ((code >= 97 && code <= 122) || // a-z
1991
+ (code >= 65 && code <= 90) || // A-Z
1992
+ (code >= 48 && code <= 57) || // 0-9
1993
+ code === 47 || // /
1994
+ code === 45 || // -
1995
+ code === 95 || // _
1996
+ code === 46 || // .
1997
+ code === 126 || // ~
1998
+ code === 94 || // ^
1999
+ code === 64 || // @
2000
+ code === 123 || // {
2001
+ code === 125 // }
2002
+ ) {
2003
+ safe.push(ref[i]);
2004
+ }
2005
+ else {
2006
+ throw createError(`Invalid character in git reference at position ${i}: "${ref[i]}"`);
2007
+ }
2008
+ }
2009
+ return safe.join('');
2010
+ }
2011
+ /**
2012
+ * Maximum allowed git path length.
2013
+ */
2014
+ const MAX_PATH_LENGTH$1 = 4096;
2015
+ /**
2016
+ * Escapes a file path for safe use in git commands.
2017
+ *
2018
+ * @param path - Path to escape
2019
+ * @returns Safe path string
2020
+ * @throws {Error} If path contains invalid characters
2021
+ */
2022
+ function escapeGitPath(path) {
2023
+ if (!path || typeof path !== 'string') {
2024
+ throw createError('Path is required');
2025
+ }
2026
+ if (path.length > MAX_PATH_LENGTH$1) {
2027
+ throw createError(`Path exceeds maximum length of ${MAX_PATH_LENGTH$1}`);
2028
+ }
2029
+ const safe = [];
2030
+ for (let i = 0; i < path.length; i++) {
2031
+ const code = path.charCodeAt(i);
2032
+ // Allow: a-z, A-Z, 0-9, /, \, -, _, ., space
2033
+ if ((code >= 97 && code <= 122) || // a-z
2034
+ (code >= 65 && code <= 90) || // A-Z
2035
+ (code >= 48 && code <= 57) || // 0-9
2036
+ code === 47 || // /
2037
+ code === 92 || // \
2038
+ code === 45 || // -
2039
+ code === 95 || // _
2040
+ code === 46 || // .
2041
+ code === 32 // space
2042
+ ) {
2043
+ safe.push(path[i]);
2044
+ }
2045
+ else {
2046
+ throw createError(`Invalid character in path at position ${i}: "${path[i]}"`);
2047
+ }
2048
+ }
2049
+ return safe.join('');
2050
+ }
2051
+ /**
2052
+ * Maximum allowed argument length.
2053
+ */
2054
+ const MAX_ARG_LENGTH = 1000;
2055
+ /**
2056
+ * Escapes a general git argument for safe use in shell commands.
2057
+ *
2058
+ * @param arg - Argument to escape
2059
+ * @returns Safe argument string
2060
+ * @throws {Error} If argument contains invalid characters
2061
+ */
2062
+ function escapeGitArg(arg) {
2063
+ if (!arg || typeof arg !== 'string') {
2064
+ throw createError('Argument is required');
2065
+ }
2066
+ if (arg.length > MAX_ARG_LENGTH) {
2067
+ throw createError(`Argument exceeds maximum length of ${MAX_ARG_LENGTH}`);
2068
+ }
2069
+ const safe = [];
2070
+ for (let i = 0; i < arg.length; i++) {
2071
+ const code = arg.charCodeAt(i);
2072
+ // Allow: a-z, A-Z, 0-9, space, @, ., -, _, <, >, +
2073
+ if ((code >= 97 && code <= 122) || // a-z
2074
+ (code >= 65 && code <= 90) || // A-Z
2075
+ (code >= 48 && code <= 57) || // 0-9
2076
+ code === 32 || // space
2077
+ code === 64 || // @
2078
+ code === 46 || // .
2079
+ code === 45 || // -
2080
+ code === 95 || // _
2081
+ code === 60 || // <
2082
+ code === 62 || // >
2083
+ code === 43 // +
2084
+ ) {
2085
+ safe.push(arg[i]);
2086
+ }
2087
+ else {
2088
+ throw createError(`Invalid character in argument at position ${i}: "${arg[i]}"`);
2089
+ }
2090
+ }
2091
+ return safe.join('');
2092
+ }
2093
+
2094
+ /**
2095
+ * Creates a lightweight git tag.
2096
+ *
2097
+ * @param options - Tag creation options
2098
+ * @returns A new GitTag object
2099
+ *
2100
+ * @example
2101
+ * const tag = createLightweightTag({
2102
+ * name: 'v1.0.0',
2103
+ * commitHash: 'abc123...',
2104
+ * })
2105
+ */
2106
+ function createLightweightTag(options) {
2107
+ return {
2108
+ name: options.name,
2109
+ commitHash: options.commitHash,
2110
+ type: 'lightweight',
2111
+ };
2112
+ }
2113
+ /**
2114
+ * Creates an annotated git tag.
2115
+ *
2116
+ * @param options - Tag creation options
2117
+ * @returns A new GitTag object
2118
+ *
2119
+ * @example
2120
+ * const tag = createAnnotatedTag({
2121
+ * name: 'v1.0.0',
2122
+ * commitHash: 'abc123...',
2123
+ * message: 'Release v1.0.0',
2124
+ * taggerName: 'John Doe',
2125
+ * taggerEmail: 'john@example.com',
2126
+ * tagDate: '2026-03-12T10:00:00Z',
2127
+ * })
2128
+ */
2129
+ function createAnnotatedTag(options) {
2130
+ return {
2131
+ name: options.name,
2132
+ commitHash: options.commitHash,
2133
+ type: 'annotated',
2134
+ message: options.message,
2135
+ taggerName: options.taggerName,
2136
+ taggerEmail: options.taggerEmail,
2137
+ tagDate: options.tagDate,
2138
+ };
2139
+ }
2140
+
2141
+ /**
2142
+ * Default tag options.
2143
+ */
2144
+ const DEFAULT_TAG_OPTIONS = {
2145
+ timeout: 10000,
2146
+ };
2147
+ /**
2148
+ * Gets all tags from the repository.
2149
+ *
2150
+ * @param options - Tag listing options
2151
+ * @returns Array of GitTag objects
2152
+ *
2153
+ * @example
2154
+ * const tags = getTags()
2155
+ * const versionTags = getTags({ pattern: 'v' })
2156
+ */
2157
+ function getTags(options = {}) {
2158
+ const opts = { ...DEFAULT_TAG_OPTIONS, ...options };
2159
+ const args = ['tag', '-l', '--sort=-creatordate'];
2160
+ if (opts.pattern) {
2161
+ const safePattern = escapeGitTagPattern(opts.pattern);
2162
+ args.push(safePattern + '*');
2163
+ }
2164
+ try {
2165
+ const output = node_child_process.execSync(`git ${args.join(' ')}`, {
2166
+ encoding: 'utf-8',
2167
+ cwd: opts.cwd,
2168
+ timeout: opts.timeout,
2169
+ stdio: ['pipe', 'pipe', 'pipe'],
2170
+ });
2171
+ const tagNames = output
2172
+ .split('\n')
2173
+ .map((line) => line.trim())
2174
+ .filter((line) => line.length > 0);
2175
+ // Limit results if requested
2176
+ const limitedNames = opts.maxCount ? tagNames.slice(0, opts.maxCount) : tagNames;
2177
+ // Get details for each tag
2178
+ const tags = [];
2179
+ for (const name of limitedNames) {
2180
+ const tag = getTagDetails(name, opts);
2181
+ if (tag) {
2182
+ tags.push(tag);
2183
+ }
2184
+ }
2185
+ return tags;
2186
+ }
2187
+ catch {
2188
+ return [];
2189
+ }
2190
+ }
2191
+ /**
2192
+ * Gets detailed information about a specific tag.
2193
+ *
2194
+ * @param name - The tag name to look up
2195
+ * @param options - Configuration for the tag operation
2196
+ * @returns GitTag or null if not found
2197
+ *
2198
+ * @example
2199
+ * const tag = getTag('v1.0.0')
2200
+ */
2201
+ function getTag(name, options = {}) {
2202
+ return getTagDetails(name, { ...DEFAULT_TAG_OPTIONS, ...options });
2203
+ }
2204
+ /**
2205
+ * Gets tag details including type and commit hash.
2206
+ *
2207
+ * @param name - The tag name to retrieve details for
2208
+ * @param options - Configuration for the tag operation
2209
+ * @returns GitTag or null
2210
+ */
2211
+ function getTagDetails(name, options) {
2212
+ const safeName = escapeGitRef(name);
2213
+ try {
2214
+ // Get the commit hash the tag points to
2215
+ const commitHash = node_child_process.execSync(`git rev-list -1 ${safeName}`, {
2216
+ encoding: 'utf-8',
2217
+ cwd: options.cwd,
2218
+ timeout: options.timeout,
2219
+ stdio: ['pipe', 'pipe', 'pipe'],
2220
+ }).trim();
2221
+ // Check if it's an annotated tag by trying to get tag message
2222
+ try {
2223
+ const tagInfo = node_child_process.execSync(`git cat-file tag ${safeName}`, {
2224
+ encoding: 'utf-8',
2225
+ cwd: options.cwd,
2226
+ timeout: options.timeout,
2227
+ stdio: ['pipe', 'pipe', 'pipe'],
2228
+ });
2229
+ // Parse annotated tag info
2230
+ const parsed = parseAnnotatedTagInfo(tagInfo);
2231
+ return createAnnotatedTag({
2232
+ name,
2233
+ commitHash,
2234
+ message: parsed.message,
2235
+ taggerName: parsed.taggerName,
2236
+ taggerEmail: parsed.taggerEmail,
2237
+ tagDate: parsed.tagDate,
2238
+ });
2239
+ }
2240
+ catch {
2241
+ // Not an annotated tag, it's lightweight
2242
+ return createLightweightTag({
2243
+ name,
2244
+ commitHash,
2245
+ });
2246
+ }
2247
+ }
2248
+ catch {
2249
+ return null;
2250
+ }
2251
+ }
2252
+ /**
2253
+ * Parses annotated tag info from git cat-file output.
2254
+ *
2255
+ * @param info - Raw tag info
2256
+ * @returns Parsed info
2257
+ */
2258
+ function parseAnnotatedTagInfo(info) {
2259
+ const lines = info.split('\n');
2260
+ let taggerName = '';
2261
+ let taggerEmail = '';
2262
+ let tagDate = '';
2263
+ let messageStart = -1;
2264
+ for (let i = 0; i < lines.length; i++) {
2265
+ const line = lines[i];
2266
+ if (startsWithPrefix$1(line, 'tagger ')) {
2267
+ const taggerLine = line.slice(7);
2268
+ const parsed = parseTaggerLine(taggerLine);
2269
+ taggerName = parsed.name;
2270
+ taggerEmail = parsed.email;
2271
+ tagDate = parsed.date;
2272
+ }
2273
+ // Empty line marks start of message
2274
+ if (line === '' && messageStart === -1) {
2275
+ messageStart = i + 1;
2276
+ break;
2277
+ }
2278
+ }
2279
+ const message = messageStart >= 0 ? lines.slice(messageStart).join('\n').trim() : '';
2280
+ return {
2281
+ message,
2282
+ taggerName,
2283
+ taggerEmail,
2284
+ tagDate,
2285
+ };
2286
+ }
2287
+ /**
2288
+ * Parses tagger line from annotated tag.
2289
+ * Format: Name <email> timestamp timezone
2290
+ *
2291
+ * @param line - Raw tagger line from git output
2292
+ * @returns Parsed tagger info with name, email, and date
2293
+ */
2294
+ function parseTaggerLine(line) {
2295
+ let name = '';
2296
+ let email = '';
2297
+ let date = '';
2298
+ // Find email in angle brackets
2299
+ let emailStart = -1;
2300
+ let emailEnd = -1;
2301
+ for (let i = 0; i < line.length; i++) {
2302
+ if (line[i] === '<') {
2303
+ emailStart = i + 1;
2304
+ }
2305
+ else if (line[i] === '>' && emailStart !== -1) {
2306
+ emailEnd = i;
2307
+ break;
2308
+ }
2309
+ }
2310
+ if (emailStart !== -1 && emailEnd !== -1) {
2311
+ name = line.slice(0, emailStart - 1).trim();
2312
+ email = line.slice(emailStart, emailEnd);
2313
+ // Rest is timestamp and timezone
2314
+ const rest = line.slice(emailEnd + 1).trim();
2315
+ const parts = rest.split(' ');
2316
+ if (parts.length >= 1) {
2317
+ // Convert Unix timestamp to ISO 8601
2318
+ const timestamp = parseInt(parts[0], 10);
2319
+ if (!globalIsNaN(timestamp)) {
2320
+ date = createDate(timestamp * 1000).toISOString();
2321
+ }
2322
+ }
2323
+ }
2324
+ return { name, email, date };
2325
+ }
2326
+ /**
2327
+ * Checks if a tag exists.
2328
+ *
2329
+ * @param name - The tag name to verify
2330
+ * @param options - Configuration for the tag operation
2331
+ * @returns True if tag exists
2332
+ *
2333
+ * @example
2334
+ * if (tagExists('v1.0.0')) { ... }
2335
+ */
2336
+ function tagExists(name, options = {}) {
2337
+ const opts = { ...DEFAULT_TAG_OPTIONS, ...options };
2338
+ const safeName = escapeGitRef(name);
2339
+ try {
2340
+ node_child_process.execSync(`git rev-parse ${safeName}`, {
2341
+ encoding: 'utf-8',
2342
+ cwd: opts.cwd,
2343
+ timeout: opts.timeout,
2344
+ stdio: ['pipe', 'pipe', 'pipe'],
2345
+ });
2346
+ return true;
2347
+ }
2348
+ catch {
2349
+ return false;
2350
+ }
2351
+ }
2352
+ /**
2353
+ * Gets the latest tag (by creation date).
2354
+ *
2355
+ * @param options - Tag options with optional pattern
2356
+ * @returns Latest GitTag or null
2357
+ *
2358
+ * @example
2359
+ * const latest = getLatestTag()
2360
+ * const latestVersion = getLatestTag({ pattern: 'v' })
2361
+ */
2362
+ function getLatestTag(options = {}) {
2363
+ const tags = getTags({ ...options, maxCount: 1 });
2364
+ return tags[0] ?? null;
2365
+ }
2366
+ /**
2367
+ * Gets tags that match a package name.
2368
+ *
2369
+ * @param packageName - Package name to match
2370
+ * @param options - Tag options
2371
+ * @returns Array of matching tags
2372
+ *
2373
+ * @example
2374
+ * const tags = getTagsForPackage('@scope/pkg')
2375
+ */
2376
+ function getTagsForPackage(packageName, options = {}) {
2377
+ // Common patterns: @scope/pkg@version, pkg@version, pkg-vversion
2378
+ const allTags = getTags(options);
2379
+ return allTags.filter((tag) => {
2380
+ // Check if tag starts with package name followed by @ or -v
2381
+ const name = tag.name;
2382
+ // Pattern: package@version
2383
+ if (startsWithPrefix$1(name, packageName + '@')) {
2384
+ return true;
2385
+ }
2386
+ // Pattern: package-v
2387
+ if (startsWithPrefix$1(name, packageName + '-v')) {
2388
+ return true;
2389
+ }
2390
+ return false;
2391
+ });
2392
+ }
2393
+ // ============================================================================
2394
+ // Helper functions
2395
+ // ============================================================================
2396
+ /**
2397
+ * Checks if string starts with prefix (no regex).
2398
+ *
2399
+ * @param str - The string to check
2400
+ * @param prefix - The prefix to look for
2401
+ * @returns True if str starts with the given prefix
2402
+ */
2403
+ function startsWithPrefix$1(str, prefix) {
2404
+ if (prefix.length > str.length)
2405
+ return false;
2406
+ for (let i = 0; i < prefix.length; i++) {
2407
+ if (str[i] !== prefix[i])
2408
+ return false;
2409
+ }
2410
+ return true;
2411
+ }
2412
+ /**
2413
+ * Maximum tag pattern length.
2414
+ */
2415
+ const MAX_PATTERN_LENGTH = 256;
2416
+ /**
2417
+ * Escapes a tag pattern for safe use in git commands.
2418
+ *
2419
+ * @param pattern - Pattern to escape
2420
+ * @returns Safe pattern string
2421
+ */
2422
+ function escapeGitTagPattern(pattern) {
2423
+ if (!pattern || typeof pattern !== 'string') {
2424
+ throw createError('Pattern is required');
2425
+ }
2426
+ if (pattern.length > MAX_PATTERN_LENGTH) {
2427
+ throw createError(`Pattern exceeds maximum length of ${MAX_PATTERN_LENGTH}`);
2428
+ }
2429
+ const safe = [];
2430
+ for (let i = 0; i < pattern.length; i++) {
2431
+ const code = pattern.charCodeAt(i);
2432
+ // Allow: a-z, A-Z, 0-9, /, -, _, ., @
2433
+ if ((code >= 97 && code <= 122) || // a-z
2434
+ (code >= 65 && code <= 90) || // A-Z
2435
+ (code >= 48 && code <= 57) || // 0-9
2436
+ code === 47 || // /
2437
+ code === 45 || // -
2438
+ code === 95 || // _
2439
+ code === 46 || // .
2440
+ code === 64 // @
2441
+ ) {
2442
+ safe.push(pattern[i]);
2443
+ }
2444
+ else {
2445
+ throw createError(`Invalid character in pattern at position ${i}: "${pattern[i]}"`);
2446
+ }
2447
+ }
2448
+ return safe.join('');
2449
+ }
2450
+
2451
+ /**
2452
+ * Creates a new tag.
2453
+ *
2454
+ * @param name - The name for the new tag
2455
+ * @param options - Configuration including optional message for annotated tags
2456
+ * @returns Created GitTag
2457
+ *
2458
+ * @example
2459
+ * // Create lightweight tag
2460
+ * const tag = createTag('v1.0.0')
2461
+ *
2462
+ * // Create annotated tag
2463
+ * const tag = createTag('v1.0.0', { message: 'Release v1.0.0' })
2464
+ */
2465
+ function createTag(name, options = {}) {
2466
+ const opts = { ...DEFAULT_TAG_OPTIONS, ...options };
2467
+ const safeName = escapeGitRef(name);
2468
+ const args = ['tag'];
2469
+ if (opts.force) {
2470
+ args.push('-f');
2471
+ }
2472
+ if (opts.message) {
2473
+ // Annotated tag
2474
+ args.push('-a');
2475
+ args.push(safeName);
2476
+ args.push('-m');
2477
+ args.push(`"${escapeGitMessage(opts.message)}"`);
2478
+ }
2479
+ else {
2480
+ // Lightweight tag
2481
+ args.push(safeName);
2482
+ }
2483
+ if (opts.target) {
2484
+ args.push(escapeGitRef(opts.target));
2485
+ }
2486
+ try {
2487
+ node_child_process.execSync(`git ${args.join(' ')}`, {
2488
+ encoding: 'utf-8',
2489
+ cwd: opts.cwd,
2490
+ timeout: opts.timeout,
2491
+ stdio: ['pipe', 'pipe', 'pipe'],
2492
+ });
2493
+ // Get the created tag
2494
+ const tag = getTag(name, opts);
2495
+ if (!tag) {
2496
+ throw createError(`Failed to retrieve created tag: ${name}`);
2497
+ }
2498
+ return tag;
2499
+ }
2500
+ catch (error) {
2501
+ if (error instanceof Error) {
2502
+ throw createError(`Failed to create tag ${name}: ${error.message}`);
2503
+ }
2504
+ throw error;
2505
+ }
2506
+ }
2507
+ /**
2508
+ * Deletes a tag.
2509
+ *
2510
+ * @param name - The tag name to delete
2511
+ * @param options - Configuration for the tag operation
2512
+ * @returns True if deleted
2513
+ *
2514
+ * @example
2515
+ * const deleted = deleteTag('v1.0.0')
2516
+ */
2517
+ function deleteTag(name, options = {}) {
2518
+ const opts = { ...DEFAULT_TAG_OPTIONS, ...options };
2519
+ const safeName = escapeGitRef(name);
2520
+ try {
2521
+ node_child_process.execSync(`git tag -d ${safeName}`, {
2522
+ encoding: 'utf-8',
2523
+ cwd: opts.cwd,
2524
+ timeout: opts.timeout,
2525
+ stdio: ['pipe', 'pipe', 'pipe'],
2526
+ });
2527
+ return true;
2528
+ }
2529
+ catch {
2530
+ return false;
2531
+ }
2532
+ }
2533
+ /**
2534
+ * Pushes a tag to a remote.
2535
+ *
2536
+ * @param name - The tag to push to the remote
2537
+ * @param remote - Remote name (defaults to 'origin')
2538
+ * @param options - Configuration for the tag operation
2539
+ * @returns True if pushed successfully
2540
+ *
2541
+ * @example
2542
+ * pushTag('v1.0.0')
2543
+ * pushTag('v1.0.0', 'upstream')
2544
+ */
2545
+ function pushTag(name, remote = 'origin', options = {}) {
2546
+ const opts = { ...DEFAULT_TAG_OPTIONS, ...options };
2547
+ const safeName = escapeGitRef(name);
2548
+ const safeRemote = escapeGitRef(remote);
2549
+ try {
2550
+ node_child_process.execSync(`git push ${safeRemote} ${safeName}`, {
2551
+ encoding: 'utf-8',
2552
+ cwd: opts.cwd,
2553
+ timeout: opts.timeout * 3, // Allow more time for network
2554
+ stdio: ['pipe', 'pipe', 'pipe'],
2555
+ });
2556
+ return true;
2557
+ }
2558
+ catch {
2559
+ return false;
2560
+ }
2561
+ }
2562
+ // ============================================================================
2563
+ // Security helpers
2564
+ // ============================================================================
2565
+ /**
2566
+ * Maximum message length.
2567
+ */
2568
+ const MAX_MESSAGE_LENGTH = 10000;
2569
+ /**
2570
+ * Escapes a message for safe use in git commands.
2571
+ *
2572
+ * @param message - Message to escape
2573
+ * @returns Safe message string
2574
+ */
2575
+ function escapeGitMessage(message) {
2576
+ if (!message || typeof message !== 'string') {
2577
+ throw createError('Message is required');
2578
+ }
2579
+ if (message.length > MAX_MESSAGE_LENGTH) {
2580
+ throw createError(`Message exceeds maximum length of ${MAX_MESSAGE_LENGTH}`);
2581
+ }
2582
+ const safe = [];
2583
+ for (let i = 0; i < message.length; i++) {
2584
+ const char = message[i];
2585
+ const code = message.charCodeAt(i);
2586
+ // Escape double quotes and backslashes
2587
+ if (char === '"' || char === '\\') {
2588
+ safe.push('\\');
2589
+ safe.push(char);
2590
+ }
2591
+ // Allow printable ASCII and common whitespace
2592
+ else if ((code >= 32 && code <= 126) || // Printable ASCII
2593
+ code === 10 || // newline
2594
+ code === 13 || // carriage return
2595
+ code === 9 // tab
2596
+ ) {
2597
+ safe.push(char);
2598
+ }
2599
+ // Skip other control characters
2600
+ }
2601
+ return safe.join('');
2602
+ }
2603
+
2604
+ /**
2605
+ * Default commit options.
2606
+ */
2607
+ const DEFAULT_COMMIT_OPTIONS = {
2608
+ timeout: 30000,
2609
+ };
2610
+ /**
2611
+ * Creates a new commit.
2612
+ *
2613
+ * @param message - Commit message (subject line)
2614
+ * @param options - Create options
2615
+ * @returns Created GitCommit
2616
+ *
2617
+ * @example
2618
+ * const commit = createCommit('feat: add new feature')
2619
+ * const commit = createCommit('fix: resolve bug', { body: 'Detailed description' })
2620
+ */
2621
+ function commit(message, options = {}) {
2622
+ const opts = { ...DEFAULT_COMMIT_OPTIONS, ...options };
2623
+ // noEdit is only valid when amending - reuse existing commit message
2624
+ const isNoEditAmend = opts.amend && opts.noEdit;
2625
+ if (!isNoEditAmend && (!message || typeof message !== 'string')) {
2626
+ throw createError('Commit message is required');
2627
+ }
2628
+ const args = ['commit'];
2629
+ if (isNoEditAmend) {
2630
+ // Amend without changing the message
2631
+ args.push('--amend', '--no-edit');
2632
+ }
2633
+ else {
2634
+ const safeMessage = escapeGitMessage(message);
2635
+ // Build message with optional body
2636
+ let fullMessage = safeMessage;
2637
+ if (opts.body) {
2638
+ const safeBody = escapeGitMessage(opts.body);
2639
+ fullMessage = `${safeMessage}\n\n${safeBody}`;
2640
+ }
2641
+ args.push('-m', `"${fullMessage}"`);
2642
+ if (opts.amend) {
2643
+ args.push('--amend');
2644
+ }
2645
+ }
2646
+ if (opts.allowEmpty) {
2647
+ args.push('--allow-empty');
2648
+ }
2649
+ if (opts.sign) {
2650
+ args.push('-S');
2651
+ }
2652
+ if (opts.noVerify) {
2653
+ args.push('--no-verify');
2654
+ }
2655
+ if (opts.author) {
2656
+ const safeAuthor = escapeAuthor(opts.author);
2657
+ args.push(`--author="${safeAuthor}"`);
2658
+ }
2659
+ // Add specific files if provided
2660
+ if (opts.files && opts.files.length > 0) {
2661
+ args.push('--');
2662
+ for (const file of opts.files) {
2663
+ args.push(escapeFilePath(file));
2664
+ }
2665
+ }
2666
+ try {
2667
+ node_child_process.execSync(`git ${args.join(' ')}`, {
2668
+ encoding: 'utf-8',
2669
+ cwd: opts.cwd,
2670
+ timeout: opts.timeout,
2671
+ stdio: ['pipe', 'pipe', 'pipe'],
2672
+ });
2673
+ // Get the created commit
2674
+ const commit = getCommit('HEAD', opts);
2675
+ if (!commit) {
2676
+ throw createError('Failed to retrieve created commit');
2677
+ }
2678
+ return commit;
2679
+ }
2680
+ catch (error) {
2681
+ if (error instanceof Error) {
2682
+ throw createError(`Failed to create commit: ${error.message}`);
2683
+ }
2684
+ throw error;
2685
+ }
2686
+ }
2687
+ /**
2688
+ * Amends the last commit with new message.
2689
+ *
2690
+ * @param message - The new commit message to use
2691
+ * @param options - Configuration for the commit operation
2692
+ * @returns GitCommit object representing the amended commit
2693
+ *
2694
+ * @example
2695
+ * const commit = amendCommit('feat: improved feature')
2696
+ */
2697
+ function amendCommit(message, options = {}) {
2698
+ return commit(message, { ...options, amend: true });
2699
+ }
2700
+ /**
2701
+ * Creates an empty commit (useful for CI triggers).
2702
+ *
2703
+ * @param message - Text for the empty commit
2704
+ * @param options - Configuration for the commit operation
2705
+ * @returns GitCommit object representing the new empty commit
2706
+ *
2707
+ * @example
2708
+ * const commit = createEmptyCommit('chore: trigger CI')
2709
+ */
2710
+ function createEmptyCommit(message, options = {}) {
2711
+ return commit(message, { ...options, allowEmpty: true });
2712
+ }
2713
+ // ============================================================================
2714
+ // Security helpers - character-by-character validation (no regex)
2715
+ // ============================================================================
2716
+ /**
2717
+ * Maximum file path length.
2718
+ */
2719
+ const MAX_PATH_LENGTH = 4096;
2720
+ /**
2721
+ * Escapes a file path for safe use in git commands.
2722
+ *
2723
+ * @param path - Path to escape
2724
+ * @returns Safe path string
2725
+ */
2726
+ function escapeFilePath(path) {
2727
+ if (!path || typeof path !== 'string') {
2728
+ throw createError('File path is required');
2729
+ }
2730
+ if (path.length > MAX_PATH_LENGTH) {
2731
+ throw createError(`Path exceeds maximum length of ${MAX_PATH_LENGTH}`);
2732
+ }
2733
+ const safe = [];
2734
+ for (let i = 0; i < path.length; i++) {
2735
+ const code = path.charCodeAt(i);
2736
+ // Allow: a-z, A-Z, 0-9, /, \, -, _, ., space
2737
+ if ((code >= 97 && code <= 122) || // a-z
2738
+ (code >= 65 && code <= 90) || // A-Z
2739
+ (code >= 48 && code <= 57) || // 0-9
2740
+ code === 47 || // /
2741
+ code === 92 || // \
2742
+ code === 45 || // -
2743
+ code === 95 || // _
2744
+ code === 46 || // .
2745
+ code === 32 // space
2746
+ ) {
2747
+ safe.push(path[i]);
2748
+ }
2749
+ else {
2750
+ throw createError(`Invalid character in path at position ${i}: "${path[i]}"`);
2751
+ }
2752
+ }
2753
+ return safe.join('');
2754
+ }
2755
+ /**
2756
+ * Maximum author length.
2757
+ */
2758
+ const MAX_AUTHOR_LENGTH = 500;
2759
+ /**
2760
+ * Escapes an author string for safe use in git commands.
2761
+ * Format: "Name <email>"
2762
+ *
2763
+ * @param author - Author to escape
2764
+ * @returns Safe author string
2765
+ */
2766
+ function escapeAuthor(author) {
2767
+ if (!author || typeof author !== 'string') {
2768
+ throw createError('Author is required');
2769
+ }
2770
+ if (author.length > MAX_AUTHOR_LENGTH) {
2771
+ throw createError(`Author exceeds maximum length of ${MAX_AUTHOR_LENGTH}`);
2772
+ }
2773
+ const safe = [];
2774
+ for (let i = 0; i < author.length; i++) {
2775
+ const code = author.charCodeAt(i);
2776
+ // Allow: a-z, A-Z, 0-9, space, @, ., -, _, <, >
2777
+ if ((code >= 97 && code <= 122) || // a-z
2778
+ (code >= 65 && code <= 90) || // A-Z
2779
+ (code >= 48 && code <= 57) || // 0-9
2780
+ code === 32 || // space
2781
+ code === 64 || // @
2782
+ code === 46 || // .
2783
+ code === 45 || // -
2784
+ code === 95 || // _
2785
+ code === 60 || // <
2786
+ code === 62 // >
2787
+ ) {
2788
+ safe.push(author[i]);
2789
+ }
2790
+ else {
2791
+ throw createError(`Invalid character in author at position ${i}: "${author[i]}"`);
2792
+ }
2793
+ }
2794
+ return safe.join('');
2795
+ }
2796
+
2797
+ /**
2798
+ * Gets the current HEAD commit hash.
2799
+ *
2800
+ * @param options - Git operation configuration
2801
+ * @returns HEAD commit hash or null
2802
+ *
2803
+ * @example
2804
+ * const head = getHead()
2805
+ */
2806
+ function getHead(options = {}) {
2807
+ const opts = { ...DEFAULT_COMMIT_OPTIONS, ...options };
2808
+ try {
2809
+ return node_child_process.execSync('git rev-parse HEAD', {
2810
+ encoding: 'utf-8',
2811
+ cwd: opts.cwd,
2812
+ timeout: opts.timeout,
2813
+ stdio: ['pipe', 'pipe', 'pipe'],
2814
+ }).trim();
2815
+ }
2816
+ catch {
2817
+ return null;
2818
+ }
2819
+ }
2820
+ /**
2821
+ * Gets the current branch name.
2822
+ *
2823
+ * @param options - Configuration for the operation
2824
+ * @returns Branch name or null if detached
2825
+ *
2826
+ * @example
2827
+ * const branch = getCurrentBranch()
2828
+ */
2829
+ function getCurrentBranch(options = {}) {
2830
+ const opts = { ...DEFAULT_COMMIT_OPTIONS, ...options };
2831
+ try {
2832
+ const result = node_child_process.execSync('git symbolic-ref --short HEAD', {
2833
+ encoding: 'utf-8',
2834
+ cwd: opts.cwd,
2835
+ timeout: opts.timeout,
2836
+ stdio: ['pipe', 'pipe', 'pipe'],
2837
+ }).trim();
2838
+ return result || null;
2839
+ }
2840
+ catch {
2841
+ // Detached HEAD or not a git repo
2842
+ return null;
2843
+ }
2844
+ }
2845
+ /**
2846
+ * Checks if there are untracked files.
2847
+ *
2848
+ * @param options - Configuration for the operation
2849
+ * @returns True if there are untracked files in the working directory
2850
+ */
2851
+ function hasUntrackedFiles(options = {}) {
2852
+ const opts = { ...DEFAULT_COMMIT_OPTIONS, ...options };
2853
+ try {
2854
+ const result = node_child_process.execSync('git ls-files --others --exclude-standard', {
2855
+ encoding: 'utf-8',
2856
+ cwd: opts.cwd,
2857
+ timeout: opts.timeout,
2858
+ stdio: ['pipe', 'pipe', 'pipe'],
2859
+ }).trim();
2860
+ return result.length > 0;
2861
+ }
2862
+ catch {
2863
+ return false;
2864
+ }
2865
+ }
2866
+
2867
+ /**
2868
+ * Stages files for commit.
2869
+ *
2870
+ * @param files - Array of file paths relative to working directory
2871
+ * @param options - Configuration for the staging operation
2872
+ * @returns True if staging succeeded
2873
+ *
2874
+ * @example
2875
+ * stage(['package.json', 'CHANGELOG.md'])
2876
+ * stage(['.'], { all: true })
2877
+ */
2878
+ function stage(files, options = {}) {
2879
+ const opts = { ...DEFAULT_COMMIT_OPTIONS, ...options };
2880
+ const args = ['add'];
2881
+ if (opts.all) {
2882
+ args.push('-A');
2883
+ }
2884
+ else if (opts.update) {
2885
+ args.push('-u');
2886
+ }
2887
+ if (opts.force) {
2888
+ args.push('-f');
2889
+ }
2890
+ // Add files
2891
+ for (const file of files) {
2892
+ args.push(escapeFilePath(file));
2893
+ }
2894
+ try {
2895
+ node_child_process.execSync(`git ${args.join(' ')}`, {
2896
+ encoding: 'utf-8',
2897
+ cwd: opts.cwd,
2898
+ timeout: opts.timeout,
2899
+ stdio: ['pipe', 'pipe', 'pipe'],
2900
+ });
2901
+ return true;
2902
+ }
2903
+ catch {
2904
+ return false;
2905
+ }
2906
+ }
2907
+ /**
2908
+ * Unstages files.
2909
+ *
2910
+ * @param files - Array of file paths to remove from staging area
2911
+ * @param options - Configuration for the unstage operation
2912
+ * @returns True if unstaging succeeded
2913
+ *
2914
+ * @example
2915
+ * unstage(['package.json'])
2916
+ */
2917
+ function unstage(files, options = {}) {
2918
+ const opts = { ...DEFAULT_COMMIT_OPTIONS, ...options };
2919
+ const args = ['reset', 'HEAD', '--'];
2920
+ for (const file of files) {
2921
+ args.push(escapeFilePath(file));
2922
+ }
2923
+ try {
2924
+ node_child_process.execSync(`git ${args.join(' ')}`, {
2925
+ encoding: 'utf-8',
2926
+ cwd: opts.cwd,
2927
+ timeout: opts.timeout,
2928
+ stdio: ['pipe', 'pipe', 'pipe'],
2929
+ });
2930
+ return true;
2931
+ }
2932
+ catch {
2933
+ return false;
2934
+ }
2935
+ }
2936
+ /**
2937
+ * Stages all changes (tracked and untracked).
2938
+ *
2939
+ * @param options - Configuration for the staging operation
2940
+ * @returns True if all changes were successfully added to the index
2941
+ *
2942
+ * @example
2943
+ * stageAll() // stages all tracked and untracked changes
2944
+ */
2945
+ function stageAll(options = {}) {
2946
+ return stage(['.'], { ...options, all: true });
2947
+ }
2948
+ /**
2949
+ * Checks if there are staged changes.
2950
+ *
2951
+ * @param options - Configuration for the operation
2952
+ * @returns True if there are staged changes ready to commit
2953
+ *
2954
+ * @example
2955
+ * if (hasStagedChanges()) { createCommit('...') }
2956
+ */
2957
+ function hasStagedChanges(options = {}) {
2958
+ const opts = { ...DEFAULT_COMMIT_OPTIONS, ...options };
2959
+ try {
2960
+ node_child_process.execSync('git diff --cached --quiet', {
2961
+ encoding: 'utf-8',
2962
+ cwd: opts.cwd,
2963
+ timeout: opts.timeout,
2964
+ stdio: ['pipe', 'pipe', 'pipe'],
2965
+ });
2966
+ // Exit code 0 means no changes
2967
+ return false;
2968
+ }
2969
+ catch {
2970
+ // Exit code 1 means there are changes
2971
+ return true;
2972
+ }
2973
+ }
2974
+ /**
2975
+ * Checks if there are unstaged changes (working tree dirty).
2976
+ *
2977
+ * @param options - Configuration for the operation
2978
+ * @returns True if there are unstaged changes in the working tree
2979
+ *
2980
+ * @example
2981
+ * if (hasUnstagedChanges()) { stage(['.']) }
2982
+ */
2983
+ function hasUnstagedChanges(options = {}) {
2984
+ const opts = { ...DEFAULT_COMMIT_OPTIONS, ...options };
2985
+ try {
2986
+ node_child_process.execSync('git diff --quiet', {
2987
+ encoding: 'utf-8',
2988
+ cwd: opts.cwd,
2989
+ timeout: opts.timeout,
2990
+ stdio: ['pipe', 'pipe', 'pipe'],
2991
+ });
2992
+ // Exit code 0 means no changes
2993
+ return false;
2994
+ }
2995
+ catch {
2996
+ // Exit code 1 means there are changes
2997
+ return true;
2998
+ }
2999
+ }
3000
+
3001
+ /**
3002
+ * Default status options.
3003
+ */
3004
+ const DEFAULT_STATUS_OPTIONS = {
3005
+ timeout: 10000,
3006
+ };
3007
+ /**
3008
+ * Gets the full repository status.
3009
+ *
3010
+ * @param options - Configuration for the status query
3011
+ * @returns Comprehensive repository status information
3012
+ *
3013
+ * @example
3014
+ * const status = getStatus()
3015
+ * if (!status.clean) {
3016
+ * console.log('Working tree has changes')
3017
+ * }
3018
+ */
3019
+ function getStatus(options = {}) {
3020
+ const opts = { ...DEFAULT_STATUS_OPTIONS, ...options };
3021
+ // Get porcelain status with branch info
3022
+ const output = node_child_process.execSync('git status --porcelain=v2 --branch', {
3023
+ encoding: 'utf-8',
3024
+ cwd: opts.cwd,
3025
+ timeout: opts.timeout,
3026
+ stdio: ['pipe', 'pipe', 'pipe'],
3027
+ });
3028
+ return parseStatus(output);
3029
+ }
3030
+ /**
3031
+ * Parses git status porcelain v2 output.
3032
+ *
3033
+ * @param output - Raw status output
3034
+ * @returns Parsed status
3035
+ */
3036
+ function parseStatus(output) {
3037
+ const lines = output.split('\n');
3038
+ let branch = null;
3039
+ let detached = false;
3040
+ let upstream;
3041
+ let ahead = 0;
3042
+ let behind = 0;
3043
+ const staged = [];
3044
+ const modified = [];
3045
+ const untracked = [];
3046
+ let hasConflicts = false;
3047
+ for (const line of lines) {
3048
+ if (!line)
3049
+ continue;
3050
+ // Branch headers
3051
+ if (startsWithPrefix(line, '# branch.head ')) {
3052
+ const branchName = line.slice(14);
3053
+ if (branchName === '(detached)') {
3054
+ detached = true;
3055
+ }
3056
+ else {
3057
+ branch = branchName;
3058
+ }
3059
+ }
3060
+ else if (startsWithPrefix(line, '# branch.upstream ')) {
3061
+ upstream = line.slice(18);
3062
+ }
3063
+ else if (startsWithPrefix(line, '# branch.ab ')) {
3064
+ const ab = parseAheadBehind(line.slice(12));
3065
+ ahead = ab.ahead;
3066
+ behind = ab.behind;
3067
+ }
3068
+ // Changed entries (ordinary changed)
3069
+ else if (line[0] === '1') {
3070
+ const entry = parseChangedEntry(line);
3071
+ if (entry) {
3072
+ if (entry.indexStatus) {
3073
+ staged.push(entry);
3074
+ }
3075
+ if (entry.workTreeStatus && entry.workTreeStatus !== 'untracked') {
3076
+ modified.push(entry);
3077
+ }
3078
+ }
3079
+ }
3080
+ // Renamed/copied entries
3081
+ else if (line[0] === '2') {
3082
+ const entry = parseRenamedEntry(line);
3083
+ if (entry) {
3084
+ if (entry.indexStatus) {
3085
+ staged.push(entry);
3086
+ }
3087
+ if (entry.workTreeStatus) {
3088
+ modified.push(entry);
3089
+ }
3090
+ }
3091
+ }
3092
+ // Unmerged entries
3093
+ else if (line[0] === 'u') {
3094
+ hasConflicts = true;
3095
+ const entry = parseUnmergedEntry(line);
3096
+ if (entry) {
3097
+ staged.push(entry);
3098
+ }
3099
+ }
3100
+ // Untracked entries
3101
+ else if (line[0] === '?') {
3102
+ const path = line.slice(2);
3103
+ untracked.push(path);
3104
+ }
3105
+ }
3106
+ const clean = staged.length === 0 && modified.length === 0 && untracked.length === 0 && !hasConflicts;
3107
+ return {
3108
+ branch,
3109
+ detached,
3110
+ upstream,
3111
+ ahead,
3112
+ behind,
3113
+ staged,
3114
+ modified,
3115
+ untracked,
3116
+ clean,
3117
+ hasConflicts,
3118
+ };
3119
+ }
3120
+ /**
3121
+ * Parses ahead/behind string.
3122
+ *
3123
+ * @param str - String like "+5 -2"
3124
+ * @returns Parsed values
3125
+ */
3126
+ function parseAheadBehind(str) {
3127
+ let ahead = 0;
3128
+ let behind = 0;
3129
+ const parts = str.split(' ');
3130
+ for (const part of parts) {
3131
+ if (part[0] === '+') {
3132
+ ahead = parseInt(part.slice(1), 10) || 0;
3133
+ }
3134
+ else if (part[0] === '-') {
3135
+ behind = parseInt(part.slice(1), 10) || 0;
3136
+ }
3137
+ }
3138
+ return { ahead, behind };
3139
+ }
3140
+ /**
3141
+ * Parses a changed entry line.
3142
+ *
3143
+ * @param line - Status line starting with '1'
3144
+ * @returns Parsed entry or null
3145
+ */
3146
+ function parseChangedEntry(line) {
3147
+ // Format: 1 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <path>
3148
+ const parts = line.split(' ');
3149
+ if (parts.length < 9)
3150
+ return null;
3151
+ const xy = parts[1];
3152
+ const path = parts.slice(8).join(' ');
3153
+ const indexStatus = statusFromChar(xy[0]);
3154
+ const workTreeStatus = statusFromChar(xy[1]);
3155
+ return {
3156
+ path,
3157
+ indexStatus,
3158
+ workTreeStatus,
3159
+ };
3160
+ }
3161
+ /**
3162
+ * Parses a renamed entry line.
3163
+ *
3164
+ * @param line - Status line starting with '2'
3165
+ * @returns Parsed entry or null
3166
+ */
3167
+ function parseRenamedEntry(line) {
3168
+ // Format: 2 <XY> <sub> <mH> <mI> <mW> <hH> <hI> <X><score> <path><tab><origPath>
3169
+ const parts = line.split(' ');
3170
+ if (parts.length < 10)
3171
+ return null;
3172
+ const xy = parts[1];
3173
+ const pathPart = parts.slice(9).join(' ');
3174
+ // Split by tab
3175
+ const tabIndex = pathPart.indexOf('\t');
3176
+ const path = tabIndex >= 0 ? pathPart.slice(0, tabIndex) : pathPart;
3177
+ const origPath = tabIndex >= 0 ? pathPart.slice(tabIndex + 1) : undefined;
3178
+ const indexStatus = statusFromChar(xy[0]);
3179
+ const workTreeStatus = statusFromChar(xy[1]);
3180
+ return {
3181
+ path,
3182
+ indexStatus,
3183
+ workTreeStatus,
3184
+ origPath,
3185
+ };
3186
+ }
3187
+ /**
3188
+ * Parses an unmerged entry line.
3189
+ *
3190
+ * @param line - Status line starting with 'u'
3191
+ * @returns Parsed entry or null
3192
+ */
3193
+ function parseUnmergedEntry(line) {
3194
+ // Format: u <XY> <sub> <m1> <m2> <m3> <mW> <h1> <h2> <h3> <path>
3195
+ const parts = line.split(' ');
3196
+ if (parts.length < 11)
3197
+ return null;
3198
+ const path = parts.slice(10).join(' ');
3199
+ return {
3200
+ path,
3201
+ indexStatus: 'unmerged',
3202
+ workTreeStatus: 'unmerged',
3203
+ };
3204
+ }
3205
+ /**
3206
+ * Converts status character to FileStatus.
3207
+ *
3208
+ * @param char - Status character
3209
+ * @returns FileStatus or null
3210
+ */
3211
+ function statusFromChar(char) {
3212
+ switch (char) {
3213
+ case 'M':
3214
+ return 'modified';
3215
+ case 'T':
3216
+ return 'modified'; // Type change
3217
+ case 'A':
3218
+ return 'added';
3219
+ case 'D':
3220
+ return 'deleted';
3221
+ case 'R':
3222
+ return 'renamed';
3223
+ case 'C':
3224
+ return 'copied';
3225
+ case 'U':
3226
+ return 'unmerged';
3227
+ case '?':
3228
+ return 'untracked';
3229
+ case '!':
3230
+ return 'ignored';
3231
+ case '.':
3232
+ return null;
3233
+ default:
3234
+ return null;
3235
+ }
3236
+ }
3237
+ /**
3238
+ * Checks if string starts with prefix (no regex).
3239
+ *
3240
+ * @param str - The string to check
3241
+ * @param prefix - The prefix to look for
3242
+ * @returns True if str starts with the given prefix
3243
+ */
3244
+ function startsWithPrefix(str, prefix) {
3245
+ if (prefix.length > str.length)
3246
+ return false;
3247
+ for (let i = 0; i < prefix.length; i++) {
3248
+ if (str[i] !== prefix[i])
3249
+ return false;
3250
+ }
3251
+ return true;
3252
+ }
3253
+ /**
3254
+ * Checks if the working tree is clean (no changes).
3255
+ *
3256
+ * @param options - Configuration for the status check
3257
+ * @returns True if working tree is clean with no uncommitted changes
3258
+ *
3259
+ * @example
3260
+ * if (!isClean()) {
3261
+ * throw new Error('Working tree has changes')
3262
+ * }
3263
+ */
3264
+ function isClean(options = {}) {
3265
+ const status = getStatus(options);
3266
+ return status.clean;
3267
+ }
3268
+ /**
3269
+ * Checks if the directory is a git repository.
3270
+ *
3271
+ * @param options - Status options
3272
+ * @returns True if in a git repository
3273
+ *
3274
+ * @example
3275
+ * if (!isGitRepository()) {
3276
+ * throw new Error('Not a git repository')
3277
+ * }
3278
+ */
3279
+ function isGitRepository(options = {}) {
3280
+ const opts = { ...DEFAULT_STATUS_OPTIONS, ...options };
3281
+ try {
3282
+ node_child_process.execSync('git rev-parse --is-inside-work-tree', {
3283
+ encoding: 'utf-8',
3284
+ cwd: opts.cwd,
3285
+ timeout: opts.timeout,
3286
+ stdio: ['pipe', 'pipe', 'pipe'],
3287
+ });
3288
+ return true;
3289
+ }
3290
+ catch {
3291
+ return false;
3292
+ }
3293
+ }
3294
+ /**
3295
+ * Gets the repository root directory.
3296
+ *
3297
+ * @param options - Status options
3298
+ * @returns Root directory path or null
3299
+ *
3300
+ * @example
3301
+ * const root = getRepositoryRoot()
3302
+ */
3303
+ function getRepositoryRoot(options = {}) {
3304
+ const opts = { ...DEFAULT_STATUS_OPTIONS, ...options };
3305
+ try {
3306
+ return node_child_process.execSync('git rev-parse --show-toplevel', {
3307
+ encoding: 'utf-8',
3308
+ cwd: opts.cwd,
3309
+ timeout: opts.timeout,
3310
+ stdio: ['pipe', 'pipe', 'pipe'],
3311
+ }).trim();
3312
+ }
3313
+ catch {
3314
+ return null;
3315
+ }
3316
+ }
3317
+ /**
3318
+ * Gets the current commit hash (HEAD).
3319
+ *
3320
+ * @param options - Status options
3321
+ * @returns Commit hash or null
3322
+ */
3323
+ function getHeadHash(options = {}) {
3324
+ const opts = { ...DEFAULT_STATUS_OPTIONS, ...options };
3325
+ try {
3326
+ return node_child_process.execSync('git rev-parse HEAD', {
3327
+ encoding: 'utf-8',
3328
+ cwd: opts.cwd,
3329
+ timeout: opts.timeout,
3330
+ stdio: ['pipe', 'pipe', 'pipe'],
3331
+ }).trim();
3332
+ }
3333
+ catch {
3334
+ return null;
3335
+ }
3336
+ }
3337
+ /**
3338
+ * Gets the short current commit hash.
3339
+ *
3340
+ * @param options - Status options
3341
+ * @returns Short hash or null
3342
+ */
3343
+ function getHeadShortHash(options = {}) {
3344
+ const opts = { ...DEFAULT_STATUS_OPTIONS, ...options };
3345
+ try {
3346
+ return node_child_process.execSync('git rev-parse --short HEAD', {
3347
+ encoding: 'utf-8',
3348
+ cwd: opts.cwd,
3349
+ timeout: opts.timeout,
3350
+ stdio: ['pipe', 'pipe', 'pipe'],
3351
+ }).trim();
3352
+ }
3353
+ catch {
3354
+ return null;
3355
+ }
3356
+ }
3357
+ /**
3358
+ * Checks if there are merge conflicts.
3359
+ *
3360
+ * @param options - Status options
3361
+ * @returns True if there are conflicts
3362
+ */
3363
+ function hasConflicts(options = {}) {
3364
+ const status = getStatus(options);
3365
+ return status.hasConflicts;
3366
+ }
3367
+ /**
3368
+ * Gets the number of commits ahead of upstream.
3369
+ *
3370
+ * @param options - Status options
3371
+ * @returns Number of commits ahead
3372
+ */
3373
+ function getAheadCount(options = {}) {
3374
+ const status = getStatus(options);
3375
+ return status.ahead;
3376
+ }
3377
+ /**
3378
+ * Gets the number of commits behind upstream.
3379
+ *
3380
+ * @param options - Status options
3381
+ * @returns Number of commits behind
3382
+ */
3383
+ function getBehindCount(options = {}) {
3384
+ const status = getStatus(options);
3385
+ return status.behind;
3386
+ }
3387
+ /**
3388
+ * Checks if the repository needs to be pushed.
3389
+ *
3390
+ * @param options - Status options
3391
+ * @returns True if there are unpushed commits
3392
+ */
3393
+ function needsPush(options = {}) {
3394
+ return getAheadCount(options) > 0;
3395
+ }
3396
+ /**
3397
+ * Checks if the repository needs to be pulled.
3398
+ *
3399
+ * @param options - Status options
3400
+ * @returns True if there are commits to pull
3401
+ */
3402
+ function needsPull(options = {}) {
3403
+ return getBehindCount(options) > 0;
3404
+ }
3405
+ /**
3406
+ * Gets list of staged file paths.
3407
+ *
3408
+ * @param options - Status options
3409
+ * @returns Array of staged file paths
3410
+ */
3411
+ function getStagedFiles(options = {}) {
3412
+ const status = getStatus(options);
3413
+ return status.staged.map((e) => e.path);
3414
+ }
3415
+ /**
3416
+ * Gets list of modified file paths (unstaged).
3417
+ *
3418
+ * @param options - Status options
3419
+ * @returns Array of modified file paths
3420
+ */
3421
+ function getModifiedFiles(options = {}) {
3422
+ const status = getStatus(options);
3423
+ return status.modified.map((e) => e.path);
3424
+ }
3425
+ /**
3426
+ * Gets list of untracked file paths.
3427
+ *
3428
+ * @param options - Status options
3429
+ * @returns Array of untracked file paths
3430
+ */
3431
+ function getUntrackedFiles(options = {}) {
3432
+ const status = getStatus(options);
3433
+ return status.untracked;
3434
+ }
3435
+
3436
+ /**
3437
+ * Default git client configuration.
3438
+ */
3439
+ const DEFAULT_GIT_CLIENT_CONFIG = {
3440
+ cwd: process.cwd(),
3441
+ timeout: 30000,
3442
+ throwOnError: true,
3443
+ };
3444
+ /**
3445
+ * Creates a git client for a specific working directory.
3446
+ *
3447
+ * @param config - Client configuration
3448
+ * @returns GitClient instance
3449
+ *
3450
+ * @example
3451
+ * const git = createGitClient({ cwd: '/path/to/repo' })
3452
+ * const status = git.getStatus()
3453
+ * const commits = git.getCommitsSince('v1.0.0')
3454
+ */
3455
+ function createGitClient(config = {}) {
3456
+ const cwd = config.cwd ?? process.cwd();
3457
+ const timeout = config.timeout ?? DEFAULT_GIT_CLIENT_CONFIG.timeout;
3458
+ const opts = { cwd, timeout };
3459
+ return {
3460
+ cwd,
3461
+ timeout,
3462
+ // Log operations
3463
+ getCommitLog: (options) => getCommitLog({ ...opts, ...options }),
3464
+ getCommitsBetween: (from, to, options) => getCommitsBetween(from, to, { ...opts, ...options }),
3465
+ getCommitsSince: (since, options) => getCommitsSince(since, { ...opts, ...options }),
3466
+ getCommit: (hash) => getCommit(hash, opts),
3467
+ commitExists: (hash) => commitExists(hash, opts),
3468
+ // Tag operations
3469
+ getTags: (options) => getTags({ ...opts, ...options }),
3470
+ getTag: (name) => getTag(name, opts),
3471
+ createTag: (name, options) => createTag(name, { ...opts, ...options }),
3472
+ deleteTag: (name) => deleteTag(name, opts),
3473
+ tagExists: (name) => tagExists(name, opts),
3474
+ getLatestTag: (options) => getLatestTag({ ...opts, ...options }),
3475
+ getTagsForPackage: (packageName, options) => getTagsForPackage(packageName, { ...opts, ...options }),
3476
+ pushTag: (name, remote) => pushTag(name, remote, opts),
3477
+ // Commit operations
3478
+ createCommit: (message, options) => commit(message, { ...opts, ...options }),
3479
+ stage: (files, options) => stage(files, { ...opts, ...options }),
3480
+ unstage: (files) => unstage(files, opts),
3481
+ stageAll: () => stageAll(opts),
3482
+ amendCommit: (message, options) => amendCommit(message, { ...opts, ...options }),
3483
+ createEmptyCommit: (message, options) => createEmptyCommit(message, { ...opts, ...options }),
3484
+ getHead: () => getHead(opts),
3485
+ getCurrentBranch: () => getCurrentBranch(opts),
3486
+ hasStagedChanges: () => hasStagedChanges(opts),
3487
+ hasUnstagedChanges: () => hasUnstagedChanges(opts),
3488
+ hasUntrackedFiles: () => hasUntrackedFiles(opts),
3489
+ // Status operations
3490
+ getStatus: () => getStatus(opts),
3491
+ isClean: () => isClean(opts),
3492
+ isGitRepository: () => isGitRepository(opts),
3493
+ getRepositoryRoot: () => getRepositoryRoot(opts),
3494
+ getHeadHash: () => getHeadHash(opts),
3495
+ getHeadShortHash: () => getHeadShortHash(opts),
3496
+ hasConflicts: () => hasConflicts(opts),
3497
+ getAheadCount: () => getAheadCount(opts),
3498
+ getBehindCount: () => getBehindCount(opts),
3499
+ needsPush: () => needsPush(opts),
3500
+ needsPull: () => needsPull(opts),
3501
+ getStagedFiles: () => getStagedFiles(opts),
3502
+ getModifiedFiles: () => getModifiedFiles(opts),
3503
+ getUntrackedFiles: () => getUntrackedFiles(opts),
3504
+ // Ref operations
3505
+ getRefs: () => getRefs(opts),
3506
+ getBranches: () => getBranches(opts),
3507
+ getRemoteBranches: (remote) => getRemoteBranches(opts, remote),
3508
+ fetch: (remote, options) => fetch(opts, remote, options),
3509
+ pull: (remote, branch) => pull(opts, remote, branch),
3510
+ push: (remote, branch, options) => push(opts, remote, branch, options),
3511
+ };
3512
+ }
3513
+ // ============================================================================
3514
+ // Additional ref operations used by the client
3515
+ // ============================================================================
3516
+ /**
3517
+ * Gets all refs from the repository.
3518
+ *
3519
+ * @param options - Configuration object containing cwd and timeout
3520
+ * @param options.cwd - Working directory for the git command
3521
+ * @param options.timeout - Command timeout in milliseconds
3522
+ * @returns Array of GitRef objects representing all refs in the repository
3523
+ */
3524
+ function getRefs(options) {
3525
+ try {
3526
+ const output = node_child_process.execSync('git show-ref', {
3527
+ encoding: 'utf-8',
3528
+ cwd: options.cwd,
3529
+ timeout: options.timeout,
3530
+ stdio: ['pipe', 'pipe', 'pipe'],
3531
+ });
3532
+ const refs = [];
3533
+ const lines = output.split('\n');
3534
+ for (const line of lines) {
3535
+ const trimmed = line.trim();
3536
+ if (!trimmed)
3537
+ continue;
3538
+ // Format: <hash> <refname>
3539
+ const spaceIndex = trimmed.indexOf(' ');
3540
+ if (spaceIndex === -1)
3541
+ continue;
3542
+ const hash = trimmed.slice(0, spaceIndex);
3543
+ const fullName = trimmed.slice(spaceIndex + 1);
3544
+ refs.push(createGitRef({ fullName, commitHash: hash }));
3545
+ }
3546
+ return refs;
3547
+ }
3548
+ catch {
3549
+ return [];
3550
+ }
3551
+ }
3552
+ /**
3553
+ * Gets local branches.
3554
+ *
3555
+ * @param options - Configuration object containing cwd and timeout
3556
+ * @param options.cwd - Working directory for the git command
3557
+ * @param options.timeout - Command timeout in milliseconds
3558
+ * @returns Array of GitRef objects representing local branches
3559
+ */
3560
+ function getBranches(options) {
3561
+ const refs = getRefs(options);
3562
+ return refs.filter((ref) => ref.type === 'branch');
3563
+ }
3564
+ /**
3565
+ * Gets remote branches.
3566
+ *
3567
+ * @param options - Configuration object containing cwd and timeout
3568
+ * @param options.cwd - Working directory for the git command
3569
+ * @param options.timeout - Command timeout in milliseconds
3570
+ * @param remote - Optional remote name to filter branches by
3571
+ * @returns Array of GitRef objects representing remote branches
3572
+ */
3573
+ function getRemoteBranches(options, remote) {
3574
+ const refs = getRefs(options);
3575
+ return refs.filter((ref) => {
3576
+ if (ref.type !== 'remote')
3577
+ return false;
3578
+ if (remote && ref.remote !== remote)
3579
+ return false;
3580
+ return true;
3581
+ });
3582
+ }
3583
+ /**
3584
+ * Fetches from remote.
3585
+ *
3586
+ * @param options - Configuration object containing cwd and timeout
3587
+ * @param options.cwd - Working directory for the git command
3588
+ * @param options.timeout - Command timeout in milliseconds
3589
+ * @param remote - Remote name to fetch from (defaults to 'origin')
3590
+ * @param fetchOptions - Additional fetch configuration
3591
+ * @param fetchOptions.prune - Whether to prune deleted remote branches
3592
+ * @param fetchOptions.tags - Whether to fetch tags
3593
+ * @returns True if fetch succeeded
3594
+ */
3595
+ function fetch(options, remote = 'origin', fetchOptions) {
3596
+ const args = ['fetch', remote];
3597
+ if (fetchOptions?.prune) {
3598
+ args.push('--prune');
3599
+ }
3600
+ if (fetchOptions?.tags) {
3601
+ args.push('--tags');
3602
+ }
3603
+ try {
3604
+ node_child_process.execSync(`git ${args.join(' ')}`, {
3605
+ encoding: 'utf-8',
3606
+ cwd: options.cwd,
3607
+ timeout: options.timeout * 3, // Allow more time for network
3608
+ stdio: ['pipe', 'pipe', 'pipe'],
3609
+ });
3610
+ return true;
3611
+ }
3612
+ catch {
3613
+ return false;
3614
+ }
3615
+ }
3616
+ /**
3617
+ * Pulls from remote.
3618
+ *
3619
+ * @param options - Configuration object containing cwd and timeout
3620
+ * @param options.cwd - Working directory for the git command
3621
+ * @param options.timeout - Command timeout in milliseconds
3622
+ * @param remote - Remote name to pull from (defaults to 'origin')
3623
+ * @param branch - Optional branch name to pull
3624
+ * @returns True if pull succeeded
3625
+ */
3626
+ function pull(options, remote = 'origin', branch) {
3627
+ const args = ['pull', remote];
3628
+ if (branch) {
3629
+ args.push(branch);
3630
+ }
3631
+ try {
3632
+ node_child_process.execSync(`git ${args.join(' ')}`, {
3633
+ encoding: 'utf-8',
3634
+ cwd: options.cwd,
3635
+ timeout: options.timeout * 3,
3636
+ stdio: ['pipe', 'pipe', 'pipe'],
3637
+ });
3638
+ return true;
3639
+ }
3640
+ catch {
3641
+ return false;
3642
+ }
3643
+ }
3644
+ /**
3645
+ * Pushes to remote.
3646
+ *
3647
+ * @param options - Configuration object containing cwd and timeout
3648
+ * @param options.cwd - Working directory for the git command
3649
+ * @param options.timeout - Command timeout in milliseconds
3650
+ * @param remote - Remote name to push to (defaults to 'origin')
3651
+ * @param branch - Optional branch name to push
3652
+ * @param pushOptions - Additional push configuration
3653
+ * @param pushOptions.force - Whether to force push
3654
+ * @param pushOptions.setUpstream - Whether to set upstream tracking
3655
+ * @returns True if push succeeded
3656
+ */
3657
+ function push(options, remote = 'origin', branch, pushOptions) {
3658
+ const args = ['push', remote];
3659
+ if (branch) {
3660
+ args.push(branch);
3661
+ }
3662
+ if (pushOptions?.force) {
3663
+ args.push('--force');
3664
+ }
3665
+ if (pushOptions?.setUpstream) {
3666
+ args.push('--set-upstream');
3667
+ }
3668
+ try {
3669
+ node_child_process.execSync(`git ${args.join(' ')}`, {
3670
+ encoding: 'utf-8',
3671
+ cwd: options.cwd,
3672
+ timeout: options.timeout * 3,
3673
+ stdio: ['pipe', 'pipe', 'pipe'],
3674
+ });
3675
+ return true;
3676
+ }
3677
+ catch {
3678
+ return false;
3679
+ }
3680
+ }
3681
+
3682
+ /**
3683
+ * Creates a new cache instance.
3684
+ *
3685
+ * @param ttl - Time-to-live in milliseconds (default: 60000 = 1 minute)
3686
+ * @returns A new Cache instance
3687
+ */
3688
+ function createCache(ttl = 60000) {
3689
+ const entries = createMap();
3690
+ return {
3691
+ get(key) {
3692
+ const entry = entries.get(key);
3693
+ if (!entry)
3694
+ return undefined;
3695
+ const now = dateNow();
3696
+ if (now - entry.timestamp > ttl) {
3697
+ entries.delete(key);
3698
+ return undefined;
3699
+ }
3700
+ return entry.data;
3701
+ },
3702
+ set(key, value) {
3703
+ entries.set(key, { data: value, timestamp: dateNow() });
3704
+ },
3705
+ delete(key) {
3706
+ entries.delete(key);
3707
+ },
3708
+ clear() {
3709
+ entries.clear();
3710
+ },
3711
+ size() {
3712
+ return entries.size;
3713
+ },
3714
+ };
3715
+ }
3716
+
3717
+ /**
3718
+ * Creates an npm registry client.
3719
+ *
3720
+ * @param config - Registry configuration
3721
+ * @returns A Registry implementation for npm
3722
+ *
3723
+ * @example
3724
+ * const registry = createNpmRegistry()
3725
+ * const version = await registry.getLatestVersion('@hyperfrontend/utils')
3726
+ */
3727
+ function createNpmRegistry(config = {}) {
3728
+ const state = {
3729
+ config: {
3730
+ url: config.url ?? 'https://registry.npmjs.org',
3731
+ timeout: config.timeout ?? 10000,
3732
+ cacheTtl: config.cacheTtl ?? 60000,
3733
+ authToken: config.authToken,
3734
+ },
3735
+ cache: createCache(config.cacheTtl ?? 60000),
3736
+ };
3737
+ return {
3738
+ name: 'npm',
3739
+ url: state.config.url,
3740
+ getLatestVersion: (packageName) => getLatestVersion(state, packageName),
3741
+ isVersionPublished: (packageName, version) => isVersionPublished(state, packageName, version),
3742
+ getPackageInfo: (packageName) => getPackageInfo(state, packageName),
3743
+ getVersionInfo: (packageName, version) => getVersionInfo(state, packageName, version),
3744
+ listVersions: (packageName) => listVersions(state, packageName),
3745
+ };
3746
+ }
3747
+ /**
3748
+ * Gets the latest published version of a package.
3749
+ *
3750
+ * @param state - Internal registry client state
3751
+ * @param packageName - Name of the package to query
3752
+ * @returns The latest version string, or null if not found
3753
+ */
3754
+ async function getLatestVersion(state, packageName) {
3755
+ const cacheKey = `latest:${packageName}`;
3756
+ const cached = state.cache.get(cacheKey);
3757
+ if (cached !== undefined)
3758
+ return cached;
3759
+ try {
3760
+ const safeName = escapePackageName(packageName);
3761
+ const result = node_child_process.execSync(`npm view ${safeName} version`, {
3762
+ encoding: 'utf-8',
3763
+ timeout: state.config.timeout,
3764
+ stdio: ['pipe', 'pipe', 'pipe'],
3765
+ }).trim();
3766
+ const version = result || null;
3767
+ state.cache.set(cacheKey, version);
3768
+ return version;
3769
+ }
3770
+ catch {
3771
+ state.cache.set(cacheKey, null);
3772
+ return null;
3773
+ }
3774
+ }
3775
+ /**
3776
+ * Checks if a specific version is published.
3777
+ *
3778
+ * @param state - Internal registry client state
3779
+ * @param packageName - Name of the package to check
3780
+ * @param version - Semver version string to verify
3781
+ * @returns True if the version is published
3782
+ */
3783
+ async function isVersionPublished(state, packageName, version) {
3784
+ const cacheKey = `published:${packageName}@${version}`;
3785
+ const cached = state.cache.get(cacheKey);
3786
+ if (cached !== undefined)
3787
+ return cached;
3788
+ try {
3789
+ const safeName = escapePackageName(packageName);
3790
+ const safeVersion = escapeVersion(version);
3791
+ const result = node_child_process.execSync(`npm view ${safeName}@${safeVersion} version`, {
3792
+ encoding: 'utf-8',
3793
+ timeout: state.config.timeout,
3794
+ stdio: ['pipe', 'pipe', 'pipe'],
3795
+ }).trim();
3796
+ const published = result === version;
3797
+ state.cache.set(cacheKey, published);
3798
+ return published;
3799
+ }
3800
+ catch {
3801
+ state.cache.set(cacheKey, false);
3802
+ return false;
3803
+ }
3804
+ }
3805
+ /**
3806
+ * Gets full package information.
3807
+ *
3808
+ * @param state - Internal registry client state
3809
+ * @param packageName - Name of the package to query
3810
+ * @returns Package info, or null if not found
3811
+ */
3812
+ async function getPackageInfo(state, packageName) {
3813
+ const cacheKey = `info:${packageName}`;
3814
+ const cached = state.cache.get(cacheKey);
3815
+ if (cached !== undefined)
3816
+ return cached;
3817
+ try {
3818
+ const safeName = escapePackageName(packageName);
3819
+ const result = node_child_process.execSync(`npm view ${safeName} --json`, {
3820
+ encoding: 'utf-8',
3821
+ timeout: state.config.timeout,
3822
+ stdio: ['pipe', 'pipe', 'pipe'],
3823
+ maxBuffer: 10 * 1024 * 1024, // 10MB
3824
+ });
3825
+ const data = parse(result);
3826
+ const info = {
3827
+ name: data.name,
3828
+ description: data.description,
3829
+ latestVersion: data.version,
3830
+ versions: isArray(data.versions) ? data.versions : [data.version],
3831
+ license: data.license,
3832
+ repository: extractRepoUrl(data.repository),
3833
+ homepage: data.homepage,
3834
+ maintainers: (data.maintainers ?? []).map((m) => {
3835
+ if (typeof m === 'string') {
3836
+ return { name: m };
3837
+ }
3838
+ return { name: m.name ?? '', email: m.email };
3839
+ }),
3840
+ keywords: data.keywords,
3841
+ lastModified: data.time?.modified,
3842
+ };
3843
+ state.cache.set(cacheKey, info);
3844
+ return info;
3845
+ }
3846
+ catch {
3847
+ state.cache.set(cacheKey, null);
3848
+ return null;
3849
+ }
3850
+ }
3851
+ /**
3852
+ * Gets version-specific information.
3853
+ *
3854
+ * @param state - Internal registry client state
3855
+ * @param packageName - Name of the package to query
3856
+ * @param version - Semver version string to look up
3857
+ * @returns Version info, or null if not found
3858
+ */
3859
+ async function getVersionInfo(state, packageName, version) {
3860
+ const cacheKey = `versionInfo:${packageName}@${version}`;
3861
+ const cached = state.cache.get(cacheKey);
3862
+ if (cached !== undefined)
3863
+ return cached;
3864
+ try {
3865
+ const safeName = escapePackageName(packageName);
3866
+ const safeVersion = escapeVersion(version);
3867
+ const result = node_child_process.execSync(`npm view ${safeName}@${safeVersion} --json`, {
3868
+ encoding: 'utf-8',
3869
+ timeout: state.config.timeout,
3870
+ stdio: ['pipe', 'pipe', 'pipe'],
3871
+ maxBuffer: 5 * 1024 * 1024, // 5MB
3872
+ });
3873
+ const data = parse(result);
3874
+ const info = {
3875
+ version: data.version,
3876
+ publishedAt: data.time ?? createDate().toISOString(),
3877
+ tarball: data.dist?.tarball ?? '',
3878
+ integrity: data.dist?.integrity,
3879
+ dependencies: data.dependencies,
3880
+ devDependencies: data.devDependencies,
3881
+ peerDependencies: data.peerDependencies,
3882
+ optionalDependencies: data.optionalDependencies,
3883
+ engines: data.engines,
3884
+ nodeVersion: data._nodeVersion,
3885
+ npmVersion: data._npmVersion,
3886
+ };
3887
+ state.cache.set(cacheKey, info);
3888
+ return info;
3889
+ }
3890
+ catch {
3891
+ state.cache.set(cacheKey, null);
3892
+ return null;
3893
+ }
3894
+ }
3895
+ /**
3896
+ * Lists all published versions.
3897
+ *
3898
+ * @param state - Internal registry client state
3899
+ * @param packageName - Name of the package to query
3900
+ * @returns Array of version strings
3901
+ */
3902
+ async function listVersions(state, packageName) {
3903
+ const cacheKey = `versions:${packageName}`;
3904
+ const cached = state.cache.get(cacheKey);
3905
+ if (cached !== undefined)
3906
+ return cached;
3907
+ try {
3908
+ const safeName = escapePackageName(packageName);
3909
+ const result = node_child_process.execSync(`npm view ${safeName} versions --json`, {
3910
+ encoding: 'utf-8',
3911
+ timeout: state.config.timeout,
3912
+ stdio: ['pipe', 'pipe', 'pipe'],
3913
+ });
3914
+ const versions = parse(result);
3915
+ const versionList = isArray(versions) ? versions : [versions];
3916
+ state.cache.set(cacheKey, versionList);
3917
+ return versionList;
3918
+ }
3919
+ catch {
3920
+ state.cache.set(cacheKey, []);
3921
+ return [];
3922
+ }
3923
+ }
3924
+ // ============================================================================
3925
+ // Security helpers - character-by-character validation (no regex)
3926
+ // ============================================================================
3927
+ /**
3928
+ * Maximum allowed package name length (npm limit).
3929
+ */
3930
+ const MAX_PACKAGE_NAME_LENGTH = 214;
3931
+ /**
3932
+ * Escapes a package name for safe use in shell commands.
3933
+ * Uses character-by-character validation to prevent injection.
3934
+ *
3935
+ * @param name - Package name to escape
3936
+ * @returns Safe package name
3937
+ * @throws {Error} If package name contains invalid characters
3938
+ */
3939
+ function escapePackageName(name) {
3940
+ if (!name || typeof name !== 'string') {
3941
+ throw createError('Package name is required');
3942
+ }
3943
+ if (name.length > MAX_PACKAGE_NAME_LENGTH) {
3944
+ throw createError(`Package name exceeds maximum length of ${MAX_PACKAGE_NAME_LENGTH}`);
3945
+ }
3946
+ const safe = [];
3947
+ for (let i = 0; i < name.length; i++) {
3948
+ const code = name.charCodeAt(i);
3949
+ // Allow: a-z, A-Z, 0-9, @, /, -, _, .
3950
+ if ((code >= 97 && code <= 122) || // a-z
3951
+ (code >= 65 && code <= 90) || // A-Z
3952
+ (code >= 48 && code <= 57) || // 0-9
3953
+ code === 64 || // @
3954
+ code === 47 || // /
3955
+ code === 45 || // -
3956
+ code === 95 || // _
3957
+ code === 46 // .
3958
+ ) {
3959
+ safe.push(name[i]);
3960
+ }
3961
+ else {
3962
+ throw createError(`Invalid character in package name at position ${i}: "${name[i]}"`);
3963
+ }
3964
+ }
3965
+ return safe.join('');
3966
+ }
3967
+ /**
3968
+ * Maximum allowed version string length.
3969
+ */
3970
+ const MAX_VERSION_LENGTH = 256;
3971
+ /**
3972
+ * Escapes a version string for safe use in shell commands.
3973
+ *
3974
+ * @param version - Version string to escape
3975
+ * @returns Safe version string
3976
+ * @throws {Error} If version contains invalid characters
3977
+ */
3978
+ function escapeVersion(version) {
3979
+ if (!version || typeof version !== 'string') {
3980
+ throw createError('Version is required');
3981
+ }
3982
+ if (version.length > MAX_VERSION_LENGTH) {
3983
+ throw createError(`Version exceeds maximum length of ${MAX_VERSION_LENGTH}`);
3984
+ }
3985
+ const safe = [];
3986
+ for (let i = 0; i < version.length; i++) {
3987
+ const code = version.charCodeAt(i);
3988
+ // Allow: 0-9, ., -, +, a-z, A-Z
3989
+ if ((code >= 48 && code <= 57) || // 0-9
3990
+ (code >= 97 && code <= 122) || // a-z
3991
+ (code >= 65 && code <= 90) || // A-Z
3992
+ code === 46 || // .
3993
+ code === 45 || // -
3994
+ code === 43 // +
3995
+ ) {
3996
+ safe.push(version[i]);
3997
+ }
3998
+ else {
3999
+ throw createError(`Invalid character in version at position ${i}: "${version[i]}"`);
4000
+ }
4001
+ }
4002
+ return safe.join('');
4003
+ }
4004
+ /**
4005
+ * Extracts repository URL from npm package repository field.
4006
+ *
4007
+ * @param repository - Repository field from package.json (string or object)
4008
+ * @returns Repository URL, or undefined if not found
4009
+ */
4010
+ function extractRepoUrl(repository) {
4011
+ if (typeof repository === 'string')
4012
+ return repository;
4013
+ if (repository && typeof repository === 'object') {
4014
+ const repo = repository;
4015
+ if (repo.url) {
4016
+ // Clean up git+ prefix and .git suffix
4017
+ let url = repo.url;
4018
+ if (url.startsWith('git+')) {
4019
+ url = url.slice(4);
4020
+ }
4021
+ if (url.endsWith('.git')) {
4022
+ url = url.slice(0, -4);
4023
+ }
4024
+ return url;
4025
+ }
4026
+ }
4027
+ return undefined;
4028
+ }
4029
+
4030
+ /**
4031
+ * Creates a registry client.
4032
+ *
4033
+ * @param type - Type of registry to create
4034
+ * @param config - Registry configuration
4035
+ * @returns A Registry instance
4036
+ *
4037
+ * @example
4038
+ * const registry = createRegistry('npm')
4039
+ * const version = await registry.getLatestVersion('lodash')
4040
+ */
4041
+ function createRegistry(type = 'npm', config = {}) {
4042
+ switch (type) {
4043
+ case 'npm':
4044
+ return createNpmRegistry(config);
4045
+ default:
4046
+ throw createError(`Unknown registry type: ${type}`);
4047
+ }
4048
+ }
4049
+
4050
+ /**
4051
+ * Default flow configuration values.
4052
+ */
4053
+ const DEFAULT_FLOW_CONFIG = {
4054
+ preset: 'conventional',
4055
+ releaseTypes: ['feat', 'fix', 'perf', 'revert'],
4056
+ minorTypes: ['feat'],
4057
+ patchTypes: ['fix', 'perf', 'revert'],
4058
+ skipGit: false,
4059
+ skipTag: false,
4060
+ skipChangelog: false,
4061
+ dryRun: false,
4062
+ commitMessage: 'chore(${projectName}): release version ${version}',
4063
+ tagFormat: '${projectName}@${version}',
4064
+ trackDeps: false,
4065
+ releaseBranch: 'main',
4066
+ firstReleaseVersion: '0.1.0',
4067
+ allowPrerelease: false,
4068
+ prereleaseId: 'alpha',
4069
+ releaseAs: undefined,
4070
+ };
4071
+
4072
+ /**
4073
+ * Resolves the project root path from workspace root and project name.
4074
+ *
4075
+ * For now, uses a simple convention: libs/{projectName} or apps/{projectName}
4076
+ * In a real implementation, this would query the workspace configuration.
4077
+ *
4078
+ * @param workspaceRoot - Workspace root path
4079
+ * @param projectName - Project name (e.g., 'lib-versioning')
4080
+ * @returns Absolute path to project root
4081
+ */
4082
+ function resolveProjectRoot(workspaceRoot, projectName) {
4083
+ // Remove 'lib-' or 'app-' prefix to get the folder name
4084
+ let folderName = projectName;
4085
+ let prefix = 'libs';
4086
+ if (projectName.startsWith('lib-')) {
4087
+ folderName = projectName.slice(4);
4088
+ prefix = 'libs';
4089
+ }
4090
+ else if (projectName.startsWith('app-')) {
4091
+ folderName = projectName.slice(4);
4092
+ prefix = 'apps';
4093
+ }
4094
+ return `${workspaceRoot}/${prefix}/${folderName}`;
4095
+ }
4096
+ /**
4097
+ * Resolves the package name from the project root.
4098
+ *
4099
+ * @param tree - Virtual file system tree
4100
+ * @param projectRoot - Project root path
4101
+ * @returns Package name from package.json
4102
+ */
4103
+ function resolvePackageName(tree, projectRoot) {
4104
+ const packageJsonPath = `${projectRoot}/package.json`;
4105
+ try {
4106
+ const content = tree.read(packageJsonPath, 'utf-8');
4107
+ if (!content) {
4108
+ return 'unknown';
4109
+ }
4110
+ const pkg = parse(content);
4111
+ return pkg.name ?? 'unknown';
4112
+ }
4113
+ catch {
4114
+ return 'unknown';
4115
+ }
4116
+ }
4117
+ /**
4118
+ * Builds a summary message from flow results.
4119
+ *
4120
+ * @param status - The overall flow status
4121
+ * @param steps - Array of step results
4122
+ * @param state - Final flow state
4123
+ * @param duration - Execution duration in milliseconds
4124
+ * @returns Human-readable summary string
4125
+ */
4126
+ function buildSummary(status, steps, state, duration) {
4127
+ const completed = steps.filter((s) => s.status === 'success').length;
4128
+ const skipped = steps.filter((s) => s.status === 'skipped').length;
4129
+ const failed = steps.filter((s) => s.status === 'failed').length;
4130
+ let summary = `Flow ${status} in ${duration}ms: `;
4131
+ summary += `${completed} completed, ${skipped} skipped, ${failed} failed`;
4132
+ if (state.nextVersion) {
4133
+ summary += `. Version: ${state.currentVersion ?? '?.?.?'} → ${state.nextVersion}`;
4134
+ }
4135
+ else if (status === 'success' && state.bumpType === 'none') {
4136
+ summary += '. No release needed';
4137
+ }
4138
+ return summary;
4139
+ }
4140
+ /**
4141
+ * Merges flow config with defaults.
4142
+ *
4143
+ * @param flowConfig - Base flow configuration
4144
+ * @param overrides - Optional configuration overrides
4145
+ * @returns Merged configuration
4146
+ */
4147
+ function mergeConfig(flowConfig, overrides) {
4148
+ return {
4149
+ ...DEFAULT_FLOW_CONFIG,
4150
+ ...flowConfig,
4151
+ ...overrides,
4152
+ };
4153
+ }
4154
+ /**
4155
+ * Executes a version flow.
4156
+ *
4157
+ * This is the main entry point for running a versioning workflow.
4158
+ * Steps are executed in order, with state accumulated between steps.
4159
+ *
4160
+ * @param flow - The version flow to execute
4161
+ * @param projectName - Name of the project to version (e.g., 'lib-versioning')
4162
+ * @param workspaceRoot - Absolute path to workspace root
4163
+ * @param options - Execution options
4164
+ * @returns Flow execution result
4165
+ *
4166
+ * @example
4167
+ * ```typescript
4168
+ * import { createConventionalFlow, executeFlow } from '@hyperfrontend/versioning'
4169
+ *
4170
+ * const flow = createConventionalFlow({ dryRun: true })
4171
+ * const result = await executeFlow(flow, 'lib-utils', '/path/to/workspace')
4172
+ *
4173
+ * console.log(result.summary)
4174
+ * // "Flow success in 234ms: 8 completed, 0 skipped, 0 failed. Version: 1.2.3 → 1.3.0"
4175
+ * ```
4176
+ */
4177
+ async function executeFlow(flow, projectName, workspaceRoot, options = {}) {
4178
+ const startTime = dateNow();
4179
+ const flowLogger = options.logger ?? logger;
4180
+ // Set log level based on verbose option
4181
+ flowLogger.setLogLevel(options.verbose ? 'debug' : 'error');
4182
+ // Merge configs
4183
+ const config = mergeConfig(flow.config, {
4184
+ dryRun: options.dryRun ?? flow.config.dryRun,
4185
+ });
4186
+ // Initialize services
4187
+ const tree = options.tree ?? createTree(workspaceRoot);
4188
+ const registry = options.registry ?? createRegistry('npm');
4189
+ const git = options.git ?? createGitClient({ ...DEFAULT_GIT_CLIENT_CONFIG, cwd: workspaceRoot });
4190
+ // Resolve paths
4191
+ const projectRoot = resolveProjectRoot(workspaceRoot, projectName);
4192
+ const packageName = resolvePackageName(tree, projectRoot);
4193
+ // Initialize context
4194
+ const context = {
4195
+ workspaceRoot,
4196
+ projectName,
4197
+ projectRoot,
4198
+ packageName,
4199
+ tree,
4200
+ registry,
4201
+ git,
4202
+ logger: flowLogger,
4203
+ config,
4204
+ state: {},
4205
+ };
4206
+ const stepResults = [];
4207
+ let failed = false;
4208
+ flowLogger.info(`Executing flow: ${flow.name}`);
4209
+ flowLogger.info(`Project: ${projectName} (${packageName})`);
4210
+ // Execute steps in order
4211
+ for (const step of flow.steps) {
4212
+ // Check dependencies
4213
+ if (step.dependsOn?.length) {
4214
+ const depsMet = step.dependsOn.every((depId) => {
4215
+ const depResult = stepResults.find((r) => r.stepId === depId);
4216
+ return depResult && depResult.status === 'success';
4217
+ });
4218
+ if (!depsMet) {
4219
+ flowLogger.debug(`Skipping step "${step.name}": dependencies not met`);
4220
+ stepResults.push({
4221
+ stepId: step.id,
4222
+ stepName: step.name,
4223
+ status: 'skipped',
4224
+ message: 'Dependencies not met',
4225
+ });
4226
+ continue;
4227
+ }
4228
+ }
4229
+ // Check skip condition
4230
+ if (step.skipIf?.(context)) {
4231
+ flowLogger.debug(`Skipping step "${step.name}": skip condition met`);
4232
+ stepResults.push({
4233
+ stepId: step.id,
4234
+ stepName: step.name,
4235
+ status: 'skipped',
4236
+ message: 'Skipped by condition',
4237
+ });
4238
+ continue;
4239
+ }
4240
+ // Execute step
4241
+ try {
4242
+ flowLogger.info(`Executing step: ${step.name}`);
4243
+ const result = await step.execute(context);
4244
+ // Apply state updates
4245
+ if (result.stateUpdates) {
4246
+ context.state = { ...context.state, ...result.stateUpdates };
4247
+ }
4248
+ stepResults.push({
4249
+ stepId: step.id,
4250
+ stepName: step.name,
4251
+ ...result,
4252
+ });
4253
+ if (result.status === 'success') {
4254
+ flowLogger.debug(`Step "${step.name}" succeeded: ${result.message ?? 'OK'}`);
4255
+ }
4256
+ else if (result.status === 'skipped') {
4257
+ flowLogger.debug(`Step "${step.name}" skipped: ${result.message ?? 'No reason'}`);
4258
+ }
4259
+ else if (result.status === 'failed') {
4260
+ flowLogger.error(`Step "${step.name}" failed: ${result.message ?? result.error?.message ?? 'Unknown error'}`);
4261
+ if (!step.continueOnError) {
4262
+ failed = true;
4263
+ break;
4264
+ }
4265
+ }
4266
+ }
4267
+ catch (error) {
4268
+ const errorObj = error instanceof Error ? error : createError(String(error));
4269
+ flowLogger.error(`Step "${step.name}" threw: ${errorObj.message}`);
4270
+ stepResults.push({
4271
+ stepId: step.id,
4272
+ stepName: step.name,
4273
+ status: 'failed',
4274
+ error: errorObj,
4275
+ message: errorObj.message,
4276
+ });
4277
+ if (!step.continueOnError) {
4278
+ failed = true;
4279
+ break;
4280
+ }
4281
+ }
4282
+ }
4283
+ // Commit VFS changes if not dry run and not failed
4284
+ if (!config.dryRun && !failed) {
4285
+ try {
4286
+ commitChanges(tree, { verbose: options.verbose });
4287
+ flowLogger.info('File changes committed to disk');
4288
+ }
4289
+ catch (error) {
4290
+ flowLogger.error(`Failed to commit file changes: ${error}`);
4291
+ }
4292
+ }
4293
+ else if (config.dryRun) {
4294
+ flowLogger.info('Dry run mode - no changes written to disk');
4295
+ }
4296
+ const duration = dateNow() - startTime;
4297
+ // Determine overall status
4298
+ const status = failed
4299
+ ? 'failed'
4300
+ : stepResults.some((r) => r.status === 'failed')
4301
+ ? 'partial'
4302
+ : stepResults.every((r) => r.status === 'skipped')
4303
+ ? 'skipped'
4304
+ : 'success';
4305
+ const summary = buildSummary(status, stepResults, context.state, duration);
4306
+ flowLogger.info(summary);
4307
+ return {
4308
+ status,
4309
+ steps: stepResults,
4310
+ state: context.state,
4311
+ duration,
4312
+ summary,
4313
+ };
4314
+ }
4315
+ /**
4316
+ * Executes a flow in dry-run mode.
4317
+ *
4318
+ * Convenience wrapper that sets dryRun: true.
4319
+ *
4320
+ * @param flow - The version flow to execute
4321
+ * @param projectName - Name of the project to version
4322
+ * @param workspaceRoot - Absolute path to workspace root
4323
+ * @param options - Execution options (dryRun forced to true)
4324
+ * @returns Flow execution result (no actual changes made)
4325
+ */
4326
+ async function dryRun(flow, projectName, workspaceRoot, options = {}) {
4327
+ return executeFlow(flow, projectName, workspaceRoot, {
4328
+ ...options,
4329
+ dryRun: true,
4330
+ });
4331
+ }
4332
+ /**
4333
+ * Validates a flow before execution.
4334
+ *
4335
+ * Checks for:
4336
+ * - Duplicate step IDs
4337
+ * - Invalid dependency references
4338
+ * - Circular dependencies
4339
+ *
4340
+ * @param flow - The flow to validate
4341
+ * @returns Array of validation errors (empty if valid)
4342
+ */
4343
+ function validateFlow(flow) {
4344
+ const errors = [];
4345
+ const stepIds = createSet();
4346
+ // Check for duplicate IDs
4347
+ for (const step of flow.steps) {
4348
+ if (stepIds.has(step.id)) {
4349
+ errors.push(`Duplicate step ID: "${step.id}"`);
4350
+ }
4351
+ stepIds.add(step.id);
4352
+ }
4353
+ // Check for valid dependency references
4354
+ for (const step of flow.steps) {
4355
+ if (step.dependsOn) {
4356
+ for (const depId of step.dependsOn) {
4357
+ if (!stepIds.has(depId)) {
4358
+ errors.push(`Step "${step.id}" depends on unknown step "${depId}"`);
4359
+ }
4360
+ }
4361
+ }
4362
+ }
4363
+ // Check for circular dependencies (simple DFS)
4364
+ const visited = createSet();
4365
+ const visiting = createSet();
4366
+ /**
4367
+ * Recursively visits a step to detect circular dependencies.
4368
+ *
4369
+ * @param stepId - The step ID to check
4370
+ * @returns True if no cycle detected, false otherwise
4371
+ */
4372
+ function visit(stepId) {
4373
+ if (visiting.has(stepId)) {
4374
+ return false; // Cycle detected
4375
+ }
4376
+ if (visited.has(stepId)) {
4377
+ return true; // Already checked
4378
+ }
4379
+ visiting.add(stepId);
4380
+ const step = flow.steps.find((s) => s.id === stepId);
4381
+ if (step?.dependsOn) {
4382
+ for (const depId of step.dependsOn) {
4383
+ if (!visit(depId)) {
4384
+ errors.push(`Circular dependency detected involving step "${stepId}"`);
4385
+ return false;
4386
+ }
4387
+ }
4388
+ }
4389
+ visiting.delete(stepId);
4390
+ visited.add(stepId);
4391
+ return true;
4392
+ }
4393
+ for (const step of flow.steps) {
4394
+ visit(step.id);
4395
+ }
4396
+ return errors;
4397
+ }
4398
+
4399
+ exports.dryRun = dryRun;
4400
+ exports.executeFlow = executeFlow;
4401
+ exports.validateFlow = validateFlow;
4402
+ //# sourceMappingURL=index.cjs.js.map