@nice2dev/ui-forms 1.3.16 → 1.3.18

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/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),ke=require("@nice2dev/ui-core"),b=require("react"),h=require("@nice2dev/ui"),P=require("./studio.cjs");function Rt(t){var a,d;const i={text:"text",email:"email",password:"password",phone:"phone",url:"url",textarea:"textarea",number:"number",date:"date",datetime:"datetime",time:"time",select:"select",multiselect:"tags",checkbox:"checkbox",toggle:"toggle",radio:"radio",slider:"slider",rating:"rating",color:"color",file:"file",image:"file"},n=[];for(const s of t.sections)for(const o of s.fields)o.type==="heading"||o.type==="paragraph"||o.type==="divider"||o.type==="spacer"||o.type==="section"||n.push({field:o.name,label:o.label||o.name,type:i[o.type]||"text",placeholder:o.placeholder,hint:o.helpText,defaultValue:o.defaultValue,required:o.required||((a=o.validations)==null?void 0:a.some(u=>u.type==="required")),disabled:o.disabled,readOnly:o.readonly,group:s.title,options:(d=o.options)==null?void 0:d.map(u=>typeof u=="string"?{label:u,value:u}:{label:u.label,value:u.value})});return n}function lt(t){var n;const i={text:"NiceTextInput",textarea:"NiceTextArea",number:"NiceNumberInput",email:"NiceTextInput",password:"NicePasswordInput",date:"NiceDateTimePicker",datetime:"NiceDateTimePicker",time:"NiceDateTimePicker",select:"NiceSelect",multiselect:"NiceTagBox",checkbox:"NiceCheckbox",toggle:"NiceToggle",radio:"NiceRadioGroup",slider:"NiceSlider",rating:"NiceRating",color:"NiceColorPicker"};return{dataField:t.name,label:{text:t.label},editorType:i[t.type]||"NiceTextInput",editorOptions:{placeholder:t.placeholder,disabled:t.disabled,readOnly:t.readonly,...t.props},colSpan:Math.ceil((t.colSpan||12)/6),validationRules:(n=t.validations)==null?void 0:n.map(a=>({type:a.type,message:a.message,...a.value!==void 0?{[a.type]:a.value}:{}})),helpText:t.helpText}}function At(t){const i=[];for(const n of t.sections)n.title?i.push({itemType:"group",caption:n.title,colCount:n.columns||2,items:n.fields.map(lt)}):i.push(...n.fields.map(lt));return i}function Lt(t){const i=[];t.version||i.push("Missing schema version"),t.id||i.push("Missing form ID"),(!t.sections||t.sections.length===0)&&i.push("Form must have at least one section");const n=new Set;for(const a of t.sections||[])for(const d of a.fields||[])d.id||i.push(`Field missing ID: ${d.name}`),d.name||i.push(`Field missing name: ${d.id}`),n.has(d.name)&&i.push(`Duplicate field name: ${d.name}`),n.add(d.name);return{valid:i.length===0,errors:i}}const qt={text:"text",string:"text",textarea:"textarea",number:"number",integer:"number",email:"email",password:"password",phone:"phone",tel:"phone",url:"url",date:"date",datetime:"datetime",time:"time",select:"select",dropdown:"select",multiselect:"multiselect",checkbox:"checkbox",boolean:"checkbox",toggle:"toggle",switch:"toggle",radio:"radio",slider:"slider",range:"slider",rating:"rating",stars:"rating",color:"color",file:"file",upload:"file",signature:"signature",richtext:"richtext",markdown:"markdown"};function xt(t){return qt[String(t??"").toLowerCase()]??"text"}function Vt(t){return(Array.isArray(t)?t:t.fields).map((n,a)=>{const d=n.name??n.field??n.id??`field${a+1}`,s=n.validation??{},o=[],u=(c,l)=>{l!==void 0&&o.push({type:c,value:l,...s.message?{message:s.message}:{}})};return u("min",s.min),u("max",s.max),u("minLength",s.minLength),u("maxLength",s.maxLength),u("pattern",s.pattern),{id:n.id??d,name:d,type:xt(n.type),...n.label!==void 0?{label:n.label}:{},...n.placeholder!==void 0?{placeholder:n.placeholder}:{},...n.helpText!==void 0?{helpText:n.helpText}:{},...n.defaultValue!==void 0?{defaultValue:n.defaultValue}:{},...n.required?{required:!0}:{},...n.options?{options:[...n.options]}:{},...o.length?{validations:o}:{}}})}const Wt={text:{type:"string"},textarea:{type:"string"},password:{type:"string",format:"password"},phone:{type:"string",format:"phone"},url:{type:"string",format:"uri"},email:{type:"string",format:"email"},date:{type:"string",format:"date"},datetime:{type:"string",format:"date-time"},time:{type:"string",format:"time"},color:{type:"string",format:"color"},number:{type:"number"},slider:{type:"number"},rating:{type:"integer"},checkbox:{type:"boolean"},toggle:{type:"boolean"},select:{type:"string"},radio:{type:"string"},multiselect:{type:"array",items:{type:"string"}},file:{type:"string",format:"data-url"},signature:{type:"string",format:"data-url"},richtext:{type:"string"},markdown:{type:"string"},code:{type:"string"},image:{type:"string",format:"uri"}};function Jt(t,i){if(i)for(const n of i)switch(n.type){case"minLength":typeof n.value=="number"&&(t.minLength=n.value);break;case"maxLength":typeof n.value=="number"&&(t.maxLength=n.value);break;case"min":typeof n.value=="number"&&(t.minimum=n.value);break;case"max":typeof n.value=="number"&&(t.maximum=n.value);break;case"pattern":typeof n.value=="string"&&(t.pattern=n.value);break;case"email":t.format="email";break;case"url":t.format="uri";break}}function Gt(t){if(t.type==="heading"||t.type==="paragraph"||t.type==="divider"||t.type==="spacer")return null;const i=Wt[t.type];if(!i)return null;const n={...i};return t.label&&(n.title=t.label),t.helpText&&(n.description=t.helpText),t.defaultValue!==void 0&&(n.default=t.defaultValue),t.options&&(t.type==="select"||t.type==="radio")&&(n.enum=t.options.map(a=>typeof a=="string"?a:a.value)),t.options&&t.type==="multiselect"&&(n.items={type:"string",enum:t.options.map(a=>typeof a=="string"?a:String(a.value))}),Jt(n,t.validations),n}function Ut(t){const i={},n=[],a=s=>{var o;for(const u of s){if(u.type==="section"&&u.children){a(u.children);continue}const c=Gt(u);c&&(i[u.name]=c,(u.required||(o=u.validations)!=null&&o.some(l=>l.type==="required"))&&n.push(u.name))}};for(const s of t.sections)a(s.fields);const d={$schema:"http://json-schema.org/draft-07/schema#",$id:t.id,type:"object",title:t.title,description:t.description,properties:i,additionalProperties:!1};return n.length>0&&(d.required=n),d}function ct(t){const{t:i}=ke.useNiceTranslation(),{value:n,onChange:a,readOnly:d}=t,[s,o]=b.useState(()=>{try{return n===void 0?"":JSON.stringify(n,null,2)}catch{return""}}),[u,c]=b.useState(null);return b.useEffect(()=>{try{o(n===void 0?"":JSON.stringify(n,null,2))}catch{}},[JSON.stringify(n)]),e.jsxs("div",{className:"nice-schema-form__json-field",children:[e.jsx("textarea",{className:"nice-schema-form__json-textarea",value:s,readOnly:d,spellCheck:!1,rows:Math.min(12,Math.max(3,s.split(`
2
- `).length)),onChange:l=>{const r=l.target.value;o(r);const p=r.trim();if(p===""){c(null),a(void 0);return}try{a(JSON.parse(p)),c(null)}catch(m){c(m instanceof Error?m.message:i("jsonSchemaToFormItems.invalidJson","Invalid JSON"))}}}),u&&e.jsx("div",{className:"nice-schema-form__json-error",children:u})]})}function Ht(t){switch(t){case"email":return"email";case"uri":case"url":return"url";case"date":return"date";case"date-time":return"datetime";case"time":return"time";case"color":return"color";case"password":return"password";case"phone":return"phone";case"data-url":return"file";default:return"text"}}function Yt(t,i,n,a={}){const d={field:t,label:i.title??t,required:n,hint:i.description,defaultValue:i.default};if(i.enum&&i.enum.length>0)return{...d,type:"select",options:i.enum.map(s=>({label:String(s),value:s}))};switch(i.type){case"number":case"integer":return{...d,type:"number"};case"boolean":return{...d,type:"checkbox"};case"string":return{...d,type:Ht(i.format)};case"array":{const s=i.items;if(s!=null&&s.enum&&s.enum.length>0)return{...d,type:"tags",options:s.enum.map(o=>({label:String(o),value:String(o)}))};if((s==null?void 0:s.type)==="object"&&s.properties&&a.renderArrayField){const o=a.renderArrayField;return{...d,render:(u,c)=>o(u??[],c,s,d.label)}}return(s==null?void 0:s.type)==="string"||(s==null?void 0:s.type)==="number"||(s==null?void 0:s.type)==="integer"?{...d,type:"tags"}:{...d,render:(o,u)=>e.jsx(ct,{value:o,onChange:u})}}case"object":if(a.renderObjectField){const s=a.renderObjectField;return{...d,render:(o,u)=>s(o??{},u,i,d.label)}}return{...d,render:(s,o)=>e.jsx(ct,{value:s,onChange:o})};default:return{...d,type:"text"}}}function Ge(t,i={}){const{uiSchema:n,renderArrayField:a,renderObjectField:d}=i,s={renderArrayField:a,renderObjectField:d},o=t.properties??{},u=new Set(t.required??[]);return Object.keys(o).map(c=>{const l=Yt(c,o[c],u.has(c),s);return n!=null&&n[c]?{...l,...n[c]}:l})}const Xt={text:"text",textarea:"textarea",number:"number",email:"email",password:"password",phone:"phone",url:"url",date:"date",datetime:"datetime",time:"time",select:"select",multiselect:"tags",checkbox:"checkbox",toggle:"toggle",radio:"radio",slider:"slider",rating:"rating",color:"color"};function Ue(t,i={}){var d,s;const{uiSchema:n}=i,a=[];for(const o of t){if(o.type==="section"&&o.children){for(const l of Ue(o.children,i))a.push(o.label?{...l,group:o.label}:l);continue}const u=Xt[o.type];if(!u)continue;const c={field:o.name,label:o.label,type:u,required:o.required||((d=o.validations)==null?void 0:d.some(l=>l.type==="required")),placeholder:o.placeholder,hint:o.helpText,defaultValue:o.defaultValue,disabled:o.disabled,readOnly:o.readonly,options:(s=o.options)==null?void 0:s.map(l=>typeof l=="string"?{label:l,value:l}:{label:l.label,value:l.value})};a.push(n!=null&&n[o.name]?{...c,...n[o.name]}:c)}return a}function ut(t){return t==null||t===""||Array.isArray(t)&&t.length===0}function He(t,i){const n=[],a=i.properties??{},d=new Set(i.required??[]);for(const s of Object.keys(a)){const o=a[s],u=t[s];if(d.has(s)&&ut(u)){n.push({field:s,message:`${o.title??s} is required`});continue}if(!ut(u)&&(o.enum&&!o.enum.includes(u)&&n.push({field:s,message:`${o.title??s} must be one of: ${o.enum.join(", ")}`}),(o.type==="number"||o.type==="integer")&&typeof u=="number"&&(o.minimum!==void 0&&u<o.minimum&&n.push({field:s,message:`${o.title??s} must be ≥ ${o.minimum}`}),o.maximum!==void 0&&u>o.maximum&&n.push({field:s,message:`${o.title??s} must be ≤ ${o.maximum}`})),o.type==="string"&&typeof u=="string"&&(o.minLength!==void 0&&u.length<o.minLength&&n.push({field:s,message:`${o.title??s} must be at least ${o.minLength} chars`}),o.maxLength!==void 0&&u.length>o.maxLength&&n.push({field:s,message:`${o.title??s} must be at most ${o.maxLength} chars`}),o.pattern)))try{new RegExp(o.pattern).test(u)||n.push({field:s,message:`${o.title??s} has an invalid format`})}catch{}}return n}const Re="__nafRid";function Zt(t){return Array.isArray(t)?`[${t.length}]`:t&&typeof t=="object"?"{…}":t==null?"":String(t)}const Ye=b.forwardRef(function(i,n){const{value:a,defaultValue:d,onChange:s,itemSchema:o,title:u,readOnly:c=!1,columns:l,className:r,style:p,"data-testid":m}=i,[g,v]=h.useControllableState({value:a,defaultValue:d,fallbackValue:[],onChange:s,componentName:"NiceArrayField"}),f=o.properties??{},j=b.useMemo(()=>(l??Object.keys(f)).map(x=>{const k=f[x]??{},M={field:x,header:k.title??x};return k.type==="boolean"?(M.render=V=>V?e.jsx(h.NiceIcon,{name:"check",size:14,title:"true"}):"",M.align="center"):(k.type==="array"||k.type==="object")&&(M.render=V=>Zt(V)),M}),[o,l]),N=b.useMemo(()=>Ge(o),[o]),$=b.useMemo(()=>g.map((y,x)=>({...y,[Re]:String(x)})),[g]),O=y=>{const{[Re]:x,...k}=y;return k},_="nice-array-field"+(r?` ${r}`:"");return e.jsx("div",{ref:n,className:_,style:p,"data-testid":m,children:e.jsx(h.NiceDataGrid,{data:$,keyField:Re,columns:j,editMode:"popup",formItems:N,editFormTitle:u?`${u} — item`:"Edit item",emptyText:`No items${u?` in ${u}`:""}`,compact:!0,onRowAdd:c?void 0:y=>v([...g,O(y)]),onRowEdit:c?void 0:(y,x)=>{const k=Number(y);v(g.map((M,V)=>V===k?O(x):M))},onRowDelete:c?void 0:y=>{const x=Number(y);v(g.filter((k,M)=>M!==x))}})})}),Qt=[{target:".nice-schema-form",titleKey:"tutorial.schemaForm.intro.title",title:"Schema form",contentKey:"tutorial.schemaForm.intro.content",content:"This form is generated from a schema. Required fields and validation errors are flagged; use the JSON toggle for raw editing.",placement:"auto"},{target:'[data-tour="sf-viewtoggle"]',titleKey:"tutorial.schemaForm.viewToggle.title",title:"Form ⇄ JSON",contentKey:"tutorial.schemaForm.viewToggle.content",content:"Switch between the visual form and the raw JSON value — handy for power users and copy/paste.",placement:"bottom"},{target:".nice-schema-form",titleKey:"tutorial.schemaForm.validation.title",title:"Live validation",contentKey:"tutorial.schemaForm.validation.content",content:"Values are validated against the schema as you type; any problems are listed below the form.",placement:"auto"}];function ei(t){const i=[],n=a=>{for(const d of a){if(d.type==="section"&&d.children){n(d.children);continue}d.required&&i.push({id:`${d.name}-required`,field:d.name,op:"required"});for(const s of d.validations??[])i.push({id:`${d.name}-${s.type}`,field:d.name,op:s.type,value:typeof s.value=="boolean"?void 0:s.value,message:s.message??(s.type==="required"?`${d.label??d.name} is required`:void 0)})}};return n(t),i}function ti(t,i){return h.evaluateValidation(ei(t),i).filter(n=>n.severity==="error").map(n=>({field:n.field,message:n.message}))}const _e=b.forwardRef(function(i,n){const{schema:a,fields:d,uiSchema:s,value:o,defaultValue:u,onChange:c,onValidate:l,showJsonView:r=!1,columns:p=1,labelPosition:m="top",readOnly:g=!1,liveValidation:v=!0,validationRules:f,tutorial:j,className:N,style:$,id:O,"data-testid":_}=i,{t:y}=h.useNiceTranslation(),[x,k]=h.useControllableState({value:o,defaultValue:u,fallbackValue:{},onChange:c,componentName:"NiceSchemaForm"}),[M,V]=b.useState(!1),[D,G]=b.useState(""),[te,Q]=b.useState(null),H=b.useMemo(()=>a?Ge(a,{uiSchema:s,renderArrayField:(L,Z,U,z)=>e.jsx(Ye,{value:L,onChange:Z,itemSchema:U,title:z,readOnly:g})}):d?Ue(d,{uiSchema:s}):[],[a,d,s,g]),C=b.useMemo(()=>{const L=a?He(x,a):d?ti(d,x):[];if(f!=null&&f.length){const Z=h.evaluateValidation(f,x).filter(U=>U.severity==="error").map(U=>({field:U.field,message:U.message}));return[...L,...Z]}return L},[a,d,x,f]);b.useEffect(()=>{l==null||l(C)},[C,l]),b.useEffect(()=>{if(M)try{G(JSON.stringify(x,null,2)),Q(null)}catch{}},[M,x]);const E=(L,Z)=>{k({...x,[L]:Z})},B="nice-schema-form"+(N?` ${N}`:"");return e.jsxs("div",{ref:n,id:O,className:B,style:$,"data-testid":_,children:[j&&e.jsx("div",{className:"nice-schema-form__tutorial",children:e.jsx(h.NiceTutorialButton,{steps:h.resolveTutorial(j,Qt)})}),r&&e.jsxs("div",{className:"nice-schema-form__toolbar","data-tour":"sf-viewtoggle",children:[e.jsx("button",{type:"button",className:"nice-schema-form__tab"+(M?"":" nice-schema-form__tab--active"),onClick:()=>V(!1),children:y("schemaForm.tab.form","Form")}),e.jsx(h.NiceTooltip,{content:y("schemaForm.tab.json.help","Edit the raw JSON value directly"),children:e.jsx("button",{type:"button",className:"nice-schema-form__tab"+(M?" nice-schema-form__tab--active":""),onClick:()=>V(!0),children:y("schemaForm.tab.json","JSON")})})]}),M?e.jsxs("div",{className:"nice-schema-form__json",children:[e.jsx("textarea",{className:"nice-schema-form__json-textarea",value:D,readOnly:g,spellCheck:!1,rows:Math.min(24,Math.max(6,D.split(`
3
- `).length)),onChange:L=>{const Z=L.target.value;G(Z);try{const U=JSON.parse(Z);Q(null),k(U)}catch(U){Q(U instanceof Error?U.message:y("schemaForm.invalidJson","Invalid JSON"))}}}),te&&e.jsx("div",{className:"nice-schema-form__json-error",children:te})]}):e.jsx(h.NiceForm,{items:H,data:x,onFieldChange:E,columns:p,labelPosition:m,readOnly:g}),v&&C.length>0&&e.jsx("ul",{className:"nice-schema-form__errors",role:"alert",children:C.map((L,Z)=>e.jsx("li",{className:"nice-schema-form__error",children:L.message},`${L.field}-${Z}`))})]})}),Ae="__eeFid",ii={},kt={type:"object",properties:{name:{type:"string",title:"Name",minLength:1,description:"Unique technical name of the entity (PascalCase)."},displayName:{type:"string",title:"Display name",description:"Human-friendly name shown in the UI."},tableName:{type:"string",title:"Table name",description:"Database table that backs this entity."},description:{type:"string",title:"Description",description:"Optional notes about the entity's purpose."},entityIcon:{type:"string",title:"Icon",description:"Icon key shown next to the entity."},isAudited:{type:"boolean",title:"Audited",description:"Track who created/changed each record and when."},isSoftDeleteEnabled:{type:"boolean",title:"Soft delete",description:"Flag rows as deleted instead of physically removing them."}},required:["name"]},bt={type:"object",properties:{name:{type:"string",title:"Name",minLength:1,description:"Field's technical name (the database column)."},displayName:{type:"string",title:"Display name",description:"Human-friendly label shown in the UI."},dataType:{type:"string",title:"Type",description:"Storage / data type of the field.",enum:["Guid","string","text","int","long","decimal","double","bool","DateTime","DateOnly","json"]},isPrimaryKey:{type:"boolean",title:"Primary key",description:"Primary key — uniquely identifies each record."},isForeignKey:{type:"boolean",title:"Foreign key",description:"Foreign key — references another entity's primary key."},isRequired:{type:"boolean",title:"Required",description:"Value must be provided (NOT NULL)."},isUnique:{type:"boolean",title:"Unique",description:"Each value must be unique across all records."},isIndexed:{type:"boolean",title:"Indexed",description:"Add a database index for faster lookups and filtering."},isNullable:{type:"boolean",title:"Nullable",description:"Allow empty (NULL) values."},maxLength:{type:"integer",title:"Max length",description:"Maximum number of characters (for string types)."},defaultValue:{type:"string",title:"Default",description:"Value used when none is provided."},description:{type:"string",title:"Description",description:"Optional notes about the field."},isComputed:{type:"boolean",title:"Computed",description:"Value is derived from an expression instead of stored input."},computedExpression:{type:"string",title:"Computed expression",description:"Expression used to compute the value (when Computed is on)."}},required:["name","dataType"]};function Le({title:t,help:i}){return e.jsxs("span",{className:"nice-entity-editor__field-label",children:[t,i?e.jsx(h.NiceTooltip,{content:i,children:e.jsx("span",{className:"nice-entity-editor__help",role:"img","aria-label":i,children:e.jsx(h.NiceIcon,{name:"info",size:14})})}):null]})}function ni({schema:t,value:i,onChange:n,readOnly:a}){const d=t.properties??{};return e.jsx("div",{className:"nice-entity-editor__field-form",children:Object.entries(d).map(([s,o])=>{const u=i[s],c=o.description,l=o.title??s;if(o.type==="boolean")return e.jsx("div",{className:"nice-entity-editor__field-row nice-entity-editor__field-row--check",children:e.jsx(h.NiceCheckbox,{label:e.jsx(Le,{title:l,help:c}),checked:!!u,onChange:p=>n(s,p),disabled:a})},s);if(Array.isArray(o.enum)&&o.enum.length>0)return e.jsxs("div",{className:"nice-entity-editor__field-row",children:[e.jsx(Le,{title:l,help:c}),e.jsx(h.NiceSelect,{options:o.enum.map(p=>({label:String(p),value:String(p)})),value:u==null?"":String(u),onChange:p=>n(s,p),clearable:!0,disabled:a})]},s);const r=o.type==="integer"||o.type==="number";return e.jsxs("div",{className:"nice-entity-editor__field-row",children:[e.jsx(Le,{title:l,help:c}),e.jsx(h.NiceTextInput,{value:u==null?"":String(u),onChange:p=>n(s,r?p===""?void 0:Number(p):p),disabled:a})]},s)})})}function si({fields:t,onChange:i,fieldSchema:n,readOnly:a}){const{t:d}=h.useNiceTranslation(),[s,o]=b.useState(null),u=b.useMemo(()=>t.map((p,m)=>({...p,[Ae]:String(m)})),[t]),c=b.useMemo(()=>[{field:"name",header:d("entityEditor.field.name","Name"),sortable:!0,render:p=>e.jsx("span",{className:"nice-entity-editor__name",children:String(p??"")})},{field:"dataType",header:d("entityEditor.field.type","Type"),sortable:!0,render:p=>e.jsx(h.NiceBadge,{variant:"secondary",size:"sm",outline:!0,children:String(p??"—")})},{field:"__flags",header:d("entityEditor.field.flags","Constraints"),headerTooltip:d("entityEditor.field.flags.help","Key / required / unique / indexed constraints on this field"),render:(p,m)=>{const g=[[!!(m!=null&&m.isPrimaryKey),"PK",d("entityEditor.flag.pk","Primary key"),"info"],[!!(m!=null&&m.isForeignKey),"FK",d("entityEditor.flag.fk","Foreign key"),"info"],[!!(m!=null&&m.isRequired),"Req",d("entityEditor.flag.required","Required (NOT NULL)"),"warning"],[!!(m!=null&&m.isUnique),"Uniq",d("entityEditor.flag.unique","Unique"),"secondary"],[!!(m!=null&&m.isIndexed),"Idx",d("entityEditor.flag.indexed","Indexed"),"secondary"]];return e.jsx("span",{className:"nice-entity-editor__flags",children:g.filter(([v])=>v).map(([,v,f,j])=>e.jsx(h.NiceTooltip,{content:f,children:e.jsx(h.NiceBadge,{variant:j,size:"sm",children:v})},v))})}}],[]),l=(p,m,g)=>{i(t.map((v,f)=>f===p?{...v,[m]:g}:v))},r=()=>{const p=[...t,{name:`field${t.length+1}`,dataType:"string"}];i(p),o(p.length-1)};if(s!=null&&t[s]){const p=t[s];return e.jsxs("div",{className:"nice-entity-editor__field-detail",children:[e.jsxs("header",{className:"nice-entity-editor__edit-header",children:[e.jsx(h.NiceTooltip,{content:d("entityEditor.field.backHint","Back to the field list"),children:e.jsx(h.NiceButton,{variant:"ghost",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"arrow-left",size:14}),onClick:()=>o(null),children:d("entityEditor.field.back","Fields")})}),e.jsx("span",{className:"nice-entity-editor__breadcrumb-sep",children:"/"}),e.jsx("span",{className:"nice-entity-editor__edit-title",children:String(p.name??d("entityEditor.field.untitled","New field"))})]}),e.jsx(ni,{schema:n,value:p,onChange:(m,g)=>l(s,m,g),readOnly:a}),e.jsx("div",{className:"nice-entity-editor__field-detail-actions",children:e.jsx(h.NiceButton,{variant:"primary",size:"sm",onClick:()=>o(null),children:d("entityEditor.field.done","Done")})})]})}return e.jsx(h.NiceDataGrid,{data:u,keyField:Ae,columns:c,searchable:!0,searchPlaceholder:d("entityEditor.field.search","Search fields…"),emptyText:d("entityEditor.field.empty","No fields yet. Add one to define this entity."),onRowClick:p=>o(Number(p[Ae])),onRowDelete:a?void 0:p=>i(t.filter((m,g)=>g!==Number(p))),toolbar:a?void 0:e.jsx(h.NiceButton,{variant:"primary",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:r,children:d("entityEditor.field.add","Add field")}),compact:!0,striped:!0})}const Xe=b.forwardRef(function(i,n){const{value:a,defaultValue:d,onChange:s,entityMetaSchema:o=kt,fieldSchema:u=bt,fieldsKey:c="fields",validationsKey:l="validations",activeTab:r,defaultActiveTab:p="general",onActiveTabChange:m,extraTabs:g,readOnly:v=!1,className:f,style:j,id:N,"data-testid":$}=i,{t:O}=h.useNiceTranslation(),[_,y]=h.useControllableState({value:a,defaultValue:d,fallbackValue:ii,onChange:s,componentName:"NiceEntityForm"}),[x,k]=h.useControllableState({value:r,defaultValue:p,fallbackValue:"general",onChange:m,componentName:"NiceEntityForm"}),M=b.useMemo(()=>{const H=_[c];return Array.isArray(H)?H:[]},[_,c]),V=b.useMemo(()=>{const H=E=>{const B=E.toLowerCase();return/(int|long|decimal|double|float|number|money)/.test(B)?"number":/bool/.test(B)?"boolean":/date|time/.test(B)?"date":"string"},C=[];for(const E of M){const B=String(E.name??"");B&&C.push({field:B,label:String(E.displayName??B),type:H(String(E.dataType??"string"))})}return C},[M]),D=b.useMemo(()=>{const H=_[l];return Array.isArray(H)?H:[]},[_,l]),G=H=>{y({..._,...H})},te=[{id:"general",label:O("entityEditor.tab.general","General"),content:e.jsx(_e,{schema:o,value:_,onChange:H=>G(H),columns:2,readOnly:v,liveValidation:!0})},{id:"fields",label:O("entityEditor.tab.fields","Fields"),badge:M.length||void 0,content:e.jsx(si,{fields:M,onChange:H=>G({[c]:H}),fieldSchema:u,readOnly:v})},{id:"validation",label:O("entityEditor.tab.validation","Validation"),badge:D.length||void 0,content:e.jsx(h.NiceValidationBuilder,{fields:V,value:D,onChange:H=>G({[l]:H})})},...g??[]],Q="nice-entity-form"+(f?` ${f}`:"");return e.jsx("div",{ref:n,id:N,className:Q,style:j,"data-testid":$,children:e.jsx(h.NiceTabs,{tabs:te,activeTab:x,onChange:k,variant:"enclosed"})})}),qe="__eeRid",oi=[{target:".nice-entity-editor",titleKey:"tutorial.entityEditor.intro.title",title:"Entity editor",contentKey:"tutorial.entityEditor.intro.content",content:"Browse your entities in the list, then click one (or “New entity”) to edit its metadata, fields and validation on a dedicated screen.",placement:"auto"}],jt=b.forwardRef(function(i,n){const{value:a,defaultValue:d,onChange:s,entityMetaSchema:o=kt,fieldSchema:u=bt,fieldsKey:c="fields",validationsKey:l="validations",nameKey:r="name",renderErPreview:p,readOnly:m=!1,tutorial:g,className:v,style:f,id:j,"data-testid":N}=i,{t:$}=h.useNiceTranslation(),[O,_]=h.useControllableState({value:a,defaultValue:d,fallbackValue:[],onChange:s,componentName:"NiceEntityEditor"}),[y,x]=b.useState("list"),[k,M]=b.useState(0),[V,D]=b.useState("general"),G=Math.min(k,Math.max(0,O.length-1)),te=O[G],Q=y==="edit"&&te!=null,H=b.useMemo(()=>O.map((z,Y)=>({...z,[qe]:String(Y)})),[O]),C=z=>{M(z),D("general"),x("edit")},E=()=>{const z=[...O,{[r]:`Entity${O.length+1}`,[c]:[]}];_(z),M(z.length-1),D("general"),x("edit")},B=z=>{_(O.filter((Y,le)=>le!==z)),M(Y=>Y>=z?Math.max(0,Y-1):Y)},L=b.useMemo(()=>[{field:r,header:$("entityEditor.col.name","Name"),sortable:!0,render:z=>e.jsx("span",{className:"nice-entity-editor__name",children:String(z??"")})},{field:"displayName",header:$("entityEditor.col.displayName","Display name"),sortable:!0,render:z=>e.jsx("span",{className:"nice-entity-editor__muted",children:String(z??"—")})},{field:"tableName",header:$("entityEditor.col.table","Table"),sortable:!0,render:z=>e.jsx("span",{className:"nice-entity-editor__muted",children:String(z??"—")})},{field:c,header:$("entityEditor.col.fields","Fields"),align:"center",headerTooltip:$("entityEditor.col.fields.help","Number of fields defined on this entity"),render:z=>e.jsx(h.NiceBadge,{variant:"secondary",size:"sm",children:Array.isArray(z)?z.length:0})},{field:"__flags",header:$("entityEditor.col.flags","Flags"),render:(z,Y)=>e.jsxs("span",{className:"nice-entity-editor__flags",children:[Y!=null&&Y.isAudited?e.jsx(h.NiceTooltip,{content:$("entityEditor.flag.audited","Audited — tracks who changed each record and when"),children:e.jsx(h.NiceBadge,{variant:"info",size:"sm",outline:!0,children:$("entityEditor.flag.audited.abbr","Audit")})}):null,Y!=null&&Y.isSoftDeleteEnabled?e.jsx(h.NiceTooltip,{content:$("entityEditor.flag.softDelete","Soft delete — rows are flagged deleted, never physically removed"),children:e.jsx(h.NiceBadge,{variant:"secondary",size:"sm",outline:!0,children:$("entityEditor.flag.softDelete.abbr","Soft-del")})}):null]})}],[r,c]),Z=p?[{id:"er",label:$("entityEditor.tab.er","ER diagram"),content:e.jsx("div",{className:"nice-entity-editor__er",children:p(O)})}]:void 0,U="nice-entity-editor"+(v?` ${v}`:"");return e.jsxs("div",{ref:n,id:j,className:U,style:f,"data-testid":N,children:[g&&e.jsx("div",{className:"nice-entity-editor__tutorial",children:e.jsx(h.NiceTutorialButton,{steps:h.resolveTutorial(g,oi)})}),Q?e.jsxs("div",{className:"nice-entity-editor__edit",children:[e.jsxs("header",{className:"nice-entity-editor__edit-header",children:[e.jsx(h.NiceTooltip,{content:$("entityEditor.backHint","Back to the entity list"),children:e.jsx(h.NiceButton,{variant:"ghost",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"arrow-left",size:14}),onClick:()=>x("list"),children:$("entityEditor.back","Entities")})}),e.jsx("span",{className:"nice-entity-editor__breadcrumb-sep",children:"/"}),e.jsx("span",{className:"nice-entity-editor__edit-title",children:String((te==null?void 0:te[r])??$("entityEditor.untitled","Untitled entity"))}),!m&&e.jsx(h.NiceTooltip,{content:$("entityEditor.deleteHint","Delete this entity"),children:e.jsx(h.NiceButton,{variant:"ghost",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"trash",size:14}),onClick:()=>{B(G),x("list")},children:$("entityEditor.delete","Delete")})})]}),e.jsx(Xe,{value:te,onChange:z=>_(O.map((Y,le)=>le===G?z:Y)),entityMetaSchema:o,fieldSchema:u,fieldsKey:c,validationsKey:l,activeTab:V,onActiveTabChange:D,extraTabs:Z,readOnly:m})]}):e.jsx("div",{className:"nice-entity-editor__list-view",children:e.jsx(h.NiceDataGrid,{data:H,keyField:qe,columns:L,searchable:!0,searchPlaceholder:$("entityEditor.search","Search entities…"),emptyText:$("entityEditor.empty","No entities yet. Create one to get started."),onRowClick:z=>C(Number(z[qe])),onRowDelete:m?void 0:z=>B(Number(z)),toolbar:m?void 0:e.jsx(h.NiceButton,{variant:"primary",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:E,children:$("entityEditor.new","New entity")}),compact:!0,striped:!0})})]})}),ai=4e6;function di(t,i){const n=t.split(/\r?\n/),a=i.split(/\r?\n/);if(n.length*a.length>ai)return[...n.map(r=>({type:"remove",text:r})),...a.map(r=>({type:"add",text:r}))];const d=n.length,s=a.length,o=Array.from({length:d+1},()=>new Uint32Array(s+1));for(let r=d-1;r>=0;r--)for(let p=s-1;p>=0;p--)o[r][p]=n[r]===a[p]?o[r+1][p+1]+1:Math.max(o[r+1][p],o[r][p+1]);const u=[];let c=0,l=0;for(;c<d&&l<s;)n[c]===a[l]?(u.push({type:"same",text:n[c]}),c++,l++):o[c+1][l]>=o[c][l+1]?u.push({type:"remove",text:n[c++]}):u.push({type:"add",text:a[l++]});for(;c<d;)u.push({type:"remove",text:n[c++]});for(;l<s;)u.push({type:"add",text:a[l++]});return u}function St({before:t,after:i,context:n=3}){const{t:a}=h.useNiceTranslation(),d=b.useMemo(()=>{const s=di(t,i),o=new Set;s.forEach((l,r)=>{if(l.type!=="same")for(let p=Math.max(0,r-n);p<=Math.min(s.length-1,r+n);p++)o.add(p)});const u=[];let c=0;return s.forEach((l,r)=>{o.has(r)?(c>0&&(u.push({type:"gap",count:c}),c=0),u.push(l)):c++}),c>0&&u.length>0&&u.push({type:"gap",count:c}),u},[t,i,n]);return d.length===0?e.jsx("p",{className:"nice-development-studio__muted",children:a("devStudio.diff.none","No changes.")}):e.jsx("pre",{className:"nice-development-studio__diff","aria-label":a("devStudio.diff.label","Changes"),children:d.map((s,o)=>s.type==="gap"?e.jsxs("span",{className:"nice-development-studio__diff-gap",children:[a("devStudio.diff.unchanged","{count} unchanged lines").replace("{count}",String(s.count)),`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),ke=require("@nice2dev/ui-core"),b=require("react"),h=require("@nice2dev/ui"),P=require("./studio.cjs"),Rt=require("@nice2dev/ui-diagrams");function At(t){var a,d;const i={text:"text",email:"email",password:"password",phone:"phone",url:"url",textarea:"textarea",number:"number",date:"date",datetime:"datetime",time:"time",select:"select",multiselect:"tags",checkbox:"checkbox",toggle:"toggle",radio:"radio",slider:"slider",rating:"rating",color:"color",file:"file",image:"file"},n=[];for(const s of t.sections)for(const o of s.fields)o.type==="heading"||o.type==="paragraph"||o.type==="divider"||o.type==="spacer"||o.type==="section"||n.push({field:o.name,label:o.label||o.name,type:i[o.type]||"text",placeholder:o.placeholder,hint:o.helpText,defaultValue:o.defaultValue,required:o.required||((a=o.validations)==null?void 0:a.some(u=>u.type==="required")),disabled:o.disabled,readOnly:o.readonly,group:s.title,options:(d=o.options)==null?void 0:d.map(u=>typeof u=="string"?{label:u,value:u}:{label:u.label,value:u.value})});return n}function lt(t){var n;const i={text:"NiceTextInput",textarea:"NiceTextArea",number:"NiceNumberInput",email:"NiceTextInput",password:"NicePasswordInput",date:"NiceDateTimePicker",datetime:"NiceDateTimePicker",time:"NiceDateTimePicker",select:"NiceSelect",multiselect:"NiceTagBox",checkbox:"NiceCheckbox",toggle:"NiceToggle",radio:"NiceRadioGroup",slider:"NiceSlider",rating:"NiceRating",color:"NiceColorPicker"};return{dataField:t.name,label:{text:t.label},editorType:i[t.type]||"NiceTextInput",editorOptions:{placeholder:t.placeholder,disabled:t.disabled,readOnly:t.readonly,...t.props},colSpan:Math.ceil((t.colSpan||12)/6),validationRules:(n=t.validations)==null?void 0:n.map(a=>({type:a.type,message:a.message,...a.value!==void 0?{[a.type]:a.value}:{}})),helpText:t.helpText}}function Lt(t){const i=[];for(const n of t.sections)n.title?i.push({itemType:"group",caption:n.title,colCount:n.columns||2,items:n.fields.map(lt)}):i.push(...n.fields.map(lt));return i}function qt(t){const i=[];t.version||i.push("Missing schema version"),t.id||i.push("Missing form ID"),(!t.sections||t.sections.length===0)&&i.push("Form must have at least one section");const n=new Set;for(const a of t.sections||[])for(const d of a.fields||[])d.id||i.push(`Field missing ID: ${d.name}`),d.name||i.push(`Field missing name: ${d.id}`),n.has(d.name)&&i.push(`Duplicate field name: ${d.name}`),n.add(d.name);return{valid:i.length===0,errors:i}}const Vt={text:"text",string:"text",textarea:"textarea",number:"number",integer:"number",email:"email",password:"password",phone:"phone",tel:"phone",url:"url",date:"date",datetime:"datetime",time:"time",select:"select",dropdown:"select",multiselect:"multiselect",checkbox:"checkbox",boolean:"checkbox",toggle:"toggle",switch:"toggle",radio:"radio",slider:"slider",range:"slider",rating:"rating",stars:"rating",color:"color",file:"file",upload:"file",signature:"signature",richtext:"richtext",markdown:"markdown"};function xt(t){return Vt[String(t??"").toLowerCase()]??"text"}function Wt(t){return(Array.isArray(t)?t:t.fields).map((n,a)=>{const d=n.name??n.field??n.id??`field${a+1}`,s=n.validation??{},o=[],u=(c,l)=>{l!==void 0&&o.push({type:c,value:l,...s.message?{message:s.message}:{}})};return u("min",s.min),u("max",s.max),u("minLength",s.minLength),u("maxLength",s.maxLength),u("pattern",s.pattern),{id:n.id??d,name:d,type:xt(n.type),...n.label!==void 0?{label:n.label}:{},...n.placeholder!==void 0?{placeholder:n.placeholder}:{},...n.helpText!==void 0?{helpText:n.helpText}:{},...n.defaultValue!==void 0?{defaultValue:n.defaultValue}:{},...n.required?{required:!0}:{},...n.options?{options:[...n.options]}:{},...o.length?{validations:o}:{}}})}const Jt={text:{type:"string"},textarea:{type:"string"},password:{type:"string",format:"password"},phone:{type:"string",format:"phone"},url:{type:"string",format:"uri"},email:{type:"string",format:"email"},date:{type:"string",format:"date"},datetime:{type:"string",format:"date-time"},time:{type:"string",format:"time"},color:{type:"string",format:"color"},number:{type:"number"},slider:{type:"number"},rating:{type:"integer"},checkbox:{type:"boolean"},toggle:{type:"boolean"},select:{type:"string"},radio:{type:"string"},multiselect:{type:"array",items:{type:"string"}},file:{type:"string",format:"data-url"},signature:{type:"string",format:"data-url"},richtext:{type:"string"},markdown:{type:"string"},code:{type:"string"},image:{type:"string",format:"uri"}};function Gt(t,i){if(i)for(const n of i)switch(n.type){case"minLength":typeof n.value=="number"&&(t.minLength=n.value);break;case"maxLength":typeof n.value=="number"&&(t.maxLength=n.value);break;case"min":typeof n.value=="number"&&(t.minimum=n.value);break;case"max":typeof n.value=="number"&&(t.maximum=n.value);break;case"pattern":typeof n.value=="string"&&(t.pattern=n.value);break;case"email":t.format="email";break;case"url":t.format="uri";break}}function Ut(t){if(t.type==="heading"||t.type==="paragraph"||t.type==="divider"||t.type==="spacer")return null;const i=Jt[t.type];if(!i)return null;const n={...i};return t.label&&(n.title=t.label),t.helpText&&(n.description=t.helpText),t.defaultValue!==void 0&&(n.default=t.defaultValue),t.options&&(t.type==="select"||t.type==="radio")&&(n.enum=t.options.map(a=>typeof a=="string"?a:a.value)),t.options&&t.type==="multiselect"&&(n.items={type:"string",enum:t.options.map(a=>typeof a=="string"?a:String(a.value))}),Gt(n,t.validations),n}function Ht(t){const i={},n=[],a=s=>{var o;for(const u of s){if(u.type==="section"&&u.children){a(u.children);continue}const c=Ut(u);c&&(i[u.name]=c,(u.required||(o=u.validations)!=null&&o.some(l=>l.type==="required"))&&n.push(u.name))}};for(const s of t.sections)a(s.fields);const d={$schema:"http://json-schema.org/draft-07/schema#",$id:t.id,type:"object",title:t.title,description:t.description,properties:i,additionalProperties:!1};return n.length>0&&(d.required=n),d}function ct(t){const{t:i}=ke.useNiceTranslation(),{value:n,onChange:a,readOnly:d}=t,[s,o]=b.useState(()=>{try{return n===void 0?"":JSON.stringify(n,null,2)}catch{return""}}),[u,c]=b.useState(null);return b.useEffect(()=>{try{o(n===void 0?"":JSON.stringify(n,null,2))}catch{}},[JSON.stringify(n)]),e.jsxs("div",{className:"nice-schema-form__json-field",children:[e.jsx("textarea",{className:"nice-schema-form__json-textarea",value:s,readOnly:d,spellCheck:!1,rows:Math.min(12,Math.max(3,s.split(`
2
+ `).length)),onChange:l=>{const r=l.target.value;o(r);const p=r.trim();if(p===""){c(null),a(void 0);return}try{a(JSON.parse(p)),c(null)}catch(m){c(m instanceof Error?m.message:i("jsonSchemaToFormItems.invalidJson","Invalid JSON"))}}}),u&&e.jsx("div",{className:"nice-schema-form__json-error",children:u})]})}function Yt(t){switch(t){case"email":return"email";case"uri":case"url":return"url";case"date":return"date";case"date-time":return"datetime";case"time":return"time";case"color":return"color";case"password":return"password";case"phone":return"phone";case"data-url":return"file";default:return"text"}}function Xt(t,i,n,a={}){const d={field:t,label:i.title??t,required:n,hint:i.description,defaultValue:i.default};if(i.enum&&i.enum.length>0)return{...d,type:"select",options:i.enum.map(s=>({label:String(s),value:s}))};switch(i.type){case"number":case"integer":return{...d,type:"number"};case"boolean":return{...d,type:"checkbox"};case"string":return{...d,type:Yt(i.format)};case"array":{const s=i.items;if(s!=null&&s.enum&&s.enum.length>0)return{...d,type:"tags",options:s.enum.map(o=>({label:String(o),value:String(o)}))};if((s==null?void 0:s.type)==="object"&&s.properties&&a.renderArrayField){const o=a.renderArrayField;return{...d,render:(u,c)=>o(u??[],c,s,d.label)}}return(s==null?void 0:s.type)==="string"||(s==null?void 0:s.type)==="number"||(s==null?void 0:s.type)==="integer"?{...d,type:"tags"}:{...d,render:(o,u)=>e.jsx(ct,{value:o,onChange:u})}}case"object":if(a.renderObjectField){const s=a.renderObjectField;return{...d,render:(o,u)=>s(o??{},u,i,d.label)}}return{...d,render:(s,o)=>e.jsx(ct,{value:s,onChange:o})};default:return{...d,type:"text"}}}function Ge(t,i={}){const{uiSchema:n,renderArrayField:a,renderObjectField:d}=i,s={renderArrayField:a,renderObjectField:d},o=t.properties??{},u=new Set(t.required??[]);return Object.keys(o).map(c=>{const l=Xt(c,o[c],u.has(c),s);return n!=null&&n[c]?{...l,...n[c]}:l})}const Zt={text:"text",textarea:"textarea",number:"number",email:"email",password:"password",phone:"phone",url:"url",date:"date",datetime:"datetime",time:"time",select:"select",multiselect:"tags",checkbox:"checkbox",toggle:"toggle",radio:"radio",slider:"slider",rating:"rating",color:"color"};function Ue(t,i={}){var d,s;const{uiSchema:n}=i,a=[];for(const o of t){if(o.type==="section"&&o.children){for(const l of Ue(o.children,i))a.push(o.label?{...l,group:o.label}:l);continue}const u=Zt[o.type];if(!u)continue;const c={field:o.name,label:o.label,type:u,required:o.required||((d=o.validations)==null?void 0:d.some(l=>l.type==="required")),placeholder:o.placeholder,hint:o.helpText,defaultValue:o.defaultValue,disabled:o.disabled,readOnly:o.readonly,options:(s=o.options)==null?void 0:s.map(l=>typeof l=="string"?{label:l,value:l}:{label:l.label,value:l.value})};a.push(n!=null&&n[o.name]?{...c,...n[o.name]}:c)}return a}function ut(t){return t==null||t===""||Array.isArray(t)&&t.length===0}function He(t,i){const n=[],a=i.properties??{},d=new Set(i.required??[]);for(const s of Object.keys(a)){const o=a[s],u=t[s];if(d.has(s)&&ut(u)){n.push({field:s,message:`${o.title??s} is required`});continue}if(!ut(u)&&(o.enum&&!o.enum.includes(u)&&n.push({field:s,message:`${o.title??s} must be one of: ${o.enum.join(", ")}`}),(o.type==="number"||o.type==="integer")&&typeof u=="number"&&(o.minimum!==void 0&&u<o.minimum&&n.push({field:s,message:`${o.title??s} must be ≥ ${o.minimum}`}),o.maximum!==void 0&&u>o.maximum&&n.push({field:s,message:`${o.title??s} must be ≤ ${o.maximum}`})),o.type==="string"&&typeof u=="string"&&(o.minLength!==void 0&&u.length<o.minLength&&n.push({field:s,message:`${o.title??s} must be at least ${o.minLength} chars`}),o.maxLength!==void 0&&u.length>o.maxLength&&n.push({field:s,message:`${o.title??s} must be at most ${o.maxLength} chars`}),o.pattern)))try{new RegExp(o.pattern).test(u)||n.push({field:s,message:`${o.title??s} has an invalid format`})}catch{}}return n}const Re="__nafRid";function Qt(t){return Array.isArray(t)?`[${t.length}]`:t&&typeof t=="object"?"{…}":t==null?"":String(t)}const Ye=b.forwardRef(function(i,n){const{value:a,defaultValue:d,onChange:s,itemSchema:o,title:u,readOnly:c=!1,columns:l,className:r,style:p,"data-testid":m}=i,[g,v]=h.useControllableState({value:a,defaultValue:d,fallbackValue:[],onChange:s,componentName:"NiceArrayField"}),f=o.properties??{},j=b.useMemo(()=>(l??Object.keys(f)).map(x=>{const k=f[x]??{},M={field:x,header:k.title??x};return k.type==="boolean"?(M.render=V=>V?e.jsx(h.NiceIcon,{name:"check",size:14,title:"true"}):"",M.align="center"):(k.type==="array"||k.type==="object")&&(M.render=V=>Qt(V)),M}),[o,l]),N=b.useMemo(()=>Ge(o),[o]),$=b.useMemo(()=>g.map((y,x)=>({...y,[Re]:String(x)})),[g]),O=y=>{const{[Re]:x,...k}=y;return k},_="nice-array-field"+(r?` ${r}`:"");return e.jsx("div",{ref:n,className:_,style:p,"data-testid":m,children:e.jsx(h.NiceDataGrid,{data:$,keyField:Re,columns:j,editMode:"popup",formItems:N,editFormTitle:u?`${u} — item`:"Edit item",emptyText:`No items${u?` in ${u}`:""}`,compact:!0,onRowAdd:c?void 0:y=>v([...g,O(y)]),onRowEdit:c?void 0:(y,x)=>{const k=Number(y);v(g.map((M,V)=>V===k?O(x):M))},onRowDelete:c?void 0:y=>{const x=Number(y);v(g.filter((k,M)=>M!==x))}})})}),ei=[{target:".nice-schema-form",titleKey:"tutorial.schemaForm.intro.title",title:"Schema form",contentKey:"tutorial.schemaForm.intro.content",content:"This form is generated from a schema. Required fields and validation errors are flagged; use the JSON toggle for raw editing.",placement:"auto"},{target:'[data-tour="sf-viewtoggle"]',titleKey:"tutorial.schemaForm.viewToggle.title",title:"Form ⇄ JSON",contentKey:"tutorial.schemaForm.viewToggle.content",content:"Switch between the visual form and the raw JSON value — handy for power users and copy/paste.",placement:"bottom"},{target:".nice-schema-form",titleKey:"tutorial.schemaForm.validation.title",title:"Live validation",contentKey:"tutorial.schemaForm.validation.content",content:"Values are validated against the schema as you type; any problems are listed below the form.",placement:"auto"}];function ti(t){const i=[],n=a=>{for(const d of a){if(d.type==="section"&&d.children){n(d.children);continue}d.required&&i.push({id:`${d.name}-required`,field:d.name,op:"required"});for(const s of d.validations??[])i.push({id:`${d.name}-${s.type}`,field:d.name,op:s.type,value:typeof s.value=="boolean"?void 0:s.value,message:s.message??(s.type==="required"?`${d.label??d.name} is required`:void 0)})}};return n(t),i}function ii(t,i){return h.evaluateValidation(ti(t),i).filter(n=>n.severity==="error").map(n=>({field:n.field,message:n.message}))}const _e=b.forwardRef(function(i,n){const{schema:a,fields:d,uiSchema:s,value:o,defaultValue:u,onChange:c,onValidate:l,showJsonView:r=!1,columns:p=1,labelPosition:m="top",readOnly:g=!1,liveValidation:v=!0,validationRules:f,tutorial:j,className:N,style:$,id:O,"data-testid":_}=i,{t:y}=h.useNiceTranslation(),[x,k]=h.useControllableState({value:o,defaultValue:u,fallbackValue:{},onChange:c,componentName:"NiceSchemaForm"}),[M,V]=b.useState(!1),[D,G]=b.useState(""),[te,Q]=b.useState(null),H=b.useMemo(()=>a?Ge(a,{uiSchema:s,renderArrayField:(L,Z,U,z)=>e.jsx(Ye,{value:L,onChange:Z,itemSchema:U,title:z,readOnly:g})}):d?Ue(d,{uiSchema:s}):[],[a,d,s,g]),C=b.useMemo(()=>{const L=a?He(x,a):d?ii(d,x):[];if(f!=null&&f.length){const Z=h.evaluateValidation(f,x).filter(U=>U.severity==="error").map(U=>({field:U.field,message:U.message}));return[...L,...Z]}return L},[a,d,x,f]);b.useEffect(()=>{l==null||l(C)},[C,l]),b.useEffect(()=>{if(M)try{G(JSON.stringify(x,null,2)),Q(null)}catch{}},[M,x]);const E=(L,Z)=>{k({...x,[L]:Z})},B="nice-schema-form"+(N?` ${N}`:"");return e.jsxs("div",{ref:n,id:O,className:B,style:$,"data-testid":_,children:[j&&e.jsx("div",{className:"nice-schema-form__tutorial",children:e.jsx(h.NiceTutorialButton,{steps:h.resolveTutorial(j,ei)})}),r&&e.jsxs("div",{className:"nice-schema-form__toolbar","data-tour":"sf-viewtoggle",children:[e.jsx("button",{type:"button",className:"nice-schema-form__tab"+(M?"":" nice-schema-form__tab--active"),onClick:()=>V(!1),children:y("schemaForm.tab.form","Form")}),e.jsx(h.NiceTooltip,{content:y("schemaForm.tab.json.help","Edit the raw JSON value directly"),children:e.jsx("button",{type:"button",className:"nice-schema-form__tab"+(M?" nice-schema-form__tab--active":""),onClick:()=>V(!0),children:y("schemaForm.tab.json","JSON")})})]}),M?e.jsxs("div",{className:"nice-schema-form__json",children:[e.jsx("textarea",{className:"nice-schema-form__json-textarea",value:D,readOnly:g,spellCheck:!1,rows:Math.min(24,Math.max(6,D.split(`
3
+ `).length)),onChange:L=>{const Z=L.target.value;G(Z);try{const U=JSON.parse(Z);Q(null),k(U)}catch(U){Q(U instanceof Error?U.message:y("schemaForm.invalidJson","Invalid JSON"))}}}),te&&e.jsx("div",{className:"nice-schema-form__json-error",children:te})]}):e.jsx(h.NiceForm,{items:H,data:x,onFieldChange:E,columns:p,labelPosition:m,readOnly:g}),v&&C.length>0&&e.jsx("ul",{className:"nice-schema-form__errors",role:"alert",children:C.map((L,Z)=>e.jsx("li",{className:"nice-schema-form__error",children:L.message},`${L.field}-${Z}`))})]})}),Ae="__eeFid",ni={},kt={type:"object",properties:{name:{type:"string",title:"Name",minLength:1,description:"Unique technical name of the entity (PascalCase)."},displayName:{type:"string",title:"Display name",description:"Human-friendly name shown in the UI."},tableName:{type:"string",title:"Table name",description:"Database table that backs this entity."},description:{type:"string",title:"Description",description:"Optional notes about the entity's purpose."},entityIcon:{type:"string",title:"Icon",description:"Icon key shown next to the entity."},isAudited:{type:"boolean",title:"Audited",description:"Track who created/changed each record and when."},isSoftDeleteEnabled:{type:"boolean",title:"Soft delete",description:"Flag rows as deleted instead of physically removing them."}},required:["name"]},bt={type:"object",properties:{name:{type:"string",title:"Name",minLength:1,description:"Field's technical name (the database column)."},displayName:{type:"string",title:"Display name",description:"Human-friendly label shown in the UI."},dataType:{type:"string",title:"Type",description:"Storage / data type of the field.",enum:["Guid","string","text","int","long","decimal","double","bool","DateTime","DateOnly","json"]},isPrimaryKey:{type:"boolean",title:"Primary key",description:"Primary key — uniquely identifies each record."},isForeignKey:{type:"boolean",title:"Foreign key",description:"Foreign key — references another entity's primary key."},isRequired:{type:"boolean",title:"Required",description:"Value must be provided (NOT NULL)."},isUnique:{type:"boolean",title:"Unique",description:"Each value must be unique across all records."},isIndexed:{type:"boolean",title:"Indexed",description:"Add a database index for faster lookups and filtering."},isNullable:{type:"boolean",title:"Nullable",description:"Allow empty (NULL) values."},maxLength:{type:"integer",title:"Max length",description:"Maximum number of characters (for string types)."},defaultValue:{type:"string",title:"Default",description:"Value used when none is provided."},description:{type:"string",title:"Description",description:"Optional notes about the field."},isComputed:{type:"boolean",title:"Computed",description:"Value is derived from an expression instead of stored input."},computedExpression:{type:"string",title:"Computed expression",description:"Expression used to compute the value (when Computed is on)."}},required:["name","dataType"]};function Le({title:t,help:i}){return e.jsxs("span",{className:"nice-entity-editor__field-label",children:[t,i?e.jsx(h.NiceTooltip,{content:i,children:e.jsx("span",{className:"nice-entity-editor__help",role:"img","aria-label":i,children:e.jsx(h.NiceIcon,{name:"info",size:14})})}):null]})}function si({schema:t,value:i,onChange:n,readOnly:a}){const d=t.properties??{};return e.jsx("div",{className:"nice-entity-editor__field-form",children:Object.entries(d).map(([s,o])=>{const u=i[s],c=o.description,l=o.title??s;if(o.type==="boolean")return e.jsx("div",{className:"nice-entity-editor__field-row nice-entity-editor__field-row--check",children:e.jsx(h.NiceCheckbox,{label:e.jsx(Le,{title:l,help:c}),checked:!!u,onChange:p=>n(s,p),disabled:a})},s);if(Array.isArray(o.enum)&&o.enum.length>0)return e.jsxs("div",{className:"nice-entity-editor__field-row",children:[e.jsx(Le,{title:l,help:c}),e.jsx(h.NiceSelect,{options:o.enum.map(p=>({label:String(p),value:String(p)})),value:u==null?"":String(u),onChange:p=>n(s,p),clearable:!0,disabled:a})]},s);const r=o.type==="integer"||o.type==="number";return e.jsxs("div",{className:"nice-entity-editor__field-row",children:[e.jsx(Le,{title:l,help:c}),e.jsx(h.NiceTextInput,{value:u==null?"":String(u),onChange:p=>n(s,r?p===""?void 0:Number(p):p),disabled:a})]},s)})})}function oi({fields:t,onChange:i,fieldSchema:n,readOnly:a}){const{t:d}=h.useNiceTranslation(),[s,o]=b.useState(null),u=b.useMemo(()=>t.map((p,m)=>({...p,[Ae]:String(m)})),[t]),c=b.useMemo(()=>[{field:"name",header:d("entityEditor.field.name","Name"),sortable:!0,render:p=>e.jsx("span",{className:"nice-entity-editor__name",children:String(p??"")})},{field:"dataType",header:d("entityEditor.field.type","Type"),sortable:!0,render:p=>e.jsx(h.NiceBadge,{variant:"secondary",size:"sm",outline:!0,children:String(p??"—")})},{field:"__flags",header:d("entityEditor.field.flags","Constraints"),headerTooltip:d("entityEditor.field.flags.help","Key / required / unique / indexed constraints on this field"),render:(p,m)=>{const g=[[!!(m!=null&&m.isPrimaryKey),"PK",d("entityEditor.flag.pk","Primary key"),"info"],[!!(m!=null&&m.isForeignKey),"FK",d("entityEditor.flag.fk","Foreign key"),"info"],[!!(m!=null&&m.isRequired),"Req",d("entityEditor.flag.required","Required (NOT NULL)"),"warning"],[!!(m!=null&&m.isUnique),"Uniq",d("entityEditor.flag.unique","Unique"),"secondary"],[!!(m!=null&&m.isIndexed),"Idx",d("entityEditor.flag.indexed","Indexed"),"secondary"]];return e.jsx("span",{className:"nice-entity-editor__flags",children:g.filter(([v])=>v).map(([,v,f,j])=>e.jsx(h.NiceTooltip,{content:f,children:e.jsx(h.NiceBadge,{variant:j,size:"sm",children:v})},v))})}}],[]),l=(p,m,g)=>{i(t.map((v,f)=>f===p?{...v,[m]:g}:v))},r=()=>{const p=[...t,{name:`field${t.length+1}`,dataType:"string"}];i(p),o(p.length-1)};if(s!=null&&t[s]){const p=t[s];return e.jsxs("div",{className:"nice-entity-editor__field-detail",children:[e.jsxs("header",{className:"nice-entity-editor__edit-header",children:[e.jsx(h.NiceTooltip,{content:d("entityEditor.field.backHint","Back to the field list"),children:e.jsx(h.NiceButton,{variant:"ghost",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"arrow-left",size:14}),onClick:()=>o(null),children:d("entityEditor.field.back","Fields")})}),e.jsx("span",{className:"nice-entity-editor__breadcrumb-sep",children:"/"}),e.jsx("span",{className:"nice-entity-editor__edit-title",children:String(p.name??d("entityEditor.field.untitled","New field"))})]}),e.jsx(si,{schema:n,value:p,onChange:(m,g)=>l(s,m,g),readOnly:a}),e.jsx("div",{className:"nice-entity-editor__field-detail-actions",children:e.jsx(h.NiceButton,{variant:"primary",size:"sm",onClick:()=>o(null),children:d("entityEditor.field.done","Done")})})]})}return e.jsx(h.NiceDataGrid,{data:u,keyField:Ae,columns:c,searchable:!0,searchPlaceholder:d("entityEditor.field.search","Search fields…"),emptyText:d("entityEditor.field.empty","No fields yet. Add one to define this entity."),onRowClick:p=>o(Number(p[Ae])),onRowDelete:a?void 0:p=>i(t.filter((m,g)=>g!==Number(p))),toolbar:a?void 0:e.jsx(h.NiceButton,{variant:"primary",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:r,children:d("entityEditor.field.add","Add field")}),compact:!0,striped:!0})}const Xe=b.forwardRef(function(i,n){const{value:a,defaultValue:d,onChange:s,entityMetaSchema:o=kt,fieldSchema:u=bt,fieldsKey:c="fields",validationsKey:l="validations",activeTab:r,defaultActiveTab:p="general",onActiveTabChange:m,extraTabs:g,readOnly:v=!1,className:f,style:j,id:N,"data-testid":$}=i,{t:O}=h.useNiceTranslation(),[_,y]=h.useControllableState({value:a,defaultValue:d,fallbackValue:ni,onChange:s,componentName:"NiceEntityForm"}),[x,k]=h.useControllableState({value:r,defaultValue:p,fallbackValue:"general",onChange:m,componentName:"NiceEntityForm"}),M=b.useMemo(()=>{const H=_[c];return Array.isArray(H)?H:[]},[_,c]),V=b.useMemo(()=>{const H=E=>{const B=E.toLowerCase();return/(int|long|decimal|double|float|number|money)/.test(B)?"number":/bool/.test(B)?"boolean":/date|time/.test(B)?"date":"string"},C=[];for(const E of M){const B=String(E.name??"");B&&C.push({field:B,label:String(E.displayName??B),type:H(String(E.dataType??"string"))})}return C},[M]),D=b.useMemo(()=>{const H=_[l];return Array.isArray(H)?H:[]},[_,l]),G=H=>{y({..._,...H})},te=[{id:"general",label:O("entityEditor.tab.general","General"),content:e.jsx(_e,{schema:o,value:_,onChange:H=>G(H),columns:2,readOnly:v,liveValidation:!0})},{id:"fields",label:O("entityEditor.tab.fields","Fields"),badge:M.length||void 0,content:e.jsx(oi,{fields:M,onChange:H=>G({[c]:H}),fieldSchema:u,readOnly:v})},{id:"validation",label:O("entityEditor.tab.validation","Validation"),badge:D.length||void 0,content:e.jsx(h.NiceValidationBuilder,{fields:V,value:D,onChange:H=>G({[l]:H})})},...g??[]],Q="nice-entity-form"+(f?` ${f}`:"");return e.jsx("div",{ref:n,id:N,className:Q,style:j,"data-testid":$,children:e.jsx(h.NiceTabs,{tabs:te,activeTab:x,onChange:k,variant:"enclosed"})})}),qe="__eeRid",ai=[{target:".nice-entity-editor",titleKey:"tutorial.entityEditor.intro.title",title:"Entity editor",contentKey:"tutorial.entityEditor.intro.content",content:"Browse your entities in the list, then click one (or “New entity”) to edit its metadata, fields and validation on a dedicated screen.",placement:"auto"}],jt=b.forwardRef(function(i,n){const{value:a,defaultValue:d,onChange:s,entityMetaSchema:o=kt,fieldSchema:u=bt,fieldsKey:c="fields",validationsKey:l="validations",nameKey:r="name",renderErPreview:p,readOnly:m=!1,tutorial:g,className:v,style:f,id:j,"data-testid":N}=i,{t:$}=h.useNiceTranslation(),[O,_]=h.useControllableState({value:a,defaultValue:d,fallbackValue:[],onChange:s,componentName:"NiceEntityEditor"}),[y,x]=b.useState("list"),[k,M]=b.useState(0),[V,D]=b.useState("general"),G=Math.min(k,Math.max(0,O.length-1)),te=O[G],Q=y==="edit"&&te!=null,H=b.useMemo(()=>O.map((z,Y)=>({...z,[qe]:String(Y)})),[O]),C=z=>{M(z),D("general"),x("edit")},E=()=>{const z=[...O,{[r]:`Entity${O.length+1}`,[c]:[]}];_(z),M(z.length-1),D("general"),x("edit")},B=z=>{_(O.filter((Y,le)=>le!==z)),M(Y=>Y>=z?Math.max(0,Y-1):Y)},L=b.useMemo(()=>[{field:r,header:$("entityEditor.col.name","Name"),sortable:!0,render:z=>e.jsx("span",{className:"nice-entity-editor__name",children:String(z??"")})},{field:"displayName",header:$("entityEditor.col.displayName","Display name"),sortable:!0,render:z=>e.jsx("span",{className:"nice-entity-editor__muted",children:String(z??"—")})},{field:"tableName",header:$("entityEditor.col.table","Table"),sortable:!0,render:z=>e.jsx("span",{className:"nice-entity-editor__muted",children:String(z??"—")})},{field:c,header:$("entityEditor.col.fields","Fields"),align:"center",headerTooltip:$("entityEditor.col.fields.help","Number of fields defined on this entity"),render:z=>e.jsx(h.NiceBadge,{variant:"secondary",size:"sm",children:Array.isArray(z)?z.length:0})},{field:"__flags",header:$("entityEditor.col.flags","Flags"),render:(z,Y)=>e.jsxs("span",{className:"nice-entity-editor__flags",children:[Y!=null&&Y.isAudited?e.jsx(h.NiceTooltip,{content:$("entityEditor.flag.audited","Audited — tracks who changed each record and when"),children:e.jsx(h.NiceBadge,{variant:"info",size:"sm",outline:!0,children:$("entityEditor.flag.audited.abbr","Audit")})}):null,Y!=null&&Y.isSoftDeleteEnabled?e.jsx(h.NiceTooltip,{content:$("entityEditor.flag.softDelete","Soft delete — rows are flagged deleted, never physically removed"),children:e.jsx(h.NiceBadge,{variant:"secondary",size:"sm",outline:!0,children:$("entityEditor.flag.softDelete.abbr","Soft-del")})}):null]})}],[r,c]),Z=p?[{id:"er",label:$("entityEditor.tab.er","ER diagram"),content:e.jsx("div",{className:"nice-entity-editor__er",children:p(O)})}]:void 0,U="nice-entity-editor"+(v?` ${v}`:"");return e.jsxs("div",{ref:n,id:j,className:U,style:f,"data-testid":N,children:[g&&e.jsx("div",{className:"nice-entity-editor__tutorial",children:e.jsx(h.NiceTutorialButton,{steps:h.resolveTutorial(g,ai)})}),Q?e.jsxs("div",{className:"nice-entity-editor__edit",children:[e.jsxs("header",{className:"nice-entity-editor__edit-header",children:[e.jsx(h.NiceTooltip,{content:$("entityEditor.backHint","Back to the entity list"),children:e.jsx(h.NiceButton,{variant:"ghost",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"arrow-left",size:14}),onClick:()=>x("list"),children:$("entityEditor.back","Entities")})}),e.jsx("span",{className:"nice-entity-editor__breadcrumb-sep",children:"/"}),e.jsx("span",{className:"nice-entity-editor__edit-title",children:String((te==null?void 0:te[r])??$("entityEditor.untitled","Untitled entity"))}),!m&&e.jsx(h.NiceTooltip,{content:$("entityEditor.deleteHint","Delete this entity"),children:e.jsx(h.NiceButton,{variant:"ghost",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"trash",size:14}),onClick:()=>{B(G),x("list")},children:$("entityEditor.delete","Delete")})})]}),e.jsx(Xe,{value:te,onChange:z=>_(O.map((Y,le)=>le===G?z:Y)),entityMetaSchema:o,fieldSchema:u,fieldsKey:c,validationsKey:l,activeTab:V,onActiveTabChange:D,extraTabs:Z,readOnly:m})]}):e.jsx("div",{className:"nice-entity-editor__list-view",children:e.jsx(h.NiceDataGrid,{data:H,keyField:qe,columns:L,searchable:!0,searchPlaceholder:$("entityEditor.search","Search entities…"),emptyText:$("entityEditor.empty","No entities yet. Create one to get started."),onRowClick:z=>C(Number(z[qe])),onRowDelete:m?void 0:z=>B(Number(z)),toolbar:m?void 0:e.jsx(h.NiceButton,{variant:"primary",size:"sm",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:E,children:$("entityEditor.new","New entity")}),compact:!0,striped:!0})})]})}),di=4e6;function ri(t,i){const n=t.split(/\r?\n/),a=i.split(/\r?\n/);if(n.length*a.length>di)return[...n.map(r=>({type:"remove",text:r})),...a.map(r=>({type:"add",text:r}))];const d=n.length,s=a.length,o=Array.from({length:d+1},()=>new Uint32Array(s+1));for(let r=d-1;r>=0;r--)for(let p=s-1;p>=0;p--)o[r][p]=n[r]===a[p]?o[r+1][p+1]+1:Math.max(o[r+1][p],o[r][p+1]);const u=[];let c=0,l=0;for(;c<d&&l<s;)n[c]===a[l]?(u.push({type:"same",text:n[c]}),c++,l++):o[c+1][l]>=o[c][l+1]?u.push({type:"remove",text:n[c++]}):u.push({type:"add",text:a[l++]});for(;c<d;)u.push({type:"remove",text:n[c++]});for(;l<s;)u.push({type:"add",text:a[l++]});return u}function St({before:t,after:i,context:n=3}){const{t:a}=h.useNiceTranslation(),d=b.useMemo(()=>{const s=ri(t,i),o=new Set;s.forEach((l,r)=>{if(l.type!=="same")for(let p=Math.max(0,r-n);p<=Math.min(s.length-1,r+n);p++)o.add(p)});const u=[];let c=0;return s.forEach((l,r)=>{o.has(r)?(c>0&&(u.push({type:"gap",count:c}),c=0),u.push(l)):c++}),c>0&&u.length>0&&u.push({type:"gap",count:c}),u},[t,i,n]);return d.length===0?e.jsx("p",{className:"nice-development-studio__muted",children:a("devStudio.diff.none","No changes.")}):e.jsx("pre",{className:"nice-development-studio__diff","aria-label":a("devStudio.diff.label","Changes"),children:d.map((s,o)=>s.type==="gap"?e.jsxs("span",{className:"nice-development-studio__diff-gap",children:[a("devStudio.diff.unchanged","{count} unchanged lines").replace("{count}",String(s.count)),`
4
4
  `]},o):e.jsxs("span",{className:`nice-development-studio__diff-line nice-development-studio__diff-line--${s.type}`,children:[s.type==="add"?"+ ":s.type==="remove"?"- ":" ",s.text,`
5
- `]},o))})}function ri({open:t,onClose:i,session:n,preset:a,locales:d,prefill:s,onCreated:o}){var O,_,y,x;const{t:u}=h.useNiceTranslation(),c=n.workspaces.filter(k=>!k.readOnly),l=a.requiredLocales??[],[r,p]=b.useState(()=>{var k;return{workspaceId:s.workspaceId&&c.some(M=>M.id===s.workspaceId)?s.workspaceId:((k=c[0])==null?void 0:k.id)??"",packageId:s.packageId,name:"",entities:[{name:"Item",fields:[{name:"Id",dataType:"Guid",isPrimaryKey:!0,isRequired:!0},{name:"Name",dataType:"string",isRequired:!0,maxLength:200}]}],locales:[...new Set([...l,...d.slice(0,2)])],views:!0,permissions:!0}}),[m,g]=b.useState(null),[v,f]=b.useState(!1),j=b.useMemo(()=>[...new Set((n.modulesByWs[r.workspaceId]??[]).map(k=>k.packageId).filter(Boolean))].sort(),[n.modulesByWs,r.workspaceId]);if(!t)return null;const N=new Set(Object.values(n.modulesByWs).flatMap(k=>k.map(M=>M.id))),$=async()=>{a.generateModule&&r.name.trim()&&g(await a.generateModule({...r,name:r.name.trim()},{existingIds:N}))};return e.jsx(h.NiceModal,{open:t,onClose:i,title:u("devStudio.wizard.title","New module"),size:"xl","data-testid":"studio-module-wizard",children:e.jsx(h.NiceWizard,{finishLabel:u("devStudio.wizard.create","Create module"),onCancel:i,onStepChange:k=>{k===3&&$()},onComplete:async()=>{if(v)return;f(!0);const k=await n.createModule({...r,name:r.name.trim()});f(!1),k&&(o({workspaceId:k.workspaceId,id:k.id}),i())},steps:[{id:"identity",title:u("devStudio.wizard.identity","Name and place"),validate:()=>r.name.trim()&&r.workspaceId?!0:u("devStudio.wizard.needName","Give the module a name."),content:e.jsxs("div",{className:"nice-development-studio__form",children:[e.jsx(h.NiceSelect,{label:u("devStudio.wizard.workspace","Project"),value:r.workspaceId,options:c.map(k=>({value:k.id,label:k.label})),onChange:k=>p({...r,workspaceId:String(k)})}),e.jsx(h.NiceTextInput,{label:u("devStudio.wizard.package","Package"),value:r.packageId??"",placeholder:j.join(", "),onChange:k=>p({...r,packageId:k||void 0})}),e.jsx(h.NiceTextInput,{label:u("devStudio.wizard.name","Name"),value:r.name,placeholder:u("devStudio.wizard.namePlaceholder","e.g. Bike rental"),onChange:k=>p({...r,name:k})}),e.jsx(h.NiceTextInput,{label:u("devStudio.wizard.description","Description"),value:r.description??"",onChange:k=>p({...r,description:k||void 0})})]})},{id:"entities",title:u("devStudio.wizard.entities","Entities"),content:e.jsx(jt,{value:r.entities,onChange:k=>p({...r,entities:k}),entityMetaSchema:(O=a.entities)==null?void 0:O.entityMetaSchema,fieldSchema:(_=a.entities)==null?void 0:_.fieldSchema,fieldsKey:(y=a.entities)==null?void 0:y.fieldsKey,nameKey:(x=a.entities)==null?void 0:x.nameKey})},{id:"options",title:u("devStudio.wizard.options","Options"),content:e.jsxs("div",{className:"nice-development-studio__form",children:[e.jsxs("fieldset",{className:"nice-development-studio__fieldset",children:[e.jsx("legend",{children:u("devStudio.wizard.locales","Languages")}),[...new Set([...l,...d])].map(k=>e.jsx(h.NiceCheckbox,{label:k,checked:r.locales.includes(k),disabled:l.includes(k),onChange:M=>p({...r,locales:M?[...r.locales,k]:r.locales.filter(V=>V!==k)})},k))]}),e.jsx(h.NiceCheckbox,{label:u("devStudio.wizard.views","A list and a form view per entity"),checked:!!r.views,onChange:k=>p({...r,views:k})}),e.jsx(h.NiceCheckbox,{label:u("devStudio.wizard.permissions","Viewer, editor and admin permissions"),checked:!!r.permissions,onChange:k=>p({...r,permissions:k})})]})},{id:"review",title:u("devStudio.wizard.review","Review"),content:m?e.jsxs("div",{children:[e.jsx("p",{children:u("devStudio.wizard.willCreate","Module {id} with these files:").replace("{id}",m.id)}),e.jsx("ul",{className:"nice-development-studio__list",children:m.files.map(k=>e.jsxs("li",{children:[e.jsx(h.NiceIcon,{name:"file",size:12})," ",k.path]},k.path))})]}):e.jsx("p",{className:"nice-development-studio__muted",children:u("devStudio.wizard.generating","Generating…")})}]})})}function li({open:t,moduleLabel:i,changes:n,original:a,conflict:d,onSave:s,onOverwrite:o,onReload:u,onClose:c}){const{t:l}=h.useNiceTranslation();return t?e.jsxs(h.NiceModal,{open:t,onClose:c,size:"xl",title:l("devStudio.review.title","Save {module}").replace("{module}",i),"data-testid":"studio-review",footer:d?e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{variant:"ghost",onClick:c,children:l("devStudio.cancel","Cancel")}),e.jsx(h.NiceButton,{variant:"secondary",onClick:u,children:l("devStudio.review.reload","Reload theirs (drop mine)")}),e.jsx(h.NiceButton,{variant:"danger",onClick:o,children:l("devStudio.review.overwrite","Overwrite with mine")})]}):e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{variant:"ghost",onClick:c,children:l("devStudio.cancel","Cancel")}),e.jsx(h.NiceButton,{variant:"primary",onClick:s,children:l("devStudio.review.save","Save {count} files").replace("{count}",String(n.length))})]}),children:[d&&e.jsxs("p",{className:"nice-development-studio__error",role:"alert",children:[l("devStudio.review.conflict","These files changed since you opened them:")," ",d.conflicts.map(r=>r.path).join(", ")]}),n.map(r=>e.jsxs("section",{className:"nice-development-studio__source",children:[e.jsx("h4",{className:"nice-development-studio__source-title",children:r.type==="delete"?l("devStudio.change.delete","Delete {path}").replace("{path}",r.path):r.baseVersion===void 0&&!a(r.path)?l("devStudio.change.new","New file {path}").replace("{path}",r.path):r.path}),e.jsx(St,{before:a(r.path),after:r.type==="write"?r.text:""})]},r.path))]}):null}function ci({open:t,moduleId:i,templates:n,onApply:a,onClose:d}){const{t:s}=h.useNiceTranslation(),o=b.useMemo(()=>n.filter(p=>p.modules.some(m=>m.moduleId===i)).map(p=>p.id),[n,i]),[u,c]=b.useState(o);if(!t)return null;const l=n.map(p=>{var m,g;return{id:p.id,label:((m=p.translations.en)==null?void 0:m.name)??((g=Object.values(p.translations)[0])==null?void 0:g.name)??p.id}}),r=[{field:"label",header:s("devStudio.explorer.name","Name")}];return e.jsx(h.NiceModal,{open:t,onClose:d,title:s("devStudio.picker.title","Templates with {module}").replace("{module}",i),"data-testid":"studio-template-picker",footer:e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{variant:"ghost",onClick:d,children:s("devStudio.cancel","Cancel")}),e.jsx(h.NiceButton,{variant:"primary",onClick:()=>{const p=n.filter(m=>u.includes(m.id)!==o.includes(m.id)).map(m=>({...m,modules:u.includes(m.id)?[...m.modules,{moduleId:i}]:m.modules.filter(g=>g.moduleId!==i)}));a(p)},children:s("devStudio.apply","Apply")})]}),children:e.jsx(h.NiceTreeGrid,{data:l,columns:r,keyField:"id",sortable:!1,compact:!0,checkable:!0,checkedKeys:u,onCheckedChange:c,searchable:!0,"aria-label":s("devStudio.explorer.templates","Templates")})})}function mt({open:t,title:i,workspaces:n,workspaceId:a,idLabel:d,initialId:s="",withLabel:o,onSubmit:u,onClose:c}){var j;const{t:l}=h.useNiceTranslation(),[r,p]=b.useState(a??((j=n[0])==null?void 0:j.id)??""),[m,g]=b.useState(s),[v,f]=b.useState("");return t?e.jsx(h.NiceModal,{open:t,onClose:c,title:i,footer:e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{variant:"ghost",onClick:c,children:l("devStudio.cancel","Cancel")}),e.jsx(h.NiceButton,{variant:"primary",disabled:!m.trim()||!r,onClick:()=>u({workspaceId:r,id:m.trim(),label:v.trim()||m.trim()}),children:l("devStudio.ok","OK")})]}),children:e.jsxs("div",{className:"nice-development-studio__form",children:[e.jsx(h.NiceSelect,{label:l("devStudio.wizard.workspace","Project"),value:r,options:n.map(N=>({value:N.id,label:N.label})),onChange:N=>p(String(N))}),e.jsx(h.NiceTextInput,{label:d,value:m,onChange:g}),o&&e.jsx(h.NiceTextInput,{label:l("devStudio.package.label","Name"),value:v,onChange:f})]})}):null}const pt=t=>JSON.stringify(t??null,null,2);function Ze({value:t,onChange:i,readOnly:n,height:a=320,label:d}){const{t:s}=h.useNiceTranslation(),[o,u]=b.useState(()=>pt(t)),[c,l]=b.useState(null),r=b.useRef(t);return b.useEffect(()=>{r.current!==t&&(r.current=t,u(pt(t)),l(null))},[t]),e.jsxs("div",{className:"nice-development-studio__json",role:"group","aria-label":d,children:[e.jsx(h.NiceSimpleCodeEditor,{value:o,language:"json",height:a,readOnly:n,lineNumbers:!0,onChange:p=>{u(p);try{const m=JSON.parse(p);l(null),r.current=m,i==null||i(m)}catch(m){l(m instanceof Error?m.message:String(m))}}}),c&&e.jsxs("p",{className:"nice-development-studio__error",role:"alert",children:[s("devStudio.json.invalid","Not valid JSON:")," ",c]})]})}const ui=[{target:".nice-i18n-editor",titleKey:"tutorial.i18nEditor.intro.title",title:"Translations",contentKey:"tutorial.i18nEditor.intro.content",content:"Edit translations as a keys × locales grid. Add keys and locales; amber cells mark missing translations.",placement:"auto"},{target:'[data-tour="i18n-grid"]',titleKey:"tutorial.i18nEditor.grid.title",title:"Keys × locales",contentKey:"tutorial.i18nEditor.grid.content",content:"Each row is a translation key and each column a locale. Edit a cell to set a translation; amber cells are still missing.",placement:"top"},{target:'[data-tour="i18n-add"]',titleKey:"tutorial.i18nEditor.add.title",title:"Add keys & locales",contentKey:"tutorial.i18nEditor.add.content",content:"Add a new translation key or a new locale column here; new cells start empty and are flagged as missing.",placement:"top"}],Qe=b.forwardRef(function(i,n){const{value:a,defaultValue:d,onChange:s,locales:o,allowEditLocales:u=!0,allowEditKeys:c=!0,highlightMissing:l=!0,readOnly:r=!1,tutorial:p,className:m,style:g,id:v,"data-testid":f}=i,{t:j}=ke.useNiceTranslation(),[N,$]=ke.useControllableState({value:a,defaultValue:d,fallbackValue:{},onChange:s,componentName:"NiceI18nEditor"}),[O,_]=b.useState(""),[y,x]=b.useState(""),k=b.useMemo(()=>o??Object.keys(N),[o,N]),M=b.useMemo(()=>{const E=new Set;for(const B of Object.keys(N))for(const L of Object.keys(N[B]??{}))E.add(L);return[...E].sort()},[N]),V=(E,B,L)=>{$({...N,[E]:{...N[E]??{},[B]:L}})},D=(E,B)=>{if(!B||B===E)return;const L={};for(const Z of Object.keys(N)){const U={...N[Z]??{}};E in U&&(U[B]=U[E],delete U[E]),L[Z]=U}$(L)},G=E=>{const B={};for(const L of Object.keys(N)){const Z={...N[L]??{}};delete Z[E],B[L]=Z}$(B)},te=()=>{const E=O.trim();if(!E||M.includes(E))return;const B={};for(const L of k)B[L]={...N[L]??{},[E]:""};for(const L of Object.keys(N))B[L]||(B[L]=N[L]);$(B),_("")},Q=()=>{const E=y.trim();if(!E||N[E])return;const B={};for(const L of M)B[L]="";$({...N,[E]:B}),x("")},H=E=>{const B={...N};delete B[E],$(B)},C="nice-i18n-editor"+(m?` ${m}`:"");return e.jsxs("div",{ref:n,id:v,className:C,style:g,"data-testid":f,children:[p&&e.jsx("div",{className:"nice-i18n-editor__tutorial",children:e.jsx(ke.NiceTutorialButton,{steps:ke.resolveTutorial(p,ui)})}),e.jsx("div",{className:"nice-i18n-editor__scroll","data-tour":"i18n-grid",children:e.jsxs("table",{className:"nice-i18n-editor__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nice-i18n-editor__key-head",children:j("i18nEditor.keyHead","Key")}),k.map(E=>e.jsxs("th",{className:"nice-i18n-editor__locale-head",children:[e.jsx("span",{children:E}),u&&!r&&e.jsx("button",{type:"button",className:"nice-i18n-editor__locale-remove","aria-label":`${j("i18nEditor.removeLocale","Remove locale")} ${E}`,onClick:()=>H(E),children:e.jsx(ke.NiceIcon,{name:"close",size:12})})]},E))]})}),e.jsxs("tbody",{children:[M.map(E=>e.jsxs("tr",{children:[e.jsxs("td",{className:"nice-i18n-editor__key-cell",children:[c&&!r?e.jsx("input",{className:"nice-i18n-editor__key-input",defaultValue:E,onBlur:B=>D(E,B.target.value.trim()),"aria-label":j("i18nEditor.keyAria","Translation key")}):e.jsx("span",{className:"nice-i18n-editor__key-text",children:E}),c&&!r&&e.jsx("button",{type:"button",className:"nice-i18n-editor__key-remove","aria-label":`${j("i18nEditor.removeKey","Remove key")} ${E}`,onClick:()=>G(E),children:e.jsx(ke.NiceIcon,{name:"close",size:12})})]}),k.map(B=>{var U;const L=((U=N[B])==null?void 0:U[E])??"",Z=l&&L==="";return e.jsx("td",{className:"nice-i18n-editor__cell",children:e.jsx("input",{className:"nice-i18n-editor__cell-input"+(Z?" nice-i18n-editor__cell-input--missing":""),value:L,readOnly:r,onChange:z=>V(B,E,z.target.value),"aria-label":`${E} (${B})`})},B)})]},E)),M.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"nice-i18n-editor__empty",colSpan:k.length+1,children:j("i18nEditor.empty","No translation keys yet.")})})]})]})}),!r&&(c||u)&&e.jsxs("div",{className:"nice-i18n-editor__toolbar","data-tour":"i18n-add",children:[c&&e.jsxs("div",{className:"nice-i18n-editor__add",children:[e.jsx("input",{className:"nice-i18n-editor__add-input",placeholder:j("i18nEditor.newKeyPlaceholder","new.key"),value:O,onChange:E=>_(E.target.value),onKeyDown:E=>{E.key==="Enter"&&te()},"aria-label":j("i18nEditor.newKeyAria","New key")}),e.jsxs("button",{type:"button",onClick:te,children:["+ ",j("i18nEditor.addKey","Key")]})]}),u&&e.jsxs("div",{className:"nice-i18n-editor__add",children:[e.jsx("input",{className:"nice-i18n-editor__add-input",placeholder:j("i18nEditor.newLocalePlaceholder","locale (e.g. de)"),value:y,onChange:E=>x(E.target.value),onKeyDown:E=>{E.key==="Enter"&&Q()},"aria-label":j("i18nEditor.newLocaleAria","New locale")}),e.jsxs("button",{type:"button",onClick:Q,children:["+ ",j("i18nEditor.addLocale","Locale")]})]})]})]})}),ee=t=>`${t.workspaceId}/${t.id}`;function Ve(t,i,n){const a=new Set(t.deleted),d=new Map;for(const m of t.files)a.has(m.path)||d.set(m.path,t.raw[m.path]!==void 0?{...m,text:t.raw[m.path]}:m);for(const[m,g]of Object.entries(t.raw))!d.has(m)&&!a.has(m)&&d.set(m,{path:m,text:g});const s=[...d.values()],o={moduleId:t.key.id,files:s,locales:n},u=P.buildDocuments(i.kinds,s,o),c=new Map(s.map(m=>[m.path,m.text])),l={};for(const m of u)if(m.key in t.drafts)try{const g=m.kind.encode(t.drafts[m.key],s.filter(v=>m.paths.includes(v.path)),o);for(const v of g.files)c.set(v.path,v.text),a.delete(v.path);for(const v of g.deleted??[])c.delete(v),a.add(v)}catch(g){l[m.key]=g instanceof Error?g.message:String(g)}const r=new Map(t.files.map(m=>[m.path,m])),p=[];for(const[m,g]of c){const v=r.get(m);(!v||v.text!==g)&&p.push({type:"write",path:m,text:g,baseVersion:v==null?void 0:v.version})}for(const m of a){const g=r.get(m);g&&p.push({type:"delete",path:m,baseVersion:g.version})}return{...t,working:s,documents:u,changes:p,pending:c,encodeErrors:l,dirty:p.length>0}}function wt(t,i){const n=[];for(const a of t.documents){if(a.error&&n.push({severity:"error",code:"file.unreadable",message:`${a.paths[0]} cannot be read: ${a.error}`,messageKey:"devStudio.issue.unreadable",params:{path:a.paths[0]},moduleId:t.key.id,path:a.paths[0]}),a.kind.editor!=="manifest"||!i.manifestSections)continue;const d=t.drafts[a.key]??a.model??{};for(const s of i.manifestSections){const{section:o}=P.fitManifestSection(s,d);if(o.schema)for(const u of He(d,o.schema))n.push({severity:"error",code:"manifest.schema",message:`${o.title}: ${u.field} — ${u.message}`,moduleId:t.key.id,path:a.paths[0],pointer:`/${u.field.replace(/\./g,"/")}`})}}for(const[a,d]of Object.entries(t.encodeErrors))n.push({severity:"error",code:"document.encode",message:`${a}: ${d}`,moduleId:t.key.id});if(i.validateModule){const a=[...t.pending.entries()].map(([d,s])=>({path:d,text:s}));n.push(...i.validateModule({key:t.key,files:a,documents:t.documents,contents:t.contents}).map(d=>({...d,moduleId:d.moduleId??t.key.id})))}return n}const mi=(t,i={})=>Object.entries(i).reduce((n,[a,d])=>n.split(`{${a}}`).join(String(d)),t),pi=t=>t instanceof Error?t.message:String(t);function hi(t,i,n){const[a,d]=b.useState([]),[s,o]=b.useState({}),u=b.useRef(s);u.current=s;const[c,l]=b.useState({}),[r,p]=b.useState(null),[m,g]=b.useState({}),[v,f]=b.useState({}),[j,N]=b.useState(0),[$,O]=b.useState([]),_=b.useRef({provider:t,preset:i,options:n});_.current={provider:t,preset:i,options:n};const y=b.useCallback((w,I,T)=>{var F,R;return mi(((R=(F=_.current.options).t)==null?void 0:R.call(F,w,I))??I,T)},[]),x=b.useCallback((w,I,T)=>{O(F=>[...F,{level:w,message:I,data:T,timestamp:Date.now()}].slice(-300))},[]),k=b.useCallback(async(w,I)=>{var T,F;N(R=>R+1);try{return await I()}catch(R){x("error",`${w}: ${pi(R)}`),(F=(T=_.current.options).onError)==null||F.call(T,R,w);return}finally{N(R=>R-1)}},[x]),M=b.useCallback(async()=>{const w=_.current.provider;w&&await k(y("devStudio.log.list","List"),async()=>{const I=await w.listWorkspaces();d(I);const T=await Promise.all(I.map(async F=>{const[R,J]=await Promise.all([w.listModules(F.id),w.listPackages?w.listPackages(F.id):Promise.resolve(void 0)]);return[F.id,R,J]}));o(Object.fromEntries(T.map(([F,R])=>[F,R]))),l(Object.fromEntries(T.filter(([,,F])=>F).map(([F,,R])=>[F,R]))),p(w.listTemplates?await w.listTemplates():null)})},[k,y]);b.useEffect(()=>{M()},[t,M]);const V=b.useMemo(()=>{const w={};for(const[I,T]of Object.entries(m))w[I]=Ve(T,i,n.locales);return w},[m,i,n.locales]),D=b.useCallback(async w=>{var X,A;const I=ee(w),T=_.current.provider;if(!T)return;const F=await k(y("devStudio.log.open","Open {id}",{id:w.id}),()=>T.readModule(w));if(!F)return;const R=(A=(X=u.current[w.workspaceId])==null?void 0:X.find(oe=>oe.id===w.id))==null?void 0:A.contents,J={key:w,files:F,raw:{},deleted:[],drafts:{},contents:R};return g(oe=>oe[I]?oe:{...oe,[I]:J}),x("info",y("devStudio.log.opened","Opened {id} ({count} files)",{id:w.id,count:F.length})),Ve(J,_.current.preset,_.current.options.locales)},[k,x,y]),G=b.useCallback((w,I)=>{const T=ee(w);g(F=>F[T]?{...F,[T]:I(F[T])}:F)},[]),te=b.useCallback((w,I,T)=>G(w,F=>({...F,drafts:{...F.drafts,[I]:T}})),[G]),Q=b.useCallback((w,I,T,F=[])=>G(w,R=>{const J={...R.raw};T===null?delete J[I]:J[I]=T;const X={...R.drafts};for(const A of F)delete X[A];return{...R,raw:J,drafts:X,deleted:R.deleted.filter(A=>A!==I)}}),[G]),H=b.useCallback((w,I)=>G(w,T=>{const F={...T.raw};delete F[I];const R=!T.files.some(J=>J.path===I);return{...T,raw:F,deleted:R?T.deleted:[...new Set([...T.deleted,I])]}}),[G]),C=b.useCallback(w=>G(w,I=>({...I,raw:{},deleted:[],drafts:{}})),[G]),E=b.useCallback(async w=>{const I=_.current.provider;if(!I)return;const T=await k(y("devStudio.log.reload","Reload {id}",{id:w.id}),()=>I.readModule(w));T&&(G(w,F=>({key:w,files:T,raw:{},deleted:[],drafts:{},contents:F.contents})),x("info",y("devStudio.log.reloaded","Reloaded {id}",{id:w.id})))},[k,G,x,y]),B=b.useCallback(w=>{const I=ee(w);g(T=>{const F={...T};return delete F[I],F})},[]),L=b.useCallback(async(w,I={})=>{var ce;const T=_.current.provider,F=ee(w),R=m[F];if(!T||!R)return;const J=Ve(R,_.current.preset,_.current.options.locales);if(J.changes.length===0)return{ok:!0};const X=I.force?J.changes.map(se=>({...se,baseVersion:void 0})):J.changes,A=await k(y("devStudio.log.save","Save {id}",{id:w.id}),()=>T.writeModule(w,X));if(!A)return;if(!A.ok)return x("warn",y("devStudio.log.conflicts","{id}: {count} file(s) changed meanwhile",{id:w.id,count:A.conflicts.length})),A;const oe=[];for(const[se,Fe]of J.pending){const fe=R.files.find(he=>he.path===se);oe.push({...fe,path:se,text:Fe,version:((ce=A.versions)==null?void 0:ce[se])??(fe==null?void 0:fe.version)})}G(w,se=>({key:w,files:oe,raw:{},deleted:[],drafts:{},contents:se.contents}));const re=X.map(se=>se.type==="delete"?y("devStudio.log.changeDelete","delete {path}",{path:se.path}):y("devStudio.log.changeWrite","write {path}",{path:se.path})).join(", ");return x("info",y("devStudio.log.saved","Saved {id}: {changes}",{id:w.id,changes:re})),A},[m,k,G,x,y]),Z=b.useCallback(async w=>{const I=ee(w),T=V[I];if(!T)return[];const F=wt(T,i),R=_.current.provider;let J=[];if(R!=null&&R.validate){const A=[...T.pending.entries()].map(([oe,re])=>({path:oe,text:re}));J=await k(y("devStudio.log.validate","Validate {id}",{id:w.id}),()=>R.validate(w,A))??[]}f(A=>({...A,[I]:J}));const X=[...F,...J];x(X.some(A=>A.severity==="error")?"warn":"info",X.length===0?y("devStudio.log.noProblems","{id}: no problems",{id:w.id}):y("devStudio.log.problems","{id}: {count} problem(s)",{id:w.id,count:X.length}));for(const A of X)x(A.severity==="error"?"error":A.severity==="warning"?"warn":"info",`${A.path?`${A.path}: `:""}${A.messageKey?y(A.messageKey,A.message,A.params):A.message}`);return X},[V,i,k,x,y]),U=b.useCallback(async w=>{const{provider:I,preset:T}=_.current;if(!(I!=null&&I.createModule)||!T.generateModule)return;const F=new Set(Object.values(s).flatMap(X=>X.map(A=>A.id))),R=await k(y("devStudio.log.generate","Generate module"),()=>T.generateModule(w,{existingIds:F}));if(!R)return;const J=await k(y("devStudio.log.create","Create {id}",{id:R.id}),()=>I.createModule({workspaceId:w.workspaceId,packageId:R.packageId??w.packageId,id:R.id,files:R.files}));return J&&(x("info",y("devStudio.log.created","Created {id}",{id:J.id})),await M()),J},[s,k,x,M,y]),z=b.useCallback(async(w,I)=>{const{provider:T,preset:F}=_.current;if(!(T!=null&&T.createModule)||!F.duplicateModule)return;const R=await k(y("devStudio.log.read","Read {id}",{id:w.id}),()=>T.readModule(w));if(!R)return;const J=await k(y("devStudio.log.duplicate","Duplicate"),()=>F.duplicateModule(R,I));if(!J)return;const X=await k(y("devStudio.log.create","Create {id}",{id:J.id}),()=>T.createModule({workspaceId:I.workspaceId,packageId:J.packageId??I.packageId,id:J.id,files:J.files}));return X&&(x("info",y("devStudio.log.duplicated","Duplicated {id} as {copy}",{id:w.id,copy:X.id})),await M()),X},[k,x,M,y]),Y=b.useCallback(async w=>{const I=_.current.provider;if(!(I!=null&&I.deleteModule))return!1;const T=await k(y("devStudio.log.delete","Delete {id}",{id:w.id}),async()=>(await I.deleteModule(w),!0));return T&&(B(w),x("info",y("devStudio.log.deleted","Deleted {id}",{id:w.id})),await M()),!!T},[k,B,x,M,y]),le=b.useCallback(async w=>{const I=_.current.provider;if(!(I!=null&&I.savePackage))return;const T=await k(y("devStudio.log.savePackage","Save package {id}",{id:w.id}),()=>I.savePackage(w));return T&&(x("info",y("devStudio.log.savedPackage","Saved package {id}",{id:T.id})),await M()),T},[k,x,M,y]),je=b.useCallback(async(w,I)=>{const T=_.current.provider;if(!(T!=null&&T.saveTemplate))return;const F=await k(y("devStudio.log.saveTemplate","Save template {id}",{id:w.id}),()=>T.saveTemplate(w,I?{previousId:I}:void 0));return F&&T.listTemplates&&(p(await T.listTemplates()),x("info",y("devStudio.log.savedTemplate","Saved template {id}",{id:F.id}))),F},[k,x,y]),q=b.useCallback(async w=>{const I=_.current.provider;if(!(I!=null&&I.deleteTemplate))return!1;const T=await k(y("devStudio.log.deleteTemplate","Delete template {id}",{id:w}),async()=>(await I.deleteTemplate(w),!0));return T&&I.listTemplates&&(p(await I.listTemplates()),x("info",y("devStudio.log.deletedTemplate","Deleted template {id}",{id:w}))),!!T},[k,x,y]);return{workspaces:a,modulesByWs:s,packagesByWs:c,templates:r,modules:V,serverIssues:v,busy:j>0,logs:$,clearLogs:()=>O([]),log:x,refresh:M,openModule:D,close:B,setDraft:te,setRaw:Q,deleteFile:H,discard:C,reload:E,save:L,validate:Z,createModule:U,duplicateModule:z,deleteModule:Y,savePackage:le,saveTemplate:je,deleteTemplate:q}}const be="__none",Oe="t:",vi={entities:"entities",views:"views",workflows:"workflows",i18n:"translations",permissions:"permissions",rbac:"access",dataSources:"dataSources",seeds:"seeds",hooks:"hooks",script:"scripts"},fi=["entities","views","workflows","translations","permissions","access","dataSources","seeds","hooks","scripts"],xe={entities:"database",views:"grid",workflows:"git-branch",translations:"globe",permissions:"shield",access:"users",dataSources:"server",seeds:"list",hooks:"zap",scripts:"code",files:"folder"},gi={views:"grid",workflows:"git-branch",dataSources:"server"},Nt=t=>vi[t.kind.editor];function Se(t,i,n){const a=(d,s)=>t(d,s).replace("{count}",String(n??0));switch(i){case"entities":return a("devStudio.group.entities","Entities: {count}");case"views":return a("devStudio.group.views","Views: {count}");case"workflows":return a("devStudio.group.workflows","Workflows: {count}");case"dataSources":return a("devStudio.group.dataSources","Data sources: {count}");case"scripts":return a("devStudio.group.scripts","Scripts: {count}");case"files":return a("devStudio.group.files","Files: {count}");case"translations":return t("devStudio.group.translations","Translations");case"permissions":return t("devStudio.group.permissions","Permissions");case"access":return t("devStudio.group.access","Access");case"seeds":return t("devStudio.group.seeds","Seed data");case"hooks":return t("devStudio.group.hooks","Lifecycle hooks")}}function _t(t){switch(t.kind){case"workspace":return`w|${t.workspaceId}`;case"package":return`p|${t.workspaceId}|${t.packageId??be}`;case"module":return`m|${ee(t.module)}`;case"group":return`g|${ee(t.module)}|${t.group}`;case"entity":return`e|${ee(t.module)}|${t.docKey}|${t.index}`;case"item":return`i|${ee(t.module)}|${t.group}|${t.docKey}|${t.itemKey}`;case"document":return`d|${ee(t.module)}|${t.docKey}`;case"panel":return`x|${ee(t.module)}|${t.panelKey}`;case"file":return`f|${ee(t.module)}|${t.path}`;case"templates":return"t";case"category":return`c|${t.category}`;case"template":return`t|${t.templateId}`;case"templateModule":return`tm|${t.templateId}|${t.moduleId}`}}const ne=(t,i)=>t.drafts[i.key]??i.model,me=(t,i)=>t.documents.find(n=>n.key===i),we=(t,i)=>t.changes.some(n=>i.paths.includes(n.path));function et(t){const i=[];for(const n of t.documents){if(n.kind.editor!=="entities")continue;const a=ne(t,n);Array.isArray(a)&&a.forEach((d,s)=>i.push({docKey:n.key,index:s,entity:d}))}return i}const Je=t=>et(t).map(i=>i.entity),tt=(t,i="name")=>String(t.displayName||t[i]||"");function pe(t,i){const n=ne(t,i);return Array.isArray(n)?i.kind.editor==="dataSources"?n.map(a=>{const d=a;return{key:String(d.key??""),label:d.label||String(d.key??""),definition:a,source:a}}):n:[]}function it(t,i,n){return n===null?t.filter((a,d)=>d!==i):t.map((a,d)=>d===i?n:a)}function It(t,i,n){return n===null?t.filter(a=>a.key!==i):t.map(a=>a.key===i?n:a)}function Tt(t,i,n){const a=new Map((i??[]).map(d=>[d.id,d]));for(const d of n){const s=d.packageId??be;a.has(s)||a.set(s,{id:s,workspaceId:t,label:d.packageId??"",derived:!0})}return[...a.values()].sort((d,s)=>d.id===be?1:s.id===be?-1:d.label.localeCompare(s.label))}const Me=(t,i)=>t&&/^[a-z0-9-]+$/.test(t)?t:i,ht=t=>t.slice(t.lastIndexOf("/")+1);function yi(t,i,n){var c;const{t:a}=n,d=i.key,s=new Map;for(const l of i.documents){const r=Nt(l);r&&s.set(r,[...s.get(r)??[],l])}const o=(l,r)=>({id:`${r}/d:${l.key}`,node:{kind:"document",module:d,docKey:l.key},label:ht(l.paths[0]??l.label),icon:"warning",noForm:!0,dirty:we(i,l)}),u=[];for(const l of fi){const r=s.get(l);if(!r)continue;const p=`${t}/g:${l}`,m={kind:"group",module:d,group:l};if(l==="entities"){const g=[];for(const f of r){const j=ne(i,f);if(!Array.isArray(j)){g.push(o(f,p));continue}const N=we(i,f);j.forEach(($,O)=>{const _=$.fields;g.push({id:`${p}/e:${f.key}#${O}`,node:{kind:"entity",module:d,docKey:f.key,index:O},label:tt($)||`#${O+1}`,icon:"table",info:Array.isArray(_)?String(_.length):void 0,dirty:N,search:String($.name??"")})})}const v=g.filter(f=>f.node.kind==="entity").length;u.push({id:p,node:m,label:Se(a,l,v),icon:xe[l],children:g});continue}if(l==="views"||l==="workflows"||l==="dataSources"){const g=[];for(const f of r){if(f.model===void 0){g.push(o(f,p));continue}const j=we(i,f);for(const N of pe(i,f))g.push({id:`${p}/i:${f.key}#${N.key}`,node:{kind:"item",module:d,group:l,docKey:f.key,itemKey:N.key},label:N.label||N.key,icon:gi[l],noForm:N.definition===void 0,dirty:j,search:N.key})}const v=g.filter(f=>f.node.kind==="item").length;u.push({id:p,node:m,label:Se(a,l,v),icon:xe[l],children:g});continue}if(l==="scripts"){u.push({id:p,node:m,label:Se(a,l,r.length),icon:xe[l],children:r.map(g=>({id:`${p}/d:${g.key}`,node:{kind:"document",module:d,docKey:g.key},label:ht(g.paths[0]??g.label),icon:"code",dirty:we(i,g),search:g.paths.join(" ")}))});continue}if(r.length===1){const g=r[0];u.push({id:p,node:{kind:"document",module:d,docKey:g.key},label:Se(a,l),icon:xe[l],noForm:g.model===void 0,dirty:we(i,g)});continue}u.push({id:p,node:m,label:Se(a,l),icon:xe[l],children:r.map(g=>({id:`${p}/d:${g.key}`,node:{kind:"document",module:d,docKey:g.key},label:g.label,icon:xe[l],noForm:g.model===void 0,dirty:we(i,g),search:g.paths.join(" ")}))})}for(const l of((c=n.panels)==null?void 0:c.call(n,i))??[])u.push({id:`${t}/x:${l.key}`,node:{kind:"panel",module:d,panelKey:l.key},label:l.label,icon:"puzzle"});if(n.advanced){const l=new Set(i.changes.map(p=>p.path)),r=[...i.working].sort((p,m)=>p.path.localeCompare(m.path));u.push({id:`${t}/g:files`,node:{kind:"group",module:d,group:"files"},label:Se(a,"files",r.length),icon:xe.files,children:r.map(p=>({id:`${t}/g:files/f:${p.path}`,node:{kind:"file",module:d,path:p.path},label:p.path,icon:"file",dirty:l.has(p.path)}))})}return u}function xi(t){const{t:i}=t,n=i("devStudio.explorer.noPackage","No package"),a=t.workspaces.map(c=>{const l=t.modulesByWs[c.id]??[],r=`w:${c.id}`;return{id:r,node:{kind:"workspace",workspaceId:c.id},label:c.label,icon:Me(c.icon,"folder"),info:String(l.length),readOnly:c.readOnly,search:c.id,children:Tt(c.id,t.packagesByWs[c.id],l).map(p=>{const m=`${r}/p:${p.id}`,g=l.filter(v=>(v.packageId??be)===p.id).sort((v,f)=>v.label.localeCompare(f.label));return{id:m,node:{kind:"package",workspaceId:c.id,packageId:p.id===be?void 0:p.id},label:p.id===be?n:p.label||p.id,icon:Me(p.icon,"archive"),info:String(g.length),search:p.id,children:g.map(v=>{var _;const f=ee(v),j=t.modules[f],N=`${m}/m:${v.id}`,$=j?yi(N,j,t):void 0,O=j?[...et(j).map(y=>`${y.entity.name??""} ${tt(y.entity)}`),...j.documents.filter(y=>y.kind.editor==="views").flatMap(y=>pe(j,y).map(x=>`${x.key} ${x.label}`))]:[];return{id:N,node:{kind:"module",module:{workspaceId:v.workspaceId,id:v.id}},label:v.label,icon:Me(v.icon,"box"),info:v.version,readOnly:v.readOnly,shadowedBy:v.shadowedBy,dirty:j==null?void 0:j.dirty,issues:(_=t.issueCounts)==null?void 0:_[f],search:[v.id,v.description??"",v.search??"",...O].join(" "),children:$}})}})}});if(t.templates){const c=new Map;for(const p of t.workspaces)for(const m of t.modulesByWs[p.id]??[])c.has(m.id)||c.set(m.id,m);const l=new Map;for(const p of t.templates){const m=p.category??"";l.set(m,[...l.get(m)??[],p])}const r=p=>{var m,g;return((m=p.translations.en)==null?void 0:m.name)??((g=Object.values(p.translations)[0])==null?void 0:g.name)??p.id};a.push({id:Oe,node:{kind:"templates"},label:i("devStudio.tree.templates","Templates"),icon:"layers",info:String(t.templates.length),children:[...l.entries()].sort(([p],[m])=>p.localeCompare(m)).map(([p,m])=>{const g=`${Oe}/c:${p}`;return{id:g,node:{kind:"category",category:p},label:p||i("devStudio.explorer.noCategory","Other"),icon:"folder",info:String(m.length),children:[...m].sort((v,f)=>(v.sortOrder??0)-(f.sortOrder??0)||r(v).localeCompare(r(f))).map(v=>{const f=`${g}/t:${v.id}`;return{id:f,node:{kind:"template",templateId:v.id},label:r(v),icon:Me(v.icon,"layers"),info:String(v.modules.length),readOnly:v.readOnly,search:`${v.id} ${(v.tags??[]).join(" ")}`,children:v.modules.map(j=>{const N=c.get(j.moduleId);return{id:`${f}/m:${j.moduleId}`,node:{kind:"templateModule",templateId:v.id,moduleId:j.moduleId,target:N?{workspaceId:N.workspaceId,id:N.id}:void 0},label:(N==null?void 0:N.label)??j.moduleId,icon:"box",info:j.required?i("devStudio.template.required","required"):void 0,missing:!N,search:j.moduleId}})}})}})})}const d=new Map,s=new Map,o=new Map,u=(c,l,r=0)=>{for(const p of c){p.depth=r,d.set(p.id,p),l&&s.set(p.id,l);const m=_t(p.node);o.has(m)||o.set(m,p.id),p.children&&u(p.children,p.id,r+1)}};return u(a),{rows:a,byId:d,parentOf:s,rowOfNode:o}}function vt(t,i){const n=[];let a=i;for(;a;){const d=t.byId.get(a);if(!d)break;n.unshift(d),a=t.parentOf.get(a)}return n}const We=(t,i)=>t.rowOfNode.get(_t(i));function Ke(t){return"module"in t?t.module:void 0}function ki(t,i){var a;const n="module"in t?i.modules[ee(t.module)]:void 0;switch(t.kind){case"module":return n!=null&&n.documents.some(d=>d.kind.editor==="manifest")?{kind:"manifest",module:t.module}:void 0;case"entity":return{kind:"entity",module:t.module,docKey:t.docKey,index:t.index};case"item":{const d=n&&me(n,t.docKey),s=d&&pe(n,d).find(o=>o.key===t.itemKey);return(s==null?void 0:s.definition)!==void 0||i.advanced?{...t}:void 0}case"document":{const d=n&&me(n,t.docKey);return(d==null?void 0:d.model)!==void 0?{kind:"document",module:t.module,docKey:t.docKey}:d&&i.advanced?{kind:"file",module:t.module,path:d.paths[0]}:void 0}case"panel":return{kind:"panel",module:t.module,panelKey:t.panelKey};case"file":return{kind:"file",module:t.module,path:t.path};case"package":{const d=(a=i.packages)==null?void 0:a.find(s=>s.id===t.packageId);return d&&!d.derived?{kind:"package",pkg:d}:void 0}case"template":return{kind:"template",templateId:t.templateId};default:return}}function ft(t){switch(t.kind){case"manifest":case"problems":case"history":return{kind:"module",module:t.module};case"entity":return{kind:"entity",module:t.module,docKey:t.docKey,index:t.index};case"item":return{...t};case"document":return{kind:"document",module:t.module,docKey:t.docKey};case"panel":return{kind:"panel",module:t.module,panelKey:t.panelKey};case"file":return{kind:"file",module:t.module,path:t.path};case"package":return{kind:"package",workspaceId:t.pkg.workspaceId,packageId:t.pkg.id};case"template":return t.templateId?{kind:"template",templateId:t.templateId}:void 0}}const bi=/^\/(?:[A-Za-z]+\/)?(\d+)(?:\/|$)/;function Ct(t,i){const n=t.key,a=i.path?t.documents.find(u=>u.paths.includes(i.path)):void 0;if(!a)return{kind:"module",module:n};const d=Nt(a),s=a.paths.length===1?bi.exec(i.pointer??""):null,o=s?Number(s[1]):-1;if(d==="entities"){const u=ne(t,a);return Array.isArray(u)&&o>=0&&o<u.length?{kind:"entity",module:n,docKey:a.key,index:o}:{kind:"group",module:n,group:d}}if(d==="views"||d==="workflows"||d==="dataSources"){const u=o>=0?pe(t,a)[o]:void 0;return u?{kind:"item",module:n,group:d,docKey:a.key,itemKey:u.key}:{kind:"group",module:n,group:d}}return d?{kind:"document",module:n,docKey:a.key}:a.kind.editor==="manifest"?{kind:"module",module:n}:{kind:"file",module:n,path:a.paths[0]}}function gt(t){var l,r;const{module:i,doc:n,preset:a,session:d,locales:s,readOnly:o}=t,u=ne(i,n),c=p=>d.setDraft(i.key,n.key,p);switch(n.kind.editor){case"manifest":return e.jsx(ji,{...t});case"i18n":{const p=u??{};return e.jsx(Qe,{value:p,onChange:c,locales:[...new Set([...s,...Object.keys(p)])],allowEditLocales:!0,allowEditKeys:!0,highlightMissing:!0,readOnly:o})}case"permissions":return e.jsx(Si,{value:u??{permissions:[],groups:[]},onChange:c,readOnly:o});case"seeds":return e.jsx(_i,{value:u??{seeds:{}},onChange:c,entities:Je(i),readOnly:o});case"rbac":return e.jsx(h.NiceAccessManager,{value:u,onChange:c,readOnly:o});case"hooks":return e.jsx(h.NiceLifecycleHooksEditor,{triggers:((l=a.hooks)==null?void 0:l.triggers)??[],handlers:(r=a.hooks)==null?void 0:r.handlers,bindings:u??[],onChange:c,groupByTrigger:!0,allowCondition:!0,readOnly:o});case"script":return t.scriptRunner?e.jsx(h.NiceScriptRunner,{...t.scriptRunner,value:String(u??""),onChange:c}):e.jsx(h.NiceSimpleCodeEditor,{value:String(u??""),onChange:c,language:"javascript",height:"100%",lineNumbers:!0,readOnly:o});case"text":return e.jsx(h.NiceSimpleCodeEditor,{value:String(u??""),onChange:c,height:"100%",lineNumbers:!0,readOnly:o});default:return e.jsx(Ze,{value:u,onChange:c,readOnly:o,height:"100%",label:n.label})}}function ji({module:t,doc:i,preset:n,session:a,readOnly:d,advanced:s}){var O;const{t:o}=h.useNiceTranslation(),u=ne(t,i),c=b.useMemo(()=>u??{},[u]),l=_=>a.setDraft(t.key,i.key,_),r=n.manifestSections,p=b.useMemo(()=>(r??[]).map(_=>P.fitManifestSection(_,c)),[r,c]),m=r??[],g=b.useMemo(()=>new Set(p.flatMap(_=>_.keys)),[p]),v=Object.keys(c).filter(_=>!g.has(_)),[f,j]=b.useState(((O=p[0])==null?void 0:O.section.id)??"__other"),N=p.find(_=>_.section.id===f),$=s?e.jsx(Ze,{value:Object.fromEntries(v.map(_=>[_,c[_]])),readOnly:d,label:o("devStudio.manifest.other","Other properties"),onChange:_=>{if(_&&typeof _=="object"&&!Array.isArray(_)){const y=Object.fromEntries(Object.entries(c).filter(([x])=>g.has(x)));l({...y,..._})}}}):e.jsxs("div",{className:"nice-development-studio__note",children:[e.jsx("p",{children:o("devStudio.manifest.kept","These properties have no form here. Saving keeps them exactly as they are; switch to the advanced mode to edit them.")}),e.jsx("ul",{className:"nice-development-studio__chips",children:v.map(_=>e.jsx("li",{className:"nice-development-studio__tag",children:_},_))})]});return e.jsxs("div",{className:"nice-development-studio__sections","data-testid":"studio-manifest-form",children:[e.jsxs("nav",{className:"nice-development-studio__section-nav","aria-label":o("devStudio.manifest.sections","Sections"),children:[p.map(({section:_})=>e.jsx(h.NiceButton,{size:"sm",variant:f===_.id?"primary":"ghost","aria-pressed":f===_.id,onClick:()=>j(_.id),children:_.title},_.id)),v.length>0&&e.jsx(h.NiceButton,{size:"sm",variant:f==="__other"?"primary":"ghost","aria-pressed":f==="__other",onClick:()=>j("__other"),children:`${o("devStudio.manifest.other","Other properties")} (${v.length})`})]}),e.jsx("div",{className:"nice-development-studio__section-body",children:N?e.jsx(_e,{schema:N.section.schema,fields:N.section.fields,uiSchema:N.section.uiSchema,value:Object.fromEntries(N.keys.filter(_=>_ in c).map(_=>[_,c[_]])),onChange:_=>{const y={...c};for(const x of N.keys)_[x]===void 0?delete y[x]:y[x]=_[x];l(y)},readOnly:d}):v.length>0||m.length===0?$:null})]})}function Si({value:t,onChange:i,readOnly:n}){const{t:a}=h.useNiceTranslation(),d={code:a("devStudio.permissions.code","Code"),name:a("devStudio.permissions.name","Name"),description:a("devStudio.permissions.description","Description")},s=b.useMemo(()=>{const u={};for(const c of t.groups)for(const l of c.permissions)u[`${c.id}:${l}`]=!0;return u},[t.groups]),o=(u,c)=>{const l=t.permissions[u],r={...l,...c};i({permissions:t.permissions.map((p,m)=>m===u?r:p),groups:c.code!==void 0&&c.code!==l.code?t.groups.map(p=>({...p,permissions:p.permissions.map(m=>m===l.code?r.code:m)})):t.groups})};return e.jsxs("div",{className:"nice-development-studio__permissions",children:[e.jsx("h4",{children:a("devStudio.permissions.codes","Permissions")}),e.jsxs("table",{className:"nice-development-studio__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d.code}),e.jsx("th",{children:d.name}),e.jsx("th",{children:d.description}),!n&&e.jsx("th",{"aria-label":a("devStudio.delete","Delete")})]})}),e.jsx("tbody",{children:t.permissions.map((u,c)=>e.jsxs("tr",{children:[["code","name","description"].map(l=>e.jsx("td",{children:e.jsx("input",{className:"nice-development-studio__cell",value:u[l]??"",readOnly:n,"aria-label":`${d[l]} ${u.code}`,onChange:r=>o(c,{[l]:r.target.value})})},l)),!n&&e.jsx("td",{children:e.jsx(h.NiceButton,{size:"sm",variant:"ghost",ariaLabel:`${a("devStudio.delete","Delete")} ${u.code}`,onClick:()=>i({permissions:t.permissions.filter((l,r)=>r!==c),groups:t.groups.map(l=>({...l,permissions:l.permissions.filter(r=>r!==u.code)}))}),children:e.jsx(h.NiceIcon,{name:"trash",size:14})})})]},c))})]}),!n&&e.jsxs("div",{className:"nice-development-studio__row",children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:()=>i({...t,permissions:[...t.permissions,{code:`New.Permission${t.permissions.length+1}`}]}),children:a("devStudio.permissions.addCode","New permission")}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:()=>i({...t,groups:[...t.groups,{id:`group${t.groups.length+1}`,label:a("devStudio.permissions.newGroup","Group {n}").replace("{n}",String(t.groups.length+1)),permissions:[]}]}),children:a("devStudio.permissions.addGroup","New group")})]}),e.jsx("h4",{children:a("devStudio.permissions.groups","Groups")}),e.jsx(h.NicePermissionMatrix,{roles:t.groups.map(u=>({id:u.id,label:u.label})),actions:t.permissions.map(u=>({id:u.code,label:u.name||u.code})),value:s,readOnly:n,showBulkActions:!0,onChange:u=>i({...t,groups:t.groups.map(c=>({...c,permissions:t.permissions.map(l=>l.code).filter(l=>u[`${c.id}:${l}`]===!0)}))})})]})}const yt=t=>t===null||typeof t!="object";function wi(t){const i=t.toLowerCase();return/(int|long|decimal|double|float|number|money)/.test(i)?"number":/bool/.test(i)?"boolean":"string"}function Ni(t,i){const n={},a=Array.isArray(i==null?void 0:i.fields)?i.fields:[];for(const d of a){const s=String(d.name??"");s&&t.every(o=>yt(o[s]))&&(n[s]={type:wi(String(d.dataType??d.type??"string")),title:String(d.displayName||s)})}for(const d of t)for(const[s,o]of Object.entries(d))!(s in n)&&t.every(u=>yt(u[s]))&&(n[s]={type:typeof o=="number"?"number":typeof o=="boolean"?"boolean":"string",title:s});return{type:"object",properties:n}}function _i({value:t,onChange:i,entities:n,readOnly:a}){const{t:d}=h.useNiceTranslation(),s=u=>n.find(c=>c.name===u||c.tableName===u),o=u=>{const c=t[u]??{},l=Object.keys(c);return l.length===0?e.jsx("p",{className:"nice-development-studio__muted",children:d("devStudio.seeds.empty","No rows.")}):e.jsx(h.NiceTabs,{tabs:l.map(r=>{const p=c[r];return{id:r,label:`${r} (${p.length})`,content:e.jsx(Ye,{value:p,itemSchema:Ni(p,s(r)),title:r,readOnly:a,onChange:m=>{const g=m.length===p.length?m.map((v,f)=>v===p[f]?v:{...p[f],...v}):m;i({...t,[u]:{...c,[r]:g}})}})}})})};return e.jsx(h.NiceTabs,{tabs:[{id:"seeds",label:d("devStudio.seeds.data","Data"),content:o("seeds")},{id:"demo",label:d("devStudio.seeds.demo","Demo data"),content:o("demoSeeds")}]})}function Ii({module:t,path:i,session:n,readOnly:a}){var r;const{t:d}=h.useNiceTranslation(),[s,o]=b.useState("source"),u=t.changes.find(p=>p.path===i),c=t.documents.filter(p=>p.paths.includes(i)).map(p=>p.key),l=((r=t.files.find(p=>p.path===i))==null?void 0:r.text)??"";return e.jsxs("div",{className:"nice-development-studio__source","data-testid":"studio-file-source",children:[e.jsx("div",{className:"nice-development-studio__row",children:e.jsxs("div",{className:"nice-development-studio__segmented",role:"group","aria-label":d("devStudio.doc.mode","Show"),children:[e.jsx(h.NiceButton,{size:"sm",variant:s==="source"?"primary":"ghost","aria-pressed":s==="source",onClick:()=>o("source"),children:d("devStudio.doc.source","Source")}),e.jsx(h.NiceButton,{size:"sm",variant:s==="changes"?"primary":"ghost","aria-pressed":s==="changes",onClick:()=>o("changes"),children:`${d("devStudio.doc.changes","Changes")}${u?" (1)":""}`})]})}),s==="source"?e.jsx(h.NiceSimpleCodeEditor,{value:t.pending.get(i)??"",language:i.endsWith(".json")?"json":i.endsWith(".js")?"javascript":"plaintext",height:"100%",lineNumbers:!0,readOnly:a,onChange:p=>n.setRaw(t.key,i,P.keepTextFormat(p,t.pending.get(i)),c)}):u?e.jsx(St,{before:l,after:u.type==="write"?u.text:""}):e.jsx("p",{className:"nice-development-studio__muted",children:d("devStudio.diff.none","No changes.")})]})}const Ti=t=>({type:"object",required:["id"],properties:{id:{type:"string",title:t("devStudio.template.id","Id (slug)")},category:{type:"string",title:t("devStudio.template.category","Category")},subCategory:{type:"string",title:t("devStudio.template.subCategory","Subcategory")},parentId:{type:"string",title:t("devStudio.template.parent","Parent template")},icon:{type:"string",title:t("devStudio.template.icon","Icon")},sortOrder:{type:"number",title:t("devStudio.template.sortOrder","Order")},tags:{type:"array",items:{type:"string"},title:t("devStudio.template.tags","Tags")}}});function Ci({session:t,template:i,locales:n,extraSchema:a,readOnly:d,onSaved:s,onDeleted:o}){var _;const{t:u}=h.useNiceTranslation(),[c,l]=b.useState(()=>i??{id:"",translations:{[n[0]??"en"]:{name:""}},modules:[]}),[r,p]=b.useState(null),m=d||!!(i!=null&&i.readOnly),g={id:c.id,category:c.category,subCategory:c.subCategory,parentId:c.parentId,icon:c.icon,sortOrder:c.sortOrder,tags:c.tags},v=Object.fromEntries(Object.entries(c.translations).map(([y,x])=>[y,{name:x.name,description:x.description??""}])),f=b.useMemo(()=>t.workspaces.map(y=>{const x=t.modulesByWs[y.id]??[],k=[...new Set(x.map(M=>M.packageId??""))].sort();return{id:`w:${y.id}`,label:y.label,kind:"workspace",children:k.map(M=>({id:`w:${y.id}/p:${M}`,label:M||u("devStudio.explorer.noPackage","No package"),kind:"package",children:x.filter(V=>(V.packageId??"")===M).map(V=>({id:`m:${V.id}`,label:V.label,kind:"module"}))}))}}),[t.workspaces,t.modulesByWs,u]),j=b.useMemo(()=>{const y=new Map;for(const x of Object.values(t.modulesByWs))for(const k of x)y.set(k.id,k.label);return y},[t.modulesByWs]),N=y=>l({...c,modules:y}),$=(y,x)=>{const k=[...c.modules],[M]=k.splice(y,1);k.splice(y+x,0,M),N(k)},O=[{field:"label",header:u("devStudio.explorer.name","Name")}];return e.jsxs("div",{className:"nice-development-studio__template","data-testid":"studio-template-editor",children:[e.jsxs("div",{className:"nice-development-studio__doc-bar",children:[e.jsx(h.NiceIcon,{name:"layers",size:14}),e.jsx("strong",{className:"nice-development-studio__doc-title",children:i?((_=c.translations.en)==null?void 0:_.name)||c.id:u("devStudio.template.new","New template")}),e.jsx("span",{className:"nice-development-studio__spacer"}),!m&&e.jsx(h.NiceButton,{size:"sm",variant:"primary",disabled:!c.id.trim(),onClick:async()=>{p(null);const y=await t.saveTemplate({...c,id:c.id.trim()},i==null?void 0:i.id);y?s==null||s(y):p(u("devStudio.template.saveFailed","The template could not be saved; see the output panel."))},children:u("devStudio.save","Save")}),!m&&i&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"trash",size:14}),onClick:async()=>{await t.deleteTemplate(i.id)&&(o==null||o())},children:u("devStudio.delete","Delete")})]}),r&&e.jsx("p",{className:"nice-development-studio__error",role:"alert",children:r}),e.jsxs("div",{className:"nice-development-studio__columns",children:[e.jsxs("section",{children:[e.jsx("h4",{children:u("devStudio.template.basics","Template")}),e.jsx(_e,{schema:Ti(u),value:g,readOnly:m,onChange:y=>l({...c,id:String(y.id??""),category:y.category||void 0,subCategory:y.subCategory||void 0,parentId:y.parentId||void 0,icon:y.icon||void 0,sortOrder:typeof y.sortOrder=="number"?y.sortOrder:void 0,tags:Array.isArray(y.tags)?y.tags:void 0})}),a&&e.jsx(_e,{schema:a,value:c.extra??{},readOnly:m,onChange:y=>l({...c,extra:y})}),e.jsx("h4",{children:u("devStudio.template.translations","Name and description")}),e.jsx(Qe,{value:v,locales:[...new Set([...n,...Object.keys(v)])],allowEditLocales:!0,readOnly:m,onChange:y=>l({...c,translations:Object.fromEntries(Object.entries(y).map(([x,k])=>[x,{name:k.name??"",...k.description?{description:k.description}:{}}]))})})]}),e.jsxs("section",{children:[e.jsx("h4",{children:u("devStudio.template.modules","Modules")}),e.jsx(h.NiceTreeGrid,{data:f,nested:!0,keyField:"id",childrenField:"children",columns:O,sortable:!1,compact:!0,checkable:!0,checkStrategy:"leaves",isRowCheckable:y=>y.kind!=="workspace",isRowDisabled:()=>m,checkedKeys:c.modules.map(y=>`m:${y.moduleId}`),onCheckedChange:y=>{const x=y.filter(V=>V.startsWith("m:")).map(V=>V.slice(2)),k=c.modules.filter(V=>x.includes(V.moduleId)),M=x.filter(V=>!k.some(D=>D.moduleId===V)).map(V=>({moduleId:V}));N([...k,...M])},checkedSummary:y=>u("devStudio.template.summary","{count} modules · {required} required").replace("{count}",String(y.checked)).replace("{required}",String(c.modules.filter(x=>x.required).length)),searchable:!0,searchFields:["label"],virtualScroll:!0,height:320,"aria-label":u("devStudio.template.modules","Modules")}),e.jsxs("table",{className:"nice-development-studio__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:u("devStudio.template.module","Module")}),e.jsx("th",{children:u("devStudio.template.required","required")}),e.jsx("th",{children:u("devStudio.template.condition","Condition")}),!m&&e.jsx("th",{"aria-label":u("devStudio.template.order","Order")})]})}),e.jsx("tbody",{children:c.modules.map((y,x)=>e.jsxs("tr",{children:[e.jsx("td",{children:j.get(y.moduleId)??y.moduleId}),e.jsx("td",{children:e.jsx("input",{type:"checkbox",checked:!!y.required,disabled:m,"aria-label":`${u("devStudio.template.required","required")} ${y.moduleId}`,onChange:k=>N(c.modules.map((M,V)=>V===x?{...M,required:k.target.checked}:M))})}),e.jsx("td",{children:e.jsx("input",{className:"nice-development-studio__cell",value:y.condition??"",readOnly:m,"aria-label":`${u("devStudio.template.condition","Condition")} ${y.moduleId}`,onChange:k=>N(c.modules.map((M,V)=>V===x?{...M,condition:k.target.value||void 0}:M))})}),!m&&e.jsxs("td",{className:"nice-development-studio__nowrap",children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",disabled:x===0,ariaLabel:u("devStudio.template.up","Move up"),onClick:()=>$(x,-1),children:e.jsx(h.NiceIcon,{name:"chevron-up",size:12})}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",disabled:x===c.modules.length-1,ariaLabel:u("devStudio.template.down","Move down"),onClick:()=>$(x,1),children:e.jsx(h.NiceIcon,{name:"chevron-down",size:12})})]})]},y.moduleId))})]})]})]})]})}function Ei({session:t,pkg:i,readOnly:n,onNewModule:a,onOpenModule:d}){const{t:s}=h.useNiceTranslation(),[o,u]=b.useState({id:i.id,label:i.label,description:i.description,icon:i.icon}),c=(t.modulesByWs[i.workspaceId]??[]).filter(r=>r.packageId===i.id),l=!n&&!i.derived&&!i.readOnly;return e.jsxs("div",{className:"nice-development-studio__template","data-testid":"studio-package-editor",children:[e.jsxs("div",{className:"nice-development-studio__doc-bar",children:[e.jsx(h.NiceIcon,{name:"archive",size:14}),e.jsx("strong",{className:"nice-development-studio__doc-title",children:i.label||i.id}),e.jsx("span",{className:"nice-development-studio__spacer"}),!n&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:a,children:s("devStudio.package.newModule","New module here")}),l&&e.jsx(h.NiceButton,{size:"sm",variant:"primary",onClick:()=>void t.savePackage({...i,id:String(o.id??i.id),label:String(o.label??""),description:o.description||void 0,icon:o.icon||void 0}),children:s("devStudio.save","Save")})]}),i.derived?e.jsx("p",{className:"nice-development-studio__muted",children:s("devStudio.package.derived","This package comes from the modules themselves (their category); rename it by changing their manifests.")}):e.jsx(_e,{schema:{type:"object",required:["id","label"],properties:{id:{type:"string",title:s("devStudio.package.id","Id")},label:{type:"string",title:s("devStudio.package.label","Name")},description:{type:"string",title:s("devStudio.package.description","Description")},icon:{type:"string",title:s("devStudio.template.icon","Icon")}}},value:o,readOnly:!l,onChange:r=>u(r)}),e.jsx("h4",{children:s("devStudio.template.modules","Modules")}),e.jsxs("ul",{className:"nice-development-studio__list",children:[c.map(r=>e.jsxs("li",{children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"box",size:14}),onClick:()=>d(r.id),children:r.label}),r.description&&e.jsx("span",{className:"nice-development-studio__muted",children:r.description})]},r.id)),c.length===0&&e.jsx("li",{className:"nice-development-studio__muted",children:s("devStudio.explorer.empty","No modules.")})]})]})}const Mi=t=>"module"in t?t.module:void 0;function Ki(t){const{screen:i,crumbs:n,session:a,readOnly:d,tutorialButton:s,onBack:o,onSave:u}=t,{t:c}=h.useNiceTranslation(),l=Mi(i),r=l?a.modules[ee(l)]:void 0,p=d(l),m=Oi(i,r,a);return e.jsxs("div",{className:"nice-development-studio__edit","data-testid":"studio-edit-screen",children:[e.jsxs("header",{className:"nice-development-studio__edit-header",children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"arrow-left",size:14}),onClick:o,"data-testid":"studio-back",children:c("devStudio.edit.back","Back")}),e.jsx(h.NiceBreadcrumb,{className:"nice-development-studio__crumbs",size:"sm",separator:"›",items:n}),e.jsx("span",{className:"nice-development-studio__spacer"}),m&&!p&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"trash",size:14}),onClick:()=>{m(),o()},children:c("devStudio.delete","Delete")}),r&&e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"check",size:14}),onClick:()=>void a.validate(r.key),children:c("devStudio.validate","Validate")}),!p&&e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",disabled:!r.dirty,onClick:()=>a.discard(r.key),children:c("devStudio.discard","Discard changes")}),e.jsx(h.NiceButton,{size:"sm",variant:"primary",disabled:!r.dirty,onClick:()=>u(r.key),"data-tour":"devstudio-save",children:r.dirty?c("devStudio.saveCount","Save ({count})").replace("{count}",String(r.changes.length)):c("devStudio.save","Save")})]})]}),s]}),e.jsx("div",{className:"nice-development-studio__edit-body",children:e.jsx(Fi,{...t,module:r,readOnlyHere:p})})]})}function Oi(t,i,n){if(!i||t.kind!=="entity"&&t.kind!=="item")return;const a=me(i,t.docKey);if(!a)return;if(t.kind==="entity"){const s=ne(i,a);return Array.isArray(s)?()=>n.setDraft(i.key,a.key,it(s,t.index,null)):void 0}if(t.group==="dataSources"){const s=ne(i,a)??[];return()=>n.setDraft(i.key,a.key,s.filter(o=>o.key!==t.itemKey))}const d=pe(i,a);return()=>n.setDraft(i.key,a.key,It(d,t.itemKey,null))}function ve(){const{t}=h.useNiceTranslation();return e.jsx("p",{className:"nice-development-studio__muted",children:t("devStudio.edit.gone","This is no longer in the module.")})}function Fi(t){var r,p,m,g,v;const{screen:i,module:n,session:a,preset:d,provider:s,locales:o,advanced:u,readOnlyHere:c}=t,{t:l}=h.useNiceTranslation();if(i.kind==="package")return e.jsx(Ei,{session:a,pkg:i.pkg,readOnly:t.readOnly(),onNewModule:()=>t.onNewModule({workspaceId:i.pkg.workspaceId,packageId:i.pkg.id}),onOpenModule:f=>t.onReveal({kind:"module",module:{workspaceId:i.pkg.workspaceId,id:f}})});if(i.kind==="template"){const f=i.templateId?(r=a.templates)==null?void 0:r.find(j=>j.id===i.templateId):void 0;return e.jsx(Ci,{session:a,template:f,locales:o,extraSchema:d.templateSchema,readOnly:t.readOnly(),onSaved:j=>{j.id!==i.templateId&&t.onScreen({kind:"template",templateId:j.id})},onDeleted:t.onBack},i.templateId??"new")}if(!n)return e.jsx("p",{className:"nice-development-studio__muted",children:l("devStudio.loading","Loading…")});switch(i.kind){case"manifest":{const f=n.documents.find(j=>j.kind.editor==="manifest");return f?e.jsx(gt,{module:n,doc:f,preset:d,session:a,locales:o,readOnly:c,advanced:u,scriptRunner:t.scriptRunner}):e.jsx(ve,{})}case"entity":{const f=me(n,i.docKey),j=f?ne(n,f):void 0,N=Array.isArray(j)?j[i.index]:void 0;return!f||!j||!N?e.jsx(ve,{}):e.jsx(Xe,{value:N,onChange:$=>a.setDraft(n.key,f.key,it(j,i.index,$)),entityMetaSchema:(p=d.entities)==null?void 0:p.entityMetaSchema,fieldSchema:(m=d.entities)==null?void 0:m.fieldSchema,fieldsKey:(g=d.entities)==null?void 0:g.fieldsKey,readOnly:c,"data-testid":"studio-entity-form"})}case"item":return e.jsx($i,{...t,screen:i,module:n});case"document":{const f=me(n,i.docKey);return f?e.jsx(gt,{module:n,doc:f,preset:d,session:a,locales:o,readOnly:c,advanced:u,scriptRunner:t.scriptRunner}):e.jsx(ve,{})}case"panel":{const f=(v=t.modulePanels)==null?void 0:v.call(t,{module:n.key,files:n.working,dirty:n.dirty}).find(j=>j.key===i.panelKey);return f?e.jsx(e.Fragment,{children:f.content}):e.jsx(ve,{})}case"file":return n.working.some(f=>f.path===i.path)?e.jsx(Ii,{module:n,path:i.path,session:a,readOnly:c}):e.jsx(ve,{});case"problems":return e.jsx(Bi,{module:n,issues:t.issues(n.key),onReveal:t.onReveal});case"history":return e.jsx(zi,{module:n,provider:s,session:a,readOnly:c})}}function $i({screen:t,module:i,session:n,readOnlyHere:a,advanced:d,renderViewPreview:s,onScreen:o}){const{t:u}=h.useNiceTranslation(),c=me(i,t.docKey);if(!c)return e.jsx(ve,{});if(t.group==="dataSources"){const v=ne(i,c)??[],f=v.find(j=>j.key===t.itemKey);return f?e.jsx(h.NiceDataSourceBuilder,{value:f,schemas:P.entitiesToSchemas(Je(i)),onChange:j=>{n.setDraft(i.key,c.key,v.map(N=>N.key===f.key?j:N)),j.key!==f.key&&o({...t,itemKey:j.key})}}):e.jsx(ve,{})}const l=pe(i,c),r=l.find(v=>v.key===t.itemKey);if(!r)return e.jsx(ve,{});const p=v=>{n.setDraft(i.key,c.key,It(l,r.key,v)),v.key!==r.key&&o({...t,itemKey:v.key})},m=v=>p({...r,definition:v,label:v.name||r.label,key:v.id&&!l.some(f=>f!==r&&f.key===v.id)?v.id:r.key});if(r.definition===void 0)return d?e.jsxs("div",{className:"nice-development-studio__source",children:[e.jsxs("p",{className:"nice-development-studio__muted",children:[u("devStudio.items.rawReason","The editor does not know this shape, so it is edited as JSON."),r.rawReason?` (${r.rawReason})`:""]}),e.jsx(Ze,{value:r.source,readOnly:a,label:r.label,height:"100%",onChange:v=>p({...r,source:v})})]}):e.jsx("p",{className:"nice-development-studio__muted",children:u("devStudio.preview.noDesigner","There is no designer for this kind of entry yet.")});if(t.group==="workflows")return e.jsx(h.NiceWorkflowDesigner,{workflow:r.definition,onChange:v=>m(v),readOnly:a});const g=e.jsx(h.NiceViewEditor,{value:r.definition,onChange:v=>m(v),entities:Je(i),dataSourceOptions:i.documents.filter(v=>v.kind.editor==="dataSources").flatMap(v=>ne(i,v)??[]).map(v=>({key:v.key,label:v.label})),height:640});return s?e.jsx(h.NiceTabs,{tabs:[{id:"design",label:u("devStudio.view.design","Design"),content:g},{id:"preview",label:u("devStudio.view.hostPreview","Preview in the app"),content:s({module:i.key,item:r,files:i.working})}]}):g}function Bi({module:t,issues:i,onReveal:n}){const{t:a}=h.useNiceTranslation();return i.length===0?e.jsx("p",{className:"nice-development-studio__muted",children:a("devStudio.overview.noProblems","No problems found.")}):e.jsx("ul",{className:"nice-development-studio__issues","data-testid":"studio-problems",children:i.map((d,s)=>e.jsxs("li",{className:`nice-development-studio__issue nice-development-studio__issue--${d.severity}`,children:[e.jsx(h.NiceIcon,{name:d.severity==="error"?"error":d.severity==="warning"?"warning":"info",size:14}),e.jsx("span",{children:Et(a,d)}),d.path&&e.jsx("span",{className:"nice-development-studio__muted",children:d.path}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",onClick:()=>n(Ct(t,d)),children:a("devStudio.problems.goTo","Go to")})]},s))})}function Et(t,i){return i.messageKey?Object.entries(i.params??{}).reduce((n,[a,d])=>n.replace(`{${a}}`,String(d)),t(i.messageKey,i.message)):i.message}function zi({module:t,provider:i,session:n,readOnly:a}){const[d,s]=b.useState(null),o=t.key;return b.useEffect(()=>{let u=!0;return i!=null&&i.listRevisions&&i.listRevisions(o).then(c=>{u&&s(c.map(l=>({id:l.id,label:l.label,author:l.author,timestamp:l.timestamp,summary:l.summary})))}).catch(()=>s([])),()=>{u=!1}},[i,o,t.files]),e.jsx(h.NiceRevisionHistory,{revisions:d??[],language:"json",loadContent:i!=null&&i.readRevision?u=>i.readRevision(o,u):void 0,onRollback:i!=null&&i.rollback&&!a?async u=>{await i.rollback(o,u),await n.reload(o)}:void 0})}function ie({icon:t,title:i,subtitle:n,badges:a,actions:d,children:s}){return e.jsxs("section",{className:"nice-development-studio__preview","data-testid":"studio-preview",children:[e.jsxs("div",{className:"nice-development-studio__preview-info",children:[e.jsxs("header",{className:"nice-development-studio__preview-head",children:[e.jsx(h.NiceIcon,{name:t,size:20}),e.jsxs("div",{className:"nice-development-studio__preview-name",children:[e.jsx("h3",{className:"nice-development-studio__preview-title",children:i}),n&&e.jsx("span",{className:"nice-development-studio__muted",children:n})]})]}),a&&e.jsx("div",{className:"nice-development-studio__preview-badges",children:a}),s]}),d&&e.jsx("footer",{className:"nice-development-studio__preview-actions",children:d})]})}function de({items:t}){const i=t.filter(([,n])=>n!=null&&n!=="");return i.length===0?null:e.jsx("dl",{className:"nice-development-studio__facts",children:i.map(([n,a])=>e.jsxs("div",{className:"nice-development-studio__fact",children:[e.jsx("dt",{children:n}),e.jsx("dd",{children:a})]},n))})}function Ne({rows:t,onSelect:i,limit:n=12}){const{t:a}=h.useNiceTranslation();return t.length===0?null:e.jsxs("ul",{className:"nice-development-studio__preview-list",children:[t.slice(0,n).map(d=>e.jsxs("li",{children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:d.icon,size:14}),onClick:()=>i(d.id),children:d.label}),d.info&&e.jsx("span",{className:"nice-development-studio__muted",children:d.info})]},d.id)),t.length>n&&e.jsx("li",{className:"nice-development-studio__muted",children:a("devStudio.preview.more","…and {count} more").replace("{count}",String(t.length-n))})]})}const Ce=t=>Array.isArray(t)?t.length:void 0;function Di(t){var p,m,g,v;const{row:i,session:n,advanced:a,onEdit:d}=t,{t:s}=h.useNiceTranslation();if(!i)return e.jsx("div",{className:"nice-development-studio__placeholder","data-testid":"studio-preview-empty",children:t.emptyText});const o=i.node,u=o.kind==="package"?Tt(o.workspaceId,n.packagesByWs[o.workspaceId],n.modulesByWs[o.workspaceId]??[]):void 0,c=ki(o,{modules:n.modules,packages:u,advanced:a}),l=c?e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"edit",size:14}),onClick:()=>d(c),"data-testid":"studio-edit","data-tour":"devstudio-edit",children:o.kind==="module"?s("devStudio.preview.editSettings","Edit settings"):s("devStudio.preview.edit","Edit")}):null,r="module"in o?n.modules[ee(o.module)]:void 0;if("module"in o&&!r)return e.jsx(ie,{icon:i.icon,title:i.label,children:e.jsx("p",{className:"nice-development-studio__muted",children:s("devStudio.loading","Loading…")})});switch(o.kind){case"workspace":return e.jsx(Pi,{...t,row:i,workspaceId:o.workspaceId});case"package":return e.jsx(Ri,{...t,row:i,workspaceId:o.workspaceId,packageId:o.packageId,editButton:l});case"module":return e.jsx(Ai,{...t,row:i,module:r,editButton:l});case"group":return e.jsx(Li,{...t,row:i,module:r,group:o.group});case"entity":return e.jsx(Wi,{...t,row:i,module:r,docKey:o.docKey,index:o.index,editButton:l});case"item":return e.jsx(Ji,{...t,row:i,module:r,node:o,editButton:l});case"document":return e.jsx(Gi,{...t,row:i,module:r,docKey:o.docKey,editButton:l});case"panel":return e.jsx(ie,{icon:i.icon,title:i.label,actions:l});case"file":{const f=r.working.find(j=>j.path===o.path);return e.jsx(ie,{icon:"file",title:i.label,actions:l,children:e.jsx(de,{items:[[s("devStudio.preview.size","Size"),f?`${new TextEncoder().encode(f.text).length} B`:void 0],[s("devStudio.preview.state","State"),i.dirty?s("devStudio.explorer.unsaved","Unsaved changes"):void 0]]})})}case"templates":return e.jsx(ie,{icon:"layers",title:i.label,actions:(p=t.provider)!=null&&p.saveTemplate&&!t.readOnly()?e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:t.onNewTemplate,children:s("devStudio.preview.newTemplate","New template")}):void 0,children:e.jsx(Ne,{rows:i.children??[],onSelect:t.onSelect})});case"category":return e.jsx(ie,{icon:"folder",title:i.label,children:e.jsx(Ne,{rows:i.children??[],onSelect:t.onSelect})});case"template":{const f=(m=n.templates)==null?void 0:m.find(N=>N.id===o.templateId),j=(f==null?void 0:f.translations.en)??Object.values((f==null?void 0:f.translations)??{})[0];return e.jsxs(ie,{icon:i.icon,title:i.label,subtitle:f==null?void 0:f.category,actions:l,children:[(j==null?void 0:j.description)&&e.jsx("p",{children:j.description}),e.jsx(de,{items:[["Id",f==null?void 0:f.id],[s("devStudio.preview.modules","Modules"),String((f==null?void 0:f.modules.length)??0)],[s("devStudio.preview.tags","Tags"),(g=f==null?void 0:f.tags)==null?void 0:g.join(", ")]]}),e.jsx(Ne,{rows:i.children??[],onSelect:t.onSelect,limit:8})]})}case"templateModule":{const f=(v=n.templates)==null?void 0:v.find(N=>N.id===o.templateId),j=f==null?void 0:f.modules.find(N=>N.moduleId===o.moduleId);return e.jsxs(ie,{icon:"box",title:i.label,subtitle:o.moduleId,actions:o.target?e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"arrow-right",size:14}),onClick:()=>t.onReveal({kind:"module",module:o.target}),children:s("devStudio.preview.goToModule","Go to the module")}):void 0,children:[e.jsx(de,{items:[[s("devStudio.preview.required","Required"),j!=null&&j.required?s("devStudio.preview.yes","yes"):void 0],[s("devStudio.preview.condition","Condition"),j==null?void 0:j.condition],[s("devStudio.preview.description","Description"),j==null?void 0:j.description]]}),i.missing&&e.jsx("p",{className:"nice-development-studio__error",children:s("devStudio.preview.missingModule","No project has this module.")})]})}}}function Pi({row:t,workspaceId:i,session:n,provider:a,readOnly:d,canCreateModule:s,onSelect:o,onNewModule:u,onNewPackage:c}){var m;const{t:l}=h.useNiceTranslation(),r=n.workspaces.find(g=>g.id===i),p=!d()&&!(r!=null&&r.readOnly);return e.jsxs(ie,{icon:t.icon,title:t.label,badges:r!=null&&r.readOnly?e.jsx("span",{className:"nice-development-studio__tag",children:l("devStudio.explorer.readOnly","Read-only")}):void 0,actions:p&&(s||a!=null&&a.savePackage)?e.jsxs(e.Fragment,{children:[s&&e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"box",size:14}),onClick:()=>u({workspaceId:i}),children:l("devStudio.preview.newModule","New module")}),(a==null?void 0:a.savePackage)&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"archive",size:14}),onClick:()=>c(i),children:l("devStudio.preview.newPackage","New package")})]}):void 0,children:[(r==null?void 0:r.description)&&e.jsx("p",{children:r.description}),e.jsx(de,{items:[[l("devStudio.preview.packages","Packages"),String(((m=t.children)==null?void 0:m.length)??0)],[l("devStudio.preview.modules","Modules"),t.info]]}),e.jsx(Ne,{rows:t.children??[],onSelect:o})]})}function Ri({row:t,workspaceId:i,packageId:n,session:a,readOnly:d,canCreateModule:s,editButton:o,onSelect:u,onNewModule:c}){var g;const{t:l}=h.useNiceTranslation(),r=(g=a.packagesByWs[i])==null?void 0:g.find(v=>v.id===n),p=a.workspaces.find(v=>v.id===i),m=!d()&&!(p!=null&&p.readOnly);return e.jsxs(ie,{icon:t.icon,title:t.label,subtitle:n,actions:e.jsxs(e.Fragment,{children:[o,m&&s&&e.jsx(h.NiceButton,{size:"sm",variant:o?"ghost":"primary",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:()=>c({workspaceId:i,packageId:n}),children:l("devStudio.preview.newModuleHere","New module here")})]}),children:[(r==null?void 0:r.description)&&e.jsx("p",{children:r.description}),e.jsx(Ne,{rows:t.children??[],onSelect:u})]})}function Ai(t){var y;const{row:i,module:n,session:a,preset:d,provider:s,readOnly:o,editButton:u}=t,{t:c}=h.useNiceTranslation(),l=n.key,r=(y=a.modulesByWs[l.workspaceId])==null?void 0:y.find(x=>x.id===l.id),p=o(l),m=t.issues(l),g=(r==null?void 0:r.contents)==="manifest"&&e.jsx("span",{title:c("devStudio.preview.manifestOnly","This provider gives only the manifest"),children:"—"}),v=et(n).length,f=n.documents.filter(x=>x.kind.editor==="views").reduce((x,k)=>x+pe(n,k).length,0),j=new Set(n.documents.filter(x=>x.kind.editor==="i18n").flatMap(x=>Object.keys(ne(n,x)??{}))),N={key:l,files:n.working,documents:n.documents},$=d.newFile?d.kinds.map(x=>{var k;return{kind:x,file:(k=d.newFile)==null?void 0:k.call(d,x.id,N)}}).filter(x=>!!x.file&&!n.working.some(k=>k.path===x.file.path)):[],O=x=>e.jsx(h.NiceIcon,{name:x,size:14}),_=[...s!=null&&s.listRevisions?[{id:"history",icon:O("clock"),label:c("devStudio.overview.history","History"),onClick:()=>t.onEdit({kind:"history",module:l})}]:[],...t.canDuplicateModule&&!o()?[{id:"duplicate",icon:O("copy"),label:c("devStudio.explorer.duplicate","Duplicate"),onClick:()=>t.onModuleAction("duplicate",l)}]:[],...s!=null&&s.saveTemplate&&a.templates&&!o()?[{id:"addToTemplate",icon:O("layers"),label:c("devStudio.explorer.addToTemplate","Add to template"),onClick:()=>t.onModuleAction("addToTemplate",l)}]:[],...p?[]:$.map(({kind:x,file:k})=>({id:`add:${x.id}`,icon:O(x.icon??"plus"),label:`${c("devStudio.preview.add","Add:")} ${x.labelKey?c(x.labelKey,x.label):x.label}`,onClick:()=>a.setRaw(l,k.path,k.text)})),...s!=null&&s.deleteModule&&!p?[{id:"sep",divider:!0},{id:"delete",icon:O("trash"),label:c("devStudio.delete","Delete"),danger:!0,onClick:()=>t.onModuleAction("delete",l)}]:[]];return e.jsxs(ie,{icon:i.icon,title:i.label,subtitle:(r==null?void 0:r.location)??l.id,badges:e.jsxs(e.Fragment,{children:[(r==null?void 0:r.readOnly)&&e.jsx("span",{className:"nice-development-studio__tag",children:c("devStudio.explorer.readOnly","Read-only")}),(r==null?void 0:r.shadowedBy)&&e.jsx("span",{className:"nice-development-studio__tag",title:r.shadowedBy,children:c("devStudio.explorer.shadowed","shadowed")})]}),actions:e.jsxs(e.Fragment,{children:[u,n.dirty&&!p&&e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:O("save"),onClick:()=>t.onSave(l),"data-tour":"devstudio-save",children:c("devStudio.saveCount","Save ({count})").replace("{count}",String(n.changes.length))}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:O("undo"),onClick:()=>a.discard(l),children:c("devStudio.discard","Discard changes")})]}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:O("check"),onClick:()=>void a.validate(l),children:c("devStudio.validate","Validate")}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:O(m.length===0?"success":"warning"),onClick:()=>t.onEdit({kind:"problems",module:l}),children:`${c("devStudio.overview.problems","Problems")} (${m.length})`}),_.length>0&&e.jsx(h.NiceMenu,{className:"nice-development-studio__more",variant:"ghost",size:"sm",fullWidth:!0,items:[{id:"more",icon:O("more-horizontal"),label:c("devStudio.preview.more.actions","More actions"),children:_}]})]}),children:[(r==null?void 0:r.description)&&e.jsx("p",{children:r.description}),e.jsx(de,{items:[["Id",l.id],[c("devStudio.preview.version","Version"),r==null?void 0:r.version],[c("devStudio.preview.entities","Entities"),g||String(v)],[c("devStudio.preview.views","Views"),g||String(f)],[c("devStudio.preview.languages","Languages"),g||[...j].join(", ")],[c("devStudio.preview.state","State"),n.dirty?c("devStudio.status.changed","{count} changed files").replace("{count}",String(n.changes.length)):void 0]]}),m.length>0&&e.jsxs("div",{className:"nice-development-studio__preview-issues",children:[e.jsx("ul",{className:"nice-development-studio__issues",children:m.slice(0,3).map((x,k)=>e.jsx("li",{className:`nice-development-studio__issue nice-development-studio__issue--${x.severity}`,children:e.jsxs("button",{type:"button",className:"nice-development-studio__issue-link",title:c("devStudio.problems.goTo","Go to"),onClick:()=>t.onReveal(Ct(n,x)),children:[e.jsx(h.NiceIcon,{name:x.severity==="error"?"error":x.severity==="warning"?"warning":"info",size:14}),e.jsx("span",{children:Et(c,x)})]})},k))}),m.length>3&&e.jsx("span",{className:"nice-development-studio__muted",children:c("devStudio.preview.more","…and {count} more").replace("{count}",String(m.length-3))})]})]})}function Li({row:t,module:i,group:n,preset:a,session:d,readOnly:s,onSelect:o,onEdit:u}){const{t:c}=h.useNiceTranslation(),r=s(i.key)?void 0:qi(n,i,a,d);return e.jsx(ie,{icon:t.icon,title:t.label,actions:r?e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:()=>u(r.run()),"data-testid":"studio-add",children:r.label(c)}):void 0,children:e.jsx(Ne,{rows:t.children??[],onSelect:o})})}function qi(t,i,n,a){var r,p;const d=t==="entities"?"entities":t==="views"?"views":t==="workflows"?"workflows":t==="dataSources"?"dataSources":void 0,s=d?i.documents.find(m=>m.kind.editor===d&&m.model!==void 0):void 0;if(!s)return;const o=i.key;if(t==="entities"){const m=ne(i,s)??[],g=((r=n.entities)==null?void 0:r.nameKey)??"name",v=((p=n.entities)==null?void 0:p.fieldsKey)??"fields";return{label:f=>f("devStudio.preview.newEntity","New entity"),run:()=>(a.setDraft(o,s.key,[...m,{[g]:`Entity${m.length+1}`,[v]:[]}]),{kind:"entity",module:o,docKey:s.key,index:m.length})}}if(t==="dataSources"){const m=ne(i,s)??[];return{label:g=>g("devStudio.items.addDataSource","New data source"),run:()=>{const g={key:`source${m.length+1}`,kind:"query",query:{tables:[],joins:[],conditions:[],sorts:[],groupBy:[],distinct:!1},sql:""};return a.setDraft(o,s.key,[...m,g]),{kind:"item",module:o,group:"dataSources",docKey:s.key,itemKey:g.key}}}}const u=pe(i,s),c=u.length+1,l=t==="views"?{id:`view-${c}`,name:`View ${c}`,version:2,columns:12,rows:[],dataSources:[]}:{id:`workflow-${c}`,name:`Workflow ${c}`,entityType:"",version:1,states:[],transitions:[]};return{label:m=>t==="views"?m("devStudio.items.addView","New view"):m("devStudio.items.addWorkflow","New workflow"),run:()=>{const m={key:l.id,label:l.name,definition:l,source:l};return a.setDraft(o,s.key,[...u,m]),{kind:"item",module:o,group:t,docKey:s.key,itemKey:l.id}}}}const Vi=[["isPrimaryKey","PK","Primary key"],["isForeignKey","FK","Foreign key"],["isRequired","Req","Required"]];function Wi({row:t,module:i,docKey:n,index:a,preset:d,session:s,readOnly:o,editButton:u,onReveal:c}){var j;const{t:l}=h.useNiceTranslation(),r=me(i,n),p=r?ne(i,r):void 0,m=Array.isArray(p)?p[a]:void 0;if(!r||!p||!m)return e.jsx(ie,{icon:"table",title:t.label,children:e.jsx("p",{className:"nice-development-studio__muted",children:l("devStudio.edit.gone","This is no longer in the module.")})});const g=((j=d.entities)==null?void 0:j.fieldsKey)??"fields",v=Array.isArray(m[g])?m[g]:[],f=o(i.key);return e.jsxs(ie,{icon:"table",title:tt(m)||t.label,subtitle:String(m.name??""),badges:e.jsxs(e.Fragment,{children:[!!m.isAudited&&e.jsx("span",{className:"nice-development-studio__tag",children:l("entityEditor.flag.audited.abbr","Audit")}),!!m.isSoftDeleteEnabled&&e.jsx("span",{className:"nice-development-studio__tag",children:l("entityEditor.flag.softDelete.abbr","Soft-del")})]}),actions:e.jsxs(e.Fragment,{children:[u,!f&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"trash",size:14}),onClick:()=>{s.setDraft(i.key,r.key,it(p,a,null)),c({kind:"group",module:i.key,group:"entities"})},children:l("devStudio.delete","Delete")})]}),children:[typeof m.description=="string"&&m.description&&e.jsx("p",{children:m.description}),e.jsx(de,{items:[[l("entityEditor.col.table","Table"),m.tableName],[l("entityEditor.col.fields","Fields"),String(v.length)]]}),v.length>0&&e.jsx("table",{className:"nice-development-studio__table nice-development-studio__preview-fields",children:e.jsx("tbody",{children:v.slice(0,8).map((N,$)=>e.jsxs("tr",{children:[e.jsx("td",{children:String(N.name??"")}),e.jsx("td",{className:"nice-development-studio__muted",children:String(N.dataType??N.type??"")}),e.jsx("td",{children:Vi.filter(([O])=>N[O]||O==="isRequired"&&N.required).map(([,O,_])=>e.jsx("span",{className:"nice-development-studio__tag",title:_,children:O},O))})]},$))})}),v.length>8&&e.jsx("span",{className:"nice-development-studio__muted",children:l("devStudio.preview.more","…and {count} more").replace("{count}",String(v.length-8))})]})}function Ji({row:t,module:i,node:n,advanced:a,renderViewPreview:d,editButton:s}){var m,g,v,f;const{t:o}=h.useNiceTranslation(),u=me(i,n.docKey),c=u?pe(i,u).find(j=>j.key===n.itemKey):void 0;if(!c)return e.jsx(ie,{icon:t.icon,title:t.label,children:e.jsx("p",{className:"nice-development-studio__muted",children:o("devStudio.edit.gone","This is no longer in the module.")})});const l=c.source??{},r=c.definition??{},p=n.group==="views"?[["Id",c.key],[o("devStudio.preview.type","Type"),l.viewType??l.type??l.kind],[o("devStudio.preview.entity","Entity"),l.entityName??l.entity],[o("devStudio.preview.columns","Columns"),(m=Ce(l.columns))==null?void 0:m.toString()],[o("devStudio.preview.rows","Rows"),(g=Ce(r.rows))==null?void 0:g.toString()]]:n.group==="workflows"?[["Id",c.key],[o("devStudio.preview.states","States"),(v=Ce(r.states??l.states))==null?void 0:v.toString()],[o("devStudio.preview.transitions","Transitions"),(f=Ce(r.transitions??l.transitions))==null?void 0:f.toString()]]:[[o("devStudio.preview.key","Key"),c.key],[o("devStudio.preview.type","Type"),r.kind??void 0]];return e.jsxs(ie,{icon:t.icon,title:c.label||c.key,badges:c.definition===void 0?e.jsx("span",{className:"nice-development-studio__tag",children:o("devStudio.tree.noForm","no designer")}):void 0,actions:s,children:[e.jsx(de,{items:p}),c.definition===void 0&&e.jsx("p",{className:"nice-development-studio__muted",children:a?o("devStudio.preview.noDesignerAdvanced","There is no designer for this kind of entry yet; edit its source."):o("devStudio.preview.noDesigner","There is no designer for this kind of entry yet.")}),n.group==="views"&&d&&e.jsx("div",{className:"nice-development-studio__preview-view",children:d({module:i.key,item:c,files:i.working})})]})}function Gi({row:t,module:i,docKey:n,advanced:a,editButton:d}){var l;const{t:s}=h.useNiceTranslation(),o=me(i,n);if(!o)return e.jsx(ie,{icon:t.icon,title:t.label,children:e.jsx("p",{className:"nice-development-studio__muted",children:s("devStudio.edit.gone","This is no longer in the module.")})});const u=ne(i,o);let c=null;if(o.model===void 0)c=e.jsxs("p",{className:"nice-development-studio__error",role:"alert",children:[a?s("devStudio.doc.unreadable","This file could not be read as its kind; edit its source."):s("devStudio.preview.unreadable","This file does not read; saving leaves it as it is. Fix it in the advanced mode.")," ",o.error]});else if(o.kind.editor==="i18n"){const r=u??{},p=Math.max(0,...Object.values(r).map(m=>Object.keys(m??{}).length));c=e.jsx(de,{items:Object.entries(r).map(([m,g])=>{const v=Object.keys(g??{}).length;return[m,v<p?s("devStudio.preview.keysMissing","{count} keys, {missing} missing").replace("{count}",String(v)).replace("{missing}",String(p-v)):s("devStudio.preview.keys","{count} keys").replace("{count}",String(v))]})})}else if(o.kind.editor==="permissions"){const r=u??{permissions:[],groups:[]};c=e.jsx(de,{items:[[s("devStudio.permissions.codes","Permissions"),String(r.permissions.length)],[s("devStudio.permissions.groups","Groups"),String(r.groups.length)]]})}else if(o.kind.editor==="seeds"){const r=u??{seeds:{}};c=e.jsx(de,{items:Object.entries(r.seeds??{}).map(([p,m])=>[p,s("devStudio.preview.rowsCount","{count} rows").replace("{count}",String(m.length))])})}else o.kind.editor==="hooks"?c=e.jsx(de,{items:[[s("devStudio.preview.bindings","Bindings"),(l=Ce(u))==null?void 0:l.toString()]]}):o.kind.editor==="script"&&(c=e.jsx(de,{items:[[s("devStudio.preview.lines","Lines"),String(String(u??"").split(`
6
- `).length)]]}));return e.jsx(ie,{icon:t.icon,title:t.label,subtitle:o.paths.join(", "),actions:d,children:c})}function Ui({tree:t,selected:i,expanded:n,onExpandedChange:a,onSelect:d,loadModule:s,newItems:o,actions:u,onRefresh:c,tutorialButton:l,emptyText:r,minWidth:p}){const{t:m}=h.useNiceTranslation(),g=b.useMemo(()=>[{field:"label",header:m("devStudio.explorer.name","Name"),render:(f,j)=>e.jsxs("span",{className:"nice-development-studio__tree-name",style:{maxWidth:`calc(100% - ${(j.depth??0)*20+28}px)`},children:[e.jsx(h.NiceIcon,{name:j.icon,size:14}),e.jsx("span",{className:`nice-development-studio__tree-label${j.missing?" nice-development-studio__missing":""}`,title:j.label,children:j.label}),j.dirty&&e.jsx("span",{className:"nice-development-studio__dot",title:m("devStudio.explorer.unsaved","Unsaved changes"),children:e.jsx(h.NiceIcon,{name:"circle",size:8})}),!!j.issues&&e.jsx("span",{className:"nice-development-studio__badge",title:m("devStudio.explorer.problems","Problems"),children:j.issues}),j.readOnly&&e.jsx("span",{title:m("devStudio.explorer.readOnly","Read-only"),children:e.jsx(h.NiceIcon,{name:"lock",size:12})}),j.noForm&&e.jsx("span",{className:"nice-development-studio__tag",children:m("devStudio.tree.noForm","no designer")}),j.shadowedBy&&e.jsx("span",{className:"nice-development-studio__tag",title:j.shadowedBy,children:m("devStudio.explorer.shadowed","shadowed")}),j.missing&&e.jsx("span",{className:"nice-development-studio__tag",children:m("devStudio.explorer.missing","missing")})]})},{field:"info",header:"",width:56,align:"right"}],[m]),v=e.jsxs("div",{className:"nice-development-studio__tree-actions",children:[o.length>0&&e.jsx(h.NiceMenu,{variant:"ghost",size:"sm",items:[{id:"new",label:m("devStudio.tree.new","New"),icon:e.jsx(h.NiceIcon,{name:"plus",size:14}),children:o}],"data-testid":"studio-new-menu"}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",ariaLabel:m("devStudio.refresh","Refresh"),onClick:c,children:e.jsx(h.NiceIcon,{name:"refresh",size:14})}),u==null?void 0:u.map(f=>e.jsx(h.NiceButton,{size:"sm",variant:"ghost",disabled:f.disabled,leftIcon:f.icon?e.jsx(h.NiceIcon,{name:f.icon,size:14}):void 0,onClick:f.onSelect,children:f.label},f.key)),l&&e.jsx("span",{className:"nice-development-studio__spacer"}),l]});return e.jsx("div",{className:"nice-development-studio__tree","data-tour":"devstudio-explorer",style:{minWidth:p},children:e.jsx(h.NiceTreeGrid,{data:t.rows,nested:!0,keyField:"id",childrenField:"children",columns:g,sortable:!1,compact:!0,searchable:!0,searchFields:["label","search"],searchPlaceholder:m("devStudio.tree.search","Search modules, entities and views"),toolbar:v,toolbarActions:["collapseAll"],expandedKeys:n,onExpandedChange:a,hasChildren:f=>f.node.kind==="module"&&!f.children,loadChildren:async f=>(f.node.kind==="module"&&await s(f.node.module),[]),onRowClick:d,rowClassName:f=>f.id===i?"nice-development-studio__tree-row--selected":void 0,emptyText:r,"aria-label":m("devStudio.explorer.modules","Modules"),"data-testid":"studio-tree"})})}const Hi=[{target:".nice-development-studio",titleKey:"tutorial.devStudio.intro.title",title:"Development studio",contentKey:"tutorial.devStudio.intro.content",content:"Design whole modules: their settings, entities, views, workflows, translations, permissions, data sources and seed data. Saving writes back only what changed.",placement:"auto"},{target:'[data-tour="devstudio-explorer"]',titleKey:"tutorial.devStudio.explorer.title",title:"Projects, packages and modules",contentKey:"tutorial.devStudio.explorer.content",content:"Browse projects, their packages and modules. Open a module to see its entities, views, translations and the rest; under Templates are the module sets installed together.",placement:"right"},{target:'[data-testid="studio-preview"]',titleKey:"tutorial.devStudio.preview.title",title:"A short preview",contentKey:"tutorial.devStudio.preview.content",content:"Pick a row in the tree to see a short preview of it here.",placement:"left"},{target:'[data-tour="devstudio-edit"]',titleKey:"tutorial.devStudio.edit.title",title:"Edit on the whole screen",contentKey:"tutorial.devStudio.edit.content",content:"Edit opens the form of what you picked on the whole studio. Back, or a step of the trail, brings you back to the tree.",placement:"bottom"},{target:'[data-tour="devstudio-save"]',titleKey:"tutorial.devStudio.save.title",title:"Validate and save",contentKey:"tutorial.devStudio.save.content",content:"Check the module, review the changed files and save them — only the bytes you changed are written.",placement:"bottom"}],Yi=["en","pl","de","fr","es","uk"],Xi=b.forwardRef(function(i,n){var at,dt;const{provider:a,preset:d,defaultModule:s,defaultExplorerTab:o="modules",displayMode:u="standard",actions:c,onModuleOpen:l,onSaved:r,onError:p,reviewBeforeSave:m=!0,scriptRunner:g,renderViewPreview:v,modulePanels:f,readOnly:j=!1,height:N=720,explorerWidth:$=320,previewWidth:O=260,tutorial:_,className:y,style:x,id:k,testId:M,"data-testid":V}=i,{t:D}=h.useNiceTranslation(),G=b.useRef(null);b.useImperativeHandle(n,()=>G.current);const te=u==="advanced",Q=b.useMemo(()=>typeof d=="function"?d(D):d??P.nativeStudioPreset,[d,D]),H=b.useMemo(()=>Q.locales??Yi,[Q]),C=hi(a,Q,{locales:H,onError:p,t:D}),{openModule:E}=C,[B,L]=b.useState(""),[Z,U]=b.useState([]),[z,Y]=b.useState(null),[le,je]=b.useState(null),[q,w]=b.useState(null),I=b.useCallback(S=>{var K;return(K=C.modulesByWs[S.workspaceId])==null?void 0:K.find(W=>W.id===S.id)},[C.modulesByWs]),T=S=>{var K;return((K=I(S))==null?void 0:K.label)??S.id},F=b.useMemo(()=>{const S={};for(const[K,W]of Object.entries(C.modules))S[K]=[...wt(W,Q),...C.serverIssues[K]??[]];return S},[C.modules,C.serverIssues,Q]),R=b.useCallback(S=>F[ee(S)]??[],[F]),J=b.useMemo(()=>Object.fromEntries(Object.entries(F).map(([S,K])=>[S,K.filter(W=>W.severity==="error").length])),[F]),X=b.useCallback(S=>{var W;if(j)return!0;if(!S)return!1;const K=C.workspaces.find(ge=>ge.id===S.workspaceId);return!!(K!=null&&K.readOnly)||!!((W=I(S))!=null&&W.readOnly)},[j,C.workspaces,I]),A=b.useMemo(()=>xi({workspaces:C.workspaces,modulesByWs:C.modulesByWs,packagesByWs:C.packagesByWs,templates:C.templates,modules:C.modules,issueCounts:J,panels:f?S=>f({module:S.key,files:S.working,dirty:S.dirty}):void 0,advanced:te,t:D}),[C.workspaces,C.modulesByWs,C.packagesByWs,C.templates,C.modules,J,f,te,D]),oe=b.useRef(!1);b.useEffect(()=>{if(!oe.current&&C.workspaces.length>0){oe.current=!0;const S=C.workspaces.map(K=>`w:${K.id}`);o==="templates"&&(S.push(Oe),L(Oe)),U(K=>[...new Set([...K,...S])])}},[C.workspaces,o]);const re=b.useCallback(S=>{const K=vt(A,S).map(W=>W.id);U(W=>[...new Set([...W,...K])]),L(S)},[A]),ce=b.useCallback(S=>{Y(null);const K=Ke(S);K&&!C.modules[ee(K)]&&E(K),je(S)},[C.modules,E]);b.useEffect(()=>{if(!le)return;const S=We(A,le);if(S){re(S),je(null);return}const K=Ke(le);if(K&&C.modules[ee(K)]){const W=We(A,{kind:"module",module:K});W&&re(W),je(null)}},[le,A,re,C.modules]);const se=b.useCallback(S=>{L(S.id);const K=Ke(S.node);K&&!C.modules[ee(K)]&&E(K),S.node.kind==="module"&&(l==null||l(S.node.module))},[C.modules,E,l]),Fe=b.useCallback(S=>{const K=A.byId.get(S);K&&(se(K),re(S))},[A,se,re]),fe=b.useRef(!1);b.useEffect(()=>{s&&!fe.current&&C.modulesByWs[s.workspaceId]&&(fe.current=!0,E(s).then(()=>l==null?void 0:l(s)),je({kind:"module",module:s}))},[s,C.modulesByWs,E,l]);const he=A.byId.get(B),ue=z?"module"in z?z.module:void 0:he?Ke(he.node):void 0,$e=b.useCallback(async S=>{const K=C.modules[ee(S)];if(!(K!=null&&K.dirty)||X(S))return;if(m){w({kind:"review",module:S});return}const W=await C.save(S);W&&!W.ok?w({kind:"review",module:S,conflict:W}):W!=null&&W.ok&&(r==null||r(S,W))},[C,X,m,r]),nt=b.useRef(()=>{});nt.current=()=>{ue&&$e(ue)},b.useEffect(()=>{const S=G.current;if(!S)return;const K=W=>{(W.ctrlKey||W.metaKey)&&!W.altKey&&W.key.toLowerCase()==="s"&&(W.preventDefault(),nt.current())};return S.addEventListener("keydown",K),()=>S.removeEventListener("keydown",K)},[]);const Mt=()=>{const S=z?ft(z):void 0;S?ce(S):Y(null)},Kt=b.useMemo(()=>{if(!z)return[];const S=ft(z),K=S?We(A,S):void 0,W=K?vt(A,K):[],ge=z.kind==="manifest"?D("devStudio.edit.settings","Settings"):z.kind==="problems"?D("devStudio.overview.problems","Problems"):z.kind==="history"?D("devStudio.overview.history","History"):z.kind==="template"&&!z.templateId?D("devStudio.template.new","New template"):void 0,ye=W.map(rt=>({label:rt.label,onClick:()=>{Y(null),re(rt.id)}}));return ge?ye.push({label:ge}):ye.length>0&&(ye[ye.length-1]={label:ye[ye.length-1].label}),ye},[z,A,re,D]),st=!!(a!=null&&a.createModule)&&!!Q.generateModule,Ot=!!(a!=null&&a.createModule)&&!!Q.duplicateModule,Ie=C.workspaces.filter(S=>!S.readOnly).map(S=>({id:S.id,label:S.label})),ae=he==null?void 0:he.node,Be=ae&&"workspaceId"in ae?ae.workspaceId:ae&&"module"in ae?ae.module.workspaceId:void 0,Ft=(ae==null?void 0:ae.kind)==="package"?ae.packageId:ae&&"module"in ae?(at=I(ae.module))==null?void 0:at.packageId:void 0,Te=Ie.some(S=>S.id===Be)?Be:(dt=Ie[0])==null?void 0:dt.id,$t=j?[]:[...st&&Te?[{id:"module",label:D("devStudio.tree.newModule","Module…"),icon:e.jsx(h.NiceIcon,{name:"box",size:14}),onClick:()=>w({kind:"wizard",prefill:{workspaceId:Te,packageId:Te===Be?Ft:void 0}})}]:[],...a!=null&&a.savePackage&&Te?[{id:"package",label:D("devStudio.tree.newPackage","Package…"),icon:e.jsx(h.NiceIcon,{name:"archive",size:14}),onClick:()=>w({kind:"package",workspaceId:Te})}]:[],...a!=null&&a.saveTemplate&&C.templates?[{id:"template",label:D("devStudio.tree.newTemplate","Template"),icon:e.jsx(h.NiceIcon,{name:"layers",size:14}),onClick:()=>Y({kind:"template",templateId:null})}]:[]],Bt=(S,K)=>{w(S==="delete"?{kind:"delete",module:K}:S==="duplicate"?{kind:"duplicate",module:K}:{kind:"templates",module:K})},ot=_?e.jsx(h.NiceTutorialButton,{steps:h.resolveTutorial(_,Hi)}):void 0,Ee=ue?C.modules[ee(ue)]:void 0,ze=ue?R(ue):[],De=C.logs[C.logs.length-1],zt=e.jsxs("div",{className:"nice-development-studio__statusbar",role:"status",children:[ue&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:T(ue)}),e.jsx("span",{children:Ee!=null&&Ee.dirty?D("devStudio.status.changed","{count} changed files").replace("{count}",String(Ee.changes.length)):D("devStudio.status.saved","Saved")}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:ze.length===0?"check":"warning",size:12}),onClick:()=>Y({kind:"problems",module:ue}),children:ze.length===0?D("devStudio.status.valid","No problems"):D("devStudio.status.problems","{count} problems").replace("{count}",String(ze.length))})]}),e.jsx("span",{className:"nice-development-studio__spacer"}),C.busy?e.jsx("span",{children:D("devStudio.loading","Loading…")}):De&&e.jsx("span",{className:`nice-development-studio__status-message nice-development-studio__status-message--${De.level}`,children:De.message})]}),Pe=(q==null?void 0:q.kind)==="review"?C.modules[ee(q.module)]:void 0,Dt=`nice-development-studio${y?` ${y}`:""}`,Pt=a?D("devStudio.preview.empty","Pick a module, an entity or a view in the tree."):D("devStudio.noProvider","Connect a provider to browse modules.");return e.jsxs("div",{ref:G,id:k,className:Dt,style:{height:N,...x},"data-testid":V??M,children:[e.jsx(h.NiceAppShell,{className:"nice-development-studio__shell",height:"100%",rightSidebar:z?void 0:e.jsx(Di,{row:he,tree:A,session:C,preset:Q,provider:a,readOnly:X,advanced:te,issues:R,canCreateModule:st,canDuplicateModule:Ot,renderViewPreview:v,emptyText:Pt,onSelect:Fe,onEdit:Y,onReveal:ce,onSave:S=>void $e(S),onNewModule:S=>w({kind:"wizard",prefill:S}),onNewPackage:S=>w({kind:"package",workspaceId:S}),onNewTemplate:()=>Y({kind:"template",templateId:null}),onModuleAction:Bt}),rightSidebarWidth:O,statusBar:zt,bottomPanel:te?e.jsx("div",{"data-tour":"devstudio-output",className:"nice-development-studio__output",children:e.jsx(h.NiceLogConsole,{title:D("devStudio.output","Output"),entries:C.logs,onClear:C.clearLogs,maxHeight:"100%"})}):void 0,bottomPanelHeight:te?140:void 0,children:z?e.jsx(Ki,{screen:z,crumbs:Kt,session:C,preset:Q,provider:a,locales:H,readOnly:X,advanced:te,issues:R,scriptRunner:g,renderViewPreview:v,modulePanels:f,tutorialButton:ot,onBack:Mt,onSave:S=>void $e(S),onReveal:ce,onScreen:Y,onNewModule:S=>w({kind:"wizard",prefill:S})}):e.jsx(Ui,{tree:A,selected:B,expanded:Z,onExpandedChange:U,onSelect:se,loadModule:async S=>{await E(S)},newItems:$t,actions:c,onRefresh:()=>void C.refresh(),tutorialButton:ot,minWidth:$,emptyText:a?D("devStudio.explorer.empty","No modules."):D("devStudio.noProvider","Connect a provider to browse modules.")})}),(q==null?void 0:q.kind)==="wizard"&&e.jsx(ri,{open:!0,onClose:()=>w(null),session:C,preset:Q,locales:H,prefill:q.prefill,onCreated:S=>{l==null||l(S),ce({kind:"module",module:S})}}),(q==null?void 0:q.kind)==="review"&&Pe&&e.jsx(li,{open:!0,moduleLabel:T(q.module),changes:Pe.changes,original:S=>{var K;return((K=Pe.files.find(W=>W.path===S))==null?void 0:K.text)??""},conflict:q.conflict,onClose:()=>w(null),onSave:async()=>{const S=await C.save(q.module);S!=null&&S.ok?(w(null),r==null||r(q.module,S)):S&&w({...q,conflict:S})},onOverwrite:async()=>{const S=await C.save(q.module,{force:!0});S!=null&&S.ok&&(w(null),r==null||r(q.module,S))},onReload:async()=>{await C.reload(q.module),w(null)}}),(q==null?void 0:q.kind)==="delete"&&e.jsx(h.NiceConfirmDialog,{visible:!0,variant:"warning",header:D("devStudio.delete.title","Delete module"),message:D("devStudio.delete.message","Delete {module} and all its files?").replace("{module}",T(q.module)),acceptLabel:D("devStudio.delete","Delete"),rejectLabel:D("devStudio.cancel","Cancel"),onReject:()=>w(null),onAccept:async()=>{const S=q.module;w(null),await C.deleteModule(S)&&(Y(null),L(`w:${S.workspaceId}`))}}),(q==null?void 0:q.kind)==="duplicate"&&e.jsx(mt,{open:!0,title:D("devStudio.duplicate.title","Duplicate {module}").replace("{module}",T(q.module)),workspaces:Ie,workspaceId:Ie.some(S=>S.id===q.module.workspaceId)?q.module.workspaceId:void 0,idLabel:D("devStudio.duplicate.id","New module id"),initialId:`${q.module.id}Copy`,onClose:()=>w(null),onSubmit:async S=>{var ge;const K=q.module;w(null);const W=await C.duplicateModule(K,{workspaceId:S.workspaceId,id:S.id,packageId:(ge=I(K))==null?void 0:ge.packageId});W&&ce({kind:"module",module:{workspaceId:W.workspaceId,id:W.id}})}}),(q==null?void 0:q.kind)==="package"&&e.jsx(mt,{open:!0,title:D("devStudio.package.new","New package"),workspaces:Ie,workspaceId:q.workspaceId,idLabel:D("devStudio.package.id","Id"),withLabel:!0,onClose:()=>w(null),onSubmit:async S=>{w(null);const K=await C.savePackage({id:S.id,workspaceId:S.workspaceId,label:S.label});K&&ce({kind:"package",workspaceId:K.workspaceId,packageId:K.id})}}),(q==null?void 0:q.kind)==="templates"&&C.templates&&e.jsx(ci,{open:!0,moduleId:q.module.id,templates:C.templates,onClose:()=>w(null),onApply:async S=>{w(null);for(const K of S)await C.saveTemplate(K,K.id)}})]})});exports.arrayFileKind=P.arrayFileKind;exports.buildDocuments=P.buildDocuments;exports.createMemoryStudioProvider=P.createMemoryStudioProvider;exports.defineManifestSection=P.defineManifestSection;exports.deriveDefaultRbac=P.deriveDefaultRbac;exports.detectJsonTextFormat=P.detectJsonTextFormat;exports.encodeDocument=P.encodeDocument;exports.endsWithAny=P.endsWithAny;exports.entitiesToSchemas=P.entitiesToSchemas;exports.fileName=P.fileName;exports.fitManifestSection=P.fitManifestSection;exports.i18nFileKind=P.i18nFileKind;exports.itemsFileKind=P.itemsFileKind;exports.jsonFallbackKind=P.jsonFallbackKind;exports.jsonFileKind=P.jsonFileKind;exports.jsonValueFitsSchema=P.jsonValueFitsSchema;exports.jsonValuesEqual=P.jsonValuesEqual;exports.keepTextFormat=P.keepTextFormat;exports.manifestSectionKeys=P.manifestSectionKeys;exports.modulePrefix=P.modulePrefix;exports.nativeDataSourcesKind=P.nativeDataSourcesKind;exports.nativeEntitiesKind=P.nativeEntitiesKind;exports.nativeFileKinds=P.nativeFileKinds;exports.nativeHooksKind=P.nativeHooksKind;exports.nativeI18nKind=P.nativeI18nKind;exports.nativeManifestKind=P.nativeManifestKind;exports.nativeRbacKind=P.nativeRbacKind;exports.nativeStudioPreset=P.nativeStudioPreset;exports.nativeViewsKind=P.nativeViewsKind;exports.nativeWorkflowsKind=P.nativeWorkflowsKind;exports.objectFileKind=P.objectFileKind;exports.parseJsonText=P.parseJsonText;exports.patchJsonText=P.patchJsonText;exports.patchJsonTextDetailed=P.patchJsonTextDetailed;exports.readTranslations=P.readTranslations;exports.resolveFileKind=P.resolveFileKind;exports.safeJson=P.safeJson;exports.slugifyModuleId=P.slugifyModuleId;exports.stringifyJsonText=P.stringifyJsonText;exports.textFallbackKind=P.textFallbackKind;exports.writeTranslations=P.writeTranslations;exports.NiceArrayField=Ye;exports.NiceDevelopmentStudio=Xi;exports.NiceEntityEditor=jt;exports.NiceEntityForm=Xe;exports.NiceI18nEditor=Qe;exports.NiceSchemaForm=_e;exports.aiFormConfigToFormFields=Vt;exports.aiFormFieldType=xt;exports.formBuilderSchemaToNiceFormItems=Rt;exports.formFieldsToFormItems=Ue;exports.formSchemaToJsonSchema=Ut;exports.jsonSchemaToFormItems=Ge;exports.schemaToFormItems=At;exports.validateAgainstJsonSchema=He;exports.validateFormSchema=Lt;
5
+ `]},o))})}function li({open:t,onClose:i,session:n,preset:a,locales:d,prefill:s,onCreated:o}){var O,_,y,x;const{t:u}=h.useNiceTranslation(),c=n.workspaces.filter(k=>!k.readOnly),l=a.requiredLocales??[],[r,p]=b.useState(()=>{var k;return{workspaceId:s.workspaceId&&c.some(M=>M.id===s.workspaceId)?s.workspaceId:((k=c[0])==null?void 0:k.id)??"",packageId:s.packageId,name:"",entities:[{name:"Item",fields:[{name:"Id",dataType:"Guid",isPrimaryKey:!0,isRequired:!0},{name:"Name",dataType:"string",isRequired:!0,maxLength:200}]}],locales:[...new Set([...l,...d.slice(0,2)])],views:!0,permissions:!0}}),[m,g]=b.useState(null),[v,f]=b.useState(!1),j=b.useMemo(()=>[...new Set((n.modulesByWs[r.workspaceId]??[]).map(k=>k.packageId).filter(Boolean))].sort(),[n.modulesByWs,r.workspaceId]);if(!t)return null;const N=new Set(Object.values(n.modulesByWs).flatMap(k=>k.map(M=>M.id))),$=async()=>{a.generateModule&&r.name.trim()&&g(await a.generateModule({...r,name:r.name.trim()},{existingIds:N}))};return e.jsx(h.NiceModal,{open:t,onClose:i,title:u("devStudio.wizard.title","New module"),size:"xl","data-testid":"studio-module-wizard",children:e.jsx(h.NiceWizard,{finishLabel:u("devStudio.wizard.create","Create module"),onCancel:i,onStepChange:k=>{k===3&&$()},onComplete:async()=>{if(v)return;f(!0);const k=await n.createModule({...r,name:r.name.trim()});f(!1),k&&(o({workspaceId:k.workspaceId,id:k.id}),i())},steps:[{id:"identity",title:u("devStudio.wizard.identity","Name and place"),validate:()=>r.name.trim()&&r.workspaceId?!0:u("devStudio.wizard.needName","Give the module a name."),content:e.jsxs("div",{className:"nice-development-studio__form",children:[e.jsx(h.NiceSelect,{label:u("devStudio.wizard.workspace","Project"),value:r.workspaceId,options:c.map(k=>({value:k.id,label:k.label})),onChange:k=>p({...r,workspaceId:String(k)})}),e.jsx(h.NiceTextInput,{label:u("devStudio.wizard.package","Package"),value:r.packageId??"",placeholder:j.join(", "),onChange:k=>p({...r,packageId:k||void 0})}),e.jsx(h.NiceTextInput,{label:u("devStudio.wizard.name","Name"),value:r.name,placeholder:u("devStudio.wizard.namePlaceholder","e.g. Bike rental"),onChange:k=>p({...r,name:k})}),e.jsx(h.NiceTextInput,{label:u("devStudio.wizard.description","Description"),value:r.description??"",onChange:k=>p({...r,description:k||void 0})})]})},{id:"entities",title:u("devStudio.wizard.entities","Entities"),content:e.jsx(jt,{value:r.entities,onChange:k=>p({...r,entities:k}),entityMetaSchema:(O=a.entities)==null?void 0:O.entityMetaSchema,fieldSchema:(_=a.entities)==null?void 0:_.fieldSchema,fieldsKey:(y=a.entities)==null?void 0:y.fieldsKey,nameKey:(x=a.entities)==null?void 0:x.nameKey})},{id:"options",title:u("devStudio.wizard.options","Options"),content:e.jsxs("div",{className:"nice-development-studio__form",children:[e.jsxs("fieldset",{className:"nice-development-studio__fieldset",children:[e.jsx("legend",{children:u("devStudio.wizard.locales","Languages")}),[...new Set([...l,...d])].map(k=>e.jsx(h.NiceCheckbox,{label:k,checked:r.locales.includes(k),disabled:l.includes(k),onChange:M=>p({...r,locales:M?[...r.locales,k]:r.locales.filter(V=>V!==k)})},k))]}),e.jsx(h.NiceCheckbox,{label:u("devStudio.wizard.views","A list and a form view per entity"),checked:!!r.views,onChange:k=>p({...r,views:k})}),e.jsx(h.NiceCheckbox,{label:u("devStudio.wizard.permissions","Viewer, editor and admin permissions"),checked:!!r.permissions,onChange:k=>p({...r,permissions:k})})]})},{id:"review",title:u("devStudio.wizard.review","Review"),content:m?e.jsxs("div",{children:[e.jsx("p",{children:u("devStudio.wizard.willCreate","Module {id} with these files:").replace("{id}",m.id)}),e.jsx("ul",{className:"nice-development-studio__list",children:m.files.map(k=>e.jsxs("li",{children:[e.jsx(h.NiceIcon,{name:"file",size:12})," ",k.path]},k.path))})]}):e.jsx("p",{className:"nice-development-studio__muted",children:u("devStudio.wizard.generating","Generating…")})}]})})}function ci({open:t,moduleLabel:i,changes:n,original:a,conflict:d,onSave:s,onOverwrite:o,onReload:u,onClose:c}){const{t:l}=h.useNiceTranslation();return t?e.jsxs(h.NiceModal,{open:t,onClose:c,size:"xl",title:l("devStudio.review.title","Save {module}").replace("{module}",i),"data-testid":"studio-review",footer:d?e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{variant:"ghost",onClick:c,children:l("devStudio.cancel","Cancel")}),e.jsx(h.NiceButton,{variant:"secondary",onClick:u,children:l("devStudio.review.reload","Reload theirs (drop mine)")}),e.jsx(h.NiceButton,{variant:"danger",onClick:o,children:l("devStudio.review.overwrite","Overwrite with mine")})]}):e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{variant:"ghost",onClick:c,children:l("devStudio.cancel","Cancel")}),e.jsx(h.NiceButton,{variant:"primary",onClick:s,children:l("devStudio.review.save","Save {count} files").replace("{count}",String(n.length))})]}),children:[d&&e.jsxs("p",{className:"nice-development-studio__error",role:"alert",children:[l("devStudio.review.conflict","These files changed since you opened them:")," ",d.conflicts.map(r=>r.path).join(", ")]}),n.map(r=>e.jsxs("section",{className:"nice-development-studio__source",children:[e.jsx("h4",{className:"nice-development-studio__source-title",children:r.type==="delete"?l("devStudio.change.delete","Delete {path}").replace("{path}",r.path):r.baseVersion===void 0&&!a(r.path)?l("devStudio.change.new","New file {path}").replace("{path}",r.path):r.path}),e.jsx(St,{before:a(r.path),after:r.type==="write"?r.text:""})]},r.path))]}):null}function ui({open:t,moduleId:i,templates:n,onApply:a,onClose:d}){const{t:s}=h.useNiceTranslation(),o=b.useMemo(()=>n.filter(p=>p.modules.some(m=>m.moduleId===i)).map(p=>p.id),[n,i]),[u,c]=b.useState(o);if(!t)return null;const l=n.map(p=>{var m,g;return{id:p.id,label:((m=p.translations.en)==null?void 0:m.name)??((g=Object.values(p.translations)[0])==null?void 0:g.name)??p.id}}),r=[{field:"label",header:s("devStudio.explorer.name","Name")}];return e.jsx(h.NiceModal,{open:t,onClose:d,title:s("devStudio.picker.title","Templates with {module}").replace("{module}",i),"data-testid":"studio-template-picker",footer:e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{variant:"ghost",onClick:d,children:s("devStudio.cancel","Cancel")}),e.jsx(h.NiceButton,{variant:"primary",onClick:()=>{const p=n.filter(m=>u.includes(m.id)!==o.includes(m.id)).map(m=>({...m,modules:u.includes(m.id)?[...m.modules,{moduleId:i}]:m.modules.filter(g=>g.moduleId!==i)}));a(p)},children:s("devStudio.apply","Apply")})]}),children:e.jsx(h.NiceTreeGrid,{data:l,columns:r,keyField:"id",sortable:!1,compact:!0,checkable:!0,checkedKeys:u,onCheckedChange:c,searchable:!0,"aria-label":s("devStudio.explorer.templates","Templates")})})}function mt({open:t,title:i,workspaces:n,workspaceId:a,idLabel:d,initialId:s="",withLabel:o,onSubmit:u,onClose:c}){var j;const{t:l}=h.useNiceTranslation(),[r,p]=b.useState(a??((j=n[0])==null?void 0:j.id)??""),[m,g]=b.useState(s),[v,f]=b.useState("");return t?e.jsx(h.NiceModal,{open:t,onClose:c,title:i,footer:e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{variant:"ghost",onClick:c,children:l("devStudio.cancel","Cancel")}),e.jsx(h.NiceButton,{variant:"primary",disabled:!m.trim()||!r,onClick:()=>u({workspaceId:r,id:m.trim(),label:v.trim()||m.trim()}),children:l("devStudio.ok","OK")})]}),children:e.jsxs("div",{className:"nice-development-studio__form",children:[e.jsx(h.NiceSelect,{label:l("devStudio.wizard.workspace","Project"),value:r,options:n.map(N=>({value:N.id,label:N.label})),onChange:N=>p(String(N))}),e.jsx(h.NiceTextInput,{label:d,value:m,onChange:g}),o&&e.jsx(h.NiceTextInput,{label:l("devStudio.package.label","Name"),value:v,onChange:f})]})}):null}const pt=t=>JSON.stringify(t??null,null,2);function Ze({value:t,onChange:i,readOnly:n,height:a=320,label:d}){const{t:s}=h.useNiceTranslation(),[o,u]=b.useState(()=>pt(t)),[c,l]=b.useState(null),r=b.useRef(t);return b.useEffect(()=>{r.current!==t&&(r.current=t,u(pt(t)),l(null))},[t]),e.jsxs("div",{className:"nice-development-studio__json",role:"group","aria-label":d,children:[e.jsx(h.NiceSimpleCodeEditor,{value:o,language:"json",height:a,readOnly:n,lineNumbers:!0,onChange:p=>{u(p);try{const m=JSON.parse(p);l(null),r.current=m,i==null||i(m)}catch(m){l(m instanceof Error?m.message:String(m))}}}),c&&e.jsxs("p",{className:"nice-development-studio__error",role:"alert",children:[s("devStudio.json.invalid","Not valid JSON:")," ",c]})]})}const mi=[{target:".nice-i18n-editor",titleKey:"tutorial.i18nEditor.intro.title",title:"Translations",contentKey:"tutorial.i18nEditor.intro.content",content:"Edit translations as a keys × locales grid. Add keys and locales; amber cells mark missing translations.",placement:"auto"},{target:'[data-tour="i18n-grid"]',titleKey:"tutorial.i18nEditor.grid.title",title:"Keys × locales",contentKey:"tutorial.i18nEditor.grid.content",content:"Each row is a translation key and each column a locale. Edit a cell to set a translation; amber cells are still missing.",placement:"top"},{target:'[data-tour="i18n-add"]',titleKey:"tutorial.i18nEditor.add.title",title:"Add keys & locales",contentKey:"tutorial.i18nEditor.add.content",content:"Add a new translation key or a new locale column here; new cells start empty and are flagged as missing.",placement:"top"}],Qe=b.forwardRef(function(i,n){const{value:a,defaultValue:d,onChange:s,locales:o,allowEditLocales:u=!0,allowEditKeys:c=!0,highlightMissing:l=!0,readOnly:r=!1,tutorial:p,className:m,style:g,id:v,"data-testid":f}=i,{t:j}=ke.useNiceTranslation(),[N,$]=ke.useControllableState({value:a,defaultValue:d,fallbackValue:{},onChange:s,componentName:"NiceI18nEditor"}),[O,_]=b.useState(""),[y,x]=b.useState(""),k=b.useMemo(()=>o??Object.keys(N),[o,N]),M=b.useMemo(()=>{const E=new Set;for(const B of Object.keys(N))for(const L of Object.keys(N[B]??{}))E.add(L);return[...E].sort()},[N]),V=(E,B,L)=>{$({...N,[E]:{...N[E]??{},[B]:L}})},D=(E,B)=>{if(!B||B===E)return;const L={};for(const Z of Object.keys(N)){const U={...N[Z]??{}};E in U&&(U[B]=U[E],delete U[E]),L[Z]=U}$(L)},G=E=>{const B={};for(const L of Object.keys(N)){const Z={...N[L]??{}};delete Z[E],B[L]=Z}$(B)},te=()=>{const E=O.trim();if(!E||M.includes(E))return;const B={};for(const L of k)B[L]={...N[L]??{},[E]:""};for(const L of Object.keys(N))B[L]||(B[L]=N[L]);$(B),_("")},Q=()=>{const E=y.trim();if(!E||N[E])return;const B={};for(const L of M)B[L]="";$({...N,[E]:B}),x("")},H=E=>{const B={...N};delete B[E],$(B)},C="nice-i18n-editor"+(m?` ${m}`:"");return e.jsxs("div",{ref:n,id:v,className:C,style:g,"data-testid":f,children:[p&&e.jsx("div",{className:"nice-i18n-editor__tutorial",children:e.jsx(ke.NiceTutorialButton,{steps:ke.resolveTutorial(p,mi)})}),e.jsx("div",{className:"nice-i18n-editor__scroll","data-tour":"i18n-grid",children:e.jsxs("table",{className:"nice-i18n-editor__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{className:"nice-i18n-editor__key-head",children:j("i18nEditor.keyHead","Key")}),k.map(E=>e.jsxs("th",{className:"nice-i18n-editor__locale-head",children:[e.jsx("span",{children:E}),u&&!r&&e.jsx("button",{type:"button",className:"nice-i18n-editor__locale-remove","aria-label":`${j("i18nEditor.removeLocale","Remove locale")} ${E}`,onClick:()=>H(E),children:e.jsx(ke.NiceIcon,{name:"close",size:12})})]},E))]})}),e.jsxs("tbody",{children:[M.map(E=>e.jsxs("tr",{children:[e.jsxs("td",{className:"nice-i18n-editor__key-cell",children:[c&&!r?e.jsx("input",{className:"nice-i18n-editor__key-input",defaultValue:E,onBlur:B=>D(E,B.target.value.trim()),"aria-label":j("i18nEditor.keyAria","Translation key")}):e.jsx("span",{className:"nice-i18n-editor__key-text",children:E}),c&&!r&&e.jsx("button",{type:"button",className:"nice-i18n-editor__key-remove","aria-label":`${j("i18nEditor.removeKey","Remove key")} ${E}`,onClick:()=>G(E),children:e.jsx(ke.NiceIcon,{name:"close",size:12})})]}),k.map(B=>{var U;const L=((U=N[B])==null?void 0:U[E])??"",Z=l&&L==="";return e.jsx("td",{className:"nice-i18n-editor__cell",children:e.jsx("input",{className:"nice-i18n-editor__cell-input"+(Z?" nice-i18n-editor__cell-input--missing":""),value:L,readOnly:r,onChange:z=>V(B,E,z.target.value),"aria-label":`${E} (${B})`})},B)})]},E)),M.length===0&&e.jsx("tr",{children:e.jsx("td",{className:"nice-i18n-editor__empty",colSpan:k.length+1,children:j("i18nEditor.empty","No translation keys yet.")})})]})]})}),!r&&(c||u)&&e.jsxs("div",{className:"nice-i18n-editor__toolbar","data-tour":"i18n-add",children:[c&&e.jsxs("div",{className:"nice-i18n-editor__add",children:[e.jsx("input",{className:"nice-i18n-editor__add-input",placeholder:j("i18nEditor.newKeyPlaceholder","new.key"),value:O,onChange:E=>_(E.target.value),onKeyDown:E=>{E.key==="Enter"&&te()},"aria-label":j("i18nEditor.newKeyAria","New key")}),e.jsxs("button",{type:"button",onClick:te,children:["+ ",j("i18nEditor.addKey","Key")]})]}),u&&e.jsxs("div",{className:"nice-i18n-editor__add",children:[e.jsx("input",{className:"nice-i18n-editor__add-input",placeholder:j("i18nEditor.newLocalePlaceholder","locale (e.g. de)"),value:y,onChange:E=>x(E.target.value),onKeyDown:E=>{E.key==="Enter"&&Q()},"aria-label":j("i18nEditor.newLocaleAria","New locale")}),e.jsxs("button",{type:"button",onClick:Q,children:["+ ",j("i18nEditor.addLocale","Locale")]})]})]})]})}),ee=t=>`${t.workspaceId}/${t.id}`;function Ve(t,i,n){const a=new Set(t.deleted),d=new Map;for(const m of t.files)a.has(m.path)||d.set(m.path,t.raw[m.path]!==void 0?{...m,text:t.raw[m.path]}:m);for(const[m,g]of Object.entries(t.raw))!d.has(m)&&!a.has(m)&&d.set(m,{path:m,text:g});const s=[...d.values()],o={moduleId:t.key.id,files:s,locales:n},u=P.buildDocuments(i.kinds,s,o),c=new Map(s.map(m=>[m.path,m.text])),l={};for(const m of u)if(m.key in t.drafts)try{const g=m.kind.encode(t.drafts[m.key],s.filter(v=>m.paths.includes(v.path)),o);for(const v of g.files)c.set(v.path,v.text),a.delete(v.path);for(const v of g.deleted??[])c.delete(v),a.add(v)}catch(g){l[m.key]=g instanceof Error?g.message:String(g)}const r=new Map(t.files.map(m=>[m.path,m])),p=[];for(const[m,g]of c){const v=r.get(m);(!v||v.text!==g)&&p.push({type:"write",path:m,text:g,baseVersion:v==null?void 0:v.version})}for(const m of a){const g=r.get(m);g&&p.push({type:"delete",path:m,baseVersion:g.version})}return{...t,working:s,documents:u,changes:p,pending:c,encodeErrors:l,dirty:p.length>0}}function wt(t,i){const n=[];for(const a of t.documents){if(a.error&&n.push({severity:"error",code:"file.unreadable",message:`${a.paths[0]} cannot be read: ${a.error}`,messageKey:"devStudio.issue.unreadable",params:{path:a.paths[0]},moduleId:t.key.id,path:a.paths[0]}),a.kind.editor!=="manifest"||!i.manifestSections)continue;const d=t.drafts[a.key]??a.model??{};for(const s of i.manifestSections){const{section:o}=P.fitManifestSection(s,d);if(o.schema)for(const u of He(d,o.schema))n.push({severity:"error",code:"manifest.schema",message:`${o.title}: ${u.field} — ${u.message}`,moduleId:t.key.id,path:a.paths[0],pointer:`/${u.field.replace(/\./g,"/")}`})}}for(const[a,d]of Object.entries(t.encodeErrors))n.push({severity:"error",code:"document.encode",message:`${a}: ${d}`,moduleId:t.key.id});if(i.validateModule){const a=[...t.pending.entries()].map(([d,s])=>({path:d,text:s}));n.push(...i.validateModule({key:t.key,files:a,documents:t.documents,contents:t.contents}).map(d=>({...d,moduleId:d.moduleId??t.key.id})))}return n}const pi=(t,i={})=>Object.entries(i).reduce((n,[a,d])=>n.split(`{${a}}`).join(String(d)),t),hi=t=>t instanceof Error?t.message:String(t);function vi(t,i,n){const[a,d]=b.useState([]),[s,o]=b.useState({}),u=b.useRef(s);u.current=s;const[c,l]=b.useState({}),[r,p]=b.useState(null),[m,g]=b.useState({}),[v,f]=b.useState({}),[j,N]=b.useState(0),[$,O]=b.useState([]),_=b.useRef({provider:t,preset:i,options:n});_.current={provider:t,preset:i,options:n};const y=b.useCallback((w,I,T)=>{var F,R;return pi(((R=(F=_.current.options).t)==null?void 0:R.call(F,w,I))??I,T)},[]),x=b.useCallback((w,I,T)=>{O(F=>[...F,{level:w,message:I,data:T,timestamp:Date.now()}].slice(-300))},[]),k=b.useCallback(async(w,I)=>{var T,F;N(R=>R+1);try{return await I()}catch(R){x("error",`${w}: ${hi(R)}`),(F=(T=_.current.options).onError)==null||F.call(T,R,w);return}finally{N(R=>R-1)}},[x]),M=b.useCallback(async()=>{const w=_.current.provider;w&&await k(y("devStudio.log.list","List"),async()=>{const I=await w.listWorkspaces();d(I);const T=await Promise.all(I.map(async F=>{const[R,J]=await Promise.all([w.listModules(F.id),w.listPackages?w.listPackages(F.id):Promise.resolve(void 0)]);return[F.id,R,J]}));o(Object.fromEntries(T.map(([F,R])=>[F,R]))),l(Object.fromEntries(T.filter(([,,F])=>F).map(([F,,R])=>[F,R]))),p(w.listTemplates?await w.listTemplates():null)})},[k,y]);b.useEffect(()=>{M()},[t,M]);const V=b.useMemo(()=>{const w={};for(const[I,T]of Object.entries(m))w[I]=Ve(T,i,n.locales);return w},[m,i,n.locales]),D=b.useCallback(async w=>{var X,A;const I=ee(w),T=_.current.provider;if(!T)return;const F=await k(y("devStudio.log.open","Open {id}",{id:w.id}),()=>T.readModule(w));if(!F)return;const R=(A=(X=u.current[w.workspaceId])==null?void 0:X.find(oe=>oe.id===w.id))==null?void 0:A.contents,J={key:w,files:F,raw:{},deleted:[],drafts:{},contents:R};return g(oe=>oe[I]?oe:{...oe,[I]:J}),x("info",y("devStudio.log.opened","Opened {id} ({count} files)",{id:w.id,count:F.length})),Ve(J,_.current.preset,_.current.options.locales)},[k,x,y]),G=b.useCallback((w,I)=>{const T=ee(w);g(F=>F[T]?{...F,[T]:I(F[T])}:F)},[]),te=b.useCallback((w,I,T)=>G(w,F=>({...F,drafts:{...F.drafts,[I]:T}})),[G]),Q=b.useCallback((w,I,T,F=[])=>G(w,R=>{const J={...R.raw};T===null?delete J[I]:J[I]=T;const X={...R.drafts};for(const A of F)delete X[A];return{...R,raw:J,drafts:X,deleted:R.deleted.filter(A=>A!==I)}}),[G]),H=b.useCallback((w,I)=>G(w,T=>{const F={...T.raw};delete F[I];const R=!T.files.some(J=>J.path===I);return{...T,raw:F,deleted:R?T.deleted:[...new Set([...T.deleted,I])]}}),[G]),C=b.useCallback(w=>G(w,I=>({...I,raw:{},deleted:[],drafts:{}})),[G]),E=b.useCallback(async w=>{const I=_.current.provider;if(!I)return;const T=await k(y("devStudio.log.reload","Reload {id}",{id:w.id}),()=>I.readModule(w));T&&(G(w,F=>({key:w,files:T,raw:{},deleted:[],drafts:{},contents:F.contents})),x("info",y("devStudio.log.reloaded","Reloaded {id}",{id:w.id})))},[k,G,x,y]),B=b.useCallback(w=>{const I=ee(w);g(T=>{const F={...T};return delete F[I],F})},[]),L=b.useCallback(async(w,I={})=>{var ce;const T=_.current.provider,F=ee(w),R=m[F];if(!T||!R)return;const J=Ve(R,_.current.preset,_.current.options.locales);if(J.changes.length===0)return{ok:!0};const X=I.force?J.changes.map(se=>({...se,baseVersion:void 0})):J.changes,A=await k(y("devStudio.log.save","Save {id}",{id:w.id}),()=>T.writeModule(w,X));if(!A)return;if(!A.ok)return x("warn",y("devStudio.log.conflicts","{id}: {count} file(s) changed meanwhile",{id:w.id,count:A.conflicts.length})),A;const oe=[];for(const[se,Fe]of J.pending){const fe=R.files.find(he=>he.path===se);oe.push({...fe,path:se,text:Fe,version:((ce=A.versions)==null?void 0:ce[se])??(fe==null?void 0:fe.version)})}G(w,se=>({key:w,files:oe,raw:{},deleted:[],drafts:{},contents:se.contents}));const re=X.map(se=>se.type==="delete"?y("devStudio.log.changeDelete","delete {path}",{path:se.path}):y("devStudio.log.changeWrite","write {path}",{path:se.path})).join(", ");return x("info",y("devStudio.log.saved","Saved {id}: {changes}",{id:w.id,changes:re})),A},[m,k,G,x,y]),Z=b.useCallback(async w=>{const I=ee(w),T=V[I];if(!T)return[];const F=wt(T,i),R=_.current.provider;let J=[];if(R!=null&&R.validate){const A=[...T.pending.entries()].map(([oe,re])=>({path:oe,text:re}));J=await k(y("devStudio.log.validate","Validate {id}",{id:w.id}),()=>R.validate(w,A))??[]}f(A=>({...A,[I]:J}));const X=[...F,...J];x(X.some(A=>A.severity==="error")?"warn":"info",X.length===0?y("devStudio.log.noProblems","{id}: no problems",{id:w.id}):y("devStudio.log.problems","{id}: {count} problem(s)",{id:w.id,count:X.length}));for(const A of X)x(A.severity==="error"?"error":A.severity==="warning"?"warn":"info",`${A.path?`${A.path}: `:""}${A.messageKey?y(A.messageKey,A.message,A.params):A.message}`);return X},[V,i,k,x,y]),U=b.useCallback(async w=>{const{provider:I,preset:T}=_.current;if(!(I!=null&&I.createModule)||!T.generateModule)return;const F=new Set(Object.values(s).flatMap(X=>X.map(A=>A.id))),R=await k(y("devStudio.log.generate","Generate module"),()=>T.generateModule(w,{existingIds:F}));if(!R)return;const J=await k(y("devStudio.log.create","Create {id}",{id:R.id}),()=>I.createModule({workspaceId:w.workspaceId,packageId:R.packageId??w.packageId,id:R.id,files:R.files}));return J&&(x("info",y("devStudio.log.created","Created {id}",{id:J.id})),await M()),J},[s,k,x,M,y]),z=b.useCallback(async(w,I)=>{const{provider:T,preset:F}=_.current;if(!(T!=null&&T.createModule)||!F.duplicateModule)return;const R=await k(y("devStudio.log.read","Read {id}",{id:w.id}),()=>T.readModule(w));if(!R)return;const J=await k(y("devStudio.log.duplicate","Duplicate"),()=>F.duplicateModule(R,I));if(!J)return;const X=await k(y("devStudio.log.create","Create {id}",{id:J.id}),()=>T.createModule({workspaceId:I.workspaceId,packageId:J.packageId??I.packageId,id:J.id,files:J.files}));return X&&(x("info",y("devStudio.log.duplicated","Duplicated {id} as {copy}",{id:w.id,copy:X.id})),await M()),X},[k,x,M,y]),Y=b.useCallback(async w=>{const I=_.current.provider;if(!(I!=null&&I.deleteModule))return!1;const T=await k(y("devStudio.log.delete","Delete {id}",{id:w.id}),async()=>(await I.deleteModule(w),!0));return T&&(B(w),x("info",y("devStudio.log.deleted","Deleted {id}",{id:w.id})),await M()),!!T},[k,B,x,M,y]),le=b.useCallback(async w=>{const I=_.current.provider;if(!(I!=null&&I.savePackage))return;const T=await k(y("devStudio.log.savePackage","Save package {id}",{id:w.id}),()=>I.savePackage(w));return T&&(x("info",y("devStudio.log.savedPackage","Saved package {id}",{id:T.id})),await M()),T},[k,x,M,y]),je=b.useCallback(async(w,I)=>{const T=_.current.provider;if(!(T!=null&&T.saveTemplate))return;const F=await k(y("devStudio.log.saveTemplate","Save template {id}",{id:w.id}),()=>T.saveTemplate(w,I?{previousId:I}:void 0));return F&&T.listTemplates&&(p(await T.listTemplates()),x("info",y("devStudio.log.savedTemplate","Saved template {id}",{id:F.id}))),F},[k,x,y]),q=b.useCallback(async w=>{const I=_.current.provider;if(!(I!=null&&I.deleteTemplate))return!1;const T=await k(y("devStudio.log.deleteTemplate","Delete template {id}",{id:w}),async()=>(await I.deleteTemplate(w),!0));return T&&I.listTemplates&&(p(await I.listTemplates()),x("info",y("devStudio.log.deletedTemplate","Deleted template {id}",{id:w}))),!!T},[k,x,y]);return{workspaces:a,modulesByWs:s,packagesByWs:c,templates:r,modules:V,serverIssues:v,busy:j>0,logs:$,clearLogs:()=>O([]),log:x,refresh:M,openModule:D,close:B,setDraft:te,setRaw:Q,deleteFile:H,discard:C,reload:E,save:L,validate:Z,createModule:U,duplicateModule:z,deleteModule:Y,savePackage:le,saveTemplate:je,deleteTemplate:q}}const be="__none",Oe="t:",fi={entities:"entities",views:"views",workflows:"workflows",i18n:"translations",permissions:"permissions",rbac:"access",dataSources:"dataSources",seeds:"seeds",hooks:"hooks",script:"scripts"},gi=["entities","views","workflows","translations","permissions","access","dataSources","seeds","hooks","scripts"],xe={entities:"database",views:"grid",workflows:"git-branch",translations:"globe",permissions:"shield",access:"users",dataSources:"server",seeds:"list",hooks:"zap",scripts:"code",files:"folder"},yi={views:"grid",workflows:"git-branch",dataSources:"server"},Nt=t=>fi[t.kind.editor];function Se(t,i,n){const a=(d,s)=>t(d,s).replace("{count}",String(n??0));switch(i){case"entities":return a("devStudio.group.entities","Entities: {count}");case"views":return a("devStudio.group.views","Views: {count}");case"workflows":return a("devStudio.group.workflows","Workflows: {count}");case"dataSources":return a("devStudio.group.dataSources","Data sources: {count}");case"scripts":return a("devStudio.group.scripts","Scripts: {count}");case"files":return a("devStudio.group.files","Files: {count}");case"translations":return t("devStudio.group.translations","Translations");case"permissions":return t("devStudio.group.permissions","Permissions");case"access":return t("devStudio.group.access","Access");case"seeds":return t("devStudio.group.seeds","Seed data");case"hooks":return t("devStudio.group.hooks","Lifecycle hooks")}}function _t(t){switch(t.kind){case"workspace":return`w|${t.workspaceId}`;case"package":return`p|${t.workspaceId}|${t.packageId??be}`;case"module":return`m|${ee(t.module)}`;case"group":return`g|${ee(t.module)}|${t.group}`;case"entity":return`e|${ee(t.module)}|${t.docKey}|${t.index}`;case"item":return`i|${ee(t.module)}|${t.group}|${t.docKey}|${t.itemKey}`;case"document":return`d|${ee(t.module)}|${t.docKey}`;case"panel":return`x|${ee(t.module)}|${t.panelKey}`;case"file":return`f|${ee(t.module)}|${t.path}`;case"templates":return"t";case"category":return`c|${t.category}`;case"template":return`t|${t.templateId}`;case"templateModule":return`tm|${t.templateId}|${t.moduleId}`}}const ne=(t,i)=>t.drafts[i.key]??i.model,me=(t,i)=>t.documents.find(n=>n.key===i),we=(t,i)=>t.changes.some(n=>i.paths.includes(n.path));function et(t){const i=[];for(const n of t.documents){if(n.kind.editor!=="entities")continue;const a=ne(t,n);Array.isArray(a)&&a.forEach((d,s)=>i.push({docKey:n.key,index:s,entity:d}))}return i}const Je=t=>et(t).map(i=>i.entity),tt=(t,i="name")=>String(t.displayName||t[i]||"");function pe(t,i){const n=ne(t,i);return Array.isArray(n)?i.kind.editor==="dataSources"?n.map(a=>{const d=a;return{key:String(d.key??""),label:d.label||String(d.key??""),definition:a,source:a}}):n:[]}function it(t,i,n){return n===null?t.filter((a,d)=>d!==i):t.map((a,d)=>d===i?n:a)}function It(t,i,n){return n===null?t.filter(a=>a.key!==i):t.map(a=>a.key===i?n:a)}function Tt(t,i,n){const a=new Map((i??[]).map(d=>[d.id,d]));for(const d of n){const s=d.packageId??be;a.has(s)||a.set(s,{id:s,workspaceId:t,label:d.packageId??"",derived:!0})}return[...a.values()].sort((d,s)=>d.id===be?1:s.id===be?-1:d.label.localeCompare(s.label))}const Me=(t,i)=>t&&/^[a-z0-9-]+$/.test(t)?t:i,ht=t=>t.slice(t.lastIndexOf("/")+1);function xi(t,i,n){var c;const{t:a}=n,d=i.key,s=new Map;for(const l of i.documents){const r=Nt(l);r&&s.set(r,[...s.get(r)??[],l])}const o=(l,r)=>({id:`${r}/d:${l.key}`,node:{kind:"document",module:d,docKey:l.key},label:ht(l.paths[0]??l.label),icon:"warning",noForm:!0,dirty:we(i,l)}),u=[];for(const l of gi){const r=s.get(l);if(!r)continue;const p=`${t}/g:${l}`,m={kind:"group",module:d,group:l};if(l==="entities"){const g=[];for(const f of r){const j=ne(i,f);if(!Array.isArray(j)){g.push(o(f,p));continue}const N=we(i,f);j.forEach(($,O)=>{const _=$.fields;g.push({id:`${p}/e:${f.key}#${O}`,node:{kind:"entity",module:d,docKey:f.key,index:O},label:tt($)||`#${O+1}`,icon:"table",info:Array.isArray(_)?String(_.length):void 0,dirty:N,search:String($.name??"")})})}const v=g.filter(f=>f.node.kind==="entity").length;u.push({id:p,node:m,label:Se(a,l,v),icon:xe[l],children:g});continue}if(l==="views"||l==="workflows"||l==="dataSources"){const g=[];for(const f of r){if(f.model===void 0){g.push(o(f,p));continue}const j=we(i,f);for(const N of pe(i,f))g.push({id:`${p}/i:${f.key}#${N.key}`,node:{kind:"item",module:d,group:l,docKey:f.key,itemKey:N.key},label:N.label||N.key,icon:yi[l],noForm:N.definition===void 0,dirty:j,search:N.key})}const v=g.filter(f=>f.node.kind==="item").length;u.push({id:p,node:m,label:Se(a,l,v),icon:xe[l],children:g});continue}if(l==="scripts"){u.push({id:p,node:m,label:Se(a,l,r.length),icon:xe[l],children:r.map(g=>({id:`${p}/d:${g.key}`,node:{kind:"document",module:d,docKey:g.key},label:ht(g.paths[0]??g.label),icon:"code",dirty:we(i,g),search:g.paths.join(" ")}))});continue}if(r.length===1){const g=r[0];u.push({id:p,node:{kind:"document",module:d,docKey:g.key},label:Se(a,l),icon:xe[l],noForm:g.model===void 0,dirty:we(i,g)});continue}u.push({id:p,node:m,label:Se(a,l),icon:xe[l],children:r.map(g=>({id:`${p}/d:${g.key}`,node:{kind:"document",module:d,docKey:g.key},label:g.label,icon:xe[l],noForm:g.model===void 0,dirty:we(i,g),search:g.paths.join(" ")}))})}for(const l of((c=n.panels)==null?void 0:c.call(n,i))??[])u.push({id:`${t}/x:${l.key}`,node:{kind:"panel",module:d,panelKey:l.key},label:l.label,icon:"puzzle"});if(n.advanced){const l=new Set(i.changes.map(p=>p.path)),r=[...i.working].sort((p,m)=>p.path.localeCompare(m.path));u.push({id:`${t}/g:files`,node:{kind:"group",module:d,group:"files"},label:Se(a,"files",r.length),icon:xe.files,children:r.map(p=>({id:`${t}/g:files/f:${p.path}`,node:{kind:"file",module:d,path:p.path},label:p.path,icon:"file",dirty:l.has(p.path)}))})}return u}function ki(t){const{t:i}=t,n=i("devStudio.explorer.noPackage","No package"),a=t.workspaces.map(c=>{const l=t.modulesByWs[c.id]??[],r=`w:${c.id}`;return{id:r,node:{kind:"workspace",workspaceId:c.id},label:c.label,icon:Me(c.icon,"folder"),info:String(l.length),readOnly:c.readOnly,search:c.id,children:Tt(c.id,t.packagesByWs[c.id],l).map(p=>{const m=`${r}/p:${p.id}`,g=l.filter(v=>(v.packageId??be)===p.id).sort((v,f)=>v.label.localeCompare(f.label));return{id:m,node:{kind:"package",workspaceId:c.id,packageId:p.id===be?void 0:p.id},label:p.id===be?n:p.label||p.id,icon:Me(p.icon,"archive"),info:String(g.length),search:p.id,children:g.map(v=>{var _;const f=ee(v),j=t.modules[f],N=`${m}/m:${v.id}`,$=j?xi(N,j,t):void 0,O=j?[...et(j).map(y=>`${y.entity.name??""} ${tt(y.entity)}`),...j.documents.filter(y=>y.kind.editor==="views").flatMap(y=>pe(j,y).map(x=>`${x.key} ${x.label}`))]:[];return{id:N,node:{kind:"module",module:{workspaceId:v.workspaceId,id:v.id}},label:v.label,icon:Me(v.icon,"box"),info:v.version,readOnly:v.readOnly,shadowedBy:v.shadowedBy,dirty:j==null?void 0:j.dirty,issues:(_=t.issueCounts)==null?void 0:_[f],search:[v.id,v.description??"",v.search??"",...O].join(" "),children:$}})}})}});if(t.templates){const c=new Map;for(const p of t.workspaces)for(const m of t.modulesByWs[p.id]??[])c.has(m.id)||c.set(m.id,m);const l=new Map;for(const p of t.templates){const m=p.category??"";l.set(m,[...l.get(m)??[],p])}const r=p=>{var m,g;return((m=p.translations.en)==null?void 0:m.name)??((g=Object.values(p.translations)[0])==null?void 0:g.name)??p.id};a.push({id:Oe,node:{kind:"templates"},label:i("devStudio.tree.templates","Templates"),icon:"layers",info:String(t.templates.length),children:[...l.entries()].sort(([p],[m])=>p.localeCompare(m)).map(([p,m])=>{const g=`${Oe}/c:${p}`;return{id:g,node:{kind:"category",category:p},label:p||i("devStudio.explorer.noCategory","Other"),icon:"folder",info:String(m.length),children:[...m].sort((v,f)=>(v.sortOrder??0)-(f.sortOrder??0)||r(v).localeCompare(r(f))).map(v=>{const f=`${g}/t:${v.id}`;return{id:f,node:{kind:"template",templateId:v.id},label:r(v),icon:Me(v.icon,"layers"),info:String(v.modules.length),readOnly:v.readOnly,search:`${v.id} ${(v.tags??[]).join(" ")}`,children:v.modules.map(j=>{const N=c.get(j.moduleId);return{id:`${f}/m:${j.moduleId}`,node:{kind:"templateModule",templateId:v.id,moduleId:j.moduleId,target:N?{workspaceId:N.workspaceId,id:N.id}:void 0},label:(N==null?void 0:N.label)??j.moduleId,icon:"box",info:j.required?i("devStudio.template.required","required"):void 0,missing:!N,search:j.moduleId}})}})}})})}const d=new Map,s=new Map,o=new Map,u=(c,l,r=0)=>{for(const p of c){p.depth=r,d.set(p.id,p),l&&s.set(p.id,l);const m=_t(p.node);o.has(m)||o.set(m,p.id),p.children&&u(p.children,p.id,r+1)}};return u(a),{rows:a,byId:d,parentOf:s,rowOfNode:o}}function vt(t,i){const n=[];let a=i;for(;a;){const d=t.byId.get(a);if(!d)break;n.unshift(d),a=t.parentOf.get(a)}return n}const We=(t,i)=>t.rowOfNode.get(_t(i));function Ke(t){return"module"in t?t.module:void 0}function bi(t,i){var a;const n="module"in t?i.modules[ee(t.module)]:void 0;switch(t.kind){case"module":return n!=null&&n.documents.some(d=>d.kind.editor==="manifest")?{kind:"manifest",module:t.module}:void 0;case"entity":return{kind:"entity",module:t.module,docKey:t.docKey,index:t.index};case"item":{const d=n&&me(n,t.docKey),s=d&&pe(n,d).find(o=>o.key===t.itemKey);return(s==null?void 0:s.definition)!==void 0||i.advanced?{...t}:void 0}case"document":{const d=n&&me(n,t.docKey);return(d==null?void 0:d.model)!==void 0?{kind:"document",module:t.module,docKey:t.docKey}:d&&i.advanced?{kind:"file",module:t.module,path:d.paths[0]}:void 0}case"panel":return{kind:"panel",module:t.module,panelKey:t.panelKey};case"file":return{kind:"file",module:t.module,path:t.path};case"package":{const d=(a=i.packages)==null?void 0:a.find(s=>s.id===t.packageId);return d&&!d.derived?{kind:"package",pkg:d}:void 0}case"template":return{kind:"template",templateId:t.templateId};default:return}}function ft(t){switch(t.kind){case"manifest":case"problems":case"history":return{kind:"module",module:t.module};case"entity":return{kind:"entity",module:t.module,docKey:t.docKey,index:t.index};case"item":return{...t};case"document":return{kind:"document",module:t.module,docKey:t.docKey};case"panel":return{kind:"panel",module:t.module,panelKey:t.panelKey};case"file":return{kind:"file",module:t.module,path:t.path};case"package":return{kind:"package",workspaceId:t.pkg.workspaceId,packageId:t.pkg.id};case"template":return t.templateId?{kind:"template",templateId:t.templateId}:void 0}}const ji=/^\/(?:[A-Za-z]+\/)?(\d+)(?:\/|$)/;function Ct(t,i){const n=t.key,a=i.path?t.documents.find(u=>u.paths.includes(i.path)):void 0;if(!a)return{kind:"module",module:n};const d=Nt(a),s=a.paths.length===1?ji.exec(i.pointer??""):null,o=s?Number(s[1]):-1;if(d==="entities"){const u=ne(t,a);return Array.isArray(u)&&o>=0&&o<u.length?{kind:"entity",module:n,docKey:a.key,index:o}:{kind:"group",module:n,group:d}}if(d==="views"||d==="workflows"||d==="dataSources"){const u=o>=0?pe(t,a)[o]:void 0;return u?{kind:"item",module:n,group:d,docKey:a.key,itemKey:u.key}:{kind:"group",module:n,group:d}}return d?{kind:"document",module:n,docKey:a.key}:a.kind.editor==="manifest"?{kind:"module",module:n}:{kind:"file",module:n,path:a.paths[0]}}function gt(t){var l,r;const{module:i,doc:n,preset:a,session:d,locales:s,readOnly:o}=t,u=ne(i,n),c=p=>d.setDraft(i.key,n.key,p);switch(n.kind.editor){case"manifest":return e.jsx(Si,{...t});case"i18n":{const p=u??{};return e.jsx(Qe,{value:p,onChange:c,locales:[...new Set([...s,...Object.keys(p)])],allowEditLocales:!0,allowEditKeys:!0,highlightMissing:!0,readOnly:o})}case"permissions":return e.jsx(wi,{value:u??{permissions:[],groups:[]},onChange:c,readOnly:o});case"seeds":return e.jsx(Ii,{value:u??{seeds:{}},onChange:c,entities:Je(i),readOnly:o});case"rbac":return e.jsx(h.NiceAccessManager,{value:u,onChange:c,readOnly:o});case"hooks":return e.jsx(h.NiceLifecycleHooksEditor,{triggers:((l=a.hooks)==null?void 0:l.triggers)??[],handlers:(r=a.hooks)==null?void 0:r.handlers,bindings:u??[],onChange:c,groupByTrigger:!0,allowCondition:!0,readOnly:o});case"script":return t.scriptRunner?e.jsx(h.NiceScriptRunner,{...t.scriptRunner,value:String(u??""),onChange:c}):e.jsx(h.NiceSimpleCodeEditor,{value:String(u??""),onChange:c,language:"javascript",height:"100%",lineNumbers:!0,readOnly:o});case"text":return e.jsx(h.NiceSimpleCodeEditor,{value:String(u??""),onChange:c,height:"100%",lineNumbers:!0,readOnly:o});default:return e.jsx(Ze,{value:u,onChange:c,readOnly:o,height:"100%",label:n.label})}}function Si({module:t,doc:i,preset:n,session:a,readOnly:d,advanced:s}){var O;const{t:o}=h.useNiceTranslation(),u=ne(t,i),c=b.useMemo(()=>u??{},[u]),l=_=>a.setDraft(t.key,i.key,_),r=n.manifestSections,p=b.useMemo(()=>(r??[]).map(_=>P.fitManifestSection(_,c)),[r,c]),m=r??[],g=b.useMemo(()=>new Set(p.flatMap(_=>_.keys)),[p]),v=Object.keys(c).filter(_=>!g.has(_)),[f,j]=b.useState(((O=p[0])==null?void 0:O.section.id)??"__other"),N=p.find(_=>_.section.id===f),$=s?e.jsx(Ze,{value:Object.fromEntries(v.map(_=>[_,c[_]])),readOnly:d,label:o("devStudio.manifest.other","Other properties"),onChange:_=>{if(_&&typeof _=="object"&&!Array.isArray(_)){const y=Object.fromEntries(Object.entries(c).filter(([x])=>g.has(x)));l({...y,..._})}}}):e.jsxs("div",{className:"nice-development-studio__note",children:[e.jsx("p",{children:o("devStudio.manifest.kept","These properties have no form here. Saving keeps them exactly as they are; switch to the advanced mode to edit them.")}),e.jsx("ul",{className:"nice-development-studio__chips",children:v.map(_=>e.jsx("li",{className:"nice-development-studio__tag",children:_},_))})]});return e.jsxs("div",{className:"nice-development-studio__sections","data-testid":"studio-manifest-form",children:[e.jsxs("nav",{className:"nice-development-studio__section-nav","aria-label":o("devStudio.manifest.sections","Sections"),children:[p.map(({section:_})=>e.jsx(h.NiceButton,{size:"sm",variant:f===_.id?"primary":"ghost","aria-pressed":f===_.id,onClick:()=>j(_.id),children:_.title},_.id)),v.length>0&&e.jsx(h.NiceButton,{size:"sm",variant:f==="__other"?"primary":"ghost","aria-pressed":f==="__other",onClick:()=>j("__other"),children:`${o("devStudio.manifest.other","Other properties")} (${v.length})`})]}),e.jsx("div",{className:"nice-development-studio__section-body",children:N?e.jsx(_e,{schema:N.section.schema,fields:N.section.fields,uiSchema:N.section.uiSchema,value:Object.fromEntries(N.keys.filter(_=>_ in c).map(_=>[_,c[_]])),onChange:_=>{const y={...c};for(const x of N.keys)_[x]===void 0?delete y[x]:y[x]=_[x];l(y)},readOnly:d}):v.length>0||m.length===0?$:null})]})}function wi({value:t,onChange:i,readOnly:n}){const{t:a}=h.useNiceTranslation(),d={code:a("devStudio.permissions.code","Code"),name:a("devStudio.permissions.name","Name"),description:a("devStudio.permissions.description","Description")},s=b.useMemo(()=>{const u={};for(const c of t.groups)for(const l of c.permissions)u[`${c.id}:${l}`]=!0;return u},[t.groups]),o=(u,c)=>{const l=t.permissions[u],r={...l,...c};i({permissions:t.permissions.map((p,m)=>m===u?r:p),groups:c.code!==void 0&&c.code!==l.code?t.groups.map(p=>({...p,permissions:p.permissions.map(m=>m===l.code?r.code:m)})):t.groups})};return e.jsxs("div",{className:"nice-development-studio__permissions",children:[e.jsx("h4",{children:a("devStudio.permissions.codes","Permissions")}),e.jsxs("table",{className:"nice-development-studio__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:d.code}),e.jsx("th",{children:d.name}),e.jsx("th",{children:d.description}),!n&&e.jsx("th",{"aria-label":a("devStudio.delete","Delete")})]})}),e.jsx("tbody",{children:t.permissions.map((u,c)=>e.jsxs("tr",{children:[["code","name","description"].map(l=>e.jsx("td",{children:e.jsx("input",{className:"nice-development-studio__cell",value:u[l]??"",readOnly:n,"aria-label":`${d[l]} ${u.code}`,onChange:r=>o(c,{[l]:r.target.value})})},l)),!n&&e.jsx("td",{children:e.jsx(h.NiceButton,{size:"sm",variant:"ghost",ariaLabel:`${a("devStudio.delete","Delete")} ${u.code}`,onClick:()=>i({permissions:t.permissions.filter((l,r)=>r!==c),groups:t.groups.map(l=>({...l,permissions:l.permissions.filter(r=>r!==u.code)}))}),children:e.jsx(h.NiceIcon,{name:"trash",size:14})})})]},c))})]}),!n&&e.jsxs("div",{className:"nice-development-studio__row",children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:()=>i({...t,permissions:[...t.permissions,{code:`New.Permission${t.permissions.length+1}`}]}),children:a("devStudio.permissions.addCode","New permission")}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:()=>i({...t,groups:[...t.groups,{id:`group${t.groups.length+1}`,label:a("devStudio.permissions.newGroup","Group {n}").replace("{n}",String(t.groups.length+1)),permissions:[]}]}),children:a("devStudio.permissions.addGroup","New group")})]}),e.jsx("h4",{children:a("devStudio.permissions.groups","Groups")}),e.jsx(h.NicePermissionMatrix,{roles:t.groups.map(u=>({id:u.id,label:u.label})),actions:t.permissions.map(u=>({id:u.code,label:u.name||u.code})),value:s,readOnly:n,showBulkActions:!0,onChange:u=>i({...t,groups:t.groups.map(c=>({...c,permissions:t.permissions.map(l=>l.code).filter(l=>u[`${c.id}:${l}`]===!0)}))})})]})}const yt=t=>t===null||typeof t!="object";function Ni(t){const i=t.toLowerCase();return/(int|long|decimal|double|float|number|money)/.test(i)?"number":/bool/.test(i)?"boolean":"string"}function _i(t,i){const n={},a=Array.isArray(i==null?void 0:i.fields)?i.fields:[];for(const d of a){const s=String(d.name??"");s&&t.every(o=>yt(o[s]))&&(n[s]={type:Ni(String(d.dataType??d.type??"string")),title:String(d.displayName||s)})}for(const d of t)for(const[s,o]of Object.entries(d))!(s in n)&&t.every(u=>yt(u[s]))&&(n[s]={type:typeof o=="number"?"number":typeof o=="boolean"?"boolean":"string",title:s});return{type:"object",properties:n}}function Ii({value:t,onChange:i,entities:n,readOnly:a}){const{t:d}=h.useNiceTranslation(),s=u=>n.find(c=>c.name===u||c.tableName===u),o=u=>{const c=t[u]??{},l=Object.keys(c);return l.length===0?e.jsx("p",{className:"nice-development-studio__muted",children:d("devStudio.seeds.empty","No rows.")}):e.jsx(h.NiceTabs,{tabs:l.map(r=>{const p=c[r];return{id:r,label:`${r} (${p.length})`,content:e.jsx(Ye,{value:p,itemSchema:_i(p,s(r)),title:r,readOnly:a,onChange:m=>{const g=m.length===p.length?m.map((v,f)=>v===p[f]?v:{...p[f],...v}):m;i({...t,[u]:{...c,[r]:g}})}})}})})};return e.jsx(h.NiceTabs,{tabs:[{id:"seeds",label:d("devStudio.seeds.data","Data"),content:o("seeds")},{id:"demo",label:d("devStudio.seeds.demo","Demo data"),content:o("demoSeeds")}]})}function Ti({module:t,path:i,session:n,readOnly:a}){var r;const{t:d}=h.useNiceTranslation(),[s,o]=b.useState("source"),u=t.changes.find(p=>p.path===i),c=t.documents.filter(p=>p.paths.includes(i)).map(p=>p.key),l=((r=t.files.find(p=>p.path===i))==null?void 0:r.text)??"";return e.jsxs("div",{className:"nice-development-studio__source","data-testid":"studio-file-source",children:[e.jsx("div",{className:"nice-development-studio__row",children:e.jsxs("div",{className:"nice-development-studio__segmented",role:"group","aria-label":d("devStudio.doc.mode","Show"),children:[e.jsx(h.NiceButton,{size:"sm",variant:s==="source"?"primary":"ghost","aria-pressed":s==="source",onClick:()=>o("source"),children:d("devStudio.doc.source","Source")}),e.jsx(h.NiceButton,{size:"sm",variant:s==="changes"?"primary":"ghost","aria-pressed":s==="changes",onClick:()=>o("changes"),children:`${d("devStudio.doc.changes","Changes")}${u?" (1)":""}`})]})}),s==="source"?e.jsx(h.NiceSimpleCodeEditor,{value:t.pending.get(i)??"",language:i.endsWith(".json")?"json":i.endsWith(".js")?"javascript":"plaintext",height:"100%",lineNumbers:!0,readOnly:a,onChange:p=>n.setRaw(t.key,i,P.keepTextFormat(p,t.pending.get(i)),c)}):u?e.jsx(St,{before:l,after:u.type==="write"?u.text:""}):e.jsx("p",{className:"nice-development-studio__muted",children:d("devStudio.diff.none","No changes.")})]})}const Ci=t=>({type:"object",required:["id"],properties:{id:{type:"string",title:t("devStudio.template.id","Id (slug)")},category:{type:"string",title:t("devStudio.template.category","Category")},subCategory:{type:"string",title:t("devStudio.template.subCategory","Subcategory")},parentId:{type:"string",title:t("devStudio.template.parent","Parent template")},icon:{type:"string",title:t("devStudio.template.icon","Icon")},sortOrder:{type:"number",title:t("devStudio.template.sortOrder","Order")},tags:{type:"array",items:{type:"string"},title:t("devStudio.template.tags","Tags")}}});function Ei({session:t,template:i,locales:n,extraSchema:a,readOnly:d,onSaved:s,onDeleted:o}){var _;const{t:u}=h.useNiceTranslation(),[c,l]=b.useState(()=>i??{id:"",translations:{[n[0]??"en"]:{name:""}},modules:[]}),[r,p]=b.useState(null),m=d||!!(i!=null&&i.readOnly),g={id:c.id,category:c.category,subCategory:c.subCategory,parentId:c.parentId,icon:c.icon,sortOrder:c.sortOrder,tags:c.tags},v=Object.fromEntries(Object.entries(c.translations).map(([y,x])=>[y,{name:x.name,description:x.description??""}])),f=b.useMemo(()=>t.workspaces.map(y=>{const x=t.modulesByWs[y.id]??[],k=[...new Set(x.map(M=>M.packageId??""))].sort();return{id:`w:${y.id}`,label:y.label,kind:"workspace",children:k.map(M=>({id:`w:${y.id}/p:${M}`,label:M||u("devStudio.explorer.noPackage","No package"),kind:"package",children:x.filter(V=>(V.packageId??"")===M).map(V=>({id:`m:${V.id}`,label:V.label,kind:"module"}))}))}}),[t.workspaces,t.modulesByWs,u]),j=b.useMemo(()=>{const y=new Map;for(const x of Object.values(t.modulesByWs))for(const k of x)y.set(k.id,k.label);return y},[t.modulesByWs]),N=y=>l({...c,modules:y}),$=(y,x)=>{const k=[...c.modules],[M]=k.splice(y,1);k.splice(y+x,0,M),N(k)},O=[{field:"label",header:u("devStudio.explorer.name","Name")}];return e.jsxs("div",{className:"nice-development-studio__template","data-testid":"studio-template-editor",children:[e.jsxs("div",{className:"nice-development-studio__doc-bar",children:[e.jsx(h.NiceIcon,{name:"layers",size:14}),e.jsx("strong",{className:"nice-development-studio__doc-title",children:i?((_=c.translations.en)==null?void 0:_.name)||c.id:u("devStudio.template.new","New template")}),e.jsx("span",{className:"nice-development-studio__spacer"}),!m&&e.jsx(h.NiceButton,{size:"sm",variant:"primary",disabled:!c.id.trim(),onClick:async()=>{p(null);const y=await t.saveTemplate({...c,id:c.id.trim()},i==null?void 0:i.id);y?s==null||s(y):p(u("devStudio.template.saveFailed","The template could not be saved; see the output panel."))},children:u("devStudio.save","Save")}),!m&&i&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"trash",size:14}),onClick:async()=>{await t.deleteTemplate(i.id)&&(o==null||o())},children:u("devStudio.delete","Delete")})]}),r&&e.jsx("p",{className:"nice-development-studio__error",role:"alert",children:r}),e.jsxs("div",{className:"nice-development-studio__columns",children:[e.jsxs("section",{children:[e.jsx("h4",{children:u("devStudio.template.basics","Template")}),e.jsx(_e,{schema:Ci(u),value:g,readOnly:m,onChange:y=>l({...c,id:String(y.id??""),category:y.category||void 0,subCategory:y.subCategory||void 0,parentId:y.parentId||void 0,icon:y.icon||void 0,sortOrder:typeof y.sortOrder=="number"?y.sortOrder:void 0,tags:Array.isArray(y.tags)?y.tags:void 0})}),a&&e.jsx(_e,{schema:a,value:c.extra??{},readOnly:m,onChange:y=>l({...c,extra:y})}),e.jsx("h4",{children:u("devStudio.template.translations","Name and description")}),e.jsx(Qe,{value:v,locales:[...new Set([...n,...Object.keys(v)])],allowEditLocales:!0,readOnly:m,onChange:y=>l({...c,translations:Object.fromEntries(Object.entries(y).map(([x,k])=>[x,{name:k.name??"",...k.description?{description:k.description}:{}}]))})})]}),e.jsxs("section",{children:[e.jsx("h4",{children:u("devStudio.template.modules","Modules")}),e.jsx(h.NiceTreeGrid,{data:f,nested:!0,keyField:"id",childrenField:"children",columns:O,sortable:!1,compact:!0,checkable:!0,checkStrategy:"leaves",isRowCheckable:y=>y.kind!=="workspace",isRowDisabled:()=>m,checkedKeys:c.modules.map(y=>`m:${y.moduleId}`),onCheckedChange:y=>{const x=y.filter(V=>V.startsWith("m:")).map(V=>V.slice(2)),k=c.modules.filter(V=>x.includes(V.moduleId)),M=x.filter(V=>!k.some(D=>D.moduleId===V)).map(V=>({moduleId:V}));N([...k,...M])},checkedSummary:y=>u("devStudio.template.summary","{count} modules · {required} required").replace("{count}",String(y.checked)).replace("{required}",String(c.modules.filter(x=>x.required).length)),searchable:!0,searchFields:["label"],virtualScroll:!0,height:320,"aria-label":u("devStudio.template.modules","Modules")}),e.jsxs("table",{className:"nice-development-studio__table",children:[e.jsx("thead",{children:e.jsxs("tr",{children:[e.jsx("th",{children:u("devStudio.template.module","Module")}),e.jsx("th",{children:u("devStudio.template.required","required")}),e.jsx("th",{children:u("devStudio.template.condition","Condition")}),!m&&e.jsx("th",{"aria-label":u("devStudio.template.order","Order")})]})}),e.jsx("tbody",{children:c.modules.map((y,x)=>e.jsxs("tr",{children:[e.jsx("td",{children:j.get(y.moduleId)??y.moduleId}),e.jsx("td",{children:e.jsx("input",{type:"checkbox",checked:!!y.required,disabled:m,"aria-label":`${u("devStudio.template.required","required")} ${y.moduleId}`,onChange:k=>N(c.modules.map((M,V)=>V===x?{...M,required:k.target.checked}:M))})}),e.jsx("td",{children:e.jsx("input",{className:"nice-development-studio__cell",value:y.condition??"",readOnly:m,"aria-label":`${u("devStudio.template.condition","Condition")} ${y.moduleId}`,onChange:k=>N(c.modules.map((M,V)=>V===x?{...M,condition:k.target.value||void 0}:M))})}),!m&&e.jsxs("td",{className:"nice-development-studio__nowrap",children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",disabled:x===0,ariaLabel:u("devStudio.template.up","Move up"),onClick:()=>$(x,-1),children:e.jsx(h.NiceIcon,{name:"chevron-up",size:12})}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",disabled:x===c.modules.length-1,ariaLabel:u("devStudio.template.down","Move down"),onClick:()=>$(x,1),children:e.jsx(h.NiceIcon,{name:"chevron-down",size:12})})]})]},y.moduleId))})]})]})]})]})}function Mi({session:t,pkg:i,readOnly:n,onNewModule:a,onOpenModule:d}){const{t:s}=h.useNiceTranslation(),[o,u]=b.useState({id:i.id,label:i.label,description:i.description,icon:i.icon}),c=(t.modulesByWs[i.workspaceId]??[]).filter(r=>r.packageId===i.id),l=!n&&!i.derived&&!i.readOnly;return e.jsxs("div",{className:"nice-development-studio__template","data-testid":"studio-package-editor",children:[e.jsxs("div",{className:"nice-development-studio__doc-bar",children:[e.jsx(h.NiceIcon,{name:"archive",size:14}),e.jsx("strong",{className:"nice-development-studio__doc-title",children:i.label||i.id}),e.jsx("span",{className:"nice-development-studio__spacer"}),!n&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:a,children:s("devStudio.package.newModule","New module here")}),l&&e.jsx(h.NiceButton,{size:"sm",variant:"primary",onClick:()=>void t.savePackage({...i,id:String(o.id??i.id),label:String(o.label??""),description:o.description||void 0,icon:o.icon||void 0}),children:s("devStudio.save","Save")})]}),i.derived?e.jsx("p",{className:"nice-development-studio__muted",children:s("devStudio.package.derived","This package comes from the modules themselves (their category); rename it by changing their manifests.")}):e.jsx(_e,{schema:{type:"object",required:["id","label"],properties:{id:{type:"string",title:s("devStudio.package.id","Id")},label:{type:"string",title:s("devStudio.package.label","Name")},description:{type:"string",title:s("devStudio.package.description","Description")},icon:{type:"string",title:s("devStudio.template.icon","Icon")}}},value:o,readOnly:!l,onChange:r=>u(r)}),e.jsx("h4",{children:s("devStudio.template.modules","Modules")}),e.jsxs("ul",{className:"nice-development-studio__list",children:[c.map(r=>e.jsxs("li",{children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"box",size:14}),onClick:()=>d(r.id),children:r.label}),r.description&&e.jsx("span",{className:"nice-development-studio__muted",children:r.description})]},r.id)),c.length===0&&e.jsx("li",{className:"nice-development-studio__muted",children:s("devStudio.explorer.empty","No modules.")})]})]})}const Ki=t=>"module"in t?t.module:void 0;function Oi(t){const{screen:i,crumbs:n,session:a,readOnly:d,tutorialButton:s,onBack:o,onSave:u}=t,{t:c}=h.useNiceTranslation(),l=Ki(i),r=l?a.modules[ee(l)]:void 0,p=d(l),m=Fi(i,r,a);return e.jsxs("div",{className:"nice-development-studio__edit","data-testid":"studio-edit-screen",children:[e.jsxs("header",{className:"nice-development-studio__edit-header",children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"arrow-left",size:14}),onClick:o,"data-testid":"studio-back",children:c("devStudio.edit.back","Back")}),e.jsx(h.NiceBreadcrumb,{className:"nice-development-studio__crumbs",size:"sm",separator:"›",items:n}),e.jsx("span",{className:"nice-development-studio__spacer"}),m&&!p&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"trash",size:14}),onClick:()=>{m(),o()},children:c("devStudio.delete","Delete")}),r&&e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"check",size:14}),onClick:()=>void a.validate(r.key),children:c("devStudio.validate","Validate")}),!p&&e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",disabled:!r.dirty,onClick:()=>a.discard(r.key),children:c("devStudio.discard","Discard changes")}),e.jsx(h.NiceButton,{size:"sm",variant:"primary",disabled:!r.dirty,onClick:()=>u(r.key),"data-tour":"devstudio-save",children:r.dirty?c("devStudio.saveCount","Save ({count})").replace("{count}",String(r.changes.length)):c("devStudio.save","Save")})]})]}),s]}),e.jsx("div",{className:"nice-development-studio__edit-body",children:e.jsx($i,{...t,module:r,readOnlyHere:p})})]})}function Fi(t,i,n){if(!i||t.kind!=="entity"&&t.kind!=="item")return;const a=me(i,t.docKey);if(!a)return;if(t.kind==="entity"){const s=ne(i,a);return Array.isArray(s)?()=>n.setDraft(i.key,a.key,it(s,t.index,null)):void 0}if(t.group==="dataSources"){const s=ne(i,a)??[];return()=>n.setDraft(i.key,a.key,s.filter(o=>o.key!==t.itemKey))}const d=pe(i,a);return()=>n.setDraft(i.key,a.key,It(d,t.itemKey,null))}function ve(){const{t}=h.useNiceTranslation();return e.jsx("p",{className:"nice-development-studio__muted",children:t("devStudio.edit.gone","This is no longer in the module.")})}function $i(t){var r,p,m,g,v;const{screen:i,module:n,session:a,preset:d,provider:s,locales:o,advanced:u,readOnlyHere:c}=t,{t:l}=h.useNiceTranslation();if(i.kind==="package")return e.jsx(Mi,{session:a,pkg:i.pkg,readOnly:t.readOnly(),onNewModule:()=>t.onNewModule({workspaceId:i.pkg.workspaceId,packageId:i.pkg.id}),onOpenModule:f=>t.onReveal({kind:"module",module:{workspaceId:i.pkg.workspaceId,id:f}})});if(i.kind==="template"){const f=i.templateId?(r=a.templates)==null?void 0:r.find(j=>j.id===i.templateId):void 0;return e.jsx(Ei,{session:a,template:f,locales:o,extraSchema:d.templateSchema,readOnly:t.readOnly(),onSaved:j=>{j.id!==i.templateId&&t.onScreen({kind:"template",templateId:j.id})},onDeleted:t.onBack},i.templateId??"new")}if(!n)return e.jsx("p",{className:"nice-development-studio__muted",children:l("devStudio.loading","Loading…")});switch(i.kind){case"manifest":{const f=n.documents.find(j=>j.kind.editor==="manifest");return f?e.jsx(gt,{module:n,doc:f,preset:d,session:a,locales:o,readOnly:c,advanced:u,scriptRunner:t.scriptRunner}):e.jsx(ve,{})}case"entity":{const f=me(n,i.docKey),j=f?ne(n,f):void 0,N=Array.isArray(j)?j[i.index]:void 0;return!f||!j||!N?e.jsx(ve,{}):e.jsx(Xe,{value:N,onChange:$=>a.setDraft(n.key,f.key,it(j,i.index,$)),entityMetaSchema:(p=d.entities)==null?void 0:p.entityMetaSchema,fieldSchema:(m=d.entities)==null?void 0:m.fieldSchema,fieldsKey:(g=d.entities)==null?void 0:g.fieldsKey,readOnly:c,"data-testid":"studio-entity-form"})}case"item":return e.jsx(Bi,{...t,screen:i,module:n});case"document":{const f=me(n,i.docKey);return f?e.jsx(gt,{module:n,doc:f,preset:d,session:a,locales:o,readOnly:c,advanced:u,scriptRunner:t.scriptRunner}):e.jsx(ve,{})}case"panel":{const f=(v=t.modulePanels)==null?void 0:v.call(t,{module:n.key,files:n.working,dirty:n.dirty}).find(j=>j.key===i.panelKey);return f?e.jsx(e.Fragment,{children:f.content}):e.jsx(ve,{})}case"file":return n.working.some(f=>f.path===i.path)?e.jsx(Ti,{module:n,path:i.path,session:a,readOnly:c}):e.jsx(ve,{});case"problems":return e.jsx(zi,{module:n,issues:t.issues(n.key),onReveal:t.onReveal});case"history":return e.jsx(Di,{module:n,provider:s,session:a,readOnly:c})}}function Bi({screen:t,module:i,session:n,readOnlyHere:a,advanced:d,renderViewPreview:s,onScreen:o}){const{t:u}=h.useNiceTranslation(),c=me(i,t.docKey);if(!c)return e.jsx(ve,{});if(t.group==="dataSources"){const v=ne(i,c)??[],f=v.find(j=>j.key===t.itemKey);return f?e.jsx(h.NiceDataSourceBuilder,{value:f,schemas:P.entitiesToSchemas(Je(i)),onChange:j=>{n.setDraft(i.key,c.key,v.map(N=>N.key===f.key?j:N)),j.key!==f.key&&o({...t,itemKey:j.key})}}):e.jsx(ve,{})}const l=pe(i,c),r=l.find(v=>v.key===t.itemKey);if(!r)return e.jsx(ve,{});const p=v=>{n.setDraft(i.key,c.key,It(l,r.key,v)),v.key!==r.key&&o({...t,itemKey:v.key})},m=v=>p({...r,definition:v,label:v.name||r.label,key:v.id&&!l.some(f=>f!==r&&f.key===v.id)?v.id:r.key});if(r.definition===void 0)return d?e.jsxs("div",{className:"nice-development-studio__source",children:[e.jsxs("p",{className:"nice-development-studio__muted",children:[u("devStudio.items.rawReason","The editor does not know this shape, so it is edited as JSON."),r.rawReason?` (${r.rawReason})`:""]}),e.jsx(Ze,{value:r.source,readOnly:a,label:r.label,height:"100%",onChange:v=>p({...r,source:v})})]}):e.jsx("p",{className:"nice-development-studio__muted",children:u("devStudio.preview.noDesigner","There is no designer for this kind of entry yet.")});if(t.group==="workflows")return e.jsx(Rt.NiceWorkflowDesigner,{workflow:r.definition,onChange:v=>m(v),readOnly:a});const g=e.jsx(h.NiceViewEditor,{value:r.definition,onChange:v=>m(v),entities:Je(i),dataSourceOptions:i.documents.filter(v=>v.kind.editor==="dataSources").flatMap(v=>ne(i,v)??[]).map(v=>({key:v.key,label:v.label})),height:640});return s?e.jsx(h.NiceTabs,{tabs:[{id:"design",label:u("devStudio.view.design","Design"),content:g},{id:"preview",label:u("devStudio.view.hostPreview","Preview in the app"),content:s({module:i.key,item:r,files:i.working})}]}):g}function zi({module:t,issues:i,onReveal:n}){const{t:a}=h.useNiceTranslation();return i.length===0?e.jsx("p",{className:"nice-development-studio__muted",children:a("devStudio.overview.noProblems","No problems found.")}):e.jsx("ul",{className:"nice-development-studio__issues","data-testid":"studio-problems",children:i.map((d,s)=>e.jsxs("li",{className:`nice-development-studio__issue nice-development-studio__issue--${d.severity}`,children:[e.jsx(h.NiceIcon,{name:d.severity==="error"?"error":d.severity==="warning"?"warning":"info",size:14}),e.jsx("span",{children:Et(a,d)}),d.path&&e.jsx("span",{className:"nice-development-studio__muted",children:d.path}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",onClick:()=>n(Ct(t,d)),children:a("devStudio.problems.goTo","Go to")})]},s))})}function Et(t,i){return i.messageKey?Object.entries(i.params??{}).reduce((n,[a,d])=>n.replace(`{${a}}`,String(d)),t(i.messageKey,i.message)):i.message}function Di({module:t,provider:i,session:n,readOnly:a}){const[d,s]=b.useState(null),o=t.key;return b.useEffect(()=>{let u=!0;return i!=null&&i.listRevisions&&i.listRevisions(o).then(c=>{u&&s(c.map(l=>({id:l.id,label:l.label,author:l.author,timestamp:l.timestamp,summary:l.summary})))}).catch(()=>s([])),()=>{u=!1}},[i,o,t.files]),e.jsx(h.NiceRevisionHistory,{revisions:d??[],language:"json",loadContent:i!=null&&i.readRevision?u=>i.readRevision(o,u):void 0,onRollback:i!=null&&i.rollback&&!a?async u=>{await i.rollback(o,u),await n.reload(o)}:void 0})}function ie({icon:t,title:i,subtitle:n,badges:a,actions:d,children:s}){return e.jsxs("section",{className:"nice-development-studio__preview","data-testid":"studio-preview",children:[e.jsxs("div",{className:"nice-development-studio__preview-info",children:[e.jsxs("header",{className:"nice-development-studio__preview-head",children:[e.jsx(h.NiceIcon,{name:t,size:20}),e.jsxs("div",{className:"nice-development-studio__preview-name",children:[e.jsx("h3",{className:"nice-development-studio__preview-title",children:i}),n&&e.jsx("span",{className:"nice-development-studio__muted",children:n})]})]}),a&&e.jsx("div",{className:"nice-development-studio__preview-badges",children:a}),s]}),d&&e.jsx("footer",{className:"nice-development-studio__preview-actions",children:d})]})}function de({items:t}){const i=t.filter(([,n])=>n!=null&&n!=="");return i.length===0?null:e.jsx("dl",{className:"nice-development-studio__facts",children:i.map(([n,a])=>e.jsxs("div",{className:"nice-development-studio__fact",children:[e.jsx("dt",{children:n}),e.jsx("dd",{children:a})]},n))})}function Ne({rows:t,onSelect:i,limit:n=12}){const{t:a}=h.useNiceTranslation();return t.length===0?null:e.jsxs("ul",{className:"nice-development-studio__preview-list",children:[t.slice(0,n).map(d=>e.jsxs("li",{children:[e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:d.icon,size:14}),onClick:()=>i(d.id),children:d.label}),d.info&&e.jsx("span",{className:"nice-development-studio__muted",children:d.info})]},d.id)),t.length>n&&e.jsx("li",{className:"nice-development-studio__muted",children:a("devStudio.preview.more","…and {count} more").replace("{count}",String(t.length-n))})]})}const Ce=t=>Array.isArray(t)?t.length:void 0;function Pi(t){var p,m,g,v;const{row:i,session:n,advanced:a,onEdit:d}=t,{t:s}=h.useNiceTranslation();if(!i)return e.jsx("div",{className:"nice-development-studio__placeholder","data-testid":"studio-preview-empty",children:t.emptyText});const o=i.node,u=o.kind==="package"?Tt(o.workspaceId,n.packagesByWs[o.workspaceId],n.modulesByWs[o.workspaceId]??[]):void 0,c=bi(o,{modules:n.modules,packages:u,advanced:a}),l=c?e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"edit",size:14}),onClick:()=>d(c),"data-testid":"studio-edit","data-tour":"devstudio-edit",children:o.kind==="module"?s("devStudio.preview.editSettings","Edit settings"):s("devStudio.preview.edit","Edit")}):null,r="module"in o?n.modules[ee(o.module)]:void 0;if("module"in o&&!r)return e.jsx(ie,{icon:i.icon,title:i.label,children:e.jsx("p",{className:"nice-development-studio__muted",children:s("devStudio.loading","Loading…")})});switch(o.kind){case"workspace":return e.jsx(Ri,{...t,row:i,workspaceId:o.workspaceId});case"package":return e.jsx(Ai,{...t,row:i,workspaceId:o.workspaceId,packageId:o.packageId,editButton:l});case"module":return e.jsx(Li,{...t,row:i,module:r,editButton:l});case"group":return e.jsx(qi,{...t,row:i,module:r,group:o.group});case"entity":return e.jsx(Ji,{...t,row:i,module:r,docKey:o.docKey,index:o.index,editButton:l});case"item":return e.jsx(Gi,{...t,row:i,module:r,node:o,editButton:l});case"document":return e.jsx(Ui,{...t,row:i,module:r,docKey:o.docKey,editButton:l});case"panel":return e.jsx(ie,{icon:i.icon,title:i.label,actions:l});case"file":{const f=r.working.find(j=>j.path===o.path);return e.jsx(ie,{icon:"file",title:i.label,actions:l,children:e.jsx(de,{items:[[s("devStudio.preview.size","Size"),f?`${new TextEncoder().encode(f.text).length} B`:void 0],[s("devStudio.preview.state","State"),i.dirty?s("devStudio.explorer.unsaved","Unsaved changes"):void 0]]})})}case"templates":return e.jsx(ie,{icon:"layers",title:i.label,actions:(p=t.provider)!=null&&p.saveTemplate&&!t.readOnly()?e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:t.onNewTemplate,children:s("devStudio.preview.newTemplate","New template")}):void 0,children:e.jsx(Ne,{rows:i.children??[],onSelect:t.onSelect})});case"category":return e.jsx(ie,{icon:"folder",title:i.label,children:e.jsx(Ne,{rows:i.children??[],onSelect:t.onSelect})});case"template":{const f=(m=n.templates)==null?void 0:m.find(N=>N.id===o.templateId),j=(f==null?void 0:f.translations.en)??Object.values((f==null?void 0:f.translations)??{})[0];return e.jsxs(ie,{icon:i.icon,title:i.label,subtitle:f==null?void 0:f.category,actions:l,children:[(j==null?void 0:j.description)&&e.jsx("p",{children:j.description}),e.jsx(de,{items:[["Id",f==null?void 0:f.id],[s("devStudio.preview.modules","Modules"),String((f==null?void 0:f.modules.length)??0)],[s("devStudio.preview.tags","Tags"),(g=f==null?void 0:f.tags)==null?void 0:g.join(", ")]]}),e.jsx(Ne,{rows:i.children??[],onSelect:t.onSelect,limit:8})]})}case"templateModule":{const f=(v=n.templates)==null?void 0:v.find(N=>N.id===o.templateId),j=f==null?void 0:f.modules.find(N=>N.moduleId===o.moduleId);return e.jsxs(ie,{icon:"box",title:i.label,subtitle:o.moduleId,actions:o.target?e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"arrow-right",size:14}),onClick:()=>t.onReveal({kind:"module",module:o.target}),children:s("devStudio.preview.goToModule","Go to the module")}):void 0,children:[e.jsx(de,{items:[[s("devStudio.preview.required","Required"),j!=null&&j.required?s("devStudio.preview.yes","yes"):void 0],[s("devStudio.preview.condition","Condition"),j==null?void 0:j.condition],[s("devStudio.preview.description","Description"),j==null?void 0:j.description]]}),i.missing&&e.jsx("p",{className:"nice-development-studio__error",children:s("devStudio.preview.missingModule","No project has this module.")})]})}}}function Ri({row:t,workspaceId:i,session:n,provider:a,readOnly:d,canCreateModule:s,onSelect:o,onNewModule:u,onNewPackage:c}){var m;const{t:l}=h.useNiceTranslation(),r=n.workspaces.find(g=>g.id===i),p=!d()&&!(r!=null&&r.readOnly);return e.jsxs(ie,{icon:t.icon,title:t.label,badges:r!=null&&r.readOnly?e.jsx("span",{className:"nice-development-studio__tag",children:l("devStudio.explorer.readOnly","Read-only")}):void 0,actions:p&&(s||a!=null&&a.savePackage)?e.jsxs(e.Fragment,{children:[s&&e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"box",size:14}),onClick:()=>u({workspaceId:i}),children:l("devStudio.preview.newModule","New module")}),(a==null?void 0:a.savePackage)&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"archive",size:14}),onClick:()=>c(i),children:l("devStudio.preview.newPackage","New package")})]}):void 0,children:[(r==null?void 0:r.description)&&e.jsx("p",{children:r.description}),e.jsx(de,{items:[[l("devStudio.preview.packages","Packages"),String(((m=t.children)==null?void 0:m.length)??0)],[l("devStudio.preview.modules","Modules"),t.info]]}),e.jsx(Ne,{rows:t.children??[],onSelect:o})]})}function Ai({row:t,workspaceId:i,packageId:n,session:a,readOnly:d,canCreateModule:s,editButton:o,onSelect:u,onNewModule:c}){var g;const{t:l}=h.useNiceTranslation(),r=(g=a.packagesByWs[i])==null?void 0:g.find(v=>v.id===n),p=a.workspaces.find(v=>v.id===i),m=!d()&&!(p!=null&&p.readOnly);return e.jsxs(ie,{icon:t.icon,title:t.label,subtitle:n,actions:e.jsxs(e.Fragment,{children:[o,m&&s&&e.jsx(h.NiceButton,{size:"sm",variant:o?"ghost":"primary",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:()=>c({workspaceId:i,packageId:n}),children:l("devStudio.preview.newModuleHere","New module here")})]}),children:[(r==null?void 0:r.description)&&e.jsx("p",{children:r.description}),e.jsx(Ne,{rows:t.children??[],onSelect:u})]})}function Li(t){var y;const{row:i,module:n,session:a,preset:d,provider:s,readOnly:o,editButton:u}=t,{t:c}=h.useNiceTranslation(),l=n.key,r=(y=a.modulesByWs[l.workspaceId])==null?void 0:y.find(x=>x.id===l.id),p=o(l),m=t.issues(l),g=(r==null?void 0:r.contents)==="manifest"&&e.jsx("span",{title:c("devStudio.preview.manifestOnly","This provider gives only the manifest"),children:"—"}),v=et(n).length,f=n.documents.filter(x=>x.kind.editor==="views").reduce((x,k)=>x+pe(n,k).length,0),j=new Set(n.documents.filter(x=>x.kind.editor==="i18n").flatMap(x=>Object.keys(ne(n,x)??{}))),N={key:l,files:n.working,documents:n.documents},$=d.newFile?d.kinds.map(x=>{var k;return{kind:x,file:(k=d.newFile)==null?void 0:k.call(d,x.id,N)}}).filter(x=>!!x.file&&!n.working.some(k=>k.path===x.file.path)):[],O=x=>e.jsx(h.NiceIcon,{name:x,size:14}),_=[...s!=null&&s.listRevisions?[{id:"history",icon:O("clock"),label:c("devStudio.overview.history","History"),onClick:()=>t.onEdit({kind:"history",module:l})}]:[],...t.canDuplicateModule&&!o()?[{id:"duplicate",icon:O("copy"),label:c("devStudio.explorer.duplicate","Duplicate"),onClick:()=>t.onModuleAction("duplicate",l)}]:[],...s!=null&&s.saveTemplate&&a.templates&&!o()?[{id:"addToTemplate",icon:O("layers"),label:c("devStudio.explorer.addToTemplate","Add to template"),onClick:()=>t.onModuleAction("addToTemplate",l)}]:[],...p?[]:$.map(({kind:x,file:k})=>({id:`add:${x.id}`,icon:O(x.icon??"plus"),label:`${c("devStudio.preview.add","Add:")} ${x.labelKey?c(x.labelKey,x.label):x.label}`,onClick:()=>a.setRaw(l,k.path,k.text)})),...s!=null&&s.deleteModule&&!p?[{id:"sep",divider:!0},{id:"delete",icon:O("trash"),label:c("devStudio.delete","Delete"),danger:!0,onClick:()=>t.onModuleAction("delete",l)}]:[]];return e.jsxs(ie,{icon:i.icon,title:i.label,subtitle:(r==null?void 0:r.location)??l.id,badges:e.jsxs(e.Fragment,{children:[(r==null?void 0:r.readOnly)&&e.jsx("span",{className:"nice-development-studio__tag",children:c("devStudio.explorer.readOnly","Read-only")}),(r==null?void 0:r.shadowedBy)&&e.jsx("span",{className:"nice-development-studio__tag",title:r.shadowedBy,children:c("devStudio.explorer.shadowed","shadowed")})]}),actions:e.jsxs(e.Fragment,{children:[u,n.dirty&&!p&&e.jsxs(e.Fragment,{children:[e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:O("save"),onClick:()=>t.onSave(l),"data-tour":"devstudio-save",children:c("devStudio.saveCount","Save ({count})").replace("{count}",String(n.changes.length))}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:O("undo"),onClick:()=>a.discard(l),children:c("devStudio.discard","Discard changes")})]}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:O("check"),onClick:()=>void a.validate(l),children:c("devStudio.validate","Validate")}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:O(m.length===0?"success":"warning"),onClick:()=>t.onEdit({kind:"problems",module:l}),children:`${c("devStudio.overview.problems","Problems")} (${m.length})`}),_.length>0&&e.jsx(h.NiceMenu,{className:"nice-development-studio__more",variant:"ghost",size:"sm",fullWidth:!0,items:[{id:"more",icon:O("more-horizontal"),label:c("devStudio.preview.more.actions","More actions"),children:_}]})]}),children:[(r==null?void 0:r.description)&&e.jsx("p",{children:r.description}),e.jsx(de,{items:[["Id",l.id],[c("devStudio.preview.version","Version"),r==null?void 0:r.version],[c("devStudio.preview.entities","Entities"),g||String(v)],[c("devStudio.preview.views","Views"),g||String(f)],[c("devStudio.preview.languages","Languages"),g||[...j].join(", ")],[c("devStudio.preview.state","State"),n.dirty?c("devStudio.status.changed","{count} changed files").replace("{count}",String(n.changes.length)):void 0]]}),m.length>0&&e.jsxs("div",{className:"nice-development-studio__preview-issues",children:[e.jsx("ul",{className:"nice-development-studio__issues",children:m.slice(0,3).map((x,k)=>e.jsx("li",{className:`nice-development-studio__issue nice-development-studio__issue--${x.severity}`,children:e.jsxs("button",{type:"button",className:"nice-development-studio__issue-link",title:c("devStudio.problems.goTo","Go to"),onClick:()=>t.onReveal(Ct(n,x)),children:[e.jsx(h.NiceIcon,{name:x.severity==="error"?"error":x.severity==="warning"?"warning":"info",size:14}),e.jsx("span",{children:Et(c,x)})]})},k))}),m.length>3&&e.jsx("span",{className:"nice-development-studio__muted",children:c("devStudio.preview.more","…and {count} more").replace("{count}",String(m.length-3))})]})]})}function qi({row:t,module:i,group:n,preset:a,session:d,readOnly:s,onSelect:o,onEdit:u}){const{t:c}=h.useNiceTranslation(),r=s(i.key)?void 0:Vi(n,i,a,d);return e.jsx(ie,{icon:t.icon,title:t.label,actions:r?e.jsx(h.NiceButton,{size:"sm",variant:"primary",leftIcon:e.jsx(h.NiceIcon,{name:"plus",size:14}),onClick:()=>u(r.run()),"data-testid":"studio-add",children:r.label(c)}):void 0,children:e.jsx(Ne,{rows:t.children??[],onSelect:o})})}function Vi(t,i,n,a){var r,p;const d=t==="entities"?"entities":t==="views"?"views":t==="workflows"?"workflows":t==="dataSources"?"dataSources":void 0,s=d?i.documents.find(m=>m.kind.editor===d&&m.model!==void 0):void 0;if(!s)return;const o=i.key;if(t==="entities"){const m=ne(i,s)??[],g=((r=n.entities)==null?void 0:r.nameKey)??"name",v=((p=n.entities)==null?void 0:p.fieldsKey)??"fields";return{label:f=>f("devStudio.preview.newEntity","New entity"),run:()=>(a.setDraft(o,s.key,[...m,{[g]:`Entity${m.length+1}`,[v]:[]}]),{kind:"entity",module:o,docKey:s.key,index:m.length})}}if(t==="dataSources"){const m=ne(i,s)??[];return{label:g=>g("devStudio.items.addDataSource","New data source"),run:()=>{const g={key:`source${m.length+1}`,kind:"query",query:{tables:[],joins:[],conditions:[],sorts:[],groupBy:[],distinct:!1},sql:""};return a.setDraft(o,s.key,[...m,g]),{kind:"item",module:o,group:"dataSources",docKey:s.key,itemKey:g.key}}}}const u=pe(i,s),c=u.length+1,l=t==="views"?{id:`view-${c}`,name:`View ${c}`,version:2,columns:12,rows:[],dataSources:[]}:{id:`workflow-${c}`,name:`Workflow ${c}`,entityType:"",version:1,states:[],transitions:[]};return{label:m=>t==="views"?m("devStudio.items.addView","New view"):m("devStudio.items.addWorkflow","New workflow"),run:()=>{const m={key:l.id,label:l.name,definition:l,source:l};return a.setDraft(o,s.key,[...u,m]),{kind:"item",module:o,group:t,docKey:s.key,itemKey:l.id}}}}const Wi=[["isPrimaryKey","PK","Primary key"],["isForeignKey","FK","Foreign key"],["isRequired","Req","Required"]];function Ji({row:t,module:i,docKey:n,index:a,preset:d,session:s,readOnly:o,editButton:u,onReveal:c}){var j;const{t:l}=h.useNiceTranslation(),r=me(i,n),p=r?ne(i,r):void 0,m=Array.isArray(p)?p[a]:void 0;if(!r||!p||!m)return e.jsx(ie,{icon:"table",title:t.label,children:e.jsx("p",{className:"nice-development-studio__muted",children:l("devStudio.edit.gone","This is no longer in the module.")})});const g=((j=d.entities)==null?void 0:j.fieldsKey)??"fields",v=Array.isArray(m[g])?m[g]:[],f=o(i.key);return e.jsxs(ie,{icon:"table",title:tt(m)||t.label,subtitle:String(m.name??""),badges:e.jsxs(e.Fragment,{children:[!!m.isAudited&&e.jsx("span",{className:"nice-development-studio__tag",children:l("entityEditor.flag.audited.abbr","Audit")}),!!m.isSoftDeleteEnabled&&e.jsx("span",{className:"nice-development-studio__tag",children:l("entityEditor.flag.softDelete.abbr","Soft-del")})]}),actions:e.jsxs(e.Fragment,{children:[u,!f&&e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:"trash",size:14}),onClick:()=>{s.setDraft(i.key,r.key,it(p,a,null)),c({kind:"group",module:i.key,group:"entities"})},children:l("devStudio.delete","Delete")})]}),children:[typeof m.description=="string"&&m.description&&e.jsx("p",{children:m.description}),e.jsx(de,{items:[[l("entityEditor.col.table","Table"),m.tableName],[l("entityEditor.col.fields","Fields"),String(v.length)]]}),v.length>0&&e.jsx("table",{className:"nice-development-studio__table nice-development-studio__preview-fields",children:e.jsx("tbody",{children:v.slice(0,8).map((N,$)=>e.jsxs("tr",{children:[e.jsx("td",{children:String(N.name??"")}),e.jsx("td",{className:"nice-development-studio__muted",children:String(N.dataType??N.type??"")}),e.jsx("td",{children:Wi.filter(([O])=>N[O]||O==="isRequired"&&N.required).map(([,O,_])=>e.jsx("span",{className:"nice-development-studio__tag",title:_,children:O},O))})]},$))})}),v.length>8&&e.jsx("span",{className:"nice-development-studio__muted",children:l("devStudio.preview.more","…and {count} more").replace("{count}",String(v.length-8))})]})}function Gi({row:t,module:i,node:n,advanced:a,renderViewPreview:d,editButton:s}){var m,g,v,f;const{t:o}=h.useNiceTranslation(),u=me(i,n.docKey),c=u?pe(i,u).find(j=>j.key===n.itemKey):void 0;if(!c)return e.jsx(ie,{icon:t.icon,title:t.label,children:e.jsx("p",{className:"nice-development-studio__muted",children:o("devStudio.edit.gone","This is no longer in the module.")})});const l=c.source??{},r=c.definition??{},p=n.group==="views"?[["Id",c.key],[o("devStudio.preview.type","Type"),l.viewType??l.type??l.kind],[o("devStudio.preview.entity","Entity"),l.entityName??l.entity],[o("devStudio.preview.columns","Columns"),(m=Ce(l.columns))==null?void 0:m.toString()],[o("devStudio.preview.rows","Rows"),(g=Ce(r.rows))==null?void 0:g.toString()]]:n.group==="workflows"?[["Id",c.key],[o("devStudio.preview.states","States"),(v=Ce(r.states??l.states))==null?void 0:v.toString()],[o("devStudio.preview.transitions","Transitions"),(f=Ce(r.transitions??l.transitions))==null?void 0:f.toString()]]:[[o("devStudio.preview.key","Key"),c.key],[o("devStudio.preview.type","Type"),r.kind??void 0]];return e.jsxs(ie,{icon:t.icon,title:c.label||c.key,badges:c.definition===void 0?e.jsx("span",{className:"nice-development-studio__tag",children:o("devStudio.tree.noForm","no designer")}):void 0,actions:s,children:[e.jsx(de,{items:p}),c.definition===void 0&&e.jsx("p",{className:"nice-development-studio__muted",children:a?o("devStudio.preview.noDesignerAdvanced","There is no designer for this kind of entry yet; edit its source."):o("devStudio.preview.noDesigner","There is no designer for this kind of entry yet.")}),n.group==="views"&&d&&e.jsx("div",{className:"nice-development-studio__preview-view",children:d({module:i.key,item:c,files:i.working})})]})}function Ui({row:t,module:i,docKey:n,advanced:a,editButton:d}){var l;const{t:s}=h.useNiceTranslation(),o=me(i,n);if(!o)return e.jsx(ie,{icon:t.icon,title:t.label,children:e.jsx("p",{className:"nice-development-studio__muted",children:s("devStudio.edit.gone","This is no longer in the module.")})});const u=ne(i,o);let c=null;if(o.model===void 0)c=e.jsxs("p",{className:"nice-development-studio__error",role:"alert",children:[a?s("devStudio.doc.unreadable","This file could not be read as its kind; edit its source."):s("devStudio.preview.unreadable","This file does not read; saving leaves it as it is. Fix it in the advanced mode.")," ",o.error]});else if(o.kind.editor==="i18n"){const r=u??{},p=Math.max(0,...Object.values(r).map(m=>Object.keys(m??{}).length));c=e.jsx(de,{items:Object.entries(r).map(([m,g])=>{const v=Object.keys(g??{}).length;return[m,v<p?s("devStudio.preview.keysMissing","{count} keys, {missing} missing").replace("{count}",String(v)).replace("{missing}",String(p-v)):s("devStudio.preview.keys","{count} keys").replace("{count}",String(v))]})})}else if(o.kind.editor==="permissions"){const r=u??{permissions:[],groups:[]};c=e.jsx(de,{items:[[s("devStudio.permissions.codes","Permissions"),String(r.permissions.length)],[s("devStudio.permissions.groups","Groups"),String(r.groups.length)]]})}else if(o.kind.editor==="seeds"){const r=u??{seeds:{}};c=e.jsx(de,{items:Object.entries(r.seeds??{}).map(([p,m])=>[p,s("devStudio.preview.rowsCount","{count} rows").replace("{count}",String(m.length))])})}else o.kind.editor==="hooks"?c=e.jsx(de,{items:[[s("devStudio.preview.bindings","Bindings"),(l=Ce(u))==null?void 0:l.toString()]]}):o.kind.editor==="script"&&(c=e.jsx(de,{items:[[s("devStudio.preview.lines","Lines"),String(String(u??"").split(`
6
+ `).length)]]}));return e.jsx(ie,{icon:t.icon,title:t.label,subtitle:o.paths.join(", "),actions:d,children:c})}function Hi({tree:t,selected:i,expanded:n,onExpandedChange:a,onSelect:d,loadModule:s,newItems:o,actions:u,onRefresh:c,tutorialButton:l,emptyText:r,minWidth:p}){const{t:m}=h.useNiceTranslation(),g=b.useMemo(()=>[{field:"label",header:m("devStudio.explorer.name","Name"),render:(f,j)=>e.jsxs("span",{className:"nice-development-studio__tree-name",style:{maxWidth:`calc(100% - ${(j.depth??0)*20+28}px)`},children:[e.jsx(h.NiceIcon,{name:j.icon,size:14}),e.jsx("span",{className:`nice-development-studio__tree-label${j.missing?" nice-development-studio__missing":""}`,title:j.label,children:j.label}),j.dirty&&e.jsx("span",{className:"nice-development-studio__dot",title:m("devStudio.explorer.unsaved","Unsaved changes"),children:e.jsx(h.NiceIcon,{name:"circle",size:8})}),!!j.issues&&e.jsx("span",{className:"nice-development-studio__badge",title:m("devStudio.explorer.problems","Problems"),children:j.issues}),j.readOnly&&e.jsx("span",{title:m("devStudio.explorer.readOnly","Read-only"),children:e.jsx(h.NiceIcon,{name:"lock",size:12})}),j.noForm&&e.jsx("span",{className:"nice-development-studio__tag",children:m("devStudio.tree.noForm","no designer")}),j.shadowedBy&&e.jsx("span",{className:"nice-development-studio__tag",title:j.shadowedBy,children:m("devStudio.explorer.shadowed","shadowed")}),j.missing&&e.jsx("span",{className:"nice-development-studio__tag",children:m("devStudio.explorer.missing","missing")})]})},{field:"info",header:"",width:56,align:"right"}],[m]),v=e.jsxs("div",{className:"nice-development-studio__tree-actions",children:[o.length>0&&e.jsx(h.NiceMenu,{variant:"ghost",size:"sm",items:[{id:"new",label:m("devStudio.tree.new","New"),icon:e.jsx(h.NiceIcon,{name:"plus",size:14}),children:o}],"data-testid":"studio-new-menu"}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",ariaLabel:m("devStudio.refresh","Refresh"),onClick:c,children:e.jsx(h.NiceIcon,{name:"refresh",size:14})}),u==null?void 0:u.map(f=>e.jsx(h.NiceButton,{size:"sm",variant:"ghost",disabled:f.disabled,leftIcon:f.icon?e.jsx(h.NiceIcon,{name:f.icon,size:14}):void 0,onClick:f.onSelect,children:f.label},f.key)),l&&e.jsx("span",{className:"nice-development-studio__spacer"}),l]});return e.jsx("div",{className:"nice-development-studio__tree","data-tour":"devstudio-explorer",style:{minWidth:p},children:e.jsx(h.NiceTreeGrid,{data:t.rows,nested:!0,keyField:"id",childrenField:"children",columns:g,sortable:!1,compact:!0,searchable:!0,searchFields:["label","search"],searchPlaceholder:m("devStudio.tree.search","Search modules, entities and views"),toolbar:v,toolbarActions:["collapseAll"],expandedKeys:n,onExpandedChange:a,hasChildren:f=>f.node.kind==="module"&&!f.children,loadChildren:async f=>(f.node.kind==="module"&&await s(f.node.module),[]),onRowClick:d,rowClassName:f=>f.id===i?"nice-development-studio__tree-row--selected":void 0,emptyText:r,"aria-label":m("devStudio.explorer.modules","Modules"),"data-testid":"studio-tree"})})}const Yi=[{target:".nice-development-studio",titleKey:"tutorial.devStudio.intro.title",title:"Development studio",contentKey:"tutorial.devStudio.intro.content",content:"Design whole modules: their settings, entities, views, workflows, translations, permissions, data sources and seed data. Saving writes back only what changed.",placement:"auto"},{target:'[data-tour="devstudio-explorer"]',titleKey:"tutorial.devStudio.explorer.title",title:"Projects, packages and modules",contentKey:"tutorial.devStudio.explorer.content",content:"Browse projects, their packages and modules. Open a module to see its entities, views, translations and the rest; under Templates are the module sets installed together.",placement:"right"},{target:'[data-testid="studio-preview"]',titleKey:"tutorial.devStudio.preview.title",title:"A short preview",contentKey:"tutorial.devStudio.preview.content",content:"Pick a row in the tree to see a short preview of it here.",placement:"left"},{target:'[data-tour="devstudio-edit"]',titleKey:"tutorial.devStudio.edit.title",title:"Edit on the whole screen",contentKey:"tutorial.devStudio.edit.content",content:"Edit opens the form of what you picked on the whole studio. Back, or a step of the trail, brings you back to the tree.",placement:"bottom"},{target:'[data-tour="devstudio-save"]',titleKey:"tutorial.devStudio.save.title",title:"Validate and save",contentKey:"tutorial.devStudio.save.content",content:"Check the module, review the changed files and save them — only the bytes you changed are written.",placement:"bottom"}],Xi=["en","pl","de","fr","es","uk"],Zi=b.forwardRef(function(i,n){var at,dt;const{provider:a,preset:d,defaultModule:s,defaultExplorerTab:o="modules",displayMode:u="standard",actions:c,onModuleOpen:l,onSaved:r,onError:p,reviewBeforeSave:m=!0,scriptRunner:g,renderViewPreview:v,modulePanels:f,readOnly:j=!1,height:N=720,explorerWidth:$=320,previewWidth:O=260,tutorial:_,className:y,style:x,id:k,testId:M,"data-testid":V}=i,{t:D}=h.useNiceTranslation(),G=b.useRef(null);b.useImperativeHandle(n,()=>G.current);const te=u==="advanced",Q=b.useMemo(()=>typeof d=="function"?d(D):d??P.nativeStudioPreset,[d,D]),H=b.useMemo(()=>Q.locales??Xi,[Q]),C=vi(a,Q,{locales:H,onError:p,t:D}),{openModule:E}=C,[B,L]=b.useState(""),[Z,U]=b.useState([]),[z,Y]=b.useState(null),[le,je]=b.useState(null),[q,w]=b.useState(null),I=b.useCallback(S=>{var K;return(K=C.modulesByWs[S.workspaceId])==null?void 0:K.find(W=>W.id===S.id)},[C.modulesByWs]),T=S=>{var K;return((K=I(S))==null?void 0:K.label)??S.id},F=b.useMemo(()=>{const S={};for(const[K,W]of Object.entries(C.modules))S[K]=[...wt(W,Q),...C.serverIssues[K]??[]];return S},[C.modules,C.serverIssues,Q]),R=b.useCallback(S=>F[ee(S)]??[],[F]),J=b.useMemo(()=>Object.fromEntries(Object.entries(F).map(([S,K])=>[S,K.filter(W=>W.severity==="error").length])),[F]),X=b.useCallback(S=>{var W;if(j)return!0;if(!S)return!1;const K=C.workspaces.find(ge=>ge.id===S.workspaceId);return!!(K!=null&&K.readOnly)||!!((W=I(S))!=null&&W.readOnly)},[j,C.workspaces,I]),A=b.useMemo(()=>ki({workspaces:C.workspaces,modulesByWs:C.modulesByWs,packagesByWs:C.packagesByWs,templates:C.templates,modules:C.modules,issueCounts:J,panels:f?S=>f({module:S.key,files:S.working,dirty:S.dirty}):void 0,advanced:te,t:D}),[C.workspaces,C.modulesByWs,C.packagesByWs,C.templates,C.modules,J,f,te,D]),oe=b.useRef(!1);b.useEffect(()=>{if(!oe.current&&C.workspaces.length>0){oe.current=!0;const S=C.workspaces.map(K=>`w:${K.id}`);o==="templates"&&(S.push(Oe),L(Oe)),U(K=>[...new Set([...K,...S])])}},[C.workspaces,o]);const re=b.useCallback(S=>{const K=vt(A,S).map(W=>W.id);U(W=>[...new Set([...W,...K])]),L(S)},[A]),ce=b.useCallback(S=>{Y(null);const K=Ke(S);K&&!C.modules[ee(K)]&&E(K),je(S)},[C.modules,E]);b.useEffect(()=>{if(!le)return;const S=We(A,le);if(S){re(S),je(null);return}const K=Ke(le);if(K&&C.modules[ee(K)]){const W=We(A,{kind:"module",module:K});W&&re(W),je(null)}},[le,A,re,C.modules]);const se=b.useCallback(S=>{L(S.id);const K=Ke(S.node);K&&!C.modules[ee(K)]&&E(K),S.node.kind==="module"&&(l==null||l(S.node.module))},[C.modules,E,l]),Fe=b.useCallback(S=>{const K=A.byId.get(S);K&&(se(K),re(S))},[A,se,re]),fe=b.useRef(!1);b.useEffect(()=>{s&&!fe.current&&C.modulesByWs[s.workspaceId]&&(fe.current=!0,E(s).then(()=>l==null?void 0:l(s)),je({kind:"module",module:s}))},[s,C.modulesByWs,E,l]);const he=A.byId.get(B),ue=z?"module"in z?z.module:void 0:he?Ke(he.node):void 0,$e=b.useCallback(async S=>{const K=C.modules[ee(S)];if(!(K!=null&&K.dirty)||X(S))return;if(m){w({kind:"review",module:S});return}const W=await C.save(S);W&&!W.ok?w({kind:"review",module:S,conflict:W}):W!=null&&W.ok&&(r==null||r(S,W))},[C,X,m,r]),nt=b.useRef(()=>{});nt.current=()=>{ue&&$e(ue)},b.useEffect(()=>{const S=G.current;if(!S)return;const K=W=>{(W.ctrlKey||W.metaKey)&&!W.altKey&&W.key.toLowerCase()==="s"&&(W.preventDefault(),nt.current())};return S.addEventListener("keydown",K),()=>S.removeEventListener("keydown",K)},[]);const Mt=()=>{const S=z?ft(z):void 0;S?ce(S):Y(null)},Kt=b.useMemo(()=>{if(!z)return[];const S=ft(z),K=S?We(A,S):void 0,W=K?vt(A,K):[],ge=z.kind==="manifest"?D("devStudio.edit.settings","Settings"):z.kind==="problems"?D("devStudio.overview.problems","Problems"):z.kind==="history"?D("devStudio.overview.history","History"):z.kind==="template"&&!z.templateId?D("devStudio.template.new","New template"):void 0,ye=W.map(rt=>({label:rt.label,onClick:()=>{Y(null),re(rt.id)}}));return ge?ye.push({label:ge}):ye.length>0&&(ye[ye.length-1]={label:ye[ye.length-1].label}),ye},[z,A,re,D]),st=!!(a!=null&&a.createModule)&&!!Q.generateModule,Ot=!!(a!=null&&a.createModule)&&!!Q.duplicateModule,Ie=C.workspaces.filter(S=>!S.readOnly).map(S=>({id:S.id,label:S.label})),ae=he==null?void 0:he.node,Be=ae&&"workspaceId"in ae?ae.workspaceId:ae&&"module"in ae?ae.module.workspaceId:void 0,Ft=(ae==null?void 0:ae.kind)==="package"?ae.packageId:ae&&"module"in ae?(at=I(ae.module))==null?void 0:at.packageId:void 0,Te=Ie.some(S=>S.id===Be)?Be:(dt=Ie[0])==null?void 0:dt.id,$t=j?[]:[...st&&Te?[{id:"module",label:D("devStudio.tree.newModule","Module…"),icon:e.jsx(h.NiceIcon,{name:"box",size:14}),onClick:()=>w({kind:"wizard",prefill:{workspaceId:Te,packageId:Te===Be?Ft:void 0}})}]:[],...a!=null&&a.savePackage&&Te?[{id:"package",label:D("devStudio.tree.newPackage","Package…"),icon:e.jsx(h.NiceIcon,{name:"archive",size:14}),onClick:()=>w({kind:"package",workspaceId:Te})}]:[],...a!=null&&a.saveTemplate&&C.templates?[{id:"template",label:D("devStudio.tree.newTemplate","Template"),icon:e.jsx(h.NiceIcon,{name:"layers",size:14}),onClick:()=>Y({kind:"template",templateId:null})}]:[]],Bt=(S,K)=>{w(S==="delete"?{kind:"delete",module:K}:S==="duplicate"?{kind:"duplicate",module:K}:{kind:"templates",module:K})},ot=_?e.jsx(h.NiceTutorialButton,{steps:h.resolveTutorial(_,Yi)}):void 0,Ee=ue?C.modules[ee(ue)]:void 0,ze=ue?R(ue):[],De=C.logs[C.logs.length-1],zt=e.jsxs("div",{className:"nice-development-studio__statusbar",role:"status",children:[ue&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:T(ue)}),e.jsx("span",{children:Ee!=null&&Ee.dirty?D("devStudio.status.changed","{count} changed files").replace("{count}",String(Ee.changes.length)):D("devStudio.status.saved","Saved")}),e.jsx(h.NiceButton,{size:"sm",variant:"ghost",leftIcon:e.jsx(h.NiceIcon,{name:ze.length===0?"check":"warning",size:12}),onClick:()=>Y({kind:"problems",module:ue}),children:ze.length===0?D("devStudio.status.valid","No problems"):D("devStudio.status.problems","{count} problems").replace("{count}",String(ze.length))})]}),e.jsx("span",{className:"nice-development-studio__spacer"}),C.busy?e.jsx("span",{children:D("devStudio.loading","Loading…")}):De&&e.jsx("span",{className:`nice-development-studio__status-message nice-development-studio__status-message--${De.level}`,children:De.message})]}),Pe=(q==null?void 0:q.kind)==="review"?C.modules[ee(q.module)]:void 0,Dt=`nice-development-studio${y?` ${y}`:""}`,Pt=a?D("devStudio.preview.empty","Pick a module, an entity or a view in the tree."):D("devStudio.noProvider","Connect a provider to browse modules.");return e.jsxs("div",{ref:G,id:k,className:Dt,style:{height:N,...x},"data-testid":V??M,children:[e.jsx(h.NiceAppShell,{className:"nice-development-studio__shell",height:"100%",rightSidebar:z?void 0:e.jsx(Pi,{row:he,tree:A,session:C,preset:Q,provider:a,readOnly:X,advanced:te,issues:R,canCreateModule:st,canDuplicateModule:Ot,renderViewPreview:v,emptyText:Pt,onSelect:Fe,onEdit:Y,onReveal:ce,onSave:S=>void $e(S),onNewModule:S=>w({kind:"wizard",prefill:S}),onNewPackage:S=>w({kind:"package",workspaceId:S}),onNewTemplate:()=>Y({kind:"template",templateId:null}),onModuleAction:Bt}),rightSidebarWidth:O,statusBar:zt,bottomPanel:te?e.jsx("div",{"data-tour":"devstudio-output",className:"nice-development-studio__output",children:e.jsx(h.NiceLogConsole,{title:D("devStudio.output","Output"),entries:C.logs,onClear:C.clearLogs,maxHeight:"100%"})}):void 0,bottomPanelHeight:te?140:void 0,children:z?e.jsx(Oi,{screen:z,crumbs:Kt,session:C,preset:Q,provider:a,locales:H,readOnly:X,advanced:te,issues:R,scriptRunner:g,renderViewPreview:v,modulePanels:f,tutorialButton:ot,onBack:Mt,onSave:S=>void $e(S),onReveal:ce,onScreen:Y,onNewModule:S=>w({kind:"wizard",prefill:S})}):e.jsx(Hi,{tree:A,selected:B,expanded:Z,onExpandedChange:U,onSelect:se,loadModule:async S=>{await E(S)},newItems:$t,actions:c,onRefresh:()=>void C.refresh(),tutorialButton:ot,minWidth:$,emptyText:a?D("devStudio.explorer.empty","No modules."):D("devStudio.noProvider","Connect a provider to browse modules.")})}),(q==null?void 0:q.kind)==="wizard"&&e.jsx(li,{open:!0,onClose:()=>w(null),session:C,preset:Q,locales:H,prefill:q.prefill,onCreated:S=>{l==null||l(S),ce({kind:"module",module:S})}}),(q==null?void 0:q.kind)==="review"&&Pe&&e.jsx(ci,{open:!0,moduleLabel:T(q.module),changes:Pe.changes,original:S=>{var K;return((K=Pe.files.find(W=>W.path===S))==null?void 0:K.text)??""},conflict:q.conflict,onClose:()=>w(null),onSave:async()=>{const S=await C.save(q.module);S!=null&&S.ok?(w(null),r==null||r(q.module,S)):S&&w({...q,conflict:S})},onOverwrite:async()=>{const S=await C.save(q.module,{force:!0});S!=null&&S.ok&&(w(null),r==null||r(q.module,S))},onReload:async()=>{await C.reload(q.module),w(null)}}),(q==null?void 0:q.kind)==="delete"&&e.jsx(h.NiceConfirmDialog,{visible:!0,variant:"warning",header:D("devStudio.delete.title","Delete module"),message:D("devStudio.delete.message","Delete {module} and all its files?").replace("{module}",T(q.module)),acceptLabel:D("devStudio.delete","Delete"),rejectLabel:D("devStudio.cancel","Cancel"),onReject:()=>w(null),onAccept:async()=>{const S=q.module;w(null),await C.deleteModule(S)&&(Y(null),L(`w:${S.workspaceId}`))}}),(q==null?void 0:q.kind)==="duplicate"&&e.jsx(mt,{open:!0,title:D("devStudio.duplicate.title","Duplicate {module}").replace("{module}",T(q.module)),workspaces:Ie,workspaceId:Ie.some(S=>S.id===q.module.workspaceId)?q.module.workspaceId:void 0,idLabel:D("devStudio.duplicate.id","New module id"),initialId:`${q.module.id}Copy`,onClose:()=>w(null),onSubmit:async S=>{var ge;const K=q.module;w(null);const W=await C.duplicateModule(K,{workspaceId:S.workspaceId,id:S.id,packageId:(ge=I(K))==null?void 0:ge.packageId});W&&ce({kind:"module",module:{workspaceId:W.workspaceId,id:W.id}})}}),(q==null?void 0:q.kind)==="package"&&e.jsx(mt,{open:!0,title:D("devStudio.package.new","New package"),workspaces:Ie,workspaceId:q.workspaceId,idLabel:D("devStudio.package.id","Id"),withLabel:!0,onClose:()=>w(null),onSubmit:async S=>{w(null);const K=await C.savePackage({id:S.id,workspaceId:S.workspaceId,label:S.label});K&&ce({kind:"package",workspaceId:K.workspaceId,packageId:K.id})}}),(q==null?void 0:q.kind)==="templates"&&C.templates&&e.jsx(ui,{open:!0,moduleId:q.module.id,templates:C.templates,onClose:()=>w(null),onApply:async S=>{w(null);for(const K of S)await C.saveTemplate(K,K.id)}})]})});exports.arrayFileKind=P.arrayFileKind;exports.buildDocuments=P.buildDocuments;exports.createMemoryStudioProvider=P.createMemoryStudioProvider;exports.defineManifestSection=P.defineManifestSection;exports.deriveDefaultRbac=P.deriveDefaultRbac;exports.detectJsonTextFormat=P.detectJsonTextFormat;exports.encodeDocument=P.encodeDocument;exports.endsWithAny=P.endsWithAny;exports.entitiesToSchemas=P.entitiesToSchemas;exports.fileName=P.fileName;exports.fitManifestSection=P.fitManifestSection;exports.i18nFileKind=P.i18nFileKind;exports.itemsFileKind=P.itemsFileKind;exports.jsonFallbackKind=P.jsonFallbackKind;exports.jsonFileKind=P.jsonFileKind;exports.jsonValueFitsSchema=P.jsonValueFitsSchema;exports.jsonValuesEqual=P.jsonValuesEqual;exports.keepTextFormat=P.keepTextFormat;exports.manifestSectionKeys=P.manifestSectionKeys;exports.modulePrefix=P.modulePrefix;exports.nativeDataSourcesKind=P.nativeDataSourcesKind;exports.nativeEntitiesKind=P.nativeEntitiesKind;exports.nativeFileKinds=P.nativeFileKinds;exports.nativeHooksKind=P.nativeHooksKind;exports.nativeI18nKind=P.nativeI18nKind;exports.nativeManifestKind=P.nativeManifestKind;exports.nativeRbacKind=P.nativeRbacKind;exports.nativeStudioPreset=P.nativeStudioPreset;exports.nativeViewsKind=P.nativeViewsKind;exports.nativeWorkflowsKind=P.nativeWorkflowsKind;exports.objectFileKind=P.objectFileKind;exports.parseJsonText=P.parseJsonText;exports.patchJsonText=P.patchJsonText;exports.patchJsonTextDetailed=P.patchJsonTextDetailed;exports.readTranslations=P.readTranslations;exports.resolveFileKind=P.resolveFileKind;exports.safeJson=P.safeJson;exports.slugifyModuleId=P.slugifyModuleId;exports.stringifyJsonText=P.stringifyJsonText;exports.textFallbackKind=P.textFallbackKind;exports.writeTranslations=P.writeTranslations;exports.NiceArrayField=Ye;exports.NiceDevelopmentStudio=Zi;exports.NiceEntityEditor=jt;exports.NiceEntityForm=Xe;exports.NiceI18nEditor=Qe;exports.NiceSchemaForm=_e;exports.aiFormConfigToFormFields=Wt;exports.aiFormFieldType=xt;exports.formBuilderSchemaToNiceFormItems=At;exports.formFieldsToFormItems=Ue;exports.formSchemaToJsonSchema=Ht;exports.jsonSchemaToFormItems=Ge;exports.schemaToFormItems=Lt;exports.validateAgainstJsonSchema=He;exports.validateFormSchema=qt;
package/dist/index.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  import { jsx as t, jsxs as _, Fragment as le } from "react/jsx-runtime";
2
2
  import { useNiceTranslation as zt, useControllableState as li, NiceTutorialButton as ci, resolveTutorial as ui, NiceIcon as _t } from "@nice2dev/ui-core";
3
3
  import mi, { useState as W, forwardRef as ze, useMemo as H, useEffect as ge, useRef as Te, useCallback as Z, useImperativeHandle as pi } from "react";
4
- import { useControllableState as Ae, NiceIcon as L, NiceDataGrid as rt, useNiceTranslation as G, evaluateValidation as Ft, NiceTutorialButton as lt, resolveTutorial as ct, NiceTooltip as Se, NiceForm as hi, NiceValidationBuilder as vi, NiceTabs as We, NiceBadge as De, NiceButton as F, NiceCheckbox as Ve, NiceSelect as ut, NiceTextInput as Ke, NiceModal as Ge, NiceWizard as fi, NiceTreeGrid as mt, NiceSimpleCodeEditor as Je, NiceScriptRunner as gi, NiceLifecycleHooksEditor as yi, NiceAccessManager as ki, NicePermissionMatrix as bi, NiceBreadcrumb as wi, NiceRevisionHistory as Si, NiceDataSourceBuilder as _i, NiceWorkflowDesigner as Ni, NiceViewEditor as Ii, NiceMenu as Pt, NiceAppShell as Ci, NiceLogConsole as Ti, NiceConfirmDialog as Ei } from "@nice2dev/ui";
5
- import { fitManifestSection as jt, buildDocuments as xi, keepTextFormat as Oi, entitiesToSchemas as $i, nativeStudioPreset as Ki } from "./studio.mjs";
6
- import { arrayFileKind as to, createMemoryStudioProvider as io, defineManifestSection as no, deriveDefaultRbac as oo, detectJsonTextFormat as so, encodeDocument as ao, endsWithAny as ro, fileName as lo, i18nFileKind as co, itemsFileKind as uo, jsonFallbackKind as mo, jsonFileKind as po, jsonValueFitsSchema as ho, jsonValuesEqual as vo, manifestSectionKeys as fo, modulePrefix as go, nativeDataSourcesKind as yo, nativeEntitiesKind as ko, nativeFileKinds as bo, nativeHooksKind as wo, nativeI18nKind as So, nativeManifestKind as _o, nativeRbacKind as No, nativeViewsKind as Io, nativeWorkflowsKind as Co, objectFileKind as To, parseJsonText as Eo, patchJsonText as xo, patchJsonTextDetailed as Oo, readTranslations as $o, resolveFileKind as Ko, safeJson as Mo, slugifyModuleId as zo, stringifyJsonText as Fo, textFallbackKind as Po, writeTranslations as jo } from "./studio.mjs";
7
- function Un(e) {
4
+ import { useControllableState as Ae, NiceIcon as L, NiceDataGrid as rt, useNiceTranslation as G, evaluateValidation as Ft, NiceTutorialButton as lt, resolveTutorial as ct, NiceTooltip as Se, NiceForm as hi, NiceValidationBuilder as vi, NiceTabs as We, NiceBadge as De, NiceButton as F, NiceCheckbox as Ve, NiceSelect as ut, NiceTextInput as Ke, NiceModal as Ge, NiceWizard as fi, NiceTreeGrid as mt, NiceSimpleCodeEditor as Je, NiceScriptRunner as gi, NiceLifecycleHooksEditor as yi, NiceAccessManager as ki, NicePermissionMatrix as bi, NiceBreadcrumb as wi, NiceRevisionHistory as Si, NiceDataSourceBuilder as _i, NiceViewEditor as Ni, NiceMenu as Pt, NiceAppShell as Ii, NiceLogConsole as Ci, NiceConfirmDialog as Ti } from "@nice2dev/ui";
5
+ import { fitManifestSection as jt, buildDocuments as Ei, keepTextFormat as xi, entitiesToSchemas as Oi, nativeStudioPreset as $i } from "./studio.mjs";
6
+ import { arrayFileKind as io, createMemoryStudioProvider as no, defineManifestSection as oo, deriveDefaultRbac as so, detectJsonTextFormat as ao, encodeDocument as ro, endsWithAny as lo, fileName as co, i18nFileKind as uo, itemsFileKind as mo, jsonFallbackKind as po, jsonFileKind as ho, jsonValueFitsSchema as vo, jsonValuesEqual as fo, manifestSectionKeys as go, modulePrefix as yo, nativeDataSourcesKind as ko, nativeEntitiesKind as bo, nativeFileKinds as wo, nativeHooksKind as So, nativeI18nKind as _o, nativeManifestKind as No, nativeRbacKind as Io, nativeViewsKind as Co, nativeWorkflowsKind as To, objectFileKind as Eo, parseJsonText as xo, patchJsonText as Oo, patchJsonTextDetailed as $o, readTranslations as Ko, resolveFileKind as Mo, safeJson as zo, slugifyModuleId as Fo, stringifyJsonText as Po, textFallbackKind as jo, writeTranslations as Do } from "./studio.mjs";
7
+ import { NiceWorkflowDesigner as Ki } from "@nice2dev/ui-diagrams";
8
+ function Gn(e) {
8
9
  var a, d;
9
10
  const i = {
10
11
  text: "text",
@@ -86,7 +87,7 @@ function Nt(e) {
86
87
  helpText: e.helpText
87
88
  };
88
89
  }
89
- function Gn(e) {
90
+ function Hn(e) {
90
91
  const i = [];
91
92
  for (const n of e.sections)
92
93
  n.title ? i.push({
@@ -97,7 +98,7 @@ function Gn(e) {
97
98
  }) : i.push(...n.fields.map(Nt));
98
99
  return i;
99
100
  }
100
- function Hn(e) {
101
+ function Yn(e) {
101
102
  const i = [];
102
103
  e.version || i.push("Missing schema version"), e.id || i.push("Missing form ID"), (!e.sections || e.sections.length === 0) && i.push("Form must have at least one section");
103
104
  const n = /* @__PURE__ */ new Set();
@@ -142,7 +143,7 @@ const Mi = {
142
143
  function zi(e) {
143
144
  return Mi[String(e ?? "").toLowerCase()] ?? "text";
144
145
  }
145
- function Yn(e) {
146
+ function Xn(e) {
146
147
  return (Array.isArray(e) ? e : e.fields).map((n, a) => {
147
148
  const d = n.name ?? n.field ?? n.id ?? `field${a + 1}`, o = n.validation ?? {}, s = [], u = (c, l) => {
148
149
  l !== void 0 && s.push({ type: c, value: l, ...o.message ? { message: o.message } : {} });
@@ -226,7 +227,7 @@ function ji(e) {
226
227
  enum: e.options.map((a) => typeof a == "string" ? a : String(a.value))
227
228
  }), Pi(n, e.validations), n;
228
229
  }
229
- function Xn(e) {
230
+ function Zn(e) {
230
231
  const i = {}, n = [], a = (o) => {
231
232
  var s;
232
233
  for (const u of o) {
@@ -1942,7 +1943,7 @@ function st(e, i, n) {
1942
1943
  a.has(m.path) || d.set(m.path, e.raw[m.path] !== void 0 ? { ...m, text: e.raw[m.path] } : m);
1943
1944
  for (const [m, f] of Object.entries(e.raw))
1944
1945
  !d.has(m) && !a.has(m) && d.set(m, { path: m, text: f });
1945
- const o = [...d.values()], s = { moduleId: e.key.id, files: o, locales: n }, u = xi(i.kinds, o, s), c = new Map(o.map((m) => [m.path, m.text])), l = {};
1946
+ const o = [...d.values()], s = { moduleId: e.key.id, files: o, locales: n }, u = Ei(i.kinds, o, s), c = new Map(o.map((m) => [m.path, m.text])), l = {};
1946
1947
  for (const m of u)
1947
1948
  if (m.key in e.drafts)
1948
1949
  try {
@@ -3270,7 +3271,7 @@ function yn({
3270
3271
  onChange: (p) => n.setRaw(
3271
3272
  e.key,
3272
3273
  i,
3273
- Oi(p, e.pending.get(i)),
3274
+ xi(p, e.pending.get(i)),
3274
3275
  c
3275
3276
  )
3276
3277
  }
@@ -3842,7 +3843,7 @@ function Cn({
3842
3843
  _i,
3843
3844
  {
3844
3845
  value: v,
3845
- schemas: $i(dt(i)),
3846
+ schemas: Oi(dt(i)),
3846
3847
  onChange: (b) => {
3847
3848
  n.setDraft(
3848
3849
  i.key,
@@ -3886,7 +3887,7 @@ function Cn({
3886
3887
  ] }) : /* @__PURE__ */ t("p", { className: "nice-development-studio__muted", children: u("devStudio.preview.noDesigner", "There is no designer for this kind of entry yet.") });
3887
3888
  if (e.group === "workflows")
3888
3889
  return /* @__PURE__ */ t(
3889
- Ni,
3890
+ Ki,
3890
3891
  {
3891
3892
  workflow: r.definition,
3892
3893
  onChange: (h) => m(h),
@@ -3894,7 +3895,7 @@ function Cn({
3894
3895
  }
3895
3896
  );
3896
3897
  const f = /* @__PURE__ */ t(
3897
- Ii,
3898
+ Ni,
3898
3899
  {
3899
3900
  value: r.definition,
3900
3901
  onChange: (h) => m(h),
@@ -4966,7 +4967,7 @@ const Rn = [
4966
4967
  content: "Check the module, review the changed files and save them — only the bytes you changed are written.",
4967
4968
  placement: "bottom"
4968
4969
  }
4969
- ], Ln = ["en", "pl", "de", "fr", "es", "uk"], Zn = /* @__PURE__ */ ze(function(i, n) {
4970
+ ], Ln = ["en", "pl", "de", "fr", "es", "uk"], Qn = /* @__PURE__ */ ze(function(i, n) {
4970
4971
  var bt, wt;
4971
4972
  const {
4972
4973
  provider: a,
@@ -4995,7 +4996,7 @@ const Rn = [
4995
4996
  } = i, { t: D } = G(), Y = Te(null);
4996
4997
  pi(n, () => Y.current);
4997
4998
  const se = u === "advanced", ie = H(
4998
- () => typeof d == "function" ? d(D) : d ?? Ki,
4999
+ () => typeof d == "function" ? d(D) : d ?? $i,
4999
5000
  [d, D]
5000
5001
  ), Q = H(() => ie.locales ?? Ln, [ie]), E = sn(a, ie, { locales: Q, onError: p, t: D }), { openModule: x } = E, [P, B] = W(""), [ne, X] = W([]), [j, ee] = W(null), [he, xe] = W(null), [q, S] = W(null), C = Z(
5001
5002
  (w) => {
@@ -5223,7 +5224,7 @@ const Rn = [
5223
5224
  "data-testid": V ?? O,
5224
5225
  children: [
5225
5226
  /* @__PURE__ */ t(
5226
- Ci,
5227
+ Ii,
5227
5228
  {
5228
5229
  className: "nice-development-studio__shell",
5229
5230
  height: "100%",
@@ -5255,7 +5256,7 @@ const Rn = [
5255
5256
  rightSidebarWidth: K,
5256
5257
  statusBar: ai,
5257
5258
  bottomPanel: se ? /* @__PURE__ */ t("div", { "data-tour": "devstudio-output", className: "nice-development-studio__output", children: /* @__PURE__ */ t(
5258
- Ti,
5259
+ Ci,
5259
5260
  {
5260
5261
  title: D("devStudio.output", "Output"),
5261
5262
  entries: E.logs,
@@ -5347,7 +5348,7 @@ const Rn = [
5347
5348
  }
5348
5349
  ),
5349
5350
  (q == null ? void 0 : q.kind) === "delete" && /* @__PURE__ */ t(
5350
- Ei,
5351
+ Ti,
5351
5352
  {
5352
5353
  visible: !0,
5353
5354
  variant: "warning",
@@ -5435,59 +5436,59 @@ const Rn = [
5435
5436
  });
5436
5437
  export {
5437
5438
  Lt as NiceArrayField,
5438
- Zn as NiceDevelopmentStudio,
5439
+ Qn as NiceDevelopmentStudio,
5439
5440
  Hi as NiceEntityEditor,
5440
5441
  Vt as NiceEntityForm,
5441
5442
  Jt as NiceI18nEditor,
5442
5443
  Re as NiceSchemaForm,
5443
- Yn as aiFormConfigToFormFields,
5444
+ Xn as aiFormConfigToFormFields,
5444
5445
  zi as aiFormFieldType,
5445
- to as arrayFileKind,
5446
- xi as buildDocuments,
5447
- io as createMemoryStudioProvider,
5448
- no as defineManifestSection,
5449
- oo as deriveDefaultRbac,
5450
- so as detectJsonTextFormat,
5451
- ao as encodeDocument,
5452
- ro as endsWithAny,
5453
- $i as entitiesToSchemas,
5454
- lo as fileName,
5446
+ io as arrayFileKind,
5447
+ Ei as buildDocuments,
5448
+ no as createMemoryStudioProvider,
5449
+ oo as defineManifestSection,
5450
+ so as deriveDefaultRbac,
5451
+ ao as detectJsonTextFormat,
5452
+ ro as encodeDocument,
5453
+ lo as endsWithAny,
5454
+ Oi as entitiesToSchemas,
5455
+ co as fileName,
5455
5456
  jt as fitManifestSection,
5456
- Un as formBuilderSchemaToNiceFormItems,
5457
+ Gn as formBuilderSchemaToNiceFormItems,
5457
5458
  At as formFieldsToFormItems,
5458
- Xn as formSchemaToJsonSchema,
5459
- co as i18nFileKind,
5460
- uo as itemsFileKind,
5461
- mo as jsonFallbackKind,
5462
- po as jsonFileKind,
5459
+ Zn as formSchemaToJsonSchema,
5460
+ uo as i18nFileKind,
5461
+ mo as itemsFileKind,
5462
+ po as jsonFallbackKind,
5463
+ ho as jsonFileKind,
5463
5464
  Dt as jsonSchemaToFormItems,
5464
- ho as jsonValueFitsSchema,
5465
- vo as jsonValuesEqual,
5466
- Oi as keepTextFormat,
5467
- fo as manifestSectionKeys,
5468
- go as modulePrefix,
5469
- yo as nativeDataSourcesKind,
5470
- ko as nativeEntitiesKind,
5471
- bo as nativeFileKinds,
5472
- wo as nativeHooksKind,
5473
- So as nativeI18nKind,
5474
- _o as nativeManifestKind,
5475
- No as nativeRbacKind,
5476
- Ki as nativeStudioPreset,
5477
- Io as nativeViewsKind,
5478
- Co as nativeWorkflowsKind,
5479
- To as objectFileKind,
5480
- Eo as parseJsonText,
5481
- xo as patchJsonText,
5482
- Oo as patchJsonTextDetailed,
5483
- $o as readTranslations,
5484
- Ko as resolveFileKind,
5485
- Mo as safeJson,
5486
- Gn as schemaToFormItems,
5487
- zo as slugifyModuleId,
5488
- Fo as stringifyJsonText,
5489
- Po as textFallbackKind,
5465
+ vo as jsonValueFitsSchema,
5466
+ fo as jsonValuesEqual,
5467
+ xi as keepTextFormat,
5468
+ go as manifestSectionKeys,
5469
+ yo as modulePrefix,
5470
+ ko as nativeDataSourcesKind,
5471
+ bo as nativeEntitiesKind,
5472
+ wo as nativeFileKinds,
5473
+ So as nativeHooksKind,
5474
+ _o as nativeI18nKind,
5475
+ No as nativeManifestKind,
5476
+ Io as nativeRbacKind,
5477
+ $i as nativeStudioPreset,
5478
+ Co as nativeViewsKind,
5479
+ To as nativeWorkflowsKind,
5480
+ Eo as objectFileKind,
5481
+ xo as parseJsonText,
5482
+ Oo as patchJsonText,
5483
+ $o as patchJsonTextDetailed,
5484
+ Ko as readTranslations,
5485
+ Mo as resolveFileKind,
5486
+ zo as safeJson,
5487
+ Hn as schemaToFormItems,
5488
+ Fo as slugifyModuleId,
5489
+ Po as stringifyJsonText,
5490
+ jo as textFallbackKind,
5490
5491
  Rt as validateAgainstJsonSchema,
5491
- Hn as validateFormSchema,
5492
- jo as writeTranslations
5492
+ Yn as validateFormSchema,
5493
+ Do as writeTranslations
5493
5494
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nice2dev/ui-forms",
3
- "version": "1.3.16",
3
+ "version": "1.3.18",
4
4
  "description": "Nice2Dev UI Forms - schema-driven forms and module editors: NiceDevelopmentStudio, NiceSchemaForm, NiceEntityEditor, NiceI18nEditor",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -40,13 +40,15 @@
40
40
  "@nice2dev/i18n": "^1.2.0",
41
41
  "@nice2dev/ui": "^1.2.0",
42
42
  "@nice2dev/ui-core": "^1.2.0",
43
+ "@nice2dev/ui-diagrams": "^1.3.17",
43
44
  "react": ">=17.0.0",
44
45
  "react-dom": ">=17.0.0"
45
46
  },
46
47
  "devDependencies": {
47
- "@nice2dev/i18n": "^1.3.16",
48
- "@nice2dev/ui": "^1.3.16",
49
- "@nice2dev/ui-core": "^1.3.16",
48
+ "@nice2dev/i18n": "^1.3.18",
49
+ "@nice2dev/ui": "^1.3.18",
50
+ "@nice2dev/ui-core": "^1.3.18",
51
+ "@nice2dev/ui-diagrams": "^1.3.18",
50
52
  "@testing-library/react": "^16.3.3",
51
53
  "@types/react": "^19.2.18",
52
54
  "@types/react-dom": "^19.2.7",