@salsita-ai/sdk 0.50.0-develop.be40f0cee8 → 0.50.0-develop.bfba230ad7

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 (113) hide show
  1. package/dist/application-spec/generate-application/code/project-scaffolding.js +2 -2
  2. package/dist/application-spec/generate-application/code/templates/index.d.ts +1 -0
  3. package/dist/application-spec/generate-application/code/templates/index.js +1 -1
  4. package/dist/application-spec/generate-application/code/templates/skills/agents-md.js +1 -1
  5. package/dist/application-spec/generate-application/code/templates/skills/phoenix-cli-skill.js +1 -1
  6. package/dist/application-spec/generate-application/code/templates/skills/phoenix-create-configurator-skill.js +41 -13
  7. package/dist/application-spec/generate-application/code/templates/skills/phoenix-feedback-skill.js +1 -1
  8. package/dist/application-spec/generate-application/code/templates/skills/phoenix-review-skill.js +1 -1
  9. package/dist/application-spec/generate-application/code/templates/skills/phoenix-skill.js +1 -1
  10. package/dist/application-spec/generate-application/code/templates/skills/phoenix-variants-skill.d.ts +1 -0
  11. package/dist/application-spec/generate-application/code/templates/skills/phoenix-variants-skill.js +6 -0
  12. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.d.ts +28 -2
  13. package/dist/application-spec/generate-application/code/templates/skills/sdk-content.js +19 -4
  14. package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
  15. package/dist/configurator/application-runtime/extensions/selectors.js +1 -1
  16. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.d.ts +146 -13
  17. package/dist/configurator/application-runtime/extensions/systems/assistant-system/assistant-system.js +1 -1
  18. package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.d.ts +85 -0
  19. package/dist/configurator/application-runtime/extensions/systems/assistant-system/change-recorder.js +1 -0
  20. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.d.ts +8 -3
  21. package/dist/configurator/application-runtime/extensions/systems/assistant-system/graphql-tools.js +1 -1
  22. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts +4 -0
  23. package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js +1 -1
  24. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.d.ts +16 -1
  25. package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
  26. package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.d.ts +9 -0
  27. package/dist/configurator/application-runtime/extensions/systems/graphql-system/side-effects.js +1 -0
  28. package/dist/configurator/application-runtime/extensions/systems/index.d.ts +1 -1
  29. package/dist/configurator/common/frontend-analytics.d.ts +21 -21
  30. package/dist/configurator/index.d.ts +0 -1
  31. package/dist/configurator/index.js +1 -1
  32. package/dist/configurator/pages/LoadedConfiguratorDetailPage.js +1 -1
  33. package/dist/configurator/scene/scene-analytics/scene-analytics.d.ts +2 -2
  34. package/dist/configurator/ui/assistant/AssistantComposer.d.ts +1 -6
  35. package/dist/configurator/ui/assistant/AssistantComposer.js +1 -1
  36. package/dist/configurator/ui/assistant/AssistantPanel.js +1 -1
  37. package/dist/configurator/ui/assistant/AssistantThread.d.ts +1 -6
  38. package/dist/configurator/ui/assistant/AssistantThread.js +1 -1
  39. package/dist/configurator/ui/assistant/index.d.ts +1 -1
  40. package/dist/configurator/ui/assistant/index.js +1 -1
  41. package/dist/configurator/ui/assistant/thread-items.d.ts +1 -1
  42. package/dist/configurator/ui/assistant/use-is-assistant-panel-open.d.ts +5 -0
  43. package/dist/configurator/ui/assistant/use-is-assistant-panel-open.js +1 -0
  44. package/dist/configurator/ui/configurator-layout/universal/DesktopLayout.js +2 -2
  45. package/dist/configurator/ui/configurator-layout/universal/Layout.js +1 -1
  46. package/dist/configurator/ui/configurator-layout/universal/MobileLayout.js +4 -4
  47. package/dist/configurator/ui/legacy/mobile-controls/MobileControls.d.ts +1 -1
  48. package/dist/configurator/ui/phoenix-layout-elements/AssistantToolbarButton.d.ts +2 -2
  49. package/dist/configurator/ui/phoenix-layout-elements/AssistantToolbarButton.js +1 -1
  50. package/dist/docs/index.json +1 -1
  51. package/dist/docs/layouts/toolbar.mdx +3 -1
  52. package/dist/docs/other-features/side-effects.mdx +26 -0
  53. package/dist/docs/phoenix/phoenix-cli.mdx +81 -2
  54. package/dist/docs/phoenix/project-structure.mdx +3 -2
  55. package/dist/docs/phoenix/sdk-builder-workflow.mdx +4 -3
  56. package/dist/domain/components/updates.d.ts +16 -0
  57. package/dist/domain/domain-context/index.d.ts +1 -1
  58. package/dist/domain/domain-context/store-system/store-system.js +1 -1
  59. package/dist/editor/Editor.js +1 -1
  60. package/dist/editor/graphql/GraphQLPanel.js +1 -1
  61. package/dist/editor/variants/VariantAnswerFooter.d.ts +17 -0
  62. package/dist/editor/variants/VariantAnswerFooter.js +1 -0
  63. package/dist/editor/variants/VariantPreviewHandler.d.ts +6 -0
  64. package/dist/editor/variants/VariantPreviewHandler.js +1 -0
  65. package/dist/editor/variants/variant-preview-styles.d.ts +49 -0
  66. package/dist/editor/variants/variant-preview-styles.js +1 -0
  67. package/dist/phoenix/application-spec/application-spec-builder.js +1 -1
  68. package/dist/phoenix/application-spec/generate-assistant-prompt.d.ts +3 -2
  69. package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
  70. package/dist/phoenix/cli.js +1 -1
  71. package/dist/phoenix/commands/deploy.js +2 -2
  72. package/dist/phoenix/commands/dev.js +5 -5
  73. package/dist/phoenix/commands/index.d.ts +1 -0
  74. package/dist/phoenix/commands/index.js +1 -1
  75. package/dist/phoenix/commands/story-dev.js +2 -2
  76. package/dist/phoenix/commands/variants.d.ts +35 -0
  77. package/dist/phoenix/commands/variants.js +1 -0
  78. package/dist/phoenix/editor-server/commands-router.d.ts +68 -1
  79. package/dist/phoenix/editor-server/commands-router.js +1 -1
  80. package/dist/phoenix/editor-server/editor-router.d.ts +65 -0
  81. package/dist/phoenix/editor-server/editor-server.d.ts +3 -3
  82. package/dist/phoenix/editor-server/editor-server.js +1 -1
  83. package/dist/phoenix/editor-server/protocol.d.ts +1 -0
  84. package/dist/phoenix/editor-server/spec-router.js +1 -1
  85. package/dist/phoenix/editor-server/trpc.d.ts +3 -0
  86. package/dist/phoenix/services/application-spec-project-watcher.d.ts +13 -2
  87. package/dist/phoenix/services/application-spec-project-watcher.js +3 -3
  88. package/dist/phoenix/services/index.d.ts +4 -0
  89. package/dist/phoenix/services/index.js +1 -1
  90. package/dist/phoenix/services/phoenix-application.d.ts +21 -0
  91. package/dist/phoenix/services/phoenix-application.js +1 -0
  92. package/dist/phoenix/services/phoenix-store.d.ts +48 -0
  93. package/dist/phoenix/services/phoenix-store.js +1 -0
  94. package/dist/phoenix/services/phx-variant-previews-plugin.d.ts +9 -0
  95. package/dist/phoenix/services/phx-variant-previews-plugin.js +1 -0
  96. package/dist/phoenix/services/variant-file-session.d.ts +36 -0
  97. package/dist/phoenix/services/variant-file-session.js +1 -0
  98. package/dist/phoenix/services/variant-preview-service.d.ts +80 -0
  99. package/dist/phoenix/services/variant-preview-service.js +1 -0
  100. package/dist/phoenix/services/vite-config.js +1 -1
  101. package/dist/react-sdk/application-runtime/common-services/analytics/analytics-service.d.ts +2 -2
  102. package/dist/react-sdk/application-runtime/common-services/analytics/domain-controls-analytics.d.ts +21 -21
  103. package/dist/react-sdk/application-runtime/hooks/data/use-published-data.d.ts +1 -1
  104. package/dist/ui-sdk/common/use-viewport-size.d.ts +4 -1
  105. package/dist/ui-sdk/common/use-viewport-size.js +1 -1
  106. package/dist/ui-sdk/components/mobile-controls/index.d.ts +1 -1
  107. package/package.json +4 -4
  108. package/dist/configurator/assistant/index.d.ts +0 -1
  109. package/dist/configurator/assistant/index.js +0 -1
  110. package/dist/configurator/assistant/use-assistant-chat.d.ts +0 -30
  111. package/dist/configurator/assistant/use-assistant-chat.js +0 -1
  112. package/dist/configurator/ui/assistant/AssistantPanelProvider.d.ts +0 -42
  113. package/dist/configurator/ui/assistant/AssistantPanelProvider.js +0 -1
@@ -1,2 +1,2 @@
1
- import{CompositeKeyMap as e,assertExistence as t,isEqualArray as i}from"@salsita-ai/common/utils";import{dragStateComponent as o}from"../../components/drag-state-component.js";import{hoverStateComponent as r}from"../../components/hover-state-component.js";import{selectionStateComponent as s}from"../../components/selection-state-component.js";import{getComponentSystemFilterState as n}from"../../components/system-component-filter.js";import{systemVirtualEntityId as a}from"../../components/system-virtual-entity.js";import{systemUpdateFactory as d}from"../../components/updates.js";import{isSystemViewportStateComponentSnapshot as m}from"../../components/viewport-state-component.js";import{isEqualComponentInstance as l}from"../../core/component.js";import{domainEntityTypeFromId as c,isVirtualEntityId as p}from"../../core/model.js";import{projectedEntitiesComponent as h}from"../../system-components/index.js";import{cloneEvalCache as f,createEvalCacheToken as v,getEvalCache as g,setEvalCache as u}from"../../utils/eval-cache.js";import{createCascadeDeletesTransformer as y}from"../relation-transformers/cascade-deletes.js";import{createCascadeRefPruningTransformer as S}from"../relation-transformers/cascade-ref-pruning.js";import{applyUpdates as I}from"./apply-updates.js";import{LifecycleStateSlice as _}from"./lifecycle-state-slice.js";import{mergeReconciliationsUpdates as x,reconcileProjectedEntities as T}from"./reconcile-projected-entities.js";let E={uninitializedError:"StoreSystem is not initialized."},k=v({clone:e=>e}),w=class InvalidInitialStateError extends Error{emission;childError;constructor(e,t,i){let o="";"uncaught"===e.validity.severity&&(o=`: ${e.validity.error.message}`),("fatal"===e.validity.severity||"fixable"===e.validity.severity)&&(o=`: ${e.validity.entityViolations.map(e=>{let i=e.violation.message;return null!=i?t(i):e.violation.type}).join(", ")}`),super(`Initial state is not valid! Severity: ${e.validity.severity}, Cause: ${o}`),this.emission=e,this.childError=i,this.name="InvalidInitialStateError"}},b=(e,t)=>{try{return e()}catch(e){throw t(e),e}};export class StoreSystem{_context;stateSlices;get isInitialized(){return this.committed.isInitialized}_onBeforeCommitHooks=[];committed=new _(E);potentiallyInvalid=new _(E);rendered=new _(E);stagedUpdates=void 0;transformToDataUpdates=(e,t)=>{let i=!1,o=e.map(e=>"modifyComponent"===e.kind?(i=!0,this.componentModificationToDataUpdate(e,t)):e);return i?o:e};createInitialTransformPipe=()=>[{transformer:this.transformToDataUpdates,priority:1/0,registrationToken:{},name:"TransformToDataUpdates"}];transformPipe=this.createInitialTransformPipe();_cascadeDeletesTransformer=(...e)=>(this._cascadeDeletesTransformerMemo??=y(this._context.selectors.getCompositionProjections()))(...e);_cascadeDeletesTransformerMemo;_refPruningTransformer=(...e)=>(this._refPruningTransformerMemo??=S(this._context.selectors.getComponentReader()))(...e);_refPruningTransformerMemo;_deselectOnDeleteTransformer=(e,t)=>{let i=new Set(e.filter(e=>"deleteEntity"===e.kind).map(e=>e.entityId));if(0===i.size)return e;let o=n(t).selectedEntityId;return o&&i.has(o)?[...e,d.EphemeralRecordModification({componentInstance:{entityId:a,componentType:s},updateTag:"AutoDeselectRemovedProjectedEntity",writableState:{selectedEntityId:t.rootEntityId}})]:e};constructor(e){this._context=e,this.stateSlices={committed:this.committed.observable,rendered:this.rendered.observable,potentiallyInvalid:this.potentiallyInvalid.observable}}_validateState=e=>this._context.selectors.getValidationProjections().validateState(e);initialize=()=>{let e=this._context.selectors.getInitialDomainState();this.stagedUpdates=void 0;let t=this._validateState(e),i={kind:"reset",state:e,validity:t,tag:void 0,transformationLog:void 0},o=i;if(!o.validity.valid&&"fatal"===o.validity.severity||"fixable"===o.validity.severity){this._context.domainServicesSelectors.getLogger().debug("Trying to fix initial emission:",o);let e=o.state,{transformedUpdates:t,transformationLog:i}=this.applyTransformers([],e,"committed"),r=I(this.transformToDataUpdates(t,e),e);f(e,r),o={kind:"reset",state:r,validity:this._validateState(r),tag:"fixed",transformationLog:i}}if(!o.validity.valid){if(this._context.domainServicesSelectors.getLogger().error("Invalid initial emission:",{initialEmission:i,fixedEmission:o}),"uncaught"===o.validity.severity)throw new w(o,this._context.domainServicesSelectors.getResolveLocalizable(),o.validity.error??void 0);throw new w(o,this._context.domainServicesSelectors.getResolveLocalizable())}this.committed.next(o),this.rendered.next(o),this.potentiallyInvalid.next(o)};registerTransformer(e,i,o){let r={};return((e,i,o)=>{let r=0;for(;r<e.length&&0>=o(t(e[r]),i);)r++;e.splice(r,0,i)})(this.transformPipe,{registrationToken:r,transformer:i,priority:e,name:o},(e,t)=>e.priority===t.priority?0:e.priority<t.priority?-1:1),()=>{let e=this.transformPipe.findIndex(e=>e.registrationToken===r);-1!==e&&this.transformPipe.splice(e,1)}}onBeforeCommit(e){return this._onBeforeCommitHooks.push(e),()=>{this._onBeforeCommitHooks=this._onBeforeCommitHooks.filter(t=>t!==e)}}componentModificationToDataUpdate=(e,t)=>{let i=e.entityId;if(!p(i)){let t=this._context.selectors.getComponentReaderIndexes().opticMap.get(c(i))?.get(e.componentInstance.componentType)?.get(e.componentInstance.instanceName);if(t?.kind==="simple"){let o=t.write(e.writableState);return{kind:"modifyDomainEntity",entityId:i,updateTag:e.updateTag,stateDelta:o,hint:e.hint,origin:e}}}let o=t.ephemeralRecords.find(t=>l(t.componentInstance,e.componentInstance));if(o)return{kind:"modifyEphemeralRecord",entityId:e.entityId,updateTag:e.updateTag,componentInstance:o.componentInstance,writableState:e.writableState,hint:e.hint};throw Error(`Component ${e.componentInstance.componentType.name} is not attached on entity #${e.entityId}`)};getNewState=(e,t)=>{let i=I(this.transformToDataUpdates(e,t),t);return f(this.rendered.isInitialized?this.rendered.value.state:t,i),i};applyTransformers(e,t,i){let o=this._context.environmentSelectors.getEnvironmentIsDev()?[]:void 0;return{transformedUpdates:this.transformPipe.reduce((e,{transformer:r,name:s})=>{let n,a=o?[]:void 0,d=a?(e,t,i)=>{n=e,a.push({phase:e,message:t,data:i})}:void 0,m=b(()=>r(e,t,i,d),r=>{this._context.domainServicesSelectors.getLogger().error("Error while applying transformer!",{name:s,updates:e,previousState:t,kind:i,transformationLog:o},r instanceof Error?r:Error(String(r)))});return a&&o&&o.push({name:s,status:n??(m===e?"no-event":"apply"),entries:a,updatesIn:e,updatesOut:m}),m},e),transformationLog:o}}_updateProjectedEntities(e,t,o){if(!e.validity.valid)return e;let r=this._context.selectors.getComponentReader().readManyComponents({componentTypes:[h]},e.state),s=g(e.previousState,k);if(s&&i(s,r))return e;let n=0,a=e,d=[];for(;a.validity.valid;){n++;let i=T(a.state.entities,r,t);if(0===i.length)break;if(n>10)throw Error(`Maximum number of reconciliation rounds reached: 10. Projected entities seem to be recursively depending on themselves.
1
+ import{CompositeKeyMap as e,assertExistence as t,isEqualArray as i}from"@salsita-ai/common/utils";import{dragStateComponent as o}from"../../components/drag-state-component.js";import{hoverStateComponent as r}from"../../components/hover-state-component.js";import{selectionStateComponent as s}from"../../components/selection-state-component.js";import{getComponentSystemFilterState as n}from"../../components/system-component-filter.js";import{systemVirtualEntityId as a}from"../../components/system-virtual-entity.js";import{systemUpdateFactory as d}from"../../components/updates.js";import{isSystemViewportStateComponentSnapshot as m}from"../../components/viewport-state-component.js";import{isEqualComponentInstance as l}from"../../core/component.js";import{domainEntityTypeFromId as c,isVirtualEntityId as p}from"../../core/model.js";import{projectedEntitiesComponent as h}from"../../system-components/index.js";import{cloneEvalCache as f,createEvalCacheToken as v,getEvalCache as g,setEvalCache as u}from"../../utils/eval-cache.js";import{createCascadeDeletesTransformer as y}from"../relation-transformers/cascade-deletes.js";import{createCascadeRefPruningTransformer as S}from"../relation-transformers/cascade-ref-pruning.js";import{applyUpdates as I}from"./apply-updates.js";import{LifecycleStateSlice as _}from"./lifecycle-state-slice.js";import{mergeReconciliationsUpdates as x,reconcileProjectedEntities as T}from"./reconcile-projected-entities.js";let E={uninitializedError:"StoreSystem is not initialized."},k=v({clone:e=>e}),w=class InvalidInitialStateError extends Error{emission;childError;constructor(e,t,i){let o="";"uncaught"===e.validity.severity&&(o=`: ${e.validity.error.message}`),("fatal"===e.validity.severity||"fixable"===e.validity.severity)&&(o=`: ${e.validity.entityViolations.map(e=>{let i=e.violation.message;return null!=i?t(i):e.violation.type}).join(", ")}`),super(`Initial state is not valid! Severity: ${e.validity.severity}, Cause: ${o}`),this.emission=e,this.childError=i,this.name="InvalidInitialStateError"}},b=(e,t)=>{try{return e()}catch(e){throw t(e),e}};export class StoreSystem{_context;stateSlices;get isInitialized(){return this.committed.isInitialized}_onBeforeCommitHooks=[];committed=new _(E);potentiallyInvalid=new _(E);rendered=new _(E);stagedUpdates=void 0;transformToDataUpdates=(e,t)=>{let i=!1,o=e.map(e=>"modifyComponent"===e.kind?(i=!0,this.componentModificationToDataUpdate(e,t)):e);return i?o:e};createInitialTransformPipe=()=>[{transformer:this.transformToDataUpdates,priority:1/0,registrationToken:{},name:"TransformToDataUpdates"}];transformPipe=this.createInitialTransformPipe();_cascadeDeletesTransformer=(...e)=>(this._cascadeDeletesTransformerMemo??=y(this._context.selectors.getCompositionProjections()))(...e);_cascadeDeletesTransformerMemo;_refPruningTransformer=(...e)=>(this._refPruningTransformerMemo??=S(this._context.selectors.getComponentReader()))(...e);_refPruningTransformerMemo;_deselectOnDeleteTransformer=(e,t)=>{let i=new Set(e.filter(e=>"deleteEntity"===e.kind).map(e=>e.entityId));if(0===i.size)return e;let o=n(t).selectedEntityId;return o&&i.has(o)?[...e,d.EphemeralRecordModification({componentInstance:{entityId:a,componentType:s},updateTag:"AutoDeselectRemovedProjectedEntity",writableState:{selectedEntityId:t.rootEntityId}})]:e};constructor(e){this._context=e,this.stateSlices={committed:this.committed.observable,rendered:this.rendered.observable,potentiallyInvalid:this.potentiallyInvalid.observable}}_validateState=e=>this._context.selectors.getValidationProjections().validateState(e);initialize=()=>{let e=this._context.selectors.getInitialDomainState();this.stagedUpdates=void 0;let t=this._validateState(e),i={kind:"reset",state:e,validity:t,tag:void 0,transformationLog:void 0},o=i;if(!o.validity.valid&&"fatal"===o.validity.severity||"fixable"===o.validity.severity){this._context.domainServicesSelectors.getLogger().debug("Trying to fix initial emission:",o);let e=o.state,{transformedUpdates:t,transformationLog:i}=this.applyTransformers([],e,"committed"),r=I(this.transformToDataUpdates(t,e),e);f(e,r),o={kind:"reset",state:r,validity:this._validateState(r),tag:"fixed",transformationLog:i}}if(!o.validity.valid){if(this._context.domainServicesSelectors.getLogger().error("Invalid initial emission:",{initialEmission:i,fixedEmission:o}),"uncaught"===o.validity.severity)throw new w(o,this._context.domainServicesSelectors.getResolveLocalizable(),o.validity.error??void 0);throw new w(o,this._context.domainServicesSelectors.getResolveLocalizable())}this.committed.next(o),this.rendered.next(o),this.potentiallyInvalid.next(o)};registerTransformer(e,i,o){let r={};return((e,i,o)=>{let r=0;for(;r<e.length&&0>=o(t(e[r]),i);)r++;e.splice(r,0,i)})(this.transformPipe,{registrationToken:r,transformer:i,priority:e,name:o},(e,t)=>e.priority===t.priority?0:e.priority<t.priority?-1:1),()=>{let e=this.transformPipe.findIndex(e=>e.registrationToken===r);-1!==e&&this.transformPipe.splice(e,1)}}onBeforeCommit(e){return this._onBeforeCommitHooks.push(e),()=>{this._onBeforeCommitHooks=this._onBeforeCommitHooks.filter(t=>t!==e)}}componentModificationToDataUpdate=(e,t)=>{let i=e.entityId;if(!p(i)){let t=this._context.selectors.getComponentReaderIndexes().opticMap.get(c(i))?.get(e.componentInstance.componentType)?.get(e.componentInstance.instanceName);if(t?.kind==="simple"){let o=t.write(e.writableState);return{kind:"modifyDomainEntity",entityId:i,updateTag:e.updateTag,stateDelta:o,hint:e.hint,agentHint:e.agentHint,origin:e}}}let o=t.ephemeralRecords.find(t=>l(t.componentInstance,e.componentInstance));if(o)return{kind:"modifyEphemeralRecord",entityId:e.entityId,updateTag:e.updateTag,componentInstance:o.componentInstance,writableState:e.writableState,hint:e.hint,agentHint:e.agentHint};throw Error(`Component ${e.componentInstance.componentType.name} is not attached on entity #${e.entityId}`)};getNewState=(e,t)=>{let i=I(this.transformToDataUpdates(e,t),t);return f(this.rendered.isInitialized?this.rendered.value.state:t,i),i};applyTransformers(e,t,i){let o=this._context.environmentSelectors.getEnvironmentIsDev()?[]:void 0;return{transformedUpdates:this.transformPipe.reduce((e,{transformer:r,name:s})=>{let n,a=o?[]:void 0,d=a?(e,t,i)=>{n=e,a.push({phase:e,message:t,data:i})}:void 0,m=b(()=>r(e,t,i,d),r=>{this._context.domainServicesSelectors.getLogger().error("Error while applying transformer!",{name:s,updates:e,previousState:t,kind:i,transformationLog:o},r instanceof Error?r:Error(String(r)))});return a&&o&&o.push({name:s,status:n??(m===e?"no-event":"apply"),entries:a,updatesIn:e,updatesOut:m}),m},e),transformationLog:o}}_updateProjectedEntities(e,t,o){if(!e.validity.valid)return e;let r=this._context.selectors.getComponentReader().readManyComponents({componentTypes:[h]},e.state),s=g(e.previousState,k);if(s&&i(s,r))return e;let n=0,a=e,d=[];for(;a.validity.valid;){n++;let i=T(a.state.entities,r,t);if(0===i.length)break;if(n>10)throw Error(`Maximum number of reconciliation rounds reached: 10. Projected entities seem to be recursively depending on themselves.
2
2
  If expressions populating 'projectedEntities' components rely on other projected entities, make sure that the dependencies do not have cycles.`);let s=(d=x(d,i)).map(e=>e.dataUpdate),m=this._cascadeDeletesTransformer(s,e.previousState,o,void 0,t),l=this._refPruningTransformer(m,e.previousState,o,void 0,t),c=this._deselectOnDeleteTransformer(l,e.previousState,o,void 0,t);if(!(a=this.prepareStateEmissionWithoutTransformation([...t,...c],e.previousState,o)).validity.valid)return this._context.domainServicesSelectors.getLogger().error("Reconciliation of projected entities led to an invalid state! Reconciliation skipped.",{emission:a}),e;r=this._context.selectors.getComponentReader().readManyComponents({componentTypes:[h]},a.state)}return u(a.state,k,r),a}prepareStateEmission(e,t,i){let{transformedUpdates:o,transformationLog:r}=this.applyTransformers(e,t,i),s=this.prepareStateEmissionWithoutTransformation(o,t,i);return{...this._updateProjectedEntities(s,o,i),transformationLog:r}}emissionCache=new e([Map,WeakMap,WeakMap,WeakMap,WeakMap]);getEmissionCacheKey=(e,t,i)=>[e,t,i,this._context.selectors.getStoreRuntimeDependencies(),this._context.selectors.getExpressionContext()];prepareStateEmissionWithoutTransformation=(e,t,i)=>{let o=this.getEmissionCacheKey(i,t,e),r=this.emissionCache.get(o);if(r)return r;let s=b(()=>this.transformToDataUpdates(e,t),o=>{this._context.domainServicesSelectors.getLogger().error("Error while transforming updates to data updates!",{updates:e,previousState:t,kind:i},o instanceof Error?o:Error(String(o)))}),n=b(()=>I(s,t),o=>{this._context.domainServicesSelectors.getLogger().error("Error while applying updates!",{updates:e,previousState:t,kind:i,dataUpdates:s},o instanceof Error?o:Error(String(o)))});f(this.rendered.isInitialized?this.rendered.value.state:t,n);let a=this._validateState(n);"uncaught"===a.severity&&this._context.domainServicesSelectors.getLogger().error("There was an uncaught validation error:",{updates:e,dataUpdates:s,previousState:t,newState:n,kind:i},a.error);let d={kind:i,previousState:t,state:n,updates:s,validity:a,transformationLog:void 0};return this.emissionCache.set(o,d),d};stage(e,t=!0){this.stagedUpdates=e;let i=this.prepareStateEmission(e,this.committed.value.state,"staged");return t&&this.emit(i),i}emit(e){"staged"===e.kind?e.validity.valid&&this.rendered.nextIfDifferent(e):(e.validity.valid?(this.committed.nextIfDifferent(e),this.rendered.nextIfDifferent(e)):this.rendered.nextIfDifferent(this.committed.value),this.potentiallyInvalid.nextIfDifferent(e))}commit=()=>{if(void 0===this.stagedUpdates)return;let e=this.prepareStateEmission(this.stagedUpdates,this.committed.value.state,"committed"),t=()=>{if(this._onBeforeCommitHooks.some(i=>!1===i(e,t))){this._context.domainServicesSelectors.getLogger().debug("Commit was canceled by one of the onBeforeCommit hooks! Resetting rendered state.",e),this.rollback();return}this.stagedUpdates=void 0,this._context.domainServicesSelectors.getLogger().debug("commit",e),this.emit(e)};t()};commitPrepared=e=>{if("committed"!==e.kind||!e.validity.valid)throw Error(`commitPrepared received a ${e.validity.valid?e.kind:"invalid"} emission, but only a valid committed emission can become the committed state. Prepare the emission with kind "committed" and check its validity before committing it.`);let t=()=>e.previousState===this.committed.value.state;if(!t())return"conflict";let i=()=>{t()?o():this._context.domainServicesSelectors.getLogger().warn("A held commit was dropped, because the committed state changed since it was prepared.",e)},o=()=>this._onBeforeCommitHooks.some(t=>!1===t(e,i))?(this._context.domainServicesSelectors.getLogger().debug("A prepared commit was held by one of the onBeforeCommit hooks.",e),!1):(this._context.domainServicesSelectors.getLogger().debug("commitPrepared",e),this.stagedUpdates=void 0,this.emit(e),!0);return o()?"committed":"held"};rollback=()=>{void 0!==this.stagedUpdates&&(this.stagedUpdates=void 0,this.emit(this.committed.value))};_resetInteractionState(e){return e.ephemeralRecords.some(e=>{let t;return(t=e.componentInstance.componentType)===r||t===o})?{...e,ephemeralRecords:e.ephemeralRecords.map(e=>e.componentInstance.componentType===r?{...e,state:{hoveredEntityId:null}}:e.componentInstance.componentType===o?{...e,state:{draggedEntityId:null}}:e)}:e}_preserveViewportState(e,t){let i=t.ephemeralRecords.find(m),o=e.ephemeralRecords.filter(e=>!m(e));return{...e,ephemeralRecords:i?[...o,i]:o}}reset(e,t){let i=this.committed.value.state,o=this._preserveViewportState(e,i),r=this._resetInteractionState(o),s=this._validateState(r);if(!s.valid)throw Error("Cannot reset to an invalid state");this.stagedUpdates=void 0,this.emit({kind:"reset",state:r,validity:s,tag:t,transformationLog:void 0})}stageAndCommit(e){if(0!==e.length){this.stagedUpdates=e;try{this.commit()}finally{this.stagedUpdates=void 0}}}}
@@ -1 +1 @@
1
- import{jsx as e,jsxs as i,Fragment as t}from"react/jsx-runtime";import{Box as o,Chip as n,CssBaseline as r,IconButton as s,ThemeProvider as l,Tooltip as a,Typography as d,createTheme as c,useMediaQuery as m,useTheme as p}from"@mui/material";import{ModalProvider as f}from"mui-modal-provider";import{memo as h,useCallback as u,useEffect as g,useRef as w,useState as k}from"react";import{match as x}from"ts-pattern";import{useLocalStorage as y}from"usehooks-ts";import{PhxIcon as b,SnackbarProvider as v,createThemeWithPhoenixIcons as S}from"#package/ui-sdk";import{EditorMode as P}from"./EditorMode.js";import{EditorRuntimeProvider as j,useWebComponent as V}from"./EditorRuntimeProvider.js";import{EditorAdminContextProvider as E}from"./admin/EditorAdminContext.js";import{EditorAdminMainContent as D}from"./admin/EditorAdminMainContent.js";import{EditorAdminSidebar as C}from"./admin/EditorAdminSidebar.js";import{useEditorAdminState as T}from"./admin/use-editor-admin-state.js";import{Analytics as A}from"./analytics/Analytics.js";import{AnalyticsProvider as L}from"./analytics/AnalyticsContext.js";import{Logotype as M}from"./common/Logotype.js";import{PanelIconButton as W}from"./common/PanelIconButton.js";import{BrowserConsoleReporter as R}from"./console-reporter/BrowserConsoleReporter.js";import{DataHandler as I}from"./data/DataHandler.js";import{DebugFlags as F}from"./debug-flags/DebugFlags.js";import{DiagnosticsPanel as G}from"./diagnostics/DiagnosticsPanel.js";import{DomainEditors as z}from"./domain-editors/DomainEditors.js";import{DomainSpecProvider as B,useDomainSpecContext as Q}from"./domain-editors/DomainSpecContext.js";import{DomainReflection as H}from"./domain-reflection/DomainReflection.js";import{GraphQLPanel as U}from"./graphql/GraphQLPanel.js";import{LogsPanel as q}from"./logs/LogsPanel.js";import{EditorMockProvider as O}from"./mocks/EditorMockContext.js";import{Mocks as K}from"./mocks/Mocks.js";import{ProfilerPanel as N}from"./profiler/ProfilerPanel.js";import{RemoteFilesList as X}from"./remote-files/RemoteFilesList.js";import{SceneHandler as Y}from"./scene/SceneHandler.js";import{ScreenshotHandler as $}from"./screenshot/ScreenshotHandler.js";import{EditorConnectionProvider as J}from"./services/EditorConnectionContext.js";import{EditorActionButtons as Z}from"./sidebar/EditorActionButtons.js";import{StateInspector as _}from"./state-inspector/index.js";import{StateHandler as ee}from"./state/StateHandler.js";import{SpaTemplate as ei}from"./templates/SpaTemplate.js";import{Templates as et}from"./templates/Templates.js";import{TemplatesList as eo}from"./templates/TemplatesList.js";import{TunnelProvider as en,useTunnel as er}from"./tunnel/TunnelContext.js";import{TunnelPanel as es}from"./tunnel/TunnelPanel.js";import{hasTunnelProblem as el}from"./tunnel/tunnel-view-model.js";import{VideoStudio as ea}from"./video-studio/VideoStudio.js";import{WebSocketStatus as ed}from"./websocket-status/WebSocketStatus.js";let ec=h(()=>{let i=w(null),t=V();return g(()=>{let e=i.current;if(e&&t)return e.appendChild(t),()=>{e.contains(t)&&e.removeChild(t)}},[t]),e("div",{ref:i,style:{width:"100%",height:"100%"}})}),em=S(c());export const EditorPanelView={Files:"Files",Reflections:"Reflections",Domain:"Domain",Templates:"Templates",Mocks:"Mocks",Inspector:"Inspector",Debug:"Debug",Profiler:"Profiler",GraphQL:"GraphQL",VideoStudio:"VideoStudio",Analytics:"Analytics",Diagnostics:"Diagnostics",Logs:"Logs",Tunnel:"Tunnel",WebSocketStatus:"WebSocketStatus",Admin:"Admin"};let ep=[{key:EditorPanelView.Templates,icon:"GridFour",title:"Templates"},{key:EditorPanelView.Reflections,icon:"House",title:"Reflections"},{key:EditorPanelView.Files,icon:"List",title:"Files"},{key:EditorPanelView.Domain,icon:"Gear",title:"Domain"},{key:EditorPanelView.Mocks,icon:"TagBold",title:"Mocks"},{key:EditorPanelView.Inspector,icon:"CurrencyDollar",title:"Inspector"},{key:EditorPanelView.Debug,icon:"EyeBold",title:"Debug"},{key:EditorPanelView.Profiler,icon:"Alarm",title:"Profiler"},{key:EditorPanelView.GraphQL,icon:"MagnifyingGlassBold",title:"GraphQL"},{key:EditorPanelView.VideoStudio,icon:"CameraRotate",title:"Video Studio"},{key:EditorPanelView.Analytics,icon:"Flame",title:"Analytics"},{key:EditorPanelView.Diagnostics,icon:"WarningCircle",title:"Diagnostics"},{key:EditorPanelView.Logs,icon:"BracketsCurly",title:"Logs"},{key:EditorPanelView.Tunnel,icon:"ArrowsHorizontal",title:"Webhook Tunnel"}],ef=h(r=>{let{panelView:l,setPanelView:c,width:m,setWidth:p,selectedTemplate:f,setSelectedTemplate:h,isResizing:w,setIsResizing:y,onExit:v,enableAdmin:S}=r,P=T(S),{unreadDiagnosticCount:j,markDiagnosticsRead:V}=Q(),{state:E}=er(),L=l?Math.max(m,240):38,[R,I]=k(0),B=u(()=>I(e=>e+1),[]);return g(()=>{l===EditorPanelView.Diagnostics&&V()},[V,l]),i(o,{component:"div",sx:{display:"grid",gridTemplateColumns:`${L}px min-content auto`,gridTemplateRows:"minmax(0, 1fr)",width:"100vw",height:"100vh",backgroundColor:"#ffffff",overflow:"hidden"},onMouseMove:e=>{w&&p(e.clientX)},onMouseUp:()=>{y(!1)},children:[i(o,{component:"div",sx:{display:"grid",gridTemplateColumns:"36px auto",backgroundColor:"#f8f9fa",borderRight:"1px solid #dee2e6",boxShadow:"2px 0 8px rgba(0, 0, 0, 0.06)",overflow:"hidden",height:"100%"},children:[i("div",{style:{backgroundColor:"#f8f9fa",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",padding:"4px 0"},children:[e("div",{style:{marginBottom:"8px"},children:e(M,{variant:"icon-only"})}),i("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"2px"},children:[S&&i(t,{children:[e(W,{icon:"SlidersHorizontal",title:"Admin",active:l===EditorPanelView.Admin,onClick:()=>{l===EditorPanelView.Admin?c(null):c(EditorPanelView.Admin)}}),e("div",{style:{borderBottom:"1px solid #dee2e6",margin:"2px 0"}})]}),ep.map(i=>e(W,{icon:i.icon,title:i.title,active:l===i.key,badgeCount:i.key===EditorPanelView.Tunnel?+!!el(E):i.key===EditorPanelView.Diagnostics?j:0,onClick:()=>{l===i.key?c(null):c(i.key)}},i.key))]}),e(Z,{reload:B}),e("div",{style:{padding:"0 2px",paddingBottom:"4px"},children:e(W,{icon:"CloudArrowUp",title:"WebSocket Status",active:l===EditorPanelView.WebSocketStatus,onClick:()=>{l===EditorPanelView.WebSocketStatus?c(null):c(EditorPanelView.WebSocketStatus)}})}),v&&e("div",{style:{padding:"0 2px",paddingBottom:"8px"},children:e(W,{icon:"SignOut",title:"Exit Editor",variant:"danger",onClick:v})})]}),l&&i(o,{component:"div",sx:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",backgroundColor:"#ffffff"},children:[e(o,{component:"div",sx:{p:1.5,borderBottom:"1px solid #e9ecef",backgroundColor:"#ffffff"},children:i(o,{component:"div",sx:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i(o,{component:"div",sx:{display:"flex",flexDirection:"row",alignItems:"center"},children:[e(d,{variant:"h6",sx:{fontSize:16,fontWeight:600,color:"#212529"},children:x(l).with("Files",()=>"Files").with("Reflections",()=>"Reflections").with("Domain",()=>"Domain").with("Templates",()=>"Templates").with("Mocks",()=>"Mocks").with("Inspector",()=>"State Inspector").with("Debug",()=>"Debug").with("Profiler",()=>"Profiler").with("GraphQL",()=>"GraphQL").with("VideoStudio",()=>"Video Studio").with("Analytics",()=>"Analytics").with("Diagnostics",()=>"Diagnostics").with("Logs",()=>"Dev Server Logs").with("Tunnel",()=>"Webhook Tunnel").with("WebSocketStatus",()=>"WebSocket Status").with("Admin",()=>"Admin").otherwise(e=>e)}),e(a,{title:x(l).with("Files",()=>"Browse and inspect loaded GLTF files and their contents").with("Reflections",()=>"Inspect internal Phoenix systems state and configuration").with("Domain",()=>"Edit YAML domain specifications and component configurations").with("Templates",()=>"Select different layout templates for the configurator interface").with("Mocks",()=>"Create and manage mock data for testing session and access configurations").with("Inspector",()=>"Walk the entity tree: fields, expressions, and children").with("Debug",()=>"Toggle scene debug visuals like offset anchors, snapping, and collision meshes").with("Profiler",()=>"Make domain expressions show up as named frames in browser CPU profiles").with("GraphQL",()=>"Run GraphQL queries against the schema generated from the assistant manifest").with("VideoStudio",()=>"Create video sequences by capturing keyframes and exporting as video").with("Analytics",()=>"View parse pipeline metrics, domain stats, and diagnostics").with("Diagnostics",()=>"View latest editor warnings and errors").with("Logs",()=>"View dev server logs: spec builds, webhooks, vite, and browser console").with("Tunnel",()=>"View webhook tunnel status and the requests routed through it").with("WebSocketStatus",()=>"View WebSocket connection status and editor mode information").with("Admin",()=>"Manage admin panel, publish data, and configure settings").otherwise(()=>"Panel information"),placement:"left",arrow:!0,children:e(s,{size:"small",sx:{ml:1,color:"#6c757d",fontSize:14,p:.25,"&:hover":{backgroundColor:"#f8f9fa",color:"#495057"}},children:e(b,{name:"Info",style:{fontSize:14}})})})]}),e(o,{component:"div",sx:{display:"flex",alignItems:"center",gap:1},children:"Templates"===l&&e(n,{label:f.charAt(0).toUpperCase()+f.slice(1),variant:"outlined",size:"small",sx:{backgroundColor:"#f8f9fa",borderColor:"#dee2e6",color:"#495057",fontWeight:500,fontSize:"0.75rem"}})})]})}),i(o,{component:"div",sx:{flex:1,backgroundColor:"#ffffff",overflow:"auto"},children:["Files"===l&&e(X,{}),"Reflections"===l&&e(H,{}),"Domain"===l&&e(z,{}),"Templates"===l&&e(eo,{selectedTemplate:f,onTemplateSelect:h}),"Mocks"===l&&e(K,{}),"Inspector"===l&&e(_,{}),"Debug"===l&&e(F,{}),"Profiler"===l&&e(N,{}),"GraphQL"===l&&e(U,{}),"VideoStudio"===l&&e(ea,{}),"Analytics"===l&&e(A,{}),"Diagnostics"===l&&e(G,{}),"Logs"===l&&e(q,{}),"Tunnel"===l&&e(es,{}),"WebSocketStatus"===l&&e(ed,{}),S&&"Admin"===l&&e(C,{...P})]})]})]}),e("div",{style:{width:"2px",backgroundColor:"#dee2e6",cursor:"ew-resize",boxShadow:"1px 0 3px rgba(0, 0, 0, 0.05)"},onMouseDown:()=>{y(!0)}}),i("div",{style:{position:"relative",overflow:"hidden"},children:[e("div",{style:{position:"absolute",inset:0,zIndex:+("Admin"!==l)},children:e(et,{selectedTemplate:f,children:e(ec,{},R)})}),S&&e("div",{style:{position:"absolute",inset:0,zIndex:+("Admin"===l)},children:e(D,{})})]})]})}),eh=h(()=>e(ei,{children:e(ec,{})})),eu=h(o=>{let{wsUrl:n="ws://localhost:3020",localMode:r=!1,domainSpec:s,initialRawProjectFiles:l,onExit:a,mockTemplates:d,autoApplyTemplate:c,environmentKey:h,tagName:u,enableAdmin:w=!0}=o,x=m(p().breakpoints.up("md")),[b,S]=y("editor-width",350),[V,D]=y("editor-view",null),[C,T]=y("editor-template","spa"),[A,M]=k(!1);return g(()=>{null===V||Object.values(EditorPanelView).some(e=>e===V)&&(w||V!==EditorPanelView.Admin)||D(null)},[w,V,D]),e(f,{children:e(v,{maxSnack:5,children:e(E,{children:e(j,{tagName:u,children:e(J,{initialWsUrl:n,localMode:r,children:e(en,{children:e(P,{children:e(L,{children:e(B,{domainSpec:s,initialRawProjectFiles:l,children:i(O,{mockTemplates:d,autoApplyTemplate:c,environmentKey:h,children:[!r&&i(t,{children:[e($,{}),e(ee,{}),e(I,{}),e(Y,{}),e(R,{})]}),x?e(ef,{panelView:V,setPanelView:D,width:b,setWidth:S,selectedTemplate:C,setSelectedTemplate:T,isResizing:A,setIsResizing:M,onExit:a,enableAdmin:w}):e(eh,{})]})})})})})})})})})})});export const Editor=h(t=>i(l,{theme:em,children:[e(r,{}),e(eu,{...t})]}));
1
+ import{jsx as e,jsxs as i,Fragment as t}from"react/jsx-runtime";import{Box as o,Chip as n,CssBaseline as r,IconButton as s,ThemeProvider as a,Tooltip as l,Typography as d,createTheme as c,useMediaQuery as m,useTheme as p}from"@mui/material";import{ModalProvider as f}from"mui-modal-provider";import{memo as h,useCallback as u,useEffect as g,useState as w}from"react";import{match as k}from"ts-pattern";import{useLocalStorage as y}from"usehooks-ts";import{PhxIcon as x,SnackbarProvider as b,createThemeWithPhoenixIcons as v}from"#package/ui-sdk";import{EditorMode as S}from"./EditorMode.js";import{EditorRuntimeProvider as P}from"./EditorRuntimeProvider.js";import{EditorAdminContextProvider as j}from"./admin/EditorAdminContext.js";import{EditorAdminMainContent as V}from"./admin/EditorAdminMainContent.js";import{EditorAdminSidebar as E}from"./admin/EditorAdminSidebar.js";import{useEditorAdminState as D}from"./admin/use-editor-admin-state.js";import{Analytics as T}from"./analytics/Analytics.js";import{AnalyticsProvider as A}from"./analytics/AnalyticsContext.js";import{Logotype as C}from"./common/Logotype.js";import{PanelIconButton as L}from"./common/PanelIconButton.js";import{BrowserConsoleReporter as M}from"./console-reporter/BrowserConsoleReporter.js";import{DataHandler as W}from"./data/DataHandler.js";import{DebugFlags as R}from"./debug-flags/DebugFlags.js";import{DiagnosticsPanel as I}from"./diagnostics/DiagnosticsPanel.js";import{DomainEditors as F}from"./domain-editors/DomainEditors.js";import{DomainSpecProvider as G,useDomainSpecContext as z}from"./domain-editors/DomainSpecContext.js";import{DomainReflection as B}from"./domain-reflection/DomainReflection.js";import{GraphQLPanel as Q}from"./graphql/GraphQLPanel.js";import{LogsPanel as H}from"./logs/LogsPanel.js";import{EditorMockProvider as U}from"./mocks/EditorMockContext.js";import{Mocks as q}from"./mocks/Mocks.js";import{ProfilerPanel as O}from"./profiler/ProfilerPanel.js";import{RemoteFilesList as K}from"./remote-files/RemoteFilesList.js";import{SceneHandler as N}from"./scene/SceneHandler.js";import{ScreenshotHandler as X}from"./screenshot/ScreenshotHandler.js";import{EditorConnectionProvider as Y}from"./services/EditorConnectionContext.js";import{EditorActionButtons as $}from"./sidebar/EditorActionButtons.js";import{StateInspector as J}from"./state-inspector/index.js";import{StateHandler as Z}from"./state/StateHandler.js";import{SpaTemplate as _}from"./templates/SpaTemplate.js";import{Templates as ee}from"./templates/Templates.js";import{TemplatesList as ei}from"./templates/TemplatesList.js";import{TunnelProvider as et,useTunnel as eo}from"./tunnel/TunnelContext.js";import{TunnelPanel as en}from"./tunnel/TunnelPanel.js";import{hasTunnelProblem as er}from"./tunnel/tunnel-view-model.js";import{HTML_VARIANT_FRAME_ATTRIBUTE as es,VariantPreviewHandler as ea,useConfiguratorContainerRef as el}from"./variants/VariantPreviewHandler.js";import{VideoStudio as ed}from"./video-studio/VideoStudio.js";import{WebSocketStatus as ec}from"./websocket-status/WebSocketStatus.js";let em=h(()=>e("div",{ref:el(),style:{width:"100%",height:"100%"}})),ep=v(c());export const EditorPanelView={Files:"Files",Reflections:"Reflections",Domain:"Domain",Templates:"Templates",Mocks:"Mocks",Inspector:"Inspector",Debug:"Debug",Profiler:"Profiler",GraphQL:"GraphQL",VideoStudio:"VideoStudio",Analytics:"Analytics",Diagnostics:"Diagnostics",Logs:"Logs",Tunnel:"Tunnel",WebSocketStatus:"WebSocketStatus",Admin:"Admin"};let ef=[{key:EditorPanelView.Templates,icon:"GridFour",title:"Templates"},{key:EditorPanelView.Reflections,icon:"House",title:"Reflections"},{key:EditorPanelView.Files,icon:"List",title:"Files"},{key:EditorPanelView.Domain,icon:"Gear",title:"Domain"},{key:EditorPanelView.Mocks,icon:"TagBold",title:"Mocks"},{key:EditorPanelView.Inspector,icon:"CurrencyDollar",title:"Inspector"},{key:EditorPanelView.Debug,icon:"EyeBold",title:"Debug"},{key:EditorPanelView.Profiler,icon:"Alarm",title:"Profiler"},{key:EditorPanelView.GraphQL,icon:"MagnifyingGlassBold",title:"GraphQL"},{key:EditorPanelView.VideoStudio,icon:"CameraRotate",title:"Video Studio"},{key:EditorPanelView.Analytics,icon:"Flame",title:"Analytics"},{key:EditorPanelView.Diagnostics,icon:"WarningCircle",title:"Diagnostics"},{key:EditorPanelView.Logs,icon:"BracketsCurly",title:"Logs"},{key:EditorPanelView.Tunnel,icon:"ArrowsHorizontal",title:"Webhook Tunnel"}],eh=h(r=>{let{panelView:a,setPanelView:c,width:m,setWidth:p,selectedTemplate:f,setSelectedTemplate:h,isResizing:y,setIsResizing:b,onExit:v,enableAdmin:S}=r,P=D(S),{unreadDiagnosticCount:j,markDiagnosticsRead:A}=z(),{state:M}=eo(),W=a?Math.max(m,240):38,[G,U]=w(0),N=u(()=>U(e=>e+1),[]);return g(()=>{a===EditorPanelView.Diagnostics&&A()},[A,a]),i(o,{component:"div",sx:{display:"grid",gridTemplateColumns:`${W}px min-content auto`,gridTemplateRows:"minmax(0, 1fr)",width:"100vw",height:"100vh",backgroundColor:"#ffffff",overflow:"hidden"},onMouseMove:e=>{y&&p(e.clientX)},onMouseUp:()=>{b(!1)},children:[i(o,{component:"div",sx:{display:"grid",gridTemplateColumns:"36px auto",backgroundColor:"#f8f9fa",borderRight:"1px solid #dee2e6",boxShadow:"2px 0 8px rgba(0, 0, 0, 0.06)",overflow:"hidden",height:"100%"},children:[i("div",{style:{backgroundColor:"#f8f9fa",height:"100%",display:"flex",flexDirection:"column",alignItems:"center",padding:"4px 0"},children:[e("div",{style:{marginBottom:"8px"},children:e(C,{variant:"icon-only"})}),i("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:"2px"},children:[S&&i(t,{children:[e(L,{icon:"SlidersHorizontal",title:"Admin",active:a===EditorPanelView.Admin,onClick:()=>{a===EditorPanelView.Admin?c(null):c(EditorPanelView.Admin)}}),e("div",{style:{borderBottom:"1px solid #dee2e6",margin:"2px 0"}})]}),ef.map(i=>e(L,{icon:i.icon,title:i.title,active:a===i.key,badgeCount:i.key===EditorPanelView.Tunnel?+!!er(M):i.key===EditorPanelView.Diagnostics?j:0,onClick:()=>{a===i.key?c(null):c(i.key)}},i.key))]}),e($,{reload:N}),e("div",{style:{padding:"0 2px",paddingBottom:"4px"},children:e(L,{icon:"CloudArrowUp",title:"WebSocket Status",active:a===EditorPanelView.WebSocketStatus,onClick:()=>{a===EditorPanelView.WebSocketStatus?c(null):c(EditorPanelView.WebSocketStatus)}})}),v&&e("div",{style:{padding:"0 2px",paddingBottom:"8px"},children:e(L,{icon:"SignOut",title:"Exit Editor",variant:"danger",onClick:v})})]}),a&&i(o,{component:"div",sx:{display:"flex",flexDirection:"column",height:"100%",overflow:"hidden",backgroundColor:"#ffffff"},children:[e(o,{component:"div",sx:{p:1.5,borderBottom:"1px solid #e9ecef",backgroundColor:"#ffffff"},children:i(o,{component:"div",sx:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i(o,{component:"div",sx:{display:"flex",flexDirection:"row",alignItems:"center"},children:[e(d,{variant:"h6",sx:{fontSize:16,fontWeight:600,color:"#212529"},children:k(a).with("Files",()=>"Files").with("Reflections",()=>"Reflections").with("Domain",()=>"Domain").with("Templates",()=>"Templates").with("Mocks",()=>"Mocks").with("Inspector",()=>"State Inspector").with("Debug",()=>"Debug").with("Profiler",()=>"Profiler").with("GraphQL",()=>"GraphQL").with("VideoStudio",()=>"Video Studio").with("Analytics",()=>"Analytics").with("Diagnostics",()=>"Diagnostics").with("Logs",()=>"Dev Server Logs").with("Tunnel",()=>"Webhook Tunnel").with("WebSocketStatus",()=>"WebSocket Status").with("Admin",()=>"Admin").otherwise(e=>e)}),e(l,{title:k(a).with("Files",()=>"Browse and inspect loaded GLTF files and their contents").with("Reflections",()=>"Inspect internal Phoenix systems state and configuration").with("Domain",()=>"Edit YAML domain specifications and component configurations").with("Templates",()=>"Select different layout templates for the configurator interface").with("Mocks",()=>"Create and manage mock data for testing session and access configurations").with("Inspector",()=>"Walk the entity tree: fields, expressions, and children").with("Debug",()=>"Toggle scene debug visuals like offset anchors, snapping, and collision meshes").with("Profiler",()=>"Make domain expressions show up as named frames in browser CPU profiles").with("GraphQL",()=>"Run GraphQL queries against the schema generated from the assistant manifest").with("VideoStudio",()=>"Create video sequences by capturing keyframes and exporting as video").with("Analytics",()=>"View parse pipeline metrics, domain stats, and diagnostics").with("Diagnostics",()=>"View latest editor warnings and errors").with("Logs",()=>"View dev server logs: spec builds, webhooks, vite, and browser console").with("Tunnel",()=>"View webhook tunnel status and the requests routed through it").with("WebSocketStatus",()=>"View WebSocket connection status and editor mode information").with("Admin",()=>"Manage admin panel, publish data, and configure settings").otherwise(()=>"Panel information"),placement:"left",arrow:!0,children:e(s,{size:"small",sx:{ml:1,color:"#6c757d",fontSize:14,p:.25,"&:hover":{backgroundColor:"#f8f9fa",color:"#495057"}},children:e(x,{name:"Info",style:{fontSize:14}})})})]}),e(o,{component:"div",sx:{display:"flex",alignItems:"center",gap:1},children:"Templates"===a&&e(n,{label:f.charAt(0).toUpperCase()+f.slice(1),variant:"outlined",size:"small",sx:{backgroundColor:"#f8f9fa",borderColor:"#dee2e6",color:"#495057",fontWeight:500,fontSize:"0.75rem"}})})]})}),i(o,{component:"div",sx:{flex:1,backgroundColor:"#ffffff",overflow:"auto"},children:["Files"===a&&e(K,{}),"Reflections"===a&&e(B,{}),"Domain"===a&&e(F,{}),"Templates"===a&&e(ei,{selectedTemplate:f,onTemplateSelect:h}),"Mocks"===a&&e(q,{}),"Inspector"===a&&e(J,{}),"Debug"===a&&e(R,{}),"Profiler"===a&&e(O,{}),"GraphQL"===a&&e(Q,{}),"VideoStudio"===a&&e(ed,{}),"Analytics"===a&&e(T,{}),"Diagnostics"===a&&e(I,{}),"Logs"===a&&e(H,{}),"Tunnel"===a&&e(en,{}),"WebSocketStatus"===a&&e(ec,{}),S&&"Admin"===a&&e(E,{...P})]})]})]}),e("div",{style:{width:"2px",backgroundColor:"#dee2e6",cursor:"ew-resize",boxShadow:"1px 0 3px rgba(0, 0, 0, 0.05)"},onMouseDown:()=>{b(!0)}}),i("div",{style:{position:"relative",overflow:"hidden"},children:[e("div",{style:{position:"absolute",inset:0,zIndex:+("Admin"!==a)},children:e(ee,{selectedTemplate:f,children:e(em,{},G)})}),S&&e("div",{style:{position:"absolute",inset:0,zIndex:+("Admin"===a)},children:e(V,{})})]})]})}),eu=h(()=>e(_,{children:e(em,{})})),eg=h(o=>{let{wsUrl:n="ws://localhost:3020",localMode:r=!1,domainSpec:s,initialRawProjectFiles:a,onExit:l,mockTemplates:d,autoApplyTemplate:c,environmentKey:h,tagName:u,enableAdmin:k=!0}=o,x=m(p().breakpoints.up("md")),[v,V]=y("editor-width",350),[E,D]=y("editor-view",null),[T,C]=y("editor-template","spa"),[L,R]=w(!1);return g(()=>{null===E||Object.values(EditorPanelView).some(e=>e===E)&&(k||E!==EditorPanelView.Admin)||D(null)},[k,E,D]),e(f,{children:e(b,{maxSnack:5,children:e(j,{children:e(P,{tagName:u,children:e(Y,{initialWsUrl:n,localMode:r,children:e(et,{children:e(S,{children:e(A,{children:e(G,{domainSpec:s,initialRawProjectFiles:a,children:i(U,{mockTemplates:d,autoApplyTemplate:c,environmentKey:h,children:[!r&&i(t,{children:[e(X,{}),e(Z,{}),e(W,{}),e(N,{}),e(M,{})]}),e(ea,{children:x?e(eh,{panelView:E,setPanelView:D,width:v,setWidth:V,selectedTemplate:T,setSelectedTemplate:C,isResizing:L,setIsResizing:R,onExit:l,enableAdmin:k}):e(eu,{})})]})})})})})})})})})})});export const Editor=h(t=>{try{if(window.frameElement?.hasAttribute(es))return e("div",{role:"alert","data-testid":"variant-page-unavailable",style:{padding:24,fontFamily:"sans-serif"},children:"This preview page is unavailable. Ask the agent to recreate it or close the comparison."})}catch{}return i(a,{theme:ep,children:[e(r,{}),e(eg,{...t})]})});
@@ -1 +1 @@
1
- import{jsx as e,jsxs as o}from"react/jsx-runtime";import t from"@monaco-editor/react";import{Box as r,Checkbox as a,FormControlLabel as i,Stack as n,Typography as s}from"@mui/material";import{useState as l}from"react";import{EditorButton as m}from"../common/EditorButton.js";import{jsonEditorOptions as c}from"../common/monaco-config.js";import{useOptionalConfigurator as d,useOptionalDomain as p}from"../hooks/use-optional-runtime.js";import{splitOperations as u}from"./split-operations.js";let h={fontSize:"12px",fontWeight:600,color:"text.secondary"};export const GraphQLPanel=()=>{let f=d()?.graphQLSystem,g=p()?.storeSystem,[x,y]=l("query { root { id type } }"),[b,v]=l(""),[S,k]=l(!1),[j,N]=l(null),[C,w]=l(null),[z,J]=l(!1),O=async()=>{let e=u(x),o=(e=>{if(""===e.trim())return{ok:!0,variables:void 0};try{let o=JSON.parse(e);return"object"!=typeof o||null===o||Array.isArray(o)?{ok:!1,message:"Variables must be a JSON object. Wrap them in {} or clear the field."}:{ok:!0,variables:o}}catch(e){return{ok:!1,message:`Variables are not valid JSON: ${e instanceof Error?e.message:String(e)}. Fix the JSON or clear the field.`}}})(b);if(f){if(w(null),!e.ok)return void N(e.message);if(!o.ok)return void N(o.message);if(S&&!g?.isInitialized)return void N("The configuration is not loaded yet, so there is no state to run against. Run again once the configurator has finished loading.");J(!0);try{let t=e.operations.map(e=>({...e,variables:o.variables})),{results:r,committed:a,message:i}=S&&g?{results:(await f.prepare(g.stateSlices.committed.value.state,t)).map(({result:e})=>e),committed:!1,message:"Dry run: nothing was committed."}:await f.execute(t),n=r.map((o,t)=>({operationName:e.operations[t]?.operationName??null,...o}));N(JSON.stringify(n,null,2)),w(a?"Committed as one undo step.":i??"Nothing was committed.")}finally{J(!1)}}};return o(n,{direction:"column",spacing:1.5,sx:{px:1.5,py:1},children:[e(s,{variant:"subtitle2",sx:h,children:"Query"}),e(r,{component:"div",sx:{height:160,border:"1px solid #dee2e6"},children:e(t,{language:"graphql",value:x,onChange:e=>y(e??""),options:c})}),e(s,{variant:"subtitle2",sx:h,children:"Variables (JSON)"}),e(r,{component:"div",sx:{height:80,border:"1px solid #dee2e6"},children:e(t,{language:"json",value:b,onChange:e=>v(e??""),options:c})}),e(i,{control:e(a,{size:"small",checked:S,onChange:e=>{k(e.target.checked)},sx:{p:.5}}),label:"Dry run",sx:{ml:-.5,mr:0,"& .MuiFormControlLabel-label":{fontSize:"12px",color:"#212529"}}}),e(m,{fullWidth:!0,disabled:!f||z,onClick:()=>void O(),children:f?"Run":"Configurator is not ready"}),null!==C&&e(s,{"data-testid":"graphql-status",sx:{fontSize:"12px",color:"text.secondary"},children:C}),null!==j&&e(r,{component:"pre","data-testid":"graphql-result",sx:{m:0,p:1,fontSize:"12px",backgroundColor:"#f8f9fa",overflow:"auto",whiteSpace:"pre-wrap"},children:j})]})};
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import o from"@monaco-editor/react";import{Box as r,Checkbox as i,FormControlLabel as a,Stack as n,Typography as s}from"@mui/material";import{useState as l}from"react";import{EditorButton as m}from"../common/EditorButton.js";import{jsonEditorOptions as d}from"../common/monaco-config.js";import{useOptionalConfigurator as c,useOptionalDomain as p}from"../hooks/use-optional-runtime.js";import{splitOperations as u}from"./split-operations.js";let h={fontSize:"12px",fontWeight:600,color:"text.secondary"};export const GraphQLPanel=()=>{let f=c()?.graphQLSystem,g=p()?.storeSystem,[x,y]=l("query { root { id type } }"),[b,v]=l(""),[S,k]=l(!1),[j,N]=l(null),[C,w]=l(null),[z,J]=l(!1),O=async()=>{let e=u(x),t=(e=>{if(""===e.trim())return{ok:!0,variables:void 0};try{let t=JSON.parse(e);return"object"!=typeof t||null===t||Array.isArray(t)?{ok:!1,message:"Variables must be a JSON object. Wrap them in {} or clear the field."}:{ok:!0,variables:t}}catch(e){return{ok:!1,message:`Variables are not valid JSON: ${e instanceof Error?e.message:String(e)}. Fix the JSON or clear the field.`}}})(b);if(f){if(w(null),!e.ok)return void N(e.message);if(!t.ok)return void N(t.message);if(S&&!g?.isInitialized)return void N("The configuration is not loaded yet, so there is no state to run against. Run again once the configurator has finished loading.");J(!0);try{let o=e.operations.map(e=>({...e,variables:t.variables})),r=S&&g?await f.prepare(g.stateSlices.committed.value.state,o):void 0,{results:i,committed:a,message:n,sideEffects:s}=r?{results:r.map(({result:e})=>e),committed:!1,message:"Dry run: nothing was committed.",sideEffects:f.readSideEffects(r)}:await f.execute(o),l=i.map((t,o)=>({operationName:e.operations[o]?.operationName??null,...t}));N(JSON.stringify(s.length>0?{results:l,sideEffects:s}:l,null,2)),w(a?"Committed as one undo step.":n??"Nothing was committed.")}finally{J(!1)}}};return t(n,{direction:"column",spacing:1.5,sx:{px:1.5,py:1},children:[e(s,{variant:"subtitle2",sx:h,children:"Query"}),e(r,{component:"div",sx:{height:160,border:"1px solid #dee2e6"},children:e(o,{language:"graphql",value:x,onChange:e=>y(e??""),options:d})}),e(s,{variant:"subtitle2",sx:h,children:"Variables (JSON)"}),e(r,{component:"div",sx:{height:80,border:"1px solid #dee2e6"},children:e(o,{language:"json",value:b,onChange:e=>v(e??""),options:d})}),e(a,{control:e(i,{size:"small",checked:S,onChange:e=>{k(e.target.checked)},sx:{p:.5}}),label:"Dry run",sx:{ml:-.5,mr:0,"& .MuiFormControlLabel-label":{fontSize:"12px",color:"#212529"}}}),e(m,{fullWidth:!0,disabled:!f||z,onClick:()=>void O(),children:f?"Run":"Configurator is not ready"}),null!==C&&e(s,{"data-testid":"graphql-status",sx:{fontSize:"12px",color:"text.secondary"},children:C}),null!==j&&e(r,{component:"pre","data-testid":"graphql-result",sx:{m:0,p:1,fontSize:"12px",backgroundColor:"#f8f9fa",overflow:"auto",whiteSpace:"pre-wrap"},children:j})]})};
@@ -0,0 +1,17 @@
1
+ /** An answer the builder gave, held back for a moment so that a slip can be undone. */
2
+ export interface HeldAnswer {
3
+ readonly secondsLeft: number;
4
+ readonly sending: boolean;
5
+ }
6
+ interface VariantAnswerFooterProps {
7
+ readonly label: string;
8
+ readonly canUse: boolean;
9
+ readonly held: HeldAnswer | null;
10
+ readonly sendError: string | null;
11
+ readonly onUse: () => void;
12
+ readonly onUndo: () => void;
13
+ readonly onSendNow: () => void;
14
+ }
15
+ /** Confirms the displayed option, with a short hold that lets an accidental answer be undone. */
16
+ export declare const VariantAnswerFooter: import("react").MemoExoticComponent<(props: VariantAnswerFooterProps) => import("react/jsx-runtime").JSX.Element>;
17
+ export {};
@@ -0,0 +1 @@
1
+ import{jsx as o,jsxs as e}from"react/jsx-runtime";import{CircularProgress as r,Typography as n}from"@mui/material";import{memo as f}from"react";import{EditorButton as i}from"../common/EditorButton.js";import{INK as t,actionButton as d,ellipsis as l,primaryButton as s}from"./variant-preview-styles.js";export const VariantAnswerFooter=f(f=>{let{label:a,canUse:c,held:x,sendError:p}=f;if(x){let l,s;return e("div",{role:"status",style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:12,boxSizing:"border-box",minHeight:40,padding:"0 12px",borderRadius:6,backgroundColor:t,color:"#ffffff"},children:[x.sending&&o(r,{size:16,"aria-label":"Sending",sx:{color:"#ffffff"}}),o(n,{sx:{flex:"1 1 200px",fontSize:"13px",fontWeight:600},children:(l=`“${a}” goes to the agent`,s=x.sending?" now…":` in ${x.secondsLeft} s.`,`${l}${s}`)}),!x.sending&&o(i,{autoFocus:!0,"data-testid":"variant-undo",onClick:f.onUndo,sx:{...d,backgroundColor:"transparent",border:"2px solid #ffffff",color:"#ffffff","&:hover":{backgroundColor:"rgba(255, 255, 255, 0.12)",borderColor:"#ffffff",color:"#ffffff"}},children:"Undo"}),!x.sending&&o(i,{"data-testid":"variant-send-now",onClick:f.onSendNow,sx:{...d,backgroundColor:"#ffffff",border:"2px solid #ffffff",color:t,"&:hover":{backgroundColor:"#e9ecef",borderColor:"#e9ecef",color:t}},children:"Send now"})]})}return e("div",{children:[o("div",{style:{display:"flex",justifyContent:"flex-end"},children:o(i,{"data-testid":"variant-use",disabled:!c,onClick:f.onUse,sx:{...d,...s,minWidth:0,maxWidth:"100%"},children:e("span",{style:{minWidth:0,...l},children:["Use ",a]})})}),null!==p&&o(n,{role:"alert",sx:{mt:.75,px:.5,fontSize:"13px",color:"#b02a37"},children:p})]})});
@@ -0,0 +1,6 @@
1
+ import { type ReactNode, type RefCallback } from 'react';
2
+ export declare const HTML_VARIANT_FRAME_ATTRIBUTE = "data-phx-html-variant";
3
+ export declare const useConfiguratorContainerRef: () => RefCallback<HTMLDivElement>;
4
+ export declare const VariantPreviewHandler: (props: {
5
+ readonly children: ReactNode;
6
+ }) => import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1 @@
1
+ import{jsx as e,jsxs as t}from"react/jsx-runtime";import{Box as r,Modal as i,Paper as n,Typography as o,useMediaQuery as a}from"@mui/material";import{createContext as l,useCallback as d,useContext as s,useEffect as p,useRef as c,useState as u}from"react";import{useWebComponent as f}from"../EditorRuntimeProvider.js";import{EditorButton as m}from"../common/EditorButton.js";import{importImplementationFile as h}from"../domain-editors/import-implementation-file.js";import{useEditorConnection as v}from"../services/EditorConnectionContext.js";import{trpc as x}from"../services/trpc.js";import{VariantAnswerFooter as g}from"./VariantAnswerFooter.js";import{INK as b,MUTED as w,variantDialogGeometry as y}from"./variant-preview-styles.js";export const HTML_VARIANT_FRAME_ATTRIBUTE="data-phx-html-variant";let E=l(null);export const useConfiguratorContainerRef=()=>{let e=s(E);if(!e)throw Error("The configurator container must be inside VariantPreviewHandler");return e};let I=l=>{let{request:d}=l,s=a("(max-width:899px)"),f=s?y.compact:y.regular,v=x.getVariantBaseline.useQuery({requestId:d.requestId},{refetchOnWindowFocus:!1}),E=x.applyVariantFiles.useMutation(),I=x.submitVariantChoice.useMutation(),[T,C]=u(null),[S,j]=u(!1),[z,R]=u(null),[V,k]=u(null),q=c(!1),A=d.variants.find(e=>e.id===T),H=A?.kind==="page"?A:null,W=A?.label??"Original";p(()=>{v.data&&C(v.data.choice)},[v.data]);let M=async e=>{if(!q.current&&v.data&&!V){q.current=!0,j(!0),R(null);try{let t=new Map,r=d.variants.find(t=>t.id===e);if(r?.kind==="script"){let e=await h(r.url);if("function"!=typeof e)throw Error("Export the variant script as the default function");let i=new Map(v.data.files.map(e=>[e.fileName,e.content]));await e({read:e=>{let t=i.get(e);if(null==t)throw Error(`The baseline has no file named ${e}`);return t},write:(e,r)=>{t.set(e,r)},remove:e=>{t.set(e,null)}})}await E.mutateAsync({requestId:d.requestId,choice:e,files:[...t].map(([e,t])=>({fileName:e,content:t}))}),C(e)}catch(e){R(e instanceof Error?e.message:String(e))}finally{q.current=!1,j(!1)}}},P=async()=>{if(V&&!V.sending){k({...V,sending:!0});try{await I.mutateAsync({requestId:d.requestId,choice:T})}catch(e){R(e instanceof Error?e.message:String(e)),k(null)}}};p(()=>{if(!V||V.sending)return;if(0===V.secondsLeft)return void P();let e=window.setTimeout(()=>{k(e=>e?{...e,secondsLeft:e.secondsLeft-1}:null)},1e3);return()=>window.clearTimeout(e)});let B=[{id:null,label:"Original",description:"The project before these changes."},...d.variants];return e(i,{open:!0,disableEscapeKeyDown:!0,BackdropProps:{sx:{bgcolor:"rgba(33, 37, 41, 0.55)"}},sx:{zIndex:1400},children:t(n,{role:"dialog","aria-labelledby":"variant-preview-title","aria-describedby":"variant-preview-description","aria-modal":"true","data-testid":"variant-preview",elevation:16,sx:{position:"fixed",inset:f.inset,zIndex:1400,borderRadius:"12px",overflow:"hidden",border:"1px solid #dee2e6",display:"grid",gridTemplateRows:`${f.header}px minmax(0, 1fr) ${f.footer}px`,bgcolor:"#fff",pointerEvents:"none"},children:[e(r,{component:"div",sx:{display:"flex",alignItems:"center",gap:2,px:s?2:3,borderBottom:"1px solid #dee2e6",bgcolor:"#fff",pointerEvents:"auto",zIndex:2},children:t(r,{component:"div",sx:{flex:1,minWidth:0},children:[e(o,{id:"variant-preview-title",component:"h2",sx:{fontSize:19,fontWeight:600,color:b,lineHeight:1.35},children:d.title}),e(o,{id:"variant-preview-description",sx:{mt:.5,fontSize:13,color:w},children:d.description})]})}),t(r,{component:"div",sx:{display:"grid",gridTemplateColumns:`${f.choices}px minmax(0, 1fr)`,minHeight:0},children:[t(r,{component:"div",role:"group","aria-label":"Variant options",sx:{p:s?1:2,minHeight:0,overflowY:"auto",borderRight:"1px solid #dee2e6",bgcolor:"#f8f9fa",pointerEvents:"auto",zIndex:2},children:[e(o,{sx:{fontSize:11,fontWeight:600,letterSpacing:"0.06em",color:w,textTransform:"uppercase",mb:1,px:.5},children:"Compare options"}),B.map(r=>{let i=T===r.id;return t(m,{"data-testid":null===r.id?"variant-baseline":"variant-tab","aria-pressed":i,disabled:S||null!==V||!v.data,fullWidth:!0,onClick:()=>{M(r.id)},sx:{display:"block",textAlign:"left",mb:.5,p:s?.875:1.125,whiteSpace:"normal",bgcolor:i?"#e9eef5":"transparent",borderColor:"transparent",boxShadow:i?"inset 2px 0 #495057":"none","&:hover":{bgcolor:i?"#e9eef5":"#eef1f4",borderColor:"#adb5bd"}},children:[e(o,{component:"span",sx:{display:"block",fontSize:13,fontWeight:600,color:b},children:r.label}),e(o,{component:"span",sx:{display:"block",mt:.375,fontSize:11.5,lineHeight:1.35,color:w},children:r.description})]},null===r.id?"original":`variant:${r.id}`)})]}),t("div",{style:{position:"relative",minWidth:0,minHeight:0,zIndex:1},children:[e("div",{ref:H?null:l.previewContainerRef,"data-testid":"variant-configurator",style:{display:H?"none":"block",width:"100%",height:"100%",pointerEvents:"auto"}}),H&&e("iframe",{title:H.label,src:H.url,"data-testid":"variant-html","data-phx-html-variant":"",style:{position:"absolute",inset:0,width:"100%",height:"100%",border:0,pointerEvents:"auto"}},H.id)]})]}),e(r,{component:"div",sx:{px:s?1.5:2,py:1.5,borderTop:"1px solid #dee2e6",bgcolor:"#fff",pointerEvents:"auto",zIndex:2,overflowY:"auto"},children:e(g,{label:W,canUse:void 0!==v.data&&!S&&null===z,held:V,sendError:z??v.error?.message??null,onUse:()=>{R(null),k({secondsLeft:4,sending:!1})},onUndo:()=>k(null),onSendNow:()=>{P()}})})]})})};export const VariantPreviewHandler=r=>{let{localMode:i}=v(),n=f(),[o,a]=u(null),l=c(null),s=c(null),p=d(()=>{let e=s.current??l.current;e&&n&&n.parentNode!==e&&e.appendChild(n)},[n]),m=d(e=>{l.current=e,p()},[p]),h=d(e=>{s.current=e,p()},[p]);return x.onVariantPreview.useSubscription(void 0,{enabled:!i,onData:a}),t(E.Provider,{value:m,children:[r.children,o&&e(I,{request:o,previewContainerRef:h},o.requestId)]})};
@@ -0,0 +1,49 @@
1
+ export declare const INK = "#212529";
2
+ export declare const MUTED = "#5c636a";
3
+ export declare const actionButton: {
4
+ height: number;
5
+ px: number;
6
+ borderRadius: string;
7
+ fontSize: string;
8
+ fontWeight: number;
9
+ whiteSpace: string;
10
+ };
11
+ export declare const primaryButton: {
12
+ backgroundColor: string;
13
+ border: string;
14
+ color: string;
15
+ '&:hover': {
16
+ backgroundColor: string;
17
+ borderColor: string;
18
+ color: string;
19
+ };
20
+ '&:active': {
21
+ backgroundColor: string;
22
+ borderColor: string;
23
+ color: string;
24
+ };
25
+ '&.Mui-disabled': {
26
+ backgroundColor: string;
27
+ borderColor: string;
28
+ color: string;
29
+ };
30
+ };
31
+ export declare const ellipsis: {
32
+ readonly overflow: 'hidden';
33
+ readonly textOverflow: 'ellipsis';
34
+ readonly whiteSpace: 'nowrap';
35
+ };
36
+ export declare const variantDialogGeometry: {
37
+ readonly regular: {
38
+ readonly inset: 24;
39
+ readonly header: 80;
40
+ readonly footer: 68;
41
+ readonly choices: 240;
42
+ };
43
+ readonly compact: {
44
+ readonly inset: 8;
45
+ readonly header: 96;
46
+ readonly footer: 112;
47
+ readonly choices: 156;
48
+ };
49
+ };
@@ -0,0 +1 @@
1
+ export const INK="#212529";export const MUTED="#5c636a";export const actionButton={height:40,px:2,borderRadius:"6px",fontSize:"13px",fontWeight:500,whiteSpace:"nowrap"};export const primaryButton={backgroundColor:INK,border:`1px solid ${INK}`,color:"#ffffff","&:hover":{backgroundColor:"#343a40",borderColor:"#343a40",color:"#ffffff"},"&:active":{backgroundColor:"#495057",borderColor:"#495057",color:"#ffffff"},"&.Mui-disabled":{backgroundColor:"#adb5bd",borderColor:"#adb5bd",color:"#ffffff"}};export const ellipsis={overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"};export const variantDialogGeometry={regular:{inset:24,header:80,footer:68,choices:240},compact:{inset:8,header:96,footer:112,choices:156}};
@@ -1 +1 @@
1
- import{existsSync as e,lstatSync as i,readFileSync as t,readdirSync as r,rmSync as o,unlinkSync as s}from"fs";import{join as n}from"path";import{format as l}from"prettier";import{prettierrc as a}from"@salsita-ai/common/prettier";import{GeneratedApplication as c,GeneratedApplicationFile as p,RuntimeReferenceStore as g,buildPhoenixDefinitions as f,createContentDiffTracker as h,generateApplicationCode as m,parseApplicationFiles as d}from"#package/application-spec";import{getAllPhxDefinitions as u}from"#package/domain";import{compileWithSwc as S}from"../services/swc.js";import{syncChangedFiles as b}from"../utils/index.js";import{readApplicationFiles as w}from"./application-spec-file-reader.js";import{cleanStaleAgentSkills as j,removeProjectFiles as D}from"./clean-project-files.js";import{swcEvalExpressionParser as F,swcModuleAnalyzer as x}from"./swc-module-analyzer.js";let P=".phoenix",k=`${P}/`,v=async e=>{if(e.binary||!1===e.format)return e;try{let i=await l(e.content,{...a,filepath:e.path});return p(e.path,i,{binary:e.binary,format:e.format})}catch{return e}},y=async e=>{let[i,t,r]=await Promise.all([Promise.all(e.generatedProjectFiles.map(v)),Promise.all(e.initialProjectFiles.map(v)),Promise.all(e.prettierFiles.map(v))]);return c({files:e.files,generatedProjectFiles:i,initialProjectFiles:t,prettierFiles:r,removedProjectFiles:e.removedProjectFiles})};export class ApplicationSpecBuilder{contentDiff;referenceStore;config;logger;phxDefinitions;constructor(e){this.config=e,this.logger=e.logger,this.referenceStore=new g,this.contentDiff=h({readDiskContent:this.readDiskContent}),this.phxDefinitions=f(u())}async build(e){let i=e?.parsingContext,t=e?.compile??!0;e?.force&&this.referenceStore.clear();let r=i?.startSpan("readFiles","build","application-spec-builder.ts"),o=e?.rawProjectFiles??await w({envs:{}});r?.();let s=d({rawProjectFiles:o,phxDefinitions:this.phxDefinitions},{analyzer:x,evalExpressionParser:F,referenceStore:this.referenceStore,logger:this.logger,parsingContext:i});if(!s.ok)return{ok:!1,rawProjectFiles:o,errors:s.errors,diagnostics:s.diagnostics,metrics:s.metrics,counts:s.counts};let{applicationSpec:n,categorizedFiles:l,rawMockTemplates:a}=s.value,c=i?.startSpan("generateCode","build","application-spec-builder.ts"),p=m({applicationSpec:n,categorizedFiles:l,phxDefinitions:this.phxDefinitions,sdkVersion:this.config.sdkVersion,cliUseWorkspace:this.config.cliUseWorkspace,name:this.config.name,description:this.config.description,projectSlug:this.config.projectSlug,environmentSlug:this.config.environmentSlug,enableEditor:this.config.enableEditor,inlineTemplates:this.config.inlineTemplates,rawMockTemplates:a});c?.();let g=i?.startSpan("cleanStaleFiles","build","application-spec-builder.ts"),f=new Set(p.files.map(e=>e.path));this.cleanStaleGeneratedFiles(f),D(p.removedProjectFiles,{logger:this.logger}),j(new Set(p.generatedProjectFiles.map(e=>e.path)),{logger:this.logger}),g?.();let h=i?.startSpan("contentDiff","build","application-spec-builder.ts"),u=await y(p),S=this.contentDiff.getChangedApplicationFiles(u,{generatedFilesPathPrefix:k,force:e?.force}),P=S.changedGeneratedFiles;h?.(),P.length>0?this.logger.info(` ${P.length}/${p.files.length} generated files changed`):this.logger.info(" No generated files changed");let v=S.filesToWrite.length-P.length;v>0&&this.logger.info(` ${v} project files changed`);let C=i?.startSpan("writeFiles","build","application-spec-builder.ts");return await b(S.filesToWrite,{logger:this.logger,skipChecksum:!0}),C?.(),t&&await this.compile(i),{ok:!0,application:s.value,changedFiles:P,diagnostics:s.diagnostics,metrics:s.metrics,counts:s.counts}}async compile(e){let i=e?.startSpan("swcCompile(src)","build","application-spec-builder.ts");await S({sourceDir:"src",outDir:`./${P}/.swc/src`},{logger:this.logger}),i?.();let t=e?.startSpan("swcCompile(.phoenix)","build","application-spec-builder.ts");await S({sourceDir:P,outDir:`./${P}/.swc/${P}`},{logger:this.logger}),t?.()}readDiskContent=i=>{try{if(e(i))return t(i,"utf-8")}catch{}};cleanStaleGeneratedFiles(t){let l=new Set(["public",".swc","dist","phoenix-dev.log","phoenix-dev.log.1","phoenix-dev.log.2"]);try{if(!e(P))return;for(let e of r(P)){if(l.has(e)||t.has(e))continue;let r=n(P,e);try{let e=i(r);if(e.isSymbolicLink())continue;e.isDirectory()?o(r,{recursive:!0}):s(r),this.logger.debug(` Removed stale: ${r}`)}catch{}}}catch{}}}
1
+ import{existsSync as e,lstatSync as i,readFileSync as t,readdirSync as r,rmSync as o,unlinkSync as s}from"fs";import{join as n}from"path";import{format as a}from"prettier";import{prettierrc as l}from"@salsita-ai/common/prettier";import{GeneratedApplication as c,GeneratedApplicationFile as p,RuntimeReferenceStore as g,buildPhoenixDefinitions as f,createContentDiffTracker as h,generateApplicationCode as m,parseApplicationFiles as d}from"#package/application-spec";import{getAllPhxDefinitions as u}from"#package/domain";import{compileWithSwc as S}from"../services/swc.js";import{syncChangedFiles as b}from"../utils/index.js";import{readApplicationFiles as w}from"./application-spec-file-reader.js";import{cleanStaleAgentSkills as j,removeProjectFiles as v}from"./clean-project-files.js";import{swcEvalExpressionParser as D,swcModuleAnalyzer as F}from"./swc-module-analyzer.js";let x=".phoenix",y=`${x}/`,P=async e=>{if(e.binary||!1===e.format)return e;try{let i=await a(e.content,{...l,filepath:e.path});return p(e.path,i,{binary:e.binary,format:e.format})}catch{return e}},k=async e=>{let[i,t,r]=await Promise.all([Promise.all(e.generatedProjectFiles.map(P)),Promise.all(e.initialProjectFiles.map(P)),Promise.all(e.prettierFiles.map(P))]);return c({files:e.files,generatedProjectFiles:i,initialProjectFiles:t,prettierFiles:r,removedProjectFiles:e.removedProjectFiles})};export class ApplicationSpecBuilder{contentDiff;referenceStore;config;logger;phxDefinitions;constructor(e){this.config=e,this.logger=e.logger,this.referenceStore=new g,this.contentDiff=h({readDiskContent:this.readDiskContent}),this.phxDefinitions=f(u())}async build(e){let i=e?.parsingContext,t=e?.compile??!0;e?.force&&this.referenceStore.clear();let r=i?.startSpan("readFiles","build","application-spec-builder.ts"),o=e?.rawProjectFiles??await w({envs:{}});r?.();let s=d({rawProjectFiles:o,phxDefinitions:this.phxDefinitions},{analyzer:F,evalExpressionParser:D,referenceStore:this.referenceStore,logger:this.logger,parsingContext:i});if(!s.ok)return{ok:!1,rawProjectFiles:o,errors:s.errors,diagnostics:s.diagnostics,metrics:s.metrics,counts:s.counts};let{applicationSpec:n,categorizedFiles:a,rawMockTemplates:l}=s.value,c=i?.startSpan("generateCode","build","application-spec-builder.ts"),p=m({applicationSpec:n,categorizedFiles:a,phxDefinitions:this.phxDefinitions,sdkVersion:this.config.sdkVersion,cliUseWorkspace:this.config.cliUseWorkspace,name:this.config.name,description:this.config.description,projectSlug:this.config.projectSlug,environmentSlug:this.config.environmentSlug,enableEditor:this.config.enableEditor,inlineTemplates:this.config.inlineTemplates,rawMockTemplates:l});c?.();let g=i?.startSpan("cleanStaleFiles","build","application-spec-builder.ts"),f=new Set(p.files.map(e=>e.path));this.cleanStaleGeneratedFiles(f),v(p.removedProjectFiles,{logger:this.logger}),j(new Set(p.generatedProjectFiles.map(e=>e.path)),{logger:this.logger}),g?.();let h=i?.startSpan("contentDiff","build","application-spec-builder.ts"),u=await k(p),S=this.contentDiff.getChangedApplicationFiles(u,{generatedFilesPathPrefix:y,force:e?.force}),x=S.changedGeneratedFiles;h?.(),x.length>0?this.logger.info(` ${x.length}/${p.files.length} generated files changed`):this.logger.info(" No generated files changed");let P=S.filesToWrite.length-x.length;P>0&&this.logger.info(` ${P} project files changed`);let C=i?.startSpan("writeFiles","build","application-spec-builder.ts");return await b(S.filesToWrite,{logger:this.logger,skipChecksum:!0}),C?.(),t&&await this.compile(i),{ok:!0,application:s.value,changedFiles:x,diagnostics:s.diagnostics,metrics:s.metrics,counts:s.counts}}async compile(e){let i=e?.startSpan("swcCompile(src)","build","application-spec-builder.ts");await S({sourceDir:"src",outDir:`./${x}/.swc/src`},{logger:this.logger}),i?.();let t=e?.startSpan("swcCompile(.phoenix)","build","application-spec-builder.ts");await S({sourceDir:x,outDir:`./${x}/.swc/${x}`},{logger:this.logger}),t?.()}readDiskContent=i=>{try{if(e(i))return t(i,"utf-8")}catch{}};cleanStaleGeneratedFiles(t){let a=new Set(["public",".swc","dist","phoenix-dev.log","phoenix-dev.log.1","phoenix-dev.log.2","variants","variant-recovery.json"]);try{if(!e(x))return;for(let e of r(x)){if(a.has(e)||t.has(e))continue;let r=n(x,e);try{let e=i(r);if(e.isSymbolicLink())continue;e.isDirectory()?o(r,{recursive:!0}):s(r),this.logger.debug(` Removed stale: ${r}`)}catch{}}}catch{}}}
@@ -6,7 +6,8 @@ import type { AssistantSpec } from '#package/application-spec';
6
6
  * about changes is left out when the schema has no `Mutation` type, the part about adding
7
7
  * entities when it has no `addChild` mutation, the part about replacing them when it has no
8
8
  * `replaceEntity` mutation, the part about the choices of a field when it has
9
- * no options edge, and the part about custom changes when the manifest exposes no action. The last section explains the
10
- * `query` and `apply` tools, which every run registers whatever the schema holds.
9
+ * no options edge, and the part about custom changes when the manifest exposes no action. The last two sections explain the
10
+ * `query` and `apply` tools, which every run registers whatever the schema holds, and the change
11
+ * record the `AssistantSystem` attaches to every user message.
11
12
  */
12
13
  export declare const generateAssistantPrompt: (assistant: NonNullable<AssistantSpec>) => string;
@@ -1 +1 @@
1
- let e=["How to read the GraphQL schema of this configurator:","- A configuration is a set of entities. `root` is the root entity, `entities` lists every entity or the ones with the given ids, and `selectedEntity` is the entity the user has selected, or the root entity when nothing is selected.","- Every entity has an `id` of the form `<Type>-<number>`, for example `Table-1`, and a `type` with its entity type name. Ids are assigned by the configurator: read them from the configuration and never make one up.","- A field whose name starts with `_` is computed by the configurator from other values. It can be read like any other field and never written.","- Numbers are in the units the configuration stores them in. A field description names the unit when the product defines one.",'- A text field that only takes fixed values lists them in its description as "One of: ...". Use exactly those values.',"- A field typed as another entity type or as a list of one is a relation: select fields on it to read the related entities.","- Field and type descriptions come from the team that built the configurator and say what a value means for the product."],t=["How changes work:","- Every field of the `Mutation` type is one change. Its description says what it changes and what it returns.","- The configurator checks the whole configuration after each change. A change that would leave it invalid fails with an error that names the entities at fault, and it is not applied. Later changes of the same request are then not run.","- The configurator may adjust other values in response to a change, so read what a mutation returns instead of assuming the values you sent."],a=["How to add entities:","- Entities are added from recipes, the same ones the configurator offers the user. An entity type that can take children has a `meta` field; `meta { childRecipes }` lists its recipe groups and their recipes.","- List the recipes of the group first, pick one by its `key`, then call `addChild` with the id of the parent, the `groupId` and the `key`. Keys change with the configuration and the language, so never reuse one from memory.","- `dryRun` on a recipe shows what adding it would do without adding it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, and the `errors` when it cannot be added. An entity whose id the configuration does not have yet is new. It is costly, so select it only on the recipes you are deciding between.","- Put each `addChild` in its own operation. The recipes of a group and what they add depend on the configuration before them, so after adding something, list the group again before adding from it once more."],n=["How to replace entities:","- An entity is replaced from recipes, the same ones the configurator offers the user. An entity type that can be replaced has a `meta` field; `meta { replaceRecipes }` lists its replace recipe groups and what the entity can be replaced with.","- List the recipes of the group first, pick one by its `key`, then call `replaceEntity` with the id of the entity, the `groupId` and the `key`. `dryRun` on a replace recipe shows what replacing would do without doing it: the replacement and everything else that changes are under `changedEntities`, and the replaced entity is among the `deletedEntityIds`.","- The replacement is a new entity with a new id, and its field values come from the recipe, so they can differ from those of the entity it replaces. Read the ids and values `replaceEntity` returns, and never use the old id again.","- Put each `replaceEntity` in its own operation. The recipes of a group and what they do depend on the configuration before them, so after replacing something, list the group of the replacement again before replacing once more."],i=["How to find the values a field can take:","- Some fields store a key whose choices the configurator holds elsewhere. Such a field has an edge under `meta` named after it: `meta { <field>Options }` lists its choices, each with the `value` to write and the `name` the user sees.","- Read the choices before you write such a field or name a choice to the user, and write the `value`, not the `name`. A value outside the list is rejected unless the edge description says the field is not checked.","- `dryRun` on an option shows what writing its value would do without writing it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, and the `errors` when the value cannot be written. It is costly, so select it only on the options you are deciding between. It is null when the edge description says the options cannot be dry-run.","- The choices can depend on the entity and on its current state. Read them again after a change, unless the edge description says they are the same for all instances or do not change."],o=["How the custom changes of this configurator work:","- Besides the generic changes, the `Mutation` type has fields the team built for this product. Each runs one domain operation the configurator itself uses, so prefer it over composing the same change from generic mutations. Its description says what it does and what its arguments mean.","- Its arguments are checked against what the operation declares; an argument that does not fit, or a change the product does not allow, fails the field with a message that says what to send instead.","- It returns an object whose fields the description names; a field typed as an entity reads that entity after the change."],s=["How to use the `query` and `apply` tools:","- Both take `operations`, a list of GraphQL documents that run in order. Each document holds exactly one operation. To do several things, send several items in one call instead of several calls.","- Write values into the document as literals. Use `variables` only for a value that cannot be written as a literal.","- Select only the fields you need: results are returned whole.","- The result has one GraphQL result per operation, in the order sent. When an operation fails, its `errors` say why and the operations after it are not run.","- `query` reads the configuration the user has open and never changes it. Call it before you say anything about the configuration."],r=["- This configurator exposes no changes, so there is nothing for `apply` to run. Say so when the user asks you to change the configuration."],h=['- Mutations inside `query` answer "what if" questions. Each operation sees the changes of the ones before it, so a mutation followed by a query shows the configuration as it would be. Nothing is kept and the user sees no change.',"- `apply` makes the changes the user asked for. It is all or nothing: when any operation fails, nothing is changed; when all succeed, the user gets them as one undo step.","- `committed` in the result says whether the changes were kept. When it is false although no operation failed, `message` says why: the changes may be waiting for the approval of the user, the user may have changed the configuration meanwhile, or this session may not change the configuration at all. Without a `message`, the operations changed nothing. Never tell the user a change was made unless `committed` is true."];export const generateAssistantPrompt=d=>{let c=/^type Mutation\b/m.test(d.sdl);return[e,...c?[t]:[],.../^\s+addChild\(/m.test(d.sdl)?[a]:[],.../^\s+replaceEntity\(/m.test(d.sdl)?[n]:[],.../^type FieldOption\b/m.test(d.sdl)?[i]:[],...Object.keys(d.actions).length>0?[o]:[],[...s,...c?h:r]].map(e=>e.join("\n")).join("\n\n")};
1
+ let e=["How to read the GraphQL schema of this configurator:","- A configuration is a set of entities. `root` is the root entity, `entities` lists every entity or the ones with the given ids, and `selectedEntity` is the entity the user has selected, or the root entity when nothing is selected.","- Every entity has an `id` of the form `<Type>-<number>`, for example `Table-1`, and a `type` with its entity type name. Ids are assigned by the configurator: read them from the configuration and never make one up.","- A field whose name starts with `_` is computed by the configurator from other values. It can be read like any other field and never written.","- Numbers are in the units the configuration stores them in. A field description names the unit when the product defines one.",'- A text field that only takes fixed values lists them in its description as "One of: ...". Use exactly those values.',"- A field typed as another entity type or as a list of one is a relation: select fields on it to read the related entities.","- Field and type descriptions come from the team that built the configurator and say what a value means for the product."],t=["How changes work:","- Every field of the `Mutation` type is one change. Its description says what it changes and what it returns.","- The configurator checks the whole configuration after each change. A change that would leave it invalid fails with an error that names the entities at fault, and it is not applied. Later changes of the same request are then not run.","- The configurator may adjust other values in response to a change, so read what a mutation returns instead of assuming the values you sent."],a=["How to add entities:","- Entities are added from recipes, the same ones the configurator offers the user. An entity type that can take children has a `meta` field; `meta { childRecipes }` lists its recipe groups and their recipes.","- List the recipes of the group first, pick one by its `key`, then call `addChild` with the id of the parent, the `groupId` and the `key`. Keys change with the configuration and the language, so never reuse one from memory.","- `dryRun` on a recipe shows what adding it would do without adding it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, the `sideEffects` the configurator says it would have, and the `errors` when it cannot be added. An entity whose id the configuration does not have yet is new. It is costly, so select it only on the recipes you are deciding between.","- Put each `addChild` in its own operation. The recipes of a group and what they add depend on the configuration before them, so after adding something, list the group again before adding from it once more."],n=["How to replace entities:","- An entity is replaced from recipes, the same ones the configurator offers the user. An entity type that can be replaced has a `meta` field; `meta { replaceRecipes }` lists its replace recipe groups and what the entity can be replaced with.","- List the recipes of the group first, pick one by its `key`, then call `replaceEntity` with the id of the entity, the `groupId` and the `key`. `dryRun` on a replace recipe shows what replacing would do without doing it: the replacement and everything else that changes are under `changedEntities`, and the replaced entity is among the `deletedEntityIds`.","- The replacement is a new entity with a new id, and its field values come from the recipe, so they can differ from those of the entity it replaces. Read the ids and values `replaceEntity` returns, and never use the old id again.","- Put each `replaceEntity` in its own operation. The recipes of a group and what they do depend on the configuration before them, so after replacing something, list the group of the replacement again before replacing once more."],o=["How to find the values a field can take:","- Some fields store a key whose choices the configurator holds elsewhere. Such a field has an edge under `meta` named after it: `meta { <field>Options }` lists its choices, each with the `value` to write and the `name` the user sees.","- Read the choices before you write such a field or name a choice to the user, and write the `value`, not the `name`. A value outside the list is rejected unless the edge description says the field is not checked.","- `dryRun` on an option shows what writing its value would do without writing it: whether it is `ok`, the `changedEntities` it would add or modify, the `deletedEntityIds` it would remove, the `sideEffects` the configurator says it would have, and the `errors` when the value cannot be written. It is costly, so select it only on the options you are deciding between. It is null when the edge description says the options cannot be dry-run.","- The choices can depend on the entity and on its current state. Read them again after a change, unless the edge description says they are the same for all instances or do not change."],i=["How the custom changes of this configurator work:","- Besides the generic changes, the `Mutation` type has fields the team built for this product. Each runs one domain operation the configurator itself uses, so prefer it over composing the same change from generic mutations. Its description says what it does and what its arguments mean.","- Its arguments are checked against what the operation declares; an argument that does not fit, or a change the product does not allow, fails the field with a message that says what to send instead.","- It returns an object whose fields the description names; a field typed as an entity reads that entity after the change."],s=["How to use the `query` and `apply` tools:","- Both take `operations`, a list of GraphQL documents that run in order. Each document holds exactly one operation. To do several things, send several items in one call instead of several calls.","- Write values into the document as literals. Use `variables` only for a value that cannot be written as a literal.","- Select only the fields you need: results are returned whole.","- The result has one GraphQL result per operation, in the order sent. When an operation fails, its `errors` say why and the operations after it are not run.","- `query` reads the configuration the user has open and never changes it. Call it before you say anything about the configuration."],h=["- This configurator exposes no changes, so there is nothing for `apply` to run. Say so when the user asks you to change the configuration."],r=['- Mutations inside `query` answer "what if" questions. Each operation sees the changes of the ones before it, so a mutation followed by a query shows the configuration as it would be. Nothing is kept and the user sees no change.',"- `apply` makes the changes the user asked for. It is all or nothing: when any operation fails, nothing is changed; when all succeed, the user gets them as one undo step.","- `committed` in the result says whether the changes were kept. When it is false although no operation failed, `message` says why: the changes may be waiting for the approval of the user, the user may have changed the configuration meanwhile, or this session may not change the configuration at all. Without a `message`, the operations changed nothing. Never tell the user a change was made unless `committed` is true.","- `sideEffects` in the result lists what the configurator did beyond what the operations asked for, such as parts it added or replaced to keep the configuration valid, in its own words. Tell the user about them when the changes were kept. When they were not, or in `query`, it lists what the mutations that succeeded would do. `dryRun` has the same list for a single recipe or option."],d=["How to read the change record:","- Every user message starts with a change record of the configuration since your previous action. It is the complete list of the entities that were added or deleted, of the stored fields of this schema that changed, and of the selection and navigation changes, so update your picture from it and do not query those again when it does not mention them.","- Fields whose name starts with `_` are computed and are never listed. Read them again when the record lists a change they may depend on.","- `[changes: none]`: nothing changed. Do not query again what you already know.","- `[changes]` is followed by one line per change. `selected`, `navigationState`, `viewState` and `toolState` lines show `<old> -> <new>` of what `selectedEntity` and `navigation` return, with `none` for an empty value. `A <id>` is an added entity and `D <id>` a deleted one. `M <id>` is a modified entity, followed by one `<field>: <old> -> <new>` line per changed field, under the name the field has in this schema. A `reset: undo/redo` line says the user undid or redid changes.","- The `#` comment at the end of a line names the control, the transformer or the explanation of the last change to that line.","- `[changes: unavailable]`: the page was loaded since your previous action, so earlier values may be stale. `[changes: too many (n)]`: n entities changed and are not listed. In both cases query what you need."],c=["- Changes you applied are not in the record, except those that were waiting for the approval of the user: they appear in it once approved."];export const generateAssistantPrompt=l=>{let u=/^type Mutation\b/m.test(l.sdl);return[e,...u?[t]:[],.../^\s+addChild\(/m.test(l.sdl)?[a]:[],.../^\s+replaceEntity\(/m.test(l.sdl)?[n]:[],.../^type FieldOption\b/m.test(l.sdl)?[o]:[],...Object.keys(l.actions).length>0?[i]:[],[...s,...u?r:h],[...d,...u?c:[]]].map(e=>e.join("\n")).join("\n\n")};