@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,2286 @@
1
+ import { existsSync, readFileSync, mkdirSync, writeFileSync, statSync, lstatSync, readdirSync, rmSync, realpathSync, mkdtempSync, unlinkSync, rmdirSync } from 'node:fs';
2
+ import { dirname, join as join$1, posix, normalize, sep, isAbsolute as isAbsolute$1, relative, resolve, basename, extname, parse as parse$1 } from 'node:path';
3
+ import { tmpdir, platform, arch } from 'node:os';
4
+
5
+ /**
6
+ * Safe copies of Error built-ins via factory functions.
7
+ *
8
+ * Since constructors cannot be safely captured via Object.assign, this module
9
+ * provides factory functions that use Reflect.construct internally.
10
+ *
11
+ * These references are captured at module initialization time to protect against
12
+ * prototype pollution attacks. Import only what you need for tree-shaking.
13
+ *
14
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
15
+ */
16
+ // Capture references at module initialization time
17
+ const _Error = globalThis.Error;
18
+ const _Reflect$2 = globalThis.Reflect;
19
+ /**
20
+ * (Safe copy) Creates a new Error using the captured Error constructor.
21
+ * Use this instead of `new Error()`.
22
+ *
23
+ * @param message - Optional error message.
24
+ * @param options - Optional error options.
25
+ * @returns A new Error instance.
26
+ */
27
+ const createError = (message, options) => _Reflect$2.construct(_Error, [message, options]);
28
+
29
+ /**
30
+ * Safe copies of JSON built-in methods.
31
+ *
32
+ * These references are captured at module initialization time to protect against
33
+ * prototype pollution attacks. Import only what you need for tree-shaking.
34
+ *
35
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/json
36
+ */
37
+ // Capture references at module initialization time
38
+ const _JSON = globalThis.JSON;
39
+ /**
40
+ * (Safe copy) Converts a JavaScript Object Notation (JSON) string into an object.
41
+ */
42
+ const parse = _JSON.parse;
43
+ /**
44
+ * (Safe copy) Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
45
+ */
46
+ const stringify = _JSON.stringify;
47
+
48
+ /**
49
+ * Safe copies of Object built-in methods.
50
+ *
51
+ * These references are captured at module initialization time to protect against
52
+ * prototype pollution attacks. Import only what you need for tree-shaking.
53
+ *
54
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
55
+ */
56
+ // Capture references at module initialization time
57
+ const _Object = globalThis.Object;
58
+ /**
59
+ * (Safe copy) Prevents modification of existing property attributes and values,
60
+ * and prevents the addition of new properties.
61
+ */
62
+ const freeze = _Object.freeze;
63
+ /**
64
+ * (Safe copy) Returns the names of the enumerable string properties and methods of an object.
65
+ */
66
+ const keys = _Object.keys;
67
+ /**
68
+ * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
69
+ */
70
+ const entries = _Object.entries;
71
+ /**
72
+ * (Safe copy) Adds a property to an object, or modifies attributes of an existing property.
73
+ */
74
+ const defineProperty = _Object.defineProperty;
75
+ /**
76
+ * (Safe copy) Adds one or more properties to an object, and/or modifies attributes of existing properties.
77
+ */
78
+ const defineProperties = _Object.defineProperties;
79
+
80
+ /**
81
+ * Safe copies of Array built-in static methods.
82
+ *
83
+ * These references are captured at module initialization time to protect against
84
+ * prototype pollution attacks. Import only what you need for tree-shaking.
85
+ *
86
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/array
87
+ */
88
+ // Capture references at module initialization time
89
+ const _Array = globalThis.Array;
90
+ /**
91
+ * (Safe copy) Determines whether the passed value is an Array.
92
+ */
93
+ const isArray = _Array.isArray;
94
+
95
+ /**
96
+ * Safe copies of Console built-in methods.
97
+ *
98
+ * These references are captured at module initialization time to protect against
99
+ * prototype pollution attacks. Import only what you need for tree-shaking.
100
+ *
101
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/console
102
+ */
103
+ // Capture references at module initialization time
104
+ const _console = globalThis.console;
105
+ /**
106
+ * (Safe copy) Outputs a message to the console.
107
+ */
108
+ const log = _console.log.bind(_console);
109
+ /**
110
+ * (Safe copy) Outputs a warning message to the console.
111
+ */
112
+ const warn = _console.warn.bind(_console);
113
+ /**
114
+ * (Safe copy) Outputs an error message to the console.
115
+ */
116
+ const error = _console.error.bind(_console);
117
+ /**
118
+ * (Safe copy) Outputs an informational message to the console.
119
+ */
120
+ const info = _console.info.bind(_console);
121
+ /**
122
+ * (Safe copy) Outputs a debug message to the console.
123
+ */
124
+ const debug = _console.debug.bind(_console);
125
+ /**
126
+ * (Safe copy) Outputs a stack trace to the console.
127
+ */
128
+ _console.trace.bind(_console);
129
+ /**
130
+ * (Safe copy) Displays an interactive listing of the properties of a specified object.
131
+ */
132
+ _console.dir.bind(_console);
133
+ /**
134
+ * (Safe copy) Displays tabular data as a table.
135
+ */
136
+ _console.table.bind(_console);
137
+ /**
138
+ * (Safe copy) Writes an error message to the console if the assertion is false.
139
+ */
140
+ _console.assert.bind(_console);
141
+ /**
142
+ * (Safe copy) Clears the console.
143
+ */
144
+ _console.clear.bind(_console);
145
+ /**
146
+ * (Safe copy) Logs the number of times that this particular call to count() has been called.
147
+ */
148
+ _console.count.bind(_console);
149
+ /**
150
+ * (Safe copy) Resets the counter used with console.count().
151
+ */
152
+ _console.countReset.bind(_console);
153
+ /**
154
+ * (Safe copy) Creates a new inline group in the console.
155
+ */
156
+ _console.group.bind(_console);
157
+ /**
158
+ * (Safe copy) Creates a new inline group in the console that is initially collapsed.
159
+ */
160
+ _console.groupCollapsed.bind(_console);
161
+ /**
162
+ * (Safe copy) Exits the current inline group.
163
+ */
164
+ _console.groupEnd.bind(_console);
165
+ /**
166
+ * (Safe copy) Starts a timer with a name specified as an input parameter.
167
+ */
168
+ _console.time.bind(_console);
169
+ /**
170
+ * (Safe copy) Stops a timer that was previously started.
171
+ */
172
+ _console.timeEnd.bind(_console);
173
+ /**
174
+ * (Safe copy) Logs the current value of a timer that was previously started.
175
+ */
176
+ _console.timeLog.bind(_console);
177
+
178
+ /**
179
+ * Safe copies of Set built-in via factory function.
180
+ *
181
+ * Since constructors cannot be safely captured via Object.assign, this module
182
+ * provides a factory function that uses Reflect.construct internally.
183
+ *
184
+ * These references are captured at module initialization time to protect against
185
+ * prototype pollution attacks. Import only what you need for tree-shaking.
186
+ *
187
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/set
188
+ */
189
+ // Capture references at module initialization time
190
+ const _Set = globalThis.Set;
191
+ const _Reflect$1 = globalThis.Reflect;
192
+ /**
193
+ * (Safe copy) Creates a new Set using the captured Set constructor.
194
+ * Use this instead of `new Set()`.
195
+ *
196
+ * @param iterable - Optional iterable of values.
197
+ * @returns A new Set instance.
198
+ */
199
+ const createSet = (iterable) => _Reflect$1.construct(_Set, iterable ? [iterable] : []);
200
+
201
+ const registeredClasses = [];
202
+
203
+ /**
204
+ * Returns the data type of the target.
205
+ * Uses native `typeof` operator, however, makes distinction between `null`, `array`, and `object`.
206
+ * Also, when classes are registered via `registerClass`, it checks if objects are instance of any known registered class.
207
+ *
208
+ * @param target - The target to get the data type of.
209
+ * @returns The data type of the target.
210
+ */
211
+ const getType = (target) => {
212
+ if (target === null)
213
+ return 'null';
214
+ const nativeDataType = typeof target;
215
+ if (nativeDataType === 'object') {
216
+ if (isArray(target))
217
+ return 'array';
218
+ for (const registeredClass of registeredClasses) {
219
+ if (target instanceof registeredClass)
220
+ return registeredClass.name;
221
+ }
222
+ }
223
+ return nativeDataType;
224
+ };
225
+
226
+ /**
227
+ * Safe copies of Map built-in via factory function.
228
+ *
229
+ * Since constructors cannot be safely captured via Object.assign, this module
230
+ * provides a factory function that uses Reflect.construct internally.
231
+ *
232
+ * These references are captured at module initialization time to protect against
233
+ * prototype pollution attacks. Import only what you need for tree-shaking.
234
+ *
235
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
236
+ */
237
+ // Capture references at module initialization time
238
+ const _Map = globalThis.Map;
239
+ const _Reflect = globalThis.Reflect;
240
+ /**
241
+ * (Safe copy) Creates a new Map using the captured Map constructor.
242
+ * Use this instead of `new Map()`.
243
+ *
244
+ * @param iterable - Optional iterable of key-value pairs.
245
+ * @returns A new Map instance.
246
+ */
247
+ const createMap = (iterable) => _Reflect.construct(_Map, iterable ? [iterable] : []);
248
+
249
+ /**
250
+ * Safe copies of Math built-in methods.
251
+ *
252
+ * These references are captured at module initialization time to protect against
253
+ * prototype pollution attacks. Import only what you need for tree-shaking.
254
+ *
255
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/math
256
+ */
257
+ // Capture references at module initialization time
258
+ const _Math = globalThis.Math;
259
+ /**
260
+ * (Safe copy) Returns the smaller of zero or more numbers.
261
+ */
262
+ const min = _Math.min;
263
+
264
+ /* eslint-disable @typescript-eslint/no-explicit-any */
265
+ /**
266
+ * Creates a wrapper function that only executes the wrapped function if the condition function returns true.
267
+ *
268
+ * @param func - The function to be conditionally executed.
269
+ * @param conditionFunc - A function that returns a boolean, determining if `func` should be executed.
270
+ * @returns A wrapped version of `func` that executes conditionally.
271
+ */
272
+ function createConditionalExecutionFunction(func, conditionFunc) {
273
+ return function (...args) {
274
+ if (conditionFunc()) {
275
+ return func(...args);
276
+ }
277
+ };
278
+ }
279
+
280
+ /* eslint-disable @typescript-eslint/no-explicit-any */
281
+ /**
282
+ * Creates a wrapper function that silently ignores any errors thrown by the wrapped void function.
283
+ * This function is specifically for wrapping functions that do not return a value (void functions).
284
+ * Exceptions are swallowed without any logging or handling.
285
+ *
286
+ * @param func - The void function to be wrapped.
287
+ * @returns A wrapped version of the input function that ignores errors.
288
+ */
289
+ function createErrorIgnoringFunction(func) {
290
+ return function (...args) {
291
+ try {
292
+ func(...args);
293
+ }
294
+ catch {
295
+ // Deliberately swallowing/ignoring the exception
296
+ }
297
+ };
298
+ }
299
+
300
+ /* eslint-disable @typescript-eslint/no-unused-vars */
301
+ /**
302
+ * A no-operation function (noop) that does nothing regardless of the arguments passed.
303
+ * It is designed to be as permissive as possible in its typing without using the `Function` keyword.
304
+ *
305
+ * @param args - Any arguments passed to the function (ignored)
306
+ */
307
+ const noop = (...args) => {
308
+ // Intentionally does nothing
309
+ };
310
+
311
+ const logLevels = ['none', 'error', 'warn', 'log', 'info', 'debug'];
312
+ const priority = {
313
+ error: 4,
314
+ warn: 3,
315
+ log: 2,
316
+ info: 1,
317
+ debug: 0,
318
+ };
319
+ /**
320
+ * Validates whether a given string is a valid log level.
321
+ *
322
+ * @param level - The log level to validate
323
+ * @returns True if the level is valid, false otherwise
324
+ */
325
+ function isValidLogLevel(level) {
326
+ return logLevels.includes(level);
327
+ }
328
+ /**
329
+ * Creates a log level configuration manager for controlling logging behavior.
330
+ * Provides methods to get, set, and evaluate log levels based on priority.
331
+ *
332
+ * @param level - The initial log level (defaults to 'error')
333
+ * @returns A configuration object with log level management methods
334
+ * @throws {Error} When the provided level is not a valid log level
335
+ */
336
+ function createLogLevelConfig(level = 'error') {
337
+ if (!isValidLogLevel(level)) {
338
+ throw createError('Cannot create log level configuration with a valid default log level');
339
+ }
340
+ const state = { level };
341
+ const getLogLevel = () => state.level;
342
+ const setLogLevel = (level) => {
343
+ if (!isValidLogLevel(level)) {
344
+ throw createError(`Cannot set value '${level}' level. Expected levels are ${logLevels}.`);
345
+ }
346
+ state.level = level;
347
+ };
348
+ const shouldLog = (level) => {
349
+ if (state.level === 'none' || level === 'none' || !isValidLogLevel(level)) {
350
+ return false;
351
+ }
352
+ return priority[level] >= priority[state.level];
353
+ };
354
+ return freeze({
355
+ getLogLevel,
356
+ setLogLevel,
357
+ shouldLog,
358
+ });
359
+ }
360
+
361
+ /**
362
+ * Creates a logger instance with configurable log level filtering.
363
+ * Each log function is wrapped to respect the current log level setting.
364
+ *
365
+ * @param error - Function to handle error-level logs (required)
366
+ * @param warn - Function to handle warning-level logs (optional, defaults to noop)
367
+ * @param log - Function to handle standard logs (optional, defaults to noop)
368
+ * @param info - Function to handle info-level logs (optional, defaults to noop)
369
+ * @param debug - Function to handle debug-level logs (optional, defaults to noop)
370
+ * @returns A frozen logger object with log methods and level control
371
+ * @throws {ErrorLevelFn} When any provided log function is invalid
372
+ */
373
+ function createLogger(error, warn = noop, log = noop, info = noop, debug = noop) {
374
+ if (notValidLogFn(error)) {
375
+ throw createError(notFnMsg('error'));
376
+ }
377
+ if (notValidLogFn(warn)) {
378
+ throw createError(notFnMsg('warn'));
379
+ }
380
+ if (notValidLogFn(log)) {
381
+ throw createError(notFnMsg('log'));
382
+ }
383
+ if (notValidLogFn(info)) {
384
+ throw createError(notFnMsg('info'));
385
+ }
386
+ if (notValidLogFn(debug)) {
387
+ throw createError(notFnMsg('debug'));
388
+ }
389
+ const { setLogLevel, getLogLevel, shouldLog } = createLogLevelConfig();
390
+ const wrapLogFn = (fn, level) => {
391
+ if (fn === noop)
392
+ return fn;
393
+ const condition = () => shouldLog(level);
394
+ return createConditionalExecutionFunction(createErrorIgnoringFunction(fn), condition);
395
+ };
396
+ return freeze({
397
+ error: wrapLogFn(error, 'error'),
398
+ warn: wrapLogFn(warn, 'warn'),
399
+ log: wrapLogFn(log, 'log'),
400
+ info: wrapLogFn(info, 'info'),
401
+ debug: wrapLogFn(debug, 'debug'),
402
+ setLogLevel,
403
+ getLogLevel,
404
+ });
405
+ }
406
+ /**
407
+ * Validates whether a given value is a valid log function.
408
+ *
409
+ * @param fn - The value to validate
410
+ * @returns True if the value is not a function (invalid), false if it is valid
411
+ */
412
+ function notValidLogFn(fn) {
413
+ return getType(fn) !== 'function' && fn !== noop;
414
+ }
415
+ /**
416
+ * Generates an error message for invalid log function parameters.
417
+ *
418
+ * @param label - The name of the log function that failed validation
419
+ * @returns A formatted error message string
420
+ */
421
+ function notFnMsg(label) {
422
+ return `Cannot create a logger when ${label} is not a function`;
423
+ }
424
+
425
+ createLogger(error, warn, log, info, debug);
426
+
427
+ /**
428
+ * Global log level registry.
429
+ * Tracks all created scoped loggers to allow global log level changes.
430
+ */
431
+ const loggerRegistry = createSet();
432
+ /**
433
+ * Current global log level override.
434
+ * When set to a value other than null, all registered loggers use this level.
435
+ */
436
+ let globalLogLevel = null;
437
+ /**
438
+ * Set the log level for all registered scoped loggers.
439
+ * This is useful for enabling verbose logging across the entire library.
440
+ *
441
+ * @param level - The log level to set globally
442
+ *
443
+ * @example
444
+ * ```typescript
445
+ * import { setGlobalLogLevel } from '@hyperfrontend/project-scope/core'
446
+ *
447
+ * // Enable debug logging for all project-scope modules
448
+ * setGlobalLogLevel('debug')
449
+ * ```
450
+ */
451
+ function setGlobalLogLevel(level) {
452
+ globalLogLevel = level;
453
+ for (const logger of loggerRegistry) {
454
+ logger.setLogLevel(level);
455
+ }
456
+ }
457
+ /**
458
+ * Get the current global log level.
459
+ *
460
+ * @returns The global log level, or null if not set
461
+ */
462
+ function getGlobalLogLevel() {
463
+ return globalLogLevel;
464
+ }
465
+ /**
466
+ * Reset the global log level override.
467
+ * Each logger will retain its current level but new loggers will use their default.
468
+ */
469
+ function resetGlobalLogLevel() {
470
+ globalLogLevel = null;
471
+ }
472
+ /** Redacted placeholder for sensitive values */
473
+ const REDACTED = '[REDACTED]';
474
+ /**
475
+ * Patterns that indicate a sensitive key name.
476
+ * Keys containing these patterns will have their values sanitized.
477
+ */
478
+ const SENSITIVE_KEY_PATTERNS = [
479
+ /token/i,
480
+ /key/i,
481
+ /password/i,
482
+ /secret/i,
483
+ /credential/i,
484
+ /auth/i,
485
+ /bearer/i,
486
+ /api[_-]?key/i,
487
+ /private/i,
488
+ /passphrase/i,
489
+ ];
490
+ /**
491
+ * Checks if a key name indicates sensitive data.
492
+ *
493
+ * @param key - Key name to check
494
+ * @returns True if the key indicates sensitive data
495
+ */
496
+ function isSensitiveKey(key) {
497
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
498
+ }
499
+ /**
500
+ * Sanitizes an object by replacing sensitive values with REDACTED.
501
+ * This function recursively processes nested objects and arrays.
502
+ *
503
+ * @param obj - Object to sanitize
504
+ * @returns New object with sensitive values redacted
505
+ */
506
+ function sanitize(obj) {
507
+ if (obj === null || obj === undefined) {
508
+ return obj;
509
+ }
510
+ if (isArray(obj)) {
511
+ return obj.map((item) => sanitize(item));
512
+ }
513
+ if (typeof obj === 'object') {
514
+ const result = {};
515
+ for (const [key, value] of entries(obj)) {
516
+ if (isSensitiveKey(key)) {
517
+ result[key] = REDACTED;
518
+ }
519
+ else if (typeof value === 'object' && value !== null) {
520
+ result[key] = sanitize(value);
521
+ }
522
+ else {
523
+ result[key] = value;
524
+ }
525
+ }
526
+ return result;
527
+ }
528
+ return obj;
529
+ }
530
+ /**
531
+ * Formats a log message with optional metadata.
532
+ *
533
+ * @param namespace - Logger namespace prefix
534
+ * @param message - Log message
535
+ * @param meta - Optional metadata object
536
+ * @returns Formatted log string
537
+ */
538
+ function formatMessage(namespace, message, meta) {
539
+ const prefix = `[${namespace}]`;
540
+ if (meta && keys(meta).length > 0) {
541
+ const sanitizedMeta = sanitize(meta);
542
+ return `${prefix} ${message} ${stringify(sanitizedMeta)}`;
543
+ }
544
+ return `${prefix} ${message}`;
545
+ }
546
+ /**
547
+ * Creates a scoped logger with namespace prefix and optional secret sanitization.
548
+ * All log messages will be prefixed with [namespace] and sensitive metadata
549
+ * values will be automatically redacted.
550
+ *
551
+ * @param namespace - Logger namespace (e.g., 'project-scope', 'analyze')
552
+ * @param options - Logger configuration options
553
+ * @returns A configured scoped logger instance
554
+ *
555
+ * @example
556
+ * ```typescript
557
+ * const logger = createScopedLogger('project-scope')
558
+ * logger.setLogLevel('debug')
559
+ *
560
+ * // Basic logging
561
+ * logger.info('Starting analysis', { path: './project' })
562
+ *
563
+ * // Sensitive data is automatically redacted
564
+ * logger.debug('Config loaded', { apiKey: 'secret123' })
565
+ * // Output: [project-scope] Config loaded {"apiKey":"[REDACTED]"}
566
+ * ```
567
+ */
568
+ function createScopedLogger(namespace, options = {}) {
569
+ const { level = 'error', sanitizeSecrets = true } = options;
570
+ // Create wrapper functions that add namespace prefix and sanitization
571
+ const createLogFn = (baseFn) => (message, meta) => {
572
+ const processedMeta = sanitizeSecrets && meta ? sanitize(meta) : meta;
573
+ baseFn(formatMessage(namespace, message, processedMeta));
574
+ };
575
+ // Create base logger with wrapped functions
576
+ const baseLogger = createLogger(createLogFn(error), createLogFn(warn), createLogFn(log), createLogFn(info), createLogFn(debug));
577
+ // Set initial log level (use global override if set)
578
+ baseLogger.setLogLevel(globalLogLevel ?? level);
579
+ const scopedLogger = freeze({
580
+ error: (message, meta) => baseLogger.error(message, meta),
581
+ warn: (message, meta) => baseLogger.warn(message, meta),
582
+ log: (message, meta) => baseLogger.log(message, meta),
583
+ info: (message, meta) => baseLogger.info(message, meta),
584
+ debug: (message, meta) => baseLogger.debug(message, meta),
585
+ setLogLevel: baseLogger.setLogLevel,
586
+ getLogLevel: baseLogger.getLogLevel,
587
+ });
588
+ // Register logger for global level management
589
+ loggerRegistry.add(scopedLogger);
590
+ return scopedLogger;
591
+ }
592
+ /**
593
+ * Default logger instance for the project-scope library.
594
+ * Use this for general logging within the library.
595
+ *
596
+ * @example
597
+ * ```typescript
598
+ * import { logger } from '@hyperfrontend/project-scope/core'
599
+ *
600
+ * logger.setLogLevel('debug')
601
+ * logger.debug('Analyzing project', { path: './src' })
602
+ * ```
603
+ */
604
+ const logger = createScopedLogger('project-scope');
605
+
606
+ const fsLogger = createScopedLogger('project-scope:fs');
607
+ /**
608
+ * Create a file system error with code and context.
609
+ *
610
+ * @param message - The error message describing what went wrong
611
+ * @param code - The category code for this type of filesystem failure
612
+ * @param context - Additional context including path, operation, and cause
613
+ * @returns A configured Error object with code and context properties
614
+ */
615
+ function createFileSystemError(message, code, context) {
616
+ const error = createError(message);
617
+ defineProperties(error, {
618
+ code: { value: code, enumerable: true },
619
+ context: { value: context, enumerable: true },
620
+ });
621
+ return error;
622
+ }
623
+ /**
624
+ * Read file contents as string.
625
+ *
626
+ * @param filePath - Path to file
627
+ * @param encoding - File encoding (default: utf-8)
628
+ * @returns File contents as string
629
+ * @throws {Error} If file doesn't exist or can't be read
630
+ *
631
+ * @example
632
+ * ```typescript
633
+ * import { readFileContent } from '@hyperfrontend/project-scope'
634
+ *
635
+ * const content = readFileContent('./package.json')
636
+ * console.log(content) // JSON string
637
+ * ```
638
+ */
639
+ function readFileContent(filePath, encoding = 'utf-8') {
640
+ if (!existsSync(filePath)) {
641
+ fsLogger.debug('File not found', { path: filePath });
642
+ throw createFileSystemError(`File not found: ${filePath}`, 'FS_NOT_FOUND', { path: filePath, operation: 'read' });
643
+ }
644
+ try {
645
+ return readFileSync(filePath, { encoding });
646
+ }
647
+ catch (error) {
648
+ fsLogger.warn('Failed to read file', { path: filePath });
649
+ throw createFileSystemError(`Failed to read file: ${filePath}`, 'FS_READ_ERROR', { path: filePath, operation: 'read', cause: error });
650
+ }
651
+ }
652
+ /**
653
+ * Read file contents as Buffer.
654
+ *
655
+ * @param filePath - Path to file
656
+ * @returns File contents as Buffer
657
+ * @throws {Error} If file doesn't exist or can't be read
658
+ */
659
+ function readFileBuffer(filePath) {
660
+ if (!existsSync(filePath)) {
661
+ throw createFileSystemError(`File not found: ${filePath}`, 'FS_NOT_FOUND', { path: filePath, operation: 'read' });
662
+ }
663
+ try {
664
+ return readFileSync(filePath);
665
+ }
666
+ catch (error) {
667
+ throw createFileSystemError(`Failed to read file: ${filePath}`, 'FS_READ_ERROR', { path: filePath, operation: 'read', cause: error });
668
+ }
669
+ }
670
+ /**
671
+ * Read file if exists, return null otherwise.
672
+ *
673
+ * @param filePath - Path to file
674
+ * @param encoding - File encoding (default: utf-8)
675
+ * @returns File contents or null if file doesn't exist
676
+ */
677
+ function readFileIfExists(filePath, encoding = 'utf-8') {
678
+ if (!existsSync(filePath)) {
679
+ return null;
680
+ }
681
+ try {
682
+ return readFileSync(filePath, { encoding });
683
+ }
684
+ catch {
685
+ return null;
686
+ }
687
+ }
688
+ /**
689
+ * Read and parse JSON file.
690
+ *
691
+ * @param filePath - Path to JSON file
692
+ * @param options - Parse options
693
+ * @param options.default - Default value if file not found (if not provided, throws on missing file)
694
+ * @returns Parsed JSON object
695
+ * @throws {Error} If file doesn't exist (when no default provided) or contains invalid JSON
696
+ *
697
+ * @example
698
+ * ```typescript
699
+ * import { readJsonFile } from '@hyperfrontend/project-scope'
700
+ *
701
+ * // Read with type inference
702
+ * interface Config { port: number }
703
+ * const config = readJsonFile<Config>('./config.json')
704
+ *
705
+ * // Read with default fallback
706
+ * const settings = readJsonFile('./settings.json', { default: {} })
707
+ * ```
708
+ */
709
+ function readJsonFile(filePath, options) {
710
+ if (!existsSync(filePath)) {
711
+ if (options && 'default' in options) {
712
+ fsLogger.debug('JSON file not found, using default', { path: filePath });
713
+ return options.default;
714
+ }
715
+ fsLogger.debug('JSON file not found', { path: filePath });
716
+ throw createFileSystemError(`File not found: ${filePath}`, 'FS_NOT_FOUND', { path: filePath, operation: 'read' });
717
+ }
718
+ try {
719
+ const content = readFileSync(filePath, { encoding: 'utf-8' });
720
+ return parse(content);
721
+ }
722
+ catch (error) {
723
+ if (error?.code === 'ENOENT') {
724
+ fsLogger.debug('JSON file not found (ENOENT)', { path: filePath });
725
+ throw createFileSystemError(`File not found: ${filePath}`, 'FS_NOT_FOUND', { path: filePath, operation: 'read', cause: error });
726
+ }
727
+ fsLogger.warn('Failed to parse JSON file', { path: filePath });
728
+ throw createFileSystemError(`Failed to parse JSON file: ${filePath}`, 'FS_PARSE_ERROR', {
729
+ path: filePath,
730
+ operation: 'read',
731
+ cause: error,
732
+ });
733
+ }
734
+ }
735
+ /**
736
+ * Read and parse JSON file if exists, return null otherwise.
737
+ *
738
+ * @param filePath - Path to JSON file
739
+ * @returns Parsed JSON object or null if file doesn't exist or is invalid
740
+ */
741
+ function readJsonFileIfExists(filePath) {
742
+ if (!existsSync(filePath)) {
743
+ return null;
744
+ }
745
+ try {
746
+ const content = readFileSync(filePath, { encoding: 'utf-8' });
747
+ return parse(content);
748
+ }
749
+ catch {
750
+ return null;
751
+ }
752
+ }
753
+
754
+ const fsWriteLogger = createScopedLogger('project-scope:fs:write');
755
+ /**
756
+ * Ensure directory exists, create recursively if not.
757
+ *
758
+ * @param dirPath - Directory path to ensure exists
759
+ */
760
+ function ensureDir(dirPath) {
761
+ if (!existsSync(dirPath)) {
762
+ fsWriteLogger.debug('Creating directory recursively', { path: dirPath });
763
+ mkdirSync(dirPath, { recursive: true });
764
+ }
765
+ }
766
+ /**
767
+ * Write string content to file.
768
+ * Creates parent directories if needed.
769
+ *
770
+ * @param filePath - Absolute or relative path to the target file
771
+ * @param content - String content to write to the file
772
+ * @param options - Optional write configuration (encoding, mode)
773
+ * @throws {Error} If write fails
774
+ *
775
+ * @example
776
+ * ```typescript
777
+ * import { writeFileContent } from '@hyperfrontend/project-scope'
778
+ *
779
+ * // Write a simple text file
780
+ * writeFileContent('./output/data.txt', 'Hello, World!')
781
+ *
782
+ * // Write with custom encoding
783
+ * writeFileContent('./output/data.txt', 'Content', { encoding: 'utf-8' })
784
+ * ```
785
+ */
786
+ function writeFileContent(filePath, content, options) {
787
+ try {
788
+ fsWriteLogger.debug('Writing file content', { path: filePath, size: content.length, encoding: options?.encoding ?? 'utf-8' });
789
+ ensureDir(dirname(filePath));
790
+ writeFileSync(filePath, content, {
791
+ encoding: options?.encoding ?? 'utf-8',
792
+ mode: options?.mode,
793
+ });
794
+ fsWriteLogger.debug('File written successfully', { path: filePath });
795
+ }
796
+ catch (error) {
797
+ fsWriteLogger.warn('Failed to write file', { path: filePath, error: error instanceof Error ? error.message : String(error) });
798
+ throw createFileSystemError(`Failed to write file: ${filePath}`, 'FS_WRITE_ERROR', { path: filePath, operation: 'write', cause: error });
799
+ }
800
+ }
801
+ /**
802
+ * Write Buffer to file.
803
+ * Creates parent directories if needed.
804
+ *
805
+ * @param filePath - Absolute or relative path to the target file
806
+ * @param content - Buffer containing binary data to write
807
+ * @param options - Optional write configuration (mode)
808
+ * @throws {Error} If write fails
809
+ */
810
+ function writeFileBuffer(filePath, content, options) {
811
+ try {
812
+ fsWriteLogger.debug('Writing file buffer', { path: filePath, size: content.length });
813
+ ensureDir(dirname(filePath));
814
+ writeFileSync(filePath, content, { mode: options?.mode });
815
+ fsWriteLogger.debug('Buffer written successfully', { path: filePath });
816
+ }
817
+ catch (error) {
818
+ fsWriteLogger.warn('Failed to write buffer', { path: filePath, error: error instanceof Error ? error.message : String(error) });
819
+ throw createFileSystemError(`Failed to write file: ${filePath}`, 'FS_WRITE_ERROR', { path: filePath, operation: 'write', cause: error });
820
+ }
821
+ }
822
+ /**
823
+ * Write JSON data to file with formatting.
824
+ * Creates parent directories if needed.
825
+ *
826
+ * @param filePath - Absolute or relative path to the target JSON file
827
+ * @param data - Object or value to serialize as JSON
828
+ * @param options - Optional write configuration (indent, encoding, mode)
829
+ * @throws {Error} If write fails
830
+ *
831
+ * @example
832
+ * ```typescript
833
+ * import { writeJsonFile } from '@hyperfrontend/project-scope'
834
+ *
835
+ * // Write object to JSON file
836
+ * writeJsonFile('./config.json', { port: 3000, debug: true })
837
+ *
838
+ * // Write with custom indentation
839
+ * writeJsonFile('./config.json', data, { indent: 4 })
840
+ * ```
841
+ */
842
+ function writeJsonFile(filePath, data, options) {
843
+ try {
844
+ fsWriteLogger.debug('Writing JSON file', { path: filePath, indent: options?.indent ?? 2 });
845
+ const indent = options?.indent ?? 2;
846
+ const content = stringify(data, null, indent) + '\n';
847
+ writeFileContent(filePath, content, options);
848
+ fsWriteLogger.debug('JSON file written successfully', { path: filePath });
849
+ }
850
+ catch (error) {
851
+ if (error?.code === 'FS_WRITE_ERROR') {
852
+ throw error;
853
+ }
854
+ fsWriteLogger.warn('Failed to write JSON file', { path: filePath, error: error instanceof Error ? error.message : String(error) });
855
+ throw createFileSystemError(`Failed to write JSON file: ${filePath}`, 'FS_WRITE_ERROR', {
856
+ path: filePath,
857
+ operation: 'write',
858
+ cause: error,
859
+ });
860
+ }
861
+ }
862
+
863
+ /**
864
+ * Get file stats with error handling.
865
+ *
866
+ * @param filePath - Path to file
867
+ * @param followSymlinks - Whether to follow symlinks (default: true)
868
+ * @returns File stats or null if path doesn't exist
869
+ */
870
+ function getFileStat(filePath, followSymlinks = true) {
871
+ if (!existsSync(filePath)) {
872
+ return null;
873
+ }
874
+ try {
875
+ const stat = followSymlinks ? statSync(filePath) : lstatSync(filePath);
876
+ return {
877
+ isFile: stat.isFile(),
878
+ isDirectory: stat.isDirectory(),
879
+ isSymlink: stat.isSymbolicLink(),
880
+ size: stat.size,
881
+ created: stat.birthtime,
882
+ modified: stat.mtime,
883
+ accessed: stat.atime,
884
+ mode: stat.mode,
885
+ };
886
+ }
887
+ catch {
888
+ return null;
889
+ }
890
+ }
891
+ /**
892
+ * Check if path is a file.
893
+ *
894
+ * @param filePath - Path to check
895
+ * @returns True if path is a file
896
+ */
897
+ function isFile(filePath) {
898
+ const stats = getFileStat(filePath);
899
+ return stats?.isFile ?? false;
900
+ }
901
+ /**
902
+ * Check if path is a directory.
903
+ *
904
+ * @param dirPath - Path to check
905
+ * @returns True if path is a directory
906
+ */
907
+ function isDirectory(dirPath) {
908
+ const stats = getFileStat(dirPath);
909
+ return stats?.isDirectory ?? false;
910
+ }
911
+ /**
912
+ * Check if path is a symbolic link.
913
+ *
914
+ * @param linkPath - Path to check
915
+ * @returns True if path is a symlink
916
+ */
917
+ function isSymlink(linkPath) {
918
+ const stats = getFileStat(linkPath, false);
919
+ return stats?.isSymlink ?? false;
920
+ }
921
+ /**
922
+ * Check if path exists.
923
+ *
924
+ * @param filePath - Path to check
925
+ * @returns True if path exists
926
+ */
927
+ function exists(filePath) {
928
+ return existsSync(filePath);
929
+ }
930
+
931
+ const fsDirLogger = createScopedLogger('project-scope:fs:dir');
932
+ /**
933
+ * List immediate contents of a directory.
934
+ *
935
+ * @param dirPath - Absolute or relative path to the directory
936
+ * @returns Array of entries with metadata for each file/directory
937
+ * @throws {Error} If directory doesn't exist or isn't a directory
938
+ *
939
+ * @example
940
+ * ```typescript
941
+ * import { readDirectory } from '@hyperfrontend/project-scope'
942
+ *
943
+ * const entries = readDirectory('./src')
944
+ * for (const entry of entries) {
945
+ * console.log(entry.name, entry.isFile ? 'file' : 'directory')
946
+ * }
947
+ * ```
948
+ */
949
+ function readDirectory(dirPath) {
950
+ fsDirLogger.debug('Reading directory', { path: dirPath });
951
+ if (!existsSync(dirPath)) {
952
+ fsDirLogger.debug('Directory not found', { path: dirPath });
953
+ throw createFileSystemError(`Directory not found: ${dirPath}`, 'FS_NOT_FOUND', { path: dirPath, operation: 'readdir' });
954
+ }
955
+ if (!isDirectory(dirPath)) {
956
+ fsDirLogger.debug('Path is not a directory', { path: dirPath });
957
+ throw createFileSystemError(`Not a directory: ${dirPath}`, 'FS_NOT_A_DIRECTORY', { path: dirPath, operation: 'readdir' });
958
+ }
959
+ try {
960
+ const entries = readdirSync(dirPath, { withFileTypes: true });
961
+ fsDirLogger.debug('Directory read complete', { path: dirPath, entryCount: entries.length });
962
+ return entries.map((entry) => ({
963
+ name: entry.name,
964
+ path: join$1(dirPath, entry.name),
965
+ isFile: entry.isFile(),
966
+ isDirectory: entry.isDirectory(),
967
+ isSymlink: entry.isSymbolicLink(),
968
+ }));
969
+ }
970
+ catch (error) {
971
+ fsDirLogger.warn('Failed to read directory', { path: dirPath, error: error instanceof Error ? error.message : String(error) });
972
+ throw createFileSystemError(`Failed to read directory: ${dirPath}`, 'FS_READ_ERROR', {
973
+ path: dirPath,
974
+ operation: 'readdir',
975
+ cause: error,
976
+ });
977
+ }
978
+ }
979
+ /**
980
+ * List directory contents recursively with depth tracking.
981
+ *
982
+ * @param dirPath - Root directory path to start traversal
983
+ * @param options - Configuration for depth limit, hidden files, and symlinks
984
+ * @returns Flat array of all entries found during traversal
985
+ *
986
+ * @example
987
+ * ```typescript
988
+ * import { readDirectoryRecursive } from '@hyperfrontend/project-scope'
989
+ *
990
+ * // List all files up to 3 levels deep
991
+ * const entries = readDirectoryRecursive('./src', { maxDepth: 3 })
992
+ *
993
+ * // Include hidden files
994
+ * const allEntries = readDirectoryRecursive('./project', { includeHidden: true })
995
+ * ```
996
+ */
997
+ function readDirectoryRecursive(dirPath, options) {
998
+ const maxDepth = options?.maxDepth ?? Infinity;
999
+ const includeHidden = options?.includeHidden ?? false;
1000
+ const followSymlinks = options?.followSymlinks ?? false;
1001
+ fsDirLogger.debug('Starting recursive directory read', {
1002
+ path: dirPath,
1003
+ maxDepth: maxDepth === Infinity ? 'unlimited' : maxDepth,
1004
+ includeHidden,
1005
+ followSymlinks,
1006
+ });
1007
+ const results = [];
1008
+ /**
1009
+ * Recursively walk directories and collect entries.
1010
+ *
1011
+ * @param currentPath - Current directory being processed
1012
+ * @param depth - Current depth level from the starting directory
1013
+ */
1014
+ function walk(currentPath, depth) {
1015
+ if (depth > maxDepth) {
1016
+ fsDirLogger.debug('Max depth reached, skipping', { path: currentPath, depth, maxDepth });
1017
+ return;
1018
+ }
1019
+ let entries;
1020
+ try {
1021
+ entries = readDirectory(currentPath);
1022
+ }
1023
+ catch {
1024
+ // Skip inaccessible directories
1025
+ fsDirLogger.debug('Skipping inaccessible directory', { path: currentPath });
1026
+ return;
1027
+ }
1028
+ for (const entry of entries) {
1029
+ // Skip hidden files/dirs if not included
1030
+ if (!includeHidden && entry.name.startsWith('.')) {
1031
+ continue;
1032
+ }
1033
+ results.push({ ...entry, depth });
1034
+ // Recurse into directories
1035
+ if (entry.isDirectory || (entry.isSymlink && followSymlinks && isDirectory(entry.path))) {
1036
+ walk(entry.path, depth + 1);
1037
+ }
1038
+ }
1039
+ }
1040
+ walk(dirPath, 0);
1041
+ fsDirLogger.debug('Recursive directory read complete', { path: dirPath, totalEntries: results.length });
1042
+ return results;
1043
+ }
1044
+ /**
1045
+ * Create a directory, optionally creating parent directories.
1046
+ *
1047
+ * @param dirPath - Path where the directory should be created
1048
+ * @param options - Creation options
1049
+ * @param options.recursive - Create parent directories if missing (default: true)
1050
+ */
1051
+ function createDirectory(dirPath, options) {
1052
+ const recursive = options?.recursive ?? true;
1053
+ fsDirLogger.debug('Creating directory', { path: dirPath, recursive });
1054
+ mkdirSync(dirPath, { recursive });
1055
+ }
1056
+ /**
1057
+ * Delete a directory from the filesystem.
1058
+ *
1059
+ * @param dirPath - Path to the directory to remove
1060
+ * @param options - Removal configuration
1061
+ * @param options.recursive - Delete directory contents recursively
1062
+ * @param options.force - Ignore errors if directory doesn't exist
1063
+ */
1064
+ function removeDirectory(dirPath, options) {
1065
+ fsDirLogger.debug('Removing directory', { path: dirPath, recursive: options?.recursive, force: options?.force });
1066
+ rmSync(dirPath, {
1067
+ recursive: options?.recursive ?? false,
1068
+ force: options?.force ?? false,
1069
+ });
1070
+ }
1071
+
1072
+ /**
1073
+ * Join path segments.
1074
+ * Uses platform-specific separators (e.g., / or \).
1075
+ *
1076
+ * @param paths - Path segments to join
1077
+ * @returns Joined path
1078
+ */
1079
+ function join(...paths) {
1080
+ return join$1(...paths);
1081
+ }
1082
+ /**
1083
+ * Join path segments using POSIX separators (/).
1084
+ * Always uses forward slashes regardless of platform.
1085
+ *
1086
+ * @param paths - Path segments to join
1087
+ * @returns Joined path with forward slashes
1088
+ */
1089
+ function joinPosix(...paths) {
1090
+ return posix.join(...paths);
1091
+ }
1092
+
1093
+ /**
1094
+ * Normalize path separators to forward slashes.
1095
+ *
1096
+ * @param filePath - Path to normalize
1097
+ * @returns Normalized path with forward slashes
1098
+ */
1099
+ function normalizePath(filePath) {
1100
+ if (!filePath)
1101
+ return '';
1102
+ // Normalize path and convert backslashes to forward slashes
1103
+ const normalized = normalize(filePath);
1104
+ return sep === '\\' ? normalized.replace(/\\/g, '/') : normalized;
1105
+ }
1106
+ /**
1107
+ * Convert path separators to forward slashes using POSIX style.
1108
+ * Resolves `.` and `..` segments for cross-platform configuration.
1109
+ *
1110
+ * @param filePath - The input path to convert
1111
+ * @returns Path with forward slashes and resolved segments
1112
+ */
1113
+ function normalizeToForwardSlashes(filePath) {
1114
+ if (!filePath)
1115
+ return '';
1116
+ return normalize(filePath).split(sep).join('/');
1117
+ }
1118
+ /**
1119
+ * Convert path to use the operating system's native separator.
1120
+ *
1121
+ * @param filePath - The input path to convert
1122
+ * @returns Path with native separators (backslash on Windows, forward slash elsewhere)
1123
+ */
1124
+ function normalizeToNative(filePath) {
1125
+ if (!filePath)
1126
+ return '';
1127
+ return normalize(filePath.replace(/[/\\]/g, sep));
1128
+ }
1129
+ /**
1130
+ * Strip any trailing forward or back slashes from a path.
1131
+ *
1132
+ * @param filePath - Path that may have trailing slashes
1133
+ * @returns Path with trailing slashes removed
1134
+ */
1135
+ function removeTrailingSlash(filePath) {
1136
+ return filePath.replace(/[/\\]+$/, '');
1137
+ }
1138
+ /**
1139
+ * Append a forward slash to the path if not already present.
1140
+ *
1141
+ * @param filePath - Path to process
1142
+ * @returns Path with trailing forward slash
1143
+ */
1144
+ function ensureTrailingSlash(filePath) {
1145
+ const normalized = removeTrailingSlash(filePath);
1146
+ return normalized + '/';
1147
+ }
1148
+
1149
+ /**
1150
+ * Resolve path segments to an absolute path.
1151
+ *
1152
+ * @param segments - Path segments to resolve
1153
+ * @returns Resolved absolute path with normalized separators
1154
+ */
1155
+ function resolvePath(...segments) {
1156
+ return normalizePath(resolve(...segments));
1157
+ }
1158
+ /**
1159
+ * Resolve path relative to workspace root.
1160
+ *
1161
+ * @param workspaceRoot - Workspace root directory
1162
+ * @param segments - Path segments relative to workspace
1163
+ * @returns Resolved absolute path with normalized separators
1164
+ */
1165
+ function resolveFromWorkspace(workspaceRoot, ...segments) {
1166
+ return normalizePath(resolve(workspaceRoot, ...segments));
1167
+ }
1168
+ /**
1169
+ * Resolve symlinks to real path.
1170
+ *
1171
+ * @param filePath - Path to resolve
1172
+ * @returns Real path or null if path doesn't exist
1173
+ */
1174
+ function resolveRealPath(filePath) {
1175
+ if (!exists(filePath)) {
1176
+ return null;
1177
+ }
1178
+ try {
1179
+ return normalizePath(realpathSync(filePath));
1180
+ }
1181
+ catch {
1182
+ return null;
1183
+ }
1184
+ }
1185
+ /**
1186
+ * Compute the normalized path from source directory to target.
1187
+ *
1188
+ * @param from - Source path (base directory)
1189
+ * @param to - Target path to reach
1190
+ * @returns Relative path from source to target with forward slashes
1191
+ */
1192
+ function relativePath(from, to) {
1193
+ return normalizePath(relative(from, to));
1194
+ }
1195
+ /**
1196
+ * Join path segments.
1197
+ *
1198
+ * @param segments - Path segments to join
1199
+ * @returns Joined path with normalized separators
1200
+ */
1201
+ function joinPath(...segments) {
1202
+ return normalizePath(join$1(...segments));
1203
+ }
1204
+ /**
1205
+ * Check if path is absolute.
1206
+ *
1207
+ * @param filePath - Path to check
1208
+ * @returns True if path is absolute
1209
+ */
1210
+ function isAbsolute(filePath) {
1211
+ return isAbsolute$1(filePath);
1212
+ }
1213
+ /**
1214
+ * Calculate offset from root (e.g., "../../../").
1215
+ *
1216
+ * @param filePath - Path to calculate offset for
1217
+ * @returns Relative offset path (e.g., "../../")
1218
+ */
1219
+ function offsetFromRoot(filePath) {
1220
+ const segments = normalizePath(filePath).split('/').filter(Boolean);
1221
+ if (segments.length === 0)
1222
+ return '';
1223
+ return segments.map(() => '..').join('/') + '/';
1224
+ }
1225
+
1226
+ /**
1227
+ * Split path into segments.
1228
+ *
1229
+ * @param filePath - Path to split
1230
+ * @returns Array of path segments
1231
+ */
1232
+ function pathSegments(filePath) {
1233
+ return filePath.split(/[/\\]/).filter((segment) => segment.length > 0);
1234
+ }
1235
+ /**
1236
+ * Get basename of path.
1237
+ *
1238
+ * @param filePath - Path to extract basename from
1239
+ * @param ext - Optional extension to strip
1240
+ * @returns Basename of path
1241
+ */
1242
+ function getBasename(filePath, ext) {
1243
+ return basename(filePath, ext);
1244
+ }
1245
+ /**
1246
+ * Get directory name of path.
1247
+ *
1248
+ * @param filePath - Path to extract directory from
1249
+ * @returns Directory name
1250
+ */
1251
+ function getDirname(filePath) {
1252
+ return normalizePath(dirname(filePath));
1253
+ }
1254
+ /**
1255
+ * Get file extension (including dot).
1256
+ *
1257
+ * @param filePath - Path to extract extension from
1258
+ * @returns Extension including dot (e.g., '.ts')
1259
+ */
1260
+ function getExtension(filePath) {
1261
+ return extname(filePath);
1262
+ }
1263
+ /**
1264
+ * Get filename without extension.
1265
+ *
1266
+ * @param filePath - Path to extract name from
1267
+ * @returns Filename without extension
1268
+ */
1269
+ function getFileNameWithoutExtension(filePath) {
1270
+ const parsed = parse$1(filePath);
1271
+ return parsed.name;
1272
+ }
1273
+ /**
1274
+ * Parse path into components.
1275
+ *
1276
+ * @param filePath - Path to parse
1277
+ * @returns Parsed path components
1278
+ */
1279
+ function parsePath(filePath) {
1280
+ const parsed = parse$1(filePath);
1281
+ return {
1282
+ root: parsed.root,
1283
+ dir: normalizePath(parsed.dir),
1284
+ base: parsed.base,
1285
+ ext: parsed.ext,
1286
+ name: parsed.name,
1287
+ };
1288
+ }
1289
+
1290
+ const fsTraversalLogger = createScopedLogger('project-scope:fs:traversal');
1291
+ /**
1292
+ * Generic upward directory traversal.
1293
+ * Name avoids similarity to fs.readdir/fs.readdirSync.
1294
+ *
1295
+ * @param startPath - Starting directory
1296
+ * @param predicate - Function to test each directory
1297
+ * @returns First matching directory or null
1298
+ */
1299
+ function traverseUpward(startPath, predicate) {
1300
+ fsTraversalLogger.debug('Starting upward traversal', { startPath });
1301
+ let currentPath = resolve(startPath);
1302
+ const rootPath = parse$1(currentPath).root;
1303
+ while (currentPath !== rootPath) {
1304
+ if (predicate(currentPath)) {
1305
+ fsTraversalLogger.debug('Upward traversal found match', { startPath, foundPath: currentPath });
1306
+ return currentPath;
1307
+ }
1308
+ currentPath = dirname(currentPath);
1309
+ }
1310
+ // Check root directory
1311
+ if (predicate(rootPath)) {
1312
+ fsTraversalLogger.debug('Upward traversal found match at root', { startPath, foundPath: rootPath });
1313
+ return rootPath;
1314
+ }
1315
+ fsTraversalLogger.debug('Upward traversal found no match', { startPath });
1316
+ return null;
1317
+ }
1318
+ /**
1319
+ * Find directory containing any of the specified marker files.
1320
+ *
1321
+ * @param startPath - Starting directory
1322
+ * @param markers - Array of marker file names to search for
1323
+ * @returns First directory containing any marker, or null
1324
+ */
1325
+ function locateByMarkers(startPath, markers) {
1326
+ fsTraversalLogger.debug('Locating by markers', { startPath, markers });
1327
+ const result = traverseUpward(startPath, (dir) => markers.some((marker) => exists(join(dir, marker))));
1328
+ if (result) {
1329
+ fsTraversalLogger.debug('Found directory with marker', { startPath, foundPath: result });
1330
+ }
1331
+ return result;
1332
+ }
1333
+ /**
1334
+ * Find directory where predicate returns true, starting from given path.
1335
+ *
1336
+ * @param startPath - Starting directory
1337
+ * @param test - Function to test if directory matches criteria
1338
+ * @returns Matching directory path or null
1339
+ */
1340
+ function findUpwardWhere(startPath, test) {
1341
+ fsTraversalLogger.debug('Finding upward where condition met', { startPath });
1342
+ return traverseUpward(startPath, test);
1343
+ }
1344
+
1345
+ const encodingLogger = createScopedLogger('project-scope:encoding');
1346
+ /** UTF-8 BOM bytes */
1347
+ const UTF8_BOM_BYTES = [0xef, 0xbb, 0xbf];
1348
+ /** UTF-16 LE BOM bytes */
1349
+ const UTF16_LE_BOM_BYTES = [0xff, 0xfe];
1350
+ /** UTF-16 BE BOM bytes */
1351
+ const UTF16_BE_BOM_BYTES = [0xfe, 0xff];
1352
+ /** UTF-8 BOM string */
1353
+ const UTF8_BOM = '\uFEFF';
1354
+ /**
1355
+ * Common binary file signatures.
1356
+ */
1357
+ const BINARY_SIGNATURES = [
1358
+ { signature: [0x89, 0x50, 0x4e, 0x47], description: 'PNG' },
1359
+ { signature: [0xff, 0xd8, 0xff], description: 'JPEG' },
1360
+ { signature: [0x47, 0x49, 0x46, 0x38], description: 'GIF' },
1361
+ { signature: [0x50, 0x4b, 0x03, 0x04], description: 'ZIP' },
1362
+ { signature: [0x1f, 0x8b], description: 'GZIP' },
1363
+ { signature: [0x42, 0x5a, 0x68], description: 'BZIP2' },
1364
+ { signature: [0x7f, 0x45, 0x4c, 0x46], description: 'ELF' },
1365
+ { signature: [0x4d, 0x5a], description: 'EXE' },
1366
+ { signature: [0x25, 0x50, 0x44, 0x46], description: 'PDF' },
1367
+ ];
1368
+ /**
1369
+ * Detect if content is likely text or binary with encoding information.
1370
+ *
1371
+ * @param buffer - Buffer to analyze
1372
+ * @returns Encoding information
1373
+ */
1374
+ function detectEncodingInfo(buffer) {
1375
+ encodingLogger.debug('Detecting encoding info', { bufferSize: buffer.length });
1376
+ // Check for UTF-8 BOM
1377
+ if (buffer.length >= 3) {
1378
+ if (buffer[0] === UTF8_BOM_BYTES[0] && buffer[1] === UTF8_BOM_BYTES[1] && buffer[2] === UTF8_BOM_BYTES[2]) {
1379
+ encodingLogger.debug('Detected UTF-8 BOM');
1380
+ return { type: 'text', encoding: 'utf-8', hasBom: true };
1381
+ }
1382
+ }
1383
+ // Check for UTF-16 BOMs
1384
+ if (buffer.length >= 2) {
1385
+ if (buffer[0] === UTF16_BE_BOM_BYTES[0] && buffer[1] === UTF16_BE_BOM_BYTES[1]) {
1386
+ encodingLogger.debug('Detected UTF-16 BE BOM');
1387
+ return { type: 'text', encoding: 'utf16le', hasBom: true }; // Node treats BE through utf16le
1388
+ }
1389
+ if (buffer[0] === UTF16_LE_BOM_BYTES[0] && buffer[1] === UTF16_LE_BOM_BYTES[1]) {
1390
+ encodingLogger.debug('Detected UTF-16 LE BOM');
1391
+ return { type: 'text', encoding: 'utf16le', hasBom: true };
1392
+ }
1393
+ }
1394
+ // Check for binary signatures
1395
+ for (const { signature, description } of BINARY_SIGNATURES) {
1396
+ if (buffer.length >= signature.length) {
1397
+ let matches = true;
1398
+ for (let i = 0; i < signature.length; i++) {
1399
+ if (buffer[i] !== signature[i]) {
1400
+ matches = false;
1401
+ break;
1402
+ }
1403
+ }
1404
+ if (matches) {
1405
+ encodingLogger.debug('Detected binary format by signature', { format: description });
1406
+ return { type: 'binary', format: description };
1407
+ }
1408
+ }
1409
+ }
1410
+ // Check for null bytes (usually indicates binary)
1411
+ const sampleSize = min(buffer.length, 8000);
1412
+ for (let i = 0; i < sampleSize; i++) {
1413
+ if (buffer[i] === 0) {
1414
+ encodingLogger.debug('Detected binary content (null byte found)', { position: i });
1415
+ return { type: 'binary' };
1416
+ }
1417
+ }
1418
+ encodingLogger.debug('Detected text content (UTF-8 default)');
1419
+ return { type: 'text', encoding: 'utf-8', hasBom: false };
1420
+ }
1421
+ /**
1422
+ * Detect file encoding from BOM or content analysis.
1423
+ *
1424
+ * @param buffer - Buffer to analyze
1425
+ * @returns Detected encoding, defaults to 'utf-8'
1426
+ */
1427
+ function detectEncoding(buffer) {
1428
+ if (buffer.length >= 3) {
1429
+ // Check for UTF-8 BOM
1430
+ if (buffer[0] === UTF8_BOM_BYTES[0] && buffer[1] === UTF8_BOM_BYTES[1] && buffer[2] === UTF8_BOM_BYTES[2]) {
1431
+ return 'utf-8';
1432
+ }
1433
+ }
1434
+ if (buffer.length >= 2) {
1435
+ // Check for UTF-16 LE BOM
1436
+ if (buffer[0] === UTF16_LE_BOM_BYTES[0] && buffer[1] === UTF16_LE_BOM_BYTES[1]) {
1437
+ return 'utf16le';
1438
+ }
1439
+ // Check for UTF-16 BE BOM
1440
+ if (buffer[0] === UTF16_BE_BOM_BYTES[0] && buffer[1] === UTF16_BE_BOM_BYTES[1]) {
1441
+ return 'utf16le'; // Node.js handles BE through utf16le
1442
+ }
1443
+ }
1444
+ // Default to UTF-8
1445
+ return 'utf-8';
1446
+ }
1447
+ /**
1448
+ * Check if buffer starts with a BOM.
1449
+ *
1450
+ * @param buffer - Buffer to check
1451
+ * @returns True if buffer has a BOM
1452
+ */
1453
+ function hasBom(buffer) {
1454
+ if (buffer.length >= 3) {
1455
+ if (buffer[0] === UTF8_BOM_BYTES[0] && buffer[1] === UTF8_BOM_BYTES[1] && buffer[2] === UTF8_BOM_BYTES[2]) {
1456
+ return true;
1457
+ }
1458
+ }
1459
+ if (buffer.length >= 2) {
1460
+ if ((buffer[0] === UTF16_LE_BOM_BYTES[0] && buffer[1] === UTF16_LE_BOM_BYTES[1]) ||
1461
+ (buffer[0] === UTF16_BE_BOM_BYTES[0] && buffer[1] === UTF16_BE_BOM_BYTES[1])) {
1462
+ return true;
1463
+ }
1464
+ }
1465
+ return false;
1466
+ }
1467
+ /**
1468
+ * Check if buffer represents text content.
1469
+ *
1470
+ * @param buffer - Buffer to check
1471
+ * @returns True if the buffer appears to be text
1472
+ */
1473
+ function isTextFile(buffer) {
1474
+ return detectEncodingInfo(buffer).type === 'text';
1475
+ }
1476
+ /**
1477
+ * Check if buffer represents binary content.
1478
+ *
1479
+ * @param buffer - Buffer to check
1480
+ * @returns True if the buffer appears to be binary
1481
+ */
1482
+ function isBinaryFile(buffer) {
1483
+ return detectEncodingInfo(buffer).type === 'binary';
1484
+ }
1485
+
1486
+ const convertLogger = createScopedLogger('project-scope:encoding:convert');
1487
+ /**
1488
+ * Convert content to UTF-8 string.
1489
+ *
1490
+ * @param content - Buffer or string content
1491
+ * @param sourceEncoding - Source encoding (auto-detected if not provided)
1492
+ * @returns UTF-8 string
1493
+ */
1494
+ function toUtf8(content, sourceEncoding = 'utf-8') {
1495
+ if (typeof content === 'string') {
1496
+ return content;
1497
+ }
1498
+ return content.toString(sourceEncoding);
1499
+ }
1500
+ /**
1501
+ * Convert buffer to string with encoding detection.
1502
+ *
1503
+ * @param content - Buffer to convert
1504
+ * @param encoding - Optional encoding override (auto-detected if not provided)
1505
+ * @returns Converted string
1506
+ * @throws {Error} If content is binary and cannot be converted
1507
+ */
1508
+ function bufferToString(content, encoding) {
1509
+ convertLogger.debug('Converting buffer to string', { bufferSize: content.length, providedEncoding: encoding });
1510
+ if (encoding) {
1511
+ convertLogger.debug('Using provided encoding', { encoding });
1512
+ return content.toString(encoding);
1513
+ }
1514
+ // Auto-detect and convert
1515
+ const info = detectEncodingInfo(content);
1516
+ if (info.type === 'text') {
1517
+ // Remove BOM if present
1518
+ let offset = 0;
1519
+ if (info.hasBom) {
1520
+ offset = info.encoding === 'utf-8' ? 3 : 2;
1521
+ convertLogger.debug('Stripping BOM from buffer', { encoding: info.encoding, bomOffset: offset });
1522
+ }
1523
+ return content.subarray(offset).toString(info.encoding);
1524
+ }
1525
+ convertLogger.warn('Cannot convert binary content to string', { format: info.type === 'binary' ? info.format : undefined });
1526
+ throw createError('Cannot convert binary content to string');
1527
+ }
1528
+ /**
1529
+ * Strip BOM from start of string if present.
1530
+ *
1531
+ * @param content - String that may have BOM
1532
+ * @returns String without BOM
1533
+ */
1534
+ function stripBom(content) {
1535
+ if (content.charCodeAt(0) === 0xfeff) {
1536
+ return content.slice(1);
1537
+ }
1538
+ return content;
1539
+ }
1540
+ /**
1541
+ * Add UTF-8 BOM to string if not present.
1542
+ *
1543
+ * @param content - String to add BOM to
1544
+ * @returns String with BOM
1545
+ */
1546
+ function addBom(content) {
1547
+ if (content.charCodeAt(0) === 0xfeff) {
1548
+ return content;
1549
+ }
1550
+ return UTF8_BOM + content;
1551
+ }
1552
+
1553
+ /**
1554
+ * Cached platform info (computed once).
1555
+ */
1556
+ let cachedPlatformInfo = null;
1557
+ /**
1558
+ * Cached case sensitivity result.
1559
+ */
1560
+ let cachedCaseSensitive = null;
1561
+ /**
1562
+ * Detect if file system is case sensitive.
1563
+ *
1564
+ * @returns True if file system is case-sensitive
1565
+ */
1566
+ function detectCaseSensitivity() {
1567
+ if (cachedCaseSensitive !== null) {
1568
+ return cachedCaseSensitive;
1569
+ }
1570
+ // Quick check based on platform
1571
+ if (process.platform === 'win32') {
1572
+ cachedCaseSensitive = false;
1573
+ return false;
1574
+ }
1575
+ // macOS is typically case-insensitive by default
1576
+ if (process.platform === 'darwin') {
1577
+ // Could be case-sensitive HFS+/APFS, but assume insensitive by default
1578
+ cachedCaseSensitive = false;
1579
+ return false;
1580
+ }
1581
+ // Test actual file system behavior for Linux and others
1582
+ // Use mkdtempSync to create a secure temporary directory
1583
+ let secureTestDir = null;
1584
+ try {
1585
+ secureTestDir = mkdtempSync(join$1(tmpdir(), 'case-sensitivity-test-'));
1586
+ const testFile = join$1(secureTestDir, 'A');
1587
+ const testFileLower = join$1(secureTestDir, 'a');
1588
+ writeFileSync(testFile, '');
1589
+ cachedCaseSensitive = !existsSync(testFileLower);
1590
+ unlinkSync(testFile);
1591
+ }
1592
+ catch {
1593
+ // Default to case-sensitive on Linux/Unix if test fails
1594
+ // (win32 and darwin already returned early, so we're on a case-sensitive platform)
1595
+ cachedCaseSensitive = true;
1596
+ }
1597
+ finally {
1598
+ // Clean up the secure temporary directory
1599
+ if (secureTestDir) {
1600
+ try {
1601
+ rmdirSync(secureTestDir);
1602
+ }
1603
+ catch {
1604
+ // Ignore cleanup errors
1605
+ }
1606
+ }
1607
+ }
1608
+ return cachedCaseSensitive;
1609
+ }
1610
+ /**
1611
+ * Check if file system is case-sensitive.
1612
+ *
1613
+ * @returns True if file system is case-sensitive
1614
+ */
1615
+ function isCaseSensitiveFs() {
1616
+ return detectCaseSensitivity();
1617
+ }
1618
+ /**
1619
+ * Get comprehensive platform information.
1620
+ *
1621
+ * @returns Platform information object (cached after first call)
1622
+ */
1623
+ function getPlatformInfo() {
1624
+ if (cachedPlatformInfo) {
1625
+ return cachedPlatformInfo;
1626
+ }
1627
+ const os = platform();
1628
+ const archInfo = arch();
1629
+ let osName;
1630
+ switch (os) {
1631
+ case 'win32':
1632
+ osName = 'win32';
1633
+ break;
1634
+ case 'darwin':
1635
+ osName = 'darwin';
1636
+ break;
1637
+ case 'linux':
1638
+ osName = 'linux';
1639
+ break;
1640
+ case 'freebsd':
1641
+ osName = 'freebsd';
1642
+ break;
1643
+ case 'sunos':
1644
+ osName = 'sunos';
1645
+ break;
1646
+ case 'aix':
1647
+ osName = 'aix';
1648
+ break;
1649
+ default:
1650
+ osName = 'other';
1651
+ }
1652
+ cachedPlatformInfo = {
1653
+ os: osName,
1654
+ arch: archInfo,
1655
+ nodeVersion: process.versions.node,
1656
+ isWindows: osName === 'win32',
1657
+ isMac: osName === 'darwin',
1658
+ isLinux: osName === 'linux',
1659
+ caseSensitive: detectCaseSensitivity(),
1660
+ pathSeparator: osName === 'win32' ? '\\' : '/',
1661
+ lineEnding: osName === 'win32' ? '\r\n' : '\n',
1662
+ };
1663
+ return cachedPlatformInfo;
1664
+ }
1665
+ /**
1666
+ * Detect current platform.
1667
+ *
1668
+ * @returns Platform information object
1669
+ */
1670
+ function detectPlatform() {
1671
+ return getPlatformInfo();
1672
+ }
1673
+ /**
1674
+ * Check if running on Windows.
1675
+ *
1676
+ * @returns True if running on Windows
1677
+ */
1678
+ function isWindows() {
1679
+ return process.platform === 'win32';
1680
+ }
1681
+ /**
1682
+ * Check if running on macOS.
1683
+ *
1684
+ * @returns True if running on macOS
1685
+ */
1686
+ function isMac() {
1687
+ return process.platform === 'darwin';
1688
+ }
1689
+ /**
1690
+ * Check if running on Linux.
1691
+ *
1692
+ * @returns True if running on Linux
1693
+ */
1694
+ function isLinux() {
1695
+ return process.platform === 'linux';
1696
+ }
1697
+
1698
+ /** Unix line ending */
1699
+ const LF = '\n';
1700
+ /** Windows line ending */
1701
+ const CRLF = '\r\n';
1702
+ /**
1703
+ * Get platform-appropriate line ending.
1704
+ *
1705
+ * @returns Line ending for current platform
1706
+ */
1707
+ function getLineEnding() {
1708
+ return isWindows() ? CRLF : LF;
1709
+ }
1710
+ /**
1711
+ * Get platform-appropriate path separator.
1712
+ *
1713
+ * @returns Path separator for current platform
1714
+ */
1715
+ function getPathSeparator() {
1716
+ return isWindows() ? '\\' : '/';
1717
+ }
1718
+ /**
1719
+ * Normalize line endings in content.
1720
+ *
1721
+ * @param content - Content to normalize
1722
+ * @param style - Target line ending style ('lf', 'crlf', or 'auto' for platform default)
1723
+ * @returns Content with normalized line endings
1724
+ */
1725
+ function normalizeLineEndings(content, style = 'lf') {
1726
+ let target;
1727
+ if (style === 'auto') {
1728
+ target = isWindows() ? CRLF : LF;
1729
+ }
1730
+ else {
1731
+ target = style === 'crlf' ? CRLF : LF;
1732
+ }
1733
+ // First normalize all to LF, then convert to target
1734
+ const normalized = content.replace(/\r\n/g, LF).replace(/\r/g, LF);
1735
+ if (target === LF) {
1736
+ return normalized;
1737
+ }
1738
+ return normalized.replace(/\n/g, target);
1739
+ }
1740
+ /**
1741
+ * Detect line ending style used in content.
1742
+ *
1743
+ * @param content - Content to analyze
1744
+ * @returns Detected line ending style
1745
+ */
1746
+ function detectLineEnding(content) {
1747
+ const hasCRLF = content.includes(CRLF);
1748
+ // Check for LF that is NOT part of CRLF
1749
+ const hasLFOnly = content.includes('\n') && content.replace(/\r\n/g, '').includes('\n');
1750
+ if (hasCRLF && hasLFOnly)
1751
+ return 'mixed';
1752
+ if (hasCRLF)
1753
+ return 'crlf';
1754
+ if (content.includes('\n'))
1755
+ return 'lf';
1756
+ return 'none';
1757
+ }
1758
+ /**
1759
+ * Compare paths with case sensitivity awareness.
1760
+ *
1761
+ * @param path1 - First path
1762
+ * @param path2 - Second path
1763
+ * @returns True if paths are equal (respecting case sensitivity)
1764
+ */
1765
+ function pathsEqual(path1, path2) {
1766
+ const caseSensitive = detectCaseSensitivity();
1767
+ if (caseSensitive) {
1768
+ return path1 === path2;
1769
+ }
1770
+ return path1.toLowerCase() === path2.toLowerCase();
1771
+ }
1772
+
1773
+ /**
1774
+ * Create a structured error with code and optional context.
1775
+ *
1776
+ * @param message - The human-readable error message
1777
+ * @param code - The machine-readable error code for programmatic handling
1778
+ * @param context - Additional contextual information about the error
1779
+ * @returns Structured error instance with code and context properties
1780
+ *
1781
+ * @example
1782
+ * ```typescript
1783
+ * import { createStructuredError } from '@hyperfrontend/project-scope'
1784
+ *
1785
+ * throw createStructuredError(
1786
+ * 'Configuration file not found',
1787
+ * 'CONFIG_NOT_FOUND',
1788
+ * { path: './config.json', searched: ['./config.json', './settings.json'] }
1789
+ * )
1790
+ * ```
1791
+ */
1792
+ function createStructuredError(message, code, context) {
1793
+ const error = createError(message);
1794
+ error.code = code;
1795
+ error.context = context ?? {};
1796
+ return error;
1797
+ }
1798
+ /**
1799
+ * Create a configuration-related error.
1800
+ *
1801
+ * @param message - The human-readable error message
1802
+ * @param code - The machine-readable error code for programmatic handling
1803
+ * @param context - Additional contextual information (e.g., file path, config key)
1804
+ * @returns Structured error instance tagged with type 'config'
1805
+ */
1806
+ function createConfigError(message, code, context) {
1807
+ return createStructuredError(message, code, { ...context, type: 'config' });
1808
+ }
1809
+ /**
1810
+ * Create a filesystem-related error.
1811
+ *
1812
+ * @param message - The human-readable error message
1813
+ * @param code - The filesystem error code (e.g., ENOENT for not found, EACCES for access denied)
1814
+ * @param context - Additional contextual information (e.g., file path, operation attempted)
1815
+ * @returns Structured error instance tagged with type 'fs'
1816
+ */
1817
+ function createFsError(message, code, context) {
1818
+ return createStructuredError(message, code, { ...context, type: 'fs' });
1819
+ }
1820
+ /**
1821
+ * Create a parsing-related error.
1822
+ *
1823
+ * @param message - The human-readable error message
1824
+ * @param code - The machine-readable error code for programmatic handling
1825
+ * @param context - Additional contextual information (e.g., file path, line/column numbers, expected format)
1826
+ * @returns Structured error instance tagged with type 'parse'
1827
+ */
1828
+ function createParseError(message, code, context) {
1829
+ return createStructuredError(message, code, { ...context, type: 'parse' });
1830
+ }
1831
+ /**
1832
+ * Create a validation-related error.
1833
+ *
1834
+ * @param message - The human-readable error message
1835
+ * @param code - The machine-readable error code for programmatic handling
1836
+ * @param context - Additional contextual information (e.g., field name, actual vs expected values)
1837
+ * @returns Structured error instance tagged with type 'validation'
1838
+ */
1839
+ function createValidationError(message, code, context) {
1840
+ return createStructuredError(message, code, { ...context, type: 'validation' });
1841
+ }
1842
+
1843
+ /**
1844
+ * Pattern matching utilities with ReDoS protection.
1845
+ * Uses character-by-character matching instead of regex where possible.
1846
+ */
1847
+ /**
1848
+ * Match path against glob pattern using safe character iteration.
1849
+ * Avoids regex to prevent ReDoS attacks.
1850
+ *
1851
+ * Supported patterns:
1852
+ * - * matches any characters except /
1853
+ * - ** matches any characters including /
1854
+ * - ? matches exactly one character except /
1855
+ * - {a,b,c} matches any of the alternatives
1856
+ *
1857
+ * @param path - The filesystem path to test against the pattern
1858
+ * @param pattern - The glob pattern to match against
1859
+ * @returns True if path matches pattern
1860
+ *
1861
+ * @example
1862
+ * ```typescript
1863
+ * import { matchGlobPattern } from '@hyperfrontend/project-scope'
1864
+ *
1865
+ * matchGlobPattern('src/utils/helper.ts', '\*\*\/*.ts') // true
1866
+ * matchGlobPattern('test.spec.ts', '\*.spec.ts') // true
1867
+ * matchGlobPattern('config.json', '\*.{json,yaml}') // true
1868
+ * matchGlobPattern('src/index.ts', 'src/\*.ts') // true
1869
+ * ```
1870
+ */
1871
+ function matchGlobPattern(path, pattern) {
1872
+ return matchSegments(path.split('/'), pattern.split('/'), 0, 0);
1873
+ }
1874
+ /**
1875
+ * Internal recursive function to match path segments against pattern segments.
1876
+ *
1877
+ * @param pathParts - Array of path segments split by '/'
1878
+ * @param patternParts - Array of pattern segments split by '/'
1879
+ * @param pathIdx - Current index in pathParts being examined
1880
+ * @param patternIdx - Current index in patternParts being examined
1881
+ * @returns True if remaining segments match
1882
+ */
1883
+ function matchSegments(pathParts, patternParts, pathIdx, patternIdx) {
1884
+ // Base cases
1885
+ if (pathIdx === pathParts.length && patternIdx === patternParts.length) {
1886
+ return true; // Both exhausted = match
1887
+ }
1888
+ if (patternIdx >= patternParts.length) {
1889
+ return false; // Pattern exhausted but path remains
1890
+ }
1891
+ const patternPart = patternParts[patternIdx];
1892
+ // Handle ** (globstar) - matches zero or more directories
1893
+ if (patternPart === '**') {
1894
+ // Try matching rest of pattern against current position and all future positions
1895
+ for (let i = pathIdx; i <= pathParts.length; i++) {
1896
+ if (matchSegments(pathParts, patternParts, i, patternIdx + 1)) {
1897
+ return true;
1898
+ }
1899
+ }
1900
+ return false;
1901
+ }
1902
+ if (pathIdx >= pathParts.length) {
1903
+ return false; // Path exhausted but pattern remains (and it's not **)
1904
+ }
1905
+ const pathPart = pathParts[pathIdx];
1906
+ // Match current segment
1907
+ if (matchSegment(pathPart, patternPart)) {
1908
+ return matchSegments(pathParts, patternParts, pathIdx + 1, patternIdx + 1);
1909
+ }
1910
+ return false;
1911
+ }
1912
+ /**
1913
+ * Match a single path segment against a pattern segment.
1914
+ * Handles *, ?, and {a,b,c} patterns.
1915
+ *
1916
+ * @param text - The path segment text to match
1917
+ * @param pattern - The pattern segment to match against
1918
+ * @returns True if the text matches the pattern
1919
+ */
1920
+ function matchSegment(text, pattern) {
1921
+ let textIdx = 0;
1922
+ let patternIdx = 0;
1923
+ while (patternIdx < pattern.length) {
1924
+ const char = pattern[patternIdx];
1925
+ if (char === '*') {
1926
+ // * matches zero or more characters
1927
+ patternIdx++;
1928
+ if (patternIdx === pattern.length) {
1929
+ return true; // * at end matches rest of string
1930
+ }
1931
+ // Try matching rest of pattern at each position in text
1932
+ for (let i = textIdx; i <= text.length; i++) {
1933
+ if (matchSegmentFrom(text, i, pattern, patternIdx)) {
1934
+ return true;
1935
+ }
1936
+ }
1937
+ return false;
1938
+ }
1939
+ else if (char === '?') {
1940
+ // ? matches exactly one character
1941
+ if (textIdx >= text.length) {
1942
+ return false;
1943
+ }
1944
+ textIdx++;
1945
+ patternIdx++;
1946
+ }
1947
+ else if (char === '{') {
1948
+ // {a,b,c} matches any alternative
1949
+ const closeIdx = findClosingBrace(pattern, patternIdx);
1950
+ if (closeIdx === -1) {
1951
+ // Unmatched brace, treat as literal
1952
+ if (textIdx >= text.length || text[textIdx] !== char) {
1953
+ return false;
1954
+ }
1955
+ textIdx++;
1956
+ patternIdx++;
1957
+ }
1958
+ else {
1959
+ const alternatives = extractAlternatives(pattern.slice(patternIdx + 1, closeIdx));
1960
+ for (const alt of alternatives) {
1961
+ if (matchSegmentFrom(text, textIdx, text.slice(0, textIdx) + alt + pattern.slice(closeIdx + 1), textIdx)) {
1962
+ return true;
1963
+ }
1964
+ }
1965
+ return false;
1966
+ }
1967
+ }
1968
+ else {
1969
+ // Literal character
1970
+ if (textIdx >= text.length || text[textIdx] !== char) {
1971
+ return false;
1972
+ }
1973
+ textIdx++;
1974
+ patternIdx++;
1975
+ }
1976
+ }
1977
+ return textIdx === text.length;
1978
+ }
1979
+ /**
1980
+ * Helper to match from a specific position.
1981
+ *
1982
+ * @param text - The full text being matched
1983
+ * @param textIdx - The starting index in text to match from
1984
+ * @param pattern - The full pattern being matched
1985
+ * @param patternIdx - The starting index in pattern to match from
1986
+ * @returns True if the text matches the pattern from the given positions
1987
+ */
1988
+ function matchSegmentFrom(text, textIdx, pattern, patternIdx) {
1989
+ const remainingText = text.slice(textIdx);
1990
+ const remainingPattern = pattern.slice(patternIdx);
1991
+ return matchSegment(remainingText, remainingPattern);
1992
+ }
1993
+ /**
1994
+ * Find closing brace for {a,b,c} pattern.
1995
+ *
1996
+ * @param pattern - The pattern string to search within
1997
+ * @param startIdx - The index of the opening brace
1998
+ * @returns The index of the matching closing brace, or -1 if not found
1999
+ */
2000
+ function findClosingBrace(pattern, startIdx) {
2001
+ let depth = 0;
2002
+ for (let i = startIdx; i < pattern.length; i++) {
2003
+ if (pattern[i] === '{') {
2004
+ depth++;
2005
+ }
2006
+ else if (pattern[i] === '}') {
2007
+ depth--;
2008
+ if (depth === 0) {
2009
+ return i;
2010
+ }
2011
+ }
2012
+ }
2013
+ return -1;
2014
+ }
2015
+ /**
2016
+ * Extract alternatives from {a,b,c} pattern content.
2017
+ *
2018
+ * @param content - The content between braces (without the braces themselves)
2019
+ * @returns Array of alternative strings split by commas at depth 0
2020
+ */
2021
+ function extractAlternatives(content) {
2022
+ const alternatives = [];
2023
+ let current = '';
2024
+ let depth = 0;
2025
+ for (let i = 0; i < content.length; i++) {
2026
+ const char = content[i];
2027
+ if (char === '{') {
2028
+ depth++;
2029
+ current += char;
2030
+ }
2031
+ else if (char === '}') {
2032
+ depth--;
2033
+ current += char;
2034
+ }
2035
+ else if (char === ',' && depth === 0) {
2036
+ alternatives.push(current);
2037
+ current = '';
2038
+ }
2039
+ else {
2040
+ current += char;
2041
+ }
2042
+ }
2043
+ if (current) {
2044
+ alternatives.push(current);
2045
+ }
2046
+ return alternatives;
2047
+ }
2048
+ /**
2049
+ * Test if path matches any of the patterns.
2050
+ *
2051
+ * @param path - Path to test
2052
+ * @param patterns - Array of glob patterns
2053
+ * @returns True if path matches any pattern
2054
+ */
2055
+ function matchesAnyPattern(path, patterns) {
2056
+ return patterns.some((pattern) => matchGlobPattern(path, pattern));
2057
+ }
2058
+ /**
2059
+ * Test if path exactly matches the pattern (no glob).
2060
+ *
2061
+ * @param path - Path to test
2062
+ * @param pattern - Exact pattern to match
2063
+ * @returns True if path equals pattern
2064
+ */
2065
+ function matchesExact(path, pattern) {
2066
+ return path === pattern;
2067
+ }
2068
+
2069
+ /**
2070
+ * Global registry of all caches for bulk operations.
2071
+ */
2072
+ const cacheRegistry = createSet();
2073
+ /**
2074
+ * Create a cache with optional TTL and size limits.
2075
+ *
2076
+ * The cache provides a simple key-value store with:
2077
+ * - Optional TTL (time-to-live) for automatic expiration
2078
+ * - Optional maxSize for limiting cache size with FIFO eviction
2079
+ * - Lazy expiration (entries are checked on access)
2080
+ *
2081
+ * @param options - Cache configuration options
2082
+ * @returns Cache instance
2083
+ *
2084
+ * @example
2085
+ * ```typescript
2086
+ * // Basic cache
2087
+ * const cache = createCache<string, number>()
2088
+ * cache.set('answer', 42)
2089
+ * cache.get('answer') // 42
2090
+ *
2091
+ * // Cache with TTL (expires after 60 seconds)
2092
+ * const ttlCache = createCache<string, object>({ ttl: 60000 })
2093
+ *
2094
+ * // Cache with max size (evicts oldest when full)
2095
+ * const lruCache = createCache<string, object>({ maxSize: 100 })
2096
+ *
2097
+ * // Combined options
2098
+ * const configCache = createCache<string, object>({
2099
+ * ttl: 30000,
2100
+ * maxSize: 50
2101
+ * })
2102
+ * ```
2103
+ */
2104
+ function createCache(options) {
2105
+ const { ttl, maxSize } = options ?? {};
2106
+ const store = createMap();
2107
+ // Track insertion order for FIFO eviction
2108
+ const insertionOrder = [];
2109
+ /**
2110
+ * Check if an entry is expired.
2111
+ *
2112
+ * @param entry - Cache entry to check
2113
+ * @returns True if entry is expired
2114
+ */
2115
+ function isExpired(entry) {
2116
+ if (ttl === undefined)
2117
+ return false;
2118
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
2119
+ return Date.now() - entry.timestamp > ttl;
2120
+ }
2121
+ /**
2122
+ * Evict oldest entries to make room for new ones.
2123
+ */
2124
+ function evictIfNeeded() {
2125
+ if (maxSize === undefined)
2126
+ return;
2127
+ while (store.size >= maxSize && insertionOrder.length > 0) {
2128
+ const oldestKey = insertionOrder.shift();
2129
+ if (oldestKey !== undefined) {
2130
+ store.delete(oldestKey);
2131
+ }
2132
+ }
2133
+ }
2134
+ /**
2135
+ * Remove key from insertion order tracking.
2136
+ *
2137
+ * @param key - Key to remove from order tracking
2138
+ */
2139
+ function removeFromOrder(key) {
2140
+ const index = insertionOrder.indexOf(key);
2141
+ if (index !== -1) {
2142
+ insertionOrder.splice(index, 1);
2143
+ }
2144
+ }
2145
+ const cache = {
2146
+ get(key) {
2147
+ const entry = store.get(key);
2148
+ if (!entry)
2149
+ return undefined;
2150
+ if (isExpired(entry)) {
2151
+ store.delete(key);
2152
+ removeFromOrder(key);
2153
+ return undefined;
2154
+ }
2155
+ return entry.value;
2156
+ },
2157
+ set(key, value) {
2158
+ // If key exists, remove from order first
2159
+ if (store.has(key)) {
2160
+ removeFromOrder(key);
2161
+ }
2162
+ else {
2163
+ // Evict if needed before adding new entry
2164
+ evictIfNeeded();
2165
+ }
2166
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
2167
+ store.set(key, { value, timestamp: Date.now() });
2168
+ insertionOrder.push(key);
2169
+ },
2170
+ has(key) {
2171
+ const entry = store.get(key);
2172
+ if (!entry)
2173
+ return false;
2174
+ if (isExpired(entry)) {
2175
+ store.delete(key);
2176
+ removeFromOrder(key);
2177
+ return false;
2178
+ }
2179
+ return true;
2180
+ },
2181
+ delete(key) {
2182
+ removeFromOrder(key);
2183
+ return store.delete(key);
2184
+ },
2185
+ clear() {
2186
+ store.clear();
2187
+ insertionOrder.length = 0;
2188
+ },
2189
+ size() {
2190
+ return store.size;
2191
+ },
2192
+ keys() {
2193
+ return [...insertionOrder];
2194
+ },
2195
+ };
2196
+ // Register cache for global operations
2197
+ cacheRegistry.add(cache);
2198
+ return freeze(cache);
2199
+ }
2200
+ /**
2201
+ * Clear all registered caches.
2202
+ *
2203
+ * Useful for testing or when a global state reset is needed.
2204
+ * This clears all caches created via `createCache()`.
2205
+ *
2206
+ * @example
2207
+ * ```typescript
2208
+ * // In tests
2209
+ * afterEach(() => {
2210
+ * clearAllCaches()
2211
+ * })
2212
+ * ```
2213
+ */
2214
+ function clearAllCaches() {
2215
+ for (const cache of cacheRegistry) {
2216
+ cache.clear();
2217
+ }
2218
+ }
2219
+ /**
2220
+ * Get the number of registered caches.
2221
+ *
2222
+ * Primarily used for testing.
2223
+ *
2224
+ * @returns Number of registered caches
2225
+ */
2226
+ function getCacheCount() {
2227
+ return cacheRegistry.size;
2228
+ }
2229
+ /**
2230
+ * Unregister a cache from the global registry.
2231
+ *
2232
+ * Useful for cleanup in tests or when a cache is no longer needed.
2233
+ *
2234
+ * @param cache - Cache to unregister
2235
+ * @returns True if cache was unregistered
2236
+ */
2237
+ function unregisterCache(cache) {
2238
+ return cacheRegistry.delete(cache);
2239
+ }
2240
+ /**
2241
+ * Create a memoized version of a function with caching.
2242
+ *
2243
+ * The memoized function caches results based on the first argument (key).
2244
+ * If additional arguments are needed, use the options.keyFn parameter.
2245
+ *
2246
+ * @param fn - Function to memoize
2247
+ * @param options - Cache options for the underlying cache
2248
+ * @returns Memoized function with cache control methods
2249
+ *
2250
+ * @example
2251
+ * ```typescript
2252
+ * // Memoize a detection function
2253
+ * const detectTechStackMemo = memoize(
2254
+ * (path: string) => expensiveDetection(path),
2255
+ * { ttl: 60000 }
2256
+ * )
2257
+ *
2258
+ * const result1 = detectTechStackMemo('/path/to/project')
2259
+ * const result2 = detectTechStackMemo('/path/to/project') // Returns cached
2260
+ *
2261
+ * // Clear the cache
2262
+ * detectTechStackMemo.cache.clear()
2263
+ * ```
2264
+ */
2265
+ function memoize(fn, options) {
2266
+ const cache = createCache(options);
2267
+ const memoized = (key) => {
2268
+ const cached = cache.get(key);
2269
+ if (cached !== undefined) {
2270
+ return cached;
2271
+ }
2272
+ const result = fn(key);
2273
+ cache.set(key, result);
2274
+ return result;
2275
+ };
2276
+ // Attach cache for direct access
2277
+ defineProperty(memoized, 'cache', {
2278
+ value: cache,
2279
+ writable: false,
2280
+ enumerable: true,
2281
+ });
2282
+ return memoized;
2283
+ }
2284
+
2285
+ export { BINARY_SIGNATURES, CRLF, LF, UTF16_BE_BOM_BYTES, UTF16_LE_BOM_BYTES, UTF8_BOM, UTF8_BOM_BYTES, addBom, bufferToString, clearAllCaches, createCache, createConfigError, createDirectory, createFileSystemError, createFsError, createParseError, createScopedLogger, createStructuredError, createValidationError, detectCaseSensitivity, detectEncoding, detectEncodingInfo, detectLineEnding, detectPlatform, ensureDir, ensureTrailingSlash, exists, findUpwardWhere, getBasename, getCacheCount, getDirname, getExtension, getFileNameWithoutExtension, getFileStat, getGlobalLogLevel, getLineEnding, getPathSeparator, getPlatformInfo, hasBom, isAbsolute, isBinaryFile, isCaseSensitiveFs, isDirectory, isFile, isLinux, isMac, isSymlink, isTextFile, isWindows, join, joinPath, joinPosix, locateByMarkers, logger, matchGlobPattern, matchesAnyPattern, matchesExact, memoize, normalizeLineEndings, normalizePath, normalizeToForwardSlashes, normalizeToNative, offsetFromRoot, parsePath, pathSegments, pathsEqual, readDirectory, readDirectoryRecursive, readFileBuffer, readFileContent, readFileIfExists, readJsonFile, readJsonFileIfExists, relativePath, removeDirectory, removeTrailingSlash, resetGlobalLogLevel, resolveFromWorkspace, resolvePath, resolveRealPath, sanitize, setGlobalLogLevel, stripBom, toUtf8, traverseUpward, unregisterCache, writeFileBuffer, writeFileContent, writeJsonFile };
2286
+ //# sourceMappingURL=index.esm.js.map