@hyperfrontend/project-scope 0.2.0 → 0.2.2

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