@rien7/seji 0.0.0 → 0.6.1

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 (414) hide show
  1. package/bin/design-surface.mjs +6 -0
  2. package/bin/postinstall.mjs +19 -0
  3. package/bin/seji.mjs +585 -0
  4. package/dist/agent/host.d.mts +34 -0
  5. package/dist/agent/host.mjs +387 -0
  6. package/dist/agent/messages.d.mts +9 -0
  7. package/dist/agent/messages.mjs +70 -0
  8. package/dist/agent/runtimes.mjs +157 -0
  9. package/dist/cli/app.mjs +321 -0
  10. package/dist/cli/appScan.mjs +284 -0
  11. package/dist/cli/catalog.mjs +78 -0
  12. package/dist/cli/component.mjs +165 -0
  13. package/dist/cli/consolidate.mjs +159 -0
  14. package/dist/cli/cssImport.mjs +68 -0
  15. package/dist/cli/dev.mjs +339 -0
  16. package/dist/cli/doctor.mjs +311 -0
  17. package/dist/cli/init.mjs +338 -0
  18. package/dist/cli/legacyNames.mjs +266 -0
  19. package/dist/cli/migrate.mjs +163 -0
  20. package/dist/cli/prompt.mjs +34 -0
  21. package/dist/cli/propose.mjs +208 -0
  22. package/dist/cli/providers.mjs +344 -0
  23. package/dist/cli/reviewOps.mjs +110 -0
  24. package/dist/cli/semver.mjs +45 -0
  25. package/dist/cli/setup.mjs +360 -0
  26. package/dist/cli/sketches.mjs +47 -0
  27. package/dist/cli/skills.mjs +150 -0
  28. package/dist/cli/snapshot.mjs +107 -0
  29. package/dist/cli/tokenOps.mjs +120 -0
  30. package/dist/cli/types.mjs +191 -0
  31. package/dist/cli/updater.mjs +274 -0
  32. package/dist/components/astIndex.mjs +992 -0
  33. package/dist/components/ops.mjs +1069 -0
  34. package/dist/editor/AgentProposalCard.d.ts +10 -0
  35. package/dist/editor/AgentProposalCard.d.ts.map +1 -0
  36. package/dist/editor/AgentProposalCard.js +31 -0
  37. package/dist/editor/AgentProposalCard.js.map +1 -0
  38. package/dist/editor/App.d.ts +2 -0
  39. package/dist/editor/App.d.ts.map +1 -0
  40. package/dist/editor/App.js +2834 -0
  41. package/dist/editor/App.js.map +1 -0
  42. package/dist/editor/CanvasHud.d.ts +12 -0
  43. package/dist/editor/CanvasHud.d.ts.map +1 -0
  44. package/dist/editor/CanvasHud.js +13 -0
  45. package/dist/editor/CanvasHud.js.map +1 -0
  46. package/dist/editor/CanvasSurface.d.ts +31 -0
  47. package/dist/editor/CanvasSurface.d.ts.map +1 -0
  48. package/dist/editor/CanvasSurface.js +270 -0
  49. package/dist/editor/CanvasSurface.js.map +1 -0
  50. package/dist/editor/CommentPopover.d.ts +17 -0
  51. package/dist/editor/CommentPopover.d.ts.map +1 -0
  52. package/dist/editor/CommentPopover.js +62 -0
  53. package/dist/editor/CommentPopover.js.map +1 -0
  54. package/dist/editor/Comments.d.ts +13 -0
  55. package/dist/editor/Comments.d.ts.map +1 -0
  56. package/dist/editor/Comments.js +41 -0
  57. package/dist/editor/Comments.js.map +1 -0
  58. package/dist/editor/ComponentPage.d.ts +28 -0
  59. package/dist/editor/ComponentPage.d.ts.map +1 -0
  60. package/dist/editor/ComponentPage.js +55 -0
  61. package/dist/editor/ComponentPage.js.map +1 -0
  62. package/dist/editor/ComponentPanel.d.ts +38 -0
  63. package/dist/editor/ComponentPanel.d.ts.map +1 -0
  64. package/dist/editor/ComponentPanel.js +275 -0
  65. package/dist/editor/ComponentPanel.js.map +1 -0
  66. package/dist/editor/Glyph.d.ts +51 -0
  67. package/dist/editor/Glyph.d.ts.map +1 -0
  68. package/dist/editor/Glyph.js +50 -0
  69. package/dist/editor/Glyph.js.map +1 -0
  70. package/dist/editor/History.d.ts +7 -0
  71. package/dist/editor/History.d.ts.map +1 -0
  72. package/dist/editor/History.js +51 -0
  73. package/dist/editor/History.js.map +1 -0
  74. package/dist/editor/Inspector.d.ts +56 -0
  75. package/dist/editor/Inspector.d.ts.map +1 -0
  76. package/dist/editor/Inspector.js +510 -0
  77. package/dist/editor/Inspector.js.map +1 -0
  78. package/dist/editor/LazyMount.d.ts +10 -0
  79. package/dist/editor/LazyMount.d.ts.map +1 -0
  80. package/dist/editor/LazyMount.js +29 -0
  81. package/dist/editor/LazyMount.js.map +1 -0
  82. package/dist/editor/LocaleSwitch.d.ts +3 -0
  83. package/dist/editor/LocaleSwitch.d.ts.map +1 -0
  84. package/dist/editor/LocaleSwitch.js +9 -0
  85. package/dist/editor/LocaleSwitch.js.map +1 -0
  86. package/dist/editor/PreviewFrame.d.ts +10 -0
  87. package/dist/editor/PreviewFrame.d.ts.map +1 -0
  88. package/dist/editor/PreviewFrame.js +22 -0
  89. package/dist/editor/PreviewFrame.js.map +1 -0
  90. package/dist/editor/ProjectIndex.d.ts +12 -0
  91. package/dist/editor/ProjectIndex.d.ts.map +1 -0
  92. package/dist/editor/ProjectIndex.js +43 -0
  93. package/dist/editor/ProjectIndex.js.map +1 -0
  94. package/dist/editor/PromoteComponent.d.ts +28 -0
  95. package/dist/editor/PromoteComponent.d.ts.map +1 -0
  96. package/dist/editor/PromoteComponent.js +33 -0
  97. package/dist/editor/PromoteComponent.js.map +1 -0
  98. package/dist/editor/PromoteForm.d.ts +18 -0
  99. package/dist/editor/PromoteForm.d.ts.map +1 -0
  100. package/dist/editor/PromoteForm.js +35 -0
  101. package/dist/editor/PromoteForm.js.map +1 -0
  102. package/dist/editor/PromoteToken.d.ts +31 -0
  103. package/dist/editor/PromoteToken.d.ts.map +1 -0
  104. package/dist/editor/PromoteToken.js +94 -0
  105. package/dist/editor/PromoteToken.js.map +1 -0
  106. package/dist/editor/StatePreviews.d.ts +28 -0
  107. package/dist/editor/StatePreviews.d.ts.map +1 -0
  108. package/dist/editor/StatePreviews.js +113 -0
  109. package/dist/editor/StatePreviews.js.map +1 -0
  110. package/dist/editor/ValueCombo.d.ts +51 -0
  111. package/dist/editor/ValueCombo.d.ts.map +1 -0
  112. package/dist/editor/ValueCombo.js +260 -0
  113. package/dist/editor/ValueCombo.js.map +1 -0
  114. package/dist/editor/agent/AgentPanel.d.ts +19 -0
  115. package/dist/editor/agent/AgentPanel.d.ts.map +1 -0
  116. package/dist/editor/agent/AgentPanel.js +271 -0
  117. package/dist/editor/agent/AgentPanel.js.map +1 -0
  118. package/dist/editor/agent/Markdown.d.ts +5 -0
  119. package/dist/editor/agent/Markdown.d.ts.map +1 -0
  120. package/dist/editor/agent/Markdown.js +28 -0
  121. package/dist/editor/agent/Markdown.js.map +1 -0
  122. package/dist/editor/agent/agentApi.d.ts +106 -0
  123. package/dist/editor/agent/agentApi.d.ts.map +1 -0
  124. package/dist/editor/agent/agentApi.js +66 -0
  125. package/dist/editor/agent/agentApi.js.map +1 -0
  126. package/dist/editor/agent/toolLines.d.ts +38 -0
  127. package/dist/editor/agent/toolLines.d.ts.map +1 -0
  128. package/dist/editor/agent/toolLines.js +159 -0
  129. package/dist/editor/agent/toolLines.js.map +1 -0
  130. package/dist/editor/agent/useAgent.d.ts +15 -0
  131. package/dist/editor/agent/useAgent.d.ts.map +1 -0
  132. package/dist/editor/agent/useAgent.js +65 -0
  133. package/dist/editor/agent/useAgent.js.map +1 -0
  134. package/dist/editor/api.d.ts +378 -0
  135. package/dist/editor/api.d.ts.map +1 -0
  136. package/dist/editor/api.js +247 -0
  137. package/dist/editor/api.js.map +1 -0
  138. package/dist/editor/camera.d.ts +18 -0
  139. package/dist/editor/camera.d.ts.map +1 -0
  140. package/dist/editor/camera.js +40 -0
  141. package/dist/editor/camera.js.map +1 -0
  142. package/dist/editor/canvas.d.ts +25 -0
  143. package/dist/editor/canvas.d.ts.map +1 -0
  144. package/dist/editor/canvas.js +35 -0
  145. package/dist/editor/canvas.js.map +1 -0
  146. package/dist/editor/changes/ChangesPage.d.ts +25 -0
  147. package/dist/editor/changes/ChangesPage.d.ts.map +1 -0
  148. package/dist/editor/changes/ChangesPage.js +132 -0
  149. package/dist/editor/changes/ChangesPage.js.map +1 -0
  150. package/dist/editor/changes/changeModel.d.ts +25 -0
  151. package/dist/editor/changes/changeModel.d.ts.map +1 -0
  152. package/dist/editor/changes/changeModel.js +81 -0
  153. package/dist/editor/changes/changeModel.js.map +1 -0
  154. package/dist/editor/changes/changeState.d.mts +29 -0
  155. package/dist/editor/changes/changeState.mjs +187 -0
  156. package/dist/editor/chrome/EditorChrome.d.ts +49 -0
  157. package/dist/editor/chrome/EditorChrome.d.ts.map +1 -0
  158. package/dist/editor/chrome/EditorChrome.js +21 -0
  159. package/dist/editor/chrome/EditorChrome.js.map +1 -0
  160. package/dist/editor/drafts.d.ts +46 -0
  161. package/dist/editor/drafts.d.ts.map +1 -0
  162. package/dist/editor/drafts.js +38 -0
  163. package/dist/editor/drafts.js.map +1 -0
  164. package/dist/editor/i18n.d.ts +29 -0
  165. package/dist/editor/i18n.d.ts.map +1 -0
  166. package/dist/editor/i18n.js +2320 -0
  167. package/dist/editor/i18n.js.map +1 -0
  168. package/dist/editor/iconStroke.d.ts +6 -0
  169. package/dist/editor/iconStroke.d.ts.map +1 -0
  170. package/dist/editor/iconStroke.js +6 -0
  171. package/dist/editor/iconStroke.js.map +1 -0
  172. package/dist/editor/main.d.ts +2 -0
  173. package/dist/editor/main.d.ts.map +1 -0
  174. package/dist/editor/main.js +14 -0
  175. package/dist/editor/main.js.map +1 -0
  176. package/dist/editor/model.d.ts +16 -0
  177. package/dist/editor/model.d.ts.map +1 -0
  178. package/dist/editor/model.js +11 -0
  179. package/dist/editor/model.js.map +1 -0
  180. package/dist/editor/reasons.d.ts +44 -0
  181. package/dist/editor/reasons.d.ts.map +1 -0
  182. package/dist/editor/reasons.js +131 -0
  183. package/dist/editor/reasons.js.map +1 -0
  184. package/dist/editor/reviewLifecycle.d.ts +8 -0
  185. package/dist/editor/reviewLifecycle.d.ts.map +1 -0
  186. package/dist/editor/reviewLifecycle.js +21 -0
  187. package/dist/editor/reviewLifecycle.js.map +1 -0
  188. package/dist/editor/styles.css +8737 -0
  189. package/dist/editor/tokenMatch.d.ts +59 -0
  190. package/dist/editor/tokenMatch.d.ts.map +1 -0
  191. package/dist/editor/tokenMatch.js +198 -0
  192. package/dist/editor/tokenMatch.js.map +1 -0
  193. package/dist/editor/tokens/ConsolidatePage.d.ts +16 -0
  194. package/dist/editor/tokens/ConsolidatePage.d.ts.map +1 -0
  195. package/dist/editor/tokens/ConsolidatePage.js +244 -0
  196. package/dist/editor/tokens/ConsolidatePage.js.map +1 -0
  197. package/dist/editor/tokens/TokenActivity.d.ts +18 -0
  198. package/dist/editor/tokens/TokenActivity.d.ts.map +1 -0
  199. package/dist/editor/tokens/TokenActivity.js +18 -0
  200. package/dist/editor/tokens/TokenActivity.js.map +1 -0
  201. package/dist/editor/tokens/TokenDialogs.d.ts +26 -0
  202. package/dist/editor/tokens/TokenDialogs.d.ts.map +1 -0
  203. package/dist/editor/tokens/TokenDialogs.js +119 -0
  204. package/dist/editor/tokens/TokenDialogs.js.map +1 -0
  205. package/dist/editor/tokens/TokenList.d.ts +21 -0
  206. package/dist/editor/tokens/TokenList.d.ts.map +1 -0
  207. package/dist/editor/tokens/TokenList.js +98 -0
  208. package/dist/editor/tokens/TokenList.js.map +1 -0
  209. package/dist/editor/tokens/TokenPage.d.ts +25 -0
  210. package/dist/editor/tokens/TokenPage.d.ts.map +1 -0
  211. package/dist/editor/tokens/TokenPage.js +108 -0
  212. package/dist/editor/tokens/TokenPage.js.map +1 -0
  213. package/dist/editor/tokens/tokenModel.d.ts +35 -0
  214. package/dist/editor/tokens/tokenModel.d.ts.map +1 -0
  215. package/dist/editor/tokens/tokenModel.js +72 -0
  216. package/dist/editor/tokens/tokenModel.js.map +1 -0
  217. package/dist/editor/ui/Button.d.ts +3 -0
  218. package/dist/editor/ui/Button.d.ts.map +1 -0
  219. package/dist/editor/ui/Button.js +6 -0
  220. package/dist/editor/ui/Button.js.map +1 -0
  221. package/dist/editor/ui/CommentBox.d.ts +23 -0
  222. package/dist/editor/ui/CommentBox.d.ts.map +1 -0
  223. package/dist/editor/ui/CommentBox.js +41 -0
  224. package/dist/editor/ui/CommentBox.js.map +1 -0
  225. package/dist/editor/ui/Icon.d.ts +8 -0
  226. package/dist/editor/ui/Icon.d.ts.map +1 -0
  227. package/dist/editor/ui/Icon.js +6 -0
  228. package/dist/editor/ui/Icon.js.map +1 -0
  229. package/dist/editor/ui/IconButton.d.ts +11 -0
  230. package/dist/editor/ui/IconButton.d.ts.map +1 -0
  231. package/dist/editor/ui/IconButton.js +6 -0
  232. package/dist/editor/ui/IconButton.js.map +1 -0
  233. package/dist/editor/ui/NumberInput.d.ts +14 -0
  234. package/dist/editor/ui/NumberInput.d.ts.map +1 -0
  235. package/dist/editor/ui/NumberInput.js +6 -0
  236. package/dist/editor/ui/NumberInput.js.map +1 -0
  237. package/dist/editor/ui/PageLine.d.ts +14 -0
  238. package/dist/editor/ui/PageLine.d.ts.map +1 -0
  239. package/dist/editor/ui/PageLine.js +7 -0
  240. package/dist/editor/ui/PageLine.js.map +1 -0
  241. package/dist/editor/ui/SearchPicker.d.ts +41 -0
  242. package/dist/editor/ui/SearchPicker.d.ts.map +1 -0
  243. package/dist/editor/ui/SearchPicker.js +82 -0
  244. package/dist/editor/ui/SearchPicker.js.map +1 -0
  245. package/dist/editor/ui/Select.d.ts +19 -0
  246. package/dist/editor/ui/Select.d.ts.map +1 -0
  247. package/dist/editor/ui/Select.js +12 -0
  248. package/dist/editor/ui/Select.js.map +1 -0
  249. package/dist/editor/ui/TokenField.d.ts +14 -0
  250. package/dist/editor/ui/TokenField.d.ts.map +1 -0
  251. package/dist/editor/ui/TokenField.js +41 -0
  252. package/dist/editor/ui/TokenField.js.map +1 -0
  253. package/dist/editor/ui/TokenPicker.d.ts +31 -0
  254. package/dist/editor/ui/TokenPicker.d.ts.map +1 -0
  255. package/dist/editor/ui/TokenPicker.js +26 -0
  256. package/dist/editor/ui/TokenPicker.js.map +1 -0
  257. package/dist/editor/useBuildError.d.ts +7 -0
  258. package/dist/editor/useBuildError.d.ts.map +1 -0
  259. package/dist/editor/useBuildError.js +30 -0
  260. package/dist/editor/useBuildError.js.map +1 -0
  261. package/dist/editor/useLatestRequest.d.ts +22 -0
  262. package/dist/editor/useLatestRequest.d.ts.map +1 -0
  263. package/dist/editor/useLatestRequest.js +49 -0
  264. package/dist/editor/useLatestRequest.js.map +1 -0
  265. package/dist/editor-bundle/editor.css +2 -0
  266. package/dist/editor-bundle/editor.js +83 -0
  267. package/dist/editor-ui.d.ts +15 -0
  268. package/dist/editor-ui.d.ts.map +1 -0
  269. package/dist/editor-ui.js +14 -0
  270. package/dist/editor-ui.js.map +1 -0
  271. package/dist/inspector/runtime.d.ts +18 -0
  272. package/dist/inspector/runtime.d.ts.map +1 -0
  273. package/dist/inspector/runtime.js +1280 -0
  274. package/dist/inspector/runtime.js.map +1 -0
  275. package/dist/preview/main.d.ts +3 -0
  276. package/dist/preview/main.d.ts.map +1 -0
  277. package/dist/preview/main.js +320 -0
  278. package/dist/preview/main.js.map +1 -0
  279. package/dist/preview/preview.css +40 -0
  280. package/dist/runtime/index.d.ts +3 -0
  281. package/dist/runtime/index.d.ts.map +1 -0
  282. package/dist/runtime/index.js +2 -0
  283. package/dist/runtime/index.js.map +1 -0
  284. package/dist/shared/buildError.d.mts +27 -0
  285. package/dist/shared/buildError.mjs +141 -0
  286. package/dist/shared/cameraFit.d.mts +16 -0
  287. package/dist/shared/cameraFit.mjs +47 -0
  288. package/dist/shared/canvasLayout.d.mts +13 -0
  289. package/dist/shared/canvasLayout.mjs +171 -0
  290. package/dist/shared/commentShots.d.mts +12 -0
  291. package/dist/shared/commentShots.mjs +53 -0
  292. package/dist/shared/componentExtract.d.mts +43 -0
  293. package/dist/shared/componentExtract.mjs +136 -0
  294. package/dist/shared/componentMeta.d.mts +26 -0
  295. package/dist/shared/componentMeta.mjs +87 -0
  296. package/dist/shared/componentOps.d.mts +70 -0
  297. package/dist/shared/componentOps.mjs +407 -0
  298. package/dist/shared/componentTarget.d.mts +15 -0
  299. package/dist/shared/componentTarget.mjs +58 -0
  300. package/dist/shared/components.d.mts +30 -0
  301. package/dist/shared/components.mjs +106 -0
  302. package/dist/shared/consolidateCategories.d.mts +2 -0
  303. package/dist/shared/consolidateCategories.mjs +6 -0
  304. package/dist/shared/env.d.mts +4 -0
  305. package/dist/shared/env.mjs +18 -0
  306. package/dist/shared/gitChanges.d.mts +2 -0
  307. package/dist/shared/gitChanges.mjs +30 -0
  308. package/dist/shared/legacyPaths.d.mts +1 -0
  309. package/dist/shared/legacyPaths.mjs +9 -0
  310. package/dist/shared/oklab.d.mts +6 -0
  311. package/dist/shared/oklab.mjs +56 -0
  312. package/dist/shared/optimizeEntries.d.mts +5 -0
  313. package/dist/shared/optimizeEntries.mjs +24 -0
  314. package/dist/shared/packages.d.mts +11 -0
  315. package/dist/shared/packages.mjs +96 -0
  316. package/dist/shared/projectFiles.d.mts +23 -0
  317. package/dist/shared/projectFiles.mjs +72 -0
  318. package/dist/shared/prompt.d.mts +25 -0
  319. package/dist/shared/prompt.mjs +217 -0
  320. package/dist/shared/proposals.d.mts +11 -0
  321. package/dist/shared/proposals.mjs +42 -0
  322. package/dist/shared/protocol.d.ts +122 -0
  323. package/dist/shared/protocol.d.ts.map +1 -0
  324. package/dist/shared/protocol.js +7 -0
  325. package/dist/shared/protocol.js.map +1 -0
  326. package/dist/shared/reviewArchive.d.mts +4 -0
  327. package/dist/shared/reviewArchive.mjs +19 -0
  328. package/dist/shared/reviewStore.d.mts +30 -0
  329. package/dist/shared/reviewStore.mjs +218 -0
  330. package/dist/shared/reviewVerify.d.mts +21 -0
  331. package/dist/shared/reviewVerify.mjs +158 -0
  332. package/dist/shared/sizeModes.d.mts +15 -0
  333. package/dist/shared/sizeModes.mjs +53 -0
  334. package/dist/shared/sketches.d.mts +10 -0
  335. package/dist/shared/sketches.mjs +64 -0
  336. package/dist/shared/snapshotCheck.d.mts +13 -0
  337. package/dist/shared/snapshotCheck.mjs +81 -0
  338. package/dist/shared/timeout.d.mts +1 -0
  339. package/dist/shared/timeout.mjs +15 -0
  340. package/dist/shared/tokens.d.ts +2 -0
  341. package/dist/shared/tokens.d.ts.map +1 -0
  342. package/dist/shared/tokens.js +2 -0
  343. package/dist/shared/tokens.js.map +1 -0
  344. package/dist/shared/types.d.ts +689 -0
  345. package/dist/shared/types.d.ts.map +1 -0
  346. package/dist/shared/types.js +13 -0
  347. package/dist/shared/types.js.map +1 -0
  348. package/dist/shared/wheelRouting.d.mts +9 -0
  349. package/dist/shared/wheelRouting.mjs +31 -0
  350. package/dist/shared/writeScope.mjs +96 -0
  351. package/dist/snapshots/diff.d.mts +28 -0
  352. package/dist/snapshots/diff.mjs +263 -0
  353. package/dist/snapshots/index.d.mts +110 -0
  354. package/dist/snapshots/index.mjs +638 -0
  355. package/dist/snapshots/render.d.mts +24 -0
  356. package/dist/snapshots/render.mjs +250 -0
  357. package/dist/snapshots/toolOps.d.mts +25 -0
  358. package/dist/snapshots/toolOps.mjs +69 -0
  359. package/dist/tokens/adapters/css.mjs +51 -0
  360. package/dist/tokens/adapters/cssInCode.mjs +314 -0
  361. package/dist/tokens/adapters/oxcShared.mjs +80 -0
  362. package/dist/tokens/adapters/preprocessor.mjs +63 -0
  363. package/dist/tokens/adapters/registry.mjs +53 -0
  364. package/dist/tokens/adapters/tailwindcss.mjs +424 -0
  365. package/dist/tokens/adapters/types.mjs +117 -0
  366. package/dist/tokens/consolidate/index.d.mts +42 -0
  367. package/dist/tokens/consolidate/index.mjs +111 -0
  368. package/dist/tokens/consolidate/normalize.mjs +479 -0
  369. package/dist/tokens/consolidate/plan.mjs +726 -0
  370. package/dist/tokens/consolidate/scan.mjs +928 -0
  371. package/dist/tokens/extract.mjs +441 -0
  372. package/dist/tokens/moduleData.d.mts +14 -0
  373. package/dist/tokens/moduleData.mjs +32 -0
  374. package/dist/tokens/opLock.d.mts +4 -0
  375. package/dist/tokens/opLock.mjs +108 -0
  376. package/dist/tokens/ops.d.mts +71 -0
  377. package/dist/tokens/ops.mjs +1511 -0
  378. package/dist/tokens/pipeline.mjs +813 -0
  379. package/dist/tokens/report.d.mts +47 -0
  380. package/dist/tokens/report.mjs +257 -0
  381. package/dist/tokens/rewrite/code.mjs +172 -0
  382. package/dist/tokens/rewrite/css.mjs +154 -0
  383. package/dist/tokens/rewrite/index.mjs +244 -0
  384. package/dist/tokens/rewrite/tailwind.mjs +288 -0
  385. package/dist/tokens/rewrite/text.mjs +116 -0
  386. package/dist/tokens/rewrite/value.mjs +115 -0
  387. package/dist/tokens/usage.d.mts +97 -0
  388. package/dist/tokens/usage.mjs +680 -0
  389. package/dist/vite/agent.d.ts +21 -0
  390. package/dist/vite/agent.d.ts.map +1 -0
  391. package/dist/vite/agent.js +165 -0
  392. package/dist/vite/agent.js.map +1 -0
  393. package/dist/vite/events.d.ts +27 -0
  394. package/dist/vite/events.d.ts.map +1 -0
  395. package/dist/vite/events.js +156 -0
  396. package/dist/vite/events.js.map +1 -0
  397. package/dist/vite/layout.d.ts +2 -0
  398. package/dist/vite/layout.d.ts.map +1 -0
  399. package/dist/vite/layout.js +4 -0
  400. package/dist/vite/layout.js.map +1 -0
  401. package/dist/vite/plugin.d.ts +40 -0
  402. package/dist/vite/plugin.d.ts.map +1 -0
  403. package/dist/vite/plugin.js +1264 -0
  404. package/dist/vite/plugin.js.map +1 -0
  405. package/dist/vite/requestGuard.d.mts +3 -0
  406. package/dist/vite/requestGuard.mjs +43 -0
  407. package/dist/vite/review.d.ts +11 -0
  408. package/dist/vite/review.d.ts.map +1 -0
  409. package/dist/vite/review.js +283 -0
  410. package/dist/vite/review.js.map +1 -0
  411. package/package.json +106 -1
  412. package/skills/seji/SKILL.md +400 -0
  413. package/skills/seji-authoring/SKILL.md +397 -0
  414. package/skills/seji-tokens/SKILL.md +432 -0
@@ -0,0 +1,1264 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import { createRequire } from 'node:module';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { COMPONENT_ACTIONS, ComponentActionError, describeComponent, listComponents, parseFrames, planComponentAction, recordComponentAction, revertComponentAction, showComponent, } from '../shared/componentOps.mjs';
7
+ import { PROPOSAL_DECISIONS, decideProposal } from '../shared/proposals.mjs';
8
+ import { componentDirsOf, scanComponentGroups } from '../shared/components.mjs';
9
+ import { designOptimizeEntries } from '../shared/optimizeEntries.mjs';
10
+ import { captureBaselines, claimBaselines, compareSnapshots, decideSnapshots, emptyCaptureError, snapshotImagePath, snapshotView, } from '../snapshots/index.mjs';
11
+ import { hasPlaywright } from '../snapshots/render.mjs';
12
+ import { baselineHooks, toolSnapshotsRequest } from '../snapshots/toolOps.mjs';
13
+ import { healthReport, verifyReviews } from '../tokens/report.mjs';
14
+ import { TOKEN_OPS, TokenOpError, runTokenOp } from '../tokens/ops.mjs';
15
+ import { buildUsageIndex } from '../tokens/usage.mjs';
16
+ import { TOKENS_DATA_EVENT, isTokenDataFile, loadTokenConfig, tokenModuleData } from '../tokens/moduleData.mjs';
17
+ import { CONSOLIDATE_COMMANDS, CONSOLIDATE_MUTATING, consolidateErrorStatus, runConsolidate, } from '../tokens/consolidate/index.mjs';
18
+ import { mutationGuardError } from './requestGuard.mjs';
19
+ import { AFTER_UPDATE_EVENT, BEFORE_UPDATE_EVENT, BUILD_ERROR_EVENT } from '../shared/buildError.mjs';
20
+ import { createAgentRoutes } from "./agent.js";
21
+ import { createReviewEventHub, extractDesignFromReviewPath, isValidDesignId, } from "./events.js";
22
+ import { readLayout, writeLayout } from "./layout.js";
23
+ import { ownRuntimeDir, runtimeAliases, workspaceRootOf } from '../shared/packages.mjs';
24
+ import { applyReviewOps, emptyReview, readReview } from "./review.js";
25
+ import { SAFE_ITEM_ID, commentShotPath, decodePngDataUrl, storeCommentShot } from '../shared/commentShots.mjs';
26
+ import { legacyEditorRedirect } from '../shared/legacyPaths.mjs';
27
+ const here = path.dirname(fileURLToPath(import.meta.url));
28
+ const packageRoot = path.resolve(here, '../..');
29
+ const packageVersion = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8')).version;
30
+ const resolveEntry = (relBase) => {
31
+ const js = path.resolve(here, `${relBase}.js`);
32
+ return fs.existsSync(js) ? js : path.resolve(here, `${relBase}.tsx`);
33
+ };
34
+ const editorSourceMain = resolveEntry('../editor/main');
35
+ const editorBundleJs = path.join(packageRoot, 'dist/editor-bundle/editor.js');
36
+ const editorBundleCss = path.join(packageRoot, 'dist/editor-bundle/editor.css');
37
+ const hasEditorBundle = () => fs.existsSync(editorBundleJs) && fs.existsSync(editorBundleCss);
38
+ const previewMain = resolveEntry('../preview/main');
39
+ const PACKAGE_NAME = '@rien7/seji';
40
+ const RUNTIME_PACKAGE_NAME = '@rien7/design-surface-runtime';
41
+ const BUNDLED_EDITOR_REACT_DEPS = [
42
+ 'react',
43
+ 'react-dom',
44
+ 'react-dom/client',
45
+ 'react/jsx-runtime',
46
+ 'react/jsx-dev-runtime',
47
+ ];
48
+ const EDITOR_PREBUNDLE_DEPS = [
49
+ `${PACKAGE_NAME} > @base-ui/react/button`,
50
+ `${PACKAGE_NAME} > @base-ui/react/dialog`,
51
+ `${PACKAGE_NAME} > @base-ui/react/field`,
52
+ `${PACKAGE_NAME} > @base-ui/react/number-field`,
53
+ `${PACKAGE_NAME} > @base-ui/react/popover`,
54
+ `${PACKAGE_NAME} > @base-ui/react/select`,
55
+ `${PACKAGE_NAME} > @base-ui/react/tabs`,
56
+ `${PACKAGE_NAME} > @base-ui/react/toggle`,
57
+ `${PACKAGE_NAME} > @base-ui/react/toggle-group`,
58
+ `${PACKAGE_NAME} > @base-ui/react/tooltip`,
59
+ `${PACKAGE_NAME} > lucide-react`,
60
+ `${PACKAGE_NAME} > modern-screenshot`,
61
+ ];
62
+ const flattenPlugins = (plugins) => {
63
+ if (!plugins)
64
+ return [];
65
+ if (!Array.isArray(plugins)) {
66
+ return typeof plugins === 'object' ? [plugins] : [];
67
+ }
68
+ const out = [];
69
+ for (const entry of plugins) {
70
+ if (!entry)
71
+ continue;
72
+ if (Array.isArray(entry))
73
+ out.push(...flattenPlugins(entry));
74
+ else if (typeof entry === 'object')
75
+ out.push(entry);
76
+ }
77
+ return out;
78
+ };
79
+ const resolveHostReactDeps = (hostRoot) => {
80
+ const hostPkg = path.join(hostRoot, 'package.json');
81
+ if (!fs.existsSync(hostPkg))
82
+ return [];
83
+ try {
84
+ const req = createRequire(hostPkg);
85
+ return BUNDLED_EDITOR_REACT_DEPS.filter((dep) => {
86
+ try {
87
+ req.resolve(dep);
88
+ return true;
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ });
94
+ }
95
+ catch {
96
+ return [];
97
+ }
98
+ };
99
+ // Self-accepting virtual modules: an edit to a design.tsx, the token data, components.ts or a
100
+ // component that is not a React Refresh boundary stops here instead of reaching the editor /
101
+ // preview root (a full reload of every window). The new module is handed to the page through a
102
+ // window event; only windows that loaded the module receive the update.
103
+ const hotAccept = (name) => `if (import.meta.hot) import.meta.hot.accept((mod) => { if (mod) window.dispatchEvent(new CustomEvent('design-surface:${name}', { detail: mod })) })\n`;
104
+ // The token data event (see tokens/moduleData.mjs) is received in the virtual module, which the
105
+ // dev server serves (the bundled editor has no import.meta.hot), and forwarded as a window event.
106
+ const tokensDataRelay = `if (import.meta.hot) import.meta.hot.on('${TOKENS_DATA_EVENT}', () => window.dispatchEvent(new CustomEvent('${TOKENS_DATA_EVENT}')))\n`;
107
+ // Vite's build errors and update cycles, forwarded as window events for the bundled editor's
108
+ // status bar and each preview frame's error card (see shared/buildError.mjs). The editor bundle
109
+ // has no import.meta.hot of its own; the virtual config module is served by the dev server.
110
+ const hmrStatusRelay = `if (import.meta.hot) {
111
+ import.meta.hot.on('vite:error', (payload) => window.dispatchEvent(new CustomEvent('${BUILD_ERROR_EVENT}', { detail: payload && payload.err })))
112
+ import.meta.hot.on('vite:beforeUpdate', (payload) => window.dispatchEvent(new CustomEvent('${BEFORE_UPDATE_EVENT}', { detail: payload })))
113
+ import.meta.hot.on('vite:afterUpdate', (payload) => window.dispatchEvent(new CustomEvent('${AFTER_UPDATE_EVENT}', { detail: payload })))
114
+ }
115
+ `;
116
+ const VIRTUAL = {
117
+ 'virtual:design/manifest': '\0virtual:design/manifest',
118
+ 'virtual:design/tokens': '\0virtual:design/tokens',
119
+ 'virtual:design/providers': '\0virtual:design/providers',
120
+ 'virtual:design/components': '\0virtual:design/components',
121
+ 'virtual:design/config': '\0virtual:design/config',
122
+ 'virtual:design/design-loader': '\0virtual:design/design-loader',
123
+ 'virtual:design/styles': '\0virtual:design/styles',
124
+ };
125
+ const toUrl = (file) => `/@fs/${file.split(path.sep).join('/')}`;
126
+ const toPosixPath = (file) => file.split(path.sep).join('/');
127
+ // A file outside the Vite root (a design dir at the repository root) is served through /@fs/.
128
+ const toRootUrl = (root, file) => {
129
+ const rel = path.relative(root, file);
130
+ if (rel.startsWith('..') || path.isAbsolute(rel))
131
+ return `/@fs/${toPosixPath(path.resolve(file)).replace(/^\/+/, '')}`;
132
+ return `/${toPosixPath(rel)}`;
133
+ };
134
+ const listDesigns = (root, dir) => {
135
+ const base = path.join(root, dir);
136
+ if (!fs.existsSync(base))
137
+ return [];
138
+ return fs
139
+ .readdirSync(base, { withFileTypes: true })
140
+ .filter((entry) => entry.isDirectory())
141
+ .map((entry) => ({ id: entry.name, file: path.join(base, entry.name, 'design.tsx') }))
142
+ .filter((entry) => fs.existsSync(entry.file))
143
+ .sort((a, b) => a.id.localeCompare(b.id));
144
+ };
145
+ /** Static directory prefix of each component glob, so new files there are watched. */
146
+ const componentGlobBases = (root, groups) => {
147
+ const dirs = new Set();
148
+ for (const group of groups) {
149
+ for (const pattern of group.globs) {
150
+ if (pattern.startsWith('!'))
151
+ continue;
152
+ const parts = [];
153
+ for (const part of pattern.split('/')) {
154
+ if (/[*?{}[\]()!]/.test(part))
155
+ break;
156
+ parts.push(part);
157
+ }
158
+ const base = path.resolve(root, parts.join('/') || '.');
159
+ if (!fs.existsSync(base))
160
+ continue;
161
+ dirs.add(fs.statSync(base).isDirectory() ? base : path.dirname(base));
162
+ }
163
+ }
164
+ return [...dirs];
165
+ };
166
+ const json = (res, status, body) => {
167
+ res.statusCode = status;
168
+ res.setHeader('content-type', 'application/json; charset=utf-8');
169
+ res.setHeader('cache-control', 'no-store');
170
+ res.end(JSON.stringify(body));
171
+ };
172
+ /**
173
+ * Every mutating /__seji/api/* route calls this first: it refuses cross-site requests
174
+ * and non-JSON bodies (see requestGuard.mjs) and answers them; returns false when refused.
175
+ */
176
+ const guardMutation = (req, res) => {
177
+ const refused = mutationGuardError(req.headers);
178
+ if (!refused)
179
+ return true;
180
+ json(res, refused.status, { error: refused.error });
181
+ return false;
182
+ };
183
+ const readBody = async (req, maxBytes = 2 * 1024 * 1024) => {
184
+ const chunks = [];
185
+ let size = 0;
186
+ for await (const chunk of req) {
187
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
188
+ size += buffer.length;
189
+ if (size > maxBytes)
190
+ throw new Error('Request body too large');
191
+ chunks.push(buffer);
192
+ }
193
+ if (!size)
194
+ return null;
195
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
196
+ };
197
+ const refreshPreamble = `
198
+ <script type="module">
199
+ import RefreshRuntime from "/@react-refresh";
200
+ RefreshRuntime.injectIntoGlobalHook(window);
201
+ window.$RefreshReg$ = () => {};
202
+ window.$RefreshSig$ = () => (type) => type;
203
+ window.__vite_plugin_react_preamble_installed__ = true;
204
+ </script>`;
205
+ const html = (title, main, reactRefresh, cssUrl, editor = false) => `<!doctype html>
206
+ <html lang="en"${editor ? ' class="ds-editor"' : ''}>
207
+ <head>
208
+ <meta charset="UTF-8" />
209
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
210
+ <title>${title}</title>${cssUrl ? `\n <link rel="stylesheet" href="${cssUrl}" />` : ''}
211
+ </head>
212
+ <body>
213
+ <div id="root"></div>
214
+ <script type="module" src="/@vite/client"></script>
215
+ ${reactRefresh ? refreshPreamble : ''}
216
+ <script type="module" src="${toUrl(main)}"></script>
217
+ </body>
218
+ </html>`;
219
+ export function designPlugin(options = {}) {
220
+ const resolved = {
221
+ dir: options.dir ?? 'design',
222
+ css: options.css ?? [],
223
+ providers: options.providers ?? '/design/providers.tsx',
224
+ tokens: options.tokens ?? '/design/tokens.ts',
225
+ tokenAliases: options.tokenAliases ?? {},
226
+ components: options.components ?? '/design/components.ts',
227
+ componentGroups: options.componentGroups ?? [],
228
+ openInEditor: options.openInEditor ?? 'code',
229
+ title: options.title ?? 'seji',
230
+ reactRefresh: options.reactRefresh ?? true,
231
+ snapshots: { autoBaseline: options.snapshots?.autoBaseline ?? true },
232
+ };
233
+ let root = process.cwd();
234
+ // The parent of the design directory: the "root" the design-data helpers (review, layout,
235
+ // snapshots, tokens) join `design/` to. The app root unless an existing design dir outside
236
+ // the app is used (`dir: '../../design'`).
237
+ let designHome = root;
238
+ const updateDesignHome = () => {
239
+ designHome = path.dirname(path.resolve(root, resolved.dir));
240
+ };
241
+ // `/design/...` URLs (defaults and surface.config.json) point into the design directory.
242
+ const designUrl = (file) => designHome !== root && (file === '/design' || file.startsWith('/design/'))
243
+ ? toRootUrl(root, path.join(designHome, file.slice(1)))
244
+ : file;
245
+ const existsAtRoot = (file) => {
246
+ const url = designUrl(file);
247
+ if (url.startsWith('/@fs/'))
248
+ return fs.existsSync(path.resolve('/', url.slice('/@fs/'.length)));
249
+ return url.startsWith('/') && fs.existsSync(path.join(root, url.slice(1)));
250
+ };
251
+ const handleLayout = async (req, res, url) => {
252
+ const design = url.searchParams.get('design');
253
+ if (req.method === 'GET') {
254
+ if (!design)
255
+ return json(res, 400, { error: 'design is required' });
256
+ const layout = readLayout(designHome, design);
257
+ // No layout yet (a fresh design) is not an error: `null`, so the editor logs nothing.
258
+ return json(res, 200, layout ?? null);
259
+ }
260
+ if (req.method === 'POST') {
261
+ if (!guardMutation(req, res))
262
+ return;
263
+ const body = (await readBody(req));
264
+ if (!body || typeof body.design !== 'string' || (!body.positions && !body.camera)) {
265
+ return json(res, 400, { error: 'design and positions or camera are required' });
266
+ }
267
+ // positions → design/<design>/canvas.json (shared); camera → the tool cache (personal).
268
+ return json(res, 200, writeLayout(designHome, body.design, {
269
+ ...(body.positions ? { positions: body.positions } : {}),
270
+ ...(body.camera ? { camera: body.camera } : {}),
271
+ ...(typeof body.page === 'string' ? { page: body.page } : {}),
272
+ }));
273
+ }
274
+ return json(res, 405, { error: 'method not allowed' });
275
+ };
276
+ let isDuplicate = false;
277
+ // Last component catalog served to the editor; the watcher compares against it.
278
+ let catalogSnapshot = null;
279
+ const plugin = {
280
+ name: 'seji',
281
+ apply: 'serve',
282
+ // Read by the CLI (cli/catalog.mjs) so `seji component …` scans the same
283
+ // component groups as the editor and /__seji/api/components.
284
+ api: { componentGroups: resolved.componentGroups },
285
+ config(userConfig) {
286
+ const surfacePlugins = flattenPlugins(userConfig.plugins).filter((entry) => entry.name === 'seji');
287
+ if (surfacePlugins.length > 1 && surfacePlugins[0] !== plugin) {
288
+ isDuplicate = true;
289
+ return;
290
+ }
291
+ const hostRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
292
+ const designDirAbs = path.resolve(hostRoot, resolved.dir);
293
+ const bundled = hasEditorBundle();
294
+ // No project dependency: a project that cannot resolve the runtime gets this CLI's copy.
295
+ const runtime = runtimeAliases(hostRoot);
296
+ const ownRuntime = ownRuntimeDir();
297
+ return {
298
+ resolve: {
299
+ alias: runtime.aliases,
300
+ // One React: the runtime / preview modules outside the project use the app's copy.
301
+ dedupe: ['react', 'react-dom'],
302
+ },
303
+ optimizeDeps: {
304
+ exclude: [PACKAGE_NAME, RUNTIME_PACKAGE_NAME],
305
+ include: bundled ? resolveHostReactDeps(hostRoot) : EDITOR_PREBUNDLE_DEPS,
306
+ // Packages first imported from design/ are pre-bundled at startup instead of causing a
307
+ // re-optimize + full reload later (merged onto the app's own entries by Vite).
308
+ entries: designOptimizeEntries({
309
+ dir: path.relative(hostRoot, designDirAbs) || '.',
310
+ componentGroups: resolved.componentGroups,
311
+ userEntries: userConfig.optimizeDeps?.entries,
312
+ }),
313
+ },
314
+ server: {
315
+ fs: {
316
+ // Setting `allow` replaces Vite's default (the workspace root), so it is listed too.
317
+ allow: [...new Set([packageRoot, workspaceRootOf(hostRoot), hostRoot, designDirAbs, ...runtime.dirs, ...(ownRuntime ? [ownRuntime] : [])])],
318
+ },
319
+ watch: {
320
+ ignored: ['**/canvas.json', '**/.seji/**', '**/.session/**'],
321
+ },
322
+ },
323
+ };
324
+ },
325
+ configResolved(config) {
326
+ if (isDuplicate)
327
+ return;
328
+ root = config.root;
329
+ updateDesignHome();
330
+ },
331
+ handleHotUpdate({ file }) {
332
+ if (isDuplicate)
333
+ return;
334
+ const designRoot = path.join(root, resolved.dir);
335
+ const relative = path.relative(designRoot, file);
336
+ if (relative &&
337
+ !relative.startsWith('..') &&
338
+ (path.basename(relative) === 'canvas.json' ||
339
+ path.basename(relative) === 'history.json' ||
340
+ path.basename(relative) === 'review.json' ||
341
+ relative === 'components.json' ||
342
+ relative.split(path.sep).includes('.session'))) {
343
+ return [];
344
+ }
345
+ },
346
+ resolveId(id) {
347
+ if (isDuplicate)
348
+ return null;
349
+ return VIRTUAL[id] ?? null;
350
+ },
351
+ async load(id) {
352
+ if (isDuplicate)
353
+ return null;
354
+ if (id === VIRTUAL['virtual:design/manifest']) {
355
+ const designs = listDesigns(root, resolved.dir);
356
+ const imports = designs
357
+ .map((design, index) => `import d${index} from '${toRootUrl(root, design.file)}'`)
358
+ .join('\n');
359
+ const entries = designs
360
+ .map((design, index) => `${JSON.stringify(design.id)}: { ...d${index}, id: ${JSON.stringify(design.id)} }`)
361
+ .join(',\n ');
362
+ return `${imports}\nexport const designs = {\n ${entries}\n}\n${hotAccept('manifest')}`;
363
+ }
364
+ if (id === VIRTUAL['virtual:design/tokens']) {
365
+ if (existsAtRoot(resolved.tokens)) {
366
+ return `export * from '${designUrl(resolved.tokens)}'\n${hotAccept('tokens')}${tokensDataRelay}`;
367
+ }
368
+ return `export const tokenGroups = []\nexport const tokenValues = {}\nexport const tokenSources = {}\nexport const tokenAliases = {}\nexport const tokenSourceHash = ''\nexport const tokenHealth = { duplicates: [], orphans: [], semanticLiterals: [], componentPrimitive: [], hardcoded: [] }\n${hotAccept('tokens')}${tokensDataRelay}`;
369
+ }
370
+ if (id === VIRTUAL['virtual:design/providers']) {
371
+ if (existsAtRoot(resolved.providers)) {
372
+ return `export { Providers } from '${designUrl(resolved.providers)}'\n${hotAccept('providers')}`;
373
+ }
374
+ return `export const Providers = ({ children }) => children\n${hotAccept('providers')}`;
375
+ }
376
+ if (id === VIRTUAL['virtual:design/components']) {
377
+ const groups = await scanComponentGroups(root, resolved.componentGroups);
378
+ catalogSnapshot = JSON.stringify(groups);
379
+ const catalog = groups.flatMap((group) => group.components);
380
+ const catalogSources = Object.fromEntries(catalog.map((entry) => [entry.name, entry.file]));
381
+ const manualImport = existsAtRoot(resolved.components)
382
+ ? `import * as manual from '${designUrl(resolved.components)}'\n`
383
+ : `const manual = {}\n`;
384
+ return `${manualImport}export const componentGroups = ${JSON.stringify(groups)}
385
+ export const componentDirs = ${JSON.stringify(componentDirsOf(root, resolved.componentGroups))}
386
+ export const componentCatalog = ${JSON.stringify(catalog)}
387
+ export const componentSources = { ...${JSON.stringify(catalogSources)}, ...(manual.componentSources ?? {}) }
388
+ export const componentPages = manual.componentPages ?? {}
389
+ ${hotAccept('components')}`;
390
+ }
391
+ if (id === VIRTUAL['virtual:design/design-loader']) {
392
+ const cases = listDesigns(root, resolved.dir)
393
+ .map((design) => `case ${JSON.stringify(design.id)}: return (await import('${toRootUrl(root, design.file)}')).default`)
394
+ .join('\n ');
395
+ return `export async function loadDesign(id) {\n switch (id) {\n ${cases}\n }\n return undefined\n}\n${hotAccept('design-loader')}`;
396
+ }
397
+ if (id === VIRTUAL['virtual:design/styles']) {
398
+ return resolved.css.map((file) => `import '${designUrl(file)}'\n`).join('');
399
+ }
400
+ if (id === VIRTUAL['virtual:design/config']) {
401
+ return `export const tokenAliases = ${JSON.stringify(resolved.tokenAliases)}\nexport const projectRoot = ${JSON.stringify(root.split(path.sep).join('/'))}\nexport const version = ${JSON.stringify(packageVersion)}\n${hotAccept('config')}${hmrStatusRelay}`;
402
+ }
403
+ return null;
404
+ },
405
+ configureServer(server) {
406
+ if (isDuplicate)
407
+ return;
408
+ const reviewHub = createReviewEventHub();
409
+ server.httpServer?.once('close', () => reviewHub.closeAll());
410
+ // Component catalog refresh: a new file is often created empty and gets its exports on
411
+ // a later save, and globs may point outside the Vite root (unwatched by default). Rescan
412
+ // on any TSX/JSX add/change/unlink and reload the virtual module only when the catalog
413
+ // actually changed, so ordinary edits never reload the editor.
414
+ for (const dir of componentGlobBases(root, resolved.componentGroups)) {
415
+ server.watcher.add(dir);
416
+ }
417
+ let catalogTimer = null;
418
+ const refreshCatalog = () => {
419
+ if (catalogTimer)
420
+ clearTimeout(catalogTimer);
421
+ catalogTimer = setTimeout(() => {
422
+ catalogTimer = null;
423
+ void scanComponentGroups(root, resolved.componentGroups)
424
+ .then((groups) => {
425
+ const next = JSON.stringify(groups);
426
+ if (catalogSnapshot === null || next === catalogSnapshot)
427
+ return;
428
+ const module = server.moduleGraph.getModuleById(VIRTUAL['virtual:design/components']);
429
+ if (!module)
430
+ return;
431
+ catalogSnapshot = next;
432
+ return server.reloadModule(module);
433
+ })
434
+ .catch(() => { });
435
+ }, 120);
436
+ };
437
+ server.httpServer?.once('close', () => {
438
+ if (catalogTimer)
439
+ clearTimeout(catalogTimer);
440
+ });
441
+ const notifyReviewChange = (file, removed = false) => {
442
+ const designId = extractDesignFromReviewPath(designHome, 'design', file);
443
+ if (!designId)
444
+ return;
445
+ try {
446
+ const review = removed ? emptyReview(designId) : readReview(designHome, designId);
447
+ reviewHub.broadcast(designId, review);
448
+ }
449
+ catch {
450
+ // ignore transient read errors during atomic writes
451
+ }
452
+ };
453
+ // Component reports depend on design/components.json (usage notes, deprecation),
454
+ // design/components.ts and the code / styles that use a component: tell open editors
455
+ // to refetch (a CLI `component describe`, another tab, an agent's edit).
456
+ const componentsJson = path.join(root, resolved.dir, 'components.json');
457
+ let componentsTimer = null;
458
+ const notifyComponentsChange = (file) => {
459
+ const relevant = path.resolve(file) === componentsJson ||
460
+ (/\.(tsx|jsx|ts|js|mts|mjs|css|scss|less)$/.test(file) && !file.includes(`${path.sep}node_modules${path.sep}`));
461
+ if (!relevant)
462
+ return;
463
+ if (componentsTimer)
464
+ clearTimeout(componentsTimer);
465
+ componentsTimer = setTimeout(() => {
466
+ componentsTimer = null;
467
+ reviewHub.broadcastAll('components', { file: path.relative(root, file).split(path.sep).join('/') });
468
+ }, 150);
469
+ };
470
+ server.httpServer?.once('close', () => {
471
+ if (componentsTimer)
472
+ clearTimeout(componentsTimer);
473
+ });
474
+ server.watcher.add(componentsJson);
475
+ try {
476
+ server.watcher.add(path.resolve(designHome, loadTokenConfig(designHome).tokenDir));
477
+ }
478
+ catch {
479
+ // an invalid tokens.config.json: the token build reports it
480
+ }
481
+ server.watcher.on('add', (file) => {
482
+ notifyTokensData(file);
483
+ if (/\.(tsx|jsx)$/.test(file))
484
+ refreshCatalog();
485
+ notifyReviewChange(file);
486
+ notifyComponentsChange(file);
487
+ });
488
+ // A token build rewrote the generated CSS (or a token file changed): editors re-fetch the
489
+ // token data over HTTP; no module is re-imported.
490
+ const notifyTokensData = (file) => {
491
+ if (isTokenDataFile(designHome, file))
492
+ server.ws.send({ type: 'custom', event: TOKENS_DATA_EVENT });
493
+ };
494
+ server.watcher.on('change', (file) => {
495
+ notifyTokensData(file);
496
+ if (/\.(tsx|jsx)$/.test(file))
497
+ refreshCatalog();
498
+ notifyReviewChange(file);
499
+ notifyComponentsChange(file);
500
+ });
501
+ server.watcher.on('unlink', (file) => {
502
+ if (/\.(tsx|jsx)$/.test(file))
503
+ refreshCatalog();
504
+ notifyReviewChange(file, true);
505
+ notifyComponentsChange(file);
506
+ });
507
+ // Snapshots render through this server; one capture runs at a time.
508
+ const selfUrl = () => {
509
+ const local = server.resolvedUrls?.local?.[0];
510
+ if (local)
511
+ return local;
512
+ const address = server.httpServer?.address();
513
+ if (!address || typeof address !== 'object')
514
+ return undefined;
515
+ const host = address.family === 'IPv6' ? (address.address === '::' ? '[::1]' : `[${address.address}]`) : address.address === '0.0.0.0' ? '127.0.0.1' : address.address;
516
+ return `http://${host}:${address.port}`;
517
+ };
518
+ let snapshotQueue = Promise.resolve();
519
+ const enqueueSnapshots = (task) => {
520
+ const run = snapshotQueue.then(task, task);
521
+ snapshotQueue = run.catch(() => { });
522
+ return run;
523
+ };
524
+ const warnSnapshots = (message) => server.config.logger.warn(`[seji] ${message}`);
525
+ let playwright = null;
526
+ const playwrightReady = () => (playwright ??= hasPlaywright(root));
527
+ // Baselines of new items. The items are claimed (`snapshots.capturingSince`) before the
528
+ // review POST answers, so an agent reading the ledger sees the running capture and
529
+ // `seji snapshot wait` blocks until "before" exists; rendering runs after.
530
+ const claimAutoBaselines = async (design, itemIds) => {
531
+ if (!resolved.snapshots.autoBaseline || !itemIds.length)
532
+ return null;
533
+ if (!(await playwrightReady()))
534
+ return null;
535
+ try {
536
+ const claim = claimBaselines({ root: designHome, design, itemIds });
537
+ return claim.claimed.length ? claim : null;
538
+ }
539
+ catch (error) {
540
+ warnSnapshots(`snapshot baseline not claimed: ${error instanceof Error ? error.message : String(error)}`);
541
+ return null;
542
+ }
543
+ };
544
+ const runAutoBaselines = (design, claim) => {
545
+ void enqueueSnapshots(() => captureBaselines({ root: designHome, design, claim, url: selfUrl() }))
546
+ .then((result) => {
547
+ const empty = emptyCaptureError(result);
548
+ if (empty)
549
+ warnSnapshots(`snapshot baseline: ${empty}`);
550
+ })
551
+ .catch((error) => {
552
+ warnSnapshots(`snapshot baseline failed: ${error instanceof Error ? error.message : String(error)}`);
553
+ })
554
+ .finally(() => reviewHub.broadcast(design, readReview(designHome, design)));
555
+ };
556
+ // Tool operations with `snapshots: true` (token ops, consolidate apply): the baseline is
557
+ // rendered inside the operation, right before it writes (hooks.beforeWrite), through the
558
+ // snapshot queue. The compare runs after the response: every module is invalidated first,
559
+ // so the renderer loads what the operation wrote instead of Vite's cached transforms.
560
+ const toolBaseline = async () => {
561
+ if (!(await playwrightReady()))
562
+ return { skipped: 'Playwright is not installed; no snapshots were taken' };
563
+ return baselineHooks({ root: designHome, url: selfUrl(), run: enqueueSnapshots });
564
+ };
565
+ const invalidateModules = () => {
566
+ const environments = server.environments;
567
+ if (environments) {
568
+ for (const environment of Object.values(environments))
569
+ environment.moduleGraph?.invalidateAll?.();
570
+ }
571
+ else {
572
+ server.moduleGraph.invalidateAll();
573
+ }
574
+ };
575
+ const compareAfterTool = (snapshot, result) => {
576
+ if ('skipped' in snapshot)
577
+ return { skipped: snapshot.skipped };
578
+ if (!snapshot.state.captured)
579
+ return { error: snapshot.state.error ?? 'no baseline was captured' };
580
+ const design = typeof result.design === 'string' ? result.design : undefined;
581
+ const itemId = typeof result.itemId === 'string' ? result.itemId : undefined;
582
+ if (!design || !itemId || !isValidDesignId(design))
583
+ return { error: 'the operation recorded no review item' };
584
+ invalidateModules();
585
+ void enqueueSnapshots(() => compareSnapshots({ root: designHome, design, itemIds: [itemId], url: selfUrl() }))
586
+ .catch((error) => {
587
+ warnSnapshots(`snapshot compare failed: ${error instanceof Error ? error.message : String(error)}`);
588
+ })
589
+ .finally(() => reviewHub.broadcast(design, readReview(designHome, design)));
590
+ return { baseline: true, comparing: true };
591
+ };
592
+ // The editor's agent (0.5.0, agent/host.mjs): runs in this server with the folder holding
593
+ // the design board as its cwd (the app, or the workspace root for a board kept outside it).
594
+ const boardDir = path.resolve(root, resolved.dir);
595
+ const agentRoutes = createAgentRoutes({
596
+ root: designHome,
597
+ board: path.basename(boardDir),
598
+ app: path.relative(designHome, root).split(path.sep).join('/') || '.',
599
+ json,
600
+ guardMutation,
601
+ readBody,
602
+ log: (message) => server.config.logger.info(`[seji] ${message}`),
603
+ });
604
+ server.httpServer?.once('close', () => void agentRoutes.close());
605
+ server.middlewares.use((req, res, next) => {
606
+ const url = new URL(req.url ?? '/', 'http://seji.local');
607
+ const moved = legacyEditorRedirect(req.url);
608
+ if (moved) {
609
+ res.statusCode = 302;
610
+ res.setHeader('location', moved);
611
+ res.setHeader('cache-control', 'no-store');
612
+ res.end();
613
+ return;
614
+ }
615
+ if (agentRoutes.handle(req, res, url))
616
+ return;
617
+ if (url.pathname === '/__seji/api/events') {
618
+ if (req.method !== 'GET') {
619
+ json(res, 405, { error: 'method not allowed' });
620
+ return;
621
+ }
622
+ const design = url.searchParams.get('design');
623
+ if (!isValidDesignId(design)) {
624
+ json(res, 400, { error: 'valid design id is required' });
625
+ return;
626
+ }
627
+ reviewHub.subscribe(design, res, req);
628
+ return;
629
+ }
630
+ if (url.pathname === '/__seji/api/layout') {
631
+ void handleLayout(req, res, url).catch((error) => {
632
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
633
+ });
634
+ return;
635
+ }
636
+ if (url.pathname === '/__seji/api/review') {
637
+ void (async () => {
638
+ const design = url.searchParams.get('design');
639
+ if (req.method === 'GET') {
640
+ if (!design) {
641
+ json(res, 400, { error: 'design is required' });
642
+ return;
643
+ }
644
+ json(res, 200, readReview(designHome, design));
645
+ return;
646
+ }
647
+ if (req.method === 'POST') {
648
+ if (!guardMutation(req, res))
649
+ return;
650
+ const body = (await readBody(req));
651
+ if (!body || typeof body.design !== 'string' || !Array.isArray(body.ops)) {
652
+ json(res, 400, { error: 'design and ops are required' });
653
+ return;
654
+ }
655
+ let known = new Set();
656
+ try {
657
+ known = new Set(readReview(designHome, body.design).items.map((item) => item.id));
658
+ }
659
+ catch {
660
+ // a new ledger has no items yet
661
+ }
662
+ let updated = applyReviewOps(designHome, body.design, body.ops);
663
+ // The store drops editor-sent snapshots, so a new item never has them yet.
664
+ const claim = await claimAutoBaselines(body.design, updated.items
665
+ .filter((item) => !known.has(item.id) && item.status !== 'archived' && !item.snapshots)
666
+ .map((item) => item.id));
667
+ if (claim)
668
+ updated = readReview(designHome, body.design);
669
+ reviewHub.broadcast(body.design, updated);
670
+ json(res, 200, updated);
671
+ if (claim)
672
+ runAutoBaselines(body.design, claim);
673
+ return;
674
+ }
675
+ json(res, 405, { error: 'method not allowed' });
676
+ })().catch((error) => {
677
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
678
+ });
679
+ return;
680
+ }
681
+ // Screenshot of a frame as the person saw it when posting a comment: the editor captures
682
+ // the live iframe DOM and sends `{ design, itemId, png: "data:image/png;base64,…" }`.
683
+ // Stored at design/.seji/comments/<design>/<itemId>.png; sets the item's `shot`.
684
+ if (url.pathname === '/__seji/api/review/shot') {
685
+ if (req.method === 'GET') {
686
+ const design = url.searchParams.get('design');
687
+ const item = url.searchParams.get('item');
688
+ if (!isValidDesignId(design) || !item || !SAFE_ITEM_ID.test(item)) {
689
+ json(res, 400, { error: 'design and item are required' });
690
+ return;
691
+ }
692
+ const stream = fs.createReadStream(path.resolve(designHome, commentShotPath(design, item)));
693
+ stream.on('error', () => {
694
+ if (!res.headersSent)
695
+ json(res, 404, { error: `no screenshot for ${item}` });
696
+ else
697
+ res.destroy();
698
+ });
699
+ stream.once('open', () => {
700
+ res.statusCode = 200;
701
+ res.setHeader('content-type', 'image/png');
702
+ res.setHeader('cache-control', 'no-store');
703
+ stream.pipe(res);
704
+ });
705
+ return;
706
+ }
707
+ if (req.method !== 'POST') {
708
+ json(res, 405, { error: 'method not allowed' });
709
+ return;
710
+ }
711
+ if (!guardMutation(req, res))
712
+ return;
713
+ void (async () => {
714
+ const body = (await readBody(req, 16 * 1024 * 1024));
715
+ const png = decodePngDataUrl(body?.png);
716
+ if (!body || typeof body.design !== 'string' || typeof body.itemId !== 'string' || !png) {
717
+ json(res, 400, { error: 'design, itemId and a PNG data URL are required' });
718
+ return;
719
+ }
720
+ const stored = storeCommentShot({ root: designHome, design: body.design, itemId: body.itemId, png });
721
+ reviewHub.broadcast(body.design, stored.review);
722
+ json(res, 200, { shot: stored.shot });
723
+ })().catch((error) => {
724
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
725
+ });
726
+ return;
727
+ }
728
+ // Headless token queries, mirroring `seji usage|health|verify`.
729
+ if (url.pathname === '/__seji/api/usage') {
730
+ if (req.method !== 'GET') {
731
+ json(res, 405, { error: 'method not allowed' });
732
+ return;
733
+ }
734
+ void (async () => {
735
+ const index = await buildUsageIndex({ root: designHome });
736
+ if (url.searchParams.has('hardcoded')) {
737
+ json(res, 200, index.hardcoded(url.searchParams.get('hardcoded') || undefined));
738
+ return;
739
+ }
740
+ const token = url.searchParams.get('token');
741
+ if (!token) {
742
+ json(res, 200, index.allTokens());
743
+ return;
744
+ }
745
+ const report = index.tokenUsage(token);
746
+ if (report)
747
+ json(res, 200, report);
748
+ else
749
+ json(res, 404, { error: `unknown token: ${token}` });
750
+ })().catch((error) => {
751
+ json(res, 500, { error: error instanceof Error ? error.message : 'Usage scan failed' });
752
+ });
753
+ return;
754
+ }
755
+ // Component pages, mirroring `seji component …` (same functions, same
756
+ // catalog). POST { action, name, … }:
757
+ // describe { description } · rename { to } · merge { to } ·
758
+ // deprecate { to | null, mode: 'mark' | 'replace', reason } · undeprecate ·
759
+ // delete · tidy { frames } · revert { batch, force? }
760
+ // `dryRun: true` (rename / merge / deprecate replace) returns the plan, writes nothing.
761
+ if (url.pathname === '/__seji/api/components') {
762
+ if (req.method !== 'GET' && req.method !== 'POST') {
763
+ json(res, 405, { error: 'method not allowed' });
764
+ return;
765
+ }
766
+ if (req.method === 'POST' && !guardMutation(req, res))
767
+ return;
768
+ void (async () => {
769
+ const catalog = (await scanComponentGroups(root, resolved.componentGroups)).flatMap((group) => group.components);
770
+ if (req.method === 'GET') {
771
+ const name = url.searchParams.get('name');
772
+ if (!name) {
773
+ json(res, 200, await listComponents({ root: designHome, catalog }));
774
+ return;
775
+ }
776
+ const report = await showComponent({ root: designHome, name, catalog });
777
+ if (report)
778
+ json(res, 200, report);
779
+ else
780
+ json(res, 404, { error: `unknown component: ${name}`, code: 'unknown-component' });
781
+ return;
782
+ }
783
+ const body = (await readBody(req));
784
+ if (!body || typeof body.action !== 'string') {
785
+ json(res, 400, { error: 'action is required', code: 'invalid-args' });
786
+ return;
787
+ }
788
+ if (body.design !== undefined && !isValidDesignId(body.design)) {
789
+ json(res, 400, { error: 'invalid design id', code: 'invalid-args' });
790
+ return;
791
+ }
792
+ const broadcastDesign = (design) => {
793
+ if (typeof design === 'string' && isValidDesignId(design)) {
794
+ reviewHub.broadcast(design, readReview(designHome, design));
795
+ }
796
+ };
797
+ if (body.action === 'revert') {
798
+ if (typeof body.batch !== 'string') {
799
+ json(res, 400, { error: 'batch is required', code: 'invalid-args' });
800
+ return;
801
+ }
802
+ const result = await revertComponentAction({
803
+ root,
804
+ batch: body.batch,
805
+ design: body.design,
806
+ force: body.force === true,
807
+ dryRun: body.dryRun === true,
808
+ });
809
+ if (body.dryRun !== true)
810
+ broadcastDesign(result.design);
811
+ json(res, 200, result);
812
+ return;
813
+ }
814
+ if (typeof body.name !== 'string') {
815
+ json(res, 400, { error: 'name is required', code: 'invalid-args' });
816
+ return;
817
+ }
818
+ if (body.action === 'describe') {
819
+ const entry = await describeComponent({
820
+ root,
821
+ catalog,
822
+ name: body.name,
823
+ description: typeof body.description === 'string' ? body.description : '',
824
+ });
825
+ json(res, 200, { name: body.name, entry });
826
+ return;
827
+ }
828
+ if (!COMPONENT_ACTIONS.includes(body.action)) {
829
+ json(res, 400, { error: `unknown action: ${body.action}`, code: 'unknown-action' });
830
+ return;
831
+ }
832
+ const args = {
833
+ root,
834
+ catalog,
835
+ name: body.name,
836
+ action: body.action,
837
+ to: typeof body.to === 'string' ? body.to : null,
838
+ reason: typeof body.reason === 'string' ? body.reason : undefined,
839
+ mode: body.mode === 'replace' ? 'replace' : 'mark',
840
+ };
841
+ if (body.dryRun === true) {
842
+ json(res, 200, await planComponentAction(args));
843
+ return;
844
+ }
845
+ const result = await recordComponentAction({
846
+ ...args,
847
+ design: body.design,
848
+ frames: parseFrames(body.frames),
849
+ });
850
+ if (result.item)
851
+ broadcastDesign(result.item.design);
852
+ json(res, 200, result);
853
+ })().catch((error) => {
854
+ if (error instanceof ComponentActionError) {
855
+ const status = error.code === 'unknown-component' ? 404 : error.code === 'busy' || error.code === 'stale' ? 409 : 400;
856
+ json(res, status, { error: error.message, code: error.code, ...(error.details ?? {}) });
857
+ return;
858
+ }
859
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
860
+ });
861
+ return;
862
+ }
863
+ // Decide an agent proposal, mirroring `seji proposal <design> <id> <decision>`.
864
+ if (url.pathname === '/__seji/api/proposal') {
865
+ if (req.method !== 'POST') {
866
+ json(res, 405, { error: 'method not allowed' });
867
+ return;
868
+ }
869
+ if (!guardMutation(req, res))
870
+ return;
871
+ void (async () => {
872
+ const body = (await readBody(req));
873
+ if (!body || !isValidDesignId(body.design) || typeof body.id !== 'string') {
874
+ json(res, 400, { error: 'design and id are required' });
875
+ return;
876
+ }
877
+ if (!PROPOSAL_DECISIONS.includes(body.decision)) {
878
+ json(res, 400, { error: `decision must be one of ${PROPOSAL_DECISIONS.join(', ')}` });
879
+ return;
880
+ }
881
+ const { item } = decideProposal({
882
+ root: designHome,
883
+ design: body.design,
884
+ id: body.id,
885
+ decision: body.decision,
886
+ note: typeof body.note === 'string' ? body.note : undefined,
887
+ value: typeof body.value === 'string' ? body.value : undefined,
888
+ });
889
+ reviewHub.broadcast(body.design, readReview(designHome, body.design));
890
+ json(res, 200, { item });
891
+ })().catch((error) => {
892
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
893
+ });
894
+ return;
895
+ }
896
+ if (url.pathname === '/__seji/api/health') {
897
+ if (req.method !== 'GET') {
898
+ json(res, 405, { error: 'method not allowed' });
899
+ return;
900
+ }
901
+ void healthReport({ root: designHome })
902
+ .then((report) => json(res, 200, report))
903
+ .catch((error) => {
904
+ json(res, 500, { error: error instanceof Error ? error.message : 'Health check failed' });
905
+ });
906
+ return;
907
+ }
908
+ if (url.pathname === '/__seji/api/verify') {
909
+ if (req.method !== 'POST') {
910
+ json(res, 405, { error: 'method not allowed' });
911
+ return;
912
+ }
913
+ if (!guardMutation(req, res))
914
+ return;
915
+ void (async () => {
916
+ const body = (await readBody(req));
917
+ const design = body?.design;
918
+ if (design !== undefined && !isValidDesignId(design)) {
919
+ json(res, 400, { error: 'invalid design id' });
920
+ return;
921
+ }
922
+ const rawItems = body?.items;
923
+ const items = Array.isArray(rawItems)
924
+ ? rawItems.filter((id) => typeof id === 'string')
925
+ : undefined;
926
+ const run = () => verifyReviews({
927
+ root: designHome,
928
+ designs: design ? [design] : undefined,
929
+ dryRun: body?.dryRun === true,
930
+ items,
931
+ snapshots: body?.snapshots === true,
932
+ url: selfUrl(),
933
+ });
934
+ // Snapshot rendering shares the queue with background baselines.
935
+ const results = await (body?.snapshots === true ? enqueueSnapshots(run) : run());
936
+ for (const result of results) {
937
+ if (result.written)
938
+ reviewHub.broadcast(result.design, readReview(designHome, result.design));
939
+ }
940
+ // Like the CLI (exit 1): snapshots were requested but could not be rendered.
941
+ json(res, results.some((result) => result.snapshotError) ? 503 : 200, results);
942
+ })().catch((error) => {
943
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
944
+ });
945
+ return;
946
+ }
947
+ // Snapshot comparison (mirrors `seji snapshot …`).
948
+ if (url.pathname === '/__seji/api/snapshots/image') {
949
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
950
+ json(res, 405, { error: 'method not allowed' });
951
+ return;
952
+ }
953
+ const design = url.searchParams.get('design');
954
+ const item = url.searchParams.get('item');
955
+ const frame = url.searchParams.get('frame');
956
+ const kind = url.searchParams.get('kind') ?? 'after';
957
+ if (!isValidDesignId(design) || !item || !frame) {
958
+ json(res, 400, { error: 'design, item and frame are required' });
959
+ return;
960
+ }
961
+ const file = snapshotImagePath(designHome, design, item, frame, kind);
962
+ if (!file) {
963
+ json(res, 404, { error: `no ${kind} snapshot for ${frame}` });
964
+ return;
965
+ }
966
+ // A capture can delete the item's images between the lookup and the read.
967
+ const stream = fs.createReadStream(file);
968
+ stream.on('error', () => {
969
+ if (!res.headersSent)
970
+ json(res, 404, { error: `no ${kind} snapshot for ${frame}` });
971
+ else
972
+ res.destroy();
973
+ });
974
+ stream.once('open', () => {
975
+ res.statusCode = 200;
976
+ res.setHeader('content-type', 'image/png');
977
+ res.setHeader('cache-control', 'no-store');
978
+ if (req.method === 'HEAD') {
979
+ stream.destroy();
980
+ res.end();
981
+ return;
982
+ }
983
+ stream.pipe(res);
984
+ });
985
+ return;
986
+ }
987
+ if (url.pathname === '/__seji/api/snapshots') {
988
+ void (async () => {
989
+ if (req.method === 'GET') {
990
+ const design = url.searchParams.get('design');
991
+ const item = url.searchParams.get('item');
992
+ if (!isValidDesignId(design) || !item) {
993
+ json(res, 400, { error: 'design and item are required' });
994
+ return;
995
+ }
996
+ json(res, 200, snapshotView(designHome, design, item));
997
+ return;
998
+ }
999
+ if (req.method !== 'POST') {
1000
+ json(res, 405, { error: 'method not allowed' });
1001
+ return;
1002
+ }
1003
+ if (!guardMutation(req, res))
1004
+ return;
1005
+ const body = (await readBody(req));
1006
+ const design = body?.design;
1007
+ const item = typeof body?.item === 'string' ? body.item : undefined;
1008
+ // `items` (several ids, like the CLI) or `item`; neither means every item.
1009
+ const rawItems = body?.items;
1010
+ const listed = Array.isArray(rawItems)
1011
+ ? rawItems.filter((id) => typeof id === 'string')
1012
+ : [];
1013
+ const itemIds = listed.length ? listed : item ? [item] : undefined;
1014
+ if (!isValidDesignId(design)) {
1015
+ json(res, 400, { error: 'valid design id is required' });
1016
+ return;
1017
+ }
1018
+ const rawFrames = body?.frames;
1019
+ const frames = Array.isArray(rawFrames)
1020
+ ? rawFrames.filter((key) => typeof key === 'string')
1021
+ : undefined;
1022
+ const action = body?.action;
1023
+ if (action === 'capture') {
1024
+ const result = await enqueueSnapshots(() => captureBaselines({
1025
+ root: designHome,
1026
+ design,
1027
+ itemIds,
1028
+ force: body?.force === true,
1029
+ url: selfUrl(),
1030
+ }));
1031
+ reviewHub.broadcast(design, readReview(designHome, design));
1032
+ // Like the CLI: an item with no rendered screen is an error (its check fails).
1033
+ const empty = emptyCaptureError(result);
1034
+ json(res, empty ? 422 : 200, empty ? { error: empty, ...result } : result);
1035
+ return;
1036
+ }
1037
+ if (action === 'compare') {
1038
+ const result = await enqueueSnapshots(() => compareSnapshots({ root: designHome, design, itemIds, url: selfUrl() }));
1039
+ reviewHub.broadcast(design, readReview(designHome, design));
1040
+ json(res, 200, result);
1041
+ return;
1042
+ }
1043
+ if (action === 'accept' || action === 'reject') {
1044
+ if (!item) {
1045
+ json(res, 400, { error: 'item is required (one item per decision)' });
1046
+ return;
1047
+ }
1048
+ const result = decideSnapshots({
1049
+ root: designHome,
1050
+ design,
1051
+ itemId: item,
1052
+ frames,
1053
+ decision: action === 'accept' ? 'accepted' : 'rejected',
1054
+ reason: typeof body?.reason === 'string' ? body.reason : undefined,
1055
+ });
1056
+ reviewHub.broadcast(design, readReview(designHome, design));
1057
+ json(res, 200, { frames: result.frames, check: result.check, status: result.item.status });
1058
+ return;
1059
+ }
1060
+ json(res, 400, { error: 'action must be capture, compare, accept or reject' });
1061
+ })().catch((error) => {
1062
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
1063
+ });
1064
+ return;
1065
+ }
1066
+ // Consolidation (整合已有样式), mirroring `seji consolidate <command>`:
1067
+ // GET /__seji/api/consolidate/scan?scope=…&category=…&tolerance=… (read-only)
1068
+ // GET /__seji/api/consolidate/plan → list of plans
1069
+ // GET /__seji/api/consolidate/plan?id=<plan> → one plan (+ readiness)
1070
+ // POST /__seji/api/consolidate/<scan|plan|set|apply|revert|discard> with the CLI
1071
+ // options as camelCase JSON ({ scope, category, plan, row, action, name, tier, … });
1072
+ // apply takes `snapshots: true` like `consolidate apply --snapshots`.
1073
+ if (url.pathname.startsWith('/__seji/api/consolidate/')) {
1074
+ const command = url.pathname.slice('/__seji/api/consolidate/'.length);
1075
+ const routes = ['scan', 'plan', 'set', 'apply', 'revert', 'discard'];
1076
+ if (!routes.includes(command) || !CONSOLIDATE_COMMANDS.includes(command)) {
1077
+ json(res, 404, { error: `unknown consolidate command: ${command}`, commands: routes });
1078
+ return;
1079
+ }
1080
+ const respond = (promise, broadcast) => {
1081
+ promise
1082
+ .then((result) => {
1083
+ const design = typeof result.design === 'string' ? result.design : undefined;
1084
+ if (broadcast && design && result.dryRun !== true && isValidDesignId(design)) {
1085
+ reviewHub.broadcast(design, readReview(designHome, design));
1086
+ }
1087
+ json(res, 200, result);
1088
+ })
1089
+ .catch((error) => {
1090
+ const details = error?.details;
1091
+ json(res, consolidateErrorStatus(error), {
1092
+ error: error instanceof Error ? error.message : 'Consolidation failed',
1093
+ ...(details ?? {}),
1094
+ });
1095
+ });
1096
+ };
1097
+ if (req.method === 'GET') {
1098
+ if (command === 'scan') {
1099
+ const args = {
1100
+ scope: url.searchParams.getAll('scope'),
1101
+ category: url.searchParams.getAll('category'),
1102
+ ...(url.searchParams.has('tolerance') ? { tolerance: url.searchParams.get('tolerance') ?? '' } : {}),
1103
+ ...(url.searchParams.has('rootPx') ? { rootPx: url.searchParams.get('rootPx') ?? '' } : {}),
1104
+ };
1105
+ respond(runConsolidate({ root, command: 'scan', args }), false);
1106
+ return;
1107
+ }
1108
+ if (command === 'plan') {
1109
+ const id = url.searchParams.get('id');
1110
+ respond(runConsolidate({ root, command: id ? 'show' : 'list', args: id ? { plan: id } : {} }), false);
1111
+ return;
1112
+ }
1113
+ json(res, 405, { error: 'method not allowed' });
1114
+ return;
1115
+ }
1116
+ if (req.method !== 'POST') {
1117
+ json(res, 405, { error: 'method not allowed' });
1118
+ return;
1119
+ }
1120
+ if (CONSOLIDATE_MUTATING.has(command) && !guardMutation(req, res))
1121
+ return;
1122
+ void (async () => {
1123
+ const raw = ((await readBody(req)) ?? {});
1124
+ const { snapshots: wantSnapshots, ...body } = raw;
1125
+ if (body.design !== undefined && !isValidDesignId(body.design)) {
1126
+ json(res, 400, { error: 'invalid design id' });
1127
+ return;
1128
+ }
1129
+ const request = toolSnapshotsRequest({ kind: 'consolidate', op: command, snapshots: wantSnapshots, dryRun: body.dryRun === true });
1130
+ if (request.error !== undefined) {
1131
+ json(res, 400, { error: request.error });
1132
+ return;
1133
+ }
1134
+ const snapshot = request.take ? await toolBaseline() : null;
1135
+ const hooks = snapshot && !('skipped' in snapshot) ? snapshot.hooks : undefined;
1136
+ respond(runConsolidate({ root, command, args: body, ...(hooks ? { hooks } : {}) }).then((result) => snapshot ? { ...result, snapshots: compareAfterTool(snapshot, result) } : result), command === 'apply' || command === 'revert');
1137
+ })().catch((error) => {
1138
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
1139
+ });
1140
+ return;
1141
+ }
1142
+ // Tool-executed token operations, mirroring `seji tokens <op>`:
1143
+ // GET /__seji/api/tokens: the virtual:design/tokens exports, built from the token files.
1144
+ if (url.pathname === '/__seji/api/tokens') {
1145
+ if (req.method !== 'GET') {
1146
+ json(res, 405, { error: 'method not allowed' });
1147
+ return;
1148
+ }
1149
+ void tokenModuleData({ root: designHome })
1150
+ .then((data) => json(res, 200, data))
1151
+ .catch((error) => json(res, 500, { error: error instanceof Error ? error.message : String(error) }));
1152
+ return;
1153
+ }
1154
+ // POST /__seji/api/tokens/<rename|merge|deprecate|delete|describe|set|create|replace-literal|revert>
1155
+ // with the CLI options as camelCase JSON ({ token, to, dryRun, design, … }), plus
1156
+ // `snapshots: true` like `--snapshots` (baseline before the write, compare after it).
1157
+ if (url.pathname.startsWith('/__seji/api/tokens/')) {
1158
+ const op = url.pathname.slice('/__seji/api/tokens/'.length);
1159
+ if (!TOKEN_OPS.includes(op)) {
1160
+ json(res, 404, { error: `unknown token operation: ${op}`, operations: TOKEN_OPS });
1161
+ return;
1162
+ }
1163
+ if (req.method !== 'POST') {
1164
+ json(res, 405, { error: 'method not allowed' });
1165
+ return;
1166
+ }
1167
+ if (!guardMutation(req, res))
1168
+ return;
1169
+ void (async () => {
1170
+ const raw = ((await readBody(req)) ?? {});
1171
+ const { snapshots: wantSnapshots, ...body } = raw;
1172
+ if (body.design !== undefined && !isValidDesignId(body.design)) {
1173
+ json(res, 400, { error: 'invalid design id' });
1174
+ return;
1175
+ }
1176
+ const request = toolSnapshotsRequest({ kind: 'tokens', op, snapshots: wantSnapshots, dryRun: body.dryRun === true });
1177
+ if (request.error !== undefined) {
1178
+ json(res, 400, { error: request.error });
1179
+ return;
1180
+ }
1181
+ const snapshot = request.take ? await toolBaseline() : null;
1182
+ const hooks = snapshot && !('skipped' in snapshot) ? snapshot.hooks : undefined;
1183
+ const result = await runTokenOp({ root: designHome, op, args: body, ...(hooks ? { hooks } : {}) });
1184
+ const design = typeof result.design === 'string' ? result.design : undefined;
1185
+ if (design && body.dryRun !== true)
1186
+ reviewHub.broadcast(design, readReview(designHome, design));
1187
+ json(res, 200, snapshot ? { ...result, snapshots: compareAfterTool(snapshot, result) } : result);
1188
+ })().catch((error) => {
1189
+ if (error instanceof TokenOpError) {
1190
+ const code = error.details?.code;
1191
+ json(res, code === 'invalid-args' ? 400 : 409, { error: error.message, ...(error.details ?? {}) });
1192
+ return;
1193
+ }
1194
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
1195
+ });
1196
+ return;
1197
+ }
1198
+ if (url.pathname === '/__seji/api/open' && req.method === 'POST') {
1199
+ if (!guardMutation(req, res))
1200
+ return;
1201
+ void (async () => {
1202
+ const body = (await readBody(req));
1203
+ if (!body || typeof body.file !== 'string') {
1204
+ json(res, 400, { error: 'file is required' });
1205
+ return;
1206
+ }
1207
+ const relative = body.file.replaceAll('\\', '/');
1208
+ if (path.isAbsolute(relative) || relative.split('/').includes('..')) {
1209
+ json(res, 400, { error: 'invalid file' });
1210
+ return;
1211
+ }
1212
+ const absolute = path.resolve(root, relative);
1213
+ if (!absolute.startsWith(`${root}${path.sep}`) || !fs.existsSync(absolute)) {
1214
+ json(res, 404, { error: 'file not found' });
1215
+ return;
1216
+ }
1217
+ if (!resolved.openInEditor) {
1218
+ json(res, 200, { opened: false, file: relative });
1219
+ return;
1220
+ }
1221
+ const line = Number.isSafeInteger(body.line) && body.line > 0 ? `:${body.line}` : '';
1222
+ const child = spawn(resolved.openInEditor, ['-g', `${absolute}${line}`], {
1223
+ detached: true,
1224
+ stdio: 'ignore',
1225
+ });
1226
+ const opened = await new Promise((resolve) => {
1227
+ child.once('spawn', () => resolve(true));
1228
+ child.once('error', () => resolve(false));
1229
+ });
1230
+ child.unref();
1231
+ if (!opened) {
1232
+ json(res, 500, { error: 'editor command not found' });
1233
+ return;
1234
+ }
1235
+ json(res, 200, { opened: true, file: relative });
1236
+ })().catch((error) => {
1237
+ json(res, 400, { error: error instanceof Error ? error.message : 'Bad request' });
1238
+ });
1239
+ return;
1240
+ }
1241
+ if (url.pathname === '/__seji/preview') {
1242
+ res.statusCode = 200;
1243
+ res.setHeader('content-type', 'text/html; charset=utf-8');
1244
+ res.setHeader('cache-control', 'no-store');
1245
+ res.end(html('Design preview', previewMain, resolved.reactRefresh));
1246
+ return;
1247
+ }
1248
+ if (url.pathname === '/__seji' || url.pathname === '/__seji/') {
1249
+ const bundled = hasEditorBundle();
1250
+ const entry = bundled ? editorBundleJs : editorSourceMain;
1251
+ const cssUrl = bundled ? toUrl(editorBundleCss) : undefined;
1252
+ res.statusCode = 200;
1253
+ res.setHeader('content-type', 'text/html; charset=utf-8');
1254
+ res.setHeader('cache-control', 'no-store');
1255
+ res.end(html(resolved.title, entry, resolved.reactRefresh, cssUrl, true));
1256
+ return;
1257
+ }
1258
+ next();
1259
+ });
1260
+ },
1261
+ };
1262
+ return plugin;
1263
+ }
1264
+ //# sourceMappingURL=plugin.js.map