@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,1581 @@
1
+ 'use strict';
2
+
3
+ var node_path = require('node:path');
4
+ var node_fs = require('node:fs');
5
+
6
+ /**
7
+ * Safe copies of Object built-in methods.
8
+ *
9
+ * These references are captured at module initialization time to protect against
10
+ * prototype pollution attacks. Import only what you need for tree-shaking.
11
+ *
12
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/object
13
+ */
14
+ // Capture references at module initialization time
15
+ const _Object = globalThis.Object;
16
+ /**
17
+ * (Safe copy) Prevents modification of existing property attributes and values,
18
+ * and prevents the addition of new properties.
19
+ */
20
+ const freeze = _Object.freeze;
21
+ /**
22
+ * (Safe copy) Returns the names of the enumerable string properties and methods of an object.
23
+ */
24
+ const keys = _Object.keys;
25
+ /**
26
+ * (Safe copy) Returns an array of key/values of the enumerable own properties of an object.
27
+ */
28
+ const entries = _Object.entries;
29
+ /**
30
+ * (Safe copy) Returns an array of values of the enumerable own properties of an object.
31
+ */
32
+ const values = _Object.values;
33
+ /**
34
+ * (Safe copy) Adds one or more properties to an object, and/or modifies attributes of existing properties.
35
+ */
36
+ const defineProperties = _Object.defineProperties;
37
+
38
+ /**
39
+ * Safe copies of Map built-in via factory function.
40
+ *
41
+ * Since constructors cannot be safely captured via Object.assign, this module
42
+ * provides a factory function that uses Reflect.construct internally.
43
+ *
44
+ * These references are captured at module initialization time to protect against
45
+ * prototype pollution attacks. Import only what you need for tree-shaking.
46
+ *
47
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/map
48
+ */
49
+ // Capture references at module initialization time
50
+ const _Map = globalThis.Map;
51
+ const _Reflect$2 = globalThis.Reflect;
52
+ /**
53
+ * (Safe copy) Creates a new Map using the captured Map constructor.
54
+ * Use this instead of `new Map()`.
55
+ *
56
+ * @param iterable - Optional iterable of key-value pairs.
57
+ * @returns A new Map instance.
58
+ */
59
+ const createMap = (iterable) => _Reflect$2.construct(_Map, iterable ? [iterable] : []);
60
+
61
+ /**
62
+ * Safe copies of Set built-in via factory function.
63
+ *
64
+ * Since constructors cannot be safely captured via Object.assign, this module
65
+ * provides a factory function that uses Reflect.construct internally.
66
+ *
67
+ * These references are captured at module initialization time to protect against
68
+ * prototype pollution attacks. Import only what you need for tree-shaking.
69
+ *
70
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/set
71
+ */
72
+ // Capture references at module initialization time
73
+ const _Set = globalThis.Set;
74
+ const _Reflect$1 = globalThis.Reflect;
75
+ /**
76
+ * (Safe copy) Creates a new Set using the captured Set constructor.
77
+ * Use this instead of `new Set()`.
78
+ *
79
+ * @param iterable - Optional iterable of values.
80
+ * @returns A new Set instance.
81
+ */
82
+ const createSet = (iterable) => _Reflect$1.construct(_Set, iterable ? [iterable] : []);
83
+
84
+ /**
85
+ * Global registry of all caches for bulk operations.
86
+ */
87
+ const cacheRegistry = createSet();
88
+ /**
89
+ * Create a cache with optional TTL and size limits.
90
+ *
91
+ * The cache provides a simple key-value store with:
92
+ * - Optional TTL (time-to-live) for automatic expiration
93
+ * - Optional maxSize for limiting cache size with FIFO eviction
94
+ * - Lazy expiration (entries are checked on access)
95
+ *
96
+ * @param options - Cache configuration options
97
+ * @returns Cache instance
98
+ *
99
+ * @example
100
+ * ```typescript
101
+ * // Basic cache
102
+ * const cache = createCache<string, number>()
103
+ * cache.set('answer', 42)
104
+ * cache.get('answer') // 42
105
+ *
106
+ * // Cache with TTL (expires after 60 seconds)
107
+ * const ttlCache = createCache<string, object>({ ttl: 60000 })
108
+ *
109
+ * // Cache with max size (evicts oldest when full)
110
+ * const lruCache = createCache<string, object>({ maxSize: 100 })
111
+ *
112
+ * // Combined options
113
+ * const configCache = createCache<string, object>({
114
+ * ttl: 30000,
115
+ * maxSize: 50
116
+ * })
117
+ * ```
118
+ */
119
+ function createCache(options) {
120
+ const { ttl, maxSize } = options ?? {};
121
+ const store = createMap();
122
+ // Track insertion order for FIFO eviction
123
+ const insertionOrder = [];
124
+ /**
125
+ * Check if an entry is expired.
126
+ *
127
+ * @param entry - Cache entry to check
128
+ * @returns True if entry is expired
129
+ */
130
+ function isExpired(entry) {
131
+ if (ttl === undefined)
132
+ return false;
133
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
134
+ return Date.now() - entry.timestamp > ttl;
135
+ }
136
+ /**
137
+ * Evict oldest entries to make room for new ones.
138
+ */
139
+ function evictIfNeeded() {
140
+ if (maxSize === undefined)
141
+ return;
142
+ while (store.size >= maxSize && insertionOrder.length > 0) {
143
+ const oldestKey = insertionOrder.shift();
144
+ if (oldestKey !== undefined) {
145
+ store.delete(oldestKey);
146
+ }
147
+ }
148
+ }
149
+ /**
150
+ * Remove key from insertion order tracking.
151
+ *
152
+ * @param key - Key to remove from order tracking
153
+ */
154
+ function removeFromOrder(key) {
155
+ const index = insertionOrder.indexOf(key);
156
+ if (index !== -1) {
157
+ insertionOrder.splice(index, 1);
158
+ }
159
+ }
160
+ const cache = {
161
+ get(key) {
162
+ const entry = store.get(key);
163
+ if (!entry)
164
+ return undefined;
165
+ if (isExpired(entry)) {
166
+ store.delete(key);
167
+ removeFromOrder(key);
168
+ return undefined;
169
+ }
170
+ return entry.value;
171
+ },
172
+ set(key, value) {
173
+ // If key exists, remove from order first
174
+ if (store.has(key)) {
175
+ removeFromOrder(key);
176
+ }
177
+ else {
178
+ // Evict if needed before adding new entry
179
+ evictIfNeeded();
180
+ }
181
+ // eslint-disable-next-line workspace/no-unsafe-builtin-methods -- Date.now() is needed for Jest fake timers compatibility
182
+ store.set(key, { value, timestamp: Date.now() });
183
+ insertionOrder.push(key);
184
+ },
185
+ has(key) {
186
+ const entry = store.get(key);
187
+ if (!entry)
188
+ return false;
189
+ if (isExpired(entry)) {
190
+ store.delete(key);
191
+ removeFromOrder(key);
192
+ return false;
193
+ }
194
+ return true;
195
+ },
196
+ delete(key) {
197
+ removeFromOrder(key);
198
+ return store.delete(key);
199
+ },
200
+ clear() {
201
+ store.clear();
202
+ insertionOrder.length = 0;
203
+ },
204
+ size() {
205
+ return store.size;
206
+ },
207
+ keys() {
208
+ return [...insertionOrder];
209
+ },
210
+ };
211
+ // Register cache for global operations
212
+ cacheRegistry.add(cache);
213
+ return freeze(cache);
214
+ }
215
+
216
+ /**
217
+ * Safe copies of Error built-ins via factory functions.
218
+ *
219
+ * Since constructors cannot be safely captured via Object.assign, this module
220
+ * provides factory functions that use Reflect.construct internally.
221
+ *
222
+ * These references are captured at module initialization time to protect against
223
+ * prototype pollution attacks. Import only what you need for tree-shaking.
224
+ *
225
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/error
226
+ */
227
+ // Capture references at module initialization time
228
+ const _Error = globalThis.Error;
229
+ const _Reflect = globalThis.Reflect;
230
+ /**
231
+ * (Safe copy) Creates a new Error using the captured Error constructor.
232
+ * Use this instead of `new Error()`.
233
+ *
234
+ * @param message - Optional error message.
235
+ * @param options - Optional error options.
236
+ * @returns A new Error instance.
237
+ */
238
+ const createError = (message, options) => _Reflect.construct(_Error, [message, options]);
239
+
240
+ /**
241
+ * Safe copies of JSON built-in methods.
242
+ *
243
+ * These references are captured at module initialization time to protect against
244
+ * prototype pollution attacks. Import only what you need for tree-shaking.
245
+ *
246
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/json
247
+ */
248
+ // Capture references at module initialization time
249
+ const _JSON = globalThis.JSON;
250
+ /**
251
+ * (Safe copy) Converts a JavaScript Object Notation (JSON) string into an object.
252
+ */
253
+ const parse = _JSON.parse;
254
+ /**
255
+ * (Safe copy) Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
256
+ */
257
+ const stringify = _JSON.stringify;
258
+
259
+ /**
260
+ * Safe copies of Array built-in static methods.
261
+ *
262
+ * These references are captured at module initialization time to protect against
263
+ * prototype pollution attacks. Import only what you need for tree-shaking.
264
+ *
265
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/array
266
+ */
267
+ // Capture references at module initialization time
268
+ const _Array = globalThis.Array;
269
+ /**
270
+ * (Safe copy) Determines whether the passed value is an Array.
271
+ */
272
+ const isArray = _Array.isArray;
273
+
274
+ /**
275
+ * Safe copies of Console built-in methods.
276
+ *
277
+ * These references are captured at module initialization time to protect against
278
+ * prototype pollution attacks. Import only what you need for tree-shaking.
279
+ *
280
+ * @module @hyperfrontend/immutable-api-utils/built-in-copy/console
281
+ */
282
+ // Capture references at module initialization time
283
+ const _console = globalThis.console;
284
+ /**
285
+ * (Safe copy) Outputs a message to the console.
286
+ */
287
+ const log = _console.log.bind(_console);
288
+ /**
289
+ * (Safe copy) Outputs a warning message to the console.
290
+ */
291
+ const warn = _console.warn.bind(_console);
292
+ /**
293
+ * (Safe copy) Outputs an error message to the console.
294
+ */
295
+ const error = _console.error.bind(_console);
296
+ /**
297
+ * (Safe copy) Outputs an informational message to the console.
298
+ */
299
+ const info = _console.info.bind(_console);
300
+ /**
301
+ * (Safe copy) Outputs a debug message to the console.
302
+ */
303
+ const debug = _console.debug.bind(_console);
304
+ /**
305
+ * (Safe copy) Outputs a stack trace to the console.
306
+ */
307
+ _console.trace.bind(_console);
308
+ /**
309
+ * (Safe copy) Displays an interactive listing of the properties of a specified object.
310
+ */
311
+ _console.dir.bind(_console);
312
+ /**
313
+ * (Safe copy) Displays tabular data as a table.
314
+ */
315
+ _console.table.bind(_console);
316
+ /**
317
+ * (Safe copy) Writes an error message to the console if the assertion is false.
318
+ */
319
+ _console.assert.bind(_console);
320
+ /**
321
+ * (Safe copy) Clears the console.
322
+ */
323
+ _console.clear.bind(_console);
324
+ /**
325
+ * (Safe copy) Logs the number of times that this particular call to count() has been called.
326
+ */
327
+ _console.count.bind(_console);
328
+ /**
329
+ * (Safe copy) Resets the counter used with console.count().
330
+ */
331
+ _console.countReset.bind(_console);
332
+ /**
333
+ * (Safe copy) Creates a new inline group in the console.
334
+ */
335
+ _console.group.bind(_console);
336
+ /**
337
+ * (Safe copy) Creates a new inline group in the console that is initially collapsed.
338
+ */
339
+ _console.groupCollapsed.bind(_console);
340
+ /**
341
+ * (Safe copy) Exits the current inline group.
342
+ */
343
+ _console.groupEnd.bind(_console);
344
+ /**
345
+ * (Safe copy) Starts a timer with a name specified as an input parameter.
346
+ */
347
+ _console.time.bind(_console);
348
+ /**
349
+ * (Safe copy) Stops a timer that was previously started.
350
+ */
351
+ _console.timeEnd.bind(_console);
352
+ /**
353
+ * (Safe copy) Logs the current value of a timer that was previously started.
354
+ */
355
+ _console.timeLog.bind(_console);
356
+
357
+ const registeredClasses = [];
358
+
359
+ /**
360
+ * Returns the data type of the target.
361
+ * Uses native `typeof` operator, however, makes distinction between `null`, `array`, and `object`.
362
+ * Also, when classes are registered via `registerClass`, it checks if objects are instance of any known registered class.
363
+ *
364
+ * @param target - The target to get the data type of.
365
+ * @returns The data type of the target.
366
+ */
367
+ const getType = (target) => {
368
+ if (target === null)
369
+ return 'null';
370
+ const nativeDataType = typeof target;
371
+ if (nativeDataType === 'object') {
372
+ if (isArray(target))
373
+ return 'array';
374
+ for (const registeredClass of registeredClasses) {
375
+ if (target instanceof registeredClass)
376
+ return registeredClass.name;
377
+ }
378
+ }
379
+ return nativeDataType;
380
+ };
381
+
382
+ /* eslint-disable @typescript-eslint/no-explicit-any */
383
+ /**
384
+ * Creates a wrapper function that only executes the wrapped function if the condition function returns true.
385
+ *
386
+ * @param func - The function to be conditionally executed.
387
+ * @param conditionFunc - A function that returns a boolean, determining if `func` should be executed.
388
+ * @returns A wrapped version of `func` that executes conditionally.
389
+ */
390
+ function createConditionalExecutionFunction(func, conditionFunc) {
391
+ return function (...args) {
392
+ if (conditionFunc()) {
393
+ return func(...args);
394
+ }
395
+ };
396
+ }
397
+
398
+ /* eslint-disable @typescript-eslint/no-explicit-any */
399
+ /**
400
+ * Creates a wrapper function that silently ignores any errors thrown by the wrapped void function.
401
+ * This function is specifically for wrapping functions that do not return a value (void functions).
402
+ * Exceptions are swallowed without any logging or handling.
403
+ *
404
+ * @param func - The void function to be wrapped.
405
+ * @returns A wrapped version of the input function that ignores errors.
406
+ */
407
+ function createErrorIgnoringFunction(func) {
408
+ return function (...args) {
409
+ try {
410
+ func(...args);
411
+ }
412
+ catch {
413
+ // Deliberately swallowing/ignoring the exception
414
+ }
415
+ };
416
+ }
417
+
418
+ /* eslint-disable @typescript-eslint/no-unused-vars */
419
+ /**
420
+ * A no-operation function (noop) that does nothing regardless of the arguments passed.
421
+ * It is designed to be as permissive as possible in its typing without using the `Function` keyword.
422
+ *
423
+ * @param args - Any arguments passed to the function (ignored)
424
+ */
425
+ const noop = (...args) => {
426
+ // Intentionally does nothing
427
+ };
428
+
429
+ const logLevels = ['none', 'error', 'warn', 'log', 'info', 'debug'];
430
+ const priority = {
431
+ error: 4,
432
+ warn: 3,
433
+ log: 2,
434
+ info: 1,
435
+ debug: 0,
436
+ };
437
+ /**
438
+ * Validates whether a given string is a valid log level.
439
+ *
440
+ * @param level - The log level to validate
441
+ * @returns True if the level is valid, false otherwise
442
+ */
443
+ function isValidLogLevel(level) {
444
+ return logLevels.includes(level);
445
+ }
446
+ /**
447
+ * Creates a log level configuration manager for controlling logging behavior.
448
+ * Provides methods to get, set, and evaluate log levels based on priority.
449
+ *
450
+ * @param level - The initial log level (defaults to 'error')
451
+ * @returns A configuration object with log level management methods
452
+ * @throws {Error} When the provided level is not a valid log level
453
+ */
454
+ function createLogLevelConfig(level = 'error') {
455
+ if (!isValidLogLevel(level)) {
456
+ throw createError('Cannot create log level configuration with a valid default log level');
457
+ }
458
+ const state = { level };
459
+ const getLogLevel = () => state.level;
460
+ const setLogLevel = (level) => {
461
+ if (!isValidLogLevel(level)) {
462
+ throw createError(`Cannot set value '${level}' level. Expected levels are ${logLevels}.`);
463
+ }
464
+ state.level = level;
465
+ };
466
+ const shouldLog = (level) => {
467
+ if (state.level === 'none' || level === 'none' || !isValidLogLevel(level)) {
468
+ return false;
469
+ }
470
+ return priority[level] >= priority[state.level];
471
+ };
472
+ return freeze({
473
+ getLogLevel,
474
+ setLogLevel,
475
+ shouldLog,
476
+ });
477
+ }
478
+
479
+ /**
480
+ * Creates a logger instance with configurable log level filtering.
481
+ * Each log function is wrapped to respect the current log level setting.
482
+ *
483
+ * @param error - Function to handle error-level logs (required)
484
+ * @param warn - Function to handle warning-level logs (optional, defaults to noop)
485
+ * @param log - Function to handle standard logs (optional, defaults to noop)
486
+ * @param info - Function to handle info-level logs (optional, defaults to noop)
487
+ * @param debug - Function to handle debug-level logs (optional, defaults to noop)
488
+ * @returns A frozen logger object with log methods and level control
489
+ * @throws {ErrorLevelFn} When any provided log function is invalid
490
+ */
491
+ function createLogger(error, warn = noop, log = noop, info = noop, debug = noop) {
492
+ if (notValidLogFn(error)) {
493
+ throw createError(notFnMsg('error'));
494
+ }
495
+ if (notValidLogFn(warn)) {
496
+ throw createError(notFnMsg('warn'));
497
+ }
498
+ if (notValidLogFn(log)) {
499
+ throw createError(notFnMsg('log'));
500
+ }
501
+ if (notValidLogFn(info)) {
502
+ throw createError(notFnMsg('info'));
503
+ }
504
+ if (notValidLogFn(debug)) {
505
+ throw createError(notFnMsg('debug'));
506
+ }
507
+ const { setLogLevel, getLogLevel, shouldLog } = createLogLevelConfig();
508
+ const wrapLogFn = (fn, level) => {
509
+ if (fn === noop)
510
+ return fn;
511
+ const condition = () => shouldLog(level);
512
+ return createConditionalExecutionFunction(createErrorIgnoringFunction(fn), condition);
513
+ };
514
+ return freeze({
515
+ error: wrapLogFn(error, 'error'),
516
+ warn: wrapLogFn(warn, 'warn'),
517
+ log: wrapLogFn(log, 'log'),
518
+ info: wrapLogFn(info, 'info'),
519
+ debug: wrapLogFn(debug, 'debug'),
520
+ setLogLevel,
521
+ getLogLevel,
522
+ });
523
+ }
524
+ /**
525
+ * Validates whether a given value is a valid log function.
526
+ *
527
+ * @param fn - The value to validate
528
+ * @returns True if the value is not a function (invalid), false if it is valid
529
+ */
530
+ function notValidLogFn(fn) {
531
+ return getType(fn) !== 'function' && fn !== noop;
532
+ }
533
+ /**
534
+ * Generates an error message for invalid log function parameters.
535
+ *
536
+ * @param label - The name of the log function that failed validation
537
+ * @returns A formatted error message string
538
+ */
539
+ function notFnMsg(label) {
540
+ return `Cannot create a logger when ${label} is not a function`;
541
+ }
542
+
543
+ createLogger(error, warn, log, info, debug);
544
+
545
+ /**
546
+ * Global log level registry.
547
+ * Tracks all created scoped loggers to allow global log level changes.
548
+ */
549
+ const loggerRegistry = createSet();
550
+ /** Redacted placeholder for sensitive values */
551
+ const REDACTED = '[REDACTED]';
552
+ /**
553
+ * Patterns that indicate a sensitive key name.
554
+ * Keys containing these patterns will have their values sanitized.
555
+ */
556
+ const SENSITIVE_KEY_PATTERNS = [
557
+ /token/i,
558
+ /key/i,
559
+ /password/i,
560
+ /secret/i,
561
+ /credential/i,
562
+ /auth/i,
563
+ /bearer/i,
564
+ /api[_-]?key/i,
565
+ /private/i,
566
+ /passphrase/i,
567
+ ];
568
+ /**
569
+ * Checks if a key name indicates sensitive data.
570
+ *
571
+ * @param key - Key name to check
572
+ * @returns True if the key indicates sensitive data
573
+ */
574
+ function isSensitiveKey(key) {
575
+ return SENSITIVE_KEY_PATTERNS.some((pattern) => pattern.test(key));
576
+ }
577
+ /**
578
+ * Sanitizes an object by replacing sensitive values with REDACTED.
579
+ * This function recursively processes nested objects and arrays.
580
+ *
581
+ * @param obj - Object to sanitize
582
+ * @returns New object with sensitive values redacted
583
+ */
584
+ function sanitize(obj) {
585
+ if (obj === null || obj === undefined) {
586
+ return obj;
587
+ }
588
+ if (isArray(obj)) {
589
+ return obj.map((item) => sanitize(item));
590
+ }
591
+ if (typeof obj === 'object') {
592
+ const result = {};
593
+ for (const [key, value] of entries(obj)) {
594
+ if (isSensitiveKey(key)) {
595
+ result[key] = REDACTED;
596
+ }
597
+ else if (typeof value === 'object' && value !== null) {
598
+ result[key] = sanitize(value);
599
+ }
600
+ else {
601
+ result[key] = value;
602
+ }
603
+ }
604
+ return result;
605
+ }
606
+ return obj;
607
+ }
608
+ /**
609
+ * Formats a log message with optional metadata.
610
+ *
611
+ * @param namespace - Logger namespace prefix
612
+ * @param message - Log message
613
+ * @param meta - Optional metadata object
614
+ * @returns Formatted log string
615
+ */
616
+ function formatMessage(namespace, message, meta) {
617
+ const prefix = `[${namespace}]`;
618
+ if (meta && keys(meta).length > 0) {
619
+ const sanitizedMeta = sanitize(meta);
620
+ return `${prefix} ${message} ${stringify(sanitizedMeta)}`;
621
+ }
622
+ return `${prefix} ${message}`;
623
+ }
624
+ /**
625
+ * Creates a scoped logger with namespace prefix and optional secret sanitization.
626
+ * All log messages will be prefixed with [namespace] and sensitive metadata
627
+ * values will be automatically redacted.
628
+ *
629
+ * @param namespace - Logger namespace (e.g., 'project-scope', 'analyze')
630
+ * @param options - Logger configuration options
631
+ * @returns A configured scoped logger instance
632
+ *
633
+ * @example
634
+ * ```typescript
635
+ * const logger = createScopedLogger('project-scope')
636
+ * logger.setLogLevel('debug')
637
+ *
638
+ * // Basic logging
639
+ * logger.info('Starting analysis', { path: './project' })
640
+ *
641
+ * // Sensitive data is automatically redacted
642
+ * logger.debug('Config loaded', { apiKey: 'secret123' })
643
+ * // Output: [project-scope] Config loaded {"apiKey":"[REDACTED]"}
644
+ * ```
645
+ */
646
+ function createScopedLogger(namespace, options = {}) {
647
+ const { level = 'error', sanitizeSecrets = true } = options;
648
+ // Create wrapper functions that add namespace prefix and sanitization
649
+ const createLogFn = (baseFn) => (message, meta) => {
650
+ const processedMeta = sanitizeSecrets && meta ? sanitize(meta) : meta;
651
+ baseFn(formatMessage(namespace, message, processedMeta));
652
+ };
653
+ // Create base logger with wrapped functions
654
+ const baseLogger = createLogger(createLogFn(error), createLogFn(warn), createLogFn(log), createLogFn(info), createLogFn(debug));
655
+ // Set initial log level (use global override if set)
656
+ baseLogger.setLogLevel(level);
657
+ const scopedLogger = freeze({
658
+ error: (message, meta) => baseLogger.error(message, meta),
659
+ warn: (message, meta) => baseLogger.warn(message, meta),
660
+ log: (message, meta) => baseLogger.log(message, meta),
661
+ info: (message, meta) => baseLogger.info(message, meta),
662
+ debug: (message, meta) => baseLogger.debug(message, meta),
663
+ setLogLevel: baseLogger.setLogLevel,
664
+ getLogLevel: baseLogger.getLogLevel,
665
+ });
666
+ // Register logger for global level management
667
+ loggerRegistry.add(scopedLogger);
668
+ return scopedLogger;
669
+ }
670
+ /**
671
+ * Default logger instance for the project-scope library.
672
+ * Use this for general logging within the library.
673
+ *
674
+ * @example
675
+ * ```typescript
676
+ * import { logger } from '@hyperfrontend/project-scope/core'
677
+ *
678
+ * logger.setLogLevel('debug')
679
+ * logger.debug('Analyzing project', { path: './src' })
680
+ * ```
681
+ */
682
+ createScopedLogger('project-scope');
683
+
684
+ createScopedLogger('project-scope:fs');
685
+ /**
686
+ * Create a file system error with code and context.
687
+ *
688
+ * @param message - The error message describing what went wrong
689
+ * @param code - The category code for this type of filesystem failure
690
+ * @param context - Additional context including path, operation, and cause
691
+ * @returns A configured Error object with code and context properties
692
+ */
693
+ function createFileSystemError(message, code, context) {
694
+ const error = createError(message);
695
+ defineProperties(error, {
696
+ code: { value: code, enumerable: true },
697
+ context: { value: context, enumerable: true },
698
+ });
699
+ return error;
700
+ }
701
+ /**
702
+ * Read file if exists, return null otherwise.
703
+ *
704
+ * @param filePath - Path to file
705
+ * @param encoding - File encoding (default: utf-8)
706
+ * @returns File contents or null if file doesn't exist
707
+ */
708
+ function readFileIfExists(filePath, encoding = 'utf-8') {
709
+ if (!node_fs.existsSync(filePath)) {
710
+ return null;
711
+ }
712
+ try {
713
+ return node_fs.readFileSync(filePath, { encoding });
714
+ }
715
+ catch {
716
+ return null;
717
+ }
718
+ }
719
+
720
+ createScopedLogger('project-scope:fs:write');
721
+
722
+ /**
723
+ * Get file stats with error handling.
724
+ *
725
+ * @param filePath - Path to file
726
+ * @param followSymlinks - Whether to follow symlinks (default: true)
727
+ * @returns File stats or null if path doesn't exist
728
+ */
729
+ function getFileStat(filePath, followSymlinks = true) {
730
+ if (!node_fs.existsSync(filePath)) {
731
+ return null;
732
+ }
733
+ try {
734
+ const stat = followSymlinks ? node_fs.statSync(filePath) : node_fs.lstatSync(filePath);
735
+ return {
736
+ isFile: stat.isFile(),
737
+ isDirectory: stat.isDirectory(),
738
+ isSymlink: stat.isSymbolicLink(),
739
+ size: stat.size,
740
+ created: stat.birthtime,
741
+ modified: stat.mtime,
742
+ accessed: stat.atime,
743
+ mode: stat.mode,
744
+ };
745
+ }
746
+ catch {
747
+ return null;
748
+ }
749
+ }
750
+ /**
751
+ * Check if path is a directory.
752
+ *
753
+ * @param dirPath - Path to check
754
+ * @returns True if path is a directory
755
+ */
756
+ function isDirectory(dirPath) {
757
+ const stats = getFileStat(dirPath);
758
+ return stats?.isDirectory ?? false;
759
+ }
760
+ /**
761
+ * Check if path exists.
762
+ *
763
+ * @param filePath - Path to check
764
+ * @returns True if path exists
765
+ */
766
+ function exists(filePath) {
767
+ return node_fs.existsSync(filePath);
768
+ }
769
+
770
+ const fsDirLogger = createScopedLogger('project-scope:fs:dir');
771
+ /**
772
+ * List immediate contents of a directory.
773
+ *
774
+ * @param dirPath - Absolute or relative path to the directory
775
+ * @returns Array of entries with metadata for each file/directory
776
+ * @throws {Error} If directory doesn't exist or isn't a directory
777
+ *
778
+ * @example
779
+ * ```typescript
780
+ * import { readDirectory } from '@hyperfrontend/project-scope'
781
+ *
782
+ * const entries = readDirectory('./src')
783
+ * for (const entry of entries) {
784
+ * console.log(entry.name, entry.isFile ? 'file' : 'directory')
785
+ * }
786
+ * ```
787
+ */
788
+ function readDirectory(dirPath) {
789
+ fsDirLogger.debug('Reading directory', { path: dirPath });
790
+ if (!node_fs.existsSync(dirPath)) {
791
+ fsDirLogger.debug('Directory not found', { path: dirPath });
792
+ throw createFileSystemError(`Directory not found: ${dirPath}`, 'FS_NOT_FOUND', { path: dirPath, operation: 'readdir' });
793
+ }
794
+ if (!isDirectory(dirPath)) {
795
+ fsDirLogger.debug('Path is not a directory', { path: dirPath });
796
+ throw createFileSystemError(`Not a directory: ${dirPath}`, 'FS_NOT_A_DIRECTORY', { path: dirPath, operation: 'readdir' });
797
+ }
798
+ try {
799
+ const entries = node_fs.readdirSync(dirPath, { withFileTypes: true });
800
+ fsDirLogger.debug('Directory read complete', { path: dirPath, entryCount: entries.length });
801
+ return entries.map((entry) => ({
802
+ name: entry.name,
803
+ path: node_path.join(dirPath, entry.name),
804
+ isFile: entry.isFile(),
805
+ isDirectory: entry.isDirectory(),
806
+ isSymlink: entry.isSymbolicLink(),
807
+ }));
808
+ }
809
+ catch (error) {
810
+ fsDirLogger.warn('Failed to read directory', { path: dirPath, error: error instanceof Error ? error.message : String(error) });
811
+ throw createFileSystemError(`Failed to read directory: ${dirPath}`, 'FS_READ_ERROR', {
812
+ path: dirPath,
813
+ operation: 'readdir',
814
+ cause: error,
815
+ });
816
+ }
817
+ }
818
+
819
+ createScopedLogger('project-scope:fs:traversal');
820
+
821
+ const packageLogger = createScopedLogger('project-scope:project:package');
822
+ /**
823
+ * Verifies that a value is an object with only string values,
824
+ * used for validating dependency maps and script definitions.
825
+ *
826
+ * @param value - Value to check
827
+ * @returns True if value is a record of strings
828
+ */
829
+ function isStringRecord(value) {
830
+ if (typeof value !== 'object' || value === null)
831
+ return false;
832
+ return values(value).every((v) => typeof v === 'string');
833
+ }
834
+ /**
835
+ * Extracts and normalizes the workspaces field from package.json,
836
+ * supporting both array format and object with packages array.
837
+ *
838
+ * @param value - Raw workspaces value from package.json
839
+ * @returns Normalized workspace patterns or undefined if invalid
840
+ */
841
+ function parseWorkspaces(value) {
842
+ if (isArray(value) && value.every((v) => typeof v === 'string')) {
843
+ return value;
844
+ }
845
+ if (typeof value === 'object' && value !== null) {
846
+ const obj = value;
847
+ if (isArray(obj['packages'])) {
848
+ return { packages: obj['packages'] };
849
+ }
850
+ }
851
+ return undefined;
852
+ }
853
+ /**
854
+ * Validate and normalize package.json data.
855
+ *
856
+ * @param data - Raw parsed data
857
+ * @returns Validated package.json
858
+ */
859
+ function validatePackageJson(data) {
860
+ if (typeof data !== 'object' || data === null) {
861
+ throw createError('package.json must be an object');
862
+ }
863
+ const pkg = data;
864
+ return {
865
+ name: typeof pkg['name'] === 'string' ? pkg['name'] : undefined,
866
+ version: typeof pkg['version'] === 'string' ? pkg['version'] : undefined,
867
+ description: typeof pkg['description'] === 'string' ? pkg['description'] : undefined,
868
+ main: typeof pkg['main'] === 'string' ? pkg['main'] : undefined,
869
+ module: typeof pkg['module'] === 'string' ? pkg['module'] : undefined,
870
+ browser: typeof pkg['browser'] === 'string' ? pkg['browser'] : undefined,
871
+ types: typeof pkg['types'] === 'string' ? pkg['types'] : undefined,
872
+ bin: typeof pkg['bin'] === 'string' || isStringRecord(pkg['bin']) ? pkg['bin'] : undefined,
873
+ scripts: isStringRecord(pkg['scripts']) ? pkg['scripts'] : undefined,
874
+ dependencies: isStringRecord(pkg['dependencies']) ? pkg['dependencies'] : undefined,
875
+ devDependencies: isStringRecord(pkg['devDependencies']) ? pkg['devDependencies'] : undefined,
876
+ peerDependencies: isStringRecord(pkg['peerDependencies']) ? pkg['peerDependencies'] : undefined,
877
+ optionalDependencies: isStringRecord(pkg['optionalDependencies']) ? pkg['optionalDependencies'] : undefined,
878
+ workspaces: parseWorkspaces(pkg['workspaces']),
879
+ exports: typeof pkg['exports'] === 'object' ? pkg['exports'] : undefined,
880
+ engines: isStringRecord(pkg['engines']) ? pkg['engines'] : undefined,
881
+ ...pkg,
882
+ };
883
+ }
884
+ /**
885
+ * Attempts to read and parse package.json if it exists,
886
+ * returning null on missing file or parse failure.
887
+ *
888
+ * @param projectPath - Project directory path or path to package.json
889
+ * @returns Parsed package.json or null if not found
890
+ */
891
+ function readPackageJsonIfExists(projectPath) {
892
+ const packageJsonPath = projectPath.endsWith('package.json') ? projectPath : node_path.join(projectPath, 'package.json');
893
+ const content = readFileIfExists(packageJsonPath);
894
+ if (!content) {
895
+ packageLogger.debug('Package.json not found', { path: packageJsonPath });
896
+ return null;
897
+ }
898
+ try {
899
+ const validated = validatePackageJson(parse(content));
900
+ packageLogger.debug('Package.json loaded', { path: packageJsonPath, name: validated.name });
901
+ return validated;
902
+ }
903
+ catch {
904
+ packageLogger.debug('Failed to parse package.json, returning null', { path: packageJsonPath });
905
+ return null;
906
+ }
907
+ }
908
+
909
+ /**
910
+ * Pattern matching utilities with ReDoS protection.
911
+ * Uses character-by-character matching instead of regex where possible.
912
+ */
913
+ /**
914
+ * Match path against glob pattern using safe character iteration.
915
+ * Avoids regex to prevent ReDoS attacks.
916
+ *
917
+ * Supported patterns:
918
+ * - * matches any characters except /
919
+ * - ** matches any characters including /
920
+ * - ? matches exactly one character except /
921
+ * - {a,b,c} matches any of the alternatives
922
+ *
923
+ * @param path - The filesystem path to test against the pattern
924
+ * @param pattern - The glob pattern to match against
925
+ * @returns True if path matches pattern
926
+ *
927
+ * @example
928
+ * ```typescript
929
+ * import { matchGlobPattern } from '@hyperfrontend/project-scope'
930
+ *
931
+ * matchGlobPattern('src/utils/helper.ts', '\*\*\/*.ts') // true
932
+ * matchGlobPattern('test.spec.ts', '\*.spec.ts') // true
933
+ * matchGlobPattern('config.json', '\*.{json,yaml}') // true
934
+ * matchGlobPattern('src/index.ts', 'src/\*.ts') // true
935
+ * ```
936
+ */
937
+ function matchGlobPattern(path, pattern) {
938
+ return matchSegments(path.split('/'), pattern.split('/'), 0, 0);
939
+ }
940
+ /**
941
+ * Internal recursive function to match path segments against pattern segments.
942
+ *
943
+ * @param pathParts - Array of path segments split by '/'
944
+ * @param patternParts - Array of pattern segments split by '/'
945
+ * @param pathIdx - Current index in pathParts being examined
946
+ * @param patternIdx - Current index in patternParts being examined
947
+ * @returns True if remaining segments match
948
+ */
949
+ function matchSegments(pathParts, patternParts, pathIdx, patternIdx) {
950
+ // Base cases
951
+ if (pathIdx === pathParts.length && patternIdx === patternParts.length) {
952
+ return true; // Both exhausted = match
953
+ }
954
+ if (patternIdx >= patternParts.length) {
955
+ return false; // Pattern exhausted but path remains
956
+ }
957
+ const patternPart = patternParts[patternIdx];
958
+ // Handle ** (globstar) - matches zero or more directories
959
+ if (patternPart === '**') {
960
+ // Try matching rest of pattern against current position and all future positions
961
+ for (let i = pathIdx; i <= pathParts.length; i++) {
962
+ if (matchSegments(pathParts, patternParts, i, patternIdx + 1)) {
963
+ return true;
964
+ }
965
+ }
966
+ return false;
967
+ }
968
+ if (pathIdx >= pathParts.length) {
969
+ return false; // Path exhausted but pattern remains (and it's not **)
970
+ }
971
+ const pathPart = pathParts[pathIdx];
972
+ // Match current segment
973
+ if (matchSegment(pathPart, patternPart)) {
974
+ return matchSegments(pathParts, patternParts, pathIdx + 1, patternIdx + 1);
975
+ }
976
+ return false;
977
+ }
978
+ /**
979
+ * Match a single path segment against a pattern segment.
980
+ * Handles *, ?, and {a,b,c} patterns.
981
+ *
982
+ * @param text - The path segment text to match
983
+ * @param pattern - The pattern segment to match against
984
+ * @returns True if the text matches the pattern
985
+ */
986
+ function matchSegment(text, pattern) {
987
+ let textIdx = 0;
988
+ let patternIdx = 0;
989
+ while (patternIdx < pattern.length) {
990
+ const char = pattern[patternIdx];
991
+ if (char === '*') {
992
+ // * matches zero or more characters
993
+ patternIdx++;
994
+ if (patternIdx === pattern.length) {
995
+ return true; // * at end matches rest of string
996
+ }
997
+ // Try matching rest of pattern at each position in text
998
+ for (let i = textIdx; i <= text.length; i++) {
999
+ if (matchSegmentFrom(text, i, pattern, patternIdx)) {
1000
+ return true;
1001
+ }
1002
+ }
1003
+ return false;
1004
+ }
1005
+ else if (char === '?') {
1006
+ // ? matches exactly one character
1007
+ if (textIdx >= text.length) {
1008
+ return false;
1009
+ }
1010
+ textIdx++;
1011
+ patternIdx++;
1012
+ }
1013
+ else if (char === '{') {
1014
+ // {a,b,c} matches any alternative
1015
+ const closeIdx = findClosingBrace(pattern, patternIdx);
1016
+ if (closeIdx === -1) {
1017
+ // Unmatched brace, treat as literal
1018
+ if (textIdx >= text.length || text[textIdx] !== char) {
1019
+ return false;
1020
+ }
1021
+ textIdx++;
1022
+ patternIdx++;
1023
+ }
1024
+ else {
1025
+ const alternatives = extractAlternatives(pattern.slice(patternIdx + 1, closeIdx));
1026
+ for (const alt of alternatives) {
1027
+ if (matchSegmentFrom(text, textIdx, text.slice(0, textIdx) + alt + pattern.slice(closeIdx + 1), textIdx)) {
1028
+ return true;
1029
+ }
1030
+ }
1031
+ return false;
1032
+ }
1033
+ }
1034
+ else {
1035
+ // Literal character
1036
+ if (textIdx >= text.length || text[textIdx] !== char) {
1037
+ return false;
1038
+ }
1039
+ textIdx++;
1040
+ patternIdx++;
1041
+ }
1042
+ }
1043
+ return textIdx === text.length;
1044
+ }
1045
+ /**
1046
+ * Helper to match from a specific position.
1047
+ *
1048
+ * @param text - The full text being matched
1049
+ * @param textIdx - The starting index in text to match from
1050
+ * @param pattern - The full pattern being matched
1051
+ * @param patternIdx - The starting index in pattern to match from
1052
+ * @returns True if the text matches the pattern from the given positions
1053
+ */
1054
+ function matchSegmentFrom(text, textIdx, pattern, patternIdx) {
1055
+ const remainingText = text.slice(textIdx);
1056
+ const remainingPattern = pattern.slice(patternIdx);
1057
+ return matchSegment(remainingText, remainingPattern);
1058
+ }
1059
+ /**
1060
+ * Find closing brace for {a,b,c} pattern.
1061
+ *
1062
+ * @param pattern - The pattern string to search within
1063
+ * @param startIdx - The index of the opening brace
1064
+ * @returns The index of the matching closing brace, or -1 if not found
1065
+ */
1066
+ function findClosingBrace(pattern, startIdx) {
1067
+ let depth = 0;
1068
+ for (let i = startIdx; i < pattern.length; i++) {
1069
+ if (pattern[i] === '{') {
1070
+ depth++;
1071
+ }
1072
+ else if (pattern[i] === '}') {
1073
+ depth--;
1074
+ if (depth === 0) {
1075
+ return i;
1076
+ }
1077
+ }
1078
+ }
1079
+ return -1;
1080
+ }
1081
+ /**
1082
+ * Extract alternatives from {a,b,c} pattern content.
1083
+ *
1084
+ * @param content - The content between braces (without the braces themselves)
1085
+ * @returns Array of alternative strings split by commas at depth 0
1086
+ */
1087
+ function extractAlternatives(content) {
1088
+ const alternatives = [];
1089
+ let current = '';
1090
+ let depth = 0;
1091
+ for (let i = 0; i < content.length; i++) {
1092
+ const char = content[i];
1093
+ if (char === '{') {
1094
+ depth++;
1095
+ current += char;
1096
+ }
1097
+ else if (char === '}') {
1098
+ depth--;
1099
+ current += char;
1100
+ }
1101
+ else if (char === ',' && depth === 0) {
1102
+ alternatives.push(current);
1103
+ current = '';
1104
+ }
1105
+ else {
1106
+ current += char;
1107
+ }
1108
+ }
1109
+ if (current) {
1110
+ alternatives.push(current);
1111
+ }
1112
+ return alternatives;
1113
+ }
1114
+
1115
+ const walkLogger = createScopedLogger('project-scope:project:walk');
1116
+ /**
1117
+ * Reads .gitignore file from the given directory and extracts
1118
+ * non-comment patterns for use in file traversal filtering.
1119
+ *
1120
+ * @param startPath - Directory containing the .gitignore file
1121
+ * @returns Array of gitignore patterns
1122
+ */
1123
+ function loadGitignorePatterns(startPath) {
1124
+ const patterns = [];
1125
+ const gitignorePath = node_path.join(startPath, '.gitignore');
1126
+ const content = readFileIfExists(gitignorePath);
1127
+ if (content) {
1128
+ const lines = content.split('\n');
1129
+ for (const line of lines) {
1130
+ const trimmed = line.trim();
1131
+ if (trimmed && !trimmed.startsWith('#')) {
1132
+ patterns.push(trimmed);
1133
+ }
1134
+ }
1135
+ }
1136
+ return patterns;
1137
+ }
1138
+ /**
1139
+ * Evaluates whether a relative path should be ignored based on
1140
+ * a list of gitignore-style patterns.
1141
+ *
1142
+ * @param relativePath - Path relative to the root directory
1143
+ * @param patterns - Array of gitignore-style patterns to test
1144
+ * @returns True if the path matches any ignore pattern
1145
+ */
1146
+ function matchesIgnorePattern(relativePath, patterns) {
1147
+ for (const pattern of patterns) {
1148
+ if (matchPattern(relativePath, pattern)) {
1149
+ return true;
1150
+ }
1151
+ }
1152
+ return false;
1153
+ }
1154
+ /**
1155
+ * Tests if the given path matches a gitignore-style pattern,
1156
+ * supporting negation patterns with '!' prefix.
1157
+ * Uses safe character-by-character matching to prevent ReDoS attacks.
1158
+ *
1159
+ * @param path - File or directory path to test
1160
+ * @param pattern - Gitignore-style pattern (may include wildcards)
1161
+ * @returns True if the path matches the pattern (or doesn't match if negated)
1162
+ */
1163
+ function matchPattern(path, pattern) {
1164
+ const normalizedPattern = pattern.startsWith('/') ? pattern.slice(1) : pattern;
1165
+ const isNegation = normalizedPattern.startsWith('!');
1166
+ const actualPattern = isNegation ? normalizedPattern.slice(1) : normalizedPattern;
1167
+ const matchesFullPath = matchGlobPattern(path, actualPattern) || matchGlobPattern(path, `**/${actualPattern}`);
1168
+ const matchesSegment = path.split('/').some((segment) => matchGlobPattern(segment, actualPattern));
1169
+ const matches = matchesFullPath || matchesSegment;
1170
+ return isNegation ? !matches : matches;
1171
+ }
1172
+ /**
1173
+ * Traverses a directory tree synchronously, calling a visitor function
1174
+ * for each file and directory encountered. Supports depth limiting,
1175
+ * hidden file filtering, and gitignore pattern matching.
1176
+ *
1177
+ * @param startPath - Root directory to begin traversal
1178
+ * @param visitor - Callback function invoked for each file system entry
1179
+ * @param options - Configuration for traversal behavior
1180
+ */
1181
+ function walkDirectory(startPath, visitor, options) {
1182
+ walkLogger.debug('Starting directory walk', {
1183
+ startPath,
1184
+ maxDepth: options?.maxDepth ?? -1,
1185
+ includeHidden: options?.includeHidden ?? false,
1186
+ respectGitignore: options?.respectGitignore ?? true,
1187
+ ignorePatterns: options?.ignorePatterns?.length ?? 0,
1188
+ });
1189
+ const maxDepth = options?.maxDepth ?? -1;
1190
+ const includeHidden = options?.includeHidden ?? false;
1191
+ const ignorePatterns = options?.ignorePatterns ?? [];
1192
+ const respectGitignore = options?.respectGitignore ?? true;
1193
+ const gitignorePatterns = respectGitignore ? loadGitignorePatterns(startPath) : [];
1194
+ const allIgnorePatterns = [...ignorePatterns, ...gitignorePatterns];
1195
+ if (gitignorePatterns.length > 0) {
1196
+ walkLogger.debug('Loaded gitignore patterns', { count: gitignorePatterns.length });
1197
+ }
1198
+ /**
1199
+ * Recursively walks directory entries, applying visitor to each.
1200
+ *
1201
+ * @param currentPath - Absolute path to current directory
1202
+ * @param relativePath - Path relative to the starting directory
1203
+ * @param depth - Current recursion depth
1204
+ * @returns False to stop walking, true to continue
1205
+ */
1206
+ function walk(currentPath, relativePath, depth) {
1207
+ if (maxDepth !== -1 && depth > maxDepth) {
1208
+ return true;
1209
+ }
1210
+ let entries;
1211
+ try {
1212
+ entries = readDirectory(currentPath);
1213
+ }
1214
+ catch {
1215
+ return true;
1216
+ }
1217
+ for (const entry of entries) {
1218
+ if (!includeHidden && entry.name.startsWith('.')) {
1219
+ continue;
1220
+ }
1221
+ const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
1222
+ if (matchesIgnorePattern(entryRelativePath, allIgnorePatterns)) {
1223
+ continue;
1224
+ }
1225
+ const walkEntry = {
1226
+ name: entry.name,
1227
+ path: entry.path,
1228
+ relativePath: entryRelativePath,
1229
+ isFile: entry.isFile,
1230
+ isDirectory: entry.isDirectory,
1231
+ isSymlink: entry.isSymlink,
1232
+ depth,
1233
+ };
1234
+ const result = visitor(walkEntry);
1235
+ if (result === 'stop') {
1236
+ return false;
1237
+ }
1238
+ if (result === 'skip') {
1239
+ continue;
1240
+ }
1241
+ if (entry.isDirectory) {
1242
+ const shouldContinue = walk(entry.path, entryRelativePath, depth + 1);
1243
+ if (!shouldContinue) {
1244
+ return false;
1245
+ }
1246
+ }
1247
+ }
1248
+ return true;
1249
+ }
1250
+ walk(startPath, '', 0);
1251
+ walkLogger.debug('Directory walk complete', { startPath });
1252
+ }
1253
+
1254
+ const searchLogger = createScopedLogger('project-scope:project:search');
1255
+ /**
1256
+ * Tests if a path matches at least one pattern from an array of globs,
1257
+ * enabling flexible multi-pattern file filtering.
1258
+ * Uses safe character-by-character matching to prevent ReDoS attacks.
1259
+ *
1260
+ * @param path - File path to test
1261
+ * @param patterns - Array of glob patterns
1262
+ * @returns True if path matches any pattern
1263
+ */
1264
+ function matchesPatterns(path, patterns) {
1265
+ return patterns.some((pattern) => matchGlobPattern(path, pattern));
1266
+ }
1267
+ /**
1268
+ * Searches a directory tree for files matching one or more glob patterns,
1269
+ * returning relative or absolute paths based on options.
1270
+ *
1271
+ * @param startPath - Root directory to begin the search
1272
+ * @param patterns - Glob patterns (e.g., '*.ts', '**\/*.json') to filter files
1273
+ * @param options - Configuration for search behavior
1274
+ * @returns List of relative file paths that match the patterns
1275
+ *
1276
+ * @example
1277
+ * ```typescript
1278
+ * import { findFiles } from '@hyperfrontend/project-scope'
1279
+ *
1280
+ * // Find all TypeScript files
1281
+ * const tsFiles = findFiles('./src', '\*\*\/*.ts')
1282
+ *
1283
+ * // Find multiple file types
1284
+ * const configFiles = findFiles('./', ['\*.json', '\*.yaml', '\*.yml'])
1285
+ *
1286
+ * // Limit results and get absolute paths
1287
+ * const first10 = findFiles('./src', '\*\*\/*.ts', {
1288
+ * maxResults: 10,
1289
+ * absolutePaths: true
1290
+ * })
1291
+ * ```
1292
+ */
1293
+ function findFiles(startPath, patterns, options) {
1294
+ const normalizedPatterns = isArray(patterns) ? patterns : [patterns];
1295
+ searchLogger.debug('Finding files', { startPath, patterns: normalizedPatterns, maxResults: options?.maxResults });
1296
+ const results = [];
1297
+ const maxResults = options?.maxResults ?? Infinity;
1298
+ walkDirectory(startPath, (entry) => {
1299
+ if (results.length >= maxResults) {
1300
+ return 'stop';
1301
+ }
1302
+ if (!entry.isFile) {
1303
+ return undefined;
1304
+ }
1305
+ if (matchesPatterns(entry.relativePath, normalizedPatterns)) {
1306
+ results.push(options?.absolutePaths ? entry.path : entry.relativePath);
1307
+ }
1308
+ return undefined;
1309
+ }, options);
1310
+ searchLogger.debug('File search complete', { startPath, matchCount: results.length });
1311
+ return results;
1312
+ }
1313
+
1314
+ const entryPointLogger = createScopedLogger('project-scope:heuristics:entry-points');
1315
+ /**
1316
+ * Cache for entry point discovery results.
1317
+ * TTL: 60 seconds (entry points are relatively stable)
1318
+ */
1319
+ const entryPointCache = createCache({ ttl: 60000, maxSize: 50 });
1320
+ /**
1321
+ * Common entry point patterns.
1322
+ */
1323
+ const ENTRY_POINT_PATTERNS = {
1324
+ /** Library entry patterns */
1325
+ library: ['src/index.ts', 'src/index.js', 'index.ts', 'index.js', 'lib/index.ts'],
1326
+ /** Application entry patterns */
1327
+ application: ['src/main.ts', 'src/main.tsx', 'main.ts', 'src/app.ts', 'app.ts'],
1328
+ /** Server entry patterns */
1329
+ server: ['src/server.ts', 'server.ts', 'src/main.ts'],
1330
+ /** CLI entry patterns */
1331
+ cli: ['src/cli.ts', 'bin/cli.ts', 'cli.ts'],
1332
+ };
1333
+ /**
1334
+ * Convention-based entry patterns with types and confidence.
1335
+ */
1336
+ const CONVENTION_ENTRIES = [
1337
+ { pattern: 'src/index.ts', type: 'main', confidence: 90 },
1338
+ { pattern: 'src/index.js', type: 'main', confidence: 90 },
1339
+ { pattern: 'src/main.ts', type: 'app', confidence: 85 },
1340
+ { pattern: 'src/main.tsx', type: 'app', confidence: 85 },
1341
+ { pattern: 'src/app.ts', type: 'app', confidence: 80 },
1342
+ { pattern: 'src/app.tsx', type: 'app', confidence: 80 },
1343
+ { pattern: 'src/server.ts', type: 'server', confidence: 85 },
1344
+ { pattern: 'src/server.js', type: 'server', confidence: 85 },
1345
+ { pattern: 'server.ts', type: 'server', confidence: 80 },
1346
+ { pattern: 'server.js', type: 'server', confidence: 80 },
1347
+ { pattern: 'index.ts', type: 'main', confidence: 85 },
1348
+ { pattern: 'index.js', type: 'main', confidence: 85 },
1349
+ { pattern: 'lib/index.ts', type: 'main', confidence: 80 },
1350
+ { pattern: 'lib/index.js', type: 'main', confidence: 80 },
1351
+ { pattern: 'src/cli.ts', type: 'cli', confidence: 85 },
1352
+ { pattern: 'bin/cli.ts', type: 'cli', confidence: 85 },
1353
+ { pattern: 'cli.ts', type: 'cli', confidence: 80 },
1354
+ ];
1355
+ /**
1356
+ * Extract entry points from exports field.
1357
+ *
1358
+ * @param exports - The exports field from package.json
1359
+ * @param entryPoints - Array to add entry points to
1360
+ */
1361
+ function discoverFromExports(exports$1, entryPoints) {
1362
+ for (const [key, value] of entries(exports$1)) {
1363
+ if (typeof value === 'string') {
1364
+ if (!entryPoints.some((e) => e.path === value)) {
1365
+ entryPoints.push({
1366
+ path: value,
1367
+ type: 'main',
1368
+ confidence: 100,
1369
+ source: { type: 'package.json', field: `exports["${key}"]` },
1370
+ });
1371
+ }
1372
+ }
1373
+ else if (typeof value === 'object' && value !== null) {
1374
+ const conditions = value;
1375
+ const paths = [conditions['import'], conditions['require'], conditions['default'], conditions['types']].filter((p) => typeof p === 'string');
1376
+ if (paths.length > 0) {
1377
+ const mainPath = paths[0];
1378
+ if (!entryPoints.some((e) => e.path === mainPath)) {
1379
+ entryPoints.push({
1380
+ path: mainPath,
1381
+ type: 'main',
1382
+ confidence: 100,
1383
+ source: { type: 'package.json', field: `exports["${key}"]` },
1384
+ });
1385
+ }
1386
+ }
1387
+ }
1388
+ }
1389
+ }
1390
+ /**
1391
+ * Discover entry points in project.
1392
+ *
1393
+ * Analyzes package.json fields (main, module, bin, exports),
1394
+ * convention-based patterns, and framework-specific entries.
1395
+ *
1396
+ * Results are cached for 60 seconds per project path and options
1397
+ * to avoid redundant file system operations on repeated calls.
1398
+ *
1399
+ * @param projectPath - Project directory path
1400
+ * @param options - Discovery options
1401
+ * @returns Array of discovered entry points sorted by confidence
1402
+ *
1403
+ * @example
1404
+ * ```typescript
1405
+ * import { discoverEntryPoints } from '@hyperfrontend/project-scope'
1406
+ *
1407
+ * const entryPoints = discoverEntryPoints('./my-app')
1408
+ * for (const entry of entryPoints) {
1409
+ * console.log(`${entry.path} (${entry.type}) - ${entry.confidence}% confidence`)
1410
+ * }
1411
+ * // Output:
1412
+ * // src/index.ts (main) - 100% confidence
1413
+ * // src/cli.ts (cli) - 85% confidence
1414
+ * ```
1415
+ */
1416
+ function discoverEntryPoints(projectPath, options) {
1417
+ entryPointLogger.debug('Discovering entry points', { projectPath, options });
1418
+ const includeFramework = options?.includeFrameworkEntries !== false;
1419
+ const maxDepth = options?.maxDepth ?? 5;
1420
+ const cacheKey = `${projectPath}:${includeFramework}:${maxDepth}`;
1421
+ if (!options?.skipCache) {
1422
+ const cached = entryPointCache.get(cacheKey);
1423
+ if (cached) {
1424
+ entryPointLogger.debug('Returning cached entry points', { projectPath });
1425
+ return cached;
1426
+ }
1427
+ }
1428
+ const extendedEntryPoints = [];
1429
+ const packageJson = readPackageJsonIfExists(projectPath);
1430
+ if (packageJson) {
1431
+ entryPointLogger.debug('Reading entry points from package.json');
1432
+ if (packageJson.main && typeof packageJson.main === 'string') {
1433
+ extendedEntryPoints.push({
1434
+ path: packageJson.main,
1435
+ type: 'main',
1436
+ confidence: 100,
1437
+ source: { type: 'package.json', field: 'main' },
1438
+ });
1439
+ }
1440
+ if (packageJson.module && typeof packageJson.module === 'string') {
1441
+ if (!extendedEntryPoints.some((e) => e.path === packageJson.module)) {
1442
+ extendedEntryPoints.push({
1443
+ path: packageJson.module,
1444
+ type: 'main',
1445
+ confidence: 100,
1446
+ source: { type: 'package.json', field: 'module' },
1447
+ });
1448
+ }
1449
+ }
1450
+ if (packageJson.browser && typeof packageJson.browser === 'string') {
1451
+ if (!extendedEntryPoints.some((e) => e.path === packageJson.browser)) {
1452
+ extendedEntryPoints.push({
1453
+ path: packageJson.browser,
1454
+ type: 'main',
1455
+ confidence: 95,
1456
+ source: { type: 'package.json', field: 'browser' },
1457
+ });
1458
+ }
1459
+ }
1460
+ if (packageJson.bin) {
1461
+ const bins = typeof packageJson.bin === 'string' ? { [packageJson.name ?? 'cli']: packageJson.bin } : packageJson.bin;
1462
+ for (const [name, path] of entries(bins)) {
1463
+ if (typeof path === 'string' && !extendedEntryPoints.some((e) => e.path === path)) {
1464
+ extendedEntryPoints.push({
1465
+ path,
1466
+ type: 'cli',
1467
+ confidence: 100,
1468
+ source: { type: 'package.json', field: `bin.${name}` },
1469
+ });
1470
+ }
1471
+ }
1472
+ }
1473
+ if (packageJson.exports && typeof packageJson.exports === 'object') {
1474
+ discoverFromExports(packageJson.exports, extendedEntryPoints);
1475
+ }
1476
+ }
1477
+ for (const entry of CONVENTION_ENTRIES) {
1478
+ const fullPath = node_path.join(projectPath, entry.pattern);
1479
+ if (exists(fullPath)) {
1480
+ if (!extendedEntryPoints.some((e) => e.path === entry.pattern)) {
1481
+ extendedEntryPoints.push({
1482
+ path: entry.pattern,
1483
+ type: entry.type,
1484
+ confidence: entry.confidence,
1485
+ source: { type: 'convention', pattern: entry.pattern },
1486
+ });
1487
+ }
1488
+ }
1489
+ }
1490
+ if (options?.includeFrameworkEntries !== false) {
1491
+ const hasNextPages = exists(node_path.join(projectPath, 'pages')) || exists(node_path.join(projectPath, 'src', 'pages'));
1492
+ const hasNextApp = exists(node_path.join(projectPath, 'app')) || exists(node_path.join(projectPath, 'src', 'app'));
1493
+ if (hasNextPages || hasNextApp) {
1494
+ const pagesDir = exists(node_path.join(projectPath, 'pages')) ? 'pages' : 'src/pages';
1495
+ const appDir = exists(node_path.join(projectPath, 'app')) ? 'app' : 'src/app';
1496
+ if (hasNextPages) {
1497
+ const pageFiles = findFiles(projectPath, `${pagesDir}/**/*.{ts,tsx,js,jsx}`, {
1498
+ maxDepth: options?.maxDepth ?? 5,
1499
+ });
1500
+ for (const file of pageFiles.slice(0, 10)) {
1501
+ if (!file.includes('_app') && !file.includes('_document') && !file.includes('api/')) {
1502
+ extendedEntryPoints.push({
1503
+ path: file,
1504
+ type: 'app',
1505
+ confidence: 80,
1506
+ source: { type: 'framework', framework: 'nextjs' },
1507
+ });
1508
+ }
1509
+ }
1510
+ }
1511
+ if (hasNextApp) {
1512
+ const appFiles = findFiles(projectPath, `${appDir}/**/page.{ts,tsx,js,jsx}`, {
1513
+ maxDepth: options?.maxDepth ?? 5,
1514
+ });
1515
+ for (const file of appFiles.slice(0, 10)) {
1516
+ extendedEntryPoints.push({
1517
+ path: file,
1518
+ type: 'app',
1519
+ confidence: 80,
1520
+ source: { type: 'framework', framework: 'nextjs' },
1521
+ });
1522
+ }
1523
+ }
1524
+ }
1525
+ const angularMain = node_path.join(projectPath, 'src', 'main.ts');
1526
+ if (exists(angularMain) && exists(node_path.join(projectPath, 'angular.json'))) {
1527
+ if (!extendedEntryPoints.some((e) => e.path === 'src/main.ts' && e.source.type === 'framework')) {
1528
+ extendedEntryPoints.push({
1529
+ path: 'src/main.ts',
1530
+ type: 'app',
1531
+ confidence: 95,
1532
+ source: { type: 'framework', framework: 'angular' },
1533
+ });
1534
+ }
1535
+ }
1536
+ const hasSvelteRoutes = exists(node_path.join(projectPath, 'src', 'routes'));
1537
+ if (hasSvelteRoutes && exists(node_path.join(projectPath, 'svelte.config.js'))) {
1538
+ const routeFiles = findFiles(projectPath, 'src/routes/**/+page.svelte', {
1539
+ maxDepth: options?.maxDepth ?? 5,
1540
+ });
1541
+ for (const file of routeFiles.slice(0, 10)) {
1542
+ extendedEntryPoints.push({
1543
+ path: file,
1544
+ type: 'app',
1545
+ confidence: 80,
1546
+ source: { type: 'framework', framework: 'sveltekit' },
1547
+ });
1548
+ }
1549
+ }
1550
+ }
1551
+ extendedEntryPoints.sort((a, b) => b.confidence - a.confidence);
1552
+ entryPointLogger.debug('Entry point discovery complete', {
1553
+ projectPath,
1554
+ totalFound: extendedEntryPoints.length,
1555
+ bySource: {
1556
+ packageJson: extendedEntryPoints.filter((e) => e.source.type === 'package.json').length,
1557
+ convention: extendedEntryPoints.filter((e) => e.source.type === 'convention').length,
1558
+ framework: extendedEntryPoints.filter((e) => e.source.type === 'framework').length,
1559
+ },
1560
+ });
1561
+ const result = extendedEntryPoints.map((e) => ({
1562
+ path: e.path,
1563
+ type: e.type,
1564
+ confidence: e.confidence,
1565
+ }));
1566
+ entryPointCache.set(cacheKey, result);
1567
+ return result;
1568
+ }
1569
+ /**
1570
+ * Clear the entry point discovery cache.
1571
+ *
1572
+ * Useful for testing or when the project files have changed.
1573
+ */
1574
+ function clearEntryPointCache() {
1575
+ entryPointCache.clear();
1576
+ }
1577
+
1578
+ exports.ENTRY_POINT_PATTERNS = ENTRY_POINT_PATTERNS;
1579
+ exports.clearEntryPointCache = clearEntryPointCache;
1580
+ exports.discoverEntryPoints = discoverEntryPoints;
1581
+ //# sourceMappingURL=index.cjs.js.map