@codeyam/codeyam-cli 0.1.0-staging.a890816 → 0.1.0-staging.ad44cd3

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 (477) hide show
  1. package/analyzer-template/.build-info.json +8 -8
  2. package/analyzer-template/log.txt +3 -3
  3. package/analyzer-template/package.json +10 -10
  4. package/analyzer-template/packages/ai/package.json +2 -2
  5. package/analyzer-template/packages/ai/src/lib/generateExecutionFlows.ts +0 -33
  6. package/analyzer-template/packages/analyze/src/lib/ProjectAnalyzer.ts +13 -7
  7. package/analyzer-template/packages/analyze/src/lib/asts/index.ts +7 -2
  8. package/analyzer-template/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.ts +0 -98
  9. package/analyzer-template/packages/aws/package.json +2 -2
  10. package/analyzer-template/packages/database/package.json +3 -3
  11. package/analyzer-template/packages/database/src/lib/kysely/tables/editorScenariosTable.ts +102 -0
  12. package/analyzer-template/packages/database/src/lib/loadEntities.ts +0 -6
  13. package/analyzer-template/packages/database/src/lib/updateCommitMetadata.ts +0 -65
  14. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts +9 -0
  15. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.d.ts.map +1 -1
  16. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js +104 -0
  17. package/analyzer-template/packages/github/dist/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
  18. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.d.ts.map +1 -1
  19. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js +0 -6
  20. package/analyzer-template/packages/github/dist/database/src/lib/loadEntities.js.map +1 -1
  21. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.d.ts.map +1 -1
  22. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js +0 -25
  23. package/analyzer-template/packages/github/dist/database/src/lib/updateCommitMetadata.js.map +1 -1
  24. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  25. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  26. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js +2 -0
  27. package/analyzer-template/packages/github/dist/types/src/enums/ProjectFramework.js.map +1 -1
  28. package/analyzer-template/packages/github/package.json +1 -1
  29. package/analyzer-template/packages/types/src/enums/ProjectFramework.ts +2 -0
  30. package/analyzer-template/packages/ui-components/package.json +1 -1
  31. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts +2 -0
  32. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.d.ts.map +1 -1
  33. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js +2 -0
  34. package/analyzer-template/packages/utils/dist/types/src/enums/ProjectFramework.js.map +1 -1
  35. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js +196 -0
  36. package/codeyam-cli/src/__tests__/memory-scripts/filter-session.test.js.map +1 -0
  37. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js +114 -0
  38. package/codeyam-cli/src/__tests__/memory-scripts/read-json-field.test.js.map +1 -0
  39. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js +149 -0
  40. package/codeyam-cli/src/__tests__/memory-scripts/ripgrep-fallback.test.js.map +1 -0
  41. package/codeyam-cli/src/cli.js +9 -0
  42. package/codeyam-cli/src/cli.js.map +1 -1
  43. package/codeyam-cli/src/commands/__tests__/editor.isolateArgs.test.js +51 -0
  44. package/codeyam-cli/src/commands/__tests__/editor.isolateArgs.test.js.map +1 -0
  45. package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js +56 -0
  46. package/codeyam-cli/src/commands/__tests__/editor.stepDispatch.test.js.map +1 -0
  47. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js +101 -47
  48. package/codeyam-cli/src/commands/__tests__/init.gitignore.test.js.map +1 -1
  49. package/codeyam-cli/src/commands/default.js +3 -46
  50. package/codeyam-cli/src/commands/default.js.map +1 -1
  51. package/codeyam-cli/src/commands/editor.js +3916 -419
  52. package/codeyam-cli/src/commands/editor.js.map +1 -1
  53. package/codeyam-cli/src/commands/editorIsolateArgs.js +25 -0
  54. package/codeyam-cli/src/commands/editorIsolateArgs.js.map +1 -0
  55. package/codeyam-cli/src/commands/init.js +74 -35
  56. package/codeyam-cli/src/commands/init.js.map +1 -1
  57. package/codeyam-cli/src/commands/telemetry.js +37 -0
  58. package/codeyam-cli/src/commands/telemetry.js.map +1 -0
  59. package/codeyam-cli/src/data/techStacks.js +77 -0
  60. package/codeyam-cli/src/data/techStacks.js.map +1 -0
  61. package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js +173 -0
  62. package/codeyam-cli/src/utils/__tests__/analyzerFinalization.test.js.map +1 -0
  63. package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js +46 -0
  64. package/codeyam-cli/src/utils/__tests__/backgroundServer.test.js.map +1 -0
  65. package/codeyam-cli/src/utils/__tests__/devServerState.test.js +134 -0
  66. package/codeyam-cli/src/utils/__tests__/devServerState.test.js.map +1 -0
  67. package/codeyam-cli/src/utils/__tests__/editorApi.test.js +137 -0
  68. package/codeyam-cli/src/utils/__tests__/editorApi.test.js.map +1 -0
  69. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js +1879 -0
  70. package/codeyam-cli/src/utils/__tests__/editorAudit.test.js.map +1 -0
  71. package/codeyam-cli/src/utils/__tests__/editorBroadcastViewport.test.js +76 -0
  72. package/codeyam-cli/src/utils/__tests__/editorBroadcastViewport.test.js.map +1 -0
  73. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js +93 -0
  74. package/codeyam-cli/src/utils/__tests__/editorCapture.test.js.map +1 -0
  75. package/codeyam-cli/src/utils/__tests__/editorDeleteScenario.test.js +100 -0
  76. package/codeyam-cli/src/utils/__tests__/editorDeleteScenario.test.js.map +1 -0
  77. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js +304 -0
  78. package/codeyam-cli/src/utils/__tests__/editorDevServer.test.js.map +1 -0
  79. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js +194 -0
  80. package/codeyam-cli/src/utils/__tests__/editorEntityChangeStatus.test.js.map +1 -0
  81. package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.test.js +261 -0
  82. package/codeyam-cli/src/utils/__tests__/editorEntityHelpers.test.js.map +1 -0
  83. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js +294 -0
  84. package/codeyam-cli/src/utils/__tests__/editorImageVerifier.test.js.map +1 -0
  85. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js +542 -0
  86. package/codeyam-cli/src/utils/__tests__/editorJournal.test.js.map +1 -0
  87. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js +594 -0
  88. package/codeyam-cli/src/utils/__tests__/editorLoaderHelpers.test.js.map +1 -0
  89. package/codeyam-cli/src/utils/__tests__/editorMigration.test.js +435 -0
  90. package/codeyam-cli/src/utils/__tests__/editorMigration.test.js.map +1 -0
  91. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js +270 -0
  92. package/codeyam-cli/src/utils/__tests__/editorMockState.test.js.map +1 -0
  93. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js +217 -0
  94. package/codeyam-cli/src/utils/__tests__/editorPreloadHelpers.test.js.map +1 -0
  95. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js +353 -0
  96. package/codeyam-cli/src/utils/__tests__/editorPreview.test.js.map +1 -0
  97. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js +153 -0
  98. package/codeyam-cli/src/utils/__tests__/editorProxySession.test.js.map +1 -0
  99. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js +139 -0
  100. package/codeyam-cli/src/utils/__tests__/editorScenarioLookup.test.js.map +1 -0
  101. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js +221 -0
  102. package/codeyam-cli/src/utils/__tests__/editorScenarioSwitch.test.js.map +1 -0
  103. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js +1483 -0
  104. package/codeyam-cli/src/utils/__tests__/editorScenarios.test.js.map +1 -0
  105. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js +280 -0
  106. package/codeyam-cli/src/utils/__tests__/editorSeedAdapter.test.js.map +1 -0
  107. package/codeyam-cli/src/utils/__tests__/editorSeedAdapterPrismaValidation.test.js +143 -0
  108. package/codeyam-cli/src/utils/__tests__/editorSeedAdapterPrismaValidation.test.js.map +1 -0
  109. package/codeyam-cli/src/utils/__tests__/editorSessionFilter.test.js +66 -0
  110. package/codeyam-cli/src/utils/__tests__/editorSessionFilter.test.js.map +1 -0
  111. package/codeyam-cli/src/utils/__tests__/editorShouldRevalidate.test.js +53 -0
  112. package/codeyam-cli/src/utils/__tests__/editorShouldRevalidate.test.js.map +1 -0
  113. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js +1857 -0
  114. package/codeyam-cli/src/utils/__tests__/entityChangeStatus.test.js.map +1 -0
  115. package/codeyam-cli/src/utils/__tests__/git.editor.test.js +134 -0
  116. package/codeyam-cli/src/utils/__tests__/git.editor.test.js.map +1 -0
  117. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js +107 -0
  118. package/codeyam-cli/src/utils/__tests__/journalCaptureStabilization.test.js.map +1 -0
  119. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js +129 -0
  120. package/codeyam-cli/src/utils/__tests__/parseRegisterArg.test.js.map +1 -0
  121. package/codeyam-cli/src/utils/__tests__/project.test.js +65 -0
  122. package/codeyam-cli/src/utils/__tests__/project.test.js.map +1 -0
  123. package/codeyam-cli/src/utils/__tests__/routePatternMatching.test.js +118 -0
  124. package/codeyam-cli/src/utils/__tests__/routePatternMatching.test.js.map +1 -0
  125. package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js +227 -0
  126. package/codeyam-cli/src/utils/__tests__/scenarioCoverage.test.js.map +1 -0
  127. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js +121 -0
  128. package/codeyam-cli/src/utils/__tests__/scenarioMarkers.test.js.map +1 -0
  129. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js +493 -0
  130. package/codeyam-cli/src/utils/__tests__/scenariosManifest.test.js.map +1 -0
  131. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js +26 -5
  132. package/codeyam-cli/src/utils/__tests__/setupClaudeCodeSettings.test.js.map +1 -1
  133. package/codeyam-cli/src/utils/__tests__/telemetry.test.js +159 -0
  134. package/codeyam-cli/src/utils/__tests__/telemetry.test.js.map +1 -0
  135. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js +51 -0
  136. package/codeyam-cli/src/utils/__tests__/templateConsistency.test.js.map +1 -0
  137. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js +142 -0
  138. package/codeyam-cli/src/utils/__tests__/webappDetection.test.js.map +1 -0
  139. package/codeyam-cli/src/utils/analysisRunner.js +3 -1
  140. package/codeyam-cli/src/utils/analysisRunner.js.map +1 -1
  141. package/codeyam-cli/src/utils/analyzer.js +9 -0
  142. package/codeyam-cli/src/utils/analyzer.js.map +1 -1
  143. package/codeyam-cli/src/utils/analyzerFinalization.js +100 -0
  144. package/codeyam-cli/src/utils/analyzerFinalization.js.map +1 -0
  145. package/codeyam-cli/src/utils/backgroundServer.js +94 -18
  146. package/codeyam-cli/src/utils/backgroundServer.js.map +1 -1
  147. package/codeyam-cli/src/utils/buildFlags.js +4 -0
  148. package/codeyam-cli/src/utils/buildFlags.js.map +1 -0
  149. package/codeyam-cli/src/utils/database.js +37 -2
  150. package/codeyam-cli/src/utils/database.js.map +1 -1
  151. package/codeyam-cli/src/utils/devServerState.js +71 -0
  152. package/codeyam-cli/src/utils/devServerState.js.map +1 -0
  153. package/codeyam-cli/src/utils/editorApi.js +79 -0
  154. package/codeyam-cli/src/utils/editorApi.js.map +1 -0
  155. package/codeyam-cli/src/utils/editorAudit.js +355 -0
  156. package/codeyam-cli/src/utils/editorAudit.js.map +1 -0
  157. package/codeyam-cli/src/utils/editorBroadcastViewport.js +26 -0
  158. package/codeyam-cli/src/utils/editorBroadcastViewport.js.map +1 -0
  159. package/codeyam-cli/src/utils/editorCapture.js +102 -0
  160. package/codeyam-cli/src/utils/editorCapture.js.map +1 -0
  161. package/codeyam-cli/src/utils/editorDeleteScenario.js +67 -0
  162. package/codeyam-cli/src/utils/editorDeleteScenario.js.map +1 -0
  163. package/codeyam-cli/src/utils/editorDevServer.js +197 -0
  164. package/codeyam-cli/src/utils/editorDevServer.js.map +1 -0
  165. package/codeyam-cli/src/utils/editorEntityChangeStatus.js +50 -0
  166. package/codeyam-cli/src/utils/editorEntityChangeStatus.js.map +1 -0
  167. package/codeyam-cli/src/utils/editorEntityHelpers.js +129 -0
  168. package/codeyam-cli/src/utils/editorEntityHelpers.js.map +1 -0
  169. package/codeyam-cli/src/utils/editorImageVerifier.js +155 -0
  170. package/codeyam-cli/src/utils/editorImageVerifier.js.map +1 -0
  171. package/codeyam-cli/src/utils/editorJournal.js +225 -0
  172. package/codeyam-cli/src/utils/editorJournal.js.map +1 -0
  173. package/codeyam-cli/src/utils/editorLoaderHelpers.js +152 -0
  174. package/codeyam-cli/src/utils/editorLoaderHelpers.js.map +1 -0
  175. package/codeyam-cli/src/utils/editorMigration.js +224 -0
  176. package/codeyam-cli/src/utils/editorMigration.js.map +1 -0
  177. package/codeyam-cli/src/utils/editorMockState.js +248 -0
  178. package/codeyam-cli/src/utils/editorMockState.js.map +1 -0
  179. package/codeyam-cli/src/utils/editorPreloadHelpers.js +135 -0
  180. package/codeyam-cli/src/utils/editorPreloadHelpers.js.map +1 -0
  181. package/codeyam-cli/src/utils/editorPreview.js +137 -0
  182. package/codeyam-cli/src/utils/editorPreview.js.map +1 -0
  183. package/codeyam-cli/src/utils/editorScenarioSwitch.js +112 -0
  184. package/codeyam-cli/src/utils/editorScenarioSwitch.js.map +1 -0
  185. package/codeyam-cli/src/utils/editorScenarios.js +548 -0
  186. package/codeyam-cli/src/utils/editorScenarios.js.map +1 -0
  187. package/codeyam-cli/src/utils/editorSeedAdapter.js +422 -0
  188. package/codeyam-cli/src/utils/editorSeedAdapter.js.map +1 -0
  189. package/codeyam-cli/src/utils/editorShouldRevalidate.js +21 -0
  190. package/codeyam-cli/src/utils/editorShouldRevalidate.js.map +1 -0
  191. package/codeyam-cli/src/utils/entityChangeStatus.js +366 -0
  192. package/codeyam-cli/src/utils/entityChangeStatus.js.map +1 -0
  193. package/codeyam-cli/src/utils/entityChangeStatus.server.js +196 -0
  194. package/codeyam-cli/src/utils/entityChangeStatus.server.js.map +1 -0
  195. package/codeyam-cli/src/utils/fileWatcher.js +38 -0
  196. package/codeyam-cli/src/utils/fileWatcher.js.map +1 -1
  197. package/codeyam-cli/src/utils/git.js +51 -0
  198. package/codeyam-cli/src/utils/git.js.map +1 -1
  199. package/codeyam-cli/src/utils/install-skills.js +37 -17
  200. package/codeyam-cli/src/utils/install-skills.js.map +1 -1
  201. package/codeyam-cli/src/utils/parseRegisterArg.js +31 -0
  202. package/codeyam-cli/src/utils/parseRegisterArg.js.map +1 -0
  203. package/codeyam-cli/src/utils/progress.js +2 -2
  204. package/codeyam-cli/src/utils/progress.js.map +1 -1
  205. package/codeyam-cli/src/utils/project.js +15 -5
  206. package/codeyam-cli/src/utils/project.js.map +1 -1
  207. package/codeyam-cli/src/utils/routePatternMatching.js +129 -0
  208. package/codeyam-cli/src/utils/routePatternMatching.js.map +1 -0
  209. package/codeyam-cli/src/utils/scenarioCoverage.js +74 -0
  210. package/codeyam-cli/src/utils/scenarioCoverage.js.map +1 -0
  211. package/codeyam-cli/src/utils/scenarioMarkers.js +134 -0
  212. package/codeyam-cli/src/utils/scenarioMarkers.js.map +1 -0
  213. package/codeyam-cli/src/utils/scenariosManifest.js +249 -0
  214. package/codeyam-cli/src/utils/scenariosManifest.js.map +1 -0
  215. package/codeyam-cli/src/utils/serverState.js +30 -0
  216. package/codeyam-cli/src/utils/serverState.js.map +1 -1
  217. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js +47 -16
  218. package/codeyam-cli/src/utils/setupClaudeCodeSettings.js.map +1 -1
  219. package/codeyam-cli/src/utils/simulationGateMiddleware.js +8 -1
  220. package/codeyam-cli/src/utils/simulationGateMiddleware.js.map +1 -1
  221. package/codeyam-cli/src/utils/slugUtils.js +25 -0
  222. package/codeyam-cli/src/utils/slugUtils.js.map +1 -0
  223. package/codeyam-cli/src/utils/syncMocksMiddleware.js +2 -2
  224. package/codeyam-cli/src/utils/syncMocksMiddleware.js.map +1 -1
  225. package/codeyam-cli/src/utils/telemetry.js +106 -0
  226. package/codeyam-cli/src/utils/telemetry.js.map +1 -0
  227. package/codeyam-cli/src/utils/telemetryMiddleware.js +22 -0
  228. package/codeyam-cli/src/utils/telemetryMiddleware.js.map +1 -0
  229. package/codeyam-cli/src/utils/testRunner.js +1 -1
  230. package/codeyam-cli/src/utils/testRunner.js.map +1 -1
  231. package/codeyam-cli/src/utils/webappDetection.js +21 -0
  232. package/codeyam-cli/src/utils/webappDetection.js.map +1 -1
  233. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js +35 -0
  234. package/codeyam-cli/src/webserver/__tests__/buildPtyEnv.test.js.map +1 -0
  235. package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js +40 -0
  236. package/codeyam-cli/src/webserver/__tests__/clientErrors.test.js.map +1 -0
  237. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js +628 -0
  238. package/codeyam-cli/src/webserver/__tests__/editorProxy.test.js.map +1 -0
  239. package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js +146 -0
  240. package/codeyam-cli/src/webserver/__tests__/idleDetector.test.js.map +1 -0
  241. package/codeyam-cli/src/webserver/app/lib/clientErrors.js +65 -0
  242. package/codeyam-cli/src/webserver/app/lib/clientErrors.js.map +1 -0
  243. package/codeyam-cli/src/webserver/app/lib/git.js +397 -0
  244. package/codeyam-cli/src/webserver/app/lib/git.js.map +1 -0
  245. package/codeyam-cli/src/webserver/app/types/editor.js +8 -0
  246. package/codeyam-cli/src/webserver/app/types/editor.js.map +1 -0
  247. package/codeyam-cli/src/webserver/backgroundServer.js +18 -4
  248. package/codeyam-cli/src/webserver/backgroundServer.js.map +1 -1
  249. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-CzTDWkF2.js +1 -0
  250. package/codeyam-cli/src/webserver/build/client/assets/{EntityItem-C76mRRiF.js → EntityItem-BFbq6iFk.js} +5 -5
  251. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-CQgyEGV-.js +1 -0
  252. package/codeyam-cli/src/webserver/build/client/assets/{EntityTypeIcon-CobE682z.js → EntityTypeIcon-B6OMi58N.js} +9 -9
  253. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-DuYodzo1.js +1 -0
  254. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-CXo9EeCl.js +25 -0
  255. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-DYCNb2It.js +3 -0
  256. package/codeyam-cli/src/webserver/build/client/assets/{LoadingDots-BU_OAEMP.js → LoadingDots-By5zI316.js} +1 -1
  257. package/codeyam-cli/src/webserver/build/client/assets/{LogViewer-ceAyBX-H.js → LogViewer-CZgY3sxX.js} +3 -3
  258. package/codeyam-cli/src/webserver/build/client/assets/{ReportIssueModal-djPLI-WV.js → ReportIssueModal-CnYYwRDw.js} +4 -4
  259. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-CDoF7ZpU.js +1 -0
  260. package/codeyam-cli/src/webserver/build/client/assets/{ScenarioViewer-B76aig_2.js → ScenarioViewer-DrnfvaLL.js} +3 -3
  261. package/codeyam-cli/src/webserver/build/client/assets/Spinner-Df3UCi8k.js +34 -0
  262. package/codeyam-cli/src/webserver/build/client/assets/TruncatedFilePath-CK7-NaPZ.js +1 -0
  263. package/codeyam-cli/src/webserver/build/client/assets/ViewportInspectBar-DRKR9T0U.js +1 -0
  264. package/codeyam-cli/src/webserver/build/client/assets/{_index-C96V0n15.js → _index-ClR-g3tY.js} +4 -4
  265. package/codeyam-cli/src/webserver/build/client/assets/{activity.(_tab)-BpKzcsJz.js → activity.(_tab)-DTH6ydEA.js} +8 -8
  266. package/codeyam-cli/src/webserver/build/client/assets/addon-canvas-DpzMmAy5.js +1 -0
  267. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-YJmn1quW.js +12 -0
  268. package/codeyam-cli/src/webserver/build/client/assets/{addon-web-links-Duc5hnl7.js → addon-web-links-74hnHF59.js} +1 -1
  269. package/codeyam-cli/src/webserver/build/client/assets/addon-webgl-DI8QOUvO.js +58 -0
  270. package/codeyam-cli/src/webserver/build/client/assets/{agent-transcripts-D9hemwl6.js → agent-transcripts-B8CYhCO9.js} +7 -7
  271. package/codeyam-cli/src/webserver/build/client/assets/api.editor-audit-l0sNRNKZ.js +1 -0
  272. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-diff-l0sNRNKZ.js +1 -0
  273. package/codeyam-cli/src/webserver/build/client/assets/api.editor-file-l0sNRNKZ.js +1 -0
  274. package/codeyam-cli/src/webserver/build/client/assets/api.editor-load-commit-l0sNRNKZ.js +1 -0
  275. package/codeyam-cli/src/webserver/build/client/assets/api.editor-project-info-l0sNRNKZ.js +1 -0
  276. package/codeyam-cli/src/webserver/build/client/assets/api.editor-rename-scenario-l0sNRNKZ.js +1 -0
  277. package/codeyam-cli/src/webserver/build/client/assets/api.editor-save-seed-state-l0sNRNKZ.js +1 -0
  278. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-coverage-l0sNRNKZ.js +1 -0
  279. package/codeyam-cli/src/webserver/build/client/assets/api.editor-scenario-prompt-l0sNRNKZ.js +1 -0
  280. package/codeyam-cli/src/webserver/build/client/assets/api.editor-session-l0sNRNKZ.js +1 -0
  281. package/codeyam-cli/src/webserver/build/client/assets/{book-open-D_nMCFmP.js → book-open-CLaoh4ac.js} +2 -2
  282. package/codeyam-cli/src/webserver/build/client/assets/{chevron-down-BH2h1Ea2.js → chevron-down-BZ2DZxbW.js} +2 -2
  283. package/codeyam-cli/src/webserver/build/client/assets/{chunk-JZWAC4HX-C4pqxYJB.js → chunk-JZWAC4HX-BBXArFPl.js} +13 -21
  284. package/codeyam-cli/src/webserver/build/client/assets/{circle-check-DyIKORY6.js → circle-check-CT4unAk-.js} +2 -2
  285. package/codeyam-cli/src/webserver/build/client/assets/{copy-NDbZjXao.js → copy-zK0B6Nu-.js} +3 -3
  286. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-DJB0YQJL.js +41 -0
  287. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-CkXFP_i-.js +1 -0
  288. package/codeyam-cli/src/webserver/build/client/assets/editor._tab-DPw7NZHc.js +1 -0
  289. package/codeyam-cli/src/webserver/build/client/assets/editor.entity.(_sha)-CjC3_6JI.js +58 -0
  290. package/codeyam-cli/src/webserver/build/client/assets/editorPreview-DBa7T2FK.js +41 -0
  291. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha._-CrjR3zZW.js → entity._sha._-BqAN7hyG.js} +3 -3
  292. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-BOi8kpwd.js +6 -0
  293. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-Dg1NhIms.js +6 -0
  294. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-CJX6kkkV.js +6 -0
  295. package/codeyam-cli/src/webserver/build/client/assets/{entity._sha_.edit._scenarioId-BMvVHNXU.js → entity._sha_.edit._scenarioId-BhVjZhKg.js} +2 -2
  296. package/codeyam-cli/src/webserver/build/client/assets/{entry.client-DTvKq3TY.js → entry.client-_gzKltPN.js} +6 -6
  297. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-Daa96Fr1.js +1 -0
  298. package/codeyam-cli/src/webserver/build/client/assets/files-CV_17tZS.js +1 -0
  299. package/codeyam-cli/src/webserver/build/client/assets/git-D-YXmMbR.js +1 -0
  300. package/codeyam-cli/src/webserver/build/client/assets/globals-DRvOjyO3.css +1 -0
  301. package/codeyam-cli/src/webserver/build/client/assets/index-Blo6EK8G.js +15 -0
  302. package/codeyam-cli/src/webserver/build/client/assets/{index-10oVnAAH.js → index-BsX0F-9C.js} +1 -1
  303. package/codeyam-cli/src/webserver/build/client/assets/{index-BcvgDzbZ.js → index-CCrgCshv.js} +1 -1
  304. package/codeyam-cli/src/webserver/build/client/assets/jsx-runtime-D_zvdyIk.js +9 -0
  305. package/codeyam-cli/src/webserver/build/client/assets/labs-Byazq8Pv.js +1 -0
  306. package/codeyam-cli/src/webserver/build/client/assets/{loader-circle-BAXYRVEO.js → loader-circle-DVQ0oHR7.js} +2 -2
  307. package/codeyam-cli/src/webserver/build/client/assets/manifest-75b1b319.js +1 -0
  308. package/codeyam-cli/src/webserver/build/client/assets/memory-b-VmA2Vj.js +101 -0
  309. package/codeyam-cli/src/webserver/build/client/assets/{pause-DTAcYxBt.js → pause-DGcndCAa.js} +3 -3
  310. package/codeyam-cli/src/webserver/build/client/assets/root-F-k2uYj5.js +67 -0
  311. package/codeyam-cli/src/webserver/build/client/assets/{search-fKo7v0Zo.js → search-C0Uw0bcK.js} +2 -2
  312. package/codeyam-cli/src/webserver/build/client/assets/settings-OoNgHIfW.js +1 -0
  313. package/codeyam-cli/src/webserver/build/client/assets/simulations-Bcemfu8a.js +1 -0
  314. package/codeyam-cli/src/webserver/build/client/assets/{terminal-BG4heKCG.js → terminal-BgMmG7R9.js} +3 -3
  315. package/codeyam-cli/src/webserver/build/client/assets/{triangle-alert-DtSmdtM4.js → triangle-alert-Cs87hJYK.js} +2 -2
  316. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-BR3Rs7JY.js +1 -0
  317. package/codeyam-cli/src/webserver/build/client/assets/{useLastLogLine-C14nCb1q.js → useLastLogLine-BxxP_XF9.js} +1 -1
  318. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-BermyNU5.js +1 -0
  319. package/codeyam-cli/src/webserver/build/client/assets/useToast-a_QN_W9_.js +1 -0
  320. package/codeyam-cli/src/webserver/build/client/assets/xterm-BqvuqXEL.js +27 -0
  321. package/codeyam-cli/src/webserver/build/client/sound-test.html +98 -0
  322. package/codeyam-cli/src/webserver/build/server/assets/analysisRunner-lv2ooewK.js +13 -0
  323. package/codeyam-cli/src/webserver/build/server/assets/index-Im3Smyei.js +1 -0
  324. package/codeyam-cli/src/webserver/build/server/assets/init-BjuAFKGM.js +10 -0
  325. package/codeyam-cli/src/webserver/build/server/assets/progress-CHTtrxFG.js +1 -0
  326. package/codeyam-cli/src/webserver/build/server/assets/server-build-CNjF0B9B.js +551 -0
  327. package/codeyam-cli/src/webserver/build/server/index.js +1 -1
  328. package/codeyam-cli/src/webserver/build-info.json +5 -5
  329. package/codeyam-cli/src/webserver/editorProxy.js +755 -51
  330. package/codeyam-cli/src/webserver/editorProxy.js.map +1 -1
  331. package/codeyam-cli/src/webserver/idleDetector.js +73 -0
  332. package/codeyam-cli/src/webserver/idleDetector.js.map +1 -0
  333. package/codeyam-cli/src/webserver/mockStateEvents.js +28 -0
  334. package/codeyam-cli/src/webserver/mockStateEvents.js.map +1 -0
  335. package/codeyam-cli/src/webserver/public/sound-test.html +98 -0
  336. package/codeyam-cli/src/webserver/scripts/codeyam-preload.mjs +414 -0
  337. package/codeyam-cli/src/webserver/scripts/journalCapture.ts +94 -4
  338. package/codeyam-cli/src/webserver/server.js +176 -12
  339. package/codeyam-cli/src/webserver/server.js.map +1 -1
  340. package/codeyam-cli/src/webserver/terminalServer.js +218 -140
  341. package/codeyam-cli/src/webserver/terminalServer.js.map +1 -1
  342. package/codeyam-cli/templates/chrome-extension-react/EXTENSION_SETUP.md +75 -0
  343. package/codeyam-cli/templates/chrome-extension-react/README.md +46 -0
  344. package/codeyam-cli/templates/chrome-extension-react/gitignore +15 -0
  345. package/codeyam-cli/templates/chrome-extension-react/index.html +12 -0
  346. package/codeyam-cli/templates/chrome-extension-react/package.json +27 -0
  347. package/codeyam-cli/templates/chrome-extension-react/popup.html +12 -0
  348. package/codeyam-cli/templates/chrome-extension-react/public/manifest.json +15 -0
  349. package/codeyam-cli/templates/chrome-extension-react/src/background/service-worker.ts +7 -0
  350. package/codeyam-cli/templates/chrome-extension-react/src/globals.css +6 -0
  351. package/codeyam-cli/templates/chrome-extension-react/src/lib/storage.ts +37 -0
  352. package/codeyam-cli/templates/chrome-extension-react/src/popup/App.tsx +12 -0
  353. package/codeyam-cli/templates/chrome-extension-react/src/popup/main.tsx +10 -0
  354. package/codeyam-cli/templates/chrome-extension-react/tsconfig.json +24 -0
  355. package/codeyam-cli/templates/chrome-extension-react/vite.config.ts +41 -0
  356. package/codeyam-cli/templates/codeyam-editor-claude.md +84 -5
  357. package/codeyam-cli/templates/editor-step-hook.py +198 -22
  358. package/codeyam-cli/templates/expo-react-native/MOBILE_SETUP.md +89 -0
  359. package/codeyam-cli/templates/expo-react-native/README.md +41 -0
  360. package/codeyam-cli/templates/expo-react-native/app/(tabs)/_layout.tsx +33 -0
  361. package/codeyam-cli/templates/expo-react-native/app/(tabs)/index.tsx +12 -0
  362. package/codeyam-cli/templates/expo-react-native/app/(tabs)/settings.tsx +12 -0
  363. package/codeyam-cli/templates/expo-react-native/app/_layout.tsx +12 -0
  364. package/codeyam-cli/templates/expo-react-native/app.json +18 -0
  365. package/codeyam-cli/templates/expo-react-native/babel.config.js +9 -0
  366. package/codeyam-cli/templates/expo-react-native/gitignore +12 -0
  367. package/codeyam-cli/templates/expo-react-native/global.css +3 -0
  368. package/codeyam-cli/templates/expo-react-native/lib/storage.ts +32 -0
  369. package/codeyam-cli/templates/expo-react-native/metro.config.js +6 -0
  370. package/codeyam-cli/templates/expo-react-native/nativewind-env.d.ts +1 -0
  371. package/codeyam-cli/templates/expo-react-native/package.json +38 -0
  372. package/codeyam-cli/templates/expo-react-native/tailwind.config.js +10 -0
  373. package/codeyam-cli/templates/expo-react-native/tsconfig.json +10 -0
  374. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_PATTERNS.md +308 -0
  375. package/codeyam-cli/templates/nextjs-prisma-sqlite/AUTH_UPGRADE.md +304 -0
  376. package/codeyam-cli/templates/nextjs-prisma-sqlite/DATABASE.md +126 -0
  377. package/codeyam-cli/templates/nextjs-prisma-sqlite/FEATURE_PATTERNS.md +37 -0
  378. package/codeyam-cli/templates/nextjs-prisma-sqlite/README.md +53 -0
  379. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/codeyam-isolate/layout.tsx +12 -0
  380. package/codeyam-cli/templates/nextjs-prisma-sqlite/app/lib/prisma.ts +9 -4
  381. package/codeyam-cli/templates/nextjs-prisma-sqlite/env +4 -0
  382. package/codeyam-cli/templates/nextjs-prisma-sqlite/gitignore +21 -0
  383. package/codeyam-cli/templates/nextjs-prisma-sqlite/package.json +5 -1
  384. package/codeyam-cli/templates/nextjs-prisma-sqlite/prisma/seed.ts +4 -1
  385. package/codeyam-cli/templates/nextjs-prisma-sqlite/seed-adapter.ts +127 -0
  386. package/codeyam-cli/templates/nextjs-prisma-sqlite/vitest.config.ts +13 -0
  387. package/codeyam-cli/templates/nextjs-prisma-supabase/README.md +52 -0
  388. package/codeyam-cli/templates/{nextjs-prisma-sqlite/PRISMA_SETUP.md → nextjs-prisma-supabase/SUPABASE_SETUP.md} +37 -17
  389. package/codeyam-cli/templates/nextjs-prisma-supabase/app/api/todos/route.ts +17 -0
  390. package/codeyam-cli/templates/nextjs-prisma-supabase/app/globals.css +26 -0
  391. package/codeyam-cli/templates/nextjs-prisma-supabase/app/layout.tsx +34 -0
  392. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/prisma.ts +20 -0
  393. package/codeyam-cli/templates/nextjs-prisma-supabase/app/lib/supabase.ts +12 -0
  394. package/codeyam-cli/templates/nextjs-prisma-supabase/app/page.tsx +10 -0
  395. package/codeyam-cli/templates/nextjs-prisma-supabase/env +9 -0
  396. package/codeyam-cli/templates/nextjs-prisma-supabase/eslint.config.mjs +11 -0
  397. package/codeyam-cli/templates/nextjs-prisma-supabase/gitignore +40 -0
  398. package/codeyam-cli/templates/nextjs-prisma-supabase/next.config.ts +11 -0
  399. package/codeyam-cli/templates/nextjs-prisma-supabase/package.json +37 -0
  400. package/codeyam-cli/templates/nextjs-prisma-supabase/postcss.config.mjs +7 -0
  401. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/schema.prisma +27 -0
  402. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma/seed.ts +39 -0
  403. package/codeyam-cli/templates/nextjs-prisma-supabase/prisma.config.ts +12 -0
  404. package/codeyam-cli/templates/nextjs-prisma-supabase/tsconfig.json +34 -0
  405. package/codeyam-cli/templates/seed-adapters/supabase.ts +282 -0
  406. package/codeyam-cli/templates/{codeyam-dev-mode.md → skills/codeyam-dev-mode/SKILL.md} +3 -3
  407. package/codeyam-cli/templates/skills/codeyam-editor/SKILL.md +211 -0
  408. package/codeyam-cli/templates/{codeyam-memory.md → skills/codeyam-memory/SKILL.md} +215 -0
  409. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/deprecated-prompt.md +100 -0
  410. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/detect-deprecated-patterns.mjs +139 -0
  411. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/find-exports.mjs +52 -0
  412. package/codeyam-cli/templates/skills/codeyam-memory/scripts/holistic-analysis/misleading-api-prompt.md +117 -0
  413. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/read-json-field.mjs +61 -0
  414. package/codeyam-cli/templates/skills/codeyam-memory/scripts/lib/ripgrep-fallback.mjs +155 -0
  415. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/analyze-prompt.md +46 -0
  416. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/cleanup.mjs +13 -0
  417. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/filter-session.mjs +95 -0
  418. package/codeyam-cli/templates/skills/codeyam-memory/scripts/session-mining/preprocess.mjs +160 -0
  419. package/package.json +16 -10
  420. package/packages/ai/src/lib/generateExecutionFlows.js +0 -11
  421. package/packages/ai/src/lib/generateExecutionFlows.js.map +1 -1
  422. package/packages/analyze/src/lib/ProjectAnalyzer.js +10 -4
  423. package/packages/analyze/src/lib/ProjectAnalyzer.js.map +1 -1
  424. package/packages/analyze/src/lib/asts/index.js +4 -2
  425. package/packages/analyze/src/lib/asts/index.js.map +1 -1
  426. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js +0 -40
  427. package/packages/analyze/src/lib/files/scenarios/generateExecutionFlows.js.map +1 -1
  428. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js +104 -0
  429. package/packages/database/src/lib/kysely/tables/editorScenariosTable.js.map +1 -1
  430. package/packages/database/src/lib/loadEntities.js +0 -6
  431. package/packages/database/src/lib/loadEntities.js.map +1 -1
  432. package/packages/database/src/lib/updateCommitMetadata.js +0 -25
  433. package/packages/database/src/lib/updateCommitMetadata.js.map +1 -1
  434. package/packages/types/src/enums/ProjectFramework.js +2 -0
  435. package/packages/types/src/enums/ProjectFramework.js.map +1 -1
  436. package/scripts/npm-post-install.cjs +34 -0
  437. package/codeyam-cli/src/webserver/build/client/assets/CopyButton-DmJveP3T.js +0 -1
  438. package/codeyam-cli/src/webserver/build/client/assets/EntityTypeBadge-g3saevPb.js +0 -1
  439. package/codeyam-cli/src/webserver/build/client/assets/InlineSpinner-Bu6c6aDe.js +0 -1
  440. package/codeyam-cli/src/webserver/build/client/assets/InteractivePreview-DYFW3lDD.js +0 -25
  441. package/codeyam-cli/src/webserver/build/client/assets/LibraryFunctionPreview-DLeucoVX.js +0 -3
  442. package/codeyam-cli/src/webserver/build/client/assets/SafeScreenshot-BED4B6sP.js +0 -1
  443. package/codeyam-cli/src/webserver/build/client/assets/Spinner-Bb5uFQ5V.js +0 -34
  444. package/codeyam-cli/src/webserver/build/client/assets/Terminal-CcG8YTLx.js +0 -41
  445. package/codeyam-cli/src/webserver/build/client/assets/TruncatedFilePath-C8OKAR5x.js +0 -1
  446. package/codeyam-cli/src/webserver/build/client/assets/addon-fit-CUXOrorO.js +0 -1
  447. package/codeyam-cli/src/webserver/build/client/assets/createLucideIcon-CMT1jU2q.js +0 -21
  448. package/codeyam-cli/src/webserver/build/client/assets/dev.empty-BiM6z3Do.js +0 -1
  449. package/codeyam-cli/src/webserver/build/client/assets/editor-W_IGJ2Kd.js +0 -7
  450. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.dev-D6SEzMCu.js +0 -6
  451. package/codeyam-cli/src/webserver/build/client/assets/entity._sha.scenarios._scenarioId.fullscreen-C28BiQzt.js +0 -6
  452. package/codeyam-cli/src/webserver/build/client/assets/entity._sha_.create-scenario-p9hhkjJM.js +0 -6
  453. package/codeyam-cli/src/webserver/build/client/assets/fileTableUtils-cPo8LiG3.js +0 -1
  454. package/codeyam-cli/src/webserver/build/client/assets/files-DO4CZ16O.js +0 -1
  455. package/codeyam-cli/src/webserver/build/client/assets/git-CFCTYk9I.js +0 -15
  456. package/codeyam-cli/src/webserver/build/client/assets/globals-BZB_H1w2.css +0 -1
  457. package/codeyam-cli/src/webserver/build/client/assets/labs-Zk7ryIM1.js +0 -1
  458. package/codeyam-cli/src/webserver/build/client/assets/manifest-8daa4147.js +0 -1
  459. package/codeyam-cli/src/webserver/build/client/assets/memory-FweZHj5U.js +0 -93
  460. package/codeyam-cli/src/webserver/build/client/assets/root-DiRdBreB.js +0 -67
  461. package/codeyam-cli/src/webserver/build/client/assets/settings-DfuTtcJP.js +0 -1
  462. package/codeyam-cli/src/webserver/build/client/assets/simulations-B3aOzpCZ.js +0 -1
  463. package/codeyam-cli/src/webserver/build/client/assets/useCustomSizes-ByhSyh0W.js +0 -1
  464. package/codeyam-cli/src/webserver/build/client/assets/useReportContext-O-jkvSPx.js +0 -1
  465. package/codeyam-cli/src/webserver/build/client/assets/useToast-9FIWuYfK.js +0 -1
  466. package/codeyam-cli/src/webserver/build/client/assets/xterm-DMSzMhqy.js +0 -9
  467. package/codeyam-cli/src/webserver/build/server/assets/index-BzAbACSx.js +0 -1
  468. package/codeyam-cli/src/webserver/build/server/assets/server-build-OdUocH6P.js +0 -362
  469. package/codeyam-cli/templates/codeyam-editor.md +0 -68
  470. package/scripts/finalize-analyzer.cjs +0 -13
  471. /package/codeyam-cli/templates/{codeyam-diagnose.md → commands/codeyam-diagnose.md} +0 -0
  472. /package/codeyam-cli/templates/{codeyam-debug.md → skills/codeyam-debug/SKILL.md} +0 -0
  473. /package/codeyam-cli/templates/{codeyam-new-rule.md → skills/codeyam-new-rule/SKILL.md} +0 -0
  474. /package/codeyam-cli/templates/{codeyam-setup.md → skills/codeyam-setup/SKILL.md} +0 -0
  475. /package/codeyam-cli/templates/{codeyam-sim.md → skills/codeyam-sim/SKILL.md} +0 -0
  476. /package/codeyam-cli/templates/{codeyam-test.md → skills/codeyam-test/SKILL.md} +0 -0
  477. /package/codeyam-cli/templates/{codeyam-verify.md → skills/codeyam-verify/SKILL.md} +0 -0
@@ -3,16 +3,168 @@ import net from 'net';
3
3
  import fs from 'fs';
4
4
  import path from 'path';
5
5
  import { getProjectRoot } from "../state.js";
6
+ import { createMockStateManager, } from "../utils/editorMockState.js";
7
+ import { computeEditorPorts } from "../utils/editorDevServer.js";
8
+ import { mockStateEventEmitter } from "./mockStateEvents.js";
9
+ /**
10
+ * Normalize a target URL by stripping trailing slashes for consistency.
11
+ *
12
+ * Previously this also replaced `localhost` with `127.0.0.1`, but that broke
13
+ * forwarding to dev servers that bind to IPv6 only (e.g. Vite 6 on macOS
14
+ * binds to `[::1]`). The hostname is now left as-is — `resolveLoopbackAddress`
15
+ * probes the actual target at startup to pick the right address.
16
+ */
17
+ export function normalizeTargetUrl(url) {
18
+ try {
19
+ const parsed = new URL(url);
20
+ return parsed.toString().replace(/\/$/, '');
21
+ }
22
+ catch {
23
+ return url;
24
+ }
25
+ }
26
+ /**
27
+ * Probe a localhost port to determine the correct loopback address.
28
+ * Dev servers may bind to IPv4 (127.0.0.1), IPv6 (::1), or both.
29
+ * Returns the first address that accepts a TCP connection.
30
+ */
31
+ export async function resolveLoopbackAddress(port) {
32
+ const candidates = ['127.0.0.1', '::1'];
33
+ for (const host of candidates) {
34
+ try {
35
+ const connected = await new Promise((resolve) => {
36
+ const socket = new net.Socket();
37
+ socket.setTimeout(1000);
38
+ socket.once('connect', () => {
39
+ socket.destroy();
40
+ resolve(true);
41
+ });
42
+ socket.once('error', () => {
43
+ socket.destroy();
44
+ resolve(false);
45
+ });
46
+ socket.once('timeout', () => {
47
+ socket.destroy();
48
+ resolve(false);
49
+ });
50
+ socket.connect(port, host);
51
+ });
52
+ if (connected) {
53
+ return host;
54
+ }
55
+ }
56
+ catch {
57
+ // Try next candidate
58
+ }
59
+ }
60
+ return null;
61
+ }
6
62
  // Global key so the proxy survives HMR
7
63
  const GLOBAL_KEY = '__codeyam_editor_proxy__';
64
+ // ─── Live Preview Health ─────────────────────────────────────────────
65
+ const PREVIEW_HEALTH_KEY = '__codeyam_preview_health__';
66
+ function getPreviewHealth() {
67
+ return globalThis[PREVIEW_HEALTH_KEY] ?? null;
68
+ }
69
+ function setPreviewHealth(report) {
70
+ globalThis[PREVIEW_HEALTH_KEY] = report;
71
+ }
72
+ /**
73
+ * Get the current live preview health report (read by API endpoint).
74
+ */
75
+ export function getPreviewHealthReport() {
76
+ return getPreviewHealth();
77
+ }
78
+ /**
79
+ * Reset preview health state (called when a new HTML page is served).
80
+ */
81
+ export function resetPreviewHealth() {
82
+ setPreviewHealth(null);
83
+ }
84
+ /**
85
+ * Error-catching script injected into HTML responses.
86
+ * Uses vanilla JS for maximum compatibility.
87
+ */
88
+ export const PREVIEW_HEALTH_SCRIPT = `<script data-codeyam-health>
89
+ (function() {
90
+ var errors = [];
91
+ var reported = false;
92
+ function report(type, msg, stack) {
93
+ errors.push({ type: type, message: msg, stack: stack, timestamp: Date.now() });
94
+ if (!reported) {
95
+ reported = true;
96
+ setTimeout(function() { flush(); }, 500);
97
+ }
98
+ }
99
+ function flush() {
100
+ fetch('/__codeyam__/preview-health', {
101
+ method: 'POST',
102
+ headers: { 'Content-Type': 'application/json' },
103
+ body: JSON.stringify({ errors: errors, url: location.href })
104
+ }).catch(function(){});
105
+ reported = false;
106
+ errors = [];
107
+ }
108
+ window.addEventListener('error', function(e) {
109
+ report('error', e.message, e.error && e.error.stack);
110
+ });
111
+ window.addEventListener('unhandledrejection', function(e) {
112
+ report('unhandledrejection', String(e.reason), e.reason && e.reason.stack);
113
+ });
114
+ var origError = console.error;
115
+ console.error = function() {
116
+ report('console.error', Array.prototype.join.call(arguments, ' '));
117
+ origError.apply(console, arguments);
118
+ };
119
+ window.addEventListener('load', function() {
120
+ setTimeout(function() {
121
+ var hasContent = document.body && document.body.innerText.trim().length > 0;
122
+ fetch('/__codeyam__/preview-health', {
123
+ method: 'POST',
124
+ headers: { 'Content-Type': 'application/json' },
125
+ body: JSON.stringify({
126
+ loaded: true,
127
+ hasContent: hasContent,
128
+ url: location.href,
129
+ errorCount: errors.length
130
+ })
131
+ }).catch(function(){});
132
+ }, 1000);
133
+ });
134
+ })();
135
+ </script>`;
8
136
  const CACHE_TTL_MS = 500;
9
137
  let scenarioCache = { data: null, timestamp: 0 };
138
+ // Session config extracted from the active scenario — drives cookie injection
139
+ let sessionConfig = undefined;
140
+ /** Session cookies from the seed adapter (e.g. Supabase auth tokens). */
141
+ let seedSessionCookies = undefined;
142
+ // localStorage config extracted from the active scenario — drives HTML injection
143
+ let localStorageConfig = null;
144
+ // Active scenario ID — used to gate localStorage seeding (only re-seed on switch)
145
+ let activeScenarioId = null;
146
+ // Prototype ID — used to gate a one-time localStorage.clear() when a new project is scaffolded
147
+ let currentPrototypeId = null;
148
+ // Current scenario type — 'application'/'user' for seed-based, 'component' for mock-based
149
+ let currentScenarioType = null;
150
+ // Max body size to buffer for mock matching (10MB)
151
+ const MAX_BODY_SIZE = 10 * 1024 * 1024;
10
152
  function getProxyState() {
11
153
  return globalThis[GLOBAL_KEY] ?? null;
12
154
  }
13
155
  function setProxyState(state) {
14
156
  globalThis[GLOBAL_KEY] = state;
15
157
  }
158
+ /**
159
+ * Get or create the mock state manager (survives HMR via globalThis).
160
+ */
161
+ function getMockStateManager() {
162
+ const key = '__codeyam_mock_state__';
163
+ if (!globalThis[key]) {
164
+ globalThis[key] = createMockStateManager();
165
+ }
166
+ return globalThis[key];
167
+ }
16
168
  /**
17
169
  * Get the proxy URL if the proxy is running.
18
170
  */
@@ -24,6 +176,13 @@ export function getProxyUrl() {
24
176
  }
25
177
  /**
26
178
  * Read the active scenario's mock data from disk, with brief caching.
179
+ * Feeds the data into the MockStateManager.
180
+ *
181
+ * For application/user scenarios (type-aware): only loads `externalApis`
182
+ * into the mock state manager. All DB-backed routes flow through to the
183
+ * real app (database is seeded with real data).
184
+ *
185
+ * For component scenarios (or legacy): loads all routes as before.
27
186
  */
28
187
  function readScenarioData() {
29
188
  const now = Date.now();
@@ -41,6 +200,8 @@ function readScenarioData() {
41
200
  const active = JSON.parse(fs.readFileSync(activeScenarioPath, 'utf-8'));
42
201
  const scenarioId = active.scenarioId;
43
202
  if (!scenarioId) {
203
+ // No active scenario — but may have a prototypeId for localStorage clearing
204
+ currentPrototypeId = active.prototypeId || null;
44
205
  scenarioCache = { data: null, timestamp: now };
45
206
  return null;
46
207
  }
@@ -50,9 +211,37 @@ function readScenarioData() {
50
211
  scenarioCache = { data: null, timestamp: now };
51
212
  return null;
52
213
  }
53
- const data = JSON.parse(fs.readFileSync(dataFilePath, 'utf-8'));
54
- scenarioCache = { data, timestamp: now };
55
- return data;
214
+ const rawData = JSON.parse(fs.readFileSync(dataFilePath, 'utf-8'));
215
+ // Extract session config for cookie injection
216
+ sessionConfig = rawData.session || null;
217
+ // Extract seed adapter session cookies (e.g. Supabase auth)
218
+ seedSessionCookies = rawData.sessionCookies || undefined;
219
+ // Extract localStorage config for HTML injection
220
+ localStorageConfig = rawData.localStorage || null;
221
+ activeScenarioId = scenarioId;
222
+ // Type-aware: for seed-based scenarios, only serve externalApis via proxy
223
+ const scenarioType = active.type || rawData.type || null;
224
+ currentScenarioType = scenarioType;
225
+ let mockData;
226
+ if ((scenarioType === 'application' || scenarioType === 'user') &&
227
+ rawData.seed) {
228
+ // Seed-based scenario: only load externalApis as routes for the proxy
229
+ if (rawData.externalApis && typeof rawData.externalApis === 'object') {
230
+ mockData = { routes: rawData.externalApis };
231
+ }
232
+ else {
233
+ // No external APIs — proxy passes everything through
234
+ mockData = {};
235
+ }
236
+ }
237
+ else {
238
+ // Component/legacy scenario: load all data
239
+ mockData = rawData;
240
+ }
241
+ scenarioCache = { data: mockData, timestamp: now };
242
+ // Feed into mock state manager (smart reload handles dedup)
243
+ getMockStateManager().loadScenario(mockData);
244
+ return mockData;
56
245
  }
57
246
  catch (err) {
58
247
  console.warn('[editorProxy] Error reading scenario data:', err);
@@ -61,50 +250,163 @@ function readScenarioData() {
61
250
  }
62
251
  }
63
252
  /**
64
- * Find a matching route in the scenario data.
65
- *
66
- * Supports two formats:
67
- * - New route-keyed: { "routes": { "/api/drinks": { "body": [...] } } }
68
- * - Legacy key-based: { "drinks": [...] } → matches /api/drinks
253
+ * Buffer the request body, up to MAX_BODY_SIZE.
254
+ * Returns null if the body exceeds the limit.
69
255
  */
70
- export function findMatchingRoute(pathname, scenarioData) {
71
- // New format: check routes map
72
- const routes = scenarioData.routes;
73
- if (routes && typeof routes === 'object') {
74
- const routeEntry = routes[pathname];
75
- if (routeEntry && typeof routeEntry === 'object') {
76
- const entry = routeEntry;
77
- return {
78
- body: entry.body ?? routeEntry,
79
- status: typeof entry.status === 'number' ? entry.status : 200,
80
- };
81
- }
256
+ function bufferRequestBody(req) {
257
+ return new Promise((resolve) => {
258
+ const chunks = [];
259
+ let totalSize = 0;
260
+ req.on('data', (chunk) => {
261
+ totalSize += chunk.length;
262
+ if (totalSize > MAX_BODY_SIZE) {
263
+ resolve(null); // Too large — skip mock matching
264
+ req.resume(); // Drain remaining
265
+ }
266
+ else {
267
+ chunks.push(chunk);
268
+ }
269
+ });
270
+ req.on('end', () => {
271
+ if (totalSize > MAX_BODY_SIZE)
272
+ return; // Already resolved
273
+ resolve(Buffer.concat(chunks));
274
+ });
275
+ req.on('error', () => {
276
+ resolve(null);
277
+ });
278
+ });
279
+ }
280
+ /**
281
+ * Strip IPv6 bracket notation for use with http.request hostname.
282
+ * URL.hostname returns `[::1]` for IPv6 but http.request needs `::1`.
283
+ */
284
+ function stripIPv6Brackets(hostname) {
285
+ if (hostname.startsWith('[') && hostname.endsWith(']')) {
286
+ return hostname.slice(1, -1);
287
+ }
288
+ return hostname;
289
+ }
290
+ /**
291
+ * Forward a buffered request to the target dev server.
292
+ * Unlike the streaming forwardRequest, this replays a buffered body.
293
+ */
294
+ function forwardBufferedRequest(req, res, targetUrl, bodyBuffer) {
295
+ const target = new URL(targetUrl);
296
+ const hostname = stripIPv6Brackets(target.hostname);
297
+ const headers = { ...req.headers, host: `${target.hostname}:${target.port}` };
298
+ // Remove accept-encoding so the dev server returns uncompressed responses.
299
+ // The proxy injects a health script into HTML — this fails on compressed bodies.
300
+ delete headers['accept-encoding'];
301
+ // Update content-length if we have the body buffer
302
+ if (bodyBuffer) {
303
+ headers['content-length'] = String(bodyBuffer.length);
82
304
  }
83
- // Legacy format: key "drinks" matches "/api/drinks"
84
- // Extract the last segment of the path after /api/
85
- const apiMatch = pathname.match(/^\/api\/(.+)$/);
86
- if (apiMatch) {
87
- const key = apiMatch[1];
88
- if (key in scenarioData && key !== 'routes') {
89
- return { body: scenarioData[key], status: 200 };
305
+ const options = {
306
+ hostname,
307
+ port: target.port,
308
+ path: req.url,
309
+ method: req.method,
310
+ headers,
311
+ };
312
+ const proxyReq = http.request(options, (proxyRes) => {
313
+ const status = proxyRes.statusCode || 200;
314
+ if (status >= 400) {
315
+ console.warn(`[editorProxy] Target returned ${status} for ${req.method} ${req.url}`);
316
+ }
317
+ const headers = { ...proxyRes.headers };
318
+ injectSessionCookie(headers);
319
+ // Check if response is HTML — if so, buffer and inject health script
320
+ const contentType = proxyRes.headers['content-type'] || '';
321
+ if (contentType.includes('text/html')) {
322
+ resetPreviewHealth();
323
+ const chunks = [];
324
+ proxyRes.on('data', (chunk) => chunks.push(chunk));
325
+ proxyRes.on('end', () => {
326
+ const body = Buffer.concat(chunks).toString('utf-8');
327
+ const lsScript = buildLocalStorageScript(localStorageConfig, activeScenarioId || '', currentPrototypeId);
328
+ const injected = injectHealthScript(body, lsScript);
329
+ delete headers['content-length'];
330
+ delete headers['content-encoding'];
331
+ // Prevent browser from caching HTML responses — scenario switches
332
+ // serve different content from the same URL (seed data changes the
333
+ // rendered page but the proxy URL stays the same).
334
+ headers['cache-control'] = 'no-store, must-revalidate';
335
+ res.writeHead(status, headers);
336
+ res.end(injected);
337
+ });
338
+ return;
90
339
  }
340
+ res.writeHead(status, headers);
341
+ proxyRes.pipe(res, { end: true });
342
+ });
343
+ proxyReq.on('error', (err) => {
344
+ console.warn(`[editorProxy] Forward error for ${req.method} ${req.url}: ${err.message}`);
345
+ if (!res.headersSent) {
346
+ res.writeHead(502, { 'Content-Type': 'text/plain' });
347
+ res.end('Bad Gateway — dev server unreachable');
348
+ }
349
+ });
350
+ if (bodyBuffer && bodyBuffer.length > 0) {
351
+ proxyReq.end(bodyBuffer);
352
+ }
353
+ else {
354
+ proxyReq.end();
91
355
  }
92
- return null;
93
356
  }
94
357
  /**
95
358
  * Forward an HTTP request to the target dev server.
359
+ * For HTML responses: buffers body to inject health-check script.
360
+ * For non-HTML responses: pipes directly (no buffering).
96
361
  */
97
362
  function forwardRequest(req, res, targetUrl) {
98
363
  const target = new URL(targetUrl);
364
+ const hostname = stripIPv6Brackets(target.hostname);
365
+ // Build headers, stripping accept-encoding so the dev server returns uncompressed
366
+ // responses. The proxy injects a health script into HTML — this fails on compressed bodies.
367
+ const { 'accept-encoding': _ae, ...forwardHeaders } = req.headers;
99
368
  const options = {
100
- hostname: target.hostname,
369
+ hostname,
101
370
  port: target.port,
102
371
  path: req.url,
103
372
  method: req.method,
104
- headers: { ...req.headers, host: `${target.hostname}:${target.port}` },
373
+ headers: {
374
+ ...forwardHeaders,
375
+ host: `${target.hostname}:${target.port}`,
376
+ },
105
377
  };
106
378
  const proxyReq = http.request(options, (proxyRes) => {
107
- res.writeHead(proxyRes.statusCode || 200, proxyRes.headers);
379
+ const status = proxyRes.statusCode || 200;
380
+ if (status >= 400) {
381
+ console.warn(`[editorProxy] Target returned ${status} for ${req.method} ${req.url}`);
382
+ }
383
+ const headers = { ...proxyRes.headers };
384
+ injectSessionCookie(headers);
385
+ // Check if response is HTML — if so, buffer and inject health script
386
+ const contentType = proxyRes.headers['content-type'] || '';
387
+ if (contentType.includes('text/html')) {
388
+ // Reset health state for new page loads
389
+ resetPreviewHealth();
390
+ const chunks = [];
391
+ proxyRes.on('data', (chunk) => chunks.push(chunk));
392
+ proxyRes.on('end', () => {
393
+ const body = Buffer.concat(chunks).toString('utf-8');
394
+ const lsScript = buildLocalStorageScript(localStorageConfig, activeScenarioId || '', currentPrototypeId);
395
+ const injected = injectHealthScript(body, lsScript);
396
+ // Remove content-length since body size changed; use chunked transfer
397
+ delete headers['content-length'];
398
+ // Remove content-encoding since we're serving uncompressed
399
+ delete headers['content-encoding'];
400
+ // Prevent browser from caching HTML responses — scenario switches
401
+ // serve different content from the same URL (seed data changes the
402
+ // rendered page but the proxy URL stays the same).
403
+ headers['cache-control'] = 'no-store, must-revalidate';
404
+ res.writeHead(status, headers);
405
+ res.end(injected);
406
+ });
407
+ return;
408
+ }
409
+ res.writeHead(status, headers);
108
410
  proxyRes.pipe(res, { end: true });
109
411
  });
110
412
  proxyReq.on('error', (err) => {
@@ -116,14 +418,251 @@ function forwardRequest(req, res, targetUrl) {
116
418
  });
117
419
  req.pipe(proxyReq, { end: true });
118
420
  }
421
+ /**
422
+ * Inject or clear the session-token cookie on proxied responses.
423
+ * When a scenario has session.cookieValue, sets the cookie to auto-log the user in.
424
+ * When a scenario has no session field (null), clears any existing session cookie.
425
+ * When sessionConfig is undefined (no scenario loaded yet), does nothing.
426
+ */
427
+ function injectSessionCookie(headers) {
428
+ const cookies = [];
429
+ // Dev auth cookie (built-in session-token)
430
+ if (sessionConfig !== undefined) {
431
+ if (sessionConfig?.cookieValue) {
432
+ cookies.push(`session-token=${sessionConfig.cookieValue}; Path=/; SameSite=Lax`);
433
+ }
434
+ else {
435
+ cookies.push(`session-token=; Path=/; Max-Age=0`);
436
+ }
437
+ }
438
+ // Seed adapter session cookies (e.g. Supabase auth tokens)
439
+ if (seedSessionCookies && seedSessionCookies.length > 0) {
440
+ for (const sc of seedSessionCookies) {
441
+ const cookiePath = sc.path || '/';
442
+ const sameSite = sc.sameSite || 'Lax';
443
+ cookies.push(`${sc.name}=${sc.value}; Path=${cookiePath}; SameSite=${sameSite}`);
444
+ }
445
+ }
446
+ if (cookies.length === 0)
447
+ return;
448
+ const existing = headers['set-cookie'];
449
+ if (existing) {
450
+ headers['set-cookie'] = [
451
+ ...(Array.isArray(existing) ? existing : [existing]),
452
+ ...cookies,
453
+ ];
454
+ }
455
+ else {
456
+ headers['set-cookie'] = cookies;
457
+ }
458
+ }
459
+ /**
460
+ * Get the current session config (for testing).
461
+ */
462
+ export function getSessionConfig() {
463
+ return sessionConfig;
464
+ }
465
+ /**
466
+ * Get the current localStorage config (for testing and script generation).
467
+ */
468
+ export function getLocalStorageConfig() {
469
+ return localStorageConfig;
470
+ }
471
+ /**
472
+ * Get the active scenario ID (for testing and script generation).
473
+ */
474
+ export function getActiveScenarioId() {
475
+ return activeScenarioId;
476
+ }
477
+ /**
478
+ * Get the current prototype ID (for testing).
479
+ */
480
+ export function getCurrentPrototypeId() {
481
+ return currentPrototypeId;
482
+ }
483
+ /**
484
+ * Simple djb2 hash — fast, deterministic, good enough for cache busting.
485
+ * Not cryptographic — just detects when localStorage config content changes.
486
+ */
487
+ function simpleHash(str) {
488
+ let hash = 5381;
489
+ for (let i = 0; i < str.length; i++) {
490
+ hash = ((hash << 5) + hash + str.charCodeAt(i)) | 0;
491
+ }
492
+ return (hash >>> 0).toString(36);
493
+ }
494
+ /**
495
+ * Build a script tag that seeds localStorage with scenario data on first load.
496
+ * Gated by scenario ID — only seeds when the scenario changes, preserving
497
+ * interactive modifications across page reloads / HMR.
498
+ *
499
+ * Returns empty string if no localStorage config is provided.
500
+ */
501
+ export function buildLocalStorageScript(localStorageConfig, scenarioId, prototypeId) {
502
+ // null/undefined means no localStorage config at all — but if we have a
503
+ // prototypeId, emit a one-time localStorage.clear() to flush stale data
504
+ // from a previous prototype session.
505
+ if (!localStorageConfig || typeof localStorageConfig !== 'object') {
506
+ if (prototypeId) {
507
+ return `<script data-codeyam-ls>
508
+ (function() {
509
+ if (localStorage.getItem('__codeyam_proto__') === ${JSON.stringify(prototypeId)}) return;
510
+ localStorage.clear();
511
+ localStorage.setItem('__codeyam_proto__', ${JSON.stringify(prototypeId)});
512
+ })();
513
+ </script>`;
514
+ }
515
+ return '';
516
+ }
517
+ // Even an empty object needs a cleanup script — switching from a scenario
518
+ // with localStorage data to one without must clear the previous keys.
519
+ const entries = Object.entries(localStorageConfig);
520
+ const keys = entries.map(([k]) => k);
521
+ // Build setItem calls — stringify non-string values
522
+ const setStatements = entries
523
+ .map(([key, value]) => {
524
+ const serialized = typeof value === 'string' ? value : JSON.stringify(value);
525
+ return `localStorage.setItem(${JSON.stringify(key)}, ${JSON.stringify(serialized)});`;
526
+ })
527
+ .join('\n');
528
+ // Guard value includes a content hash so re-registering a scenario with
529
+ // updated data (same ID, different content) busts the cache. Without this,
530
+ // the browser skips re-seeding because the scenario ID hasn't changed,
531
+ // causing stale data in the live preview while screenshots show fresh data.
532
+ const contentHash = simpleHash(JSON.stringify(localStorageConfig));
533
+ const guardValue = `${scenarioId}:${contentHash}`;
534
+ return (`<script data-codeyam-ls>
535
+ (function() {
536
+ if (localStorage.getItem('__codeyam_ls_sid__') === ${JSON.stringify(guardValue)}) return;
537
+ var prev = JSON.parse(localStorage.getItem('__codeyam_ls_keys__') || '[]');
538
+ for (var i = 0; i < prev.length; i++) localStorage.removeItem(prev[i]);
539
+ ${setStatements}
540
+ localStorage.setItem('__codeyam_ls_keys__', ${JSON.stringify(JSON.stringify(keys))});
541
+ localStorage.setItem('__codeyam_ls_sid__', ${JSON.stringify(guardValue)});
542
+ })();
543
+ </script>` + buildLocalStorageWatcherScript());
544
+ }
545
+ /**
546
+ * Build a script that watches for localStorage mutations and notifies the parent
547
+ * frame via postMessage. Also responds to `codeyam-get-localstorage` requests so
548
+ * the editor can read the current localStorage state when saving.
549
+ */
550
+ function buildLocalStorageWatcherScript() {
551
+ return `<script data-codeyam-ls-watcher>
552
+ (function() {
553
+ if (window.__codeyam_ls_watcher_installed__) return;
554
+ window.__codeyam_ls_watcher_installed__ = true;
555
+
556
+ var origSet = localStorage.setItem.bind(localStorage);
557
+ var origRemove = localStorage.removeItem.bind(localStorage);
558
+ var origClear = localStorage.clear.bind(localStorage);
559
+ window.__codeyam_orig_setItem__ = origSet;
560
+ window.__codeyam_orig_removeItem__ = origRemove;
561
+ window.__codeyam_orig_clear__ = origClear;
562
+
563
+ function isInternal(key) {
564
+ return typeof key === 'string' && key.indexOf('__codeyam_') === 0;
565
+ }
566
+
567
+ localStorage.setItem = function(key, value) {
568
+ origSet(key, value);
569
+ if (!isInternal(key) && window.parent !== window) {
570
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'set', key: key }, '*');
571
+ }
572
+ };
573
+
574
+ localStorage.removeItem = function(key) {
575
+ origRemove(key);
576
+ if (!isInternal(key) && window.parent !== window) {
577
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'remove', key: key }, '*');
578
+ }
579
+ };
580
+
581
+ localStorage.clear = function() {
582
+ origClear();
583
+ if (window.parent !== window) {
584
+ window.parent.postMessage({ type: 'codeyam-localstorage-changed', action: 'clear' }, '*');
585
+ }
586
+ };
587
+
588
+ window.addEventListener('message', function(event) {
589
+ if (event.data && event.data.type === 'codeyam-get-localstorage') {
590
+ var data = {};
591
+ for (var i = 0; i < localStorage.length; i++) {
592
+ var k = localStorage.key(i);
593
+ if (k && !isInternal(k)) {
594
+ data[k] = localStorage.getItem(k);
595
+ }
596
+ }
597
+ event.source.postMessage({ type: 'codeyam-localstorage-state', data: data }, '*');
598
+ }
599
+ });
600
+ })();
601
+ </script>`;
602
+ }
603
+ /**
604
+ * Inject the health-check script (and optional localStorage script) into an HTML response body.
605
+ * Inserts before </head> if present, otherwise before </body>, otherwise appends.
606
+ * When a localStorageScript is provided, it's injected BEFORE the health script
607
+ * so localStorage is populated before the app loads.
608
+ */
609
+ export function injectHealthScript(html, localStorageScript) {
610
+ const scripts = (localStorageScript || '') + PREVIEW_HEALTH_SCRIPT;
611
+ if (html.includes('</head>')) {
612
+ return html.replace('</head>', scripts + '</head>');
613
+ }
614
+ if (html.includes('</body>')) {
615
+ return html.replace('</body>', scripts + '</body>');
616
+ }
617
+ return html + scripts;
618
+ }
619
+ /**
620
+ * Handle POST /__codeyam__/preview-health — store health data in globalThis.
621
+ */
622
+ function handlePreviewHealthPost(req, res) {
623
+ const chunks = [];
624
+ req.on('data', (chunk) => chunks.push(chunk));
625
+ req.on('end', () => {
626
+ try {
627
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf-8'));
628
+ const current = getPreviewHealth() || {
629
+ errors: [],
630
+ loaded: false,
631
+ hasContent: false,
632
+ url: '',
633
+ lastUpdated: 0,
634
+ };
635
+ if (body.errors && Array.isArray(body.errors)) {
636
+ current.errors = current.errors.concat(body.errors);
637
+ }
638
+ if (body.loaded !== undefined) {
639
+ current.loaded = body.loaded;
640
+ }
641
+ if (body.hasContent !== undefined) {
642
+ current.hasContent = body.hasContent;
643
+ }
644
+ if (body.url) {
645
+ current.url = body.url;
646
+ }
647
+ current.lastUpdated = Date.now();
648
+ setPreviewHealth(current);
649
+ }
650
+ catch {
651
+ // Ignore malformed JSON
652
+ }
653
+ res.writeHead(204);
654
+ res.end();
655
+ });
656
+ }
119
657
  /**
120
658
  * Handle WebSocket upgrade by piping to the target dev server.
121
659
  */
122
660
  function handleUpgrade(req, socket, head, targetUrl) {
123
661
  const target = new URL(targetUrl);
662
+ const hostname = stripIPv6Brackets(target.hostname);
124
663
  const port = parseInt(target.port, 10) || 80;
125
- console.log(`[editorProxy] WebSocket upgrade: ${req.url} → ${target.hostname}:${port}`);
126
- const proxySocket = net.connect(port, target.hostname, () => {
664
+ console.log(`[editorProxy] WebSocket upgrade: ${req.url} → ${hostname}:${port}`);
665
+ const proxySocket = net.connect(port, hostname, () => {
127
666
  // Reconstruct the HTTP upgrade request
128
667
  const requestLine = `${req.method} ${req.url} HTTP/${req.httpVersion}\r\n`;
129
668
  const headers = Object.entries(req.headers)
@@ -146,38 +685,157 @@ function handleUpgrade(req, socket, head, targetUrl) {
146
685
  proxySocket.destroy();
147
686
  });
148
687
  }
688
+ /**
689
+ * Write proxy-config.json so the preload module can discover the proxy.
690
+ */
691
+ function writeProxyConfig(proxyPort, targetUrl) {
692
+ const projectRoot = getProjectRoot() || process.env.CODEYAM_ROOT_PATH || process.cwd();
693
+ const configPath = path.join(projectRoot, '.codeyam', 'proxy-config.json');
694
+ try {
695
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
696
+ fs.writeFileSync(configPath, JSON.stringify({
697
+ proxyUrl: `http://localhost:${proxyPort}`,
698
+ devServerUrl: targetUrl,
699
+ }), 'utf-8');
700
+ console.log(`[editorProxy] Wrote proxy config to ${configPath}`);
701
+ }
702
+ catch (err) {
703
+ console.warn('[editorProxy] Failed to write proxy-config.json:', err);
704
+ }
705
+ }
706
+ /**
707
+ * Remove proxy-config.json on proxy stop.
708
+ */
709
+ function removeProxyConfig() {
710
+ const projectRoot = getProjectRoot() || process.env.CODEYAM_ROOT_PATH || process.cwd();
711
+ const configPath = path.join(projectRoot, '.codeyam', 'proxy-config.json');
712
+ try {
713
+ if (fs.existsSync(configPath)) {
714
+ fs.unlinkSync(configPath);
715
+ }
716
+ }
717
+ catch {
718
+ // Best effort
719
+ }
720
+ }
149
721
  /**
150
722
  * Start the editor proxy server.
151
- * Intercepts GET requests to API routes matching the active scenario, forwards everything else.
723
+ * Intercepts requests to API routes matching the active scenario, forwards everything else.
724
+ * Supports all HTTP methods (GET, POST, PUT, DELETE, PATCH) with body buffering.
152
725
  */
153
726
  export async function startEditorProxy(options) {
154
- // Stop existing proxy first
727
+ // If proxy is already running, reuse it (prevents second tab from killing first tab's proxy)
728
+ const existing = getProxyState();
729
+ if (existing) {
730
+ console.log(`[editorProxy] Proxy already running on port ${existing.port} → ${existing.targetUrl}`);
731
+ return { port: existing.port };
732
+ }
733
+ // Stop any leftover state (shouldn't happen, but defensive)
155
734
  await stopEditorProxy();
156
- const { targetUrl } = options;
735
+ let targetUrl = normalizeTargetUrl(options.targetUrl);
157
736
  let port = options.port;
737
+ // When the target is localhost, probe to find the correct loopback address.
738
+ // Dev servers may bind to IPv4 (127.0.0.1) or IPv6 (::1) — Vite 6 on macOS
739
+ // binds to ::1 by default. We need to match the actual binding.
740
+ try {
741
+ const parsed = new URL(targetUrl);
742
+ if (parsed.hostname === 'localhost') {
743
+ const targetPort = parseInt(parsed.port || '80', 10);
744
+ const resolvedHost = await resolveLoopbackAddress(targetPort);
745
+ if (resolvedHost) {
746
+ parsed.hostname = resolvedHost;
747
+ targetUrl = parsed.toString().replace(/\/$/, '');
748
+ console.log(`[editorProxy] Resolved localhost to ${resolvedHost} for port ${targetPort}`);
749
+ }
750
+ }
751
+ }
752
+ catch {
753
+ // Keep original targetUrl
754
+ }
158
755
  console.log(`[editorProxy] Starting proxy (requested port ${port}, target ${targetUrl})`);
756
+ const mockState = getMockStateManager();
159
757
  const server = http.createServer((req, res) => {
160
- const parsedUrl = new URL(req.url || '/', `http://localhost:${port}`);
161
- const pathname = parsedUrl.pathname;
162
- // Only intercept GET requests
163
- if (req.method === 'GET') {
164
- const scenarioData = readScenarioData();
165
- if (scenarioData) {
166
- const match = findMatchingRoute(pathname, scenarioData);
758
+ void (async () => {
759
+ const parsedUrl = new URL(req.url || '/', `http://localhost:${port}`);
760
+ const pathname = parsedUrl.pathname;
761
+ const method = req.method || 'GET';
762
+ // CORS preflight — permissive 204 for browser cross-origin requests
763
+ if (method === 'OPTIONS') {
764
+ res.writeHead(204, {
765
+ 'Access-Control-Allow-Origin': '*',
766
+ 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, PATCH, OPTIONS',
767
+ 'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
768
+ 'Access-Control-Max-Age': '86400',
769
+ });
770
+ res.end();
771
+ return;
772
+ }
773
+ // Intercept preview health reports from the injected script
774
+ if (method === 'POST' && pathname === '/__codeyam__/preview-health') {
775
+ handlePreviewHealthPost(req, res);
776
+ return;
777
+ }
778
+ // Load scenario data (also feeds MockStateManager)
779
+ readScenarioData();
780
+ // For methods that may carry a body, buffer it first
781
+ const needsBody = method === 'POST' ||
782
+ method === 'PUT' ||
783
+ method === 'DELETE' ||
784
+ method === 'PATCH';
785
+ if (needsBody) {
786
+ const bodyBuffer = await bufferRequestBody(req);
787
+ if (bodyBuffer === null) {
788
+ // Body too large — forward without mock matching
789
+ forwardBufferedRequest(req, res, targetUrl, null);
790
+ return;
791
+ }
792
+ // Try to parse body as JSON for mock matching
793
+ let parsedBody = undefined;
794
+ if (bodyBuffer.length > 0) {
795
+ try {
796
+ parsedBody = JSON.parse(bodyBuffer.toString('utf-8'));
797
+ }
798
+ catch {
799
+ // Not JSON — that's fine, still try mock matching without parsed body
800
+ }
801
+ }
802
+ const match = mockState.matchRequest(method, pathname, parsedBody);
167
803
  if (match) {
168
- console.log(`[editorProxy] Intercepted ${req.method} ${pathname} → scenario data (status ${match.status})`);
804
+ console.log(`[editorProxy] Intercepted ${method} ${pathname} → mock response (status ${match.status})`);
169
805
  res.writeHead(match.status, {
170
806
  'Content-Type': 'application/json',
171
807
  'Access-Control-Allow-Origin': '*',
172
808
  'X-CodeYam-Proxy': 'scenario-data',
809
+ 'Cache-Control': 'no-store',
173
810
  });
174
- res.end(JSON.stringify(match.body));
811
+ res.end(match.body != null ? JSON.stringify(match.body) : '');
175
812
  return;
176
813
  }
814
+ // No mock match — forward with buffered body
815
+ if ((currentScenarioType === 'application' ||
816
+ currentScenarioType === 'user') &&
817
+ pathname.startsWith('/api/')) {
818
+ mockStateEventEmitter.emitDataMutationForwarded(method, pathname);
819
+ }
820
+ forwardBufferedRequest(req, res, targetUrl, bodyBuffer);
821
+ return;
177
822
  }
178
- }
179
- // Forward everything else to the dev server
180
- forwardRequest(req, res, targetUrl);
823
+ // GET, HEAD, etc. — try mock matching (no body)
824
+ const match = mockState.matchRequest(method, pathname);
825
+ if (match) {
826
+ console.log(`[editorProxy] Intercepted ${method} ${pathname} → mock response (status ${match.status})`);
827
+ res.writeHead(match.status, {
828
+ 'Content-Type': 'application/json',
829
+ 'Access-Control-Allow-Origin': '*',
830
+ 'X-CodeYam-Proxy': 'scenario-data',
831
+ 'Cache-Control': 'no-store',
832
+ });
833
+ res.end(match.body != null ? JSON.stringify(match.body) : '');
834
+ return;
835
+ }
836
+ // Forward everything else to the dev server
837
+ forwardRequest(req, res, targetUrl);
838
+ })();
181
839
  });
182
840
  // Handle WebSocket upgrades (for HMR)
183
841
  server.on('upgrade', (req, socket, head) => {
@@ -195,9 +853,14 @@ export async function startEditorProxy(options) {
195
853
  resolve();
196
854
  });
197
855
  });
198
- port = currentPort;
856
+ // When port 0 is requested, the OS assigns an ephemeral port
857
+ const addr = server.address();
858
+ port =
859
+ typeof addr === 'object' && addr !== null ? addr.port : currentPort;
199
860
  const state = { server, port, targetUrl };
200
861
  setProxyState(state);
862
+ // Write proxy-config.json for the preload module
863
+ writeProxyConfig(port, targetUrl);
201
864
  console.log(`[editorProxy] Proxy started on port ${port}, forwarding to ${targetUrl}`);
202
865
  return { port };
203
866
  }
@@ -220,6 +883,7 @@ export async function stopEditorProxy() {
220
883
  if (!state)
221
884
  return;
222
885
  console.log(`[editorProxy] Stopping proxy on port ${state.port}`);
886
+ removeProxyConfig();
223
887
  return new Promise((resolve) => {
224
888
  state.server.close(() => {
225
889
  console.log('[editorProxy] Proxy stopped');
@@ -235,6 +899,41 @@ export async function stopEditorProxy() {
235
899
  */
236
900
  export function invalidateScenarioCache() {
237
901
  scenarioCache = { data: null, timestamp: 0 };
902
+ sessionConfig = undefined;
903
+ seedSessionCookies = undefined;
904
+ localStorageConfig = null;
905
+ activeScenarioId = null;
906
+ currentPrototypeId = null;
907
+ }
908
+ /**
909
+ * Verify that the proxy can successfully forward a request to the target dev server.
910
+ * Makes a HEAD request through the proxy and checks that it gets a response (any status).
911
+ * Returns false if the proxy isn't running or if the request fails entirely.
912
+ */
913
+ export async function verifyProxyForwarding() {
914
+ const state = getProxyState();
915
+ if (!state) {
916
+ console.warn('[editorProxy] Cannot verify — proxy is not running');
917
+ return false;
918
+ }
919
+ try {
920
+ const response = await fetch(`http://127.0.0.1:${state.port}/`, {
921
+ method: 'HEAD',
922
+ signal: AbortSignal.timeout(5000),
923
+ });
924
+ // Any response from the target (even 404) means forwarding works.
925
+ // Only 502 (our own Bad Gateway) means the target is unreachable.
926
+ if (response.status === 502) {
927
+ console.warn(`[editorProxy] Verification failed — proxy returned 502 (target unreachable)`);
928
+ return false;
929
+ }
930
+ console.log(`[editorProxy] Verification passed — proxy forwarding to ${state.targetUrl} (status ${response.status})`);
931
+ return true;
932
+ }
933
+ catch (err) {
934
+ console.warn(`[editorProxy] Verification failed — could not reach proxy on port ${state.port}`);
935
+ return false;
936
+ }
238
937
  }
239
938
  /**
240
939
  * Ensure the proxy is running. If it's not, start it using the current dev server URL.
@@ -256,9 +955,10 @@ export async function ensureProxyRunning() {
256
955
  return null;
257
956
  }
258
957
  const codeyamPort = parseInt(process.env.CODEYAM_PORT || '3111', 10);
259
- console.log(`[editorProxy] Proxy not running, starting on-demand (port ${codeyamPort + 1}, target ${devServer.url})`);
958
+ const { proxyPort } = computeEditorPorts(codeyamPort);
959
+ console.log(`[editorProxy] Proxy not running, starting on-demand (port ${proxyPort}, target ${devServer.url})`);
260
960
  const result = await startEditorProxy({
261
- port: codeyamPort + 1,
961
+ port: proxyPort,
262
962
  targetUrl: devServer.url,
263
963
  });
264
964
  if (result) {
@@ -269,4 +969,8 @@ export async function ensureProxyRunning() {
269
969
  console.error('[editorProxy] Failed to start on-demand proxy');
270
970
  return null;
271
971
  }
972
+ /**
973
+ * Test-only export: trigger readScenarioData so tests can verify session config extraction.
974
+ */
975
+ export const _readScenarioDataForTest = readScenarioData;
272
976
  //# sourceMappingURL=editorProxy.js.map