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