import{dF as ce,fH as s,c as le,iv as _,ck as x,aD as k,bU as T,jD as U,cz as v,ce as b,dW as de,c7 as H,hc as ue,gw as pe,ds as ge,d9 as me,dn as he,dh as fe,eO as ke,dk as Ae,ey as ye,i$ as W,bL as M,iG as Te,iB as xe,gH as g,iY as Ee,iQ as Ie,iC as je,hi as Ce,iF as Se,ap as Pe,ao as be,aZ as ve,fo as B}from"./strapi-ye6TfKul.js";import{e as _e,u as Re,i as Oe}from"./apiTokens-DAwv_6wW.js";import{A as P,a as Le}from"./constants-pDXhqpw2.js";import{F as Me}from"./FormApiTokenContainer-DvEgHtKy.js";import{F as Ne,A as we}from"./TokenBox-CEBEn4T7.js";import{t as $e,m as Ue}from"./tail-NS65kI-u.js";import"./index-DJ1SXY40.js";import"./index-BRVyLNfZ.js";import"./transferTokens-BQ1MV1-4.js";import"./_baseMap-CagEH0Ml.js";import"./_baseEach-BHFmNlG9.js";const De=ce.injectEndpoints({endpoints:t=>({getPermissions:t.query({query:()=>"/admin/content-api/permissions",transformResponse:e=>e.data}),getRoutes:t.query({query:()=>"/admin/content-api/routes",transformResponse:e=>e.data})}),overrideExisting:!1}),{useGetPermissionsQuery:Fe,useGetRoutesQuery:He}=De,[Be,Ge]=le("ApiTokenPermissionsContext"),Ke=({children:t,...e})=>s.jsx(Be,{...e,children:t}),D=()=>Ge("useApiTokenPermissions"),Ve=t=>{switch(t){case"POST":return{text:"success600",border:"success200",background:"success100"};case"GET":return{text:"secondary600",border:"secondary200",background:"secondary100"};case"PUT":return{text:"warning600",border:"warning200",background:"warning100"};case"DELETE":return{text:"danger600",border:"danger200",background:"danger100"};default:return{text:"neutral600",border:"neutral200",background:"neutral100"}}},We=U(T)`
  margin: -1px;
  border-radius: ${({theme:t})=>t.spaces[1]} 0 0 ${({theme:t})=>t.spaces[1]};
`,Qe=({route:t={handler:"Nocontroller.error",method:"GET",path:"/there-is-no-path"}})=>{const{formatMessage:e}=_(),{method:i,handler:o,path:n}=t,u=n?$e(n.split("/")):[],[d="",m=""]=o?o.split("."):[],c=Ve(t.method);return s.jsxs(x,{direction:"column",alignItems:"stretch",gap:2,children:[s.jsxs(k,{variant:"delta",tag:"h3",children:[e({id:"Settings.apiTokens.createPage.BoundRoute.title",defaultMessage:"Bound route to"})," ",s.jsx("span",{children:d}),s.jsxs(k,{variant:"delta",textColor:"primary600",children:[".",m]})]}),s.jsxs(x,{hasRadius:!0,background:"neutral0",borderColor:"neutral200",gap:0,children:[s.jsx(We,{background:c.background,borderColor:c.border,padding:2,children:s.jsx(k,{fontWeight:"bold",textColor:c.text,children:i})}),s.jsx(T,{paddingLeft:2,paddingRight:2,children:Ue(u,p=>s.jsxs(k,{textColor:p.includes(":")?"neutral600":"neutral900",children:["/",p]},p))})]})]})},Ye=()=>{const{value:{selectedAction:t,routes:e}}=D(),{formatMessage:i}=_(),o=t?.split(".")[0];return s.jsx(v.Item,{xs:12,m:5,col:5,background:"neutral150",paddingTop:6,paddingBottom:6,paddingLeft:7,paddingRight:7,style:{minHeight:"100%"},direction:"column",alignItems:"stretch",children:t?s.jsx(x,{direction:"column",alignItems:"stretch",gap:2,children:o&&o in e&&e[o].map(n=>n.config.auth?.scope?.includes(t)||n.handler===t?s.jsx(Qe,{route:n},n.handler):null)}):s.jsxs(x,{direction:"column",alignItems:"stretch",gap:2,children:[s.jsx(k,{variant:"delta",tag:"h3",children:i({id:"Settings.apiTokens.createPage.permissions.header.title",defaultMessage:"Advanced settings"})}),s.jsx(k,{tag:"p",textColor:"neutral600",children:i({id:"Settings.apiTokens.createPage.permissions.header.hint",defaultMessage:"Select the application's actions or the plugin's actions and click on the cog icon to display the bound route"})})]})})},G=pe`
  background: ${t=>t.theme.colors.primary100};

  #cog {
    opacity: 1;
  }
`,qe=U(T)`
  display: flex;
  justify-content: space-between;
  align-items: center;

  #cog {
    opacity: 0;
    path {
      fill: ${t=>t.theme.colors.primary600};
    }
  }

  /* Show active style both on hover and when the action is selected */
  ${t=>t.$isActive&&G}
  &:hover {
    ${G}
  }
`,ze=U.div`
  flex: 1;
  align-self: center;
  border-top: 1px solid ${({theme:t})=>t.colors.neutral150};
`,Ze=({controllers:t=[],label:e,orderNumber:i=0,disabled:o=!1})=>{const{value:{onChangeSelectAll:n,onChange:u,selectedActions:d,setSelectedAction:m,selectedAction:c}}=D(),{formatMessage:p}=_(),C=h=>h===c;return s.jsxs(b.Item,{value:`${e}-${i}`,children:[s.jsx(b.Header,{variant:i%2?"primary":"secondary",children:s.jsx(b.Trigger,{children:de(e)})}),s.jsx(b.Content,{children:t?.map(h=>{const R=h.actions.every(r=>d.includes(r.actionId)),S=h.actions.some(r=>d.includes(r.actionId));return s.jsxs(T,{children:[s.jsxs(x,{justifyContent:"space-between",alignItems:"center",padding:4,children:[s.jsx(T,{paddingRight:4,children:s.jsx(k,{variant:"sigma",textColor:"neutral600",children:h?.controller})}),s.jsx(ze,{}),s.jsx(T,{paddingLeft:4,children:s.jsx(H,{checked:!R&&S?"indeterminate":R,onCheckedChange:()=>{n({target:{value:[...h.actions]}})},disabled:o,children:p({id:"app.utils.select-all",defaultMessage:"Select all"})})})]}),s.jsx(v.Root,{gap:4,padding:4,children:h?.actions&&h?.actions.map(r=>s.jsx(v.Item,{xs:12,s:6,direction:"column",alignItems:"stretch",children:s.jsxs(qe,{$isActive:C(r.actionId),padding:2,hasRadius:!0,children:[s.jsx(H,{checked:d.includes(r.actionId),name:r.actionId,onCheckedChange:()=>{u({target:{value:r.actionId}})},disabled:o,children:s.jsx("span",{style:{overflowWrap:"anywhere"},children:r.action})}),s.jsx("button",{type:"button","data-testid":"action-cog",onClick:()=>m({target:{value:r.actionId}}),style:{display:"inline-flex",alignItems:"center"},children:s.jsx(ue,{id:"cog"})})]})},r.actionId))})]},`${e}.${h?.controller}`)})})]})},Je=({section:t=null,...e})=>s.jsx(T,{children:s.jsx(b.Root,{size:"M",children:t&&t.map((i,o)=>s.jsx(Ze,{label:i.label,controllers:i.controllers,orderNumber:o,...e},i.apiId))})}),Xe=({...t})=>{const{value:{data:e}}=D(),{formatMessage:i}=_();return s.jsxs(v.Root,{gap:0,shadow:"filterShadow",hasRadius:!0,background:"neutral0",children:[s.jsxs(v.Item,{xs:12,col:7,paddingTop:6,paddingBottom:6,paddingLeft:7,paddingRight:7,direction:"column",alignItems:"stretch",gap:6,children:[s.jsxs(x,{direction:"column",alignItems:"stretch",gap:2,children:[s.jsx(k,{variant:"delta",tag:"h2",children:i({id:"Settings.apiTokens.createPage.permissions.title",defaultMessage:"Permissions"})}),s.jsx(k,{tag:"p",textColor:"neutral600",children:i({id:"Settings.apiTokens.createPage.permissions.description",defaultMessage:"Only actions bound by a route are listed below."})})]}),e?.permissions&&s.jsx(Je,{section:e?.permissions,...t})]}),s.jsx(Ye,{})]})};function es(t,e,i,o){for(var n=i-1,u=t.length;++n<u;)if(o(t[n],e))return n;return-1}var ss=es,ts=me,ns=fe,is=ss,as=he,os=ge,rs=Array.prototype,K=rs.splice;function cs(t,e,i,o){var n=o?is:ns,u=-1,d=e.length,m=t;for(t===e&&(e=os(e)),i&&(m=ts(t,as(i)));++u<d;)for(var c=0,p=e[u],C=i?i(p):p;(c=n(m,C,c,o))>-1;)m!==t&&K.call(m,c,1),K.call(t,c,1);return t}var ls=cs,ds=ls;function us(t,e){return t&&t.length&&e&&e.length?ds(t,e):t}var ps=us,gs=Ae,ms=ps,hs=gs(ms),fs=hs;const V=ke(fs),ks=t=>{const e={allActionsIds:[],permissions:[]};return e.permissions=Object.entries(t).map(([i,o])=>({apiId:i,label:i.split("::")[1],controllers:Object.keys(o.controllers).map(n=>({controller:n,actions:n in o.controllers?o.controllers[n].map(u=>{const d=`${i}.${n}.${u}`;return i.includes("api::")&&e.allActionsIds.push(d),{action:u,actionId:d}}).flat():[]})).flat()})),e},As={data:{allActionsIds:[],permissions:[]},routes:{},selectedAction:"",selectedActions:[]},ys=(t,e)=>ye(t,i=>{switch(e.type){case"ON_CHANGE":{i.selectedActions.includes(e.value)?V(i.selectedActions,e.value):i.selectedActions.push(e.value);break}case"SELECT_ALL_IN_PERMISSION":{e.value.every(n=>i.selectedActions.includes(n.actionId))?e.value.forEach(n=>{V(i.selectedActions,n.actionId)}):e.value.forEach(n=>{i.selectedActions.push(n.actionId)});break}case"SELECT_ALL_ACTIONS":{i.selectedActions=[...i.data.allActionsIds];break}case"ON_CHANGE_READ_ONLY":{const o=i.data.allActionsIds.filter(n=>n.includes("find")||n.includes("findOne"));i.selectedActions=[...o];break}case"UPDATE_PERMISSIONS_LAYOUT":{i.data=ks(e.value);break}case"UPDATE_ROUTES":{i.routes={...e.value};break}case"UPDATE_PERMISSIONS":{i.selectedActions=[...e.value];break}case"SET_SELECTED_ACTION":{i.selectedAction=e.value;break}default:return i}}),Ts=()=>{const{formatMessage:t}=_(),{toggleNotification:e}=Te(),{state:i}=xe(),o=W(a=>a.admin_app.permissions),[n,u]=g.useState(i?.apiToken?.accessKey!==void 0&&i?.apiToken?.accessKey!==""?{...i.apiToken}:null),[d,m]=g.useState(i?.apiToken?.accessKey!==void 0&&i?.apiToken?.accessKey!==""),c=g.useRef(null),{trackUsage:p}=Ee(),{allowedActions:{canCreate:C,canUpdate:h,canRegenerate:R}}=Ie(o.settings?.["api-tokens"]),[S,r]=g.useReducer(ys,As),O=je("/settings/api-tokens/:id")?.params?.id,f=O==="create",{_unstableFormatAPIError:A,_unstableFormatValidationErrors:F}=Ce(),Q=Se(),E=Fe(),I=He();g.useEffect(()=>{E.error&&e({type:"danger",message:A(E.error)})},[E.error,A,e]),g.useEffect(()=>{I.error&&e({type:"danger",message:A(I.error)})},[I.error,A,e]),g.useEffect(()=>{E.data&&r({type:"UPDATE_PERMISSIONS_LAYOUT",value:E.data})},[E.data]),g.useEffect(()=>{I.data&&r({type:"UPDATE_ROUTES",value:I.data})},[I.data]),g.useEffect(()=>{n!==null&&(n.type==="read-only"&&r({type:"ON_CHANGE_READ_ONLY"}),n.type==="full-access"&&r({type:"SELECT_ALL_ACTIONS"}),n.type==="custom"&&r({type:"UPDATE_PERMISSIONS",value:n.permissions}))},[n]),g.useEffect(()=>{p(f?"didAddTokenFromList":"didEditTokenFromList",{tokenType:P})},[f,p]);const{data:y,error:N,isLoading:Y}=_e(O,{skip:!O||f||!!n});g.useEffect(()=>{N&&e({type:"danger",message:A(N)})},[N,A,e]),g.useEffect(()=>{y&&(u(y),y.kind==="content-api"&&(y.type==="read-only"&&r({type:"ON_CHANGE_READ_ONLY"}),y.type==="full-access"&&r({type:"SELECT_ALL_ACTIONS"}),y.type==="custom"&&r({type:"UPDATE_PERMISSIONS",value:y.permissions})))},[y]),g.useEffect(()=>{if(d)return c.current=setTimeout(()=>{m(!1)},3e4),()=>{c.current&&(clearTimeout(c.current),c.current=null)}},[d]);const[q]=Re(),[z]=Oe(),Z=a=>a&&a!=="0"?parseInt(a.toString(),10):null,J=async(a,j)=>{p(f?"willCreateToken":"willEditToken",{tokenType:P});try{if(f){const l=await q({name:a.name,description:a.description,type:a.type,lifespan:Z(a.lifespan),permissions:a.type==="custom"?S.selectedActions:null});if("error"in l){B(l.error)&&l.error.name==="ValidationError"?j.setErrors(F(l.error)):e({type:"danger",message:A(l.error)});return}e({type:"success",message:t({id:"notification.success.apitokencreated",defaultMessage:"API Token successfully created"})}),p("didCreateToken",{kind:"content-api",tokenType:P}),Q(`../api-tokens/${l.data.id.toString()}`,{state:{apiToken:l.data},replace:!0})}else{const l=await z({id:O,name:a.name,description:a.description,type:a.type,permissions:a.type==="custom"?S.selectedActions:null});if("error"in l){B(l.error)&&l.error.name==="ValidationError"?j.setErrors(F(l.error)):e({type:"danger",message:A(l.error)});return}e({type:"success",message:t({id:"notification.success.apitokenedited",defaultMessage:"API Token successfully edited"})}),p("didEditToken",{kind:l.data.kind,type:l.data.type,tokenType:P})}}catch{e({type:"danger",message:t({id:"notification.error",defaultMessage:"Something went wrong"})})}},[X,w]=g.useState(!1),ee=({target:{value:a}})=>{w(!0),r({type:"ON_CHANGE",value:a})},se=({target:{value:a}})=>{w(!0),r({type:"SELECT_ALL_IN_PERMISSION",value:a})},te=({target:{value:a}})=>{r({type:"SET_SELECTED_ACTION",value:a})},ne=()=>{m(a=>!a),c.current&&(clearTimeout(c.current),c.current=null)},ie={...S,onChange:ee,onChangeSelectAll:se,setSelectedAction:te},$=h&&!f||C&&f,ae=n?.accessKey!==void 0&&n.accessKey!=="",oe=n!==null&&n.kind==="content-api"?n.type:void 0;return Y?s.jsx(M.Loading,{}):s.jsx(Ke,{value:ie,children:s.jsxs(M.Main,{children:[s.jsx(M.Title,{children:t({id:"Settings.PageTitle",defaultMessage:"Settings - {name}"},{name:"API Tokens"})}),s.jsx(Pe,{validationSchema:Le,validateOnChange:!1,initialValues:{name:n?.name||"",description:n?.description||"",type:oe,lifespan:n?.lifespan},enableReinitialize:!0,onSubmit:(a,j)=>J(a,j),children:({errors:a,handleChange:j,isSubmitting:l,values:L,setFieldValue:re})=>(X&&L?.type!=="custom"&&re("type","custom"),s.jsxs(be,{children:[s.jsx(Ne,{title:f?{id:"Settings.apiTokens.createPage.title",defaultMessage:"Create API Token"}:{id:"Settings.apiTokens.createPage.title",defaultMessage:"Edit API Token"},token:n,setToken:u,toggleToken:ne,showToken:d,canEditInputs:$,canRegenerate:R,canShowToken:ae,isSubmitting:l,regenerateUrl:"/admin/api-tokens/"}),s.jsx(ve.Content,{children:s.jsxs(x,{direction:"column",alignItems:"stretch",gap:6,children:[n?.accessKey!==void 0&&n.accessKey!==""&&d===!0&&s.jsx(s.Fragment,{children:s.jsx(we,{token:n.accessKey,tokenType:P})}),s.jsx(Me,{errors:a,onChange:j,canEditInputs:$,isCreating:f,values:L,apiToken:n,kind:"content-api",onDispatch:r,setHasChangedPermissions:w}),s.jsx(Xe,{disabled:!$||L?.type==="read-only"||L?.type==="full-access"})]})})]}))})]})})},Ls=()=>{const t=W(e=>e.admin_app.permissions.settings?.["api-tokens"].read);return s.jsx(M.Protect,{permissions:t,children:s.jsx(Ts,{})})};export{Ts as EditView,Ls as ProtectedEditView};
