create-threenative 0.2.2 → 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 (588) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +61 -2
  3. package/agent-docs/references/assertion-reference.md +819 -0
  4. package/agent-docs/references/capability-reference.md +4483 -0
  5. package/agent-docs/references/capture-the-frame.md +60 -0
  6. package/agent-docs/references/creating-creatures.md +215 -0
  7. package/agent-docs/references/ctx-cookbook.md +120 -0
  8. package/agent-docs/references/debug-surface.md +68 -0
  9. package/agent-docs/references/dream-loop.md +150 -0
  10. package/agent-docs/references/finding-assets.md +215 -0
  11. package/agent-docs/references/gameplay-recipes.md +54 -0
  12. package/agent-docs/references/menu-screens.md +69 -0
  13. package/agent-docs/references/mobile-memory-budget.md +87 -0
  14. package/agent-docs/references/sculpt-from-a-reference.md +40 -0
  15. package/agent-docs/references/trace-a-slow-frame.md +99 -0
  16. package/agent-docs/references/visual-baseline.md +174 -0
  17. package/agent-docs/references/webview-ui.md +113 -0
  18. package/agent-files/.agents/skills/file-engine-bug/SKILL.md +59 -0
  19. package/agent-files/.agents/skills/prd-creator/SKILL.md +40 -0
  20. package/agent-files/.agents/skills/threenative-assets/SKILL.md +45 -0
  21. package/agent-files/.agents/skills/threenative-builder/SKILL.md +7 -0
  22. package/agent-files/.agents/skills/threenative-capabilities/SKILL.md +27 -0
  23. package/agent-files/.agents/skills/threenative-context/SKILL.md +57 -0
  24. package/agent-files/.agents/skills/threenative-performance/SKILL.md +42 -0
  25. package/agent-files/.agents/skills/threenative-playtest/SKILL.md +44 -0
  26. package/agent-files/.agents/skills/threenative-ui/SKILL.md +20 -0
  27. package/agent-files/.agents/skills/threenative-verifier/SKILL.md +7 -0
  28. package/agent-files/.agents/skills/threenative-visuals/SKILL.md +41 -0
  29. package/agent-files/.claude/agents/threenative-builder.md +7 -0
  30. package/agent-files/.claude/agents/threenative-verifier.md +7 -0
  31. package/agent-files/.claude/skills/file-engine-bug/SKILL.md +59 -0
  32. package/agent-files/.claude/skills/prd-creator/SKILL.md +40 -0
  33. package/agent-files/.claude/skills/threenative-assets/SKILL.md +45 -0
  34. package/agent-files/.claude/skills/threenative-capabilities/SKILL.md +27 -0
  35. package/agent-files/.claude/skills/threenative-context/SKILL.md +57 -0
  36. package/agent-files/.claude/skills/threenative-performance/SKILL.md +42 -0
  37. package/agent-files/.claude/skills/threenative-playtest/SKILL.md +44 -0
  38. package/agent-files/.claude/skills/threenative-ui/SKILL.md +20 -0
  39. package/agent-files/.claude/skills/threenative-visuals/SKILL.md +41 -0
  40. package/agent-files/.threenative/agents/builder.md +32 -0
  41. package/agent-files/.threenative/agents/verifier.md +31 -0
  42. package/agent-files/AGENT-ROLES.md +26 -0
  43. package/agent-files/scripts/reference.mjs +705 -0
  44. package/agent-files/scripts/visual-loop.mjs +382 -0
  45. package/capabilities.json +5292 -0
  46. package/dist/index.d.ts +224 -3
  47. package/dist/index.js +1972 -73
  48. package/dist/threenative.d.ts +9 -2
  49. package/dist/threenative.js +2570 -176
  50. package/package.json +55 -6
  51. package/template-assets/icon.png +0 -0
  52. package/template-assets/loading.ts +325 -0
  53. package/template-assets/patches/three@0.185.1.patch +522 -0
  54. package/template-assets/worldEnvironment.ts +758 -0
  55. package/templates/action-rpg/.codex/config.toml +19 -0
  56. package/templates/action-rpg/.cursor/mcp.json +32 -0
  57. package/templates/action-rpg/.gemini/settings.json +32 -0
  58. package/templates/action-rpg/.mcp.json +18 -2
  59. package/templates/action-rpg/.vscode/mcp.json +36 -0
  60. package/templates/action-rpg/.zed/settings.json +36 -0
  61. package/templates/action-rpg/AGENTS.md +84 -29
  62. package/templates/action-rpg/CLAUDE.md +84 -29
  63. package/templates/action-rpg/index.html +0 -1
  64. package/templates/action-rpg/opencode.json +41 -0
  65. package/templates/action-rpg/package.json +15 -11
  66. package/templates/action-rpg/playtests/combat.playtest.json +32 -9
  67. package/templates/action-rpg/playtests/fail.playtest.json +3 -3
  68. package/templates/action-rpg/playtests/inventory.playtest.json +16 -10
  69. package/templates/action-rpg/playtests/performance.playtest.json +39 -0
  70. package/templates/action-rpg/playtests/progress.playtest.json +18 -13
  71. package/templates/action-rpg/playtests/survives.playtest.json +27 -0
  72. package/templates/action-rpg/playtests/touch-controls.playtest.json +42 -0
  73. package/templates/action-rpg/playtests/win.playtest.json +10 -4
  74. package/templates/action-rpg/src/conventions.ts +35 -0
  75. package/templates/action-rpg/src/entities/Enemy.ts +16 -7
  76. package/templates/action-rpg/src/entities/Player.ts +20 -3
  77. package/templates/action-rpg/src/game.ts +21 -0
  78. package/templates/action-rpg/src/render/camera.ts +7 -2
  79. package/templates/action-rpg/src/render/lighting.ts +11 -4
  80. package/templates/action-rpg/src/render/loading.ts +278 -43
  81. package/templates/action-rpg/src/render/materials.ts +11 -0
  82. package/templates/action-rpg/src/render/palette.ts +10 -3
  83. package/templates/action-rpg/src/render/postprocessing.ts +32 -16
  84. package/templates/action-rpg/src/render/quality.ts +170 -0
  85. package/templates/action-rpg/src/render/shapes.ts +185 -26
  86. package/templates/action-rpg/src/render/touch-controls.ts +185 -0
  87. package/templates/action-rpg/src/render/vfx.ts +257 -0
  88. package/templates/action-rpg/src/render/worldEnvironment.ts +758 -0
  89. package/templates/action-rpg/src/scenes/Play.ts +91 -24
  90. package/templates/action-rpg/src/state.ts +4 -0
  91. package/templates/action-rpg/src/style.css +65 -1
  92. package/templates/action-rpg/src/ui/AbilityBar.tsx +9 -7
  93. package/templates/action-rpg/src/ui/App.tsx +9 -8
  94. package/templates/action-rpg/src/ui/CharacterPanel.tsx +10 -8
  95. package/templates/action-rpg/src/ui/GameUi.tsx +24 -0
  96. package/templates/action-rpg/src/ui/Hud.tsx +10 -8
  97. package/templates/action-rpg/src/ui/InventoryPanel.tsx +9 -7
  98. package/templates/action-rpg/src/ui/main.tsx +14 -0
  99. package/templates/action-rpg/threenative.config.ts +28 -8
  100. package/templates/action-rpg/vite.config.ts +32 -2
  101. package/templates/defense/.codex/config.toml +19 -0
  102. package/templates/defense/.cursor/mcp.json +32 -0
  103. package/templates/defense/.gemini/settings.json +32 -0
  104. package/templates/defense/.mcp.json +18 -2
  105. package/templates/defense/.vscode/mcp.json +36 -0
  106. package/templates/defense/.zed/settings.json +36 -0
  107. package/templates/defense/AGENTS.md +81 -41
  108. package/templates/defense/CLAUDE.md +81 -41
  109. package/templates/defense/README.md +2 -1
  110. package/templates/defense/index.html +0 -1
  111. package/templates/defense/opencode.json +41 -0
  112. package/templates/defense/package.json +16 -12
  113. package/templates/defense/playtests/leak.playtest.json +9 -4
  114. package/templates/defense/playtests/performance.playtest.json +39 -0
  115. package/templates/defense/playtests/placement.playtest.json +5 -5
  116. package/templates/defense/playtests/pointer-placement.playtest.json +156 -0
  117. package/templates/defense/playtests/scan.playtest.json +4 -4
  118. package/templates/defense/playtests/survive.playtest.json +25 -6
  119. package/templates/defense/src/attackers/Attacker.ts +32 -16
  120. package/templates/defense/src/board/Route.ts +22 -8
  121. package/templates/defense/src/conventions.ts +18 -0
  122. package/templates/defense/src/entities/Player.ts +11 -3
  123. package/templates/defense/src/game.ts +25 -4
  124. package/templates/defense/src/physics.ts +9 -39
  125. package/templates/defense/src/placement/Buildable.ts +4 -4
  126. package/templates/defense/src/render/camera.ts +9 -3
  127. package/templates/defense/src/render/lighting.ts +6 -1
  128. package/templates/defense/src/render/loading.ts +274 -38
  129. package/templates/defense/src/render/materials.ts +9 -0
  130. package/templates/defense/src/render/palette.ts +12 -5
  131. package/templates/defense/src/render/postprocessing.ts +32 -12
  132. package/templates/defense/src/render/quality.ts +170 -0
  133. package/templates/defense/src/render/shapes.ts +180 -23
  134. package/templates/defense/src/render/sky.ts +2 -2
  135. package/templates/defense/src/render/worldEnvironment.ts +758 -0
  136. package/templates/defense/src/scenes/Boot.ts +2 -2
  137. package/templates/defense/src/scenes/Defense.ts +122 -56
  138. package/templates/defense/src/state.ts +6 -0
  139. package/templates/defense/src/style.css +65 -1
  140. package/templates/defense/src/towers/Tower.ts +11 -12
  141. package/templates/defense/src/towers/targeting.ts +1 -1
  142. package/templates/defense/src/ui/App.tsx +11 -6
  143. package/templates/defense/src/ui/GameUi.tsx +20 -0
  144. package/templates/defense/src/ui/Hud.tsx +6 -5
  145. package/templates/defense/src/ui/main.tsx +14 -0
  146. package/templates/defense/threenative.config.ts +28 -8
  147. package/templates/defense/vite.config.ts +34 -1
  148. package/templates/minimal/.codex/config.toml +19 -0
  149. package/templates/minimal/.cursor/mcp.json +32 -0
  150. package/templates/minimal/.gemini/settings.json +32 -0
  151. package/templates/minimal/.mcp.json +18 -2
  152. package/templates/minimal/.vscode/mcp.json +36 -0
  153. package/templates/minimal/.zed/settings.json +36 -0
  154. package/templates/minimal/AGENTS.md +78 -382
  155. package/templates/minimal/CLAUDE.md +78 -382
  156. package/templates/minimal/index.html +0 -1
  157. package/templates/minimal/opencode.json +41 -0
  158. package/templates/minimal/package.json +14 -11
  159. package/templates/minimal/playtests/atmosphere.playtest.json +32 -0
  160. package/templates/minimal/playtests/play.playtest.json +18 -5
  161. package/templates/minimal/playtests/survives.playtest.json +48 -4
  162. package/templates/minimal/playtests/touch-controls.playtest.json +42 -0
  163. package/templates/minimal/src/conventions.ts +18 -0
  164. package/templates/minimal/src/entities/Player.ts +39 -6
  165. package/templates/minimal/src/game.ts +1 -0
  166. package/templates/minimal/src/main.ts +14 -4
  167. package/templates/minimal/src/render/camera.ts +1 -1
  168. package/templates/minimal/src/render/hud.ts +24 -8
  169. package/templates/minimal/src/render/lighting.ts +23 -2
  170. package/templates/minimal/src/render/loading.ts +23 -103
  171. package/templates/minimal/src/render/materials.ts +7 -0
  172. package/templates/minimal/src/render/palette.ts +3 -3
  173. package/templates/minimal/src/render/postprocessing.ts +55 -16
  174. package/templates/minimal/src/render/quality.ts +162 -0
  175. package/templates/minimal/src/render/sky.ts +51 -32
  176. package/templates/minimal/src/render/touch-controls.ts +165 -0
  177. package/templates/minimal/src/render/worldEnvironment.ts +758 -0
  178. package/templates/minimal/src/scenes/Play.ts +128 -14
  179. package/templates/minimal/src/state.ts +8 -1
  180. package/templates/minimal/src/style.css +20 -0
  181. package/templates/minimal/threenative.config.ts +22 -10
  182. package/templates/minimal/vite.config.ts +28 -1
  183. package/templates/platformer/.codex/config.toml +19 -0
  184. package/templates/platformer/.cursor/mcp.json +32 -0
  185. package/templates/platformer/.gemini/settings.json +32 -0
  186. package/templates/platformer/.mcp.json +18 -2
  187. package/templates/platformer/.vscode/mcp.json +36 -0
  188. package/templates/platformer/.zed/settings.json +36 -0
  189. package/templates/platformer/AGENTS.md +81 -186
  190. package/templates/platformer/CLAUDE.md +81 -186
  191. package/templates/platformer/index.html +0 -1
  192. package/templates/platformer/opencode.json +41 -0
  193. package/templates/platformer/package.json +17 -14
  194. package/templates/platformer/playtests/avoidance.playtest.json +6 -1
  195. package/templates/platformer/playtests/branding.playtest.json +29 -0
  196. package/templates/platformer/playtests/buffer.playtest.json +1 -1
  197. package/templates/platformer/playtests/collect.playtest.json +1 -1
  198. package/templates/platformer/playtests/collision-layers.playtest.json +2 -2
  199. package/templates/platformer/playtests/coyote.playtest.json +42 -8
  200. package/templates/platformer/playtests/damage.playtest.json +4 -1
  201. package/templates/platformer/playtests/dash.playtest.json +2 -2
  202. package/templates/platformer/playtests/jump.playtest.json +2 -3
  203. package/templates/platformer/playtests/native/touch-controls.playtest.json +33 -0
  204. package/templates/platformer/playtests/oneway.playtest.json +30 -3
  205. package/templates/platformer/playtests/performance.playtest.json +7 -5
  206. package/templates/platformer/playtests/respawn.playtest.json +2 -2
  207. package/templates/platformer/playtests/stomp-rise.playtest.json +17 -3
  208. package/templates/platformer/playtests/stomp.playtest.json +11 -3
  209. package/templates/platformer/playtests/survives.playtest.json +31 -0
  210. package/templates/platformer/playtests/terminal-loop-fail.playtest.json +16 -4
  211. package/templates/platformer/playtests/terminal-loop-win.playtest.json +3 -3
  212. package/templates/platformer/playtests/touch-controls-web.playtest.json +57 -0
  213. package/templates/platformer/src/conventions.ts +18 -0
  214. package/templates/platformer/src/entities/Character.ts +79 -11
  215. package/templates/platformer/src/entities/Patrol.ts +5 -0
  216. package/templates/platformer/src/game.ts +27 -2
  217. package/templates/platformer/src/level/Platform.ts +13 -1
  218. package/templates/platformer/src/render/lighting.ts +13 -5
  219. package/templates/platformer/src/render/loading.ts +281 -62
  220. package/templates/platformer/src/render/palette.ts +4 -1
  221. package/templates/platformer/src/render/postprocessing.ts +42 -14
  222. package/templates/platformer/src/render/quality.ts +170 -0
  223. package/templates/platformer/src/render/touch-controls.ts +54 -36
  224. package/templates/platformer/src/render/worldEnvironment.ts +758 -0
  225. package/templates/platformer/src/scenes/Level.ts +97 -32
  226. package/templates/platformer/src/state.ts +4 -0
  227. package/templates/platformer/src/style.css +65 -1
  228. package/templates/platformer/src/ui/App.tsx +9 -4
  229. package/templates/platformer/src/ui/GameUi.tsx +20 -0
  230. package/templates/platformer/src/ui/Hud.tsx +6 -5
  231. package/templates/platformer/src/ui/main.tsx +14 -0
  232. package/templates/platformer/threenative.config.ts +27 -10
  233. package/templates/platformer/vite.config.ts +34 -1
  234. package/templates/puzzle/.codex/config.toml +19 -0
  235. package/templates/puzzle/.cursor/mcp.json +32 -0
  236. package/templates/puzzle/.gemini/settings.json +32 -0
  237. package/templates/puzzle/.mcp.json +32 -0
  238. package/templates/puzzle/.vscode/mcp.json +36 -0
  239. package/templates/puzzle/.zed/settings.json +36 -0
  240. package/templates/puzzle/AGENTS.md +96 -0
  241. package/templates/puzzle/CLAUDE.md +98 -0
  242. package/templates/puzzle/README.md +43 -0
  243. package/templates/puzzle/index.html +12 -0
  244. package/templates/puzzle/kit.json +7 -0
  245. package/templates/puzzle/opencode.json +41 -0
  246. package/templates/puzzle/package.json +50 -0
  247. package/templates/puzzle/playtests/carry.playtest.json +71 -0
  248. package/templates/puzzle/playtests/performance.playtest.json +23 -0
  249. package/templates/puzzle/playtests/survives.playtest.json +51 -0
  250. package/templates/puzzle/playtests/swing.playtest.json +38 -0
  251. package/templates/puzzle/public/favicon.svg +5 -0
  252. package/templates/puzzle/src/conventions.ts +25 -0
  253. package/templates/puzzle/src/entities/Ball.ts +70 -0
  254. package/templates/puzzle/src/entities/Crate.ts +76 -0
  255. package/templates/puzzle/src/entities/Gripper.ts +69 -0
  256. package/templates/puzzle/src/entities/Pendulum.ts +89 -0
  257. package/templates/puzzle/src/game.ts +48 -0
  258. package/templates/puzzle/src/main.ts +15 -0
  259. package/templates/puzzle/src/physics.ts +19 -0
  260. package/templates/puzzle/src/render/camera.ts +37 -0
  261. package/templates/puzzle/src/render/lighting.ts +55 -0
  262. package/templates/puzzle/src/render/loading.ts +325 -0
  263. package/templates/puzzle/src/render/materials.ts +28 -0
  264. package/templates/puzzle/src/render/palette.ts +31 -0
  265. package/templates/puzzle/src/render/postprocessing.ts +34 -0
  266. package/templates/puzzle/src/render/quality.ts +170 -0
  267. package/templates/puzzle/src/render/shapes.ts +134 -0
  268. package/templates/puzzle/src/render/sky.ts +16 -0
  269. package/templates/puzzle/src/render/touch-controls.ts +185 -0
  270. package/templates/puzzle/src/render/worldEnvironment.ts +758 -0
  271. package/templates/puzzle/src/room.ts +83 -0
  272. package/templates/puzzle/src/scenes/Boot.ts +12 -0
  273. package/templates/puzzle/src/scenes/Puzzle.ts +158 -0
  274. package/templates/puzzle/src/state.ts +30 -0
  275. package/templates/puzzle/src/style.css +96 -0
  276. package/templates/puzzle/src/ui/App.tsx +22 -0
  277. package/templates/puzzle/src/ui/GameUi.tsx +20 -0
  278. package/templates/puzzle/src/ui/Hud.tsx +57 -0
  279. package/templates/puzzle/src/ui/Menu.tsx +7 -0
  280. package/templates/puzzle/src/ui/main.tsx +14 -0
  281. package/templates/puzzle/tailwind.config.ts +1 -0
  282. package/templates/puzzle/threenative.config.ts +49 -0
  283. package/templates/puzzle/tsconfig.json +17 -0
  284. package/templates/puzzle/vite.config.ts +38 -0
  285. package/templates/racing/.codex/config.toml +19 -0
  286. package/templates/racing/.cursor/mcp.json +32 -0
  287. package/templates/racing/.gemini/settings.json +32 -0
  288. package/templates/racing/.mcp.json +18 -2
  289. package/templates/racing/.vscode/mcp.json +36 -0
  290. package/templates/racing/.zed/settings.json +36 -0
  291. package/templates/racing/AGENTS.md +84 -36
  292. package/templates/racing/CLAUDE.md +84 -36
  293. package/templates/racing/index.html +0 -1
  294. package/templates/racing/native-playtests/survives.playtest.json +43 -0
  295. package/templates/racing/opencode.json +41 -0
  296. package/templates/racing/package.json +17 -12
  297. package/templates/racing/playtests/boost.playtest.json +5 -5
  298. package/templates/racing/playtests/outcome.playtest.json +14 -4
  299. package/templates/racing/playtests/performance.playtest.json +39 -0
  300. package/templates/racing/playtests/ranking.playtest.json +2 -2
  301. package/templates/racing/playtests/rescue.playtest.json +12 -6
  302. package/templates/racing/playtests/reverse.playtest.json +3 -3
  303. package/templates/racing/playtests/shortcut.playtest.json +3 -3
  304. package/templates/racing/playtests/survives.playtest.json +36 -4
  305. package/templates/racing/playtests/touch-controls.playtest.json +41 -0
  306. package/templates/racing/src/conventions.ts +6 -0
  307. package/templates/racing/src/entities/RacingCar.ts +16 -4
  308. package/templates/racing/src/entities/Rival.ts +5 -2
  309. package/templates/racing/src/game.ts +24 -1
  310. package/templates/racing/src/render/camera.ts +15 -8
  311. package/templates/racing/src/render/lighting.ts +28 -14
  312. package/templates/racing/src/render/loading.ts +302 -35
  313. package/templates/racing/src/render/materials.ts +54 -4
  314. package/templates/racing/src/render/palette.ts +23 -6
  315. package/templates/racing/src/render/postprocessing.ts +32 -12
  316. package/templates/racing/src/render/quality.ts +170 -0
  317. package/templates/racing/src/render/shapes.ts +537 -26
  318. package/templates/racing/src/render/sky.ts +5 -2
  319. package/templates/racing/src/render/touch-controls.ts +185 -0
  320. package/templates/racing/src/render/worldEnvironment.ts +758 -0
  321. package/templates/racing/src/scenes/Race.ts +84 -37
  322. package/templates/racing/src/state.ts +4 -0
  323. package/templates/racing/src/style.css +65 -1
  324. package/templates/racing/src/track/Lap.ts +20 -9
  325. package/templates/racing/src/track/Ranking.ts +53 -14
  326. package/templates/racing/src/track/Track.ts +284 -32
  327. package/templates/racing/src/track/TrackSector.ts +14 -4
  328. package/templates/racing/src/ui/App.tsx +9 -4
  329. package/templates/racing/src/ui/GameUi.tsx +20 -0
  330. package/templates/racing/src/ui/Hud.tsx +6 -5
  331. package/templates/racing/src/ui/main.tsx +14 -0
  332. package/templates/racing/threenative.config.ts +28 -8
  333. package/templates/racing/vite.config.ts +34 -1
  334. package/templates/runner/.codex/config.toml +19 -0
  335. package/templates/runner/.cursor/mcp.json +32 -0
  336. package/templates/runner/.gemini/settings.json +32 -0
  337. package/templates/runner/.mcp.json +32 -0
  338. package/templates/runner/.vscode/mcp.json +36 -0
  339. package/templates/runner/.zed/settings.json +36 -0
  340. package/templates/runner/AGENTS.md +96 -0
  341. package/templates/runner/CLAUDE.md +98 -0
  342. package/templates/runner/README.md +43 -0
  343. package/templates/runner/index.html +12 -0
  344. package/templates/runner/kit.json +7 -0
  345. package/templates/runner/opencode.json +41 -0
  346. package/templates/runner/package.json +50 -0
  347. package/templates/runner/playtests/performance.playtest.json +23 -0
  348. package/templates/runner/playtests/streams.playtest.json +38 -0
  349. package/templates/runner/playtests/survives.playtest.json +51 -0
  350. package/templates/runner/public/favicon.svg +5 -0
  351. package/templates/runner/src/conventions.ts +24 -0
  352. package/templates/runner/src/entities/Runner.ts +135 -0
  353. package/templates/runner/src/game.ts +50 -0
  354. package/templates/runner/src/main.ts +15 -0
  355. package/templates/runner/src/physics.ts +13 -0
  356. package/templates/runner/src/render/camera.ts +39 -0
  357. package/templates/runner/src/render/dust.ts +131 -0
  358. package/templates/runner/src/render/lighting.ts +57 -0
  359. package/templates/runner/src/render/loading.ts +325 -0
  360. package/templates/runner/src/render/materials.ts +27 -0
  361. package/templates/runner/src/render/palette.ts +30 -0
  362. package/templates/runner/src/render/postprocessing.ts +34 -0
  363. package/templates/runner/src/render/quality.ts +170 -0
  364. package/templates/runner/src/render/shapes.ts +68 -0
  365. package/templates/runner/src/render/sky.ts +51 -0
  366. package/templates/runner/src/render/touch-controls.ts +185 -0
  367. package/templates/runner/src/render/worldEnvironment.ts +758 -0
  368. package/templates/runner/src/scenes/Boot.ts +12 -0
  369. package/templates/runner/src/scenes/Run.ts +142 -0
  370. package/templates/runner/src/state.ts +29 -0
  371. package/templates/runner/src/style.css +96 -0
  372. package/templates/runner/src/track.ts +176 -0
  373. package/templates/runner/src/ui/App.tsx +22 -0
  374. package/templates/runner/src/ui/GameUi.tsx +20 -0
  375. package/templates/runner/src/ui/Hud.tsx +55 -0
  376. package/templates/runner/src/ui/Menu.tsx +7 -0
  377. package/templates/runner/src/ui/main.tsx +14 -0
  378. package/templates/runner/tailwind.config.ts +1 -0
  379. package/templates/runner/threenative.config.ts +49 -0
  380. package/templates/runner/tsconfig.json +17 -0
  381. package/templates/runner/vite.config.ts +38 -0
  382. package/templates/sailing/.codex/config.toml +19 -0
  383. package/templates/sailing/.cursor/mcp.json +32 -0
  384. package/templates/sailing/.gemini/settings.json +32 -0
  385. package/templates/sailing/.mcp.json +32 -0
  386. package/templates/sailing/.vscode/mcp.json +36 -0
  387. package/templates/sailing/.zed/settings.json +36 -0
  388. package/templates/sailing/AGENTS.md +95 -0
  389. package/templates/sailing/CLAUDE.md +97 -0
  390. package/templates/sailing/README.md +28 -0
  391. package/templates/sailing/index.html +12 -0
  392. package/templates/sailing/kit.json +7 -0
  393. package/templates/sailing/native-playtests/float.playtest.json +55 -0
  394. package/templates/sailing/native-playtests/survives.playtest.json +38 -0
  395. package/templates/sailing/opencode.json +41 -0
  396. package/templates/sailing/package.json +52 -0
  397. package/templates/sailing/playtests/fail.playtest.json +24 -0
  398. package/templates/sailing/playtests/float-after-the-run-ends.playtest.json +75 -0
  399. package/templates/sailing/playtests/float.playtest.json +59 -0
  400. package/templates/sailing/playtests/performance.playtest.json +36 -0
  401. package/templates/sailing/playtests/survives.playtest.json +46 -0
  402. package/templates/sailing/playtests/touch-controls.playtest.json +48 -0
  403. package/templates/sailing/playtests/win.playtest.json +31 -0
  404. package/templates/sailing/public/favicon.svg +5 -0
  405. package/templates/sailing/src/conventions.ts +8 -0
  406. package/templates/sailing/src/entities/Ship.ts +233 -0
  407. package/templates/sailing/src/game.ts +40 -0
  408. package/templates/sailing/src/main.ts +15 -0
  409. package/templates/sailing/src/render/camera.ts +28 -0
  410. package/templates/sailing/src/render/lighting.ts +41 -0
  411. package/templates/sailing/src/render/loading.ts +325 -0
  412. package/templates/sailing/src/render/materials.ts +44 -0
  413. package/templates/sailing/src/render/ocean.ts +179 -0
  414. package/templates/sailing/src/render/palette.ts +17 -0
  415. package/templates/sailing/src/render/postprocessing.ts +34 -0
  416. package/templates/sailing/src/render/props.ts +602 -0
  417. package/templates/sailing/src/render/quality.ts +140 -0
  418. package/templates/sailing/src/render/sky.ts +37 -0
  419. package/templates/sailing/src/render/touch-controls.ts +142 -0
  420. package/templates/sailing/src/render/worldEnvironment.ts +758 -0
  421. package/templates/sailing/src/scenes/Boot.ts +12 -0
  422. package/templates/sailing/src/scenes/Sailing.ts +133 -0
  423. package/templates/sailing/src/state.ts +10 -0
  424. package/templates/sailing/src/style.css +81 -0
  425. package/templates/sailing/src/ui/App.tsx +15 -0
  426. package/templates/sailing/src/ui/GameUi.tsx +12 -0
  427. package/templates/sailing/src/ui/Hud.tsx +55 -0
  428. package/templates/sailing/src/ui/Menu.tsx +30 -0
  429. package/templates/sailing/src/ui/main.tsx +7 -0
  430. package/templates/sailing/tailwind.config.ts +2 -0
  431. package/templates/sailing/threenative.config.ts +40 -0
  432. package/templates/sailing/tsconfig.json +17 -0
  433. package/templates/sailing/vite.config.ts +34 -0
  434. package/templates/shooter/.codex/config.toml +19 -0
  435. package/templates/shooter/.cursor/mcp.json +32 -0
  436. package/templates/shooter/.gemini/settings.json +32 -0
  437. package/templates/shooter/.mcp.json +18 -2
  438. package/templates/shooter/.vscode/mcp.json +36 -0
  439. package/templates/shooter/.zed/settings.json +36 -0
  440. package/templates/shooter/AGENTS.md +81 -54
  441. package/templates/shooter/CLAUDE.md +81 -54
  442. package/templates/shooter/index.html +0 -1
  443. package/templates/shooter/kit.json +2 -2
  444. package/templates/shooter/opencode.json +41 -0
  445. package/templates/shooter/package.json +16 -11
  446. package/templates/shooter/playtests/combat.playtest.json +48 -0
  447. package/templates/shooter/playtests/fail.playtest.json +5 -4
  448. package/templates/shooter/playtests/input-control.playtest.json +261 -0
  449. package/templates/shooter/playtests/per-item.playtest.json +59 -0
  450. package/templates/shooter/playtests/performance.playtest.json +39 -0
  451. package/templates/shooter/playtests/shooter.playtest.json +31 -21
  452. package/templates/shooter/playtests/survives.playtest.json +28 -1
  453. package/templates/shooter/playtests/touch-controls.playtest.json +42 -0
  454. package/templates/shooter/playtests/weapon-cycle.playtest.json +164 -0
  455. package/templates/shooter/public/favicon.svg +1 -1
  456. package/templates/shooter/src/combat/damage.ts +1 -2
  457. package/templates/shooter/src/conventions.ts +51 -0
  458. package/templates/shooter/src/entities/Player.ts +235 -18
  459. package/templates/shooter/src/entities/Target.ts +2 -2
  460. package/templates/shooter/src/game.ts +35 -3
  461. package/templates/shooter/src/main.ts +3 -13
  462. package/templates/shooter/src/render/camera.ts +78 -18
  463. package/templates/shooter/src/render/decals.ts +211 -0
  464. package/templates/shooter/src/render/lighting.ts +13 -4
  465. package/templates/shooter/src/render/loading.ts +274 -35
  466. package/templates/shooter/src/render/materials.ts +56 -3
  467. package/templates/shooter/src/render/palette.ts +6 -3
  468. package/templates/shooter/src/render/postprocessing.ts +32 -17
  469. package/templates/shooter/src/render/quality.ts +170 -0
  470. package/templates/shooter/src/render/scale.ts +22 -0
  471. package/templates/shooter/src/render/shapes.ts +519 -60
  472. package/templates/shooter/src/render/sky.ts +5 -1
  473. package/templates/shooter/src/render/touch-controls.ts +305 -0
  474. package/templates/shooter/src/render/ui.css +119 -1
  475. package/templates/shooter/src/render/ui.ts +19 -3
  476. package/templates/shooter/src/render/vfx.ts +215 -0
  477. package/templates/shooter/src/render/worldEnvironment.ts +758 -0
  478. package/templates/shooter/src/scenes/Play.ts +385 -97
  479. package/templates/shooter/src/state.ts +18 -0
  480. package/templates/shooter/src/style.css +46 -0
  481. package/templates/shooter/src/ui/App.tsx +10 -12
  482. package/templates/shooter/src/ui/Crosshair.tsx +25 -0
  483. package/templates/shooter/src/ui/GameUi.tsx +22 -0
  484. package/templates/shooter/src/ui/Hud.tsx +14 -10
  485. package/templates/shooter/src/ui/Menu.tsx +24 -9
  486. package/templates/shooter/src/ui/main.tsx +15 -0
  487. package/templates/shooter/src/weapons/Hitscan.ts +3 -4
  488. package/templates/shooter/src/weapons/Projectile.ts +29 -13
  489. package/templates/shooter/src/weapons/Viewmodel.ts +275 -0
  490. package/templates/shooter/threenative.config.ts +28 -8
  491. package/templates/shooter/vite.config.ts +32 -2
  492. package/templates/starter/.codex/config.toml +19 -0
  493. package/templates/starter/.cursor/mcp.json +32 -0
  494. package/templates/starter/.gemini/settings.json +32 -0
  495. package/templates/starter/.mcp.json +18 -2
  496. package/templates/starter/.vscode/mcp.json +36 -0
  497. package/templates/starter/.zed/settings.json +36 -0
  498. package/templates/starter/AGENTS.md +72 -426
  499. package/templates/starter/CLAUDE.md +72 -426
  500. package/templates/starter/assets/pickup.wav +0 -0
  501. package/templates/starter/gitignore +4 -0
  502. package/templates/starter/index.html +0 -1
  503. package/templates/starter/native-playtests/react-hud.playtest.json +20 -0
  504. package/templates/starter/native-playtests/render-chain.playtest.json +81 -0
  505. package/templates/starter/opencode.json +41 -0
  506. package/templates/starter/package.json +16 -12
  507. package/templates/starter/playtests/assets.playtest.json +65 -0
  508. package/templates/starter/playtests/boot-failure.playtest.json +45 -0
  509. package/templates/starter/playtests/buffer.playtest.json +59 -9
  510. package/templates/starter/playtests/cloth.playtest.json +113 -0
  511. package/templates/starter/playtests/coyote.playtest.json +60 -8
  512. package/templates/starter/playtests/forward.playtest.json +29 -4
  513. package/templates/starter/playtests/gameover.playtest.json +66 -0
  514. package/templates/starter/playtests/goal.playtest.json +67 -0
  515. package/templates/starter/playtests/hot-reload.playtest.json +48 -8
  516. package/templates/starter/playtests/look.playtest.json +142 -10
  517. package/templates/starter/playtests/models-baseline.png +0 -0
  518. package/templates/starter/playtests/models.playtest.json +74 -0
  519. package/templates/starter/playtests/monitoring.playtest.json +38 -7
  520. package/templates/starter/playtests/odometer.playtest.json +54 -0
  521. package/templates/starter/playtests/pause.playtest.json +27 -4
  522. package/templates/starter/playtests/play.playtest.json +44 -7
  523. package/templates/starter/playtests/respawn.playtest.json +46 -6
  524. package/templates/starter/playtests/restart.playtest.json +65 -10
  525. package/templates/starter/playtests/seed.playtest.json +44 -8
  526. package/templates/starter/playtests/survives.playtest.json +48 -4
  527. package/templates/starter/playtests/textures-baseline.png +0 -0
  528. package/templates/starter/playtests/textures.playtest.json +74 -0
  529. package/templates/starter/playtests/touch-controls.playtest.json +42 -0
  530. package/templates/starter/playtests/zoom-pinch.playtest.json +86 -0
  531. package/templates/starter/playtests/zoom-wheel.playtest.json +59 -0
  532. package/templates/starter/src/conventions.ts +18 -0
  533. package/templates/starter/src/entities/Goal.ts +137 -0
  534. package/templates/starter/src/entities/Player.ts +111 -10
  535. package/templates/starter/src/game.ts +27 -0
  536. package/templates/starter/src/render/adaptiveQuality.ts +195 -0
  537. package/templates/starter/src/render/camera.ts +31 -5
  538. package/templates/starter/src/render/coast.ts +199 -0
  539. package/templates/starter/src/render/easing.ts +5 -0
  540. package/templates/starter/src/render/effects/gradualBackground.ts +48 -0
  541. package/templates/starter/src/render/effects/lensDistortion.ts +43 -0
  542. package/templates/starter/src/render/effects/sparkle.ts +49 -0
  543. package/templates/starter/src/render/hero.ts +88 -0
  544. package/templates/starter/src/render/implicitSurface.ts +199 -0
  545. package/templates/starter/src/render/kuwahara.ts +174 -0
  546. package/templates/starter/src/render/lighting.ts +10 -5
  547. package/templates/starter/src/render/loading.ts +325 -0
  548. package/templates/starter/src/render/materials.ts +39 -4
  549. package/templates/starter/src/render/outline.ts +141 -0
  550. package/templates/starter/src/render/painterly.ts +86 -0
  551. package/templates/starter/src/render/palette.ts +15 -6
  552. package/templates/starter/src/render/pennant.ts +54 -0
  553. package/templates/starter/src/render/postprocessing.ts +97 -15
  554. package/templates/starter/src/render/quality.ts +185 -0
  555. package/templates/starter/src/render/rockRidge.ts +198 -0
  556. package/templates/starter/src/render/rockRidge.worker.ts +77 -0
  557. package/templates/starter/src/render/scenery.ts +40 -0
  558. package/templates/starter/src/render/shapes.ts +9 -21
  559. package/templates/starter/src/render/textureLifetime.ts +53 -0
  560. package/templates/starter/src/render/touch-controls.ts +165 -0
  561. package/templates/starter/src/render/water.ts +38 -0
  562. package/templates/starter/src/render/watercolor.ts +85 -0
  563. package/templates/starter/src/render/worldEnvironment.ts +758 -0
  564. package/templates/starter/src/scenes/Play.ts +243 -46
  565. package/templates/starter/src/state.ts +12 -0
  566. package/templates/starter/src/style.css +72 -8
  567. package/templates/starter/src/ui/App.tsx +9 -6
  568. package/templates/starter/src/ui/GameUi.tsx +20 -0
  569. package/templates/starter/src/ui/Hud.tsx +52 -29
  570. package/templates/starter/src/ui/Menu.tsx +25 -23
  571. package/templates/starter/src/ui/main.tsx +14 -0
  572. package/templates/starter/threenative.config.ts +27 -9
  573. package/templates/starter/tools/look.mjs +109 -0
  574. package/templates/starter/vite.config.ts +32 -2
  575. package/templates/action-rpg/src/physics.ts +0 -40
  576. package/templates/minimal/assets/.gitkeep +0 -0
  577. package/templates/minimal/public/.gitkeep +0 -0
  578. package/templates/minimal/public/icon.png +0 -0
  579. package/templates/platformer/assets/.gitkeep +0 -0
  580. package/templates/platformer/public/.gitkeep +0 -0
  581. package/templates/platformer/public/icon.png +0 -0
  582. package/templates/shooter/src/physics.ts +0 -49
  583. package/templates/starter/assets/.gitkeep +0 -0
  584. package/templates/starter/public/.gitkeep +0 -0
  585. package/templates/starter/public/icon.png +0 -0
  586. package/templates/starter/public/pickup.ogg +0 -0
  587. /package/templates/starter/{public → assets}/native-proof.glb +0 -0
  588. /package/templates/starter/{public → assets}/native-proof.png +0 -0
@@ -1,10 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import { spawn } from 'child_process';
3
- import { stat, mkdir, writeFile, readFile, access, unlink } from 'fs/promises';
4
- import { createRequire } from 'module';
5
- import path from 'path';
2
+ import { createRequire } from 'node:module';
3
+ import { spawnSync, execFileSync, spawn } from 'child_process';
4
+ import { randomUUID, createHash } from 'crypto';
5
+ import { readFile, readdir, stat, mkdir, writeFile, rm, rename, access, unlink } from 'fs/promises';
6
+ import { createRequire as createRequire$1 } from 'module';
7
+ import path2 from 'path';
8
+ import { compileAssets, parsePng, parseAudioConfig } from '@threenative/assets';
6
9
  import { pathToFileURL, fileURLToPath } from 'url';
10
+ import { existsSync, realpathSync, readFileSync, statSync, openSync, readSync, closeSync, accessSync, constants } from 'fs';
11
+ import { platform, homedir } from 'os';
7
12
 
13
+ createRequire(import.meta.url);
8
14
  var ORIENTATIONS = ["landscape", "portrait", "sensor"];
9
15
  var CONFIG_FILE = "threenative.config.ts";
10
16
  var ConfigFailure = class extends Error {
@@ -55,6 +61,16 @@ function positiveInteger(value, fallback, code, label) {
55
61
  }
56
62
  return value;
57
63
  }
64
+ function maxFpsValue(value) {
65
+ if (value === void 0) return 60;
66
+ if (!Number.isSafeInteger(value) || value < 0 || value > 1e3) {
67
+ fail(
68
+ "TN_CONFIG_MAX_FPS_INVALID",
69
+ "display.maxFps must be a whole number between 0 (uncapped) and 1000."
70
+ );
71
+ }
72
+ return value;
73
+ }
58
74
  function packageDisplayName(manifest) {
59
75
  if (typeof manifest.name !== "string" || manifest.name.trim().length === 0) {
60
76
  fail("TN_CONFIG_PACKAGE_NAME_MISSING", "package.json must declare a non-empty name.");
@@ -68,54 +84,14 @@ function defaultAppId(name) {
68
84
  if (!/^[a-z]/u.test(segment)) segment = `game${segment}`;
69
85
  return `com.threenative.${segment}`;
70
86
  }
71
- var PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
72
- function crc32(value) {
73
- let crc = 4294967295;
74
- for (const byte of value) {
75
- crc ^= byte;
76
- for (let bit = 0; bit < 8; bit += 1) {
77
- crc = crc >>> 1 ^ (crc & 1 ? 3988292384 : 0);
78
- }
79
- }
80
- return (crc ^ 4294967295) >>> 0;
81
- }
82
- function isPng(value) {
83
- if (value.length < PNG_SIGNATURE.length || !value.subarray(0, 8).equals(PNG_SIGNATURE)) {
84
- return false;
85
- }
86
- let offset = PNG_SIGNATURE.length;
87
- let hasHeader = false;
88
- let hasData = false;
89
- while (offset + 12 <= value.length) {
90
- const length = value.readUInt32BE(offset);
91
- const chunkEnd = offset + 12 + length;
92
- if (chunkEnd > value.length) return false;
93
- const type = value.toString("ascii", offset + 4, offset + 8);
94
- const chunk = value.subarray(offset + 4, offset + 8 + length);
95
- if (crc32(chunk) !== value.readUInt32BE(offset + 8 + length)) return false;
96
- if (type === "IHDR") {
97
- if (hasHeader || length !== 13) return false;
98
- if (value.readUInt32BE(offset + 8) === 0 || value.readUInt32BE(offset + 12) === 0) {
99
- return false;
100
- }
101
- hasHeader = true;
102
- } else if (type === "IDAT") {
103
- hasData = true;
104
- } else if (type === "IEND") {
105
- return length === 0 && hasHeader && hasData && chunkEnd === value.length;
106
- }
107
- offset = chunkEnd;
108
- }
109
- return false;
110
- }
111
87
  function projectRequire(cwd) {
112
- return createRequire(path.join(cwd, "package.json"));
88
+ return createRequire$1(path2.join(cwd, "package.json"));
113
89
  }
114
90
  function configLoaderSearch(cwd) {
115
91
  return [
116
- path.join(cwd, "node_modules", "vite"),
117
- path.join(cwd, "node_modules", "esbuild"),
118
- path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "node_modules", "esbuild")
92
+ path2.join(cwd, "node_modules", "vite"),
93
+ path2.join(cwd, "node_modules", "esbuild"),
94
+ path2.resolve(path2.dirname(fileURLToPath(import.meta.url)), "..", "node_modules", "esbuild")
119
95
  ];
120
96
  }
121
97
  var CONFIG_BUILD_COMMAND = "pnpm exec threenative build --target web";
@@ -123,7 +99,7 @@ function configContext(cwd, layer, sources, searched, fix) {
123
99
  return { cwd, fix, layer, searched, sources };
124
100
  }
125
101
  function packageContext(cwd) {
126
- const packagePath = path.join(cwd, "package.json");
102
+ const packagePath = path2.join(cwd, "package.json");
127
103
  return configContext(
128
104
  cwd,
129
105
  "package manifest",
@@ -146,8 +122,8 @@ function validationContext(cwd, sources) {
146
122
  cwd,
147
123
  "config validation",
148
124
  sources,
149
- [path.join(cwd, "package.json"), path.join(cwd, CONFIG_FILE)],
150
- `fix '${path.join(cwd, CONFIG_FILE)}' and rerun ${CONFIG_BUILD_COMMAND}`
125
+ [path2.join(cwd, "package.json"), path2.join(cwd, CONFIG_FILE)],
126
+ `fix '${path2.join(cwd, CONFIG_FILE)}' and rerun ${CONFIG_BUILD_COMMAND}`
151
127
  );
152
128
  }
153
129
  function configFailure(code, context, detail) {
@@ -176,10 +152,10 @@ function resolveEsbuild(cwd) {
176
152
  } catch {
177
153
  try {
178
154
  const vite = require2.resolve("vite");
179
- return createRequire(vite).resolve("esbuild");
155
+ return createRequire$1(vite).resolve("esbuild");
180
156
  } catch {
181
157
  try {
182
- return createRequire(import.meta.url).resolve("esbuild");
158
+ return createRequire$1(import.meta.url).resolve("esbuild");
183
159
  } catch {
184
160
  return void 0;
185
161
  }
@@ -187,7 +163,7 @@ function resolveEsbuild(cwd) {
187
163
  }
188
164
  }
189
165
  async function importConfig(cwd) {
190
- const sourcePath = path.join(cwd, CONFIG_FILE);
166
+ const sourcePath = path2.join(cwd, CONFIG_FILE);
191
167
  try {
192
168
  await access(sourcePath);
193
169
  } catch {
@@ -200,9 +176,12 @@ async function importConfig(cwd) {
200
176
  loadingContext(
201
177
  cwd,
202
178
  sourcePath,
203
- `run pnpm add -D vite in '${cwd}' and rerun ${CONFIG_BUILD_COMMAND}`
179
+ `run pnpm add -D esbuild in '${cwd}' and rerun ${CONFIG_BUILD_COMMAND}`
204
180
  ),
205
- "threenative.config.ts needs project-resolved esbuild; install Vite or esbuild."
181
+ // Not "install Vite": Vite 8 dropped esbuild for rolldown, so a project on it satisfies the
182
+ // old advice and still lands here. The templates ship esbuild explicitly for this reason;
183
+ // projects scaffolded before that do not.
184
+ "threenative.config.ts needs project-resolved esbuild; install esbuild."
206
185
  );
207
186
  }
208
187
  let esbuild;
@@ -245,7 +224,7 @@ async function importConfig(cwd) {
245
224
  error instanceof Error ? error.message : String(error)
246
225
  );
247
226
  }
248
- const compiledPath = path.join(cwd, `.threenative.config.${process.pid}.${Date.now()}.mjs`);
227
+ const compiledPath = path2.join(cwd, `.threenative.config.${process.pid}.${Date.now()}.mjs`);
249
228
  try {
250
229
  await writeFile(compiledPath, code, "utf8");
251
230
  } catch (error) {
@@ -281,7 +260,7 @@ async function importConfig(cwd) {
281
260
  async function readManifest(cwd) {
282
261
  let parsed;
283
262
  try {
284
- parsed = JSON.parse(await readFile(path.join(cwd, "package.json"), "utf8"));
263
+ parsed = JSON.parse(await readFile(path2.join(cwd, "package.json"), "utf8"));
285
264
  } catch (error) {
286
265
  fail("TN_CONFIG_PACKAGE_INVALID", error instanceof Error ? error.message : String(error));
287
266
  }
@@ -300,19 +279,19 @@ function packageNativeEntry(manifest) {
300
279
  }
301
280
  function validateNativeEntry(value, cwd) {
302
281
  const entry = nonEmptyString(value, "TN_NATIVE_ENTRY_MISSING", "nativeEntry");
303
- if (path.isAbsolute(entry)) {
282
+ if (path2.isAbsolute(entry)) {
304
283
  fail("TN_CONFIG_NATIVE_ENTRY_INVALID", "nativeEntry must be project-relative.");
305
284
  }
306
- const resolved = path.resolve(cwd, entry);
307
- const relative = path.relative(cwd, resolved);
308
- if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
285
+ const resolved = path2.resolve(cwd, entry);
286
+ const relative = path2.relative(cwd, resolved);
287
+ if (relative === ".." || relative.startsWith(`..${path2.sep}`) || path2.isAbsolute(relative)) {
309
288
  fail("TN_CONFIG_NATIVE_ENTRY_INVALID", "nativeEntry must stay inside the project.");
310
289
  }
311
290
  return entry;
312
291
  }
313
292
  async function validateApp(raw, name, cwd) {
314
293
  const app = assertRecord(raw, "app");
315
- assertKeys(app, "app", ["id", "name", "version", "build", "icon"]);
294
+ assertKeys(app, "app", ["id", "name", "version", "build", "icon", "icons"]);
316
295
  const id = app.id === void 0 ? defaultAppId(name) : nonEmptyString(app.id, "TN_CONFIG_APP_ID_INVALID", "app.id");
317
296
  if (!/^[a-z][a-z0-9]*(?:\.[a-z][a-z0-9]*)+$/u.test(id)) {
318
297
  fail("TN_CONFIG_APP_ID_INVALID", "app.id must be a lower-case reverse-DNS identifier.");
@@ -326,33 +305,201 @@ async function validateApp(raw, name, cwd) {
326
305
  );
327
306
  }
328
307
  const build2 = positiveInteger(app.build, 1, "TN_CONFIG_APP_BUILD_INVALID", "app.build");
329
- if (app.icon === void 0) return { id, name: appName, version, build: build2 };
330
- const icon = nonEmptyString(app.icon, "TN_CONFIG_ICON_INVALID", "app.icon");
331
- if (path.extname(icon).toLowerCase() !== ".png") {
332
- fail("TN_CONFIG_ICON_INVALID", "app.icon must point to a PNG file.");
308
+ const icon = app.icon === void 0 ? void 0 : await validateProjectAsset(app.icon, cwd, "app.icon", {
309
+ codePrefix: "TN_CONFIG_ICON",
310
+ formats: ["png"],
311
+ square: true
312
+ });
313
+ const icons = await validateIconVariants(app.icons, cwd);
314
+ if (icons?.android !== void 0 && icon === void 0 && icons.android.foreground === void 0) {
315
+ fail(
316
+ "TN_CONFIG_BRAND_ANDROID_FOREGROUND_MISSING",
317
+ "app.icons.android.foreground is required when app.icon is not declared."
318
+ );
319
+ }
320
+ return {
321
+ id,
322
+ name: appName,
323
+ version,
324
+ build: build2,
325
+ ...icon === void 0 ? {} : { icon },
326
+ ...icons === void 0 ? {} : { icons }
327
+ };
328
+ }
329
+ async function validateProjectAsset(raw, cwd, label, options) {
330
+ const relative = nonEmptyString(raw, `${options.codePrefix}_INVALID`, label);
331
+ if (path2.isAbsolute(relative)) {
332
+ fail(`${options.codePrefix}_PATH_INVALID`, `${label} must be project-relative: ${relative}`);
333
+ }
334
+ const resolved = path2.resolve(cwd, relative);
335
+ const withinProject = path2.relative(cwd, resolved);
336
+ if (withinProject === ".." || withinProject.startsWith(`..${path2.sep}`) || path2.isAbsolute(withinProject)) {
337
+ fail(
338
+ `${options.codePrefix}_PATH_INVALID`,
339
+ `${label} must stay inside the project: ${relative}`
340
+ );
333
341
  }
334
- const iconPath = path.resolve(cwd, icon);
342
+ const extension = path2.extname(relative).slice(1).toLowerCase();
343
+ if (!options.formats.includes(extension)) {
344
+ fail(
345
+ options.codePrefix === "TN_CONFIG_ICON" ? `${options.codePrefix}_INVALID` : `${options.codePrefix}_FORMAT_INVALID`,
346
+ `${label} must use ${options.formats.map((format) => `.${format}`).join(" or ")}: ${relative}`
347
+ );
348
+ }
349
+ let info;
335
350
  try {
336
- const info = await stat(iconPath);
337
- if (!info.isFile()) fail("TN_CONFIG_ICON_MISSING", `app.icon does not name a file: ${icon}`);
338
- } catch (error) {
339
- if (error instanceof ConfigFailure) throw error;
340
- fail("TN_CONFIG_ICON_MISSING", `app.icon does not exist: ${icon}`);
351
+ info = await stat(resolved);
352
+ } catch {
353
+ fail(`${options.codePrefix}_MISSING`, `${label} does not exist: ${relative}`);
341
354
  }
355
+ if (!info.isFile()) fail(`${options.codePrefix}_MISSING`, `${label} is not a file: ${relative}`);
342
356
  let contents;
343
357
  try {
344
- contents = await readFile(iconPath);
358
+ contents = await readFile(resolved);
345
359
  } catch (error) {
346
- fail("TN_CONFIG_ICON_INVALID", error instanceof Error ? error.message : String(error));
360
+ fail(
361
+ `${options.codePrefix}_INVALID`,
362
+ `${label} could not be read at ${relative}: ${error instanceof Error ? error.message : String(error)}`
363
+ );
364
+ }
365
+ if (extension === "svg") {
366
+ if (!/<svg(?:\s|>)/iu.test(contents.toString("utf8"))) {
367
+ fail(`${options.codePrefix}_INVALID`, `${label} is not a valid SVG file: ${relative}`);
368
+ }
369
+ return relative;
370
+ }
371
+ const png = parsePng(contents);
372
+ if (png === void 0) {
373
+ fail(`${options.codePrefix}_INVALID`, `${label} is not a valid PNG file: ${relative}`);
374
+ }
375
+ if (options.square === true && png.width !== png.height) {
376
+ fail(
377
+ `${options.codePrefix}_DIMENSIONS_INVALID`,
378
+ `${label} must be square (${png.width}x${png.height}): ${relative}`
379
+ );
380
+ }
381
+ if (options.requiresAlpha === true && !png.hasAlpha) {
382
+ fail(
383
+ `${options.codePrefix}_ALPHA_INVALID`,
384
+ `${label} must include an alpha channel: ${relative}`
385
+ );
347
386
  }
348
- if (!isPng(contents)) {
349
- fail("TN_CONFIG_ICON_INVALID", `app.icon is not a valid PNG file: ${icon}`);
387
+ return relative;
388
+ }
389
+ function validateBrandColor(raw, label) {
390
+ if (typeof raw !== "string" || !/^#[0-9a-f]{6}$/iu.test(raw)) {
391
+ fail("TN_CONFIG_BRAND_COLOR_INVALID", `${label} must be a #rrggbb colour.`);
350
392
  }
351
- return { id, name: appName, version, build: build2, icon };
393
+ return raw;
394
+ }
395
+ async function validateIconVariants(raw, cwd) {
396
+ if (raw === void 0) return void 0;
397
+ const icons = assertRecord(raw, "app.icons");
398
+ assertKeys(icons, "app.icons", ["android", "ios", "web"]);
399
+ const android = icons.android === void 0 ? void 0 : assertRecord(icons.android, "app.icons.android");
400
+ const ios = icons.ios === void 0 ? void 0 : assertRecord(icons.ios, "app.icons.ios");
401
+ const web = icons.web === void 0 ? void 0 : assertRecord(icons.web, "app.icons.web");
402
+ if (android !== void 0)
403
+ assertKeys(android, "app.icons.android", ["foreground", "background", "monochrome"]);
404
+ if (ios !== void 0) assertKeys(ios, "app.icons.ios", ["dark", "tinted"]);
405
+ if (web !== void 0)
406
+ assertKeys(web, "app.icons.web", ["favicon", "maskable", "monochrome", "appleTouch"]);
407
+ const androidResult = android === void 0 ? void 0 : {
408
+ ...android.foreground === void 0 ? {} : {
409
+ foreground: await validateProjectAsset(
410
+ android.foreground,
411
+ cwd,
412
+ "app.icons.android.foreground",
413
+ {
414
+ codePrefix: "TN_CONFIG_BRAND_ANDROID_FOREGROUND",
415
+ formats: ["png"],
416
+ requiresAlpha: true,
417
+ square: true
418
+ }
419
+ )
420
+ },
421
+ ...android.background === void 0 ? {} : {
422
+ background: validateBrandColor(android.background, "app.icons.android.background")
423
+ },
424
+ ...android.monochrome === void 0 ? {} : {
425
+ monochrome: await validateProjectAsset(
426
+ android.monochrome,
427
+ cwd,
428
+ "app.icons.android.monochrome",
429
+ {
430
+ codePrefix: "TN_CONFIG_BRAND_ANDROID_MONOCHROME",
431
+ formats: ["png"],
432
+ requiresAlpha: true,
433
+ square: true
434
+ }
435
+ )
436
+ }
437
+ };
438
+ const iosResult = ios === void 0 ? void 0 : {
439
+ ...ios.dark === void 0 ? {} : {
440
+ dark: await validateProjectAsset(ios.dark, cwd, "app.icons.ios.dark", {
441
+ codePrefix: "TN_CONFIG_BRAND_IOS_DARK",
442
+ formats: ["png"],
443
+ square: true
444
+ })
445
+ },
446
+ ...ios.tinted === void 0 ? {} : {
447
+ tinted: await validateProjectAsset(ios.tinted, cwd, "app.icons.ios.tinted", {
448
+ codePrefix: "TN_CONFIG_BRAND_IOS_TINTED",
449
+ formats: ["png"],
450
+ square: true
451
+ })
452
+ }
453
+ };
454
+ const webResult = web === void 0 ? void 0 : {
455
+ ...web.favicon === void 0 ? {} : {
456
+ favicon: await validateProjectAsset(web.favicon, cwd, "app.icons.web.favicon", {
457
+ codePrefix: "TN_CONFIG_BRAND_WEB_FAVICON",
458
+ formats: ["png", "svg"],
459
+ square: true
460
+ })
461
+ },
462
+ ...web.maskable === void 0 ? {} : {
463
+ maskable: await validateProjectAsset(web.maskable, cwd, "app.icons.web.maskable", {
464
+ codePrefix: "TN_CONFIG_BRAND_WEB_MASKABLE",
465
+ formats: ["png"],
466
+ square: true
467
+ })
468
+ },
469
+ ...web.monochrome === void 0 ? {} : {
470
+ monochrome: await validateProjectAsset(
471
+ web.monochrome,
472
+ cwd,
473
+ "app.icons.web.monochrome",
474
+ {
475
+ codePrefix: "TN_CONFIG_BRAND_WEB_MONOCHROME",
476
+ formats: ["png"],
477
+ square: true
478
+ }
479
+ )
480
+ },
481
+ ...web.appleTouch === void 0 ? {} : {
482
+ appleTouch: await validateProjectAsset(
483
+ web.appleTouch,
484
+ cwd,
485
+ "app.icons.web.appleTouch",
486
+ {
487
+ codePrefix: "TN_CONFIG_BRAND_WEB_APPLE_TOUCH",
488
+ formats: ["png"],
489
+ square: true
490
+ }
491
+ )
492
+ }
493
+ };
494
+ return {
495
+ ...androidResult === void 0 ? {} : { android: androidResult },
496
+ ...iosResult === void 0 ? {} : { ios: iosResult },
497
+ ...webResult === void 0 ? {} : { web: webResult }
498
+ };
352
499
  }
353
500
  function validateDisplay(raw) {
354
501
  const display = assertRecord(raw, "display");
355
- assertKeys(display, "display", ["orientation", "fullscreen", "keepScreenOn"]);
502
+ assertKeys(display, "display", ["orientation", "fullscreen", "keepScreenOn", "maxFps"]);
356
503
  const orientation = display.orientation === void 0 ? "landscape" : display.orientation;
357
504
  if (typeof orientation !== "string" || !ORIENTATIONS.includes(orientation)) {
358
505
  fail(
@@ -373,16 +520,23 @@ function validateDisplay(raw) {
373
520
  false,
374
521
  "TN_CONFIG_KEEP_SCREEN_ON_INVALID",
375
522
  "display.keepScreenOn"
376
- )
523
+ ),
524
+ maxFps: maxFpsValue(display.maxFps)
377
525
  };
378
526
  }
379
527
  function validateWindow(raw, appName) {
380
528
  const window = assertRecord(raw, "window");
381
- assertKeys(window, "window", ["title", "width", "height", "resizable"]);
529
+ assertKeys(window, "window", ["title", "width", "height", "maximized", "resizable"]);
382
530
  return {
383
531
  title: window.title === void 0 ? appName : nonEmptyString(window.title, "TN_CONFIG_WINDOW_TITLE_INVALID", "window.title"),
384
532
  width: positiveInteger(window.width, 1280, "TN_CONFIG_WINDOW_WIDTH_INVALID", "window.width"),
385
533
  height: positiveInteger(window.height, 720, "TN_CONFIG_WINDOW_HEIGHT_INVALID", "window.height"),
534
+ maximized: booleanValue(
535
+ window.maximized,
536
+ false,
537
+ "TN_CONFIG_WINDOW_MAXIMIZED_INVALID",
538
+ "window.maximized"
539
+ ),
386
540
  resizable: booleanValue(
387
541
  window.resizable,
388
542
  true,
@@ -391,54 +545,371 @@ function validateWindow(raw, appName) {
391
545
  )
392
546
  };
393
547
  }
394
- function validateLoading(raw) {
395
- const loading = assertRecord(raw, "loading");
396
- assertKeys(loading, "loading", [
397
- "image",
398
- "backdropColor",
399
- "trackColor",
400
- "progressColor",
401
- "showProgressBar"
402
- ]);
403
- const color = (value, fallback, label) => {
404
- if (value === void 0) return fallback;
405
- if (typeof value !== "string" || !/^#[0-9a-f]{6}$/iu.test(value)) {
406
- fail("TN_CONFIG_LOADING_COLOR_INVALID", `${label} must be a #rrggbb colour.`);
407
- }
408
- return value;
409
- };
410
- const image = loading.image === void 0 ? void 0 : nonEmptyString(loading.image, "TN_CONFIG_LOADING_IMAGE_INVALID", "loading.image");
411
- if (image !== void 0 && path.isAbsolute(image)) {
412
- fail("TN_CONFIG_LOADING_IMAGE_INVALID", "loading.image must be project-relative.");
413
- }
548
+ async function validateBootSplash(raw, cwd) {
549
+ if (raw === void 0) return void 0;
550
+ const bootSplash = assertRecord(raw, "bootSplash");
551
+ assertKeys(bootSplash, "bootSplash", ["backgroundColor", "image"]);
552
+ const backgroundColor = bootSplash.backgroundColor === void 0 ? void 0 : validateBrandColor(bootSplash.backgroundColor, "bootSplash.backgroundColor");
553
+ const image = bootSplash.image === void 0 ? void 0 : await validateProjectAsset(bootSplash.image, cwd, "bootSplash.image", {
554
+ codePrefix: "TN_CONFIG_BRAND_SPLASH",
555
+ formats: ["png"]
556
+ });
414
557
  return {
415
- ...image === void 0 ? {} : { image },
416
- backdropColor: color(loading.backdropColor, "#0d1b2a", "loading.backdropColor"),
417
- trackColor: color(loading.trackColor, "#274060", "loading.trackColor"),
418
- progressColor: color(loading.progressColor, "#8fd694", "loading.progressColor"),
419
- showProgressBar: booleanValue(
420
- loading.showProgressBar,
421
- true,
422
- "TN_CONFIG_LOADING_BAR_INVALID",
423
- "loading.showProgressBar"
424
- )
558
+ ...backgroundColor === void 0 ? {} : { backgroundColor },
559
+ ...image === void 0 ? {} : { image }
425
560
  };
426
561
  }
562
+ var UI_RENDERERS = ["native", "web"];
563
+ function validateUi(raw) {
564
+ const ui = assertRecord(raw, "ui");
565
+ assertKeys(ui, "ui", ["renderer"]);
566
+ const renderer = ui.renderer === void 0 ? "native" : ui.renderer;
567
+ if (typeof renderer !== "string" || !UI_RENDERERS.includes(renderer)) {
568
+ fail("TN_CONFIG_UI_RENDERER_INVALID", "ui.renderer must be web or native.");
569
+ }
570
+ return { renderer };
571
+ }
427
572
  function validateRenderer(raw) {
428
573
  const renderer = assertRecord(raw, "renderer");
429
- assertKeys(renderer, "renderer", ["preferWebGPU"]);
574
+ assertKeys(renderer, "renderer", [
575
+ "preferWebGPU",
576
+ "resolutionScale",
577
+ "antialias",
578
+ "alphaAntialiasing",
579
+ "android"
580
+ ]);
581
+ const android = assertRecord(renderer.android, "renderer.android");
582
+ assertKeys(android, "renderer.android", ["resolutionScale", "antialias", "alphaAntialiasing"]);
583
+ const resolutionScale = renderer.resolutionScale;
584
+ const androidResolutionScale = android.resolutionScale;
585
+ for (const [name, value] of [
586
+ ["renderer.resolutionScale", resolutionScale],
587
+ ["renderer.android.resolutionScale", androidResolutionScale]
588
+ ]) {
589
+ if (value === void 0 || value === "auto") continue;
590
+ if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 1) {
591
+ fail(
592
+ "TN_CONFIG_RENDERER_RESOLUTION_SCALE_INVALID",
593
+ `${name} must be "auto" or a number within (0, 1].`
594
+ );
595
+ }
596
+ }
597
+ const antialias = booleanOrUndefined(renderer.antialias, "renderer.antialias");
598
+ const androidAntialias = booleanOrUndefined(android.antialias, "renderer.android.antialias");
599
+ const alphaAntialiasing = booleanOrUndefined(
600
+ renderer.alphaAntialiasing,
601
+ "renderer.alphaAntialiasing"
602
+ );
603
+ const androidAlphaAntialiasing = booleanOrUndefined(
604
+ android.alphaAntialiasing,
605
+ "renderer.android.alphaAntialiasing"
606
+ );
607
+ const androidOverrides = {
608
+ ...androidResolutionScale === void 0 ? {} : { resolutionScale: androidResolutionScale },
609
+ ...androidAntialias === void 0 ? {} : { antialias: androidAntialias },
610
+ ...androidAlphaAntialiasing === void 0 ? {} : { alphaAntialiasing: androidAlphaAntialiasing }
611
+ };
430
612
  return {
431
613
  preferWebGPU: booleanValue(
432
614
  renderer.preferWebGPU,
433
615
  true,
434
616
  "TN_CONFIG_RENDERER_INVALID",
435
617
  "renderer.preferWebGPU"
436
- )
618
+ ),
619
+ ...antialias === void 0 ? {} : { antialias },
620
+ ...alphaAntialiasing === void 0 ? {} : { alphaAntialiasing },
621
+ ...resolutionScale === void 0 ? {} : { resolutionScale },
622
+ ...Object.keys(androidOverrides).length === 0 ? {} : { android: androidOverrides }
623
+ };
624
+ }
625
+ function booleanOrUndefined(value, name) {
626
+ if (value === void 0) return void 0;
627
+ if (typeof value !== "boolean") fail("TN_CONFIG_RENDERER_INVALID", `${name} must be a boolean.`);
628
+ return value;
629
+ }
630
+ var ASSET_TARGET_KEYS = [
631
+ "maxMaterials",
632
+ "maxTriangles",
633
+ "maxTextureDimension"
634
+ ];
635
+ function validateAssetTargets(raw) {
636
+ const targets = assertRecord(raw, "assets.targets");
637
+ assertKeys(targets, "assets.targets", ASSET_TARGET_KEYS);
638
+ return {
639
+ ...targets.maxMaterials === void 0 ? {} : {
640
+ maxMaterials: positiveInteger(
641
+ targets.maxMaterials,
642
+ 1,
643
+ "TN_CONFIG_ASSETS_INVALID",
644
+ "assets.targets.maxMaterials"
645
+ )
646
+ },
647
+ ...targets.maxTriangles === void 0 ? {} : {
648
+ maxTriangles: positiveInteger(
649
+ targets.maxTriangles,
650
+ 1,
651
+ "TN_CONFIG_ASSETS_INVALID",
652
+ "assets.targets.maxTriangles"
653
+ )
654
+ },
655
+ ...targets.maxTextureDimension === void 0 ? {} : {
656
+ maxTextureDimension: positiveInteger(
657
+ targets.maxTextureDimension,
658
+ 1,
659
+ "TN_CONFIG_ASSETS_INVALID",
660
+ "assets.targets.maxTextureDimension"
661
+ )
662
+ }
663
+ };
664
+ }
665
+ var ASSET_TEXTURE_KEYS = ["maxSize", "overrides", "quality"];
666
+ var TEXTURE_OVERRIDE_KEYS = ["codec", "glob", "quality"];
667
+ var TEXTURE_CODECS = ["etc1s", "none", "uastc"];
668
+ function textureQuality(value, label) {
669
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > 255) {
670
+ fail("TN_CONFIG_ASSETS_INVALID", `${label} must be an integer between 1 and 255.`);
671
+ }
672
+ return value;
673
+ }
674
+ function textureMaxSize(value) {
675
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 4) {
676
+ fail(
677
+ "TN_CONFIG_ASSETS_INVALID",
678
+ "assets.textures.maxSize must be a positive integer of at least 4."
679
+ );
680
+ }
681
+ return value;
682
+ }
683
+ function validateTextureOverrides(raw) {
684
+ if (!Array.isArray(raw)) {
685
+ fail("TN_CONFIG_ASSETS_INVALID", "assets.textures.overrides must be an array.");
686
+ }
687
+ return raw.map((item, index) => {
688
+ if (!isRecord(item)) {
689
+ fail(
690
+ "TN_CONFIG_ASSETS_INVALID",
691
+ `assets.textures.overrides[${String(index)}] must be an object.`
692
+ );
693
+ }
694
+ assertKeys(item, `assets.textures.overrides[${String(index)}]`, TEXTURE_OVERRIDE_KEYS);
695
+ const glob = nonEmptyString(
696
+ item.glob,
697
+ "TN_CONFIG_ASSETS_INVALID",
698
+ `assets.textures.overrides[${String(index)}].glob`
699
+ );
700
+ if (typeof item.codec !== "string" || !TEXTURE_CODECS.includes(item.codec)) {
701
+ fail(
702
+ "TN_CONFIG_ASSETS_INVALID",
703
+ `assets.textures.overrides[${String(index)}].codec must be one of ${TEXTURE_CODECS.join(", ")}; received '${String(item.codec)}'.`
704
+ );
705
+ }
706
+ return {
707
+ codec: item.codec,
708
+ glob,
709
+ ...item.quality === void 0 ? {} : {
710
+ quality: textureQuality(
711
+ item.quality,
712
+ `assets.textures.overrides[${String(index)}].quality`
713
+ )
714
+ }
715
+ };
716
+ });
717
+ }
718
+ function validateTextures(raw) {
719
+ if (raw === "none") return "none";
720
+ const textures = assertRecord(raw, "assets.textures");
721
+ assertKeys(textures, "assets.textures", ASSET_TEXTURE_KEYS);
722
+ return {
723
+ ...textures.maxSize === void 0 ? {} : { maxSize: textureMaxSize(textures.maxSize) },
724
+ ...textures.quality === void 0 ? {} : { quality: textureQuality(textures.quality, "assets.textures.quality") },
725
+ ...textures.overrides === void 0 ? {} : { overrides: validateTextureOverrides(textures.overrides) }
726
+ };
727
+ }
728
+ var MODEL_PASS_KEYS = ["dedup", "meshopt", "prune", "quantize", "reorder"];
729
+ var MODEL_QUANTIZE_KEYS = ["normalBits", "positionBits", "uvBits"];
730
+ var MODEL_VIRTUAL_KEYS = [
731
+ "groupSize",
732
+ "maxTriangles",
733
+ "minSourceTriangles",
734
+ "minTriangles",
735
+ "simplifyRatio"
736
+ ];
737
+ function bitDepth(value, label) {
738
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1 || value > 16) {
739
+ fail("TN_CONFIG_ASSETS_INVALID", `${label} must be an integer between 1 and 16 bits.`);
740
+ }
741
+ return value;
742
+ }
743
+ function validateModels(raw) {
744
+ if (raw === "none") return "none";
745
+ const models = assertRecord(raw, "assets.models");
746
+ assertKeys(models, "assets.models", [
747
+ "lightmap",
748
+ "passes",
749
+ "quantize",
750
+ "sharedImages",
751
+ "simplify",
752
+ "textures",
753
+ "virtual"
754
+ ]);
755
+ if (models.sharedImages !== void 0 && typeof models.sharedImages !== "boolean") {
756
+ fail("TN_CONFIG_ASSETS_INVALID", "assets.models.sharedImages must be true or false.");
757
+ }
758
+ const sharedImages = models.sharedImages;
759
+ let lightmap;
760
+ if (models.lightmap !== void 0) {
761
+ const rawLightmap = assertRecord(models.lightmap, "assets.models.lightmap");
762
+ assertKeys(rawLightmap, "assets.models.lightmap", ["atlasSize", "padding"]);
763
+ if (rawLightmap.atlasSize === void 0 || rawLightmap.padding === void 0) {
764
+ fail("TN_CONFIG_ASSETS_INVALID", "assets.models.lightmap requires atlasSize and padding.");
765
+ }
766
+ lightmap = {
767
+ atlasSize: positiveInteger(
768
+ rawLightmap.atlasSize,
769
+ 1,
770
+ "TN_CONFIG_ASSETS_INVALID",
771
+ "assets.models.lightmap.atlasSize"
772
+ ),
773
+ padding: positiveInteger(
774
+ rawLightmap.padding,
775
+ 1,
776
+ "TN_CONFIG_ASSETS_INVALID",
777
+ "assets.models.lightmap.padding"
778
+ )
779
+ };
780
+ }
781
+ let passes;
782
+ if (models.passes !== void 0) {
783
+ const rawPasses = assertRecord(models.passes, "assets.models.passes");
784
+ assertKeys(rawPasses, "assets.models.passes", MODEL_PASS_KEYS);
785
+ passes = {};
786
+ for (const key of MODEL_PASS_KEYS) {
787
+ const value = rawPasses[key];
788
+ if (value === void 0) continue;
789
+ if (typeof value !== "boolean")
790
+ fail("TN_CONFIG_ASSETS_INVALID", `assets.models.passes.${key} must be true or false.`);
791
+ passes = { ...passes, [key]: value };
792
+ }
793
+ }
794
+ let quantize;
795
+ if (models.quantize !== void 0) {
796
+ const rawQuantize = assertRecord(models.quantize, "assets.models.quantize");
797
+ assertKeys(rawQuantize, "assets.models.quantize", MODEL_QUANTIZE_KEYS);
798
+ quantize = {};
799
+ for (const key of MODEL_QUANTIZE_KEYS) {
800
+ const value = rawQuantize[key];
801
+ if (value === void 0) continue;
802
+ quantize = {
803
+ ...quantize,
804
+ [key]: bitDepth(value, `assets.models.quantize.${key}`)
805
+ };
806
+ }
807
+ }
808
+ const simplify = models.simplify;
809
+ const textures = models.textures;
810
+ let virtual;
811
+ if (models.virtual === "none") {
812
+ virtual = "none";
813
+ } else if (models.virtual !== void 0) {
814
+ const rawVirtual = assertRecord(models.virtual, "assets.models.virtual");
815
+ assertKeys(rawVirtual, "assets.models.virtual", MODEL_VIRTUAL_KEYS);
816
+ const bake = {};
817
+ for (const key of MODEL_VIRTUAL_KEYS) {
818
+ const value = rawVirtual[key];
819
+ if (value === void 0) continue;
820
+ if (key === "simplifyRatio") {
821
+ if (typeof value !== "number" || !(value > 0) || !(value < 1))
822
+ fail(
823
+ "TN_CONFIG_ASSETS_INVALID",
824
+ "assets.models.virtual.simplifyRatio must be a number between 0 and 1, exclusive."
825
+ );
826
+ bake.simplifyRatio = value;
827
+ continue;
828
+ }
829
+ bake[key] = positiveInteger(
830
+ value,
831
+ 1,
832
+ "TN_CONFIG_ASSETS_INVALID",
833
+ `assets.models.virtual.${key}`
834
+ );
835
+ }
836
+ virtual = bake;
837
+ }
838
+ return {
839
+ ...lightmap === void 0 ? {} : { lightmap },
840
+ ...passes === void 0 || Object.keys(passes).length === 0 ? {} : { passes },
841
+ ...quantize === void 0 || Object.keys(quantize).length === 0 ? {} : { quantize },
842
+ ...sharedImages === void 0 ? {} : { sharedImages },
843
+ ...simplify === void 0 ? {} : { simplify },
844
+ ...textures === void 0 ? {} : { textures },
845
+ ...virtual === void 0 ? {} : { virtual }
846
+ };
847
+ }
848
+ function validateBudget(raw) {
849
+ const limit = (value) => value === "none" || typeof value === "number" && Number.isSafeInteger(value) && value > 0;
850
+ if (limit(raw)) return raw;
851
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw) || Object.entries(raw).some(
852
+ ([key, value]) => !["uncooked", "total"].includes(key) || !limit(value)
853
+ )) {
854
+ fail(
855
+ "TN_CONFIG_ASSETS_INVALID",
856
+ 'assets.budget must contain positive integer byte limits or "none" for uncooked and total.'
857
+ );
858
+ }
859
+ return raw;
860
+ }
861
+ function validateAudio(raw) {
862
+ try {
863
+ parseAudioConfig(raw);
864
+ } catch (error) {
865
+ fail("TN_CONFIG_ASSETS_INVALID", error instanceof Error ? error.message : String(error));
866
+ }
867
+ return raw;
868
+ }
869
+ function validateAssets(raw) {
870
+ const assets = assertRecord(raw, "assets");
871
+ assertKeys(assets, "assets", [
872
+ "audio",
873
+ "budget",
874
+ "exclude",
875
+ "concurrency",
876
+ "models",
877
+ "source",
878
+ "output",
879
+ "targets",
880
+ "textures"
881
+ ]);
882
+ const targets = assets.targets === void 0 ? void 0 : validateAssetTargets(assets.targets);
883
+ const models = assets.models === void 0 ? void 0 : validateModels(assets.models);
884
+ const textures = assets.textures === void 0 ? void 0 : validateTextures(assets.textures);
885
+ if (assets.exclude !== void 0 && (!Array.isArray(assets.exclude) || assets.exclude.some((glob) => typeof glob !== "string" || glob.trim() === ""))) {
886
+ fail("TN_CONFIG_ASSETS_INVALID", "assets.exclude must be an array of non-empty glob strings.");
887
+ }
888
+ return {
889
+ ...assets.audio === void 0 ? {} : { audio: validateAudio(assets.audio) },
890
+ ...assets.exclude === void 0 ? {} : { exclude: assets.exclude },
891
+ ...assets.budget === void 0 ? {} : { budget: validateBudget(assets.budget) },
892
+ // The worker bound a bake may use. Validated here so a malformed value fails at config
893
+ // load with the named code, and handed to the driver unchanged, which re-checks it —
894
+ // the producer→consumer seam the config spec proves by running the pipeline.
895
+ ...assets.concurrency === void 0 ? {} : {
896
+ concurrency: positiveInteger(
897
+ assets.concurrency,
898
+ 1,
899
+ "TN_CONFIG_ASSETS_INVALID",
900
+ "assets.concurrency"
901
+ )
902
+ },
903
+ ...assets.source === void 0 ? {} : { source: nonEmptyString(assets.source, "TN_CONFIG_ASSETS_INVALID", "assets.source") },
904
+ ...assets.output === void 0 ? {} : { output: nonEmptyString(assets.output, "TN_CONFIG_ASSETS_INVALID", "assets.output") },
905
+ ...targets === void 0 ? {} : { targets },
906
+ ...models === void 0 ? {} : { models },
907
+ ...textures === void 0 ? {} : { textures }
437
908
  };
438
909
  }
439
910
  async function loadConfigInternal(root) {
440
- const packagePath = path.join(root, "package.json");
441
- const sourcePath = path.join(root, CONFIG_FILE);
911
+ const packagePath = path2.join(root, "package.json");
912
+ const sourcePath = path2.join(root, CONFIG_FILE);
442
913
  const manifest = await withConfigContext(
443
914
  packageContext(root),
444
915
  "TN_CONFIG_PACKAGE_INVALID",
@@ -464,10 +935,12 @@ async function loadConfigInternal(root) {
464
935
  assertKeys(raw, "config", [
465
936
  "app",
466
937
  "display",
467
- "loading",
938
+ "bootSplash",
468
939
  "window",
469
940
  "nativeEntry",
470
- "renderer"
941
+ "renderer",
942
+ "ui",
943
+ "assets"
471
944
  ]);
472
945
  }
473
946
  const configuredEntry = raw?.nativeEntry;
@@ -478,21 +951,25 @@ async function loadConfigInternal(root) {
478
951
  );
479
952
  }
480
953
  const app = await validateApp(raw?.app, name, root);
954
+ const bootSplash = await validateBootSplash(raw?.bootSplash, root);
955
+ const assets = raw?.assets === void 0 ? void 0 : validateAssets(raw.assets);
481
956
  return {
482
957
  app,
483
958
  display: validateDisplay(raw?.display),
484
- loading: validateLoading(raw?.loading),
485
959
  window: validateWindow(raw?.window, app.name),
486
960
  nativeEntry: validateNativeEntry(configuredEntry ?? packageEntry ?? "src/game.ts", root),
487
- renderer: validateRenderer(raw?.renderer)
961
+ renderer: validateRenderer(raw?.renderer),
962
+ ui: validateUi(raw?.ui),
963
+ ...bootSplash === void 0 ? {} : { bootSplash },
964
+ ...assets === void 0 ? {} : { assets }
488
965
  };
489
966
  }
490
967
  );
491
968
  }
492
969
  async function loadConfig(cwd) {
493
- const root = path.resolve(cwd);
970
+ const root = path2.resolve(cwd);
494
971
  return withConfigContext(
495
- validationContext(root, [path.join(root, CONFIG_FILE), path.join(root, "package.json")]),
972
+ validationContext(root, [path2.join(root, CONFIG_FILE), path2.join(root, "package.json")]),
496
973
  "TN_CONFIG_VALIDATION_FAILED",
497
974
  () => loadConfigInternal(root)
498
975
  );
@@ -501,11 +978,11 @@ async function loadConfig(cwd) {
501
978
  // src/build.ts
502
979
  var TARGETS = ["web", "desktop", "android", "ios"];
503
980
  function projectRequire2(cwd) {
504
- return createRequire(path.join(cwd, "package.json"));
981
+ return createRequire$1(path2.join(cwd, "package.json"));
505
982
  }
506
983
  function packageRoot(cwd, packageName) {
507
984
  try {
508
- return path.dirname(projectRequire2(cwd).resolve(`${packageName}/package.json`));
985
+ return path2.dirname(projectRequire2(cwd).resolve(`${packageName}/package.json`));
509
986
  } catch {
510
987
  throw new Error(
511
988
  `Cannot build a native target because '${packageName}' is not installed in ${cwd}.`
@@ -514,7 +991,7 @@ function packageRoot(cwd, packageName) {
514
991
  }
515
992
  function executable(cwd, name) {
516
993
  const suffix = process.platform === "win32" ? ".cmd" : "";
517
- return path.join(cwd, "node_modules", ".bin", `${name}${suffix}`);
994
+ return path2.join(cwd, "node_modules", ".bin", `${name}${suffix}`);
518
995
  }
519
996
  async function run(command, args, cwd) {
520
997
  await new Promise((resolve, reject) => {
@@ -522,12 +999,12 @@ async function run(command, args, cwd) {
522
999
  child.once("error", reject);
523
1000
  child.once("exit", (code) => {
524
1001
  if (code === 0) resolve();
525
- else reject(new Error(`${path.basename(command)} exited with code ${code ?? "unknown"}.`));
1002
+ else reject(new Error(`${path2.basename(command)} exited with code ${code ?? "unknown"}.`));
526
1003
  });
527
1004
  });
528
1005
  }
529
1006
  async function projectName(cwd) {
530
- const manifest = JSON.parse(await readFile(path.join(cwd, "package.json"), "utf8"));
1007
+ const manifest = JSON.parse(await readFile(path2.join(cwd, "package.json"), "utf8"));
531
1008
  const name = manifest.name?.replace(/^@[^/]+\//u, "").replace(/[^a-zA-Z0-9._-]/gu, "-");
532
1009
  if (name === void 0 || name.length === 0) throw new Error("package.json must name the game.");
533
1010
  return name;
@@ -554,13 +1031,154 @@ async function assertNativeBundleCompatible(bundle, target) {
554
1031
  `TN_NATIVE_WASM_ON_MOBILE: ${target} bundle contains ${wasm.map(([label]) => label).join(", ")}. Move web-only WASM imports out of src/game.ts or provide a threenative-native conditional backend; mobile navigation is owned by PRD-052.`
555
1032
  );
556
1033
  }
1034
+ function assertNativeUiRendererCompatible(target, renderer, platform2 = process.platform) {
1035
+ if (renderer === "native" || target === "android" || target === "ios") return;
1036
+ if (target === "desktop" && platform2 === "linux") return;
1037
+ const platformName = platform2 === "darwin" ? "macOS" : platform2 === "win32" ? "Windows" : platform2;
1038
+ throw new Error(
1039
+ `TN_UI_RENDERER_UNSUPPORTED: ui.renderer is "web", but ${target} has no WebView host on ${platformName}. Set ui.renderer to "native" for ${target}.`
1040
+ );
1041
+ }
1042
+ var COMPRESSED_MODEL_EXTENSIONS = [
1043
+ "EXT_meshopt_compression",
1044
+ "KHR_draco_mesh_compression",
1045
+ "KHR_meshopt_compression"
1046
+ ];
1047
+ function namedAssets(logicalPaths) {
1048
+ const shown = logicalPaths.slice(0, 3).join(", ");
1049
+ const rest = logicalPaths.length - 3;
1050
+ return rest > 0 ? `${shown} and ${rest} more` : shown;
1051
+ }
1052
+ async function assertNativeAssetsCompatible(cwd, target, config) {
1053
+ if (target === "desktop" || target === "web") return;
1054
+ const outputRoot = path2.resolve(cwd, config.assets?.output ?? "public");
1055
+ const manifestPath = path2.join(outputRoot, "assets.manifest.json");
1056
+ let raw;
1057
+ try {
1058
+ raw = await readFile(manifestPath, "utf8");
1059
+ } catch {
1060
+ return;
1061
+ }
1062
+ let parsed;
1063
+ try {
1064
+ parsed = JSON.parse(raw);
1065
+ } catch (error) {
1066
+ throw new Error(
1067
+ `TN_NATIVE_ASSET_MANIFEST_INVALID: '${manifestPath}' is not valid JSON: ${error instanceof Error ? error.message : String(error)}`
1068
+ );
1069
+ }
1070
+ const entries = parsed.entries;
1071
+ if (typeof entries !== "object" || entries === null) {
1072
+ throw new Error(`TN_NATIVE_ASSET_MANIFEST_INVALID: '${manifestPath}' has no 'entries' object.`);
1073
+ }
1074
+ const rows = Object.entries(entries).map(
1075
+ ([logical, entry]) => [logical, entry ?? {}]
1076
+ );
1077
+ const ktx2 = rows.filter(([, entry]) => typeof entry.output === "string" && /\.ktx2$/iu.test(entry.output)).map(([logical]) => logical);
1078
+ if (ktx2.length > 0) {
1079
+ throw new Error(
1080
+ `TN_NATIVE_KTX2_UNSUPPORTED: ${target} cannot ship compiled KTX2 textures (${namedAssets(ktx2)}). The mobile native runtime has no WebAssembly and therefore no Basis transcoder, so nothing in the bundle can decode them. Replace or transcode the authored KTX2 source for mobile, or exclude it from mobile builds; keep compressed textures on the web target.`
1081
+ );
1082
+ }
1083
+ const compressedModels = rows.filter(
1084
+ ([, entry]) => (Array.isArray(entry.extensions) ? entry.extensions : []).some(
1085
+ (extension) => typeof extension === "string" && COMPRESSED_MODEL_EXTENSIONS.includes(extension)
1086
+ )
1087
+ ).map(([logical]) => logical);
1088
+ if (compressedModels.length > 0) {
1089
+ throw new Error(
1090
+ `TN_NATIVE_MESH_COMPRESSION_UNSUPPORTED: ${target} cannot ship compressed model geometry (${namedAssets(compressedModels)}). The mobile native runtime has no WebAssembly and therefore no Meshopt or Draco decoder. Native compilation keeps shared images and decoder-free model rewrites while omitting Meshopt output; rebuild the native target, or keep compressed models on the web target.`
1091
+ );
1092
+ }
1093
+ }
1094
+ var UI_ENTRY = path2.join("src", "ui", "main.tsx");
1095
+ var UI_PAGE_PREFIX = ".threenative-ui-";
1096
+ async function buildUi(cwd, config) {
1097
+ const output = path2.join(cwd, ".threenative", "build", "ui");
1098
+ const entry = path2.join(cwd, UI_ENTRY);
1099
+ try {
1100
+ if (!(await stat(entry)).isFile()) throw new Error("not a file");
1101
+ } catch {
1102
+ throw new Error(
1103
+ `TN_UI_ENTRY_MISSING: ui.renderer is "${config.ui.renderer}" but ${UI_ENTRY} does not exist. It is the entry every platform's web view loads; create it, or set ui.renderer to "native".`
1104
+ );
1105
+ }
1106
+ const buildRoot = path2.join(cwd, ".threenative", "build");
1107
+ await mkdir(buildRoot, { recursive: true });
1108
+ const page = path2.join(cwd, `${UI_PAGE_PREFIX}${randomUUID()}.html`);
1109
+ await writeFile(
1110
+ page,
1111
+ [
1112
+ "<!doctype html>",
1113
+ '<html lang="en">',
1114
+ " <head>",
1115
+ ' <meta charset="utf-8" />',
1116
+ ' <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />',
1117
+ " <style>html,body,#tn-ui{margin:0;height:100%;background:transparent}</style>",
1118
+ " </head>",
1119
+ " <body>",
1120
+ ' <div id="tn-ui"></div>',
1121
+ ` <script type="module" src="/${UI_ENTRY.split(path2.sep).join("/")}"></script>`,
1122
+ " </body>",
1123
+ "</html>"
1124
+ ].join("\n")
1125
+ );
1126
+ const driver = path2.join(buildRoot, "build-ui.mjs");
1127
+ await writeFile(driver, uiBuildDriver(cwd, page, output));
1128
+ try {
1129
+ await run(process.execPath, [driver], cwd);
1130
+ } finally {
1131
+ await rm(page, { force: true });
1132
+ }
1133
+ const generatedPage = path2.join(output, path2.basename(page));
1134
+ const index = path2.join(output, "index.html");
1135
+ await rename(generatedPage, index);
1136
+ return output;
1137
+ }
1138
+ function uiBuildDriver(cwd, page, output) {
1139
+ const literal = (value) => JSON.stringify(value);
1140
+ return `${[
1141
+ 'import { build, loadConfigFromFile, mergeConfig } from "vite";',
1142
+ "",
1143
+ `const root = ${literal(cwd)};`,
1144
+ `const loaded = await loadConfigFromFile({ command: "build", mode: "production" }, undefined, root);`,
1145
+ "await build(",
1146
+ " mergeConfig(loaded?.config ?? {}, {",
1147
+ " root,",
1148
+ ' base: "./",',
1149
+ // The UI is a HUD page, not the game: it must not carry the game's `public/`. Vite copies
1150
+ // `publicDir` into every build it runs, and this output is packaged *beside* the game's own
1151
+ // assets — so every model, texture and sound shipped twice. One game's APK came to 361 MB, of
1152
+ // which 97.6 MB was a second copy of its own 97.3 MB asset directory, six copies of one 11 MB
1153
+ // weapon among them. Nothing in `src/ui/` reads those files; it reaches the game through
1154
+ // published state and intents.
1155
+ " publicDir: false,",
1156
+ // One React, one ReactDOM, whatever the import graph looks like. The UI entry resolves its
1157
+ // peers beside the game while a linked package — `@threenative/ui`, or anything else pnpm
1158
+ // symlinks in — resolves the same bare specifiers beside itself, so a hook-owning package
1159
+ // installed outside the project brings a second physical copy into the bundle. React's
1160
+ // dispatcher lives in module state, so the copy the entry did not mount reads null and the
1161
+ // first `useState` on the phone throws `Cannot read properties of null`. `mergeConfig`
1162
+ // concatenates arrays, so a project that deduped its own packages keeps every one of them.
1163
+ ' resolve: { dedupe: ["react", "react-dom"] },',
1164
+ " build: {",
1165
+ ` outDir: ${literal(output)},`,
1166
+ " emptyOutDir: true,",
1167
+ ` rollupOptions: { input: { index: ${literal(page)} } },`,
1168
+ " },",
1169
+ " }),",
1170
+ ");"
1171
+ ].join("\n")}
1172
+ `;
1173
+ }
557
1174
  async function buildWeb(cwd, viteArgs = []) {
558
- await loadConfig(cwd);
1175
+ const config = await loadConfig(cwd);
1176
+ await compileAssets({ config: config.assets, cwd, platform: "web" });
559
1177
  await run(executable(cwd, "vite"), ["build", ...viteArgs], cwd);
560
1178
  }
561
1179
  async function nativeEntry(cwd, config) {
562
1180
  const relative = (config ?? await loadConfig(cwd)).nativeEntry;
563
- const entry = path.resolve(cwd, relative);
1181
+ const entry = path2.resolve(cwd, relative);
564
1182
  try {
565
1183
  if (!(await stat(entry)).isFile()) throw new Error("not a file");
566
1184
  } catch {
@@ -568,27 +1186,63 @@ async function nativeEntry(cwd, config) {
568
1186
  }
569
1187
  return entry;
570
1188
  }
571
- async function writePackagingConfig(cwd, config) {
572
- const directory = path.join(cwd, ".threenative", "build");
573
- await mkdir(directory, { recursive: true });
1189
+ function resolvePackagingConfig(cwd, config) {
1190
+ const resolve = (value) => value === void 0 ? void 0 : path2.resolve(cwd, value);
574
1191
  const artifact = {
575
1192
  ...config,
576
1193
  app: {
577
1194
  ...config.app,
578
- ...config.app.icon === void 0 ? {} : { icon: path.resolve(cwd, config.app.icon) }
1195
+ ...config.app.icon === void 0 ? {} : { icon: path2.resolve(cwd, config.app.icon) },
1196
+ ...config.app.icons === void 0 ? {} : {
1197
+ icons: {
1198
+ ...config.app.icons.android === void 0 ? {} : {
1199
+ android: {
1200
+ ...config.app.icons.android.foreground === void 0 ? {} : { foreground: path2.resolve(cwd, config.app.icons.android.foreground) },
1201
+ ...config.app.icons.android.background === void 0 ? {} : { background: config.app.icons.android.background },
1202
+ ...config.app.icons.android.monochrome === void 0 ? {} : { monochrome: path2.resolve(cwd, config.app.icons.android.monochrome) }
1203
+ }
1204
+ },
1205
+ ...config.app.icons.ios === void 0 ? {} : {
1206
+ ios: {
1207
+ ...config.app.icons.ios.dark === void 0 ? {} : { dark: path2.resolve(cwd, config.app.icons.ios.dark) },
1208
+ ...config.app.icons.ios.tinted === void 0 ? {} : { tinted: path2.resolve(cwd, config.app.icons.ios.tinted) }
1209
+ }
1210
+ },
1211
+ ...config.app.icons.web === void 0 ? {} : {
1212
+ web: {
1213
+ ...config.app.icons.web.favicon === void 0 ? {} : { favicon: resolve(config.app.icons.web.favicon) },
1214
+ ...config.app.icons.web.maskable === void 0 ? {} : { maskable: resolve(config.app.icons.web.maskable) },
1215
+ ...config.app.icons.web.monochrome === void 0 ? {} : { monochrome: resolve(config.app.icons.web.monochrome) },
1216
+ ...config.app.icons.web.appleTouch === void 0 ? {} : { appleTouch: resolve(config.app.icons.web.appleTouch) }
1217
+ }
1218
+ }
1219
+ }
1220
+ }
1221
+ },
1222
+ ...config.bootSplash === void 0 ? {} : {
1223
+ bootSplash: {
1224
+ ...config.bootSplash,
1225
+ ...config.bootSplash.image === void 0 ? {} : { image: path2.resolve(cwd, config.bootSplash.image) }
1226
+ }
579
1227
  }
580
1228
  };
581
- const output = path.join(directory, "config.json");
1229
+ return artifact;
1230
+ }
1231
+ async function writePackagingConfig(cwd, config) {
1232
+ const directory = path2.join(cwd, ".threenative", "build");
1233
+ await mkdir(directory, { recursive: true });
1234
+ const artifact = resolvePackagingConfig(cwd, config);
1235
+ const output = path2.join(directory, "config.json");
582
1236
  await writeFile(output, `${JSON.stringify(artifact, null, 2)}
583
1237
  `);
584
1238
  return output;
585
1239
  }
586
1240
  async function bundleNative(cwd, runtimeRoot, entry, target) {
587
- const output = path.join(cwd, ".threenative", "build", "game.js");
1241
+ const output = path2.join(cwd, ".threenative", "build", "game.js");
588
1242
  await run(
589
1243
  process.execPath,
590
1244
  [
591
- path.join(runtimeRoot, "scripts", "bundle.mjs"),
1245
+ path2.join(runtimeRoot, "scripts", "bundle.mjs"),
592
1246
  "--project",
593
1247
  cwd,
594
1248
  "--entry",
@@ -602,32 +1256,30 @@ async function bundleNative(cwd, runtimeRoot, entry, target) {
602
1256
  );
603
1257
  return output;
604
1258
  }
605
- function installedRuntime(runtimeRoot) {
606
- if (process.env.THREENATIVE_RUNTIME_BINARY)
607
- return path.resolve(process.env.THREENATIVE_RUNTIME_BINARY);
608
- const key = `${process.platform}-${process.arch}`;
609
- const filename = process.platform === "win32" ? "threenative-runtime.exe" : "threenative-runtime";
610
- return path.join(runtimeRoot, "prebuilt", key, filename);
611
- }
612
- async function buildNative(target, cwd) {
1259
+ async function buildNative(target, cwd, allowSourceBuild = false) {
613
1260
  const config = await loadConfig(cwd);
1261
+ assertNativeUiRendererCompatible(target, config.ui.renderer);
1262
+ await compileAssets({ config: config.assets, cwd, platform: target });
1263
+ await assertNativeAssetsCompatible(cwd, target, config);
614
1264
  const entry = await nativeEntry(cwd, config);
615
1265
  const orientation = config.display.orientation;
616
1266
  const configPath = await writePackagingConfig(cwd, config);
617
1267
  const runtimeRoot = packageRoot(cwd, "@threenative/runtime-native");
618
1268
  const bundle = await bundleNative(cwd, runtimeRoot, entry, target);
619
1269
  await assertNativeBundleCompatible(bundle, target);
620
- const assets = path.join(cwd, "public");
1270
+ const assets = path2.join(cwd, "public");
1271
+ const ui = config.ui.renderer === "web" ? await buildUi(cwd, config) : void 0;
621
1272
  if (target === "ios") {
622
- const output2 = path.join(cwd, "dist-native", `${await projectName(cwd)}.app`);
1273
+ const output2 = path2.join(cwd, "dist-native", `${await projectName(cwd)}.app`);
623
1274
  await run(
624
1275
  process.execPath,
625
1276
  [
626
- path.join(runtimeRoot, "scripts", "package-ios.mjs"),
1277
+ path2.join(runtimeRoot, "scripts", "package-ios.mjs"),
627
1278
  "--bundle",
628
1279
  bundle,
629
1280
  "--assets",
630
1281
  assets,
1282
+ ...ui === void 0 ? [] : ["--ui", ui],
631
1283
  "--orientation",
632
1284
  orientation,
633
1285
  "--config",
@@ -640,15 +1292,17 @@ async function buildNative(target, cwd) {
640
1292
  return;
641
1293
  }
642
1294
  if (target === "android") {
643
- const output2 = path.join(cwd, "dist-native", `${await projectName(cwd)}.apk`);
1295
+ const output2 = path2.join(cwd, "dist-native", `${await projectName(cwd)}.apk`);
644
1296
  await run(
645
1297
  process.execPath,
646
1298
  [
647
- path.join(runtimeRoot, "scripts", "package-android.mjs"),
1299
+ path2.join(runtimeRoot, "scripts", "package-android.mjs"),
1300
+ ...allowSourceBuild ? ["--allow-source-build"] : [],
648
1301
  "--bundle",
649
1302
  bundle,
650
1303
  "--assets",
651
1304
  assets,
1305
+ ...ui === void 0 ? [] : ["--ui", ui],
652
1306
  "--orientation",
653
1307
  orientation,
654
1308
  "--config",
@@ -660,19 +1314,19 @@ async function buildNative(target, cwd) {
660
1314
  );
661
1315
  return;
662
1316
  }
663
- const output = path.join(cwd, "dist-native", await projectName(cwd));
1317
+ const output = path2.join(cwd, "dist-native", await projectName(cwd));
664
1318
  await run(
665
1319
  process.execPath,
666
1320
  [
667
- path.join(runtimeRoot, "scripts", "package-desktop.mjs"),
1321
+ path2.join(runtimeRoot, "scripts", "package-desktop.mjs"),
668
1322
  "--bundle",
669
1323
  bundle,
670
1324
  "--assets",
671
1325
  assets,
1326
+ ...ui === void 0 ? [] : ["--ui", ui],
672
1327
  "--config",
673
1328
  configPath,
674
- "--runtime",
675
- installedRuntime(runtimeRoot),
1329
+ ...process.env.THREENATIVE_RUNTIME_BINARY ? ["--runtime", path2.resolve(process.env.THREENATIVE_RUNTIME_BINARY)] : [],
676
1330
  "--output",
677
1331
  output
678
1332
  ],
@@ -680,7 +1334,10 @@ async function buildNative(target, cwd) {
680
1334
  );
681
1335
  }
682
1336
  async function build(options) {
683
- const cwd = path.resolve(options.cwd ?? process.cwd());
1337
+ if (options.allowSourceBuild && options.target !== "android") {
1338
+ throw new Error("--allow-source-build is supported only for --target android.");
1339
+ }
1340
+ const cwd = path2.resolve(options.cwd ?? process.cwd());
684
1341
  if (options.target === "web") await buildWeb(cwd, options.viteArgs);
685
1342
  else {
686
1343
  if ((options.viteArgs?.length ?? 0) > 0) {
@@ -688,7 +1345,7 @@ async function build(options) {
688
1345
  `${options.target} build does not accept ${options.viteArgs?.join(" ")}. iOS output is simulator-only; device signing remains OPEN.`
689
1346
  );
690
1347
  }
691
- await buildNative(options.target, cwd);
1348
+ await buildNative(options.target, cwd, options.allowSourceBuild === true);
692
1349
  }
693
1350
  }
694
1351
  function buildHelp() {
@@ -697,6 +1354,7 @@ function buildHelp() {
697
1354
  "",
698
1355
  "Options:",
699
1356
  " --target <target> Choose web, desktop, android, or ios (default: web).",
1357
+ " --allow-source-build Explicitly allow Android maintainer source compilation.",
700
1358
  " --help Show this help."
701
1359
  ].join("\n")}
702
1360
  `;
@@ -710,40 +1368,1776 @@ function parseBuildArgs(argv) {
710
1368
  if (!TARGETS.includes(value)) {
711
1369
  throw new Error(`Unknown build target '${value ?? ""}'. Choose ${TARGETS.join(", ")}.`);
712
1370
  }
1371
+ const allowSourceBuild = argv.includes("--allow-source-build");
1372
+ if (allowSourceBuild && value !== "android") {
1373
+ throw new Error("--allow-source-build is supported only for --target android.");
1374
+ }
713
1375
  const consumed = /* @__PURE__ */ new Set([0]);
1376
+ if (allowSourceBuild) {
1377
+ for (let index = 1; index < argv.length; index += 1) {
1378
+ if (argv[index] === "--allow-source-build") consumed.add(index);
1379
+ }
1380
+ }
714
1381
  if (targetIndex !== -1) {
715
1382
  consumed.add(targetIndex);
716
1383
  consumed.add(targetIndex + 1);
717
1384
  }
718
1385
  return {
719
1386
  target: value,
1387
+ ...allowSourceBuild ? { allowSourceBuild: true } : {},
720
1388
  viteArgs: argv.filter((_, index) => !consumed.has(index))
721
1389
  };
722
1390
  }
723
1391
 
724
- // src/threenative.ts
725
- function cliHelp(command) {
726
- if (command === "build") return buildHelp();
727
- return `${[
728
- "Usage: threenative build [options]",
729
- "",
730
- "Commands:",
731
- " build Build web or native output.",
732
- "",
733
- "Run 'threenative build --help' for command-specific help."
734
- ].join("\n")}
735
- `;
1392
+ // src/commands.ts
1393
+ var threenativeCommands = ["build", "doctor"];
1394
+ var commandSummaries = {
1395
+ build: "Build web or native output.",
1396
+ doctor: "Check this project and report what would break a build."
1397
+ };
1398
+ var BLENDER_VERSION_FLOOR = Object.freeze({ major: 4, minor: 2 });
1399
+ var BLENDER_INSTALL_GUIDANCE = Object.freeze({
1400
+ linux: "sudo snap install blender --classic (or your distribution's package, or https://www.blender.org/download/)",
1401
+ macos: "brew install --cask blender (or https://www.blender.org/download/)",
1402
+ windows: "winget install --id BlenderFoundation.Blender (or https://www.blender.org/download/)"
1403
+ });
1404
+ function floorString() {
1405
+ return `${BLENDER_VERSION_FLOOR.major}.${BLENDER_VERSION_FLOOR.minor}`;
736
1406
  }
737
- function helpFor(argv) {
738
- const command = argv[0];
739
- if (command === void 0 || command.startsWith("-")) return cliHelp();
740
- if (command === "build") return cliHelp("build");
741
- throw new Error(`Unknown threenative command '${command}'.
742
- ${cliHelp()}`);
1407
+ function installCommandFor(platformName = platform()) {
1408
+ if (platformName === "darwin") return BLENDER_INSTALL_GUIDANCE.macos;
1409
+ if (platformName === "win32") return BLENDER_INSTALL_GUIDANCE.windows;
1410
+ return BLENDER_INSTALL_GUIDANCE.linux;
743
1411
  }
744
- async function main(argv = process.argv.slice(2)) {
745
- if (argv.includes("--help") || argv.includes("-h")) {
746
- process.stdout.write(helpFor(argv));
1412
+ function executableFile(candidate) {
1413
+ try {
1414
+ if (!existsSync(candidate) || !statSync(candidate).isFile()) return false;
1415
+ accessSync(candidate, constants.X_OK);
1416
+ return true;
1417
+ } catch {
1418
+ return false;
1419
+ }
1420
+ }
1421
+ function binaryNames(platformName) {
1422
+ return platformName === "win32" ? ["blender.exe", "blender.com"] : ["blender"];
1423
+ }
1424
+ function pathCandidates(environment, platformName) {
1425
+ const raw = environment.PATH ?? environment.Path ?? "";
1426
+ if (raw.trim().length === 0) return [];
1427
+ return raw.split(path2.delimiter).filter((directory) => directory.trim().length > 0).flatMap((directory) => binaryNames(platformName).map((name) => path2.join(directory, name)));
1428
+ }
1429
+ function conventionalCandidates(platformName, home) {
1430
+ if (platformName === "darwin") {
1431
+ return [
1432
+ "/Applications/Blender.app/Contents/MacOS/Blender",
1433
+ path2.join(home, "Applications/Blender.app/Contents/MacOS/Blender")
1434
+ ];
1435
+ }
1436
+ if (platformName === "win32") {
1437
+ const roots = [
1438
+ process.env.ProgramFiles ?? "C:\\Program Files",
1439
+ process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)"
1440
+ ];
1441
+ return roots.flatMap(
1442
+ (root) => ["5.2", "5.1", "5.0", "4.5", "4.2"].map(
1443
+ (release) => path2.join(root, "Blender Foundation", `Blender ${release}`, "blender.exe")
1444
+ )
1445
+ );
1446
+ }
1447
+ return [
1448
+ "/usr/bin/blender",
1449
+ "/usr/local/bin/blender",
1450
+ "/snap/bin/blender",
1451
+ "/var/lib/flatpak/exports/bin/org.blender.Blender",
1452
+ path2.join(home, ".local/bin/blender")
1453
+ ];
1454
+ }
1455
+ function parseBlenderVersion(output) {
1456
+ const match = /^Blender\s+(\d+\.\d+(?:\.\d+)?)/mu.exec(output);
1457
+ return match?.[1];
1458
+ }
1459
+ function compareToFloor(version) {
1460
+ const [major = 0, minor = 0] = version.split(".").map((part) => Number.parseInt(part, 10));
1461
+ if (Number.isNaN(major) || Number.isNaN(minor)) return false;
1462
+ if (major !== BLENDER_VERSION_FLOOR.major) return major > BLENDER_VERSION_FLOOR.major;
1463
+ return minor >= BLENDER_VERSION_FLOOR.minor;
1464
+ }
1465
+ var probeBlenderVersion = (binary) => {
1466
+ try {
1467
+ const output = execFileSync(binary, ["--version"], {
1468
+ encoding: "utf8",
1469
+ stdio: ["ignore", "pipe", "pipe"],
1470
+ timeout: 3e4
1471
+ });
1472
+ return parseBlenderVersion(output);
1473
+ } catch {
1474
+ return void 0;
1475
+ }
1476
+ };
1477
+ function resolveBlender(environment = process.env, options = {}) {
1478
+ const platformName = options.platform ?? platform();
1479
+ const home = options.home ?? environment.HOME ?? environment.USERPROFILE ?? homedir();
1480
+ const probeVersion = options.probeVersion ?? probeBlenderVersion;
1481
+ const minimumVersion = floorString();
1482
+ const install = BLENDER_INSTALL_GUIDANCE;
1483
+ const override = environment.THREENATIVE_BLENDER_PATH;
1484
+ if (override !== void 0 && override.trim().length > 0) {
1485
+ const candidate = path2.resolve(override.trim());
1486
+ if (!executableFile(candidate)) {
1487
+ return {
1488
+ available: false,
1489
+ cause: "blender-unreadable",
1490
+ detail: `THREENATIVE_BLENDER_PATH points at '${candidate}', which is not an executable file.`,
1491
+ install,
1492
+ minimumVersion,
1493
+ path: candidate
1494
+ };
1495
+ }
1496
+ return classify(candidate, probeVersion, minimumVersion, install);
1497
+ }
1498
+ const candidates = [
1499
+ ...pathCandidates(environment, platformName),
1500
+ ...conventionalCandidates(platformName, home)
1501
+ ];
1502
+ for (const candidate of candidates) {
1503
+ if (!executableFile(candidate)) continue;
1504
+ const classified = classify(candidate, probeVersion, minimumVersion, install);
1505
+ if (classified.cause !== "blender-unreadable") return classified;
1506
+ }
1507
+ return {
1508
+ available: false,
1509
+ cause: "blender-missing",
1510
+ detail: `No Blender ${minimumVersion} or newer was found. Set THREENATIVE_BLENDER_PATH, or install it: ${installCommandFor(platformName)}`,
1511
+ install,
1512
+ minimumVersion
1513
+ };
1514
+ }
1515
+ function classify(binary, probeVersion, minimumVersion, install) {
1516
+ const version = probeVersion(binary);
1517
+ if (version === void 0) {
1518
+ return {
1519
+ available: false,
1520
+ cause: "blender-unreadable",
1521
+ detail: `'${binary}' did not report a Blender version.`,
1522
+ install,
1523
+ minimumVersion,
1524
+ path: binary
1525
+ };
1526
+ }
1527
+ if (!compareToFloor(version)) {
1528
+ return {
1529
+ available: false,
1530
+ cause: "blender-too-old",
1531
+ detail: `Blender ${version} at '${binary}' is older than the supported floor ${minimumVersion}.`,
1532
+ install,
1533
+ minimumVersion,
1534
+ path: binary,
1535
+ version
1536
+ };
1537
+ }
1538
+ return {
1539
+ available: true,
1540
+ detail: `Blender ${version} at '${binary}'.`,
1541
+ install,
1542
+ minimumVersion,
1543
+ path: binary,
1544
+ version
1545
+ };
1546
+ }
1547
+
1548
+ // ../core/mcp/servers.mjs
1549
+ var MCP_SERVERS = Object.freeze({
1550
+ "threenative-assets": Object.freeze({
1551
+ command: "node",
1552
+ args: Object.freeze(["./node_modules/@threenative/core/mcp/assets.mjs"]),
1553
+ // Entries rather than an object literal: these are environment variable names, not identifiers,
1554
+ // and written as property names they read as names the naming rule must judge.
1555
+ env: Object.freeze(
1556
+ Object.fromEntries([
1557
+ ["ASSET_DOWNLOAD_DIR", "./public/assets"],
1558
+ ["AUDIO_DOWNLOAD_DIR", "./public/audio"]
1559
+ ])
1560
+ )
1561
+ }),
1562
+ "threenative-sculpt": Object.freeze({
1563
+ command: "node",
1564
+ args: Object.freeze(["./node_modules/@threenative/core/mcp/sculpt.mjs"])
1565
+ }),
1566
+ "threenative-engine": Object.freeze({
1567
+ command: "node",
1568
+ args: Object.freeze(["./node_modules/@threenative/core/mcp/engine.mjs"])
1569
+ }),
1570
+ // Drives an installed Blender headlessly so a downloaded .fbx becomes a GLB. It ships no
1571
+ // Blender and probes for one only when a tool is called, so a project that never converts a
1572
+ // model pays nothing for having this server wired.
1573
+ "threenative-blender": Object.freeze({
1574
+ command: "node",
1575
+ args: Object.freeze(["./node_modules/@threenative/core/mcp/blender.mjs"])
1576
+ })
1577
+ });
1578
+ var MCP_PACKAGES = Object.freeze({
1579
+ assets: Object.freeze({ name: "threenative-asset-mcp", version: "0.8.0" }),
1580
+ sculpt: Object.freeze({ name: "threenative-sculpt-mcp", version: "0.1.1" }),
1581
+ engine: Object.freeze({ name: "threenative-engine-mcp", version: "0.2.1" }),
1582
+ blender: Object.freeze({ name: "threenative-blender-mcp", version: "0.1.1" })
1583
+ });
1584
+ var SERVER_FORMATS = Object.freeze({
1585
+ // Claude Code (`.mcp.json`), Cursor and the Gemini CLI all read this one.
1586
+ mcpServers: Object.freeze({
1587
+ key: "mcpServers",
1588
+ entry: (server) => ({
1589
+ command: server.command,
1590
+ args: [...server.args],
1591
+ ...server.env === void 0 ? {} : { env: { ...server.env } }
1592
+ })
1593
+ }),
1594
+ // VS Code names the table `servers` and requires an explicit transport per server.
1595
+ vscode: Object.freeze({
1596
+ key: "servers",
1597
+ entry: (server) => ({
1598
+ type: "stdio",
1599
+ command: server.command,
1600
+ args: [...server.args],
1601
+ ...server.env === void 0 ? {} : { env: { ...server.env } }
1602
+ })
1603
+ }),
1604
+ // opencode folds the command and its arguments into one array and spells the environment
1605
+ // `environment`. A server it does not mark enabled is written down and never started.
1606
+ opencode: Object.freeze({
1607
+ key: "mcp",
1608
+ entry: (server) => ({
1609
+ type: "local",
1610
+ command: [server.command, ...server.args],
1611
+ enabled: true,
1612
+ ...server.env === void 0 ? {} : { environment: { ...server.env } }
1613
+ })
1614
+ }),
1615
+ // Zed calls them context servers and needs `source: "custom"` to accept a command of our own.
1616
+ zed: Object.freeze({
1617
+ key: "context_servers",
1618
+ entry: (server) => ({
1619
+ source: "custom",
1620
+ command: server.command,
1621
+ args: [...server.args],
1622
+ ...server.env === void 0 ? {} : { env: { ...server.env } }
1623
+ })
1624
+ })
1625
+ });
1626
+ Object.freeze(Object.keys(SERVER_FORMATS));
1627
+ function codexServerBlock(name, server) {
1628
+ const args = server.args.map((argument) => JSON.stringify(argument)).join(", ");
1629
+ const lines = [
1630
+ `[mcp_servers.${name}]`,
1631
+ `command = ${JSON.stringify(server.command)}`,
1632
+ `args = [${args}]`
1633
+ ];
1634
+ if (server.env !== void 0) {
1635
+ lines.push("", `[mcp_servers.${name}.env]`);
1636
+ for (const [key, value] of Object.entries(server.env)) {
1637
+ lines.push(`${key} = ${JSON.stringify(value)}`);
1638
+ }
1639
+ }
1640
+ return lines.join("\n");
1641
+ }
1642
+ Object.freeze(
1643
+ Object.entries(MCP_SERVERS).map(
1644
+ ([name, server]) => Object.freeze({ body: codexServerBlock(name, server), name })
1645
+ )
1646
+ );
1647
+
1648
+ // ../core/mcp/install.mjs
1649
+ var MCP_HOSTS = Object.freeze([
1650
+ Object.freeze({
1651
+ id: "claude-code",
1652
+ label: "Claude Code",
1653
+ file: ".mcp.json",
1654
+ format: "mcpServers"
1655
+ }),
1656
+ Object.freeze({ id: "codex", label: "Codex", file: ".codex/config.toml", format: "codex" }),
1657
+ Object.freeze({ id: "cursor", label: "Cursor", file: ".cursor/mcp.json", format: "mcpServers" }),
1658
+ Object.freeze({ id: "vscode", label: "VS Code", file: ".vscode/mcp.json", format: "vscode" }),
1659
+ Object.freeze({
1660
+ id: "gemini-cli",
1661
+ label: "Gemini CLI",
1662
+ file: ".gemini/settings.json",
1663
+ format: "mcpServers"
1664
+ }),
1665
+ Object.freeze({
1666
+ id: "opencode",
1667
+ label: "opencode",
1668
+ file: "opencode.json",
1669
+ format: "opencode",
1670
+ // Written only when this installer creates the file, so a second install still reports
1671
+ // "unchanged" rather than rewriting a config the user has since edited.
1672
+ seed: Object.freeze({ $schema: "https://opencode.ai/config.json" })
1673
+ }),
1674
+ Object.freeze({ id: "zed", label: "Zed", file: ".zed/settings.json", format: "zed" })
1675
+ ]);
1676
+
1677
+ // src/mcp-servers.ts
1678
+ function serverEntryPath(server) {
1679
+ const entry = server.args[0];
1680
+ if (entry === void 0) {
1681
+ throw new Error("TN_MCP_TABLE: an MCP server entry declares no shim to launch.");
1682
+ }
1683
+ return entry;
1684
+ }
1685
+ function serverPackageKey(server) {
1686
+ const entry = serverEntryPath(server);
1687
+ const file = entry.slice(entry.lastIndexOf("/") + 1);
1688
+ return file.endsWith(".mjs") ? file.slice(0, -".mjs".length) : file;
1689
+ }
1690
+
1691
+ // src/doctor.ts
1692
+ var ANDROID_RELEASE_SIGNING_ENV = [
1693
+ "ORG_GRADLE_PROJECT_threenativeKeystore",
1694
+ "ORG_GRADLE_PROJECT_threenativeKeystoreAlias",
1695
+ "ORG_GRADLE_PROJECT_threenativeKeystorePassword",
1696
+ "ORG_GRADLE_PROJECT_threenativeKeyPassword"
1697
+ ];
1698
+ var DEFAULT_NATIVE_ENTRY = "src/game.ts";
1699
+ var RUNTIME_PACKAGE = "@threenative/runtime-native";
1700
+ var PLAYTEST_BINARY = "threenative-playtest";
1701
+ var ANDROID_JDK_MAJOR = 17;
1702
+ var ANDROID_COMPILE_SDK = 35;
1703
+ var CORE_PACKAGE_NAME = "@threenative/core";
1704
+ var CORE_PACKAGE_VERSION = "0.3.1";
1705
+ var CORE_RESOLVED_SERVERS = /* @__PURE__ */ new Set([
1706
+ "threenative-engine",
1707
+ "threenative-blender"
1708
+ ]);
1709
+ var MCP_SERVER_SPECS = Object.entries(MCP_SERVERS).map(
1710
+ ([configName, server]) => {
1711
+ const resolvesToCore = CORE_RESOLVED_SERVERS.has(configName);
1712
+ const key = serverPackageKey(server);
1713
+ const declared = MCP_PACKAGES[key];
1714
+ if (!resolvesToCore && declared === void 0) {
1715
+ throw new Error(
1716
+ `TN_DOCTOR_MCP_TABLE: MCP server '${configName}' launches '${key}.mjs', which MCP_PACKAGES does not declare.`
1717
+ );
1718
+ }
1719
+ return {
1720
+ configName,
1721
+ expectedArgs: serverEntryPath(server),
1722
+ packageName: resolvesToCore ? CORE_PACKAGE_NAME : declared.name,
1723
+ version: resolvesToCore ? CORE_PACKAGE_VERSION : declared.version
1724
+ };
1725
+ }
1726
+ );
1727
+ var ASSET_DOWNLOAD_DIRECTORIES = ["public/assets", "public/audio"];
1728
+ var BLENDER_SOURCE_SUFFIXES = [".fbx", ".blend", ".obj", ".dae"];
1729
+ var BLENDER_PACKAGE = (() => {
1730
+ const declared = MCP_PACKAGES.blender;
1731
+ if (declared === void 0) {
1732
+ throw new Error("TN_DOCTOR_MCP_TABLE: MCP_PACKAGES declares no 'blender' package.");
1733
+ }
1734
+ return declared;
1735
+ })();
1736
+ var BLENDER_SERVER = (() => {
1737
+ const entry = Object.entries(MCP_SERVERS).find(
1738
+ ([, server]) => serverPackageKey(server) === "blender"
1739
+ );
1740
+ if (entry === void 0) {
1741
+ throw new Error("TN_DOCTOR_MCP_TABLE: no configured MCP server launches blender.mjs.");
1742
+ }
1743
+ return entry[0];
1744
+ })();
1745
+ var MCP_HOST_TABLE = MCP_HOSTS;
1746
+ var MANUAL_GLOBAL_MCP_HOSTS = Object.freeze([
1747
+ "Windsurf",
1748
+ "Cline",
1749
+ "Amp",
1750
+ "the JetBrains assistants"
1751
+ ]);
1752
+ for (const host of MCP_HOSTS) {
1753
+ const claimed = MANUAL_GLOBAL_MCP_HOSTS.find(
1754
+ (name) => host.label.toLowerCase() === name.toLowerCase()
1755
+ );
1756
+ if (claimed !== void 0) {
1757
+ throw new Error(
1758
+ `TN_DOCTOR_MCP_TABLE: '${claimed}' is wired project-scoped now, so doctor must stop calling it machine-wide only.`
1759
+ );
1760
+ }
1761
+ }
1762
+ var SHAPE_VERIFIABLE_HOSTS = MCP_HOSTS.filter(
1763
+ ({ format }) => format === "mcpServers"
1764
+ );
1765
+ function detectX11Compositor(environment = process.env) {
1766
+ if (environment.DISPLAY === void 0) return void 0;
1767
+ try {
1768
+ const output = execFileSync("xprop", ["-root", "_NET_WM_CM_S0"], {
1769
+ encoding: "utf8",
1770
+ env: { ...environment },
1771
+ stdio: ["ignore", "pipe", "pipe"]
1772
+ });
1773
+ return /window id\s*#/u.test(output);
1774
+ } catch (error) {
1775
+ return error.code === "ENOENT" ? void 0 : false;
1776
+ }
1777
+ }
1778
+ function probeDesktopOverlay(environment = process.env, compositor = detectX11Compositor) {
1779
+ const wayland = environment.WAYLAND_DISPLAY !== void 0 || environment.XDG_SESSION_TYPE === "wayland";
1780
+ if (wayland) {
1781
+ return {
1782
+ detail: "the transparent container could not be created on this Wayland/Xwayland session",
1783
+ fix: "Run the desktop target under an X11 session (for example SDL_VIDEODRIVER=x11) or use the web UI target.",
1784
+ status: "fail"
1785
+ };
1786
+ }
1787
+ if (environment.DISPLAY === void 0) {
1788
+ return {
1789
+ detail: "no display is available, so the desktop overlay could not be probed",
1790
+ fix: "Run doctor in the display session that will host the desktop target.",
1791
+ status: "warn"
1792
+ };
1793
+ }
1794
+ const present = compositor(environment);
1795
+ if (present === true) {
1796
+ return {
1797
+ detail: "an X11 compositing manager owns _NET_WM_CM_S0; transparent overlay alpha can blend",
1798
+ fix: "",
1799
+ status: "ok"
1800
+ };
1801
+ }
1802
+ if (present === false) {
1803
+ return {
1804
+ detail: "no compositing manager is running, so nothing would blend the overlay",
1805
+ fix: "Start a compositing manager or run the desktop target under a composited X11 session.",
1806
+ status: "fail"
1807
+ };
1808
+ }
1809
+ return {
1810
+ detail: "the X11 compositor probe could not run, so overlay transparency is unknown",
1811
+ fix: "Install xprop and rerun doctor in the desktop display session.",
1812
+ status: "warn"
1813
+ };
1814
+ }
1815
+ function record(value) {
1816
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
1817
+ }
1818
+ function declaredDependencies(packageJson) {
1819
+ const manifest = record(packageJson);
1820
+ if (manifest === void 0) return [];
1821
+ const names = /* @__PURE__ */ new Set();
1822
+ for (const field of ["dependencies", "devDependencies", "optionalDependencies"]) {
1823
+ for (const name of Object.keys(record(manifest[field]) ?? {})) {
1824
+ if (name.startsWith("@threenative/")) names.add(name);
1825
+ }
1826
+ }
1827
+ return [...names].sort();
1828
+ }
1829
+ function nativeEntryFrom(config) {
1830
+ const configured = record(config)?.nativeEntry;
1831
+ return typeof configured === "string" && configured.length > 0 ? configured : DEFAULT_NATIVE_ENTRY;
1832
+ }
1833
+ function usesDesktopOverlay(config) {
1834
+ return record(record(config)?.ui)?.renderer === "web";
1835
+ }
1836
+ function nativeEntryCompat(value) {
1837
+ const entry = record(value)?.nativeEntry;
1838
+ return typeof entry === "string" && entry.length > 0 ? { nativeEntry: entry } : void 0;
1839
+ }
1840
+ function resolvePackageDirectoryFrom(start, name) {
1841
+ let directory = path2.resolve(start);
1842
+ while (true) {
1843
+ const candidate = path2.join(directory, "node_modules", name);
1844
+ if (existsSync(path2.join(candidate, "package.json"))) return candidate;
1845
+ const parent = path2.dirname(directory);
1846
+ if (parent === directory) return void 0;
1847
+ directory = parent;
1848
+ }
1849
+ }
1850
+ function resolvePackageDirectory(snapshot, name) {
1851
+ if (snapshot.resolvePackageDirectory !== void 0) {
1852
+ return snapshot.resolvePackageDirectory(name);
1853
+ }
1854
+ if (snapshot.projectRoot === void 0) return void 0;
1855
+ const direct = resolvePackageDirectoryFrom(snapshot.projectRoot, name);
1856
+ if (direct !== void 0) return direct;
1857
+ const core = resolvePackageDirectoryFrom(snapshot.projectRoot, "@threenative/core");
1858
+ if (core === void 0) return void 0;
1859
+ try {
1860
+ return resolvePackageDirectoryFrom(realpathSync(core), name);
1861
+ } catch {
1862
+ return void 0;
1863
+ }
1864
+ }
1865
+ function resolveBinaryFrom(start, name) {
1866
+ let directory = path2.resolve(start);
1867
+ while (true) {
1868
+ const binDirectory = path2.join(directory, "node_modules", ".bin");
1869
+ const candidates = process.platform === "win32" ? [path2.join(binDirectory, `${name}.cmd`), path2.join(binDirectory, name)] : [path2.join(binDirectory, name)];
1870
+ const found = candidates.find((candidate) => existsSync(candidate));
1871
+ if (found !== void 0) return found;
1872
+ const parent = path2.dirname(directory);
1873
+ if (parent === directory) return void 0;
1874
+ directory = parent;
1875
+ }
1876
+ }
1877
+ function expectedMcpServer(spec) {
1878
+ return {
1879
+ command: "node",
1880
+ args: [spec.expectedArgs],
1881
+ ...spec.configName === "threenative-assets" ? {
1882
+ env: Object.fromEntries([
1883
+ ["ASSET_DOWNLOAD_DIR", "./public/assets"],
1884
+ ["AUDIO_DOWNLOAD_DIR", "./public/audio"]
1885
+ ])
1886
+ } : {}
1887
+ };
1888
+ }
1889
+ function mcpServerMatches(spec, value) {
1890
+ const server = record(value);
1891
+ if (server === void 0 || server.command !== "node") return false;
1892
+ if (!Array.isArray(server.args) || server.args.length !== 1 || server.args[0] !== spec.expectedArgs)
1893
+ return false;
1894
+ if (spec.configName !== "threenative-assets") return true;
1895
+ const env = record(server.env);
1896
+ return env?.ASSET_DOWNLOAD_DIR === "./public/assets" && env.AUDIO_DOWNLOAD_DIR === "./public/audio";
1897
+ }
1898
+ function readServerTable(snapshot, host) {
1899
+ const source = snapshot.readText(host.file);
1900
+ if (source === void 0) return { detail: `${host.file} could not be read` };
1901
+ let parsed;
1902
+ try {
1903
+ parsed = JSON.parse(source);
1904
+ } catch (error) {
1905
+ return {
1906
+ detail: `${host.file} is invalid JSON: ${error instanceof Error ? error.message : String(error)}`
1907
+ };
1908
+ }
1909
+ const servers = record(record(parsed)?.mcpServers);
1910
+ return servers === void 0 ? { detail: `${host.file} is missing an object-valued mcpServers property` } : { servers };
1911
+ }
1912
+ function mcpConfig(snapshot) {
1913
+ const present = SHAPE_VERIFIABLE_HOSTS.filter(({ file }) => snapshot.files.has(file));
1914
+ if (present.length === 0) return { kind: "missing" };
1915
+ const malformed = [];
1916
+ const parsed = [];
1917
+ for (const host of present) {
1918
+ const result = readServerTable(snapshot, host);
1919
+ if ("servers" in result) parsed.push({ host, servers: result.servers });
1920
+ else malformed.push(result.detail);
1921
+ }
1922
+ if (parsed.length === 0) return { detail: malformed.join("; "), kind: "malformed" };
1923
+ const wired = ({ servers }) => MCP_SERVER_SPECS.filter(({ configName }) => servers[configName] !== void 0).length;
1924
+ const best = parsed.reduce((left, right) => wired(right) > wired(left) ? right : left);
1925
+ return { host: best.host, kind: "ready", servers: best.servers };
1926
+ }
1927
+ function mcpServerCheck(snapshot, spec, value, file) {
1928
+ const name = `capability search: ${spec.packageName}`;
1929
+ if (value === void 0) {
1930
+ return {
1931
+ detail: `${spec.configName} is missing from ${file}; expected ${spec.packageName}@${spec.version}`,
1932
+ fix: `Restore the server entry in ${file}, which @threenative/core generates.`,
1933
+ name,
1934
+ status: "fail"
1935
+ };
1936
+ }
1937
+ if (!mcpServerMatches(spec, value)) {
1938
+ return {
1939
+ detail: `${spec.configName} is hand-edited or malformed; expected ${JSON.stringify(expectedMcpServer(spec))}`,
1940
+ fix: `Restore the generated ${file} entry so the ThreeNative shim and asset directories remain wired.`,
1941
+ name,
1942
+ status: "fail"
1943
+ };
1944
+ }
1945
+ if (snapshot.projectRoot !== void 0 && !existsSync(path2.resolve(snapshot.projectRoot, spec.expectedArgs))) {
1946
+ return {
1947
+ detail: `${spec.configName} points at missing ${spec.expectedArgs}; @threenative/core is not providing the configured server shim`,
1948
+ fix: "Install @threenative/core again so the generated MCP server entry exists.",
1949
+ name,
1950
+ status: "fail"
1951
+ };
1952
+ }
1953
+ const health = snapshot.mcpServerHealth?.get(spec.configName);
1954
+ if (health?.status === "fail") {
1955
+ return {
1956
+ detail: `${spec.configName} is configured, but ${health.detail}`,
1957
+ fix: `Reinstall @threenative/core and ${spec.packageName}, then rerun doctor.`,
1958
+ name,
1959
+ status: "fail"
1960
+ };
1961
+ }
1962
+ const packageDirectory = resolvePackageDirectory(snapshot, spec.packageName);
1963
+ if (packageDirectory === void 0) {
1964
+ return {
1965
+ detail: `${spec.configName} is reachable by npx only: ${spec.packageName}@${spec.version} is not installed (npx --yes ${spec.packageName}@${spec.version})`,
1966
+ fix: `Install ${spec.packageName}@${spec.version} when this server is needed, or use the npx fallback named above.`,
1967
+ name,
1968
+ status: "warn"
1969
+ };
1970
+ }
1971
+ const manifest = readJsonSync(path2.join(packageDirectory, "package.json"));
1972
+ const installedVersion = record(manifest)?.version;
1973
+ if (typeof installedVersion !== "string") {
1974
+ return {
1975
+ detail: `${spec.configName} resolves ${spec.packageName}, but its package.json has no version`,
1976
+ fix: `Reinstall ${spec.packageName}@${spec.version}.`,
1977
+ name,
1978
+ status: "fail"
1979
+ };
1980
+ }
1981
+ if (installedVersion !== spec.version) {
1982
+ return {
1983
+ detail: `${spec.configName} resolves ${spec.packageName}@${installedVersion}; the ${file} fallback is ${spec.packageName}@${spec.version}`,
1984
+ fix: `Install ${spec.packageName}@${spec.version} so the capability contract is version-matched.`,
1985
+ name,
1986
+ status: "warn"
1987
+ };
1988
+ }
1989
+ return {
1990
+ detail: `${spec.configName} resolves ${spec.packageName}@${installedVersion}${health === void 0 ? "" : `; ${health.detail}`}`,
1991
+ name,
1992
+ status: "ok"
1993
+ };
1994
+ }
1995
+ function probeMcpServer(projectRoot, spec) {
1996
+ const initialize = JSON.stringify({
1997
+ id: 1,
1998
+ jsonrpc: "2.0",
1999
+ method: "initialize",
2000
+ params: {
2001
+ capabilities: {},
2002
+ clientInfo: { name: "threenative-doctor", version: "0.3.1" },
2003
+ protocolVersion: "2025-06-18"
2004
+ }
2005
+ });
2006
+ const initialized = JSON.stringify({
2007
+ jsonrpc: "2.0",
2008
+ method: "notifications/initialized"
2009
+ });
2010
+ const list = JSON.stringify({ id: 2, jsonrpc: "2.0", method: "tools/list", params: {} });
2011
+ const result = spawnSync("node", [spec.expectedArgs], {
2012
+ cwd: projectRoot,
2013
+ encoding: "utf8",
2014
+ env: {
2015
+ ...process.env,
2016
+ ...spec.configName === "threenative-assets" ? Object.fromEntries([
2017
+ ["ASSET_DOWNLOAD_DIR", "./public/assets"],
2018
+ ["AUDIO_DOWNLOAD_DIR", "./public/audio"]
2019
+ ]) : {}
2020
+ },
2021
+ input: `${initialize}
2022
+ ${initialized}
2023
+ ${list}
2024
+ `,
2025
+ maxBuffer: 4 * 1024 * 1024,
2026
+ timeout: 5e3
2027
+ });
2028
+ if (result.error !== void 0 || result.status !== 0) {
2029
+ const stderr = result.stderr.trim();
2030
+ const reason = result.error?.message ?? (stderr.length > 0 ? stderr : `exited ${result.status}`);
2031
+ return { detail: `its MCP transport failed to start: ${reason}`, status: "fail" };
2032
+ }
2033
+ const responses = result.stdout.split(/\r?\n/u).flatMap((line) => {
2034
+ try {
2035
+ return [JSON.parse(line)];
2036
+ } catch {
2037
+ return [];
2038
+ }
2039
+ }).map(record).filter((value) => value !== void 0);
2040
+ const initializeResponse = responses.find(({ id }) => id === 1);
2041
+ const listResponse = responses.find(({ id }) => id === 2);
2042
+ const tools = record(listResponse?.result)?.tools;
2043
+ if (record(initializeResponse?.result) === void 0 || !Array.isArray(tools) || tools.length === 0) {
2044
+ return {
2045
+ detail: "its MCP transport did not complete initialize and advertise tools",
2046
+ status: "fail"
2047
+ };
2048
+ }
2049
+ return { detail: `transport initialized and advertised ${tools.length} tool(s)`, status: "ok" };
2050
+ }
2051
+ function mcpSummary(serverChecks, host) {
2052
+ const failed = serverChecks.filter(({ status: status2 }) => status2 === "fail").length;
2053
+ const warned = serverChecks.filter(({ status: status2 }) => status2 === "warn").length;
2054
+ const status = failed > 0 ? "fail" : warned > 0 ? "warn" : "ok";
2055
+ return {
2056
+ // Transport, and only transport. A server that starts is a server that answers `tools/list`;
2057
+ // whether the application one of its tools drives is installed is a separate fact, reported by
2058
+ // `model conversion`. The old wording — "all three configured MCP servers resolve" — claimed a
2059
+ // complete authoring toolchain, and had also been wrong about the count since the fourth
2060
+ // server landed.
2061
+ detail: status === "ok" ? `all ${serverChecks.length} servers in ${host.file} resolve; transport only, external applications are reported separately` : `${serverChecks.length - failed - warned} of ${serverChecks.length} server(s) in ${host.file} resolve; ${warned} reachable by npx only; ${failed} malformed or missing; transport only, external applications are reported separately`,
2062
+ fix: status === "ok" ? void 0 : "Inspect the per-server capability search checks below.",
2063
+ name: "capability search",
2064
+ status
2065
+ };
2066
+ }
2067
+ function capabilitySearchChecks(snapshot) {
2068
+ const config = mcpConfig(snapshot);
2069
+ const verifiable = SHAPE_VERIFIABLE_HOSTS.map(({ file }) => file).join(", ");
2070
+ if (config.kind === "missing" || config.kind === "malformed") {
2071
+ const elsewhere = MCP_HOST_TABLE.filter((host) => hostWiring(snapshot, host) === "wired").map(
2072
+ ({ label }) => label
2073
+ );
2074
+ const cause = config.kind === "missing" ? `no server table this check can validate (${verifiable})` : `no readable server table: ${config.detail}`;
2075
+ if (elsewhere.length > 0) {
2076
+ return [
2077
+ {
2078
+ detail: `${cause}; ${elsewhere.join(", ")} carry the servers in a format only 'editor activation' reads`,
2079
+ fix: `Reinstall @threenative/core if you also want ${verifiable} wired; an agent in ${elsewhere[0]} already has capability search.`,
2080
+ name: "capability search",
2081
+ status: "warn"
2082
+ }
2083
+ ];
2084
+ }
2085
+ return [
2086
+ {
2087
+ detail: config.kind === "missing" ? `no ${verifiable}, so an agent here cannot search engine capabilities and will hand-write what exists` : cause,
2088
+ fix: config.kind === "missing" ? "Restore the .mcp.json a scaffolded project ships, which wires the ThreeNative MCP servers." : "Restore a valid generated config, preserving any unrelated servers.",
2089
+ name: "capability search",
2090
+ status: "fail"
2091
+ }
2092
+ ];
2093
+ }
2094
+ const serverChecks = MCP_SERVER_SPECS.map(
2095
+ (spec) => mcpServerCheck(snapshot, spec, config.servers[spec.configName], config.host.file)
2096
+ );
2097
+ return [mcpSummary(serverChecks, config.host), ...serverChecks];
2098
+ }
2099
+ function readJsonSync(file) {
2100
+ try {
2101
+ return JSON.parse(readFileSync(file, "utf8"));
2102
+ } catch {
2103
+ return void 0;
2104
+ }
2105
+ }
2106
+ function addCommandTargets(targets, value) {
2107
+ if (typeof value !== "string") return;
2108
+ for (const match of value.matchAll(/--target(?:=|\s+)(web|desktop|android|ios)\b/gu)) {
2109
+ const target = match[1];
2110
+ if (target !== void 0) targets.add(target);
2111
+ }
2112
+ }
2113
+ function addConfiguredTargets(targets, value) {
2114
+ if (Array.isArray(value)) {
2115
+ for (const target of value) if (typeof target === "string") targets.add(target);
2116
+ } else if (typeof value === "string") {
2117
+ targets.add(value);
2118
+ }
2119
+ }
2120
+ function configuredTargets(snapshot) {
2121
+ const targets = /* @__PURE__ */ new Set();
2122
+ const packageScripts = record(record(snapshot.packageJson)?.scripts);
2123
+ for (const value of Object.values(packageScripts ?? {})) addCommandTargets(targets, value);
2124
+ const configRecord = record(snapshot.config);
2125
+ for (const key of ["targets", "nativeTargets"])
2126
+ addConfiguredTargets(targets, configRecord?.[key]);
2127
+ return [...targets];
2128
+ }
2129
+ function directoryCanBeWritten(snapshot, relative) {
2130
+ if (snapshot.directoryWritable !== void 0) return snapshot.directoryWritable(relative);
2131
+ if (snapshot.projectRoot === void 0) return void 0;
2132
+ const root = path2.resolve(snapshot.projectRoot);
2133
+ let candidate = path2.resolve(root, relative);
2134
+ if (candidate !== root && !candidate.startsWith(`${root}${path2.sep}`)) return false;
2135
+ while (candidate !== root && !existsSync(candidate)) candidate = path2.dirname(candidate);
2136
+ if (!existsSync(candidate)) return false;
2137
+ try {
2138
+ if (!statSync(candidate).isDirectory()) return false;
2139
+ accessSync(candidate, constants.W_OK);
2140
+ return true;
2141
+ } catch {
2142
+ return false;
2143
+ }
2144
+ }
2145
+ function assetPipelineCheck(snapshot) {
2146
+ const details = [];
2147
+ let status = "ok";
2148
+ for (const directory of ASSET_DOWNLOAD_DIRECTORIES) {
2149
+ const writable = directoryCanBeWritten(snapshot, directory);
2150
+ if (writable === false) {
2151
+ details.push(`${directory} is not writable and cannot receive MCP downloads`);
2152
+ status = "warn";
2153
+ } else if (writable === true) {
2154
+ details.push(`${directory} exists or can be created`);
2155
+ } else {
2156
+ details.push(`${directory} was not probed in this in-memory snapshot`);
2157
+ }
2158
+ }
2159
+ const assets = record(record(snapshot.config)?.assets) ?? {};
2160
+ const mobileTargets = configuredTargets(snapshot).filter(
2161
+ (target) => target === "android" || target === "ios"
2162
+ );
2163
+ if (mobileTargets.length > 0) {
2164
+ const textures = assets.textures;
2165
+ if (textures !== "none") {
2166
+ details.push(
2167
+ `TN_NATIVE_KTX2_UNSUPPORTED: assets.textures compiles textures for ${mobileTargets.join("/")}; mobile native targets require assets.textures to be "none"`
2168
+ );
2169
+ status = "warn";
2170
+ }
2171
+ const models = assets.models;
2172
+ if (models !== "none") {
2173
+ details.push(
2174
+ `TN_NATIVE_MESH_COMPRESSION_UNSUPPORTED: assets.models compiles model geometry for ${mobileTargets.join("/")}; mobile native targets require assets.models to be "none"`
2175
+ );
2176
+ status = "warn";
2177
+ }
2178
+ }
2179
+ return {
2180
+ detail: details.join("; "),
2181
+ ...status === "ok" ? {} : {
2182
+ fix: "Make public/assets and public/audio writable, and disable compiled assets for Android/iOS native builds."
2183
+ },
2184
+ name: "asset pipeline",
2185
+ status
2186
+ };
2187
+ }
2188
+ function androidToolchainFacts(probe) {
2189
+ const details = [];
2190
+ const blockers = [];
2191
+ let status = probe.status ?? "ok";
2192
+ if (probe.jdkVersion === void 0 || probe.jdkMajor === void 0) {
2193
+ const blocker = `JDK not found; Android builds require JDK ${ANDROID_JDK_MAJOR}`;
2194
+ details.push(blocker);
2195
+ blockers.push(blocker);
2196
+ status = "warn";
2197
+ } else if (probe.jdkMajor !== ANDROID_JDK_MAJOR) {
2198
+ const blocker = `JDK ${probe.jdkVersion} found; Android builds support JDK ${ANDROID_JDK_MAJOR} only`;
2199
+ details.push(blocker);
2200
+ blockers.push(blocker);
2201
+ status = "warn";
2202
+ } else {
2203
+ details.push(`JDK ${probe.jdkVersion} found (supported JDK ${ANDROID_JDK_MAJOR})`);
2204
+ }
2205
+ if (probe.sdkVersion === void 0) {
2206
+ const blocker = `Android SDK platform android-${ANDROID_COMPILE_SDK} not found`;
2207
+ details.push(blocker);
2208
+ blockers.push(blocker);
2209
+ status = "warn";
2210
+ } else {
2211
+ details.push(`Android SDK platform android-${ANDROID_COMPILE_SDK} ${probe.sdkVersion} found`);
2212
+ }
2213
+ return { blockers, details, status };
2214
+ }
2215
+ function androidToolchainStatus(probe) {
2216
+ const { details, status } = androidToolchainFacts(probe);
2217
+ return {
2218
+ detail: details.join("; "),
2219
+ fix: status === "ok" ? void 0 : `Install Android SDK platform android-${ANDROID_COMPILE_SDK} and JDK ${ANDROID_JDK_MAJOR}, or set ANDROID_HOME or ANDROID_SDK_ROOT and JAVA_HOME (or put JDK ${ANDROID_JDK_MAJOR} on PATH).`,
2220
+ name: "android toolchain",
2221
+ status
2222
+ };
2223
+ }
2224
+ function playtestRunner(snapshot) {
2225
+ if (snapshot.playtestRunnerPath !== void 0) return snapshot.playtestRunnerPath;
2226
+ return snapshot.projectRoot === void 0 ? void 0 : resolveBinaryFrom(snapshot.projectRoot, PLAYTEST_BINARY);
2227
+ }
2228
+ function missingPlaytestCheck(snapshot) {
2229
+ return {
2230
+ detail: snapshot.projectRoot === void 0 ? "runner was not probed in this in-memory snapshot" : "threenative-playtest is missing from node_modules/.bin",
2231
+ fix: "Install the test runner: npm install -D @threenative/playtest, then rerun doctor.",
2232
+ name: "playtest",
2233
+ status: snapshot.projectRoot === void 0 ? "warn" : "fail"
2234
+ };
2235
+ }
2236
+ function childOutput(value) {
2237
+ const text = typeof value === "string" ? value : Buffer.isBuffer(value) ? value.toString("utf8") : void 0;
2238
+ const trimmed = text?.trim();
2239
+ return trimmed === void 0 || trimmed.length === 0 ? void 0 : trimmed;
2240
+ }
2241
+ function playtestFailureDetail(error) {
2242
+ const fields = record(error);
2243
+ const output = [childOutput(fields?.stderr), childOutput(fields?.stdout)].filter((value) => value !== void 0).join("\n");
2244
+ return output.length > 0 ? output : error instanceof Error ? error.message : String(error);
2245
+ }
2246
+ function playtestInvocation(runner, capturePath) {
2247
+ if (process.platform !== "win32" || !/\.cmd$/iu.test(runner)) {
2248
+ return {
2249
+ args: ["doctor", "--text", ...capturePath === void 0 ? [] : ["--capture", capturePath]],
2250
+ command: runner
2251
+ };
2252
+ }
2253
+ const command = process.env.ComSpec ?? process.env.COMSPEC ?? "cmd.exe";
2254
+ const capture = capturePath === void 0 ? "" : ` --capture "${capturePath.replaceAll('"', '\\"')}"`;
2255
+ return {
2256
+ args: ["/d", "/s", "/c", `"${runner}" doctor --text${capture}`],
2257
+ command
2258
+ };
2259
+ }
2260
+ function executePlaytestDoctor(runner, projectRoot, capturePath) {
2261
+ const invocation = playtestInvocation(runner, capturePath);
2262
+ return execFileSync(invocation.command, invocation.args, {
2263
+ cwd: projectRoot,
2264
+ encoding: "utf8",
2265
+ stdio: ["ignore", "pipe", "pipe"],
2266
+ timeout: 3e4
2267
+ });
2268
+ }
2269
+ function playtestCheck(snapshot, capturePath) {
2270
+ const runner = playtestRunner(snapshot);
2271
+ if (runner === void 0) return missingPlaytestCheck(snapshot);
2272
+ try {
2273
+ const output = snapshot.runPlaytestDoctor?.(capturePath) ?? executePlaytestDoctor(runner, snapshot.projectRoot, capturePath);
2274
+ const detail = output.trim();
2275
+ return {
2276
+ detail: detail.length === 0 ? "threenative-playtest doctor completed" : `threenative-playtest doctor completed:
2277
+ ${detail}`,
2278
+ name: "playtest",
2279
+ status: "ok"
2280
+ };
2281
+ } catch (error) {
2282
+ return {
2283
+ detail: `threenative-playtest doctor failed: ${playtestFailureDetail(error)}`,
2284
+ fix: "Run npx @threenative/playtest doctor --text directly and fix the first reported machine or browser blocker.",
2285
+ name: "playtest",
2286
+ status: "fail"
2287
+ };
2288
+ }
2289
+ }
2290
+ var APK_SIZE_RECORD = /^docs\/verification\/apk-size-(\d{4}-\d{2}-\d{2})\.md$/u;
2291
+ function parseApkSizeRecord(source) {
2292
+ const bytesMatch = source.match(/^\s*-\s*Rebuilt APK bytes:\s*\*\*(\d[\d,]*)\*\*\s*$/mu);
2293
+ const artifactMatch = source.match(/^\s*-\s*APK artifact:\s*`([^`]+)`\s*$/mu);
2294
+ const buildDirectoryMatch = source.match(/^\s*-\s*Build directory:\s*`([^`]+)`\s*$/mu);
2295
+ const sha256Match = source.match(/^\s*-\s*APK SHA-256:\s*`([0-9a-f]{64})`\s*$/imu);
2296
+ if (bytesMatch === null || artifactMatch === null || buildDirectoryMatch === null || sha256Match === null)
2297
+ return void 0;
2298
+ const bytesText = bytesMatch[1];
2299
+ const artifact = artifactMatch[1];
2300
+ const buildDirectory = buildDirectoryMatch[1];
2301
+ const sha256 = sha256Match[1];
2302
+ if (bytesText === void 0 || artifact === void 0 || buildDirectory === void 0 || sha256 === void 0)
2303
+ return void 0;
2304
+ const bytes = Number(bytesText.replaceAll(",", ""));
2305
+ if (!Number.isSafeInteger(bytes) || bytes <= 0) return void 0;
2306
+ if (artifact.length === 0 || buildDirectory.length === 0) return void 0;
2307
+ return { artifact, buildDirectory, bytes, sha256: sha256.toLowerCase() };
2308
+ }
2309
+ function sha256File(file) {
2310
+ const hash = createHash("sha256");
2311
+ const descriptor = openSync(file, "r");
2312
+ const buffer = Buffer.allocUnsafe(1024 * 1024);
2313
+ try {
2314
+ let bytesRead = 0;
2315
+ do {
2316
+ bytesRead = readSync(descriptor, buffer, 0, buffer.length, null);
2317
+ if (bytesRead > 0) hash.update(buffer.subarray(0, bytesRead));
2318
+ } while (bytesRead > 0);
2319
+ return hash.digest("hex");
2320
+ } finally {
2321
+ closeSync(descriptor);
2322
+ }
2323
+ }
2324
+ function evidencePath(snapshot, relative) {
2325
+ if (snapshot.projectRoot === void 0 || path2.isAbsolute(relative)) return void 0;
2326
+ const root = path2.resolve(snapshot.projectRoot);
2327
+ const resolved = path2.resolve(root, relative);
2328
+ return resolved === root || resolved.startsWith(`${root}${path2.sep}`) ? resolved : void 0;
2329
+ }
2330
+ function evidenceExists(snapshot, relative, directory) {
2331
+ const absolute = evidencePath(snapshot, relative);
2332
+ if (absolute !== void 0) {
2333
+ try {
2334
+ const stats = statSync(absolute);
2335
+ return directory ? stats.isDirectory() : stats.isFile();
2336
+ } catch {
2337
+ return false;
2338
+ }
2339
+ }
2340
+ return snapshot.files.has(relative);
2341
+ }
2342
+ function apkSizeCheck(snapshot) {
2343
+ const recordPath = [...snapshot.files].filter((file) => APK_SIZE_RECORD.test(file)).sort().at(-1);
2344
+ if (recordPath === void 0) return void 0;
2345
+ const source = snapshot.readText(recordPath);
2346
+ const record2 = source === void 0 ? void 0 : parseApkSizeRecord(source);
2347
+ if (record2 === void 0) {
2348
+ return {
2349
+ detail: `attribution record ${recordPath} is malformed; no APK total was trusted`,
2350
+ fix: "Regenerate the record with the APK artifact, SHA-256, build directory, and rebuilt byte total.",
2351
+ name: "APK size",
2352
+ status: "warn"
2353
+ };
2354
+ }
2355
+ if (!evidenceExists(snapshot, record2.buildDirectory, true)) {
2356
+ return {
2357
+ detail: `missing evidence \u2014 attribution record ${recordPath} names build directory ${record2.buildDirectory}, which is missing`,
2358
+ fix: "Rebuild the recorded Android variant before using its attribution total.",
2359
+ name: "APK size",
2360
+ status: "warn"
2361
+ };
2362
+ }
2363
+ const artifact = evidencePath(snapshot, record2.artifact);
2364
+ if (!evidenceExists(snapshot, record2.artifact, false) || artifact === void 0) {
2365
+ return {
2366
+ detail: `missing evidence \u2014 attribution record ${recordPath} names APK artifact ${record2.artifact}, which is missing`,
2367
+ fix: "Rebuild the recorded Android variant before using its attribution total.",
2368
+ name: "APK size",
2369
+ status: "warn"
2370
+ };
2371
+ }
2372
+ let actualBytes;
2373
+ let actualSha256;
2374
+ try {
2375
+ actualBytes = statSync(artifact).size;
2376
+ actualSha256 = sha256File(artifact);
2377
+ } catch {
2378
+ return {
2379
+ detail: `missing evidence \u2014 APK artifact ${record2.artifact} could not be read`,
2380
+ fix: "Rebuild the recorded Android variant before using its attribution total.",
2381
+ name: "APK size",
2382
+ status: "warn"
2383
+ };
2384
+ }
2385
+ if (actualBytes !== record2.bytes) {
2386
+ return {
2387
+ detail: `evidence differs \u2014 ${record2.artifact} is ${actualBytes.toLocaleString("en-US")} bytes, but ${recordPath} records a different total`,
2388
+ fix: "Regenerate the attribution record from this APK before trusting its rows.",
2389
+ name: "APK size",
2390
+ status: "warn"
2391
+ };
2392
+ }
2393
+ if (actualSha256 !== record2.sha256) {
2394
+ return {
2395
+ detail: `evidence differs \u2014 ${record2.artifact} has SHA-256 ${actualSha256}, but ${recordPath} records ${record2.sha256}`,
2396
+ fix: "Regenerate the attribution record from this APK before trusting its rows.",
2397
+ name: "APK size",
2398
+ status: "warn"
2399
+ };
2400
+ }
2401
+ return {
2402
+ detail: `last attributed APK: ${record2.bytes.toLocaleString("en-US")} bytes (${recordPath})`,
2403
+ name: "APK size",
2404
+ status: "ok"
2405
+ };
2406
+ }
2407
+ function dependencyChecks(snapshot) {
2408
+ const declared = declaredDependencies(snapshot.packageJson);
2409
+ const missing = declared.filter((name) => !snapshot.installedVersions.has(name));
2410
+ const installed = [...snapshot.installedVersions].sort(([a], [b]) => a.localeCompare(b));
2411
+ const versions = new Set(installed.map(([, version]) => version));
2412
+ return [
2413
+ missing.length > 0 ? {
2414
+ detail: `declared but not installed: ${missing.join(", ")}`,
2415
+ fix: "Install dependencies: 'npm install' (or the package manager this project uses).",
2416
+ name: "dependencies",
2417
+ status: "fail"
2418
+ } : {
2419
+ detail: declared.length === 0 ? "no @threenative packages declared" : `${declared.length} installed`,
2420
+ name: "dependencies",
2421
+ status: "ok"
2422
+ },
2423
+ versions.size > 1 ? {
2424
+ detail: `@threenative packages disagree on version: ${installed.map(([name, version]) => `${name}@${version}`).join(", ")}`,
2425
+ fix: "Install one version across all @threenative packages; mixed versions break at the package boundary.",
2426
+ name: "versions",
2427
+ status: "fail"
2428
+ } : {
2429
+ detail: versions.size === 0 ? "nothing installed to compare" : `all at ${[...versions][0]}`,
2430
+ name: "versions",
2431
+ status: "ok"
2432
+ }
2433
+ ];
2434
+ }
2435
+ function nativeEntryCheck(snapshot) {
2436
+ const entry = nativeEntryFrom(snapshot.config);
2437
+ if (!snapshot.files.has(entry)) {
2438
+ return {
2439
+ detail: `the portable entry ${entry} does not exist, so a native build has nothing to start`,
2440
+ fix: `Create ${entry} with a default game export, or point threenative.nativeEntry at the file that has one.`,
2441
+ name: "native entry",
2442
+ status: "fail"
2443
+ };
2444
+ }
2445
+ const source = snapshot.readText(entry) ?? "";
2446
+ if (!/export\s+default\b/u.test(source)) {
2447
+ return {
2448
+ detail: `${entry} has no default export; the native host rejects it with TN_NATIVE_ENTRY_NO_DEFAULT`,
2449
+ fix: `Add 'export default' to the game defined in ${entry}.`,
2450
+ name: "native entry",
2451
+ status: "fail"
2452
+ };
2453
+ }
2454
+ return { detail: `${entry} default-exports a game`, name: "native entry", status: "ok" };
2455
+ }
2456
+ function nativeRuntimeKey() {
2457
+ return `${process.platform}-${process.arch}`;
2458
+ }
2459
+ function nativeRuntimeFilename() {
2460
+ return process.platform === "win32" ? "threenative-runtime.exe" : "threenative-runtime";
2461
+ }
2462
+ function nativeRuntimeCheck(snapshot) {
2463
+ const key = nativeRuntimeKey();
2464
+ if (snapshot.runtimeRoot === void 0 || snapshot.readRuntimeText === void 0) {
2465
+ return snapshot.installedVersions.has(RUNTIME_PACKAGE) ? {
2466
+ detail: `unavailable \u2014 ${RUNTIME_PACKAGE} is installed but its package root could not be resolved`,
2467
+ fix: "Reinstall dependencies so the native runtime package resolves from node_modules.",
2468
+ name: "native runtime",
2469
+ status: "fail"
2470
+ } : {
2471
+ detail: "unknown \u2014 no install status recorded",
2472
+ fix: "Install @threenative/runtime-native before building a native target.",
2473
+ name: "native runtime",
2474
+ status: "warn"
2475
+ };
2476
+ }
2477
+ const statusText = snapshot.readRuntimeText("prebuilt/install-status.json");
2478
+ if (statusText === void 0) {
2479
+ return {
2480
+ detail: "unknown \u2014 no install status recorded",
2481
+ fix: "Run npm install so the runtime install hook can record its result.",
2482
+ name: "native runtime",
2483
+ status: "warn"
2484
+ };
2485
+ }
2486
+ let status;
2487
+ try {
2488
+ const parsed = JSON.parse(statusText);
2489
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
2490
+ throw new Error("status is not an object");
2491
+ status = parsed;
2492
+ } catch (error) {
2493
+ return {
2494
+ detail: `unavailable \u2014 install status is malformed: ${error instanceof Error ? error.message : String(error)}`,
2495
+ fix: "Remove node_modules/@threenative/runtime-native and run npm install again.",
2496
+ name: "native runtime",
2497
+ status: "fail"
2498
+ };
2499
+ }
2500
+ if (status.ok !== true) {
2501
+ const reason = typeof status.reason === "string" ? status.reason : "the install hook recorded no reason";
2502
+ return {
2503
+ detail: `unavailable \u2014 ${key}: ${reason}`,
2504
+ fix: "Fix the recorded prebuilt download failure, then run npm install again.",
2505
+ name: "native runtime",
2506
+ status: "fail"
2507
+ };
2508
+ }
2509
+ if (status.key !== key) {
2510
+ return {
2511
+ detail: `unavailable \u2014 install status is for ${String(status.key ?? "an unknown target")}, not ${key}`,
2512
+ fix: "Remove the runtime package and run npm install on this platform.",
2513
+ name: "native runtime",
2514
+ status: "fail"
2515
+ };
2516
+ }
2517
+ const installedVersion = snapshot.installedVersions.get(RUNTIME_PACKAGE);
2518
+ if (status.version !== installedVersion) {
2519
+ return {
2520
+ detail: `unavailable \u2014 install status version ${String(status.version ?? "is missing")} does not match installed runtime ${String(installedVersion ?? "with no version")}`,
2521
+ fix: "Remove the runtime package and run npm install to refresh its prebuilt status.",
2522
+ name: "native runtime",
2523
+ status: "fail"
2524
+ };
2525
+ }
2526
+ if (snapshot.runtimeManifestUrl === void 0) {
2527
+ return {
2528
+ detail: "unavailable \u2014 the installed runtime release URL contract could not be loaded",
2529
+ fix: "Reinstall @threenative/runtime-native so scripts/install-prebuilt.mjs is present.",
2530
+ name: "native runtime",
2531
+ status: "fail"
2532
+ };
2533
+ }
2534
+ if (status.url !== snapshot.runtimeManifestUrl) {
2535
+ return {
2536
+ detail: `unavailable \u2014 install status release URL ${String(status.url ?? "is missing")} does not match ${snapshot.runtimeManifestUrl}`,
2537
+ fix: "Remove the runtime package and run npm install to fetch the current release manifest.",
2538
+ name: "native runtime",
2539
+ status: "fail"
2540
+ };
2541
+ }
2542
+ const binary = `prebuilt/${key}/${nativeRuntimeFilename()}`;
2543
+ const exists = snapshot.runtimeFileExists?.(binary) ?? existsSync(path2.join(snapshot.runtimeRoot, binary));
2544
+ if (!exists) {
2545
+ return {
2546
+ detail: `unavailable \u2014 ${key} prebuilt binary is missing`,
2547
+ fix: "Run npm install again to restore the native runtime prebuilt.",
2548
+ name: "native runtime",
2549
+ status: "fail"
2550
+ };
2551
+ }
2552
+ return { detail: `available (${key})`, name: "native runtime", status: "ok" };
2553
+ }
2554
+ function javaVersion(output) {
2555
+ const match = output.match(/version\s+["']([^"']+)["']/iu);
2556
+ const version = match?.[1];
2557
+ if (version === void 0) return void 0;
2558
+ const majorMatch = version.startsWith("1.") ? version.match(/^1\.(\d+)/u) : version.match(/^(\d+)/u);
2559
+ const majorText = majorMatch?.[1];
2560
+ const major = majorText === void 0 ? Number.NaN : Number(majorText);
2561
+ return Number.isSafeInteger(major) ? { major, version } : void 0;
2562
+ }
2563
+ function androidSdkVersion(root) {
2564
+ const sourceProperties = path2.join(
2565
+ root,
2566
+ "platforms",
2567
+ `android-${ANDROID_COMPILE_SDK}`,
2568
+ "source.properties"
2569
+ );
2570
+ try {
2571
+ const source = readFileSync(sourceProperties, "utf8");
2572
+ const match = source.match(/^Pkg\.Revision\s*=\s*(\S+)/mu);
2573
+ return match?.[1];
2574
+ } catch {
2575
+ return void 0;
2576
+ }
2577
+ }
2578
+ function probeAndroidToolchain(environment = process.env) {
2579
+ const javaHome = environment.JAVA_HOME?.trim() || void 0;
2580
+ const java = javaHome === void 0 ? "java" : path2.join(javaHome, "bin", process.platform === "win32" ? "java.exe" : "java");
2581
+ let jdkMajor;
2582
+ let jdkVersion;
2583
+ try {
2584
+ const result = spawnSync(java, ["-version"], {
2585
+ encoding: "utf8",
2586
+ env: { ...environment },
2587
+ stdio: ["ignore", "pipe", "pipe"],
2588
+ timeout: 5e3
2589
+ });
2590
+ const parsed = javaVersion(`${result.stdout ?? ""}${result.stderr ?? ""}`);
2591
+ jdkMajor = parsed?.major;
2592
+ jdkVersion = parsed?.version;
2593
+ } catch {
2594
+ }
2595
+ const sdkCandidates = [
2596
+ environment.ANDROID_HOME,
2597
+ environment.ANDROID_SDK_ROOT,
2598
+ path2.join(homedir(), "Android", "Sdk")
2599
+ ].map((candidate) => candidate?.trim()).filter((candidate) => candidate !== void 0 && candidate.length > 0);
2600
+ const sdkRoot = sdkCandidates.find((candidate) => existsSync(candidate));
2601
+ return {
2602
+ ...jdkMajor === void 0 ? {} : { jdkMajor },
2603
+ ...jdkVersion === void 0 ? {} : { jdkVersion },
2604
+ ...sdkRoot === void 0 ? {} : { sdkVersion: androidSdkVersion(sdkRoot) }
2605
+ };
2606
+ }
2607
+ function runtimeFileAvailable(snapshot, relative) {
2608
+ if (snapshot.runtimeRoot === void 0) return false;
2609
+ return snapshot.runtimeFileExists?.(relative) ?? existsSync(path2.join(snapshot.runtimeRoot, relative));
2610
+ }
2611
+ function androidTargetCheck(snapshot) {
2612
+ if (!runtimeFileAvailable(snapshot, "scripts/package-android.mjs")) {
2613
+ return {
2614
+ detail: "unavailable \u2014 @threenative/runtime-native has no Android packager",
2615
+ name: "target android",
2616
+ status: snapshot.runtimeRoot === void 0 ? "warn" : "fail"
2617
+ };
2618
+ }
2619
+ const androidToolchain = snapshot.androidToolchain ?? (snapshot.projectRoot === void 0 ? void 0 : probeAndroidToolchain());
2620
+ const toolchain = androidToolchain === void 0 ? void 0 : androidToolchainStatus(androidToolchain);
2621
+ return {
2622
+ detail: toolchain === void 0 ? "available \u2014 runtime packager installed; Android toolchain was not probed in this in-memory snapshot" : `available \u2014 runtime packager installed; ${toolchain.detail}`,
2623
+ ...toolchain?.fix === void 0 ? {} : { fix: toolchain.fix },
2624
+ name: "target android",
2625
+ status: toolchain?.status ?? "ok"
2626
+ };
2627
+ }
2628
+ function iosTargetCheck(snapshot) {
2629
+ const iosPackager = runtimeFileAvailable(snapshot, "scripts/package-ios.mjs");
2630
+ const iosHost = process.platform === "darwin" && process.arch === "arm64";
2631
+ if (iosHost && iosPackager) {
2632
+ return {
2633
+ detail: "available \u2014 darwin-arm64 simulator packager installed",
2634
+ name: "target ios",
2635
+ status: "ok"
2636
+ };
2637
+ }
2638
+ return {
2639
+ detail: iosHost ? "unavailable \u2014 @threenative/runtime-native has no iOS packager" : `unavailable \u2014 iOS simulator packaging requires darwin-arm64; received ${process.platform}-${process.arch}`,
2640
+ name: "target ios",
2641
+ status: iosHost ? "fail" : "warn"
2642
+ };
2643
+ }
2644
+ function requestedBuildBlockers(snapshot, request, nativeRuntime) {
2645
+ const blockers = [];
2646
+ if (request.target === "web") {
2647
+ if (!snapshot.files.has("src/main.ts")) blockers.push("src/main.ts is missing");
2648
+ return blockers;
2649
+ }
2650
+ if (nativeRuntime.status !== "ok")
2651
+ blockers.push(nativeRuntime.detail.replace(/^(?:unavailable|unknown) — /u, ""));
2652
+ const nativeEntry2 = nativeEntryCheck(snapshot);
2653
+ if (nativeEntry2.status === "fail") blockers.push(nativeEntry2.detail);
2654
+ if (request.target === "desktop") {
2655
+ const overlay = snapshot.desktopOverlay;
2656
+ if (overlay?.status === "fail") blockers.push(overlay.detail);
2657
+ return blockers;
2658
+ }
2659
+ if (request.target === "ios") {
2660
+ if (process.platform !== "darwin" || process.arch !== "arm64")
2661
+ blockers.push(
2662
+ `iOS packaging requires darwin-arm64; this host is ${process.platform}-${process.arch}`
2663
+ );
2664
+ else if (!runtimeFileAvailable(snapshot, "scripts/package-ios.mjs"))
2665
+ blockers.push(`${RUNTIME_PACKAGE} has no iOS packager`);
2666
+ return blockers;
2667
+ }
2668
+ if (!runtimeFileAvailable(snapshot, "scripts/package-android.mjs"))
2669
+ blockers.push(`${RUNTIME_PACKAGE} has no Android packager`);
2670
+ const androidToolchain = snapshot.androidToolchain ?? (snapshot.projectRoot === void 0 ? void 0 : probeAndroidToolchain());
2671
+ if (androidToolchain === void 0) blockers.push("the Android toolchain was not probed");
2672
+ else blockers.push(...androidToolchainFacts(androidToolchain).blockers);
2673
+ if (request.mode === "release") {
2674
+ const environment = snapshot.environment ?? {};
2675
+ const missing = ANDROID_RELEASE_SIGNING_ENV.filter(
2676
+ (name) => (environment[name] ?? "").trim().length === 0
2677
+ );
2678
+ if (missing.length > 0)
2679
+ blockers.push(`release signing inputs are not set: ${missing.join(", ")}`);
2680
+ }
2681
+ return blockers;
2682
+ }
2683
+ function requestedBuildCheck(snapshot, request, nativeRuntime) {
2684
+ const { target } = request;
2685
+ if (target === void 0) return void 0;
2686
+ const scope = `${target}${request.mode === void 0 ? "" : ` ${request.mode}`}`;
2687
+ const blockers = requestedBuildBlockers(snapshot, { ...request, target }, nativeRuntime);
2688
+ if (blockers.length === 0)
2689
+ return { detail: `buildable \u2014 ${scope}`, name: "requested build", status: "ok" };
2690
+ return {
2691
+ detail: `not buildable \u2014 ${scope}: ${blockers.join("; ")}`,
2692
+ fix: target === "android" ? `Install JDK ${ANDROID_JDK_MAJOR} and Android SDK platform android-${ANDROID_COMPILE_SDK}, reinstall ${RUNTIME_PACKAGE} so its prebuilt downloads${request.mode === "release" ? `, and export ${ANDROID_RELEASE_SIGNING_ENV.join(", ")} from the game's build environment` : ""}.` : `Resolve the cause above, then run 'threenative doctor --target ${target}' again.`,
2693
+ name: "requested build",
2694
+ status: "fail"
2695
+ };
2696
+ }
2697
+ var TARGET_PREREQUISITE_OWNERS = Object.freeze(
2698
+ {
2699
+ "desktop overlay": Object.freeze(["desktop"]),
2700
+ // Its own words are "so a native build has nothing to start"; a web build starts src/main.ts.
2701
+ "native entry": Object.freeze(["android", "desktop", "ios"]),
2702
+ "native runtime": Object.freeze(["android", "desktop", "ios"])
2703
+ }
2704
+ );
2705
+ function unrequestedTarget(check) {
2706
+ return check.status === "fail" ? { ...check, status: "warn" } : check;
2707
+ }
2708
+ function requestedTarget(check, requestedBuild) {
2709
+ if (requestedBuild?.status !== "fail") return check;
2710
+ const probed = /^available(?: — (?<facts>.+)| \((?<key>[^)]+)\))$/su.exec(check.detail)?.groups;
2711
+ const facts = probed?.facts ?? probed?.key;
2712
+ if (facts === void 0) return check;
2713
+ const blockers = /^not buildable — [^:]*: (?<why>.+)$/su.exec(requestedBuild.detail)?.groups?.why ?? requestedBuild.detail;
2714
+ return {
2715
+ ...check,
2716
+ detail: `not buildable \u2014 ${blockers}; probed: ${facts}`,
2717
+ fix: requestedBuild.fix ?? check.fix,
2718
+ status: "fail"
2719
+ };
2720
+ }
2721
+ function targetChecks(snapshot, nativeRuntime, request, requestedBuild) {
2722
+ const webAvailable = snapshot.files.has("src/main.ts");
2723
+ const desktopDetail = nativeRuntime.status === "ok" ? nativeRuntime.detail : `unavailable \u2014 ${nativeRuntime.detail.replace(/^(?:unavailable|unknown) — /u, "")}`;
2724
+ const checks = [
2725
+ webAvailable ? { detail: "available \u2014 src/main.ts", name: "target web", status: "ok" } : {
2726
+ detail: "unavailable \u2014 src/main.ts is missing",
2727
+ name: "target web",
2728
+ status: "warn"
2729
+ },
2730
+ {
2731
+ detail: desktopDetail,
2732
+ name: "target desktop",
2733
+ status: nativeRuntime.status
2734
+ },
2735
+ androidTargetCheck(snapshot),
2736
+ iosTargetCheck(snapshot)
2737
+ ];
2738
+ if (request.target === void 0) return checks;
2739
+ return checks.map(
2740
+ (check) => check.name === `target ${request.target}` ? requestedTarget(check, requestedBuild) : unrequestedTarget(check)
2741
+ );
2742
+ }
2743
+ function desktopOverlayCheck(probe) {
2744
+ return {
2745
+ detail: probe.detail,
2746
+ fix: probe.fix,
2747
+ name: "desktop overlay",
2748
+ status: probe.status
2749
+ };
2750
+ }
2751
+ var ASSET_MANIFEST = "public/assets.manifest.json";
2752
+ function hostWiring(snapshot, host) {
2753
+ if (!snapshot.files.has(host.file)) return "absent";
2754
+ const source = snapshot.readText(host.file);
2755
+ if (source === void 0) return "unreadable";
2756
+ if (host.file.endsWith(".json")) {
2757
+ try {
2758
+ const parsed = JSON.parse(source);
2759
+ if (record(parsed) === void 0) return "unreadable";
2760
+ } catch {
2761
+ return "unreadable";
2762
+ }
2763
+ }
2764
+ const missing = MCP_SERVER_SPECS.filter(({ configName }) => !source.includes(configName));
2765
+ return missing.length === 0 ? "wired" : "incomplete";
2766
+ }
2767
+ function editorActivationCheck(snapshot) {
2768
+ const wirings = MCP_HOST_TABLE.map((host) => ({ host, wiring: hostWiring(snapshot, host) }));
2769
+ const broken = wirings.filter(({ wiring }) => wiring === "incomplete" || wiring === "unreadable");
2770
+ const wired = wirings.filter(({ wiring }) => wiring === "wired");
2771
+ const manual = `${MANUAL_GLOBAL_MCP_HOSTS.join(", ")} read a machine-wide config only and are wired by hand`;
2772
+ const named = broken.map(
2773
+ ({ host, wiring }) => `${host.file} is ${wiring === "unreadable" ? "unreadable" : "missing ThreeNative servers"}`
2774
+ ).join("; ");
2775
+ if (wired.length === 0) {
2776
+ return {
2777
+ detail: `no project-scoped host config carries the ThreeNative servers (looked for ${MCP_HOST_TABLE.map(({ file }) => file).join(", ")})${named === "" ? "" : `; ${named}`}. ${manual}`,
2778
+ fix: "Reinstall @threenative/core in this project; its postinstall writes every project-scoped host config.",
2779
+ name: "editor activation",
2780
+ status: "fail"
2781
+ };
2782
+ }
2783
+ if (broken.length > 0) {
2784
+ return {
2785
+ // The file is the user's: doctor names it and never rewrites it.
2786
+ detail: `${named} \u2014 ${wired.length} of ${MCP_HOST_TABLE.length} host configs are complete. ${manual}`,
2787
+ fix: "Reinstall @threenative/core to rewrite the host configs it owns, or restore the listed file by hand; doctor never edits it.",
2788
+ name: "editor activation",
2789
+ status: "warn"
2790
+ };
2791
+ }
2792
+ return {
2793
+ detail: `${wired.length} of ${MCP_HOST_TABLE.length} host configs carry the servers (${wired.map(({ host }) => host.label).join(
2794
+ ", "
2795
+ )}); one is enough for the host you work in. Whether an editor loaded it is not observable from here. ${manual}`,
2796
+ name: "editor activation",
2797
+ status: "ok"
2798
+ };
2799
+ }
2800
+ function conversionsExecuted(snapshot) {
2801
+ const source = snapshot.readText(ASSET_MANIFEST);
2802
+ if (source === void 0) return void 0;
2803
+ let parsed;
2804
+ try {
2805
+ parsed = JSON.parse(source);
2806
+ } catch {
2807
+ return void 0;
2808
+ }
2809
+ const entries = record(parsed)?.entries;
2810
+ if (!Array.isArray(entries)) return void 0;
2811
+ return entries.filter((entry) => typeof record(entry)?.importedFrom === "string").length;
2812
+ }
2813
+ function modelConversionCheck(snapshot) {
2814
+ const probe = snapshot.blender;
2815
+ if (probe === void 0) return void 0;
2816
+ const name = "model conversion";
2817
+ const sources = [...snapshot.files].filter(
2818
+ (file) => BLENDER_SOURCE_SUFFIXES.some((suffix) => file.toLowerCase().endsWith(suffix))
2819
+ );
2820
+ const executed = conversionsExecuted(snapshot);
2821
+ const ran = executed === void 0 ? "no bake manifest here, so no conversion is proven" : executed === 0 ? "the bake manifest records no converted model" : `the bake manifest records ${executed} converted model(s)`;
2822
+ const transport = snapshot.mcpServerHealth?.get(BLENDER_SERVER);
2823
+ if (transport?.status === "fail") {
2824
+ return {
2825
+ detail: `${BLENDER_SERVER} is configured, but ${transport.detail}; no conversion tool is reachable \u2014 ${ran}`,
2826
+ fix: `Reinstall @threenative/core and ${BLENDER_PACKAGE.name}, then rerun doctor.`,
2827
+ name,
2828
+ status: "fail"
2829
+ };
2830
+ }
2831
+ const reachable = transport === void 0 ? `${BLENDER_SERVER} was not probed` : `${BLENDER_SERVER} transport is up`;
2832
+ if (!probe.available) {
2833
+ const carried = sources.length === 0 ? "no .fbx, .blend, .obj or .dae in this project, so nothing needs it yet" : `${sources.length} source(s) in this project need it: ${sources.slice(0, 3).join(", ")}`;
2834
+ return {
2835
+ detail: `${reachable}, but conversion is unavailable: ${probe.detail} \u2014 ${carried}; ${ran}`,
2836
+ fix: `Install Blender when you want to convert those formats: ${probe.installCommand}`,
2837
+ name,
2838
+ status: "warn"
2839
+ };
2840
+ }
2841
+ return {
2842
+ detail: `${reachable} and Blender ${probe.version ?? "(version unreported)"} converts .fbx, .blend, .obj and .dae on this machine; ${ran}`,
2843
+ name,
2844
+ status: "ok"
2845
+ };
2846
+ }
2847
+ function diagnoseProject(snapshot, options = {}) {
2848
+ if (record(snapshot.packageJson) === void 0) {
2849
+ return {
2850
+ checks: [
2851
+ {
2852
+ detail: "no readable package.json in this directory",
2853
+ fix: "Run this inside a generated project, or scaffold one with 'npm create threenative@latest'.",
2854
+ name: "package.json",
2855
+ status: "fail"
2856
+ }
2857
+ ],
2858
+ pass: false
2859
+ };
2860
+ }
2861
+ const hasPlaytests = [...snapshot.files].some((file) => file.endsWith(".playtest.json"));
2862
+ const blender = modelConversionCheck(snapshot);
2863
+ const nativeRuntime = nativeRuntimeCheck(snapshot);
2864
+ const apkSize = apkSizeCheck(snapshot);
2865
+ const playtest = playtestCheck(snapshot, options.capturePath);
2866
+ const requestedBuild = requestedBuildCheck(snapshot, options, nativeRuntime);
2867
+ const checks = [
2868
+ { detail: "readable", name: "package.json", status: "ok" },
2869
+ ...dependencyChecks(snapshot),
2870
+ nativeEntryCheck(snapshot),
2871
+ nativeRuntime,
2872
+ assetPipelineCheck(snapshot),
2873
+ ...apkSize === void 0 ? [] : [apkSize],
2874
+ ...!usesDesktopOverlay(snapshot.config) || snapshot.desktopOverlay === void 0 ? [] : [desktopOverlayCheck(snapshot.desktopOverlay)],
2875
+ ...targetChecks(snapshot, nativeRuntime, options, requestedBuild),
2876
+ ...requestedBuild === void 0 ? [] : [requestedBuild],
2877
+ snapshot.files.has("src/main.ts") ? { detail: "src/main.ts is the web entry", name: "web entry", status: "ok" } : {
2878
+ detail: "no src/main.ts, so 'threenative build' has no web entry to bundle",
2879
+ fix: "Add src/main.ts, which mounts the game and any browser-only UI.",
2880
+ name: "web entry",
2881
+ status: "warn"
2882
+ },
2883
+ playtest,
2884
+ hasPlaytests ? { detail: "at least one scenario can prove this game", name: "playtests", status: "ok" } : {
2885
+ detail: "no *.playtest.json scenario, so nothing here proves the game runs",
2886
+ fix: "Create one: 'npx @threenative/playtest init'.",
2887
+ name: "playtests",
2888
+ status: "warn"
2889
+ },
2890
+ ...capabilitySearchChecks(snapshot),
2891
+ editorActivationCheck(snapshot),
2892
+ ...blender === void 0 ? [] : [blender]
2893
+ ];
2894
+ const scoped = options.target === void 0 ? checks : checks.map((check) => {
2895
+ const owners = TARGET_PREREQUISITE_OWNERS[check.name];
2896
+ return owners === void 0 || owners.includes(options.target) ? check : unrequestedTarget(check);
2897
+ });
2898
+ return { checks: scoped, pass: scoped.every(({ status }) => status !== "fail") };
2899
+ }
2900
+ async function collectFiles(root, relative = "", depth = 0) {
2901
+ if (depth > 3) return [];
2902
+ const absolute = path2.join(root, relative);
2903
+ if (!existsSync(absolute)) return [];
2904
+ const entries = await readdir(absolute, { withFileTypes: true });
2905
+ const files = [];
2906
+ for (const entry of entries) {
2907
+ if (entry.name === "node_modules" || entry.name.startsWith(".git")) continue;
2908
+ const next = relative === "" ? entry.name : `${relative}/${entry.name}`;
2909
+ if (entry.isDirectory()) files.push(...await collectFiles(root, next, depth + 1));
2910
+ else files.push(next);
2911
+ }
2912
+ return files;
2913
+ }
2914
+ async function readJson(file) {
2915
+ try {
2916
+ return JSON.parse(await readFile(file, "utf8"));
2917
+ } catch {
2918
+ return void 0;
2919
+ }
2920
+ }
2921
+ async function runtimeReleaseManifestUrl(runtimeRoot, version) {
2922
+ try {
2923
+ const module = await import(pathToFileURL(path2.join(runtimeRoot, "scripts", "install-prebuilt.mjs")).href);
2924
+ const releaseUrl = record(module)?.releaseManifestUrl;
2925
+ if (typeof releaseUrl !== "function") return void 0;
2926
+ const result = releaseUrl(version);
2927
+ return typeof result === "string" ? result : void 0;
2928
+ } catch {
2929
+ return void 0;
2930
+ }
2931
+ }
2932
+ async function readProject(root) {
2933
+ const projectRoot = path2.resolve(root);
2934
+ const packageJson = await readJson(path2.join(projectRoot, "package.json"));
2935
+ const typeScriptConfig = path2.join(projectRoot, "threenative.config.ts");
2936
+ const config = existsSync(typeScriptConfig) ? await readTypeScriptConfig(projectRoot) : nativeEntryCompat(record(packageJson)?.threenative);
2937
+ const files = new Set(await collectFiles(projectRoot));
2938
+ const installedVersions = /* @__PURE__ */ new Map();
2939
+ for (const name of declaredDependencies(packageJson)) {
2940
+ const manifest = await readJson(path2.join(projectRoot, "node_modules", name, "package.json"));
2941
+ const version = record(manifest)?.version;
2942
+ if (typeof version === "string") installedVersions.set(name, version);
2943
+ }
2944
+ const runtimeRoot = installedVersions.has(RUNTIME_PACKAGE) ? (() => {
2945
+ const candidate = path2.join(projectRoot, "node_modules", RUNTIME_PACKAGE);
2946
+ try {
2947
+ return realpathSync(candidate);
2948
+ } catch {
2949
+ return void 0;
2950
+ }
2951
+ })() : void 0;
2952
+ const runtimeVersion = installedVersions.get(RUNTIME_PACKAGE);
2953
+ const runtimeManifestUrl = runtimeRoot === void 0 || runtimeVersion === void 0 ? void 0 : await runtimeReleaseManifestUrl(runtimeRoot, runtimeVersion);
2954
+ const playtestRunnerPath = resolveBinaryFrom(projectRoot, PLAYTEST_BINARY);
2955
+ const mcpServerHealth = /* @__PURE__ */ new Map();
2956
+ if (SHAPE_VERIFIABLE_HOSTS.some(({ file }) => files.has(file))) {
2957
+ for (const spec of MCP_SERVER_SPECS) {
2958
+ if (existsSync(path2.resolve(projectRoot, spec.expectedArgs))) {
2959
+ mcpServerHealth.set(spec.configName, probeMcpServer(projectRoot, spec));
2960
+ }
2961
+ }
2962
+ }
2963
+ return {
2964
+ config,
2965
+ files,
2966
+ installedVersions,
2967
+ mcpServerHealth,
2968
+ packageJson,
2969
+ projectRoot,
2970
+ readText: (relative) => {
2971
+ const file = path2.join(projectRoot, relative);
2972
+ try {
2973
+ return existsSync(file) ? readFileSync(file, "utf8") : void 0;
2974
+ } catch {
2975
+ return void 0;
2976
+ }
2977
+ },
2978
+ androidToolchain: probeAndroidToolchain(),
2979
+ blender: (() => {
2980
+ const status = resolveBlender();
2981
+ return {
2982
+ available: status.available,
2983
+ detail: status.detail,
2984
+ installCommand: installCommandFor(),
2985
+ ...status.version === void 0 ? {} : { version: status.version }
2986
+ };
2987
+ })(),
2988
+ ...usesDesktopOverlay(config) ? { desktopOverlay: probeDesktopOverlay() } : {},
2989
+ environment: process.env,
2990
+ ...playtestRunnerPath === void 0 ? {} : {
2991
+ playtestRunnerPath,
2992
+ runPlaytestDoctor: (capturePath) => executePlaytestDoctor(playtestRunnerPath, projectRoot, capturePath)
2993
+ },
2994
+ ...runtimeRoot === void 0 ? {} : {
2995
+ readRuntimeText: (relative) => {
2996
+ try {
2997
+ return readFileSync(path2.join(runtimeRoot, relative), "utf8");
2998
+ } catch {
2999
+ return void 0;
3000
+ }
3001
+ },
3002
+ runtimeFileExists: (relative) => existsSync(path2.join(runtimeRoot, relative)),
3003
+ ...runtimeManifestUrl === void 0 ? {} : { runtimeManifestUrl },
3004
+ runtimeRoot
3005
+ }
3006
+ };
3007
+ }
3008
+ async function readTypeScriptConfig(root) {
3009
+ try {
3010
+ return await loadConfig(root);
3011
+ } catch {
3012
+ return void 0;
3013
+ }
3014
+ }
3015
+ function formatDoctorReport(report) {
3016
+ const symbols = { fail: "\u2717", ok: "\u2713", warn: "!" };
3017
+ const isBaseline = (name) => ["package.json", "dependencies", "versions"].includes(name);
3018
+ const isCraft = (name) => name.startsWith("capability search");
3019
+ const isTest = (name) => name === "playtest" || name === "playtests";
3020
+ const groups = [
3021
+ ["Baseline", isBaseline],
3022
+ ["Craft", isCraft],
3023
+ ["Test", isTest],
3024
+ ["Ship", (name) => !isBaseline(name) && !isCraft(name) && !isTest(name)]
3025
+ ];
3026
+ const lines = [];
3027
+ for (const [group, belongs] of groups) {
3028
+ const checks = report.checks.filter(({ name }) => belongs(name));
3029
+ if (checks.length === 0) continue;
3030
+ lines.push(`${group}:`);
3031
+ lines.push(
3032
+ ...checks.map(
3033
+ ({ detail, fix, name, status }) => `${symbols[status]} ${name}: ${detail}${fix === void 0 || status === "ok" ? "" : `
3034
+ fix: ${fix}`}`
3035
+ )
3036
+ );
3037
+ }
3038
+ if (!report.pass) lines.push("\nAt least one check failed; fix it before trusting a build here.");
3039
+ return `${lines.join("\n")}
3040
+ `;
3041
+ }
3042
+
3043
+ // src/threenative.ts
3044
+ var DOCTOR_TARGETS = ["web", "desktop", "android", "ios"];
3045
+ var DOCTOR_MODES = ["debug", "release"];
3046
+ function cliHelp(command) {
3047
+ if (command === "build") return buildHelp();
3048
+ if (command === "doctor") {
3049
+ return `${[
3050
+ "Usage: threenative doctor [--target web|desktop|android|ios] [--mode debug|release]",
3051
+ " [--text] [--capture <path>]",
3052
+ "",
3053
+ "Checks this project against what the build and the native host assume about it:",
3054
+ "installed and version-matched @threenative packages, a portable entry that",
3055
+ "default-exports a game, a web entry, a scenario that can prove it, and the",
3056
+ "capability search an authoring agent needs.",
3057
+ "",
3058
+ "--target names the build you are about to run, so a prerequisite that build needs",
3059
+ " fails the report instead of describing the target as available with a warning.",
3060
+ " Targets you did not ask for stay in the report but no longer decide the exit code.",
3061
+ "--mode debug|release scopes it further; release additionally requires the game's own",
3062
+ " Android signing inputs. Requires --target.",
3063
+ " Release packaging itself is not implemented yet: 'threenative build' has no --mode, and",
3064
+ " the Android packager still assembles debug. --mode release predicts what that build will",
3065
+ " need once PRD-212 ships it, so a green report here is a forecast, not a release.",
3066
+ "Prints JSON by default; --text prints the same report for a person.",
3067
+ "--capture forwards a browser census JSON or native TN_PIPELINE_EVENT log to the playtest doctor.",
3068
+ "Exits 0 when nothing failed, 1 when a check failed."
3069
+ ].join("\n")}
3070
+ `;
3071
+ }
3072
+ return `${[
3073
+ "Usage: threenative <command> [options]",
3074
+ "",
3075
+ "Commands:",
3076
+ ...threenativeCommands.map((command2) => ` ${command2.padEnd(6)} ${commandSummaries[command2]}`),
3077
+ "",
3078
+ "Run 'threenative <command> --help' for command-specific help."
3079
+ ].join("\n")}
3080
+ `;
3081
+ }
3082
+ function helpFor(argv) {
3083
+ const command = argv[0];
3084
+ if (command === void 0 || command.startsWith("-")) return cliHelp();
3085
+ if (command === "build") return cliHelp("build");
3086
+ if (command === "doctor") return cliHelp("doctor");
3087
+ throw new Error(`Unknown threenative command '${command}'.
3088
+ ${cliHelp()}`);
3089
+ }
3090
+ async function runDoctorCommand(argv, cwd = process.cwd()) {
3091
+ let capturePath;
3092
+ let mode;
3093
+ let target;
3094
+ const valueFor = (flag, value) => {
3095
+ if (value === void 0 || value.startsWith("--"))
3096
+ throw new Error(`doctor: '${flag}' requires a value.`);
3097
+ return value;
3098
+ };
3099
+ for (let index = 0; index < argv.length; index += 1) {
3100
+ const flag = argv[index];
3101
+ if (flag === "--text") continue;
3102
+ if (flag === "--capture") {
3103
+ capturePath = valueFor(flag, argv[index + 1]);
3104
+ index += 1;
3105
+ continue;
3106
+ }
3107
+ if (flag === "--target") {
3108
+ const value = valueFor(flag, argv[index + 1]);
3109
+ if (!DOCTOR_TARGETS.includes(value))
3110
+ throw new Error(`doctor: '--target' must be one of ${DOCTOR_TARGETS.join(", ")}.`);
3111
+ target = value;
3112
+ index += 1;
3113
+ continue;
3114
+ }
3115
+ if (flag === "--mode") {
3116
+ const value = valueFor(flag, argv[index + 1]);
3117
+ if (!DOCTOR_MODES.includes(value))
3118
+ throw new Error(`doctor: '--mode' must be one of ${DOCTOR_MODES.join(", ")}.`);
3119
+ mode = value;
3120
+ index += 1;
3121
+ continue;
3122
+ }
3123
+ throw new Error(`doctor: unknown option '${String(flag)}'.`);
3124
+ }
3125
+ if (mode !== void 0 && target === void 0)
3126
+ throw new Error("doctor: '--mode' requires '--target'.");
3127
+ const report = diagnoseProject(await readProject(cwd), { capturePath, mode, target });
3128
+ process.stdout.write(
3129
+ argv.includes("--text") ? formatDoctorReport(report) : `${JSON.stringify(report, null, 2)}
3130
+ `
3131
+ );
3132
+ return report.pass ? 0 : 1;
3133
+ }
3134
+ async function main(argv = process.argv.slice(2)) {
3135
+ if (argv.includes("--help") || argv.includes("-h")) {
3136
+ process.stdout.write(helpFor(argv));
3137
+ return;
3138
+ }
3139
+ if (argv[0] === "doctor") {
3140
+ process.exitCode = await runDoctorCommand(argv.slice(1));
747
3141
  return;
748
3142
  }
749
3143
  await build(parseBuildArgs(argv));
@@ -754,4 +3148,4 @@ main().catch((error) => {
754
3148
  process.exitCode = 1;
755
3149
  });
756
3150
 
757
- export { cliHelp, main };
3151
+ export { cliHelp, main, runDoctorCommand };