@salsita-ai/sdk 0.49.0-develop.f5fc5cfc25 → 0.49.0
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.
- package/CHANGELOG.md +479 -0
- package/dist/application-spec/generate-application/code/templates/env-example.js +1 -0
- package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.d.ts +6 -3
- package/dist/application-spec/parse-application-files/raw-spec/raw-assistant.js +1 -1
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-field-type.js +1 -1
- package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts +32 -32
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js +1 -1
- package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js +1 -1
- package/dist/docs/index.json +1 -1
- package/dist/docs/phoenix/csp.mdx +6 -2
- package/dist/docs/phoenix/phoenix-cli.mdx +14 -13
- package/dist/domain/application/application-config.d.ts +3 -1
- package/dist/domain/application/assistant-mutations.d.ts +1 -1
- package/dist/domain/application/assistant-mutations.js +1 -1
- package/dist/legacy/domain-cli/utils/cache.d.ts +1 -1
- package/dist/legacy/domain-cli/utils/cache.js +1 -1
- package/dist/legacy/phoenix-cli/commands/dev.d.ts +2 -0
- package/dist/legacy/phoenix-cli/commands/dev.js +5 -5
- package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/env-example.d.ts +1 -1
- package/dist/legacy/phoenix-cli/project-gen/generators/file-templates/env-example.js +1 -0
- package/dist/phoenix/application-spec/generate-assistant-prompt.js +1 -1
- package/dist/phoenix/cli.js +1 -1
- package/package.json +3 -3
package/dist/application-spec/parse-application-files/spec/sections/assistant/assistant-schema.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GraphQLBoolean as e,GraphQLID as t,GraphQLInputObjectType as n,GraphQLInterfaceType as i,GraphQLList as r,GraphQLNonNull as o,GraphQLObjectType as s,GraphQLSchema as a,GraphQLString as p,getNullableType as l,isInputType as d,printSchema as c,validateSchema as h}from"graphql";import{DiagnosticCode as f,diagnosticMessages as y}from"../../../../errors/index.js";import{ASSISTANT_HINTS as u}from"../../../raw-spec/index.js";import{GraphQLJSON as g,assistantFieldType as m,createAssistantRefResolver as S}from"./assistant-field-type.js";let T="AnyDomainEntity",w="RootEntity",N="RecipeGroup",E="Recipe",A="RecipeDryRun",_="RecipeDryRunError",I="FieldOption",O={section:"childRecipes",component:"childEntityRecipes",mutation:"addChild"},v={section:"replaceRecipes",component:"replaceEntityRecipes",mutation:"replaceEntity"},b=new Set(["id","type","meta"]),$=new Set(["Query","Mutation","Navigation",N,E,A,_,I,"JSON","String","Int","Float","Boolean","ID"]),R=(e,t)=>{if(!t||0===t.length)return e;let n=`One of: ${t.map(e=>`"${e}"`).join(", ")}.`;return e?/[.!?]$/.test(e)?`${e} ${n}`:`${e}. ${n}`:n},M=new Set(["id","type"]),j="The raw stored value: a string, a message descriptor or a multilingual object.",D=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],P=(e,t,{model:n,components:i})=>{let r=new Set([e,...[...n.aliases].filter(([,t])=>t.includes(e)).map(([e])=>e)]);return i.filter(({componentName:e,typeOrAlias:n})=>e===t&&r.has(n)).map(({instanceName:e})=>String(e))},U=(...e)=>u.filter(t=>e.some(e=>e?.includes(t))),C=(e,t,n,i)=>{let{model:r}=n,o=new Map,s=new Map;for(let[a,{groups:p,hints:l}]of Object.entries(e)){let e=r.entityTypes.find(e=>e===a),d=e?[e]:[...r.aliases].find(([e])=>e===a)?.[1];if(!d){i.at(a).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE(t.section,a));continue}for(let[e,r]of(d.forEach(e=>s.set(e,U(s.get(e),l))),Object.entries(p))){let s=i.at(a,"groups",e),p=`${a}.groups.${e}`,l={groupId:r?.as??e,instanceName:e,...r?.description===void 0?{}:{description:r.description},dryRuns:r?.allowDryRuns??!0};for(let i of d){let r=P(i,t.component,n),d=o.get(i)??[],c=d.find(e=>e.group.groupId===l.groupId);r.includes(e)?c?s.error(f.ASSISTANT_DUPLICATE_RECIPE_GROUP,y.ASSISTANT_DUPLICATE_RECIPE_GROUP(t,i,l.groupId,[c.entry,p])):o.set(i,[...d,{group:l,entry:p,entryCtx:s}]):s.error(f.ASSISTANT_UNKNOWN_RECIPE_GROUP,y.ASSISTANT_UNKNOWN_RECIPE_GROUP(t,a,e,i,r))}}}let a=r.entityTypes.flatMap(e=>{let t=o.get(e);return t?[{entityType:e,groups:t}]:[]});return{groups:Object.fromEntries(a.map(({entityType:e,groups:t})=>[e,t.map(({group:e})=>e)])),hints:s,metaEntries:new Map(a.flatMap(({entityType:e,groups:[t]})=>t?[[e,t.entryCtx]]:[]))}},k=e=>`${e}Meta`,W={sameForAllInstances:e=>`All ${e} instances have the same recipe groups and recipes.`,stable:()=>"They do not change during the session."},L={sameForAllInstances:e=>`All ${e} instances have the same options.`,stable:()=>"The options do not change during the session."},F=(e,t,n)=>e.map(e=>` ${t[e](n)}`).join(""),K=({section:e},{groups:t,hints:n},{entityType:i,purpose:s,recipeGroup:a})=>{let p=t.filter(({dryRuns:e})=>!e).map(({groupId:e})=>e);return 0===t.length?{}:{[e]:{type:new o(new r(new o(a))),description:`The recipe groups for ${s} this ${i}: ${t.map(({groupId:e})=>e).join(", ")}. A group is listed only while the configurator offers it on the entity.${p.length>0?` Recipes of these groups cannot be dry-run: ${p.join(", ")}.`:""}${F(n,W,i)}`}}},G=({entityType:e,childRecipes:t,replaceRecipes:n,optionsEdges:i},{recipeGroup:a,fieldOption:p})=>new s({name:k(e),fields:Object.assign(K(O,t,{entityType:e,purpose:"adding children to",recipeGroup:a}),K(v,n,{entityType:e,purpose:"replacing",recipeGroup:a}),...i.map(({options:{edgeName:t,field:n,validate:i},hints:s})=>({[t]:{type:new r(new o(p)),description:`The values "${n}" of this ${e} can take, as the configurator offers them in the current state of the entity. Null when the configurator does not offer a choice on this entity. ${i?`modify${e} rejects a "${n}" value that is not in the list.`:`modify${e} does not check "${n}" against the list.`}${F(s,L,e)}`}})))}),Y=e=>Object.entries(e).map(([e,t])=>`${e} (${t.map(({groupId:e})=>e).join(", ")})`),V=(e,t)=>{let{type:n,enumValues:i,localized:r,description:o}=m(e,t);return{type:{kind:"value",type:n},localized:!0===r,description:o,enumValues:i}},x=(e,t,n,i,r)=>{let o=t.startsWith("$")?((e,t,n,i)=>{let r=((e,t,{expressions:n,entityTypes:i})=>{let r=i.find(t=>t===e);for(let i of void 0===r?[e]:n.entityExpressions.get(r)?.shapeGroups??[]){let e=[...n.expressions.get(i)?.values()??[]].find(e=>e.name===t);if(e?.declaredSchema)return{implementation:e.implementation,declaredSchema:e.declaredSchema}}})(e.name,t,n);if(!r)return void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t));let{implementation:o}=r;if("violations"===o.kind)return void i.error(f.ASSISTANT_UNSUPPORTED_EXPRESSION,y.ASSISTANT_UNSUPPORTED_EXPRESSION(e.name,t));if("relation"===o.kind){let[{target:e,cardinality:t}]=o.params;return{type:{kind:"edge",target:e,cardinality:t},localized:!1,description:void 0}}return V(r.declaredSchema,n.resolveRef)})(e,t,i,r):((e,t,{resolveRef:n},i)=>{let r=Object.entries(e.shape.properties).find(([e])=>e===t)?.[1];return r?V(r,n):void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t))})(e,t,i,r);if(!o)return;let s=n?.as??(t.startsWith("$")?`_${t.slice(1)}`:t);return b.has(s)?void r.error(f.ASSISTANT_RESERVED_FIELD_NAME,y.ASSISTANT_RESERVED_FIELD_NAME(e.name,t,s)):{name:s,source:t,type:o.type,localized:o.localized,description:R(n?.description??o.description,o.enumValues),describedByManifest:n?.description!==void 0}},B=(e,t,n,i)=>{let r=new Map,o=new Set(n);for(let s of[...t.flat(),...n]){let t=r.get(s.name);t?t.source!==s.source?i.error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,s.name,[t.source,s.source])):o.has(s)&&s.describedByManifest&&r.set(s.name,{...t,description:s.description,describedByManifest:!0}):r.set(s.name,s)}return[...r.values()]},q=({target:e,cardinality:t},n)=>{let i=n(e);switch(t){case"1-1":return new o(i);case"0-1":return i;case"0-N":case"1-N":return new o(new r(new o(i)))}},z=(e,n,i)=>{let r={id:{type:new o(t),description:i?`Unique id of the entity, e.g. "${i}-1".`:void 0},type:{type:new o(p),description:i?`Entity type name, e.g. "${i}".`:void 0}};for(let t of e)r[t.name]={type:"edge"===t.type.kind?q(t.type,n):t.type.type,description:t.description};return r},H=e=>Object.fromEntries(e.map(({name:e,source:t,localized:n})=>[e,n?{source:t,localized:!0}:{source:t}]));export const createAssistantSchema=(u,{model:b,states:W,phxDefinitions:L,expressions:F,components:K},V)=>{let q,Q,X,J,Z=V.errors.length,ee=V.at("entities"),et=S(b.commonTypes,L),en=b.rootEntityTypes[0]??b.entityTypes[0];for(let e of b.resolvedShapes.keys())$.has(e)&&V.error(f.ASSISTANT_RESERVED_TYPE_NAME,y.ASSISTANT_RESERVED_TYPE_NAME(e,[...$]));let ei=((e,t,n)=>{let i=new Map;for(let r of e){let e=[];for(let[i,o]of Object.entries(r.entries)){let s=x(r,i,o,t,n.at(r.name,i));s&&e.push(s)}i.set(r.name,e)}return i})(((e,t,n)=>{let i=[];for(let[n,r]of t.resolvedShapes){let t=e[n];t&&i.push({name:n,shape:r,entries:t})}let r=new Set(t.resolvedShapes.keys());for(let t of Object.keys(e))r.has(t)||n.at(t).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("entities",t));return i})(u.entities??{},b,ee),{resolveRef:et,expressions:F,entityTypes:b.entityTypes},ee),er=B(T,[],ei.get(T)??[],V),eo=new Map,es=C(u.childRecipes??{},O,{model:b,components:K},V.at(O.section)),ea=C(u.replaceRecipes??{},v,{model:b,components:K},V.at(v.section)),ep=es.groups,el=ea.groups,ed=new Map,ec=e=>{let[t,...n]=[...b.aliases].find(([t])=>t===e)?.[1]??[];return(t&&0===n.length?eo.get(t):void 0)??ey.get(e)??ef},eh=e=>eo.get(e)??ec(e),ef=new i({name:T,description:"Every domain entity.",fields:()=>z(er,eh,en)}),ey=new Map([[T,ef]]),eu=new Map([[T,er]]);for(let e of b.aliases.keys()){if(e===T)continue;let t=B(e,[er],ei.get(e)??[],V);eu.set(e,t),ey.set(e,new i({name:e,interfaces:[ef],fields:()=>z(t,eh)}))}let eg={};for(let e of b.entityTypes){let t=[T,...[...b.aliases].filter(([t,n])=>t!==T&&n.includes(e)).map(([e])=>e)],n=B(e,t.map(e=>eu.get(e)??[]),ei.get(e)??[],V);eg[e]=H(n),eo.set(e,new s({name:e,interfaces:t.flatMap(e=>ey.get(e)??[]),fields:()=>{let t=ed.get(e);return{...z(n,eh),...t?{meta:{type:new o(t),description:"What the configurator offers on this entity besides its fields."}}:{}}}}))}let em=((e,t,n)=>{let i=new Set;for(let r of Object.keys(e)){let e=t.entityTypes.find(e=>e===r),o=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1];o?o.forEach(e=>i.add(e)):n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("deletable",r))}return t.entityTypes.filter(e=>i.has(e))})(u.deletable??{},b,V.at("deletable")),eS=((e,t,n)=>{let{model:i}=t,r=((e,t,n)=>{let i=new Map;for(let[r,o]of Object.entries(e)){let e=t.entityTypes.find(e=>e===r),s=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1],a=[...t.resolvedShapes].find(([e])=>e===r)?.[1];if(!s||!a){n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("writable",r));continue}for(let e of Object.keys(o)){let t=n.at(r,e);e.startsWith("$")||M.has(e)?t.error(f.ASSISTANT_NOT_WRITABLE,y.ASSISTANT_NOT_WRITABLE(r,e)):D(a.properties,e)?s.forEach(t=>{let n=i.get(t)??new Map;i.set(t,n.has(e)?n:n.set(e,r))}):t.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("writable",r,e))}}return i})(e,i,n);return i.entityTypes.flatMap(e=>{let o=[...i.resolvedShapes].find(([t])=>t===e)?.[1],s=[...r.get(e)??[]].flatMap(([i,r])=>{let s=o&&D(o.properties,i);return(s&&((e,{property:t,writableKey:n},i,{resolveRef:r,exposed:o,sources:s},a)=>{let p=Object.entries(D(s,e)??{}),c=o.get(e)?.find(({source:e})=>e===t)?.name??p.find(([,{source:e}])=>e===t)?.[0],h=void 0===c?p.find(([e])=>e===t)?.[1]:void 0;if(h)return void a.at(n,t).error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,t,[h.source,t],`${n}.${t}`));let{type:u,enumValues:S,localized:T,description:w}=m(i,r),N=l(u),E=c??t,A=void 0===c?R(w,S):void 0;return T?{name:E,property:t,type:g,description:A?`${A} ${j}`:j}:{name:E,property:t,type:d(N)?N:g,description:A}})(e,{property:i,writableKey:r},s,t,n))??[]});return s.length>0?[{entityType:e,fields:s}]:[]})})(u.writable??{},{model:b,resolveRef:et,exposed:ei,sources:eg},V.at("writable")),eT=((e,t,n,i)=>{let{model:r}=n,o=new Map;for(let[s,a]of Object.entries(e)){let e=r.entityTypes.find(e=>e===s),p=e?[e]:[...r.aliases].find(([e])=>e===s)?.[1]??[];for(let[e,r]of Object.entries(a)){let a=r?.options;if(!a)continue;let l=i.at(s,e,"options"),d=`${s}.${e}`;for(let i of p){let r=t.find(e=>e.entityType===i)?.fields.find(t=>t.property===e);if(!r)continue;let s=a.as??`${r.name}Options`,p=P(i,a.componentType,n),c=o.get(i)??[],h=c.find(e=>e.options.edgeName===s||e.options.field===r.name);if(p.includes(a.instanceName))if(s===O.section||s===v.section)l.error(f.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME,y.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME(d,s,r.name));else if(h)l.error(f.ASSISTANT_DUPLICATE_OPTIONS_EDGE,y.ASSISTANT_DUPLICATE_OPTIONS_EDGE(i,h.options.edgeName===s?{edgeName:s}:{field:r.name},[h.entry,d]));else{let e={field:r.name,edgeName:s,componentType:a.componentType,instanceName:a.instanceName,validate:a.validate??!0};o.set(i,[...c,{options:e,hints:U(a.hints),entry:d,entryCtx:l}])}else l.error(f.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT,y.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT(d,a,i,p))}}}return o})(u.writable??{},eS,{model:b,components:K},V.at("writable"));var ew,eN,eE,eA=[es.metaEntries,ea.metaEntries,new Map([...eT].flatMap(([e,[t]])=>t?[[e,t.entryCtx]]:[]))];for(let e of b.entityTypes){let t=eA.flatMap(t=>t.get(e)??[])[0],n=k(e);t&&[...b.resolvedShapes.keys()].some(e=>e===n)&&t.error(f.ASSISTANT_META_TYPE_NAME_CONFLICT,y.ASSISTANT_META_TYPE_NAME_CONFLICT(e,n))}let e_={recipeGroup:(ew=[...Object.keys(ep).length>0?[O.mutation]:[],...Object.keys(el).length>0?[v.mutation]:[]],eN=()=>ec(ey.has(w)?w:T),eE=()=>ec(T),q=ew.join(" or "),Q=new s({name:_,description:"One reason a recipe cannot be used right now.",fields:{type:{type:new o(p),description:'Kind of the problem, or "uncaught".'},entityId:{type:t,description:"The entity the problem is on, when it is on one."},message:{type:p,description:"The problem as the configurator words it for the user."}}}),X=new s({name:A,description:"What using a recipe would do, tried out on the configuration the query reads. Nothing is changed.",fields:()=>({ok:{type:new o(e),description:`Whether ${q} would succeed with this recipe.`},root:{type:eN(),description:"The root entity of the configuration as it would be after the change; null when ok is false. Everything selected under it reads that configuration."},newEntities:{type:new o(new r(new o(eE()))),description:`The entities ${q} would return, read from that configuration; empty when ok is false.`},errors:{type:new o(new r(new o(Q))),description:"Why the recipe cannot be used; empty when ok is true."}})}),J=new s({name:E,description:"One recipe of a recipe group: something that can be added to the entity, or something the entity can be replaced with, depending on the edge the group is listed under.",fields:{key:{type:new o(p),description:`Identifies the recipe within its group; pass it to ${q} as recipeKey. Keys can change with the configuration and with the language, so read them from the listing rather than remembering them.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Thumbnail shown to the user."},entityType:{type:new o(p),description:"Type of the entity the recipe adds under the parent, or of the entity it replaces the current one with."},dryRun:{type:X,description:"Tries the recipe out. Each selected dry-run costs a full recalculation, so select it only on the recipes you are deciding between. Null for a group whose recipes cannot be dry-run."}}}),new s({name:N,description:"A group of recipes of an entity, as the configurator offers them to the user.",fields:{groupId:{type:new o(p),description:`Identifies the group on its entity; pass it to ${q} as recipeGroupId.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},recipes:{type:new o(new r(new o(J)))}}})),fieldOption:new s({name:I,description:"One choice of a field, as the configurator offers it to the user.",fields:{value:{type:new o(g),description:"The value to write to the field."},name:{type:p,description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Image shown to the user."},color:{type:p,description:'Color shown to the user, as "#rrggbb".'}}})};for(let e of b.entityTypes){let t=D(ep,e)??[],n=D(el,e)??[],i=eT.get(e)??[];(t.length>0||n.length>0||i.length>0)&&ed.set(e,G({entityType:e,childRecipes:{groups:t,hints:es.hints.get(e)??[]},replaceRecipes:{groups:n,hints:ea.hints.get(e)??[]},optionsEdges:i},e_))}let eI=Object.fromEntries(b.entityTypes.flatMap(e=>{let t=eT.get(e);return t?[[e,t.map(({options:e})=>e)]]:[]}));if(V.errors.length>Z)return;let eO=((e,t)=>{let n;try{let t=e();if(n=h(t).map(e=>e.message),0===n.length)return c(t)}catch(e){n=[e instanceof Error?e.message:String(e)]}t.error(f.ASSISTANT_INVALID_SCHEMA,y.ASSISTANT_INVALID_SCHEMA(n))})(()=>{var e,i;let l;return new a({query:(e=ec(ey.has(w)?w:T),i=ec(T),l=(e=>{let t={};for(let[n,i,r]of[["navigationState","Active navigation state.",e.navigationStates],["viewState","Active view state.",e.viewStates],["toolState","Active tool state.",e.toolStates]])r.length>1&&(t[n]={type:new o(p),description:R(i,r)});if(0!==Object.keys(t).length)return new s({name:"Navigation",description:"The active UI states of the configurator.",fields:t})})(W),new s({name:"Query",fields:{root:{type:new o(e),description:"The root entity of the configuration."},entities:{type:new o(new r(i)),args:{ids:{type:new r(new o(t))}},description:`Every entity of the configuration, or, when ids are given, those entities in the same order with null for an unknown id. Ids have the form "<Type>-<number>"${en?`, e.g. "${en}-1"`:""}; any other id is an error.`},selectedEntity:{type:new o(i),description:"The selected entity, or the root entity when nothing is selected."},...l?{navigation:{type:new o(l)}}:{}}})),mutation:(({deletableTypes:e,writableTypes:i,childRecipes:a,replaceRecipes:l,objectTypes:d,anyDomainEntity:c})=>{let h,f;if(0!==e.length||0!==i.length||0!==Object.keys(a).length||0!==Object.keys(l).length)return new s({name:"Mutation",fields:Object.assign(0===e.length?{}:{deleteEntity:{type:new o(new r(new o(t))),args:{id:{type:new o(t)}},description:`Deletes the entity with the given id, together with the entities composed into it, and returns the ids of every entity the deletion removed, the given one first. Deletable entity types: ${e.join(", ")}. Nothing can be read from removed entities afterwards, so query what you need from them before deleting.`}},0===(h=Y(a)).length?{}:{addChild:{type:new o(new r(new o(c))),args:{parentId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Adds a child to the entity with the id parentId by one recipe of one of its recipe groups. Entity types with recipe groups: ${h.join("; ")}. Read the groupId and the recipe key from "meta { childRecipes }" of the parent. Returns every entity the change added, the recipe's own first and then whatever the configurator added in response, such as a part the new child needs; the list is empty when the configurator removed them again.`}},0===(f=Y(l)).length?{}:{replaceEntity:{type:new o(new r(new o(c))),args:{entityId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Replaces the entity with the id entityId by one recipe of one of its replace recipe groups. Entity types with replace recipe groups: ${f.join("; ")}. Read the groupId and the recipe key from "meta { replaceRecipes }" of the entity. The replacement is a new entity with a new id: the id passed in no longer exists afterwards, and the replacement has the field values of its recipe, not those of the entity it replaces. Returns every entity the change added, the replacement first and then whatever the configurator added in response, such as a part the replacement needs; the list is empty when the configurator removed them again.`}},...i.flatMap(e=>{let i=d.get(e.entityType);return i?[(({entityType:e,fields:i},r)=>{let s=Object.fromEntries(i.map(({name:e,type:t,description:n})=>[e,{type:t,description:n}]));return{[`modify${e}`]:{type:r,args:{id:{type:new o(t)},delta:{type:new o(new n({name:`${e}Delta`,fields:s}))}},description:`Changes writable fields of the one ${e} with the given id: ${i.map(({name:e})=>e).join(", ")}. The delta sets only the fields it names and needs at least one; values are in stored units, as the field descriptions say. Returns the entity as it is after the change, including what the configurator adjusted in response, or null when the change caused the entity to be removed.`}}})(e,i)]:[]}))})})({deletableTypes:em,writableTypes:eS,childRecipes:ep,replaceRecipes:el,objectTypes:eo,anyDomainEntity:ec(T)}),types:[...ey.values(),...eo.values()]})},V);return void 0===eO?void 0:{sdl:eO,fields:eg,deletableTypes:em,writableFields:Object.fromEntries(eS.map(({entityType:e,fields:t})=>[e,Object.fromEntries(t.map(({name:e,property:t})=>[e,t]))])),childRecipes:ep,replaceRecipes:el,fieldOptions:eI}};
|
|
1
|
+
import{GraphQLBoolean as e,GraphQLID as t,GraphQLInputObjectType as n,GraphQLInterfaceType as i,GraphQLList as r,GraphQLNonNull as o,GraphQLObjectType as s,GraphQLSchema as a,GraphQLString as p,getNullableType as d,isInputType as l,printSchema as c,validateSchema as h}from"graphql";import{DiagnosticCode as f,diagnosticMessages as y}from"../../../../errors/index.js";import{ASSISTANT_HINTS as u}from"../../../raw-spec/index.js";import{GraphQLJSON as g,assistantFieldType as m,createAssistantRefResolver as S}from"./assistant-field-type.js";let w="AnyDomainEntity",T="RootEntity",N="RecipeGroup",E="Recipe",A="DryRun",I="DryRunError",_="FieldOption",v={section:"childRecipes",component:"childEntityRecipes",mutation:"addChild"},O={section:"replaceRecipes",component:"replaceEntityRecipes",mutation:"replaceEntity"},b=new Set(["id","type","meta"]),R=new Set(["Query","Mutation","Navigation",N,E,A,I,_,"JSON","String","Int","Float","Boolean","ID"]),$=(e,t)=>{if(!t||0===t.length)return e;let n=`One of: ${t.map(e=>`"${e}"`).join(", ")}.`;return e?/[.!?]$/.test(e)?`${e} ${n}`:`${e}. ${n}`:n},D=new Set(["id","type"]),M="The raw stored value: a string, a message descriptor or a multilingual object.",j=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],P=(e,t,{model:n,components:i})=>{let r=new Set([e,...[...n.aliases].filter(([,t])=>t.includes(e)).map(([e])=>e)]);return i.filter(({componentName:e,typeOrAlias:n})=>e===t&&r.has(n)).map(({instanceName:e})=>String(e))},U=(...e)=>u.filter(t=>e.some(e=>e?.includes(t))),C=(e,t,n,i)=>{let{model:r}=n,o=new Map,s=new Map;for(let[a,{groups:p,hints:d}]of Object.entries(e)){let e=r.entityTypes.find(e=>e===a),l=e?[e]:[...r.aliases].find(([e])=>e===a)?.[1];if(!l){i.at(a).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE(t.section,a));continue}for(let[e,r]of(l.forEach(e=>s.set(e,U(s.get(e),d))),Object.entries(p))){let s=i.at(a,"groups",e),p=`${a}.groups.${e}`,d={groupId:r?.as??e,instanceName:e,...r?.description===void 0?{}:{description:r.description},dryRuns:r?.allowDryRuns??!0};for(let i of l){let r=P(i,t.component,n),l=o.get(i)??[],c=l.find(e=>e.group.groupId===d.groupId);r.includes(e)?c?s.error(f.ASSISTANT_DUPLICATE_RECIPE_GROUP,y.ASSISTANT_DUPLICATE_RECIPE_GROUP(t,i,d.groupId,[c.entry,p])):o.set(i,[...l,{group:d,entry:p,entryCtx:s}]):s.error(f.ASSISTANT_UNKNOWN_RECIPE_GROUP,y.ASSISTANT_UNKNOWN_RECIPE_GROUP(t,a,e,i,r))}}}let a=r.entityTypes.flatMap(e=>{let t=o.get(e);return t?[{entityType:e,groups:t}]:[]});return{groups:Object.fromEntries(a.map(({entityType:e,groups:t})=>[e,t.map(({group:e})=>e)])),hints:s,metaEntries:new Map(a.flatMap(({entityType:e,groups:[t]})=>t?[[e,t.entryCtx]]:[]))}},k=e=>`${e}Meta`,W={sameForAllInstances:e=>`All ${e} instances have the same recipe groups and recipes.`,constantDuringSession:()=>"They do not change during the session."},L={sameForAllInstances:e=>`All ${e} instances have the same options.`,constantDuringSession:()=>"The options do not change during the session."},F=(e,t,n)=>e.map(e=>` ${t[e](n)}`).join(""),K=({section:e},{groups:t,hints:n},{entityType:i,purpose:s,recipeGroup:a})=>{let p=t.filter(({dryRuns:e})=>!e).map(({groupId:e})=>e);return 0===t.length?{}:{[e]:{type:new o(new r(new o(a))),description:`The recipe groups for ${s} this ${i}: ${t.map(({groupId:e})=>e).join(", ")}. A group is listed only while the configurator offers it on the entity.${p.length>0?` Recipes of these groups cannot be dry-run: ${p.join(", ")}.`:""}${F(n,W,i)}`}}},G=({entityType:e,childRecipes:t,replaceRecipes:n,optionsEdges:i},{recipeGroup:a,fieldOption:p})=>new s({name:k(e),fields:Object.assign(K(v,t,{entityType:e,purpose:"adding children to",recipeGroup:a}),K(O,n,{entityType:e,purpose:"replacing",recipeGroup:a}),...i.map(({options:{edgeName:t,field:n,validate:i,dryRuns:s},hints:a})=>({[t]:{type:new r(new o(p)),description:`The values "${n}" of this ${e} can take, as the configurator offers them in the current state of the entity. Null when the configurator does not offer a choice on this entity. ${i?`modify${e} rejects a "${n}" value that is not in the list.`:`modify${e} does not check "${n}" against the list.`}${s?"":" Its options cannot be dry-run."}${F(a,L,e)}`}})))}),V=e=>Object.entries(e).map(([e,t])=>`${e} (${t.map(({groupId:e})=>e).join(", ")})`),Y=(e,t)=>{let{type:n,enumValues:i,localized:r,description:o}=m(e,t);return{type:{kind:"value",type:n},localized:!0===r,description:o,enumValues:i}},x=(e,t,n,i,r)=>{let o=t.startsWith("$")?((e,t,n,i)=>{let r=((e,t,{expressions:n,entityTypes:i})=>{let r=i.find(t=>t===e);for(let i of void 0===r?[e]:n.entityExpressions.get(r)?.shapeGroups??[]){let e=[...n.expressions.get(i)?.values()??[]].find(e=>e.name===t);if(e?.declaredSchema)return{implementation:e.implementation,declaredSchema:e.declaredSchema}}})(e.name,t,n);if(!r)return void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t));let{implementation:o}=r;if("violations"===o.kind)return void i.error(f.ASSISTANT_UNSUPPORTED_EXPRESSION,y.ASSISTANT_UNSUPPORTED_EXPRESSION(e.name,t));if("relation"===o.kind){let[{target:e,cardinality:t}]=o.params;return{type:{kind:"edge",target:e,cardinality:t},localized:!1,description:void 0}}return Y(r.declaredSchema,n.resolveRef)})(e,t,i,r):((e,t,{resolveRef:n},i)=>{let r=Object.entries(e.shape.properties).find(([e])=>e===t)?.[1];return r?Y(r,n):void i.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("entities",e.name,t))})(e,t,i,r);if(!o)return;let s=n?.as??(t.startsWith("$")?`_${t.slice(1)}`:t);return b.has(s)?void r.error(f.ASSISTANT_RESERVED_FIELD_NAME,y.ASSISTANT_RESERVED_FIELD_NAME(e.name,t,s)):{name:s,source:t,type:o.type,localized:o.localized,description:$(n?.description??o.description,o.enumValues),describedByManifest:n?.description!==void 0,enumValues:o.enumValues,valueDescription:n?.description??o.description}},q=(e,t,n,i,r)=>{let o=new Map,s=new Set(n);for(let i of[...t.flat(),...n]){let t=o.get(i.name);t?t.source!==i.source?r.error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,i.name,[t.source,i.source])):s.has(i)&&i.describedByManifest&&o.set(i.name,{...t,description:i.description,describedByManifest:!0,valueDescription:i.valueDescription}):o.set(i.name,i)}return[...o.values()].map(e=>{let t=e.enumValues&&i(e.source);return t?{...e,enumValues:t,description:$(e.valueDescription,t)}:e})},B=({target:e,cardinality:t},n)=>{let i=n(e);switch(t){case"1-1":return new o(i);case"0-1":return i;case"0-N":case"1-N":return new o(new r(new o(i)))}},z=(e,n,i)=>{let r={id:{type:new o(t),description:i?`Unique id of the entity, e.g. "${i}-1".`:void 0},type:{type:new o(p),description:i?`Entity type name, e.g. "${i}".`:void 0}};for(let t of e)r[t.name]={type:"edge"===t.type.kind?B(t.type,n):t.type.type,description:t.description};return r},H=e=>Object.fromEntries(e.map(({name:e,source:t,localized:n})=>[e,n?{source:t,localized:!0}:{source:t}]));export const createAssistantSchema=(u,{model:b,states:W,phxDefinitions:L,expressions:F,components:K},Y)=>{let B,Q,X,J=Y.errors.length,Z=Y.at("entities"),ee=S(b.commonTypes,L),et=b.rootEntityTypes[0]??b.entityTypes[0];for(let e of b.resolvedShapes.keys())R.has(e)&&Y.error(f.ASSISTANT_RESERVED_TYPE_NAME,y.ASSISTANT_RESERVED_TYPE_NAME(e,[...R]));let en=((e,t,n)=>{let i=new Map;for(let r of e){let e=[];for(let[i,o]of Object.entries(r.entries)){let s=x(r,i,o,t,n.at(r.name,i));s&&e.push(s)}i.set(r.name,e)}return i})(((e,t,n)=>{let i=[];for(let[n,r]of t.resolvedShapes){let t=e[n];t&&i.push({name:n,shape:r,entries:t})}let r=new Set(t.resolvedShapes.keys());for(let t of Object.keys(e))r.has(t)||n.at(t).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("entities",t));return i})(u.entities??{},b,Z),{resolveRef:ee,expressions:F,entityTypes:b.entityTypes},Z),ei=q(w,[],en.get(w)??[],()=>void 0,Y),er=new Map,eo=C(u.childRecipes??{},v,{model:b,components:K},Y.at(v.section)),es=C(u.replaceRecipes??{},O,{model:b,components:K},Y.at(O.section)),ea=eo.groups,ep=es.groups,ed=new Map,el=e=>{let[t,...n]=[...b.aliases].find(([t])=>t===e)?.[1]??[];return(t&&0===n.length?er.get(t):void 0)??ef.get(e)??eh},ec=e=>er.get(e)??el(e),eh=new i({name:w,description:"Every domain entity.",fields:()=>z(ei,ec,et)}),ef=new Map([[w,eh]]),ey=new Map([[w,ei]]);for(let e of b.aliases.keys()){if(e===w)continue;let t=q(e,[ei],en.get(e)??[],()=>void 0,Y);ey.set(e,t),ef.set(e,new i({name:e,interfaces:[eh],fields:()=>z(t,ec)}))}let eu={};for(let e of b.entityTypes){let t=[w,...[...b.aliases].filter(([t,n])=>t!==w&&n.includes(e)).map(([e])=>e)],n=[...b.resolvedShapes].find(([t])=>t===e)?.[1],i=q(e,t.map(e=>ey.get(e)??[]),en.get(e)??[],e=>{let t=Object.entries(n?.properties??{}).find(([t])=>t===e)?.[1];return t&&m(t,ee).enumValues},Y);eu[e]=H(i),er.set(e,new s({name:e,interfaces:t.flatMap(e=>ef.get(e)??[]),fields:()=>{let t=ed.get(e);return{...z(i,ec),...t?{meta:{type:new o(t),description:"What the configurator offers on this entity besides its fields."}}:{}}}}))}let eg=((e,t,n)=>{let i=new Set;for(let r of Object.keys(e)){let e=t.entityTypes.find(e=>e===r),o=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1];o?o.forEach(e=>i.add(e)):n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("deletable",r))}return t.entityTypes.filter(e=>i.has(e))})(u.deletable??{},b,Y.at("deletable")),em=((e,t,n)=>{let{model:i}=t,r=((e,t,n)=>{let i=new Map;for(let[r,o]of Object.entries(e)){let e=t.entityTypes.find(e=>e===r),s=e?[e]:[...t.aliases].find(([e])=>e===r)?.[1],a=[...t.resolvedShapes].find(([e])=>e===r)?.[1];if(!s||!a){n.at(r).error(f.ASSISTANT_UNKNOWN_TYPE,y.ASSISTANT_UNKNOWN_TYPE("writable",r));continue}for(let e of Object.keys(o)){let t=n.at(r,e);e.startsWith("$")||D.has(e)?t.error(f.ASSISTANT_NOT_WRITABLE,y.ASSISTANT_NOT_WRITABLE(r,e)):j(a.properties,e)?s.forEach(t=>{let n=i.get(t)??new Map;i.set(t,n.has(e)?n:n.set(e,r))}):t.error(f.ASSISTANT_UNKNOWN_FIELD,y.ASSISTANT_UNKNOWN_FIELD("writable",r,e))}}return i})(e,i,n);return i.entityTypes.flatMap(e=>{let o=[...i.resolvedShapes].find(([t])=>t===e)?.[1],s=[...r.get(e)??[]].flatMap(([i,r])=>{let s=o&&j(o.properties,i);return(s&&((e,{property:t,writableKey:n},i,{resolveRef:r,exposed:o,sources:s},a)=>{let p=Object.entries(j(s,e)??{}),c=o.get(e)?.find(({source:e})=>e===t)?.name??p.find(([,{source:e}])=>e===t)?.[0],h=void 0===c?p.find(([e])=>e===t)?.[1]:void 0;if(h)return void a.at(n,t).error(f.ASSISTANT_FIELD_NAME_CONFLICT,y.ASSISTANT_FIELD_NAME_CONFLICT(e,t,[h.source,t],`${n}.${t}`));let{type:u,enumValues:S,localized:w,description:T}=m(i,r),N=d(u),E=c??t,A=void 0===c?$(T,S):void 0;return w?{name:E,property:t,type:g,description:A?`${A} ${M}`:M}:{name:E,property:t,type:l(N)?N:g,description:A}})(e,{property:i,writableKey:r},s,t,n))??[]});return s.length>0?[{entityType:e,fields:s}]:[]})})(u.writable??{},{model:b,resolveRef:ee,exposed:en,sources:eu},Y.at("writable")),eS=((e,t,n,i)=>{let{model:r}=n,o=new Map;for(let[s,a]of Object.entries(e)){let e=r.entityTypes.find(e=>e===s),p=e?[e]:[...r.aliases].find(([e])=>e===s)?.[1]??[];for(let[e,r]of Object.entries(a)){let a=r?.options;if(!a)continue;let d=i.at(s,e,"options"),l=`${s}.${e}`;for(let i of p){let r=t.find(e=>e.entityType===i)?.fields.find(t=>t.property===e);if(!r)continue;let s=a.as??`${r.name}Options`,p=P(i,a.componentType,n),c=o.get(i)??[],h=c.find(e=>e.options.edgeName===s||e.options.field===r.name);if(p.includes(a.instanceName))if(s===v.section||s===O.section)d.error(f.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME,y.ASSISTANT_RESERVED_OPTIONS_EDGE_NAME(l,s,r.name));else if(h)d.error(f.ASSISTANT_DUPLICATE_OPTIONS_EDGE,y.ASSISTANT_DUPLICATE_OPTIONS_EDGE(i,h.options.edgeName===s?{edgeName:s}:{field:r.name},[h.entry,l]));else{let e={field:r.name,edgeName:s,componentType:a.componentType,instanceName:a.instanceName,validate:a.validate??!0,dryRuns:a.allowDryRuns??!0};o.set(i,[...c,{options:e,hints:U(a.hints),entry:l,entryCtx:d}])}else d.error(f.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT,y.ASSISTANT_UNKNOWN_OPTIONS_COMPONENT(l,a,i,p))}}}return o})(u.writable??{},em,{model:b,components:K},Y.at("writable"));var ew,eT,eN,eE=[eo.metaEntries,es.metaEntries,new Map([...eS].flatMap(([e,[t]])=>t?[[e,t.entryCtx]]:[]))];for(let e of b.entityTypes){let t=eE.flatMap(t=>t.get(e)??[])[0],n=k(e);t&&[...b.resolvedShapes.keys()].some(e=>e===n)&&t.error(f.ASSISTANT_META_TYPE_NAME_CONFLICT,y.ASSISTANT_META_TYPE_NAME_CONFLICT(e,n))}let eA=(ew=()=>el(ef.has(T)?T:w),eT=()=>el(w),B=new s({name:I,description:"One reason a change cannot be made right now.",fields:{type:{type:new o(p),description:'Kind of the problem, or "uncaught".'},entityId:{type:t,description:"The entity the problem is on, when it is on one."},message:{type:p,description:"The problem as the configurator words it for the user."}}}),new s({name:A,description:"What using a recipe or writing an option would do, tried out on the configuration the query reads. Nothing is changed.",fields:()=>({ok:{type:new o(e),description:"Whether the change would succeed on the configuration the query reads."},root:{type:ew(),description:"The root entity of the configuration as it would be after the change; null when ok is false. Everything selected under it reads that configuration."},changedEntities:{type:new o(new r(new o(eT()))),description:"Every entity the change would add or modify, read from that configuration; empty when ok is false. An entity whose id the configuration does not have yet would be added, and its id may differ in the real mutation. An entity that is written to is listed even when it gets the values it already has."},deletedEntityIds:{type:new o(new r(new o(t))),description:"The ids of the entities the change would remove; empty when ok is false."},errors:{type:new o(new r(new o(B))),description:"Why the change cannot be made; empty when ok is true."}})})),eI={recipeGroup:(eN=[...Object.keys(ea).length>0?[v.mutation]:[],...Object.keys(ep).length>0?[O.mutation]:[]],Q=eN.join(" or "),X=new s({name:E,description:"One recipe of a recipe group: something that can be added to the entity, or something the entity can be replaced with, depending on the edge the group is listed under.",fields:{key:{type:new o(p),description:`Identifies the recipe within its group; pass it to ${Q} as recipeKey. Keys can change with the configuration and with the language, so read them from the listing rather than remembering them.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Thumbnail shown to the user."},dryRun:{type:eA,description:"Tries the recipe out. Each selected dry-run costs a full recalculation, so select it only on the recipes you are deciding between. Null for a group whose recipes cannot be dry-run."}}}),new s({name:N,description:"A group of recipes of an entity, as the configurator offers them to the user.",fields:{groupId:{type:new o(p),description:`Identifies the group on its entity; pass it to ${Q} as recipeGroupId.`},name:{type:new o(p),description:"Name shown to the user."},description:{type:p},recipes:{type:new o(new r(new o(X)))}}})),fieldOption:new s({name:_,description:"One choice of a field, as the configurator offers it to the user.",fields:{value:{type:new o(g),description:"The value to write to the field."},name:{type:p,description:"Name shown to the user."},description:{type:p},imageUrl:{type:p,description:"Image shown to the user."},color:{type:p,description:'Color shown to the user, as "#rrggbb".'},dryRun:{type:eA,description:"Tries writing the value to the field. Each selected dry-run costs a full recalculation, so select it only on the options you are deciding between. Null for a field whose options cannot be dry-run."}}})};for(let e of b.entityTypes){let t=j(ea,e)??[],n=j(ep,e)??[],i=eS.get(e)??[];(t.length>0||n.length>0||i.length>0)&&ed.set(e,G({entityType:e,childRecipes:{groups:t,hints:eo.hints.get(e)??[]},replaceRecipes:{groups:n,hints:es.hints.get(e)??[]},optionsEdges:i},eI))}let e_=Object.fromEntries(b.entityTypes.flatMap(e=>{let t=eS.get(e);return t?[[e,t.map(({options:e})=>e)]]:[]}));if(Y.errors.length>J)return;let ev=((e,t)=>{let n;try{let t=e();if(n=h(t).map(e=>e.message),0===n.length)return c(t)}catch(e){n=[e instanceof Error?e.message:String(e)]}t.error(f.ASSISTANT_INVALID_SCHEMA,y.ASSISTANT_INVALID_SCHEMA(n))})(()=>{var e,i;let d;return new a({query:(e=el(ef.has(T)?T:w),i=el(w),d=(e=>{let t={};for(let[n,i,r]of[["navigationState","Active navigation state.",e.navigationStates],["viewState","Active view state.",e.viewStates],["toolState","Active tool state.",e.toolStates]])r.length>1&&(t[n]={type:new o(p),description:$(i,r)});if(0!==Object.keys(t).length)return new s({name:"Navigation",description:"The active UI states of the configurator.",fields:t})})(W),new s({name:"Query",fields:{root:{type:new o(e),description:"The root entity of the configuration."},entities:{type:new o(new r(i)),args:{ids:{type:new r(new o(t))}},description:`Every entity of the configuration, or, when ids are given, those entities in the same order with null for an unknown id. Ids have the form "<Type>-<number>"${et?`, e.g. "${et}-1"`:""}; any other id is an error.`},selectedEntity:{type:new o(i),description:"The selected entity, or the root entity when nothing is selected."},...d?{navigation:{type:new o(d)}}:{}}})),mutation:(({deletableTypes:e,writableTypes:i,childRecipes:a,replaceRecipes:d,objectTypes:l,anyDomainEntity:c})=>{let h,f;if(0!==e.length||0!==i.length||0!==Object.keys(a).length||0!==Object.keys(d).length)return new s({name:"Mutation",fields:Object.assign(0===e.length?{}:{deleteEntity:{type:new o(new r(new o(t))),args:{id:{type:new o(t)}},description:`Deletes the entity with the given id, together with the entities composed into it, and returns the ids of every entity the deletion removed, the given one first. Deletable entity types: ${e.join(", ")}. Nothing can be read from removed entities afterwards, so query what you need from them before deleting.`}},0===(h=V(a)).length?{}:{addChild:{type:new o(new r(new o(c))),args:{parentId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Adds a child to the entity with the id parentId by one recipe of one of its recipe groups. Entity types with recipe groups: ${h.join("; ")}. Read the groupId and the recipe key from "meta { childRecipes }" of the parent. Returns every entity the change added, the recipe's own first and then whatever the configurator added in response, such as a part the new child needs; the list is empty when the configurator removed them again.`}},0===(f=V(d)).length?{}:{replaceEntity:{type:new o(new r(new o(c))),args:{entityId:{type:new o(t)},recipeGroupId:{type:new o(p)},recipeKey:{type:new o(p)}},description:`Replaces the entity with the id entityId by one recipe of one of its replace recipe groups. Entity types with replace recipe groups: ${f.join("; ")}. Read the groupId and the recipe key from "meta { replaceRecipes }" of the entity. The replacement is a new entity with a new id: the id passed in no longer exists afterwards, and the replacement has the field values of its recipe, not those of the entity it replaces. Returns every entity the change added, the replacement first and then whatever the configurator added in response, such as a part the replacement needs; the list is empty when the configurator removed them again.`}},...i.flatMap(e=>{let i=l.get(e.entityType);return i?[(({entityType:e,fields:i},r)=>{let s=Object.fromEntries(i.map(({name:e,type:t,description:n})=>[e,{type:t,description:n}]));return{[`modify${e}`]:{type:r,args:{id:{type:new o(t)},delta:{type:new o(new n({name:`${e}Delta`,fields:s}))}},description:`Changes writable fields of the one ${e} with the given id: ${i.map(({name:e})=>e).join(", ")}. The delta sets only the fields it names and needs at least one; values are in stored units, as the field descriptions say. Returns the entity as it is after the change, including what the configurator adjusted in response, or null when the change caused the entity to be removed.`}}})(e,i)]:[]}))})})({deletableTypes:eg,writableTypes:em,childRecipes:ea,replaceRecipes:ep,objectTypes:er,anyDomainEntity:el(w)}),types:[...ef.values(),...er.values()]})},Y);return void 0===ev?void 0:{sdl:ev,fields:eu,deletableTypes:eg,writableFields:Object.fromEntries(em.map(({entityType:e,fields:t})=>[e,Object.fromEntries(t.map(({name:e,property:t})=>[e,t]))])),childRecipes:ea,replaceRecipes:ep,fieldOptions:e_}};
|
package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { type $DomainEntity, type AssistantManifest, type AssistantRecipeContext, type DomainEntity, type DomainEntityId, type DomainState, type StateUpdate, type StateUpdateEmission } from '#package/domain';
|
|
1
|
+
import { type $DomainEntity, type AssistantManifest, type AssistantRecipeContext, type DomainEntity, type DomainEntityId, type DomainState, type EntityId, type StateUpdate, type StateUpdateEmission } from '#package/domain';
|
|
2
2
|
type AnyDomainState = DomainState<DomainEntity<string>>;
|
|
3
|
+
type AnyStateUpdate = StateUpdate<DomainEntity<string>, DomainEntity<string>>;
|
|
3
4
|
/** An entity and the state it was read on, which everything under its `meta` field resolves against. */
|
|
4
5
|
export interface EntityMetaSource {
|
|
5
6
|
readonly entity: DomainEntity<string>;
|
|
@@ -9,9 +10,22 @@ export interface EntityMetaContext {
|
|
|
9
10
|
readonly manifest: AssistantManifest;
|
|
10
11
|
readonly recipes: AssistantRecipeContext;
|
|
11
12
|
/** Prepares the emission of a dry-run from the state being read; nothing is staged or committed. */
|
|
12
|
-
readonly prepareStateEmission: (updates:
|
|
13
|
+
readonly prepareStateEmission: (updates: readonly AnyStateUpdate[], state: AnyDomainState, kind: 'committed') => StateUpdateEmission<DomainEntity<string>, Record<string, $DomainEntity<DomainEntity<string>>>>;
|
|
13
14
|
/** Reads the entities of a dry-run's resulting state; `null` when the entity is not in it. */
|
|
14
15
|
readonly find$Entity: (id: DomainEntityId<string>, state: AnyDomainState) => unknown;
|
|
16
|
+
/** Checks an entity an option dry-run would write against its shape, which the emission does not do. */
|
|
17
|
+
readonly validateEntity: (entity: DomainEntity<string>) => {
|
|
18
|
+
readonly success: true;
|
|
19
|
+
} | {
|
|
20
|
+
readonly success: false;
|
|
21
|
+
readonly errors: readonly string[];
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** One reason a dry-run reports for a change that cannot be made; a violation can sit on a virtual entity. */
|
|
25
|
+
interface DryRunError {
|
|
26
|
+
readonly type: string;
|
|
27
|
+
readonly entityId: EntityId<DomainEntity<string>> | null;
|
|
28
|
+
readonly message: string | null;
|
|
15
29
|
}
|
|
16
30
|
/**
|
|
17
31
|
* The value of an entity's `meta` field: its built-ins, resolved lazily against the state the entity
|
|
@@ -28,25 +42,18 @@ export declare const createEntityMeta: (source: EntityMetaSource, context: Entit
|
|
|
28
42
|
name: string;
|
|
29
43
|
description: string | null;
|
|
30
44
|
imageUrl: string | null;
|
|
31
|
-
entityType: () => string | undefined;
|
|
32
45
|
dryRun: () => {
|
|
33
46
|
ok: boolean;
|
|
34
|
-
root:
|
|
35
|
-
|
|
36
|
-
|
|
47
|
+
root: null;
|
|
48
|
+
changedEntities: never[];
|
|
49
|
+
deletedEntityIds: never[];
|
|
50
|
+
errors: readonly DryRunError[];
|
|
37
51
|
} | {
|
|
38
52
|
ok: boolean;
|
|
39
|
-
root:
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
entityId: null;
|
|
44
|
-
message: string;
|
|
45
|
-
}[] | {
|
|
46
|
-
type: never;
|
|
47
|
-
entityId: import("#package/domain").EntityId<DomainEntity<string>>;
|
|
48
|
-
message: string | null;
|
|
49
|
-
}[];
|
|
53
|
+
root: unknown;
|
|
54
|
+
changedEntities: {}[];
|
|
55
|
+
deletedEntityIds: DomainEntityId<string>[];
|
|
56
|
+
errors: never[];
|
|
50
57
|
} | null;
|
|
51
58
|
}[];
|
|
52
59
|
}[];
|
|
@@ -59,25 +66,18 @@ export declare const createEntityMeta: (source: EntityMetaSource, context: Entit
|
|
|
59
66
|
name: string;
|
|
60
67
|
description: string | null;
|
|
61
68
|
imageUrl: string | null;
|
|
62
|
-
entityType: () => string | undefined;
|
|
63
69
|
dryRun: () => {
|
|
64
70
|
ok: boolean;
|
|
65
|
-
root:
|
|
66
|
-
|
|
67
|
-
|
|
71
|
+
root: null;
|
|
72
|
+
changedEntities: never[];
|
|
73
|
+
deletedEntityIds: never[];
|
|
74
|
+
errors: readonly DryRunError[];
|
|
68
75
|
} | {
|
|
69
76
|
ok: boolean;
|
|
70
|
-
root:
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
entityId: null;
|
|
75
|
-
message: string;
|
|
76
|
-
}[] | {
|
|
77
|
-
type: never;
|
|
78
|
-
entityId: import("#package/domain").EntityId<DomainEntity<string>>;
|
|
79
|
-
message: string | null;
|
|
80
|
-
}[];
|
|
77
|
+
root: unknown;
|
|
78
|
+
changedEntities: {}[];
|
|
79
|
+
deletedEntityIds: DomainEntityId<string>[];
|
|
80
|
+
errors: never[];
|
|
81
81
|
} | null;
|
|
82
82
|
}[];
|
|
83
83
|
}[];
|
package/dist/configurator/application-runtime/extensions/systems/graphql-system/entity-meta.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{findAssistantFieldOptions as e,findAssistantRecipeGroups as t,modifyEntityUpdateTag as i,prepareAssistantRecipeUpdates as r,readAssistantFieldOptions as n,readAssistantRecipeGroup as s,systemUpdateFactory as a}from"#package/domain";let o=e=>({ok:!1,root:null,changedEntities:[],deletedEntityIds:[],errors:e}),d=(e,{state:t},{recipes:i,prepareStateEmission:r,find$Entity:n})=>{let{validity:s,state:a}=r(e,t,"committed");if(s.valid){let e=new Map(t.entities.map(e=>[e.id,e])),i=new Set(a.entities.map(e=>e.id));return{ok:!0,root:n(a.rootEntityId,a),changedEntities:a.entities.filter(t=>e.get(t.id)!==t).flatMap(e=>n(e.id,a)??[]),deletedEntityIds:t.entities.map(e=>e.id).filter(e=>!i.has(e)),errors:[]}}return o("uncaught"===s.severity?[{type:"uncaught",entityId:null,message:s.error.message}]:s.entityViolations.filter(({violation:e})=>e.severity===s.severity).map(({entityId:e,violation:t})=>({type:t.type,entityId:e,message:void 0===t.message?null:i.resolveLocalizable(t.message)})))};export const createEntityMeta=(l,c)=>{let p=e=>()=>t(c.manifest,e,l.entity.type).flatMap(t=>{let i=s(e,t,l.entity.id,l.state,c.recipes);return i?[((e,t,i)=>{let{group:n,label:s,description:a,recipes:l}=e,{resolveLocalizable:c}=i.recipes;return{groupId:n.groupId,name:void 0===s?n.instanceName:c(s),description:n.description??(void 0===a?null:c(a)),recipes:l.map(n=>((e,t,i,n)=>{let{key:s,item:a}=e,{resolveLocalizable:l}=n.recipes;return{key:s,name:l(a.title),description:void 0===a.description?null:l(a.description),imageUrl:void 0===a.thumbnailUrl?null:l(a.thumbnailUrl),dryRun:()=>t.group.dryRuns?((e,t,i,n)=>{let{updates:s,error:a}=((e,t,{entity:i,state:n},{recipes:s})=>{try{return{updates:r(e,t,i.id,n,s),error:void 0}}catch(e){if("child"===t.target.kind)throw e;return{updates:void 0,error:e instanceof Error?e.message:String(e)}}})(e,t,i,n);return void 0===s?o([{type:"uncaught",entityId:null,message:a}]):d(s,i,n)})(e,t,i,n):null}})(n,e,t,i))}})(i,l,c)]:[]});return{...Object.fromEntries(e(c.manifest,l.entity.type).map(e=>[e.edgeName,()=>n(e,l.entity.id,l.state,c.recipes)?.map(t=>({...t,dryRun:()=>e.dryRuns?(({field:e},{value:t},r,n)=>{let{entity:s}=r,l=Object.entries(Object.entries(n.manifest.writableFields??{}).find(([e])=>e===s.type)?.[1]??{}).find(([t])=>t===e)?.[1];if(void 0===l)throw Error(`The options of "${e}" on "${s.id}" cannot be dry-run: the schema lists them, but the configurator has no writable field "${e}" on ${s.type}. Regenerate the application so the schema matches the configurator.`);let c=r.state.entities.find(e=>e.id===s.id),p={[l]:t},u=c?n.validateEntity({...c,...p}):{success:!0};return u.success?d([a.DomainEntityModification({entityId:s.id,stateDelta:p,updateTag:i})],r,n):o([{type:"uncaught",entityId:s.id,message:`Writing ${JSON.stringify(t)} to "${e}" would make "${s.id}" an invalid ${s.type}: ${u.errors.join("; ")}.${e===l?"":` The message names the stored property: ${e} is stored as ${l}.`} The option comes from the configurator and cannot be corrected from here, so do not write it.`}])})(e,t,l,c):null}))??null])),childRecipes:p("child"),replaceRecipes:p("replace")}};
|
package/dist/configurator/application-runtime/extensions/systems/graphql-system/graphql-system.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{GraphQLError as e,buildSchema as t,defaultFieldResolver as i,getNamedType as o,graphql as a,validateSchema as n}from"graphql";import{assertExistence as r,createSelector as s,isMessageDescriptor as l,isMultilingualString as c}from"@salsita-ai/common/utils";import{DomainEntityIdSchema as h,findAssistantMutation as d}from"#package/domain";import{createEntityMeta as m}from"./entity-meta.js";let p={errors:[new e('No assistant manifest in the application spec. The GraphQL schema is generated from the "assistant" section. Add an "assistant" section to a spec file to expose a schema.')]},u={errors:[new e("The configuration is not loaded yet, so there is no state to query. Run the query again once the configurator has finished loading.")]},f=new RegExp(h.pattern),y=e=>"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"id"in e&&"string"==typeof e.id,g=(e,t)=>"object"==typeof e&&null!==e?Reflect.get(e,t):void 0,v=e=>e instanceof Error?e.message:String(e),S=e=>/[.!?]$/.test(e)?e:`${e}.`,_=e=>"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype,
|
|
1
|
+
import{GraphQLError as e,buildSchema as t,defaultFieldResolver as i,getNamedType as o,graphql as a,validateSchema as n}from"graphql";import{assertExistence as r,createSelector as s,isMessageDescriptor as l,isMultilingualString as c}from"@salsita-ai/common/utils";import{DomainEntityIdSchema as h,findAssistantMutation as d}from"#package/domain";import{createEntityMeta as m}from"./entity-meta.js";let p={errors:[new e('No assistant manifest in the application spec. The GraphQL schema is generated from the "assistant" section. Add an "assistant" section to a spec file to expose a schema.')]},u={errors:[new e("The configuration is not loaded yet, so there is no state to query. Run the query again once the configurator has finished loading.")]},f=new RegExp(h.pattern),y=e=>"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type&&"id"in e&&"string"==typeof e.id,g=(e,t)=>"object"==typeof e&&null!==e?Reflect.get(e,t):void 0,v=e=>e instanceof Error?e.message:String(e),S=e=>/[.!?]$/.test(e)?e:`${e}.`,_=e=>"object"==typeof e&&null!==e&&Object.getPrototypeOf(e)===Object.prototype,x=(e,t)=>{let i=_(e)?e._raw:void 0;if(y(i))return i;if(!Array.isArray(e)&&!_(e))return e;if(t.has(e))throw Error("The value contains itself. Return ids or copies of the values instead of objects that reference each other.");let o=new Set([...t,e]);return Array.isArray(e)?e.map(e=>x(e,o)):Object.fromEntries(Object.entries(e).map(([e,t])=>[e,x(t,o)]))},w=(e,t)=>Array.isArray(e)?e.map(e=>w(e,t)):"string"==typeof e||l(e)||c(e)?t(e):e,$=t=>new e(`The GraphQL schema generated from the "assistant" manifest is invalid: ${S(t)} Regenerate the application so the schema is rebuilt from the current spec.`),E=e=>(e.errors?.length??0)>0,b=t=>({errors:[new e(`Not run: operation ${t+1} failed, so the operations after it were skipped and no change of the list takes effect. Fix the failing operation and send the whole list again.`)]});export class GraphQLSystem{_context;_selectSchema=s([s.leaf(e=>e)],e=>{try{let i=t(e),o=n(i);return o.length>0?$(o.map(e=>e.message).join(" ")):i}catch(e){return $(v(e))}});_selectFieldResolver=s([s.leaf(e=>e)],t=>(a,n,r,s)=>{if(s.parentType===s.schema.getQueryType())return i(a,n,r,s);if(s.parentType===s.schema.getMutationType())return this._resolveMutation(s.fieldName,String(s.path.key),n,r);if(!y(a))return i(a,n,r,s);if("meta"===s.fieldName){let e;return m({entity:a,state:("object"==typeof(e=g(a,"_state"))&&null!==e&&"entities"in e&&"rootEntityId"in e?e:void 0)??r.state},{manifest:r.manifest,recipes:this._recipeContext(),prepareStateEmission:(e,t,i)=>this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(e,t,i),find$Entity:(e,t)=>this._find$Entity(e,t),validateEntity:e=>this._context.domainContextSelectors.getDomain().validateEntity(e)})}let{source:l,localized:c}=t[s.parentType.name]?.[s.fieldName]??{source:s.fieldName},h=((t,i)=>{try{return g(t,i)}catch(o){throw new e(`Expression "${i}" failed on ${y(t)?t.id:"an entity"}: ${S(v(o))} The expression threw while the query read it; fix the expression or the configuration state it reads.`,{originalError:o instanceof Error?o:void 0})}})(a,l);return c?w(h,this._context.domainServicesSelectors.getResolveLocalizable()):l.startsWith("$")&&"JSON"===o(s.returnType).name?((t,i,o)=>{try{return x(o,new Set)}catch(o){throw new e(`Expression "${i}" returned a value that is not plain serializable data on ${y(t)?t.id:"an entity"}: ${S(v(o))} A JSON field can only return data that serializes to JSON.`,{originalError:o instanceof Error?o:void 0})}})(a,l,h):h});constructor(e){this._context=e}_get$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().get$Entity(e,t);_find$Entity=(e,t)=>this._context.domainContextSelectors.getDomain().getEntity(e,t)?this._get$Entity(e,t):null;_recipeContext=()=>({componentReader:this._context.domainContextSelectors.getComponentReader(),recipeCooker:this._context.domainContextSelectors.getRecipeCookerSystem(),resolveLocalizable:this._context.domainServicesSelectors.getResolveLocalizable()});_rootValue={root:(e,{state:t})=>this._get$Entity(t.rootEntityId,t),entities:({ids:t},{state:i})=>{if(null==t)return i.entities.map(e=>this._get$Entity(e.id,i));var o=i.rootEntityId;let a=t.filter(e=>!f.test(e));if(a.length>0)throw new e(`${a.map(e=>`"${e}"`).join(", ")} ${1===a.length?"is not an entity id":"are not entity ids"}. Entity ids have the form "<Type>-<number>", e.g. "${o}". Use ids as returned by the "id" field.`);return t.map(e=>f.test(e)?this._find$Entity(e,i):null)},selectedEntity:(e,{state:t})=>this._find$Entity(this._context.domainContextSelectors.getNavigationSystem().getActiveSelectionState(t),t),navigation:(e,{state:t})=>{let i=this._context.domainContextSelectors.getNavigationSystem();return{navigationState:i.getActiveNavigationState(t),viewState:i.getActiveViewState(t),toolState:i.getActiveToolState(t)}}};_resolveType=e=>y(e)?e.type:void 0;initialize=()=>{};_resolveMutation=(t,i,o,a)=>{if(void 0!==a.failedMutationField)throw new e(`Not run: the earlier field "${a.failedMutationField}" of this operation failed, so "${i}" was skipped and no change of the operation takes effect. Fix the failing field and send the operation again.`);try{return this._runMutation(t,o,a)}catch(e){throw a.failedMutationField=i,e}};_runMutation=(t,i,o)=>{let a=d(t,o.manifest);if(!a)throw new e(`The schema declares the mutation "${t}", but the configurator has no implementation for it. Regenerate the application so the schema matches the configurator.`);let n=o.state,r=a.implementation(i,n,{manifest:o.manifest,domain:this._context.domainContextSelectors.getDomain(),...this._recipeContext()});if(r.updates.length>0){let i=this._context.domainContextSelectors.getStoreSystem().prepareStateEmission(r.updates,n,"committed");if(!i.validity.valid)throw new e(`The changes of "${t}" were not applied, because the resulting configuration is invalid: ${(e=>{if("uncaught"===e.severity)return`validating it threw: ${S(v(e.error))}`;let t=[...new Set(e.entityViolations.filter(({violation:t})=>t.severity===e.severity).map(({entityId:e})=>e))];return`it has ${e.severity} violations on ${t.join(", ")}.`})(i.validity)} Change the request so the configuration stays valid.`);o.emissions.push(i),o.state=i.state}return r.readResult({previousState:n,state:o.state})};_setup=()=>{let t=this._context.specSelectors.getAssistant();if(!t)return{ready:!1,result:p};let i=this._selectSchema(t.sdl);return i instanceof e?{ready:!1,result:{errors:[i]}}:{ready:!0,assistant:t,schema:i,fieldResolver:this._selectFieldResolver(t.fields)}};prepare=async(e,t)=>{let i,o=this._setup();if(!o.ready)return t.map(()=>({result:o.result,emissions:[]}));let n={manifest:o.assistant,state:e,emissions:[],failedMutationField:void 0},r=[];for(let[e,s]of t.entries())if(void 0===i){let t=n.emissions.length;n.failedMutationField=void 0;let l=await a({schema:o.schema,source:s.document,rootValue:this._rootValue,contextValue:n,variableValues:s.variables,operationName:s.operationName,fieldResolver:o.fieldResolver,typeResolver:this._resolveType});r.push({result:l,emissions:n.emissions.slice(t)}),E(l)&&(i=e)}else r.push({result:b(i),emissions:[]});return r};_prepareAndCommit=async e=>{let t,i,o,a=this._context.domainContextSelectors.getStoreSystem(),n=await this.prepare(a.stateSlices.committed.value.state,e),s=n.map(({result:e})=>e),l=n.flatMap(e=>e.emissions);return s.some(E)||0===l.length?{results:s,outcome:"none"}:{results:s,outcome:a.commitPrepared((t=r(l[0]),i=r(l[l.length-1]),o=l.some(e=>void 0!==e.transformationLog),{kind:"committed",previousState:t.previousState,state:i.state,updates:l.flatMap(e=>e.updates),validity:i.validity,transformationLog:o?l.flatMap(e=>e.transformationLog??[]):void 0}))}};execute=async e=>{if(!this._context.domainContextSelectors.getStoreSystem().isInitialized)return{results:e.map(()=>u),committed:!1};let t=await this._prepareAndCommit(e),{results:i,outcome:o}="conflict"===t.outcome?await this._prepareAndCommit(e):t;return"committed"===o?{results:i,committed:!0}:"held"===o?{results:i,committed:!1,message:"The changes were not committed yet: the application held them, usually to ask the user for approval. They may still be applied once the user approves, and the next turn shows whether they were. Do not send the operations again."}:"conflict"===o?{results:i,committed:!1,message:"The changes were not committed, because the configuration changed while they were being applied. The results describe a state that was discarded. Query the current configuration and send the operations again if they still make sense."}:{results:i,committed:!1}}}
|
package/dist/docs/index.json
CHANGED
|
@@ -149,13 +149,17 @@ Host must pass the nonce into the web component:
|
|
|
149
149
|
<salsita-configurator nonce="YOUR_REQUEST_NONCE"></salsita-configurator>
|
|
150
150
|
```
|
|
151
151
|
|
|
152
|
+
### Starting Policy from Studio
|
|
153
|
+
|
|
154
|
+
The **CSP** tab of an environment in Studio generates a starting `<meta http-equiv="Content-Security-Policy">` tag with that environment's configurator, server and S3 bucket origins filled in. Its `script-src` and `style-src` carry the `'nonce-YOUR_REQUEST_NONCE'` placeholder: the host still has to replace it with a cryptographically random nonce generated for every request and pass the same value to `<salsita-configurator nonce="…">`. Extend the policy with any origins the host page itself needs.
|
|
155
|
+
|
|
152
156
|
## What Phoenix Does Not Configure
|
|
153
157
|
|
|
154
158
|
Phoenix options only change SDK runtime internals. They **do not**:
|
|
155
159
|
|
|
156
160
|
- set CSP headers for your hosting platform
|
|
157
|
-
-
|
|
158
|
-
- choose your nonce strategy
|
|
161
|
+
- enforce `script-src`, `style-src`, `connect-src`, etc. (the Studio CSP tab only suggests a starting policy)
|
|
162
|
+
- generate nonces or choose your nonce strategy
|
|
159
163
|
|
|
160
164
|
CSP policy itself is owned by the host page / hosting infra.
|
|
161
165
|
|
|
@@ -283,19 +283,20 @@ The Phoenix CLI auto-generates config files that read these variables:
|
|
|
283
283
|
|
|
284
284
|
Starts the full development environment: Vite dev server, development webhook tunnel, domain-cli watcher, and editor WebSocket server.
|
|
285
285
|
|
|
286
|
-
| Flag
|
|
287
|
-
|
|
|
288
|
-
| `--workspace`
|
|
289
|
-
| `--editor`
|
|
290
|
-
| `--editorWsPort`
|
|
291
|
-
| `--debug`
|
|
292
|
-
| `--projectSlug`
|
|
293
|
-
| `--environmentSlug`
|
|
294
|
-
| `--withLingui`
|
|
295
|
-
| `--persistence`
|
|
296
|
-
| `--force` / `-f`
|
|
297
|
-
| `--serverUrl`
|
|
298
|
-
| `--region`
|
|
286
|
+
| Flag | Env Variable | Default | Description |
|
|
287
|
+
| ---------------------- | ------------------ | -------------------- | ------------------------------------------------------------------------------- |
|
|
288
|
+
| `--workspace` | — | from `.phoenix.json` | Override workspace mode |
|
|
289
|
+
| `--editor` | `ENABLE_EDITOR` | `true` | Enable editor file generation |
|
|
290
|
+
| `--editorWsPort` | `EDITOR_WS_PORT` | `3020` | Editor WebSocket port |
|
|
291
|
+
| `--debug` | `DEBUG` | `false` | Verbose logging |
|
|
292
|
+
| `--projectSlug` | `PROJECT_SLUG` | `local` | Project slug |
|
|
293
|
+
| `--environmentSlug` | `ENVIRONMENT_SLUG` | package.json name | Environment slug |
|
|
294
|
+
| `--withLingui` | `WITH_LINGUI` | `false` | Enable i18n extraction/compilation and watch i18n sources during dev |
|
|
295
|
+
| `--persistence` | `PERSISTENCE_MODE` | `server` | Persistence mode |
|
|
296
|
+
| `--force` / `-f` | `FORCE_REBUILD` | `false` | Force full rebuild, skip cache |
|
|
297
|
+
| `--serverUrl` | `SERVER_URL` | the region's server | Phoenix server URL |
|
|
298
|
+
| `--region` | `PHOENIX_REGION` | `eu` | Region of the signed-in workspace, used when no server URL is set |
|
|
299
|
+
| `--skipUpload` / `-su` | `SKIP_UPLOAD` | `false` | Skip the S3 asset upload when the development deployment is prepared at startup |
|
|
299
300
|
|
|
300
301
|
In `server` persistence mode the project comes from `--projectSlug`, `PROJECT_SLUG` or `project` in the spec, and the credential from `DEVELOPMENT_KEY` or the `phoenix login` sign-in; see [Starting a New Project](#starting-a-new-project). When signed in, the environment is always your own development environment and `--environmentSlug` is ignored.
|
|
301
302
|
|
|
@@ -90,7 +90,8 @@ export interface AssistantRecipeGroup {
|
|
|
90
90
|
* The options edge of one writable field the assistant manifest links to its component. `field` is
|
|
91
91
|
* the delta field of `modify<Type>` the choices are for, `edgeName` the field of `<Type>Meta` that
|
|
92
92
|
* lists them, `componentType` and `instanceName` the component instance they are read from, and
|
|
93
|
-
* `validate` whether `modify<Type>` rejects a value that is not among them
|
|
93
|
+
* `validate` whether `modify<Type>` rejects a value that is not among them, and `dryRuns` whether
|
|
94
|
+
* the choices can be dry-run.
|
|
94
95
|
*/
|
|
95
96
|
export interface AssistantFieldOptions {
|
|
96
97
|
readonly field: string;
|
|
@@ -98,6 +99,7 @@ export interface AssistantFieldOptions {
|
|
|
98
99
|
readonly componentType: 'materialSwatch' | 'attributeSelection' | 'distanceDimensionSelect';
|
|
99
100
|
readonly instanceName: string;
|
|
100
101
|
readonly validate: boolean;
|
|
102
|
+
readonly dryRuns: boolean;
|
|
101
103
|
}
|
|
102
104
|
/**
|
|
103
105
|
* Experimental assistant manifest generated from the application spec `assistant` section. `sdl` is
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type StateUpdate } from '../components/updates.js';
|
|
2
2
|
import type { Domain } from '../core/domain.js';
|
|
3
|
-
import type
|
|
3
|
+
import { type $DomainEntity, type DomainEntity } from '../core/model.js';
|
|
4
4
|
import type { DomainState } from '../core/state.js';
|
|
5
5
|
import type { AssistantManifest } from './application-config.js';
|
|
6
6
|
import { type AssistantRecipeContext } from './assistant-recipe-groups.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{z as e}from"zod";import{systemUpdateFactory as t}from"../components/updates.js";import{DomainEntityIdSchema as i}from"../core/model.js";import{findAssistantFieldOptions as r,readAssistantFieldOptions as n}from"./assistant-field-options.js";import{assistantAddedEntityIds as o,findAssistantRecipeGroups as a,prepareAssistantRecipeUpdates as s,readAssistantRecipeGroup as d}from"./assistant-recipe-groups.js";export const deleteEntityUpdateTag="deleteEntity";export const modifyEntityUpdateTag="modifyEntity";let l=e.string().regex(new RegExp(i.pattern),'An entity id is the type name, a dash and a number, e.g. "Root-1". Query the current entities and use an id they return.'),p=e.object({id:l}),h=e.object({id:l,delta:e.record(e.unknown())}),u="modify",f=(e,t)=>Object.entries(e).find(([e])=>e===t)?.[1],y=e=>Array.isArray(e)?e.map(y):"object"!=typeof e||null===e||Array.isArray(e)?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,y(t)])),c=e.object({parentId:l,recipeGroupId:e.string(),recipeKey:e.string()}),g=e.object({entityId:l,recipeGroupId:e.string(),recipeKey:e.string()}),m=e=>e.map(e=>`"${e}"`).join(", "),$=[{name:"deleteEntity",implementation:(e,i,{manifest:r})=>{let{id:n}=p.parse(e),o=i.entities.find(e=>e.id===n);if(!o)throw Error(`Entity "${n}" does not exist, so it cannot be deleted. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);let a=r.deletableTypes??[];if(!a.includes(o.type))throw Error(`Entity "${n}" is a ${o.type}, which is not deletable. ${a.length>0?`Only entities of these types can be deleted: ${a.join(", ")}.`:"No entity type is deletable."} Delete an entity of a deletable type instead.`);return{updates:[t.EntityDeletion({entityId:o.id,updateTag:"deleteEntity"})],readResult:({previousState:e,state:t})=>{var i;let r;return[o.id,...(i=o.id,r=new Set(t.entities.map(e=>e.id)),e.entities.map(e=>e.id).filter(e=>e!==i&&!r.has(e)))]}}}},{name:"addChild",implementation:(e,t,i)=>{let{parentId:r,recipeGroupId:n,recipeKey:l}=c.parse(e),p=t.entities.find(e=>e.id===r);if(!p)throw Error(`Entity "${r}" does not exist, so nothing can be added to it. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);let h=a(i.manifest,"child",p.type),u=h.find(e=>e.groupId===n);if(!u)throw Error(`Entity "${r}" is a ${p.type}, which has no recipe group "${n}". ${h.length>0?`Its recipe groups are: ${m(h.map(({groupId:e})=>e))}.`:`Nothing can be added to a ${p.type}.`} Query "meta { childRecipes { groupId } }" on the entity you want to add to and use a groupId it returns.`);let f=d("child",u,p.id,t,i);if(!f)throw Error(`The recipe group "${n}" is not available on "${r}" right now, so nothing can be added from it. The configurator offers a group only in some states of the configuration. Query "meta { childRecipes { groupId } }" on "${r}" to see the groups it offers now.`);let y=f.recipes.find(e=>e.key===l);if(!y)throw Error(`The recipe group "${n}" on "${r}" has no recipe with the key "${l}". Recipes and their keys change with the configuration and with the language. List the recipes of the group again and use a key it returns.`);let g=s(y,f,p.id,t,i);return{updates:g,readResult:e=>o(g,p.id,e).map(t=>i.domain.get$Entity(t,e.state))}}},{name:"replaceEntity",implementation:(e,t,i)=>{let{entityId:r,recipeGroupId:n,recipeKey:l}=g.parse(e),p=t.entities.find(e=>e.id===r);if(!p)throw Error(`Entity "${r}" does not exist, so it cannot be replaced. It may have been deleted or replaced by an earlier operation or field; a replaced entity gets a new id. Query the current entities and use an id they return.`);let h=a(i.manifest,"replace",p.type),u=h.find(e=>e.groupId===n);if(!u)throw Error(`Entity "${r}" is a ${p.type}, which has no replace recipe group "${n}". ${h.length>0?`Its replace recipe groups are: ${m(h.map(({groupId:e})=>e))}.`:`A ${p.type} cannot be replaced.`} Query "meta { replaceRecipes { groupId } }" on the entity you want to replace and use a groupId it returns.`);let f=d("replace",u,p.id,t,i);if(!f)throw Error(`The recipe group "${n}" is not available on "${r}" right now, so it cannot be replaced from it. The configurator offers a group only in some states of the configuration. Query "meta { replaceRecipes { groupId } }" on "${r}" to see the groups it offers now.`);let y=f.recipes.find(e=>e.key===l);if(!y)throw Error(`The recipe group "${n}" on "${r}" has no recipe with the key "${l}". Recipes and their keys change with the configuration and with the language. List the recipes of the group again and use a key it returns.`);let c=s(y,f,p.id,t,i);return{updates:c,readResult:e=>o(c,p.id,e).map(t=>i.domain.get$Entity(t,e.state))}}}];export const findAssistantMutation=(e,i)=>{let o,a,s=$.find(t=>t.name===e);if(s||!e.startsWith(u))return s;let d=e.slice(u.length),l=f(i.writableFields??{},d);return l&&(o=`${u}${d}`,a=Object.keys(l).join(", "),{name:o,implementation:(e,i,s)=>{let{manifest:p,domain:c}=s,{id:g,delta:m}=h.parse(e),$=i.entities.find(e=>e.id===g);if(!$)throw Error(`Entity "${g}" does not exist, so it cannot be modified. It may have been deleted by an earlier operation or field. Query the current entities and use an id they return.`);if($.type!==d)throw Error(`Entity "${g}" is a ${$.type}, but ${o} modifies only ${d} entities. ${f(p.writableFields??{},$.type)?`Use ${u}${$.type} for it instead.`:`${$.type} has no writable fields, so it cannot be modified; pass the id of a ${d}.`}`);let w=Object.entries(m).flatMap(([e,t])=>{let i=f(l,e);return void 0===i?[]:[{field:e,property:i,value:y(t)}]}),b=Object.fromEntries(w.map(({property:e,value:t})=>[e,t]));if(0===Object.keys(b).length)throw Error(`The delta of ${o} is empty, so there is nothing to change on "${g}". Set at least one of its fields: ${a}.`);let E=c.validateEntity({...$,...b});if(!E.success){let e=w.filter(({field:e,property:t})=>e!==t).map(({field:e,property:t})=>`${e} is stored as ${t}`);throw Error(`The delta would make "${g}" an invalid ${d}: ${E.errors.join("; ")}. ${e.length>0?`The messages name stored properties: ${e.join(", ")}. `:""}Nothing was changed. Send values that fit the types and the allowed values the schema describes for these fields.`)}let j=r(p,d);for(let{field:e,value:t}of w){let r=j.find(t=>t.field===e);if(!r?.validate||null===t)continue;let o=n(r,$.id,i,s);if(o&&!o.some(e=>e.value===t))throw Error(`${JSON.stringify(t)} is not a value "${e}" of "${g}" can take right now. ${o.length>0?`The configurator offers these values: ${o.map(e=>JSON.stringify(e.value)).join(", ")}.`:"The configurator offers no value for it in this state."} Nothing was changed. Send one of the offered values; "meta { ${r.edgeName} }" on the entity lists them with their names. When the values depend on another field of this delta, change that field in an earlier mutation field of the same operation.`)}return{updates:[t.DomainEntityModification({entityId:$.id,stateDelta:b,updateTag:"modifyEntity"})],readResult:({state:e})=>c.getEntity($.id,e)?c.get$Entity($.id,e):null}}})};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export declare const cacheVersion =
|
|
1
|
+
export declare const cacheVersion = 757;
|
|
2
2
|
export declare const needsRebuild: (fileContents: string[], outputDirectory: string) => Promise<boolean>;
|
|
3
3
|
export declare const writeCacheInfo: (fileContents: string[], outputDirectory: string) => Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createHash as e}from"crypto";import{existsSync as r}from"fs";import{readFile as t}from"fs/promises";import{isEqualArray as o}from"@salsita-ai/common/utils";import{writeFormatted as i}from"../gen/write-formatted.js";export const cacheVersion=
|
|
1
|
+
import{createHash as e}from"crypto";import{existsSync as r}from"fs";import{readFile as t}from"fs/promises";import{isEqualArray as o}from"@salsita-ai/common/utils";import{writeFormatted as i}from"../gen/write-formatted.js";export const cacheVersion=757;let s=r=>({version:757,files:r.map(r=>e("md5").update(r).digest("base64")).sort()});export const needsRebuild=async(e,i)=>{let a=`${i}/cache.json`;if(!r(a))return!0;try{let r=JSON.parse(await t(a,"utf-8")),i=s(e);return 757!==r.version||!o(r.files,i.files)}catch(e){return console.error("Failed to read cache file, forcing rebuild",e),!0}};export const writeCacheInfo=async(e,r)=>{let t=`${r}/cache.json`,o=s(e);await i(t,JSON.stringify(o,null,2))};
|
|
@@ -13,5 +13,7 @@ export interface DevCommandProps {
|
|
|
13
13
|
readonly tui?: boolean;
|
|
14
14
|
readonly serverUrl?: string;
|
|
15
15
|
readonly developmentKey?: string;
|
|
16
|
+
/** Skips the asset upload of the start-up prepare; the re-prepare after a rebuild never uploads. */
|
|
17
|
+
readonly skipUpload: boolean;
|
|
16
18
|
}
|
|
17
19
|
export declare const runDevCommand: (props: DevCommandProps, context: CommandContext) => Promise<void>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{format as e}from"node:util";import{createServer as t}from"vite";import{runBuildCommand as r,setLambdaLocalLogger as o,webhookLogContext as s}from"../../webhook-cli/index.js";import{startEditorServer as n}from"../editor-server/index.js";import{DomainSpecProjectWatcher as i,LinguiWatcher as a,LogBus as l,MockTemplateWatcher as c,PhoenixPubSub as p,WebhookTunnelMonitor as d,createBusLogger as u,getViteDevConfig as m,patchConsole as g,setViteLogSink as w}from"../services/index.js";import{prepareDevelopmentEnvironment as v}from"../services/prepare-development-environment.js";import{createWebhookTunnelTransport as h,readOrCreateTunnelSessionId as f,startWebhookService as E}from"../services/webhook-service/index.js";import{startTui as b}from"../tui/index.js";import{FileLogger as S,createLogger as I,exists as k}from"../utils/index.js";import{generateProjectFilesAndInstallDependencies as T}from"./generate-project-files.js";import{readGeneratedEnvMarkers as x}from"./generated-env-markers.js";export const runDevCommand=async(N,$)=>{let{logger:j}=$,{sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,editorWsPort:O,debug:L=!1,withLingui:V=!1,persistenceMode:M,force:U=!1,tui:W=!1,serverUrl:C,developmentKey:Y}=N,
|
|
2
|
-
${t.join("\n ")}`),
|
|
3
|
-
`)}}),
|
|
4
|
-
`)}),
|
|
5
|
-
`)};e("\n\uD83D\uDE80 Phoenix Dev Server\n"),y&&O&&e(`Editor WebSocket: ws://localhost:${O}`),e("\n\uD83D\uDC40 Watching for changes...\n")}}catch(e){
|
|
1
|
+
import{format as e}from"node:util";import{createServer as t}from"vite";import{runBuildCommand as r,setLambdaLocalLogger as o,webhookLogContext as s}from"../../webhook-cli/index.js";import{startEditorServer as n}from"../editor-server/index.js";import{DomainSpecProjectWatcher as i,LinguiWatcher as a,LogBus as l,MockTemplateWatcher as c,PhoenixPubSub as p,WebhookTunnelMonitor as d,createBusLogger as u,getViteDevConfig as m,patchConsole as g,setViteLogSink as w}from"../services/index.js";import{prepareDevelopmentEnvironment as v}from"../services/prepare-development-environment.js";import{createWebhookTunnelTransport as h,readOrCreateTunnelSessionId as f,startWebhookService as E}from"../services/webhook-service/index.js";import{startTui as b}from"../tui/index.js";import{FileLogger as S,createLogger as I,exists as k}from"../utils/index.js";import{generateProjectFilesAndInstallDependencies as T}from"./generate-project-files.js";import{readGeneratedEnvMarkers as x}from"./generated-env-markers.js";export const runDevCommand=async(N,$)=>{let{logger:j}=$,{sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,editorWsPort:O,debug:L=!1,withLingui:V=!1,persistenceMode:M,force:U=!1,tui:W=!1,serverUrl:C,developmentKey:Y,skipUpload:G}=N,B=null,H=null,X=null,q=null,F=null,J=null,K=new S,Q=new p,z=new l,A=W&&!!process.stdout.isTTY&&!!process.stdin.isTTY,Z=!A,ee=null;W&&!A&&j.warn("TUI requested but stdin/stdout is not an interactive terminal — falling back to plain log output. Run phoenix dev --tui directly in a terminal to use the TUI.");let et=null,er=j,eo=null,es=()=>{ee&&(ee(),ee=null),et&&(et.unmount(),et=null,er=I({debug:L,fileLogger:K}))},en=(e=0)=>eo||(eo=(async()=>{process.off("SIGINT",ei),process.off("SIGTERM",ei),process.off("uncaughtException",ea),es(),er.debug("Shutting down...");let t=[];for(let e of[{name:"lingui watcher",close:()=>q?.close()},{name:"project watcher",close:()=>J?.close()},{name:"mock template watcher",close:()=>F?.close()},{name:"editor server",close:()=>X?.close()},{name:"vite server",close:()=>B?.close()},{name:"webhook tunnel",close:()=>H?.stop()}])try{er.debug(`Shutting down ${e.name}`),await e.close()}catch(r){t.push(`${e.name}: ${r instanceof Error?r.message:String(r)}`)}t.length>0&&er.warn(`Cleanup warnings:
|
|
2
|
+
${t.join("\n ")}`),er.debug("Shutdown complete"),await K.close(),process.exit(e)})()),ei=()=>{en(0)},ea=e=>{es(),er.error(`Uncaught exception: ${e.message}`),en(1)};process.once("SIGINT",ei),process.once("SIGTERM",ei),process.once("uncaughtException",ea);try{await K.init(".phoenix"),er=u({bus:z,stream:"spec",debug:L,fileLogger:K,echo:!0}),w((e,t)=>z.push("vite",e,t),{echo:Z}),o({transports:[],log:(t,...r)=>{z.push("webhook","warn"===t||"error"===t?t:"info",e(...r)),Z&&process.stdout.write(`${e(t,...r)}
|
|
3
|
+
`)}}),Q.browserConsole$.subscribe(e=>{z.push("browser",e.level,e.source?`[${e.source}] ${e.message}`:e.message);let t=`[${e.source?`browser:${e.source}`:"browser"}] ${e.message}`;K.write("warn",t),Z&&process.stderr.write(`⚠️ ${t}
|
|
4
|
+
`)}),Z&&(ee=g(z,{echo:!0})),process.env.NODE_ENV="development",M&&(process.env.PERSISTENCE_MODE=M);let l=!M||"server"===M,p=l&&C?new d(C):void 0;if(er.step("Starting development mode"),!await k("spec")){er.error('Spec folder not found. Run "phoenix init" first.'),await en(1);return}if(l){if(!C||!Y)throw Error("Server persistence needs SERVER_URL and DEVELOPMENT_KEY. Create a development environment in Studio and paste its .env block into .env.");let e=await x(".env.generated");e?.PHOENIX_PROJECT_SLUG!==D||e.PHOENIX_ENVIRONMENT_SLUG!==P||e.PHOENIX_SERVER_URL!==C?(er.step("Preparing development deployment"),await v({serverUrl:C,projectSlug:D,environmentSlug:P,developmentKey:Y,outFile:".env.generated",skipUpload:G,overrideSchema:!0,debug:L,projectVersion:R},{logger:er})):er.debug(".env.generated matches the current development environment, skipping prepare")}er.step("Building project files");let{templateFiles:S}=await T({sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,withLingui:V,force:U},{logger:er});if(er.success("Project files built successfully"),A&&(er=u({bus:z,stream:"spec",debug:L,fileLogger:K}),ee=g(z),et=b(z,{onQuit:()=>void en(0)})),V?(q=new a({logger:er})).start():er.warn("Lingui is disabled: i18n messages are not extracted or compiled during dev. Pass --withLingui or set WITH_LINGUI=true to enable."),l&&(er.step("Building webhooks"),await s.run("webhook",async()=>{await r({experimental:!0,skipNodeEnvOverride:!0,webhookEntryPoint:void 0})})),l&&C&&Y){let e=await x(".env.generated");if(!e?.DEPLOYMENT_ID)throw Error("Webhook tunnel cannot start because .env.generated has no DEPLOYMENT_ID. Rerun phoenix dev to prepare the development deployment.");let t=await f();H=await E({experimental:!0,transport:h({serverUrl:C,developmentKey:Y,projectSlug:D,environmentSlug:P}),projectSlug:D,environmentSlug:P,deploymentId:e.DEPLOYMENT_ID,sessionId:t,onStatus:(r,o)=>{p?.setStatus(r,{deploymentId:e.DEPLOYMENT_ID,sessionId:t,message:o??null})},onRequest:e=>p?.record(e)}),p?.setStatus("waiting",{deploymentId:e.DEPLOYMENT_ID,sessionId:t}),H.stopped.catch(e=>{es(),er.error(`Webhook tunnel failed: ${e instanceof Error?e.message:String(e)}`),en(1)}),er.success("Webhook tunnel started")}if(y&&O){er.step("Starting editor WebSocket server");let e=parseInt(O,10);X=n({port:e,projectRoot:process.cwd(),pubsub:Q,logger:er,logBus:z,tunnelMonitor:p,debug:L,prepareDeployment:l&&C&&Y?()=>v({serverUrl:C,projectSlug:D,environmentSlug:P,developmentKey:Y,outFile:".env.generated",skipUpload:!0,overrideSchema:!0,debug:!1,projectVersion:R},{logger:er}):void 0}),await X.ready,er.debug(`Editor WebSocket server started on port ${e}`),(F=new c({projectRoot:process.cwd(),pubsub:Q,logger:er})).start()}let I=await m({templateFiles:S});if(B=await t(I),await B.listen(),er.step("Starting Vite dev server"),(J=new i({viteServer:B,sdkVersion:R,projectSlug:D,environmentSlug:P,cliUseWorkspace:_,enableEditor:y,useServer:l,logger:er,onRebuilt:()=>q?.trigger(),onViteServerChange:e=>{B=e}})).start(),A)er.success("Vite dev server started — watching for changes"),y&&O&&er.info(`Editor WebSocket: ws://localhost:${O}`);else if(L)er.success("Vite dev server started");else{let e=e=>{z.push("spec","info",e),process.stdout.write(`${e}
|
|
5
|
+
`)};e("\n\uD83D\uDE80 Phoenix Dev Server\n"),y&&O&&e(`Editor WebSocket: ws://localhost:${O}`),e("\n\uD83D\uDC40 Watching for changes...\n")}}catch(e){es(),er.error(`Dev mode failed: ${e instanceof Error?e.message:String(e)}`,e),await en(1)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const envExampleFile = "# This file documents developer-supplied Phoenix variables. Copy the values you\n# need into an untracked .env; never commit .env.\n# phoenix dev, deployment:prepare-dev, and deployment:prepare-local write\n# server-generated values to .env.generated; do not maintain them here.\n\n# ============================================================================\n# Development environment (phoenix dev and deployment:prepare-dev)\n# ============================================================================\n# Create a development environment in PHX Studio and paste its block here.\n#\n# SERVER_URL=http://localhost:3000\n# PROJECT_SLUG=<project-slug>\n# ENVIRONMENT_SLUG=<development-environment-slug>\n# DEVELOPMENT_KEY=<development-key>\n\n# ============================================================================\n# Shared-server access (deployment:prepare-local and CI commands only)\n# ============================================================================\n# Ask DevOps for these values when using the legacy prepare-local or CI flows.\n# SERVER_URL=https://phoenix.example.com\n# ENVIRONMENT_API_KEY=<shared-server-api-key>\n# PROJECT_KEY=<shared-server-project-key>\n# PROJECT_SLUG=<project-slug>\n# ENVIRONMENT_SLUG=<environment-slug>\n# LAMBDA_URL=http://localhost:8080\n\n# ============================================================================\n# Dev Configuration (phoenix dev)\n# ============================================================================\n# Override these to run multiple projects simultaneously.\n# Ports auto-increment if occupied, but setting explicit values avoids surprises.\n#\n# EDITOR_WS_PORT=3020\n# ENABLE_EDITOR=true\n# Enable Lingui extraction and compilation during dev. Phoenix warns when this is disabled.\n# WITH_LINGUI=false\n# DEBUG=false\n# FORCE_REBUILD=false\n# USE_APPLICATION_SPEC=false\n# IS_DEV=true\n#\n# Persistence mode controls how configurator state is stored.\n# Options: 'server' (default), 'local-storage', 'memory'\n# PERSISTENCE_MODE=server\n\n# deployment:prepare-dev and deployment:prepare-local output and behavior overrides:\n# OUT_FILE=.env.generated\n# SKIP_UPLOAD=false\n# OVERRIDE_SCHEMA=true\n\n# ============================================================================\n# Project-Specific Environment Variables\n# ============================================================================\n# Additional environment variables can be defined in spec/application.yaml\n# under the 'env.frontend' and 'env.webhook' sections.\n#\n# These are useful for project-specific needs such as:\n# - Third-party API keys (e.g., salesforce)\n# - External service URLs\n# - Feature flags\n# - Custom configuration values\n#\n# Example in spec/application.yaml:\n# env:\n# frontend:\n# SALESFORCE_CLIENT_ID:\n# type: str\n# devDefault: pk_test_xxx\n# webhook:\n# SALESFORCE_CLIENT_SECRET:\n# type: str\n# SALESFORCE_REDIRECT_URI:\n# type: str\n#\n# These will be automatically validated and available in your code via\n# the generated frontend.config.ts and webhooks.config.ts files.\n#\n# IMPORTANT: If you add required custom environment variables (without defaults),\n# remember to also add them to .env.ci with mock values so CI builds can succeed.\n\n# ============================================================================\n# Generated environment\n# ============================================================================\n# Deployment variables (DEPLOYMENT_ID, RESOURCES_URL, and related values)\n# are auto-generated by the PHX server and written to .env.generated when you run\n# phoenix dev, deployment:prepare-dev, or deployment:prepare-local. Development\n# environment settings can be managed via PHX Studio.\n";
|
|
1
|
+
export declare const envExampleFile = "# This file documents developer-supplied Phoenix variables. Copy the values you\n# need into an untracked .env; never commit .env.\n# phoenix dev, deployment:prepare-dev, and deployment:prepare-local write\n# server-generated values to .env.generated; do not maintain them here.\n\n# ============================================================================\n# Development environment (phoenix dev and deployment:prepare-dev)\n# ============================================================================\n# Create a development environment in PHX Studio and paste its block here.\n#\n# SERVER_URL=http://localhost:3000\n# PROJECT_SLUG=<project-slug>\n# ENVIRONMENT_SLUG=<development-environment-slug>\n# DEVELOPMENT_KEY=<development-key>\n\n# ============================================================================\n# Shared-server access (deployment:prepare-local and CI commands only)\n# ============================================================================\n# Ask DevOps for these values when using the legacy prepare-local or CI flows.\n# SERVER_URL=https://phoenix.example.com\n# ENVIRONMENT_API_KEY=<shared-server-api-key>\n# PROJECT_KEY=<shared-server-project-key>\n# PROJECT_SLUG=<project-slug>\n# ENVIRONMENT_SLUG=<environment-slug>\n# LAMBDA_URL=http://localhost:8080\n\n# ============================================================================\n# Dev Configuration (phoenix dev)\n# ============================================================================\n# Override these to run multiple projects simultaneously.\n# Ports auto-increment if occupied, but setting explicit values avoids surprises.\n#\n# EDITOR_WS_PORT=3020\n# ENABLE_EDITOR=true\n# Enable Lingui extraction and compilation during dev. Phoenix warns when this is disabled.\n# WITH_LINGUI=false\n# DEBUG=false\n# FORCE_REBUILD=false\n# USE_APPLICATION_SPEC=false\n# IS_DEV=true\n#\n# Persistence mode controls how configurator state is stored.\n# Options: 'server' (default), 'local-storage', 'memory'\n# PERSISTENCE_MODE=server\n\n# deployment:prepare-dev and deployment:prepare-local output and behavior overrides:\n# OUT_FILE=.env.generated\n# SKIP_UPLOAD also applies to the deployment phoenix dev prepares at startup.\n# SKIP_UPLOAD=false\n# OVERRIDE_SCHEMA=true\n\n# ============================================================================\n# Project-Specific Environment Variables\n# ============================================================================\n# Additional environment variables can be defined in spec/application.yaml\n# under the 'env.frontend' and 'env.webhook' sections.\n#\n# These are useful for project-specific needs such as:\n# - Third-party API keys (e.g., salesforce)\n# - External service URLs\n# - Feature flags\n# - Custom configuration values\n#\n# Example in spec/application.yaml:\n# env:\n# frontend:\n# SALESFORCE_CLIENT_ID:\n# type: str\n# devDefault: pk_test_xxx\n# webhook:\n# SALESFORCE_CLIENT_SECRET:\n# type: str\n# SALESFORCE_REDIRECT_URI:\n# type: str\n#\n# These will be automatically validated and available in your code via\n# the generated frontend.config.ts and webhooks.config.ts files.\n#\n# IMPORTANT: If you add required custom environment variables (without defaults),\n# remember to also add them to .env.ci with mock values so CI builds can succeed.\n\n# ============================================================================\n# Generated environment\n# ============================================================================\n# Deployment variables (DEPLOYMENT_ID, RESOURCES_URL, and related values)\n# are auto-generated by the PHX server and written to .env.generated when you run\n# phoenix dev, deployment:prepare-dev, or deployment:prepare-local. Development\n# environment settings can be managed via PHX Studio.\n";
|
|
@@ -45,6 +45,7 @@ export const envExampleFile=`# This file documents developer-supplied Phoenix va
|
|
|
45
45
|
|
|
46
46
|
# deployment:prepare-dev and deployment:prepare-local output and behavior overrides:
|
|
47
47
|
# OUT_FILE=.env.generated
|
|
48
|
+
# SKIP_UPLOAD also applies to the deployment phoenix dev prepares at startup.
|
|
48
49
|
# SKIP_UPLOAD=false
|
|
49
50
|
# OVERRIDE_SCHEMA=true
|
|
50
51
|
|
|
@@ -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."],
|
|
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."],n=["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."],a=["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 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."],s=["- 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."];export const generateAssistantPrompt=h=>{let d=/^type Mutation\b/m.test(h.sdl);return[e,...d?[t]:[],.../^\s+addChild\(/m.test(h.sdl)?[n]:[],.../^\s+replaceEntity\(/m.test(h.sdl)?[a]:[],.../^type FieldOption\b/m.test(h.sdl)?[i]:[],[...o,...d?r:s]].map(e=>e.join("\n")).join("\n\n")};
|