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