@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,2663 @@
1
+ import 'node:util';
2
+ import { dirname } from 'node:path';
3
+ import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
4
+ import 'node:os';
5
+
6
+ /**
7
+ * Safe copies of Error built-ins via factory functions.
8
+ *
9
+ * Since constructors cannot be safely captured via Object.assign, this module
10
+ * provides factory functions that use Reflect.construct internally.
11
+ *
12
+ * These references are captured at module initialization time to protect against
13
+ * prototype pollution attacks. Import only what you need for tree-shaking.
14
+ *
15
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
16
+ */
17
+ // Capture references at module initialization time
18
+ const _Error = globalThis.Error;
19
+ const _Reflect$2 = globalThis.Reflect;
20
+ /**
21
+ * (Safe copy) Creates a new Error using the captured Error constructor.
22
+ * Use this instead of `new Error()`.
23
+ *
24
+ * @param message - Optional error message.
25
+ * @param options - Optional error options.
26
+ * @returns A new Error instance.
27
+ */
28
+ const createError = (message, options) => _Reflect$2.construct(_Error, [message, options]);
29
+
30
+ /**
31
+ * Safe copies of Map built-in via factory function.
32
+ *
33
+ * Since constructors cannot be safely captured via Object.assign, this module
34
+ * provides a factory function that uses Reflect.construct internally.
35
+ *
36
+ * These references are captured at module initialization time to protect against
37
+ * prototype pollution attacks. Import only what you need for tree-shaking.
38
+ *
39
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
40
+ */
41
+ // Capture references at module initialization time
42
+ const _Map = globalThis.Map;
43
+ const _Reflect$1 = globalThis.Reflect;
44
+ /**
45
+ * (Safe copy) Creates a new Map using the captured Map constructor.
46
+ * Use this instead of `new Map()`.
47
+ *
48
+ * @param iterable - Optional iterable of key-value pairs.
49
+ * @returns A new Map instance.
50
+ */
51
+ const createMap = (iterable) => _Reflect$1.construct(_Map, iterable ? [iterable] : []);
52
+
53
+ /**
54
+ * Safe copies of Set built-in via factory function.
55
+ *
56
+ * Since constructors cannot be safely captured via Object.assign, this module
57
+ * provides a factory function that uses Reflect.construct internally.
58
+ *
59
+ * These references are captured at module initialization time to protect against
60
+ * prototype pollution attacks. Import only what you need for tree-shaking.
61
+ *
62
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/set
63
+ */
64
+ // Capture references at module initialization time
65
+ const _Set = globalThis.Set;
66
+ const _Reflect = globalThis.Reflect;
67
+ /**
68
+ * (Safe copy) Creates a new Set using the captured Set constructor.
69
+ * Use this instead of `new Set()`.
70
+ *
71
+ * @param iterable - Optional iterable of values.
72
+ * @returns A new Set instance.
73
+ */
74
+ const createSet = (iterable) => _Reflect.construct(_Set, iterable ? [iterable] : []);
75
+
76
+ /**
77
+ * Converts a SemVer to its canonical string representation.
78
+ *
79
+ * @param version - The version to format
80
+ * @returns The version string (e.g., "1.2.3-alpha.1+build.123")
81
+ */
82
+ function format(version) {
83
+ let result = `${version.major}.${version.minor}.${version.patch}`;
84
+ if (version.prerelease.length > 0) {
85
+ result += '-' + version.prerelease.join('.');
86
+ }
87
+ if (version.build.length > 0) {
88
+ result += '+' + version.build.join('.');
89
+ }
90
+ return result;
91
+ }
92
+
93
+ /**
94
+ * Safe copies of Number built-in methods and constants.
95
+ *
96
+ * These references are captured at module initialization time to protect against
97
+ * prototype pollution attacks. Import only what you need for tree-shaking.
98
+ *
99
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/number
100
+ */
101
+ // Capture references at module initialization time
102
+ const _parseInt = globalThis.parseInt;
103
+ const _isNaN = globalThis.isNaN;
104
+ // ============================================================================
105
+ // Parsing
106
+ // ============================================================================
107
+ /**
108
+ * (Safe copy) Parses a string and returns an integer.
109
+ */
110
+ const parseInt = _parseInt;
111
+ // ============================================================================
112
+ // Global Type Checking (legacy, less strict)
113
+ // ============================================================================
114
+ /**
115
+ * (Safe copy) Global isNaN function (coerces to number first, less strict than Number.isNaN).
116
+ */
117
+ const globalIsNaN = _isNaN;
118
+
119
+ /**
120
+ * Creates a new SemVer object.
121
+ *
122
+ * @param options - Version components
123
+ * @returns A new SemVer object
124
+ */
125
+ function createSemVer(options) {
126
+ return {
127
+ major: options.major,
128
+ minor: options.minor,
129
+ patch: options.patch,
130
+ prerelease: options.prerelease ?? [],
131
+ build: options.build ?? [],
132
+ raw: options.raw,
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Increments a version based on the bump type.
138
+ *
139
+ * @param version - The version to increment
140
+ * @param type - The type of bump (major, minor, patch, etc.)
141
+ * @param prereleaseId - Optional prerelease identifier for prerelease bumps
142
+ * @returns A new incremented SemVer
143
+ *
144
+ * @example
145
+ * increment(parseVersion('1.2.3'), 'minor') // 1.3.0
146
+ * increment(parseVersion('1.2.3'), 'major') // 2.0.0
147
+ * increment(parseVersion('1.2.3'), 'prerelease', 'alpha') // 1.2.4-alpha.0
148
+ */
149
+ function increment(version, type, prereleaseId) {
150
+ switch (type) {
151
+ case 'major':
152
+ return createSemVer({
153
+ major: version.major + 1,
154
+ minor: 0,
155
+ patch: 0,
156
+ prerelease: [],
157
+ build: [],
158
+ });
159
+ case 'minor':
160
+ return createSemVer({
161
+ major: version.major,
162
+ minor: version.minor + 1,
163
+ patch: 0,
164
+ prerelease: [],
165
+ build: [],
166
+ });
167
+ case 'patch':
168
+ // If version has prerelease, just remove it (1.2.3-alpha -> 1.2.3)
169
+ if (version.prerelease.length > 0) {
170
+ return createSemVer({
171
+ major: version.major,
172
+ minor: version.minor,
173
+ patch: version.patch,
174
+ prerelease: [],
175
+ build: [],
176
+ });
177
+ }
178
+ return createSemVer({
179
+ major: version.major,
180
+ minor: version.minor,
181
+ patch: version.patch + 1,
182
+ prerelease: [],
183
+ build: [],
184
+ });
185
+ case 'premajor':
186
+ return createSemVer({
187
+ major: version.major + 1,
188
+ minor: 0,
189
+ patch: 0,
190
+ prerelease: [prereleaseId ?? 'alpha', '0'],
191
+ build: [],
192
+ });
193
+ case 'preminor':
194
+ return createSemVer({
195
+ major: version.major,
196
+ minor: version.minor + 1,
197
+ patch: 0,
198
+ prerelease: [prereleaseId ?? 'alpha', '0'],
199
+ build: [],
200
+ });
201
+ case 'prepatch':
202
+ return createSemVer({
203
+ major: version.major,
204
+ minor: version.minor,
205
+ patch: version.patch + 1,
206
+ prerelease: [prereleaseId ?? 'alpha', '0'],
207
+ build: [],
208
+ });
209
+ case 'prerelease':
210
+ return incrementPrerelease(version, prereleaseId);
211
+ case 'none':
212
+ default:
213
+ return version;
214
+ }
215
+ }
216
+ /**
217
+ * Increments the prerelease portion of a version.
218
+ *
219
+ * @param version - The version to increment
220
+ * @param id - Optional prerelease identifier
221
+ * @returns A new version with incremented prerelease
222
+ */
223
+ function incrementPrerelease(version, id) {
224
+ const prerelease = [...version.prerelease];
225
+ if (prerelease.length === 0) {
226
+ // No existing prerelease - start at patch+1 with id.0
227
+ return createSemVer({
228
+ major: version.major,
229
+ minor: version.minor,
230
+ patch: version.patch + 1,
231
+ prerelease: [id ?? 'alpha', '0'],
232
+ build: [],
233
+ });
234
+ }
235
+ // Check if the last identifier is numeric
236
+ const lastIdx = prerelease.length - 1;
237
+ const last = prerelease[lastIdx];
238
+ const lastNum = parseInt(last, 10);
239
+ if (!globalIsNaN(lastNum)) {
240
+ // Increment the numeric part
241
+ prerelease[lastIdx] = String(lastNum + 1);
242
+ }
243
+ else {
244
+ // Append .0
245
+ prerelease.push('0');
246
+ }
247
+ // If a different id is specified, replace the base identifier
248
+ if (id && prerelease.length > 0 && prerelease[0] !== id) {
249
+ prerelease[0] = id;
250
+ // Reset numeric part
251
+ if (prerelease.length > 1) {
252
+ prerelease[prerelease.length - 1] = '0';
253
+ }
254
+ }
255
+ return createSemVer({
256
+ major: version.major,
257
+ minor: version.minor,
258
+ patch: version.patch,
259
+ prerelease,
260
+ build: [],
261
+ });
262
+ }
263
+
264
+ /**
265
+ * Maximum version string length to prevent memory exhaustion.
266
+ */
267
+ const MAX_VERSION_LENGTH = 256;
268
+ /**
269
+ * Parses a semantic version string.
270
+ *
271
+ * Accepts versions in the format: MAJOR.MINOR.PATCH[-prerelease][+build]
272
+ * Optional leading 'v' or '=' prefixes are stripped.
273
+ *
274
+ * @param input - The version string to parse
275
+ * @returns A ParseVersionResult with the parsed version or error
276
+ *
277
+ * @example
278
+ * parseVersion('1.2.3') // { success: true, version: { major: 1, minor: 2, patch: 3, ... } }
279
+ * parseVersion('v1.0.0-alpha.1+build.123') // { success: true, ... }
280
+ * parseVersion('invalid') // { success: false, error: '...' }
281
+ */
282
+ function parseVersion(input) {
283
+ // Input validation
284
+ if (!input || typeof input !== 'string') {
285
+ return { success: false, error: 'Version string is required' };
286
+ }
287
+ if (input.length > MAX_VERSION_LENGTH) {
288
+ return { success: false, error: `Version string exceeds maximum length of ${MAX_VERSION_LENGTH}` };
289
+ }
290
+ // Strip leading whitespace
291
+ let pos = 0;
292
+ while (pos < input.length && isWhitespace(input.charCodeAt(pos))) {
293
+ pos++;
294
+ }
295
+ // Strip trailing whitespace
296
+ let end = input.length;
297
+ while (end > pos && isWhitespace(input.charCodeAt(end - 1))) {
298
+ end--;
299
+ }
300
+ // Strip optional leading 'v' or '='
301
+ if (pos < end) {
302
+ const code = input.charCodeAt(pos);
303
+ if (code === 118 || code === 86) {
304
+ // 'v' or 'V'
305
+ pos++;
306
+ }
307
+ else if (code === 61) {
308
+ // '='
309
+ pos++;
310
+ }
311
+ }
312
+ // Parse major version
313
+ const majorResult = parseNumericIdentifier(input, pos, end);
314
+ if (!majorResult.success) {
315
+ return { success: false, error: majorResult.error ?? 'Invalid major version' };
316
+ }
317
+ pos = majorResult.endPos;
318
+ // Expect dot
319
+ if (pos >= end || input.charCodeAt(pos) !== 46) {
320
+ // '.'
321
+ return { success: false, error: 'Expected "." after major version' };
322
+ }
323
+ pos++;
324
+ // Parse minor version
325
+ const minorResult = parseNumericIdentifier(input, pos, end);
326
+ if (!minorResult.success) {
327
+ return { success: false, error: minorResult.error ?? 'Invalid minor version' };
328
+ }
329
+ pos = minorResult.endPos;
330
+ // Expect dot
331
+ if (pos >= end || input.charCodeAt(pos) !== 46) {
332
+ // '.'
333
+ return { success: false, error: 'Expected "." after minor version' };
334
+ }
335
+ pos++;
336
+ // Parse patch version
337
+ const patchResult = parseNumericIdentifier(input, pos, end);
338
+ if (!patchResult.success) {
339
+ return { success: false, error: patchResult.error ?? 'Invalid patch version' };
340
+ }
341
+ pos = patchResult.endPos;
342
+ // Parse optional prerelease
343
+ const prerelease = [];
344
+ if (pos < end && input.charCodeAt(pos) === 45) {
345
+ // '-'
346
+ pos++;
347
+ const prereleaseResult = parseIdentifiers(input, pos, end, [43]); // Stop at '+'
348
+ if (!prereleaseResult.success) {
349
+ return { success: false, error: prereleaseResult.error ?? 'Invalid prerelease' };
350
+ }
351
+ prerelease.push(...prereleaseResult.identifiers);
352
+ pos = prereleaseResult.endPos;
353
+ }
354
+ // Parse optional build metadata
355
+ const build = [];
356
+ if (pos < end && input.charCodeAt(pos) === 43) {
357
+ // '+'
358
+ pos++;
359
+ const buildResult = parseIdentifiers(input, pos, end, []);
360
+ if (!buildResult.success) {
361
+ return { success: false, error: buildResult.error ?? 'Invalid build metadata' };
362
+ }
363
+ build.push(...buildResult.identifiers);
364
+ pos = buildResult.endPos;
365
+ }
366
+ // Check for trailing characters
367
+ if (pos < end) {
368
+ return { success: false, error: `Unexpected character at position ${pos}: "${input[pos]}"` };
369
+ }
370
+ return {
371
+ success: true,
372
+ version: createSemVer({
373
+ major: majorResult.value,
374
+ minor: minorResult.value,
375
+ patch: patchResult.value,
376
+ prerelease,
377
+ build,
378
+ raw: input,
379
+ }),
380
+ };
381
+ }
382
+ /**
383
+ * Parses a numeric identifier (non-negative integer, no leading zeros except for "0").
384
+ *
385
+ * @param input - Input string to parse
386
+ * @param start - Start position in the input
387
+ * @param end - End position in the input
388
+ * @returns Numeric parsing result
389
+ */
390
+ function parseNumericIdentifier(input, start, end) {
391
+ if (start >= end) {
392
+ return { success: false, value: 0, endPos: start, error: 'Expected numeric identifier' };
393
+ }
394
+ let pos = start;
395
+ const firstCode = input.charCodeAt(pos);
396
+ // Must start with a digit
397
+ if (!isDigit(firstCode)) {
398
+ return { success: false, value: 0, endPos: pos, error: 'Expected digit' };
399
+ }
400
+ // Check for leading zero (only "0" is valid, not "01", "007", etc.)
401
+ if (firstCode === 48 && pos + 1 < end && isDigit(input.charCodeAt(pos + 1))) {
402
+ return { success: false, value: 0, endPos: pos, error: 'Numeric identifier cannot have leading zeros' };
403
+ }
404
+ // Consume digits
405
+ let value = 0;
406
+ while (pos < end && isDigit(input.charCodeAt(pos))) {
407
+ value = value * 10 + (input.charCodeAt(pos) - 48);
408
+ pos++;
409
+ // Prevent overflow
410
+ if (value > Number.MAX_SAFE_INTEGER) {
411
+ return { success: false, value: 0, endPos: pos, error: 'Numeric identifier is too large' };
412
+ }
413
+ }
414
+ return { success: true, value, endPos: pos };
415
+ }
416
+ /**
417
+ * Parses dot-separated identifiers (for prerelease/build).
418
+ *
419
+ * @param input - Input string to parse
420
+ * @param start - Start position in the input
421
+ * @param end - End position in the input
422
+ * @param stopCodes - Character codes that signal end of identifiers
423
+ * @returns Identifiers parsing result
424
+ */
425
+ function parseIdentifiers(input, start, end, stopCodes) {
426
+ const identifiers = [];
427
+ let pos = start;
428
+ while (pos < end) {
429
+ // Check for stop characters
430
+ if (stopCodes.includes(input.charCodeAt(pos))) {
431
+ break;
432
+ }
433
+ // Parse one identifier
434
+ const identStart = pos;
435
+ while (pos < end) {
436
+ const code = input.charCodeAt(pos);
437
+ // Stop at dot or stop characters
438
+ if (code === 46 || stopCodes.includes(code)) {
439
+ break;
440
+ }
441
+ // Must be alphanumeric or hyphen
442
+ if (!isAlphanumeric(code) && code !== 45) {
443
+ return { success: false, identifiers: [], endPos: pos, error: `Invalid character in identifier: "${input[pos]}"` };
444
+ }
445
+ pos++;
446
+ }
447
+ // Empty identifier is not allowed
448
+ if (pos === identStart) {
449
+ return { success: false, identifiers: [], endPos: pos, error: 'Empty identifier' };
450
+ }
451
+ identifiers.push(input.slice(identStart, pos));
452
+ // Consume dot separator
453
+ if (pos < end && input.charCodeAt(pos) === 46) {
454
+ pos++;
455
+ // Dot at end is invalid
456
+ if (pos >= end || stopCodes.includes(input.charCodeAt(pos))) {
457
+ return { success: false, identifiers: [], endPos: pos, error: 'Identifier expected after dot' };
458
+ }
459
+ }
460
+ }
461
+ return { success: true, identifiers, endPos: pos };
462
+ }
463
+ /**
464
+ * Checks if a character code is a digit (0-9).
465
+ *
466
+ * @param code - Character code to check
467
+ * @returns True if the code represents a digit
468
+ */
469
+ function isDigit(code) {
470
+ return code >= 48 && code <= 57;
471
+ }
472
+ /**
473
+ * Checks if a character code is alphanumeric or hyphen.
474
+ *
475
+ * @param code - Character code to check
476
+ * @returns True if the code represents an alphanumeric character
477
+ */
478
+ function isAlphanumeric(code) {
479
+ return ((code >= 48 && code <= 57) || // 0-9
480
+ (code >= 65 && code <= 90) || // A-Z
481
+ (code >= 97 && code <= 122) // a-z
482
+ );
483
+ }
484
+ /**
485
+ * Checks if a character code is whitespace.
486
+ *
487
+ * @param code - Character code to check
488
+ * @returns True if the code represents whitespace
489
+ */
490
+ function isWhitespace(code) {
491
+ return code === 32 || code === 9 || code === 10 || code === 13;
492
+ }
493
+
494
+ /**
495
+ * Safe copies of Object built-in methods.
496
+ *
497
+ * These references are captured at module initialization time to protect against
498
+ * prototype pollution attacks. Import only what you need for tree-shaking.
499
+ *
500
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
501
+ */
502
+ // Capture references at module initialization time
503
+ const _Object = globalThis.Object;
504
+ /**
505
+ * (Safe copy) Prevents modification of existing property attributes and values,
506
+ * and prevents the addition of new properties.
507
+ */
508
+ const freeze = _Object.freeze;
509
+ /**
510
+ * (Safe copy) Returns the names of the enumerable string properties and methods of an object.
511
+ */
512
+ const keys = _Object.keys;
513
+ /**
514
+ * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
515
+ */
516
+ const entries = _Object.entries;
517
+ /**
518
+ * (Safe copy) Adds one or more properties to an object, and/or modifies attributes of existing properties.
519
+ */
520
+ const defineProperties = _Object.defineProperties;
521
+
522
+ /**
523
+ * Dependency Graph
524
+ *
525
+ * Builds and analyzes dependency relationships between workspace projects.
526
+ * Provides functions for traversing the dependency graph and determining
527
+ * build/release order.
528
+ */
529
+ /**
530
+ * Gets all transitive dependents of a package (direct and indirect).
531
+ *
532
+ * @param workspace - The workspace containing projects
533
+ * @param packageName - Name of the package to analyze
534
+ * @returns Set of all packages that depend on this package
535
+ *
536
+ * @example
537
+ * ```typescript
538
+ * // If lib-a depends on lib-utils and app-main depends on lib-a
539
+ * // Then getTransitiveDependents('lib-utils') returns ['lib-a', 'app-main']
540
+ * ```
541
+ */
542
+ function getTransitiveDependents(workspace, packageName) {
543
+ const dependents = createSet();
544
+ const queue = [packageName];
545
+ while (queue.length > 0) {
546
+ const current = queue.shift();
547
+ if (current === undefined) {
548
+ break;
549
+ }
550
+ const directDependents = workspace.dependencyGraph.get(current) ?? [];
551
+ for (const dep of directDependents) {
552
+ if (!dependents.has(dep)) {
553
+ dependents.add(dep);
554
+ queue.push(dep);
555
+ }
556
+ }
557
+ }
558
+ return dependents;
559
+ }
560
+
561
+ /**
562
+ * Cascade Bump
563
+ *
564
+ * Calculates which packages need version bumps when dependencies change.
565
+ * Implements cascade versioning for monorepos where dependents may need
566
+ * to be bumped when their dependencies are updated.
567
+ */
568
+ /**
569
+ * Default cascade bump options.
570
+ */
571
+ const DEFAULT_CASCADE_OPTIONS = {
572
+ cascadeBumpType: 'patch',
573
+ includeDevDependencies: false,
574
+ includePeerDependencies: true,
575
+ prereleaseId: 'alpha',
576
+ };
577
+ /**
578
+ * Calculates cascade bumps for a workspace given direct bumps.
579
+ *
580
+ * When packages are directly bumped (e.g., due to commits), their dependents
581
+ * may also need version bumps. This function calculates all affected packages.
582
+ *
583
+ * @param workspace - Workspace containing projects and dependency graph
584
+ * @param directBumps - Packages with direct changes
585
+ * @param options - Configuration for cascade bump calculation
586
+ * @returns Cascade bump result
587
+ *
588
+ * @example
589
+ * ```typescript
590
+ * import { calculateCascadeBumps } from '@hyperfrontend/versioning'
591
+ *
592
+ * // If lib-utils is getting a minor bump
593
+ * const result = calculateCascadeBumps(workspace, [
594
+ * { name: 'lib-utils', bumpType: 'minor' }
595
+ * ])
596
+ *
597
+ * // result.bumps includes lib-utils and all packages that depend on it
598
+ * for (const bump of result.bumps) {
599
+ * console.log(`${bump.name}: ${bump.currentVersion} -> ${bump.nextVersion}`)
600
+ * }
601
+ * ```
602
+ */
603
+ function calculateCascadeBumps(workspace, directBumps, options = {}) {
604
+ const opts = { ...DEFAULT_CASCADE_OPTIONS, ...options };
605
+ const directBumpMap = createMap(directBumps.map((b) => [b.name, b]));
606
+ const allBumps = createMap();
607
+ // Process direct bumps first
608
+ for (const input of directBumps) {
609
+ const project = workspace.projects.get(input.name);
610
+ if (!project) {
611
+ continue;
612
+ }
613
+ const planned = createPlannedBump(project, input.bumpType, 'direct', [], opts.prereleaseId);
614
+ allBumps.set(input.name, planned);
615
+ }
616
+ // Calculate cascade bumps
617
+ const processed = createSet();
618
+ const queue = [...directBumps.map((b) => b.name)];
619
+ while (queue.length > 0) {
620
+ const current = queue.shift();
621
+ if (current === undefined || processed.has(current)) {
622
+ continue;
623
+ }
624
+ processed.add(current);
625
+ // Get dependents
626
+ const dependents = getTransitiveDependents(workspace, current);
627
+ for (const depName of dependents) {
628
+ // Skip if already has a direct bump
629
+ if (directBumpMap.has(depName)) {
630
+ continue;
631
+ }
632
+ // Skip if already planned
633
+ if (allBumps.has(depName)) {
634
+ // Update triggered by list
635
+ const existing = allBumps.get(depName);
636
+ if (existing && !existing.triggeredBy.includes(current)) {
637
+ allBumps.set(depName, {
638
+ ...existing,
639
+ triggeredBy: [...existing.triggeredBy, current],
640
+ });
641
+ }
642
+ continue;
643
+ }
644
+ const project = workspace.projects.get(depName);
645
+ if (!project) {
646
+ continue;
647
+ }
648
+ // Check if we should include this dependent based on dependency type
649
+ if (!shouldCascade(workspace, depName, current, opts)) {
650
+ continue;
651
+ }
652
+ const planned = createPlannedBump(project, opts.cascadeBumpType, 'cascade', [current], opts.prereleaseId);
653
+ allBumps.set(depName, planned);
654
+ // Continue cascading from this dependent
655
+ queue.push(depName);
656
+ }
657
+ }
658
+ // Convert to arrays and categorize
659
+ const bumps = [...allBumps.values()];
660
+ const directBumpsArray = bumps.filter((b) => b.reason === 'direct');
661
+ const cascadeBumpsArray = bumps.filter((b) => b.reason === 'cascade');
662
+ // Sort bumps by name for consistent output
663
+ bumps.sort((a, b) => a.name.localeCompare(b.name));
664
+ return {
665
+ bumps,
666
+ directBumps: directBumpsArray,
667
+ cascadeBumps: cascadeBumpsArray,
668
+ totalAffected: bumps.length,
669
+ };
670
+ }
671
+ /**
672
+ * Determines if a cascade should propagate based on dependency type.
673
+ *
674
+ * @param workspace - Workspace containing the project
675
+ * @param dependent - Name of the dependent package
676
+ * @param dependency - Name of the dependency being bumped
677
+ * @param opts - Cascade bump options
678
+ * @returns True if the bump should cascade to this dependent
679
+ */
680
+ function shouldCascade(workspace, dependent, dependency, opts) {
681
+ const project = workspace.projects.get(dependent);
682
+ if (!project) {
683
+ return false;
684
+ }
685
+ const pkg = project.packageJson;
686
+ // Check production dependencies (always cascades)
687
+ if (pkg.dependencies?.[dependency]) {
688
+ return true;
689
+ }
690
+ // Check dev dependencies
691
+ if (opts.includeDevDependencies && pkg.devDependencies?.[dependency]) {
692
+ return true;
693
+ }
694
+ // Check peer dependencies
695
+ if (opts.includePeerDependencies && pkg.peerDependencies?.[dependency]) {
696
+ return true;
697
+ }
698
+ return false;
699
+ }
700
+ /**
701
+ * Creates a planned bump for a project.
702
+ *
703
+ * @param project - Project to create bump plan for
704
+ * @param bumpType - Type of version bump to apply
705
+ * @param reason - Reason for the bump (direct, cascade, or sync)
706
+ * @param triggeredBy - List of packages that triggered this bump
707
+ * @param prereleaseId - Optional prerelease identifier
708
+ * @returns Planned bump object with version information
709
+ */
710
+ function createPlannedBump(project, bumpType, reason, triggeredBy, prereleaseId) {
711
+ const parseResult = parseVersion(project.version);
712
+ if (!parseResult.success || !parseResult.version) {
713
+ throw createError(`Invalid version for ${project.name}: ${project.version}`);
714
+ }
715
+ const next = computeNextVersion(parseResult.version, bumpType, prereleaseId);
716
+ return {
717
+ name: project.name,
718
+ currentVersion: project.version,
719
+ nextVersion: format(next),
720
+ bumpType,
721
+ reason,
722
+ triggeredBy,
723
+ };
724
+ }
725
+ /**
726
+ * Computes the next version based on bump type.
727
+ *
728
+ * @param current - Current semantic version
729
+ * @param bumpType - Type of version bump to apply
730
+ * @param prereleaseId - Optional prerelease identifier
731
+ * @returns New semantic version after bump
732
+ */
733
+ function computeNextVersion(current, bumpType, prereleaseId) {
734
+ if (bumpType === 'none') {
735
+ return current;
736
+ }
737
+ return increment(current, bumpType, prereleaseId);
738
+ }
739
+ /**
740
+ * Calculates cascade bumps starting from a single package.
741
+ *
742
+ * @param workspace - Workspace containing projects and dependency graph
743
+ * @param packageName - Package with direct changes
744
+ * @param bumpType - Type of bump for the direct change
745
+ * @param options - Configuration for cascade behavior
746
+ * @returns Cascade bump result
747
+ */
748
+ function calculateCascadeBumpsFromPackage(workspace, packageName, bumpType, options = {}) {
749
+ return calculateCascadeBumps(workspace, [{ name: packageName, bumpType }], options);
750
+ }
751
+ /**
752
+ * Gets a summary of the cascade bump calculation.
753
+ *
754
+ * @param result - Result object from cascade bump calculation
755
+ * @returns Human-readable summary
756
+ */
757
+ function summarizeCascadeBumps(result) {
758
+ if (result.totalAffected === 0) {
759
+ return 'No packages affected';
760
+ }
761
+ const lines = [];
762
+ lines.push(`${result.totalAffected} package(s) affected:`);
763
+ lines.push(` - ${result.directBumps.length} direct bump(s)`);
764
+ lines.push(` - ${result.cascadeBumps.length} cascade bump(s)`);
765
+ lines.push('');
766
+ lines.push('Planned bumps:');
767
+ for (const bump of result.bumps) {
768
+ const suffix = bump.reason === 'cascade' ? ` (triggered by ${bump.triggeredBy.join(', ')})` : '';
769
+ lines.push(` ${bump.name}: ${bump.currentVersion} -> ${bump.nextVersion} [${bump.bumpType}]${suffix}`);
770
+ }
771
+ return lines.join('\n');
772
+ }
773
+
774
+ /**
775
+ * Safe copies of JSON built-in methods.
776
+ *
777
+ * These references are captured at module initialization time to protect against
778
+ * prototype pollution attacks. Import only what you need for tree-shaking.
779
+ *
780
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/json
781
+ */
782
+ // Capture references at module initialization time
783
+ const _JSON = globalThis.JSON;
784
+ /**
785
+ * (Safe copy) Converts a JavaScript Object Notation (JSON) string into an object.
786
+ */
787
+ const parse = _JSON.parse;
788
+ /**
789
+ * (Safe copy) Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
790
+ */
791
+ const stringify = _JSON.stringify;
792
+
793
+ /**
794
+ * Safe copies of Console built-in methods.
795
+ *
796
+ * These references are captured at module initialization time to protect against
797
+ * prototype pollution attacks. Import only what you need for tree-shaking.
798
+ *
799
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/console
800
+ */
801
+ // Capture references at module initialization time
802
+ const _console = globalThis.console;
803
+ /**
804
+ * (Safe copy) Outputs a message to the console.
805
+ */
806
+ const log = _console.log.bind(_console);
807
+ /**
808
+ * (Safe copy) Outputs a warning message to the console.
809
+ */
810
+ const warn = _console.warn.bind(_console);
811
+ /**
812
+ * (Safe copy) Outputs an error message to the console.
813
+ */
814
+ const error = _console.error.bind(_console);
815
+ /**
816
+ * (Safe copy) Outputs an informational message to the console.
817
+ */
818
+ const info = _console.info.bind(_console);
819
+ /**
820
+ * (Safe copy) Outputs a debug message to the console.
821
+ */
822
+ const debug = _console.debug.bind(_console);
823
+ /**
824
+ * (Safe copy) Outputs a stack trace to the console.
825
+ */
826
+ _console.trace.bind(_console);
827
+ /**
828
+ * (Safe copy) Displays an interactive listing of the properties of a specified object.
829
+ */
830
+ _console.dir.bind(_console);
831
+ /**
832
+ * (Safe copy) Displays tabular data as a table.
833
+ */
834
+ _console.table.bind(_console);
835
+ /**
836
+ * (Safe copy) Writes an error message to the console if the assertion is false.
837
+ */
838
+ _console.assert.bind(_console);
839
+ /**
840
+ * (Safe copy) Clears the console.
841
+ */
842
+ _console.clear.bind(_console);
843
+ /**
844
+ * (Safe copy) Logs the number of times that this particular call to count() has been called.
845
+ */
846
+ _console.count.bind(_console);
847
+ /**
848
+ * (Safe copy) Resets the counter used with console.count().
849
+ */
850
+ _console.countReset.bind(_console);
851
+ /**
852
+ * (Safe copy) Creates a new inline group in the console.
853
+ */
854
+ _console.group.bind(_console);
855
+ /**
856
+ * (Safe copy) Creates a new inline group in the console that is initially collapsed.
857
+ */
858
+ _console.groupCollapsed.bind(_console);
859
+ /**
860
+ * (Safe copy) Exits the current inline group.
861
+ */
862
+ _console.groupEnd.bind(_console);
863
+ /**
864
+ * (Safe copy) Starts a timer with a name specified as an input parameter.
865
+ */
866
+ _console.time.bind(_console);
867
+ /**
868
+ * (Safe copy) Stops a timer that was previously started.
869
+ */
870
+ _console.timeEnd.bind(_console);
871
+ /**
872
+ * (Safe copy) Logs the current value of a timer that was previously started.
873
+ */
874
+ _console.timeLog.bind(_console);
875
+
876
+ /**
877
+ * Safe copies of Array built-in static methods.
878
+ *
879
+ * These references are captured at module initialization time to protect against
880
+ * prototype pollution attacks. Import only what you need for tree-shaking.
881
+ *
882
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/array
883
+ */
884
+ // Capture references at module initialization time
885
+ const _Array = globalThis.Array;
886
+ /**
887
+ * (Safe copy) Determines whether the passed value is an Array.
888
+ */
889
+ const isArray = _Array.isArray;
890
+
891
+ const registeredClasses = [];
892
+
893
+ /**
894
+ * Returns the data type of the target.
895
+ * Uses native `typeof` operator, however, makes distinction between `null`, `array`, and `object`.
896
+ * Also, when classes are registered via `registerClass`, it checks if objects are instance of any known registered class.
897
+ *
898
+ * @param target - The target to get the data type of.
899
+ * @returns The data type of the target.
900
+ */
901
+ const getType = (target) => {
902
+ if (target === null)
903
+ return 'null';
904
+ const nativeDataType = typeof target;
905
+ if (nativeDataType === 'object') {
906
+ if (isArray(target))
907
+ return 'array';
908
+ for (const registeredClass of registeredClasses) {
909
+ if (target instanceof registeredClass)
910
+ return registeredClass.name;
911
+ }
912
+ }
913
+ return nativeDataType;
914
+ };
915
+
916
+ /**
917
+ * Safe copies of Math built-in methods.
918
+ *
919
+ * These references are captured at module initialization time to protect against
920
+ * prototype pollution attacks. Import only what you need for tree-shaking.
921
+ *
922
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/math
923
+ */
924
+ // Capture references at module initialization time
925
+ const _Math = globalThis.Math;
926
+ // ============================================================================
927
+ // Min/Max
928
+ // ============================================================================
929
+ /**
930
+ * (Safe copy) Returns the larger of zero or more numbers.
931
+ */
932
+ const max = _Math.max;
933
+
934
+ /* eslint-disable @typescript-eslint/no-explicit-any */
935
+ /**
936
+ * Creates a wrapper function that only executes the wrapped function if the condition function returns true.
937
+ *
938
+ * @param func - The function to be conditionally executed.
939
+ * @param conditionFunc - A function that returns a boolean, determining if `func` should be executed.
940
+ * @returns A wrapped version of `func` that executes conditionally.
941
+ */
942
+ function createConditionalExecutionFunction(func, conditionFunc) {
943
+ return function (...args) {
944
+ if (conditionFunc()) {
945
+ return func(...args);
946
+ }
947
+ };
948
+ }
949
+
950
+ /* eslint-disable @typescript-eslint/no-explicit-any */
951
+ /**
952
+ * Creates a wrapper function that silently ignores any errors thrown by the wrapped void function.
953
+ * This function is specifically for wrapping functions that do not return a value (void functions).
954
+ * Exceptions are swallowed without any logging or handling.
955
+ *
956
+ * @param func - The void function to be wrapped.
957
+ * @returns A wrapped version of the input function that ignores errors.
958
+ */
959
+ function createErrorIgnoringFunction(func) {
960
+ return function (...args) {
961
+ try {
962
+ func(...args);
963
+ }
964
+ catch {
965
+ // Deliberately swallowing/ignoring the exception
966
+ }
967
+ };
968
+ }
969
+
970
+ /* eslint-disable @typescript-eslint/no-unused-vars */
971
+ /**
972
+ * A no-operation function (noop) that does nothing regardless of the arguments passed.
973
+ * It is designed to be as permissive as possible in its typing without using the `Function` keyword.
974
+ *
975
+ * @param args - Any arguments passed to the function (ignored)
976
+ */
977
+ const noop = (...args) => {
978
+ // Intentionally does nothing
979
+ };
980
+
981
+ const logLevels = ['none', 'error', 'warn', 'log', 'info', 'debug'];
982
+ const priority = {
983
+ error: 4,
984
+ warn: 3,
985
+ log: 2,
986
+ info: 1,
987
+ debug: 0,
988
+ };
989
+ /**
990
+ * Validates whether a given string is a valid log level.
991
+ *
992
+ * @param level - The log level to validate
993
+ * @returns True if the level is valid, false otherwise
994
+ */
995
+ function isValidLogLevel(level) {
996
+ return logLevels.includes(level);
997
+ }
998
+ /**
999
+ * Creates a log level configuration manager for controlling logging behavior.
1000
+ * Provides methods to get, set, and evaluate log levels based on priority.
1001
+ *
1002
+ * @param level - The initial log level (defaults to 'error')
1003
+ * @returns A configuration object with log level management methods
1004
+ * @throws {Error} When the provided level is not a valid log level
1005
+ */
1006
+ function createLogLevelConfig(level = 'error') {
1007
+ if (!isValidLogLevel(level)) {
1008
+ throw createError('Cannot create log level configuration with a valid default log level');
1009
+ }
1010
+ const state = { level };
1011
+ const getLogLevel = () => state.level;
1012
+ const setLogLevel = (level) => {
1013
+ if (!isValidLogLevel(level)) {
1014
+ throw createError(`Cannot set value '${level}' level. Expected levels are ${logLevels}.`);
1015
+ }
1016
+ state.level = level;
1017
+ };
1018
+ const shouldLog = (level) => {
1019
+ if (state.level === 'none' || level === 'none' || !isValidLogLevel(level)) {
1020
+ return false;
1021
+ }
1022
+ return priority[level] >= priority[state.level];
1023
+ };
1024
+ return freeze({
1025
+ getLogLevel,
1026
+ setLogLevel,
1027
+ shouldLog,
1028
+ });
1029
+ }
1030
+
1031
+ /**
1032
+ * Creates a logger instance with configurable log level filtering.
1033
+ * Each log function is wrapped to respect the current log level setting.
1034
+ *
1035
+ * @param error - Function to handle error-level logs (required)
1036
+ * @param warn - Function to handle warning-level logs (optional, defaults to noop)
1037
+ * @param log - Function to handle standard logs (optional, defaults to noop)
1038
+ * @param info - Function to handle info-level logs (optional, defaults to noop)
1039
+ * @param debug - Function to handle debug-level logs (optional, defaults to noop)
1040
+ * @returns A frozen logger object with log methods and level control
1041
+ * @throws {ErrorLevelFn} When any provided log function is invalid
1042
+ */
1043
+ function createLogger(error, warn = noop, log = noop, info = noop, debug = noop) {
1044
+ if (notValidLogFn(error)) {
1045
+ throw createError(notFnMsg('error'));
1046
+ }
1047
+ if (notValidLogFn(warn)) {
1048
+ throw createError(notFnMsg('warn'));
1049
+ }
1050
+ if (notValidLogFn(log)) {
1051
+ throw createError(notFnMsg('log'));
1052
+ }
1053
+ if (notValidLogFn(info)) {
1054
+ throw createError(notFnMsg('info'));
1055
+ }
1056
+ if (notValidLogFn(debug)) {
1057
+ throw createError(notFnMsg('debug'));
1058
+ }
1059
+ const { setLogLevel, getLogLevel, shouldLog } = createLogLevelConfig();
1060
+ const wrapLogFn = (fn, level) => {
1061
+ if (fn === noop)
1062
+ return fn;
1063
+ const condition = () => shouldLog(level);
1064
+ return createConditionalExecutionFunction(createErrorIgnoringFunction(fn), condition);
1065
+ };
1066
+ return freeze({
1067
+ error: wrapLogFn(error, 'error'),
1068
+ warn: wrapLogFn(warn, 'warn'),
1069
+ log: wrapLogFn(log, 'log'),
1070
+ info: wrapLogFn(info, 'info'),
1071
+ debug: wrapLogFn(debug, 'debug'),
1072
+ setLogLevel,
1073
+ getLogLevel,
1074
+ });
1075
+ }
1076
+ /**
1077
+ * Validates whether a given value is a valid log function.
1078
+ *
1079
+ * @param fn - The value to validate
1080
+ * @returns True if the value is not a function (invalid), false if it is valid
1081
+ */
1082
+ function notValidLogFn(fn) {
1083
+ return getType(fn) !== 'function' && fn !== noop;
1084
+ }
1085
+ /**
1086
+ * Generates an error message for invalid log function parameters.
1087
+ *
1088
+ * @param label - The name of the log function that failed validation
1089
+ * @returns A formatted error message string
1090
+ */
1091
+ function notFnMsg(label) {
1092
+ return `Cannot create a logger when ${label} is not a function`;
1093
+ }
1094
+
1095
+ createLogger(error, warn, log, info, debug);
1096
+
1097
+ /**
1098
+ * Global log level registry.
1099
+ * Tracks all created scoped loggers to allow global log level changes.
1100
+ */
1101
+ const loggerRegistry = createSet();
1102
+ /** Redacted placeholder for sensitive values */
1103
+ const REDACTED = '[REDACTED]';
1104
+ /**
1105
+ * Patterns that indicate a sensitive key name.
1106
+ * Keys containing these patterns will have their values sanitized.
1107
+ */
1108
+ const SENSITIVE_KEY_PATTERNS = [
1109
+ /token/i,
1110
+ /key/i,
1111
+ /password/i,
1112
+ /secret/i,
1113
+ /credential/i,
1114
+ /auth/i,
1115
+ /bearer/i,
1116
+ /api[_-]?key/i,
1117
+ /private/i,
1118
+ /passphrase/i,
1119
+ ];
1120
+ /**
1121
+ * Checks if a key name indicates sensitive data.
1122
+ *
1123
+ * @param key - Key name to check
1124
+ * @returns True if the key indicates sensitive data
1125
+ */
1126
+ function isSensitiveKey(key) {
1127
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
1128
+ }
1129
+ /**
1130
+ * Sanitizes an object by replacing sensitive values with REDACTED.
1131
+ * This function recursively processes nested objects and arrays.
1132
+ *
1133
+ * @param obj - Object to sanitize
1134
+ * @returns New object with sensitive values redacted
1135
+ */
1136
+ function sanitize(obj) {
1137
+ if (obj === null || obj === undefined) {
1138
+ return obj;
1139
+ }
1140
+ if (isArray(obj)) {
1141
+ return obj.map((item) => sanitize(item));
1142
+ }
1143
+ if (typeof obj === 'object') {
1144
+ const result = {};
1145
+ for (const [key, value] of entries(obj)) {
1146
+ if (isSensitiveKey(key)) {
1147
+ result[key] = REDACTED;
1148
+ }
1149
+ else if (typeof value === 'object' && value !== null) {
1150
+ result[key] = sanitize(value);
1151
+ }
1152
+ else {
1153
+ result[key] = value;
1154
+ }
1155
+ }
1156
+ return result;
1157
+ }
1158
+ return obj;
1159
+ }
1160
+ /**
1161
+ * Formats a log message with optional metadata.
1162
+ *
1163
+ * @param namespace - Logger namespace prefix
1164
+ * @param message - Log message
1165
+ * @param meta - Optional metadata object
1166
+ * @returns Formatted log string
1167
+ */
1168
+ function formatMessage(namespace, message, meta) {
1169
+ const prefix = `[${namespace}]`;
1170
+ if (meta && keys(meta).length > 0) {
1171
+ const sanitizedMeta = sanitize(meta);
1172
+ return `${prefix} ${message} ${stringify(sanitizedMeta)}`;
1173
+ }
1174
+ return `${prefix} ${message}`;
1175
+ }
1176
+ /**
1177
+ * Creates a scoped logger with namespace prefix and optional secret sanitization.
1178
+ * All log messages will be prefixed with [namespace] and sensitive metadata
1179
+ * values will be automatically redacted.
1180
+ *
1181
+ * @param namespace - Logger namespace (e.g., 'project-scope', 'analyze')
1182
+ * @param options - Logger configuration options
1183
+ * @returns A configured scoped logger instance
1184
+ *
1185
+ * @example
1186
+ * ```typescript
1187
+ * const logger = createScopedLogger('project-scope')
1188
+ * logger.setLogLevel('debug')
1189
+ *
1190
+ * // Basic logging
1191
+ * logger.info('Starting analysis', { path: './project' })
1192
+ *
1193
+ * // Sensitive data is automatically redacted
1194
+ * logger.debug('Config loaded', { apiKey: 'secret123' })
1195
+ * // Output: [project-scope] Config loaded {"apiKey":"[REDACTED]"}
1196
+ * ```
1197
+ */
1198
+ function createScopedLogger(namespace, options = {}) {
1199
+ const { level = 'error', sanitizeSecrets = true } = options;
1200
+ // Create wrapper functions that add namespace prefix and sanitization
1201
+ const createLogFn = (baseFn) => (message, meta) => {
1202
+ const processedMeta = sanitizeSecrets && meta ? sanitize(meta) : meta;
1203
+ baseFn(formatMessage(namespace, message, processedMeta));
1204
+ };
1205
+ // Create base logger with wrapped functions
1206
+ const baseLogger = createLogger(createLogFn(error), createLogFn(warn), createLogFn(log), createLogFn(info), createLogFn(debug));
1207
+ // Set initial log level (use global override if set)
1208
+ baseLogger.setLogLevel(level);
1209
+ const scopedLogger = freeze({
1210
+ error: (message, meta) => baseLogger.error(message, meta),
1211
+ warn: (message, meta) => baseLogger.warn(message, meta),
1212
+ log: (message, meta) => baseLogger.log(message, meta),
1213
+ info: (message, meta) => baseLogger.info(message, meta),
1214
+ debug: (message, meta) => baseLogger.debug(message, meta),
1215
+ setLogLevel: baseLogger.setLogLevel,
1216
+ getLogLevel: baseLogger.getLogLevel,
1217
+ });
1218
+ // Register logger for global level management
1219
+ loggerRegistry.add(scopedLogger);
1220
+ return scopedLogger;
1221
+ }
1222
+ /**
1223
+ * Default logger instance for the project-scope library.
1224
+ * Use this for general logging within the library.
1225
+ *
1226
+ * @example
1227
+ * ```typescript
1228
+ * import { logger } from '@hyperfrontend/project-scope/core'
1229
+ *
1230
+ * logger.setLogLevel('debug')
1231
+ * logger.debug('Analyzing project', { path: './src' })
1232
+ * ```
1233
+ */
1234
+ createScopedLogger('project-scope');
1235
+
1236
+ const fsLogger = createScopedLogger('project-scope:fs');
1237
+ /**
1238
+ * Create a file system error with code and context.
1239
+ *
1240
+ * @param message - The error message describing what went wrong
1241
+ * @param code - The category code for this type of filesystem failure
1242
+ * @param context - Additional context including path, operation, and cause
1243
+ * @returns A configured Error object with code and context properties
1244
+ */
1245
+ function createFileSystemError(message, code, context) {
1246
+ const error = createError(message);
1247
+ defineProperties(error, {
1248
+ code: { value: code, enumerable: true },
1249
+ context: { value: context, enumerable: true },
1250
+ });
1251
+ return error;
1252
+ }
1253
+ /**
1254
+ * Read file contents as string.
1255
+ *
1256
+ * @param filePath - Path to file
1257
+ * @param encoding - File encoding (default: utf-8)
1258
+ * @returns File contents as string
1259
+ * @throws {Error} If file doesn't exist or can't be read
1260
+ *
1261
+ * @example
1262
+ * ```typescript
1263
+ * import { readFileContent } from '@hyperfrontend/project-scope'
1264
+ *
1265
+ * const content = readFileContent('./package.json')
1266
+ * console.log(content) // JSON string
1267
+ * ```
1268
+ */
1269
+ function readFileContent(filePath, encoding = 'utf-8') {
1270
+ if (!existsSync(filePath)) {
1271
+ fsLogger.debug('File not found', { path: filePath });
1272
+ throw createFileSystemError(`File not found: ${filePath}`, 'FS_NOT_FOUND', { path: filePath, operation: 'read' });
1273
+ }
1274
+ try {
1275
+ return readFileSync(filePath, { encoding });
1276
+ }
1277
+ catch (error) {
1278
+ fsLogger.warn('Failed to read file', { path: filePath });
1279
+ throw createFileSystemError(`Failed to read file: ${filePath}`, 'FS_READ_ERROR', { path: filePath, operation: 'read', cause: error });
1280
+ }
1281
+ }
1282
+
1283
+ const fsWriteLogger = createScopedLogger('project-scope:fs:write');
1284
+ /**
1285
+ * Ensure directory exists, create recursively if not.
1286
+ *
1287
+ * @param dirPath - Directory path to ensure exists
1288
+ */
1289
+ function ensureDir(dirPath) {
1290
+ if (!existsSync(dirPath)) {
1291
+ fsWriteLogger.debug('Creating directory recursively', { path: dirPath });
1292
+ mkdirSync(dirPath, { recursive: true });
1293
+ }
1294
+ }
1295
+ /**
1296
+ * Write string content to file.
1297
+ * Creates parent directories if needed.
1298
+ *
1299
+ * @param filePath - Absolute or relative path to the target file
1300
+ * @param content - String content to write to the file
1301
+ * @param options - Optional write configuration (encoding, mode)
1302
+ * @throws {Error} If write fails
1303
+ *
1304
+ * @example
1305
+ * ```typescript
1306
+ * import { writeFileContent } from '@hyperfrontend/project-scope'
1307
+ *
1308
+ * // Write a simple text file
1309
+ * writeFileContent('./output/data.txt', 'Hello, World!')
1310
+ *
1311
+ * // Write with custom encoding
1312
+ * writeFileContent('./output/data.txt', 'Content', { encoding: 'utf-8' })
1313
+ * ```
1314
+ */
1315
+ function writeFileContent(filePath, content, options) {
1316
+ try {
1317
+ fsWriteLogger.debug('Writing file content', { path: filePath, size: content.length, encoding: options?.encoding ?? 'utf-8' });
1318
+ ensureDir(dirname(filePath));
1319
+ writeFileSync(filePath, content, {
1320
+ encoding: options?.encoding ?? 'utf-8',
1321
+ mode: options?.mode,
1322
+ });
1323
+ fsWriteLogger.debug('File written successfully', { path: filePath });
1324
+ }
1325
+ catch (error) {
1326
+ fsWriteLogger.warn('Failed to write file', { path: filePath, error: error instanceof Error ? error.message : String(error) });
1327
+ throw createFileSystemError(`Failed to write file: ${filePath}`, 'FS_WRITE_ERROR', { path: filePath, operation: 'write', cause: error });
1328
+ }
1329
+ }
1330
+
1331
+ createScopedLogger('project-scope:fs:dir');
1332
+
1333
+ createScopedLogger('project-scope:fs:traversal');
1334
+
1335
+ createScopedLogger('project-scope:project:package');
1336
+
1337
+ createScopedLogger('project-scope:heuristics:deps');
1338
+
1339
+ /**
1340
+ * Global registry of all caches for bulk operations.
1341
+ */
1342
+ const cacheRegistry = createSet();
1343
+ /**
1344
+ * Create a cache with optional TTL and size limits.
1345
+ *
1346
+ * The cache provides a simple key-value store with:
1347
+ * - Optional TTL (time-to-live) for automatic expiration
1348
+ * - Optional maxSize for limiting cache size with FIFO eviction
1349
+ * - Lazy expiration (entries are checked on access)
1350
+ *
1351
+ * @param options - Cache configuration options
1352
+ * @returns Cache instance
1353
+ *
1354
+ * @example
1355
+ * ```typescript
1356
+ * // Basic cache
1357
+ * const cache = createCache<string, number>()
1358
+ * cache.set('answer', 42)
1359
+ * cache.get('answer') // 42
1360
+ *
1361
+ * // Cache with TTL (expires after 60 seconds)
1362
+ * const ttlCache = createCache<string, object>({ ttl: 60000 })
1363
+ *
1364
+ * // Cache with max size (evicts oldest when full)
1365
+ * const lruCache = createCache<string, object>({ maxSize: 100 })
1366
+ *
1367
+ * // Combined options
1368
+ * const configCache = createCache<string, object>({
1369
+ * ttl: 30000,
1370
+ * maxSize: 50
1371
+ * })
1372
+ * ```
1373
+ */
1374
+ function createCache(options) {
1375
+ const { ttl, maxSize } = options ?? {};
1376
+ const store = createMap();
1377
+ // Track insertion order for FIFO eviction
1378
+ const insertionOrder = [];
1379
+ /**
1380
+ * Check if an entry is expired.
1381
+ *
1382
+ * @param entry - Cache entry to check
1383
+ * @returns True if entry is expired
1384
+ */
1385
+ function isExpired(entry) {
1386
+ if (ttl === undefined)
1387
+ return false;
1388
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
1389
+ return Date.now() - entry.timestamp > ttl;
1390
+ }
1391
+ /**
1392
+ * Evict oldest entries to make room for new ones.
1393
+ */
1394
+ function evictIfNeeded() {
1395
+ if (maxSize === undefined)
1396
+ return;
1397
+ while (store.size >= maxSize && insertionOrder.length > 0) {
1398
+ const oldestKey = insertionOrder.shift();
1399
+ if (oldestKey !== undefined) {
1400
+ store.delete(oldestKey);
1401
+ }
1402
+ }
1403
+ }
1404
+ /**
1405
+ * Remove key from insertion order tracking.
1406
+ *
1407
+ * @param key - Key to remove from order tracking
1408
+ */
1409
+ function removeFromOrder(key) {
1410
+ const index = insertionOrder.indexOf(key);
1411
+ if (index !== -1) {
1412
+ insertionOrder.splice(index, 1);
1413
+ }
1414
+ }
1415
+ const cache = {
1416
+ get(key) {
1417
+ const entry = store.get(key);
1418
+ if (!entry)
1419
+ return undefined;
1420
+ if (isExpired(entry)) {
1421
+ store.delete(key);
1422
+ removeFromOrder(key);
1423
+ return undefined;
1424
+ }
1425
+ return entry.value;
1426
+ },
1427
+ set(key, value) {
1428
+ // If key exists, remove from order first
1429
+ if (store.has(key)) {
1430
+ removeFromOrder(key);
1431
+ }
1432
+ else {
1433
+ // Evict if needed before adding new entry
1434
+ evictIfNeeded();
1435
+ }
1436
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
1437
+ store.set(key, { value, timestamp: Date.now() });
1438
+ insertionOrder.push(key);
1439
+ },
1440
+ has(key) {
1441
+ const entry = store.get(key);
1442
+ if (!entry)
1443
+ return false;
1444
+ if (isExpired(entry)) {
1445
+ store.delete(key);
1446
+ removeFromOrder(key);
1447
+ return false;
1448
+ }
1449
+ return true;
1450
+ },
1451
+ delete(key) {
1452
+ removeFromOrder(key);
1453
+ return store.delete(key);
1454
+ },
1455
+ clear() {
1456
+ store.clear();
1457
+ insertionOrder.length = 0;
1458
+ },
1459
+ size() {
1460
+ return store.size;
1461
+ },
1462
+ keys() {
1463
+ return [...insertionOrder];
1464
+ },
1465
+ };
1466
+ // Register cache for global operations
1467
+ cacheRegistry.add(cache);
1468
+ return freeze(cache);
1469
+ }
1470
+
1471
+ createScopedLogger('project-scope:project:walk');
1472
+
1473
+ createScopedLogger('project-scope:project:search');
1474
+
1475
+ createScopedLogger('project-scope:heuristics:entry-points');
1476
+ /**
1477
+ * Cache for entry point discovery results.
1478
+ * TTL: 60 seconds (entry points are relatively stable)
1479
+ */
1480
+ createCache({ ttl: 60000, maxSize: 50 });
1481
+
1482
+ createScopedLogger('project-scope:tech');
1483
+ /**
1484
+ * Cache for tech detection results.
1485
+ * TTL: 60 seconds (tech stack can change during active development)
1486
+ */
1487
+ createCache({ ttl: 60000, maxSize: 50 });
1488
+
1489
+ createScopedLogger('project-scope:heuristics:project-type');
1490
+
1491
+ createScopedLogger('project-scope:root');
1492
+
1493
+ createScopedLogger('project-scope:nx');
1494
+
1495
+ createScopedLogger('project-scope:nx:devkit');
1496
+
1497
+ createScopedLogger('project-scope:nx:config');
1498
+
1499
+ createScopedLogger('project-scope:config');
1500
+ /**
1501
+ * Cache for config detection results.
1502
+ * TTL: 30 seconds (configs can change frequently during setup)
1503
+ */
1504
+ createCache({ ttl: 30000, maxSize: 50 });
1505
+
1506
+ /** Logger for analysis operations */
1507
+ createScopedLogger('project-scope:analyze');
1508
+
1509
+ /** Logger for CLI operations */
1510
+ createScopedLogger('project-scope:cli');
1511
+
1512
+ createScopedLogger('project-scope:encoding');
1513
+
1514
+ createScopedLogger('project-scope:encoding:convert');
1515
+
1516
+ createScopedLogger('project-scope:heuristics:framework');
1517
+ /**
1518
+ * Cache for framework identification results.
1519
+ * TTL: 60 seconds (frameworks are stable but can change during development)
1520
+ */
1521
+ createCache({ ttl: 60000, maxSize: 50 });
1522
+
1523
+ createScopedLogger('project-scope:vfs:tree');
1524
+
1525
+ createScopedLogger('project-scope:vfs:factory');
1526
+
1527
+ createScopedLogger('project-scope:vfs');
1528
+
1529
+ createScopedLogger('project-scope:vfs:diff');
1530
+
1531
+ /**
1532
+ * Batch Update
1533
+ *
1534
+ * Utilities for updating multiple packages at once.
1535
+ * Supports updating versions, dependencies, and other package.json fields.
1536
+ */
1537
+ /**
1538
+ * Default batch update options.
1539
+ */
1540
+ const DEFAULT_BATCH_UPDATE_OPTIONS = {
1541
+ dryRun: false,
1542
+ updateDependencyReferences: true,
1543
+ };
1544
+ /**
1545
+ * Applies planned bumps to the workspace.
1546
+ * Updates package.json version fields for all affected packages.
1547
+ *
1548
+ * @param workspace - Workspace containing projects to update
1549
+ * @param bumps - Planned version bumps
1550
+ * @param options - Update options
1551
+ * @returns Batch update result
1552
+ *
1553
+ * @example
1554
+ * ```typescript
1555
+ * import { applyBumps, calculateCascadeBumps } from '@hyperfrontend/versioning'
1556
+ *
1557
+ * const cascadeResult = calculateCascadeBumps(workspace, directBumps)
1558
+ * const updateResult = applyBumps(workspace, cascadeResult.bumps)
1559
+ *
1560
+ * if (updateResult.success) {
1561
+ * console.log(`Updated ${updateResult.updated.length} packages`)
1562
+ * } else {
1563
+ * console.error('Some updates failed:', updateResult.failed)
1564
+ * }
1565
+ * ```
1566
+ */
1567
+ function applyBumps(workspace, bumps, options = {}) {
1568
+ const opts = { ...DEFAULT_BATCH_UPDATE_OPTIONS, ...options };
1569
+ const updated = [];
1570
+ const failed = [];
1571
+ // Build a map for dependency reference updates
1572
+ const versionUpdates = createMap();
1573
+ for (const bump of bumps) {
1574
+ versionUpdates.set(bump.name, bump.nextVersion);
1575
+ }
1576
+ for (const bump of bumps) {
1577
+ const project = workspace.projects.get(bump.name);
1578
+ if (!project) {
1579
+ failed.push({
1580
+ name: bump.name,
1581
+ packageJsonPath: '',
1582
+ error: 'Project not found in workspace',
1583
+ });
1584
+ continue;
1585
+ }
1586
+ try {
1587
+ if (!opts.dryRun) {
1588
+ updatePackageVersion(project.packageJsonPath, bump.nextVersion);
1589
+ }
1590
+ updated.push({
1591
+ name: bump.name,
1592
+ packageJsonPath: project.packageJsonPath,
1593
+ previousVersion: bump.currentVersion,
1594
+ newVersion: bump.nextVersion,
1595
+ });
1596
+ }
1597
+ catch (error) {
1598
+ failed.push({
1599
+ name: bump.name,
1600
+ packageJsonPath: project.packageJsonPath,
1601
+ error: error instanceof Error ? error.message : String(error),
1602
+ });
1603
+ }
1604
+ }
1605
+ // Update dependency references if requested
1606
+ if (opts.updateDependencyReferences && !opts.dryRun) {
1607
+ for (const project of workspace.projectList) {
1608
+ try {
1609
+ updateDependencyReferences(project.packageJsonPath, versionUpdates);
1610
+ }
1611
+ catch {
1612
+ // Dependency reference updates are best-effort
1613
+ }
1614
+ }
1615
+ }
1616
+ return {
1617
+ updated,
1618
+ failed,
1619
+ total: bumps.length,
1620
+ success: failed.length === 0,
1621
+ };
1622
+ }
1623
+ /**
1624
+ * Updates the version field in a package.json file.
1625
+ *
1626
+ * @param packageJsonPath - Path to package.json
1627
+ * @param newVersion - New version string
1628
+ */
1629
+ function updatePackageVersion(packageJsonPath, newVersion) {
1630
+ const content = readFileContent(packageJsonPath);
1631
+ const pkg = parse(content);
1632
+ pkg.version = newVersion;
1633
+ const formatted = stringify(pkg, null, 2) + '\n';
1634
+ writeFileContent(packageJsonPath, formatted);
1635
+ }
1636
+ /**
1637
+ * Updates dependency version references in a package.json file.
1638
+ *
1639
+ * @param packageJsonPath - Path to package.json
1640
+ * @param versionUpdates - Map of package name to new version
1641
+ */
1642
+ function updateDependencyReferences(packageJsonPath, versionUpdates) {
1643
+ const content = readFileContent(packageJsonPath);
1644
+ const pkg = parse(content);
1645
+ let modified = false;
1646
+ const depTypes = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
1647
+ for (const depType of depTypes) {
1648
+ const deps = pkg[depType];
1649
+ if (deps) {
1650
+ for (const [name, newVersion] of versionUpdates) {
1651
+ if (deps[name]) {
1652
+ // Preserve version prefix (^, ~, etc.) or use exact version
1653
+ const currentRange = deps[name];
1654
+ const prefix = extractVersionPrefix(currentRange);
1655
+ deps[name] = prefix + newVersion;
1656
+ modified = true;
1657
+ }
1658
+ }
1659
+ }
1660
+ }
1661
+ if (modified) {
1662
+ const formatted = stringify(pkg, null, 2) + '\n';
1663
+ writeFileContent(packageJsonPath, formatted);
1664
+ }
1665
+ }
1666
+ /**
1667
+ * Extracts the version prefix from a version range.
1668
+ *
1669
+ * @param versionRange - Version range string
1670
+ * @returns The prefix (^, ~, >=, etc.) or empty string
1671
+ */
1672
+ function extractVersionPrefix(versionRange) {
1673
+ if (versionRange.startsWith('^'))
1674
+ return '^';
1675
+ if (versionRange.startsWith('~'))
1676
+ return '~';
1677
+ if (versionRange.startsWith('>='))
1678
+ return '>=';
1679
+ if (versionRange.startsWith('>'))
1680
+ return '>';
1681
+ if (versionRange.startsWith('<='))
1682
+ return '<=';
1683
+ if (versionRange.startsWith('<'))
1684
+ return '<';
1685
+ if (versionRange.startsWith('='))
1686
+ return '=';
1687
+ return '';
1688
+ }
1689
+ /**
1690
+ * Updates a package.json file using a VFS Tree.
1691
+ *
1692
+ * @param tree - Virtual file system tree
1693
+ * @param packageJsonPath - Relative path to package.json
1694
+ * @param newVersion - New version string
1695
+ */
1696
+ function updatePackageVersionInTree(tree, packageJsonPath, newVersion) {
1697
+ const content = tree.read(packageJsonPath, 'utf-8');
1698
+ if (!content) {
1699
+ throw createError(`Could not read ${packageJsonPath}`);
1700
+ }
1701
+ const pkg = parse(content);
1702
+ pkg.version = newVersion;
1703
+ const formatted = stringify(pkg, null, 2) + '\n';
1704
+ tree.write(packageJsonPath, formatted);
1705
+ }
1706
+ /**
1707
+ * Creates a summary of the batch update result.
1708
+ *
1709
+ * @param result - Result object from batch update operation
1710
+ * @returns Human-readable summary
1711
+ */
1712
+ function summarizeBatchUpdate(result) {
1713
+ const lines = [];
1714
+ if (result.success) {
1715
+ lines.push(`Successfully updated ${result.updated.length} package(s)`);
1716
+ }
1717
+ else {
1718
+ lines.push(`Updated ${result.updated.length}/${result.total} package(s)`);
1719
+ lines.push(`Failed: ${result.failed.length} package(s)`);
1720
+ }
1721
+ if (result.updated.length > 0) {
1722
+ lines.push('');
1723
+ lines.push('Updated packages:');
1724
+ for (const pkg of result.updated) {
1725
+ lines.push(` ${pkg.name}: ${pkg.previousVersion} -> ${pkg.newVersion}`);
1726
+ }
1727
+ }
1728
+ if (result.failed.length > 0) {
1729
+ lines.push('');
1730
+ lines.push('Failed packages:');
1731
+ for (const pkg of result.failed) {
1732
+ lines.push(` ${pkg.name}: ${pkg.error}`);
1733
+ }
1734
+ }
1735
+ return lines.join('\n');
1736
+ }
1737
+
1738
+ /**
1739
+ * Compares two semantic versions.
1740
+ *
1741
+ * @param a - First version
1742
+ * @param b - Second version
1743
+ * @returns -1 if a < b, 0 if a == b, 1 if a > b
1744
+ *
1745
+ * @example
1746
+ * compare(parseVersion('1.0.0'), parseVersion('2.0.0')) // -1
1747
+ * compare(parseVersion('1.0.0'), parseVersion('1.0.0')) // 0
1748
+ * compare(parseVersion('2.0.0'), parseVersion('1.0.0')) // 1
1749
+ */
1750
+ function compare(a, b) {
1751
+ // Compare major, minor, patch
1752
+ if (a.major !== b.major) {
1753
+ return a.major < b.major ? -1 : 1;
1754
+ }
1755
+ if (a.minor !== b.minor) {
1756
+ return a.minor < b.minor ? -1 : 1;
1757
+ }
1758
+ if (a.patch !== b.patch) {
1759
+ return a.patch < b.patch ? -1 : 1;
1760
+ }
1761
+ // Compare prerelease
1762
+ // Version with prerelease has lower precedence than release
1763
+ if (a.prerelease.length === 0 && b.prerelease.length > 0) {
1764
+ return 1; // a is release, b is prerelease -> a > b
1765
+ }
1766
+ if (a.prerelease.length > 0 && b.prerelease.length === 0) {
1767
+ return -1; // a is prerelease, b is release -> a < b
1768
+ }
1769
+ // Both have prerelease - compare identifiers
1770
+ const maxLen = max(a.prerelease.length, b.prerelease.length);
1771
+ for (let i = 0; i < maxLen; i++) {
1772
+ const aId = a.prerelease[i];
1773
+ const bId = b.prerelease[i];
1774
+ // Shorter prerelease array has lower precedence
1775
+ if (aId === undefined && bId !== undefined) {
1776
+ return -1;
1777
+ }
1778
+ if (aId !== undefined && bId === undefined) {
1779
+ return 1;
1780
+ }
1781
+ if (aId === undefined || bId === undefined) {
1782
+ continue;
1783
+ }
1784
+ // Compare identifiers
1785
+ const cmp = compareIdentifiers(aId, bId);
1786
+ if (cmp !== 0) {
1787
+ return cmp;
1788
+ }
1789
+ }
1790
+ return 0;
1791
+ }
1792
+ /**
1793
+ * Checks if a version satisfies a comparator.
1794
+ *
1795
+ * @param version - Version to check
1796
+ * @param comparator - Comparator to test against
1797
+ * @returns True if version satisfies the comparator
1798
+ */
1799
+ function satisfiesComparator(version, comparator) {
1800
+ const cmp = compare(version, comparator.version);
1801
+ switch (comparator.operator) {
1802
+ case '=':
1803
+ return cmp === 0;
1804
+ case '>':
1805
+ return cmp === 1;
1806
+ case '>=':
1807
+ return cmp >= 0;
1808
+ case '<':
1809
+ return cmp === -1;
1810
+ case '<=':
1811
+ return cmp <= 0;
1812
+ case '^':
1813
+ case '~':
1814
+ // These should have been expanded during parsing
1815
+ // If we encounter them here, treat as >=
1816
+ return cmp >= 0;
1817
+ default:
1818
+ return false;
1819
+ }
1820
+ }
1821
+ /**
1822
+ * Checks if a version satisfies a range.
1823
+ *
1824
+ * @param version - Version to check
1825
+ * @param range - Range to test against
1826
+ * @returns True if version satisfies the range
1827
+ *
1828
+ * @example
1829
+ * satisfies(parseVersion('1.2.3'), parseRange('^1.0.0')) // true
1830
+ * satisfies(parseVersion('2.0.0'), parseRange('^1.0.0')) // false
1831
+ */
1832
+ function satisfies(version, range) {
1833
+ // Empty range matches any
1834
+ if (range.sets.length === 0) {
1835
+ return true;
1836
+ }
1837
+ // OR logic: at least one set must be satisfied
1838
+ for (const set of range.sets) {
1839
+ // AND logic: all comparators in set must be satisfied
1840
+ let allSatisfied = true;
1841
+ // Empty comparator set matches any
1842
+ if (set.comparators.length === 0) {
1843
+ return true;
1844
+ }
1845
+ for (const comp of set.comparators) {
1846
+ if (!satisfiesComparator(version, comp)) {
1847
+ allSatisfied = false;
1848
+ break;
1849
+ }
1850
+ }
1851
+ if (allSatisfied) {
1852
+ return true;
1853
+ }
1854
+ }
1855
+ return false;
1856
+ }
1857
+ // ============================================================================
1858
+ // Internal helpers
1859
+ // ============================================================================
1860
+ /**
1861
+ * Compares two prerelease identifiers.
1862
+ * Numeric identifiers have lower precedence than alphanumeric.
1863
+ * Numeric identifiers are compared numerically.
1864
+ * Alphanumeric identifiers are compared lexically.
1865
+ *
1866
+ * @param a - First prerelease identifier
1867
+ * @param b - Second prerelease identifier
1868
+ * @returns -1 if a < b, 0 if equal, 1 if a > b
1869
+ */
1870
+ function compareIdentifiers(a, b) {
1871
+ const aIsNumeric = isNumeric(a);
1872
+ const bIsNumeric = isNumeric(b);
1873
+ // Numeric identifiers have lower precedence
1874
+ if (aIsNumeric && !bIsNumeric) {
1875
+ return -1;
1876
+ }
1877
+ if (!aIsNumeric && bIsNumeric) {
1878
+ return 1;
1879
+ }
1880
+ // Both numeric - compare as numbers
1881
+ if (aIsNumeric && bIsNumeric) {
1882
+ const aNum = parseInt(a, 10);
1883
+ const bNum = parseInt(b, 10);
1884
+ if (aNum < bNum)
1885
+ return -1;
1886
+ if (aNum > bNum)
1887
+ return 1;
1888
+ return 0;
1889
+ }
1890
+ // Both alphanumeric - compare lexically
1891
+ if (a < b)
1892
+ return -1;
1893
+ if (a > b)
1894
+ return 1;
1895
+ return 0;
1896
+ }
1897
+ /**
1898
+ * Checks if a string consists only of digits.
1899
+ *
1900
+ * @param str - String to check for numeric content
1901
+ * @returns True if string contains only digits
1902
+ */
1903
+ function isNumeric(str) {
1904
+ if (str.length === 0)
1905
+ return false;
1906
+ for (let i = 0; i < str.length; i++) {
1907
+ const code = str.charCodeAt(i);
1908
+ if (code < 48 || code > 57) {
1909
+ return false;
1910
+ }
1911
+ }
1912
+ return true;
1913
+ }
1914
+
1915
+ /**
1916
+ * Creates a new Comparator.
1917
+ *
1918
+ * @param operator - The comparison operator
1919
+ * @param version - The version to compare against
1920
+ * @returns A new Comparator
1921
+ */
1922
+ function createComparator(operator, version) {
1923
+ return { operator, version };
1924
+ }
1925
+ /**
1926
+ * Creates a new ComparatorSet.
1927
+ *
1928
+ * @param comparators - Array of comparators (AND logic)
1929
+ * @returns A new ComparatorSet
1930
+ */
1931
+ function createComparatorSet(comparators) {
1932
+ return { comparators };
1933
+ }
1934
+ /**
1935
+ * Creates a new Range.
1936
+ *
1937
+ * @param sets - Array of comparator sets (OR logic)
1938
+ * @param raw - Original raw string
1939
+ * @returns A new Range
1940
+ */
1941
+ function createRange(sets, raw) {
1942
+ return { sets, raw };
1943
+ }
1944
+
1945
+ /**
1946
+ * Maximum range string length.
1947
+ */
1948
+ const MAX_RANGE_LENGTH = 1024;
1949
+ /**
1950
+ * Parses a semver range string.
1951
+ *
1952
+ * Supports:
1953
+ * - Exact: 1.2.3, =1.2.3
1954
+ * - Comparators: >1.0.0, >=1.0.0, <2.0.0, <=2.0.0
1955
+ * - Caret: ^1.2.3 (compatible with version)
1956
+ * - Tilde: ~1.2.3 (approximately equivalent)
1957
+ * - X-ranges: 1.x, 1.2.x, *
1958
+ * - Hyphen ranges: 1.0.0 - 2.0.0
1959
+ * - OR: 1.0.0 || 2.0.0
1960
+ * - AND: >=1.0.0 <2.0.0
1961
+ *
1962
+ * @param input - The range string to parse
1963
+ * @returns A ParseRangeResult with the parsed range or error
1964
+ */
1965
+ function parseRange(input) {
1966
+ if (!input || typeof input !== 'string') {
1967
+ return { success: false, error: 'Range string is required' };
1968
+ }
1969
+ if (input.length > MAX_RANGE_LENGTH) {
1970
+ return { success: false, error: `Range string exceeds maximum length of ${MAX_RANGE_LENGTH}` };
1971
+ }
1972
+ // Trim whitespace
1973
+ const trimmed = input.trim();
1974
+ // Handle wildcard/any
1975
+ if (trimmed === '' || trimmed === '*' || trimmed.toLowerCase() === 'x') {
1976
+ return { success: true, range: createRange([], input) };
1977
+ }
1978
+ // Split by || for OR logic
1979
+ const orParts = splitByOr(trimmed);
1980
+ const sets = [];
1981
+ for (const part of orParts) {
1982
+ const setResult = parseComparatorSet(part.trim());
1983
+ if (!setResult.success) {
1984
+ return { success: false, error: setResult.error };
1985
+ }
1986
+ if (setResult.set) {
1987
+ sets.push(setResult.set);
1988
+ }
1989
+ }
1990
+ return { success: true, range: createRange(sets, input) };
1991
+ }
1992
+ /**
1993
+ * Splits a string by || delimiter, respecting nesting.
1994
+ *
1995
+ * @param input - Range string containing OR groups
1996
+ * @returns Array of OR-separated parts
1997
+ */
1998
+ function splitByOr(input) {
1999
+ const parts = [];
2000
+ let current = '';
2001
+ let pos = 0;
2002
+ while (pos < input.length) {
2003
+ if (input[pos] === '|' && pos + 1 < input.length && input[pos + 1] === '|') {
2004
+ parts.push(current);
2005
+ current = '';
2006
+ pos += 2;
2007
+ }
2008
+ else {
2009
+ current += input[pos];
2010
+ pos++;
2011
+ }
2012
+ }
2013
+ parts.push(current);
2014
+ return parts;
2015
+ }
2016
+ /**
2017
+ * Parses a single comparator set (space-separated comparators = AND logic).
2018
+ *
2019
+ * @param input - Comparator set string
2020
+ * @returns Parsed set result
2021
+ */
2022
+ function parseComparatorSet(input) {
2023
+ if (!input || input.trim() === '') {
2024
+ return { success: true }; // Empty set matches any
2025
+ }
2026
+ const trimmed = input.trim();
2027
+ // Check for hyphen range: "1.0.0 - 2.0.0"
2028
+ const hyphenMatch = parseHyphenRange(trimmed);
2029
+ if (hyphenMatch.isHyphenRange) {
2030
+ if (!hyphenMatch.success) {
2031
+ return { success: false, error: hyphenMatch.error };
2032
+ }
2033
+ return { success: true, set: hyphenMatch.set };
2034
+ }
2035
+ // Split by whitespace for AND logic
2036
+ const tokens = splitByWhitespace(trimmed);
2037
+ const comparators = [];
2038
+ for (const token of tokens) {
2039
+ const compResult = parseSingleComparator(token);
2040
+ if (!compResult.success) {
2041
+ return { success: false, error: compResult.error };
2042
+ }
2043
+ if (compResult.comparators) {
2044
+ comparators.push(...compResult.comparators);
2045
+ }
2046
+ }
2047
+ if (comparators.length === 0) {
2048
+ return { success: true }; // Empty matches any
2049
+ }
2050
+ return { success: true, set: createComparatorSet(comparators) };
2051
+ }
2052
+ /**
2053
+ * Checks for and parses hyphen ranges like "1.0.0 - 2.0.0".
2054
+ *
2055
+ * @param input - Potential hyphen range string
2056
+ * @returns Hyphen range parsing result
2057
+ */
2058
+ function parseHyphenRange(input) {
2059
+ // Look for " - " (space-hyphen-space)
2060
+ let hyphenPos = -1;
2061
+ for (let i = 0; i < input.length - 2; i++) {
2062
+ if (input[i] === ' ' && input[i + 1] === '-' && input[i + 2] === ' ') {
2063
+ hyphenPos = i;
2064
+ break;
2065
+ }
2066
+ }
2067
+ if (hyphenPos === -1) {
2068
+ return { isHyphenRange: false, success: true };
2069
+ }
2070
+ const leftPart = input.slice(0, hyphenPos).trim();
2071
+ const rightPart = input.slice(hyphenPos + 3).trim();
2072
+ const leftVersion = parseSimpleVersion(leftPart);
2073
+ if (!leftVersion) {
2074
+ return { isHyphenRange: true, success: false, error: `Invalid left side of hyphen range: "${leftPart}"` };
2075
+ }
2076
+ const rightVersion = parseSimpleVersion(rightPart);
2077
+ if (!rightVersion) {
2078
+ return { isHyphenRange: true, success: false, error: `Invalid right side of hyphen range: "${rightPart}"` };
2079
+ }
2080
+ // Hyphen range: >=left <=right
2081
+ const comparators = [createComparator('>=', leftVersion), createComparator('<=', rightVersion)];
2082
+ return {
2083
+ isHyphenRange: true,
2084
+ success: true,
2085
+ set: createComparatorSet(comparators),
2086
+ };
2087
+ }
2088
+ /**
2089
+ * Splits by whitespace.
2090
+ *
2091
+ * @param input - String to split
2092
+ * @returns Array of whitespace-separated tokens
2093
+ */
2094
+ function splitByWhitespace(input) {
2095
+ const tokens = [];
2096
+ let current = '';
2097
+ for (const char of input) {
2098
+ if (char === ' ' || char === '\t') {
2099
+ if (current) {
2100
+ tokens.push(current);
2101
+ current = '';
2102
+ }
2103
+ }
2104
+ else {
2105
+ current += char;
2106
+ }
2107
+ }
2108
+ if (current) {
2109
+ tokens.push(current);
2110
+ }
2111
+ return tokens;
2112
+ }
2113
+ /**
2114
+ * Parses a single comparator token (e.g., ">=1.0.0", "^1.2.3", "~1.0").
2115
+ *
2116
+ * @param token - Comparator token to parse
2117
+ * @returns Parsed comparator result
2118
+ */
2119
+ function parseSingleComparator(token) {
2120
+ let pos = 0;
2121
+ let operator = '=';
2122
+ // Parse operator
2123
+ if (token[pos] === '^') {
2124
+ operator = '^';
2125
+ pos++;
2126
+ }
2127
+ else if (token[pos] === '~') {
2128
+ operator = '~';
2129
+ pos++;
2130
+ }
2131
+ else if (token[pos] === '>') {
2132
+ if (token[pos + 1] === '=') {
2133
+ operator = '>=';
2134
+ pos += 2;
2135
+ }
2136
+ else {
2137
+ operator = '>';
2138
+ pos++;
2139
+ }
2140
+ }
2141
+ else if (token[pos] === '<') {
2142
+ if (token[pos + 1] === '=') {
2143
+ operator = '<=';
2144
+ pos += 2;
2145
+ }
2146
+ else {
2147
+ operator = '<';
2148
+ pos++;
2149
+ }
2150
+ }
2151
+ else if (token[pos] === '=') {
2152
+ operator = '=';
2153
+ pos++;
2154
+ }
2155
+ const versionPart = token.slice(pos);
2156
+ // Handle wildcards: *, x, X
2157
+ if (versionPart === '*' || versionPart.toLowerCase() === 'x') {
2158
+ // Wildcard matches any - return empty (will be handled as match-all)
2159
+ return { success: true, comparators: [] };
2160
+ }
2161
+ // Handle x-ranges: 1.x, 1.2.x
2162
+ if (versionPart.includes('x') || versionPart.includes('X') || versionPart.includes('*')) {
2163
+ return parseXRange(versionPart);
2164
+ }
2165
+ // Parse version
2166
+ const version = parseSimpleVersion(versionPart);
2167
+ if (!version) {
2168
+ return { success: false, error: `Invalid version in comparator: "${versionPart}"` };
2169
+ }
2170
+ // For caret and tilde, expand to range
2171
+ if (operator === '^') {
2172
+ return expandCaretRange(version);
2173
+ }
2174
+ if (operator === '~') {
2175
+ return expandTildeRange(version);
2176
+ }
2177
+ return { success: true, comparators: [createComparator(operator, version)] };
2178
+ }
2179
+ /**
2180
+ * Parses x-ranges like 1.x, 1.2.x, etc.
2181
+ *
2182
+ * @param input - X-range string to parse
2183
+ * @param _operator - Range operator (unused but kept for interface consistency)
2184
+ * @returns Comparator result
2185
+ */
2186
+ function parseXRange(input, _operator) {
2187
+ const parts = input.split('.');
2188
+ const nums = [];
2189
+ for (const part of parts) {
2190
+ const lower = part.toLowerCase();
2191
+ if (lower === 'x' || lower === '*' || lower === '') {
2192
+ break;
2193
+ }
2194
+ const num = parseInt(part, 10);
2195
+ if (globalIsNaN(num) || num < 0) {
2196
+ return { success: false, error: `Invalid x-range: "${input}"` };
2197
+ }
2198
+ nums.push(num);
2199
+ }
2200
+ if (nums.length === 0) {
2201
+ // * or X alone - match any
2202
+ return { success: true, comparators: [] };
2203
+ }
2204
+ if (nums.length === 1) {
2205
+ // 1.x or 1.* -> >=1.0.0 <2.0.0
2206
+ const lower = createSemVer({ major: nums[0], minor: 0, patch: 0 });
2207
+ const upper = createSemVer({ major: nums[0] + 1, minor: 0, patch: 0 });
2208
+ return { success: true, comparators: [createComparator('>=', lower), createComparator('<', upper)] };
2209
+ }
2210
+ // 1.2.x -> >=1.2.0 <1.3.0
2211
+ const lower = createSemVer({ major: nums[0], minor: nums[1], patch: 0 });
2212
+ const upper = createSemVer({ major: nums[0], minor: nums[1] + 1, patch: 0 });
2213
+ return { success: true, comparators: [createComparator('>=', lower), createComparator('<', upper)] };
2214
+ }
2215
+ /**
2216
+ * Expands caret range: ^1.2.3 -> >=1.2.3 <2.0.0
2217
+ *
2218
+ * @param version - Base version for caret range
2219
+ * @returns Expanded comparator result
2220
+ */
2221
+ function expandCaretRange(version) {
2222
+ let upperMajor = version.major;
2223
+ let upperMinor = 0;
2224
+ let upperPatch = 0;
2225
+ if (version.major === 0) {
2226
+ if (version.minor === 0) {
2227
+ // ^0.0.x -> >=0.0.x <0.0.(x+1)
2228
+ upperPatch = version.patch + 1;
2229
+ upperMinor = version.minor;
2230
+ }
2231
+ else {
2232
+ // ^0.x.y -> >=0.x.y <0.(x+1).0
2233
+ upperMinor = version.minor + 1;
2234
+ }
2235
+ }
2236
+ else {
2237
+ // ^x.y.z -> >=x.y.z <(x+1).0.0
2238
+ upperMajor = version.major + 1;
2239
+ }
2240
+ const upper = createSemVer({ major: upperMajor, minor: upperMinor, patch: upperPatch });
2241
+ return { success: true, comparators: [createComparator('>=', version), createComparator('<', upper)] };
2242
+ }
2243
+ /**
2244
+ * Expands tilde range: ~1.2.3 -> >=1.2.3 <1.3.0
2245
+ *
2246
+ * @param version - Base version for tilde range
2247
+ * @returns Expanded comparator result
2248
+ */
2249
+ function expandTildeRange(version) {
2250
+ const upper = createSemVer({
2251
+ major: version.major,
2252
+ minor: version.minor + 1,
2253
+ patch: 0,
2254
+ });
2255
+ return { success: true, comparators: [createComparator('>=', version), createComparator('<', upper)] };
2256
+ }
2257
+ /**
2258
+ * Parses a simple version string (no range operators).
2259
+ * More lenient - accepts partial versions.
2260
+ *
2261
+ * @param input - Version string to parse
2262
+ * @returns Parsed SemVer or null if invalid
2263
+ */
2264
+ function parseSimpleVersion(input) {
2265
+ if (!input)
2266
+ return null;
2267
+ let pos = 0;
2268
+ // Skip leading v
2269
+ if (input[pos] === 'v' || input[pos] === 'V') {
2270
+ pos++;
2271
+ }
2272
+ const parts = input.slice(pos).split('.');
2273
+ if (parts.length === 0)
2274
+ return null;
2275
+ const nums = [];
2276
+ for (const part of parts) {
2277
+ // Stop at prerelease or build
2278
+ const dashIdx = part.indexOf('-');
2279
+ const plusIdx = part.indexOf('+');
2280
+ let numPart = part;
2281
+ if (dashIdx !== -1) {
2282
+ numPart = part.slice(0, dashIdx);
2283
+ }
2284
+ else if (plusIdx !== -1) {
2285
+ numPart = part.slice(0, plusIdx);
2286
+ }
2287
+ if (numPart === '' || numPart.toLowerCase() === 'x' || numPart === '*') {
2288
+ break;
2289
+ }
2290
+ const num = parseInt(numPart, 10);
2291
+ if (globalIsNaN(num) || num < 0)
2292
+ return null;
2293
+ nums.push(num);
2294
+ }
2295
+ if (nums.length === 0)
2296
+ return null;
2297
+ return createSemVer({
2298
+ major: nums[0],
2299
+ minor: nums[1] ?? 0,
2300
+ patch: nums[2] ?? 0,
2301
+ prerelease: [],
2302
+ build: [],
2303
+ raw: input,
2304
+ });
2305
+ }
2306
+
2307
+ /**
2308
+ * Workspace Validation
2309
+ *
2310
+ * Validation utilities for workspace integrity checks.
2311
+ * Verifies package configurations, dependencies, and workspace structure.
2312
+ */
2313
+ /**
2314
+ * Validates a workspace for common issues.
2315
+ *
2316
+ * @param workspace - The workspace to validate
2317
+ * @returns Validation report
2318
+ *
2319
+ * @example
2320
+ * ```typescript
2321
+ * import { validateWorkspace } from '@hyperfrontend/versioning'
2322
+ *
2323
+ * const report = validateWorkspace(workspace)
2324
+ *
2325
+ * if (!report.valid) {
2326
+ * console.error(`${report.errorCount} error(s) found`)
2327
+ * for (const result of report.results) {
2328
+ * if (!result.result.valid) {
2329
+ * console.error(` ${result.checkName}: ${result.result.error}`)
2330
+ * }
2331
+ * }
2332
+ * }
2333
+ * ```
2334
+ */
2335
+ function validateWorkspace(workspace) {
2336
+ const results = [];
2337
+ // Workspace-level checks
2338
+ results.push({
2339
+ checkId: 'workspace-has-projects',
2340
+ checkName: 'Workspace has projects',
2341
+ packageName: null,
2342
+ result: validateHasProjects(workspace),
2343
+ });
2344
+ results.push({
2345
+ checkId: 'no-circular-dependencies',
2346
+ checkName: 'No circular dependencies',
2347
+ packageName: null,
2348
+ result: validateNoCircularDependencies(workspace),
2349
+ });
2350
+ // Package-level checks
2351
+ for (const project of workspace.projectList) {
2352
+ results.push({
2353
+ checkId: 'valid-version',
2354
+ checkName: `Valid semver version`,
2355
+ packageName: project.name,
2356
+ result: validateProjectVersion(project),
2357
+ });
2358
+ results.push({
2359
+ checkId: 'valid-name',
2360
+ checkName: `Valid package name`,
2361
+ packageName: project.name,
2362
+ result: validateProjectName(project),
2363
+ });
2364
+ results.push({
2365
+ checkId: 'dependency-versions',
2366
+ checkName: `Internal dependency versions`,
2367
+ packageName: project.name,
2368
+ result: validateDependencyVersions(workspace, project),
2369
+ });
2370
+ }
2371
+ // Aggregate results
2372
+ const errors = results.filter((r) => !r.result.valid);
2373
+ const warnings = results.filter((r) => r.result.warning !== undefined);
2374
+ const invalidPackageNames = errors
2375
+ .filter((r) => r.packageName !== null)
2376
+ .map((r) => r.packageName)
2377
+ .filter((name) => name !== null);
2378
+ const invalidPackages = createSet(invalidPackageNames);
2379
+ return {
2380
+ results,
2381
+ valid: errors.length === 0,
2382
+ errorCount: errors.length,
2383
+ warningCount: warnings.length,
2384
+ invalidPackages: [...invalidPackages],
2385
+ };
2386
+ }
2387
+ /**
2388
+ * Validates that the workspace has at least one project.
2389
+ *
2390
+ * @param workspace - Workspace to validate for project existence
2391
+ * @returns Validation result indicating success or failure
2392
+ */
2393
+ function validateHasProjects(workspace) {
2394
+ if (workspace.projects.size === 0) {
2395
+ return {
2396
+ valid: false,
2397
+ error: 'Workspace has no projects',
2398
+ };
2399
+ }
2400
+ return { valid: true };
2401
+ }
2402
+ /**
2403
+ * Validates that there are no circular dependencies.
2404
+ *
2405
+ * @param workspace - Workspace to check for circular dependencies
2406
+ * @returns Validation result indicating success or failure with cycle info
2407
+ */
2408
+ function validateNoCircularDependencies(workspace) {
2409
+ // Build adjacency list
2410
+ const visited = createSet();
2411
+ const recursionStack = createSet();
2412
+ /**
2413
+ * Depth-first search to detect cycles in the dependency graph.
2414
+ *
2415
+ * @param node - Current node being visited
2416
+ * @returns True if a cycle was found starting from this node
2417
+ */
2418
+ function hasCycle(node) {
2419
+ visited.add(node);
2420
+ recursionStack.add(node);
2421
+ const deps = workspace.reverseDependencyGraph.get(node) ?? [];
2422
+ for (const dep of deps) {
2423
+ if (!visited.has(dep)) {
2424
+ if (hasCycle(dep)) {
2425
+ return true;
2426
+ }
2427
+ }
2428
+ else if (recursionStack.has(dep)) {
2429
+ return true;
2430
+ }
2431
+ }
2432
+ recursionStack.delete(node);
2433
+ return false;
2434
+ }
2435
+ for (const name of workspace.projects.keys()) {
2436
+ if (!visited.has(name)) {
2437
+ if (hasCycle(name)) {
2438
+ return {
2439
+ valid: false,
2440
+ error: 'Circular dependency detected',
2441
+ };
2442
+ }
2443
+ }
2444
+ }
2445
+ return { valid: true };
2446
+ }
2447
+ /**
2448
+ * Validates a project's version is valid semver.
2449
+ *
2450
+ * @param project - Project to validate version for
2451
+ * @returns Validation result indicating success or failure
2452
+ */
2453
+ function validateProjectVersion(project) {
2454
+ const result = parseVersion(project.version);
2455
+ if (!result.success) {
2456
+ return {
2457
+ valid: false,
2458
+ error: `Invalid semver version: ${project.version}`,
2459
+ };
2460
+ }
2461
+ return { valid: true };
2462
+ }
2463
+ /**
2464
+ * Validates a project's package name.
2465
+ *
2466
+ * @param project - Project to validate name for
2467
+ * @returns Validation result indicating success or failure
2468
+ */
2469
+ function validateProjectName(project) {
2470
+ if (!project.name || project.name.trim() === '') {
2471
+ return {
2472
+ valid: false,
2473
+ error: 'Package name is required',
2474
+ };
2475
+ }
2476
+ // Check for valid npm package name using safe validation without complex regex
2477
+ const nameValidationResult = validatePackageNameFormat(project.name);
2478
+ if (!nameValidationResult.valid) {
2479
+ return {
2480
+ valid: false,
2481
+ error: `Invalid package name format: ${project.name}`,
2482
+ };
2483
+ }
2484
+ // Check length
2485
+ if (project.name.length > 214) {
2486
+ return {
2487
+ valid: false,
2488
+ error: 'Package name exceeds 214 characters',
2489
+ };
2490
+ }
2491
+ return { valid: true };
2492
+ }
2493
+ /**
2494
+ * Validates that internal dependency versions are satisfiable.
2495
+ *
2496
+ * @param workspace - Workspace containing all projects
2497
+ * @param project - Project to validate dependencies for
2498
+ * @returns Validation result with warnings for unsatisfied versions
2499
+ */
2500
+ function validateDependencyVersions(workspace, project) {
2501
+ const warnings = [];
2502
+ for (const depName of project.internalDependencies) {
2503
+ const dep = workspace.projects.get(depName);
2504
+ if (!dep) {
2505
+ continue; // Handled by dependency existence check
2506
+ }
2507
+ // Get the version range from package.json
2508
+ const depTypes = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
2509
+ let versionRange;
2510
+ for (const depType of depTypes) {
2511
+ const deps = project.packageJson[depType];
2512
+ if (deps?.[depName]) {
2513
+ versionRange = deps[depName];
2514
+ break;
2515
+ }
2516
+ }
2517
+ if (versionRange) {
2518
+ const depVersionResult = parseVersion(dep.version);
2519
+ if (depVersionResult.success && depVersionResult.version && !isWorkspaceVersion(versionRange)) {
2520
+ // Parse the version range
2521
+ const rangeResult = parseRange(versionRange);
2522
+ if (rangeResult.success && rangeResult.range) {
2523
+ // Check if the current version satisfies the range
2524
+ if (!satisfies(depVersionResult.version, rangeResult.range)) {
2525
+ warnings.push(`${depName}@${dep.version} does not satisfy ${versionRange}`);
2526
+ }
2527
+ }
2528
+ }
2529
+ }
2530
+ }
2531
+ if (warnings.length > 0) {
2532
+ return {
2533
+ valid: true, // Warning, not error
2534
+ warning: warnings.join('; '),
2535
+ };
2536
+ }
2537
+ return { valid: true };
2538
+ }
2539
+ /**
2540
+ * Validates npm package name format without using complex regex.
2541
+ * This avoids ReDoS vulnerabilities from backtracking regex patterns.
2542
+ *
2543
+ * @param name - Package name to validate
2544
+ * @returns Validation result
2545
+ */
2546
+ function validatePackageNameFormat(name) {
2547
+ // Valid characters for package names: lowercase letters, digits, hyphens, underscores, dots
2548
+ const isValidChar = (char) => {
2549
+ const code = char.charCodeAt(0);
2550
+ return ((code >= 97 && code <= 122) || // a-z
2551
+ (code >= 48 && code <= 57) || // 0-9
2552
+ code === 45 || // -
2553
+ code === 95 || // _
2554
+ code === 46 // .
2555
+ );
2556
+ };
2557
+ // First char must be lowercase letter or digit
2558
+ const isValidFirstChar = (char) => {
2559
+ const code = char.charCodeAt(0);
2560
+ return (code >= 97 && code <= 122) || (code >= 48 && code <= 57);
2561
+ };
2562
+ // Handle scoped packages (@scope/name)
2563
+ if (name.startsWith('@')) {
2564
+ const slashIndex = name.indexOf('/');
2565
+ if (slashIndex === -1 || slashIndex === 1 || slashIndex === name.length - 1) {
2566
+ return { valid: false };
2567
+ }
2568
+ // Validate scope (after @, before /)
2569
+ const scope = name.slice(1, slashIndex);
2570
+ if (!isValidFirstChar(scope[0]))
2571
+ return { valid: false };
2572
+ for (const char of scope) {
2573
+ if (!isValidChar(char))
2574
+ return { valid: false };
2575
+ }
2576
+ // Validate name (after /)
2577
+ const packageName = name.slice(slashIndex + 1);
2578
+ if (!isValidFirstChar(packageName[0]))
2579
+ return { valid: false };
2580
+ for (const char of packageName) {
2581
+ if (!isValidChar(char))
2582
+ return { valid: false };
2583
+ }
2584
+ }
2585
+ else {
2586
+ // Unscoped package
2587
+ if (!isValidFirstChar(name[0]))
2588
+ return { valid: false };
2589
+ for (const char of name) {
2590
+ if (!isValidChar(char))
2591
+ return { valid: false };
2592
+ }
2593
+ }
2594
+ return { valid: true };
2595
+ }
2596
+ /**
2597
+ * Checks if a version range is a workspace protocol version.
2598
+ *
2599
+ * @param versionRange - Version range string to check
2600
+ * @returns True if the range uses workspace protocol
2601
+ */
2602
+ function isWorkspaceVersion(versionRange) {
2603
+ return versionRange.startsWith('workspace:') || versionRange === '*' || versionRange === 'link:';
2604
+ }
2605
+ /**
2606
+ * Validates a single project.
2607
+ *
2608
+ * @param project - The project to validate
2609
+ * @returns Validation result
2610
+ */
2611
+ function validateProject(project) {
2612
+ const versionResult = validateProjectVersion(project);
2613
+ if (!versionResult.valid) {
2614
+ return versionResult;
2615
+ }
2616
+ const nameResult = validateProjectName(project);
2617
+ if (!nameResult.valid) {
2618
+ return nameResult;
2619
+ }
2620
+ return { valid: true };
2621
+ }
2622
+ /**
2623
+ * Creates a summary of the validation report.
2624
+ *
2625
+ * @param report - Report object from workspace validation
2626
+ * @returns Human-readable summary
2627
+ */
2628
+ function summarizeValidation(report) {
2629
+ const lines = [];
2630
+ if (report.valid) {
2631
+ lines.push('Workspace validation passed');
2632
+ if (report.warningCount > 0) {
2633
+ lines.push(` ${report.warningCount} warning(s)`);
2634
+ }
2635
+ }
2636
+ else {
2637
+ lines.push('Workspace validation failed');
2638
+ lines.push(` ${report.errorCount} error(s)`);
2639
+ lines.push(` ${report.warningCount} warning(s)`);
2640
+ lines.push('');
2641
+ lines.push('Errors:');
2642
+ for (const result of report.results) {
2643
+ if (!result.result.valid) {
2644
+ const pkg = result.packageName ? `[${result.packageName}] ` : '';
2645
+ lines.push(` ${pkg}${result.checkName}: ${result.result.error}`);
2646
+ }
2647
+ }
2648
+ if (report.warningCount > 0) {
2649
+ lines.push('');
2650
+ lines.push('Warnings:');
2651
+ for (const result of report.results) {
2652
+ if (result.result.warning) {
2653
+ const pkg = result.packageName ? `[${result.packageName}] ` : '';
2654
+ lines.push(` ${pkg}${result.checkName}: ${result.result.warning}`);
2655
+ }
2656
+ }
2657
+ }
2658
+ }
2659
+ return lines.join('\n');
2660
+ }
2661
+
2662
+ export { DEFAULT_BATCH_UPDATE_OPTIONS, DEFAULT_CASCADE_OPTIONS, applyBumps, calculateCascadeBumps, calculateCascadeBumpsFromPackage, summarizeBatchUpdate, summarizeCascadeBumps, summarizeValidation, updatePackageVersionInTree, validateProject, validateWorkspace };
2663
+ //# sourceMappingURL=index.esm.js.map