funkscript 0.0.0-stage → 0.2.4

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 (631) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -2
  3. package/dist/Widget.tsx +9 -0
  4. package/dist/ast/types.d.ts +513 -0
  5. package/dist/ast/types.d.ts.map +1 -0
  6. package/dist/ast/types.js +5 -0
  7. package/dist/ast/types.js.map +1 -0
  8. package/dist/ast/walk.d.ts +8 -0
  9. package/dist/ast/walk.d.ts.map +1 -0
  10. package/dist/ast/walk.js +23 -0
  11. package/dist/ast/walk.js.map +1 -0
  12. package/dist/cli/build-bun.d.ts +24 -0
  13. package/dist/cli/build-bun.d.ts.map +1 -0
  14. package/dist/cli/build-bun.js +190 -0
  15. package/dist/cli/build-bun.js.map +1 -0
  16. package/dist/cli/build-watch.d.ts +21 -0
  17. package/dist/cli/build-watch.d.ts.map +1 -0
  18. package/dist/cli/build-watch.js +244 -0
  19. package/dist/cli/build-watch.js.map +1 -0
  20. package/dist/cli/build.d.ts +4 -0
  21. package/dist/cli/build.d.ts.map +1 -0
  22. package/dist/cli/build.js +338 -0
  23. package/dist/cli/build.js.map +1 -0
  24. package/dist/cli/check.d.ts +4 -0
  25. package/dist/cli/check.d.ts.map +1 -0
  26. package/dist/cli/check.js +278 -0
  27. package/dist/cli/check.js.map +1 -0
  28. package/dist/cli/commands.d.ts +13 -0
  29. package/dist/cli/commands.d.ts.map +1 -0
  30. package/dist/cli/commands.js +262 -0
  31. package/dist/cli/commands.js.map +1 -0
  32. package/dist/cli/doc.d.ts +3 -0
  33. package/dist/cli/doc.d.ts.map +1 -0
  34. package/dist/cli/doc.js +71 -0
  35. package/dist/cli/doc.js.map +1 -0
  36. package/dist/cli/doctor.d.ts +3 -0
  37. package/dist/cli/doctor.d.ts.map +1 -0
  38. package/dist/cli/doctor.js +121 -0
  39. package/dist/cli/doctor.js.map +1 -0
  40. package/dist/cli/emit.d.ts +4 -0
  41. package/dist/cli/emit.d.ts.map +1 -0
  42. package/dist/cli/emit.js +87 -0
  43. package/dist/cli/emit.js.map +1 -0
  44. package/dist/cli/explain.d.ts +3 -0
  45. package/dist/cli/explain.d.ts.map +1 -0
  46. package/dist/cli/explain.js +103 -0
  47. package/dist/cli/explain.js.map +1 -0
  48. package/dist/cli/fmt.d.ts +3 -0
  49. package/dist/cli/fmt.d.ts.map +1 -0
  50. package/dist/cli/fmt.js +146 -0
  51. package/dist/cli/fmt.js.map +1 -0
  52. package/dist/cli/index.d.ts +3 -0
  53. package/dist/cli/index.d.ts.map +1 -0
  54. package/dist/cli/index.js +186 -0
  55. package/dist/cli/index.js.map +1 -0
  56. package/dist/cli/init.d.ts +10 -0
  57. package/dist/cli/init.d.ts.map +1 -0
  58. package/dist/cli/init.js +412 -0
  59. package/dist/cli/init.js.map +1 -0
  60. package/dist/cli/io.d.ts +9 -0
  61. package/dist/cli/io.d.ts.map +1 -0
  62. package/dist/cli/io.js +113 -0
  63. package/dist/cli/io.js.map +1 -0
  64. package/dist/cli/output-collisions.d.ts +2 -0
  65. package/dist/cli/output-collisions.d.ts.map +1 -0
  66. package/dist/cli/output-collisions.js +39 -0
  67. package/dist/cli/output-collisions.js.map +1 -0
  68. package/dist/cli/pipeline-style.d.ts +3 -0
  69. package/dist/cli/pipeline-style.d.ts.map +1 -0
  70. package/dist/cli/pipeline-style.js +45 -0
  71. package/dist/cli/pipeline-style.js.map +1 -0
  72. package/dist/cli/repl.d.ts +37 -0
  73. package/dist/cli/repl.d.ts.map +1 -0
  74. package/dist/cli/repl.js +334 -0
  75. package/dist/cli/repl.js.map +1 -0
  76. package/dist/cli/run.d.ts +4 -0
  77. package/dist/cli/run.d.ts.map +1 -0
  78. package/dist/cli/run.js +185 -0
  79. package/dist/cli/run.js.map +1 -0
  80. package/dist/cli/test.d.ts +3 -0
  81. package/dist/cli/test.d.ts.map +1 -0
  82. package/dist/cli/test.js +124 -0
  83. package/dist/cli/test.js.map +1 -0
  84. package/dist/cli/tsc.d.ts +3 -0
  85. package/dist/cli/tsc.d.ts.map +1 -0
  86. package/dist/cli/tsc.js +143 -0
  87. package/dist/cli/tsc.js.map +1 -0
  88. package/dist/cli/typecheck.d.ts +23 -0
  89. package/dist/cli/typecheck.d.ts.map +1 -0
  90. package/dist/cli/typecheck.js +65 -0
  91. package/dist/cli/typecheck.js.map +1 -0
  92. package/dist/compiler/ast-inspection.d.ts +18 -0
  93. package/dist/compiler/ast-inspection.d.ts.map +1 -0
  94. package/dist/compiler/ast-inspection.js +96 -0
  95. package/dist/compiler/ast-inspection.js.map +1 -0
  96. package/dist/compiler/boolean-operators.d.ts +8 -0
  97. package/dist/compiler/boolean-operators.d.ts.map +1 -0
  98. package/dist/compiler/boolean-operators.js +84 -0
  99. package/dist/compiler/boolean-operators.js.map +1 -0
  100. package/dist/compiler/check.d.ts +87 -0
  101. package/dist/compiler/check.d.ts.map +1 -0
  102. package/dist/compiler/check.js +1830 -0
  103. package/dist/compiler/check.js.map +1 -0
  104. package/dist/compiler/diagnostics.d.ts +6 -0
  105. package/dist/compiler/diagnostics.d.ts.map +1 -0
  106. package/dist/compiler/diagnostics.js +136 -0
  107. package/dist/compiler/diagnostics.js.map +1 -0
  108. package/dist/compiler/effect-mutation-rule.d.ts +4 -0
  109. package/dist/compiler/effect-mutation-rule.d.ts.map +1 -0
  110. package/dist/compiler/effect-mutation-rule.js +348 -0
  111. package/dist/compiler/effect-mutation-rule.js.map +1 -0
  112. package/dist/compiler/entry-rules.d.ts +5 -0
  113. package/dist/compiler/entry-rules.d.ts.map +1 -0
  114. package/dist/compiler/entry-rules.js +89 -0
  115. package/dist/compiler/entry-rules.js.map +1 -0
  116. package/dist/compiler/imported-record-functions.d.ts +4 -0
  117. package/dist/compiler/imported-record-functions.d.ts.map +1 -0
  118. package/dist/compiler/imported-record-functions.js +706 -0
  119. package/dist/compiler/imported-record-functions.js.map +1 -0
  120. package/dist/compiler/imported-schemas.d.ts +21 -0
  121. package/dist/compiler/imported-schemas.d.ts.map +1 -0
  122. package/dist/compiler/imported-schemas.js +461 -0
  123. package/dist/compiler/imported-schemas.js.map +1 -0
  124. package/dist/compiler/incremental-build.d.ts +23 -0
  125. package/dist/compiler/incremental-build.d.ts.map +1 -0
  126. package/dist/compiler/incremental-build.js +90 -0
  127. package/dist/compiler/incremental-build.js.map +1 -0
  128. package/dist/compiler/incremental-dependencies.d.ts +7 -0
  129. package/dist/compiler/incremental-dependencies.d.ts.map +1 -0
  130. package/dist/compiler/incremental-dependencies.js +190 -0
  131. package/dist/compiler/incremental-dependencies.js.map +1 -0
  132. package/dist/compiler/js-interop-nullability.d.ts +9 -0
  133. package/dist/compiler/js-interop-nullability.d.ts.map +1 -0
  134. package/dist/compiler/js-interop-nullability.js +57 -0
  135. package/dist/compiler/js-interop-nullability.js.map +1 -0
  136. package/dist/compiler/module-resolution.d.ts +6 -0
  137. package/dist/compiler/module-resolution.d.ts.map +1 -0
  138. package/dist/compiler/module-resolution.js +44 -0
  139. package/dist/compiler/module-resolution.js.map +1 -0
  140. package/dist/compiler/modules/output-collisions.d.ts +2 -0
  141. package/dist/compiler/modules/output-collisions.d.ts.map +1 -0
  142. package/dist/compiler/modules/output-collisions.js +39 -0
  143. package/dist/compiler/modules/output-collisions.js.map +1 -0
  144. package/dist/compiler/modules/output-plan.d.ts +7 -0
  145. package/dist/compiler/modules/output-plan.d.ts.map +1 -0
  146. package/dist/compiler/modules/output-plan.js +37 -0
  147. package/dist/compiler/modules/output-plan.js.map +1 -0
  148. package/dist/compiler/modules/resolution.d.ts +8 -0
  149. package/dist/compiler/modules/resolution.d.ts.map +1 -0
  150. package/dist/compiler/modules/resolution.js +48 -0
  151. package/dist/compiler/modules/resolution.js.map +1 -0
  152. package/dist/compiler/numeric-comparisons.d.ts +9 -0
  153. package/dist/compiler/numeric-comparisons.d.ts.map +1 -0
  154. package/dist/compiler/numeric-comparisons.js +153 -0
  155. package/dist/compiler/numeric-comparisons.js.map +1 -0
  156. package/dist/compiler/optional-arguments.d.ts +11 -0
  157. package/dist/compiler/optional-arguments.d.ts.map +1 -0
  158. package/dist/compiler/optional-arguments.js +246 -0
  159. package/dist/compiler/optional-arguments.js.map +1 -0
  160. package/dist/compiler/package-fingerprint.d.ts +7 -0
  161. package/dist/compiler/package-fingerprint.d.ts.map +1 -0
  162. package/dist/compiler/package-fingerprint.js +178 -0
  163. package/dist/compiler/package-fingerprint.js.map +1 -0
  164. package/dist/compiler/package-record-contracts.d.ts +5 -0
  165. package/dist/compiler/package-record-contracts.d.ts.map +1 -0
  166. package/dist/compiler/package-record-contracts.js +126 -0
  167. package/dist/compiler/package-record-contracts.js.map +1 -0
  168. package/dist/compiler/pipeline-companions.d.ts +18 -0
  169. package/dist/compiler/pipeline-companions.d.ts.map +1 -0
  170. package/dist/compiler/pipeline-companions.js +1042 -0
  171. package/dist/compiler/pipeline-companions.js.map +1 -0
  172. package/dist/compiler/pipelines/catalog.d.ts +15 -0
  173. package/dist/compiler/pipelines/catalog.d.ts.map +1 -0
  174. package/dist/compiler/pipelines/catalog.js +55 -0
  175. package/dist/compiler/pipelines/catalog.js.map +1 -0
  176. package/dist/compiler/pipelines/companions.d.ts +18 -0
  177. package/dist/compiler/pipelines/companions.d.ts.map +1 -0
  178. package/dist/compiler/pipelines/companions.js +1042 -0
  179. package/dist/compiler/pipelines/companions.js.map +1 -0
  180. package/dist/compiler/pipelines/resolution.d.ts +38 -0
  181. package/dist/compiler/pipelines/resolution.d.ts.map +1 -0
  182. package/dist/compiler/pipelines/resolution.js +571 -0
  183. package/dist/compiler/pipelines/resolution.js.map +1 -0
  184. package/dist/compiler/project-config.d.ts +28 -0
  185. package/dist/compiler/project-config.d.ts.map +1 -0
  186. package/dist/compiler/project-config.js +155 -0
  187. package/dist/compiler/project-config.js.map +1 -0
  188. package/dist/compiler/providers.d.ts +4 -0
  189. package/dist/compiler/providers.d.ts.map +1 -0
  190. package/dist/compiler/providers.js +101 -0
  191. package/dist/compiler/providers.js.map +1 -0
  192. package/dist/compiler/record-contracts.d.ts +6 -0
  193. package/dist/compiler/record-contracts.d.ts.map +1 -0
  194. package/dist/compiler/record-contracts.js +41 -0
  195. package/dist/compiler/record-contracts.js.map +1 -0
  196. package/dist/compiler/rules/control-flow.d.ts +10 -0
  197. package/dist/compiler/rules/control-flow.d.ts.map +1 -0
  198. package/dist/compiler/rules/control-flow.js +19 -0
  199. package/dist/compiler/rules/control-flow.js.map +1 -0
  200. package/dist/compiler/rules/diagnostic.d.ts +4 -0
  201. package/dist/compiler/rules/diagnostic.d.ts.map +1 -0
  202. package/dist/compiler/rules/diagnostic.js +2 -0
  203. package/dist/compiler/rules/diagnostic.js.map +1 -0
  204. package/dist/compiler/rules/module-scope-refs.d.ts +5 -0
  205. package/dist/compiler/rules/module-scope-refs.d.ts.map +1 -0
  206. package/dist/compiler/rules/module-scope-refs.js +47 -0
  207. package/dist/compiler/rules/module-scope-refs.js.map +1 -0
  208. package/dist/compiler/schemas/analysis.d.ts +13 -0
  209. package/dist/compiler/schemas/analysis.d.ts.map +1 -0
  210. package/dist/compiler/schemas/analysis.js +24 -0
  211. package/dist/compiler/schemas/analysis.js.map +1 -0
  212. package/dist/compiler/schemas/imported-record-functions.d.ts +4 -0
  213. package/dist/compiler/schemas/imported-record-functions.d.ts.map +1 -0
  214. package/dist/compiler/schemas/imported-record-functions.js +706 -0
  215. package/dist/compiler/schemas/imported-record-functions.js.map +1 -0
  216. package/dist/compiler/schemas/imported-schemas.d.ts +21 -0
  217. package/dist/compiler/schemas/imported-schemas.d.ts.map +1 -0
  218. package/dist/compiler/schemas/imported-schemas.js +461 -0
  219. package/dist/compiler/schemas/imported-schemas.js.map +1 -0
  220. package/dist/compiler/source-map.d.ts +6 -0
  221. package/dist/compiler/source-map.d.ts.map +1 -0
  222. package/dist/compiler/source-map.js +127 -0
  223. package/dist/compiler/source-map.js.map +1 -0
  224. package/dist/compiler/typescript-context.d.ts +33 -0
  225. package/dist/compiler/typescript-context.d.ts.map +1 -0
  226. package/dist/compiler/typescript-context.js +200 -0
  227. package/dist/compiler/typescript-context.js.map +1 -0
  228. package/dist/compiler.d.ts +77 -0
  229. package/dist/compiler.d.ts.map +1 -0
  230. package/dist/compiler.js +497 -0
  231. package/dist/compiler.js.map +1 -0
  232. package/dist/emitter/assemblyscript.d.ts +5 -0
  233. package/dist/emitter/assemblyscript.d.ts.map +1 -0
  234. package/dist/emitter/assemblyscript.js +979 -0
  235. package/dist/emitter/assemblyscript.js.map +1 -0
  236. package/dist/emitter/declarations.d.ts +46 -0
  237. package/dist/emitter/declarations.d.ts.map +1 -0
  238. package/dist/emitter/declarations.js +739 -0
  239. package/dist/emitter/declarations.js.map +1 -0
  240. package/dist/emitter/emitter.d.ts +165 -0
  241. package/dist/emitter/emitter.d.ts.map +1 -0
  242. package/dist/emitter/emitter.js +2448 -0
  243. package/dist/emitter/emitter.js.map +1 -0
  244. package/dist/emitter/imports.d.ts +6 -0
  245. package/dist/emitter/imports.d.ts.map +1 -0
  246. package/dist/emitter/imports.js +73 -0
  247. package/dist/emitter/imports.js.map +1 -0
  248. package/dist/emitter/indent.d.ts +3 -0
  249. package/dist/emitter/indent.d.ts.map +1 -0
  250. package/dist/emitter/indent.js +31 -0
  251. package/dist/emitter/indent.js.map +1 -0
  252. package/dist/emitter/jsx.d.ts +20 -0
  253. package/dist/emitter/jsx.d.ts.map +1 -0
  254. package/dist/emitter/jsx.js +82 -0
  255. package/dist/emitter/jsx.js.map +1 -0
  256. package/dist/emitter/local-bindings.d.ts +6 -0
  257. package/dist/emitter/local-bindings.d.ts.map +1 -0
  258. package/dist/emitter/local-bindings.js +32 -0
  259. package/dist/emitter/local-bindings.js.map +1 -0
  260. package/dist/emitter/match.d.ts +56 -0
  261. package/dist/emitter/match.d.ts.map +1 -0
  262. package/dist/emitter/match.js +1287 -0
  263. package/dist/emitter/match.js.map +1 -0
  264. package/dist/emitter/pipeline-catalog.d.ts +15 -0
  265. package/dist/emitter/pipeline-catalog.d.ts.map +1 -0
  266. package/dist/emitter/pipeline-catalog.js +55 -0
  267. package/dist/emitter/pipeline-catalog.js.map +1 -0
  268. package/dist/emitter/pipeline-resolution.d.ts +38 -0
  269. package/dist/emitter/pipeline-resolution.d.ts.map +1 -0
  270. package/dist/emitter/pipeline-resolution.js +571 -0
  271. package/dist/emitter/pipeline-resolution.js.map +1 -0
  272. package/dist/emitter/runtime-helpers.d.ts +10 -0
  273. package/dist/emitter/runtime-helpers.d.ts.map +1 -0
  274. package/dist/emitter/runtime-helpers.js +22 -0
  275. package/dist/emitter/runtime-helpers.js.map +1 -0
  276. package/dist/emitter/schemas.d.ts +36 -0
  277. package/dist/emitter/schemas.d.ts.map +1 -0
  278. package/dist/emitter/schemas.js +766 -0
  279. package/dist/emitter/schemas.js.map +1 -0
  280. package/dist/emitter/statements.d.ts +23 -0
  281. package/dist/emitter/statements.d.ts.map +1 -0
  282. package/dist/emitter/statements.js +216 -0
  283. package/dist/emitter/statements.js.map +1 -0
  284. package/dist/emitter/tagged-match.d.ts +23 -0
  285. package/dist/emitter/tagged-match.d.ts.map +1 -0
  286. package/dist/emitter/tagged-match.js +109 -0
  287. package/dist/emitter/tagged-match.js.map +1 -0
  288. package/dist/emitter/types.d.ts +22 -0
  289. package/dist/emitter/types.d.ts.map +1 -0
  290. package/dist/emitter/types.js +231 -0
  291. package/dist/emitter/types.js.map +1 -0
  292. package/dist/errors.d.ts +39 -0
  293. package/dist/errors.d.ts.map +1 -0
  294. package/dist/errors.js +98 -0
  295. package/dist/errors.js.map +1 -0
  296. package/dist/formatter/comments.d.ts +25 -0
  297. package/dist/formatter/comments.d.ts.map +1 -0
  298. package/dist/formatter/comments.js +283 -0
  299. package/dist/formatter/comments.js.map +1 -0
  300. package/dist/formatter/index.d.ts +71 -0
  301. package/dist/formatter/index.d.ts.map +1 -0
  302. package/dist/formatter/index.js +1113 -0
  303. package/dist/formatter/index.js.map +1 -0
  304. package/dist/formatter/operator-precedence.d.ts +3 -0
  305. package/dist/formatter/operator-precedence.d.ts.map +1 -0
  306. package/dist/formatter/operator-precedence.js +27 -0
  307. package/dist/formatter/operator-precedence.js.map +1 -0
  308. package/dist/formatter/prettier.d.ts +7 -0
  309. package/dist/formatter/prettier.d.ts.map +1 -0
  310. package/dist/formatter/prettier.js +51 -0
  311. package/dist/formatter/prettier.js.map +1 -0
  312. package/dist/index.d.ts +17 -0
  313. package/dist/index.d.ts.map +1 -0
  314. package/dist/index.js +17 -0
  315. package/dist/index.js.map +1 -0
  316. package/dist/interop/callback.d.ts +38 -0
  317. package/dist/interop/callback.d.ts.map +1 -0
  318. package/dist/interop/callback.js +130 -0
  319. package/dist/interop/callback.js.map +1 -0
  320. package/dist/interop/index.d.ts +6 -0
  321. package/dist/interop/index.d.ts.map +1 -0
  322. package/dist/interop/index.js +6 -0
  323. package/dist/interop/index.js.map +1 -0
  324. package/dist/interop/js.d.ts +16 -0
  325. package/dist/interop/js.d.ts.map +1 -0
  326. package/dist/interop/js.js +35 -0
  327. package/dist/interop/js.js.map +1 -0
  328. package/dist/interop/record.d.ts +9 -0
  329. package/dist/interop/record.d.ts.map +1 -0
  330. package/dist/interop/record.js +18 -0
  331. package/dist/interop/record.js.map +1 -0
  332. package/dist/interop/valibot.d.ts +9 -0
  333. package/dist/interop/valibot.d.ts.map +1 -0
  334. package/dist/interop/valibot.js +94 -0
  335. package/dist/interop/valibot.js.map +1 -0
  336. package/dist/interop/zod.d.ts +45 -0
  337. package/dist/interop/zod.d.ts.map +1 -0
  338. package/dist/interop/zod.js +143 -0
  339. package/dist/interop/zod.js.map +1 -0
  340. package/dist/lexer/lexer.d.ts +65 -0
  341. package/dist/lexer/lexer.d.ts.map +1 -0
  342. package/dist/lexer/lexer.js +1335 -0
  343. package/dist/lexer/lexer.js.map +1 -0
  344. package/dist/lexer/tokens.d.ts +96 -0
  345. package/dist/lexer/tokens.d.ts.map +1 -0
  346. package/dist/lexer/tokens.js +150 -0
  347. package/dist/lexer/tokens.js.map +1 -0
  348. package/dist/lsp/code-action-worker.d.ts +2 -0
  349. package/dist/lsp/code-action-worker.d.ts.map +1 -0
  350. package/dist/lsp/code-action-worker.js +17 -0
  351. package/dist/lsp/code-action-worker.js.map +1 -0
  352. package/dist/lsp/completion.d.ts +11 -0
  353. package/dist/lsp/completion.d.ts.map +1 -0
  354. package/dist/lsp/completion.js +260 -0
  355. package/dist/lsp/completion.js.map +1 -0
  356. package/dist/lsp/definition.d.ts +42 -0
  357. package/dist/lsp/definition.d.ts.map +1 -0
  358. package/dist/lsp/definition.js +1074 -0
  359. package/dist/lsp/definition.js.map +1 -0
  360. package/dist/lsp/diagnostics-worker.d.ts +2 -0
  361. package/dist/lsp/diagnostics-worker.d.ts.map +1 -0
  362. package/dist/lsp/diagnostics-worker.js +169 -0
  363. package/dist/lsp/diagnostics-worker.js.map +1 -0
  364. package/dist/lsp/docs.d.ts +37 -0
  365. package/dist/lsp/docs.d.ts.map +1 -0
  366. package/dist/lsp/docs.js +830 -0
  367. package/dist/lsp/docs.js.map +1 -0
  368. package/dist/lsp/error-channel.d.ts +3 -0
  369. package/dist/lsp/error-channel.d.ts.map +1 -0
  370. package/dist/lsp/error-channel.js +48 -0
  371. package/dist/lsp/error-channel.js.map +1 -0
  372. package/dist/lsp/hover.d.ts +5 -0
  373. package/dist/lsp/hover.d.ts.map +1 -0
  374. package/dist/lsp/hover.js +651 -0
  375. package/dist/lsp/hover.js.map +1 -0
  376. package/dist/lsp/imports.d.ts +5 -0
  377. package/dist/lsp/imports.d.ts.map +1 -0
  378. package/dist/lsp/imports.js +317 -0
  379. package/dist/lsp/imports.js.map +1 -0
  380. package/dist/lsp/index.d.ts +16 -0
  381. package/dist/lsp/index.d.ts.map +1 -0
  382. package/dist/lsp/index.js +17 -0
  383. package/dist/lsp/index.js.map +1 -0
  384. package/dist/lsp/inlay-hints.d.ts +3 -0
  385. package/dist/lsp/inlay-hints.d.ts.map +1 -0
  386. package/dist/lsp/inlay-hints.js +236 -0
  387. package/dist/lsp/inlay-hints.js.map +1 -0
  388. package/dist/lsp/interop-rename.d.ts +26 -0
  389. package/dist/lsp/interop-rename.d.ts.map +1 -0
  390. package/dist/lsp/interop-rename.js +346 -0
  391. package/dist/lsp/interop-rename.js.map +1 -0
  392. package/dist/lsp/match-arms.d.ts +3 -0
  393. package/dist/lsp/match-arms.d.ts.map +1 -0
  394. package/dist/lsp/match-arms.js +341 -0
  395. package/dist/lsp/match-arms.js.map +1 -0
  396. package/dist/lsp/navigation.d.ts +23 -0
  397. package/dist/lsp/navigation.d.ts.map +1 -0
  398. package/dist/lsp/navigation.js +430 -0
  399. package/dist/lsp/navigation.js.map +1 -0
  400. package/dist/lsp/parsed-documents.d.ts +25 -0
  401. package/dist/lsp/parsed-documents.d.ts.map +1 -0
  402. package/dist/lsp/parsed-documents.js +47 -0
  403. package/dist/lsp/parsed-documents.js.map +1 -0
  404. package/dist/lsp/rename-worker.d.ts +2 -0
  405. package/dist/lsp/rename-worker.d.ts.map +1 -0
  406. package/dist/lsp/rename-worker.js +27 -0
  407. package/dist/lsp/rename-worker.js.map +1 -0
  408. package/dist/lsp/server.d.ts +78 -0
  409. package/dist/lsp/server.d.ts.map +1 -0
  410. package/dist/lsp/server.js +1098 -0
  411. package/dist/lsp/server.js.map +1 -0
  412. package/dist/lsp/thunk-pipeline.d.ts +4 -0
  413. package/dist/lsp/thunk-pipeline.d.ts.map +1 -0
  414. package/dist/lsp/thunk-pipeline.js +95 -0
  415. package/dist/lsp/thunk-pipeline.js.map +1 -0
  416. package/dist/lsp/validation.d.ts +8 -0
  417. package/dist/lsp/validation.d.ts.map +1 -0
  418. package/dist/lsp/validation.js +124 -0
  419. package/dist/lsp/validation.js.map +1 -0
  420. package/dist/lsp/workspace.d.ts +8 -0
  421. package/dist/lsp/workspace.d.ts.map +1 -0
  422. package/dist/lsp/workspace.js +70 -0
  423. package/dist/lsp/workspace.js.map +1 -0
  424. package/dist/math.ts +1 -0
  425. package/dist/parser/declarations.d.ts +21 -0
  426. package/dist/parser/declarations.d.ts.map +1 -0
  427. package/dist/parser/declarations.js +626 -0
  428. package/dist/parser/declarations.js.map +1 -0
  429. package/dist/parser/errors.d.ts +9 -0
  430. package/dist/parser/errors.d.ts.map +1 -0
  431. package/dist/parser/errors.js +11 -0
  432. package/dist/parser/errors.js.map +1 -0
  433. package/dist/parser/index.d.ts +9 -0
  434. package/dist/parser/index.d.ts.map +1 -0
  435. package/dist/parser/index.js +9 -0
  436. package/dist/parser/index.js.map +1 -0
  437. package/dist/parser/jsx.d.ts +5 -0
  438. package/dist/parser/jsx.d.ts.map +1 -0
  439. package/dist/parser/jsx.js +188 -0
  440. package/dist/parser/jsx.js.map +1 -0
  441. package/dist/parser/operator-expressions.d.ts +16 -0
  442. package/dist/parser/operator-expressions.d.ts.map +1 -0
  443. package/dist/parser/operator-expressions.js +146 -0
  444. package/dist/parser/operator-expressions.js.map +1 -0
  445. package/dist/parser/parser.d.ts +104 -0
  446. package/dist/parser/parser.d.ts.map +1 -0
  447. package/dist/parser/parser.js +1216 -0
  448. package/dist/parser/parser.js.map +1 -0
  449. package/dist/parser/patterns.d.ts +9 -0
  450. package/dist/parser/patterns.d.ts.map +1 -0
  451. package/dist/parser/patterns.js +292 -0
  452. package/dist/parser/patterns.js.map +1 -0
  453. package/dist/parser/pipeline-expressions.d.ts +10 -0
  454. package/dist/parser/pipeline-expressions.d.ts.map +1 -0
  455. package/dist/parser/pipeline-expressions.js +57 -0
  456. package/dist/parser/pipeline-expressions.js.map +1 -0
  457. package/dist/parser/scope.d.ts +17 -0
  458. package/dist/parser/scope.d.ts.map +1 -0
  459. package/dist/parser/scope.js +56 -0
  460. package/dist/parser/scope.js.map +1 -0
  461. package/dist/parser/statements.d.ts +13 -0
  462. package/dist/parser/statements.d.ts.map +1 -0
  463. package/dist/parser/statements.js +737 -0
  464. package/dist/parser/statements.js.map +1 -0
  465. package/dist/parser/types.d.ts +13 -0
  466. package/dist/parser/types.d.ts.map +1 -0
  467. package/dist/parser/types.js +371 -0
  468. package/dist/parser/types.js.map +1 -0
  469. package/dist/plugins/bun-preload.d.ts +4 -0
  470. package/dist/plugins/bun-preload.d.ts.map +1 -0
  471. package/dist/plugins/bun-preload.js +18 -0
  472. package/dist/plugins/bun-preload.js.map +1 -0
  473. package/dist/plugins/bun.d.ts +115 -0
  474. package/dist/plugins/bun.d.ts.map +1 -0
  475. package/dist/plugins/bun.js +240 -0
  476. package/dist/plugins/bun.js.map +1 -0
  477. package/dist/plugins/esbuild.d.ts +45 -0
  478. package/dist/plugins/esbuild.d.ts.map +1 -0
  479. package/dist/plugins/esbuild.js +184 -0
  480. package/dist/plugins/esbuild.js.map +1 -0
  481. package/dist/plugins/type-view.d.ts +30 -0
  482. package/dist/plugins/type-view.d.ts.map +1 -0
  483. package/dist/plugins/type-view.js +245 -0
  484. package/dist/plugins/type-view.js.map +1 -0
  485. package/dist/plugins/vite.d.ts +56 -0
  486. package/dist/plugins/vite.d.ts.map +1 -0
  487. package/dist/plugins/vite.js +182 -0
  488. package/dist/plugins/vite.js.map +1 -0
  489. package/dist/service.ts +3 -0
  490. package/dist/service.ts.map +1 -0
  491. package/dist/testing/index.d.ts +24 -0
  492. package/dist/testing/index.d.ts.map +1 -0
  493. package/dist/testing/index.js +56 -0
  494. package/dist/testing/index.js.map +1 -0
  495. package/dist/tooling/doc.d.ts +82 -0
  496. package/dist/tooling/doc.d.ts.map +1 -0
  497. package/dist/tooling/doc.js +624 -0
  498. package/dist/tooling/doc.js.map +1 -0
  499. package/dist/tooling/idiomatic.d.ts +20 -0
  500. package/dist/tooling/idiomatic.d.ts.map +1 -0
  501. package/dist/tooling/idiomatic.js +154 -0
  502. package/dist/tooling/idiomatic.js.map +1 -0
  503. package/dist/tooling/migrate.d.ts +62 -0
  504. package/dist/tooling/migrate.d.ts.map +1 -0
  505. package/dist/tooling/migrate.js +608 -0
  506. package/dist/tooling/migrate.js.map +1 -0
  507. package/dist/tooling/pipeline-style.d.ts +12 -0
  508. package/dist/tooling/pipeline-style.d.ts.map +1 -0
  509. package/dist/tooling/pipeline-style.js +208 -0
  510. package/dist/tooling/pipeline-style.js.map +1 -0
  511. package/dist/version.d.ts +2 -0
  512. package/dist/version.d.ts.map +1 -0
  513. package/dist/version.js +25 -0
  514. package/dist/version.js.map +1 -0
  515. package/package.json +128 -4
  516. package/src/ast/types.ts +753 -0
  517. package/src/ast/walk.ts +35 -0
  518. package/src/cli/build-bun.ts +249 -0
  519. package/src/cli/build-watch.ts +299 -0
  520. package/src/cli/build.ts +450 -0
  521. package/src/cli/check.ts +342 -0
  522. package/src/cli/commands.ts +301 -0
  523. package/src/cli/doc.ts +81 -0
  524. package/src/cli/doctor.ts +173 -0
  525. package/src/cli/emit.ts +138 -0
  526. package/src/cli/explain.ts +127 -0
  527. package/src/cli/fmt.ts +170 -0
  528. package/src/cli/index.ts +227 -0
  529. package/src/cli/init.ts +491 -0
  530. package/src/cli/io.ts +150 -0
  531. package/src/cli/pipeline-style.ts +55 -0
  532. package/src/cli/repl.ts +443 -0
  533. package/src/cli/run.ts +238 -0
  534. package/src/cli/test.ts +148 -0
  535. package/src/cli/tsc.ts +207 -0
  536. package/src/cli/typecheck.ts +100 -0
  537. package/src/compiler/ast-inspection.ts +121 -0
  538. package/src/compiler/boolean-operators.ts +108 -0
  539. package/src/compiler/check.ts +2763 -0
  540. package/src/compiler/diagnostics.ts +179 -0
  541. package/src/compiler/effect-mutation-rule.ts +407 -0
  542. package/src/compiler/entry-rules.ts +116 -0
  543. package/src/compiler/incremental-build.ts +131 -0
  544. package/src/compiler/incremental-dependencies.ts +200 -0
  545. package/src/compiler/js-interop-nullability.ts +67 -0
  546. package/src/compiler/modules/output-collisions.ts +48 -0
  547. package/src/compiler/modules/output-plan.ts +46 -0
  548. package/src/compiler/modules/resolution.ts +56 -0
  549. package/src/compiler/numeric-comparisons.ts +213 -0
  550. package/src/compiler/optional-arguments.ts +335 -0
  551. package/src/compiler/package-fingerprint.ts +216 -0
  552. package/src/compiler/package-record-contracts.ts +156 -0
  553. package/src/compiler/pipelines/catalog.ts +1128 -0
  554. package/src/compiler/pipelines/companions.ts +1279 -0
  555. package/src/compiler/pipelines/resolution.ts +684 -0
  556. package/src/compiler/project-config.ts +221 -0
  557. package/src/compiler/record-contracts.ts +46 -0
  558. package/src/compiler/rules/control-flow.ts +57 -0
  559. package/src/compiler/rules/diagnostic.ts +11 -0
  560. package/src/compiler/rules/module-scope-refs.ts +63 -0
  561. package/src/compiler/schemas/analysis.ts +45 -0
  562. package/src/compiler/schemas/imported-record-functions.ts +984 -0
  563. package/src/compiler/schemas/imported-schemas.ts +761 -0
  564. package/src/compiler/source-map.ts +165 -0
  565. package/src/compiler/typescript-context.ts +250 -0
  566. package/src/compiler.ts +865 -0
  567. package/src/emitter/assemblyscript.ts +1220 -0
  568. package/src/emitter/declarations.ts +916 -0
  569. package/src/emitter/emitter.ts +3128 -0
  570. package/src/emitter/imports.ts +89 -0
  571. package/src/emitter/indent.ts +39 -0
  572. package/src/emitter/jsx.ts +122 -0
  573. package/src/emitter/local-bindings.ts +40 -0
  574. package/src/emitter/match.ts +1631 -0
  575. package/src/emitter/runtime-helpers.ts +31 -0
  576. package/src/emitter/schemas.ts +969 -0
  577. package/src/emitter/statements.ts +310 -0
  578. package/src/emitter/tagged-match.ts +171 -0
  579. package/src/emitter/types.ts +289 -0
  580. package/src/errors.ts +115 -0
  581. package/src/formatter/comments.ts +350 -0
  582. package/src/formatter/index.ts +1457 -0
  583. package/src/formatter/operator-precedence.ts +36 -0
  584. package/src/formatter/prettier.ts +61 -0
  585. package/src/index.ts +16 -0
  586. package/src/interop/callback.ts +188 -0
  587. package/src/interop/js.ts +66 -0
  588. package/src/interop/record.ts +36 -0
  589. package/src/interop/valibot.ts +141 -0
  590. package/src/interop/zod.ts +219 -0
  591. package/src/lexer/lexer.ts +1521 -0
  592. package/src/lexer/tokens.ts +174 -0
  593. package/src/lsp/code-action-worker.ts +31 -0
  594. package/src/lsp/completion.ts +343 -0
  595. package/src/lsp/definition.ts +1165 -0
  596. package/src/lsp/diagnostics-worker.ts +198 -0
  597. package/src/lsp/docs.ts +864 -0
  598. package/src/lsp/error-channel.ts +63 -0
  599. package/src/lsp/hover.ts +803 -0
  600. package/src/lsp/imports.ts +380 -0
  601. package/src/lsp/index.ts +55 -0
  602. package/src/lsp/inlay-hints.ts +308 -0
  603. package/src/lsp/interop-rename.ts +454 -0
  604. package/src/lsp/match-arms.ts +400 -0
  605. package/src/lsp/navigation.ts +553 -0
  606. package/src/lsp/parsed-documents.ts +64 -0
  607. package/src/lsp/rename-worker.ts +40 -0
  608. package/src/lsp/server.ts +1437 -0
  609. package/src/lsp/thunk-pipeline.ts +117 -0
  610. package/src/lsp/validation.ts +147 -0
  611. package/src/lsp/workspace.ts +74 -0
  612. package/src/parser/declarations.ts +808 -0
  613. package/src/parser/errors.ts +18 -0
  614. package/src/parser/jsx.ts +253 -0
  615. package/src/parser/operator-expressions.ts +170 -0
  616. package/src/parser/parser.ts +1565 -0
  617. package/src/parser/patterns.ts +342 -0
  618. package/src/parser/pipeline-expressions.ts +77 -0
  619. package/src/parser/scope.ts +69 -0
  620. package/src/parser/statements.ts +831 -0
  621. package/src/parser/types.ts +453 -0
  622. package/src/plugins/bun-preload.ts +25 -0
  623. package/src/plugins/bun.ts +448 -0
  624. package/src/plugins/esbuild.ts +308 -0
  625. package/src/plugins/type-view.ts +326 -0
  626. package/src/plugins/vite.ts +294 -0
  627. package/src/testing/index.ts +72 -0
  628. package/src/tooling/doc.ts +786 -0
  629. package/src/tooling/idiomatic.ts +202 -0
  630. package/src/tooling/pipeline-style.ts +248 -0
  631. package/src/version.ts +27 -0
@@ -0,0 +1,2763 @@
1
+ import { checkControlFlowRules } from "./rules/control-flow.js";
2
+ import { checkModuleScopeRefs } from "./rules/module-scope-refs.js";
3
+ import { isEntryModule, getEffectRunnerName } from "./entry-rules.js";
4
+ export { isEntryModule } from "./entry-rules.js";
5
+ import { checkCapturedMutInEffect } from "./effect-mutation-rule.js";
6
+ import {
7
+ asRecord,
8
+ isAstNode,
9
+ astChild,
10
+ astChildren,
11
+ astString,
12
+ astBool,
13
+ astName,
14
+ getMemberNames,
15
+ collectPatternVars,
16
+ type AstInspectNode,
17
+ } from "./ast-inspection.js";
18
+ import { isEffectOnlyFile, isPathPolicyEnabled } from "./project-config.js";
19
+ import ts from "typescript";
20
+ import * as path from "node:path";
21
+ import * as fs from "node:fs/promises";
22
+ import * as syncFs from "node:fs";
23
+ import * as Effect from "effect/Effect";
24
+ import { TraceMap } from "@jridgewell/trace-mapping";
25
+ import { mapDiagnosticLocation, formatDiagnostics } from "./diagnostics.js";
26
+ export { mapDiagnosticLocation, formatDiagnostics } from "./diagnostics.js";
27
+ import { compileString, CompilerError, type SourceMap } from "../compiler.js";
28
+ import { incrementalDependencyKeys } from "./incremental-dependencies.js";
29
+ import { ImportedSchemaError } from "./schemas/imported-schemas.js";
30
+ import { resolveFunModule } from "./modules/resolution.js";
31
+ import {
32
+ isFileNotFoundError,
33
+ safeCodeFrame,
34
+ toErrorMessage,
35
+ } from "../errors.js";
36
+ import type { Program, Span } from "../ast/types.js";
37
+ import {
38
+ TS_RESET_DECLARATION,
39
+ JSX_INTRINSICS_DECLARATION,
40
+ TYPE_FEST_DECLARATION,
41
+ } from "./typescript-context.js";
42
+
43
+ export type DiagnosticCategory = "error" | "warning" | "suggestion" | "message";
44
+
45
+ export interface DiagnosticLocation {
46
+ file: string;
47
+ line: number;
48
+ column: number;
49
+ endLine?: number;
50
+ endColumn?: number;
51
+ }
52
+
53
+ export interface TypeCheckDiagnostic {
54
+ file: string;
55
+ line: number;
56
+ column: number;
57
+ endLine?: number;
58
+ endColumn?: number;
59
+ message: string;
60
+ /** Stable FunkScript diagnostic identifier; TypeScript codes remain available in `code`. */
61
+ diagnosticCode?: string;
62
+ explanation?: string;
63
+ suggestedAction?: string;
64
+ related?: DiagnosticLocation;
65
+ category: DiagnosticCategory;
66
+ code?: number | string;
67
+ frame?: string;
68
+ formatted: string;
69
+ }
70
+
71
+ export interface TypeCheckResult {
72
+ success: boolean;
73
+ diagnostics: TypeCheckDiagnostic[];
74
+ errorCount: number;
75
+ warningCount: number;
76
+ formattedOutput: string;
77
+ }
78
+
79
+ export interface CachedSourceFile {
80
+ mtime?: number;
81
+ stamp?: string;
82
+ sourceFile: ts.SourceFile;
83
+ }
84
+
85
+ export interface TypeCheckCache {
86
+ oldProgram?: ts.Program;
87
+ sourceFiles: Map<string, CachedSourceFile>;
88
+ compiledFiles: Map<
89
+ string,
90
+ {
91
+ source: string;
92
+ dependencyKey?: string;
93
+ compiled: {
94
+ typescript: string;
95
+ map?: SourceMap;
96
+ ast?: Program;
97
+ pipelineStageInputCompanions?: ReadonlyMap<number, string>;
98
+ };
99
+ }
100
+ >;
101
+ clear(): void;
102
+ }
103
+
104
+ export function createTypeCheckCache(): TypeCheckCache {
105
+ return {
106
+ sourceFiles: new Map(),
107
+ compiledFiles: new Map(),
108
+ clear() {
109
+ this.oldProgram = undefined;
110
+ this.sourceFiles.clear();
111
+ this.compiledFiles.clear();
112
+ },
113
+ };
114
+ }
115
+
116
+ export interface CheckOptions {
117
+ /** Reject raw TypeScript escapes in all checked FunkScript files. */
118
+ noTs?: boolean;
119
+ noGlobalThis?: boolean;
120
+ barePipelines?: boolean;
121
+ noDeepDestructure?: boolean;
122
+ maxDestructureDepth?: number;
123
+ effectOnly?: string[];
124
+ noTsPaths?: string[];
125
+ noGlobalThisPaths?: string[];
126
+ barePipelinesPaths?: string[];
127
+ noDeepDestructurePaths?: string[];
128
+ /** Allow unfinished typed holes ('???') during type-checking (defaults to false; holes fail check by default). */
129
+ allowHoles?: boolean;
130
+ allowHolesPaths?: string[];
131
+ /** Allow early returns ('when (...) =>') during type-checking (defaults to false). */
132
+ allowEarlyReturns?: boolean;
133
+ allowEarlyReturnsPaths?: string[];
134
+ compilerOptions?: ts.CompilerOptions;
135
+ cwd?: string;
136
+ highlightCode?: boolean;
137
+ cache?: TypeCheckCache;
138
+ }
139
+
140
+ export const DEFAULT_COMPILER_OPTIONS: ts.CompilerOptions = {
141
+ noEmit: true,
142
+ strict: true,
143
+ target: ts.ScriptTarget.ES2022,
144
+ module: ts.ModuleKind.NodeNext,
145
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
146
+ esModuleInterop: true,
147
+ skipLibCheck: true,
148
+ allowSyntheticDefaultImports: true,
149
+ jsx: ts.JsxEmit.Preserve,
150
+ };
151
+
152
+ function getCompilerOptions(
153
+ cwd: string,
154
+ userOptions?: ts.CompilerOptions,
155
+ ): ts.CompilerOptions {
156
+ let baseOptions = { ...DEFAULT_COMPILER_OPTIONS };
157
+ const configPath = ts.findConfigFile(cwd, ts.sys.fileExists, "tsconfig.json");
158
+ if (configPath) {
159
+ const configFile = ts.readConfigFile(configPath, ts.sys.readFile);
160
+ if (!configFile.error && configFile.config) {
161
+ const parsed = ts.parseJsonConfigFileContent(
162
+ configFile.config,
163
+ ts.sys,
164
+ path.dirname(configPath),
165
+ );
166
+ baseOptions = { ...baseOptions, ...parsed.options };
167
+ }
168
+ }
169
+ return {
170
+ ...baseOptions,
171
+ noEmit: true,
172
+ allowImportingTsExtensions: true,
173
+ ...userOptions,
174
+ };
175
+ }
176
+
177
+ function mapCategory(category: ts.DiagnosticCategory): DiagnosticCategory {
178
+ switch (category) {
179
+ case ts.DiagnosticCategory.Error:
180
+ return "error";
181
+ case ts.DiagnosticCategory.Warning:
182
+ return "warning";
183
+ case ts.DiagnosticCategory.Suggestion:
184
+ return "suggestion";
185
+ case ts.DiagnosticCategory.Message:
186
+ return "message";
187
+ default:
188
+ return "error";
189
+ }
190
+ }
191
+
192
+ export const typeCheckVirtualFiles = (
193
+ virtualInputFiles: Record<string, string>,
194
+ options?: CheckOptions,
195
+ ): Effect.Effect<TypeCheckResult, Error> =>
196
+ Effect.tryPromise({
197
+ try: async () => {
198
+ const cwd = options?.cwd ? path.resolve(options.cwd) : process.cwd();
199
+ const compilerOptions = getCompilerOptions(cwd, options?.compilerOptions);
200
+
201
+ const virtualTsFiles = new Map<string, string>();
202
+ const virtualSourceMap = new Map<
203
+ string,
204
+ {
205
+ funPath: string;
206
+ funSource: string;
207
+ traceMap: TraceMap;
208
+ tsCode: string;
209
+ ast?: Program;
210
+ }
211
+ >();
212
+
213
+ const earlyDiagnostics: TypeCheckDiagnostic[] = [];
214
+ const virtualSources = new Map(
215
+ Object.entries(virtualInputFiles).map(([file, content]) => [
216
+ path.resolve(cwd, file),
217
+ content,
218
+ ]),
219
+ );
220
+
221
+ const cache = options?.cache;
222
+ const dependencyKeys = cache
223
+ ? incrementalDependencyKeys(virtualSources, cwd)
224
+ : undefined;
225
+
226
+ for (const [filePath, source] of Object.entries(virtualInputFiles)) {
227
+ const fullFunPath = path.isAbsolute(filePath)
228
+ ? path.normalize(filePath)
229
+ : path.normalize(path.join(cwd, filePath));
230
+ const ext = fullFunPath.endsWith(".funx") ? ".tsx" : ".ts";
231
+ const virtualTsPath = fullFunPath + ext;
232
+
233
+ let compiled;
234
+ const effectOnly = isEffectOnlyFile(
235
+ { effectOnly: options?.effectOnly },
236
+ cwd,
237
+ fullFunPath,
238
+ );
239
+ const noTs =
240
+ !!options?.noTs ||
241
+ isPathPolicyEnabled(options?.noTsPaths, cwd, fullFunPath);
242
+ const noGlobalThis =
243
+ !!options?.noGlobalThis ||
244
+ isPathPolicyEnabled(options?.noGlobalThisPaths, cwd, fullFunPath);
245
+ const barePipelines =
246
+ !!options?.barePipelines ||
247
+ isPathPolicyEnabled(options?.barePipelinesPaths, cwd, fullFunPath);
248
+ const noDeepDestructure =
249
+ !!options?.noDeepDestructure ||
250
+ isPathPolicyEnabled(
251
+ options?.noDeepDestructurePaths,
252
+ cwd,
253
+ fullFunPath,
254
+ );
255
+ const maxDestructureDepth = options?.maxDestructureDepth;
256
+ const allowHoles =
257
+ !!options?.allowHoles ||
258
+ isPathPolicyEnabled(options?.allowHolesPaths, cwd, fullFunPath);
259
+ const allowEarlyReturns =
260
+ !!options?.allowEarlyReturns ||
261
+ isPathPolicyEnabled(
262
+ options?.allowEarlyReturnsPaths,
263
+ cwd,
264
+ fullFunPath,
265
+ );
266
+ const graphKey = dependencyKeys?.get(fullFunPath);
267
+ const dependencyKey =
268
+ graphKey &&
269
+ JSON.stringify([
270
+ graphKey,
271
+ noTs,
272
+ noGlobalThis,
273
+ barePipelines,
274
+ effectOnly,
275
+ options?.effectOnly ?? [],
276
+ compilerOptions,
277
+ noDeepDestructure,
278
+ maxDestructureDepth,
279
+ allowHoles,
280
+ allowEarlyReturns,
281
+ ]);
282
+ const existing = cache?.compiledFiles.get(fullFunPath);
283
+ if (
284
+ cache &&
285
+ existing &&
286
+ existing.source === source &&
287
+ existing.dependencyKey !== dependencyKey
288
+ ) {
289
+ // TypeScript's old program can retain module-resolution and package
290
+ // metadata after a dependency changes. Recreate it before checking.
291
+ cache.oldProgram = undefined;
292
+ cache.sourceFiles.clear();
293
+ }
294
+ const cachedCompiled = !dependencyKey ? undefined : existing;
295
+ if (
296
+ cachedCompiled &&
297
+ cachedCompiled.source === source &&
298
+ cachedCompiled.dependencyKey === dependencyKey
299
+ ) {
300
+ compiled = cachedCompiled.compiled;
301
+ } else {
302
+ try {
303
+ compiled = await Effect.runPromise(
304
+ compileString(source, filePath, {
305
+ sourcemap: true,
306
+ preserveFunImports: true,
307
+ sourcePath: fullFunPath,
308
+ virtualSources,
309
+ noTs,
310
+ noGlobalThis,
311
+ barePipelines,
312
+ noDeepDestructure,
313
+ maxDestructureDepth,
314
+ allowHoles,
315
+ allowEarlyReturns,
316
+ effectOnly,
317
+ effectOnlyDirectories: options?.effectOnly,
318
+ policyRoot: cwd,
319
+ }),
320
+ );
321
+ if (cache && dependencyKey) {
322
+ cache.compiledFiles.set(fullFunPath, {
323
+ source,
324
+ dependencyKey,
325
+ compiled,
326
+ });
327
+ } else {
328
+ cache?.compiledFiles.delete(fullFunPath);
329
+ }
330
+ } catch (err: unknown) {
331
+ if (cache) {
332
+ cache.compiledFiles.delete(fullFunPath);
333
+ cache.sourceFiles.delete(virtualTsPath);
334
+ }
335
+ const compErr =
336
+ err instanceof CompilerError
337
+ ? err
338
+ : new CompilerError(
339
+ toErrorMessage(err),
340
+ err instanceof Error ? err : new Error(toErrorMessage(err)),
341
+ );
342
+ let errLine = 1;
343
+ let errCol = 1;
344
+ if ("span" in compErr.error && compErr.error.span?.start) {
345
+ errLine = compErr.error.span.start.line;
346
+ errCol = compErr.error.span.start.column;
347
+ }
348
+
349
+ const frame = safeCodeFrame(
350
+ source,
351
+ { start: { line: errLine, column: errCol } },
352
+ {
353
+ message: compErr.message,
354
+ highlightCode: options?.highlightCode ?? false,
355
+ },
356
+ );
357
+
358
+ const schemaError =
359
+ compErr.error instanceof ImportedSchemaError
360
+ ? compErr.error
361
+ : undefined;
362
+ let code = schemaError ? "IMPORTED_SCHEMA" : "SYNTAX";
363
+ let diagnosticCode = schemaError?.code ?? "FS_SYNTAX";
364
+ let explanation =
365
+ schemaError?.explanation ??
366
+ "The FunkScript source could not be parsed.";
367
+ let suggestedAction =
368
+ schemaError?.suggestedAction ??
369
+ "Fix the syntax at the highlighted location and run `funkscript check` again.";
370
+
371
+ if (compErr.message.includes("Typed hole")) {
372
+ code = "TYPED_HOLE";
373
+ diagnosticCode = "FS_TYPED_HOLE";
374
+ explanation =
375
+ "Typed holes are placeholders for incomplete code during drafting. They throw at runtime and are prohibited by default in completed builds and type-checking.";
376
+ suggestedAction =
377
+ "Implement this expression before building or type-checking.";
378
+ } else if (
379
+ compErr.message.includes("FunkScript has no 'throw'") ||
380
+ compErr.message.includes("is unsafe because it throws")
381
+ ) {
382
+ code = "THROW";
383
+ diagnosticCode = "FS_THROW";
384
+ explanation =
385
+ "FunkScript has no 'throw' and bans throwing APIs. Recoverable failures must be modeled using typed errors in the Effect E channel, and unrecoverable bugs should use 'Effect.die'.";
386
+ suggestedAction =
387
+ "Replace throwing code with Effect typed errors or schema decoding.";
388
+ } else if (
389
+ compErr.message.includes("is banned by the Effect style guide") ||
390
+ compErr.message.includes("In-place mutation") ||
391
+ compErr.message.includes("quarantined")
392
+ ) {
393
+ code = "INPLACE_MUTATION";
394
+ diagnosticCode = "FS_INPLACE_MUTATION";
395
+ explanation =
396
+ "In-place mutation is quarantined in FunkScript. Arrays and records are immutable by default outside 'mut (draft) =>' blocks.";
397
+ suggestedAction =
398
+ "Use immutable functional alternatives (e.g. 'Array.append', 'Array.modify') or wrap local mutations in 'mut (draft) => { ... }'.";
399
+ } else if (
400
+ compErr.message.includes(
401
+ "TypeScript escapes are disabled by --no-ts",
402
+ ) ||
403
+ compErr.message.includes(
404
+ "AssemblyScript blocks are disabled by --no-ts",
405
+ ) ||
406
+ compErr.message.includes(
407
+ "globalThis is disabled by project policy",
408
+ ) ||
409
+ compErr.message.includes("Redundant pipeline prefix") ||
410
+ compErr.message.includes(
411
+ "exceeds the maximum allowed depth of",
412
+ ) ||
413
+ compErr.message.includes(
414
+ "Early returns ('when (...) =>') are disabled by default",
415
+ ) ||
416
+ compErr.message.includes("Effect-only policy disallows") ||
417
+ compErr.message.includes("Effect-only local import")
418
+ ) {
419
+ code = "POLICY";
420
+ diagnosticCode = "FS_POLICY";
421
+ explanation =
422
+ "A configured project policy disallowed this construct.";
423
+ suggestedAction =
424
+ "Update the code to comply with the active project policy or adjust the policy in funscript.config.fun.";
425
+ }
426
+
427
+ const header = `${filePath}:${errLine}:${errCol} - error: ${compErr.message}`;
428
+ const related = schemaError?.related;
429
+ const relatedText = related
430
+ ? `\n TypeScript declaration: ${related.file}:${related.line + 1}:${related.column + 1}`
431
+ : "";
432
+ const formatted = `${frame ? `${header}\n${frame}` : header}${relatedText}\n help: ${suggestedAction}`;
433
+
434
+ earlyDiagnostics.push({
435
+ file: filePath,
436
+ line: errLine,
437
+ column: errCol,
438
+ message: compErr.message,
439
+ diagnosticCode,
440
+ explanation,
441
+ suggestedAction,
442
+ ...(related
443
+ ? {
444
+ related: {
445
+ file: related.file,
446
+ line: related.line + 1,
447
+ column: related.column + 1,
448
+ endLine: related.endLine + 1,
449
+ endColumn: related.endColumn + 1,
450
+ },
451
+ }
452
+ : {}),
453
+ category: "error",
454
+ code,
455
+ frame,
456
+ formatted,
457
+ });
458
+ continue;
459
+ }
460
+ }
461
+
462
+ virtualTsFiles.set(virtualTsPath, compiled.typescript);
463
+ virtualSourceMap.set(virtualTsPath, {
464
+ funPath: filePath,
465
+ funSource: source,
466
+ traceMap: new TraceMap(compiled.map!.toString()),
467
+ tsCode: compiled.typescript,
468
+ ast: compiled.ast,
469
+ });
470
+ }
471
+
472
+ if (cache) {
473
+ for (const key of cache.compiledFiles.keys()) {
474
+ if (!(key in virtualInputFiles) && !virtualSources.has(key)) {
475
+ cache.compiledFiles.delete(key);
476
+ const ext = key.endsWith(".funx") ? ".tsx" : ".ts";
477
+ cache.sourceFiles.delete(key + ext);
478
+ }
479
+ }
480
+ }
481
+
482
+ const hasTsx = Array.from(virtualTsFiles.keys()).some((fileName) =>
483
+ fileName.endsWith(".tsx"),
484
+ );
485
+ const hasJsxIntrinsicTypes = Array.from(virtualTsFiles.values()).some(
486
+ (source) => /namespace\s+JSX[\s\S]*?IntrinsicElements/.test(source),
487
+ );
488
+ if (hasTsx && !hasJsxIntrinsicTypes) {
489
+ const jsxTypesPath = path.join(
490
+ cwd,
491
+ "__funscript_jsx_intrinsics__.d.ts",
492
+ );
493
+ virtualTsFiles.set(jsxTypesPath, JSX_INTRINSICS_DECLARATION);
494
+ }
495
+
496
+ const resetPath = path.join(cwd, "__funscript_ts_reset__.d.ts");
497
+ virtualTsFiles.set(resetPath, TS_RESET_DECLARATION);
498
+
499
+ const typeFestPath = path.join(cwd, "__funscript_type_fest__.d.ts");
500
+ virtualTsFiles.set(typeFestPath, TYPE_FEST_DECLARATION);
501
+
502
+ const defaultHost = ts.createCompilerHost(compilerOptions);
503
+
504
+ const resolveVirtualContent = (fileName: string): string | undefined => {
505
+ const norm = path.normalize(fileName);
506
+ const content = virtualTsFiles.get(norm);
507
+ if (content !== undefined) return content;
508
+ if (virtualTsFiles.has(norm + ".ts"))
509
+ return virtualTsFiles.get(norm + ".ts");
510
+ if (virtualTsFiles.has(norm + ".tsx"))
511
+ return virtualTsFiles.get(norm + ".tsx");
512
+ if (
513
+ norm.endsWith(".js") &&
514
+ virtualTsFiles.has(norm.slice(0, -3) + ".ts")
515
+ ) {
516
+ return virtualTsFiles.get(norm.slice(0, -3) + ".ts");
517
+ }
518
+ if (
519
+ norm.endsWith(".jsx") &&
520
+ virtualTsFiles.has(norm.slice(0, -4) + ".tsx")
521
+ ) {
522
+ return virtualTsFiles.get(norm.slice(0, -4) + ".tsx");
523
+ }
524
+ if (path.basename(fileName) === "__funscript_type_fest__.d.ts") {
525
+ return TYPE_FEST_DECLARATION;
526
+ }
527
+ if (path.basename(fileName) === "__funscript_ts_reset__.d.ts") {
528
+ return TS_RESET_DECLARATION;
529
+ }
530
+ if (path.basename(fileName) === "__funscript_jsx_intrinsics__.d.ts") {
531
+ return JSX_INTRINSICS_DECLARATION;
532
+ }
533
+ return undefined;
534
+ };
535
+
536
+ const host: ts.CompilerHost = {
537
+ ...defaultHost,
538
+ getSourceFile: (
539
+ fileName,
540
+ languageVersion,
541
+ onError,
542
+ shouldCreateNewSourceFile,
543
+ ) => {
544
+ const content = resolveVirtualContent(fileName);
545
+ const norm = path.normalize(fileName);
546
+
547
+ if (content !== undefined) {
548
+ if (cache) {
549
+ const cached = cache.sourceFiles.get(norm);
550
+ if (cached && cached.sourceFile.text === content) {
551
+ return cached.sourceFile;
552
+ }
553
+ const sf = ts.createSourceFile(
554
+ fileName,
555
+ content,
556
+ languageVersion,
557
+ true,
558
+ );
559
+ cache.sourceFiles.set(norm, { sourceFile: sf });
560
+ return sf;
561
+ }
562
+ return ts.createSourceFile(
563
+ fileName,
564
+ content,
565
+ languageVersion,
566
+ true,
567
+ );
568
+ }
569
+
570
+ if (cache) {
571
+ const cached = cache.sourceFiles.get(norm);
572
+ if (cached) {
573
+ try {
574
+ const stat = syncFs.statSync(fileName, { bigint: true });
575
+ const stamp = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
576
+ if (cached.stamp === stamp) return cached.sourceFile;
577
+ } catch (error) {
578
+ // A removed file must not reuse its old source.
579
+ if (!isFileNotFoundError(error)) throw error;
580
+ }
581
+ }
582
+
583
+ const sf = defaultHost.getSourceFile(
584
+ fileName,
585
+ languageVersion,
586
+ onError,
587
+ shouldCreateNewSourceFile,
588
+ );
589
+ if (sf) {
590
+ let stamp: string | undefined;
591
+ try {
592
+ const stat = syncFs.statSync(fileName, { bigint: true });
593
+ stamp = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
594
+ } catch (error) {
595
+ /* Missing files are never reused. */
596
+ if (!isFileNotFoundError(error)) throw error;
597
+ }
598
+ cache.sourceFiles.set(norm, { sourceFile: sf, stamp });
599
+ }
600
+ return sf;
601
+ }
602
+
603
+ return defaultHost.getSourceFile(
604
+ fileName,
605
+ languageVersion,
606
+ onError,
607
+ shouldCreateNewSourceFile,
608
+ );
609
+ },
610
+ fileExists: (fileName) => {
611
+ if (resolveVirtualContent(fileName) !== undefined) return true;
612
+ return defaultHost.fileExists(fileName);
613
+ },
614
+ directoryExists: (dirName) => {
615
+ const norm = path.normalize(dirName);
616
+ for (const file of virtualTsFiles.keys()) {
617
+ const dir = path.dirname(file);
618
+ if (dir === norm || dir.startsWith(norm + path.sep)) return true;
619
+ }
620
+ return defaultHost.directoryExists?.(dirName) ?? true;
621
+ },
622
+ readFile: (fileName) => {
623
+ const content = resolveVirtualContent(fileName);
624
+ if (content !== undefined) return content;
625
+ return defaultHost.readFile(fileName);
626
+ },
627
+ writeFile: () => {},
628
+ };
629
+
630
+ // Keep FunkScript sources at distinct virtual paths so an explicit .fun
631
+ // import cannot accidentally bind to a same-named TypeScript module.
632
+ host.resolveModuleNames = (names, containingFile) =>
633
+ names.map((name) => {
634
+ if (/^\.{1,2}\//.test(name)) {
635
+ if (name.endsWith(".js")) {
636
+ const regular = ts.resolveModuleName(
637
+ name,
638
+ containingFile,
639
+ compilerOptions,
640
+ defaultHost,
641
+ ).resolvedModule;
642
+ if (regular) return regular;
643
+ }
644
+ const source = resolveFunModule(
645
+ containingFile,
646
+ name,
647
+ (file) =>
648
+ /\.funx?$/.test(file) &&
649
+ virtualTsFiles.has(
650
+ file + (file.endsWith(".funx") ? ".tsx" : ".ts"),
651
+ ),
652
+ { directories: true },
653
+ );
654
+ if (source)
655
+ return {
656
+ resolvedFileName:
657
+ source + (source.endsWith(".funx") ? ".tsx" : ".ts"),
658
+ extension: source.endsWith(".funx")
659
+ ? ts.Extension.Tsx
660
+ : ts.Extension.Ts,
661
+ };
662
+ if (/\.funx?$/.test(name)) return undefined;
663
+ }
664
+ return ts.resolveModuleName(
665
+ name,
666
+ containingFile,
667
+ compilerOptions,
668
+ host,
669
+ ).resolvedModule;
670
+ });
671
+
672
+ const tsDiagnostics: TypeCheckDiagnostic[] = [...earlyDiagnostics];
673
+
674
+ if (virtualTsFiles.size > 0) {
675
+ const rootNames = Array.from(virtualTsFiles.keys());
676
+ const program = ts.createProgram({
677
+ rootNames,
678
+ options: compilerOptions,
679
+ host,
680
+ oldProgram: cache?.oldProgram,
681
+ });
682
+
683
+ if (cache) {
684
+ cache.oldProgram = program;
685
+ }
686
+
687
+ const preEmit = ts.getPreEmitDiagnostics(program);
688
+
689
+ for (const diag of preEmit) {
690
+ if (!diag.file) continue;
691
+ const normFile = path.normalize(diag.file.fileName);
692
+ const meta = virtualSourceMap.get(normFile);
693
+ if (!meta) continue;
694
+
695
+ const loc = mapDiagnosticLocation(
696
+ diag,
697
+ meta.funPath,
698
+ meta.funSource,
699
+ meta.traceMap,
700
+ meta.tsCode,
701
+ );
702
+ const category = mapCategory(diag.category);
703
+ let message = ts.flattenDiagnosticMessageText(diag.messageText, "\n");
704
+ let code: number | string = diag.code;
705
+
706
+ // Only customize unresolved names: TypeScript has already accounted for
707
+ // local shadowing and imported bindings, so valid user functions are untouched.
708
+ if (
709
+ diag.code === 2304 &&
710
+ diag.start !== undefined &&
711
+ diag.length !== undefined
712
+ ) {
713
+ const identifier = diag.file.text.slice(
714
+ diag.start,
715
+ diag.start + diag.length,
716
+ );
717
+ if (identifier.endsWith("DecodeChecked")) {
718
+ const contract = identifier.slice(0, -"DecodeChecked".length);
719
+ if (
720
+ meta.tsCode.includes(
721
+ `declare const $funscriptRecordContract$${contract}: unique symbol;`,
722
+ )
723
+ ) {
724
+ code = "CHECKED_DECODER_UNSUPPORTED";
725
+ message = `${contract} has no generated checked decoder for this signature. Only required callbacks with supported primitive or local data-schema arguments and results are supported; use explicit callback adapters for other shapes.`;
726
+ }
727
+ }
728
+ if (identifier.endsWith("FromUnknown")) {
729
+ const contract = identifier.slice(0, -"FromUnknown".length);
730
+ if (
731
+ meta.tsCode.includes(
732
+ `declare const $funscriptRecordContract$${contract}: unique symbol;`,
733
+ )
734
+ ) {
735
+ code = "CONTRACT_DECODER";
736
+ message = `${contract} is a compile-time record contract and has no generated FromUnknown decoder. Use its DecodeChecked function when supported, or validate data separately and use an explicit checked callback boundary.`;
737
+ }
738
+ }
739
+ }
740
+
741
+ let explanation =
742
+ typeof code === "number"
743
+ ? `TypeScript reported diagnostic TS${code} for the generated source.`
744
+ : message;
745
+ let suggestedAction: string | undefined;
746
+
747
+ if (
748
+ (diag.code === 2488 || diag.code === 2461) &&
749
+ /Promise/.test(message)
750
+ ) {
751
+ code = "PROMISE_BIND";
752
+ message =
753
+ "Cannot bind raw Promise in effect block. External asynchronous calls must be explicitly lifted using the 'js' operator (e.g. '<- js <expr>') or wrapped in 'Effect.tryPromise'.";
754
+ explanation = message;
755
+ suggestedAction =
756
+ "Use '<- js <expr>' to lift foreign asynchronous calls into the effect block.";
757
+ }
758
+
759
+ if (
760
+ diag.code === 2339 &&
761
+ /Option<|Option\.|\bOption\b/.test(message) &&
762
+ /Property 'fromNullishOr'/.test(message) &&
763
+ !diag.file.text
764
+ .slice(
765
+ Math.max(0, (diag.start ?? 0) - 100),
766
+ (diag.start ?? 0) + (diag.length ?? 0),
767
+ )
768
+ .includes("Option.fromNullishOr") &&
769
+ diag.file.text
770
+ .slice(
771
+ Math.max(0, (diag.start ?? 0) - 100),
772
+ (diag.start ?? 0) + (diag.length ?? 0),
773
+ )
774
+ .includes("fromNullishOr")
775
+ ) {
776
+ continue;
777
+ }
778
+
779
+ // Map Effect error-channel mismatches to a clearer FunkScript diagnostic.
780
+ const effectMatches = message.match(/Effect<([^>]*)>/g);
781
+ if (effectMatches && effectMatches.length >= 2) {
782
+ const parsed = effectMatches.map((m) => {
783
+ const inner = m.slice("Effect<".length, -1);
784
+ return inner.split(",").map((part) => part.trim());
785
+ });
786
+ const [actual, expected] = parsed;
787
+ const neverTargetMismatch =
788
+ /Effect</.test(message) &&
789
+ /is not assignable to type 'never'\./.test(message);
790
+ if (
791
+ (actual &&
792
+ expected &&
793
+ actual.length === 3 &&
794
+ expected.length === 3 &&
795
+ actual[2] === expected[2] &&
796
+ actual[1] !== expected[1]) ||
797
+ neverTargetMismatch
798
+ ) {
799
+ code = "UNHANDLED_ERROR";
800
+ explanation =
801
+ "An Effect's typed error channel does not match the expected failure type.";
802
+ suggestedAction =
803
+ "Handle the failing error with Effect.catchTag/Effect.catch, or update the declared error type.";
804
+ message = `Effect error channel mismatch: expected ${expected[1]}, got ${actual[1]}.`;
805
+ }
806
+ }
807
+
808
+ if (diag.code === 2349 && message.includes("NonExhaustiveError")) {
809
+ code = "NON_EXHAUSTIVE_MATCH";
810
+ const tagMatch = message.match(/_tag:\s*["']([^"']+)["']/);
811
+ const missingInfo = tagMatch
812
+ ? ` Missing variant: '${tagMatch[1]}'.`
813
+ : "";
814
+ explanation =
815
+ "The pattern match expression does not handle all possible variants of the scrutinee type.";
816
+ suggestedAction = tagMatch
817
+ ? `Add arm '| ${tagMatch[1]} => ...' or use wildcard '| _ => ...' to handle remaining cases.`
818
+ : "Add arms for the missing variants or use a wildcard '| _ => ...'.";
819
+ message = `Pattern match is not exhaustive.${missingInfo} In FunkScript, all variants must be handled or guarded with a fallback '| _ =>'.`;
820
+ }
821
+
822
+ const frame = safeCodeFrame(
823
+ meta.funSource,
824
+ {
825
+ start: { line: loc.line, column: loc.column },
826
+ end: loc.endColumn
827
+ ? { line: loc.line, column: loc.endColumn }
828
+ : undefined,
829
+ },
830
+ {
831
+ message,
832
+ highlightCode: options?.highlightCode ?? false,
833
+ },
834
+ );
835
+
836
+ const codePrefix = typeof code === "number" ? `TS${code}` : code;
837
+ const header = `${loc.file}:${loc.line}:${loc.column} - ${category} ${codePrefix}: ${message}`;
838
+ const formatted = `${frame ? `${header}\n${frame}` : header}${suggestedAction ? `\n help: ${suggestedAction}` : ""}`;
839
+
840
+ tsDiagnostics.push({
841
+ file: loc.file,
842
+ line: loc.line,
843
+ column: loc.column,
844
+ endLine: loc.endLine,
845
+ endColumn: loc.endColumn,
846
+ message,
847
+ diagnosticCode:
848
+ typeof code === "number" ? `TS${code}` : `FS_${code}`,
849
+ explanation,
850
+ suggestedAction,
851
+ category,
852
+ code,
853
+ frame,
854
+ formatted,
855
+ });
856
+ }
857
+
858
+ const collectBindingPatternNames = (
859
+ target: unknown,
860
+ names: Set<string>,
861
+ ): void => {
862
+ if (!target || typeof target !== "object") return;
863
+ const node = target as Record<string, unknown>;
864
+ if (
865
+ (node.kind === "Identifier" || node.kind === "UpperIdentifier") &&
866
+ typeof node.name === "string"
867
+ ) {
868
+ names.add(node.name);
869
+ return;
870
+ }
871
+ if (node.kind === "VariablePattern") {
872
+ collectBindingPatternNames(node.name, names);
873
+ return;
874
+ }
875
+ if (node.kind === "RestPattern") {
876
+ collectBindingPatternNames(node.argument, names);
877
+ return;
878
+ }
879
+ if (node.kind === "RecordPattern" && Array.isArray(node.fields)) {
880
+ for (const field of node.fields as Array<Record<string, unknown>>) {
881
+ if (field.pattern) {
882
+ collectBindingPatternNames(field.pattern, names);
883
+ } else {
884
+ collectBindingPatternNames(field.key, names);
885
+ }
886
+ }
887
+ return;
888
+ }
889
+ if (node.kind === "ArrayPattern" && Array.isArray(node.elements)) {
890
+ for (const elem of node.elements) {
891
+ collectBindingPatternNames(elem, names);
892
+ }
893
+ }
894
+ };
895
+
896
+ const getFunScriptUnannotatedBindings = (
897
+ ast?: Program,
898
+ ): Set<string> => {
899
+ const names = new Set<string>();
900
+ const walk = (node: unknown) => {
901
+ if (!node || typeof node !== "object") return;
902
+ const n = node as Record<string, unknown>;
903
+ if (
904
+ n.kind === "TsEscapeDeclaration" ||
905
+ n.kind === "TsEscapeExpression"
906
+ )
907
+ return;
908
+ if (n.kind === "BindingDeclaration" && !n.typeAnnotation) {
909
+ collectBindingPatternNames(n.id, names);
910
+ }
911
+ for (const key of Object.keys(n)) {
912
+ if (key === "span") continue;
913
+ const child = n[key];
914
+ if (Array.isArray(child)) {
915
+ for (const c of child) walk(c);
916
+ } else if (child && typeof child === "object") {
917
+ walk(child);
918
+ }
919
+ }
920
+ };
921
+ walk(ast);
922
+ return names;
923
+ };
924
+
925
+ const getFunScriptMemberAccesses = (ast?: Program): Set<string> => {
926
+ const names = new Set<string>();
927
+ const walk = (node: unknown) => {
928
+ if (!node || typeof node !== "object") return;
929
+ const n = node as Record<string, unknown>;
930
+ if (
931
+ n.kind === "TsEscapeDeclaration" ||
932
+ n.kind === "TsEscapeExpression"
933
+ )
934
+ return;
935
+ if (n.kind === "MemberExpression") {
936
+ const prop = n.property as { name?: string } | undefined;
937
+ if (prop?.name) {
938
+ names.add(prop.name);
939
+ }
940
+ }
941
+ for (const key of Object.keys(n)) {
942
+ if (key === "span") continue;
943
+ const child = n[key];
944
+ if (Array.isArray(child)) {
945
+ for (const c of child) walk(c);
946
+ } else if (child && typeof child === "object") {
947
+ walk(child);
948
+ }
949
+ }
950
+ };
951
+ walk(ast);
952
+ return names;
953
+ };
954
+
955
+ const getFunScriptTsEscapeRanges = (
956
+ ast: Program | undefined,
957
+ tsCode: string,
958
+ ): Array<{ start: number; end: number }> => {
959
+ const ranges: Array<{ start: number; end: number }> = [];
960
+ let searchFrom = 0;
961
+ const walk = (node: unknown) => {
962
+ if (!node || typeof node !== "object") return;
963
+ const n = node as Record<string, unknown>;
964
+ if (
965
+ (n.kind === "TsEscapeDeclaration" ||
966
+ n.kind === "TsEscapeExpression") &&
967
+ typeof n.code === "string"
968
+ ) {
969
+ const idx = tsCode.indexOf(n.code, searchFrom);
970
+ if (idx !== -1) {
971
+ ranges.push({ start: idx, end: idx + n.code.length });
972
+ searchFrom = idx + n.code.length;
973
+ }
974
+ return;
975
+ }
976
+ for (const key of Object.keys(n)) {
977
+ if (key === "span") continue;
978
+ const child = n[key];
979
+ if (Array.isArray(child)) {
980
+ for (const c of child) walk(c);
981
+ } else if (child && typeof child === "object") {
982
+ walk(child);
983
+ }
984
+ }
985
+ };
986
+ walk(ast);
987
+ return ranges;
988
+ };
989
+
990
+ const checker = program.getTypeChecker();
991
+ for (const [normFile, meta] of virtualSourceMap) {
992
+ const sf = program.getSourceFile(normFile);
993
+ if (!sf) continue;
994
+
995
+ const unannotatedBindings = getFunScriptUnannotatedBindings(meta.ast);
996
+ const memberAccesses = getFunScriptMemberAccesses(meta.ast);
997
+ const tsEscapeRanges = getFunScriptTsEscapeRanges(
998
+ meta.ast,
999
+ meta.tsCode,
1000
+ );
1001
+
1002
+ const isOptionType = (t: ts.Type): boolean =>
1003
+ t.isUnion()
1004
+ ? t.types.length > 0 &&
1005
+ t.types.every((m) =>
1006
+ Boolean(checker.getPropertyOfType(m, "~effect/Option")),
1007
+ )
1008
+ : Boolean(checker.getPropertyOfType(t, "~effect/Option"));
1009
+
1010
+ const isNullishFlag = (t: ts.Type): boolean =>
1011
+ Boolean(t.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined));
1012
+
1013
+ const hasDirectNullish = (t: ts.Type): boolean =>
1014
+ t.isUnion()
1015
+ ? !isOptionType(t) && t.types.some(isNullishFlag)
1016
+ : isNullishFlag(t);
1017
+
1018
+ const hasNullishMember = (t: ts.Type): boolean => {
1019
+ if (hasDirectNullish(t)) return true;
1020
+ const awaited = checker.getAwaitedType(t);
1021
+ if (awaited && awaited !== t && hasDirectNullish(awaited)) {
1022
+ return true;
1023
+ }
1024
+ return false;
1025
+ };
1026
+
1027
+ const isNodeInTsEscape = (targetNode: ts.Node): boolean => {
1028
+ if (tsEscapeRanges.length === 0) return false;
1029
+ const pos = targetNode.getStart(sf);
1030
+ return tsEscapeRanges.some((r) => pos >= r.start && pos < r.end);
1031
+ };
1032
+
1033
+ const isEffectType = (type: ts.Type): boolean => {
1034
+ if (!type) return false;
1035
+ if (type.isUnion()) return type.types.some((t) => isEffectType(t));
1036
+ if (
1037
+ type.symbol?.name === "Effect" ||
1038
+ type.aliasSymbol?.name === "Effect"
1039
+ )
1040
+ return true;
1041
+ if (
1042
+ type.getProperties().some((p) => p.name.includes("effect/Effect"))
1043
+ )
1044
+ return true;
1045
+ const str = checker.typeToString(type);
1046
+ return str.startsWith("Effect<") || str.includes("Effect.Effect<");
1047
+ };
1048
+
1049
+ const addCustomDiag = (
1050
+ targetNode: ts.Node,
1051
+ code: string,
1052
+ customMsg: string,
1053
+ explanation?: string,
1054
+ suggestedAction?: string,
1055
+ ) => {
1056
+ const loc = mapDiagnosticLocation(
1057
+ {
1058
+ file: sf,
1059
+ start: targetNode.getStart(sf),
1060
+ length: targetNode.getWidth(sf),
1061
+ messageText: customMsg,
1062
+ category: ts.DiagnosticCategory.Error,
1063
+ code: 9999,
1064
+ },
1065
+ meta.funPath,
1066
+ meta.funSource,
1067
+ meta.traceMap,
1068
+ meta.tsCode,
1069
+ );
1070
+ const frame = safeCodeFrame(
1071
+ meta.funSource,
1072
+ {
1073
+ start: { line: loc.line, column: loc.column },
1074
+ end: loc.endColumn
1075
+ ? { line: loc.line, column: loc.endColumn }
1076
+ : undefined,
1077
+ },
1078
+ {
1079
+ message: customMsg,
1080
+ highlightCode: options?.highlightCode ?? false,
1081
+ },
1082
+ );
1083
+ const header = `${loc.file}:${loc.line}:${loc.column} - error ${code}: ${customMsg}`;
1084
+ tsDiagnostics.push({
1085
+ file: loc.file,
1086
+ line: loc.line,
1087
+ column: loc.column,
1088
+ endLine: loc.endLine,
1089
+ endColumn: loc.endColumn,
1090
+ message: customMsg,
1091
+ diagnosticCode: `FS_${code}`,
1092
+ explanation,
1093
+ suggestedAction,
1094
+ category: "error",
1095
+ code,
1096
+ frame,
1097
+ formatted: frame ? `${header}\n${frame}` : header,
1098
+ });
1099
+ };
1100
+
1101
+ const reportedSpans = new Set<string>();
1102
+ const addAstDiag = (
1103
+ span:
1104
+ | {
1105
+ start: { line: number; column: number };
1106
+ end: { line: number; column: number };
1107
+ }
1108
+ | undefined,
1109
+ code: string,
1110
+ customMsg: string,
1111
+ category: DiagnosticCategory = "error",
1112
+ explanation?: string,
1113
+ suggestedAction?: string,
1114
+ ) => {
1115
+ if (!span || !span.start || !span.end) return;
1116
+ const key = `${span.start.line}:${span.start.column}:${code}`;
1117
+ if (reportedSpans.has(key)) return;
1118
+ reportedSpans.add(key);
1119
+
1120
+ const frame = safeCodeFrame(
1121
+ meta.funSource,
1122
+ {
1123
+ start: { line: span.start.line, column: span.start.column },
1124
+ end: { line: span.end.line, column: span.end.column },
1125
+ },
1126
+ {
1127
+ message: customMsg,
1128
+ highlightCode: options?.highlightCode ?? false,
1129
+ },
1130
+ );
1131
+ const header = `${meta.funPath}:${span.start.line}:${span.start.column} - ${category} ${code}: ${customMsg}`;
1132
+ tsDiagnostics.push({
1133
+ file: meta.funPath,
1134
+ line: span.start.line,
1135
+ column: span.start.column,
1136
+ endLine: span.end.line,
1137
+ endColumn: span.end.column,
1138
+ message: customMsg,
1139
+ diagnosticCode: `FS_${code}`,
1140
+ explanation,
1141
+ suggestedAction,
1142
+ category,
1143
+ code,
1144
+ frame,
1145
+ formatted: frame ? `${header}\n${frame}` : header,
1146
+ });
1147
+ };
1148
+
1149
+ if (meta.ast) {
1150
+ const isEntry = isEntryModule(meta.funPath, meta.ast, cwd);
1151
+ const controlFlowPolicy = {
1152
+ allowHoles:
1153
+ !!options?.allowHoles ||
1154
+ isPathPolicyEnabled(
1155
+ options?.allowHolesPaths,
1156
+ cwd,
1157
+ meta.funPath,
1158
+ ),
1159
+ allowEarlyReturns:
1160
+ !!options?.allowEarlyReturns ||
1161
+ isPathPolicyEnabled(
1162
+ options?.allowEarlyReturnsPaths,
1163
+ cwd,
1164
+ meta.funPath,
1165
+ ),
1166
+ };
1167
+ const INPLACE_MUTATING_METHODS = new Set([
1168
+ "push",
1169
+ "pop",
1170
+ "shift",
1171
+ "unshift",
1172
+ "splice",
1173
+ "sort",
1174
+ "reverse",
1175
+ ]);
1176
+ const ERROR_CONSTRUCTORS = new Set([
1177
+ "Error",
1178
+ "TypeError",
1179
+ "RangeError",
1180
+ "SyntaxError",
1181
+ "ReferenceError",
1182
+ "EvalError",
1183
+ "URIError",
1184
+ ]);
1185
+
1186
+ checkModuleScopeRefs(meta.ast, addAstDiag);
1187
+ const processPropertySuggestion = (prop: string): string => {
1188
+ switch (prop) {
1189
+ case "argv":
1190
+ return "Accept `args: Array<String>` explicitly in library functions and pass CLI args from the entrypoint (or use `@effect/cli`).";
1191
+ case "cwd":
1192
+ return "Use the Effect `Path` / `FileSystem` service or pass the working directory explicitly as a parameter.";
1193
+ case "stdin":
1194
+ case "stdout":
1195
+ case "stderr":
1196
+ return "Use Effect `Console` or `Terminal` from `@effect/platform-*`.";
1197
+ case "nextTick":
1198
+ return "Use `Effect.yieldNow` or `Effect.forkScoped`.";
1199
+ default:
1200
+ return "Use Effect services (`Config`, `Path`, `Terminal`, `Clock`) or isolate runtime-specific access inside an entry module or `ts { ... }` block.";
1201
+ }
1202
+ };
1203
+ const hasUserProcessBinding = (() => {
1204
+ let shadowed = false;
1205
+ const scan = (n: AstInspectNode | null | undefined) => {
1206
+ if (!n || typeof n !== "object" || shadowed) return;
1207
+ const nId = astChild(n, "id");
1208
+ if (
1209
+ n.kind === "BindingDeclaration" &&
1210
+ nId?.kind === "Identifier" &&
1211
+ astName(nId) === "process"
1212
+ ) {
1213
+ shadowed = true;
1214
+ return;
1215
+ }
1216
+ if (
1217
+ (n.kind === "VariablePattern" || n.kind === "Parameter") &&
1218
+ (astName(astChild(n, "name")) === "process" ||
1219
+ astName(nId) === "process")
1220
+ ) {
1221
+ shadowed = true;
1222
+ return;
1223
+ }
1224
+ if (
1225
+ n.kind === "ImportDeclaration" &&
1226
+ astString(astChild(n, "source"), "value") !== "node:process"
1227
+ ) {
1228
+ const specs = [
1229
+ ...astChildren(n, "specifiers"),
1230
+ astChild(n, "defaultImport"),
1231
+ astChild(n, "namespaceImport"),
1232
+ ].filter((s): s is AstInspectNode => s !== null);
1233
+ if (
1234
+ specs.some(
1235
+ (s) =>
1236
+ astName(astChild(s, "local")) === "process" ||
1237
+ astName(s) === "process",
1238
+ )
1239
+ ) {
1240
+ shadowed = true;
1241
+ return;
1242
+ }
1243
+ }
1244
+ const rec = asRecord(n);
1245
+ for (const key of Object.keys(rec)) {
1246
+ if (key === "span" || key === "kind") continue;
1247
+ const val = rec[key];
1248
+ if (Array.isArray(val)) {
1249
+ for (const item of val) {
1250
+ if (isAstNode(item)) scan(item);
1251
+ }
1252
+ } else if (isAstNode(val)) {
1253
+ scan(val);
1254
+ }
1255
+ }
1256
+ };
1257
+ scan(meta.ast);
1258
+ return shadowed;
1259
+ })();
1260
+ const walkAst = (
1261
+ node: AstInspectNode | null | undefined,
1262
+ parent?: AstInspectNode | null,
1263
+ inMutBlock = false,
1264
+ inMatchArm = false,
1265
+ ) => {
1266
+ if (!node || typeof node !== "object") return;
1267
+ if (
1268
+ node.kind === "TsEscapeDeclaration" ||
1269
+ node.kind === "TsEscapeExpression" ||
1270
+ node.kind === "JsExpression"
1271
+ )
1272
+ return;
1273
+
1274
+ const currentInMut =
1275
+ inMutBlock || node.kind === "MutBlockExpression";
1276
+ const currentInMatchArm =
1277
+ node.kind === "FunctionExpression" ||
1278
+ node.kind === "ArrowFunction"
1279
+ ? false
1280
+ : inMatchArm;
1281
+
1282
+ checkControlFlowRules(
1283
+ node,
1284
+ currentInMatchArm,
1285
+ controlFlowPolicy,
1286
+ addAstDiag,
1287
+ );
1288
+
1289
+ if (node.kind === "CallExpression") {
1290
+ const callee = astChild(node, "callee");
1291
+ const calleeMember = getMemberNames(callee);
1292
+ const calleeName = astName(callee);
1293
+ const nodeArgs = astChildren(node, "args");
1294
+ if (
1295
+ !currentInMut &&
1296
+ calleeMember?.property &&
1297
+ INPLACE_MUTATING_METHODS.has(calleeMember.property)
1298
+ ) {
1299
+ addAstDiag(
1300
+ node.span,
1301
+ "INPLACE_MUTATION",
1302
+ `In-place mutation '.${calleeMember.property}()' is quarantined in FunkScript. Arrays are immutable by default outside 'mut (draft) =>' blocks.`,
1303
+ "error",
1304
+ "Direct array mutation outside draft proxy blocks causes accidental state pollution.",
1305
+ `Use immutable functional alternatives (e.g. 'Array.append', 'Array.modify') or wrap local mutations in 'mut (draft) => { ... }'.`,
1306
+ );
1307
+ } else if (
1308
+ (callee?.kind === "UpperIdentifier" ||
1309
+ callee?.kind === "Identifier") &&
1310
+ calleeName &&
1311
+ ERROR_CONSTRUCTORS.has(calleeName)
1312
+ ) {
1313
+ addAstDiag(
1314
+ node.span,
1315
+ "THROW",
1316
+ `\`${calleeName}(...)\` constructs an unmanaged JavaScript exception. In FunkScript, declare domain failures with 'error Name { ... }' or fail within Effect using 'Effect.fail' or 'Effect.die'.`,
1317
+ "error",
1318
+ "FunkScript avoids raw JavaScript Error exceptions in favor of typed errors or explicit defects.",
1319
+ "Declare a typed error using `error Name { ... }` or use `Effect.dieMessage(...)`.",
1320
+ );
1321
+ } else if (
1322
+ callee?.kind === "Identifier" &&
1323
+ calleeName === "fetch"
1324
+ ) {
1325
+ addAstDiag(
1326
+ node.span,
1327
+ "NATIVE_API",
1328
+ "`fetch` is an unmanaged native HTTP client returning an untyped Promise. In FunkScript, use '@effect/platform' HttpClient or lift with 'js fetch(...)'.",
1329
+ "error",
1330
+ "Bare fetch returns an unmanaged Promise without typed errors or retry policies.",
1331
+ "Use '@effect/platform' HttpClient or lift with `js fetch(...)`.",
1332
+ );
1333
+ } else if (
1334
+ callee?.kind === "Identifier" &&
1335
+ (calleeName === "setTimeout" ||
1336
+ calleeName === "setInterval" ||
1337
+ calleeName === "clearTimeout" ||
1338
+ calleeName === "clearInterval")
1339
+ ) {
1340
+ addAstDiag(
1341
+ node.span,
1342
+ "NATIVE_API",
1343
+ `\`${calleeName}\` is an unmanaged native timer. Time and scheduling are Effect services; use 'Effect.sleep' or 'Schedule.spaced' to ensure fibers can be interrupted and tested deterministically.`,
1344
+ "error",
1345
+ "Native timers run outside Effect's fiber scheduler, leak when tasks are cancelled, and cannot be controlled with TestClock.",
1346
+ "Replace with `Effect.sleep(...)` or `Schedule.spaced(...)`.",
1347
+ );
1348
+ } else if (
1349
+ callee?.kind === "Identifier" &&
1350
+ (calleeName === "getOrThrow" ||
1351
+ calleeName === "getOrThrowWith")
1352
+ ) {
1353
+ addAstDiag(
1354
+ node.span,
1355
+ "THROW",
1356
+ `\`${calleeName}\` throws an unhandled exception at runtime. In FunkScript, handle absence or failure safely using 'getOrElse', pattern matching ('match'), or lift with 'Effect.fromOption'.`,
1357
+ "error",
1358
+ "FunkScript disallows runtime throwing methods.",
1359
+ "Use `Option.getOrElse`, `Option.match`, or `Effect.fromOption`.",
1360
+ );
1361
+ } else if (
1362
+ callee?.kind === "UpperIdentifier" &&
1363
+ calleeName === "Date"
1364
+ ) {
1365
+ addAstDiag(
1366
+ node.span,
1367
+ "HIDDEN_INPUT",
1368
+ "`Date()` is a hidden input. Time is an Effect service; use 'Clock.currentTimeMillis' or 'DateTime.now' to make code testable.",
1369
+ "error",
1370
+ "Time and randomness are Effect services; reading global non-deterministic constructors creates flaky tests.",
1371
+ "Replace `Date()` with `now <- Clock.currentTimeMillis` or `DateTime.now`.",
1372
+ );
1373
+ } else if (calleeMember) {
1374
+ const o = calleeMember.object;
1375
+ const p = calleeMember.property;
1376
+ if (
1377
+ (o === "Semaphore" || (o && /semaphore|sem/i.test(o))) &&
1378
+ (p === "take" || p === "release")
1379
+ ) {
1380
+ addAstDiag(
1381
+ node.span,
1382
+ "MANUAL_SEMAPHORE",
1383
+ `Manual semaphore permit management leaks permits on fiber interruption. Use 'withPermits' instead.`,
1384
+ "error",
1385
+ "Manually calling take and release on a semaphore leaks permits if the fiber is interrupted or fails between take and release.",
1386
+ "Wrap the critical section in 'semaphore.withPermits(n)(effect)' for guaranteed permit acquisition and release.",
1387
+ );
1388
+ } else if (o === "Queue" && p === "unbounded") {
1389
+ addAstDiag(
1390
+ node.span,
1391
+ "UNBOUNDED_QUEUE",
1392
+ `Queue created with infinite capacity. High-volume producers can exhaust memory without backpressure. Prefer 'Queue.bounded(capacity)' or 'Queue.make({ capacity })'.`,
1393
+ "warning",
1394
+ "Unbounded queues buffer work indefinitely without limit. If producers outpace consumers, the queue will grow until memory is exhausted.",
1395
+ "Specify a bounded capacity with 'Queue.bounded(capacity)' or 'Queue.make({ capacity })'.",
1396
+ );
1397
+ } else if (
1398
+ o === "Queue" &&
1399
+ p === "make" &&
1400
+ nodeArgs.length === 0
1401
+ ) {
1402
+ addAstDiag(
1403
+ node.span,
1404
+ "UNBOUNDED_QUEUE",
1405
+ `Queue created with infinite capacity. High-volume producers can exhaust memory without backpressure. Prefer 'Queue.bounded(capacity)' or specify '{ capacity: 1024 }'.`,
1406
+ "warning",
1407
+ "Queue.make() defaults to unbounded capacity in Effect v4.",
1408
+ "Specify a bounded capacity with 'Queue.bounded(capacity)' or 'Queue.make({ capacity })'.",
1409
+ );
1410
+ } else if (o === "Date" && p === "now") {
1411
+ addAstDiag(
1412
+ node.span,
1413
+ "HIDDEN_INPUT",
1414
+ "`Date.now()` is a hidden input. Time is an Effect service; use 'Clock.currentTimeMillis' or 'DateTime.now' to make code testable.",
1415
+ "error",
1416
+ "Time and randomness are Effect services; reading global non-deterministic APIs creates flaky tests.",
1417
+ "Replace `Date.now()` with `now <- Clock.currentTimeMillis` or `DateTime.now`.",
1418
+ );
1419
+ } else if (o === "Math" && p === "random") {
1420
+ addAstDiag(
1421
+ node.span,
1422
+ "HIDDEN_INPUT",
1423
+ "`Math.random()` is a hidden input. Randomness is an Effect service; use 'Random.nextInt', 'Random.next', or 'Random.nextIntBetween' to make code testable.",
1424
+ "error",
1425
+ "Randomness is an Effect service; reading global non-deterministic Math.random creates non-reproducible bugs.",
1426
+ "Replace `Math.random()` with `Random.nextInt` or `Random.next` from the Effect Random service.",
1427
+ );
1428
+ } else if (o === "performance" && p === "now") {
1429
+ addAstDiag(
1430
+ node.span,
1431
+ "HIDDEN_INPUT",
1432
+ "`performance.now()` is a hidden input. Time is an Effect service; use 'Clock.currentTimeNanos' or 'Clock.currentTimeMillis' to make code testable.",
1433
+ "error",
1434
+ "Time is an Effect service; use Clock to measure duration deterministically.",
1435
+ "Replace `performance.now()` with `Clock.currentTimeNanos`.",
1436
+ );
1437
+ } else if (o === "crypto" && p === "randomUUID") {
1438
+ addAstDiag(
1439
+ node.span,
1440
+ "HIDDEN_INPUT",
1441
+ "`crypto.randomUUID()` is a hidden input. Randomness is an Effect service; use 'Random' or 'UUID' schemas to make code testable.",
1442
+ "error",
1443
+ "Randomness is an Effect service; reading crypto directly creates non-reproducible states in tests.",
1444
+ "Use Effect's Random service or validated UUID schemas.",
1445
+ );
1446
+ } else if (o === "crypto" && p === "getRandomValues") {
1447
+ addAstDiag(
1448
+ node.span,
1449
+ "HIDDEN_INPUT",
1450
+ "`crypto.getRandomValues()` is a hidden input. Randomness is an Effect service; use 'Random' to make code testable.",
1451
+ "error",
1452
+ "Randomness is an Effect service; reading crypto directly creates non-reproducible states in tests.",
1453
+ "Use Effect's Random service.",
1454
+ );
1455
+ } else if (o === "JSON" && p === "parse") {
1456
+ addAstDiag(
1457
+ node.span,
1458
+ "THROW",
1459
+ "`JSON.parse` is an unmanaged API that throws SyntaxError on invalid input. In FunkScript, decode JSON safely using Effect's 'Schema.parseJson' or 'Schema.decodeUnknown'.",
1460
+ "error",
1461
+ "JSON.parse throws raw exceptions on malformed input.",
1462
+ "Use `Schema.parseJson(MySchema)` or `Schema.decodeUnknown(MySchema)`.",
1463
+ );
1464
+ } else if (
1465
+ (o === "Option" || o === "Either") &&
1466
+ (p === "getOrThrow" || p === "getOrThrowWith")
1467
+ ) {
1468
+ addAstDiag(
1469
+ node.span,
1470
+ "THROW",
1471
+ `\`${o}.${p}\` throws an unhandled exception at runtime. In FunkScript, handle absence or failure safely using '${o}.getOrElse', pattern matching ('match'), or lift with 'Effect.from${o}'.`,
1472
+ "error",
1473
+ "FunkScript disallows runtime throwing methods.",
1474
+ `Use \`${o}.getOrElse\`, \`${o}.match\`, or \`Effect.from${o}\`.`,
1475
+ );
1476
+ } else if (
1477
+ (o === "globalThis" || o === "window") &&
1478
+ (p === "setTimeout" ||
1479
+ p === "setInterval" ||
1480
+ p === "clearTimeout" ||
1481
+ p === "clearInterval" ||
1482
+ p === "fetch")
1483
+ ) {
1484
+ addAstDiag(
1485
+ node.span,
1486
+ "NATIVE_API",
1487
+ `\`${o}.${p}\` is an unmanaged native API. In FunkScript, use Effect services instead.`,
1488
+ "error",
1489
+ "Unmanaged native APIs bypass Effect cancellation and tracing.",
1490
+ "Use Effect services ('Effect.sleep', '@effect/platform' HttpClient).",
1491
+ );
1492
+ } else if (o === "Reflect") {
1493
+ addAstDiag(
1494
+ node.span,
1495
+ "UNSAFE_REFLECT",
1496
+ `\`Reflect.${p}\` is an unsafe reflection escape hatch that bypasses static type safety.`,
1497
+ "warning",
1498
+ "Reflective property access and dynamic invocation bypass FunkScript's static type and schema guarantees.",
1499
+ "Use `Schema.decodeUnknownOption`, `Record.*`, or type-guard narrowing in `match` instead.",
1500
+ );
1501
+ } else if (
1502
+ !isEntry &&
1503
+ o === "console" &&
1504
+ (p === "log" ||
1505
+ p === "error" ||
1506
+ p === "warn" ||
1507
+ p === "info")
1508
+ ) {
1509
+ addAstDiag(
1510
+ node.span,
1511
+ "NATIVE_API",
1512
+ `\`console.${p}\` writes unmanaged output to global stream. In FunkScript library code, use Effect's 'Console.${p}' service to keep logging contextual, traceable, and testable.`,
1513
+ "error",
1514
+ "Direct console logging in library code bypasses Effect's Logger services and cannot be intercepted or silenced in tests.",
1515
+ `Use \`Console.${p}\` from 'effect'.`,
1516
+ );
1517
+ }
1518
+ }
1519
+ }
1520
+
1521
+ if (
1522
+ node.kind === "Identifier" ||
1523
+ node.kind === "UpperIdentifier"
1524
+ ) {
1525
+ const isProp =
1526
+ parent?.kind === "MemberExpression" &&
1527
+ astChild(parent, "property") === node;
1528
+ const isCallee =
1529
+ parent?.kind === "CallExpression" &&
1530
+ astChild(parent, "callee") === node;
1531
+ const isBinding =
1532
+ (parent?.kind === "BindingDeclaration" &&
1533
+ astChild(parent, "id") === node) ||
1534
+ parent?.kind === "FunctionDeclaration" ||
1535
+ parent?.kind === "VariablePattern";
1536
+ const isImport =
1537
+ parent?.kind === "ImportSpecifier" ||
1538
+ parent?.kind === "ImportDeclaration";
1539
+ const isType =
1540
+ parent?.kind === "TypeReferenceNode" ||
1541
+ parent?.kind === "QualifiedTypeReferenceNode";
1542
+
1543
+ const nodeName = astName(node);
1544
+ if (
1545
+ !isProp &&
1546
+ !isCallee &&
1547
+ !isBinding &&
1548
+ !isImport &&
1549
+ !isType &&
1550
+ nodeName
1551
+ ) {
1552
+ if (nodeName === "fetch") {
1553
+ addAstDiag(
1554
+ node.span,
1555
+ "NATIVE_API",
1556
+ "`fetch` is an unmanaged native HTTP client returning an untyped Promise. In FunkScript, use '@effect/platform' HttpClient or lift with 'js fetch(...)'.",
1557
+ "error",
1558
+ "Bare fetch returns an unmanaged Promise without typed errors or retry policies.",
1559
+ "Use '@effect/platform' HttpClient or lift with `js fetch(...)`.",
1560
+ );
1561
+ } else if (
1562
+ nodeName === "setTimeout" ||
1563
+ nodeName === "setInterval" ||
1564
+ nodeName === "clearTimeout" ||
1565
+ nodeName === "clearInterval"
1566
+ ) {
1567
+ addAstDiag(
1568
+ node.span,
1569
+ "NATIVE_API",
1570
+ `\`${nodeName}\` is an unmanaged native timer. Time and scheduling are Effect services; use 'Effect.sleep' or 'Schedule.spaced'.`,
1571
+ "error",
1572
+ "Native timers run outside Effect's fiber scheduler and cannot be controlled with TestClock.",
1573
+ "Replace with `Effect.sleep(...)` or `Schedule.spaced(...)`.",
1574
+ );
1575
+ } else if (ERROR_CONSTRUCTORS.has(nodeName)) {
1576
+ addAstDiag(
1577
+ node.span,
1578
+ "THROW",
1579
+ `\`${nodeName}\` is an unmanaged JavaScript exception constructor. In FunkScript, declare domain failures with 'error Name { ... }' or fail within Effect using 'Effect.fail' or 'Effect.die'.`,
1580
+ "error",
1581
+ "FunkScript avoids raw JavaScript Error exceptions in favor of typed errors or explicit defects.",
1582
+ "Declare a typed error using `error Name { ... }` or use `Effect.dieMessage(...)`.",
1583
+ );
1584
+ }
1585
+ }
1586
+ } else if (node.kind === "PipelineExpression") {
1587
+ const r = astChild(node, "right");
1588
+ const rMember = getMemberNames(r);
1589
+ const rName = astName(r);
1590
+ if (
1591
+ (rMember &&
1592
+ (rMember.object === "Option" ||
1593
+ rMember.object === "Either") &&
1594
+ (rMember.property === "getOrThrow" ||
1595
+ rMember.property === "getOrThrowWith")) ||
1596
+ (r?.kind === "Identifier" &&
1597
+ (rName === "getOrThrow" || rName === "getOrThrowWith"))
1598
+ ) {
1599
+ const targetName = rMember
1600
+ ? `${rMember.object}.${rMember.property}`
1601
+ : rName;
1602
+ const o = rMember?.object ?? "Option";
1603
+ addAstDiag(
1604
+ r?.span || node.span,
1605
+ "THROW",
1606
+ `\`${targetName}\` throws an unhandled exception at runtime. In FunkScript, handle absence or failure safely using 'getOrElse', pattern matching ('match'), or lift to Effect.`,
1607
+ "error",
1608
+ "FunkScript disallows runtime throwing methods.",
1609
+ `Use \`${o}.getOrElse\`, \`${o}.match\`, or \`Effect.from${o}\`.`,
1610
+ );
1611
+ } else if (r?.kind === "CallExpression") {
1612
+ const c = astChild(r, "callee");
1613
+ const cMember = getMemberNames(c);
1614
+ const cName = astName(c);
1615
+ if (
1616
+ (cMember &&
1617
+ (cMember.object === "Option" ||
1618
+ cMember.object === "Either") &&
1619
+ (cMember.property === "getOrThrow" ||
1620
+ cMember.property === "getOrThrowWith")) ||
1621
+ (c?.kind === "Identifier" &&
1622
+ (cName === "getOrThrow" || cName === "getOrThrowWith"))
1623
+ ) {
1624
+ const targetName = cMember
1625
+ ? `${cMember.object}.${cMember.property}`
1626
+ : cName;
1627
+ const o = cMember?.object ?? "Option";
1628
+ addAstDiag(
1629
+ c?.span || r.span,
1630
+ "THROW",
1631
+ `\`${targetName}\` throws an unhandled exception at runtime. In FunkScript, handle absence or failure safely using 'getOrElse', pattern matching ('match'), or lift to Effect.`,
1632
+ "error",
1633
+ "FunkScript disallows runtime throwing methods.",
1634
+ `Use \`${o}.getOrElse\`, \`${o}.match\`, or \`Effect.from${o}\`.`,
1635
+ );
1636
+ }
1637
+ }
1638
+ } else if (node.kind === "MemberExpression") {
1639
+ const nodeObj = astChild(node, "object");
1640
+ const nodeProp = astChild(node, "property");
1641
+ if (
1642
+ nodeObj?.kind === "IndexExpression" &&
1643
+ astChild(nodeObj, "index")?.kind !== "StringLiteral"
1644
+ ) {
1645
+ addAstDiag(
1646
+ node.span,
1647
+ "INDEX_OPTION_PROPERTY",
1648
+ "Array indexing returns an Option<T>. Unwrap with match, Option.map, or Option.getOrElse before accessing properties.",
1649
+ "error",
1650
+ "In FunkScript's Pit of Success, array indexing returns an Option<T> to prevent runtime undefined errors. Direct property access on an Option reads undefined at runtime.",
1651
+ "Unwrap with match, Option.map, or Option.getOrElse before accessing properties.",
1652
+ );
1653
+ }
1654
+ const o = astName(nodeObj);
1655
+ const p = astName(nodeProp);
1656
+ if (parent?.kind !== "CallExpression") {
1657
+ if (o === "Date" && p === "now") {
1658
+ addAstDiag(
1659
+ node.span,
1660
+ "HIDDEN_INPUT",
1661
+ "`Date.now` is a hidden input. Time is an Effect service; use 'Clock.currentTimeMillis' or 'DateTime.now' to make code testable.",
1662
+ "error",
1663
+ );
1664
+ } else if (o === "Math" && p === "random") {
1665
+ addAstDiag(
1666
+ node.span,
1667
+ "HIDDEN_INPUT",
1668
+ "`Math.random` is a hidden input. Randomness is an Effect service; use 'Random.nextInt', 'Random.next', or 'Random.nextIntBetween' to make code testable.",
1669
+ "error",
1670
+ );
1671
+ } else if (o === "performance" && p === "now") {
1672
+ addAstDiag(
1673
+ node.span,
1674
+ "HIDDEN_INPUT",
1675
+ "`performance.now` is a hidden input. Time is an Effect service; use 'Clock.currentTimeNanos' or 'Clock.currentTimeMillis' to make code testable.",
1676
+ "error",
1677
+ );
1678
+ }
1679
+ }
1680
+ if (
1681
+ nodeObj?.kind === "Identifier" &&
1682
+ (o === "process" || o === "Bun" || o === "Deno") &&
1683
+ p === "exit" &&
1684
+ !(o === "process" && hasUserProcessBinding)
1685
+ ) {
1686
+ addAstDiag(
1687
+ node.span,
1688
+ "PROCESS_EXIT",
1689
+ `\`${o}.exit\` aborts the runtime immediately and skips Effect Scope finalizers.`,
1690
+ "error",
1691
+ "Calling `.exit()` bypasses structured concurrency cleanup and resource finalizers.",
1692
+ "Return a typed failure (`Effect.fail(...)`) and run the root program with `BunRuntime.runMain` or `NodeRuntime.runMain`.",
1693
+ );
1694
+ }
1695
+ }
1696
+
1697
+ if (!isEntry) {
1698
+ // §1.10: Running Effects mid-program
1699
+ let runnerName: string | null = null;
1700
+ let runnerSpan: Span | null = null;
1701
+
1702
+ if (node.kind === "CallExpression") {
1703
+ const callee = astChild(node, "callee");
1704
+ runnerName = getEffectRunnerName(callee);
1705
+ runnerSpan = callee?.span || node.span || null;
1706
+ } else if (node.kind === "PipelineExpression") {
1707
+ const r = astChild(node, "right");
1708
+ if (r?.kind === "CallExpression") {
1709
+ const rCallee = astChild(r, "callee");
1710
+ runnerName = getEffectRunnerName(rCallee);
1711
+ runnerSpan = rCallee?.span || r.span || null;
1712
+ } else {
1713
+ runnerName = getEffectRunnerName(r);
1714
+ runnerSpan = r?.span || node.span || null;
1715
+ }
1716
+ }
1717
+
1718
+ if (runnerName && runnerSpan) {
1719
+ addAstDiag(
1720
+ runnerSpan,
1721
+ "EFFECT_RUN",
1722
+ `\`${runnerName}\` executes an Effect mid-program. In FunkScript, library code must compose and return Effects. Only entry modules (e.g. 'main.fun', or modules exporting 'main') may run effects.`,
1723
+ "error",
1724
+ "Running effects mid-program breaks composability, defeats dependency injection with Layer/Context, and prevents the caller from controlling execution or handling errors.",
1725
+ "Return the `Effect` directly from this function and allow the entry module (or main) to execute it.",
1726
+ );
1727
+ }
1728
+
1729
+ // §1.11: Reading globals for configuration and ambient process state
1730
+ if (node.kind === "MemberExpression") {
1731
+ const obj = astChild(node, "object");
1732
+ const prop = astChild(node, "property");
1733
+ const objName = astName(obj);
1734
+ const propName = astName(prop);
1735
+ if (
1736
+ obj?.kind === "Identifier" &&
1737
+ (objName === "process" ||
1738
+ objName === "Deno" ||
1739
+ objName === "Bun") &&
1740
+ propName === "env" &&
1741
+ !(objName === "process" && hasUserProcessBinding)
1742
+ ) {
1743
+ const fullName = `${objName}.env`;
1744
+ addAstDiag(
1745
+ node.span,
1746
+ "ENV_GLOBAL",
1747
+ `\`${fullName}\` reads environment configuration directly from global state. In FunkScript, library code should declare configuration dependencies using Effect's 'Config' service, or receive configuration as parameters.`,
1748
+ "error",
1749
+ "Reading global environment variables in library code couples modules to ambient state and makes testing and re-configuration difficult.",
1750
+ "Use Effect 'Config' (e.g. `Config.string('VAR')`) or pass configuration explicitly as arguments.",
1751
+ );
1752
+ } else if (
1753
+ obj?.kind === "Identifier" &&
1754
+ objName === "process" &&
1755
+ !hasUserProcessBinding &&
1756
+ propName &&
1757
+ propName !== "env" &&
1758
+ propName !== "exit"
1759
+ ) {
1760
+ addAstDiag(
1761
+ node.span,
1762
+ "PROCESS_GLOBAL",
1763
+ `\`process.${propName}\` reads ambient Node/Bun process state directly. In FunkScript, library code should depend on Effect services instead of global \`process\`.`,
1764
+ "error",
1765
+ "Direct `process` access in library code couples modules to ambient runtime state and makes testing difficult.",
1766
+ processPropertySuggestion(propName),
1767
+ );
1768
+ }
1769
+ } else if (
1770
+ node.kind === "Identifier" &&
1771
+ astName(node) === "process" &&
1772
+ !hasUserProcessBinding &&
1773
+ !(
1774
+ parent?.kind === "MemberExpression" &&
1775
+ (astChild(parent, "object") === node ||
1776
+ astChild(parent, "property") === node)
1777
+ ) &&
1778
+ !(
1779
+ parent?.kind === "CallExpression" &&
1780
+ astChild(parent, "callee") === node
1781
+ ) &&
1782
+ !(
1783
+ (parent?.kind === "BindingDeclaration" &&
1784
+ astChild(parent, "id") === node) ||
1785
+ parent?.kind === "FunctionDeclaration" ||
1786
+ parent?.kind === "VariablePattern"
1787
+ ) &&
1788
+ !(
1789
+ parent?.kind === "ImportSpecifier" ||
1790
+ parent?.kind === "ImportDeclaration"
1791
+ ) &&
1792
+ !(
1793
+ parent?.kind === "TypeReferenceNode" ||
1794
+ parent?.kind === "QualifiedTypeReferenceNode"
1795
+ ) &&
1796
+ !(
1797
+ parent?.kind === "FieldEntry" &&
1798
+ astChild(parent, "key") === node
1799
+ ) &&
1800
+ !(
1801
+ parent?.kind === "Parameter" &&
1802
+ astChild(parent, "name") === node
1803
+ )
1804
+ ) {
1805
+ addAstDiag(
1806
+ node.span,
1807
+ "PROCESS_GLOBAL",
1808
+ "`process` accesses ambient Node/Bun runtime global state. In FunkScript, library code should use Effect services (`Config`, `Console`, `Terminal`, `Path`, `FileSystem`) instead of passing or reflecting on global `process`.",
1809
+ "error",
1810
+ "Passing or reflecting on global `process` (e.g. `Reflect.get(process, ...)`) bypasses dependency injection and breaks testability.",
1811
+ "Use Effect services (`Config`, `Path`, `Terminal`, `Clock`) or isolate runtime access in an entry module / `ts { ... }` block.",
1812
+ );
1813
+ }
1814
+
1815
+ // §1.13: Detached fibers
1816
+ if (node.kind === "CallExpression") {
1817
+ const c = astChild(node, "callee");
1818
+ const cMember = getMemberNames(c);
1819
+ if (
1820
+ (cMember?.object === "Effect" &&
1821
+ cMember.property === "forkDetach") ||
1822
+ (c?.kind === "Identifier" && astName(c) === "forkDetach")
1823
+ ) {
1824
+ addAstDiag(
1825
+ c?.span || node.span,
1826
+ "DETACHED_FIBER",
1827
+ "`Effect.forkDetach` creates a detached fiber nobody owns. It keeps running after its caller is interrupted. Use 'Effect.forkScoped' (tied to Scope) or 'Effect.forkChild' (tied to parent fiber) to ensure structured concurrency.",
1828
+ "error",
1829
+ "Detached fibers leak beyond the lifetime of the caller with no owner.",
1830
+ "Use `Effect.forkScoped` (tied to Scope) or `Effect.forkChild` (tied to parent fiber), or long-lived background work in `Layer.effectDiscard(Effect.forkScoped(...))`.",
1831
+ );
1832
+ }
1833
+ } else if (node.kind === "PipelineExpression") {
1834
+ const r = astChild(node, "right");
1835
+ const rMember = getMemberNames(r);
1836
+ if (
1837
+ (rMember?.object === "Effect" &&
1838
+ rMember.property === "forkDetach") ||
1839
+ (r?.kind === "Identifier" && astName(r) === "forkDetach")
1840
+ ) {
1841
+ addAstDiag(
1842
+ r?.span || node.span,
1843
+ "DETACHED_FIBER",
1844
+ "`Effect.forkDetach` creates a detached fiber nobody owns. It keeps running after its caller is interrupted. Use 'Effect.forkScoped' (tied to Scope) or 'Effect.forkChild' (tied to parent fiber) to ensure structured concurrency.",
1845
+ "error",
1846
+ "Detached fibers leak beyond the lifetime of the caller with no owner.",
1847
+ "Use `Effect.forkScoped` (tied to Scope) or `Effect.forkChild` (tied to parent fiber), or long-lived background work in `Layer.effectDiscard(Effect.forkScoped(...))`.",
1848
+ );
1849
+ } else if (r?.kind === "CallExpression") {
1850
+ const c = astChild(r, "callee");
1851
+ const cMember = getMemberNames(c);
1852
+ if (
1853
+ (cMember?.object === "Effect" &&
1854
+ cMember.property === "forkDetach") ||
1855
+ (c?.kind === "Identifier" && astName(c) === "forkDetach")
1856
+ ) {
1857
+ addAstDiag(
1858
+ c?.span || r.span,
1859
+ "DETACHED_FIBER",
1860
+ "`Effect.forkDetach` creates a detached fiber nobody owns. It keeps running after its caller is interrupted. Use 'Effect.forkScoped' (tied to Scope) or 'Effect.forkChild' (tied to parent fiber) to ensure structured concurrency.",
1861
+ "error",
1862
+ "Detached fibers leak beyond the lifetime of the caller with no owner.",
1863
+ "Use `Effect.forkScoped` (tied to Scope) or `Effect.forkChild` (tied to parent fiber), or long-lived background work in `Layer.effectDiscard(Effect.forkScoped(...))`.",
1864
+ );
1865
+ }
1866
+ }
1867
+ }
1868
+
1869
+ // § Pit of Success: Untyped literal error in Effect.fail
1870
+ if (node.kind === "CallExpression") {
1871
+ const callee = astChild(node, "callee");
1872
+ const calleeMember = getMemberNames(callee);
1873
+ const isFail =
1874
+ (calleeMember?.object === "Effect" &&
1875
+ calleeMember.property === "fail") ||
1876
+ (callee?.kind === "Identifier" &&
1877
+ astName(callee) === "fail");
1878
+ const args = astChildren(node, "args");
1879
+ if (isFail && args.length > 0) {
1880
+ const arg = args[0];
1881
+ if (
1882
+ arg.kind === "StringLiteral" ||
1883
+ arg.kind === "NumberLiteral"
1884
+ ) {
1885
+ addAstDiag(
1886
+ arg.span || node.span,
1887
+ "UNTYPED_ERROR",
1888
+ "`Effect.fail` with untyped literal. In FunkScript, library domain errors should be tagged (using Schema.TaggedError or Data.TaggedError) to enable type-safe error discrimination with 'catchTag'.",
1889
+ "warning",
1890
+ "Failing with raw strings or numbers prevents callers from discriminating errors with catchTag or pattern matching.",
1891
+ "Define a tagged error schema or use `Data.TaggedError` to represent expected failures.",
1892
+ );
1893
+ }
1894
+ }
1895
+ } else if (node.kind === "PipelineExpression") {
1896
+ const r = astChild(node, "right");
1897
+ const rMember = getMemberNames(r);
1898
+ const isFail =
1899
+ (rMember?.object === "Effect" &&
1900
+ rMember.property === "fail") ||
1901
+ (r?.kind === "Identifier" && astName(r) === "fail");
1902
+ const left = astChild(node, "left");
1903
+ if (
1904
+ isFail &&
1905
+ (left?.kind === "StringLiteral" ||
1906
+ left?.kind === "NumberLiteral")
1907
+ ) {
1908
+ addAstDiag(
1909
+ left.span || node.span,
1910
+ "UNTYPED_ERROR",
1911
+ "`Effect.fail` with untyped literal. In FunkScript, library domain errors should be tagged (using Schema.TaggedError or Data.TaggedError) to enable type-safe error discrimination with 'catchTag'.",
1912
+ "warning",
1913
+ "Failing with raw strings or numbers prevents callers from discriminating errors with catchTag or pattern matching.",
1914
+ "Define a tagged error schema or use `Data.TaggedError` to represent expected failures.",
1915
+ );
1916
+ }
1917
+ }
1918
+ }
1919
+
1920
+ if (node.kind === "RecordExpression") {
1921
+ for (const entry of astChildren(node, "entries")) {
1922
+ if (entry.kind === "FieldEntry") {
1923
+ const key = astName(astChild(entry, "key"));
1924
+ const entryVal = astChild(entry, "value");
1925
+ const val =
1926
+ astString(entryVal, "raw") ||
1927
+ astString(astChildren(entryVal, "parts")[0], "value");
1928
+ if (
1929
+ key === "concurrency" &&
1930
+ (val === '"unbounded"' || val === "unbounded")
1931
+ ) {
1932
+ addAstDiag(
1933
+ entry.span || node.span,
1934
+ "UNBOUNDED_CONCURRENCY",
1935
+ '`concurrency: "unbounded"` can overwhelm system resources. Specify an explicit concurrency limit (e.g. `{ concurrency: 10 }`).',
1936
+ "warning",
1937
+ "Unbounded concurrency can exhaust sockets, file handles, or memory under burst traffic.",
1938
+ "Specify a bounded concurrency number, e.g. `{ concurrency: 10 }`.",
1939
+ );
1940
+ }
1941
+ }
1942
+ }
1943
+ }
1944
+
1945
+ // § Pit of Success: Eager evaluation in Effect.succeed
1946
+ const isPureDataConstructor = (expr: unknown): boolean => {
1947
+ if (!expr || typeof expr !== "object") return false;
1948
+ const e = expr as Record<string, unknown>;
1949
+ if (e.kind !== "CallExpression") return false;
1950
+ const c = e.callee as Record<string, unknown> | undefined;
1951
+ if (c?.kind === "MemberExpression") {
1952
+ const obj = (c.object as { name?: string } | undefined)?.name;
1953
+ const prop = (c.property as { name?: string } | undefined)
1954
+ ?.name;
1955
+ if (obj === "Option" && (prop === "some" || prop === "none"))
1956
+ return true;
1957
+ if (obj === "Chunk" && (prop === "empty" || prop === "make"))
1958
+ return true;
1959
+ if (
1960
+ obj === "HashMap" &&
1961
+ (prop === "empty" || prop === "make")
1962
+ )
1963
+ return true;
1964
+ if (
1965
+ obj === "HashSet" &&
1966
+ (prop === "empty" || prop === "make")
1967
+ )
1968
+ return true;
1969
+ }
1970
+ return false;
1971
+ };
1972
+
1973
+ if (node.kind === "CallExpression") {
1974
+ const callee = astChild(node, "callee");
1975
+ const calleeMember = getMemberNames(callee);
1976
+ const isSucceed =
1977
+ (calleeMember?.object === "Effect" &&
1978
+ calleeMember.property === "succeed") ||
1979
+ (callee?.kind === "Identifier" &&
1980
+ astName(callee) === "succeed");
1981
+ const args = astChildren(node, "args");
1982
+ if (isSucceed && args.length > 0) {
1983
+ const arg = args[0];
1984
+ if (
1985
+ (arg.kind === "CallExpression" &&
1986
+ !isPureDataConstructor(arg)) ||
1987
+ arg.kind === "NewExpression"
1988
+ ) {
1989
+ addAstDiag(
1990
+ arg.span || node.span,
1991
+ "EAGER_SUCCEED",
1992
+ "`Effect.succeed` evaluates its argument eagerly at construction time. If the expression contains function calls or side effects, use `Effect.sync(() => ...)` for deferred evaluation.",
1993
+ "warning",
1994
+ "Passing a function call or constructor to Effect.succeed executes it immediately upon effect construction, not when the effect runs.",
1995
+ "Use `Effect.sync(() => ...)` or `Effect.try(...)` to defer evaluation until the effect is executed.",
1996
+ );
1997
+ }
1998
+ }
1999
+ } else if (node.kind === "PipelineExpression") {
2000
+ const r = astChild(node, "right");
2001
+ const rMember = getMemberNames(r);
2002
+ const isSucceed =
2003
+ (rMember?.object === "Effect" &&
2004
+ rMember.property === "succeed") ||
2005
+ (r?.kind === "Identifier" && astName(r) === "succeed");
2006
+ if (isSucceed) {
2007
+ const left = astChild(node, "left");
2008
+ if (
2009
+ (left?.kind === "CallExpression" &&
2010
+ !isPureDataConstructor(left)) ||
2011
+ left?.kind === "NewExpression"
2012
+ ) {
2013
+ addAstDiag(
2014
+ left.span || node.span,
2015
+ "EAGER_SUCCEED",
2016
+ "`Effect.succeed` evaluates its argument eagerly at construction time. If the expression contains function calls or side effects, use `Effect.sync(() => ...)` for deferred evaluation.",
2017
+ "warning",
2018
+ "Passing a function call or constructor to Effect.succeed executes it immediately upon effect construction, not when the effect runs.",
2019
+ "Use `Effect.sync(() => ...)` or `Effect.try(...)` to defer evaluation until the effect is executed.",
2020
+ );
2021
+ }
2022
+ }
2023
+ }
2024
+
2025
+ if (
2026
+ node.kind === "EffectBlockExpression" ||
2027
+ node.kind === "ParBlockExpression"
2028
+ ) {
2029
+ const readRefs = new Set<string>();
2030
+ const getRefOp = (
2031
+ expr: unknown,
2032
+ ): { type: "get" | "set"; refName: string } | null => {
2033
+ if (!expr || typeof expr !== "object") return null;
2034
+ const e = expr as Record<string, unknown>;
2035
+ if (e.kind !== "CallExpression") return null;
2036
+ const c = e.callee as Record<string, unknown> | undefined;
2037
+ if (!c || c.kind !== "MemberExpression") return null;
2038
+ const obj = c.object as Record<string, unknown> | undefined;
2039
+ const prop = (c.property as { name?: string } | undefined)
2040
+ ?.name;
2041
+ if (
2042
+ (obj as { name?: string } | undefined)?.name === "Ref" &&
2043
+ (prop === "get" || prop === "set")
2044
+ ) {
2045
+ const args = e.args as unknown[] | undefined;
2046
+ const firstArg = args?.[0] as
2047
+ Record<string, unknown> | undefined;
2048
+ if (
2049
+ firstArg &&
2050
+ (firstArg.kind === "Identifier" ||
2051
+ firstArg.kind === "UpperIdentifier")
2052
+ ) {
2053
+ return { type: prop, refName: firstArg.name as string };
2054
+ }
2055
+ } else if (
2056
+ (prop === "get" || prop === "set") &&
2057
+ (obj?.kind === "Identifier" ||
2058
+ obj?.kind === "UpperIdentifier")
2059
+ ) {
2060
+ return { type: prop, refName: obj.name as string };
2061
+ }
2062
+ return null;
2063
+ };
2064
+
2065
+ for (const stmt of astChildren(node, "body")) {
2066
+ const effExpr =
2067
+ stmt.kind === "EffectBindStatement" ||
2068
+ stmt.kind === "EffectDiscardStatement"
2069
+ ? astChild(stmt, "effect")
2070
+ : null;
2071
+ if (effExpr) {
2072
+ const op = getRefOp(effExpr);
2073
+ if (op) {
2074
+ if (op.type === "get") {
2075
+ readRefs.add(op.refName);
2076
+ } else if (
2077
+ op.type === "set" &&
2078
+ readRefs.has(op.refName)
2079
+ ) {
2080
+ addAstDiag(
2081
+ stmt.span,
2082
+ "REF_RACE",
2083
+ `Insecure non-atomic Ref mutation. Consecutive 'Ref.get' and 'Ref.set' on '${op.refName}' creates a concurrency race condition. Use 'Ref.update(${op.refName}, ...)' or 'Ref.modify' for atomic updates.`,
2084
+ "error",
2085
+ "Reading a Ref and subsequently writing to it in separate effect steps allows concurrent fibers to interleave and overwrite state updates.",
2086
+ `Use 'Ref.update(${op.refName}, ...)' or 'Ref.modify' for atomic updates.`,
2087
+ );
2088
+ }
2089
+ }
2090
+ }
2091
+ }
2092
+ }
2093
+
2094
+ if (
2095
+ node.kind === "EffectBlockExpression" &&
2096
+ !astBool(node, "unscoped")
2097
+ ) {
2098
+ const finalExpr = astChild(node, "finalExpression");
2099
+ const isUnit =
2100
+ (finalExpr?.kind === "Identifier" ||
2101
+ finalExpr?.kind === "UpperIdentifier") &&
2102
+ astName(finalExpr) === "Void";
2103
+
2104
+ if (!isUnit) {
2105
+ const findFinalizer = (
2106
+ n: unknown,
2107
+ allowAcquire: boolean,
2108
+ ): { name: string; span: Span } | null => {
2109
+ if (!n || typeof n !== "object") return null;
2110
+ const objNode = n as Record<string, unknown>;
2111
+ if (n !== node && objNode.kind === "EffectBlockExpression")
2112
+ return null;
2113
+ if (objNode.kind === "CallExpression") {
2114
+ const callee = objNode.callee as
2115
+ Record<string, unknown> | undefined;
2116
+ if (callee?.kind === "MemberExpression") {
2117
+ const obj = (
2118
+ callee.object as { name?: string } | undefined
2119
+ )?.name;
2120
+ const prop = (
2121
+ callee.property as { name?: string } | undefined
2122
+ )?.name;
2123
+ if (
2124
+ (obj === "Effect" || obj === "Scope") &&
2125
+ (prop === "addFinalizer" ||
2126
+ (allowAcquire && prop === "acquireRelease"))
2127
+ ) {
2128
+ return {
2129
+ name: `${obj}.${prop}`,
2130
+ span: objNode.span as Span,
2131
+ };
2132
+ }
2133
+ } else if (callee?.kind === "Identifier") {
2134
+ const calleeName = (callee as { name?: string }).name;
2135
+ if (
2136
+ calleeName === "addFinalizer" ||
2137
+ (allowAcquire && calleeName === "acquireRelease")
2138
+ ) {
2139
+ return {
2140
+ name: calleeName,
2141
+ span: objNode.span as Span,
2142
+ };
2143
+ }
2144
+ }
2145
+ }
2146
+ for (const k of Object.keys(objNode)) {
2147
+ if (k === "span") continue;
2148
+ const val = objNode[k];
2149
+ if (Array.isArray(val)) {
2150
+ for (const item of val) {
2151
+ const res = findFinalizer(item, allowAcquire);
2152
+ if (res) return res;
2153
+ }
2154
+ } else if (val && typeof val === "object") {
2155
+ const res = findFinalizer(val, allowAcquire);
2156
+ if (res) return res;
2157
+ }
2158
+ }
2159
+ return null;
2160
+ };
2161
+
2162
+ let detectedCall: { name: string; span: Span } | null = null;
2163
+ for (const stmt of astChildren(node, "body")) {
2164
+ const returnsBinding =
2165
+ finalExpr?.kind === "Identifier" &&
2166
+ stmt.kind === "EffectBindStatement" &&
2167
+ astName(astChild(stmt, "id")) === astName(finalExpr);
2168
+ const res = findFinalizer(stmt, returnsBinding);
2169
+ if (res) {
2170
+ detectedCall = res;
2171
+ break;
2172
+ }
2173
+ }
2174
+ if (!detectedCall && finalExpr) {
2175
+ detectedCall = findFinalizer(finalExpr, false);
2176
+ }
2177
+
2178
+ // Follow simple local aliases and providers only
2179
+ // when the acquired value itself is returned from this scope.
2180
+ // Derived values (e.g. resource.fd) remain valid consumers.
2181
+ if (!detectedCall && finalExpr?.kind === "Identifier") {
2182
+ const bindings = new Map<string, AstInspectNode>();
2183
+ for (const item of meta.ast?.body ?? []) {
2184
+ const decl =
2185
+ item.kind === "ExportDeclaration"
2186
+ ? item.declaration
2187
+ : item;
2188
+ if (
2189
+ decl.kind === "BindingDeclaration" &&
2190
+ decl.id.kind === "Identifier"
2191
+ ) {
2192
+ bindings.set(decl.id.name, decl.init);
2193
+ }
2194
+ }
2195
+ // Function parameters shadow module bindings, including
2196
+ // inside nested functions. Never follow a shadowed name.
2197
+ const shadowed = new Set<string>();
2198
+ const collectEnclosingParams = (
2199
+ candidate: AstInspectNode,
2200
+ ): void => {
2201
+ if (
2202
+ !candidate.span ||
2203
+ !node.span ||
2204
+ candidate.span.start.offset > node.span.start.offset ||
2205
+ candidate.span.end.offset < node.span.end.offset
2206
+ )
2207
+ return;
2208
+ if (candidate.kind === "FunctionExpression") {
2209
+ for (const param of astChildren(candidate, "params")) {
2210
+ for (const name of collectPatternVars(
2211
+ astChild(param, "name"),
2212
+ ))
2213
+ shadowed.add(name);
2214
+ }
2215
+ }
2216
+ for (const [key, value] of Object.entries(
2217
+ asRecord(candidate),
2218
+ )) {
2219
+ if (key === "span") continue;
2220
+ if (Array.isArray(value)) {
2221
+ for (const item of value)
2222
+ if (isAstNode(item)) collectEnclosingParams(item);
2223
+ } else if (isAstNode(value))
2224
+ collectEnclosingParams(value);
2225
+ }
2226
+ };
2227
+ if (meta.ast) collectEnclosingParams(meta.ast);
2228
+ for (const name of shadowed) bindings.delete(name);
2229
+ for (const stmt of astChildren(node, "body")) {
2230
+ if (stmt.kind === "BindingDeclaration") {
2231
+ const name = astName(astChild(stmt, "id"));
2232
+ const init = astChild(stmt, "init");
2233
+ if (name && init) bindings.set(name, init);
2234
+ }
2235
+ }
2236
+ const resolveReturned = (
2237
+ name: string | undefined,
2238
+ seen: Set<string>,
2239
+ ): AstInspectNode | undefined => {
2240
+ if (!name || seen.has(name)) return undefined;
2241
+ const stmts = astChildren(node, "body");
2242
+ const bind = stmts.find(
2243
+ (stmt) =>
2244
+ stmt.kind === "EffectBindStatement" &&
2245
+ astName(astChild(stmt, "id")) === name,
2246
+ );
2247
+ if (bind) return bind;
2248
+ const alias = stmts.find(
2249
+ (stmt) =>
2250
+ stmt.kind === "BindingDeclaration" &&
2251
+ astName(astChild(stmt, "id")) === name,
2252
+ );
2253
+ const init = astChild(alias, "init");
2254
+ return init?.kind === "Identifier"
2255
+ ? resolveReturned(
2256
+ astName(init),
2257
+ new Set([...seen, name]),
2258
+ )
2259
+ : undefined;
2260
+ };
2261
+ const bind = resolveReturned(astName(finalExpr), new Set());
2262
+ const source = astChild(bind, "effect");
2263
+ const followsAcquire = (
2264
+ expr: AstInspectNode | null,
2265
+ seen: Set<string>,
2266
+ ): boolean => {
2267
+ if (!expr) return false;
2268
+ if (expr.kind === "Identifier") {
2269
+ const name = astName(expr);
2270
+ if (!name || seen.has(name)) return false;
2271
+ const next = bindings.get(name);
2272
+ if (!next) return false;
2273
+ return followsAcquire(next, new Set([...seen, name]));
2274
+ }
2275
+ if (expr.kind === "FunctionExpression") {
2276
+ const nestedSeen = new Set(seen);
2277
+ for (const param of astChildren(expr, "params")) {
2278
+ for (const name of collectPatternVars(
2279
+ astChild(param, "name"),
2280
+ ))
2281
+ nestedSeen.add(name);
2282
+ }
2283
+ return followsAcquire(
2284
+ astChild(expr, "body"),
2285
+ nestedSeen,
2286
+ );
2287
+ }
2288
+ if (expr.kind === "BlockStatement") {
2289
+ return followsAcquire(
2290
+ astChild(expr, "finalExpression"),
2291
+ seen,
2292
+ );
2293
+ }
2294
+ if (
2295
+ expr.kind === "EffectBlockExpression" &&
2296
+ astBool(expr, "unscoped")
2297
+ ) {
2298
+ const result = astChild(expr, "finalExpression");
2299
+ if (result?.kind !== "Identifier") return false;
2300
+ const bind = astChildren(expr, "body").find(
2301
+ (stmt) =>
2302
+ stmt.kind === "EffectBindStatement" &&
2303
+ astName(astChild(stmt, "id")) === astName(result),
2304
+ );
2305
+ return followsAcquire(astChild(bind, "effect"), seen);
2306
+ }
2307
+ if (expr.kind === "CallExpression") {
2308
+ const callee = astChild(expr, "callee");
2309
+ const member = getMemberNames(callee);
2310
+ if (
2311
+ (member?.object === "Effect" &&
2312
+ member.property === "acquireRelease") ||
2313
+ (callee?.kind === "Identifier" &&
2314
+ astName(callee) === "acquireRelease")
2315
+ )
2316
+ return true;
2317
+ if (callee?.kind === "Identifier") {
2318
+ return followsAcquire(callee, seen);
2319
+ }
2320
+ }
2321
+ return false;
2322
+ };
2323
+ if (source && followsAcquire(source, new Set())) {
2324
+ detectedCall = {
2325
+ name: "Effect.acquireRelease (through an alias)",
2326
+ span: source.span ?? node.span!,
2327
+ };
2328
+ }
2329
+ }
2330
+
2331
+ if (detectedCall) {
2332
+ const callInfo: { name: string; span: Span } = detectedCall;
2333
+ addAstDiag(
2334
+ callInfo.span,
2335
+ "PREMATURE_FINALIZER_CLOSE",
2336
+ `Finalizer registered with '${callInfo.name}' in a scoped effect block will execute immediately when this function returns, closing the returned resource.`,
2337
+ "error",
2338
+ "By default, 'effect' blocks create a scoped boundary ('Effect.scoped'). Any finalizer registered via 'Effect.addFinalizer' or 'Effect.acquireRelease' executes as soon as the block returns, tearing down the resource before the caller can use it.",
2339
+ "Change 'effect' to 'effect (unscoped)' so the resource's lifetime is bound to the caller's scope, or return 'Void' if all work is completed inside this block.",
2340
+ );
2341
+ }
2342
+ }
2343
+ }
2344
+
2345
+ const nodeRecord = asRecord(node);
2346
+ for (const k of Object.keys(nodeRecord)) {
2347
+ if (k === "span") continue;
2348
+ const child = nodeRecord[k];
2349
+ const nextInMatchArm =
2350
+ node.kind === "MatchArm" && k === "body"
2351
+ ? true
2352
+ : currentInMatchArm;
2353
+ if (Array.isArray(child)) {
2354
+ for (const c of child) {
2355
+ if (isAstNode(c)) {
2356
+ walkAst(c, node, currentInMut, nextInMatchArm);
2357
+ }
2358
+ }
2359
+ } else if (isAstNode(child)) {
2360
+ walkAst(child, node, currentInMut, nextInMatchArm);
2361
+ }
2362
+ }
2363
+ };
2364
+ walkAst(meta.ast);
2365
+ checkCapturedMutInEffect(meta.ast, addAstDiag);
2366
+ }
2367
+
2368
+ const reportUnhandledNullishReturn = (expr: ts.Expression) => {
2369
+ const retType = checker.getTypeAtLocation(expr);
2370
+ if (hasNullishMember(retType)) {
2371
+ addCustomDiag(
2372
+ expr,
2373
+ "UNHANDLED_NULLISH",
2374
+ `Return value has nullable/optional type '${checker.typeToString(retType)}' from JS/TS interop.`,
2375
+ "Raw 'null' and 'undefined' values cannot flow out of FunkScript returns; absence must be lifted to Option<T> at the interop edge.",
2376
+ `Wrap the returned value at the edge with 'fromNullishOr(...)' or 'fromNullishOrElse(..., fallback)' (or '<- js ...' for Promises).`,
2377
+ );
2378
+ }
2379
+ };
2380
+
2381
+ const hasExplicitTypeAnnotation = (expr: ts.Node): boolean => {
2382
+ let curr: ts.Node | undefined = expr;
2383
+ while (curr && curr.parent) {
2384
+ const p: ts.Node = curr.parent;
2385
+ if (ts.isParenthesizedExpression(p)) {
2386
+ curr = p;
2387
+ continue;
2388
+ }
2389
+ if (
2390
+ (ts.isVariableDeclaration(p) ||
2391
+ ts.isParameter(p) ||
2392
+ ts.isPropertyDeclaration(p)) &&
2393
+ p.initializer === curr &&
2394
+ Boolean(p.type)
2395
+ ) {
2396
+ return true;
2397
+ }
2398
+ if (
2399
+ ts.isAsExpression(p) ||
2400
+ ts.isTypeAssertionExpression(p) ||
2401
+ ts.isSatisfiesExpression(p)
2402
+ ) {
2403
+ return true;
2404
+ }
2405
+ break;
2406
+ }
2407
+ return false;
2408
+ };
2409
+
2410
+ const isOptionBoundaryAdapter = (expr: ts.Expression): boolean => {
2411
+ if (!ts.isCallExpression(expr)) return false;
2412
+ const text = expr.expression.getText(sf);
2413
+ return (
2414
+ text === "Option.getOrNull" || text === "Option.getOrUndefined"
2415
+ );
2416
+ };
2417
+
2418
+ const reportUnhandledNullishValue = (
2419
+ expr: ts.Node,
2420
+ type: ts.Type,
2421
+ contextDescription: string,
2422
+ ) => {
2423
+ addCustomDiag(
2424
+ expr,
2425
+ "UNHANDLED_NULLISH",
2426
+ `${contextDescription} has nullable/optional type '${checker.typeToString(type)}' from JS/TS interop.`,
2427
+ "Raw 'null' and 'undefined' values cannot flow through FunkScript values; absence must be lifted to Option<T> at the interop edge.",
2428
+ `Wrap the value at the edge with 'fromNullishOr(...)' or 'fromNullishOrElse(..., fallback)' (or '<- js ...' for Promises).`,
2429
+ );
2430
+ };
2431
+
2432
+ const checkBindingTarget = (
2433
+ bindingName: ts.BindingName,
2434
+ hasInitializer: boolean,
2435
+ ): void => {
2436
+ if (ts.isIdentifier(bindingName)) {
2437
+ if (unannotatedBindings.has(bindingName.text)) {
2438
+ const type = checker.getTypeAtLocation(bindingName);
2439
+ if (type.flags & ts.TypeFlags.Any) {
2440
+ addCustomDiag(
2441
+ bindingName,
2442
+ "ANY_BINDING",
2443
+ `Cannot infer untyped 'any' for binding '${bindingName.text}'. Values from untyped foreign JavaScript or TypeScript must be explicitly typed as 'Unknown' (e.g. '${bindingName.text}: Unknown = ...') or validated with a schema.`,
2444
+ );
2445
+ } else if (hasInitializer && hasNullishMember(type)) {
2446
+ addCustomDiag(
2447
+ bindingName,
2448
+ "UNHANDLED_NULLISH",
2449
+ `Binding '${bindingName.text}' has nullable/optional type '${checker.typeToString(type)}' from JS/TS interop.`,
2450
+ "Raw 'null' and 'undefined' values cannot flow into FunkScript bindings; absence must be lifted to Option<T> at the interop edge.",
2451
+ `Wrap the value at the edge with 'fromNullishOr(...)' or 'fromNullishOrElse(..., fallback)' (or '<- js ...' for Promises).`,
2452
+ );
2453
+ }
2454
+ }
2455
+ return;
2456
+ }
2457
+ if (
2458
+ ts.isObjectBindingPattern(bindingName) ||
2459
+ ts.isArrayBindingPattern(bindingName)
2460
+ ) {
2461
+ for (const elem of bindingName.elements) {
2462
+ if (ts.isBindingElement(elem)) {
2463
+ checkBindingTarget(elem.name, hasInitializer);
2464
+ }
2465
+ }
2466
+ }
2467
+ };
2468
+
2469
+ const visit = (node: ts.Node): void => {
2470
+ if (
2471
+ ts.isFunctionDeclaration(node) &&
2472
+ (node.name?.text === "__funscriptJs" ||
2473
+ node.name?.text === "fromNullishOrElse" ||
2474
+ node.name?.text === "fromNullishOr" ||
2475
+ node.name?.text === "optionTry")
2476
+ )
2477
+ return;
2478
+ if (
2479
+ ts.isClassDeclaration(node) &&
2480
+ node.name?.text === "JsInteropError"
2481
+ )
2482
+ return;
2483
+ if (ts.isCallExpression(node) && node.arguments.length >= 1) {
2484
+ const calleeText = node.expression.getText(sf);
2485
+ if (
2486
+ calleeText === "fromNullishOr" ||
2487
+ calleeText === "fromNullishOrElse" ||
2488
+ calleeText === "Option.fromNullable" ||
2489
+ calleeText === "Option.fromNullishOr" ||
2490
+ calleeText === "Option.fromUndefinedOr"
2491
+ ) {
2492
+ const argType = checker.getTypeAtLocation(node.arguments[0]);
2493
+ const isOptionValue = isOptionType(argType);
2494
+ const argTypeStr = checker.typeToString(argType);
2495
+ if (
2496
+ isOptionValue ||
2497
+ ((!argType.isUnion() || !argType.types.some(isNullishFlag)) &&
2498
+ (/^Option</.test(argTypeStr) ||
2499
+ /^Option\.Option</.test(argTypeStr)))
2500
+ ) {
2501
+ addCustomDiag(
2502
+ node,
2503
+ "REDUNDANT_OPTION_WRAP",
2504
+ `Value is already an '${argTypeStr}'; calling '${calleeText}' again double-wraps it into 'Option<Option<...>>'.`,
2505
+ "Wrapping an existing Option with fromNullishOr/fromNullishOrElse/Option.fromNullable/Option.fromUndefinedOr creates Option<Option<T>>, which breaks downstream Option.getOrElse and pattern matching.",
2506
+ "Use the Option value directly without calling the Option wrapper again.",
2507
+ );
2508
+ }
2509
+ } else if (
2510
+ (calleeText === "Option.some" ||
2511
+ calleeText === "Effect.succeed") &&
2512
+ !isNodeInTsEscape(node) &&
2513
+ !hasExplicitTypeAnnotation(node) &&
2514
+ !node.typeArguments?.length
2515
+ ) {
2516
+ const argType = checker.getTypeAtLocation(node.arguments[0]);
2517
+ if (hasNullishMember(argType)) {
2518
+ reportUnhandledNullishValue(
2519
+ node.arguments[0],
2520
+ argType,
2521
+ `Argument to '${calleeText}'`,
2522
+ );
2523
+ }
2524
+ }
2525
+ }
2526
+ if (
2527
+ ts.isObjectLiteralExpression(node) &&
2528
+ !isNodeInTsEscape(node) &&
2529
+ !hasExplicitTypeAnnotation(node)
2530
+ ) {
2531
+ for (const prop of node.properties) {
2532
+ if (
2533
+ ts.isPropertyAssignment(prop) &&
2534
+ !isOptionBoundaryAdapter(prop.initializer)
2535
+ ) {
2536
+ const valType = checker.getTypeAtLocation(prop.initializer);
2537
+ if (hasNullishMember(valType)) {
2538
+ reportUnhandledNullishValue(
2539
+ prop.initializer,
2540
+ valType,
2541
+ "Object property value",
2542
+ );
2543
+ }
2544
+ } else if (ts.isShorthandPropertyAssignment(prop)) {
2545
+ const valType = checker.getTypeAtLocation(prop.name);
2546
+ if (hasNullishMember(valType)) {
2547
+ reportUnhandledNullishValue(
2548
+ prop.name,
2549
+ valType,
2550
+ `Object property '${prop.name.text}'`,
2551
+ );
2552
+ }
2553
+ }
2554
+ }
2555
+ } else if (
2556
+ ts.isArrayLiteralExpression(node) &&
2557
+ !isNodeInTsEscape(node) &&
2558
+ !hasExplicitTypeAnnotation(node)
2559
+ ) {
2560
+ for (const elem of node.elements) {
2561
+ if (!ts.isSpreadElement(elem)) {
2562
+ const elemType = checker.getTypeAtLocation(elem);
2563
+ if (hasNullishMember(elemType)) {
2564
+ reportUnhandledNullishValue(
2565
+ elem,
2566
+ elemType,
2567
+ "Array element",
2568
+ );
2569
+ }
2570
+ }
2571
+ }
2572
+ }
2573
+ if (ts.isReturnStatement(node) && node.expression) {
2574
+ let enc: ts.Node | undefined = node.parent;
2575
+ while (
2576
+ enc &&
2577
+ !ts.isFunctionExpression(enc) &&
2578
+ !ts.isArrowFunction(enc) &&
2579
+ !ts.isFunctionDeclaration(enc) &&
2580
+ !ts.isMethodDeclaration(enc) &&
2581
+ !ts.isGetAccessorDeclaration(enc)
2582
+ ) {
2583
+ enc = enc.parent;
2584
+ }
2585
+ if (enc && ts.isFunctionExpression(enc) && enc.asteriskToken) {
2586
+ const parentCall = enc.parent;
2587
+ if (parentCall && ts.isCallExpression(parentCall)) {
2588
+ const calleeText = parentCall.expression.getText(sf);
2589
+ if (
2590
+ calleeText === "Effect.gen" ||
2591
+ calleeText.endsWith(".gen")
2592
+ ) {
2593
+ const retType = checker.getTypeAtLocation(node.expression);
2594
+ if (isEffectType(retType)) {
2595
+ addCustomDiag(
2596
+ node.expression,
2597
+ "NESTED_EFFECT",
2598
+ "Returning an Effect from inside an 'effect' block creates a nested 'Effect<Effect<...>>' that will not be executed. Use '<-' to bind and execute the effect (e.g. 'result <- <effect>; => result').",
2599
+ "An 'effect' block automatically wraps its final value in an Effect. Returning an Effect without binding it means the inner effect is returned as unexecuted data.",
2600
+ "Bind the effect with `<-` before returning it, or return a non-Effect value.",
2601
+ );
2602
+ }
2603
+ }
2604
+ }
2605
+ }
2606
+ const hasExplicitReturnType =
2607
+ Boolean(enc?.type) ||
2608
+ Boolean(
2609
+ enc &&
2610
+ ts.isFunctionExpression(enc) &&
2611
+ enc.asteriskToken &&
2612
+ enc.parent &&
2613
+ ts.isCallExpression(enc.parent) &&
2614
+ enc.parent.parent &&
2615
+ (ts.isArrowFunction(enc.parent.parent) ||
2616
+ ts.isFunctionExpression(enc.parent.parent) ||
2617
+ ts.isFunctionDeclaration(enc.parent.parent) ||
2618
+ ts.isMethodDeclaration(enc.parent.parent) ||
2619
+ ts.isGetAccessorDeclaration(enc.parent.parent)) &&
2620
+ enc.parent.parent.type,
2621
+ );
2622
+ if (enc && !hasExplicitReturnType && !isNodeInTsEscape(node)) {
2623
+ reportUnhandledNullishReturn(node.expression);
2624
+ }
2625
+ } else if (
2626
+ ts.isArrowFunction(node) &&
2627
+ !ts.isBlock(node.body) &&
2628
+ !node.type &&
2629
+ !(
2630
+ node.parent &&
2631
+ ts.isCallExpression(node.parent) &&
2632
+ ts.isIdentifier(node.parent.expression) &&
2633
+ node.parent.expression.text === "__funscriptJs"
2634
+ ) &&
2635
+ !isNodeInTsEscape(node.body)
2636
+ ) {
2637
+ reportUnhandledNullishReturn(node.body);
2638
+ } else if (
2639
+ ts.isYieldExpression(node) &&
2640
+ node.asteriskToken &&
2641
+ node.expression
2642
+ ) {
2643
+ const isJsInterop =
2644
+ ts.isCallExpression(node.expression) &&
2645
+ ts.isIdentifier(node.expression.expression) &&
2646
+ node.expression.expression.text === "__funscriptJs";
2647
+
2648
+ if (!isJsInterop) {
2649
+ const type = checker.getTypeAtLocation(node.expression);
2650
+ const isAny = Boolean(type.flags & ts.TypeFlags.Any);
2651
+ if (isAny) {
2652
+ addCustomDiag(
2653
+ node.expression,
2654
+ "ANY_BIND",
2655
+ "Cannot bind untyped 'any' expression in effect block. External asynchronous calls must be explicitly lifted using the 'js' operator (e.g. '<- js <expr>') or validated with a schema.",
2656
+ );
2657
+ }
2658
+ }
2659
+ } else if (ts.isVariableDeclaration(node) && !node.type) {
2660
+ checkBindingTarget(node.name, Boolean(node.initializer));
2661
+ } else if (ts.isPropertyAccessExpression(node)) {
2662
+ if (memberAccesses.has(node.name.text)) {
2663
+ const targetType = checker.getTypeAtLocation(node.expression);
2664
+ if (targetType.flags & ts.TypeFlags.Any) {
2665
+ if (
2666
+ !ts.isPropertyAccessExpression(node.expression) &&
2667
+ !ts.isElementAccessExpression(node.expression)
2668
+ ) {
2669
+ addCustomDiag(
2670
+ node.name,
2671
+ "ANY_ACCESS",
2672
+ `Cannot access property '${node.name.text}' on untyped 'any' value. External values must be typed as 'Unknown' and validated with a schema before accessing properties.`,
2673
+ );
2674
+ }
2675
+ }
2676
+ }
2677
+ } else if (ts.isElementAccessExpression(node)) {
2678
+ const targetType = checker.getTypeAtLocation(node.expression);
2679
+ if (targetType.flags & ts.TypeFlags.Any) {
2680
+ if (
2681
+ !ts.isPropertyAccessExpression(node.expression) &&
2682
+ !ts.isElementAccessExpression(node.expression)
2683
+ ) {
2684
+ addCustomDiag(
2685
+ node.argumentExpression,
2686
+ "ANY_ACCESS",
2687
+ "Cannot access index on untyped 'any' value. External values must be typed as 'Unknown' and validated with a schema.",
2688
+ );
2689
+ }
2690
+ }
2691
+ } else if (ts.isCallExpression(node)) {
2692
+ const calleeType = checker.getTypeAtLocation(node.expression);
2693
+ if (calleeType.flags & ts.TypeFlags.Any) {
2694
+ if (
2695
+ !ts.isPropertyAccessExpression(node.expression) &&
2696
+ !ts.isElementAccessExpression(node.expression)
2697
+ ) {
2698
+ addCustomDiag(
2699
+ node.expression,
2700
+ "ANY_CALL",
2701
+ "Cannot call untyped 'any' value as a function. External functions must have typed signatures or be adapted with an explicit signature.",
2702
+ );
2703
+ }
2704
+ }
2705
+ }
2706
+ ts.forEachChild(node, visit);
2707
+ };
2708
+ visit(sf);
2709
+ }
2710
+ }
2711
+
2712
+ const errorCount = tsDiagnostics.filter(
2713
+ (d) => d.category === "error",
2714
+ ).length;
2715
+ const warningCount = tsDiagnostics.filter(
2716
+ (d) => d.category === "warning",
2717
+ ).length;
2718
+ const success = errorCount === 0;
2719
+ const formattedOutput = formatDiagnostics(tsDiagnostics);
2720
+
2721
+ return {
2722
+ success,
2723
+ diagnostics: tsDiagnostics,
2724
+ errorCount,
2725
+ warningCount,
2726
+ formattedOutput,
2727
+ };
2728
+ },
2729
+ catch: (error: unknown) =>
2730
+ new Error(`Type-checking failed: ${toErrorMessage(error)}`),
2731
+ });
2732
+
2733
+ export const typeCheckSource = (
2734
+ source: string,
2735
+ filename: string = "source.fun",
2736
+ options?: CheckOptions,
2737
+ ): Effect.Effect<TypeCheckResult, Error> =>
2738
+ typeCheckVirtualFiles({ [filename]: source }, options);
2739
+
2740
+ export const typeCheckFiles = (
2741
+ filePaths: string[],
2742
+ options?: CheckOptions,
2743
+ ): Effect.Effect<TypeCheckResult, Error> =>
2744
+ Effect.gen(function* () {
2745
+ const cwd = options?.cwd ? path.resolve(options.cwd) : process.cwd();
2746
+ const virtualFiles: Record<string, string> = {};
2747
+
2748
+ for (const filePath of filePaths) {
2749
+ const fullPath = path.isAbsolute(filePath)
2750
+ ? filePath
2751
+ : path.resolve(cwd, filePath);
2752
+ const content = yield* Effect.tryPromise({
2753
+ try: () => fs.readFile(fullPath, "utf-8"),
2754
+ catch: (err: unknown) =>
2755
+ new Error(
2756
+ `Failed to read file '${filePath}': ${toErrorMessage(err)}`,
2757
+ ),
2758
+ });
2759
+ virtualFiles[filePath] = content;
2760
+ }
2761
+
2762
+ return yield* typeCheckVirtualFiles(virtualFiles, options);
2763
+ });