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