@salsita-ai/sdk 0.50.0-develop.da56a0c6c3 → 0.50.0-develop.db8514eccf

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 (283) hide show
  1. package/README.md +19 -11
  2. package/dist/application-spec/errors/diagnostic-codes.d.ts +6 -0
  3. package/dist/application-spec/errors/diagnostic-codes.js +1 -1
  4. package/dist/application-spec/errors/diagnostic-messages.d.ts +6 -0
  5. package/dist/application-spec/errors/diagnostic-messages.js +1 -1
  6. package/dist/application-spec/generate-application/code/domain-runtime-files.js +1 -1
  7. package/dist/application-spec/generate-application/code/project-scaffolding.js +2 -2
  8. package/dist/application-spec/generate-application/code/templates/application-types.js +6 -6
  9. package/dist/application-spec/generate-application/code/templates/configurator-domain-code.d.ts +1 -0
  10. package/dist/application-spec/generate-application/code/templates/configurator-domain-code.js +11 -8
  11. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-domain-block.d.ts +3 -1
  12. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-domain-block.js +70 -66
  13. package/dist/application-spec/generate-application/code/templates/domain-spec/generate-phx-globals.js +3 -0
  14. package/dist/application-spec/generate-application/code/templates/domain-spec.js +5 -5
  15. package/dist/application-spec/generate-application/code/templates/domain.js +2 -2
  16. package/dist/application-spec/generate-application/code/templates/global-definition/generate-action-types.d.ts +11 -0
  17. package/dist/application-spec/generate-application/code/templates/global-definition/generate-action-types.js +8 -0
  18. package/dist/application-spec/generate-application/code/templates/global-definition/index.d.ts +1 -0
  19. package/dist/application-spec/generate-application/code/templates/global-definition/index.js +1 -1
  20. package/dist/application-spec/generate-application/code/templates/globals.js +1 -0
  21. package/dist/application-spec/generate-application/code/templates/index.d.ts +1 -0
  22. package/dist/application-spec/generate-application/code/templates/index.js +1 -1
  23. package/dist/application-spec/generate-application/code/templates/skills/agents-md.js +1 -1
  24. package/dist/application-spec/generate-application/code/templates/skills/phoenix-cli-skill.js +1 -1
  25. package/dist/application-spec/generate-application/code/templates/skills/phoenix-create-configurator-skill.js +43 -13
  26. package/dist/application-spec/generate-application/code/templates/skills/phoenix-feedback-skill.js +39 -16
  27. package/dist/application-spec/generate-application/code/templates/skills/phoenix-review-skill.js +5 -3
  28. package/dist/application-spec/generate-application/code/templates/skills/phoenix-skill.js +1 -1
  29. package/dist/application-spec/generate-application/code/templates/skills/phoenix-variants-skill.d.ts +1 -0
  30. package/dist/application-spec/generate-application/code/templates/skills/phoenix-variants-skill.js +6 -0
  31. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.d.ts +31 -3
  32. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.js +19 -4
  33. package/dist/application-spec/generate-application/runtime/configurator-runtime/configurator-runtime.d.ts +2 -0
  34. package/dist/application-spec/generate-application/runtime/configurator-runtime/configurator-runtime.js +1 -1
  35. package/dist/application-spec/generate-application/runtime/sections/actions-runtime.d.ts +14 -0
  36. package/dist/application-spec/generate-application/runtime/sections/actions-runtime.js +1 -0
  37. package/dist/application-spec/generate-application/runtime/sections/index.d.ts +1 -0
  38. package/dist/application-spec/generate-application/runtime/sections/index.js +1 -1
  39. package/dist/application-spec/parse-application-files/categorize/categorize-files.d.ts +3 -1
  40. package/dist/application-spec/parse-application-files/categorize/categorize-files.js +1 -1
  41. package/dist/application-spec/parse-application-files/merge/index.d.ts +1 -0
  42. package/dist/application-spec/parse-application-files/merge/index.js +1 -1
  43. package/dist/application-spec/parse-application-files/merge/merged-actions.d.ts +11 -0
  44. package/dist/application-spec/parse-application-files/merge/merged-actions.js +1 -0
  45. package/dist/application-spec/parse-application-files/merge/merged-spec.d.ts +2 -0
  46. package/dist/application-spec/parse-application-files/merge/merged-spec.js +1 -1
  47. package/dist/application-spec/parse-application-files/raw-spec/index.d.ts +1 -0
  48. package/dist/application-spec/parse-application-files/raw-spec/index.js +1 -1
  49. package/dist/application-spec/parse-application-files/raw-spec/raw-actions.d.ts +18 -0
  50. package/dist/application-spec/parse-application-files/raw-spec/raw-actions.js +1 -0
  51. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.d.ts +14 -2
  52. package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.js +1 -1
  53. package/dist/application-spec/parse-application-files/raw-spec/raw-spec-file.d.ts +2 -0
  54. package/dist/application-spec/parse-application-files/raw-spec/raw-spec-file.js +1 -1
  55. package/dist/application-spec/parse-application-files/resolve/resolve-import-modules.js +1 -1
  56. package/dist/application-spec/parse-application-files/spec/application/application-spec.js +1 -1
  57. package/dist/application-spec/parse-application-files/spec/application/configurator-spec/configurator-spec.d.ts +4 -2
  58. package/dist/application-spec/parse-application-files/spec/application/configurator-spec/configurator-spec.js +1 -1
  59. package/dist/application-spec/parse-application-files/spec/common/index.d.ts +1 -0
  60. package/dist/application-spec/parse-application-files/spec/common/index.js +1 -1
  61. package/dist/application-spec/parse-application-files/spec/common/schema-ref-resolver.d.ts +23 -0
  62. package/dist/application-spec/parse-application-files/spec/common/schema-ref-resolver.js +1 -0
  63. package/dist/application-spec/parse-application-files/spec/model/names/action-name.d.ts +10 -0
  64. package/dist/application-spec/parse-application-files/spec/model/names/action-name.js +1 -0
  65. package/dist/application-spec/parse-application-files/spec/model/names/index.d.ts +1 -0
  66. package/dist/application-spec/parse-application-files/spec/model/names/index.js +1 -1
  67. package/dist/application-spec/parse-application-files/spec/sections/actions.d.ts +35 -0
  68. package/dist/application-spec/parse-application-files/spec/sections/actions.js +1 -0
  69. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.d.ts +3 -14
  70. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.js +1 -1
  71. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.d.ts +12 -3
  72. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
  73. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant.d.ts +5 -3
  74. package/dist/application-spec/parse-application-files/spec/sections/index.d.ts +1 -0
  75. package/dist/application-spec/parse-application-files/spec/sections/index.js +1 -1
  76. package/dist/configurator/application-runtime/extensions/configurator-extension-systems.d.ts +2 -1
  77. package/dist/configurator/application-runtime/extensions/configurator-extension-systems.js +1 -1
  78. package/dist/configurator/application-runtime/extensions/selectors.d.ts +2 -1
  79. package/dist/configurator/application-runtime/extensions/selectors.js +1 -1
  80. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +168 -0
  81. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -0
  82. package/dist/configurator/{assistant → application-runtime/extensions/systems/assistant-system}/browser-details.d.ts +1 -1
  83. package/dist/configurator/application-runtime/extensions/systems/assistant-system/browser-details.js +1 -0
  84. package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.d.ts +85 -0
  85. package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.js +1 -0
  86. package/dist/configurator/{assistant → application-runtime/extensions/systems/assistant-system}/graphql-tools.d.ts +20 -16
  87. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.js +1 -0
  88. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts +4 -0
  89. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js +1 -1
  90. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.d.ts +16 -1
  91. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
  92. package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.d.ts +9 -0
  93. package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.js +1 -0
  94. package/dist/configurator/application-runtime/extensions/systems/index.d.ts +1 -0
  95. package/dist/configurator/application-runtime/extensions/systems/index.js +1 -1
  96. package/dist/configurator/application-runtime/extensions/systems/layout-system/layout-system.d.ts +2 -0
  97. package/dist/configurator/application-runtime/extensions/systems/layout-system/layout-system.js +1 -1
  98. package/dist/configurator/common/frontend-analytics.d.ts +21 -21
  99. package/dist/configurator/index.d.ts +0 -1
  100. package/dist/configurator/index.js +1 -1
  101. package/dist/configurator/pages/LoadedConfiguratorDetailPage.js +1 -1
  102. package/dist/configurator/scene/scene-analytics/scene-analytics.d.ts +2 -2
  103. package/dist/configurator/ui/assistant/AssistantChips.d.ts +11 -0
  104. package/dist/configurator/ui/assistant/AssistantChips.js +1 -0
  105. package/dist/configurator/ui/assistant/AssistantComposer.d.ts +6 -0
  106. package/dist/configurator/ui/assistant/AssistantComposer.js +1 -0
  107. package/dist/configurator/ui/assistant/AssistantMarkdown.d.ts +7 -0
  108. package/dist/configurator/ui/assistant/AssistantMarkdown.js +1 -0
  109. package/dist/configurator/ui/assistant/AssistantPanel.d.ts +11 -0
  110. package/dist/configurator/ui/assistant/AssistantPanel.js +1 -0
  111. package/dist/configurator/ui/assistant/AssistantThread.d.ts +6 -0
  112. package/dist/configurator/ui/assistant/AssistantThread.js +1 -0
  113. package/dist/configurator/ui/assistant/assistant-failure.d.ts +18 -0
  114. package/dist/configurator/ui/assistant/assistant-failure.js +1 -0
  115. package/dist/configurator/ui/assistant/index.d.ts +2 -0
  116. package/dist/configurator/ui/assistant/index.js +1 -0
  117. package/dist/configurator/ui/assistant/streamed-markdown.d.ts +6 -0
  118. package/dist/configurator/ui/assistant/streamed-markdown.js +2 -0
  119. package/dist/configurator/ui/assistant/theme.d.ts +2 -0
  120. package/dist/configurator/ui/assistant/theme.js +1 -0
  121. package/dist/configurator/ui/assistant/thread-items.d.ts +37 -0
  122. package/dist/configurator/ui/assistant/thread-items.js +1 -0
  123. package/dist/configurator/ui/assistant/tool-chip.d.ts +37 -0
  124. package/dist/configurator/ui/assistant/tool-chip.js +1 -0
  125. package/dist/configurator/ui/assistant/use-follow-stream.d.ts +17 -0
  126. package/dist/configurator/ui/assistant/use-follow-stream.js +1 -0
  127. package/dist/configurator/ui/assistant/use-is-assistant-panel-open.d.ts +5 -0
  128. package/dist/configurator/ui/assistant/use-is-assistant-panel-open.js +1 -0
  129. package/dist/configurator/ui/configurator-layout/universal/DesktopLayout.js +5 -5
  130. package/dist/configurator/ui/configurator-layout/universal/MobileLayout.d.ts +2 -0
  131. package/dist/configurator/ui/configurator-layout/universal/MobileLayout.js +4 -4
  132. package/dist/configurator/ui/legacy/mobile-controls/MobileControls.d.ts +1 -1
  133. package/dist/configurator/ui/phoenix-layout-elements/AssistantToolbarButton.d.ts +10 -0
  134. package/dist/configurator/ui/phoenix-layout-elements/AssistantToolbarButton.js +1 -0
  135. package/dist/configurator/ui/phoenix-layout-elements/index.d.ts +1 -0
  136. package/dist/configurator/ui/phoenix-layout-elements/index.js +1 -1
  137. package/dist/docs/index.json +12 -2
  138. package/dist/docs/layouts/toolbar.mdx +6 -0
  139. package/dist/docs/other-features/domain-actions.mdx +418 -0
  140. package/dist/docs/other-features/side-effects.mdx +26 -0
  141. package/dist/docs/phoenix/admin.mdx +2 -2
  142. package/dist/docs/phoenix/best-practices.mdx +1 -0
  143. package/dist/docs/phoenix/finalization.mdx +1 -1
  144. package/dist/docs/phoenix/integration/headless-mode-external.mdx +5 -5
  145. package/dist/docs/phoenix/integration/widget-mode-external.mdx +5 -5
  146. package/dist/docs/phoenix/phoenix-cli.mdx +139 -20
  147. package/dist/docs/phoenix/project-structure.mdx +7 -3
  148. package/dist/docs/phoenix/sdk-builder-workflow.mdx +8 -6
  149. package/dist/domain/actions/action-factory.d.ts +10 -0
  150. package/dist/domain/actions/action-factory.js +1 -0
  151. package/dist/domain/actions/prepare-action-implementations.d.ts +15 -0
  152. package/dist/domain/actions/prepare-action-implementations.js +5 -0
  153. package/dist/domain/application/application-config.d.ts +3 -1
  154. package/dist/domain/application/assistant-mutations.d.ts +15 -14
  155. package/dist/domain/application/assistant-mutations.js +1 -1
  156. package/dist/domain/components/updates.d.ts +16 -0
  157. package/dist/domain/core/action.d.ts +67 -0
  158. package/dist/domain/core/action.js +1 -0
  159. package/dist/domain/core/domain-factory.d.ts +4 -0
  160. package/dist/domain/core/index.d.ts +1 -0
  161. package/dist/domain/domain-builder.d.ts +7 -0
  162. package/dist/domain/domain-builder.js +1 -1
  163. package/dist/domain/domain-context/action-system/action-system.d.ts +40 -0
  164. package/dist/domain/domain-context/action-system/action-system.js +1 -0
  165. package/dist/domain/domain-context/domain-context-systems.d.ts +5 -2
  166. package/dist/domain/domain-context/index.d.ts +2 -1
  167. package/dist/domain/domain-context/index.js +1 -1
  168. package/dist/domain/domain-context/store-system/store-system.js +1 -1
  169. package/dist/domain/domain-runtime/domain-context/domain-context.js +1 -1
  170. package/dist/domain/domain-runtime/domain-context/selectors.d.ts +4 -0
  171. package/dist/domain/domain-runtime/domain-context/selectors.js +1 -1
  172. package/dist/domain/domain-runtime/domain-runtime.d.ts +12 -0
  173. package/dist/domain/domain-runtime/spec/initialize.js +1 -1
  174. package/dist/domain/domain-runtime/spec/types.d.ts +15 -1
  175. package/dist/domain/index.d.ts +2 -0
  176. package/dist/domain/index.js +1 -1
  177. package/dist/domain/mocks/create-mock-domain-runtime.d.ts +6 -0
  178. package/dist/domain/system-components/phoenix-layout-elements/assistant-toolbar-button.d.ts +44 -0
  179. package/dist/domain/system-components/phoenix-layout-elements/assistant-toolbar-button.js +1 -0
  180. package/dist/domain/system-components/phoenix-layout-elements/index.d.ts +1 -0
  181. package/dist/domain/system-components/phoenix-layout-elements/index.js +1 -1
  182. package/dist/domain/system-components/phoenix-layout-elements/phoenix-layout-element.d.ts +2 -1
  183. package/dist/domain/system-components/phoenix-layout-elements/phoenix-layout-element.js +1 -1
  184. package/dist/editor/Editor.js +1 -1
  185. package/dist/editor/domain-editors/DomainSpecContext.js +1 -1
  186. package/dist/editor/domain-editors/apply-spec-update.js +1 -1
  187. package/dist/editor/domain-editors/use-implementation-files.d.ts +7 -3
  188. package/dist/editor/domain-editors/use-implementation-files.js +1 -1
  189. package/dist/editor/graphql/GraphQLPanel.js +1 -1
  190. package/dist/editor/variants/VariantAnswerFooter.d.ts +17 -0
  191. package/dist/editor/variants/VariantAnswerFooter.js +1 -0
  192. package/dist/editor/variants/VariantPreviewHandler.d.ts +6 -0
  193. package/dist/editor/variants/VariantPreviewHandler.js +1 -0
  194. package/dist/editor/variants/variant-preview-styles.d.ts +49 -0
  195. package/dist/editor/variants/variant-preview-styles.js +1 -0
  196. package/dist/i18n/locales/cs/messages.js +1 -1
  197. package/dist/i18n/locales/da/messages.js +1 -1
  198. package/dist/i18n/locales/de/messages.js +1 -1
  199. package/dist/i18n/locales/de-AT/messages.js +1 -1
  200. package/dist/i18n/locales/en/messages.js +1 -1
  201. package/dist/i18n/locales/en-AU/messages.js +1 -1
  202. package/dist/i18n/locales/en-GB/messages.js +1 -1
  203. package/dist/i18n/locales/es/messages.js +1 -1
  204. package/dist/i18n/locales/fr/messages.js +1 -1
  205. package/dist/i18n/locales/hu/messages.js +1 -1
  206. package/dist/i18n/locales/it/messages.js +1 -1
  207. package/dist/i18n/locales/nl/messages.js +1 -1
  208. package/dist/i18n/locales/pl/messages.js +1 -1
  209. package/dist/i18n/locales/pt/messages.js +1 -1
  210. package/dist/i18n/locales/ro/messages.js +1 -1
  211. package/dist/i18n/locales/sk/messages.js +1 -1
  212. package/dist/i18n/locales/tr/messages.js +1 -1
  213. package/dist/legacy/domain-spec/__generated/domain-schema.d.ts +6 -0
  214. package/dist/phoenix/application-spec/application-spec-builder.js +1 -1
  215. package/dist/phoenix/application-spec/generate-assistant-prompt.d.ts +4 -3
  216. package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
  217. package/dist/phoenix/cli.js +1 -1
  218. package/dist/phoenix/commands/build.d.ts +5 -0
  219. package/dist/phoenix/commands/build.js +1 -1
  220. package/dist/phoenix/commands/deploy.js +2 -2
  221. package/dist/phoenix/commands/dev.js +5 -5
  222. package/dist/phoenix/commands/feedback.d.ts +2 -1
  223. package/dist/phoenix/commands/feedback.js +1 -1
  224. package/dist/phoenix/commands/index.d.ts +1 -0
  225. package/dist/phoenix/commands/index.js +1 -1
  226. package/dist/phoenix/commands/login.d.ts +24 -6
  227. package/dist/phoenix/commands/login.js +2 -2
  228. package/dist/phoenix/commands/story-dev.js +2 -2
  229. package/dist/phoenix/commands/variants.d.ts +35 -0
  230. package/dist/phoenix/commands/variants.js +1 -0
  231. package/dist/phoenix/editor-server/commands-router.d.ts +68 -1
  232. package/dist/phoenix/editor-server/commands-router.js +1 -1
  233. package/dist/phoenix/editor-server/editor-router.d.ts +65 -0
  234. package/dist/phoenix/editor-server/editor-server.d.ts +3 -3
  235. package/dist/phoenix/editor-server/editor-server.js +1 -1
  236. package/dist/phoenix/editor-server/protocol.d.ts +1 -0
  237. package/dist/phoenix/editor-server/spec-router.js +1 -1
  238. package/dist/phoenix/editor-server/trpc.d.ts +3 -0
  239. package/dist/phoenix/services/application-spec-project-watcher.d.ts +13 -2
  240. package/dist/phoenix/services/application-spec-project-watcher.js +3 -3
  241. package/dist/phoenix/services/index.d.ts +5 -0
  242. package/dist/phoenix/services/index.js +1 -1
  243. package/dist/phoenix/services/phoenix-application.d.ts +21 -0
  244. package/dist/phoenix/services/phoenix-application.js +1 -0
  245. package/dist/phoenix/services/phoenix-store.d.ts +48 -0
  246. package/dist/phoenix/services/phoenix-store.js +1 -0
  247. package/dist/phoenix/services/phx-banner-plugin.d.ts +32 -0
  248. package/dist/phoenix/services/phx-banner-plugin.js +1 -0
  249. package/dist/phoenix/services/phx-licenses-plugin.d.ts +55 -0
  250. package/dist/phoenix/services/phx-licenses-plugin.js +8 -0
  251. package/dist/phoenix/services/phx-variant-previews-plugin.d.ts +9 -0
  252. package/dist/phoenix/services/phx-variant-previews-plugin.js +1 -0
  253. package/dist/phoenix/services/variant-file-session.d.ts +36 -0
  254. package/dist/phoenix/services/variant-file-session.js +1 -0
  255. package/dist/phoenix/services/variant-preview-service.d.ts +80 -0
  256. package/dist/phoenix/services/variant-preview-service.js +1 -0
  257. package/dist/phoenix/services/vite-config.d.ts +2 -0
  258. package/dist/phoenix/services/vite-config.js +1 -1
  259. package/dist/phoenix/utils/index.d.ts +1 -0
  260. package/dist/phoenix/utils/index.js +1 -1
  261. package/dist/phoenix/utils/read-git-commit.d.ts +14 -0
  262. package/dist/phoenix/utils/read-git-commit.js +1 -0
  263. package/dist/react-sdk/application-runtime/common-services/analytics/analytics-service.d.ts +2 -2
  264. package/dist/react-sdk/application-runtime/common-services/analytics/domain-controls-analytics.d.ts +21 -21
  265. package/dist/react-sdk/application-runtime/hooks/data/use-published-data.d.ts +1 -1
  266. package/dist/react-sdk/application-runtime/runtime/create-application-runtime.d.ts +12 -0
  267. package/dist/react-sdk/domain-context/common-hooks/use-domain-context.d.ts +3 -0
  268. package/dist/ui-sdk/common/use-viewport-size.d.ts +4 -1
  269. package/dist/ui-sdk/common/use-viewport-size.js +1 -1
  270. package/dist/ui-sdk/components/mobile-controls/index.d.ts +1 -1
  271. package/dist/ui-sdk/theme/types.d.ts +4 -0
  272. package/package.json +5 -8
  273. package/schema/domain-spec.json +24 -0
  274. package/dist/configurator/assistant/browser-details.js +0 -1
  275. package/dist/configurator/assistant/graphql-tools.js +0 -1
  276. package/dist/configurator/assistant/index.d.ts +0 -1
  277. package/dist/configurator/assistant/index.js +0 -1
  278. package/dist/configurator/assistant/use-assistant-chat.d.ts +0 -20
  279. package/dist/configurator/assistant/use-assistant-chat.js +0 -1
  280. package/dist/extras/assistant/AssistantChat.d.ts +0 -6
  281. package/dist/extras/assistant/AssistantChat.js +0 -1
  282. package/dist/extras/assistant/index.d.ts +0 -1
  283. package/dist/extras/assistant/index.js +0 -1
@@ -2,7 +2,8 @@ import { type FeedbackType } from '@salsita-ai/contracts/domain';
2
2
  import type { CommandContext } from './types.js';
3
3
  export interface FeedbackCommandProps {
4
4
  readonly serverUrl: string;
5
- readonly message: string;
5
+ readonly message: string | undefined;
6
+ readonly file: string | undefined;
6
7
  readonly type: FeedbackType;
7
8
  readonly contact: string | undefined;
8
9
  readonly agent: string | undefined;
@@ -1 +1 @@
1
- import{FEEDBACK_CONTACT_MAX_LENGTH as e,FEEDBACK_MESSAGE_MAX_LENGTH as t}from"@salsita-ai/contracts/domain";import{createApiBaseClient as a}from"#package/client";import{getServerCredentials as r}from"../services/index.js";export const runFeedbackCommand=async(o,{logger:n})=>{let s=o.message.trim(),c=o.contact?.trim(),i=o.agent?.trim();if(0===s.length)throw Error('The feedback message is empty. Pass what you want to tell us: phoenix feedback "<message>".');if(s.length>t)throw Error(`The feedback message has ${s.length} characters, but at most ${t} are accepted. Shorten it and send it again.`);if(c&&c.length>e)throw Error(`The contact detail has ${c.length} characters, but at most ${e} are accepted. Shorten --contact and send the feedback again.`);let h=await r(o.serverUrl);if(!h)throw Error(`You are not signed in to ${o.serverUrl}, so the feedback was not sent. Run \`phoenix login <workspace>\` first, then send it again.`);let{error:d}=await a(o.serverUrl).POST("/feedback",{body:{message:s,type:o.type,clientVersion:o.sdkVersion,clientInfo:o.clientInfo,...c?{contact:c}:{},...i?{agent:i}:{},...o.project?{project:o.project}:{}},headers:{authorization:`Bearer ${h.token}`}});if(d)throw Error(`The server did not accept the feedback: ${d.message}`);n.success(`Feedback sent to the Phoenix team from workspace ${h.customerName}. Thank you.`)};
1
+ import{readFile as e}from"node:fs/promises";import{FEEDBACK_CONTACT_MAX_LENGTH as t,FEEDBACK_MESSAGE_MAX_LENGTH as a}from"@salsita-ai/contracts/domain";import{createApiBaseClient as r}from"#package/client";import{getServerCredentials as o}from"../services/index.js";let s=async t=>{if(void 0!==t.message&&void 0!==t.file)throw Error("Both a message and --file were given, so it is unclear which one to send. Pass the message as an argument or put it in the file, not both.");if(void 0!==t.file)return e(t.file,"utf8").catch(e=>{throw Error(`The feedback file ${t.file} could not be read: ${e instanceof Error?e.message:String(e)}. Check the path passed to --file and send the feedback again.`)});if(void 0===t.message)throw Error('No feedback message was given. Pass it as an argument, phoenix feedback "<message>", or in a text file with --file <path>.');return t.message};export const runFeedbackCommand=async(e,{logger:i})=>{let n=(await s(e)).trim(),c=e.contact?.trim(),h=e.agent?.trim();if(0===n.length)throw Error('The feedback message is empty. Pass what you want to tell us: phoenix feedback "<message>", or a text file with --file <path>.');if(n.length>a)throw Error(`The feedback message has ${n.length} characters, but at most ${a} are accepted. Shorten it and send it again.`);if(c&&c.length>t)throw Error(`The contact detail has ${c.length} characters, but at most ${t} are accepted. Shorten --contact and send the feedback again.`);let d=await o(e.serverUrl);if(!d)throw Error(`You are not signed in to ${e.serverUrl}, so the feedback was not sent. Run \`phoenix login <workspace>\` first, then send it again.`);let{error:f}=await r(e.serverUrl).POST("/feedback",{body:{message:n,type:e.type,clientVersion:e.sdkVersion,clientInfo:e.clientInfo,...c?{contact:c}:{},...h?{agent:h}:{},...e.project?{project:e.project}:{}},headers:{authorization:`Bearer ${d.token}`}});if(f)throw Error(`The server did not accept the feedback: ${f.message}`);i.success(`Feedback sent to the Phoenix team from workspace ${d.customerName}. Thank you.`)};
@@ -30,6 +30,7 @@ export { runScreenshotCommand } from './screenshot.js';
30
30
  export { runStateCommand } from './state.js';
31
31
  export { runDataCommand } from './data.js';
32
32
  export { runSceneCommand } from './scene.js';
33
+ export { runVariantsCommand } from './variants.js';
33
34
  export { runLoginCommand } from './login.js';
34
35
  export { runLogoutCommand } from './logout.js';
35
36
  export { runDeployCommand } from './deploy.js';
@@ -1 +1 @@
1
- export{runBuildCommand}from"./build.js";export{runCheckCommand}from"./check.js";export{runCleanCommand}from"./clean.js";export{runActivateDeploymentCommand}from"./activate-deployment.js";export{runCreateEnvironmentCommand}from"./create-environment.js";export{runCleanupEnvironmentCommand}from"./cleanup-environment.js";export{runListEnvironmentsCommand}from"./list-environments.js";export{runRegisterDeploymentCommand}from"./register-deployment.js";export{runPrepareDeploymentCommand}from"./prepare-deployment-command.js";export{prepareDevelopmentEnvironment}from"../services/prepare-development-environment.js";export{prepareLocalEnvironment}from"./prepare-local-environment-command.js";export{runFinishDeploymentCommand}from"./finish-deployment-command.js";export{runDeploymentBuildEnvsCommand}from"./deployment-build-envs-command.js";export{runDevCommand}from"./dev.js";export{runFixCommand}from"./fix.js";export{runLinkCommand}from"./link.js";export{runUnlinkCommand}from"./unlink.js";export{runPrepareCiCommand}from"./prepare-ci.js";export{runStoryCommand}from"./story.js";export{runStoryBuildCommand}from"./story-build.js";export{runStoryCreateCommand}from"./story-create.js";export{runStoryDevCommand}from"./story-dev.js";export{runInitCommand}from"./init.js";export{runSyncCommand}from"./sync.js";export{runChangelogCommand}from"./changelog.js";export{runDocsCommand}from"./docs.js";export{runInspectAssetsCommand}from"./inspect-assets.js";export{runScreenshotCommand}from"./screenshot.js";export{runStateCommand}from"./state.js";export{runDataCommand}from"./data.js";export{runSceneCommand}from"./scene.js";export{runLoginCommand}from"./login.js";export{runLogoutCommand}from"./logout.js";export{runDeployCommand}from"./deploy.js";export{runFeedbackCommand}from"./feedback.js";export{runExtractSourcesCommand}from"./extract-sources-command.js";
1
+ export{runBuildCommand}from"./build.js";export{runCheckCommand}from"./check.js";export{runCleanCommand}from"./clean.js";export{runActivateDeploymentCommand}from"./activate-deployment.js";export{runCreateEnvironmentCommand}from"./create-environment.js";export{runCleanupEnvironmentCommand}from"./cleanup-environment.js";export{runListEnvironmentsCommand}from"./list-environments.js";export{runRegisterDeploymentCommand}from"./register-deployment.js";export{runPrepareDeploymentCommand}from"./prepare-deployment-command.js";export{prepareDevelopmentEnvironment}from"../services/prepare-development-environment.js";export{prepareLocalEnvironment}from"./prepare-local-environment-command.js";export{runFinishDeploymentCommand}from"./finish-deployment-command.js";export{runDeploymentBuildEnvsCommand}from"./deployment-build-envs-command.js";export{runDevCommand}from"./dev.js";export{runFixCommand}from"./fix.js";export{runLinkCommand}from"./link.js";export{runUnlinkCommand}from"./unlink.js";export{runPrepareCiCommand}from"./prepare-ci.js";export{runStoryCommand}from"./story.js";export{runStoryBuildCommand}from"./story-build.js";export{runStoryCreateCommand}from"./story-create.js";export{runStoryDevCommand}from"./story-dev.js";export{runInitCommand}from"./init.js";export{runSyncCommand}from"./sync.js";export{runChangelogCommand}from"./changelog.js";export{runDocsCommand}from"./docs.js";export{runInspectAssetsCommand}from"./inspect-assets.js";export{runScreenshotCommand}from"./screenshot.js";export{runStateCommand}from"./state.js";export{runDataCommand}from"./data.js";export{runSceneCommand}from"./scene.js";export{runVariantsCommand}from"./variants.js";export{runLoginCommand}from"./login.js";export{runLogoutCommand}from"./logout.js";export{runDeployCommand}from"./deploy.js";export{runFeedbackCommand}from"./feedback.js";export{runExtractSourcesCommand}from"./extract-sources-command.js";
@@ -5,19 +5,37 @@ export interface LoginCommandProps {
5
5
  readonly studioUrl: string;
6
6
  readonly open: boolean;
7
7
  }
8
+ type LoginOutcome = {
9
+ readonly signedIn: true;
10
+ } | {
11
+ readonly signedIn: false;
12
+ readonly message: string;
13
+ };
14
+ interface LoginCallback {
15
+ readonly code: string;
16
+ readonly tokenName: string | null;
17
+ readonly finish: (outcome: LoginOutcome) => Promise<void>;
18
+ }
8
19
  interface LoginCallbackListener {
9
20
  readonly port: number;
10
- readonly code: Promise<string>;
21
+ readonly callback: Promise<LoginCallback>;
11
22
  readonly close: () => void;
12
23
  }
24
+ interface LoginCallbackListenerProps {
25
+ readonly state: string;
26
+ readonly studioUrl: string;
27
+ readonly customer: string;
28
+ }
13
29
  /**
14
- * Receives the one-time code from Studio on 127.0.0.1. Only a callback carrying this session's state is accepted,
15
- * so another page cannot feed the CLI a code of its own.
30
+ * Receives Studio's answer on 127.0.0.1: the one-time code of an approval, or a denial. Only a callback carrying
31
+ * this session's state is accepted, so another page cannot feed the CLI a code of its own. The browser ends on a
32
+ * Studio page; its address is built from the CLI's own Studio URL, never from the request.
16
33
  */
17
- export declare const startLoginCallbackListener: (state: string) => Promise<LoginCallbackListener>;
34
+ export declare const startLoginCallbackListener: (props: LoginCallbackListenerProps) => Promise<LoginCallbackListener>;
18
35
  /**
19
- * Signs the CLI in to an SDK-builder workspace: the user approves in Studio, Studio returns a one-time code to this
20
- * CLI's loopback listener, and the CLI exchanges it with its PKCE verifier for an API token.
36
+ * Signs the CLI in to an SDK-builder workspace: the user names the token and approves in Studio, Studio returns a
37
+ * one-time code to this CLI's loopback listener, and the CLI exchanges it with its PKCE verifier for an API token.
38
+ * The browser waits on the callback meanwhile and ends on Studio's page for the outcome.
21
39
  */
22
40
  export declare const runLoginCommand: (props: LoginCommandProps, { logger }: CommandContext) => Promise<void>;
23
41
  export {};
@@ -1,4 +1,4 @@
1
- import{spawn as e}from"node:child_process";import{createHash as t,randomBytes as r}from"node:crypto";import{createServer as o}from"node:http";import{hostname as n}from"node:os";import{createApiBaseClient as i}from"#package/client";import{getServerCredentials as s,saveServerCredentials as a}from"../services/index.js";let l=(e,t)=>`<!doctype html><html><head><meta charset="utf-8"><title>${e}</title></head><body style="font-family:system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0"><main style="text-align:center"><h1>${e}</h1><p>${t}</p></main></body></html>`;export const startLoginCallbackListener=async e=>{let t=null,r=new Promise((e,r)=>{t={resolve:e,reject:r}}),n=o((r,o)=>{let n=new URL(r.url??"/","http://127.0.0.1"),i=n.searchParams.get("code");if("/callback"!==n.pathname)return void o.writeHead(404).end();if(n.searchParams.get("state")!==e||!i){o.writeHead(400,{"content-type":"text/html"}),o.end(l("Sign-in failed","This response does not belong to the waiting CLI. Run phoenix login again.")),t?.reject(Error("The sign-in response did not match this CLI session. Run `phoenix login` again."));return}o.writeHead(200,{"content-type":"text/html"}),o.end(l("Phoenix CLI signed in","You can close this tab and return to the terminal.")),t?.resolve(i)}),i=await new Promise((e,t)=>{n.once("error",t),n.listen(0,"127.0.0.1",()=>{let r=n.address();null===r||"string"==typeof r?t(Error("The login callback listener did not get a port. Run `phoenix login` again.")):e(r.port)})}),s=setTimeout(()=>{t?.reject(Error("Nobody approved the sign-in within 5 minutes. Run `phoenix login` again."))},3e5);return{port:i,code:r,close:()=>{clearTimeout(s),n.close()}}};let c=async(e,t)=>{try{let{error:r,response:o}=await i(e).DELETE("/auth/token",{headers:{authorization:`Bearer ${t}`,"content-type":null}});return r&&401!==o.status?r.message:null}catch(e){return e instanceof Error?e.message:String(e)}};export const runLoginCommand=async(o,{logger:l})=>{let d=r(32).toString("base64url"),h=t("sha256").update(d).digest("base64url"),u=r(16).toString("base64url"),m=await startLoginCallbackListener(u);try{let t=new URL("/builder/cli-login",o.studioUrl);t.searchParams.set("customer",o.customer),t.searchParams.set("port",String(m.port)),t.searchParams.set("state",u),t.searchParams.set("challenge",h),l.step(`Signing in to workspace "${o.customer}" on ${o.serverUrl}`),l.info(`Approve the CLI in your browser:
1
+ import{spawn as e}from"node:child_process";import{createHash as t,randomBytes as r}from"node:crypto";import{createServer as o}from"node:http";import{hostname as n}from"node:os";import{createApiBaseClient as s}from"#package/client";import{getServerCredentials as i,saveServerCredentials as a}from"../services/index.js";let l={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},c=(e,t)=>`<!doctype html><html><head><meta charset="utf-8"><title>${e}</title></head><body style="font-family:system-ui,sans-serif;display:grid;place-items:center;height:100vh;margin:0"><main style="text-align:center"><h1>${e}</h1><p>${t.replace(/[&<>"']/g,e=>l[e]??e)}</p></main></body></html>`,d=(e,t,r,o)=>new Promise(n=>{e.destroyed?n():(e.once("close",n),e.writeHead(t,{...r,connection:"close"}).end(o))});export const startLoginCallbackListener=async e=>{let{state:t,studioUrl:r,customer:n}=e,s=(e,t)=>{let o=new URL(e,r);return o.searchParams.set("customer",n),t&&o.searchParams.set("name",t),o.toString()},i=null,a=!1,l=new Promise((e,t)=>{i={resolve:e,reject:t}}),m=o((e,r)=>{let o=new URL(e.url??"/","http://127.0.0.1"),n=o.searchParams.get("code"),l="access_denied"===o.searchParams.get("error");if("/callback"!==o.pathname)return void r.writeHead(404).end();if(o.searchParams.get("state")!==t||a||!n&&!l){d(r,400,{"content-type":"text/html"},c("Sign-in failed","This response does not belong to the waiting CLI. Run phoenix login again.")),a||i?.reject(Error("The sign-in response did not match this CLI session. Run `phoenix login` again."));return}if(a=!0,l||!n)return void d(r,302,{location:s("/builder/cli-login/denied",null)}).then(()=>{i?.reject(Error("The sign-in was denied in Studio. Run `phoenix login` again to sign in."))});let m=o.searchParams.get("name");i?.resolve({code:n,tokenName:m,finish:e=>e.signedIn?d(r,302,{location:s("/builder/cli-login/done",m)}):d(r,200,{"content-type":"text/html"},c("Sign-in failed",e.message))})}),h=await new Promise((e,t)=>{m.once("error",t),m.listen(0,"127.0.0.1",()=>{let r=m.address();null===r||"string"==typeof r?t(Error("The login callback listener did not get a port. Run `phoenix login` again.")):e(r.port)})}),u=setTimeout(()=>{i?.reject(Error("Nobody approved the sign-in within 5 minutes. Run `phoenix login` again."))},3e5);return{port:h,callback:l,close:()=>{clearTimeout(u),m.close()}}};let m=async(e,t)=>{try{let{error:r,response:o}=await s(e).DELETE("/auth/token",{headers:{authorization:`Bearer ${t}`,"content-type":null}});return r&&401!==o.status?r.message:null}catch(e){return e instanceof Error?e.message:String(e)}},h=async(e,t)=>{let{data:r,error:o}=await s(e.serverUrl).POST("/auth/token",{body:t});if(o||!r)throw Error(`The server did not accept the sign-in: ${o?.message??"no response"}`);if(r.customer.slug!==e.customer)throw await m(e.serverUrl,r.token),Error(`The sign-in was approved in workspace "${r.customer.slug}", not "${e.customer}". Check --region or --studioUrl and run \`phoenix login ${e.customer}\` again.`);let n=await i(e.serverUrl),l=await a(e.serverUrl,{token:r.token,userId:r.userId,customerSlug:r.customer.slug,customerName:r.customer.name,studioUrl:e.studioUrl,createdAt:new Date().toISOString()}),c=n?await m(e.serverUrl,n.token):null;return{customerName:r.customer.name,path:l,revokeError:c}};export const runLoginCommand=async(o,{logger:s})=>{let i=r(32).toString("base64url"),a=t("sha256").update(i).digest("base64url"),l=r(16).toString("base64url"),c=n(),d=`phoenix CLI on ${c}`,m=await startLoginCallbackListener({state:l,studioUrl:o.studioUrl,customer:o.customer});try{let t=new URL("/builder/cli-login",o.studioUrl);t.searchParams.set("customer",o.customer),t.searchParams.set("port",String(m.port)),t.searchParams.set("state",l),t.searchParams.set("challenge",a),t.searchParams.set("name",d),t.searchParams.set("host",c),t.searchParams.set("started",String(Date.now())),s.step(`Signing in to workspace "${o.customer}" on ${o.serverUrl}`),s.info(`Approve the CLI in your browser:
2
2
 
3
3
  ${t.toString()}
4
- `),o.open&&(t=>{let[r,o]="darwin"===process.platform?["open",[t]]:"win32"===process.platform?["rundll32",["url.dll,FileProtocolHandler",t]]:["xdg-open",[t]];e(r,o,{stdio:"ignore",detached:!0}).on("error",()=>void 0).unref()})(t.toString());let r=await m.code,{data:p,error:g}=await i(o.serverUrl).POST("/auth/token",{body:{code:r,codeVerifier:d,port:m.port,name:`phoenix CLI on ${n()}`}});if(g||!p)throw Error(`The server did not accept the sign-in: ${g?.message??"no response"}`);if(p.customer.slug!==o.customer)throw await c(o.serverUrl,p.token),Error(`The sign-in was approved in workspace "${p.customer.slug}", not "${o.customer}". Check --region or --studioUrl and run \`phoenix login ${o.customer}\` again.`);let w=await s(o.serverUrl),y=await a(o.serverUrl,{token:p.token,userId:p.userId,customerSlug:p.customer.slug,customerName:p.customer.name,studioUrl:o.studioUrl,createdAt:new Date().toISOString()}),f=w?await c(o.serverUrl,w.token):null;f&&l.warn(`The server did not revoke the token this sign-in replaces (${f}). It stays valid on the server. Contact Phoenix support to revoke it.`),l.success(`Signed in to ${p.customer.name}. The token is stored in ${y}; revoke it with phoenix logout.`)}finally{m.close()}};
4
+ `),o.open&&(t=>{let[r,o]="darwin"===process.platform?["open",[t]]:"win32"===process.platform?["rundll32",["url.dll,FileProtocolHandler",t]]:["xdg-open",[t]];e(r,o,{stdio:"ignore",detached:!0}).on("error",()=>void 0).unref()})(t.toString());let r=await m.callback;try{let e=await h(o,{code:r.code,codeVerifier:i,port:m.port,name:d});e.revokeError&&s.warn(`The server did not revoke the token this sign-in replaces (${e.revokeError}). It stays valid on the server. Contact Phoenix support to revoke it.`),await r.finish({signedIn:!0}),s.success(`Signed in to ${e.customerName}. The token is stored in ${e.path}; revoke it with phoenix logout.`)}catch(e){throw await r.finish({signedIn:!1,message:e instanceof Error?e.message:String(e)}),e}}finally{m.close()}};
@@ -1,2 +1,2 @@
1
- import{globby as e}from"globby";import{rmSync as r}from"node:fs";import{mkdir as o,writeFile as t}from"node:fs/promises";import{dirname as s,resolve as i}from"node:path";import{startEditorServer as a}from"../editor-server/index.js";import{ApplicationSpecStoryWatcher as n}from"../services/application-spec-story-watcher.js";import{STORY_DEV_MARKER_PATH as l,readActiveStoryDevMarker as c}from"../services/index.js";import{MockTemplateWatcher as d}from"../services/mock-template-watcher.js";import{PhoenixPubSub as f}from"../services/phoenix-pubsub.js";import{resolveGlobToDirectories as p}from"./resolve-story-directories.js";import{runStoryBuildCommand as g}from"./story-build.js";let m=async(r,o)=>{let t=o?i(process.cwd(),o):s(r),a=new Set([r,...(await e(`*/${l}`,{cwd:t,absolute:!0})).map(e=>s(s(e)))]);return(await Promise.all([...a].map(c))).find(e=>null!==e)??null},w=async(e,r)=>{let a=i(e,l),n={projectRoot:e,pid:process.pid,port:r};return await o(s(a),{recursive:!0}),await t(a,`${JSON.stringify(n)}
2
- `),a},u=async(e,o)=>{let t=await p(e.folder,e.baseDir),[s]=t,i=e.editorWsPort??3120;if(!s||1!==t.length)throw Error(`Story dev requires exactly one existing story folder, but "${e.folder}" resolved ${t.length}. Pass one concrete folder and check the base directory.`);let l=await m(s,e.baseDir);if(l)throw Error(`Story dev is already running for "${l.projectRoot}" (PID ${l.pid}) on port ${l.port}. Stop that process before starting another story.`);let c=await w(s,i),u=()=>r(c,{force:!0});process.once("exit",u);let y=new f,h=null,b=null,S=null,v=!1,$=async()=>{if(!v){for(let e of(v=!0,process.off("exit",u),[{name:"story source watcher",close:()=>S?.close()},{name:"mock-template watcher",close:()=>b?.close()},{name:"editor server",close:()=>h?.close()}]))try{await e.close()}catch(r){o.logger.warn(`Failed to close the story-dev ${e.name}: ${r instanceof Error?r.message:String(r)}. The process will continue shutting down.`)}r(c,{force:!0})}};try{return o.logger.step(`Building application-spec story in ${s}`),await g({folder:s,baseDir:e.baseDir},o),h=a({port:i,projectRoot:s,pubsub:y,logger:o.logger,storyMode:!0}),await h.ready,(b=new d({projectRoot:s,pubsub:y,logger:o.logger})).start(),(S=new n({projectRoot:s,pubsub:y,logger:o.logger})).start(),o.logger.success(`Story dev is running for ${s}`),o.logger.info(`Editor WebSocket: ws://localhost:${i}`),o.logger.info("Source changes update the editor without regenerating Storybook files."),{markerPath:c,close:$}}catch(e){throw await $(),e}};export const runStoryDevCommand=async(e,r)=>{let o;if(o=e.folder,/[*?[\]{}()!]/.test(o))throw Error(`Story dev accepts one concrete story folder, but "${e.folder}" contains glob syntax. Pass a folder name without wildcards.`);let t=await u(e,r),s=null,i=new Promise(e=>{s=e}),a=()=>s?.();process.once("SIGINT",a),process.once("SIGTERM",a),e.shutdownSignal?.addEventListener("abort",a,{once:!0}),e.shutdownSignal?.aborted&&a();try{await i}finally{process.off("SIGINT",a),process.off("SIGTERM",a),e.shutdownSignal?.removeEventListener("abort",a),await t.close()}};
1
+ import{globby as e}from"globby";import{rmSync as r}from"node:fs";import{mkdir as o,writeFile as t}from"node:fs/promises";import{dirname as s,resolve as i}from"node:path";import{startEditorServer as a}from"../editor-server/index.js";import{ApplicationSpecStoryWatcher as n}from"../services/application-spec-story-watcher.js";import{STORY_DEV_MARKER_PATH as l,readActiveStoryDevMarker as c}from"../services/index.js";import{MockTemplateWatcher as p}from"../services/mock-template-watcher.js";import{PhoenixApplication as d}from"../services/phoenix-application.js";import{PhoenixPubSub as f}from"../services/phoenix-pubsub.js";import{PhoenixStore as m}from"../services/phoenix-store.js";import{resolveGlobToDirectories as w}from"./resolve-story-directories.js";import{runStoryBuildCommand as g}from"./story-build.js";let u=async(r,o)=>{let t=o?i(process.cwd(),o):s(r),a=new Set([r,...(await e(`*/${l}`,{cwd:t,absolute:!0})).map(e=>s(s(e)))]);return(await Promise.all([...a].map(c))).find(e=>null!==e)??null},y=async(e,r)=>{let a=i(e,l),n={projectRoot:e,pid:process.pid,port:r};return await o(s(a),{recursive:!0}),await t(a,`${JSON.stringify(n)}
2
+ `),a},h=async(e,o)=>{let t=await w(e.folder,e.baseDir),[s]=t,i=e.editorWsPort??3120;if(!s||1!==t.length)throw Error(`Story dev requires exactly one existing story folder, but "${e.folder}" resolved ${t.length}. Pass one concrete folder and check the base directory.`);let l=await u(s,e.baseDir);if(l)throw Error(`Story dev is already running for "${l.projectRoot}" (PID ${l.pid}) on port ${l.port}. Stop that process before starting another story.`);let c=await y(s,i),h=()=>r(c,{force:!0});process.once("exit",h);let v=new f,b=null,S=null,$=null,x=!1,j=async()=>{if(!x){for(let e of(x=!0,process.off("exit",h),[{name:"story source watcher",close:()=>$?.close()},{name:"mock-template watcher",close:()=>S?.close()},{name:"editor server",close:()=>b?.close()}]))try{await e.close()}catch(r){o.logger.warn(`Failed to close the story-dev ${e.name}: ${r instanceof Error?r.message:String(r)}. The process will continue shutting down.`)}r(c,{force:!0})}};try{return o.logger.step(`Building application-spec story in ${s}`),await g({folder:s,baseDir:e.baseDir},o),b=a({port:i,projectRoot:s,application:new d({store:new m,pubsub:v,variantPreviews:void 0}),logger:o.logger,storyMode:!0}),await b.ready,(S=new p({projectRoot:s,pubsub:v,logger:o.logger})).start(),($=new n({projectRoot:s,pubsub:v,logger:o.logger})).start(),o.logger.success(`Story dev is running for ${s}`),o.logger.info(`Editor WebSocket: ws://localhost:${i}`),o.logger.info("Source changes update the editor without regenerating Storybook files."),{markerPath:c,close:j}}catch(e){throw await j(),e}};export const runStoryDevCommand=async(e,r)=>{let o;if(o=e.folder,/[*?[\]{}()!]/.test(o))throw Error(`Story dev accepts one concrete story folder, but "${e.folder}" contains glob syntax. Pass a folder name without wildcards.`);let t=await h(e,r),s=null,i=new Promise(e=>{s=e}),a=()=>s?.();process.once("SIGINT",a),process.once("SIGTERM",a),e.shutdownSignal?.addEventListener("abort",a,{once:!0}),e.shutdownSignal?.aborted&&a();try{await i}finally{process.off("SIGINT",a),process.off("SIGTERM",a),e.shutdownSignal?.removeEventListener("abort",a),await t.close()}};
@@ -0,0 +1,35 @@
1
+ import type { VariantPreviewOption } from '../services/phoenix-store.js';
2
+ import type { CommandContext } from './types.js';
3
+ export interface VariantsCommandProps {
4
+ /** Folder of the option set; only `close` works without one. */
5
+ readonly directory: string | undefined;
6
+ readonly title: string | undefined;
7
+ readonly description: string | undefined;
8
+ /** Seconds to wait for the answer. */
9
+ readonly timeout: number | undefined;
10
+ readonly keep: boolean | undefined;
11
+ readonly close: boolean | undefined;
12
+ readonly port: string;
13
+ }
14
+ /** One folder of options below `.phoenix/variants/`, as the editor is asked to show it. */
15
+ export interface VariantSet {
16
+ /** Absolute path of the folder; the command removes it once the builder has answered. */
17
+ readonly directory: string;
18
+ /** Absolute path of `.phoenix/variants/`, removed together with the last set in it. */
19
+ readonly variantsRoot: string;
20
+ readonly options: readonly VariantPreviewOption[];
21
+ }
22
+ /**
23
+ * Reads scripts and standalone HTML pages in file-name order. Other files are helpers the options share.
24
+ *
25
+ * @throws when the folder is not a variant set the dev server can show
26
+ */
27
+ export declare const readVariantSet: (props: {
28
+ readonly projectRoot: string;
29
+ readonly directory: string;
30
+ }) => VariantSet;
31
+ /**
32
+ * Shows the options of one `.phoenix/variants/<name>/` folder over the configurator of a running
33
+ * `phoenix dev`, waits for the builder to answer, prints the answer as JSON and removes the folder.
34
+ */
35
+ export declare const runVariantsCommand: (props: VariantsCommandProps, context: CommandContext) => Promise<void>;
@@ -0,0 +1 @@
1
+ import{createTRPCClient as e,createWSClient as t,wsLink as o}from"@trpc/client";import{existsSync as r,readFileSync as i,readdirSync as n,rmSync as a,statSync as s}from"fs";import{isAbsolute as l,join as c,relative as p,resolve as d,sep as h}from"path";import f from"ws";import{toPosixPath as w}from"../utils/path.js";let m=".phoenix",u="variants",v=".variant.js",g=".html",y={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},$=e=>{let t=e?.trim();return""===t?void 0:t},b=e=>$(e?.replace(/&(?:amp|lt|gt|quot|#39);/g,e=>y[e]??e)),C=(e,t)=>{let o=e.match(RegExp(`export\\s+const\\s+${t}\\s*=\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`))?.[2];return $(o?.replace(/\\(.)/g,"$1"))};export const readVariantSet=e=>{let t=d(e.projectRoot,m),o=c(t,u),a=d(e.projectRoot,e.directory),f=p(o,a),y=`${m}/${u}/<name>/`;if(""===f||".."===f||f.startsWith(`..${h}`)||l(f))throw Error(`Cannot preview ${e.directory}: the dev server only shows options from a folder of their own below ${m}/${u}/. Write the option files to ${y} and pass that folder`);if(!r(a)||!s(a).isDirectory())throw Error(`Cannot preview ${e.directory}: there is no such folder. Write one ${v} or ${g} file per option to ${y} first`);let $=n(a),E=Math.round(Math.max(0,...$.map(e=>s(c(a,e)).mtimeMs))),x=$.filter(e=>e.endsWith(v)||e.endsWith(g)).sort().map(e=>(e=>{let{webRoot:t,directory:o,name:r,version:n}=e,a=c(o,r),s=i(a,"utf8"),l=`/${w(p(t,a)).split("/").map(encodeURIComponent).join("/")}`,d=r.endsWith(v),h=r.slice(0,-(d?v:g).length),f=s.match(/<meta\b[^>]*\bname=(["'])description\1[^>]*>/i)?.[0];return{id:h,kind:d?"script":"page",label:(d?C(s,"title"):b(s.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1]))??h,description:(d?C(s,"description"):b(f?.match(/\bcontent=(["'])(.*?)\1/i)?.[2]))??"",url:`${l}?t=${n}`}})({webRoot:t,directory:a,name:e,version:E}));if(0===x.length)throw Error(`Cannot preview ${e.directory}: it holds no ${v} or ${g} file, so there is no option to show. Write one file per option; any other file is a helper the options share`);let R=x.find((e,t)=>x.findIndex(t=>t.id===e.id)!==t);if(R)throw Error(`Cannot preview ${e.directory}: two options are named "${R.id}", and the answer names an option by its file name without the suffix. Rename one of the files`);return{directory:a,variantsRoot:o,options:x}};let E=r=>{let i=t({url:`ws://localhost:${r}`,WebSocket:f});return{wsClient:i,client:e({links:[o({client:i})]})}},x=e=>{console.log(JSON.stringify(e,null,2))},R=async e=>{let{wsClient:t,client:o}=E(e);try{let{closed:e}=await o.closeVariantPreview.mutate();x({status:"closed",message:e?"The open preview was closed.":"No preview was open."})}finally{await t.close()}},S=async(e,t,o,i)=>{let{wsClient:s,client:l}=E(t.port);try{let s=await l.previewVariants.mutate({title:t.title??"Which option do you prefer?",description:t.description??"",variants:[...e.options],timeoutMs:o});if("waiting"===s.status)return void x({status:"waiting",message:"The preview is still open and nothing was picked yet. Run the same command again to keep waiting."});if("closed"===s.status)return void x({status:"closed",message:"The preview was closed before an answer was given. The option folder is kept."});await l.claimVariantChoice.mutate({requestId:s.requestId});let c=e.options.find(e=>e.id===s.choice);if(x({status:"chosen",choice:s.choice,label:c?.label??"Original"}),!t.keep)try{a(e.directory,{recursive:!0,force:!0}),r(e.variantsRoot)&&0===n(e.variantsRoot).length&&a(e.variantsRoot,{recursive:!0,force:!0})}catch(t){i.logger.warn(`Could not remove ${e.directory} after the answer: ${t instanceof Error?t.message:String(t)}. Remove the folder yourself`)}}finally{await s.close()}};export const runVariantsCommand=async(e,t)=>{let{logger:o}=t;try{if(e.close)return void await R(e.port);if(void 0===e.directory)throw Error(`Cannot preview without a folder: the options to show are read from it. Pass ${m}/${u}/<name>/, or --close to close the open preview`);let o=(e=>{let t=Math.round((e??540)*1e3);if(!Number.isFinite(t)||t<=0)throw Error(`Cannot wait for ${e} seconds: --timeout is how long the command waits for the answer. Pass a positive number of seconds`);if(t>0x7fffffff)throw Error(`Cannot wait for ${e} seconds: a wait is at most ${Math.floor(2147483.647)} seconds. Pass a smaller --timeout and run the command again while it answers "waiting"`);return t})(e.timeout),r=readVariantSet({projectRoot:process.cwd(),directory:e.directory});await S(r,e,o,t)}catch(e){o.error((e=>{let t;if(!(e instanceof Error))return`Variant preview failed: ${String(e)}`;let o=e.cause;return null!=o&&"object"==typeof o&&"code"in o&&"ECONNREFUSED"===o.code?"Dev server not running. Start with `phoenix dev`":"object"==typeof(t="data"in e?e.data:void 0)&&null!==t&&"code"in t&&"NOT_FOUND"===t.code?"Cannot preview: the dev server that is running has no variant previews, because it runs the legacy pipeline or an older SDK. Variant previews need `phoenix dev` of a project on the application-spec pipeline, started with this SDK version":e.message})(e)),process.exit(1)}};
@@ -1,8 +1,10 @@
1
1
  import { type LogEntry } from '../services/log-bus.js';
2
2
  import type { BrowserConsoleEvent, DataRequest, SceneRequest, ScreenshotRequest, StateRequest } from '../services/phoenix-pubsub.js';
3
+ import type { VariantPreviewRequest } from '../services/phoenix-store.js';
3
4
  import type { TunnelEvent } from '../services/webhook-tunnel-monitor.js';
5
+ import { type Context } from './trpc.js';
4
6
  export declare const commandsRouter: import("@trpc/server").TRPCBuiltRouter<{
5
- ctx: import("./trpc.js").Context;
7
+ ctx: Context;
6
8
  meta: object;
7
9
  errorShape: import("@trpc/server").TRPCDefaultErrorShape;
8
10
  transformer: false;
@@ -167,4 +169,69 @@ export declare const commandsRouter: import("@trpc/server").TRPCBuiltRouter<{
167
169
  output: void;
168
170
  meta: object;
169
171
  }>;
172
+ previewVariants: import("@trpc/server").TRPCMutationProcedure<{
173
+ input: {
174
+ title: string;
175
+ description: string;
176
+ variants: {
177
+ id: string;
178
+ kind: "page" | "script";
179
+ label: string;
180
+ description: string;
181
+ url: string;
182
+ }[];
183
+ timeoutMs: number;
184
+ };
185
+ output: import("../services/variant-preview-service.js").VariantPreviewOutcome;
186
+ meta: object;
187
+ }>;
188
+ onVariantPreview: import("@trpc/server/unstable-core-do-not-import").LegacyObservableSubscriptionProcedure<{
189
+ input: void;
190
+ output: VariantPreviewRequest | null;
191
+ meta: object;
192
+ }>;
193
+ getVariantBaseline: import("@trpc/server").TRPCQueryProcedure<{
194
+ input: {
195
+ requestId: string;
196
+ };
197
+ output: {
198
+ readonly files: readonly import("../services/variant-file-session.js").VariantFileEdit[];
199
+ readonly choice: string | null;
200
+ };
201
+ meta: object;
202
+ }>;
203
+ applyVariantFiles: import("@trpc/server").TRPCMutationProcedure<{
204
+ input: {
205
+ requestId: string;
206
+ choice: string | null;
207
+ files: {
208
+ fileName: string;
209
+ content: string | null;
210
+ }[];
211
+ };
212
+ output: void;
213
+ meta: object;
214
+ }>;
215
+ submitVariantChoice: import("@trpc/server").TRPCMutationProcedure<{
216
+ input: {
217
+ requestId: string;
218
+ choice: string | null;
219
+ };
220
+ output: void;
221
+ meta: object;
222
+ }>;
223
+ closeVariantPreview: import("@trpc/server").TRPCMutationProcedure<{
224
+ input: void;
225
+ output: {
226
+ readonly closed: boolean;
227
+ };
228
+ meta: object;
229
+ }>;
230
+ claimVariantChoice: import("@trpc/server").TRPCMutationProcedure<{
231
+ input: {
232
+ requestId: string;
233
+ };
234
+ output: void;
235
+ meta: object;
236
+ }>;
170
237
  }>>;
@@ -1 +1 @@
1
- import{observable as e}from"@trpc/server/observable";import{writeFile as t}from"fs/promises";import{resolve as r}from"path";import{filter as s,firstValueFrom as o,timeout as n}from"rxjs";import{z as u}from"zod";import{LOG_STREAMS as i}from"../services/log-bus.js";import{publicProcedure as a,router as b}from"./trpc.js";let c=u.enum(["all",...i]);export const commandsRouter=b({getLogs:a.input(u.object({stream:c,beforeSeq:u.number().int().positive().optional(),limit:u.number().int().positive().max(500).default(200)})).query(({input:e,ctx:t})=>{if(!t.logBus)return{entries:[],hasMore:!1,counts:null};let r=t.logBus.query(e);return{entries:r.entries,hasMore:r.hasMore,counts:t.logBus.allCounts()}}),onLog:a.subscription(({ctx:t})=>e(e=>t.logBus?t.logBus.subscribe(t=>{e.next(t)}):()=>{})),getTunnelState:a.query(({ctx:e})=>e.tunnelMonitor?{state:e.tunnelMonitor.state(),entries:e.tunnelMonitor.summaries()}:{state:null,entries:[]}),getTunnelRequest:a.input(u.object({seq:u.number().int().positive()})).query(({ctx:e,input:t})=>e.tunnelMonitor?.entry(t.seq)??null),onTunnelEvent:a.subscription(({ctx:t})=>e(e=>t.tunnelMonitor?t.tunnelMonitor.subscribe(t=>{e.next(t)}):()=>{})),takeScreenshot:a.input(u.object({width:u.number().int().positive(),height:u.number().int().positive(),fileFormat:u.enum(["PNG","JPEG"]),output:u.string()})).mutation(async({input:e,ctx:u})=>{let i;if(0===u.pubsub.screenshotRequest$.observers.length)throw Error("No editor connected. Open the configurator in a browser");let a=crypto.randomUUID(),b=o(u.pubsub.screenshotResult$.pipe(s(e=>e.requestId===a),n(3e4)));u.pubsub.screenshotRequest$.next({requestId:a,width:e.width,height:e.height,fileFormat:e.fileFormat});try{i=await b}catch{throw Error("Screenshot timed out. Ensure configurator is fully loaded")}let c=r(e.output),l=Buffer.from(i.imageBase64,"base64");try{await t(c,l)}catch(e){throw Error(`Failed to save screenshot: ${e instanceof Error?e.message:String(e)}`)}return{filePath:c}}),onScreenshotRequest:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.screenshotRequest$.subscribe({next:r=>{t.logger.debug(`Emitting screenshot request to subscriber: ${r.requestId}`),e.next(r)},error:r=>{t.logger.error(`Screenshot request subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{t.logger.debug("Screenshot request subscription unsubscribed"),r.unsubscribe()}})),submitScreenshot:a.input(u.object({requestId:u.string(),imageBase64:u.string(),fileFormat:u.enum(["PNG","JPEG"])})).mutation(({input:e,ctx:t})=>{t.logger.debug(`Received screenshot result for request: ${e.requestId}`),t.pubsub.screenshotResult$.next({requestId:e.requestId,imageBase64:e.imageBase64,fileFormat:e.fileFormat})}),reportBrowserConsole:a.input(u.object({level:u.enum(["error","warn","info"]),message:u.string(),source:u.string().optional(),timestamp:u.string().optional()})).mutation(({input:e,ctx:t})=>{if(!t.logBus){let r=e.source?`browser:${e.source}`:"browser";t.logger.warn(`[${r}] ${e.message}`)}t.pubsub.browserConsole$.next({level:e.level,message:e.message,source:e.source,timestamp:e.timestamp})}),onBrowserConsole:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.browserConsole$.subscribe({next:t=>{e.next(t)},error:r=>{t.logger.error(`Browser console subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{r.unsubscribe()}})),getEditorState:a.input(u.object({sections:u.array(u.enum(["entities","navigation","validation"])).optional()})).mutation(async({input:e,ctx:t})=>{let r;if(0===t.pubsub.stateRequest$.observers.length)throw Error("No editor connected. Open the configurator in a browser");let u=crypto.randomUUID(),i=e.sections??["entities","navigation","validation"],a=o(t.pubsub.stateResult$.pipe(s(e=>e.requestId===u),n(1e4)));t.pubsub.stateRequest$.next({requestId:u,sections:i});try{r=await a}catch{throw Error("State request timed out. Ensure configurator is fully loaded")}return r.state}),onStateRequest:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.stateRequest$.subscribe({next:r=>{t.logger.debug(`Emitting state request to subscriber: ${r.requestId}`),e.next(r)},error:r=>{t.logger.error(`State request subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{t.logger.debug("State request subscription unsubscribed"),r.unsubscribe()}})),submitEditorState:a.input(u.object({requestId:u.string(),state:u.object({lifecycle:u.object({domainLoaded:u.boolean(),domainContextReady:u.boolean(),configuratorReady:u.boolean(),sessionAuthenticated:u.boolean(),editorMode:u.boolean()}),entities:u.array(u.record(u.unknown())).nullable(),navigation:u.record(u.unknown()).nullable(),validation:u.record(u.unknown()).nullable()})})).mutation(({input:e,ctx:t})=>{t.logger.debug(`Received editor state for request: ${e.requestId}`),t.pubsub.stateResult$.next({requestId:e.requestId,state:e.state})}),getEditorData:a.mutation(async({ctx:e})=>{let t;if(0===e.pubsub.dataRequest$.observers.length)throw Error("No editor connected. Open the configurator in a browser");let r=crypto.randomUUID(),u=o(e.pubsub.dataResult$.pipe(s(e=>e.requestId===r),n(1e4)));e.pubsub.dataRequest$.next({requestId:r});try{t=await u}catch{throw Error("Data request timed out. Ensure configurator is fully loaded")}return t.data}),onDataRequest:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.dataRequest$.subscribe({next:r=>{t.logger.debug(`Emitting data request to subscriber: ${r.requestId}`),e.next(r)},error:r=>{t.logger.error(`Data request subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{t.logger.debug("Data request subscription unsubscribed"),r.unsubscribe()}})),submitEditorData:a.input(u.object({requestId:u.string(),data:u.object({publishedData:u.record(u.unknown()).nullable(),frontendData:u.record(u.unknown()).nullable(),backendData:u.record(u.unknown()).nullable(),sessionData:u.record(u.unknown()).nullable(),accessData:u.record(u.unknown()).nullable(),webComponentProperties:u.record(u.unknown()).nullable()})})).mutation(({input:e,ctx:t})=>{t.logger.debug(`Received editor data for request: ${e.requestId}`),t.pubsub.dataResult$.next({requestId:e.requestId,data:e.data})}),getEditorScene:a.mutation(async({ctx:e})=>{let t;if(0===e.pubsub.sceneRequest$.observers.length)throw Error("No editor connected. Open the configurator in a browser");let r=crypto.randomUUID(),u=o(e.pubsub.sceneResult$.pipe(s(e=>e.requestId===r),n(1e4)));e.pubsub.sceneRequest$.next({requestId:r});try{t=await u}catch{throw Error("Scene request timed out. Ensure configurator is fully loaded")}return t.scene}),onSceneRequest:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.sceneRequest$.subscribe({next:r=>{t.logger.debug(`Emitting scene request to subscriber: ${r.requestId}`),e.next(r)},error:r=>{t.logger.error(`Scene request subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{t.logger.debug("Scene request subscription unsubscribed"),r.unsubscribe()}})),submitEditorScene:a.input(u.object({requestId:u.string(),scene:u.record(u.unknown()).nullable()})).mutation(({input:e,ctx:t})=>{t.logger.debug(`Received editor scene for request: ${e.requestId}`),t.pubsub.sceneResult$.next({requestId:e.requestId,scene:e.scene})})});
1
+ import{observable as e}from"@trpc/server/observable";import{writeFile as t}from"fs/promises";import{resolve as r}from"path";import{filter as s,firstValueFrom as n,timeout as o}from"rxjs";import{z as i}from"zod";import{LOG_STREAMS as u}from"../services/log-bus.js";import{publicProcedure as a,router as l}from"./trpc.js";let b=i.enum(["all",...u]),c=e=>{if(!e.variantPreviews)throw Error("Cannot preview variants: this session cannot rewrite project files, because it is not `phoenix dev`. Run `phoenix dev` in the project and try again");return e.variantPreviews};export const commandsRouter=l({getLogs:a.input(i.object({stream:b,beforeSeq:i.number().int().positive().optional(),limit:i.number().int().positive().max(500).default(200)})).query(({input:e,ctx:t})=>{if(!t.logBus)return{entries:[],hasMore:!1,counts:null};let r=t.logBus.query(e);return{entries:r.entries,hasMore:r.hasMore,counts:t.logBus.allCounts()}}),onLog:a.subscription(({ctx:t})=>e(e=>t.logBus?t.logBus.subscribe(t=>{e.next(t)}):()=>{})),getTunnelState:a.query(({ctx:e})=>e.tunnelMonitor?{state:e.tunnelMonitor.state(),entries:e.tunnelMonitor.summaries()}:{state:null,entries:[]}),getTunnelRequest:a.input(i.object({seq:i.number().int().positive()})).query(({ctx:e,input:t})=>e.tunnelMonitor?.entry(t.seq)??null),onTunnelEvent:a.subscription(({ctx:t})=>e(e=>t.tunnelMonitor?t.tunnelMonitor.subscribe(t=>{e.next(t)}):()=>{})),takeScreenshot:a.input(i.object({width:i.number().int().positive(),height:i.number().int().positive(),fileFormat:i.enum(["PNG","JPEG"]),output:i.string()})).mutation(async({input:e,ctx:i})=>{let u;if(0===i.pubsub.screenshotRequest$.observers.length)throw Error("No editor connected. Open the configurator in a browser");let a=crypto.randomUUID(),l=n(i.pubsub.screenshotResult$.pipe(s(e=>e.requestId===a),o(3e4)));i.pubsub.screenshotRequest$.next({requestId:a,width:e.width,height:e.height,fileFormat:e.fileFormat});try{u=await l}catch{throw Error("Screenshot timed out. Ensure configurator is fully loaded")}let b=r(e.output),c=Buffer.from(u.imageBase64,"base64");try{await t(b,c)}catch(e){throw Error(`Failed to save screenshot: ${e instanceof Error?e.message:String(e)}`)}return{filePath:b}}),onScreenshotRequest:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.screenshotRequest$.subscribe({next:r=>{t.logger.debug(`Emitting screenshot request to subscriber: ${r.requestId}`),e.next(r)},error:r=>{t.logger.error(`Screenshot request subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{t.logger.debug("Screenshot request subscription unsubscribed"),r.unsubscribe()}})),submitScreenshot:a.input(i.object({requestId:i.string(),imageBase64:i.string(),fileFormat:i.enum(["PNG","JPEG"])})).mutation(({input:e,ctx:t})=>{t.logger.debug(`Received screenshot result for request: ${e.requestId}`),t.pubsub.screenshotResult$.next({requestId:e.requestId,imageBase64:e.imageBase64,fileFormat:e.fileFormat})}),reportBrowserConsole:a.input(i.object({level:i.enum(["error","warn","info"]),message:i.string(),source:i.string().optional(),timestamp:i.string().optional()})).mutation(({input:e,ctx:t})=>{if(!t.logBus){let r=e.source?`browser:${e.source}`:"browser";t.logger.warn(`[${r}] ${e.message}`)}t.pubsub.browserConsole$.next({level:e.level,message:e.message,source:e.source,timestamp:e.timestamp})}),onBrowserConsole:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.browserConsole$.subscribe({next:t=>{e.next(t)},error:r=>{t.logger.error(`Browser console subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{r.unsubscribe()}})),getEditorState:a.input(i.object({sections:i.array(i.enum(["entities","navigation","validation"])).optional()})).mutation(async({input:e,ctx:t})=>{let r;if(0===t.pubsub.stateRequest$.observers.length)throw Error("No editor connected. Open the configurator in a browser");let i=crypto.randomUUID(),u=e.sections??["entities","navigation","validation"],a=n(t.pubsub.stateResult$.pipe(s(e=>e.requestId===i),o(1e4)));t.pubsub.stateRequest$.next({requestId:i,sections:u});try{r=await a}catch{throw Error("State request timed out. Ensure configurator is fully loaded")}return r.state}),onStateRequest:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.stateRequest$.subscribe({next:r=>{t.logger.debug(`Emitting state request to subscriber: ${r.requestId}`),e.next(r)},error:r=>{t.logger.error(`State request subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{t.logger.debug("State request subscription unsubscribed"),r.unsubscribe()}})),submitEditorState:a.input(i.object({requestId:i.string(),state:i.object({lifecycle:i.object({domainLoaded:i.boolean(),domainContextReady:i.boolean(),configuratorReady:i.boolean(),sessionAuthenticated:i.boolean(),editorMode:i.boolean()}),entities:i.array(i.record(i.unknown())).nullable(),navigation:i.record(i.unknown()).nullable(),validation:i.record(i.unknown()).nullable()})})).mutation(({input:e,ctx:t})=>{t.logger.debug(`Received editor state for request: ${e.requestId}`),t.pubsub.stateResult$.next({requestId:e.requestId,state:e.state})}),getEditorData:a.mutation(async({ctx:e})=>{let t;if(0===e.pubsub.dataRequest$.observers.length)throw Error("No editor connected. Open the configurator in a browser");let r=crypto.randomUUID(),i=n(e.pubsub.dataResult$.pipe(s(e=>e.requestId===r),o(1e4)));e.pubsub.dataRequest$.next({requestId:r});try{t=await i}catch{throw Error("Data request timed out. Ensure configurator is fully loaded")}return t.data}),onDataRequest:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.dataRequest$.subscribe({next:r=>{t.logger.debug(`Emitting data request to subscriber: ${r.requestId}`),e.next(r)},error:r=>{t.logger.error(`Data request subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{t.logger.debug("Data request subscription unsubscribed"),r.unsubscribe()}})),submitEditorData:a.input(i.object({requestId:i.string(),data:i.object({publishedData:i.record(i.unknown()).nullable(),frontendData:i.record(i.unknown()).nullable(),backendData:i.record(i.unknown()).nullable(),sessionData:i.record(i.unknown()).nullable(),accessData:i.record(i.unknown()).nullable(),webComponentProperties:i.record(i.unknown()).nullable()})})).mutation(({input:e,ctx:t})=>{t.logger.debug(`Received editor data for request: ${e.requestId}`),t.pubsub.dataResult$.next({requestId:e.requestId,data:e.data})}),getEditorScene:a.mutation(async({ctx:e})=>{let t;if(0===e.pubsub.sceneRequest$.observers.length)throw Error("No editor connected. Open the configurator in a browser");let r=crypto.randomUUID(),i=n(e.pubsub.sceneResult$.pipe(s(e=>e.requestId===r),o(1e4)));e.pubsub.sceneRequest$.next({requestId:r});try{t=await i}catch{throw Error("Scene request timed out. Ensure configurator is fully loaded")}return t.scene}),onSceneRequest:a.subscription(({ctx:t})=>e(e=>{let r=t.pubsub.sceneRequest$.subscribe({next:r=>{t.logger.debug(`Emitting scene request to subscriber: ${r.requestId}`),e.next(r)},error:r=>{t.logger.error(`Scene request subject error: ${r instanceof Error?r.message:String(r)}`),e.error(r)}});return()=>{t.logger.debug("Scene request subscription unsubscribed"),r.unsubscribe()}})),submitEditorScene:a.input(i.object({requestId:i.string(),scene:i.record(i.unknown()).nullable()})).mutation(({input:e,ctx:t})=>{t.logger.debug(`Received editor scene for request: ${e.requestId}`),t.pubsub.sceneResult$.next({requestId:e.requestId,scene:e.scene})}),previewVariants:a.input(i.object({title:i.string(),description:i.string(),variants:i.array(i.object({id:i.string(),kind:i.enum(["script","page"]),label:i.string(),description:i.string(),url:i.string().refine(e=>{try{let t=decodeURIComponent(new URL(e,"http://variant.invalid").pathname);return e.startsWith("/variants/")&&t.startsWith("/variants/")&&!t.includes("\\")&&!t.split("/").some(e=>"."===e||".."===e)}catch{return!1}},"Option URLs must stay below /variants/; use a file from the variant set")})).min(1),timeoutMs:i.number().int().positive().max(0x7fffffff)})).mutation(({input:e,ctx:t})=>c(t).open(e)),onVariantPreview:a.subscription(({ctx:t})=>e(e=>{let r=t.variantPreviews;if(!r)return e.next(null),()=>void 0;let s=r.request$.subscribe(t=>{e.next(t)});return()=>{s.unsubscribe()}})),getVariantBaseline:a.input(i.object({requestId:i.string()})).query(({input:e,ctx:t})=>c(t).getBaseline(e.requestId)),applyVariantFiles:a.input(i.object({requestId:i.string(),choice:i.string().nullable(),files:i.array(i.object({fileName:i.string(),content:i.string().nullable()}))})).mutation(({input:e,ctx:t})=>c(t).applyFiles(e)),submitVariantChoice:a.input(i.object({requestId:i.string(),choice:i.string().nullable()})).mutation(({input:e,ctx:t})=>c(t).submit(e)),closeVariantPreview:a.mutation(({ctx:e})=>e.variantPreviews?.close()??Promise.resolve({closed:!1})),claimVariantChoice:a.input(i.object({requestId:i.string()})).mutation(({input:e,ctx:t})=>{t.variantPreviews?.claim(e.requestId)})});
@@ -165,6 +165,71 @@ export declare const appRouter: import("@trpc/server").TRPCBuiltRouter<{
165
165
  output: void;
166
166
  meta: object;
167
167
  }>;
168
+ previewVariants: import("@trpc/server").TRPCMutationProcedure<{
169
+ input: {
170
+ title: string;
171
+ description: string;
172
+ variants: {
173
+ id: string;
174
+ kind: "page" | "script";
175
+ label: string;
176
+ description: string;
177
+ url: string;
178
+ }[];
179
+ timeoutMs: number;
180
+ };
181
+ output: import("../services/variant-preview-service.js").VariantPreviewOutcome;
182
+ meta: object;
183
+ }>;
184
+ onVariantPreview: import("@trpc/server/unstable-core-do-not-import").LegacyObservableSubscriptionProcedure<{
185
+ input: void;
186
+ output: import("./protocol.js").VariantPreviewRequest | null;
187
+ meta: object;
188
+ }>;
189
+ getVariantBaseline: import("@trpc/server").TRPCQueryProcedure<{
190
+ input: {
191
+ requestId: string;
192
+ };
193
+ output: {
194
+ readonly files: readonly import("../services/variant-file-session.js").VariantFileEdit[];
195
+ readonly choice: string | null;
196
+ };
197
+ meta: object;
198
+ }>;
199
+ applyVariantFiles: import("@trpc/server").TRPCMutationProcedure<{
200
+ input: {
201
+ requestId: string;
202
+ choice: string | null;
203
+ files: {
204
+ fileName: string;
205
+ content: string | null;
206
+ }[];
207
+ };
208
+ output: void;
209
+ meta: object;
210
+ }>;
211
+ submitVariantChoice: import("@trpc/server").TRPCMutationProcedure<{
212
+ input: {
213
+ requestId: string;
214
+ choice: string | null;
215
+ };
216
+ output: void;
217
+ meta: object;
218
+ }>;
219
+ closeVariantPreview: import("@trpc/server").TRPCMutationProcedure<{
220
+ input: void;
221
+ output: {
222
+ readonly closed: boolean;
223
+ };
224
+ meta: object;
225
+ }>;
226
+ claimVariantChoice: import("@trpc/server").TRPCMutationProcedure<{
227
+ input: {
228
+ requestId: string;
229
+ };
230
+ output: void;
231
+ meta: object;
232
+ }>;
168
233
  }> & import("@trpc/server").TRPCDecorateCreateRouterOptions<{
169
234
  saveMock: import("@trpc/server").TRPCMutationProcedure<{
170
235
  input: {
@@ -1,11 +1,11 @@
1
1
  import type { LogBus } from '../services/log-bus.js';
2
- import type { PhoenixPubSub } from '../services/phoenix-pubsub.js';
2
+ import type { PhoenixApplication } from '../services/phoenix-application.js';
3
3
  import type { WebhookTunnelMonitor } from '../services/webhook-tunnel-monitor.js';
4
4
  import type { Logger } from '../utils/index.js';
5
5
  export interface EditorServerOptions {
6
6
  readonly port: number;
7
7
  readonly projectRoot: string;
8
- readonly pubsub: PhoenixPubSub;
8
+ readonly application: PhoenixApplication;
9
9
  readonly logger: Logger;
10
10
  readonly debug?: boolean;
11
11
  /** Bound to this dev session; absent for offline and story sessions. */
@@ -14,7 +14,7 @@ export interface EditorServerOptions {
14
14
  readonly logBus?: LogBus;
15
15
  readonly tunnelMonitor?: WebhookTunnelMonitor;
16
16
  }
17
- export declare const startEditorServer: ({ port, projectRoot, pubsub, logger, prepareDeployment, storyMode, logBus, tunnelMonitor, }: EditorServerOptions) => {
17
+ export declare const startEditorServer: ({ port, projectRoot, application, logger, prepareDeployment, storyMode, logBus, tunnelMonitor, }: EditorServerOptions) => {
18
18
  ready: Promise<void>;
19
19
  close: () => Promise<void>;
20
20
  };
@@ -1 +1 @@
1
- import{applyWSSHandler as e}from"@trpc/server/adapters/ws";import{WebSocketServer as o}from"ws";import{appRouter as r}from"./editor-router.js";export const startEditorServer=({port:n,projectRoot:t,pubsub:i,logger:s,prepareDeployment:c,storyMode:l,logBus:a,tunnelMonitor:f})=>{let m=new o({port:n}),d=e({wss:m,router:r,createContext:()=>({projectRoot:t,pubsub:i,logger:s,prepareDeployment:c,storyMode:l,logBus:a,tunnelMonitor:f})});m.on("connection",(e,o)=>{let r=o.headers.origin??"unknown";s.info(`WS connected (clients: ${m.clients.size}, origin: ${r})`),e.on("error",e=>{s.warn(`WS error: ${e.message}`)}),e.once("close",(e,o)=>{s.info(`WS disconnected (clients: ${m.clients.size}, code: ${e}, reason: ${o.toString()||"none"})`)})}),m.on("error",e=>{s.error(`WebSocket server error: ${e.message}`)});let S=new Promise((e,o)=>{let r=()=>{m.off("error",t),s.info(`WebSocket Server listening on ws://localhost:${n}`),e()},t=e=>{m.off("listening",r),o(e)};m.once("listening",r),m.once("error",t)}),g=null;return{ready:S,close:()=>g||(s.info("Shutting down WebSocket server"),d.broadcastReconnectNotification(),g=new Promise((e,o)=>{let r=setTimeout(()=>{for(let e of m.clients)e.terminate()},3e3);m.close(n=>{clearTimeout(r),n?o(n):e()})}))}};
1
+ import{applyWSSHandler as e}from"@trpc/server/adapters/ws";import{WebSocketServer as r}from"ws";import{appRouter as o}from"./editor-router.js";export const startEditorServer=({port:n,projectRoot:t,application:i,logger:s,prepareDeployment:c,storyMode:l,logBus:a,tunnelMonitor:f})=>{let m=new r({port:n}),u=e({wss:m,router:o,createContext:()=>({projectRoot:t,pubsub:i.pubsub,variantPreviews:i.variantPreviews,logger:s,prepareDeployment:c,storyMode:l,logBus:a,tunnelMonitor:f})});m.on("connection",(e,r)=>{let o=r.headers.origin??"unknown";s.info(`WS connected (clients: ${m.clients.size}, origin: ${o})`),e.on("error",e=>{s.warn(`WS error: ${e.message}`)}),e.once("close",(e,r)=>{s.info(`WS disconnected (clients: ${m.clients.size}, code: ${e}, reason: ${r.toString()||"none"})`)})}),m.on("error",e=>{s.error(`WebSocket server error: ${e.message}`)});let w=new Promise((e,r)=>{let o=()=>{m.off("error",t),s.info(`WebSocket Server listening on ws://localhost:${n}`),e()},t=e=>{m.off("listening",o),r(e)};m.once("listening",o),m.once("error",t)}),d=null;return{ready:w,close:()=>d||(s.info("Shutting down WebSocket server"),u.broadcastReconnectNotification(),d=new Promise((e,r)=>{let o=setTimeout(()=>{for(let e of m.clients)e.terminate()},3e3);m.close(n=>{clearTimeout(o),n?r(n):e()})}))}};
@@ -1,3 +1,4 @@
1
1
  /** Internal browser/editor protocol. This entry has no runtime package mapping. */
2
2
  export type { AppRouter } from './editor-router.js';
3
3
  export type { DataRequest, EditorContextData, SceneRequest, EditorLifecycleStatus, StateRequest, ScreenshotRequest, } from '../services/phoenix-pubsub.js';
4
+ export type { VariantPreviewOption, VariantPreviewRequest } from '../services/phoenix-store.js';
@@ -1 +1 @@
1
- import{TRPCError as e}from"@trpc/server";import{observable as o}from"@trpc/server/observable";import{writeFile as t}from"fs/promises";import{join as r}from"path";import{z as i}from"zod";import{readApplicationFiles as p}from"../application-spec/index.js";import{exists as s}from"../utils/index.js";import{publicProcedure as n,router as a}from"./trpc.js";export const specRouter=a({getEditorConfig:n.query(()=>({specSync:!0})),prepareDeployment:n.mutation(async({ctx:o})=>{if(o.storyMode)throw new e({code:"BAD_REQUEST",message:"Deployment preparation is disabled in Storybook story mode."});if(!o.prepareDeployment)throw new e({code:"BAD_REQUEST",message:"Deployment preparation requires a deployment configuration outside story mode."});await o.prepareDeployment()}),requestSpecFiles:n.mutation(async({ctx:e})=>{let o=e.storyMode?await p({projectRoot:e.projectRoot,envs:{}}):await p();e.pubsub.specFile$.next({rawProjectFiles:o,projectRoot:e.projectRoot})}),save:n.input(i.array(i.object({fileName:i.string(),content:i.string()}))).mutation(async({ctx:e,input:o})=>{for(let i of o){let o=r(e.projectRoot,i.fileName),p=r(e.projectRoot,i.fileName.split("/").slice(0,-1).join("/"));await s(p)&&await t(o,i.content)}}),onSpecChange:n.subscription(({ctx:e})=>o(o=>{let t=e.pubsub.specFile$.subscribe(e=>{o.next(e)});return()=>{t.unsubscribe()}}))});
1
+ import{TRPCError as e}from"@trpc/server";import{observable as o}from"@trpc/server/observable";import{writeFile as t}from"fs/promises";import{join as r}from"path";import{z as i}from"zod";import{readApplicationFiles as s}from"../application-spec/index.js";import{exists as p}from"../utils/index.js";import{publicProcedure as a,router as n}from"./trpc.js";export const specRouter=n({getEditorConfig:a.query(()=>({specSync:!0})),prepareDeployment:a.mutation(async({ctx:o})=>{if(o.variantPreviews?.isOpen)throw new e({code:"BAD_REQUEST",message:"Deployment preparation is disabled during variant previews. Close the preview first."});if(o.storyMode)throw new e({code:"BAD_REQUEST",message:"Deployment preparation is disabled in Storybook story mode."});if(!o.prepareDeployment)throw new e({code:"BAD_REQUEST",message:"Deployment preparation requires a deployment configuration outside story mode."});await o.prepareDeployment()}),requestSpecFiles:a.mutation(async({ctx:e})=>{let o=e.storyMode?await s({projectRoot:e.projectRoot,envs:{}}):await s();e.pubsub.specFile$.next({rawProjectFiles:o,projectRoot:e.projectRoot})}),save:a.input(i.array(i.object({fileName:i.string(),content:i.string()}))).mutation(async({ctx:o,input:i})=>{if(o.variantPreviews?.isOpen)throw new e({code:"BAD_REQUEST",message:"Close the variant preview before editing source files."});for(let e of i){let i=r(o.projectRoot,e.fileName),s=r(o.projectRoot,e.fileName.split("/").slice(0,-1).join("/"));await p(s)&&await t(i,e.content)}}),onSpecChange:a.subscription(({ctx:e})=>o(o=>{let t=e.pubsub.specFile$.subscribe(e=>{o.next(e)});return()=>{t.unsubscribe()}}))});
@@ -1,11 +1,14 @@
1
1
  import type { LogBus } from '../services/log-bus.js';
2
2
  import type { PhoenixPubSub } from '../services/phoenix-pubsub.js';
3
+ import type { VariantPreviewService } from '../services/variant-preview-service.js';
3
4
  import type { WebhookTunnelMonitor } from '../services/webhook-tunnel-monitor.js';
4
5
  import type { Logger } from '../utils/index.js';
5
6
  export type Context = {
6
7
  readonly projectRoot: string;
7
8
  readonly pubsub: PhoenixPubSub;
8
9
  readonly logger: Logger;
10
+ /** The session's variant comparison; absent where project files cannot be rewritten, such as story-dev. */
11
+ readonly variantPreviews: VariantPreviewService | undefined;
9
12
  /** Bound to this dev session; absent for offline and story sessions. */
10
13
  readonly prepareDeployment?: () => Promise<void>;
11
14
  readonly storyMode?: boolean;
@@ -1,9 +1,9 @@
1
1
  import { type ViteDevServer } from 'vite';
2
2
  import type { Logger } from '../utils/index.js';
3
3
  import type { PhoenixPubSub } from './phoenix-pubsub.js';
4
+ import type { VariantFileEdit } from './variant-file-session.js';
4
5
  /** Configuration for {@link ApplicationSpecProjectWatcher}. */
5
6
  export interface ApplicationSpecProjectWatcherConfig {
6
- readonly viteServer: ViteDevServer;
7
7
  readonly pubsub: PhoenixPubSub;
8
8
  readonly logger: Logger;
9
9
  readonly onRebuilt?: () => void;
@@ -42,8 +42,19 @@ export declare class ApplicationSpecProjectWatcher {
42
42
  private readonly builder;
43
43
  private readonly useServer;
44
44
  private isShuttingDown;
45
+ private suspended;
46
+ private readonly heldChanges;
45
47
  constructor(config: ApplicationSpecProjectWatcherConfig);
46
- start(): void;
48
+ start(viteServer: ViteDevServer): void;
49
+ /** Rebuilds a batch a variant comparison wrote, at once and without the server work of a source change. */
50
+ applyVariantFiles(files: readonly VariantFileEdit[]): void;
51
+ /**
52
+ * Holds source changes back until `resume`: a variant comparison rewrites files and rebuilds them itself,
53
+ * and a rebuild from the watcher would repeat that with the server work on top.
54
+ */
55
+ suspend(): void;
56
+ /** Rebuilds once for everything that changed while suspended, so no edit made meanwhile is lost. */
57
+ resume(): void;
47
58
  close(): Promise<void>;
48
59
  private setupFileWatcher;
49
60
  private setupRebuildSubscription;
@@ -1,4 +1,4 @@
1
- import{resolve as e}from"path";import t from"promise-queue";import{Subject as i,buffer as s,debounceTime as r}from"rxjs";import{createServer as o,normalizePath as n}from"vite";import{watch as l}from"#package/watch";import{ApplicationSpecBuilder as c}from"../application-spec/application-spec-builder.js";import{logDiagnostics as a}from"../application-spec/metrics/index.js";import{syncTemplateFiles as h}from"../application-spec/template-files.js";import{buildWebhooks as u}from"../webhooks/index.js";import{getViteDevConfig as p}from"./vite-config.js";let g=["spec/**/*.{yaml,yml}","src/**/*.{ts,tsx,yaml,yml,json,html,css}","templates/*.html",".env",".env.generated"],b=["src/locales/**/*.{ts,tsx}",".phoenix/**"];export class ApplicationSpecProjectWatcher{watcher=null;subscription=null;rebuildQueue=new t(1,1/0);changeSubject$=new i;viteServer;pubsub;logger;onRebuilt;onViteServerChange;builder;useServer;isShuttingDown=!1;constructor(e){this.viteServer=e.viteServer,this.pubsub=e.pubsub,this.logger=e.logger,this.onRebuilt=e.onRebuilt,this.onViteServerChange=e.onViteServerChange,this.builder=new c({logger:e.logger,sdkVersion:e.sdkVersion,projectSlug:e.projectSlug,environmentSlug:e.environmentSlug,cliUseWorkspace:e.cliUseWorkspace,name:e.name,description:e.description,enableEditor:e.enableEditor,inlineTemplates:e.inlineTemplates}),this.useServer=e.useServer}start(){this.setupFileWatcher(),this.setupRebuildSubscription()}async close(){this.isShuttingDown=!0,this.watcher&&(await this.watcher.close(),this.watcher=null),this.subscription?.unsubscribe(),this.changeSubject$.complete()}setupFileWatcher(){this.watcher=l(g,{ignored:b,cwd:process.cwd(),persistent:!0,ignoreInitial:!1}),this.watcher.on("all",(e,t)=>{("change"===e||"add"===e||"unlink"===e)&&(this.logger.info(`
2
- 📝 Detected ${e}: ${t}`),this.changeSubject$.next(t))})}setupRebuildSubscription(){let e=this.changeSubject$.pipe(r(10));this.subscription=this.changeSubject$.pipe(s(e)).subscribe(e=>{let t=new Set(e),i=t.has(".env");this.rebuildQueue.add(async()=>{this.isShuttingDown||(this.logger.info(`
1
+ import{resolve as e}from"path";import t from"promise-queue";import{Subject as i,buffer as s,debounceTime as r}from"rxjs";import{createServer as o,normalizePath as n}from"vite";import{watch as l}from"#package/watch";import{ApplicationSpecBuilder as h}from"../application-spec/application-spec-builder.js";import{logDiagnostics as a}from"../application-spec/metrics/index.js";import{syncTemplateFiles as c}from"../application-spec/template-files.js";import{buildWebhooks as u}from"../webhooks/index.js";import{getViteDevConfig as p}from"./vite-config.js";let g=["spec/**/*.{yaml,yml}","src/**/*.{ts,tsx,yaml,yml,json,html,css}","templates/*.html",".env",".env.generated"],d=["src/locales/**/*.{ts,tsx}",".phoenix/**"];export class ApplicationSpecProjectWatcher{watcher=null;subscription=null;rebuildQueue=new t(1,1/0);changeSubject$=new i;viteServer=null;pubsub;logger;onRebuilt;onViteServerChange;builder;useServer;isShuttingDown=!1;suspended=!1;heldChanges=new Set;constructor(e){this.pubsub=e.pubsub,this.logger=e.logger,this.onRebuilt=e.onRebuilt,this.onViteServerChange=e.onViteServerChange,this.builder=new h({logger:e.logger,sdkVersion:e.sdkVersion,projectSlug:e.projectSlug,environmentSlug:e.environmentSlug,cliUseWorkspace:e.cliUseWorkspace,name:e.name,description:e.description,enableEditor:e.enableEditor,inlineTemplates:e.inlineTemplates}),this.useServer=e.useServer}start(e){this.viteServer=e,this.setupFileWatcher(),this.setupRebuildSubscription()}applyVariantFiles(e){this.rebuildQueue.add(async()=>{this.isShuttingDown||await this.rebuild(new Set(e.map(e=>e.fileName)),!1,!0)})}suspend(){this.suspended=!0}resume(){for(let e of(this.suspended=!1,this.heldChanges))this.changeSubject$.next(e);this.heldChanges.clear()}async close(){this.isShuttingDown=!0,this.watcher&&(await this.watcher.close(),this.watcher=null),this.subscription?.unsubscribe(),this.changeSubject$.complete()}setupFileWatcher(){this.watcher=l(g,{ignored:d,cwd:process.cwd(),persistent:!0,ignoreInitial:!1}),this.watcher.on("all",(e,t)=>{if("change"===e||"add"===e||"unlink"===e){if(this.suspended)return void this.heldChanges.add(t);this.logger.info(`
2
+ 📝 Detected ${e}: ${t}`),this.changeSubject$.next(t)}})}setupRebuildSubscription(){let e=this.changeSubject$.pipe(r(10));this.subscription=this.changeSubject$.pipe(s(e)).subscribe(e=>{let t=new Set(e),i=t.has(".env");this.rebuildQueue.add(async()=>{this.isShuttingDown||(this.logger.info(`
3
3
  🔨 Rebuilding spec files...
4
- `),await this.rebuild(t,i))})})}async rebuild(t,i){try{let s=await h();if(this.isShuttingDown)return;let r=await this.builder.build();if(this.isShuttingDown)return;if(a(r.diagnostics,this.logger),!r.ok){for(let e of r.errors)this.logger.error(`[${e.code}] ${e.message}${e.file?` (${e.file})`:""}`);this.pubsub.specFile$.next({rawProjectFiles:r.rawProjectFiles,projectRoot:process.cwd()});return}this.onRebuilt?.();let{application:l,changedFiles:c}=r,g=this.viteServer.moduleGraph,b=Date.now(),w=new Set,d=process.cwd(),f=e=>{let t=g.getModulesByFile(n(e));if(t)for(let e of t)g.invalidateModule(e,w,b,!0)};for(let i of t)f(e(d,i));for(let t of c)f(e(d,`.phoenix/${t.path}`));if(this.pubsub.specFile$.next({rawProjectFiles:l.rawProjectFiles,projectRoot:process.cwd(),configurationSchemaHash:l.applicationSpec.configurator.configurationSchema.hash}),this.isShuttingDown)return;if(i){if(await this.viteServer.close(),this.isShuttingDown)return;let e=await p({templateFiles:s});if(this.isShuttingDown)return;let t=await o(e);if(this.isShuttingDown||(await t.listen(),this.isShuttingDown))return void await t.close();this.viteServer=t,this.onViteServerChange?.(t),this.logger.success("Vite server restarted (env changed)")}if(this.useServer){if(this.logger.step("Building webhooks"),await u({experimental:!0,skipNodeEnvOverride:!0,webhookEntryPoint:"./.phoenix/.swc/.phoenix/webhook.js",preserveExistingOutput:!0}),this.isShuttingDown)return;this.logger.success("Webhooks rebuilt successfully")}this.logger.success("Project files rebuilt successfully")}catch(e){this.logger.error(`Build failed: ${e instanceof Error?e.message:String(e)}`,e)}}}
4
+ `),await this.rebuild(t,i,!1))})})}async rebuild(t,i,s){try{let r=this.viteServer;if(!r)throw Error("Cannot rebuild the project: the watcher has no Vite server yet, because it was not started. Start the watcher before applying files");let l=await c();if(this.isShuttingDown)return;let h=await this.builder.build({compile:!s});if(this.isShuttingDown)return;if(a(h.diagnostics,this.logger),!h.ok){for(let e of h.errors)this.logger.error(`[${e.code}] ${e.message}${e.file?` (${e.file})`:""}`);this.pubsub.specFile$.next({rawProjectFiles:h.rawProjectFiles,projectRoot:process.cwd()});return}this.onRebuilt?.();let{application:g,changedFiles:d}=h,w=r.moduleGraph,b=Date.now(),f=new Set,m=process.cwd(),S=e=>{let t=w.getModulesByFile(n(e));if(t)for(let e of t)w.invalidateModule(e,f,b,!0)};for(let i of t)S(e(m,i));for(let t of d)S(e(m,`.phoenix/${t.path}`));if(this.pubsub.specFile$.next({rawProjectFiles:g.rawProjectFiles,projectRoot:process.cwd(),configurationSchemaHash:g.applicationSpec.configurator.configurationSchema.hash}),this.isShuttingDown)return;if(i){if(await r.close(),this.isShuttingDown)return;let e=await p({templateFiles:l});if(this.isShuttingDown)return;let t=await o(e);if(this.isShuttingDown||(await t.listen(),this.isShuttingDown))return void await t.close();this.viteServer=t,this.onViteServerChange?.(t),this.logger.success("Vite server restarted (env changed)")}if(this.useServer&&!s){if(this.logger.step("Building webhooks"),await u({experimental:!0,skipNodeEnvOverride:!0,webhookEntryPoint:"./.phoenix/.swc/.phoenix/webhook.js",preserveExistingOutput:!0}),this.isShuttingDown)return;this.logger.success("Webhooks rebuilt successfully")}this.logger.success("Project files rebuilt successfully")}catch(e){this.logger.error(`Build failed: ${e instanceof Error?e.message:String(e)}`,e)}}}
@@ -1,5 +1,9 @@
1
1
  export type { BrowserConsoleEvent, DataRequest, DataResult, EditorContextData, EditorLifecycleStatus, EditorStateData, MockTemplateUpdateEvent, SceneRequest, SceneResult, ScreenshotRequest, ScreenshotResult, SpecUpdateEvent, StateRequest, StateResult, StateSection, } from './phoenix-pubsub.js';
2
2
  export { PhoenixPubSub } from './phoenix-pubsub.js';
3
+ export { PhoenixStore } from './phoenix-store.js';
4
+ export { PhoenixApplication } from './phoenix-application.js';
5
+ export { VariantFileSession } from './variant-file-session.js';
6
+ export { VariantPreviewService } from './variant-preview-service.js';
3
7
  export { MockTemplateWatcher, type MockTemplateWatcherConfig } from './mock-template-watcher.js';
4
8
  export { ApplicationSpecProjectWatcher, type ApplicationSpecProjectWatcherConfig, } from './application-spec-project-watcher.js';
5
9
  export { ApplicationSpecStoryWatcher, type ApplicationSpecStoryWatcherConfig, } from './application-spec-story-watcher.js';
@@ -11,6 +15,7 @@ export { patchConsole, type PatchConsoleOptions } from './console-capture.js';
11
15
  export { WebhookTunnelMonitor, type TunnelEvent, type TunnelRequestEntry, type TunnelRequestSummary, type TunnelStatus, type TunnelStatusState, } from './webhook-tunnel-monitor.js';
12
16
  export { compileWithSwc, watchWithSwc } from './swc.js';
13
17
  export { STORY_DEV_MARKER_PATH, readActiveStoryDevMarker, type StoryDevMarker } from './story-dev-marker.js';
18
+ export { composeDefaultBanner } from './phx-banner-plugin.js';
14
19
  export { getViteBuildConfigs, getViteDevConfig, setViteLogSink, type ViteLogSink, type ViteLogSinkOptions, } from './vite-config.js';
15
20
  export { getServerCredentials, removeServerCredentials, saveServerCredentials } from './cli-credentials.js';
16
21
  export { createSourceArchive, extractSourceArchive } from './source-archive.js';
@@ -1 +1 @@
1
- export{PhoenixPubSub}from"./phoenix-pubsub.js";export{MockTemplateWatcher}from"./mock-template-watcher.js";export{ApplicationSpecProjectWatcher}from"./application-spec-project-watcher.js";export{ApplicationSpecStoryWatcher}from"./application-spec-story-watcher.js";export{LinguiWatcher}from"./lingui-watcher.js";export{loadMockTemplates,parseMockTemplateYaml}from"./spec-files.js";export{LOG_STREAMS,LogBus}from"./log-bus.js";export{createBusLogger}from"./bus-logger.js";export{patchConsole}from"./console-capture.js";export{WebhookTunnelMonitor}from"./webhook-tunnel-monitor.js";export{compileWithSwc,watchWithSwc}from"./swc.js";export{STORY_DEV_MARKER_PATH,readActiveStoryDevMarker}from"./story-dev-marker.js";export{getViteBuildConfigs,getViteDevConfig,setViteLogSink}from"./vite-config.js";export{getServerCredentials,removeServerCredentials,saveServerCredentials}from"./cli-credentials.js";export{createSourceArchive,extractSourceArchive}from"./source-archive.js";export{resolveSignedInDevelopmentEnvironment}from"./signed-in-development-environment.js";export{DEFAULT_PHOENIX_REGION,PHOENIX_REGIONS,PUBLIC_PHOENIX_REGIONS,getRegionServerUrl,getRegionStudioUrl}from"./phoenix-regions.js";
1
+ export{PhoenixPubSub}from"./phoenix-pubsub.js";export{PhoenixStore}from"./phoenix-store.js";export{PhoenixApplication}from"./phoenix-application.js";export{VariantFileSession}from"./variant-file-session.js";export{VariantPreviewService}from"./variant-preview-service.js";export{MockTemplateWatcher}from"./mock-template-watcher.js";export{ApplicationSpecProjectWatcher}from"./application-spec-project-watcher.js";export{ApplicationSpecStoryWatcher}from"./application-spec-story-watcher.js";export{LinguiWatcher}from"./lingui-watcher.js";export{loadMockTemplates,parseMockTemplateYaml}from"./spec-files.js";export{LOG_STREAMS,LogBus}from"./log-bus.js";export{createBusLogger}from"./bus-logger.js";export{patchConsole}from"./console-capture.js";export{WebhookTunnelMonitor}from"./webhook-tunnel-monitor.js";export{compileWithSwc,watchWithSwc}from"./swc.js";export{STORY_DEV_MARKER_PATH,readActiveStoryDevMarker}from"./story-dev-marker.js";export{composeDefaultBanner}from"./phx-banner-plugin.js";export{getViteBuildConfigs,getViteDevConfig,setViteLogSink}from"./vite-config.js";export{getServerCredentials,removeServerCredentials,saveServerCredentials}from"./cli-credentials.js";export{createSourceArchive,extractSourceArchive}from"./source-archive.js";export{resolveSignedInDevelopmentEnvironment}from"./signed-in-development-environment.js";export{DEFAULT_PHOENIX_REGION,PHOENIX_REGIONS,PUBLIC_PHOENIX_REGIONS,getRegionServerUrl,getRegionStudioUrl}from"./phoenix-regions.js";
@@ -0,0 +1,21 @@
1
+ import type { PhoenixPubSub } from './phoenix-pubsub.js';
2
+ import type { PhoenixStore } from './phoenix-store.js';
3
+ import type { VariantPreviewService } from './variant-preview-service.js';
4
+ export interface PhoenixApplicationProps {
5
+ readonly store: PhoenixStore;
6
+ readonly pubsub: PhoenixPubSub;
7
+ /** Absent in a session that cannot rewrite project files, such as story-dev. */
8
+ readonly variantPreviews: VariantPreviewService | undefined;
9
+ }
10
+ /**
11
+ * One running dev session: its state, its event bus and the services built on them. The command that
12
+ * starts the session composes it once and hands it to the transports, so the editor server's routers get
13
+ * their services from here instead of from callbacks threaded through the command.
14
+ */
15
+ export declare class PhoenixApplication {
16
+ readonly store: PhoenixStore;
17
+ readonly pubsub: PhoenixPubSub;
18
+ readonly variantPreviews: VariantPreviewService | undefined;
19
+ constructor(props: PhoenixApplicationProps);
20
+ close(): Promise<void>;
21
+ }
@@ -0,0 +1 @@
1
+ export class PhoenixApplication{store;pubsub;variantPreviews;constructor(s){this.store=s.store,this.pubsub=s.pubsub,this.variantPreviews=s.variantPreviews}async close(){await this.variantPreviews?.dispose()}}