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