@hyperfrontend/project-scope 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 (391) hide show
  1. package/ARCHITECTURE.md +370 -0
  2. package/CHANGELOG.md +10 -0
  3. package/FUNDING.md +141 -0
  4. package/LICENSE.md +21 -0
  5. package/README.md +242 -0
  6. package/SECURITY.md +82 -0
  7. package/analyze.d.ts +33 -0
  8. package/analyze.d.ts.map +1 -0
  9. package/cli/commands/analyze.d.ts +20 -0
  10. package/cli/commands/analyze.d.ts.map +1 -0
  11. package/cli/commands/config.d.ts +20 -0
  12. package/cli/commands/config.d.ts.map +1 -0
  13. package/cli/commands/deps.d.ts +18 -0
  14. package/cli/commands/deps.d.ts.map +1 -0
  15. package/cli/commands/tree.d.ts +24 -0
  16. package/cli/commands/tree.d.ts.map +1 -0
  17. package/cli/index.cjs.js +6639 -0
  18. package/cli/index.cjs.js.map +1 -0
  19. package/cli/index.d.ts +7 -0
  20. package/cli/index.d.ts.map +1 -0
  21. package/cli/index.esm.js +6629 -0
  22. package/cli/index.esm.js.map +1 -0
  23. package/cli/run.d.ts +25 -0
  24. package/cli/run.d.ts.map +1 -0
  25. package/cli/types.d.ts +55 -0
  26. package/cli/types.d.ts.map +1 -0
  27. package/core/cache.d.ts +157 -0
  28. package/core/cache.d.ts.map +1 -0
  29. package/core/encoding/convert.d.ts +32 -0
  30. package/core/encoding/convert.d.ts.map +1 -0
  31. package/core/encoding/detect.d.ts +86 -0
  32. package/core/encoding/detect.d.ts.map +1 -0
  33. package/core/encoding/index.cjs.js +751 -0
  34. package/core/encoding/index.cjs.js.map +1 -0
  35. package/core/encoding/index.d.ts +3 -0
  36. package/core/encoding/index.d.ts.map +1 -0
  37. package/core/encoding/index.esm.js +736 -0
  38. package/core/encoding/index.esm.js.map +1 -0
  39. package/core/errors/structured-errors.d.ts +64 -0
  40. package/core/errors/structured-errors.d.ts.map +1 -0
  41. package/core/fs/directory.d.ts +88 -0
  42. package/core/fs/directory.d.ts.map +1 -0
  43. package/core/fs/index.cjs.js +1079 -0
  44. package/core/fs/index.cjs.js.map +1 -0
  45. package/core/fs/index.d.ts +6 -0
  46. package/core/fs/index.d.ts.map +1 -0
  47. package/core/fs/index.esm.js +1056 -0
  48. package/core/fs/index.esm.js.map +1 -0
  49. package/core/fs/read.d.ts +86 -0
  50. package/core/fs/read.d.ts.map +1 -0
  51. package/core/fs/stat.d.ts +58 -0
  52. package/core/fs/stat.d.ts.map +1 -0
  53. package/core/fs/traversal.d.ts +26 -0
  54. package/core/fs/traversal.d.ts.map +1 -0
  55. package/core/fs/write.d.ts +75 -0
  56. package/core/fs/write.d.ts.map +1 -0
  57. package/core/index.cjs.js +2376 -0
  58. package/core/index.cjs.js.map +1 -0
  59. package/core/index.d.ts +9 -0
  60. package/core/index.d.ts.map +1 -0
  61. package/core/index.esm.js +2286 -0
  62. package/core/index.esm.js.map +1 -0
  63. package/core/logger.d.ts +111 -0
  64. package/core/logger.d.ts.map +1 -0
  65. package/core/path/index.cjs.js +254 -0
  66. package/core/path/index.cjs.js.map +1 -0
  67. package/core/path/index.d.ts +5 -0
  68. package/core/path/index.d.ts.map +1 -0
  69. package/core/path/index.esm.js +233 -0
  70. package/core/path/index.esm.js.map +1 -0
  71. package/core/path/join.d.ts +17 -0
  72. package/core/path/join.d.ts.map +1 -0
  73. package/core/path/normalize.d.ts +37 -0
  74. package/core/path/normalize.d.ts.map +1 -0
  75. package/core/path/resolve.d.ts +52 -0
  76. package/core/path/resolve.d.ts.map +1 -0
  77. package/core/path/segments.d.ts +59 -0
  78. package/core/path/segments.d.ts.map +1 -0
  79. package/core/patterns/glob.d.ts +46 -0
  80. package/core/patterns/glob.d.ts.map +1 -0
  81. package/core/platform/detect.d.ts +66 -0
  82. package/core/platform/detect.d.ts.map +1 -0
  83. package/core/platform/index.cjs.js +241 -0
  84. package/core/platform/index.cjs.js.map +1 -0
  85. package/core/platform/index.d.ts +3 -0
  86. package/core/platform/index.d.ts.map +1 -0
  87. package/core/platform/index.esm.js +226 -0
  88. package/core/platform/index.esm.js.map +1 -0
  89. package/core/platform/line-endings.d.ts +48 -0
  90. package/core/platform/line-endings.d.ts.map +1 -0
  91. package/heuristics/dependencies/analyze.d.ts +77 -0
  92. package/heuristics/dependencies/analyze.d.ts.map +1 -0
  93. package/heuristics/dependencies/index.cjs.js +1126 -0
  94. package/heuristics/dependencies/index.cjs.js.map +1 -0
  95. package/heuristics/dependencies/index.d.ts +2 -0
  96. package/heuristics/dependencies/index.d.ts.map +1 -0
  97. package/heuristics/dependencies/index.esm.js +1122 -0
  98. package/heuristics/dependencies/index.esm.js.map +1 -0
  99. package/heuristics/entry-points/discover.d.ts +86 -0
  100. package/heuristics/entry-points/discover.d.ts.map +1 -0
  101. package/heuristics/entry-points/index.cjs.js +1581 -0
  102. package/heuristics/entry-points/index.cjs.js.map +1 -0
  103. package/heuristics/entry-points/index.d.ts +2 -0
  104. package/heuristics/entry-points/index.d.ts.map +1 -0
  105. package/heuristics/entry-points/index.esm.js +1577 -0
  106. package/heuristics/entry-points/index.esm.js.map +1 -0
  107. package/heuristics/framework/identify.d.ts +84 -0
  108. package/heuristics/framework/identify.d.ts.map +1 -0
  109. package/heuristics/framework/index.cjs.js +3618 -0
  110. package/heuristics/framework/index.cjs.js.map +1 -0
  111. package/heuristics/framework/index.d.ts +2 -0
  112. package/heuristics/framework/index.d.ts.map +1 -0
  113. package/heuristics/framework/index.esm.js +3614 -0
  114. package/heuristics/framework/index.esm.js.map +1 -0
  115. package/heuristics/index.cjs.js +4833 -0
  116. package/heuristics/index.cjs.js.map +1 -0
  117. package/heuristics/index.d.ts +5 -0
  118. package/heuristics/index.d.ts.map +1 -0
  119. package/heuristics/index.esm.js +4822 -0
  120. package/heuristics/index.esm.js.map +1 -0
  121. package/heuristics/project-type/detect.d.ts +61 -0
  122. package/heuristics/project-type/detect.d.ts.map +1 -0
  123. package/heuristics/project-type/index.cjs.js +3633 -0
  124. package/heuristics/project-type/index.cjs.js.map +1 -0
  125. package/heuristics/project-type/index.d.ts +2 -0
  126. package/heuristics/project-type/index.d.ts.map +1 -0
  127. package/heuristics/project-type/index.esm.js +3631 -0
  128. package/heuristics/project-type/index.esm.js.map +1 -0
  129. package/index.cjs.js +10255 -0
  130. package/index.cjs.js.map +1 -0
  131. package/index.d.ts +10 -0
  132. package/index.d.ts.map +1 -0
  133. package/index.esm.js +10006 -0
  134. package/index.esm.js.map +1 -0
  135. package/models/index.cjs.js +3 -0
  136. package/models/index.cjs.js.map +1 -0
  137. package/models/index.d.ts +176 -0
  138. package/models/index.d.ts.map +1 -0
  139. package/models/index.esm.js +2 -0
  140. package/models/index.esm.js.map +1 -0
  141. package/nx/detect.d.ts +105 -0
  142. package/nx/detect.d.ts.map +1 -0
  143. package/nx/devkit-loader.d.ts +62 -0
  144. package/nx/devkit-loader.d.ts.map +1 -0
  145. package/nx/index.cjs.js +1302 -0
  146. package/nx/index.cjs.js.map +1 -0
  147. package/nx/index.d.ts +4 -0
  148. package/nx/index.d.ts.map +1 -0
  149. package/nx/index.esm.js +1286 -0
  150. package/nx/index.esm.js.map +1 -0
  151. package/nx/project-config.d.ts +109 -0
  152. package/nx/project-config.d.ts.map +1 -0
  153. package/package.json +218 -0
  154. package/project/config/detect.d.ts +77 -0
  155. package/project/config/detect.d.ts.map +1 -0
  156. package/project/config/index.cjs.js +1982 -0
  157. package/project/config/index.cjs.js.map +1 -0
  158. package/project/config/index.d.ts +4 -0
  159. package/project/config/index.d.ts.map +1 -0
  160. package/project/config/index.esm.js +1971 -0
  161. package/project/config/index.esm.js.map +1 -0
  162. package/project/config/parse.d.ts +53 -0
  163. package/project/config/parse.d.ts.map +1 -0
  164. package/project/config/patterns.d.ts +31 -0
  165. package/project/config/patterns.d.ts.map +1 -0
  166. package/project/index.cjs.js +2585 -0
  167. package/project/index.cjs.js.map +1 -0
  168. package/project/index.d.ts +5 -0
  169. package/project/index.d.ts.map +1 -0
  170. package/project/index.esm.js +2549 -0
  171. package/project/index.esm.js.map +1 -0
  172. package/project/package/dependencies.d.ts +101 -0
  173. package/project/package/dependencies.d.ts.map +1 -0
  174. package/project/package/index.cjs.js +972 -0
  175. package/project/package/index.cjs.js.map +1 -0
  176. package/project/package/index.d.ts +3 -0
  177. package/project/package/index.d.ts.map +1 -0
  178. package/project/package/index.esm.js +957 -0
  179. package/project/package/index.esm.js.map +1 -0
  180. package/project/package/read.d.ts +66 -0
  181. package/project/package/read.d.ts.map +1 -0
  182. package/project/root/detect.d.ts +65 -0
  183. package/project/root/detect.d.ts.map +1 -0
  184. package/project/root/index.cjs.js +860 -0
  185. package/project/root/index.cjs.js.map +1 -0
  186. package/project/root/index.d.ts +2 -0
  187. package/project/root/index.d.ts.map +1 -0
  188. package/project/root/index.esm.js +853 -0
  189. package/project/root/index.esm.js.map +1 -0
  190. package/project/traversal/index.cjs.js +1179 -0
  191. package/project/traversal/index.cjs.js.map +1 -0
  192. package/project/traversal/index.d.ts +3 -0
  193. package/project/traversal/index.d.ts.map +1 -0
  194. package/project/traversal/index.esm.js +1173 -0
  195. package/project/traversal/index.esm.js.map +1 -0
  196. package/project/traversal/search.d.ts +59 -0
  197. package/project/traversal/search.d.ts.map +1 -0
  198. package/project/traversal/walk.d.ts +63 -0
  199. package/project/traversal/walk.d.ts.map +1 -0
  200. package/tech/backend/detect-all.d.ts +13 -0
  201. package/tech/backend/detect-all.d.ts.map +1 -0
  202. package/tech/backend/express.d.ts +11 -0
  203. package/tech/backend/express.d.ts.map +1 -0
  204. package/tech/backend/fastify.d.ts +11 -0
  205. package/tech/backend/fastify.d.ts.map +1 -0
  206. package/tech/backend/hono.d.ts +11 -0
  207. package/tech/backend/hono.d.ts.map +1 -0
  208. package/tech/backend/index.cjs.js +939 -0
  209. package/tech/backend/index.cjs.js.map +1 -0
  210. package/tech/backend/index.d.ts +8 -0
  211. package/tech/backend/index.d.ts.map +1 -0
  212. package/tech/backend/index.esm.js +931 -0
  213. package/tech/backend/index.esm.js.map +1 -0
  214. package/tech/backend/koa.d.ts +11 -0
  215. package/tech/backend/koa.d.ts.map +1 -0
  216. package/tech/backend/nestjs.d.ts +11 -0
  217. package/tech/backend/nestjs.d.ts.map +1 -0
  218. package/tech/backend/types.d.ts +31 -0
  219. package/tech/backend/types.d.ts.map +1 -0
  220. package/tech/build/babel.d.ts +13 -0
  221. package/tech/build/babel.d.ts.map +1 -0
  222. package/tech/build/detect-all.d.ts +13 -0
  223. package/tech/build/detect-all.d.ts.map +1 -0
  224. package/tech/build/esbuild.d.ts +11 -0
  225. package/tech/build/esbuild.d.ts.map +1 -0
  226. package/tech/build/index.cjs.js +1118 -0
  227. package/tech/build/index.cjs.js.map +1 -0
  228. package/tech/build/index.d.ts +10 -0
  229. package/tech/build/index.d.ts.map +1 -0
  230. package/tech/build/index.esm.js +1102 -0
  231. package/tech/build/index.esm.js.map +1 -0
  232. package/tech/build/parcel.d.ts +13 -0
  233. package/tech/build/parcel.d.ts.map +1 -0
  234. package/tech/build/rollup.d.ts +13 -0
  235. package/tech/build/rollup.d.ts.map +1 -0
  236. package/tech/build/swc.d.ts +13 -0
  237. package/tech/build/swc.d.ts.map +1 -0
  238. package/tech/build/types.d.ts +31 -0
  239. package/tech/build/types.d.ts.map +1 -0
  240. package/tech/build/vite.d.ts +13 -0
  241. package/tech/build/vite.d.ts.map +1 -0
  242. package/tech/build/webpack.d.ts +13 -0
  243. package/tech/build/webpack.d.ts.map +1 -0
  244. package/tech/frontend/angular.d.ts +11 -0
  245. package/tech/frontend/angular.d.ts.map +1 -0
  246. package/tech/frontend/astro.d.ts +11 -0
  247. package/tech/frontend/astro.d.ts.map +1 -0
  248. package/tech/frontend/detect-all.d.ts +13 -0
  249. package/tech/frontend/detect-all.d.ts.map +1 -0
  250. package/tech/frontend/gatsby.d.ts +11 -0
  251. package/tech/frontend/gatsby.d.ts.map +1 -0
  252. package/tech/frontend/index.cjs.js +1310 -0
  253. package/tech/frontend/index.cjs.js.map +1 -0
  254. package/tech/frontend/index.d.ts +15 -0
  255. package/tech/frontend/index.d.ts.map +1 -0
  256. package/tech/frontend/index.esm.js +1295 -0
  257. package/tech/frontend/index.esm.js.map +1 -0
  258. package/tech/frontend/nextjs.d.ts +11 -0
  259. package/tech/frontend/nextjs.d.ts.map +1 -0
  260. package/tech/frontend/nuxt.d.ts +11 -0
  261. package/tech/frontend/nuxt.d.ts.map +1 -0
  262. package/tech/frontend/qwik.d.ts +11 -0
  263. package/tech/frontend/qwik.d.ts.map +1 -0
  264. package/tech/frontend/react.d.ts +11 -0
  265. package/tech/frontend/react.d.ts.map +1 -0
  266. package/tech/frontend/remix.d.ts +11 -0
  267. package/tech/frontend/remix.d.ts.map +1 -0
  268. package/tech/frontend/solid.d.ts +11 -0
  269. package/tech/frontend/solid.d.ts.map +1 -0
  270. package/tech/frontend/svelte.d.ts +11 -0
  271. package/tech/frontend/svelte.d.ts.map +1 -0
  272. package/tech/frontend/sveltekit.d.ts +11 -0
  273. package/tech/frontend/sveltekit.d.ts.map +1 -0
  274. package/tech/frontend/types.d.ts +35 -0
  275. package/tech/frontend/types.d.ts.map +1 -0
  276. package/tech/frontend/vue.d.ts +11 -0
  277. package/tech/frontend/vue.d.ts.map +1 -0
  278. package/tech/index.cjs.js +3684 -0
  279. package/tech/index.cjs.js.map +1 -0
  280. package/tech/index.d.ts +96 -0
  281. package/tech/index.d.ts.map +1 -0
  282. package/tech/index.esm.js +3603 -0
  283. package/tech/index.esm.js.map +1 -0
  284. package/tech/legacy/angularjs.d.ts +12 -0
  285. package/tech/legacy/angularjs.d.ts.map +1 -0
  286. package/tech/legacy/backbone.d.ts +11 -0
  287. package/tech/legacy/backbone.d.ts.map +1 -0
  288. package/tech/legacy/detect-all.d.ts +13 -0
  289. package/tech/legacy/detect-all.d.ts.map +1 -0
  290. package/tech/legacy/ember.d.ts +11 -0
  291. package/tech/legacy/ember.d.ts.map +1 -0
  292. package/tech/legacy/index.cjs.js +903 -0
  293. package/tech/legacy/index.cjs.js.map +1 -0
  294. package/tech/legacy/index.d.ts +7 -0
  295. package/tech/legacy/index.d.ts.map +1 -0
  296. package/tech/legacy/index.esm.js +896 -0
  297. package/tech/legacy/index.esm.js.map +1 -0
  298. package/tech/legacy/jquery.d.ts +11 -0
  299. package/tech/legacy/jquery.d.ts.map +1 -0
  300. package/tech/legacy/types.d.ts +33 -0
  301. package/tech/legacy/types.d.ts.map +1 -0
  302. package/tech/linting/biome.d.ts +11 -0
  303. package/tech/linting/biome.d.ts.map +1 -0
  304. package/tech/linting/detect-all.d.ts +13 -0
  305. package/tech/linting/detect-all.d.ts.map +1 -0
  306. package/tech/linting/eslint.d.ts +13 -0
  307. package/tech/linting/eslint.d.ts.map +1 -0
  308. package/tech/linting/index.cjs.js +992 -0
  309. package/tech/linting/index.cjs.js.map +1 -0
  310. package/tech/linting/index.d.ts +7 -0
  311. package/tech/linting/index.d.ts.map +1 -0
  312. package/tech/linting/index.esm.js +982 -0
  313. package/tech/linting/index.esm.js.map +1 -0
  314. package/tech/linting/prettier.d.ts +13 -0
  315. package/tech/linting/prettier.d.ts.map +1 -0
  316. package/tech/linting/stylelint.d.ts +13 -0
  317. package/tech/linting/stylelint.d.ts.map +1 -0
  318. package/tech/linting/types.d.ts +31 -0
  319. package/tech/linting/types.d.ts.map +1 -0
  320. package/tech/monorepo/detect-all.d.ts +13 -0
  321. package/tech/monorepo/detect-all.d.ts.map +1 -0
  322. package/tech/monorepo/index.cjs.js +1021 -0
  323. package/tech/monorepo/index.cjs.js.map +1 -0
  324. package/tech/monorepo/index.d.ts +10 -0
  325. package/tech/monorepo/index.d.ts.map +1 -0
  326. package/tech/monorepo/index.esm.js +1011 -0
  327. package/tech/monorepo/index.esm.js.map +1 -0
  328. package/tech/monorepo/lerna.d.ts +11 -0
  329. package/tech/monorepo/lerna.d.ts.map +1 -0
  330. package/tech/monorepo/npm-workspaces.d.ts +11 -0
  331. package/tech/monorepo/npm-workspaces.d.ts.map +1 -0
  332. package/tech/monorepo/nx.d.ts +11 -0
  333. package/tech/monorepo/nx.d.ts.map +1 -0
  334. package/tech/monorepo/pnpm-workspaces.d.ts +9 -0
  335. package/tech/monorepo/pnpm-workspaces.d.ts.map +1 -0
  336. package/tech/monorepo/rush.d.ts +11 -0
  337. package/tech/monorepo/rush.d.ts.map +1 -0
  338. package/tech/monorepo/turborepo.d.ts +11 -0
  339. package/tech/monorepo/turborepo.d.ts.map +1 -0
  340. package/tech/monorepo/types.d.ts +39 -0
  341. package/tech/monorepo/types.d.ts.map +1 -0
  342. package/tech/monorepo/yarn-workspaces.d.ts +11 -0
  343. package/tech/monorepo/yarn-workspaces.d.ts.map +1 -0
  344. package/tech/shared-utils/detector-helpers.d.ts +52 -0
  345. package/tech/shared-utils/detector-helpers.d.ts.map +1 -0
  346. package/tech/shared-utils/types.d.ts +41 -0
  347. package/tech/shared-utils/types.d.ts.map +1 -0
  348. package/tech/testing/cypress.d.ts +13 -0
  349. package/tech/testing/cypress.d.ts.map +1 -0
  350. package/tech/testing/detect-all.d.ts +13 -0
  351. package/tech/testing/detect-all.d.ts.map +1 -0
  352. package/tech/testing/index.cjs.js +1031 -0
  353. package/tech/testing/index.cjs.js.map +1 -0
  354. package/tech/testing/index.d.ts +8 -0
  355. package/tech/testing/index.d.ts.map +1 -0
  356. package/tech/testing/index.esm.js +1018 -0
  357. package/tech/testing/index.esm.js.map +1 -0
  358. package/tech/testing/jest.d.ts +13 -0
  359. package/tech/testing/jest.d.ts.map +1 -0
  360. package/tech/testing/mocha.d.ts +13 -0
  361. package/tech/testing/mocha.d.ts.map +1 -0
  362. package/tech/testing/playwright.d.ts +13 -0
  363. package/tech/testing/playwright.d.ts.map +1 -0
  364. package/tech/testing/types.d.ts +35 -0
  365. package/tech/testing/types.d.ts.map +1 -0
  366. package/tech/testing/vitest.d.ts +13 -0
  367. package/tech/testing/vitest.d.ts.map +1 -0
  368. package/tech/types/detectors.d.ts +67 -0
  369. package/tech/types/detectors.d.ts.map +1 -0
  370. package/tech/types/index.cjs.js +1045 -0
  371. package/tech/types/index.cjs.js.map +1 -0
  372. package/tech/types/index.d.ts +2 -0
  373. package/tech/types/index.d.ts.map +1 -0
  374. package/tech/types/index.esm.js +1039 -0
  375. package/tech/types/index.esm.js.map +1 -0
  376. package/vfs/commit.d.ts +32 -0
  377. package/vfs/commit.d.ts.map +1 -0
  378. package/vfs/diff.d.ts +73 -0
  379. package/vfs/diff.d.ts.map +1 -0
  380. package/vfs/factory.d.ts +37 -0
  381. package/vfs/factory.d.ts.map +1 -0
  382. package/vfs/fs-tree.d.ts +13 -0
  383. package/vfs/fs-tree.d.ts.map +1 -0
  384. package/vfs/index.cjs.js +1600 -0
  385. package/vfs/index.cjs.js.map +1 -0
  386. package/vfs/index.d.ts +6 -0
  387. package/vfs/index.d.ts.map +1 -0
  388. package/vfs/index.esm.js +1590 -0
  389. package/vfs/index.esm.js.map +1 -0
  390. package/vfs/types.d.ts +178 -0
  391. package/vfs/types.d.ts.map +1 -0
@@ -0,0 +1,2549 @@
1
+ import { join as join$1, resolve, parse as parse$1, dirname, basename } from 'node:path';
2
+ import { existsSync, readFileSync, statSync, lstatSync, readdirSync } from 'node:fs';
3
+
4
+ /**
5
+ * Safe copies of Error built-ins via factory functions.
6
+ *
7
+ * Since constructors cannot be safely captured via Object.assign, this module
8
+ * provides factory functions that use Reflect.construct internally.
9
+ *
10
+ * These references are captured at module initialization time to protect against
11
+ * prototype pollution attacks. Import only what you need for tree-shaking.
12
+ *
13
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
14
+ */
15
+ // Capture references at module initialization time
16
+ const _Error = globalThis.Error;
17
+ const _Reflect$2 = globalThis.Reflect;
18
+ /**
19
+ * (Safe copy) Creates a new Error using the captured Error constructor.
20
+ * Use this instead of `new Error()`.
21
+ *
22
+ * @param message - Optional error message.
23
+ * @param options - Optional error options.
24
+ * @returns A new Error instance.
25
+ */
26
+ const createError = (message, options) => _Reflect$2.construct(_Error, [message, options]);
27
+
28
+ /**
29
+ * Safe copies of JSON built-in methods.
30
+ *
31
+ * These references are captured at module initialization time to protect against
32
+ * prototype pollution attacks. Import only what you need for tree-shaking.
33
+ *
34
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/json
35
+ */
36
+ // Capture references at module initialization time
37
+ const _JSON = globalThis.JSON;
38
+ /**
39
+ * (Safe copy) Converts a JavaScript Object Notation (JSON) string into an object.
40
+ */
41
+ const parse = _JSON.parse;
42
+ /**
43
+ * (Safe copy) Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
44
+ */
45
+ const stringify = _JSON.stringify;
46
+
47
+ /**
48
+ * Safe copies of Object built-in methods.
49
+ *
50
+ * These references are captured at module initialization time to protect against
51
+ * prototype pollution attacks. Import only what you need for tree-shaking.
52
+ *
53
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
54
+ */
55
+ // Capture references at module initialization time
56
+ const _Object = globalThis.Object;
57
+ /**
58
+ * (Safe copy) Prevents modification of existing property attributes and values,
59
+ * and prevents the addition of new properties.
60
+ */
61
+ const freeze = _Object.freeze;
62
+ /**
63
+ * (Safe copy) Returns the names of the enumerable string properties and methods of an object.
64
+ */
65
+ const keys = _Object.keys;
66
+ /**
67
+ * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
68
+ */
69
+ const entries = _Object.entries;
70
+ /**
71
+ * (Safe copy) Returns an array of values of the enumerable own properties of an object.
72
+ */
73
+ const values = _Object.values;
74
+ /**
75
+ * (Safe copy) Adds one or more properties to an object, and/or modifies attributes of existing properties.
76
+ */
77
+ const defineProperties = _Object.defineProperties;
78
+
79
+ /**
80
+ * Safe copies of Array built-in static methods.
81
+ *
82
+ * These references are captured at module initialization time to protect against
83
+ * prototype pollution attacks. Import only what you need for tree-shaking.
84
+ *
85
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/array
86
+ */
87
+ // Capture references at module initialization time
88
+ const _Array = globalThis.Array;
89
+ /**
90
+ * (Safe copy) Determines whether the passed value is an Array.
91
+ */
92
+ const isArray = _Array.isArray;
93
+
94
+ /**
95
+ * Safe copies of Console built-in methods.
96
+ *
97
+ * These references are captured at module initialization time to protect against
98
+ * prototype pollution attacks. Import only what you need for tree-shaking.
99
+ *
100
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/console
101
+ */
102
+ // Capture references at module initialization time
103
+ const _console = globalThis.console;
104
+ /**
105
+ * (Safe copy) Outputs a message to the console.
106
+ */
107
+ const log = _console.log.bind(_console);
108
+ /**
109
+ * (Safe copy) Outputs a warning message to the console.
110
+ */
111
+ const warn = _console.warn.bind(_console);
112
+ /**
113
+ * (Safe copy) Outputs an error message to the console.
114
+ */
115
+ const error = _console.error.bind(_console);
116
+ /**
117
+ * (Safe copy) Outputs an informational message to the console.
118
+ */
119
+ const info = _console.info.bind(_console);
120
+ /**
121
+ * (Safe copy) Outputs a debug message to the console.
122
+ */
123
+ const debug = _console.debug.bind(_console);
124
+ /**
125
+ * (Safe copy) Outputs a stack trace to the console.
126
+ */
127
+ _console.trace.bind(_console);
128
+ /**
129
+ * (Safe copy) Displays an interactive listing of the properties of a specified object.
130
+ */
131
+ _console.dir.bind(_console);
132
+ /**
133
+ * (Safe copy) Displays tabular data as a table.
134
+ */
135
+ _console.table.bind(_console);
136
+ /**
137
+ * (Safe copy) Writes an error message to the console if the assertion is false.
138
+ */
139
+ _console.assert.bind(_console);
140
+ /**
141
+ * (Safe copy) Clears the console.
142
+ */
143
+ _console.clear.bind(_console);
144
+ /**
145
+ * (Safe copy) Logs the number of times that this particular call to count() has been called.
146
+ */
147
+ _console.count.bind(_console);
148
+ /**
149
+ * (Safe copy) Resets the counter used with console.count().
150
+ */
151
+ _console.countReset.bind(_console);
152
+ /**
153
+ * (Safe copy) Creates a new inline group in the console.
154
+ */
155
+ _console.group.bind(_console);
156
+ /**
157
+ * (Safe copy) Creates a new inline group in the console that is initially collapsed.
158
+ */
159
+ _console.groupCollapsed.bind(_console);
160
+ /**
161
+ * (Safe copy) Exits the current inline group.
162
+ */
163
+ _console.groupEnd.bind(_console);
164
+ /**
165
+ * (Safe copy) Starts a timer with a name specified as an input parameter.
166
+ */
167
+ _console.time.bind(_console);
168
+ /**
169
+ * (Safe copy) Stops a timer that was previously started.
170
+ */
171
+ _console.timeEnd.bind(_console);
172
+ /**
173
+ * (Safe copy) Logs the current value of a timer that was previously started.
174
+ */
175
+ _console.timeLog.bind(_console);
176
+
177
+ /**
178
+ * Safe copies of Set built-in via factory function.
179
+ *
180
+ * Since constructors cannot be safely captured via Object.assign, this module
181
+ * provides a factory function that uses Reflect.construct internally.
182
+ *
183
+ * These references are captured at module initialization time to protect against
184
+ * prototype pollution attacks. Import only what you need for tree-shaking.
185
+ *
186
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/set
187
+ */
188
+ // Capture references at module initialization time
189
+ const _Set = globalThis.Set;
190
+ const _Reflect$1 = globalThis.Reflect;
191
+ /**
192
+ * (Safe copy) Creates a new Set using the captured Set constructor.
193
+ * Use this instead of `new Set()`.
194
+ *
195
+ * @param iterable - Optional iterable of values.
196
+ * @returns A new Set instance.
197
+ */
198
+ const createSet = (iterable) => _Reflect$1.construct(_Set, iterable ? [iterable] : []);
199
+
200
+ const registeredClasses = [];
201
+
202
+ /**
203
+ * Returns the data type of the target.
204
+ * Uses native `typeof` operator, however, makes distinction between `null`, `array`, and `object`.
205
+ * Also, when classes are registered via `registerClass`, it checks if objects are instance of any known registered class.
206
+ *
207
+ * @param target - The target to get the data type of.
208
+ * @returns The data type of the target.
209
+ */
210
+ const getType = (target) => {
211
+ if (target === null)
212
+ return 'null';
213
+ const nativeDataType = typeof target;
214
+ if (nativeDataType === 'object') {
215
+ if (isArray(target))
216
+ return 'array';
217
+ for (const registeredClass of registeredClasses) {
218
+ if (target instanceof registeredClass)
219
+ return registeredClass.name;
220
+ }
221
+ }
222
+ return nativeDataType;
223
+ };
224
+
225
+ /**
226
+ * Safe copies of Map built-in via factory function.
227
+ *
228
+ * Since constructors cannot be safely captured via Object.assign, this module
229
+ * provides a factory function that uses Reflect.construct internally.
230
+ *
231
+ * These references are captured at module initialization time to protect against
232
+ * prototype pollution attacks. Import only what you need for tree-shaking.
233
+ *
234
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
235
+ */
236
+ // Capture references at module initialization time
237
+ const _Map = globalThis.Map;
238
+ const _Reflect = globalThis.Reflect;
239
+ /**
240
+ * (Safe copy) Creates a new Map using the captured Map constructor.
241
+ * Use this instead of `new Map()`.
242
+ *
243
+ * @param iterable - Optional iterable of key-value pairs.
244
+ * @returns A new Map instance.
245
+ */
246
+ const createMap = (iterable) => _Reflect.construct(_Map, iterable ? [iterable] : []);
247
+
248
+ /* eslint-disable @typescript-eslint/no-explicit-any */
249
+ /**
250
+ * Creates a wrapper function that only executes the wrapped function if the condition function returns true.
251
+ *
252
+ * @param func - The function to be conditionally executed.
253
+ * @param conditionFunc - A function that returns a boolean, determining if `func` should be executed.
254
+ * @returns A wrapped version of `func` that executes conditionally.
255
+ */
256
+ function createConditionalExecutionFunction(func, conditionFunc) {
257
+ return function (...args) {
258
+ if (conditionFunc()) {
259
+ return func(...args);
260
+ }
261
+ };
262
+ }
263
+
264
+ /* eslint-disable @typescript-eslint/no-explicit-any */
265
+ /**
266
+ * Creates a wrapper function that silently ignores any errors thrown by the wrapped void function.
267
+ * This function is specifically for wrapping functions that do not return a value (void functions).
268
+ * Exceptions are swallowed without any logging or handling.
269
+ *
270
+ * @param func - The void function to be wrapped.
271
+ * @returns A wrapped version of the input function that ignores errors.
272
+ */
273
+ function createErrorIgnoringFunction(func) {
274
+ return function (...args) {
275
+ try {
276
+ func(...args);
277
+ }
278
+ catch {
279
+ // Deliberately swallowing/ignoring the exception
280
+ }
281
+ };
282
+ }
283
+
284
+ /* eslint-disable @typescript-eslint/no-unused-vars */
285
+ /**
286
+ * A no-operation function (noop) that does nothing regardless of the arguments passed.
287
+ * It is designed to be as permissive as possible in its typing without using the `Function` keyword.
288
+ *
289
+ * @param args - Any arguments passed to the function (ignored)
290
+ */
291
+ const noop = (...args) => {
292
+ // Intentionally does nothing
293
+ };
294
+
295
+ const logLevels = ['none', 'error', 'warn', 'log', 'info', 'debug'];
296
+ const priority = {
297
+ error: 4,
298
+ warn: 3,
299
+ log: 2,
300
+ info: 1,
301
+ debug: 0,
302
+ };
303
+ /**
304
+ * Validates whether a given string is a valid log level.
305
+ *
306
+ * @param level - The log level to validate
307
+ * @returns True if the level is valid, false otherwise
308
+ */
309
+ function isValidLogLevel(level) {
310
+ return logLevels.includes(level);
311
+ }
312
+ /**
313
+ * Creates a log level configuration manager for controlling logging behavior.
314
+ * Provides methods to get, set, and evaluate log levels based on priority.
315
+ *
316
+ * @param level - The initial log level (defaults to 'error')
317
+ * @returns A configuration object with log level management methods
318
+ * @throws {Error} When the provided level is not a valid log level
319
+ */
320
+ function createLogLevelConfig(level = 'error') {
321
+ if (!isValidLogLevel(level)) {
322
+ throw createError('Cannot create log level configuration with a valid default log level');
323
+ }
324
+ const state = { level };
325
+ const getLogLevel = () => state.level;
326
+ const setLogLevel = (level) => {
327
+ if (!isValidLogLevel(level)) {
328
+ throw createError(`Cannot set value '${level}' level. Expected levels are ${logLevels}.`);
329
+ }
330
+ state.level = level;
331
+ };
332
+ const shouldLog = (level) => {
333
+ if (state.level === 'none' || level === 'none' || !isValidLogLevel(level)) {
334
+ return false;
335
+ }
336
+ return priority[level] >= priority[state.level];
337
+ };
338
+ return freeze({
339
+ getLogLevel,
340
+ setLogLevel,
341
+ shouldLog,
342
+ });
343
+ }
344
+
345
+ /**
346
+ * Creates a logger instance with configurable log level filtering.
347
+ * Each log function is wrapped to respect the current log level setting.
348
+ *
349
+ * @param error - Function to handle error-level logs (required)
350
+ * @param warn - Function to handle warning-level logs (optional, defaults to noop)
351
+ * @param log - Function to handle standard logs (optional, defaults to noop)
352
+ * @param info - Function to handle info-level logs (optional, defaults to noop)
353
+ * @param debug - Function to handle debug-level logs (optional, defaults to noop)
354
+ * @returns A frozen logger object with log methods and level control
355
+ * @throws {ErrorLevelFn} When any provided log function is invalid
356
+ */
357
+ function createLogger(error, warn = noop, log = noop, info = noop, debug = noop) {
358
+ if (notValidLogFn(error)) {
359
+ throw createError(notFnMsg('error'));
360
+ }
361
+ if (notValidLogFn(warn)) {
362
+ throw createError(notFnMsg('warn'));
363
+ }
364
+ if (notValidLogFn(log)) {
365
+ throw createError(notFnMsg('log'));
366
+ }
367
+ if (notValidLogFn(info)) {
368
+ throw createError(notFnMsg('info'));
369
+ }
370
+ if (notValidLogFn(debug)) {
371
+ throw createError(notFnMsg('debug'));
372
+ }
373
+ const { setLogLevel, getLogLevel, shouldLog } = createLogLevelConfig();
374
+ const wrapLogFn = (fn, level) => {
375
+ if (fn === noop)
376
+ return fn;
377
+ const condition = () => shouldLog(level);
378
+ return createConditionalExecutionFunction(createErrorIgnoringFunction(fn), condition);
379
+ };
380
+ return freeze({
381
+ error: wrapLogFn(error, 'error'),
382
+ warn: wrapLogFn(warn, 'warn'),
383
+ log: wrapLogFn(log, 'log'),
384
+ info: wrapLogFn(info, 'info'),
385
+ debug: wrapLogFn(debug, 'debug'),
386
+ setLogLevel,
387
+ getLogLevel,
388
+ });
389
+ }
390
+ /**
391
+ * Validates whether a given value is a valid log function.
392
+ *
393
+ * @param fn - The value to validate
394
+ * @returns True if the value is not a function (invalid), false if it is valid
395
+ */
396
+ function notValidLogFn(fn) {
397
+ return getType(fn) !== 'function' && fn !== noop;
398
+ }
399
+ /**
400
+ * Generates an error message for invalid log function parameters.
401
+ *
402
+ * @param label - The name of the log function that failed validation
403
+ * @returns A formatted error message string
404
+ */
405
+ function notFnMsg(label) {
406
+ return `Cannot create a logger when ${label} is not a function`;
407
+ }
408
+
409
+ createLogger(error, warn, log, info, debug);
410
+
411
+ /**
412
+ * Global log level registry.
413
+ * Tracks all created scoped loggers to allow global log level changes.
414
+ */
415
+ const loggerRegistry = createSet();
416
+ /** Redacted placeholder for sensitive values */
417
+ const REDACTED = '[REDACTED]';
418
+ /**
419
+ * Patterns that indicate a sensitive key name.
420
+ * Keys containing these patterns will have their values sanitized.
421
+ */
422
+ const SENSITIVE_KEY_PATTERNS = [
423
+ /token/i,
424
+ /key/i,
425
+ /password/i,
426
+ /secret/i,
427
+ /credential/i,
428
+ /auth/i,
429
+ /bearer/i,
430
+ /api[_-]?key/i,
431
+ /private/i,
432
+ /passphrase/i,
433
+ ];
434
+ /**
435
+ * Checks if a key name indicates sensitive data.
436
+ *
437
+ * @param key - Key name to check
438
+ * @returns True if the key indicates sensitive data
439
+ */
440
+ function isSensitiveKey(key) {
441
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
442
+ }
443
+ /**
444
+ * Sanitizes an object by replacing sensitive values with REDACTED.
445
+ * This function recursively processes nested objects and arrays.
446
+ *
447
+ * @param obj - Object to sanitize
448
+ * @returns New object with sensitive values redacted
449
+ */
450
+ function sanitize(obj) {
451
+ if (obj === null || obj === undefined) {
452
+ return obj;
453
+ }
454
+ if (isArray(obj)) {
455
+ return obj.map((item) => sanitize(item));
456
+ }
457
+ if (typeof obj === 'object') {
458
+ const result = {};
459
+ for (const [key, value] of entries(obj)) {
460
+ if (isSensitiveKey(key)) {
461
+ result[key] = REDACTED;
462
+ }
463
+ else if (typeof value === 'object' && value !== null) {
464
+ result[key] = sanitize(value);
465
+ }
466
+ else {
467
+ result[key] = value;
468
+ }
469
+ }
470
+ return result;
471
+ }
472
+ return obj;
473
+ }
474
+ /**
475
+ * Formats a log message with optional metadata.
476
+ *
477
+ * @param namespace - Logger namespace prefix
478
+ * @param message - Log message
479
+ * @param meta - Optional metadata object
480
+ * @returns Formatted log string
481
+ */
482
+ function formatMessage(namespace, message, meta) {
483
+ const prefix = `[${namespace}]`;
484
+ if (meta && keys(meta).length > 0) {
485
+ const sanitizedMeta = sanitize(meta);
486
+ return `${prefix} ${message} ${stringify(sanitizedMeta)}`;
487
+ }
488
+ return `${prefix} ${message}`;
489
+ }
490
+ /**
491
+ * Creates a scoped logger with namespace prefix and optional secret sanitization.
492
+ * All log messages will be prefixed with [namespace] and sensitive metadata
493
+ * values will be automatically redacted.
494
+ *
495
+ * @param namespace - Logger namespace (e.g., 'project-scope', 'analyze')
496
+ * @param options - Logger configuration options
497
+ * @returns A configured scoped logger instance
498
+ *
499
+ * @example
500
+ * ```typescript
501
+ * const logger = createScopedLogger('project-scope')
502
+ * logger.setLogLevel('debug')
503
+ *
504
+ * // Basic logging
505
+ * logger.info('Starting analysis', { path: './project' })
506
+ *
507
+ * // Sensitive data is automatically redacted
508
+ * logger.debug('Config loaded', { apiKey: 'secret123' })
509
+ * // Output: [project-scope] Config loaded {"apiKey":"[REDACTED]"}
510
+ * ```
511
+ */
512
+ function createScopedLogger(namespace, options = {}) {
513
+ const { level = 'error', sanitizeSecrets = true } = options;
514
+ // Create wrapper functions that add namespace prefix and sanitization
515
+ const createLogFn = (baseFn) => (message, meta) => {
516
+ const processedMeta = sanitizeSecrets && meta ? sanitize(meta) : meta;
517
+ baseFn(formatMessage(namespace, message, processedMeta));
518
+ };
519
+ // Create base logger with wrapped functions
520
+ const baseLogger = createLogger(createLogFn(error), createLogFn(warn), createLogFn(log), createLogFn(info), createLogFn(debug));
521
+ // Set initial log level (use global override if set)
522
+ baseLogger.setLogLevel(level);
523
+ const scopedLogger = freeze({
524
+ error: (message, meta) => baseLogger.error(message, meta),
525
+ warn: (message, meta) => baseLogger.warn(message, meta),
526
+ log: (message, meta) => baseLogger.log(message, meta),
527
+ info: (message, meta) => baseLogger.info(message, meta),
528
+ debug: (message, meta) => baseLogger.debug(message, meta),
529
+ setLogLevel: baseLogger.setLogLevel,
530
+ getLogLevel: baseLogger.getLogLevel,
531
+ });
532
+ // Register logger for global level management
533
+ loggerRegistry.add(scopedLogger);
534
+ return scopedLogger;
535
+ }
536
+ /**
537
+ * Default logger instance for the project-scope library.
538
+ * Use this for general logging within the library.
539
+ *
540
+ * @example
541
+ * ```typescript
542
+ * import { logger } from '@hyperfrontend/project-scope/core'
543
+ *
544
+ * logger.setLogLevel('debug')
545
+ * logger.debug('Analyzing project', { path: './src' })
546
+ * ```
547
+ */
548
+ createScopedLogger('project-scope');
549
+
550
+ const fsLogger = createScopedLogger('project-scope:fs');
551
+ /**
552
+ * Create a file system error with code and context.
553
+ *
554
+ * @param message - The error message describing what went wrong
555
+ * @param code - The category code for this type of filesystem failure
556
+ * @param context - Additional context including path, operation, and cause
557
+ * @returns A configured Error object with code and context properties
558
+ */
559
+ function createFileSystemError(message, code, context) {
560
+ const error = createError(message);
561
+ defineProperties(error, {
562
+ code: { value: code, enumerable: true },
563
+ context: { value: context, enumerable: true },
564
+ });
565
+ return error;
566
+ }
567
+ /**
568
+ * Read file contents as string.
569
+ *
570
+ * @param filePath - Path to file
571
+ * @param encoding - File encoding (default: utf-8)
572
+ * @returns File contents as string
573
+ * @throws {Error} If file doesn't exist or can't be read
574
+ *
575
+ * @example
576
+ * ```typescript
577
+ * import { readFileContent } from '@hyperfrontend/project-scope'
578
+ *
579
+ * const content = readFileContent('./package.json')
580
+ * console.log(content) // JSON string
581
+ * ```
582
+ */
583
+ function readFileContent(filePath, encoding = 'utf-8') {
584
+ if (!existsSync(filePath)) {
585
+ fsLogger.debug('File not found', { path: filePath });
586
+ throw createFileSystemError(`File not found: ${filePath}`, 'FS_NOT_FOUND', { path: filePath, operation: 'read' });
587
+ }
588
+ try {
589
+ return readFileSync(filePath, { encoding });
590
+ }
591
+ catch (error) {
592
+ fsLogger.warn('Failed to read file', { path: filePath });
593
+ throw createFileSystemError(`Failed to read file: ${filePath}`, 'FS_READ_ERROR', { path: filePath, operation: 'read', cause: error });
594
+ }
595
+ }
596
+ /**
597
+ * Read file if exists, return null otherwise.
598
+ *
599
+ * @param filePath - Path to file
600
+ * @param encoding - File encoding (default: utf-8)
601
+ * @returns File contents or null if file doesn't exist
602
+ */
603
+ function readFileIfExists(filePath, encoding = 'utf-8') {
604
+ if (!existsSync(filePath)) {
605
+ return null;
606
+ }
607
+ try {
608
+ return readFileSync(filePath, { encoding });
609
+ }
610
+ catch {
611
+ return null;
612
+ }
613
+ }
614
+
615
+ createScopedLogger('project-scope:fs:write');
616
+
617
+ /**
618
+ * Get file stats with error handling.
619
+ *
620
+ * @param filePath - Path to file
621
+ * @param followSymlinks - Whether to follow symlinks (default: true)
622
+ * @returns File stats or null if path doesn't exist
623
+ */
624
+ function getFileStat(filePath, followSymlinks = true) {
625
+ if (!existsSync(filePath)) {
626
+ return null;
627
+ }
628
+ try {
629
+ const stat = followSymlinks ? statSync(filePath) : lstatSync(filePath);
630
+ return {
631
+ isFile: stat.isFile(),
632
+ isDirectory: stat.isDirectory(),
633
+ isSymlink: stat.isSymbolicLink(),
634
+ size: stat.size,
635
+ created: stat.birthtime,
636
+ modified: stat.mtime,
637
+ accessed: stat.atime,
638
+ mode: stat.mode,
639
+ };
640
+ }
641
+ catch {
642
+ return null;
643
+ }
644
+ }
645
+ /**
646
+ * Check if path is a directory.
647
+ *
648
+ * @param dirPath - Path to check
649
+ * @returns True if path is a directory
650
+ */
651
+ function isDirectory(dirPath) {
652
+ const stats = getFileStat(dirPath);
653
+ return stats?.isDirectory ?? false;
654
+ }
655
+ /**
656
+ * Check if path exists.
657
+ *
658
+ * @param filePath - Path to check
659
+ * @returns True if path exists
660
+ */
661
+ function exists(filePath) {
662
+ return existsSync(filePath);
663
+ }
664
+
665
+ const fsDirLogger = createScopedLogger('project-scope:fs:dir');
666
+ /**
667
+ * List immediate contents of a directory.
668
+ *
669
+ * @param dirPath - Absolute or relative path to the directory
670
+ * @returns Array of entries with metadata for each file/directory
671
+ * @throws {Error} If directory doesn't exist or isn't a directory
672
+ *
673
+ * @example
674
+ * ```typescript
675
+ * import { readDirectory } from '@hyperfrontend/project-scope'
676
+ *
677
+ * const entries = readDirectory('./src')
678
+ * for (const entry of entries) {
679
+ * console.log(entry.name, entry.isFile ? 'file' : 'directory')
680
+ * }
681
+ * ```
682
+ */
683
+ function readDirectory(dirPath) {
684
+ fsDirLogger.debug('Reading directory', { path: dirPath });
685
+ if (!existsSync(dirPath)) {
686
+ fsDirLogger.debug('Directory not found', { path: dirPath });
687
+ throw createFileSystemError(`Directory not found: ${dirPath}`, 'FS_NOT_FOUND', { path: dirPath, operation: 'readdir' });
688
+ }
689
+ if (!isDirectory(dirPath)) {
690
+ fsDirLogger.debug('Path is not a directory', { path: dirPath });
691
+ throw createFileSystemError(`Not a directory: ${dirPath}`, 'FS_NOT_A_DIRECTORY', { path: dirPath, operation: 'readdir' });
692
+ }
693
+ try {
694
+ const entries = readdirSync(dirPath, { withFileTypes: true });
695
+ fsDirLogger.debug('Directory read complete', { path: dirPath, entryCount: entries.length });
696
+ return entries.map((entry) => ({
697
+ name: entry.name,
698
+ path: join$1(dirPath, entry.name),
699
+ isFile: entry.isFile(),
700
+ isDirectory: entry.isDirectory(),
701
+ isSymlink: entry.isSymbolicLink(),
702
+ }));
703
+ }
704
+ catch (error) {
705
+ fsDirLogger.warn('Failed to read directory', { path: dirPath, error: error instanceof Error ? error.message : String(error) });
706
+ throw createFileSystemError(`Failed to read directory: ${dirPath}`, 'FS_READ_ERROR', {
707
+ path: dirPath,
708
+ operation: 'readdir',
709
+ cause: error,
710
+ });
711
+ }
712
+ }
713
+
714
+ /**
715
+ * Join path segments.
716
+ * Uses platform-specific separators (e.g., / or \).
717
+ *
718
+ * @param paths - Path segments to join
719
+ * @returns Joined path
720
+ */
721
+ function join(...paths) {
722
+ return join$1(...paths);
723
+ }
724
+
725
+ const fsTraversalLogger = createScopedLogger('project-scope:fs:traversal');
726
+ /**
727
+ * Generic upward directory traversal.
728
+ * Name avoids similarity to fs.readdir/fs.readdirSync.
729
+ *
730
+ * @param startPath - Starting directory
731
+ * @param predicate - Function to test each directory
732
+ * @returns First matching directory or null
733
+ */
734
+ function traverseUpward(startPath, predicate) {
735
+ fsTraversalLogger.debug('Starting upward traversal', { startPath });
736
+ let currentPath = resolve(startPath);
737
+ const rootPath = parse$1(currentPath).root;
738
+ while (currentPath !== rootPath) {
739
+ if (predicate(currentPath)) {
740
+ fsTraversalLogger.debug('Upward traversal found match', { startPath, foundPath: currentPath });
741
+ return currentPath;
742
+ }
743
+ currentPath = dirname(currentPath);
744
+ }
745
+ // Check root directory
746
+ if (predicate(rootPath)) {
747
+ fsTraversalLogger.debug('Upward traversal found match at root', { startPath, foundPath: rootPath });
748
+ return rootPath;
749
+ }
750
+ fsTraversalLogger.debug('Upward traversal found no match', { startPath });
751
+ return null;
752
+ }
753
+ /**
754
+ * Find directory containing any of the specified marker files.
755
+ *
756
+ * @param startPath - Starting directory
757
+ * @param markers - Array of marker file names to search for
758
+ * @returns First directory containing any marker, or null
759
+ */
760
+ function locateByMarkers(startPath, markers) {
761
+ fsTraversalLogger.debug('Locating by markers', { startPath, markers });
762
+ const result = traverseUpward(startPath, (dir) => markers.some((marker) => exists(join(dir, marker))));
763
+ if (result) {
764
+ fsTraversalLogger.debug('Found directory with marker', { startPath, foundPath: result });
765
+ }
766
+ return result;
767
+ }
768
+ /**
769
+ * Find directory where predicate returns true, starting from given path.
770
+ *
771
+ * @param startPath - Starting directory
772
+ * @param test - Function to test if directory matches criteria
773
+ * @returns Matching directory path or null
774
+ */
775
+ function findUpwardWhere(startPath, test) {
776
+ fsTraversalLogger.debug('Finding upward where condition met', { startPath });
777
+ return traverseUpward(startPath, test);
778
+ }
779
+
780
+ /**
781
+ * Pattern matching utilities with ReDoS protection.
782
+ * Uses character-by-character matching instead of regex where possible.
783
+ */
784
+ /**
785
+ * Match path against glob pattern using safe character iteration.
786
+ * Avoids regex to prevent ReDoS attacks.
787
+ *
788
+ * Supported patterns:
789
+ * - * matches any characters except /
790
+ * - ** matches any characters including /
791
+ * - ? matches exactly one character except /
792
+ * - {a,b,c} matches any of the alternatives
793
+ *
794
+ * @param path - The filesystem path to test against the pattern
795
+ * @param pattern - The glob pattern to match against
796
+ * @returns True if path matches pattern
797
+ *
798
+ * @example
799
+ * ```typescript
800
+ * import { matchGlobPattern } from '@hyperfrontend/project-scope'
801
+ *
802
+ * matchGlobPattern('src/utils/helper.ts', '\*\*\/*.ts') // true
803
+ * matchGlobPattern('test.spec.ts', '\*.spec.ts') // true
804
+ * matchGlobPattern('config.json', '\*.{json,yaml}') // true
805
+ * matchGlobPattern('src/index.ts', 'src/\*.ts') // true
806
+ * ```
807
+ */
808
+ function matchGlobPattern(path, pattern) {
809
+ return matchSegments(path.split('/'), pattern.split('/'), 0, 0);
810
+ }
811
+ /**
812
+ * Internal recursive function to match path segments against pattern segments.
813
+ *
814
+ * @param pathParts - Array of path segments split by '/'
815
+ * @param patternParts - Array of pattern segments split by '/'
816
+ * @param pathIdx - Current index in pathParts being examined
817
+ * @param patternIdx - Current index in patternParts being examined
818
+ * @returns True if remaining segments match
819
+ */
820
+ function matchSegments(pathParts, patternParts, pathIdx, patternIdx) {
821
+ // Base cases
822
+ if (pathIdx === pathParts.length && patternIdx === patternParts.length) {
823
+ return true; // Both exhausted = match
824
+ }
825
+ if (patternIdx >= patternParts.length) {
826
+ return false; // Pattern exhausted but path remains
827
+ }
828
+ const patternPart = patternParts[patternIdx];
829
+ // Handle ** (globstar) - matches zero or more directories
830
+ if (patternPart === '**') {
831
+ // Try matching rest of pattern against current position and all future positions
832
+ for (let i = pathIdx; i <= pathParts.length; i++) {
833
+ if (matchSegments(pathParts, patternParts, i, patternIdx + 1)) {
834
+ return true;
835
+ }
836
+ }
837
+ return false;
838
+ }
839
+ if (pathIdx >= pathParts.length) {
840
+ return false; // Path exhausted but pattern remains (and it's not **)
841
+ }
842
+ const pathPart = pathParts[pathIdx];
843
+ // Match current segment
844
+ if (matchSegment(pathPart, patternPart)) {
845
+ return matchSegments(pathParts, patternParts, pathIdx + 1, patternIdx + 1);
846
+ }
847
+ return false;
848
+ }
849
+ /**
850
+ * Match a single path segment against a pattern segment.
851
+ * Handles *, ?, and {a,b,c} patterns.
852
+ *
853
+ * @param text - The path segment text to match
854
+ * @param pattern - The pattern segment to match against
855
+ * @returns True if the text matches the pattern
856
+ */
857
+ function matchSegment(text, pattern) {
858
+ let textIdx = 0;
859
+ let patternIdx = 0;
860
+ while (patternIdx < pattern.length) {
861
+ const char = pattern[patternIdx];
862
+ if (char === '*') {
863
+ // * matches zero or more characters
864
+ patternIdx++;
865
+ if (patternIdx === pattern.length) {
866
+ return true; // * at end matches rest of string
867
+ }
868
+ // Try matching rest of pattern at each position in text
869
+ for (let i = textIdx; i <= text.length; i++) {
870
+ if (matchSegmentFrom(text, i, pattern, patternIdx)) {
871
+ return true;
872
+ }
873
+ }
874
+ return false;
875
+ }
876
+ else if (char === '?') {
877
+ // ? matches exactly one character
878
+ if (textIdx >= text.length) {
879
+ return false;
880
+ }
881
+ textIdx++;
882
+ patternIdx++;
883
+ }
884
+ else if (char === '{') {
885
+ // {a,b,c} matches any alternative
886
+ const closeIdx = findClosingBrace(pattern, patternIdx);
887
+ if (closeIdx === -1) {
888
+ // Unmatched brace, treat as literal
889
+ if (textIdx >= text.length || text[textIdx] !== char) {
890
+ return false;
891
+ }
892
+ textIdx++;
893
+ patternIdx++;
894
+ }
895
+ else {
896
+ const alternatives = extractAlternatives(pattern.slice(patternIdx + 1, closeIdx));
897
+ for (const alt of alternatives) {
898
+ if (matchSegmentFrom(text, textIdx, text.slice(0, textIdx) + alt + pattern.slice(closeIdx + 1), textIdx)) {
899
+ return true;
900
+ }
901
+ }
902
+ return false;
903
+ }
904
+ }
905
+ else {
906
+ // Literal character
907
+ if (textIdx >= text.length || text[textIdx] !== char) {
908
+ return false;
909
+ }
910
+ textIdx++;
911
+ patternIdx++;
912
+ }
913
+ }
914
+ return textIdx === text.length;
915
+ }
916
+ /**
917
+ * Helper to match from a specific position.
918
+ *
919
+ * @param text - The full text being matched
920
+ * @param textIdx - The starting index in text to match from
921
+ * @param pattern - The full pattern being matched
922
+ * @param patternIdx - The starting index in pattern to match from
923
+ * @returns True if the text matches the pattern from the given positions
924
+ */
925
+ function matchSegmentFrom(text, textIdx, pattern, patternIdx) {
926
+ const remainingText = text.slice(textIdx);
927
+ const remainingPattern = pattern.slice(patternIdx);
928
+ return matchSegment(remainingText, remainingPattern);
929
+ }
930
+ /**
931
+ * Find closing brace for {a,b,c} pattern.
932
+ *
933
+ * @param pattern - The pattern string to search within
934
+ * @param startIdx - The index of the opening brace
935
+ * @returns The index of the matching closing brace, or -1 if not found
936
+ */
937
+ function findClosingBrace(pattern, startIdx) {
938
+ let depth = 0;
939
+ for (let i = startIdx; i < pattern.length; i++) {
940
+ if (pattern[i] === '{') {
941
+ depth++;
942
+ }
943
+ else if (pattern[i] === '}') {
944
+ depth--;
945
+ if (depth === 0) {
946
+ return i;
947
+ }
948
+ }
949
+ }
950
+ return -1;
951
+ }
952
+ /**
953
+ * Extract alternatives from {a,b,c} pattern content.
954
+ *
955
+ * @param content - The content between braces (without the braces themselves)
956
+ * @returns Array of alternative strings split by commas at depth 0
957
+ */
958
+ function extractAlternatives(content) {
959
+ const alternatives = [];
960
+ let current = '';
961
+ let depth = 0;
962
+ for (let i = 0; i < content.length; i++) {
963
+ const char = content[i];
964
+ if (char === '{') {
965
+ depth++;
966
+ current += char;
967
+ }
968
+ else if (char === '}') {
969
+ depth--;
970
+ current += char;
971
+ }
972
+ else if (char === ',' && depth === 0) {
973
+ alternatives.push(current);
974
+ current = '';
975
+ }
976
+ else {
977
+ current += char;
978
+ }
979
+ }
980
+ if (current) {
981
+ alternatives.push(current);
982
+ }
983
+ return alternatives;
984
+ }
985
+
986
+ const walkLogger = createScopedLogger('project-scope:project:walk');
987
+ /**
988
+ * Reads .gitignore file from the given directory and extracts
989
+ * non-comment patterns for use in file traversal filtering.
990
+ *
991
+ * @param startPath - Directory containing the .gitignore file
992
+ * @returns Array of gitignore patterns
993
+ */
994
+ function loadGitignorePatterns(startPath) {
995
+ const patterns = [];
996
+ const gitignorePath = join$1(startPath, '.gitignore');
997
+ const content = readFileIfExists(gitignorePath);
998
+ if (content) {
999
+ const lines = content.split('\n');
1000
+ for (const line of lines) {
1001
+ const trimmed = line.trim();
1002
+ if (trimmed && !trimmed.startsWith('#')) {
1003
+ patterns.push(trimmed);
1004
+ }
1005
+ }
1006
+ }
1007
+ return patterns;
1008
+ }
1009
+ /**
1010
+ * Evaluates whether a relative path should be ignored based on
1011
+ * a list of gitignore-style patterns.
1012
+ *
1013
+ * @param relativePath - Path relative to the root directory
1014
+ * @param patterns - Array of gitignore-style patterns to test
1015
+ * @returns True if the path matches any ignore pattern
1016
+ */
1017
+ function matchesIgnorePattern(relativePath, patterns) {
1018
+ for (const pattern of patterns) {
1019
+ if (matchPattern(relativePath, pattern)) {
1020
+ return true;
1021
+ }
1022
+ }
1023
+ return false;
1024
+ }
1025
+ /**
1026
+ * Tests if the given path matches a gitignore-style pattern,
1027
+ * supporting negation patterns with '!' prefix.
1028
+ * Uses safe character-by-character matching to prevent ReDoS attacks.
1029
+ *
1030
+ * @param path - File or directory path to test
1031
+ * @param pattern - Gitignore-style pattern (may include wildcards)
1032
+ * @returns True if the path matches the pattern (or doesn't match if negated)
1033
+ */
1034
+ function matchPattern(path, pattern) {
1035
+ const normalizedPattern = pattern.startsWith('/') ? pattern.slice(1) : pattern;
1036
+ const isNegation = normalizedPattern.startsWith('!');
1037
+ const actualPattern = isNegation ? normalizedPattern.slice(1) : normalizedPattern;
1038
+ const matchesFullPath = matchGlobPattern(path, actualPattern) || matchGlobPattern(path, `**/${actualPattern}`);
1039
+ const matchesSegment = path.split('/').some((segment) => matchGlobPattern(segment, actualPattern));
1040
+ const matches = matchesFullPath || matchesSegment;
1041
+ return isNegation ? !matches : matches;
1042
+ }
1043
+ /**
1044
+ * Traverses a directory tree synchronously, calling a visitor function
1045
+ * for each file and directory encountered. Supports depth limiting,
1046
+ * hidden file filtering, and gitignore pattern matching.
1047
+ *
1048
+ * @param startPath - Root directory to begin traversal
1049
+ * @param visitor - Callback function invoked for each file system entry
1050
+ * @param options - Configuration for traversal behavior
1051
+ */
1052
+ function walkDirectory(startPath, visitor, options) {
1053
+ walkLogger.debug('Starting directory walk', {
1054
+ startPath,
1055
+ maxDepth: options?.maxDepth ?? -1,
1056
+ includeHidden: options?.includeHidden ?? false,
1057
+ respectGitignore: options?.respectGitignore ?? true,
1058
+ ignorePatterns: options?.ignorePatterns?.length ?? 0,
1059
+ });
1060
+ const maxDepth = options?.maxDepth ?? -1;
1061
+ const includeHidden = options?.includeHidden ?? false;
1062
+ const ignorePatterns = options?.ignorePatterns ?? [];
1063
+ const respectGitignore = options?.respectGitignore ?? true;
1064
+ const gitignorePatterns = respectGitignore ? loadGitignorePatterns(startPath) : [];
1065
+ const allIgnorePatterns = [...ignorePatterns, ...gitignorePatterns];
1066
+ if (gitignorePatterns.length > 0) {
1067
+ walkLogger.debug('Loaded gitignore patterns', { count: gitignorePatterns.length });
1068
+ }
1069
+ /**
1070
+ * Recursively walks directory entries, applying visitor to each.
1071
+ *
1072
+ * @param currentPath - Absolute path to current directory
1073
+ * @param relativePath - Path relative to the starting directory
1074
+ * @param depth - Current recursion depth
1075
+ * @returns False to stop walking, true to continue
1076
+ */
1077
+ function walk(currentPath, relativePath, depth) {
1078
+ if (maxDepth !== -1 && depth > maxDepth) {
1079
+ return true;
1080
+ }
1081
+ let entries;
1082
+ try {
1083
+ entries = readDirectory(currentPath);
1084
+ }
1085
+ catch {
1086
+ return true;
1087
+ }
1088
+ for (const entry of entries) {
1089
+ if (!includeHidden && entry.name.startsWith('.')) {
1090
+ continue;
1091
+ }
1092
+ const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
1093
+ if (matchesIgnorePattern(entryRelativePath, allIgnorePatterns)) {
1094
+ continue;
1095
+ }
1096
+ const walkEntry = {
1097
+ name: entry.name,
1098
+ path: entry.path,
1099
+ relativePath: entryRelativePath,
1100
+ isFile: entry.isFile,
1101
+ isDirectory: entry.isDirectory,
1102
+ isSymlink: entry.isSymlink,
1103
+ depth,
1104
+ };
1105
+ const result = visitor(walkEntry);
1106
+ if (result === 'stop') {
1107
+ return false;
1108
+ }
1109
+ if (result === 'skip') {
1110
+ continue;
1111
+ }
1112
+ if (entry.isDirectory) {
1113
+ const shouldContinue = walk(entry.path, entryRelativePath, depth + 1);
1114
+ if (!shouldContinue) {
1115
+ return false;
1116
+ }
1117
+ }
1118
+ }
1119
+ return true;
1120
+ }
1121
+ walk(startPath, '', 0);
1122
+ walkLogger.debug('Directory walk complete', { startPath });
1123
+ }
1124
+ /**
1125
+ * Traverses a virtual file system tree, calling a visitor function
1126
+ * for each file and directory. Operates on in-memory tree structure
1127
+ * without disk I/O.
1128
+ *
1129
+ * @param tree - In-memory virtual file system representation
1130
+ * @param startPath - Root path within the tree to begin traversal
1131
+ * @param visitor - Callback function invoked for each tree entry
1132
+ * @param options - Configuration for traversal behavior
1133
+ */
1134
+ function walkTree(tree, startPath, visitor, options) {
1135
+ const maxDepth = options?.maxDepth ?? -1;
1136
+ const includeHidden = options?.includeHidden ?? false;
1137
+ /**
1138
+ * Recursively walks tree entries, applying visitor to each.
1139
+ *
1140
+ * @param currentPath - Current path within the tree
1141
+ * @param relativePath - Path relative to the starting path
1142
+ * @param depth - Current recursion depth
1143
+ * @returns False to stop walking, true to continue
1144
+ */
1145
+ function walk(currentPath, relativePath, depth) {
1146
+ if (maxDepth !== -1 && depth > maxDepth) {
1147
+ return true;
1148
+ }
1149
+ let children;
1150
+ try {
1151
+ children = tree.children(currentPath);
1152
+ }
1153
+ catch {
1154
+ return true;
1155
+ }
1156
+ for (const name of children) {
1157
+ if (!includeHidden && name.startsWith('.')) {
1158
+ continue;
1159
+ }
1160
+ const childPath = currentPath ? `${currentPath}/${name}` : name;
1161
+ const entryRelativePath = relativePath ? `${relativePath}/${name}` : name;
1162
+ const isFileEntry = tree.isFile(childPath);
1163
+ const walkEntry = {
1164
+ name,
1165
+ path: childPath,
1166
+ relativePath: entryRelativePath,
1167
+ isFile: isFileEntry,
1168
+ isDirectory: !isFileEntry,
1169
+ isSymlink: false,
1170
+ depth,
1171
+ };
1172
+ const result = visitor(walkEntry);
1173
+ if (result === 'stop') {
1174
+ return false;
1175
+ }
1176
+ if (result === 'skip') {
1177
+ continue;
1178
+ }
1179
+ if (!isFileEntry) {
1180
+ const shouldContinue = walk(childPath, entryRelativePath, depth + 1);
1181
+ if (!shouldContinue) {
1182
+ return false;
1183
+ }
1184
+ }
1185
+ }
1186
+ return true;
1187
+ }
1188
+ walk(startPath, '', 0);
1189
+ }
1190
+
1191
+ const searchLogger = createScopedLogger('project-scope:project:search');
1192
+ /**
1193
+ * Tests if a path matches at least one pattern from an array of globs,
1194
+ * enabling flexible multi-pattern file filtering.
1195
+ * Uses safe character-by-character matching to prevent ReDoS attacks.
1196
+ *
1197
+ * @param path - File path to test
1198
+ * @param patterns - Array of glob patterns
1199
+ * @returns True if path matches any pattern
1200
+ */
1201
+ function matchesPatterns(path, patterns) {
1202
+ return patterns.some((pattern) => matchGlobPattern(path, pattern));
1203
+ }
1204
+ /**
1205
+ * Searches a directory tree for files matching one or more glob patterns,
1206
+ * returning relative or absolute paths based on options.
1207
+ *
1208
+ * @param startPath - Root directory to begin the search
1209
+ * @param patterns - Glob patterns (e.g., '*.ts', '**\/*.json') to filter files
1210
+ * @param options - Configuration for search behavior
1211
+ * @returns List of relative file paths that match the patterns
1212
+ *
1213
+ * @example
1214
+ * ```typescript
1215
+ * import { findFiles } from '@hyperfrontend/project-scope'
1216
+ *
1217
+ * // Find all TypeScript files
1218
+ * const tsFiles = findFiles('./src', '\*\*\/*.ts')
1219
+ *
1220
+ * // Find multiple file types
1221
+ * const configFiles = findFiles('./', ['\*.json', '\*.yaml', '\*.yml'])
1222
+ *
1223
+ * // Limit results and get absolute paths
1224
+ * const first10 = findFiles('./src', '\*\*\/*.ts', {
1225
+ * maxResults: 10,
1226
+ * absolutePaths: true
1227
+ * })
1228
+ * ```
1229
+ */
1230
+ function findFiles(startPath, patterns, options) {
1231
+ const normalizedPatterns = isArray(patterns) ? patterns : [patterns];
1232
+ searchLogger.debug('Finding files', { startPath, patterns: normalizedPatterns, maxResults: options?.maxResults });
1233
+ const results = [];
1234
+ const maxResults = options?.maxResults ?? Infinity;
1235
+ walkDirectory(startPath, (entry) => {
1236
+ if (results.length >= maxResults) {
1237
+ return 'stop';
1238
+ }
1239
+ if (!entry.isFile) {
1240
+ return undefined;
1241
+ }
1242
+ if (matchesPatterns(entry.relativePath, normalizedPatterns)) {
1243
+ results.push(options?.absolutePaths ? entry.path : entry.relativePath);
1244
+ }
1245
+ return undefined;
1246
+ }, options);
1247
+ searchLogger.debug('File search complete', { startPath, matchCount: results.length });
1248
+ return results;
1249
+ }
1250
+ /**
1251
+ * Searches a virtual file system tree for files matching glob patterns,
1252
+ * useful for analyzing project structure without disk I/O.
1253
+ *
1254
+ * @param tree - In-memory virtual file system representation
1255
+ * @param patterns - Glob patterns (e.g., '*.ts', '**\/*.json') to filter files
1256
+ * @param options - Configuration for search behavior
1257
+ * @returns List of virtual file paths that match the patterns
1258
+ */
1259
+ function findFilesInTree(tree, patterns, options) {
1260
+ const normalizedPatterns = isArray(patterns) ? patterns : [patterns];
1261
+ const results = [];
1262
+ const maxResults = options?.maxResults ?? Infinity;
1263
+ walkTree(tree, tree.root || '', (entry) => {
1264
+ if (results.length >= maxResults) {
1265
+ return 'stop';
1266
+ }
1267
+ if (!entry.isFile) {
1268
+ return undefined;
1269
+ }
1270
+ if (matchesPatterns(entry.relativePath, normalizedPatterns)) {
1271
+ results.push(entry.relativePath);
1272
+ }
1273
+ return undefined;
1274
+ }, options);
1275
+ return results;
1276
+ }
1277
+ /**
1278
+ * Searches a directory tree for directories matching one or more glob patterns,
1279
+ * returning relative or absolute paths based on options.
1280
+ *
1281
+ * @param startPath - Root directory to begin the search
1282
+ * @param patterns - Glob patterns to filter directories (supports wildcards)
1283
+ * @param options - Configuration for search behavior
1284
+ * @returns List of relative directory paths that match the patterns
1285
+ */
1286
+ function findDirectories(startPath, patterns, options) {
1287
+ const normalizedPatterns = isArray(patterns) ? patterns : [patterns];
1288
+ const results = [];
1289
+ const maxResults = options?.maxResults ?? Infinity;
1290
+ walkDirectory(startPath, (entry) => {
1291
+ if (results.length >= maxResults) {
1292
+ return 'stop';
1293
+ }
1294
+ if (!entry.isDirectory) {
1295
+ return undefined;
1296
+ }
1297
+ if (matchesPatterns(entry.relativePath, normalizedPatterns)) {
1298
+ results.push(options?.absolutePaths ? entry.path : entry.relativePath);
1299
+ }
1300
+ return undefined;
1301
+ }, options);
1302
+ return results;
1303
+ }
1304
+
1305
+ /**
1306
+ * Known configuration file patterns organized by type.
1307
+ */
1308
+ const CONFIG_PATTERNS = {
1309
+ // Package Management
1310
+ 'package.json': {
1311
+ patterns: ['package.json'],
1312
+ format: 'json',
1313
+ description: 'NPM package manifest',
1314
+ },
1315
+ 'package-lock.json': {
1316
+ patterns: ['package-lock.json'],
1317
+ format: 'json',
1318
+ description: 'NPM lockfile',
1319
+ },
1320
+ 'pnpm-lock.yaml': {
1321
+ patterns: ['pnpm-lock.yaml'],
1322
+ format: 'yaml',
1323
+ description: 'PNPM lockfile',
1324
+ },
1325
+ 'yarn.lock': {
1326
+ patterns: ['yarn.lock'],
1327
+ format: 'text',
1328
+ description: 'Yarn lockfile',
1329
+ },
1330
+ '.npmrc': {
1331
+ patterns: ['.npmrc'],
1332
+ format: 'ini',
1333
+ description: 'NPM configuration',
1334
+ sensitive: true,
1335
+ },
1336
+ // TypeScript
1337
+ tsconfig: {
1338
+ patterns: ['tsconfig.json', 'tsconfig.*.json'],
1339
+ format: 'jsonc',
1340
+ description: 'TypeScript configuration',
1341
+ canExtend: true,
1342
+ },
1343
+ // Monorepo
1344
+ nx: {
1345
+ patterns: ['nx.json'],
1346
+ format: 'json',
1347
+ description: 'NX workspace configuration',
1348
+ },
1349
+ 'project.json': {
1350
+ patterns: ['project.json', '**/project.json'],
1351
+ format: 'json',
1352
+ description: 'NX project configuration',
1353
+ },
1354
+ 'workspace.json': {
1355
+ patterns: ['workspace.json'],
1356
+ format: 'json',
1357
+ description: 'NX workspace projects (deprecated)',
1358
+ },
1359
+ turbo: {
1360
+ patterns: ['turbo.json'],
1361
+ format: 'jsonc',
1362
+ description: 'TurboRepo configuration',
1363
+ },
1364
+ lerna: {
1365
+ patterns: ['lerna.json'],
1366
+ format: 'json',
1367
+ description: 'Lerna configuration',
1368
+ },
1369
+ // Build Tools
1370
+ webpack: {
1371
+ patterns: ['webpack.config.js', 'webpack.config.ts', 'webpack.config.cjs', 'webpack.config.mjs'],
1372
+ format: 'js',
1373
+ description: 'Webpack configuration',
1374
+ },
1375
+ rollup: {
1376
+ patterns: ['rollup.config.js', 'rollup.config.ts', 'rollup.config.mjs'],
1377
+ format: 'js',
1378
+ description: 'Rollup configuration',
1379
+ },
1380
+ vite: {
1381
+ patterns: ['vite.config.js', 'vite.config.ts', 'vite.config.mjs'],
1382
+ format: 'js',
1383
+ description: 'Vite configuration',
1384
+ },
1385
+ esbuild: {
1386
+ patterns: ['esbuild.config.js', 'esbuild.config.ts', 'esbuild.config.mjs'],
1387
+ format: 'js',
1388
+ description: 'esbuild configuration',
1389
+ },
1390
+ babel: {
1391
+ patterns: ['babel.config.js', 'babel.config.json', '.babelrc', '.babelrc.js', '.babelrc.json'],
1392
+ format: 'json',
1393
+ description: 'Babel configuration',
1394
+ },
1395
+ swc: {
1396
+ patterns: ['.swcrc'],
1397
+ format: 'json',
1398
+ description: 'SWC configuration',
1399
+ },
1400
+ // Testing
1401
+ jest: {
1402
+ patterns: ['jest.config.js', 'jest.config.ts', 'jest.config.mjs'],
1403
+ description: 'Jest configuration',
1404
+ },
1405
+ vitest: {
1406
+ patterns: ['vitest.config.js', 'vitest.config.ts'],
1407
+ description: 'Vitest configuration',
1408
+ },
1409
+ cypress: {
1410
+ patterns: ['cypress.config.js', 'cypress.config.ts'],
1411
+ description: 'Cypress configuration',
1412
+ },
1413
+ playwright: {
1414
+ patterns: ['playwright.config.js', 'playwright.config.ts'],
1415
+ description: 'Playwright configuration',
1416
+ },
1417
+ // Framework configs
1418
+ next: {
1419
+ patterns: ['next.config.js', 'next.config.mjs', 'next.config.ts'],
1420
+ format: 'js',
1421
+ description: 'Next.js configuration',
1422
+ },
1423
+ angular: {
1424
+ patterns: ['angular.json'],
1425
+ format: 'json',
1426
+ description: 'Angular CLI configuration',
1427
+ },
1428
+ nuxt: {
1429
+ patterns: ['nuxt.config.js', 'nuxt.config.ts'],
1430
+ format: 'js',
1431
+ description: 'Nuxt.js configuration',
1432
+ },
1433
+ svelte: {
1434
+ patterns: ['svelte.config.js', 'svelte.config.ts'],
1435
+ format: 'js',
1436
+ description: 'SvelteKit configuration',
1437
+ },
1438
+ astro: {
1439
+ patterns: ['astro.config.js', 'astro.config.ts', 'astro.config.mjs'],
1440
+ format: 'js',
1441
+ description: 'Astro configuration',
1442
+ },
1443
+ // Linting & Formatting
1444
+ eslint: {
1445
+ patterns: [
1446
+ 'eslint.config.js',
1447
+ 'eslint.config.cjs',
1448
+ 'eslint.config.mjs',
1449
+ '.eslintrc',
1450
+ '.eslintrc.js',
1451
+ '.eslintrc.json',
1452
+ '.eslintrc.yml',
1453
+ ],
1454
+ format: 'js',
1455
+ description: 'ESLint configuration',
1456
+ },
1457
+ prettier: {
1458
+ patterns: ['prettier.config.js', 'prettier.config.cjs', '.prettierrc', '.prettierrc.js', '.prettierrc.json', '.prettierrc.yml'],
1459
+ format: 'json',
1460
+ description: 'Prettier configuration',
1461
+ },
1462
+ // Environment (sensitive)
1463
+ env: {
1464
+ patterns: ['.env', '.env.*', '*.env'],
1465
+ format: 'dotenv',
1466
+ description: 'Environment variables',
1467
+ sensitive: true,
1468
+ },
1469
+ // Git
1470
+ '.gitignore': {
1471
+ patterns: ['.gitignore'],
1472
+ format: 'text',
1473
+ description: 'Git ignore patterns',
1474
+ },
1475
+ '.gitattributes': {
1476
+ patterns: ['.gitattributes'],
1477
+ format: 'text',
1478
+ description: 'Git attributes',
1479
+ },
1480
+ };
1481
+ /**
1482
+ * Get patterns for specific config types.
1483
+ *
1484
+ * @param types - Array of config types to get patterns for
1485
+ * @returns Array of file patterns
1486
+ */
1487
+ function getConfigPatternsByType(types) {
1488
+ return types.flatMap((type) => CONFIG_PATTERNS[type]?.patterns ?? []);
1489
+ }
1490
+
1491
+ /**
1492
+ * Global registry of all caches for bulk operations.
1493
+ */
1494
+ const cacheRegistry = createSet();
1495
+ /**
1496
+ * Create a cache with optional TTL and size limits.
1497
+ *
1498
+ * The cache provides a simple key-value store with:
1499
+ * - Optional TTL (time-to-live) for automatic expiration
1500
+ * - Optional maxSize for limiting cache size with FIFO eviction
1501
+ * - Lazy expiration (entries are checked on access)
1502
+ *
1503
+ * @param options - Cache configuration options
1504
+ * @returns Cache instance
1505
+ *
1506
+ * @example
1507
+ * ```typescript
1508
+ * // Basic cache
1509
+ * const cache = createCache<string, number>()
1510
+ * cache.set('answer', 42)
1511
+ * cache.get('answer') // 42
1512
+ *
1513
+ * // Cache with TTL (expires after 60 seconds)
1514
+ * const ttlCache = createCache<string, object>({ ttl: 60000 })
1515
+ *
1516
+ * // Cache with max size (evicts oldest when full)
1517
+ * const lruCache = createCache<string, object>({ maxSize: 100 })
1518
+ *
1519
+ * // Combined options
1520
+ * const configCache = createCache<string, object>({
1521
+ * ttl: 30000,
1522
+ * maxSize: 50
1523
+ * })
1524
+ * ```
1525
+ */
1526
+ function createCache(options) {
1527
+ const { ttl, maxSize } = options ?? {};
1528
+ const store = createMap();
1529
+ // Track insertion order for FIFO eviction
1530
+ const insertionOrder = [];
1531
+ /**
1532
+ * Check if an entry is expired.
1533
+ *
1534
+ * @param entry - Cache entry to check
1535
+ * @returns True if entry is expired
1536
+ */
1537
+ function isExpired(entry) {
1538
+ if (ttl === undefined)
1539
+ return false;
1540
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
1541
+ return Date.now() - entry.timestamp > ttl;
1542
+ }
1543
+ /**
1544
+ * Evict oldest entries to make room for new ones.
1545
+ */
1546
+ function evictIfNeeded() {
1547
+ if (maxSize === undefined)
1548
+ return;
1549
+ while (store.size >= maxSize && insertionOrder.length > 0) {
1550
+ const oldestKey = insertionOrder.shift();
1551
+ if (oldestKey !== undefined) {
1552
+ store.delete(oldestKey);
1553
+ }
1554
+ }
1555
+ }
1556
+ /**
1557
+ * Remove key from insertion order tracking.
1558
+ *
1559
+ * @param key - Key to remove from order tracking
1560
+ */
1561
+ function removeFromOrder(key) {
1562
+ const index = insertionOrder.indexOf(key);
1563
+ if (index !== -1) {
1564
+ insertionOrder.splice(index, 1);
1565
+ }
1566
+ }
1567
+ const cache = {
1568
+ get(key) {
1569
+ const entry = store.get(key);
1570
+ if (!entry)
1571
+ return undefined;
1572
+ if (isExpired(entry)) {
1573
+ store.delete(key);
1574
+ removeFromOrder(key);
1575
+ return undefined;
1576
+ }
1577
+ return entry.value;
1578
+ },
1579
+ set(key, value) {
1580
+ // If key exists, remove from order first
1581
+ if (store.has(key)) {
1582
+ removeFromOrder(key);
1583
+ }
1584
+ else {
1585
+ // Evict if needed before adding new entry
1586
+ evictIfNeeded();
1587
+ }
1588
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
1589
+ store.set(key, { value, timestamp: Date.now() });
1590
+ insertionOrder.push(key);
1591
+ },
1592
+ has(key) {
1593
+ const entry = store.get(key);
1594
+ if (!entry)
1595
+ return false;
1596
+ if (isExpired(entry)) {
1597
+ store.delete(key);
1598
+ removeFromOrder(key);
1599
+ return false;
1600
+ }
1601
+ return true;
1602
+ },
1603
+ delete(key) {
1604
+ removeFromOrder(key);
1605
+ return store.delete(key);
1606
+ },
1607
+ clear() {
1608
+ store.clear();
1609
+ insertionOrder.length = 0;
1610
+ },
1611
+ size() {
1612
+ return store.size;
1613
+ },
1614
+ keys() {
1615
+ return [...insertionOrder];
1616
+ },
1617
+ };
1618
+ // Register cache for global operations
1619
+ cacheRegistry.add(cache);
1620
+ return freeze(cache);
1621
+ }
1622
+
1623
+ const configLogger = createScopedLogger('project-scope:config');
1624
+ /**
1625
+ * Cache for config detection results.
1626
+ * TTL: 30 seconds (configs can change frequently during setup)
1627
+ */
1628
+ const configDetectionCache = createCache({ ttl: 30000, maxSize: 50 });
1629
+ /**
1630
+ * Detect all configuration files in a directory.
1631
+ *
1632
+ * Results are cached for 30 seconds per project path and options
1633
+ * to avoid redundant file system operations on repeated calls.
1634
+ *
1635
+ * @param rootPath - Project root directory
1636
+ * @param types - Optional array of config types to check (defaults to all)
1637
+ * @param options - Detection options
1638
+ * @returns Array of detected configuration files
1639
+ *
1640
+ * @example
1641
+ * ```typescript
1642
+ * import { detectConfigs } from '@hyperfrontend/project-scope'
1643
+ *
1644
+ * // Detect all config files
1645
+ * const configs = detectConfigs('./my-project')
1646
+ * for (const config of configs) {
1647
+ * console.log(`${config.type}: ${config.path}`)
1648
+ * }
1649
+ * // Output:
1650
+ * // typescript: tsconfig.json
1651
+ * // eslint: eslint.config.js
1652
+ * // jest: jest.config.ts
1653
+ *
1654
+ * // Detect specific config types only
1655
+ * const tsConfigs = detectConfigs('./my-project', ['typescript', 'eslint'])
1656
+ * ```
1657
+ */
1658
+ function detectConfigs(rootPath, types, options) {
1659
+ const typesToCheck = types ?? keys(CONFIG_PATTERNS);
1660
+ const results = [];
1661
+ const maxDepth = options?.maxDepth ?? 10;
1662
+ const includeHidden = options?.includeHidden ?? true;
1663
+ const typeKey = types ? types.sort().join(',') : 'all';
1664
+ const cacheKey = `${rootPath}:${typeKey}:${maxDepth}:${includeHidden}`;
1665
+ if (!options?.skipCache) {
1666
+ const cached = configDetectionCache.get(cacheKey);
1667
+ if (cached) {
1668
+ configLogger.debug('Returning cached config detection results', { rootPath });
1669
+ return cached;
1670
+ }
1671
+ }
1672
+ configLogger.debug('Detecting config files', { rootPath, types: typesToCheck.length });
1673
+ for (const type of typesToCheck) {
1674
+ const info = CONFIG_PATTERNS[type];
1675
+ if (!info)
1676
+ continue;
1677
+ for (const pattern of info.patterns) {
1678
+ const isRecursive = pattern.includes('**');
1679
+ if (isRecursive) {
1680
+ const files = findFiles(rootPath, pattern, {
1681
+ maxDepth,
1682
+ includeHidden: options?.includeHidden ?? true,
1683
+ });
1684
+ for (const file of files) {
1685
+ if (!results.some((r) => r.path === file && r.type === type)) {
1686
+ configLogger.debug('Found config file', { type, path: file });
1687
+ results.push({
1688
+ type,
1689
+ path: file,
1690
+ matchedPattern: pattern,
1691
+ info,
1692
+ });
1693
+ }
1694
+ }
1695
+ }
1696
+ else {
1697
+ const fullPath = join$1(rootPath, pattern);
1698
+ if (exists(fullPath)) {
1699
+ if (!results.some((r) => r.path === pattern && r.type === type)) {
1700
+ configLogger.debug('Found config file', { type, path: pattern });
1701
+ results.push({
1702
+ type,
1703
+ path: pattern,
1704
+ matchedPattern: pattern,
1705
+ info,
1706
+ });
1707
+ }
1708
+ }
1709
+ }
1710
+ }
1711
+ }
1712
+ configLogger.debug('Config detection complete', { found: results.length });
1713
+ configDetectionCache.set(cacheKey, results);
1714
+ return results;
1715
+ }
1716
+ /**
1717
+ * Clear the config detection cache.
1718
+ *
1719
+ * Useful for testing or when the project files have changed.
1720
+ */
1721
+ function clearConfigDetectionCache() {
1722
+ configDetectionCache.clear();
1723
+ }
1724
+ /**
1725
+ * Find a specific configuration file.
1726
+ *
1727
+ * @param rootPath - Project root directory
1728
+ * @param type - Config type to find
1729
+ * @returns Full path to config file or null if not found
1730
+ */
1731
+ function findConfigFile(rootPath, type) {
1732
+ const info = CONFIG_PATTERNS[type];
1733
+ if (!info)
1734
+ return null;
1735
+ for (const pattern of info.patterns) {
1736
+ if (!pattern.includes('*')) {
1737
+ const fullPath = join$1(rootPath, pattern);
1738
+ if (exists(fullPath)) {
1739
+ return fullPath;
1740
+ }
1741
+ }
1742
+ }
1743
+ for (const pattern of info.patterns) {
1744
+ if (pattern.includes('*') && !pattern.includes('**')) {
1745
+ const files = findFiles(rootPath, pattern, { maxDepth: 0 });
1746
+ if (files.length > 0) {
1747
+ return join$1(rootPath, files[0]);
1748
+ }
1749
+ }
1750
+ }
1751
+ return null;
1752
+ }
1753
+ /**
1754
+ * Get all known config file patterns for a given configuration type.
1755
+ *
1756
+ * @param type - Configuration type identifier
1757
+ * @returns Array of glob patterns for matching config files
1758
+ */
1759
+ function getConfigPaths(type) {
1760
+ const info = CONFIG_PATTERNS[type];
1761
+ return info?.patterns ?? [];
1762
+ }
1763
+
1764
+ /**
1765
+ * Safe copies of Number built-in methods and constants.
1766
+ *
1767
+ * These references are captured at module initialization time to protect against
1768
+ * prototype pollution attacks. Import only what you need for tree-shaking.
1769
+ *
1770
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/number
1771
+ */
1772
+ // Capture references at module initialization time
1773
+ const _parseInt = globalThis.parseInt;
1774
+ const _parseFloat = globalThis.parseFloat;
1775
+ // ============================================================================
1776
+ // Parsing
1777
+ // ============================================================================
1778
+ /**
1779
+ * (Safe copy) Parses a string and returns an integer.
1780
+ */
1781
+ const parseInt = _parseInt;
1782
+ /**
1783
+ * (Safe copy) Parses a string and returns a floating point number.
1784
+ */
1785
+ const parseFloat = _parseFloat;
1786
+
1787
+ /**
1788
+ * Create a structured error with code and optional context.
1789
+ *
1790
+ * @param message - The human-readable error message
1791
+ * @param code - The machine-readable error code for programmatic handling
1792
+ * @param context - Additional contextual information about the error
1793
+ * @returns Structured error instance with code and context properties
1794
+ *
1795
+ * @example
1796
+ * ```typescript
1797
+ * import { createStructuredError } from '@hyperfrontend/project-scope'
1798
+ *
1799
+ * throw createStructuredError(
1800
+ * 'Configuration file not found',
1801
+ * 'CONFIG_NOT_FOUND',
1802
+ * { path: './config.json', searched: ['./config.json', './settings.json'] }
1803
+ * )
1804
+ * ```
1805
+ */
1806
+ function createStructuredError(message, code, context) {
1807
+ const error = createError(message);
1808
+ error.code = code;
1809
+ error.context = context ?? {};
1810
+ return error;
1811
+ }
1812
+ /**
1813
+ * Create a configuration-related error.
1814
+ *
1815
+ * @param message - The human-readable error message
1816
+ * @param code - The machine-readable error code for programmatic handling
1817
+ * @param context - Additional contextual information (e.g., file path, config key)
1818
+ * @returns Structured error instance tagged with type 'config'
1819
+ */
1820
+ function createConfigError(message, code, context) {
1821
+ return createStructuredError(message, code, { ...context, type: 'config' });
1822
+ }
1823
+
1824
+ /**
1825
+ * Detect config type from file name.
1826
+ * Uses safe character-by-character matching to prevent ReDoS attacks.
1827
+ *
1828
+ * @param filePath - Path to config file
1829
+ * @returns Detected config type or undefined
1830
+ */
1831
+ function detectConfigType(filePath) {
1832
+ const fileName = basename(filePath);
1833
+ for (const [type, info] of entries(CONFIG_PATTERNS)) {
1834
+ for (const pattern of info.patterns) {
1835
+ if (matchGlobPattern(fileName, pattern)) {
1836
+ return type;
1837
+ }
1838
+ }
1839
+ }
1840
+ return undefined;
1841
+ }
1842
+ /**
1843
+ * Detect format from file path.
1844
+ *
1845
+ * @param filePath - Path to config file
1846
+ * @returns Detected format
1847
+ */
1848
+ function detectFormat(filePath) {
1849
+ const ext = filePath.split('.').pop()?.toLowerCase();
1850
+ switch (ext) {
1851
+ case 'json':
1852
+ return 'json';
1853
+ case 'yaml':
1854
+ case 'yml':
1855
+ return 'yaml';
1856
+ case 'js':
1857
+ case 'cjs':
1858
+ case 'mjs':
1859
+ return 'js';
1860
+ case 'ts':
1861
+ return 'ts';
1862
+ case 'toml':
1863
+ return 'toml';
1864
+ case 'ini':
1865
+ return 'ini';
1866
+ default:
1867
+ return 'text';
1868
+ }
1869
+ }
1870
+ /**
1871
+ * Strip JSON comments (// and /* *\/).
1872
+ *
1873
+ * @param content - JSONC content
1874
+ * @returns JSON content without comments
1875
+ */
1876
+ function stripJsonComments(content) {
1877
+ let result = '';
1878
+ let inString = false;
1879
+ let inLineComment = false;
1880
+ let inBlockComment = false;
1881
+ let stringChar = '';
1882
+ for (let i = 0; i < content.length; i++) {
1883
+ const char = content[i];
1884
+ const nextChar = content[i + 1];
1885
+ if (inLineComment) {
1886
+ if (char === '\n') {
1887
+ inLineComment = false;
1888
+ result += char;
1889
+ }
1890
+ continue;
1891
+ }
1892
+ if (inBlockComment) {
1893
+ if (char === '*' && nextChar === '/') {
1894
+ inBlockComment = false;
1895
+ i++;
1896
+ }
1897
+ continue;
1898
+ }
1899
+ if (inString) {
1900
+ result += char;
1901
+ if (char === stringChar && content[i - 1] !== '\\') {
1902
+ inString = false;
1903
+ }
1904
+ continue;
1905
+ }
1906
+ if (char === '"' || char === "'") {
1907
+ inString = true;
1908
+ stringChar = char;
1909
+ result += char;
1910
+ continue;
1911
+ }
1912
+ if (char === '/' && nextChar === '/') {
1913
+ inLineComment = true;
1914
+ i++;
1915
+ continue;
1916
+ }
1917
+ if (char === '/' && nextChar === '*') {
1918
+ inBlockComment = true;
1919
+ i++;
1920
+ continue;
1921
+ }
1922
+ result += char;
1923
+ }
1924
+ return result;
1925
+ }
1926
+ /**
1927
+ * Parse simple YAML key-value pairs into an object.
1928
+ * Note: This is a simplified parser for basic config structures.
1929
+ *
1930
+ * @param content - Raw YAML file content to parse
1931
+ * @returns Object representation of the YAML key-value pairs
1932
+ */
1933
+ function parseSimpleYaml(content) {
1934
+ const lines = content.split('\n');
1935
+ const result = {};
1936
+ for (const line of lines) {
1937
+ if (line.trim().startsWith('#') || !line.includes(':')) {
1938
+ continue;
1939
+ }
1940
+ const colonIndex = line.indexOf(':');
1941
+ const key = line.substring(0, colonIndex).trim();
1942
+ const value = line.substring(colonIndex + 1).trim();
1943
+ if (key && value) {
1944
+ if (value === 'true') {
1945
+ result[key] = true;
1946
+ }
1947
+ else if (value === 'false') {
1948
+ result[key] = false;
1949
+ }
1950
+ else if (value === 'null') {
1951
+ result[key] = null;
1952
+ }
1953
+ else if (/^-?\d+$/.test(value)) {
1954
+ result[key] = parseInt(value, 10);
1955
+ }
1956
+ else if (/^-?\d+\.\d+$/.test(value)) {
1957
+ result[key] = parseFloat(value);
1958
+ }
1959
+ else {
1960
+ result[key] = value.replace(/^["']|["']$/g, '');
1961
+ }
1962
+ }
1963
+ }
1964
+ return result;
1965
+ }
1966
+ /**
1967
+ * Parse INI-style configuration format into an object.
1968
+ * Supports sections and key-value pairs.
1969
+ *
1970
+ * @param content - Raw INI file content to parse
1971
+ * @returns Object with sections as keys and their key-value pairs
1972
+ */
1973
+ function parseIniConfig(content) {
1974
+ const result = {};
1975
+ let currentSection = '';
1976
+ for (const line of content.split('\n')) {
1977
+ const trimmed = line.trim();
1978
+ if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith(';')) {
1979
+ continue;
1980
+ }
1981
+ const sectionMatch = trimmed.match(/^\[([^\]]+)\]$/);
1982
+ if (sectionMatch) {
1983
+ currentSection = sectionMatch[1];
1984
+ result[currentSection] = {};
1985
+ continue;
1986
+ }
1987
+ const keyValueMatch = trimmed.match(/^([^=]+)=(.*)$/);
1988
+ if (keyValueMatch) {
1989
+ const key = keyValueMatch[1].trim();
1990
+ const value = keyValueMatch[2].trim();
1991
+ if (currentSection) {
1992
+ result[currentSection][key] = value;
1993
+ }
1994
+ else {
1995
+ result[key] = value;
1996
+ }
1997
+ }
1998
+ }
1999
+ return result;
2000
+ }
2001
+ /**
2002
+ * Parse dotenv-style environment variable format.
2003
+ * Handles quoted values and comments.
2004
+ *
2005
+ * @param content - Raw dotenv file content to parse
2006
+ * @returns Object mapping variable names to their values
2007
+ */
2008
+ function parseDotenv(content) {
2009
+ const result = {};
2010
+ for (const line of content.split('\n')) {
2011
+ const trimmed = line.trim();
2012
+ if (!trimmed || trimmed.startsWith('#')) {
2013
+ continue;
2014
+ }
2015
+ const match = trimmed.match(/^([^=]+)=(.*)$/);
2016
+ if (match) {
2017
+ const key = match[1].trim();
2018
+ let value = match[2].trim();
2019
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
2020
+ value = value.slice(1, -1);
2021
+ }
2022
+ result[key] = value;
2023
+ }
2024
+ }
2025
+ return result;
2026
+ }
2027
+ /**
2028
+ * Parse JSON configuration file.
2029
+ *
2030
+ * @param filePath - Path to the JSON configuration file
2031
+ * @param content - Raw file content to parse
2032
+ * @param type - Category of configuration (e.g., typescript, eslint)
2033
+ * @param format - Whether to strip comments (jsonc) or parse strictly (json)
2034
+ * @returns Configuration object with parsed data and extends references
2035
+ */
2036
+ function parseJsonConfig(filePath, content, type, format = 'json') {
2037
+ const cleanContent = format === 'jsonc' ? stripJsonComments(content) : content;
2038
+ try {
2039
+ const data = parse(cleanContent);
2040
+ let extendsPath;
2041
+ if (typeof data['extends'] === 'string') {
2042
+ extendsPath = [data['extends']];
2043
+ }
2044
+ else if (isArray(data['extends'])) {
2045
+ extendsPath = data['extends'];
2046
+ }
2047
+ return {
2048
+ type: type ?? 'unknown',
2049
+ path: filePath,
2050
+ format,
2051
+ data,
2052
+ extends: extendsPath,
2053
+ };
2054
+ }
2055
+ catch (error) {
2056
+ throw createConfigError(`Failed to parse JSON config: ${filePath}`, 'CONFIG_PARSE_ERROR', {
2057
+ filePath,
2058
+ format,
2059
+ cause: error,
2060
+ });
2061
+ }
2062
+ }
2063
+ /**
2064
+ * Parse YAML configuration file.
2065
+ *
2066
+ * @param filePath - Path to the YAML configuration file
2067
+ * @param content - Raw file content to parse
2068
+ * @param type - Category of configuration (e.g., github-actions, docker-compose)
2069
+ * @returns Configuration object with parsed YAML data
2070
+ */
2071
+ function parseYamlConfig(filePath, content, type) {
2072
+ const data = parseSimpleYaml(content);
2073
+ return {
2074
+ type: type ?? 'unknown',
2075
+ path: filePath,
2076
+ format: 'yaml',
2077
+ data,
2078
+ };
2079
+ }
2080
+ /**
2081
+ * Parse configuration file.
2082
+ *
2083
+ * @param filePath - Path to config file
2084
+ * @param type - Optional config type (auto-detected if not provided)
2085
+ * @returns Parsed configuration
2086
+ */
2087
+ function parseConfig(filePath, type) {
2088
+ const content = readFileContent(filePath);
2089
+ const detectedType = type ?? detectConfigType(filePath);
2090
+ const info = detectedType ? CONFIG_PATTERNS[detectedType] : null;
2091
+ const format = info?.format ?? detectFormat(filePath);
2092
+ switch (format) {
2093
+ case 'json':
2094
+ return parseJsonConfig(filePath, content, detectedType, 'json');
2095
+ case 'jsonc':
2096
+ return parseJsonConfig(filePath, content, detectedType, 'jsonc');
2097
+ case 'yaml':
2098
+ return parseYamlConfig(filePath, content, detectedType);
2099
+ case 'ini':
2100
+ return {
2101
+ type: detectedType ?? 'unknown',
2102
+ path: filePath,
2103
+ format: 'ini',
2104
+ data: parseIniConfig(content),
2105
+ };
2106
+ case 'dotenv':
2107
+ return {
2108
+ type: detectedType ?? 'unknown',
2109
+ path: filePath,
2110
+ format: 'dotenv',
2111
+ data: parseDotenv(content),
2112
+ };
2113
+ case 'js':
2114
+ case 'ts':
2115
+ return {
2116
+ type: detectedType ?? 'unknown',
2117
+ path: filePath,
2118
+ format,
2119
+ raw: content,
2120
+ };
2121
+ default:
2122
+ return {
2123
+ type: detectedType ?? 'unknown',
2124
+ path: filePath,
2125
+ format: 'text',
2126
+ raw: content,
2127
+ };
2128
+ }
2129
+ }
2130
+ /**
2131
+ * Read and parse config file if it exists.
2132
+ *
2133
+ * @param configPath - Path to config file
2134
+ * @returns Parsed config or null if file doesn't exist
2135
+ */
2136
+ function readConfigIfExists(configPath) {
2137
+ const content = readFileIfExists(configPath);
2138
+ if (!content)
2139
+ return null;
2140
+ try {
2141
+ const format = detectFormat(configPath);
2142
+ switch (format) {
2143
+ case 'json':
2144
+ return parse(content);
2145
+ case 'jsonc':
2146
+ return parse(stripJsonComments(content));
2147
+ case 'yaml':
2148
+ return parseSimpleYaml(content);
2149
+ default:
2150
+ return null;
2151
+ }
2152
+ }
2153
+ catch {
2154
+ return null;
2155
+ }
2156
+ }
2157
+
2158
+ const packageLogger = createScopedLogger('project-scope:project:package');
2159
+ /**
2160
+ * Verifies that a value is an object with only string values,
2161
+ * used for validating dependency maps and script definitions.
2162
+ *
2163
+ * @param value - Value to check
2164
+ * @returns True if value is a record of strings
2165
+ */
2166
+ function isStringRecord(value) {
2167
+ if (typeof value !== 'object' || value === null)
2168
+ return false;
2169
+ return values(value).every((v) => typeof v === 'string');
2170
+ }
2171
+ /**
2172
+ * Extracts and normalizes the workspaces field from package.json,
2173
+ * supporting both array format and object with packages array.
2174
+ *
2175
+ * @param value - Raw workspaces value from package.json
2176
+ * @returns Normalized workspace patterns or undefined if invalid
2177
+ */
2178
+ function parseWorkspaces(value) {
2179
+ if (isArray(value) && value.every((v) => typeof v === 'string')) {
2180
+ return value;
2181
+ }
2182
+ if (typeof value === 'object' && value !== null) {
2183
+ const obj = value;
2184
+ if (isArray(obj['packages'])) {
2185
+ return { packages: obj['packages'] };
2186
+ }
2187
+ }
2188
+ return undefined;
2189
+ }
2190
+ /**
2191
+ * Validate and normalize package.json data.
2192
+ *
2193
+ * @param data - Raw parsed data
2194
+ * @returns Validated package.json
2195
+ */
2196
+ function validatePackageJson(data) {
2197
+ if (typeof data !== 'object' || data === null) {
2198
+ throw createError('package.json must be an object');
2199
+ }
2200
+ const pkg = data;
2201
+ return {
2202
+ name: typeof pkg['name'] === 'string' ? pkg['name'] : undefined,
2203
+ version: typeof pkg['version'] === 'string' ? pkg['version'] : undefined,
2204
+ description: typeof pkg['description'] === 'string' ? pkg['description'] : undefined,
2205
+ main: typeof pkg['main'] === 'string' ? pkg['main'] : undefined,
2206
+ module: typeof pkg['module'] === 'string' ? pkg['module'] : undefined,
2207
+ browser: typeof pkg['browser'] === 'string' ? pkg['browser'] : undefined,
2208
+ types: typeof pkg['types'] === 'string' ? pkg['types'] : undefined,
2209
+ bin: typeof pkg['bin'] === 'string' || isStringRecord(pkg['bin']) ? pkg['bin'] : undefined,
2210
+ scripts: isStringRecord(pkg['scripts']) ? pkg['scripts'] : undefined,
2211
+ dependencies: isStringRecord(pkg['dependencies']) ? pkg['dependencies'] : undefined,
2212
+ devDependencies: isStringRecord(pkg['devDependencies']) ? pkg['devDependencies'] : undefined,
2213
+ peerDependencies: isStringRecord(pkg['peerDependencies']) ? pkg['peerDependencies'] : undefined,
2214
+ optionalDependencies: isStringRecord(pkg['optionalDependencies']) ? pkg['optionalDependencies'] : undefined,
2215
+ workspaces: parseWorkspaces(pkg['workspaces']),
2216
+ exports: typeof pkg['exports'] === 'object' ? pkg['exports'] : undefined,
2217
+ engines: isStringRecord(pkg['engines']) ? pkg['engines'] : undefined,
2218
+ ...pkg,
2219
+ };
2220
+ }
2221
+ /**
2222
+ * Reads and parses package.json from a directory, validating
2223
+ * the structure and normalizing fields to the PackageJson interface.
2224
+ *
2225
+ * @param projectPath - Project directory path or path to package.json
2226
+ * @returns Parsed package.json
2227
+ * @throws {Error} Error if file doesn't exist or is invalid
2228
+ */
2229
+ function readPackageJson(projectPath) {
2230
+ const packageJsonPath = projectPath.endsWith('package.json') ? projectPath : join$1(projectPath, 'package.json');
2231
+ packageLogger.debug('Reading package.json', { path: packageJsonPath });
2232
+ const content = readFileContent(packageJsonPath);
2233
+ try {
2234
+ const data = parse(content);
2235
+ const validated = validatePackageJson(data);
2236
+ packageLogger.debug('Package.json read successfully', { path: packageJsonPath, name: validated.name });
2237
+ return validated;
2238
+ }
2239
+ catch (error) {
2240
+ packageLogger.warn('Failed to parse package.json', {
2241
+ path: packageJsonPath,
2242
+ error: error instanceof Error ? error.message : String(error),
2243
+ });
2244
+ throw createConfigError(`Failed to parse package.json: ${packageJsonPath}`, 'CONFIG_PARSE_ERROR', {
2245
+ filePath: packageJsonPath,
2246
+ cause: error,
2247
+ });
2248
+ }
2249
+ }
2250
+ /**
2251
+ * Attempts to read and parse package.json if it exists,
2252
+ * returning null on missing file or parse failure.
2253
+ *
2254
+ * @param projectPath - Project directory path or path to package.json
2255
+ * @returns Parsed package.json or null if not found
2256
+ */
2257
+ function readPackageJsonIfExists(projectPath) {
2258
+ const packageJsonPath = projectPath.endsWith('package.json') ? projectPath : join$1(projectPath, 'package.json');
2259
+ const content = readFileIfExists(packageJsonPath);
2260
+ if (!content) {
2261
+ packageLogger.debug('Package.json not found', { path: packageJsonPath });
2262
+ return null;
2263
+ }
2264
+ try {
2265
+ const validated = validatePackageJson(parse(content));
2266
+ packageLogger.debug('Package.json loaded', { path: packageJsonPath, name: validated.name });
2267
+ return validated;
2268
+ }
2269
+ catch {
2270
+ packageLogger.debug('Failed to parse package.json, returning null', { path: packageJsonPath });
2271
+ return null;
2272
+ }
2273
+ }
2274
+ /**
2275
+ * Find nearest package.json by walking up the directory tree.
2276
+ *
2277
+ * @param startPath - Starting path
2278
+ * @returns Path to directory containing package.json, or null if not found
2279
+ */
2280
+ function findNearestPackageJson(startPath) {
2281
+ return locateByMarkers(startPath, ['package.json']);
2282
+ }
2283
+
2284
+ /**
2285
+ * Extract all dependencies from package.json.
2286
+ *
2287
+ * @param packageJson - Parsed package.json
2288
+ * @returns All dependencies categorized
2289
+ */
2290
+ function getDependencies(packageJson) {
2291
+ return {
2292
+ dependencies: packageJson.dependencies ?? {},
2293
+ devDependencies: packageJson.devDependencies ?? {},
2294
+ peerDependencies: packageJson.peerDependencies ?? {},
2295
+ optionalDependencies: packageJson.optionalDependencies ?? {},
2296
+ };
2297
+ }
2298
+ /**
2299
+ * Get production dependencies only.
2300
+ *
2301
+ * @param packageJson - Parsed package.json
2302
+ * @returns Map of dependency name to version for runtime dependencies
2303
+ */
2304
+ function getProductionDependencies(packageJson) {
2305
+ return packageJson.dependencies ?? {};
2306
+ }
2307
+ /**
2308
+ * Get development dependencies only.
2309
+ *
2310
+ * @param packageJson - Parsed package.json
2311
+ * @returns Map of dependency name to version for dev-time dependencies
2312
+ */
2313
+ function getDevDependencies(packageJson) {
2314
+ return packageJson.devDependencies ?? {};
2315
+ }
2316
+ /**
2317
+ * Get peer dependencies only.
2318
+ *
2319
+ * @param packageJson - Parsed package.json
2320
+ * @returns Map of dependency name to version for peer requirements
2321
+ */
2322
+ function getPeerDependencies(packageJson) {
2323
+ return packageJson.peerDependencies ?? {};
2324
+ }
2325
+ /**
2326
+ * Get all dependencies merged into a single map.
2327
+ *
2328
+ * @param packageJson - Parsed package.json
2329
+ * @returns All dependencies merged
2330
+ */
2331
+ function getAllDependencies(packageJson) {
2332
+ return {
2333
+ ...packageJson.dependencies,
2334
+ ...packageJson.devDependencies,
2335
+ ...packageJson.peerDependencies,
2336
+ ...packageJson.optionalDependencies,
2337
+ };
2338
+ }
2339
+ /**
2340
+ * Check if package has a dependency of any type.
2341
+ *
2342
+ * @param packageJson - Parsed package.json content
2343
+ * @param name - Name of the dependency to check
2344
+ * @param depTypes - Optional array of dependency types to check (defaults to all)
2345
+ * @returns True if dependency exists in specified categories
2346
+ */
2347
+ function hasDependency(packageJson, name, depTypes) {
2348
+ const typesToCheck = depTypes ?? ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
2349
+ for (const depType of typesToCheck) {
2350
+ if (packageJson[depType] && name in packageJson[depType]) {
2351
+ return true;
2352
+ }
2353
+ }
2354
+ return false;
2355
+ }
2356
+ /**
2357
+ * Get version string of a specific dependency.
2358
+ *
2359
+ * @param packageJson - Parsed package.json content
2360
+ * @param name - Name of the dependency to look up
2361
+ * @returns Version string or null if not found
2362
+ */
2363
+ function getDependencyVersion(packageJson, name) {
2364
+ const deps = getDependencies(packageJson);
2365
+ return deps.dependencies[name] ?? deps.devDependencies[name] ?? deps.peerDependencies[name] ?? deps.optionalDependencies[name] ?? null;
2366
+ }
2367
+ /**
2368
+ * Get workspace patterns from package.json.
2369
+ *
2370
+ * @param packageJson - Parsed package.json
2371
+ * @returns Array of workspace patterns or empty array
2372
+ */
2373
+ function getWorkspaces(packageJson) {
2374
+ if (!packageJson.workspaces)
2375
+ return [];
2376
+ if (isArray(packageJson.workspaces)) {
2377
+ return packageJson.workspaces;
2378
+ }
2379
+ if (typeof packageJson.workspaces === 'object' && 'packages' in packageJson.workspaces) {
2380
+ return packageJson.workspaces.packages;
2381
+ }
2382
+ return [];
2383
+ }
2384
+ /**
2385
+ * Check if package has workspaces configured (monorepo).
2386
+ *
2387
+ * @param packageJson - Parsed package.json
2388
+ * @returns True if workspaces are defined
2389
+ */
2390
+ function hasWorkspaces(packageJson) {
2391
+ return getWorkspaces(packageJson).length > 0;
2392
+ }
2393
+ /**
2394
+ * Check if a package is installed in node_modules.
2395
+ *
2396
+ * @param projectPath - Project root directory
2397
+ * @param packageName - Package name to check
2398
+ * @returns Boolean indicating whether the package exists in node_modules
2399
+ */
2400
+ function hasInstalledPackage(projectPath, packageName) {
2401
+ const pkgPath = join$1(projectPath, 'node_modules', packageName, 'package.json');
2402
+ return readPackageJsonIfExists(pkgPath) !== null;
2403
+ }
2404
+ /**
2405
+ * Get installed package version from node_modules.
2406
+ *
2407
+ * @param projectPath - Project root directory
2408
+ * @param packageName - Name of the npm package to look up
2409
+ * @returns Installed version or null if not found
2410
+ */
2411
+ function getInstalledVersion(projectPath, packageName) {
2412
+ const pkg = readPackageJsonIfExists(join$1(projectPath, 'node_modules', packageName, 'package.json'));
2413
+ return pkg?.version ?? null;
2414
+ }
2415
+
2416
+ const rootLogger = createScopedLogger('project-scope:root');
2417
+ /**
2418
+ * Files indicating project root.
2419
+ */
2420
+ const ROOT_MARKERS = ['package.json', '.git'];
2421
+ /**
2422
+ * Files indicating workspace/monorepo root.
2423
+ */
2424
+ const WORKSPACE_MARKERS = ['nx.json', 'turbo.json', 'lerna.json', 'pnpm-workspace.yaml', 'rush.json'];
2425
+ /**
2426
+ * Check if directory looks like a project directory.
2427
+ *
2428
+ * @param dirPath - Directory path to check
2429
+ * @returns True if directory appears to be a project
2430
+ */
2431
+ function looksLikeProjectDir(dirPath) {
2432
+ if (exists(join$1(dirPath, 'src'))) {
2433
+ return true;
2434
+ }
2435
+ const entryPoints = ['index.ts', 'index.js', 'index.tsx', 'index.jsx', 'main.ts', 'main.js'];
2436
+ for (const entry of entryPoints) {
2437
+ if (exists(join$1(dirPath, entry))) {
2438
+ return true;
2439
+ }
2440
+ }
2441
+ if (exists(join$1(dirPath, 'project.json'))) {
2442
+ return true;
2443
+ }
2444
+ return false;
2445
+ }
2446
+ /**
2447
+ * Find the project root from a starting path.
2448
+ * Project root is the nearest directory containing package.json
2449
+ * with source files.
2450
+ *
2451
+ * @param startPath - Starting path
2452
+ * @returns Project root path or null
2453
+ *
2454
+ * @example
2455
+ * ```typescript
2456
+ * import { findProjectRoot } from '@hyperfrontend/project-scope'
2457
+ *
2458
+ * // Find project root from current directory
2459
+ * const root = findProjectRoot(process.cwd())
2460
+ * if (root) {
2461
+ * console.log('Project root:', root)
2462
+ * }
2463
+ *
2464
+ * // Find root from a deeply nested file
2465
+ * const root2 = findProjectRoot('./libs/my-lib/src/utils/helper.ts')
2466
+ * ```
2467
+ */
2468
+ function findProjectRoot(startPath) {
2469
+ rootLogger.debug('Finding project root', { startPath });
2470
+ const result = findUpwardWhere(startPath, (dir) => {
2471
+ if (exists(join$1(dir, 'package.json')) && looksLikeProjectDir(dir)) {
2472
+ return true;
2473
+ }
2474
+ if (exists(join$1(dir, 'project.json'))) {
2475
+ return true;
2476
+ }
2477
+ return false;
2478
+ });
2479
+ if (result) {
2480
+ rootLogger.debug('Found project root', { root: result });
2481
+ }
2482
+ else {
2483
+ rootLogger.debug('Project root not found');
2484
+ }
2485
+ return result;
2486
+ }
2487
+ /**
2488
+ * Find workspace root (monorepo root).
2489
+ * Searches up for workspace markers like nx.json, turbo.json, etc.
2490
+ *
2491
+ * @param startPath - Starting path
2492
+ * @returns Workspace root path or null
2493
+ *
2494
+ * @example
2495
+ * ```typescript
2496
+ * import { findWorkspaceRoot } from '@hyperfrontend/project-scope'
2497
+ *
2498
+ * const root = findWorkspaceRoot('./libs/my-lib')
2499
+ * if (root) {
2500
+ * console.log('Monorepo root:', root) // e.g., '/home/user/my-monorepo'
2501
+ * }
2502
+ * ```
2503
+ */
2504
+ function findWorkspaceRoot(startPath) {
2505
+ rootLogger.debug('Finding workspace root', { startPath });
2506
+ const byMarker = locateByMarkers(startPath, WORKSPACE_MARKERS);
2507
+ if (byMarker) {
2508
+ rootLogger.debug('Found workspace root by marker', { root: byMarker });
2509
+ return byMarker;
2510
+ }
2511
+ const byWorkspaces = findUpwardWhere(startPath, (dir) => {
2512
+ const pkg = readPackageJsonIfExists(dir);
2513
+ return pkg?.workspaces !== undefined;
2514
+ });
2515
+ if (byWorkspaces) {
2516
+ rootLogger.debug('Found workspace root by workspaces field', { root: byWorkspaces });
2517
+ return byWorkspaces;
2518
+ }
2519
+ const byPackage = findNearestPackageJson(startPath);
2520
+ if (byPackage) {
2521
+ rootLogger.debug('Found workspace root by package.json', { root: byPackage });
2522
+ }
2523
+ else {
2524
+ rootLogger.debug('Workspace root not found');
2525
+ }
2526
+ return byPackage;
2527
+ }
2528
+ /**
2529
+ * Generic root finder - walk up looking for any marker file.
2530
+ *
2531
+ * @param startPath - Starting path
2532
+ * @param markers - Files to search for
2533
+ * @returns Root directory path or null
2534
+ */
2535
+ function findRootDirectory(startPath, markers) {
2536
+ return locateByMarkers(startPath, markers);
2537
+ }
2538
+ /**
2539
+ * Find nearest .git directory (repo root).
2540
+ *
2541
+ * @param startPath - Starting path
2542
+ * @returns Git root path or null
2543
+ */
2544
+ function findGitRoot(startPath) {
2545
+ return locateByMarkers(startPath, ['.git']);
2546
+ }
2547
+
2548
+ export { CONFIG_PATTERNS, ROOT_MARKERS, WORKSPACE_MARKERS, clearConfigDetectionCache, detectConfigs, findConfigFile, findDirectories, findFiles, findFilesInTree, findGitRoot, findNearestPackageJson, findProjectRoot, findRootDirectory, findWorkspaceRoot, getAllDependencies, getConfigPaths, getConfigPatternsByType, getDependencies, getDependencyVersion, getDevDependencies, getInstalledVersion, getPeerDependencies, getProductionDependencies, getWorkspaces, hasDependency, hasInstalledPackage, hasWorkspaces, parseConfig, parseJsonConfig, parseYamlConfig, readConfigIfExists, readPackageJson, readPackageJsonIfExists, walkDirectory, walkTree };
2549
+ //# sourceMappingURL=index.esm.js.map