@c-time/frelio-cms 1.3.5 → 1.3.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/assets/{index-Qi4Cp3k2.js → index-D36XnvJP.js} +1 -1
  2. package/dist/assets/{index-Dr4qYonI.js → index-DCWmZub0.js} +4 -4
  3. package/dist/index.html +1 -1
  4. package/functions/api/auth/callback.ts +138 -0
  5. package/functions/api/storage/_middleware.ts +76 -0
  6. package/functions/api/storage/files/[uuid].ts +35 -0
  7. package/functions/api/storage/list.ts +19 -0
  8. package/functions/api/storage/rebuild/[year].ts +27 -0
  9. package/functions/api/storage/upload-set.ts +18 -0
  10. package/functions/api/storage/upload.ts +18 -0
  11. package/functions/api/storage/years.ts +18 -0
  12. package/package.json +6 -4
  13. package/workers/file-upload/package-lock.json +1606 -0
  14. package/workers/file-upload/package.json +14 -0
  15. package/workers/file-upload/src/controller/DIContainer.ts +103 -0
  16. package/workers/file-upload/src/controller/FileController.ts +248 -0
  17. package/workers/file-upload/src/domain/AuthEntity.ts +17 -0
  18. package/workers/file-upload/src/domain/FileEntity.ts +113 -0
  19. package/workers/file-upload/src/index.ts +134 -0
  20. package/workers/file-upload/src/infra/LoggerSingleton.ts +162 -0
  21. package/workers/file-upload/src/presenter/HttpPresenterImpl.ts +86 -0
  22. package/workers/file-upload/src/repository/AuthRepositoryPort.ts +11 -0
  23. package/workers/file-upload/src/repository/GitHubAuthRepositoryImpl.ts +58 -0
  24. package/workers/file-upload/src/repository/R2RepositoryImpl.ts +145 -0
  25. package/workers/file-upload/src/repository/R2RepositoryPort.ts +86 -0
  26. package/workers/file-upload/src/usecase/DeleteFileUseCase.ts +97 -0
  27. package/workers/file-upload/src/usecase/GetFileUseCase.ts +50 -0
  28. package/workers/file-upload/src/usecase/ListFilesUseCase.ts +52 -0
  29. package/workers/file-upload/src/usecase/RebuildIndexUseCase.ts +182 -0
  30. package/workers/file-upload/src/usecase/UpdateFileMetadataUseCase.ts +43 -0
  31. package/workers/file-upload/src/usecase/UploadFileUseCase.ts +62 -0
  32. package/workers/file-upload/src/usecase/UploadImageSetUseCase.ts +95 -0
  33. package/workers/file-upload/src/usecase/ValidateAuthUseCase.ts +26 -0
  34. package/workers/file-upload/tsconfig.json +13 -0
  35. package/workers/file-upload/wrangler.toml.example +11 -0
@@ -276,7 +276,7 @@ export default theme;`}function sC(t={},...e){const{breakpoints:n,mixins:r={},sp
276
276
  OAuth App に組織へのアクセス権を付与してください:
277
277
  1. https://github.com/settings/applications を開く
278
278
  2. この OAuth App をクリック
279
- 3.「Organization access」で対象の組織の「Grant」をクリック`,severity:"error"}):this.store.setState({open:!0,message:`${r}GitHub API エラー(${e})`,severity:"error"})}dismiss(){this.store.setState({open:!1})}};St(Rl,"instance",null);let jC=Rl;const Pd=jC.getInstance();var Ix="frelio-data/site",Tm="frelio-data/admin",tP=`${Ix}/content_types`,Qi=`${Ix}/contents`,h2=`${Ix}/templates`,m2=`${Tm}/content_types`,nP=`${Tm}/metadata`,rP=`${Tm}/users`,Bc=`${nP}/content_types.json`,kh=`${nP}/_dashboard.json`,Mh=`${rP}/_index.json`,ZK=`${Tm}/recipes`,KK=`${Ix}/data`,TC=[{id:"templates",label:"テンプレート",path:h2}];function Kl(t){return`${tP}/${t}.json`}function Ld(t){return`${m2}/${t}.ui.json`}function sc(t){return`${m2}/${t}.views.json`}function QK(t,e){return`${Qi}/${t}/${e}`}function Oh(t,e,n){return`${Qi}/${t}/${e}/${n}.json`}function Ah(t,e){return`${Qi}/${t}/${e}/_index.json`}function Ql(t,e,n,r=null){return n===null||n===r?`${Qi}/${t}/${e}/_index.json`:`${Qi}/${t}/${e}/_index.${n}.json`}function TM(){return`${ZK}/build-data-recipe.json`}function JK(){return`${KK}/_dependency-map.json`}var Ts={DATA_ROOT:"frelio-data",CONTENT_TYPES:tP,CONTENTS_PRIVATE:`${Qi}/private`,TEMPLATES:h2,ADMIN_ROOT:Tm,ADMIN_CONTENT_TYPES:m2,ADMIN_USERS:rP};function YK(t){return{contentId:t.contentId,title:t.title,status:t.status,createdAt:t.createdAt,updatedAt:t.updatedAt,publishedAt:t.publishedAt,createdBy:t.createdBy,updatedBy:t.updatedBy}}function DC(t,e){const n={contentId:t.contentId,status:t.status,createdAt:t.createdAt,updatedAt:t.updatedAt};for(const r of e){const s=rQ(t,r.field);s!==void 0&&(n[r.field]=s)}return n}function XK(t,e){const n=t.findIndex(r=>r.contentId===e.contentId);if(n>=0){const r=[...t];return r[n]=e,r}return[...t,e]}function eQ(t,e){return t.filter(n=>n.contentId!==e)}function tQ(t,e){const n=t.findIndex(r=>r.contentId===e.contentId);if(n>=0){const r=[...t];return r[n]=e,r}return[...t,e]}function nQ(t,e){return t.filter(n=>n.contentId!==e)}function rQ(t,e){if(e in t)return t[e];if(e.startsWith("data.")){const n=e.substring(5);return t.data[n]}return t.data[e]}async function sP(t,e){const{basePath:n,contentTypeId:r,content:s}=e,i=sc(r),l=await t.readJson(i),u=(l==null?void 0:l.views)??[],p=(l==null?void 0:l.defaultViewId)??null,f=[];for(const m of u){const g=Ql(n,r,m.id,p),y=await t.readJson(g)??[],v=DC(s,m.columns),C=XK(y,v);f.push({path:g,content:JSON.stringify(C,null,2)})}if(u.length===0){const m=Ql(n,r,null,null),g=await t.readJson(m)??[],y=YK(s),v=tQ(g,y);f.push({path:m,content:JSON.stringify(v,null,2)})}return f}async function iP(t,e){const{basePath:n,contentTypeId:r,contentId:s}=e,i=sc(r),l=await t.readJson(i),u=(l==null?void 0:l.views)??[],p=(l==null?void 0:l.defaultViewId)??null,f=[];for(const m of u){const g=Ql(n,r,m.id,p),y=await t.readJson(g)??[],v=eQ(y,s);f.push({path:g,content:JSON.stringify(v,null,2)})}if(u.length===0){const m=Ql(n,r,null,null),g=await t.readJson(m)??[],y=nQ(g,s);f.push({path:m,content:JSON.stringify(y,null,2)})}return f}var oP={lastUpdatedAt:"",lastUpdatedBy:"",totalCount:0,draftCount:0,publishedCount:0};function sQ(t,e,n,r,s,i=new Date().toISOString()){const l={...t,contentTypes:{...t.contentTypes}},u={...l.contentTypes[e]??{...oP}};return u.lastUpdatedAt=i,u.lastUpdatedBy=n,r===null?(u.totalCount+=1,s==="draft"?u.draftCount+=1:s==="published"&&(u.publishedCount+=1)):r!==s&&(r==="draft"&&(u.draftCount-=1),r==="published"&&(u.publishedCount-=1),s==="draft"&&(u.draftCount+=1),s==="published"&&(u.publishedCount+=1)),l.contentTypes[e]=u,l}function iQ(t,e,n,r,s=new Date().toISOString()){const i={...t,contentTypes:{...t.contentTypes}},l={...i.contentTypes[e]??{...oP}};return l.lastUpdatedAt=s,l.lastUpdatedBy=n,l.totalCount=Math.max(0,l.totalCount-1),r==="draft"?l.draftCount=Math.max(0,l.draftCount-1):r==="published"&&(l.publishedCount=Math.max(0,l.publishedCount-1)),i.contentTypes[e]=l,i}var aP={contentTypes:{}};async function lP(t,e){const n=await t.readJson(kh)??{...aP},r=sQ(n,e.contentTypeId,e.updatedBy,e.oldStatus,e.newStatus,e.now);return{path:kh,content:JSON.stringify(r,null,2)}}async function oQ(t,e){const n=await t.readJson(kh)??{...aP},r=iQ(n,e.contentTypeId,e.deletedBy,e.deletedStatus,e.now);return{path:kh,content:JSON.stringify(r,null,2)}}function DM(t,e,n){var s,i;const r=[];if((s=t.branchName)!=null&&s.trim()?(/^[a-zA-Z0-9_\-/]+$/.test(t.branchName)||r.push({field:"branchName",message:"ブランチ名には英数字、ハイフン、アンダースコア、スラッシュのみ使用できます"}),e.some(p=>p.branchName===t.branchName&&p.branchName!==n)&&r.push({field:"branchName",message:"このブランチ名は既に登録されています"})):r.push({field:"branchName",message:"ブランチ名は必須です"}),(i=t.previewUrl)!=null&&i.trim())try{new URL(t.previewUrl)}catch{r.push({field:"previewUrl",message:"有効な URL を入力してください"})}return r}function EM(t){return!t.isDefault}function cP(t,e){const n=e.filter(l=>!l.isDefault),r=n.filter(l=>l.allowedUsers.includes(t)),s=n.filter(l=>l.allowedUsers.length===0),i=[...r];for(const l of s)i.some(u=>u.branchName===l.branchName)||i.push(l);return i}function Dm(){return{branchName:"staging",previewUrl:"",allowedUsers:[],isDefault:!0}}function RM(t){return t.split(",").map(e=>e.trim()).filter(e=>e.length>0)}function aQ(t){return t.join(", ")}const Sv=[{edit:"canEditContent",view:"canViewContent"},{edit:"canEditStorage",view:"canViewStorage"},{edit:"canEditTemplates",view:"canViewTemplates"},{edit:"canEditUsers",view:"canViewUsers"},{edit:"canEditStaging",view:"canViewStaging"},{edit:"canEditContentType",view:"canViewContentType"},{edit:"canEditBuildRecipes",view:"canViewBuildRecipes"},{edit:"canEditDeploy",view:"canViewDeploy"}],Cv={canViewContent:!0,canEditContent:!0,canViewStorage:!0,canEditStorage:!0,canViewTemplates:!0,canEditTemplates:!0,canViewUsers:!0,canEditUsers:!0,canViewStaging:!0,canEditStaging:!0,canViewContentType:!0,canEditContentType:!0,canViewBuildRecipes:!0,canEditBuildRecipes:!0,canViewDeploy:!0,canEditDeploy:!0},lQ={canViewContent:!0,canEditContent:!0,canViewStorage:!0,canEditStorage:!0,canViewTemplates:!0,canEditTemplates:!0,canViewUsers:!1,canEditUsers:!1,canViewStaging:!1,canEditStaging:!1,canViewContentType:!0,canEditContentType:!0,canViewBuildRecipes:!0,canEditBuildRecipes:!0,canViewDeploy:!1,canEditDeploy:!1},cQ={canViewContent:!0,canEditContent:!0,canViewStorage:!0,canEditStorage:!0,canViewTemplates:!0,canEditTemplates:!0,canViewUsers:!1,canEditUsers:!1,canViewStaging:!1,canEditStaging:!1,canViewContentType:!0,canEditContentType:!1,canViewBuildRecipes:!0,canEditBuildRecipes:!1,canViewDeploy:!1,canEditDeploy:!1},uQ={canViewContent:!0,canEditContent:!1,canViewStorage:!0,canEditStorage:!1,canViewTemplates:!0,canEditTemplates:!1,canViewUsers:!1,canEditUsers:!1,canViewStaging:!1,canEditStaging:!1,canViewContentType:!0,canEditContentType:!1,canViewBuildRecipes:!0,canEditBuildRecipes:!1,canViewDeploy:!1,canEditDeploy:!1},wv={owner:Cv,admin:Cv,developer:lQ,editor:cQ,viewer:uQ},dQ={owner:"所有者",admin:"管理者",developer:"開発者",editor:"編集者",viewer:"閲覧者",custom:"カスタム"},uP={content:{label:"コンテンツ",pairs:[{view:"canViewContent",edit:"canEditContent"},{view:"canViewStorage",edit:"canEditStorage"},{view:"canViewTemplates",edit:"canEditTemplates"}]},admin:{label:"管理",pairs:[{view:"canViewUsers",edit:"canEditUsers"},{view:"canViewStaging",edit:"canEditStaging"},{view:"canViewDeploy",edit:"canEditDeploy"}]},development:{label:"開発",pairs:[{view:"canViewContentType",edit:"canEditContentType"},{view:"canViewBuildRecipes",edit:"canEditBuildRecipes"}]}},dP={canViewContent:"コンテンツ",canViewStorage:"ストレージ",canViewTemplates:"テンプレート",canViewUsers:"ユーザー管理",canViewStaging:"ステージング",canViewContentType:"コンテンツタイプ",canViewBuildRecipes:"ビルドレシピ",canViewDeploy:"デプロイ"};function pQ(t,e){return Object.keys(t).every(r=>t[r]===e[r])}function _h(t,e=!1){if(e)return"owner";const n=["admin","developer","editor","viewer"];for(const r of n)if(pQ(t,wv[r]))return r;return"custom"}function Ih(t){return t==="custom"?{...wv.viewer}:{...wv[t]}}function fQ(){return{canViewContent:!1,canEditContent:!1,canViewStorage:!1,canEditStorage:!1,canViewTemplates:!1,canEditTemplates:!1,canViewUsers:!1,canEditUsers:!1,canViewStaging:!1,canEditStaging:!1,canViewContentType:!1,canEditContentType:!1,canViewBuildRecipes:!1,canEditBuildRecipes:!1,canViewDeploy:!1,canEditDeploy:!1}}const Gf=Fs(t=>({isActive:!1,virtualPermissions:null,virtualRoleTemplate:null,simulatedUserDisplayName:null,simulatedGithubUsername:null,startSimulation:(e,n,r,s)=>{t({isActive:!0,virtualPermissions:e,virtualRoleTemplate:n,simulatedUserDisplayName:r,simulatedGithubUsername:s})},stopSimulation:()=>{t({isActive:!1,virtualPermissions:null,virtualRoleTemplate:null,simulatedUserDisplayName:null,simulatedGithubUsername:null})},updatePermissions:(e,n)=>{t({virtualPermissions:e,virtualRoleTemplate:n})}}));let Dy=null,kM=null;function hQ(){const t=Gf.getState();return kM===t&&Dy!==null||(kM=t,Dy={isActive:t.isActive,virtualPermissions:t.virtualPermissions,virtualRoleTemplate:t.virtualRoleTemplate,simulatedUserDisplayName:t.simulatedUserDisplayName,simulatedGithubUsername:t.simulatedGithubUsername}),Dy}class mQ{startSimulation(e,n,r,s){Gf.getState().startSimulation(e,n,r,s)}stopSimulation(){Gf.getState().stopSimulation()}updatePermissions(e,n){Gf.getState().updatePermissions(e,n)}getState(){return hQ()}subscribe(e){return Gf.subscribe(e)}}const Px=new mQ;function ws(t,e){const n=Px.getState();return n.isActive&&n.virtualPermissions?n.virtualPermissions[e]===!0:t?t.isOwner?!0:t.permissions[e]===!0:!1}function gQ(t){return t==="/login"||t.startsWith("/auth/")||t==="/"?null:t==="/users"||t.startsWith("/users/")?"canViewUsers":t==="/staging"||t.startsWith("/staging/")?"canViewStaging":t==="/storage"||t.startsWith("/storage/")?"canViewStorage":t==="/templates"||t.startsWith("/templates/")?"canViewTemplates":t==="/build-recipes"||t.startsWith("/build-recipes/")?"canViewBuildRecipes":t==="/deploy-history"||t.startsWith("/deploy-history/")?"canViewDeploy":t.match(/^\/content-types\/[^/]+\/edit/)||t.match(/^\/content-types\/[^/]+\/views/)||t==="/content-types"||t.startsWith("/content-types/")?"canViewContentType":t.match(/^\/contents\/[^/]+\/new$/)?"canEditContent":t.match(/^\/contents\/[^/]+/)?"canViewContent":null}function yQ(t){return{...wv[t]}}function vQ(t){return{githubUsername:t.githubUsername,displayName:t.displayName,allowPersonalBranch:t.allowPersonalBranch,permissions:yQ(t.role),isOwner:!1}}function xQ(t){let e=!1;return t.map(n=>{const r=vQ(n);return!e&&n.role==="admin"&&(r.isOwner=!0,e=!0),r})}function bQ(t){return{...fQ(),...t}}function SQ(t){return typeof t=="object"&&t!==null&&"role"in t&&!("permissions"in t)}function CQ(t){return t.some(SQ)}function pP(t){return CQ(t)?xQ(t):t.map(e=>({...e,permissions:bQ(e.permissions)}))}let jv=null;async function wQ(){if(jv)return;const e=await fetch("/admin/config.json");if(!e.ok)throw new Error(`Failed to load config.json (${e.status}). Ensure config.json exists at the app root, or set VITE_CONTENT_REPO at build time.`);const n=await e.json();jv={contentRepo:n.contentRepo,githubClientId:n.githubClientId,fileUploadUrl:n.fileUploadUrl??"/api/storage",siteTitle:n.siteTitle??"",productionUrl:n.productionUrl??"",previewUrl:n.previewUrl??""}}function ta(){if(!jv)throw new Error("Config not loaded. Call loadConfig() before accessing config.");return jv}const MM="https://api.github.com",e1="frelio_github_token";class jQ{get contentRepo(){return ta().contentRepo}async fetchGitHubUser(e){oe.debug("GitHubAuthRepositoryImpl.fetchGitHubUser");const n=await fetch(`${MM}/user`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!n.ok)throw oe.error("GitHubAuthRepositoryImpl.fetchGitHubUser","API error",{status:n.status}),(n.status===401||n.status===403)&&Pd.notifyPermissionError(n.status,"ユーザー情報取得"),new lh(n.status,`GitHub API error: ${n.status}`,"ユーザー情報取得");const r=await n.json();return{login:r.login,avatar_url:r.avatar_url,name:r.name}}async fetchAdminData(e){var g;oe.debug("GitHubAuthRepositoryImpl.fetchAdminData");const[n,r]=this.contentRepo.split("/"),s=await fetch(`${MM}/repos/${n}/${r}/contents/${Mh}?ref=develop`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!s.ok)throw oe.error("GitHubAuthRepositoryImpl.fetchAdminData","API error",{status:s.status}),(s.status===401||s.status===403)&&Pd.notifyPermissionError(s.status,"管理データ取得"),new lh(s.status,`Failed to fetch admin data: ${s.status}`,"管理データ取得");const i=await s.json(),l=decodeURIComponent(escape(atob(i.content))),u=JSON.parse(l),p=pP(u.users??[]),m=((g=u.stagingBranches)==null?void 0:g.some(y=>y.isDefault))??!1?u.stagingBranches:[Dm(),...u.stagingBranches??[]];return{users:p,stagingBranches:m}}saveToken(e){oe.debug("GitHubAuthRepositoryImpl.saveToken"),localStorage.setItem(e1,e)}getToken(){return localStorage.getItem(e1)}clearToken(){oe.debug("GitHubAuthRepositoryImpl.clearToken"),localStorage.removeItem(e1)}getAuthUrl(){const e=ta().githubClientId;return`https://github.com/login/oauth/authorize?${new URLSearchParams({client_id:e,scope:"repo",redirect_uri:`${window.location.origin}/api/auth/callback`}).toString()}`}}function TQ(t){return t?t.allowPersonalBranch!==!1:!1}function OM(t,e,n){var s,i;const r=[];return(s=t.githubUsername)!=null&&s.trim()?e.some(u=>u.githubUsername===t.githubUsername&&u.githubUsername!==n)&&r.push({field:"githubUsername",message:"このユーザー名は既に登録されています"}):r.push({field:"githubUsername",message:"GitHub ユーザー名は必須です"}),(i=t.displayName)!=null&&i.trim()||r.push({field:"displayName",message:"表示名は必須です"}),t.permissions||r.push({field:"permissions",message:"権限は必須です"}),r}function AM(t,e){return t!==e}function Tv(t){return dQ[t]}function g2(t){return _h(t.permissions,t.isOwner??!1)}const Zf=Fs(t=>({githubUser:null,currentUser:null,token:null,isInitialized:!1,users:[],stagingBranches:[],setAuth:(e,n,r,s,i)=>{t({githubUser:e,currentUser:n,token:r,users:s,stagingBranches:i})},clearAuth:()=>{t({githubUser:null,currentUser:null,token:null,users:[],stagingBranches:[]})},setInitialized:()=>{t({isInitialized:!0})}}));let Ey=null,_M=null;function DQ(){const t=Zf.getState();if(_M===t&&Ey!==null)return Ey;_M=t;const e=t.currentUser,n=(e==null?void 0:e.permissions)??null,r=e?_h(e.permissions,e.isOwner??!1):null,s=(e==null?void 0:e.isOwner)??!1,i=TQ(e??void 0);return Ey={githubUser:t.githubUser,currentUser:t.currentUser,token:t.token,isInitialized:t.isInitialized,users:t.users,stagingBranches:t.stagingBranches,permissions:n,roleTemplate:r,isOwner:s,allowPersonalBranch:i},Ey}class EQ{setAuth(e,n,r,s,i){Zf.getState().setAuth(e,n,r,s,i)}clearAuth(){Zf.getState().clearAuth()}setInitialized(){Zf.getState().setInitialized()}getState(){return DQ()}subscribe(e){return Zf.subscribe(e)}}const Em=new EQ;class fP{constructor(e){this.repository=e}async execute(e){oe.info("LoginUseCase.execute");const n=await this.repository.fetchGitHubUser(e);oe.debug("LoginUseCase.execute","GitHub user fetched",{login:n.login});const r=await this.repository.fetchAdminData(e),{users:s,stagingBranches:i}=r;oe.debug("LoginUseCase.execute","Admin data fetched",{usersCount:s.length,stagingBranchesCount:i.length});const l=s.find(u=>u.githubUsername===n.login);if(!l)throw oe.warn("LoginUseCase.execute","User not authorized",{login:n.login}),new Error(`User ${n.login} is not authorized`);return this.repository.saveToken(e),oe.info("LoginUseCase.execute","Login successful",{login:n.login}),{user:l,githubUser:n,users:s,stagingBranches:i}}async restoreSession(){oe.debug("LoginUseCase.restoreSession");const e=this.repository.getToken();if(!e)return oe.debug("LoginUseCase.restoreSession","No token found"),null;try{return await this.execute(e)}catch(n){return oe.warn("LoginUseCase.restoreSession","Failed to restore session",{error:n}),this.repository.clearToken(),null}}}class RQ{constructor(e){this.repository=e}execute(){oe.info("LogoutUseCase.execute"),this.repository.clearToken()}}class kQ{constructor(e){this.repository=e}execute(){return oe.debug("GetAuthUrlUseCase.execute"),this.repository.getAuthUrl()}}class MQ{constructor(e,n){this.repository=e,this.presenter=n}async execute(){oe.debug("InitAuthUseCase.execute");const e=this.repository.getToken();if(!e){oe.debug("InitAuthUseCase.execute","No token found"),this.presenter.setInitialized();return}try{oe.debug("InitAuthUseCase.execute","Restoring session...");const r=await new fP(this.repository).execute(e);this.presenter.setAuth(r.githubUser,r.user,e,r.users,r.stagingBranches),oe.info("InitAuthUseCase.execute","Session restored",{login:r.githubUser.login})}catch(n){oe.warn("InitAuthUseCase.execute","Failed to restore session",{error:n}),this.repository.clearToken(),this.presenter.clearAuth()}finally{this.presenter.setInitialized()}}}class OQ{constructor(e){this.deps=e}getState(){return this.deps.presenter.getState()}async login(e){const{presenter:n,loginUseCase:r}=this.deps,s=await r.execute(e);return n.setAuth(s.githubUser,s.user,e,s.users,s.stagingBranches),s}logout(){const{presenter:e,logoutUseCase:n}=this.deps;n.execute(),e.clearAuth()}getAuthUrl(){return this.deps.getAuthUrlUseCase.execute()}}let t1=!1;const Lx=new jQ,AQ=new fP(Lx),_Q=new RQ(Lx),IQ=new kQ(Lx),PQ=new MQ(Lx,Em),IM=new OQ({presenter:Em,loginUseCase:AQ,logoutUseCase:_Q,getAuthUrlUseCase:IQ}),LQ=t=>Em.subscribe(t),PM=()=>Em.getState();function rr(){b.useSyncExternalStore(LQ,PM,PM);const t=IM.getState(),e=b.useRef(!1);return b.useEffect(()=>{t.isInitialized||e.current||t1||(e.current=!0,t1=!0,PQ.execute().finally(()=>{t1=!1}))},[t.isInitialized]),{authUseCase:IM}}function Qr(){return ta().contentRepo}const zQ="https://api.github.com/graphql";class At{constructor(e){this.token=e}async fetchFile(e,n="main"){const[r,s]=Qr().split("/"),i=`${n}:${e}`,u=await this.graphql(`
279
+ 3.「Organization access」で対象の組織の「Grant」をクリック`,severity:"error"}):this.store.setState({open:!0,message:`${r}GitHub API エラー(${e})`,severity:"error"})}dismiss(){this.store.setState({open:!1})}};St(Rl,"instance",null);let jC=Rl;const Pd=jC.getInstance();var Ix="frelio-data/site",Tm="frelio-data/admin",tP=`${Ix}/content_types`,Qi=`${Ix}/contents`,h2=`${Ix}/templates`,m2=`${Tm}/content_types`,nP=`${Tm}/metadata`,rP=`${Tm}/users`,Bc=`${nP}/content_types.json`,kh=`${nP}/_dashboard.json`,Mh=`${rP}/_index.json`,ZK=`${Tm}/recipes`,KK=`${Ix}/data`,TC=[{id:"templates",label:"テンプレート",path:h2}];function Kl(t){return`${tP}/${t}.json`}function Ld(t){return`${m2}/${t}.ui.json`}function sc(t){return`${m2}/${t}.views.json`}function QK(t,e){return`${Qi}/${t}/${e}`}function Oh(t,e,n){return`${Qi}/${t}/${e}/${n}.json`}function Ah(t,e){return`${Qi}/${t}/${e}/_index.json`}function Ql(t,e,n,r=null){return n===null||n===r?`${Qi}/${t}/${e}/_index.json`:`${Qi}/${t}/${e}/_index.${n}.json`}function TM(){return`${ZK}/build-data-recipe.json`}function JK(){return`${KK}/_dependency-map.json`}var Ts={DATA_ROOT:"frelio-data",CONTENT_TYPES:tP,CONTENTS_PRIVATE:`${Qi}/private`,TEMPLATES:h2,ADMIN_ROOT:Tm,ADMIN_CONTENT_TYPES:m2,ADMIN_USERS:rP};function YK(t){return{contentId:t.contentId,title:t.title,status:t.status,createdAt:t.createdAt,updatedAt:t.updatedAt,publishedAt:t.publishedAt,createdBy:t.createdBy,updatedBy:t.updatedBy}}function DC(t,e){const n={contentId:t.contentId,status:t.status,createdAt:t.createdAt,updatedAt:t.updatedAt};for(const r of e){const s=rQ(t,r.field);s!==void 0&&(n[r.field]=s)}return n}function XK(t,e){const n=t.findIndex(r=>r.contentId===e.contentId);if(n>=0){const r=[...t];return r[n]=e,r}return[...t,e]}function eQ(t,e){return t.filter(n=>n.contentId!==e)}function tQ(t,e){const n=t.findIndex(r=>r.contentId===e.contentId);if(n>=0){const r=[...t];return r[n]=e,r}return[...t,e]}function nQ(t,e){return t.filter(n=>n.contentId!==e)}function rQ(t,e){if(e in t)return t[e];if(e.startsWith("data.")){const n=e.substring(5);return t.data[n]}return t.data[e]}async function sP(t,e){const{basePath:n,contentTypeId:r,content:s}=e,i=sc(r),l=await t.readJson(i),u=(l==null?void 0:l.views)??[],p=(l==null?void 0:l.defaultViewId)??null,f=[];for(const m of u){const g=Ql(n,r,m.id,p),y=await t.readJson(g)??[],v=DC(s,m.columns),C=XK(y,v);f.push({path:g,content:JSON.stringify(C,null,2)})}if(u.length===0){const m=Ql(n,r,null,null),g=await t.readJson(m)??[],y=YK(s),v=tQ(g,y);f.push({path:m,content:JSON.stringify(v,null,2)})}return f}async function iP(t,e){const{basePath:n,contentTypeId:r,contentId:s}=e,i=sc(r),l=await t.readJson(i),u=(l==null?void 0:l.views)??[],p=(l==null?void 0:l.defaultViewId)??null,f=[];for(const m of u){const g=Ql(n,r,m.id,p),y=await t.readJson(g)??[],v=eQ(y,s);f.push({path:g,content:JSON.stringify(v,null,2)})}if(u.length===0){const m=Ql(n,r,null,null),g=await t.readJson(m)??[],y=nQ(g,s);f.push({path:m,content:JSON.stringify(y,null,2)})}return f}var oP={lastUpdatedAt:"",lastUpdatedBy:"",totalCount:0,draftCount:0,publishedCount:0};function sQ(t,e,n,r,s,i=new Date().toISOString()){const l={...t,contentTypes:{...t.contentTypes}},u={...l.contentTypes[e]??{...oP}};return u.lastUpdatedAt=i,u.lastUpdatedBy=n,r===null?(u.totalCount+=1,s==="draft"?u.draftCount+=1:s==="published"&&(u.publishedCount+=1)):r!==s&&(r==="draft"&&(u.draftCount-=1),r==="published"&&(u.publishedCount-=1),s==="draft"&&(u.draftCount+=1),s==="published"&&(u.publishedCount+=1)),l.contentTypes[e]=u,l}function iQ(t,e,n,r,s=new Date().toISOString()){const i={...t,contentTypes:{...t.contentTypes}},l={...i.contentTypes[e]??{...oP}};return l.lastUpdatedAt=s,l.lastUpdatedBy=n,l.totalCount=Math.max(0,l.totalCount-1),r==="draft"?l.draftCount=Math.max(0,l.draftCount-1):r==="published"&&(l.publishedCount=Math.max(0,l.publishedCount-1)),i.contentTypes[e]=l,i}var aP={contentTypes:{}};async function lP(t,e){const n=await t.readJson(kh)??{...aP},r=sQ(n,e.contentTypeId,e.updatedBy,e.oldStatus,e.newStatus,e.now);return{path:kh,content:JSON.stringify(r,null,2)}}async function oQ(t,e){const n=await t.readJson(kh)??{...aP},r=iQ(n,e.contentTypeId,e.deletedBy,e.deletedStatus,e.now);return{path:kh,content:JSON.stringify(r,null,2)}}function DM(t,e,n){var s,i;const r=[];if((s=t.branchName)!=null&&s.trim()?(/^[a-zA-Z0-9_\-/]+$/.test(t.branchName)||r.push({field:"branchName",message:"ブランチ名には英数字、ハイフン、アンダースコア、スラッシュのみ使用できます"}),e.some(p=>p.branchName===t.branchName&&p.branchName!==n)&&r.push({field:"branchName",message:"このブランチ名は既に登録されています"})):r.push({field:"branchName",message:"ブランチ名は必須です"}),(i=t.previewUrl)!=null&&i.trim())try{new URL(t.previewUrl)}catch{r.push({field:"previewUrl",message:"有効な URL を入力してください"})}return r}function EM(t){return!t.isDefault}function cP(t,e){const n=e.filter(l=>!l.isDefault),r=n.filter(l=>l.allowedUsers.includes(t)),s=n.filter(l=>l.allowedUsers.length===0),i=[...r];for(const l of s)i.some(u=>u.branchName===l.branchName)||i.push(l);return i}function Dm(){return{branchName:"staging",previewUrl:"",allowedUsers:[],isDefault:!0}}function RM(t){return t.split(",").map(e=>e.trim()).filter(e=>e.length>0)}function aQ(t){return t.join(", ")}const Sv=[{edit:"canEditContent",view:"canViewContent"},{edit:"canEditStorage",view:"canViewStorage"},{edit:"canEditTemplates",view:"canViewTemplates"},{edit:"canEditUsers",view:"canViewUsers"},{edit:"canEditStaging",view:"canViewStaging"},{edit:"canEditContentType",view:"canViewContentType"},{edit:"canEditBuildRecipes",view:"canViewBuildRecipes"},{edit:"canEditDeploy",view:"canViewDeploy"}],Cv={canViewContent:!0,canEditContent:!0,canViewStorage:!0,canEditStorage:!0,canViewTemplates:!0,canEditTemplates:!0,canViewUsers:!0,canEditUsers:!0,canViewStaging:!0,canEditStaging:!0,canViewContentType:!0,canEditContentType:!0,canViewBuildRecipes:!0,canEditBuildRecipes:!0,canViewDeploy:!0,canEditDeploy:!0},lQ={canViewContent:!0,canEditContent:!0,canViewStorage:!0,canEditStorage:!0,canViewTemplates:!0,canEditTemplates:!0,canViewUsers:!1,canEditUsers:!1,canViewStaging:!1,canEditStaging:!1,canViewContentType:!0,canEditContentType:!0,canViewBuildRecipes:!0,canEditBuildRecipes:!0,canViewDeploy:!1,canEditDeploy:!1},cQ={canViewContent:!0,canEditContent:!0,canViewStorage:!0,canEditStorage:!0,canViewTemplates:!0,canEditTemplates:!0,canViewUsers:!1,canEditUsers:!1,canViewStaging:!1,canEditStaging:!1,canViewContentType:!0,canEditContentType:!1,canViewBuildRecipes:!0,canEditBuildRecipes:!1,canViewDeploy:!1,canEditDeploy:!1},uQ={canViewContent:!0,canEditContent:!1,canViewStorage:!0,canEditStorage:!1,canViewTemplates:!0,canEditTemplates:!1,canViewUsers:!1,canEditUsers:!1,canViewStaging:!1,canEditStaging:!1,canViewContentType:!0,canEditContentType:!1,canViewBuildRecipes:!0,canEditBuildRecipes:!1,canViewDeploy:!1,canEditDeploy:!1},wv={owner:Cv,admin:Cv,developer:lQ,editor:cQ,viewer:uQ},dQ={owner:"所有者",admin:"管理者",developer:"開発者",editor:"編集者",viewer:"閲覧者",custom:"カスタム"},uP={content:{label:"コンテンツ",pairs:[{view:"canViewContent",edit:"canEditContent"},{view:"canViewStorage",edit:"canEditStorage"},{view:"canViewTemplates",edit:"canEditTemplates"}]},admin:{label:"管理",pairs:[{view:"canViewUsers",edit:"canEditUsers"},{view:"canViewStaging",edit:"canEditStaging"},{view:"canViewDeploy",edit:"canEditDeploy"}]},development:{label:"開発",pairs:[{view:"canViewContentType",edit:"canEditContentType"},{view:"canViewBuildRecipes",edit:"canEditBuildRecipes"}]}},dP={canViewContent:"コンテンツ",canViewStorage:"ストレージ",canViewTemplates:"テンプレート",canViewUsers:"ユーザー管理",canViewStaging:"ステージング",canViewContentType:"コンテンツタイプ",canViewBuildRecipes:"ビルドレシピ",canViewDeploy:"デプロイ"};function pQ(t,e){return Object.keys(t).every(r=>t[r]===e[r])}function _h(t,e=!1){if(e)return"owner";const n=["admin","developer","editor","viewer"];for(const r of n)if(pQ(t,wv[r]))return r;return"custom"}function Ih(t){return t==="custom"?{...wv.viewer}:{...wv[t]}}function fQ(){return{canViewContent:!1,canEditContent:!1,canViewStorage:!1,canEditStorage:!1,canViewTemplates:!1,canEditTemplates:!1,canViewUsers:!1,canEditUsers:!1,canViewStaging:!1,canEditStaging:!1,canViewContentType:!1,canEditContentType:!1,canViewBuildRecipes:!1,canEditBuildRecipes:!1,canViewDeploy:!1,canEditDeploy:!1}}const Gf=Fs(t=>({isActive:!1,virtualPermissions:null,virtualRoleTemplate:null,simulatedUserDisplayName:null,simulatedGithubUsername:null,startSimulation:(e,n,r,s)=>{t({isActive:!0,virtualPermissions:e,virtualRoleTemplate:n,simulatedUserDisplayName:r,simulatedGithubUsername:s})},stopSimulation:()=>{t({isActive:!1,virtualPermissions:null,virtualRoleTemplate:null,simulatedUserDisplayName:null,simulatedGithubUsername:null})},updatePermissions:(e,n)=>{t({virtualPermissions:e,virtualRoleTemplate:n})}}));let Dy=null,kM=null;function hQ(){const t=Gf.getState();return kM===t&&Dy!==null||(kM=t,Dy={isActive:t.isActive,virtualPermissions:t.virtualPermissions,virtualRoleTemplate:t.virtualRoleTemplate,simulatedUserDisplayName:t.simulatedUserDisplayName,simulatedGithubUsername:t.simulatedGithubUsername}),Dy}class mQ{startSimulation(e,n,r,s){Gf.getState().startSimulation(e,n,r,s)}stopSimulation(){Gf.getState().stopSimulation()}updatePermissions(e,n){Gf.getState().updatePermissions(e,n)}getState(){return hQ()}subscribe(e){return Gf.subscribe(e)}}const Px=new mQ;function ws(t,e){const n=Px.getState();return n.isActive&&n.virtualPermissions?n.virtualPermissions[e]===!0:t?t.isOwner?!0:t.permissions[e]===!0:!1}function gQ(t){return t==="/login"||t.startsWith("/auth/")||t==="/"?null:t==="/users"||t.startsWith("/users/")?"canViewUsers":t==="/staging"||t.startsWith("/staging/")?"canViewStaging":t==="/storage"||t.startsWith("/storage/")?"canViewStorage":t==="/templates"||t.startsWith("/templates/")?"canViewTemplates":t==="/build-recipes"||t.startsWith("/build-recipes/")?"canViewBuildRecipes":t==="/deploy-history"||t.startsWith("/deploy-history/")?"canViewDeploy":t.match(/^\/content-types\/[^/]+\/edit/)||t.match(/^\/content-types\/[^/]+\/views/)||t==="/content-types"||t.startsWith("/content-types/")?"canViewContentType":t.match(/^\/contents\/[^/]+\/new$/)?"canEditContent":t.match(/^\/contents\/[^/]+/)?"canViewContent":null}function yQ(t){return{...wv[t]}}function vQ(t){return{githubUsername:t.githubUsername,displayName:t.displayName,allowPersonalBranch:t.allowPersonalBranch,permissions:yQ(t.role),isOwner:!1}}function xQ(t){let e=!1;return t.map(n=>{const r=vQ(n);return!e&&n.role==="admin"&&(r.isOwner=!0,e=!0),r})}function bQ(t){return{...fQ(),...t}}function SQ(t){return typeof t=="object"&&t!==null&&"role"in t&&!("permissions"in t)}function CQ(t){return t.some(SQ)}function pP(t){return CQ(t)?xQ(t):t.map(e=>({...e,permissions:bQ(e.permissions)}))}let jv=null;async function wQ(){if(jv)return;const e=await fetch("/config.json");if(!e.ok)throw new Error(`Failed to load config.json (${e.status}). Ensure config.json exists at the app root, or set VITE_CONTENT_REPO at build time.`);const n=await e.json();jv={contentRepo:n.contentRepo,githubClientId:n.githubClientId,fileUploadUrl:n.fileUploadUrl??"/api/storage",siteTitle:n.siteTitle??"",productionUrl:n.productionUrl??"",previewUrl:n.previewUrl??""}}function ta(){if(!jv)throw new Error("Config not loaded. Call loadConfig() before accessing config.");return jv}const MM="https://api.github.com",e1="frelio_github_token";class jQ{get contentRepo(){return ta().contentRepo}async fetchGitHubUser(e){oe.debug("GitHubAuthRepositoryImpl.fetchGitHubUser");const n=await fetch(`${MM}/user`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!n.ok)throw oe.error("GitHubAuthRepositoryImpl.fetchGitHubUser","API error",{status:n.status}),(n.status===401||n.status===403)&&Pd.notifyPermissionError(n.status,"ユーザー情報取得"),new lh(n.status,`GitHub API error: ${n.status}`,"ユーザー情報取得");const r=await n.json();return{login:r.login,avatar_url:r.avatar_url,name:r.name}}async fetchAdminData(e){var g;oe.debug("GitHubAuthRepositoryImpl.fetchAdminData");const[n,r]=this.contentRepo.split("/"),s=await fetch(`${MM}/repos/${n}/${r}/contents/${Mh}?ref=develop`,{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!s.ok)throw oe.error("GitHubAuthRepositoryImpl.fetchAdminData","API error",{status:s.status}),(s.status===401||s.status===403)&&Pd.notifyPermissionError(s.status,"管理データ取得"),new lh(s.status,`Failed to fetch admin data: ${s.status}`,"管理データ取得");const i=await s.json(),l=decodeURIComponent(escape(atob(i.content))),u=JSON.parse(l),p=pP(u.users??[]),m=((g=u.stagingBranches)==null?void 0:g.some(y=>y.isDefault))??!1?u.stagingBranches:[Dm(),...u.stagingBranches??[]];return{users:p,stagingBranches:m}}saveToken(e){oe.debug("GitHubAuthRepositoryImpl.saveToken"),localStorage.setItem(e1,e)}getToken(){return localStorage.getItem(e1)}clearToken(){oe.debug("GitHubAuthRepositoryImpl.clearToken"),localStorage.removeItem(e1)}getAuthUrl(){const e=ta().githubClientId;return`https://github.com/login/oauth/authorize?${new URLSearchParams({client_id:e,scope:"repo",redirect_uri:`${window.location.origin}/api/auth/callback`}).toString()}`}}function TQ(t){return t?t.allowPersonalBranch!==!1:!1}function OM(t,e,n){var s,i;const r=[];return(s=t.githubUsername)!=null&&s.trim()?e.some(u=>u.githubUsername===t.githubUsername&&u.githubUsername!==n)&&r.push({field:"githubUsername",message:"このユーザー名は既に登録されています"}):r.push({field:"githubUsername",message:"GitHub ユーザー名は必須です"}),(i=t.displayName)!=null&&i.trim()||r.push({field:"displayName",message:"表示名は必須です"}),t.permissions||r.push({field:"permissions",message:"権限は必須です"}),r}function AM(t,e){return t!==e}function Tv(t){return dQ[t]}function g2(t){return _h(t.permissions,t.isOwner??!1)}const Zf=Fs(t=>({githubUser:null,currentUser:null,token:null,isInitialized:!1,users:[],stagingBranches:[],setAuth:(e,n,r,s,i)=>{t({githubUser:e,currentUser:n,token:r,users:s,stagingBranches:i})},clearAuth:()=>{t({githubUser:null,currentUser:null,token:null,users:[],stagingBranches:[]})},setInitialized:()=>{t({isInitialized:!0})}}));let Ey=null,_M=null;function DQ(){const t=Zf.getState();if(_M===t&&Ey!==null)return Ey;_M=t;const e=t.currentUser,n=(e==null?void 0:e.permissions)??null,r=e?_h(e.permissions,e.isOwner??!1):null,s=(e==null?void 0:e.isOwner)??!1,i=TQ(e??void 0);return Ey={githubUser:t.githubUser,currentUser:t.currentUser,token:t.token,isInitialized:t.isInitialized,users:t.users,stagingBranches:t.stagingBranches,permissions:n,roleTemplate:r,isOwner:s,allowPersonalBranch:i},Ey}class EQ{setAuth(e,n,r,s,i){Zf.getState().setAuth(e,n,r,s,i)}clearAuth(){Zf.getState().clearAuth()}setInitialized(){Zf.getState().setInitialized()}getState(){return DQ()}subscribe(e){return Zf.subscribe(e)}}const Em=new EQ;class fP{constructor(e){this.repository=e}async execute(e){oe.info("LoginUseCase.execute");const n=await this.repository.fetchGitHubUser(e);oe.debug("LoginUseCase.execute","GitHub user fetched",{login:n.login});const r=await this.repository.fetchAdminData(e),{users:s,stagingBranches:i}=r;oe.debug("LoginUseCase.execute","Admin data fetched",{usersCount:s.length,stagingBranchesCount:i.length});const l=s.find(u=>u.githubUsername===n.login);if(!l)throw oe.warn("LoginUseCase.execute","User not authorized",{login:n.login}),new Error(`User ${n.login} is not authorized`);return this.repository.saveToken(e),oe.info("LoginUseCase.execute","Login successful",{login:n.login}),{user:l,githubUser:n,users:s,stagingBranches:i}}async restoreSession(){oe.debug("LoginUseCase.restoreSession");const e=this.repository.getToken();if(!e)return oe.debug("LoginUseCase.restoreSession","No token found"),null;try{return await this.execute(e)}catch(n){return oe.warn("LoginUseCase.restoreSession","Failed to restore session",{error:n}),this.repository.clearToken(),null}}}class RQ{constructor(e){this.repository=e}execute(){oe.info("LogoutUseCase.execute"),this.repository.clearToken()}}class kQ{constructor(e){this.repository=e}execute(){return oe.debug("GetAuthUrlUseCase.execute"),this.repository.getAuthUrl()}}class MQ{constructor(e,n){this.repository=e,this.presenter=n}async execute(){oe.debug("InitAuthUseCase.execute");const e=this.repository.getToken();if(!e){oe.debug("InitAuthUseCase.execute","No token found"),this.presenter.setInitialized();return}try{oe.debug("InitAuthUseCase.execute","Restoring session...");const r=await new fP(this.repository).execute(e);this.presenter.setAuth(r.githubUser,r.user,e,r.users,r.stagingBranches),oe.info("InitAuthUseCase.execute","Session restored",{login:r.githubUser.login})}catch(n){oe.warn("InitAuthUseCase.execute","Failed to restore session",{error:n}),this.repository.clearToken(),this.presenter.clearAuth()}finally{this.presenter.setInitialized()}}}class OQ{constructor(e){this.deps=e}getState(){return this.deps.presenter.getState()}async login(e){const{presenter:n,loginUseCase:r}=this.deps,s=await r.execute(e);return n.setAuth(s.githubUser,s.user,e,s.users,s.stagingBranches),s}logout(){const{presenter:e,logoutUseCase:n}=this.deps;n.execute(),e.clearAuth()}getAuthUrl(){return this.deps.getAuthUrlUseCase.execute()}}let t1=!1;const Lx=new jQ,AQ=new fP(Lx),_Q=new RQ(Lx),IQ=new kQ(Lx),PQ=new MQ(Lx,Em),IM=new OQ({presenter:Em,loginUseCase:AQ,logoutUseCase:_Q,getAuthUrlUseCase:IQ}),LQ=t=>Em.subscribe(t),PM=()=>Em.getState();function rr(){b.useSyncExternalStore(LQ,PM,PM);const t=IM.getState(),e=b.useRef(!1);return b.useEffect(()=>{t.isInitialized||e.current||t1||(e.current=!0,t1=!0,PQ.execute().finally(()=>{t1=!1}))},[t.isInitialized]),{authUseCase:IM}}function Qr(){return ta().contentRepo}const zQ="https://api.github.com/graphql";class At{constructor(e){this.token=e}async fetchFile(e,n="main"){const[r,s]=Qr().split("/"),i=`${n}:${e}`,u=await this.graphql(`
280
280
  query GetFile($owner: String!, $repo: String!, $expression: String!) {
281
281
  repository(owner: $owner, name: $repo) {
282
282
  object(expression: $expression) {
@@ -382,8 +382,8 @@ OAuth App に組織へのアクセス権を付与してください:
382
382
  }
383
383
  }
384
384
  }
385
- `,m={branch:{repositoryNameWithOwner:`${s}/${i}`,branchName:r},message:{headline:e},expectedHeadOid:l,fileChanges:{}};return u.length>0&&(m.fileChanges.additions=u),p.length>0&&(m.fileChanges.deletions=p),(await this.graphql(f,{input:m})).createCommitOnBranch.commit.oid}handleApiError(e,n){throw(e===401||e===403)&&Pd.notifyPermissionError(e,n),new lh(e,`GitHub API error: ${e}`,n)}async graphql(e,n){const r=await fetch(zQ,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:n})});r.ok||this.handleApiError(r.status,"GraphQL");const s=await r.json();if(s.errors)throw new Error(`GitHub GraphQL errors: ${JSON.stringify(s.errors)}`);return s.data}async triggerWorkflow(e,n="main"){const[r,s]=Qr().split("/"),i=await fetch(`https://api.github.com/repos/${r}/${s}/actions/workflows/${e}/dispatches`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({ref:n})});if(!i.ok){const l=await i.text();this.handleApiError(i.status,`ワークフロー実行 ${l}`)}}async getLatestWorkflowRun(e){const[n,r]=Qr().split("/"),s=await fetch(`https://api.github.com/repos/${n}/${r}/actions/workflows/${e}/runs?per_page=1`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github.v3+json"}});return s.ok||this.handleApiError(s.status,"ワークフロー実行状態取得"),(await s.json()).workflow_runs[0]??null}}const LM="frelio-branch-type",y2="frelio-branch-diff-cache";function n1(t){try{localStorage.setItem(y2,JSON.stringify(t))}catch{}}function $Q(){try{const t=localStorage.getItem(y2);return t?JSON.parse(t):null}catch{return null}}function If(){try{localStorage.removeItem(y2)}catch{}}const NQ={currentBranch:"develop",branchType:"develop",hasDiff:!1,diffCount:0,behindCount:0,conflicts:[],changedContents:[],isLoading:!1,isSyncing:!1,error:null};class FQ{constructor(){St(this,"state",{...NQ});St(this,"listeners",new Set);this.getSavedBranchType()==="personal"&&(this.state.branchType="personal")}getState(){return this.state}getSavedBranchType(){try{if(localStorage.getItem(LM)==="personal")return"personal"}catch{}return"develop"}setBranch(e,n){this.state={...this.state,currentBranch:e,branchType:n};try{localStorage.setItem(LM,n)}catch{}this.notify()}setDiffStatus(e,n,r){this.state={...this.state,hasDiff:e,diffCount:n,behindCount:r},this.notify()}setConflicts(e){this.state={...this.state,conflicts:e},this.notify()}setChangedContents(e){this.state={...this.state,changedContents:e},this.notify()}setLoading(e){this.state={...this.state,isLoading:e},this.notify()}setSyncing(e){this.state={...this.state,isSyncing:e},this.notify()}setError(e){this.state={...this.state,error:e},this.notify()}clearConflicts(){this.state={...this.state,conflicts:[]},this.notify()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){this.listeners.forEach(e=>e())}}const Rm=new FQ,BQ="frelio-cms",mr="develop",zM="main",r1=[3e3,5e3,1e4],UQ=3,s1=[5e3,1e4,15e3,2e4,3e4],VQ=5;function HQ(t){return t.toLowerCase().replace(/[._]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function $M(t){return`${BQ}/${HQ(t)}`}class WQ{constructor(e,n,r){St(this,"syncTimeoutId",null);this.presenter=e,this.gitHubClient=n,this.username=r}getState(){return{...this.presenter.getState(),developBranchName:mr,personalBranchName:$M(this.username)}}getCurrentBranch(){return this.presenter.getState().currentBranch}async switchToDevelop(){oe.info("BranchUseCase.switchToDevelop"),this.presenter.setLoading(!0),this.presenter.setError(null);try{await this.gitHubClient.ensureBranch(mr,zM),this.presenter.setBranch(mr,"develop"),this.presenter.setDiffStatus(!1,0,0),this.presenter.clearConflicts(),oe.info("BranchUseCase.switchToDevelop completed")}catch(e){throw oe.error("BranchUseCase.switchToDevelop failed",{error:e}),this.presenter.setError(e instanceof Error?e:new Error(String(e))),e}finally{this.presenter.setLoading(!1)}}async switchToPersonal(){const e=$M(this.username);oe.info("BranchUseCase.switchToPersonal",{personalBranch:e}),this.presenter.setLoading(!0),this.presenter.setError(null);try{await this.gitHubClient.ensureBranch(mr,zM),await this.gitHubClient.ensureBranch(e,mr),this.presenter.setBranch(e,"personal"),await this.checkDiff(),oe.info("BranchUseCase.switchToPersonal completed",{personalBranch:e})}catch(n){throw oe.error("BranchUseCase.switchToPersonal failed",{error:n}),this.presenter.setError(n instanceof Error?n:new Error(String(n))),n}finally{this.presenter.setLoading(!1)}}async checkDiff(){const e=this.presenter.getState();if(e.branchType==="develop"){this.presenter.setDiffStatus(!1,0,0),If();return}oe.info("BranchUseCase.checkDiff",{branch:e.currentBranch});const n=$Q();if(n){this.presenter.setDiffStatus(n.hasDiff,n.diffCount,n.behindCount),this.presenter.setSyncing(!0),oe.info("BranchUseCase.checkDiff: using cache, syncing",{hasDiff:n.hasDiff,diffCount:n.diffCount,age:Date.now()-n.timestamp}),this.startBackgroundSyncSilent();return}try{const[r,s]=await Promise.all([this.gitHubClient.compareBranches(mr,e.currentBranch),this.gitHubClient.compareBranches(e.currentBranch,mr)]),i=r.files.length>0,l=s.files.length>0?r.behind:0;this.presenter.setDiffStatus(i,r.ahead,l),oe.info("BranchUseCase.checkDiff completed",{ahead:r.ahead,behind:r.behind,aheadFilesCount:r.files.length,behindFilesCount:s.files.length})}catch(r){oe.error("BranchUseCase.checkDiff failed",{error:r}),this.presenter.setDiffStatus(!1,0,0)}}startBackgroundSyncSilent(){this.syncTimeoutId!==null&&(clearTimeout(this.syncTimeoutId),this.syncTimeoutId=null),this.backgroundSyncSilentWithRetry(0)}backgroundSyncSilentWithRetry(e){const n=s1[e]??s1[s1.length-1];this.syncTimeoutId=setTimeout(async()=>{const r=this.presenter.getState();if(r.branchType==="develop"){this.presenter.setSyncing(!1);return}oe.info("BranchUseCase.backgroundSyncSilent: checking",{retry:e});try{const[s,i]=await Promise.all([this.gitHubClient.compareBranches(mr,r.currentBranch),this.gitHubClient.compareBranches(r.currentBranch,mr)]),l=s.files.length>0,u=i.files.length>0?s.behind:0,p=this.presenter.getState();p.hasDiff===l?(this.presenter.setDiffStatus(l,s.ahead,u),this.presenter.setSyncing(!1),If(),oe.info("BranchUseCase.backgroundSyncSilent: synced, cache cleared",{ahead:s.ahead,behind:u})):e<VQ-1?(oe.info("BranchUseCase.backgroundSyncSilent: inconsistent, retrying",{cached:{hasDiff:p.hasDiff,diffCount:p.diffCount},api:{hasDiff:l,ahead:s.ahead},retry:e+1}),this.backgroundSyncSilentWithRetry(e+1)):(this.presenter.setDiffStatus(l,s.ahead,u),this.presenter.setSyncing(!1),If(),oe.warn("BranchUseCase.backgroundSyncSilent: max retries reached, using API value",{ahead:s.ahead,behind:u}))}catch(s){oe.error("BranchUseCase.backgroundSyncSilent: failed",{error:s}),this.presenter.setSyncing(!1)}},n)}async refreshDiff(){await this.checkDiff()}async refreshDiffAfterSave(){const e=this.presenter.getState();if(e.branchType==="develop")return;const n=e.diffCount+1;this.presenter.setDiffStatus(!0,n,e.behindCount),n1({hasDiff:!0,diffCount:n,behindCount:e.behindCount,timestamp:Date.now()}),oe.info("BranchUseCase.refreshDiffAfterSave: optimistic update + cache",{diffCount:n}),this.startBackgroundSync()}async refreshDiffAfterMerge(){this.presenter.getState().branchType!=="develop"&&(this.presenter.setDiffStatus(!1,0,0),n1({hasDiff:!1,diffCount:0,behindCount:0,timestamp:Date.now()}),oe.info("BranchUseCase.refreshDiffAfterMerge: optimistic update + cache (no diff)"),this.startBackgroundSync())}async refreshDiffAfterRebase(){const e=this.presenter.getState();e.branchType!=="develop"&&(this.presenter.setDiffStatus(e.hasDiff,e.diffCount,0),n1({hasDiff:e.hasDiff,diffCount:e.diffCount,behindCount:0,timestamp:Date.now()}),oe.info("BranchUseCase.refreshDiffAfterRebase: optimistic update + cache",{hasDiff:e.hasDiff,diffCount:e.diffCount,behindCount:0}),this.startBackgroundSync())}startBackgroundSync(){this.syncTimeoutId!==null&&(clearTimeout(this.syncTimeoutId),this.syncTimeoutId=null),this.presenter.setSyncing(!0),this.backgroundSyncWithRetry(0)}backgroundSyncWithRetry(e){const n=r1[e]??r1[r1.length-1];this.syncTimeoutId=setTimeout(async()=>{const r=this.presenter.getState();if(r.branchType==="develop"){this.presenter.setSyncing(!1);return}oe.info("BranchUseCase.backgroundSync: checking",{retry:e});try{const[s,i]=await Promise.all([this.gitHubClient.compareBranches(mr,r.currentBranch),this.gitHubClient.compareBranches(r.currentBranch,mr)]),l=s.files.length>0,u=i.files.length>0?s.behind:0,p=this.presenter.getState();p.hasDiff===l?(this.presenter.setDiffStatus(l,s.ahead,u),this.presenter.setSyncing(!1),If(),oe.info("BranchUseCase.backgroundSync: synced, cache cleared",{ahead:s.ahead,behind:u})):e<UQ-1?(oe.info("BranchUseCase.backgroundSync: inconsistent, retrying",{localHasDiff:p.hasDiff,apiHasDiff:l,retry:e+1}),this.backgroundSyncWithRetry(e+1)):(this.presenter.setDiffStatus(l,s.ahead,u),this.presenter.setSyncing(!1),If(),oe.warn("BranchUseCase.backgroundSync: max retries reached, using API value",{ahead:s.ahead,behind:u}))}catch(s){oe.error("BranchUseCase.backgroundSync: failed",{error:s}),this.presenter.setSyncing(!1)}},n)}cancelBackgroundSync(){this.syncTimeoutId!==null&&(clearTimeout(this.syncTimeoutId),this.syncTimeoutId=null,this.presenter.setSyncing(!1))}async rebaseFromDevelop(){const e=this.presenter.getState();if(e.branchType==="develop")return oe.info("BranchUseCase.rebaseFromDevelop: skipped (on develop)"),!1;oe.info("BranchUseCase.rebaseFromDevelop",{branch:e.currentBranch}),this.presenter.setLoading(!0),this.presenter.setError(null);try{const n=await this.gitHubClient.mergeBranches(e.currentBranch,mr,`Merge develop into ${e.currentBranch}`);if(oe.info("BranchUseCase.rebaseFromDevelop: merge result",{sha:n.sha,hasConflict:n.hasConflict}),n.hasConflict){if(oe.warn("BranchUseCase.rebaseFromDevelop: conflict detected"),await this.fetchConflictingContents(),this.presenter.getState().conflicts.length===0){oe.info("BranchUseCase.rebaseFromDevelop: no real conflicts, auto-resolving");const s=await this.gitHubClient.findConflictingFiles(e.currentBranch,mr),i=await Promise.all(s.map(async u=>{const p=await this.gitHubClient.fetchFileOrNull(u,mr);return{path:u,content:p??"",delete:p===null}}));i.length>0&&(await this.gitHubClient.commitFiles("Auto-resolve conflicts: accept develop version",i,e.currentBranch),oe.info("BranchUseCase.rebaseFromDevelop: auto-resolve committed",{count:i.length}));const l=await this.gitHubClient.mergeBranches(e.currentBranch,mr,`Merge develop into ${e.currentBranch}`);return oe.info("BranchUseCase.rebaseFromDevelop: retry merge result",{sha:l.sha,hasConflict:l.hasConflict}),l.hasConflict?(oe.warn("BranchUseCase.rebaseFromDevelop: still has conflict after auto-resolve"),await this.fetchConflictingContents(),!0):(await this.refreshDiffAfterRebase(),oe.info("BranchUseCase.rebaseFromDevelop: auto-resolved and merged"),!1)}return!0}return await this.refreshDiffAfterRebase(),oe.info("BranchUseCase.rebaseFromDevelop completed",{sha:n.sha}),!1}catch(n){throw oe.error("BranchUseCase.rebaseFromDevelop failed",{error:n}),this.presenter.setError(n instanceof Error?n:new Error(String(n))),n}finally{this.presenter.setLoading(!1)}}async fetchConflictingContents(){const e=this.presenter.getState();if(e.branchType==="develop"){this.presenter.setConflicts([]);return}oe.info("BranchUseCase.fetchConflictingContents",{branch:e.currentBranch});try{const r=(await this.gitHubClient.findConflictingFiles(e.currentBranch,mr)).map(l=>{const u=this.parseContentPath(l);return u?{...u,path:l}:null}).filter(l=>l!==null),i=(await Promise.all(r.map(async l=>{try{const[u,p]=await Promise.all([this.gitHubClient.fetchFileOrNull(l.path,e.currentBranch),this.gitHubClient.fetchFileOrNull(l.path,mr)]);return u===p?null:{contentTypeId:l.contentTypeId,contentId:l.contentId,title:l.contentId,path:l.path}}catch{return{contentTypeId:l.contentTypeId,contentId:l.contentId,title:l.contentId,path:l.path}}}))).filter(l=>l!==null);this.presenter.setConflicts(i),oe.info("BranchUseCase.fetchConflictingContents completed",{candidateCount:r.length,realConflictCount:i.length})}catch(n){oe.error("BranchUseCase.fetchConflictingContents failed",{error:n}),this.presenter.setConflicts([])}}async discardConflictingFiles(){const e=this.presenter.getState();if(e.branchType==="develop"){oe.info("BranchUseCase.discardConflictingFiles: skipped (on develop)");return}const n=e.conflicts;if(n.length===0){oe.info("BranchUseCase.discardConflictingFiles: no conflicts");return}oe.info("BranchUseCase.discardConflictingFiles",{branch:e.currentBranch,count:n.length}),this.presenter.setLoading(!0),this.presenter.setError(null);try{const r=await Promise.all(n.map(async s=>{const i=await this.gitHubClient.fetchFileOrNull(s.path,mr);return{path:s.path,content:i??"",delete:i===null}}));await this.gitHubClient.commitFiles("Resolve conflicts by accepting develop version",r,e.currentBranch),this.presenter.clearConflicts(),await this.checkDiff(),oe.info("BranchUseCase.discardConflictingFiles completed")}catch(r){throw oe.error("BranchUseCase.discardConflictingFiles failed",{error:r}),this.presenter.setError(r instanceof Error?r:new Error(String(r))),r}finally{this.presenter.setLoading(!1)}}async discardPersonalChanges(){const e=this.presenter.getState();if(e.branchType==="develop"){oe.info("BranchUseCase.discardPersonalChanges: skipped (on develop)");return}oe.info("BranchUseCase.discardPersonalChanges",{branch:e.currentBranch}),this.presenter.setLoading(!0),this.presenter.setError(null);try{await this.gitHubClient.resetBranch(e.currentBranch,mr),this.presenter.setDiffStatus(!1,0,0),this.presenter.clearConflicts(),oe.info("BranchUseCase.discardPersonalChanges completed")}catch(n){throw oe.error("BranchUseCase.discardPersonalChanges failed",{error:n}),this.presenter.setError(n instanceof Error?n:new Error(String(n))),n}finally{this.presenter.setLoading(!1)}}async fetchChangedContents(){const e=this.presenter.getState();if(e.branchType==="develop"){oe.info("BranchUseCase.fetchChangedContents: skipped (on develop)"),this.presenter.setChangedContents([]);return}oe.info("BranchUseCase.fetchChangedContents",{branch:e.currentBranch}),this.presenter.setLoading(!0);try{const n=await this.gitHubClient.compareBranches(mr,e.currentBranch),r=[];for(const s of n.files){const i=this.parseContentPath(s.filename);i&&r.push({...i,status:s.status==="renamed"?"modified":s.status})}this.presenter.setChangedContents(r),oe.info("BranchUseCase.fetchChangedContents completed",{count:r.length})}catch(n){oe.error("BranchUseCase.fetchChangedContents failed",{error:n}),this.presenter.setChangedContents([])}finally{this.presenter.setLoading(!1)}}parseContentPath(e){if(e.endsWith("_index.json"))return null;const n=e.match(/^frelio-data\/site\/contents\/published\/([^/]+)\/([^/]+)\.json$/);if(n)return{basePath:"published",contentTypeId:n[1],contentId:n[2]};const r=e.match(/^frelio-data\/site\/contents\/private\/([^/]+)\/([^/]+)\.json$/);return r?{basePath:"private",contentTypeId:r[1],contentId:r[2]}:null}async pullContentFromDevelop(e){const n=this.presenter.getState();if(n.branchType==="develop"){oe.info("BranchUseCase.pullContentFromDevelop: skipped (on develop)");return}const r=`${Qi}/${e.basePath}/${e.contentTypeId}/${e.contentId}.json`;oe.info("BranchUseCase.pullContentFromDevelop",{filePath:r}),this.presenter.setLoading(!0),this.presenter.setError(null);try{const s=await this.gitHubClient.fetchFileOrNull(r,mr);s===null?await this.gitHubClient.commitFiles(`Pull from develop: delete ${e.contentId}`,[{path:r,content:"",delete:!0}],n.currentBranch):await this.gitHubClient.commitFiles(`Pull from develop: ${e.contentId}`,[{path:r,content:s,delete:!1}],n.currentBranch),await this.checkDiff(),oe.info("BranchUseCase.pullContentFromDevelop completed")}catch(s){throw oe.error("BranchUseCase.pullContentFromDevelop failed",{error:s}),this.presenter.setError(s instanceof Error?s:new Error(String(s))),s}finally{this.presenter.setLoading(!1)}}async isSameAsDevelop(e){if(this.presenter.getState().branchType==="develop")return!0;const r=`${Qi}/${e.basePath}/${e.contentTypeId}/${e.contentId}.json`;try{const s=await this.gitHubClient.fetchFileOrNull(r,mr);if(s===null)return!1;const i=JSON.parse(s);return JSON.stringify(i)===JSON.stringify(e.content)}catch{return!1}}async mergeToDevelop(){const e=this.presenter.getState();if(e.branchType==="develop")return oe.info("BranchUseCase.mergeToDevelop: skipped (on develop)"),{success:!0,hasConflict:!1};if(!e.hasDiff)return oe.info("BranchUseCase.mergeToDevelop: skipped (no diff)"),{success:!0,hasConflict:!1};oe.info("BranchUseCase.mergeToDevelop",{branch:e.currentBranch}),this.presenter.setLoading(!0),this.presenter.setError(null);try{const n=await this.gitHubClient.mergeBranches(mr,e.currentBranch,`Merge ${e.currentBranch} into develop`);return oe.info("BranchUseCase.mergeToDevelop: merge result",{sha:n.sha,hasConflict:n.hasConflict}),n.hasConflict?(oe.warn("BranchUseCase.mergeToDevelop: conflict detected"),await this.fetchConflictingContents(),{success:!1,hasConflict:!0}):(n.sha?(await this.gitHubClient.resetBranchToCommit(e.currentBranch,n.sha),oe.info("BranchUseCase.mergeToDevelop: fast-forwarded personal branch to merge commit",{sha:n.sha})):(await this.gitHubClient.resetBranch(e.currentBranch,mr),oe.info("BranchUseCase.mergeToDevelop: fast-forwarded personal branch to develop (already merged)")),await this.refreshDiffAfterMerge(),oe.info("BranchUseCase.mergeToDevelop completed",{sha:n.sha}),{success:!0,hasConflict:!1})}catch(n){throw oe.error("BranchUseCase.mergeToDevelop failed",{error:n}),this.presenter.setError(n instanceof Error?n:new Error(String(n))),n}finally{this.presenter.setLoading(!1)}}async initialize(){const e=this.presenter.getSavedBranchType();oe.info("BranchUseCase.initialize",{savedBranchType:e}),e==="personal"?await this.switchToPersonal():await this.switchToDevelop(),oe.info("BranchUseCase.initialize completed",{savedBranchType:e})}}const qQ=t=>Rm.subscribe(t),NM=()=>Rm.getState();function Ei(){const{authUseCase:t}=rr(),{token:e,githubUser:n,allowPersonalBranch:r}=t.getState(),s=b.useRef(!1);b.useSyncExternalStore(qQ,NM,NM);const i=b.useMemo(()=>{if(!e||!n)return null;const l=new At(e);return new WQ(Rm,l,n.login)},[e,n]);return b.useEffect(()=>{if(!(!i||s.current)){if(s.current=!0,!r){i.switchToDevelop();return}i.initialize()}},[i,r]),{branchUseCase:i}}function GQ(){return{users:[],stagingBranches:[Dm()]}}class uu{constructor(e,n){this.queries=e,this.saveMutation=n}static AdminDataQueryParams(e,n){return{queryKey:["adminData",n],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJsonOrDefault(Mh,GQ(),n)},enabled:!!e}}static SaveAdminDataMutationParams(e,n,r){return{mutationFn:async s=>{if(!n)throw new Error("Not authenticated");await new At(n).commitFiles("chore: ユーザー一覧を更新",[{path:Mh,content:JSON.stringify(s,null,2)}],r)},onSuccess:()=>{e.invalidateQueries({queryKey:["adminData",r]})}}}getUsers(){var n;const e=((n=this.queries.adminData.data)==null?void 0:n.users)??[];return pP(e)}isLoading(){return this.queries.adminData.isLoading}getError(){return this.queries.adminData.error}async saveUsers(e){const n=this.queries.adminData.data,r={users:e,stagingBranches:(n==null?void 0:n.stagingBranches)??[Dm()]};await this.saveMutation.mutateAsync(r)}isSaving(){return this.saveMutation.isPending}}const Ry=20;function ZQ(t,e){if(!t)return"不明";const n=e.find(r=>r.githubUsername===t);return(n==null?void 0:n.displayName)??t}function FM(t,e){return{sha:t.sha,shortSha:t.sha.slice(0,7),message:t.message,authorGithubUsername:t.author.login,authorDisplayName:ZQ(t.author.login,e),date:new Date(t.author.date)}}class i1{constructor(e,n,r,s,i,l,u,p){this.queries=e,this.users=n,this.token=r,this.paginationState=s,this.updatePaginationState=i,this.folderPath=l,this.filePath=u,this.branch=p}static FolderCommitsQueryParams(e,n,r){return{queryKey:["activityLog","folder",n,r],queryFn:async()=>!e||!n?{commits:[],hasMore:!1}:new At(e).getCommits(n,r,Ry,1),enabled:!!e&&!!n}}static FileCommitsQueryParams(e,n,r){return{queryKey:["activityLog","file",n,r],queryFn:async()=>!e||!n?{commits:[],hasMore:!1}:new At(e).getCommits(n,r,Ry,1),enabled:!!e&&!!n}}getFolderCommits(){var r;return[...((r=this.queries.folderCommits.data)==null?void 0:r.commits)??[],...this.paginationState.additionalFolderCommits].map(s=>FM(s,this.users))}getFileCommits(){var r;return[...((r=this.queries.fileCommits.data)==null?void 0:r.commits)??[],...this.paginationState.additionalFileCommits].map(s=>FM(s,this.users))}isFolderLoading(){return this.queries.folderCommits.isLoading}isFileLoading(){return this.queries.fileCommits.isLoading}isFolderFetchingMore(){return this.paginationState.isFolderFetchingMore}isFileFetchingMore(){return this.paginationState.isFileFetchingMore}hasFolderMore(){var e;return this.paginationState.folderPage===1?((e=this.queries.folderCommits.data)==null?void 0:e.hasMore)??!1:this.paginationState.folderHasMore}hasFileMore(){var e;return this.paginationState.filePage===1?((e=this.queries.fileCommits.data)==null?void 0:e.hasMore)??!1:this.paginationState.fileHasMore}getFolderError(){return this.queries.folderCommits.error}getFileError(){return this.queries.fileCommits.error}async fetchMoreFolderCommits(){if(!(!this.token||!this.folderPath)&&!this.paginationState.isFolderFetchingMore){this.updatePaginationState({isFolderFetchingMore:!0});try{const e=new At(this.token),n=this.paginationState.folderPage+1,r=await e.getCommits(this.folderPath,this.branch,Ry,n);this.updatePaginationState({folderPage:n,additionalFolderCommits:[...this.paginationState.additionalFolderCommits,...r.commits],folderHasMore:r.hasMore,isFolderFetchingMore:!1})}catch{this.updatePaginationState({isFolderFetchingMore:!1})}}}async fetchMoreFileCommits(){if(!(!this.token||!this.filePath)&&!this.paginationState.isFileFetchingMore){this.updatePaginationState({isFileFetchingMore:!0});try{const e=new At(this.token),n=this.paginationState.filePage+1,r=await e.getCommits(this.filePath,this.branch,Ry,n);this.updatePaginationState({filePage:n,additionalFileCommits:[...this.paginationState.additionalFileCommits,...r.commits],fileHasMore:r.hasMore,isFileFetchingMore:!1})}catch{this.updatePaginationState({isFileFetchingMore:!1})}}}async getFileContentAtCommit(e,n){if(!this.token)throw new Error("Not authenticated");return new At(this.token).fetchFile(n,e)}}const hP="frelio_activity_log_open";function KQ(){try{return localStorage.getItem(hP)==="true"}catch{return!1}}function QQ(t){try{localStorage.setItem(hP,t?"true":"false")}catch{}}function JQ(){return Fs(t=>({isOpen:KQ(),activeTab:"folder",fileContentDialogSha:null,fileContentDialogPath:null,setOpen:e=>{QQ(e),t({isOpen:e})},setActiveTab:e=>t({activeTab:e}),setFileContentDialog:(e,n)=>t({fileContentDialogSha:e,fileContentDialogPath:n})}))}let o1=null;function YQ(){return o1||(o1=JQ()),o1}let ky=null,BM=null;class XQ{constructor(){St(this,"store",YQ())}getState(){const e=this.store.getState();return BM===e&&ky!==null||(BM=e,ky={isOpen:e.isOpen,activeTab:e.activeTab,fileContentDialogSha:e.fileContentDialogSha,fileContentDialogPath:e.fileContentDialogPath}),ky}subscribe(e){return this.store.subscribe(e)}open(){this.store.getState().setOpen(!0)}close(){this.store.getState().setOpen(!1)}toggle(){const e=this.store.getState().isOpen;this.store.getState().setOpen(!e)}setActiveTab(e){this.store.getState().setActiveTab(e)}openFileContentDialog(e,n){this.store.getState().setFileContentDialog(e,n)}closeFileContentDialog(){this.store.getState().setFileContentDialog(null,null)}}class eJ{constructor(e,n,r){this.repository=e,this.presenter=n,this.paths=r}getState(){var n,r;const e=this.presenter.getState();return{isAvailable:this.paths!==null,isOpen:e.isOpen,activeTab:e.activeTab,folderCommits:this.repository.getFolderCommits(),fileCommits:this.repository.getFileCommits(),isFolderLoading:this.repository.isFolderLoading(),isFileLoading:this.repository.isFileLoading(),isFolderFetchingMore:this.repository.isFolderFetchingMore(),isFileFetchingMore:this.repository.isFileFetchingMore(),hasFolderMore:this.repository.hasFolderMore(),hasFileMore:this.repository.hasFileMore(),folderError:this.repository.getFolderError(),fileError:this.repository.getFileError(),fileTabEnabled:((n=this.paths)==null?void 0:n.filePath)!==null&&((r=this.paths)==null?void 0:r.filePath)!==void 0,paths:this.paths,fileContentDialogSha:e.fileContentDialogSha,fileContentDialogPath:e.fileContentDialogPath}}subscribe(e){return this.presenter.subscribe(e)}open(){this.presenter.open()}close(){this.presenter.close()}toggle(){this.presenter.toggle()}setActiveTab(e){this.presenter.setActiveTab(e)}async loadMoreFolderCommits(){await this.repository.fetchMoreFolderCommits()}async loadMoreFileCommits(){await this.repository.fetchMoreFileCommits()}async getFileContentAtCommit(e){var r;const n=(r=this.paths)==null?void 0:r.filePath;if(!n)throw new Error("File path is not available");return this.repository.getFileContentAtCommit(e,n)}openFileContentDialog(e){var r;const n=(r=this.paths)==null?void 0:r.filePath;n&&this.presenter.openFileContentDialog(e,n)}closeFileContentDialog(){this.presenter.closeFileContentDialog()}}function tJ(t,e,n){if(t.startsWith("/storage")||t.startsWith("/login")||t.startsWith("/auth"))return null;if(t==="/")return{folderPath:Ts.DATA_ROOT,filePath:null};if(/^\/contents\/[^/]+\/?$/.test(t)){const r=e.contentTypeId;return r?{folderPath:`${Ts.CONTENTS_PRIVATE}/${r}`,filePath:null}:null}if(/^\/contents\/[^/]+\/[^/]+$/.test(t)){const{contentTypeId:r,contentId:s}=e;return!r||!s?null:{folderPath:`${Ts.CONTENTS_PRIVATE}/${r}`,filePath:`${Ts.CONTENTS_PRIVATE}/${r}/${s}.json`}}if(t==="/content-types"||t==="/content-types/")return{folderPath:Ts.CONTENT_TYPES,filePath:null};if(/^\/content-types\/[^/]+\/edit$/.test(t)){const r=e.contentTypeId;return r?{folderPath:Ts.CONTENT_TYPES,filePath:`${Ts.CONTENT_TYPES}/${r}.json`}:null}if(/^\/content-types\/[^/]+\/views$/.test(t)){const r=e.contentTypeId;return r?{folderPath:Ts.ADMIN_CONTENT_TYPES,filePath:`${Ts.ADMIN_CONTENT_TYPES}/${r}.views.json`}:null}return t==="/templates"||t==="/templates/"?{folderPath:Ts.TEMPLATES,filePath:n??null}:t==="/build-recipes"||t==="/build-recipes/"?{folderPath:`${Ts.ADMIN_ROOT}/recipes`,filePath:`${Ts.ADMIN_ROOT}/recipes/build-data-recipe.json`}:t==="/users"||t==="/users/"?{folderPath:Ts.ADMIN_USERS,filePath:null}:t==="/staging"||t==="/staging/"?{folderPath:Ts.ADMIN_USERS,filePath:null}:{folderPath:Ts.DATA_ROOT,filePath:null}}const v2=new XQ,nJ=t=>v2.subscribe(t),UM=()=>v2.getState(),rJ="develop",EC=new Map;function sJ(t,e){return`${t??""}|${e??""}`}function VM(t){let e=EC.get(t);return e||(e={folderPage:1,filePage:1,additionalFolderCommits:[],additionalFileCommits:[],folderHasMore:!0,fileHasMore:!0,isFolderFetchingMore:!1,isFileFetchingMore:!1},EC.set(t,e)),e}function iJ(t){const e=ox(),n=uc({strict:!1});return b.useMemo(()=>tJ(e.pathname,n,t),[e.pathname,n,t])}function oJ(t){var j;const{authUseCase:e}=rr(),{branchUseCase:n}=Ei(),{token:r}=e.getState(),s=(n==null?void 0:n.getCurrentBranch())??"develop";b.useSyncExternalStore(nJ,UM,UM);const i=iJ(t),u=((j=jn(uu.AdminDataQueryParams(r,rJ)).data)==null?void 0:j.users)??[],p=sJ((i==null?void 0:i.folderPath)??null,(i==null?void 0:i.filePath)??null),f=b.useRef({key:p,state:VM(p)});f.current.key!==p&&(f.current={key:p,state:VM(p)});const m=b.useRef(0),g=b.useMemo(()=>D=>{const T={...f.current.state,...D};f.current.state=T,EC.set(f.current.key,T),m.current+=1},[]),y=jn(i1.FolderCommitsQueryParams(r,(i==null?void 0:i.folderPath)??null,s)),v=jn(i1.FileCommitsQueryParams(r,(i==null?void 0:i.filePath)??null,s)),C=new i1({folderCommits:y,fileCommits:v},u,r,f.current.state,g,(i==null?void 0:i.folderPath)??null,(i==null?void 0:i.filePath)??null,s);return{activityLogUseCase:new eJ(C,v2,i)}}const aJ=ye([a.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),a.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")],"AccessTime"),lJ=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 4c1.93 0 3.5 1.57 3.5 3.5S13.93 13 12 13s-3.5-1.57-3.5-3.5S10.07 6 12 6m0 14c-2.03 0-4.43-.82-6.14-2.88C7.55 15.8 9.68 15 12 15s4.45.8 6.14 2.12C16.43 19.18 14.03 20 12 20"}),"AccountCircle"),mP=ye(a.jsx("path",{d:"M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3z"}),"AccountTree"),Qn=ye(a.jsx("path",{d:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"}),"Add"),cJ=ye(a.jsx("path",{d:"m22 5.72-4.6-3.86-1.29 1.53 4.6 3.86zM7.88 3.39 6.6 1.86 2 5.71l1.29 1.53zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9m0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7"}),"Alarm"),uJ=ye(a.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2M9 17H7v-5h2zm4 0h-2v-3h2zm0-5h-2v-2h2zm4 5h-2V7h2z"}),"Analytics"),dJ=ye(a.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2m-7 9h-2V5h2zm0 4h-2v-2h2z"}),"Announcement"),zx=ye(a.jsx("path",{d:"m20 12-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8z"}),"ArrowDownward"),pJ=ye(a.jsx("path",{d:"m7 10 5 5 5-5z"}),"ArrowDropDown"),fJ=ye(a.jsx("path",{d:"m12 4-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"}),"ArrowForward"),x2=ye(a.jsx("path",{d:"m4 12 1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8z"}),"ArrowUpward"),km=ye(a.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-5 14H7v-2h7zm3-4H7v-2h10zm0-4H7V7h10z"}),"Article"),gP=ye(a.jsx("path",{d:"M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6z"}),"AttachFile"),hJ=ye(a.jsx("path",{d:"M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm2 11h-3v3.75c0 1.24-1.01 2.25-2.25 2.25S8.5 17.99 8.5 16.75s1.01-2.25 2.25-2.25c.46 0 .89.14 1.25.38V11h4zm-3-4V3.5L18.5 9z"}),"AudioFile"),mJ=ye(a.jsx("path",{d:"m19 1-5 5v11l5-4.5zM1 6v14.65c0 .25.25.5.5.5.1 0 .15-.05.25-.05C3.1 20.45 5.05 20 6.5 20c1.95 0 4.05.4 5.5 1.5V6c-1.45-1.1-3.55-1.5-5.5-1.5S2.45 4.9 1 6m22 13.5V6c-.6-.45-1.25-.75-2-1v13.5c-1.1-.35-2.3-.5-3.5-.5-1.7 0-4.15.65-5.5 1.5v2c1.35-.85 3.8-1.5 5.5-1.5 1.65 0 3.35.3 4.75 1.05.1.05.15.05.25.05.25 0 .5-.25.5-.5z"}),"AutoStories"),gJ=ye(a.jsx("path",{d:"M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2M6 4h5v8l-2.5-1.5L6 12z"}),"Book"),yJ=ye(a.jsx("path",{d:"M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2"}),"Bookmark"),b2=ye(a.jsx("path",{d:"m22.7 19-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4"}),"Build"),vJ=ye(a.jsx("path",{d:"M12 7V3H2v18h20V7zM6 19H4v-2h2zm0-4H4v-2h2zm0-4H4V9h2zm0-4H4V5h2zm4 12H8v-2h2zm0-4H8v-2h2zm0-4H8V9h2zm0-4H8V5h2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8zm-2-8h-2v2h2zm0 4h-2v2h2z"}),"Business"),yP=ye(a.jsx("path",{d:"M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 18H4V8h16z"}),"CalendarToday"),xJ=ye([a.jsx("path",{d:"m12 2-5.5 9h11z"},"0"),a.jsx("circle",{cx:"17.5",cy:"17.5",r:"4.5"},"1"),a.jsx("path",{d:"M3 13.5h8v8H3z"},"2")],"Category"),bJ=ye(a.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2M6 9h12v2H6zm8 5H6v-2h8zm4-6H6V6h12z"}),"Chat"),Ph=ye(a.jsx("path",{d:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"}),"Check"),vP=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8z"}),"CheckCircle"),xP=ye(a.jsx("path",{d:"M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"}),"ChevronLeft"),Jl=ye(a.jsx("path",{d:"M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"}),"ChevronRight"),SJ=ye(a.jsx("path",{d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}),"Clear"),$x=ye(a.jsx("path",{d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}),"Close"),CJ=ye(a.jsx("path",{d:"M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96M17 13l-5 5-5-5h3V9h4v4z"}),"CloudDownload"),Ti=ye(a.jsx("path",{d:"M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96M14 13v4h-4v-4H7l5-5 5 5z"}),"CloudUpload"),S2=ye(a.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"}),"Code"),wJ=ye(a.jsx("path",{d:"M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2m-11-4 2.03 2.71L16 11l4 5H8zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6z"}),"Collections"),jJ=ye(a.jsx("path",{d:"M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4zM18 14H6v-2h12zm0-3H6V9h12zm0-3H6V6h12z"}),"Comment"),TJ=ye(a.jsx("path",{d:"M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8zm-2 8c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2m4 8H8v-.57c0-.81.48-1.53 1.22-1.85.85-.37 1.79-.58 2.78-.58s1.93.21 2.78.58c.74.32 1.22 1.04 1.22 1.85z"}),"ContactPage"),bP=ye(a.jsx("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2m0 16H8V7h11z"}),"ContentCopy"),C2=ye(a.jsx("path",{d:"M20 6h-8l-2-2H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2m-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3z"}),"CreateNewFolder"),DJ=ye(a.jsx("path",{d:"M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2m0 14H4v-6h16zm0-10H4V6h16z"}),"CreditCard"),EJ=ye(a.jsx("path",{d:"M19 7H5c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2m0 8H5V9h14z"}),"Crop169"),RJ=ye(a.jsx("path",{d:"M19 6H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2m0 10H5V8h14z"}),"Crop32"),kJ=ye(a.jsx("path",{d:"M17 3H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H7V5h10z"}),"CropPortrait"),MJ=ye(a.jsx("path",{d:"M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2m0 14H6V6h12z"}),"CropSquare"),SP=ye(a.jsx("path",{d:"M3 13h8V3H3zm0 8h8v-6H3zm10 0h8V11h-8zm0-18v6h8V3z"}),"Dashboard"),OJ=ye(a.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"}),"DataArray"),zn=ye(a.jsx("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"}),"Delete"),Tp=ye(a.jsx("path",{d:"M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm2 16H8v-2h8zm0-4H8v-2h8zm-3-5V3.5L18.5 9z"}),"Description"),AJ=ye(a.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}),"Download"),wu=ye(a.jsx("path",{d:"M11 18c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2m-2-8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m6 4c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"DragIndicator"),Ri=ye(a.jsx("path",{d:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.996.996 0 0 0-1.41 0l-1.83 1.83 3.75 3.75z"}),"Edit"),_J=ye(a.jsx("path",{d:"M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2m0 4-8 5-8-5V6l8 5 8-5z"}),"Email"),IJ=ye(a.jsx("path",{d:"M17 12h-5v5h5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1zm3 18H5V8h14z"}),"Event"),Wr=ye(a.jsx("path",{d:"M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z"}),"ExpandMore"),CP=ye(a.jsx("path",{d:"M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-1.99.9-1.99 2v3.8H3.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7s2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11"}),"Extension"),PJ=ye(a.jsx("path",{d:"M9 11.75c-.69 0-1.25.56-1.25 1.25s.56 1.25 1.25 1.25 1.25-.56 1.25-1.25-.56-1.25-1.25-1.25m6 0c-.69 0-1.25.56-1.25 1.25s.56 1.25 1.25 1.25 1.25-.56 1.25-1.25-.56-1.25-1.25-1.25M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8 0-.29.02-.58.05-.86 2.36-1.05 4.23-2.98 5.21-5.37C11.07 8.33 14.05 10 17.42 10c.78 0 1.53-.09 2.25-.26.21.71.33 1.47.33 2.26 0 4.41-3.59 8-8 8"}),"Face"),LJ=ye(a.jsx("path",{d:"m12 21.35-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54z"}),"Favorite"),zJ=ye(a.jsx("path",{d:"M16 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8zM7 7h5v2H7zm10 10H7v-2h10zm0-4H7v-2h10zm-2-4V5l4 4z"}),"Feed"),$J=ye(a.jsx("path",{d:"M15 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V7zM6 20V4h8v4h4v12zm10-10v5c0 2.21-1.79 4-4 4s-4-1.79-4-4V8.5c0-1.47 1.26-2.64 2.76-2.49 1.3.13 2.24 1.32 2.24 2.63V15h-2V8.5c0-.28-.22-.5-.5-.5s-.5.22-.5.5V15c0 1.1.9 2 2 2s2-.9 2-2v-5z"}),"FilePresent"),NJ=ye(a.jsx("path",{d:"M14.4 6 14 4H5v17h2v-7h5.6l.4 2h7V6z"}),"Flag"),ic=ye(a.jsx("path",{d:"M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8z"}),"Folder"),FJ=ye(a.jsx("path",{d:"M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2m0 12H4V8h16z"}),"FolderOpen"),BJ=ye(a.jsx("path",{d:"M21 6h-2v9H6v2c0 .55.45 1 1 1h11l4 4V7c0-.55-.45-1-1-1m-4 6V3c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v14l4-4h10c.55 0 1-.45 1-1"}),"Forum"),UJ=ye(a.jsx("path",{d:"M12 1.27a11 11 0 00-3.48 21.46c.55.09.73-.28.73-.55v-1.84c-3.03.64-3.67-1.46-3.67-1.46-.55-1.29-1.28-1.65-1.28-1.65-.92-.65.1-.65.1-.65 1.1 0 1.73 1.1 1.73 1.1.92 1.65 2.57 1.2 3.21.92a2 2 0 01.64-1.47c-2.47-.27-5.04-1.19-5.04-5.5 0-1.1.46-2.1 1.2-2.84a3.76 3.76 0 010-2.93s.91-.28 3.11 1.1c1.8-.49 3.7-.49 5.5 0 2.1-1.38 3.02-1.1 3.02-1.1a3.76 3.76 0 010 2.93c.83.74 1.2 1.74 1.2 2.94 0 4.21-2.57 5.13-5.04 5.4.45.37.82.92.82 2.02v3.03c0 .27.1.64.73.55A11 11 0 0012 1.27"}),"GitHub"),Nx=ye(a.jsx("path",{d:"M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5s-3 1.34-3 3 1.34 3 3 3m-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5 5 6.34 5 8s1.34 3 3 3m0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5m8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5"}),"Group"),VJ=ye(a.jsx("path",{d:"M12 3c-4.97 0-9 4.03-9 9v7c0 1.1.9 2 2 2h4v-8H5v-1c0-3.87 3.13-7 7-7s7 3.13 7 7v1h-4v8h4c1.1 0 2-.9 2-2v-7c0-4.97-4.03-9-9-9"}),"Headphones"),HJ=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 17h-2v-2h2zm2.07-7.75-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25"}),"Help"),WJ=ye(a.jsx("path",{d:"M11 18h2v-2h-2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8m0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4"}),"HelpOutline"),wP=ye(a.jsx("path",{d:"M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9m-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8z"}),"History"),qJ=ye(a.jsx("path",{d:"M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"}),"Home"),GJ=ye(a.jsx("path",{d:"M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3m12-6h-8v7H3V5H1v15h2v-3h18v3h2v-9c0-2.21-1.79-4-4-4"}),"Hotel"),jP=ye(a.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2M8.5 13.5l2.5 3.01L14.5 12l4.5 6H5z"}),"Image"),ZJ=ye(a.jsx("path",{d:"M19 5v14H5V5zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-4.86 8.86-3 3.87L9 13.14 6 17h12z"}),"ImageOutlined"),KJ=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-6h2zm0-8h-2V7h2z"}),"Info"),vc=ye(a.jsx("path",{d:"M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm7 7V3.5L18.5 9z"}),"InsertDriveFile"),QJ=ye(a.jsx("path",{d:"M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2m-5 12H9v-2h6zm5-7H4V4l16-.02z"}),"Inventory"),w2=ye(a.jsx("path",{d:"M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6z"}),"KeyboardArrowDown"),TP=ye(a.jsx("path",{d:"M7.41 15.41 12 10.83l4.59 4.58L18 14l-6-6-6 6z"}),"KeyboardArrowUp"),JJ=ye(a.jsx("path",{d:"M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"}),"KeyboardReturn"),ch=ye(a.jsx("path",{d:"M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84L22 12z"}),"Label"),RC=ye(a.jsx("path",{d:"M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2zM4 6h16v10H4z"}),"Laptop"),YJ=ye(a.jsx("path",{d:"M4 6H2v14c0 1.1.9 2 2 2h14v-2H4zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2m-1 9H9V9h10zm-4 4H9v-2h6zm4-8H9V5h10z"}),"LibraryBooks"),j2=ye(a.jsx("path",{d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1M8 13h8v-2H8zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5"}),"Link"),DP=ye(a.jsx("path",{d:"M3 13h2v-2H3zm0 4h2v-2H3zm0-8h2V7H3zm4 4h14v-2H7zm0 4h14v-2H7zM7 7v2h14V7z"}),"List"),XJ=ye(a.jsx("path",{d:"M19 5v14H5V5zm1.1-2H3.9c-.5 0-.9.4-.9.9v16.2c0 .4.4.9.9.9h16.2c.4 0 .9-.5.9-.9V3.9c0-.5-.5-.9-.9-.9M11 7h6v2h-6zm0 4h6v2h-6zm0 4h6v2h-6zM7 7h2v2H7zm0 4h2v2H7zm0 4h2v2H7z"}),"ListAlt"),eY=ye(a.jsx("path",{d:"M19 3H5c-1.1 0-1.99.9-1.99 2L3 19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-1 11h-4v4h-4v-4H6v-4h4V6h4v4h4z"}),"LocalHospital"),tY=ye(a.jsx("path",{d:"m21.41 11.58-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58s1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41s-.23-1.06-.59-1.42M5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7"}),"LocalOffer"),nY=ye(a.jsx("path",{d:"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7m0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5"}),"LocationOn"),rY=ye(a.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2m-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2m3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1z"}),"Lock"),sY=ye(a.jsx("path",{d:"m20.5 3-.16.03L15 5.1 9 3 3.36 4.9c-.21.07-.36.25-.36.48V20.5c0 .28.22.5.5.5l.16-.03L9 18.9l6 2.1 5.64-1.9c.21-.07.36-.25.36-.48V3.5c0-.28-.22-.5-.5-.5M15 19l-6-2.11V5l6 2.11z"}),"Map"),iY=ye(a.jsx("path",{d:"M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3m5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72z"}),"Mic"),EP=ye(a.jsx("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"MoreVert"),oY=ye(a.jsx("path",{d:"m18 4 2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4z"}),"Movie"),aY=ye(a.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3z"}),"MusicNote"),lY=ye(a.jsx("path",{d:"M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"}),"NavigateNext"),cY=ye(a.jsx("path",{d:"m22 3-1.67 1.67L18.67 3 17 4.67 15.33 3l-1.66 1.67L12 3l-1.67 1.67L8.67 3 7 4.67 5.33 3 3.67 4.67 2 3v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2zM11 19H4v-6h7zm9 0h-7v-2h7zm0-4h-7v-2h7zm0-4H4V8h16z"}),"Newspaper"),uY=ye(a.jsx("path",{d:"M3 18h12v-2H3zM3 6v2h18V6zm0 7h18v-2H3z"}),"Notes"),dY=ye(a.jsx("path",{d:"m20.5 10 .5-2h-4l1-4h-2l-1 4h-4l1-4h-2L9 8H5l-.5 2h4l-1 4h-4L3 16h4l-1 4h2l1-4h4l-1 4h2l1-4h4l.5-2h-4l1-4zm-7 4h-4l1-4h4z"}),"Numbers"),ip=ye(a.jsx("path",{d:"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z"}),"OpenInNew"),pY=ye(a.jsx("path",{d:"M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2m0 14H4v-6h16zm0-10H4V6h16z"}),"Payment"),RP=ye(a.jsx("path",{d:"M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5s-3 1.34-3 3 1.34 3 3 3m-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5 5 6.34 5 8s1.34 3 3 3m0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5m8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5"}),"People"),Mm=ye(a.jsx("path",{d:"M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4m0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4"}),"Person"),fY=ye(a.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02z"}),"Phone"),hY=ye([a.jsx("circle",{cx:"12",cy:"12",r:"3.2"},"0"),a.jsx("path",{d:"M9 2 7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5"},"1")],"PhotoCamera"),Fx=ye(a.jsx("path",{d:"M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2m-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v2H7.5V7H10c.83 0 1.5.67 1.5 1.5zm5 2c0 .83-.67 1.5-1.5 1.5h-2.5V7H15c.83 0 1.5.67 1.5 1.5zm4-3H19v1h1.5V11H19v2h-1.5V7h3zM9 9.5h1v-1H9zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4zm10 5.5h1v-3h-1z"}),"PictureAsPdf"),mY=ye(a.jsx("path",{d:"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7m0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5"}),"Place"),gY=ye(a.jsx("path",{d:"M8 5v14l11-7z"}),"PlayArrow"),yY=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2M9.5 16.5v-9l7 4.5z"}),"PlayCircle"),kC=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39"}),"Public"),vY=ye(a.jsx("path",{d:"M18 17H6v-2h12zm0-4H6v-2h12zm0-4H6V7h12zM3 22l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2z"}),"Receipt"),kP=ye(a.jsx("path",{d:"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4z"}),"Refresh"),xY=ye(a.jsx("path",{d:"M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2zm5-3v8h2.5v8H21V2c-2.76 0-5 2.24-5 4"}),"Restaurant"),bY=ye(a.jsx("path",{d:"M12 2.5s4.5 2.04 4.5 10.5c0 2.49-1.04 5.57-1.6 7H9.1c-.56-1.43-1.6-4.51-1.6-7C7.5 4.54 12 2.5 12 2.5m2 8.5c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2m-6.31 9.52c-.48-1.23-1.52-4.17-1.67-6.87l-1.13.75c-.56.38-.89 1-.89 1.67V22zM20 22v-5.93c0-.67-.33-1.29-.89-1.66l-1.13-.75c-.15 2.69-1.2 5.64-1.67 6.87z"}),"Rocket"),na=ye(a.jsx("path",{d:"M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3m3-10H5V5h10z"}),"Save"),SY=ye([a.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),a.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")],"Schedule"),CY=ye(a.jsx("path",{d:"M14 9v2h-3V9H8.5V7H11V1H4v6h2.5v2H4v6h2.5v2H4v6h7v-6H8.5v-2H11v-2h3v2h7V9z"}),"Schema"),wY=ye(a.jsx("path",{d:"M5 13.18v4L12 21l7-3.82v-4L12 17zM12 3 1 9l11 6 9-4.91V17h2V9z"}),"School"),Om=ye(a.jsx("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14"}),"Search"),Bx=ye(a.jsx("path",{d:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6"}),"Settings"),jY=ye(a.jsx("path",{d:"M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2M1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2"}),"ShoppingCart"),MP=ye(a.jsx("path",{d:"M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"}),"Star"),TY=ye(a.jsx("path",{d:"m22 9.24-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28z"}),"StarBorder"),DY=ye(a.jsx("path",{d:"M20 4H4v2h16zm1 10v-2l-1-5H4l-1 5v2h1v6h10v-6h4v6h2v-6zm-9 4H6v-4h6z"}),"Store"),EY=ye(a.jsx("path",{d:"m21.9 8.89-1.05-4.37c-.22-.9-1-1.52-1.91-1.52H5.05c-.9 0-1.69.63-1.9 1.52L2.1 8.89c-.24 1.02-.02 2.06.62 2.88.08.11.19.19.28.29V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-6.94c.09-.09.2-.18.28-.28.64-.82.87-1.87.62-2.89m-2.99-3.9 1.05 4.37c.1.42.01.84-.25 1.17-.14.18-.44.47-.94.47-.61 0-1.14-.49-1.21-1.14L16.98 5zM13 5h1.96l.54 4.52c.05.39-.07.78-.33 1.07-.22.26-.54.41-.95.41-.67 0-1.22-.59-1.22-1.31zM8.49 9.52 9.04 5H11v4.69c0 .72-.55 1.31-1.29 1.31-.34 0-.65-.15-.89-.41-.25-.29-.37-.68-.33-1.07m-4.45-.16L5.05 5h1.97l-.58 4.86c-.08.65-.6 1.14-1.21 1.14-.49 0-.8-.29-.93-.47-.27-.32-.36-.75-.26-1.17M5 19v-6.03c.08.01.15.03.23.03.87 0 1.66-.36 2.24-.95.6.6 1.4.95 2.31.95.87 0 1.65-.36 2.23-.93.59.57 1.39.93 2.29.93.84 0 1.64-.35 2.24-.95.58.59 1.37.95 2.24.95.08 0 .15-.02.23-.03V19z"}),"Storefront"),RY=ye(a.jsx("path",{d:"M16.5 12c1.38 0 2.49-1.12 2.49-2.5S17.88 7 16.5 7 14 8.12 14 9.5s1.12 2.5 2.5 2.5M9 11c1.66 0 2.99-1.34 2.99-3S10.66 5 9 5 6 6.34 6 8s1.34 3 3 3m7.5 3c-1.83 0-5.5.92-5.5 2.75V19h11v-2.25c0-1.83-3.67-2.75-5.5-2.75M9 13c-2.33 0-7 1.17-7 3.5V19h7v-2.25c0-.85.33-2.34 2.37-3.47C10.5 13.1 9.66 13 9 13"}),"SupervisorAccount"),OP=ye(a.jsx("path",{d:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8m0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4z"}),"Sync"),T2=ye(a.jsx("path",{d:"M2.5 4v3h5v12h3V7h5V4zm19 5h-9v3h3v7h3v-7h3z"}),"TextFields"),kY=ye(a.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2M9 11H7V9h2zm4 0h-2V9h2zm4 0h-2V9h2z"}),"Textsms"),MY=ye(a.jsx("path",{d:"M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V8h14zM7 10h5v5H7z"}),"Today"),OY=ye(a.jsx("path",{d:"M17 7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h10c2.76 0 5-2.24 5-5s-2.24-5-5-5m0 8c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3"}),"ToggleOn"),AY=ye(a.jsx("path",{d:"m16 6 2.29 2.29-4.88 4.88-4-4L2 16.59 3.41 18l6-6 4 4 6.3-6.29L22 12V6z"}),"TrendingUp"),_Y=ye(a.jsx("path",{d:"M3 17v2h6v-2zM3 5v2h10V5zm10 16v-2h8v-2h-8v-2h-2v6zM7 9v2H3v2h4v2h2V9zm14 4v-2H11v2zm-6-4h2V7h4V5h-4V3h-2z"}),"Tune"),IY=ye(a.jsx("path",{d:"M14 2H6.01c-1.1 0-2 .89-2 2L4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8zm-1 7V3.5L18.5 9zm1 5 2-1.06v4.12L14 16v1c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h4c.55 0 1 .45 1 1z"}),"VideoFile"),PY=ye(a.jsx("path",{d:"M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11z"}),"Videocam"),AP=ye(a.jsx("path",{d:"M3 14h4v-4H3zm0 5h4v-4H3zM3 9h4V5H3zm5 5h13v-4H8zm0 5h13v-4H8zM8 5v4h13V5z"}),"ViewList"),_P=ye(a.jsx("path",{d:"M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5M12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5m0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3"}),"Visibility"),LY=ye(a.jsx("path",{d:"M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7M2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2m4.31-.78 3.15 3.15.02-.16c0-1.66-1.34-3-3-3z"}),"VisibilityOff"),zY=ye(a.jsx("path",{d:"M3 9v6h4l5 5V4L7 9zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77"}),"VolumeUp"),IP=ye(a.jsx("path",{d:"M1 21h22L12 2zm12-3h-2v-2h2zm0-4h-2v-4h2z"}),"Warning"),$Y=ye(a.jsx("path",{d:"M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2m-6 0h-4V4h4z"}),"Work");class NY{constructor(e){this.deps=e}getState(){return this.deps.presenter.getState()}isAvailable(){var n,r;return((r=(n=this.deps.authPresenter.getState().currentUser)==null?void 0:n.permissions)==null?void 0:r.canViewUsers)===!0}startSimulation(e,n,r,s){return this.isAvailable()?(this.deps.presenter.startSimulation(e,n,r,s),oe.info("SimulationUseCase.startSimulation",{displayName:r,roleTemplate:n}),!0):(oe.warn("SimulationUseCase.startSimulation: not available"),!1)}stopSimulation(){this.deps.presenter.stopSimulation(),oe.info("SimulationUseCase.stopSimulation")}setTemplate(e){const n=Ih(e);this.deps.presenter.updatePermissions(n,e)}setPermission(e,n){const r=this.deps.presenter.getState();if(!r.virtualPermissions)return;const s={...r.virtualPermissions,[e]:n},i=_h(s);this.deps.presenter.updatePermissions(s,i)}updatePermissions(e){const n=_h(e);this.deps.presenter.updatePermissions(e,n)}getEffectivePermissions(){const e=this.deps.presenter.getState();return e.isActive&&e.virtualPermissions?e.virtualPermissions:this.deps.authPresenter.getState().permissions}getEffectiveRoleTemplate(){const e=this.deps.presenter.getState();return e.isActive&&e.virtualRoleTemplate?e.virtualRoleTemplate:this.deps.authPresenter.getState().roleTemplate}}const FY=t=>Px.subscribe(t),HM=()=>Px.getState();function D2(){return b.useSyncExternalStore(FY,HM,HM),{simulationUseCase:new NY({presenter:Px,authPresenter:Em})}}function PP({open:t,onClose:e,onDiscard:n,onContinue:r,conflicts:s=[],isLoading:i=!1}){const l=ur(),u=async()=>{await n(),e()},p=()=>{r(),e()},f=(m,g)=>{e(),l({to:"/contents/$contentTypeId/$contentId",params:{contentTypeId:m,contentId:g}})};return a.jsxs(Qt,{open:t,onClose:e,maxWidth:"sm",fullWidth:!0,children:[a.jsxs(Yt,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(IP,{color:"warning"}),"コンフリクトが発生しました"]}),a.jsxs(Jt,{children:[a.jsx(zt,{severity:"warning",sx:{mb:2},children:"共有ブランチと個人ブランチで同じファイルが変更されています。"}),s.length>0&&a.jsxs(a.Fragment,{children:[a.jsxs(G,{variant:"subtitle2",gutterBottom:!0,children:["コンフリクトしているコンテンツ (",s.length,"件):"]}),a.jsx(as,{dense:!0,sx:{mb:2,bgcolor:"grey.50",borderRadius:1},children:s.map(m=>a.jsxs(os,{onClick:()=>f(m.contentTypeId,m.contentId),children:[a.jsx(Un,{children:a.jsx(Tp,{fontSize:"small"})}),a.jsx(Zn,{primary:m.contentId,secondary:`${m.contentTypeId}`})]},m.path))}),a.jsx(wo,{sx:{my:2}})]}),a.jsx(G,{variant:"body1",gutterBottom:!0,children:"以下のいずれかを選択してください:"}),a.jsxs(B,{sx:{mt:2},children:[a.jsx(G,{variant:"subtitle2",color:"error.main",gutterBottom:!0,children:"コンフリクトを破棄"}),a.jsx(G,{variant:"body2",color:"text.secondary",sx:{ml:2,mb:2},children:s.length>0?`上記 ${s.length} 件のコンテンツのみ共有ブランチの内容で上書きします。他の変更は保持されます。`:"個人ブランチの変更を破棄し、共有ブランチの内容で上書きします。"}),a.jsx(G,{variant:"subtitle2",color:"info.main",gutterBottom:!0,children:"このまま作業を続ける"}),a.jsx(G,{variant:"body2",color:"text.secondary",sx:{ml:2},children:"コンフリクトを無視して編集を続けます。 後で「共有ブランチに送る」際に再度コンフリクトを解消する必要があります。"})]})]}),a.jsxs(rn,{sx:{px:3,pb:2},children:[a.jsx(pe,{onClick:p,disabled:i,children:"このまま作業を続ける"}),a.jsx(pe,{onClick:u,color:"error",variant:"contained",disabled:i,startIcon:i?a.jsx(ut,{size:16}):void 0,children:s.length>0?"コンフリクトを破棄":"破棄して共有ブランチに戻す"})]})]})}const Ux=t=>Rm.subscribe(t),oc=()=>Rm.getState();function BY({branchUseCase:t}){const[e,n]=b.useState(null);b.useSyncExternalStore(Ux,oc,oc);const r=t.getState(),s=f=>{n(f.currentTarget)},i=()=>{n(null)},l=async()=>{i(),await t.switchToDevelop(),window.location.reload()},u=async()=>{i(),await t.switchToPersonal(),window.location.reload()},p=r.branchType==="develop";return a.jsxs(B,{children:[a.jsx(pe,{variant:"outlined",size:"small",color:p?"info":"success",onClick:s,startIcon:r.isLoading?a.jsx(ut,{size:16}):a.jsx(mP,{}),endIcon:a.jsx(w2,{}),disabled:r.isLoading,sx:{textTransform:"none"},children:p?"共有ブランチ":"個人ブランチ"}),a.jsxs(Cp,{anchorEl:e,open:!!e,onClose:i,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},children:[a.jsxs(nt,{onClick:l,children:[a.jsx(Un,{children:p?a.jsx(Ph,{fontSize:"small"}):a.jsx(Nx,{fontSize:"small"})}),a.jsx(Zn,{primary:"共有ブランチ",secondary:r.developBranchName})]}),a.jsxs(nt,{onClick:u,children:[a.jsx(Un,{children:p?a.jsx(Mm,{fontSize:"small"}):a.jsx(Ph,{fontSize:"small"})}),a.jsx(Zn,{primary:"個人ブランチ",secondary:r.personalBranchName})]})]})]})}function UY({branchUseCase:t,onClick:e}){b.useSyncExternalStore(Ux,oc,oc);const n=t.getState(),r=n.branchType==="develop",s=n.isSyncing?a.jsx(ut,{size:16,color:"inherit"}):r?a.jsx(Nx,{}):a.jsx(Mm,{}),i=a.jsx(Ht,{icon:s,label:r?"共有":"個人",size:"small",color:r?"info":"success",variant:"outlined",onClick:e,sx:{mr:1,cursor:e?"pointer":"default"}});if(n.isSyncing)return a.jsx(Er,{title:"GitHub と同期中...",arrow:!0,children:a.jsx(xv,{badgeContent:n.diffCount,color:"warning",max:99,invisible:!n.hasDiff,children:i})});if(!r&&n.hasDiff)return a.jsx(Er,{title:`共有ブランチより ${n.diffCount} コミット進んでいます`,arrow:!0,children:a.jsx(xv,{badgeContent:n.diffCount,color:"warning",max:99,children:i})});const l=r?"共有ブランチで作業中":"個人ブランチで作業中";return a.jsx(Er,{title:l,arrow:!0,children:i})}function VY({branchUseCase:t}){const[e,n]=b.useState(!1),r=b.useSyncExternalStore(Ux,oc,oc);if(r.branchType==="develop"||!r.hasDiff&&r.behindCount===0)return null;const s=async()=>{await t.rebaseFromDevelop()&&n(!0)},i=async()=>{r.conflicts.length>0?await t.discardConflictingFiles():await t.discardPersonalChanges()},l=()=>{t.getState()};return r.behindCount>0?a.jsxs(a.Fragment,{children:[a.jsxs(zt,{severity:"warning",icon:a.jsx(OP,{}),action:a.jsx(pe,{color:"inherit",size:"small",onClick:s,disabled:r.isLoading,children:"最新を取り込む"}),sx:{mb:2},children:[a.jsxs(bI,{children:["共有ブランチが ",r.behindCount," コミット先に進んでいます"]}),r.hasDiff?`個人ブランチは ${r.diffCount} コミット進んでいます。「最新を取り込む」で共有ブランチの変更を反映できます。反映には数分かかることがあります。`:"「最新を取り込む」で共有ブランチの変更を反映できます。反映には数分かかることがあります。"]}),a.jsx(PP,{open:e,onClose:()=>n(!1),onDiscard:i,onContinue:l,conflicts:r.conflicts,isLoading:r.isLoading})]}):a.jsx(HY,{branchUseCase:t})}function HY({branchUseCase:t}){const e=ur(),[n,r]=b.useState(!1),[s,i]=b.useState(!1),[l,u]=b.useState(!1),p=b.useSyncExternalStore(Ux,oc,oc),f=async()=>{await t.fetchChangedContents(),r(!0)},m=()=>{r(!1)},g=(D,M)=>{r(!1),e({to:"/contents/$contentTypeId/$contentId",params:{contentTypeId:D,contentId:M}})},y=async()=>{i(!1),(await t.mergeToDevelop()).hasConflict&&u(!0)},v=async()=>{await t.discardConflictingFiles(),u(!1)},C=()=>{u(!1)},S=D=>{switch(D){case"added":return a.jsx(Qn,{color:"success",fontSize:"small"});case"modified":return a.jsx(Ri,{color:"info",fontSize:"small"});case"removed":return a.jsx(zn,{color:"error",fontSize:"small"})}},j=D=>{switch(D){case"added":return"追加";case"modified":return"変更";case"removed":return"削除"}};return a.jsxs(a.Fragment,{children:[a.jsxs(zt,{severity:"info",icon:a.jsx(OP,{}),sx:{mb:2},children:[a.jsx(bI,{children:"共有ブランチに反映されていない変更があります"}),a.jsx(B,{sx:{mb:1},children:"個人ブランチで作業中です。完了したら「共有ブランチに反映」で変更を反映してください。反映には数分かかることがあります。"}),a.jsxs(B,{sx:{display:"flex",gap:1,flexWrap:"wrap"},children:[a.jsx(pe,{color:"inherit",size:"small",onClick:f,disabled:p.isLoading,startIcon:a.jsx(Om,{}),variant:"outlined",children:"変更を確認"}),a.jsx(pe,{color:"primary",size:"small",onClick:()=>i(!0),disabled:p.isLoading,variant:"contained",children:"共有ブランチに反映"})]})]}),a.jsx(WY,{open:n,onClose:m,contents:p.changedContents,isLoading:p.isLoading,onNavigate:g,getStatusIcon:S,getStatusLabel:j}),a.jsxs(Qt,{open:s,onClose:()=>i(!1),children:[a.jsx(Yt,{children:"共有ブランチに反映"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{py:1},children:["個人ブランチの変更を共有ブランチに反映しますか?",a.jsx("br",{}),"チームメンバー全員がこの変更を確認できるようになります。"]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>i(!1),disabled:p.isLoading,children:"キャンセル"}),a.jsx(pe,{onClick:y,color:"primary",variant:"contained",disabled:p.isLoading,startIcon:p.isLoading?a.jsx(ut,{size:16}):void 0,children:"反映する"})]})]}),a.jsx(PP,{open:l,onClose:()=>u(!1),onDiscard:v,onContinue:C,conflicts:p.conflicts,isLoading:p.isLoading})]})}function WY({open:t,onClose:e,contents:n,isLoading:r,onNavigate:s,getStatusIcon:i,getStatusLabel:l}){return a.jsxs(Qt,{open:t,onClose:e,maxWidth:"sm",fullWidth:!0,children:[a.jsx(Yt,{children:"変更されたコンテンツ"}),a.jsx(Jt,{children:r?a.jsx(B,{sx:{display:"flex",justifyContent:"center",py:4},children:a.jsx(ut,{})}):n.length===0?a.jsx(B,{sx:{py:2,textAlign:"center",color:"text.secondary"},children:"変更されたコンテンツはありません"}):a.jsxs(a.Fragment,{children:[a.jsxs(B,{sx:{mb:1,color:"text.secondary",fontSize:"0.875rem"},children:[n.length,"件の変更があります"]}),a.jsx(as,{children:n.map(u=>a.jsxs(os,{onClick:()=>s(u.contentTypeId,u.contentId),children:[a.jsx(Un,{children:i(u.status)}),a.jsx(Zn,{primary:u.contentId,secondary:`${u.contentTypeId} / ${u.basePath==="private"?"下書き":"公開済み"} (${l(u.status)})`})]},`${u.basePath}/${u.contentTypeId}/${u.contentId}`))})]})})]})}const qY="/admin/assets/logo-DRV9kVVU.png",WM="develop";function qM(t){switch(t){case"owner":case"admin":return"error";case"developer":return"warning";case"editor":return"primary";case"viewer":return"default";case"custom":default:return"success"}}function GY(){const t=ta().siteTitle,e=ta().productionUrl,{authUseCase:n}=rr(),{branchUseCase:r}=Ei(),{simulationUseCase:s}=D2(),{githubUser:i,currentUser:l,token:u,roleTemplate:p,allowPersonalBranch:f}=n.getState(),m=s.getState(),g=r==null?void 0:r.getState(),y=ur(),v=ys(),[C,S]=b.useState(null),[j,D]=b.useState(!1),[M,T]=b.useState(!1),[E,k]=b.useState(!1),[A,O]=b.useState(""),[I,$]=b.useState("success"),R=jn(uu.AdminDataQueryParams(u,WM)),P=Pn(uu.SaveAdminDataMutationParams(v,u,WM)),z=te=>{S(te.currentTarget)},N=()=>{S(null)},H=()=>{N(),n.logout(),y({to:"/login"})},U=async()=>{N(),await(r==null?void 0:r.switchToDevelop())},L=async()=>{N(),await(r==null?void 0:r.switchToPersonal())},W=()=>{N(),s.stopSimulation()},K=()=>{N(),D(!0)},Q=()=>{D(!1)},le=()=>{N(),T(!0)},F=()=>{T(!1)},J=async()=>{const te=m;if(!te.isActive||!te.virtualPermissions||!te.simulatedGithubUsername){O("シミュレーションがアクティブではありません"),$("error"),k(!0),T(!1);return}const de=R.data;if(!de){O("ユーザーデータを取得できませんでした"),$("error"),k(!0),T(!1);return}const fe=de.users.find(we=>we.githubUsername===te.simulatedGithubUsername);if(!fe){O("対象ユーザーが見つかりません"),$("error"),k(!0),T(!1);return}const Re={...fe,permissions:te.virtualPermissions},Pe=de.users.map(we=>we.githubUsername===te.simulatedGithubUsername?Re:we),$e={...de,users:Pe};try{await P.mutateAsync($e),O("ユーザー設定に反映しました"),$("success")}catch{O("反映に失敗しました"),$("error")}k(!0),T(!1)};if(!i||!l)return null;const ie=(g==null?void 0:g.branchType)==="develop";return a.jsxs(nV,{"data-component-name":"cmp:AppBar",position:"static",color:"default",elevation:1,sx:{bgcolor:"white"},children:[a.jsxs(iK,{children:[a.jsx(ft,{component:gs,to:"/",sx:{mr:1,p:.5},children:a.jsx("img",{src:qY,alt:"ダッシュボード",style:{width:32,height:32}})}),t?a.jsxs(B,{sx:{display:"flex",flexDirection:{xs:"column",sm:"row"},alignItems:{xs:"flex-start",sm:"baseline"},gap:{xs:0,sm:1}},children:[a.jsx(G,{variant:"h6",sx:{lineHeight:1.2},children:t}),e&&a.jsxs(G,{variant:"body2",component:"a",href:e,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.secondary",textDecoration:"none","&:hover":{textDecoration:"underline"},lineHeight:1.2},children:[a.jsx(B,{component:"span",sx:{display:{xs:"none",sm:"inline"}},children:"- "}),e]})]}):a.jsx(G,{variant:"h6",children:"Frelio CMS"}),a.jsx(B,{sx:{flexGrow:1}}),r&&f&&a.jsx(UY,{branchUseCase:r,onClick:z}),a.jsx(ft,{"data-testid":"avatar-menu-button",onClick:z,sx:{p:0},children:a.jsx(o7,{src:i.avatar_url,alt:i.login,sx:{width:32,height:32}})}),a.jsxs(Cp,{anchorEl:C,open:!!C,onClose:N,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[a.jsxs(B,{sx:{px:3,py:1.5},children:[a.jsx(G,{variant:"body1",fontWeight:"bold",children:l.displayName||i.name||i.login}),a.jsxs(G,{variant:"body2",color:"text.secondary",children:["@",i.login]}),p&&a.jsx(Ht,{label:Tv(p),color:qM(p),size:"small",sx:{mt:1}})]}),a.jsx(wo,{}),f&&[a.jsxs(nt,{onClick:U,children:[a.jsx(Un,{children:ie?a.jsx(Ph,{fontSize:"small"}):a.jsx(Nx,{fontSize:"small"})}),a.jsx(Zn,{primary:"共有ブランチ",secondary:g==null?void 0:g.developBranchName})]},"develop"),a.jsxs(nt,{onClick:L,children:[a.jsx(Un,{children:ie?a.jsx(Mm,{fontSize:"small"}):a.jsx(Ph,{fontSize:"small"})}),a.jsx(Zn,{primary:"個人ブランチ",secondary:g==null?void 0:g.personalBranchName})]},"personal"),a.jsx(wo,{},"divider")],a.jsx(nt,{onClick:H,children:"ログアウト"}),m.isActive&&[a.jsx(wo,{},"sim-divider"),a.jsxs(B,{sx:{px:3,py:1.5,bgcolor:"warning.light"},children:[a.jsx(G,{variant:"caption",color:"warning.dark",fontWeight:"bold",children:"UI再現モード"}),a.jsx(G,{variant:"body2",fontWeight:"bold",children:m.simulatedUserDisplayName}),a.jsx(Ht,{label:m.virtualRoleTemplate?Tv(m.virtualRoleTemplate):"",color:m.virtualRoleTemplate?qM(m.virtualRoleTemplate):"default",size:"small",sx:{mt:.5}})]},"sim-info"),a.jsxs(nt,{onClick:K,sx:{color:"warning.main"},children:[a.jsx(Un,{sx:{color:"warning.main"},children:a.jsx(Ri,{fontSize:"small"})}),a.jsx(Zn,{primary:"権限を編集"})]},"sim-edit"),a.jsxs(nt,{onClick:le,sx:{color:"warning.main"},children:[a.jsx(Un,{sx:{color:"warning.main"},children:a.jsx(na,{fontSize:"small"})}),a.jsx(Zn,{primary:"ユーザーに反映"})]},"sim-apply"),a.jsxs(nt,{onClick:W,sx:{color:"warning.main"},children:[a.jsx(Un,{sx:{color:"warning.main"},children:a.jsx($x,{fontSize:"small"})}),a.jsx(Zn,{primary:"UI再現を終了"})]},"sim-stop")]]})]}),a.jsx(ZY,{open:j,onClose:Q,simulationUseCase:s}),a.jsxs(Qt,{"data-component-name":"cmp:ApplyToUserDialog",open:M,onClose:F,children:[a.jsx(Yt,{children:"ユーザーに反映"}),a.jsxs(Jt,{children:[a.jsxs(G,{children:["シミュレーション中の権限を「",m.simulatedUserDisplayName,"」に反映しますか?"]}),a.jsx(G,{variant:"body2",color:"text.secondary",sx:{mt:1},children:"この操作は実際のユーザー設定を更新します。"})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:F,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:J,children:"反映"})]})]}),a.jsx(ea,{open:E,autoHideDuration:4e3,onClose:()=>k(!1),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:()=>k(!1),severity:I,sx:{width:"100%"},children:A})})]})}function ZY({open:t,onClose:e,simulationUseCase:n}){const r=n.getState(),s=r.virtualPermissions,i=r.virtualRoleTemplate;if(!s||!i)return null;const l=p=>{n.setTemplate(p)},u=(p,f)=>{if(n.setPermission(p,f),f){const m=Sv.find(g=>g.edit===p);m&&n.setPermission(m.view,!0)}if(!f){const m=Sv.find(g=>g.view===p);m&&n.setPermission(m.edit,!1)}};return a.jsxs(Qt,{"data-component-name":"cmp:SimulationEditDialog",open:t,onClose:e,maxWidth:"sm",fullWidth:!0,children:[a.jsx(Yt,{children:"権限を編集"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1},children:[a.jsxs(_n,{fullWidth:!0,children:[a.jsx(nr,{children:"ロール"}),a.jsxs(wn,{value:i,label:"ロール",onChange:p=>l(p.target.value),children:[a.jsx(nt,{value:"admin",children:"管理者"}),a.jsx(nt,{value:"developer",children:"開発者"}),a.jsx(nt,{value:"editor",children:"編集者"}),a.jsx(nt,{value:"viewer",children:"閲覧者"}),a.jsx(nt,{value:"custom",children:"カスタム"})]})]}),a.jsxs(_s,{defaultExpanded:i==="custom",sx:{boxShadow:"none",border:1,borderColor:"divider","&:before":{display:"none"}},children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(G,{children:"権限の詳細"})}),a.jsx(Is,{sx:{pt:0},children:a.jsx(Ro,{spacing:2,children:Object.entries(uP).map(([p,f])=>a.jsxs(B,{children:[a.jsx(G,{variant:"subtitle2",color:"text.secondary",sx:{mb:.5},children:f.label}),a.jsx(B,{sx:{display:"flex",flexDirection:"column",ml:1,gap:.5},children:f.pairs.map(m=>a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(G,{variant:"body2",sx:{minWidth:100},children:dP[m.view]}),a.jsx(_r,{control:a.jsx(es,{checked:s[m.view],onChange:g=>u(m.view,g.target.checked),size:"small"}),label:"閲覧",sx:{mr:0}}),a.jsx(_r,{control:a.jsx(es,{checked:s[m.edit],onChange:g=>u(m.edit,g.target.checked),size:"small"}),label:"編集",sx:{mr:0}})]},m.view))})]},p))})})]})]})}),a.jsx(rn,{children:a.jsx(pe,{onClick:e,children:"閉じる"})})]})}function GM(){const{open:t,message:e,severity:n}=b.useSyncExternalStore(Pd.subscribe,Pd.getSnapshot),r=(s,i)=>{i!=="clickaway"&&Pd.dismiss()};return a.jsx(ea,{"data-component-name":"cmp:GlobalSnackbar",open:t,onClose:r,autoHideDuration:n==="error"?null:6e3,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:r,severity:n,variant:"filled",sx:{whiteSpace:"pre-line",maxWidth:600},children:e})})}function KY({useCase:t}){const{activeTab:e,fileTabEnabled:n}=t.getState(),r=(i,l)=>{t.setActiveTab(l)},s=()=>{t.close()};return a.jsxs(B,{"data-component-name":"cmp:ActivityLogHeader",sx:{borderBottom:1,borderColor:"divider"},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",px:2,py:1},children:[a.jsx(G,{variant:"subtitle2",fontWeight:"bold",children:"アクティビティログ"}),a.jsx(Er,{title:"閉じる",children:a.jsx(ft,{size:"small",onClick:s,children:a.jsx(Jl,{fontSize:"small"})})})]}),a.jsxs(_K,{value:e,onChange:r,variant:"fullWidth",sx:{minHeight:36,"& .MuiTab-root":{minHeight:36,py:.5,fontSize:"0.75rem"}},children:[a.jsx(hM,{value:"folder",label:"フォルダ",icon:a.jsx(ic,{sx:{fontSize:16}}),iconPosition:"start",sx:{minHeight:36}}),a.jsx(hM,{value:"file",label:"ファイル",icon:a.jsx(vc,{sx:{fontSize:16}}),iconPosition:"start",disabled:!n,sx:{minHeight:36}})]})]})}function QY(t){const n=new Date().getTime()-t.getTime(),r=Math.floor(n/1e3),s=Math.floor(r/60),i=Math.floor(s/60),l=Math.floor(i/24);return l>0?`${l}日前`:i>0?`${i}時間前`:s>0?`${s}分前`:"今"}function JY({commit:t,showViewButton:e,onViewContent:n}){const r=()=>{n==null||n(t.sha)},s=t.message.split(`
386
- `)[0];return a.jsxs(B,{"data-component-name":"cmp:ActivityLogItem",sx:{px:2,py:1.5,borderBottom:1,borderColor:"divider","&:hover":{bgcolor:"action.hover"}},children:[a.jsx(G,{variant:"body2",sx:{fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",mb:.5},title:s,children:s}),a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(Ht,{label:t.authorDisplayName,size:"small",sx:{height:20,fontSize:"0.7rem","& .MuiChip-label":{px:1}}}),a.jsx(G,{variant:"caption",color:"text.secondary",children:QY(t.date)}),a.jsx(G,{variant:"caption",color:"text.disabled",sx:{ml:"auto"},children:t.shortSha}),e&&a.jsx(Er,{title:"この時点のファイルを表示",children:a.jsx(ft,{size:"small",onClick:r,sx:{ml:.5},children:a.jsx(_P,{sx:{fontSize:16}})})})]})]})}function ZM({commits:t,isLoading:e,isFetchingMore:n,hasMore:r,error:s,showViewButton:i,onLoadMore:l,onViewContent:u}){return e?a.jsx(B,{"data-component-name":"cmp:ActivityLogList",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",p:3},children:a.jsx(ut,{size:24})}):s?a.jsx(B,{"data-component-name":"cmp:ActivityLogList",sx:{flex:1,p:2},children:a.jsx(zt,{severity:"error",sx:{fontSize:"0.75rem"},children:s.message})}):t.length===0?a.jsx(B,{"data-component-name":"cmp:ActivityLogList",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",p:3},children:a.jsx(G,{variant:"body2",color:"text.secondary",children:"履歴がありません"})}):a.jsxs(B,{"data-component-name":"cmp:ActivityLogList",sx:{flex:1,overflow:"auto"},children:[t.map(p=>a.jsx(JY,{commit:p,showViewButton:i,onViewContent:u},p.sha)),r&&a.jsx(B,{sx:{p:2,textAlign:"center"},children:a.jsx(pe,{variant:"text",size:"small",onClick:l,disabled:n,startIcon:n?a.jsx(ut,{size:14}):null,children:n?"読み込み中...":"もっと読み込む"})})]})}function KM({useCase:t}){const{fileContentDialogSha:e,fileContentDialogPath:n}=t.getState(),r=e!==null&&n!==null,[s,i]=b.useState(null),[l,u]=b.useState(!1),[p,f]=b.useState(null),[m,g]=b.useState(!1);b.useEffect(()=>{if(!r||!e){i(null),f(null);return}u(!0),f(null),i(null),t.getFileContentAtCommit(e).then(i).catch(f).finally(()=>u(!1))},[r,e,t]);const y=()=>{t.closeFileContentDialog()},v=async()=>{if(s)try{await navigator.clipboard.writeText(s),g(!0),setTimeout(()=>g(!1),2e3)}catch{}},C=(n==null?void 0:n.split("/").pop())??"ファイル",S=(e==null?void 0:e.slice(0,7))??"";return a.jsxs(Qt,{"data-component-name":"cmp:FileContentDialog",open:r,onClose:y,maxWidth:"md",fullWidth:!0,children:[a.jsxs(Yt,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsxs(G,{variant:"h6",component:"span",sx:{flex:1},children:[C,a.jsxs(G,{variant:"caption",color:"text.secondary",sx:{ml:1},children:["@ ",S]})]}),a.jsx(ft,{size:"small",onClick:y,children:a.jsx($x,{})})]}),a.jsxs(Jt,{dividers:!0,children:[l&&a.jsx(B,{sx:{display:"flex",justifyContent:"center",p:4},children:a.jsx(ut,{})}),p&&a.jsxs(zt,{severity:"error",children:["ファイルの読み込みに失敗しました: ",p.message]}),s!==null&&!l&&!p&&a.jsx(B,{component:"pre",sx:{m:0,p:2,bgcolor:"grey.100",borderRadius:1,overflow:"auto",fontSize:"0.8rem",fontFamily:"monospace",whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:"60vh"},children:s})]}),a.jsxs(rn,{children:[a.jsx(pe,{startIcon:a.jsx(bP,{}),onClick:v,disabled:!s||l,children:m?"コピーしました":"コピー"}),a.jsx(pe,{onClick:y,children:"閉じる"})]})]})}const a1=320;function QM({useCase:t}){const e=t.getState(),{activeTab:n,folderCommits:r,fileCommits:s,isFolderLoading:i,isFileLoading:l,isFolderFetchingMore:u,isFileFetchingMore:p,hasFolderMore:f,hasFileMore:m,folderError:g,fileError:y,fileTabEnabled:v}=e,C=()=>{t.loadMoreFolderCommits()},S=()=>{t.loadMoreFileCommits()},j=D=>{t.openFileContentDialog(D)};return a.jsxs(a.Fragment,{children:[a.jsx(KY,{useCase:t}),n==="folder"&&a.jsx(ZM,{commits:r,isLoading:i,isFetchingMore:u,hasMore:f,error:g,showViewButton:!1,onLoadMore:C}),n==="file"&&v&&a.jsx(ZM,{commits:s,isLoading:l,isFetchingMore:p,hasMore:m,error:y,showViewButton:!0,onLoadMore:S,onViewContent:j})]})}function YY(){const t=new URL(window.location.href);return t.searchParams.delete("activity_log"),t.pathname+t.search+t.hash}function XY({useCase:t}){const e=vr(),n=aa(e.breakpoints.down("md")),r=ox(),s=Ns(),{isOpen:i}=t.getState(),u=new URLSearchParams(r.searchStr).get("activity_log")==="1",p=n?u:i,f=b.useRef(u);b.useEffect(()=>{n&&f.current!==u&&(u&&!i?t.open():!u&&i&&t.close(),f.current=u)},[n,u,i,t]);const m=()=>{if(n){const g=YY();s.history.push(g)}t.close()};return n?a.jsxs(a.Fragment,{children:[a.jsx(Cu,{"data-component-name":"cmp:ActivityLogPanel",anchor:"right",open:p,onClose:m,PaperProps:{sx:{width:a1,maxWidth:"100vw"}},children:a.jsx(B,{sx:{display:"flex",flexDirection:"column",height:"100%"},children:a.jsx(QM,{useCase:t})})}),a.jsx(KM,{useCase:t})]}):a.jsxs(a.Fragment,{children:[a.jsx(B,{"data-component-name":"cmp:ActivityLogPanel",sx:{width:p?a1:0,minWidth:p?a1:0,height:"100%",overflow:"hidden",transition:"width 0.2s ease-in-out, min-width 0.2s ease-in-out",borderLeft:p?1:0,borderColor:"divider",bgcolor:"background.paper",display:"flex",flexDirection:"column"},children:p&&a.jsx(QM,{useCase:t})}),a.jsx(KM,{useCase:t})]})}function eX(){const t=new URL(window.location.href);return t.searchParams.set("activity_log","1"),t.pathname+t.search+t.hash}function tX(){const t=new URL(window.location.href);return t.searchParams.delete("activity_log"),t.pathname+t.search+t.hash}function nX({useCase:t}){const e=vr(),n=aa(e.breakpoints.down("md")),r=ox(),s=Ns(),{isOpen:i}=t.getState(),u=new URLSearchParams(r.searchStr).get("activity_log")==="1",p=n?u:i,f=()=>{n?p?(s.history.push(tX()),t.close()):(s.history.push(eX()),t.open()):t.toggle()};return a.jsx(Er,{title:p?"アクティビティログを閉じる":"アクティビティログを開く",placement:"left",children:a.jsx(CW,{"data-component-name":"cmp:ActivityLogToggleButton",size:"small",color:"default",onClick:f,sx:{position:"fixed",bottom:24,right:24,zIndex:m=>m.zIndex.speedDial,bgcolor:"background.paper",boxShadow:2,"&:hover":{bgcolor:"action.hover"}},children:p?a.jsx(Jl,{}):a.jsx(wP,{})})})}const Bs=z$({component:rX});function rX(){const{authUseCase:t}=rr(),{githubUser:e,currentUser:n,isInitialized:r}=t.getState(),s=ur(),i=ox();return b.useEffect(()=>{if(!r)return;const u=i.pathname==="/login",p=i.pathname.startsWith("/auth/callback");if(!e&&!u&&!p){s({to:"/login"});return}if(e&&n&&u){s({to:"/"});return}if(n){const f=gQ(i.pathname);f&&!ws(n,f)&&s({to:"/"})}},[r,e,n,s,i.pathname]),r?i.pathname==="/login"||i.pathname.startsWith("/auth/")?a.jsxs(a.Fragment,{children:[a.jsx(bw,{}),a.jsx(GM,{})]}):a.jsxs(a.Fragment,{children:[a.jsx(sX,{}),a.jsx(GM,{})]}):a.jsx(B,{"data-component-name":"cmp:RootLayoutLoading",display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",children:a.jsx(ut,{})})}function sX(){const{activityLogUseCase:t}=oJ(),{isAvailable:e}=t.getState();return a.jsxs(B,{"data-component-name":"cmp:RootLayout",sx:{display:"flex",flexDirection:"column",height:"100vh"},children:[a.jsx(B,{"data-component-name":"cmp:RootLayoutHeader",component:"header",sx:{position:"sticky",top:0,zIndex:n=>n.zIndex.appBar,flexShrink:0},children:a.jsx(GY,{})}),a.jsxs(B,{"data-component-name":"cmp:RootLayoutBody",sx:{flex:1,overflow:"hidden",display:"flex",flexDirection:"row"},children:[a.jsx(B,{"data-component-name":"cmp:RootLayoutMain",component:"main",sx:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:a.jsx(bw,{})}),e&&a.jsx(XY,{useCase:t})]}),e&&a.jsx(nX,{useCase:t})]})}const iX=Ss("/login")({component:oX});function oX(){const{authUseCase:t}=rr(),{githubUser:e}=t.getState();if(e)return null;const n=()=>{oe.debug("LoginPage","Login button clicked");try{const r=t.getAuthUrl();oe.debug("LoginPage","Redirecting to auth URL"),window.location.href=r}catch(r){oe.error("LoginPage","Error getting auth URL",{error:r})}};return a.jsx(ji,{"data-component-name":"cmp:LoginPage",maxWidth:"sm",children:a.jsx(B,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",children:a.jsxs($t,{"data-component-name":"cmp:LoginForm",elevation:3,sx:{p:4,textAlign:"center",width:"100%"},children:[a.jsx(G,{variant:"h4",component:"h1",gutterBottom:!0,children:"Frelio CMS"}),a.jsx(G,{variant:"body1",color:"text.secondary",sx:{mb:4},children:"GitHub アカウントでログインしてください"}),a.jsx(pe,{variant:"contained",size:"large",startIcon:a.jsx(UJ,{}),onClick:n,sx:{textTransform:"none"},children:"Login with GitHub"})]})})})}const aX={contentTypes:{}};class Pf{constructor(e,n,r,s){this.queryResult=e,this.mergeStagingMutation=n,this.mergeProductionMutation=r,this.directDeployMutation=s}static QueryParams(e,n,r,s){return{queryKey:["dashboard",n,r,s],queryFn:async()=>{if(!e)return{contentTypes:[],metadata:null,branchLastCommit:{develop:null,staging:null,production:null},branchComparisons:{}};const i=new At(e),u=(await i.fetchJsonOrDefault(Bc,{contentTypes:[]},n)).contentTypes,p=await i.fetchJsonOrDefault(kh,aX,n),f={develop:null,staging:null,production:null};try{const g=await i.getLatestCommitForPath("develop",Qi);g&&(f.develop=g.date)}catch{oe.debug("GitHubDashboardRepositoryImpl.QueryParams: failed to get develop branch info")}try{const g=await i.getLatestCommitForPath("staging",Qi);g&&(f.staging=g.date)}catch{oe.debug("GitHubDashboardRepositoryImpl.QueryParams: failed to get staging branch info")}try{const g=await i.getLatestCommitForPath("main",Qi);g&&(f.production=g.date)}catch{oe.debug("GitHubDashboardRepositoryImpl.QueryParams: failed to get main branch info")}const m={};if(r&&s&&s.length>0)for(const g of s)try{const y=await i.compareBranches(g,r),v=y.files.filter(C=>C.filename.startsWith(Qi));m[g]={ahead:v.length>0?y.ahead:0,behind:y.behind}}catch{oe.debug("GitHubDashboardRepositoryImpl.QueryParams: failed to compare branches",{stagingBranch:g,personalBranchName:r})}return{contentTypes:u,metadata:p,branchLastCommit:f,branchComparisons:m}},enabled:!!e,staleTime:0}}static MergeStagingMutationParams(e,n){return{mutationFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).mergeBranches("staging","develop","Merge develop into staging")},onSuccess:()=>{n.invalidateQueries({queryKey:["dashboard"]})}}}static MergeProductionMutationParams(e,n){return{mutationFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).mergeBranches("main","staging","Merge staging into main")},onSuccess:()=>{n.invalidateQueries({queryKey:["dashboard"]})}}}static DirectDeployMutationParams(e,n){return{mutationFn:async()=>{if(!e)throw new Error("Not authenticated");await new At(e).triggerWorkflow("direct-deploy.yml","main")},onSuccess:()=>{n.invalidateQueries({queryKey:["dashboard"]})}}}getContentTypes(){var e;return((e=this.queryResult.data)==null?void 0:e.contentTypes)??[]}isLoading(){return this.queryResult.isLoading}getLastUpdated(){var r;const e=(r=this.queryResult.data)==null?void 0:r.metadata;if(!(e!=null&&e.contentTypes))return null;const n=Object.values(e.contentTypes).map(s=>s.lastUpdatedAt).filter(s=>!!s).map(s=>new Date(s));return n.length===0?null:new Date(Math.max(...n.map(s=>s.getTime())))}getContentTypeMetadata(e){var n,r;return((r=(n=this.queryResult.data)==null?void 0:n.metadata)==null?void 0:r.contentTypes[e])??null}getMetadata(){var e;return((e=this.queryResult.data)==null?void 0:e.metadata)??null}getStagingLastCommit(){var e,n;return((n=(e=this.queryResult.data)==null?void 0:e.branchLastCommit)==null?void 0:n.staging)??null}getProductionLastCommit(){var e,n;return((n=(e=this.queryResult.data)==null?void 0:e.branchLastCommit)==null?void 0:n.production)??null}getDevelopLastCommit(){var e,n;return((n=(e=this.queryResult.data)==null?void 0:e.branchLastCommit)==null?void 0:n.develop)??null}getBranchComparison(e){var n;return((n=this.queryResult.data)==null?void 0:n.branchComparisons[e])??null}async mergeToStaging(){return this.mergeStagingMutation.mutateAsync()}async mergeToProduction(){return this.mergeProductionMutation.mutateAsync()}async triggerDirectDeploy(){await this.directDeployMutation.mutateAsync()}async refetch(){await this.queryResult.refetch()}}function lX(){return Fs(t=>({deployStatus:"idle",deployTarget:null,deployError:null,setDeployStatus:e=>t({deployStatus:e}),setDeployTarget:e=>t({deployTarget:e}),setDeployError:e=>t({deployError:e})}))}class cX{constructor(){St(this,"store");this.store=lX()}getState(){const{deployStatus:e,deployTarget:n,deployError:r}=this.store.getState();return{deployStatus:e,deployTarget:n,deployError:r}}setDeployStatus(e){this.store.getState().setDeployStatus(e)}setDeployTarget(e){this.store.getState().setDeployTarget(e)}setDeployError(e){this.store.getState().setDeployError(e)}startDeploy(e){this.store.setState({deployStatus:"loading",deployTarget:e,deployError:null})}completeDeploy(){this.store.setState({deployStatus:"success"})}failDeploy(e){this.store.setState({deployStatus:"error",deployError:e})}resetDeployState(){this.store.setState({deployStatus:"idle",deployTarget:null,deployError:null})}subscribe(e){return this.store.subscribe(e)}}class uX{constructor(e,n){this.repository=e,this.presenter=n}getState(){return{contentTypes:this.repository.getContentTypes(),isLoading:this.repository.isLoading(),metadata:this.repository.getMetadata(),developLastCommit:this.repository.getDevelopLastCommit(),stagingLastCommit:this.repository.getStagingLastCommit(),productionLastCommit:this.repository.getProductionLastCommit()}}getButtonStates(){var s,i,l;const e=((s=this.repository.getDevelopLastCommit())==null?void 0:s.getTime())??0,n=((i=this.repository.getStagingLastCommit())==null?void 0:i.getTime())??0,r=((l=this.repository.getProductionLastCommit())==null?void 0:l.getTime())??0;return{previewEnabled:e>n,productionEnabled:n>r,directDeployEnabled:e>r}}getContentTypeMetadata(e){return this.repository.getContentTypeMetadata(e)}formatRelativeTime(e){if(!e)return"";const n=typeof e=="string"?new Date(e):e,s=new Date().getTime()-n.getTime(),i=Math.floor(s/(1e3*60)),l=Math.floor(s/(1e3*60*60)),u=Math.floor(s/(1e3*60*60*24));return i<1?"たった今":i<60?`${i}分前`:l<24?`${l}時間前`:u<7?`${u}日前`:n.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"})}getBranchComparison(e){return this.repository.getBranchComparison(e)}isPreviewEnabled(e){const n=this.repository.getBranchComparison(e);return((n==null?void 0:n.ahead)??0)>0}getDeployState(){return this.presenter.getState()}resetDeployState(){this.presenter.resetDeployState()}async mergeToStaging(){this.presenter.startDeploy("preview");try{const e=await this.repository.mergeToStaging();return e.hasConflict?(this.presenter.failDeploy("コンフリクトが発生しました。手動で解決してください。"),{success:!1,hasConflict:!0}):(this.presenter.completeDeploy(),await this.repository.refetch(),oe.info("DashboardUseCase.mergeToStaging: completed",{sha:e.sha}),{success:!0,hasConflict:!1})}catch(e){const n=e instanceof Error?e.message:String(e);return this.presenter.failDeploy(n),oe.error("DashboardUseCase.mergeToStaging: failed",{error:n}),{success:!1,hasConflict:!1}}}async mergeToProduction(){this.presenter.startDeploy("production");try{const e=await this.repository.mergeToProduction();return e.hasConflict?(this.presenter.failDeploy("コンフリクトが発生しました。手動で解決してください。"),{success:!1,hasConflict:!0}):(this.presenter.completeDeploy(),await this.repository.refetch(),oe.info("DashboardUseCase.mergeToProduction: completed",{sha:e.sha}),{success:!0,hasConflict:!1})}catch(e){const n=e instanceof Error?e.message:String(e);return this.presenter.failDeploy(n),oe.error("DashboardUseCase.mergeToProduction: failed",{error:n}),{success:!1,hasConflict:!1}}}async directDeploy(){this.presenter.startDeploy("direct");try{return await this.repository.triggerDirectDeploy(),this.presenter.completeDeploy(),oe.info("DashboardUseCase.directDeploy: workflow dispatched"),{success:!0}}catch(e){const n=e instanceof Error?e.message:String(e);return this.presenter.failDeploy(n),oe.error("DashboardUseCase.directDeploy: failed",{error:n}),{success:!1}}}}function LP(){const{authUseCase:t}=rr(),{branchUseCase:e}=Ei(),n=ys(),{token:r,githubUser:s,stagingBranches:i}=t.getState(),l=(e==null?void 0:e.getCurrentBranch())??"develop",u=e==null?void 0:e.getState(),p=(u==null?void 0:u.branchType)==="personal",f=(u==null?void 0:u.currentBranch)??"",m=s?cP(s.login,i):[],g=p?m.map(S=>S.branchName):[],y=new Pf(jn(Pf.QueryParams(r,l,p?f:void 0,g)),Pn(Pf.MergeStagingMutationParams(r,n)),Pn(Pf.MergeProductionMutationParams(r,n)),Pn(Pf.DirectDeployMutationParams(r,n))),v=new cX;return{dashboardUseCase:new uX(y,v)}}const dX="modulepreload",pX=function(t){return"/admin/"+t},JM={},fX=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){let l=function(f){return Promise.all(f.map(m=>Promise.resolve(m).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const u=document.querySelector("meta[property=csp-nonce]"),p=(u==null?void 0:u.nonce)||(u==null?void 0:u.getAttribute("nonce"));s=l(n.map(f=>{if(f=pX(f),f in JM)return;JM[f]=!0;const m=f.endsWith(".css"),g=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${g}`))return;const y=document.createElement("link");if(y.rel=m?"stylesheet":dX,m||(y.as="script"),y.crossOrigin="",y.href=f,p&&y.setAttribute("nonce",p),document.head.appendChild(y),m)return new Promise((v,C)=>{y.addEventListener("load",v),y.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${f}`)))})}))}function i(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&i(u.reason);return e().catch(i)})},YM={Article:km,Description:Tp,Folder:ic,Image:jP,Movie:oY,MusicNote:aY,Book:gJ,Feed:zJ,Newspaper:cY,LibraryBooks:YJ,AutoStories:mJ,Notes:uY,TextFields:T2,Email:_J,Chat:bJ,Forum:BJ,Comment:jJ,ContactPage:TJ,Textsms:kY,Phone:fY,Announcement:dJ,Work:$Y,Store:DY,ShoppingCart:jY,Payment:pY,Receipt:vY,CreditCard:DJ,Inventory:QJ,Analytics:uJ,TrendingUp:AY,Business:vJ,Person:Mm,People:RP,Group:Nx,AccountCircle:lJ,Face:PJ,SupervisorAccount:RY,Event:IJ,CalendarToday:yP,Schedule:SY,AccessTime:aJ,Alarm:cJ,Today:MY,Place:mY,Map:sY,Home:qJ,LocationOn:nY,School:wY,LocalHospital:eY,Restaurant:xY,Hotel:GJ,Storefront:EY,PhotoCamera:hY,Videocam:PY,Mic:iY,Headphones:VJ,PlayCircle:yY,VolumeUp:zY,Settings:Bx,Build:b2,Dashboard:SP,Tune:_Y,Code:S2,Extension:CP,AttachFile:gP,CloudUpload:Ti,FilePresent:$J,PictureAsPdf:Fx,CloudDownload:CJ,Star:MP,Favorite:LJ,Flag:NJ,LocalOffer:tY,Label:ch,Category:xJ,Help:HJ,Info:KJ,CheckCircle:vP,Search:Om,Bookmark:yJ,Link:j2,Public:kC,Lock:rY},Lf={};function MC({iconName:t,sx:e}){const[n,r]=b.useState(null),[s,i]=b.useState(!1);if(YM[t]){const l=YM[t];return a.jsx(l,{sx:e})}return b.useEffect(()=>{if(Lf[t]!==void 0){r(Lf[t]);return}i(!0),fX(()=>import("./index-Qi4Cp3k2.js"),[]).then(l=>{const u=l[t];u?(Lf[t]=u,r(u)):(Lf[t]=null,r(null))}).catch(()=>{Lf[t]=null,r(null)}).finally(()=>{i(!1)})},[t]),s?a.jsx(ut,{size:16,sx:e}):n?a.jsx(n,{sx:e}):a.jsx(km,{sx:e})}function Vx({iconName:t,sx:e}){return a.jsx(MC,{iconName:t,sx:e})}const hX=Ss("/")({component:mX});function mX(){const t=ta().productionUrl,e=ta().previewUrl,{authUseCase:n}=rr(),{branchUseCase:r}=Ei(),{simulationUseCase:s}=D2(),{githubUser:i,currentUser:l,permissions:u,stagingBranches:p,allowPersonalBranch:f}=n.getState(),{dashboardUseCase:m}=LP(),g=s.getEffectivePermissions(),y=l!=null&&l.isOwner&&!s.getState().isActive?Cv:g,{contentTypes:v,isLoading:C,stagingLastCommit:S,productionLastCommit:j}=m.getState(),{previewEnabled:D,productionEnabled:M,directDeployEnabled:T}=m.getButtonStates(),[E,k]=b.useState(!1),A=r==null?void 0:r.getState(),O=(A==null?void 0:A.branchType)==="personal",I=i?cP(i.login,p):[],$=(A==null?void 0:A.currentBranch)??"";if(!i||!l)return null;const R=(y==null?void 0:y.canViewDeploy)??!1,P=(y==null?void 0:y.canEditDeploy)??!1,z=(y==null?void 0:y.canViewUsers)||(y==null?void 0:y.canViewStaging),N=(y==null?void 0:y.canViewContentType)||(y==null?void 0:y.canViewBuildRecipes),H=y==null?void 0:y.canViewTemplates,U=y==null?void 0:y.canViewStorage;return a.jsx(B,{"data-component-name":"cmp:DashboardPage",sx:{flex:1,overflow:"auto"},children:a.jsxs(ji,{maxWidth:"lg",sx:{py:3},children:[a.jsxs(B,{sx:{mb:2},children:[a.jsx(G,{variant:"h5",children:"ダッシュボード"}),a.jsx(G,{variant:"caption",color:"text.secondary",children:"repository: @ctime-projects/frelio-demo"})]}),r&&f&&a.jsx(VY,{branchUseCase:r}),a.jsxs(Et,{container:!0,spacing:3,children:[a.jsxs(Et,{item:!0,xs:12,md:6,children:[a.jsxs($t,{"data-component-name":"cmp:ContentSection",sx:{p:2},children:[a.jsxs(B,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:1},children:[a.jsx(G,{variant:"h6",children:"コンテンツ"}),r&&f&&a.jsx(BY,{branchUseCase:r})]}),a.jsx(xX,{contentTypes:v,dashboardUseCase:m,stagingLastCommit:S,isLoading:C,canEditContentType:(y==null?void 0:y.canEditContentType)??!1}),H&&a.jsxs(B,{"data-component-name":"cmp:FileManagementSection",sx:{mt:2,pt:2,borderTop:1,borderColor:"divider"},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"ファイル管理"}),a.jsx(as,{children:a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/templates",children:[a.jsx(Un,{sx:{mr:2},children:a.jsx(ic,{sx:{fontSize:52}})}),a.jsx(Zn,{primary:"テンプレート",secondary:"github内ファイルの管理"})]})})})]})]}),U&&a.jsx(B,{"data-component-name":"cmp:StorageSection",sx:{p:2,mt:3},children:a.jsx(as,{children:a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/storage",children:[a.jsx(Un,{sx:{mr:2},children:a.jsx(ic,{sx:{fontSize:52}})}),a.jsx(Zn,{primary:"ストレージ",secondary:"R2の画像やファイルの管理"})]})})})})]}),R&&a.jsx(Et,{item:!0,xs:12,md:6,children:O&&f?a.jsx(gX,{userStagingBranches:I,personalBranchName:$,dashboardUseCase:m,canEditDeploy:P}):a.jsx(vX,{previewEnabled:D,productionEnabled:M,directDeployEnabled:T,stagingLastCommit:S,productionLastCommit:j,previewUrl:e,productionUrl:t,badgeTooltipOpen:E,setBadgeTooltipOpen:k,dashboardUseCase:m,canEditDeploy:P})}),z&&a.jsx(Et,{item:!0,xs:12,children:a.jsxs($t,{"data-component-name":"cmp:AdminSection",sx:{p:2},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"管理"}),a.jsxs(as,{children:[(y==null?void 0:y.canViewUsers)&&a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/users",children:[a.jsx(Un,{children:a.jsx(RP,{})}),a.jsx(Zn,{primary:"ユーザー管理",secondary:"ユーザーの追加・編集・削除"})]})}),(y==null?void 0:y.canViewStaging)&&a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/staging",children:[a.jsx(Un,{children:a.jsx(mP,{})}),a.jsx(Zn,{primary:"ステージングブランチ管理",secondary:"プレビュー用ブランチの設定"})]})})]})]})}),N&&a.jsx(Et,{item:!0,xs:12,children:a.jsxs($t,{"data-component-name":"cmp:DevelopSection",sx:{p:2},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"開発"}),a.jsxs(as,{children:[(y==null?void 0:y.canViewContentType)&&a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/content-types",children:[a.jsx(Un,{children:a.jsx(CY,{})}),a.jsx(Zn,{primary:"コンテンツタイプ編集",secondary:"フィールド定義・UI設定・ビュー定義"})]})}),(y==null?void 0:y.canViewBuildRecipes)&&a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/build-recipes",children:[a.jsx(Un,{children:a.jsx(b2,{})}),a.jsx(Zn,{primary:"ビルドデータレシピ編集",secondary:"コンテンツからJSONへの変換定義"})]})})]})]})})]})]})})}function gX({userStagingBranches:t,personalBranchName:e,dashboardUseCase:n,canEditDeploy:r}){return a.jsxs($t,{"data-component-name":"cmp:PersonalBranchPreviewSection",sx:{p:3},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"プレビュー"}),t.length>0?a.jsx(B,{sx:{display:"flex",flexDirection:"column",gap:3,py:2},children:t.map(s=>a.jsx(yX,{stagingBranch:s,personalBranchName:e,previewEnabled:n.isPreviewEnabled(s.branchName),canEditDeploy:r},s.branchName))}):a.jsx(zt,{severity:"info",sx:{mt:2},children:"個人ブランチ用ステージングブランチは設定されていません"})]})}function yX({stagingBranch:t,personalBranchName:e,previewEnabled:n,canEditDeploy:r}){const s=t.isDefault?ta().previewUrl:t.previewUrl;return a.jsxs(B,{sx:{display:"flex",flexDirection:"column",alignItems:"center",p:2,border:"1px dashed",borderColor:"divider",borderRadius:1},children:[a.jsx(G,{variant:"subtitle1",fontWeight:"bold",gutterBottom:!0,children:t.branchName}),a.jsx(RC,{sx:{fontSize:48,color:"success.main",mb:1}}),a.jsxs(G,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:["frelio-cms/",e,"ブランチを",t.branchName,"ブランチにマージ"]}),a.jsx(pe,{variant:"contained",color:"success",fullWidth:!0,disabled:!r||!n,size:"small",children:"プレビューに反映"}),s&&a.jsx(pe,{variant:"outlined",color:"success",size:"small",startIcon:a.jsx(ip,{}),fullWidth:!0,sx:{mt:1},href:s,target:"_blank",rel:"noopener noreferrer",children:"プレビューを見る"})]})}function vX({previewEnabled:t,productionEnabled:e,directDeployEnabled:n,stagingLastCommit:r,productionLastCommit:s,previewUrl:i,productionUrl:l,badgeTooltipOpen:u,setBadgeTooltipOpen:p,dashboardUseCase:f,canEditDeploy:m}){const{deployStatus:g,deployTarget:y,deployError:v}=f.getDeployState(),C=g==="loading",S=async()=>{await f.mergeToStaging()},j=async()=>{await f.mergeToProduction()},D=async()=>{await f.directDeploy()},M=()=>{f.resetDeployState()},T=()=>{switch(y){case"preview":return"プレビューに反映しました";case"production":return"本番に反映しました";case"direct":return"直接デプロイを開始しました。GitHub Actions で実行中です。";default:return"デプロイが完了しました"}};return a.jsxs($t,{"data-component-name":"cmp:DevelopBranchPreviewSection",sx:{p:3},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"プレビューと本番化"}),a.jsxs(B,{sx:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,py:3},children:[a.jsxs(B,{sx:{display:"flex",flexDirection:"column",alignItems:"center"},children:[a.jsx(RC,{sx:{fontSize:64,color:"info.main",mb:1}}),a.jsx(G,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:"developブランチをstagingブランチにマージ"}),a.jsxs(B,{sx:{position:"relative",width:"100%"},children:[a.jsx(pe,{variant:"contained",color:"info",fullWidth:!0,disabled:!m||!t||C,onClick:S,startIcon:C&&y==="preview"?a.jsx(ut,{size:16,color:"inherit"}):void 0,children:C&&y==="preview"?"反映中...":"プレビューに反映"}),t&&e&&a.jsx(PI,{onClickAway:()=>p(!1),children:a.jsx(Er,{title:a.jsxs(a.Fragment,{children:["プレビューは最新ではありません。",a.jsx("br",{}),"本番を最新にするには、「本番に反映」をする前に「プレビューに反映」を行う必要があります。"]}),arrow:!0,open:u,disableFocusListener:!0,disableHoverListener:!0,disableTouchListener:!0,children:a.jsx(B,{onClick:()=>p(!u),sx:{position:"absolute",top:-8,right:-8,width:20,height:20,borderRadius:"50%",bgcolor:"warning.main",color:"warning.contrastText",display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:"bold",cursor:"pointer"},children:"!"})})})]}),a.jsx(pe,{variant:"outlined",color:"info",size:"small",startIcon:a.jsx(ip,{}),fullWidth:!0,sx:{mt:1},href:i,target:"_blank",rel:"noopener noreferrer",disabled:!i,children:"今のプレビューを見る"}),r&&a.jsxs(G,{variant:"caption",color:"text.secondary",sx:{mt:.5},children:["最終反映: ",f.formatRelativeTime(r)]})]}),a.jsx(zx,{sx:{fontSize:48,color:"grey.400"}}),a.jsxs(B,{sx:{display:"flex",flexDirection:"column",alignItems:"center"},children:[a.jsx(kC,{sx:{fontSize:64,color:"success.main",mb:1}}),a.jsx(G,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:"stagingブランチをmainブランチにマージ"}),a.jsx(pe,{variant:"contained",color:"success",fullWidth:!0,disabled:!m||!e||C,onClick:j,startIcon:C&&y==="production"?a.jsx(ut,{size:16,color:"inherit"}):void 0,children:C&&y==="production"?"反映中...":"本番に反映"}),a.jsx(pe,{variant:"text",color:"success",size:"small",startIcon:a.jsx(ip,{}),fullWidth:!0,sx:{mt:1},href:l,target:"_blank",rel:"noopener noreferrer",disabled:!l,children:"今の本番を見る"}),s&&a.jsxs(G,{variant:"caption",color:"text.secondary",sx:{mt:.5},children:["最終反映: ",f.formatRelativeTime(s)]})]}),a.jsxs(B,{sx:{mt:3,pt:3,borderTop:1,borderColor:"divider",width:"100%",textAlign:"center"},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",justifyContent:"center",gap:1,mb:2},children:[a.jsx(RC,{sx:{fontSize:64,color:"warning.main"}}),a.jsx(fJ,{sx:{fontSize:48,color:"grey.400"}}),a.jsx(kC,{sx:{fontSize:64,color:"warning.main"}})]}),a.jsx(pe,{variant:"outlined",color:"warning",startIcon:C&&y==="direct"?a.jsx(ut,{size:16,color:"inherit"}):a.jsx(gY,{}),disabled:!m||!n||C,onClick:D,children:C&&y==="direct"?"デプロイ中...":"プレビューに反映してそのまま本番化"})]}),a.jsx(B,{sx:{mt:2,textAlign:"center"},children:a.jsx(pe,{component:gs,to:"/deploy-history",variant:"text",size:"small",startIcon:a.jsx(wP,{}),color:"inherit",children:"本番化履歴"})})]}),a.jsx(ea,{open:g==="success",autoHideDuration:5e3,onClose:M,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:M,severity:"success",variant:"filled",children:T()})}),a.jsx(ea,{open:g==="error",autoHideDuration:8e3,onClose:M,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:M,severity:"error",variant:"filled",children:v??"エラーが発生しました"})})]})}function xX({contentTypes:t,dashboardUseCase:e,stagingLastCommit:n,isLoading:r,canEditContentType:s}){const i=t.filter(y=>(y.displayLocation??"normal")==="normal"),l=t.filter(y=>y.displayLocation==="collapsed"),u=s?t.filter(y=>y.displayLocation==="hidden"):[],p=i.length>0||l.length>0||u.length>0,f=y=>y.some(v=>{const C=e.getContentTypeMetadata(v.id);return C!=null&&C.lastUpdatedAt&&n?new Date(C.lastUpdatedAt).getTime()>n.getTime():!1}),m=f(l),g=f(u);return r?a.jsx(B,{display:"flex",justifyContent:"center",p:2,children:a.jsx(ut,{size:24})}):p?a.jsxs(a.Fragment,{children:[i.length>0&&a.jsx(as,{"data-component-name":"cmp:NormalContentTypeList",children:i.map(y=>a.jsx(OC,{ct:y,dashboardUseCase:e,stagingLastCommit:n},y.id))}),l.length>0&&a.jsx(bX,{contentTypes:l,dashboardUseCase:e,stagingLastCommit:n,hasUnreflected:m}),u.length>0&&a.jsxs(_s,{"data-component-name":"cmp:HiddenContentTypesSection",defaultExpanded:!1,sx:{mt:2,"&:before":{display:"none"},boxShadow:"none",border:"1px dashed",borderColor:"warning.main",borderRadius:1,bgcolor:"warning.lighter"},children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(xv,{variant:"dot",color:"warning",invisible:!g,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(LY,{fontSize:"small",color:"warning"}),a.jsx(G,{variant:"body2",color:"warning.dark",children:"非表示コンテンツ"})]})})}),a.jsx(Is,{sx:{p:0},children:a.jsx(as,{disablePadding:!0,children:u.map(y=>a.jsx(OC,{ct:y,dashboardUseCase:e,stagingLastCommit:n},y.id))})})]})]}):a.jsxs(B,{p:2,textAlign:"center",children:[a.jsx(Tp,{sx:{fontSize:48,color:"grey.400",mb:1}}),a.jsx(G,{color:"text.secondary",children:"コンテンツタイプがまだありません"}),a.jsx(G,{variant:"body2",color:"text.secondary",children:"content-repo に定義を追加してください"})]})}function OC({ct:t,dashboardUseCase:e,stagingLastCommit:n}){const r=e.getContentTypeMetadata(t.id),s=r!=null&&r.lastUpdatedAt?e.formatRelativeTime(r.lastUpdatedAt):null,i=s?`最終更新: ${s}`:"",l=r!=null&&r.lastUpdatedAt&&n?new Date(r.lastUpdatedAt).getTime()>n.getTime():!1;return a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:`/contents/${t.id}`,children:[a.jsx(Un,{sx:{mr:2},children:a.jsx(xv,{variant:"dot",color:"warning",invisible:!l,children:a.jsx(Vx,{iconName:t.icon,sx:{fontSize:48}})})}),a.jsx(Zn,{primary:t.label,secondary:i})]})})}function bX({contentTypes:t,dashboardUseCase:e,stagingLastCommit:n,hasUnreflected:r}){const[s,i]=b.useState(!1);return a.jsxs(_s,{"data-component-name":"cmp:CollapsedContentTypesSection",expanded:s,onChange:(l,u)=>i(u),disableGutters:!0,sx:{mt:1,"&:before":{display:"none"},boxShadow:"none",bgcolor:"transparent"},children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{fontSize:"small"}),sx:{minHeight:"auto",p:0,justifyContent:"flex-start","& .MuiAccordionSummary-content":{m:0,flexGrow:0},"& .MuiAccordionSummary-expandIconWrapper":{ml:.5}},children:a.jsxs(B,{sx:{display:"flex",alignItems:"center"},children:[a.jsx(G,{variant:"body2",color:"text.secondary",children:"その他"}),r&&!s&&a.jsx(B,{sx:{width:8,height:8,borderRadius:"50%",bgcolor:"warning.main",ml:.5}})]})}),a.jsx(Is,{sx:{p:0},children:a.jsx(as,{disablePadding:!0,children:t.map(l=>a.jsx(OC,{ct:l,dashboardUseCase:e,stagingLastCommit:n},l.id))})})]})}var xn;(function(t){t.assertEqual=s=>s;function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const l of s)i[l]=l;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of i)l[u]=s[u];return t.objectValues(l)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&i.push(l);return i},t.find=(s,i)=>{for(const l of s)if(i(l))return l},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(xn||(xn={}));var AC;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(AC||(AC={}));const pt=xn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ml=t=>{switch(typeof t){case"undefined":return pt.undefined;case"string":return pt.string;case"number":return isNaN(t)?pt.nan:pt.number;case"boolean":return pt.boolean;case"function":return pt.function;case"bigint":return pt.bigint;case"symbol":return pt.symbol;case"object":return Array.isArray(t)?pt.array:t===null?pt.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?pt.promise:typeof Map<"u"&&t instanceof Map?pt.map:typeof Set<"u"&&t instanceof Set?pt.set:typeof Date<"u"&&t instanceof Date?pt.date:pt.object;default:return pt.unknown}},He=xn.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),SX=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");let To=class zP extends Error{constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const l of i.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)r._errors.push(n(l));else{let u=r,p=0;for(;p<l.path.length;){const f=l.path[p];p===l.path.length-1?(u[f]=u[f]||{_errors:[]},u[f]._errors.push(n(l))):u[f]=u[f]||{_errors:[]},u=u[f],p++}}};return s(this),r}static assert(e){if(!(e instanceof zP))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,xn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};To.create=t=>new To(t);const op=(t,e)=>{let n;switch(t.code){case He.invalid_type:t.received===pt.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case He.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,xn.jsonStringifyReplacer)}`;break;case He.unrecognized_keys:n=`Unrecognized key(s) in object: ${xn.joinValues(t.keys,", ")}`;break;case He.invalid_union:n="Invalid input";break;case He.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${xn.joinValues(t.options)}`;break;case He.invalid_enum_value:n=`Invalid enum value. Expected ${xn.joinValues(t.options)}, received '${t.received}'`;break;case He.invalid_arguments:n="Invalid function arguments";break;case He.invalid_return_type:n="Invalid function return type";break;case He.invalid_date:n="Invalid date";break;case He.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:xn.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case He.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case He.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case He.custom:n="Invalid input";break;case He.invalid_intersection_types:n="Intersection results could not be merged";break;case He.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case He.not_finite:n="Number must be finite";break;default:n=e.defaultError,xn.assertNever(t)}return{message:n}};let $P=op;function CX(t){$P=t}function Dv(){return $P}const Ev=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],l={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let u="";const p=r.filter(f=>!!f).slice().reverse();for(const f of p)u=f(l,{data:e,defaultError:u}).message;return{...s,path:i,message:u}},wX=[];function ot(t,e){const n=Dv(),r=Ev({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===op?void 0:op].filter(s=>!!s)});t.common.issues.push(r)}let ni=class NP{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return Lt;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,l=await s.value;r.push({key:i,value:l})}return NP.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:l}=s;if(i.status==="aborted"||l.status==="aborted")return Lt;i.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(r[i.value]=l.value)}return{status:e.value,value:r}}};const Lt=Object.freeze({status:"aborted"}),Dd=t=>({status:"dirty",value:t}),zs=t=>({status:"valid",value:t}),_C=t=>t.status==="aborted",IC=t=>t.status==="dirty",Lh=t=>t.status==="valid",zh=t=>typeof Promise<"u"&&t instanceof Promise;function Rv(t,e,n,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function FP(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}var Tt;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Tt||(Tt={}));var Kf,Qf;let ra=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const XM=(t,e)=>{if(Lh(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new To(t.common.issues);return this._error=n,this._error}}};function Gt(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{var p,f;const{message:m}=t;return l.code==="invalid_enum_value"?{message:m??u.defaultError}:typeof u.data>"u"?{message:(p=m??r)!==null&&p!==void 0?p:u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:(f=m??n)!==null&&f!==void 0?f:u.defaultError}},description:s}}let nn=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Ml(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ml(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ni,ctx:{common:e.parent.common,data:e.data,parsedType:Ml(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(zh(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){var r;const s={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ml(e)},i=this._parseSync({data:e,path:s.path,parent:s});return XM(s,i)}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ml(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(zh(s)?s:Promise.resolve(s));return XM(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const l=e(s),u=()=>i.addIssue({code:He.custom,...r(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(p=>p?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new ko({schema:this,typeName:Pt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Zo.create(this,this._def)}nullable(){return lc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return vu.create(this,this._def)}promise(){return cp.create(this,this._def)}or(e){return Hh.create([this,e],this._def)}and(e){return Wh.create(this,e,this._def)}transform(e){return new ko({...Gt(this._def),schema:this,typeName:Pt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Kh({...Gt(this._def),innerType:this,defaultValue:n,typeName:Pt.ZodDefault})}brand(){return new E2({typeName:Pt.ZodBranded,type:this,...Gt(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Qh({...Gt(this._def),innerType:this,catchValue:n,typeName:Pt.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return R2.create(this,e)}readonly(){return Jh.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const jX=/^c[^\s-]{8,}$/i,TX=/^[0-9a-z]+$/,DX=/^[0-9A-HJKMNP-TV-Z]{26}$/,EX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,RX=/^[a-z0-9_-]{21}$/i,kX=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,MX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let l1;const AX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_X=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,IX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BP="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",PX=new RegExp(`^${BP}$`);function UP(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function LX(t){return new RegExp(`^${UP(t)}$`)}function VP(t){let e=`${BP}T${UP(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function zX(t,e){return!!((e==="v4"||!e)&&AX.test(t)||(e==="v6"||!e)&&_X.test(t))}let ap=class Jf extends nn{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==pt.string){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_type,expected:pt.string,received:i.parsedType}),Lt}const r=new ni;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),ot(s,{code:He.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),ot(s,{code:He.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const l=e.data.length>i.value,u=e.data.length<i.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?ot(s,{code:He.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):u&&ot(s,{code:He.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")MX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"email",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")l1||(l1=new RegExp(OX,"u")),l1.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"emoji",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")EX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"uuid",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")RX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"nanoid",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")jX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"cuid",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")TX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"cuid2",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")DX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"ulid",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ot(s,{validation:"url",code:He.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"regex",code:He.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?VP(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?PX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?LX(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?kX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"duration",code:He.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?zX(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"ip",code:He.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?IX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"base64",code:He.invalid_string,message:i.message}),r.dirty()):xn.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:He.invalid_string,...Tt.errToObj(r)})}_addCheck(e){return new Jf({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Tt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Tt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Tt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Tt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Tt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Tt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Tt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Tt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Tt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Tt.errToObj(e)})}datetime(e){var n,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(n=e==null?void 0:e.offset)!==null&&n!==void 0?n:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...Tt.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...Tt.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Tt.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Tt.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...Tt.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Tt.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Tt.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Tt.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Tt.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Tt.errToObj(n)})}nonempty(e){return this.min(1,Tt.errToObj(e))}trim(){return new Jf({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Jf({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Jf({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};ap.create=t=>{var e;return new ap({checks:[],typeName:Pt.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...Gt(t)})};function $X(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=parseInt(t.toFixed(s).replace(".","")),l=parseInt(e.toFixed(s).replace(".",""));return i%l/Math.pow(10,s)}let $h=class PC extends nn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==pt.number){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_type,expected:pt.number,received:i.parsedType}),Lt}let r;const s=new ni;for(const i of this._def.checks)i.kind==="int"?xn.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ot(r,{code:He.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?$X(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ot(r,{code:He.not_finite,message:i.message}),s.dirty()):xn.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Tt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Tt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Tt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Tt.toString(n))}setLimit(e,n,r,s){return new PC({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Tt.toString(s)}]})}_addCheck(e){return new PC({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Tt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Tt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Tt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Tt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Tt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Tt.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Tt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Tt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Tt.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&xn.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};$h.create=t=>new $h({checks:[],typeName:Pt.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Gt(t)});let Nh=class LC extends nn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==pt.bigint){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_type,expected:pt.bigint,received:i.parsedType}),Lt}let r;const s=new ni;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):xn.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Tt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Tt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Tt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Tt.toString(n))}setLimit(e,n,r,s){return new LC({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Tt.toString(s)}]})}_addCheck(e){return new LC({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Tt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Tt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Tt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Tt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Tt.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Nh.create=t=>{var e;return new Nh({checks:[],typeName:Pt.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...Gt(t)})};let Fh=class extends nn{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==pt.boolean){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.boolean,received:r.parsedType}),Lt}return zs(e.data)}};Fh.create=t=>new Fh({typeName:Pt.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Gt(t)});let Bh=class HP extends nn{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==pt.date){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_type,expected:pt.date,received:i.parsedType}),Lt}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_date}),Lt}const r=new ni;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),ot(s,{code:He.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),ot(s,{code:He.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):xn.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new HP({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Tt.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Tt.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Bh.create=t=>new Bh({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:Pt.ZodDate,...Gt(t)});let kv=class extends nn{_parse(e){if(this._getType(e)!==pt.symbol){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.symbol,received:r.parsedType}),Lt}return zs(e.data)}};kv.create=t=>new kv({typeName:Pt.ZodSymbol,...Gt(t)});let Uh=class extends nn{_parse(e){if(this._getType(e)!==pt.undefined){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.undefined,received:r.parsedType}),Lt}return zs(e.data)}};Uh.create=t=>new Uh({typeName:Pt.ZodUndefined,...Gt(t)});let Vh=class extends nn{_parse(e){if(this._getType(e)!==pt.null){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.null,received:r.parsedType}),Lt}return zs(e.data)}};Vh.create=t=>new Vh({typeName:Pt.ZodNull,...Gt(t)});let lp=class extends nn{constructor(){super(...arguments),this._any=!0}_parse(e){return zs(e.data)}};lp.create=t=>new lp({typeName:Pt.ZodAny,...Gt(t)});let du=class extends nn{constructor(){super(...arguments),this._unknown=!0}_parse(e){return zs(e.data)}};du.create=t=>new du({typeName:Pt.ZodUnknown,...Gt(t)});let Ga=class extends nn{_parse(e){const n=this._getOrReturnCtx(e);return ot(n,{code:He.invalid_type,expected:pt.never,received:n.parsedType}),Lt}};Ga.create=t=>new Ga({typeName:Pt.ZodNever,...Gt(t)});let Mv=class extends nn{_parse(e){if(this._getType(e)!==pt.undefined){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.void,received:r.parsedType}),Lt}return zs(e.data)}};Mv.create=t=>new Mv({typeName:Pt.ZodVoid,...Gt(t)});let vu=class Jy extends nn{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==pt.array)return ot(n,{code:He.invalid_type,expected:pt.array,received:n.parsedType}),Lt;if(s.exactLength!==null){const l=n.data.length>s.exactLength.value,u=n.data.length<s.exactLength.value;(l||u)&&(ot(n,{code:l?He.too_big:He.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(ot(n,{code:He.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(ot(n,{code:He.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((l,u)=>s.type._parseAsync(new ra(n,l,n.path,u)))).then(l=>ni.mergeArray(r,l));const i=[...n.data].map((l,u)=>s.type._parseSync(new ra(n,l,n.path,u)));return ni.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new Jy({...this._def,minLength:{value:e,message:Tt.toString(n)}})}max(e,n){return new Jy({...this._def,maxLength:{value:e,message:Tt.toString(n)}})}length(e,n){return new Jy({...this._def,exactLength:{value:e,message:Tt.toString(n)}})}nonempty(e){return this.min(1,e)}};vu.create=(t,e)=>new vu({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Pt.ZodArray,...Gt(e)});function bd(t){if(t instanceof to){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Zo.create(bd(r))}return new to({...t._def,shape:()=>e})}else return t instanceof vu?new vu({...t._def,type:bd(t.element)}):t instanceof Zo?Zo.create(bd(t.unwrap())):t instanceof lc?lc.create(bd(t.unwrap())):t instanceof ac?ac.create(t.items.map(e=>bd(e))):t}let to=class ho extends nn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=xn.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==pt.object){const f=this._getOrReturnCtx(e);return ot(f,{code:He.invalid_type,expected:pt.object,received:f.parsedType}),Lt}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof Ga&&this._def.unknownKeys==="strip"))for(const f in s.data)l.includes(f)||u.push(f);const p=[];for(const f of l){const m=i[f],g=s.data[f];p.push({key:{status:"valid",value:f},value:m._parse(new ra(s,g,s.path,f)),alwaysSet:f in s.data})}if(this._def.catchall instanceof Ga){const f=this._def.unknownKeys;if(f==="passthrough")for(const m of u)p.push({key:{status:"valid",value:m},value:{status:"valid",value:s.data[m]}});else if(f==="strict")u.length>0&&(ot(s,{code:He.unrecognized_keys,keys:u}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const m of u){const g=s.data[m];p.push({key:{status:"valid",value:m},value:f._parse(new ra(s,g,s.path,m)),alwaysSet:m in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const f=[];for(const m of p){const g=await m.key,y=await m.value;f.push({key:g,value:y,alwaysSet:m.alwaysSet})}return f}).then(f=>ni.mergeObjectSync(r,f)):ni.mergeObjectSync(r,p)}get shape(){return this._def.shape()}strict(e){return Tt.errToObj,new ho({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var s,i,l,u;const p=(l=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,n,r).message)!==null&&l!==void 0?l:r.defaultError;return n.code==="unrecognized_keys"?{message:(u=Tt.errToObj(e).message)!==null&&u!==void 0?u:p}:{message:p}}}:{}})}strip(){return new ho({...this._def,unknownKeys:"strip"})}passthrough(){return new ho({...this._def,unknownKeys:"passthrough"})}extend(e){return new ho({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ho({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Pt.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new ho({...this._def,catchall:e})}pick(e){const n={};return xn.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new ho({...this._def,shape:()=>n})}omit(e){const n={};return xn.objectKeys(this.shape).forEach(r=>{e[r]||(n[r]=this.shape[r])}),new ho({...this._def,shape:()=>n})}deepPartial(){return bd(this)}partial(e){const n={};return xn.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}),new ho({...this._def,shape:()=>n})}required(e){const n={};return xn.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Zo;)i=i._def.innerType;n[r]=i}}),new ho({...this._def,shape:()=>n})}keyof(){return GP(xn.objectKeys(this.shape))}};to.create=(t,e)=>new to({shape:()=>t,unknownKeys:"strip",catchall:Ga.create(),typeName:Pt.ZodObject,...Gt(e)});to.strictCreate=(t,e)=>new to({shape:()=>t,unknownKeys:"strict",catchall:Ga.create(),typeName:Pt.ZodObject,...Gt(e)});to.lazycreate=(t,e)=>new to({shape:t,unknownKeys:"strip",catchall:Ga.create(),typeName:Pt.ZodObject,...Gt(e)});let Hh=class extends nn{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const u of i)if(u.result.status==="valid")return u.result;for(const u of i)if(u.result.status==="dirty")return n.common.issues.push(...u.ctx.common.issues),u.result;const l=i.map(u=>new To(u.ctx.common.issues));return ot(n,{code:He.invalid_union,unionErrors:l}),Lt}if(n.common.async)return Promise.all(r.map(async i=>{const l={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:l}),ctx:l}})).then(s);{let i;const l=[];for(const p of r){const f={...n,common:{...n.common,issues:[]},parent:null},m=p._parseSync({data:n.data,path:n.path,parent:f});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:f}),f.common.issues.length&&l.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const u=l.map(p=>new To(p));return ot(n,{code:He.invalid_union,unionErrors:u}),Lt}}get options(){return this._def.options}};Hh.create=(t,e)=>new Hh({options:t,typeName:Pt.ZodUnion,...Gt(e)});const Aa=t=>t instanceof qh?Aa(t.schema):t instanceof ko?Aa(t.innerType()):t instanceof Gh?[t.value]:t instanceof Am?t.options:t instanceof Zh?xn.objectValues(t.enum):t instanceof Kh?Aa(t._def.innerType):t instanceof Uh?[void 0]:t instanceof Vh?[null]:t instanceof Zo?[void 0,...Aa(t.unwrap())]:t instanceof lc?[null,...Aa(t.unwrap())]:t instanceof E2||t instanceof Jh?Aa(t.unwrap()):t instanceof Qh?Aa(t._def.innerType):[];class Hx extends nn{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==pt.object)return ot(n,{code:He.invalid_type,expected:pt.object,received:n.parsedType}),Lt;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(ot(n,{code:He.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Lt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const l=Aa(i.shape[e]);if(!l.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const u of l){if(s.has(u))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(u)}`);s.set(u,i)}}return new Hx({typeName:Pt.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Gt(r)})}}function zC(t,e){const n=Ml(t),r=Ml(e);if(t===e)return{valid:!0,data:t};if(n===pt.object&&r===pt.object){const s=xn.objectKeys(e),i=xn.objectKeys(t).filter(u=>s.indexOf(u)!==-1),l={...t,...e};for(const u of i){const p=zC(t[u],e[u]);if(!p.valid)return{valid:!1};l[u]=p.data}return{valid:!0,data:l}}else if(n===pt.array&&r===pt.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const l=t[i],u=e[i],p=zC(l,u);if(!p.valid)return{valid:!1};s.push(p.data)}return{valid:!0,data:s}}else return n===pt.date&&r===pt.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let Wh=class extends nn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(i,l)=>{if(_C(i)||_C(l))return Lt;const u=zC(i.value,l.value);return u.valid?((IC(i)||IC(l))&&n.dirty(),{status:n.value,value:u.data}):(ot(r,{code:He.invalid_intersection_types}),Lt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,l])=>s(i,l)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Wh.create=(t,e,n)=>new Wh({left:t,right:e,typeName:Pt.ZodIntersection,...Gt(n)});let ac=class WP extends nn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==pt.array)return ot(r,{code:He.invalid_type,expected:pt.array,received:r.parsedType}),Lt;if(r.data.length<this._def.items.length)return ot(r,{code:He.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Lt;!this._def.rest&&r.data.length>this._def.items.length&&(ot(r,{code:He.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((l,u)=>{const p=this._def.items[u]||this._def.rest;return p?p._parse(new ra(r,l,r.path,u)):null}).filter(l=>!!l);return r.common.async?Promise.all(i).then(l=>ni.mergeArray(n,l)):ni.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new WP({...this._def,rest:e})}};ac.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ac({items:t,typeName:Pt.ZodTuple,rest:null,...Gt(e)})};let qP=class $C extends nn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==pt.object)return ot(r,{code:He.invalid_type,expected:pt.object,received:r.parsedType}),Lt;const s=[],i=this._def.keyType,l=this._def.valueType;for(const u in r.data)s.push({key:i._parse(new ra(r,u,r.path,u)),value:l._parse(new ra(r,r.data[u],r.path,u)),alwaysSet:u in r.data});return r.common.async?ni.mergeObjectAsync(n,s):ni.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof nn?new $C({keyType:e,valueType:n,typeName:Pt.ZodRecord,...Gt(r)}):new $C({keyType:ap.create(),valueType:e,typeName:Pt.ZodRecord,...Gt(n)})}},Ov=class extends nn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==pt.map)return ot(r,{code:He.invalid_type,expected:pt.map,received:r.parsedType}),Lt;const s=this._def.keyType,i=this._def.valueType,l=[...r.data.entries()].map(([u,p],f)=>({key:s._parse(new ra(r,u,r.path,[f,"key"])),value:i._parse(new ra(r,p,r.path,[f,"value"]))}));if(r.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const p of l){const f=await p.key,m=await p.value;if(f.status==="aborted"||m.status==="aborted")return Lt;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),u.set(f.value,m.value)}return{status:n.value,value:u}})}else{const u=new Map;for(const p of l){const f=p.key,m=p.value;if(f.status==="aborted"||m.status==="aborted")return Lt;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),u.set(f.value,m.value)}return{status:n.value,value:u}}}};Ov.create=(t,e,n)=>new Ov({valueType:e,keyType:t,typeName:Pt.ZodMap,...Gt(n)});let Av=class NC extends nn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==pt.set)return ot(r,{code:He.invalid_type,expected:pt.set,received:r.parsedType}),Lt;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(ot(r,{code:He.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(ot(r,{code:He.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function l(p){const f=new Set;for(const m of p){if(m.status==="aborted")return Lt;m.status==="dirty"&&n.dirty(),f.add(m.value)}return{status:n.value,value:f}}const u=[...r.data.values()].map((p,f)=>i._parse(new ra(r,p,r.path,f)));return r.common.async?Promise.all(u).then(p=>l(p)):l(u)}min(e,n){return new NC({...this._def,minSize:{value:e,message:Tt.toString(n)}})}max(e,n){return new NC({...this._def,maxSize:{value:e,message:Tt.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Av.create=(t,e)=>new Av({valueType:t,minSize:null,maxSize:null,typeName:Pt.ZodSet,...Gt(e)});class zd extends nn{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==pt.function)return ot(n,{code:He.invalid_type,expected:pt.function,received:n.parsedType}),Lt;function r(u,p){return Ev({data:u,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Dv(),op].filter(f=>!!f),issueData:{code:He.invalid_arguments,argumentsError:p}})}function s(u,p){return Ev({data:u,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Dv(),op].filter(f=>!!f),issueData:{code:He.invalid_return_type,returnTypeError:p}})}const i={errorMap:n.common.contextualErrorMap},l=n.data;if(this._def.returns instanceof cp){const u=this;return zs(async function(...p){const f=new To([]),m=await u._def.args.parseAsync(p,i).catch(v=>{throw f.addIssue(r(p,v)),f}),g=await Reflect.apply(l,this,m);return await u._def.returns._def.type.parseAsync(g,i).catch(v=>{throw f.addIssue(s(g,v)),f})})}else{const u=this;return zs(function(...p){const f=u._def.args.safeParse(p,i);if(!f.success)throw new To([r(p,f.error)]);const m=Reflect.apply(l,this,f.data),g=u._def.returns.safeParse(m,i);if(!g.success)throw new To([s(m,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new zd({...this._def,args:ac.create(e).rest(du.create())})}returns(e){return new zd({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new zd({args:e||ac.create([]).rest(du.create()),returns:n||du.create(),typeName:Pt.ZodFunction,...Gt(r)})}}let qh=class extends nn{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};qh.create=(t,e)=>new qh({getter:t,typeName:Pt.ZodLazy,...Gt(e)});let Gh=class extends nn{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return ot(n,{received:n.data,code:He.invalid_literal,expected:this._def.value}),Lt}return{status:"valid",value:e.data}}get value(){return this._def.value}};Gh.create=(t,e)=>new Gh({value:t,typeName:Pt.ZodLiteral,...Gt(e)});function GP(t,e){return new Am({values:t,typeName:Pt.ZodEnum,...Gt(e)})}let Am=class FC extends nn{constructor(){super(...arguments),Kf.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return ot(n,{expected:xn.joinValues(r),received:n.parsedType,code:He.invalid_type}),Lt}if(Rv(this,Kf)||FP(this,Kf,new Set(this._def.values)),!Rv(this,Kf).has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return ot(n,{received:n.data,code:He.invalid_enum_value,options:r}),Lt}return zs(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return FC.create(e,{...this._def,...n})}exclude(e,n=this._def){return FC.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Kf=new WeakMap;Am.create=GP;let Zh=class extends nn{constructor(){super(...arguments),Qf.set(this,void 0)}_parse(e){const n=xn.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==pt.string&&r.parsedType!==pt.number){const s=xn.objectValues(n);return ot(r,{expected:xn.joinValues(s),received:r.parsedType,code:He.invalid_type}),Lt}if(Rv(this,Qf)||FP(this,Qf,new Set(xn.getValidEnumValues(this._def.values))),!Rv(this,Qf).has(e.data)){const s=xn.objectValues(n);return ot(r,{received:r.data,code:He.invalid_enum_value,options:s}),Lt}return zs(e.data)}get enum(){return this._def.values}};Qf=new WeakMap;Zh.create=(t,e)=>new Zh({values:t,typeName:Pt.ZodNativeEnum,...Gt(e)});let cp=class extends nn{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==pt.promise&&n.common.async===!1)return ot(n,{code:He.invalid_type,expected:pt.promise,received:n.parsedType}),Lt;const r=n.parsedType===pt.promise?n.data:Promise.resolve(n.data);return zs(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};cp.create=(t,e)=>new cp({type:t,typeName:Pt.ZodPromise,...Gt(e)});let ko=class extends nn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Pt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:l=>{ot(r,l),l.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const l=s.transform(r.data,i);if(r.common.async)return Promise.resolve(l).then(async u=>{if(n.value==="aborted")return Lt;const p=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return p.status==="aborted"?Lt:p.status==="dirty"||n.value==="dirty"?Dd(p.value):p});{if(n.value==="aborted")return Lt;const u=this._def.schema._parseSync({data:l,path:r.path,parent:r});return u.status==="aborted"?Lt:u.status==="dirty"||n.value==="dirty"?Dd(u.value):u}}if(s.type==="refinement"){const l=u=>{const p=s.refinement(u,i);if(r.common.async)return Promise.resolve(p);if(p instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?Lt:(u.status==="dirty"&&n.dirty(),l(u.value),{status:n.value,value:u.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>u.status==="aborted"?Lt:(u.status==="dirty"&&n.dirty(),l(u.value).then(()=>({status:n.value,value:u.value}))))}if(s.type==="transform")if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Lh(l))return l;const u=s.transform(l.value,i);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:u}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>Lh(l)?Promise.resolve(s.transform(l.value,i)).then(u=>({status:n.value,value:u})):l);xn.assertNever(s)}};ko.create=(t,e,n)=>new ko({schema:t,typeName:Pt.ZodEffects,effect:e,...Gt(n)});ko.createWithPreprocess=(t,e,n)=>new ko({schema:e,effect:{type:"preprocess",transform:t},typeName:Pt.ZodEffects,...Gt(n)});let Zo=class extends nn{_parse(e){return this._getType(e)===pt.undefined?zs(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Zo.create=(t,e)=>new Zo({innerType:t,typeName:Pt.ZodOptional,...Gt(e)});let lc=class extends nn{_parse(e){return this._getType(e)===pt.null?zs(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lc.create=(t,e)=>new lc({innerType:t,typeName:Pt.ZodNullable,...Gt(e)});let Kh=class extends nn{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===pt.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Kh.create=(t,e)=>new Kh({innerType:t,typeName:Pt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Gt(e)});let Qh=class extends nn{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return zh(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new To(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new To(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Qh.create=(t,e)=>new Qh({innerType:t,typeName:Pt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Gt(e)});let _v=class extends nn{_parse(e){if(this._getType(e)!==pt.nan){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.nan,received:r.parsedType}),Lt}return{status:"valid",value:e.data}}};_v.create=t=>new _v({typeName:Pt.ZodNaN,...Gt(t)});const NX=Symbol("zod_brand");let E2=class extends nn{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},R2=class ZP extends nn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Lt:i.status==="dirty"?(n.dirty(),Dd(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Lt:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new ZP({in:e,out:n,typeName:Pt.ZodPipeline})}},Jh=class extends nn{_parse(e){const n=this._def.innerType._parse(e),r=s=>(Lh(s)&&(s.value=Object.freeze(s.value)),s);return zh(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Jh.create=(t,e)=>new Jh({innerType:t,typeName:Pt.ZodReadonly,...Gt(e)});function KP(t,e={},n){return t?lp.create().superRefine((r,s)=>{var i,l;if(!t(r)){const u=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e,p=(l=(i=u.fatal)!==null&&i!==void 0?i:n)!==null&&l!==void 0?l:!0,f=typeof u=="string"?{message:u}:u;s.addIssue({code:"custom",...f,fatal:p})}}):lp.create()}const FX={object:to.lazycreate};var Pt;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Pt||(Pt={}));const BX=(t,e={message:`Input not instance of ${t.name}`})=>KP(n=>n instanceof t,e),QP=ap.create,JP=$h.create,UX=_v.create,VX=Nh.create,YP=Fh.create,HX=Bh.create,WX=kv.create,qX=Uh.create,GX=Vh.create,ZX=lp.create,KX=du.create,QX=Ga.create,JX=Mv.create,YX=vu.create,XX=to.create,eee=to.strictCreate,tee=Hh.create,nee=Hx.create,ree=Wh.create,see=ac.create,iee=qP.create,oee=Ov.create,aee=Av.create,lee=zd.create,cee=qh.create,uee=Gh.create,dee=Am.create,pee=Zh.create,fee=cp.create,eO=ko.create,hee=Zo.create,mee=lc.create,gee=ko.createWithPreprocess,yee=R2.create,vee=()=>QP().optional(),xee=()=>JP().optional(),bee=()=>YP().optional(),See={string:(t=>ap.create({...t,coerce:!0})),number:(t=>$h.create({...t,coerce:!0})),boolean:(t=>Fh.create({...t,coerce:!0})),bigint:(t=>Nh.create({...t,coerce:!0})),date:(t=>Bh.create({...t,coerce:!0}))},Cee=Lt;var Tr=Object.freeze({__proto__:null,defaultErrorMap:op,setErrorMap:CX,getErrorMap:Dv,makeIssue:Ev,EMPTY_PATH:wX,addIssueToContext:ot,ParseStatus:ni,INVALID:Lt,DIRTY:Dd,OK:zs,isAborted:_C,isDirty:IC,isValid:Lh,isAsync:zh,get util(){return xn},get objectUtil(){return AC},ZodParsedType:pt,getParsedType:Ml,ZodType:nn,datetimeRegex:VP,ZodString:ap,ZodNumber:$h,ZodBigInt:Nh,ZodBoolean:Fh,ZodDate:Bh,ZodSymbol:kv,ZodUndefined:Uh,ZodNull:Vh,ZodAny:lp,ZodUnknown:du,ZodNever:Ga,ZodVoid:Mv,ZodArray:vu,ZodObject:to,ZodUnion:Hh,ZodDiscriminatedUnion:Hx,ZodIntersection:Wh,ZodTuple:ac,ZodRecord:qP,ZodMap:Ov,ZodSet:Av,ZodFunction:zd,ZodLazy:qh,ZodLiteral:Gh,ZodEnum:Am,ZodNativeEnum:Zh,ZodPromise:cp,ZodEffects:ko,ZodTransformer:ko,ZodOptional:Zo,ZodNullable:lc,ZodDefault:Kh,ZodCatch:Qh,ZodNaN:_v,BRAND:NX,ZodBranded:E2,ZodPipeline:R2,ZodReadonly:Jh,custom:KP,Schema:nn,ZodSchema:nn,late:FX,get ZodFirstPartyTypeKind(){return Pt},coerce:See,any:ZX,array:YX,bigint:VX,boolean:YP,date:HX,discriminatedUnion:nee,effect:eO,enum:dee,function:lee,instanceof:BX,intersection:ree,lazy:cee,literal:uee,map:oee,nan:UX,nativeEnum:pee,never:QX,null:GX,nullable:mee,number:JP,object:XX,oboolean:bee,onumber:xee,optional:hee,ostring:vee,pipeline:yee,preprocess:gee,promise:fee,record:iee,set:aee,strictObject:eee,string:QP,symbol:WX,transformer:eO,tuple:see,undefined:qX,union:tee,unknown:KX,void:JX,NEVER:Cee,ZodIssueCode:He,quotelessJson:SX,ZodError:To});function no({items:t,dropdown:e}){var f;const[n,r]=b.useState(null),s=!!n,i=m=>{r(m.currentTarget)},l=()=>{r(null)},u=m=>{e==null||e.onChange(m),l()},p=(f=e==null?void 0:e.options.find(m=>m.value===e.value))==null?void 0:f.label;return a.jsxs(a.Fragment,{children:[a.jsxs(k7,{"data-component-name":"cmp:Breadcrumb",separator:a.jsx(lY,{fontSize:"small"}),sx:{mb:2},children:[a.jsx(B,{component:gs,to:"/",sx:{display:"flex",alignItems:"center",textDecoration:"none",color:"text.secondary","&:hover":{color:"primary.main"}},children:a.jsx(SP,{fontSize:"small"})}),t.map(m=>m.to?a.jsx(B,{component:gs,to:m.to,sx:{textDecoration:"none",color:"text.secondary","&:hover":{color:"primary.main",textDecoration:"underline"}},children:m.label},m.label):a.jsx(G,{color:"text.secondary",children:m.label},m.label)),e&&a.jsx(pe,{"data-component-name":"cmp:BreadcrumbDropdown",onClick:i,endIcon:a.jsx(pJ,{}),sx:{textTransform:"none",color:"text.secondary",minWidth:"auto",p:0,"&:hover":{bgcolor:"transparent",color:"primary.main"}},children:p})]}),e&&a.jsx(Cp,{anchorEl:n,open:s,onClose:l,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},children:e.options.map(m=>a.jsx(nt,{selected:m.value===e.value,onClick:()=>u(m.value),children:m.label},m.value))})]})}function la({title:t,titleNode:e,titleSx:n,actions:r,mb:s=3}){return a.jsxs(B,{"data-component-name":"cmp:PageHeader",sx:{display:"flex",flexDirection:{xs:"column",sm:"row"},justifyContent:"space-between",alignItems:{xs:"stretch",sm:"center"},gap:2,mb:s},children:[e??a.jsx(G,{variant:"h5",component:"h1",sx:n,children:t}),r&&a.jsx(B,{sx:{display:"flex",gap:2,flexWrap:"wrap",justifyContent:"flex-end",alignItems:"center"},children:r})]})}function Dp({title:t,icon:e,onClose:n,actions:r,componentName:s}){return a.jsxs(B,{"data-component-name":s,sx:{display:"flex",alignItems:"center",gap:1,p:2,borderBottom:1,borderColor:"divider",flexShrink:0},children:[a.jsx(ft,{onClick:n,edge:"start",size:"small",children:a.jsx(xP,{})}),e,a.jsx(G,{variant:"h6",sx:{flex:1},children:t}),r]})}function wee(){return Fs(t=>({dialogMode:null,editingUser:null,deleteDialogOpen:!1,deleteTargetUser:null,formData:{githubUsername:"",displayName:"",selectedTemplate:"viewer",permissions:Ih("viewer"),allowPersonalBranch:!0},validationErrors:[],isSaving:!1,isDeleting:!1,snackbar:{open:!1,message:"",severity:"success"},isFormDirty:!1,closeConfirmDialogOpen:!1,setDialogMode:e=>t({dialogMode:e}),setEditingUser:e=>t({editingUser:e}),setDeleteDialogOpen:e=>t({deleteDialogOpen:e}),setDeleteTargetUser:e=>t({deleteTargetUser:e}),setFormData:e=>t(n=>({formData:{...n.formData,...e}})),setValidationErrors:e=>t({validationErrors:e}),setSaving:e=>t({isSaving:e}),setDeleting:e=>t({isDeleting:e}),setSnackbar:e=>t({snackbar:e}),setFormDirty:e=>t({isFormDirty:e}),setCloseConfirmDialogOpen:e=>t({closeConfirmDialogOpen:e})}))}class jee{constructor(){St(this,"store",wee());St(this,"cachedState",null);St(this,"cachedStoreState",null)}getState(){const e=this.store.getState();return this.cachedStoreState===e&&this.cachedState!==null?this.cachedState:(this.cachedStoreState=e,this.cachedState={dialogMode:e.dialogMode,editingUser:e.editingUser,deleteDialogOpen:e.deleteDialogOpen,deleteTargetUser:e.deleteTargetUser,formData:e.formData,validationErrors:e.validationErrors,isSaving:e.isSaving,isDeleting:e.isDeleting,snackbar:e.snackbar,isFormDirty:e.isFormDirty,closeConfirmDialogOpen:e.closeConfirmDialogOpen},this.cachedState)}openAddDialog(){this.store.getState().setFormData({githubUsername:"",displayName:"",selectedTemplate:"viewer",permissions:Ih("viewer"),allowPersonalBranch:!0}),this.store.getState().setValidationErrors([]),this.store.getState().setFormDirty(!1),this.store.getState().setDialogMode("add")}openEditDialog(e){this.store.getState().setEditingUser(e);const n=g2(e),r=e.permissions??Ih("viewer");this.store.getState().setFormData({githubUsername:e.githubUsername,displayName:e.displayName,selectedTemplate:n,permissions:r,allowPersonalBranch:e.allowPersonalBranch!==!1}),this.store.getState().setValidationErrors([]),this.store.getState().setFormDirty(!1),this.store.getState().setDialogMode("edit")}closeDialog(){this.store.getState().setDialogMode(null),this.store.getState().setEditingUser(null),this.store.getState().setValidationErrors([]),this.store.getState().setFormDirty(!1),this.store.getState().setCloseConfirmDialogOpen(!1)}openDeleteDialog(e){this.store.getState().setDeleteTargetUser(e),this.store.getState().setDeleteDialogOpen(!0)}closeDeleteDialog(){this.store.getState().setDeleteDialogOpen(!1),this.store.getState().setDeleteTargetUser(null)}setFormField(e,n){this.store.getState().setFormData({[e]:n}),this.store.getState().setFormDirty(!0)}setPermission(e,n){const r=this.store.getState().formData.permissions;this.store.getState().setFormData({permissions:{...r,[e]:n}}),this.store.getState().setFormDirty(!0)}setValidationErrors(e){this.store.getState().setValidationErrors(e)}clearValidationErrors(){this.store.getState().setValidationErrors([])}setSaving(e){this.store.getState().setSaving(e)}setDeleting(e){this.store.getState().setDeleting(e)}showSnackbar(e,n){this.store.getState().setSnackbar({open:!0,message:e,severity:n})}hideSnackbar(){this.store.getState().setSnackbar({open:!1,message:"",severity:"success"})}setFormDirty(e){this.store.getState().setFormDirty(e)}openCloseConfirmDialog(){this.store.getState().setCloseConfirmDialogOpen(!0)}closeCloseConfirmDialog(){this.store.getState().setCloseConfirmDialogOpen(!1)}subscribe(e){return this.store.subscribe(e)}}const k2=new jee;class Tee{constructor(e){this.deps=e}getState(){const{repo:e,presenter:n,currentUsername:r}=this.deps,s=n.getState();return{users:e.getUsers(),isLoading:e.isLoading(),error:e.getError(),currentUsername:r,...s}}openAddDialog(){this.deps.presenter.openAddDialog()}openEditDialog(e){this.deps.presenter.openEditDialog(e)}closeDialog(){this.deps.presenter.closeDialog()}openDeleteDialog(e){this.deps.presenter.openDeleteDialog(e)}closeDeleteDialog(){this.deps.presenter.closeDeleteDialog()}setFormField(e,n){this.deps.presenter.setFormField(e,n)}setTemplate(e){const n=Ih(e);this.deps.presenter.setFormField("selectedTemplate",e),this.deps.presenter.setFormField("permissions",n)}setPermission(e,n){this.deps.presenter.setPermission(e,n);const s={...this.deps.presenter.getState().formData.permissions,[e]:n},i=_h(s);this.deps.presenter.setFormField("selectedTemplate",i)}async addUser(){const{repo:e,presenter:n}=this.deps,r=n.getState(),s=e.getUsers(),i={githubUsername:r.formData.githubUsername.trim(),displayName:r.formData.displayName.trim(),permissions:r.formData.permissions,allowPersonalBranch:r.formData.allowPersonalBranch},l=OM(i,s);if(l.length>0)return n.setValidationErrors(l),!1;n.setSaving(!0);try{const u=[...s,i];return await e.saveUsers(u),n.closeDialog(),n.showSnackbar("ユーザーを追加しました","success"),oe.info("UserListUseCase.addUser",{githubUsername:i.githubUsername}),!0}catch(u){return oe.error("UserListUseCase.addUser failed",{error:u}),n.showSnackbar("ユーザーの追加に失敗しました","error"),!1}finally{n.setSaving(!1)}}async updateUser(){const{repo:e,presenter:n}=this.deps,r=n.getState(),s=e.getUsers(),i=r.editingUser;if(!i)return!1;const l={githubUsername:r.formData.githubUsername.trim(),displayName:r.formData.displayName.trim(),permissions:r.formData.permissions,allowPersonalBranch:r.formData.allowPersonalBranch,isOwner:i.isOwner},u=OM(l,s,i.githubUsername);if(u.length>0)return n.setValidationErrors(u),!1;n.setSaving(!0);try{const p=s.map(f=>f.githubUsername===i.githubUsername?l:f);return await e.saveUsers(p),n.closeDialog(),n.showSnackbar("ユーザーを更新しました","success"),oe.info("UserListUseCase.updateUser",{githubUsername:l.githubUsername}),!0}catch(p){return oe.error("UserListUseCase.updateUser failed",{error:p}),n.showSnackbar("ユーザーの更新に失敗しました","error"),!1}finally{n.setSaving(!1)}}async deleteUser(){const{repo:e,presenter:n,currentUsername:r}=this.deps,s=n.getState(),i=e.getUsers(),l=s.deleteTargetUser;if(!l)return!1;if(!AM(l.githubUsername,r))return n.showSnackbar("自分自身は削除できません","error"),n.closeDeleteDialog(),!1;n.setDeleting(!0);try{const u=i.filter(p=>p.githubUsername!==l.githubUsername);return await e.saveUsers(u),n.closeDeleteDialog(),n.showSnackbar("ユーザーを削除しました","success"),oe.info("UserListUseCase.deleteUser",{githubUsername:l.githubUsername}),!0}catch(u){return oe.error("UserListUseCase.deleteUser failed",{error:u}),n.showSnackbar("ユーザーの削除に失敗しました","error"),!1}finally{n.setDeleting(!1)}}hideSnackbar(){this.deps.presenter.hideSnackbar()}getRoleTemplateLabel(e){const n=g2(e);return Tv(n)}canDelete(e){return AM(e.githubUsername,this.deps.currentUsername)}requestCloseDialog(){const{presenter:e}=this.deps;e.getState().isFormDirty?e.openCloseConfirmDialog():e.closeDialog()}cancelCloseDialog(){this.deps.presenter.closeCloseConfirmDialog()}discardAndCloseDialog(){this.deps.presenter.closeDialog()}}const Dee=t=>k2.subscribe(t),tO=()=>k2.getState(),nO="develop";function Eee(){const{authUseCase:t}=rr(),{token:e,githubUser:n,currentUser:r}=t.getState(),s=ys();b.useSyncExternalStore(Dee,tO,tO);const i=new uu({adminData:jn(uu.AdminDataQueryParams(e,nO))},Pn(uu.SaveAdminDataMutationParams(s,e,nO)));return{userListUseCase:new Tee({repo:i,presenter:k2,currentUsername:(n==null?void 0:n.login)??"",currentUser:r})}}const Ree=Tr.object({action:Tr.enum(["add","edit"]).optional(),user:Tr.string().optional()}),kee=Ss("/users/")({component:Mee,validateSearch:Ree});function Mee(){const{authUseCase:t}=rr(),{currentUser:e}=t.getState(),n=ur(),r=ws(e,"canViewUsers"),s=ws(e,"canEditUsers");return b.useEffect(()=>{e&&!r&&n({to:"/"})},[e,r,n]),r?a.jsx(Oee,{canEdit:s}):null}function Oee({canEdit:t}){const{userListUseCase:e}=Eee(),{simulationUseCase:n}=D2(),r=e.getState(),s=vr(),i=aa(s.breakpoints.down("sm")),l=ur(),u=Di({from:"/users/"}),{users:p,isLoading:f,error:m,dialogMode:g,formData:y,validationErrors:v,isSaving:C,deleteDialogOpen:S,deleteTargetUser:j,isDeleting:D,snackbar:M,currentUsername:T,editingUser:E,isFormDirty:k,closeConfirmDialogOpen:A}=r,O=[...p].sort((z,N)=>z.isOwner&&!N.isOwner?-1:!z.isOwner&&N.isOwner?1:z.githubUsername.localeCompare(N.githubUsername));b.useEffect(()=>{if(!f){if(!t){u.action&&l({to:"/users",search:{}});return}if(u.action==="add"&&g!=="add")e.openAddDialog();else if(u.action==="edit"&&u.user&&g!=="edit"){const z=O.find(N=>N.githubUsername===u.user);z&&e.openEditDialog(z)}else!u.action&&g!==null&&e.closeDialog()}},[u.action,u.user,f,O,g,e,t,l]);const I=()=>{l({to:"/users",search:{action:"add"}})},$=z=>{l({to:"/users",search:{action:"edit",user:z.githubUsername}})},R=()=>{k?e.requestCloseDialog():l({to:"/users",search:{}})},P=()=>{e.discardAndCloseDialog(),l({to:"/users",search:{}})};return f?a.jsx(B,{"data-component-name":"cmp:UserListPageLoading",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(ut,{})}):m?a.jsx(B,{"data-component-name":"cmp:UserListPageError",sx:{flex:1,overflow:"auto"},children:a.jsx(ji,{maxWidth:"lg",sx:{py:3},children:a.jsxs(zt,{severity:"error",children:["エラー: ",m.message]})})}):a.jsxs(B,{"data-component-name":"cmp:UserListPage",sx:{flex:1,overflow:"auto"},children:[a.jsxs(ji,{maxWidth:"lg",sx:{py:3},children:[a.jsx(no,{items:[{label:"ユーザー管理"}]}),a.jsx(la,{title:"ユーザー管理",actions:t&&a.jsx(pe,{variant:"contained",startIcon:a.jsx(Qn,{}),onClick:I,children:"ユーザー追加"})}),a.jsxs(zt,{severity:"info",sx:{mb:3},children:["ここに追加するユーザーは",a.jsxs(Ox,{href:`https://github.com/${Qr()}`,target:"_blank",rel:"noopener noreferrer",children:["@",Qr()]}),"で、別途招待をする必要があります。"]}),O.length===0?a.jsx(zt,{severity:"info",children:"ユーザーが登録されていません"}):i?a.jsx(_ee,{users:O,currentUsername:T,userListUseCase:e,onEdit:$,canEdit:t}):a.jsx(Aee,{users:O,currentUsername:T,userListUseCase:e,onEdit:$,canEdit:t})]}),a.jsx(Iee,{open:g!==null,mode:g,formData:y,validationErrors:v,isSaving:C,isOwner:(E==null?void 0:E.isOwner)===!0,isSelf:(E==null?void 0:E.githubUsername)===T,simulationUseCase:n,onClose:R,onSave:async()=>{(g==="add"?await e.addUser():await e.updateUser())&&l({to:"/users",search:{}})},onFieldChange:(z,N)=>e.setFormField(z,N),onTemplateChange:z=>e.setTemplate(z),onPermissionChange:(z,N)=>e.setPermission(z,N)}),a.jsxs(Qt,{"data-component-name":"cmp:CloseConfirmDialog",open:A,onClose:()=>e.cancelCloseDialog(),children:[a.jsx(Yt,{children:"変更を破棄しますか?"}),a.jsx(Jt,{children:a.jsx(G,{children:"保存されていない変更があります。変更を破棄してもよろしいですか?"})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>e.cancelCloseDialog(),children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:P,children:"破棄"})]})]}),a.jsxs(Qt,{"data-component-name":"cmp:DeleteUserDialog",open:S,onClose:()=>e.closeDeleteDialog(),children:[a.jsx(Yt,{children:"ユーザーの削除"}),a.jsxs(Jt,{children:[a.jsxs(G,{children:[j==null?void 0:j.displayName,"(",j==null?void 0:j.githubUsername,")を削除しますか?"]}),a.jsx(G,{variant:"body2",color:"text.secondary",mt:1,children:"この操作は取り消せません。"})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>e.closeDeleteDialog(),children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:()=>e.deleteUser(),disabled:D,children:D?a.jsx(ut,{size:24}):"削除"})]})]}),a.jsx(ea,{open:M.open,autoHideDuration:4e3,onClose:()=>e.hideSnackbar(),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:()=>e.hideSnackbar(),severity:M.severity,sx:{width:"100%"},children:M.message})})]})}function Aee({users:t,currentUsername:e,userListUseCase:n,onEdit:r,canEdit:s}){return a.jsx($t,{"data-component-name":"cmp:UserTable",children:a.jsxs(wp,{children:[a.jsx(jm,{children:a.jsxs(eo,{children:[a.jsx(Kt,{children:"GitHub ユーザー名"}),a.jsx(Kt,{children:"表示名"}),a.jsx(Kt,{children:"ロール"}),a.jsx(Kt,{children:"個人ブランチ"}),s&&a.jsx(Kt,{width:"120px",children:"操作"})]})}),a.jsx(jp,{children:t.map(i=>a.jsxs(eo,{children:[a.jsxs(Kt,{children:[i.githubUsername,i.githubUsername===e&&a.jsx(Ht,{label:"自分",size:"small",sx:{ml:1}})]}),a.jsx(Kt,{children:i.displayName}),a.jsx(Kt,{children:a.jsx(XP,{user:i})}),a.jsx(Kt,{children:i.allowPersonalBranch!==!1?a.jsx(Ht,{label:"許可",color:"success",size:"small"}):a.jsx(Ht,{label:"不許可",size:"small"})}),s&&a.jsxs(Kt,{children:[a.jsx(ft,{size:"small",onClick:()=>r(i),title:"編集",children:a.jsx(Ri,{})}),a.jsx(ft,{size:"small",onClick:()=>n.openDeleteDialog(i),disabled:!n.canDelete(i),title:n.canDelete(i)?"削除":"自分自身は削除できません",children:a.jsx(zn,{})})]})]},i.githubUsername))})]})})}function _ee({users:t,currentUsername:e,userListUseCase:n,onEdit:r,canEdit:s}){return a.jsx(Ro,{"data-component-name":"cmp:UserCardList",spacing:2,children:t.map(i=>a.jsxs(Su,{"data-component-name":"cmp:UserCard",children:[a.jsxs(Sp,{sx:{pb:1},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[a.jsx(G,{variant:"subtitle1",fontWeight:"bold",children:i.displayName}),i.githubUsername===e&&a.jsx(Ht,{label:"自分",size:"small"})]}),a.jsxs(G,{variant:"body2",color:"text.secondary",sx:{mb:1},children:["@",i.githubUsername]}),a.jsxs(B,{sx:{display:"flex",gap:1,flexWrap:"wrap"},children:[a.jsx(XP,{user:i}),i.allowPersonalBranch!==!1?a.jsx(Ht,{label:"個人ブランチ許可",color:"success",size:"small"}):a.jsx(Ht,{label:"個人ブランチ不許可",size:"small"})]})]}),s&&a.jsxs(s2,{children:[a.jsx(pe,{size:"small",startIcon:a.jsx(Ri,{}),onClick:()=>r(i),children:"編集"}),a.jsx(pe,{size:"small",color:"error",startIcon:a.jsx(zn,{}),onClick:()=>n.openDeleteDialog(i),disabled:!n.canDelete(i),children:"削除"})]})]},i.githubUsername))})}function XP({user:t}){const e=g2(t),n=()=>{switch(e){case"owner":return"error";case"admin":return"error";case"developer":return"warning";case"editor":return"primary";case"viewer":return"default";case"custom":default:return"success"}},r=Tv(e);return a.jsx(Ht,{label:r,color:n(),size:"small"})}function Iee({open:t,mode:e,formData:n,validationErrors:r,isSaving:s,isOwner:i,isSelf:l,simulationUseCase:u,onClose:p,onSave:f,onFieldChange:m,onTemplateChange:g,onPermissionChange:y}){const v=j=>{var D;return(D=r.find(M=>M.field===j))==null?void 0:D.message},C=()=>{u.startSimulation(n.permissions,n.selectedTemplate,n.displayName,n.githubUsername),p(),setTimeout(()=>{const j=document.querySelector('[data-testid="avatar-menu-button"]');j==null||j.click()},100)},S=e==="edit"&&!l;return a.jsxs(Cu,{anchor:"right",open:t,onClose:p,"data-component-name":"cmp:UserEditDrawer",PaperProps:{sx:{width:{xs:"100vw",sm:480},maxWidth:"100vw",display:"flex",flexDirection:"column"}},children:[a.jsx(Dp,{title:e==="add"?"ユーザー追加":"ユーザー編集",icon:a.jsx(Mm,{color:"action"}),onClose:p,actions:a.jsxs(B,{sx:{display:"flex",gap:1},children:[S&&a.jsx(pe,{variant:"outlined",color:"info",onClick:C,size:"small",startIcon:a.jsx(_P,{}),children:"UI再現"}),a.jsx(pe,{variant:"contained",onClick:f,disabled:s,size:"small",children:s?a.jsx(ut,{size:20}):"保存"})]}),componentName:"cmp:UserEditDrawerHeader"}),a.jsxs(B,{"data-component-name":"cmp:UserEditDrawerContent",sx:{flex:1,overflow:"auto",p:2,display:"flex",flexDirection:"column",gap:2},children:[a.jsx(Xe,{label:"GitHub ユーザー名",value:n.githubUsername,onChange:j=>m("githubUsername",j.target.value),error:!!v("githubUsername"),helperText:v("githubUsername"),disabled:e==="edit",fullWidth:!0,required:!0}),a.jsx(Xe,{label:"表示名",value:n.displayName,onChange:j=>m("displayName",j.target.value),error:!!v("displayName"),helperText:v("displayName"),fullWidth:!0,required:!0}),a.jsxs(_n,{fullWidth:!0,error:!!v("selectedTemplate"),disabled:i,children:[a.jsx(nr,{required:!0,children:"ロール"}),a.jsxs(wn,{value:n.selectedTemplate,label:"ロール",onChange:j=>g(j.target.value),children:[i&&a.jsx(nt,{value:"owner",children:"所有者"}),a.jsx(nt,{value:"admin",children:"管理者"}),a.jsx(nt,{value:"developer",children:"開発者"}),a.jsx(nt,{value:"editor",children:"編集者"}),a.jsx(nt,{value:"viewer",children:"閲覧者"}),a.jsx(nt,{value:"custom",children:"カスタム"})]}),i&&a.jsx(Dh,{children:"所有者のロールは変更できません"}),v("selectedTemplate")&&a.jsx(Dh,{children:v("selectedTemplate")})]}),a.jsx(Pee,{permissions:i?Cv:n.permissions,onPermissionChange:y,disabled:i}),a.jsx(_r,{control:a.jsx(Ax,{checked:n.allowPersonalBranch,onChange:j=>m("allowPersonalBranch",j.target.checked)}),label:"個人ブランチの使用を許可"})]})]})}function Pee({permissions:t,onPermissionChange:e,disabled:n}){const r=(s,i)=>{if(e(s,i),i){const l=Sv.find(u=>u.edit===s);l&&e(l.view,!0)}if(!i){const l=Sv.find(u=>u.view===s);l&&e(l.edit,!1)}};return a.jsx(B,{"data-component-name":"cmp:PermissionEditor",sx:{px:2},children:a.jsx(Ro,{spacing:2,children:Object.entries(uP).map(([s,i])=>a.jsxs(B,{children:[a.jsx(G,{variant:"subtitle2",color:"text.secondary",sx:{mb:.5},children:i.label}),a.jsx(B,{sx:{display:"flex",flexDirection:"column",ml:2,gap:.5},children:i.pairs.map(l=>a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(G,{variant:"body2",sx:{minWidth:100},children:dP[l.view]}),a.jsx(_r,{control:a.jsx(es,{checked:t[l.view],onChange:u=>r(l.view,u.target.checked),size:"small",disabled:n}),label:"閲覧",sx:{mr:0}}),a.jsx(_r,{control:a.jsx(es,{checked:t[l.edit],onChange:u=>r(l.edit,u.target.checked),size:"small",disabled:n}),label:"編集",sx:{mr:0}})]},l.view))})]},s))})})}function M2(t){return[".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico"].some(n=>t.toLowerCase().endsWith(n))}function Lee(t){const e=zee(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon"}[e]??"application/octet-stream"}function O2(t){const e=[".html",".htm",".css",".js",".ts",".jsx",".tsx",".json",".xml",".svg",".md",".txt",".yaml",".yml",".toml",".ini",".conf",".sh",".bat",".ps1",".gitignore",".gitkeep",".env"],n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function zee(t){const e=t.lastIndexOf(".");return e>0?t.slice(e):""}class Cl{constructor(e,n,r,s,i,l,u,p,f,m,g){this.token=e,this.basePath=n,this.branch=r,this.rootQuery=s,this.fileQuery=i,this.saveMutation=l,this.deleteMutation=u,this.deleteDirectoryMutation=p,this.uploadMutation=f,this.createFolderMutation=m,this.queryClient=g}static RootEntriesQueryParams(e,n,r){return{queryKey:["fileManager","root",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return(await new At(e).listDirectoryEntries(n,r)).map(l=>({name:l.name,path:`${n}/${l.name}`,type:l.type==="tree"?"directory":"file"}))},enabled:!!e}}static FileContentQueryParams(e,n,r){return{queryKey:["fileManager","file",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");if(!n)return null;const s=new At(e),i=n.split("/").pop()??"";return M2(i)?s.fetchFileBase64OrNull(n,r):s.fetchFileOrNull(n,r)},enabled:!!e&&!!n}}static SaveFileMutationParams(e,n,r){return{mutationFn:async({path:s,content:i})=>{if(!n)throw new Error("Not authenticated");const l=new At(n),u=s.split("/").pop()??"file";await l.commitFiles(`テンプレート更新: ${u}`,[{path:s,content:i}],r)},onSuccess:(s,i)=>{e.invalidateQueries({queryKey:["fileManager","file",i.path,r]})}}}static DeleteFileMutationParams(e,n,r,s){return{mutationFn:async i=>{if(!n)throw new Error("Not authenticated");const l=new At(n),u=i.split("/").pop()??"file";await l.commitFiles(`テンプレート削除: ${u}`,[{path:i,content:"",delete:!0}],s)},onSuccess:()=>{e.invalidateQueries({queryKey:["fileManager","root",r,s]}),e.invalidateQueries({queryKey:["fileManager","directory"]})}}}static DeleteDirectoryMutationParams(e,n,r,s){return{mutationFn:async i=>{if(!n)throw new Error("Not authenticated");const l=new At(n),u=await e5(l,i,s);if(u.length===0)return;const p=i.split("/").pop()??"folder";await l.commitFiles(`テンプレートフォルダ削除: ${p}`,u.map(f=>({path:f,content:"",delete:!0})),s)},onSuccess:()=>{e.invalidateQueries({queryKey:["fileManager","root",r,s]}),e.invalidateQueries({queryKey:["fileManager","directory"]})}}}static UploadFileMutationParams(e,n,r,s){return{mutationFn:async({targetDir:i,fileName:l,content:u})=>{if(!n)throw new Error("Not authenticated");const p=new At(n),f=`${i}/${l}`;await p.commitFiles(`テンプレートアップロード: ${l}`,[{path:f,content:u}],s)},onSuccess:()=>{e.invalidateQueries({queryKey:["fileManager","root",r,s]}),e.invalidateQueries({queryKey:["fileManager","directory"]})}}}static CreateFolderMutationParams(e,n,r,s){return{mutationFn:async({targetDir:i,folderName:l})=>{if(!n)throw new Error("Not authenticated");const u=new At(n),p=`${i}/${l}/.gitkeep`;await u.commitFiles(`テンプレートフォルダ作成: ${l}`,[{path:p,content:""}],s)},onSuccess:()=>{e.invalidateQueries({queryKey:["fileManager","root",r,s]}),e.invalidateQueries({queryKey:["fileManager","directory"]})}}}getRootEntries(){return this.rootQuery.data??[]}isRootLoading(){return this.rootQuery.isLoading}getRootError(){return this.rootQuery.error??null}getFileContent(){return this.fileQuery.data??null}isFileLoading(){return this.fileQuery.isLoading}getFileError(){return this.fileQuery.error??null}async fetchDirectoryEntries(e){if(!this.token)throw new Error("Not authenticated");return(await new At(this.token).listDirectoryEntries(e,this.branch)).map(s=>({name:s.name,path:`${e}/${s.name}`,type:s.type==="tree"?"directory":"file"}))}async saveFile(e,n){await this.saveMutation.mutateAsync({path:e,content:n})}async deleteFile(e){await this.deleteMutation.mutateAsync(e)}async deleteDirectory(e){await this.deleteDirectoryMutation.mutateAsync(e)}async uploadFile(e,n,r){await this.uploadMutation.mutateAsync({targetDir:e,fileName:n,content:r})}async createFolder(e,n){await this.createFolderMutation.mutateAsync({targetDir:e,folderName:n})}isSaving(){return this.saveMutation.isPending}isDeleting(){return this.deleteMutation.isPending||this.deleteDirectoryMutation.isPending}invalidateRoot(){this.queryClient.invalidateQueries({queryKey:["fileManager","root",this.basePath,this.branch]})}invalidateFile(){this.queryClient.invalidateQueries({queryKey:["fileManager","file"]})}invalidateDirectory(e){this.queryClient.invalidateQueries({queryKey:["fileManager","directory",e,this.branch]})}}async function e5(t,e,n){const r=await t.listDirectoryEntries(e,n),s=[];for(const i of r){const l=`${e}/${i.name}`;if(i.type==="blob")s.push(l);else{const u=await e5(t,l,n);s.push(...u)}}return s}function $ee(){return Fs((t,e)=>({targetId:"templates",expandedPaths:[],directoryContentsEntries:[],selectedPath:null,editContent:"",originalContent:"",deleteDialogOpen:!1,deleteTarget:null,uploadDialogOpen:!1,uploadTargetDir:"",createFolderDialogOpen:!1,createFolderTargetDir:"",isUploading:!1,uploadError:null,isSaving:!1,saveError:null,setTargetId:n=>t({targetId:n,expandedPaths:[],directoryContentsEntries:[],selectedPath:null,editContent:"",originalContent:""}),toggleExpand:n=>{const r=e().expandedPaths,s=r.includes(n);t({expandedPaths:s?r.filter(i=>i!==n):[...r,n]})},setExpandedPaths:n=>t({expandedPaths:n}),setDirectoryContents:(n,r)=>{const s=e().directoryContentsEntries,i=s.findIndex(([l])=>l===n);if(i>=0){const l=[...s];l[i]=[n,r],t({directoryContentsEntries:l})}else t({directoryContentsEntries:[...s,[n,r]]})},clearDirectoryContents:()=>t({directoryContentsEntries:[]}),removeDirectoryContents:n=>{const r=e().directoryContentsEntries;t({directoryContentsEntries:r.filter(([s])=>s!==n)})},setSelectedPath:n=>t({selectedPath:n}),setEditContent:n=>t({editContent:n}),setOriginalContent:n=>t({originalContent:n}),setDeleteDialogOpen:n=>t({deleteDialogOpen:n}),setDeleteTarget:n=>t({deleteTarget:n}),setUploadDialogOpen:n=>t({uploadDialogOpen:n}),setUploadTargetDir:n=>t({uploadTargetDir:n}),setCreateFolderDialogOpen:n=>t({createFolderDialogOpen:n}),setCreateFolderTargetDir:n=>t({createFolderTargetDir:n}),setUploading:n=>t({isUploading:n}),setUploadError:n=>t({uploadError:n}),setSaving:n=>t({isSaving:n}),setSaveError:n=>t({saveError:n})}))}class Nee{constructor(){St(this,"store",$ee());St(this,"cachedStoreState",null);St(this,"cachedState",null)}getState(){const e=this.store.getState();return this.cachedStoreState===e&&this.cachedState!==null?this.cachedState:(this.cachedStoreState=e,this.cachedState={targetId:e.targetId,expandedPaths:new Set(e.expandedPaths),directoryContents:new Map(e.directoryContentsEntries),selectedPath:e.selectedPath,editContent:e.editContent,originalContent:e.originalContent,deleteDialogOpen:e.deleteDialogOpen,deleteTarget:e.deleteTarget,uploadDialogOpen:e.uploadDialogOpen,uploadTargetDir:e.uploadTargetDir,createFolderDialogOpen:e.createFolderDialogOpen,createFolderTargetDir:e.createFolderTargetDir,isUploading:e.isUploading,uploadError:e.uploadError,isSaving:e.isSaving,saveError:e.saveError},this.cachedState)}setTargetId(e){this.store.getState().setTargetId(e)}toggleExpand(e){this.store.getState().toggleExpand(e)}setExpandedPaths(e){this.store.getState().setExpandedPaths([...e])}setDirectoryContents(e,n){this.store.getState().setDirectoryContents(e,n)}clearDirectoryContents(){this.store.getState().clearDirectoryContents()}removeDirectoryContents(e){this.store.getState().removeDirectoryContents(e)}setSelectedPath(e){this.store.getState().setSelectedPath(e)}setEditContent(e){this.store.getState().setEditContent(e)}setOriginalContent(e){this.store.getState().setOriginalContent(e)}openDeleteDialog(e,n){this.store.getState().setDeleteTarget({path:e,type:n}),this.store.getState().setDeleteDialogOpen(!0)}closeDeleteDialog(){this.store.getState().setDeleteDialogOpen(!1),this.store.getState().setDeleteTarget(null)}openUploadDialog(e){this.store.getState().setUploadTargetDir(e),this.store.getState().setUploadDialogOpen(!0)}closeUploadDialog(){this.store.getState().setUploadDialogOpen(!1),this.store.getState().setUploadTargetDir(""),this.store.getState().setUploadError(null)}openCreateFolderDialog(e){this.store.getState().setCreateFolderTargetDir(e),this.store.getState().setCreateFolderDialogOpen(!0)}closeCreateFolderDialog(){this.store.getState().setCreateFolderDialogOpen(!1),this.store.getState().setCreateFolderTargetDir("")}setUploading(e){this.store.getState().setUploading(e)}setUploadError(e){this.store.getState().setUploadError(e)}setSaving(e){this.store.getState().setSaving(e)}setSaveError(e){this.store.getState().setSaveError(e)}subscribe(e){return this.store.subscribe(e)}}const Iv=new Nee;class Fee{constructor(e){this.deps=e}getState(){const e=this.deps.presenter.getState(),n=this.deps.repo.getRootEntries(),r=this.findEntry(e.selectedPath,n,e.directoryContents),s=this.deps.repo.getFileContent(),i=(r==null?void 0:r.type)==="file"&&O2(r.name),l=!this.deps.isAuthInitialized||this.deps.repo.isRootLoading();return{targetId:e.targetId,targets:TC,branch:this.deps.branch,rootEntries:n,isRootLoading:l,rootError:this.deps.repo.getRootError(),expandedPaths:e.expandedPaths,directoryContents:e.directoryContents,selectedPath:e.selectedPath,selectedEntry:r,fileContent:s,isFileLoading:this.deps.repo.isFileLoading(),fileError:this.deps.repo.getFileError(),editContent:e.editContent,originalContent:e.originalContent,isDirty:e.editContent!==e.originalContent,canEdit:i,deleteDialogOpen:e.deleteDialogOpen,deleteTarget:e.deleteTarget,uploadDialogOpen:e.uploadDialogOpen,uploadTargetDir:e.uploadTargetDir,createFolderDialogOpen:e.createFolderDialogOpen,createFolderTargetDir:e.createFolderTargetDir,isUploading:e.isUploading,uploadError:e.uploadError,isSaving:this.deps.repo.isSaving()||e.isSaving,saveError:e.saveError,isDeleting:this.deps.repo.isDeleting(),hasEditPermission:this.deps.hasEditPermission}}changeTarget(e){this.deps.presenter.setTargetId(e),this.deps.presenter.clearDirectoryContents()}async toggleExpand(e){if(this.deps.presenter.getState().expandedPaths.has(e)){this.deps.presenter.toggleExpand(e);return}this.deps.presenter.setDirectoryContents(e,{entries:[],isLoading:!0,error:null}),this.deps.presenter.toggleExpand(e);try{const s=await this.deps.repo.fetchDirectoryEntries(e);this.deps.presenter.setDirectoryContents(e,{entries:s,isLoading:!1,error:null})}catch(s){oe.error("Failed to fetch directory entries",{path:e,error:s}),this.deps.presenter.setDirectoryContents(e,{entries:[],isLoading:!1,error:s})}}selectFile(e){this.getState().isDirty,this.deps.presenter.setSelectedPath(e),this.deps.presenter.setEditContent(""),this.deps.presenter.setOriginalContent(""),this.deps.navigateToFile(e)}clearSelection(){this.deps.presenter.setSelectedPath(null),this.deps.presenter.setEditContent(""),this.deps.presenter.setOriginalContent(""),this.deps.navigateToFile(void 0)}onFileContentLoaded(e){this.deps.presenter.setOriginalContent(e),this.deps.presenter.setEditContent(e)}updateContent(e){this.deps.presenter.setEditContent(e)}async save(){const e=this.getState();if(!(!e.selectedPath||!e.isDirty)){this.deps.presenter.setSaving(!0),this.deps.presenter.setSaveError(null);try{await this.deps.repo.saveFile(e.selectedPath,e.editContent),this.deps.presenter.setOriginalContent(e.editContent),oe.info("File saved",{path:e.selectedPath})}catch(n){oe.error("Failed to save file",{path:e.selectedPath,error:n}),this.deps.presenter.setSaveError(n instanceof Error?n.message:"保存に失敗しました")}finally{this.deps.presenter.setSaving(!1)}}}openDeleteDialog(e,n){this.deps.presenter.openDeleteDialog(e,n)}closeDeleteDialog(){this.deps.presenter.closeDeleteDialog()}async confirmDelete(){const e=this.getState();if(e.deleteTarget)try{if(e.deleteTarget.type==="directory"){await this.deps.repo.deleteDirectory(e.deleteTarget.path);const n=new Set(e.expandedPaths);for(const r of n)r.startsWith(e.deleteTarget.path)&&n.delete(r);this.deps.presenter.setExpandedPaths(n),this.deps.presenter.removeDirectoryContents(e.deleteTarget.path)}else await this.deps.repo.deleteFile(e.deleteTarget.path);e.selectedPath===e.deleteTarget.path&&this.clearSelection(),oe.info("Deleted",{path:e.deleteTarget.path,type:e.deleteTarget.type})}catch(n){throw oe.error("Failed to delete",{...e.deleteTarget,error:n}),n}finally{this.closeDeleteDialog()}}openUploadDialog(e){this.deps.presenter.openUploadDialog(e)}closeUploadDialog(){this.deps.presenter.closeUploadDialog()}async uploadFile(e){const n=this.getState();if(n.uploadTargetDir){this.deps.presenter.setUploading(!0),this.deps.presenter.setUploadError(null);try{const r=await Bee(e);if(await this.deps.repo.uploadFile(n.uploadTargetDir,e.name,r),oe.info("File uploaded",{targetDir:n.uploadTargetDir,fileName:e.name}),n.directoryContents.has(n.uploadTargetDir)){const s=await this.deps.repo.fetchDirectoryEntries(n.uploadTargetDir);this.deps.presenter.setDirectoryContents(n.uploadTargetDir,{entries:s,isLoading:!1,error:null})}this.closeUploadDialog()}catch(r){oe.error("Failed to upload file",{error:r}),this.deps.presenter.setUploadError(r instanceof Error?r.message:"アップロードに失敗しました")}finally{this.deps.presenter.setUploading(!1)}}}openCreateFolderDialog(e){this.deps.presenter.openCreateFolderDialog(e)}closeCreateFolderDialog(){this.deps.presenter.closeCreateFolderDialog()}async createFolder(e){const n=this.getState();if(!(!n.createFolderTargetDir||!e))try{if(await this.deps.repo.createFolder(n.createFolderTargetDir,e),oe.info("Folder created",{targetDir:n.createFolderTargetDir,folderName:e}),n.directoryContents.has(n.createFolderTargetDir)){const r=await this.deps.repo.fetchDirectoryEntries(n.createFolderTargetDir);this.deps.presenter.setDirectoryContents(n.createFolderTargetDir,{entries:r,isLoading:!1,error:null})}this.closeCreateFolderDialog()}catch(r){throw oe.error("Failed to create folder",{error:r}),r}}findEntry(e,n,r){if(!e)return null;for(const s of n)if(s.path===e)return s;for(const s of r.values())for(const i of s.entries)if(i.path===e)return i;return null}}function Bee(t){return new Promise((e,n)=>{const r=new FileReader;r.onload=()=>e(r.result),r.onerror=()=>n(r.error),r.readAsText(t)})}const Uee=t=>Iv.subscribe(t),rO=()=>Iv.getState();function Vee(){const{authUseCase:t}=rr(),{branchUseCase:e}=Ei(),n=t.getState(),{token:r,isInitialized:s,currentUser:i}=n,l=(e==null?void 0:e.getCurrentBranch())??"develop",u=ys(),p=ws(i,"canEditTemplates"),f=Di({from:"/templates/"}),m=ur(),g=P=>{m({to:"/templates",search:P?{file:P}:{},replace:!0})},y=b.useSyncExternalStore(Uee,rO,rO),v=b.useMemo(()=>{const P=TC.find(z=>z.id===y.targetId);return(P==null?void 0:P.path)??TC[0].path},[y.targetId]),C=jn(Cl.RootEntriesQueryParams(r,v,l)),S=jn(Cl.FileContentQueryParams(r,y.selectedPath,l)),j=Pn(Cl.SaveFileMutationParams(u,r,l)),D=Pn(Cl.DeleteFileMutationParams(u,r,v,l)),M=Pn(Cl.DeleteDirectoryMutationParams(u,r,v,l)),T=Pn(Cl.UploadFileMutationParams(u,r,v,l)),E=Pn(Cl.CreateFolderMutationParams(u,r,v,l)),k=new Cl(r,v,l,C,S,j,D,M,T,E,u),A=new Fee({repo:k,presenter:Iv,basePath:v,branch:l,isAuthInitialized:s,navigateToFile:g,hasEditPermission:p}),O=k.getFileContent(),I=b.useRef(null),$=b.useRef(null);b.useEffect(()=>{(y.selectedPath!==$.current||O!==null&&I.current===null)&&O!==null&&A.onFileContentLoaded(O),I.current=O,$.current=y.selectedPath},[O,y.selectedPath,A]);const R=b.useRef(!1);return b.useEffect(()=>{!R.current&&f.file&&!y.selectedPath&&(Iv.setSelectedPath(f.file),R.current=!0)},[f.file,y.selectedPath]),{templateUseCase:A}}function sO({useCase:t,state:e}){return a.jsxs($t,{"data-component-name":"cmp:TemplateTreePanel",sx:{height:"100%",display:"flex",flexDirection:"column"},children:[a.jsxs(B,{"data-component-name":"cmp:TemplateTreeHeader",sx:{p:2,borderBottom:1,borderColor:"divider"},children:[a.jsxs(_n,{fullWidth:!0,size:"small",sx:{mb:1},children:[a.jsx(nr,{children:"対象フォルダ"}),a.jsx(wn,{value:e.targetId,label:"対象フォルダ",onChange:n=>t.changeTarget(n.target.value),children:e.targets.map(n=>a.jsx(nt,{value:n.id,children:a.jsxs(B,{children:[a.jsx(G,{variant:"body1",children:n.label}),a.jsx(G,{variant:"caption",color:"text.secondary",children:n.path})]})},n.id))})]}),e.hasEditPermission&&a.jsxs(B,{sx:{display:"flex",gap:1},children:[a.jsx(Er,{title:"フォルダを作成",children:a.jsx(ft,{size:"small",onClick:()=>{var n;return t.openCreateFolderDialog(((n=e.targets.find(r=>r.id===e.targetId))==null?void 0:n.path)??"")},children:a.jsx(C2,{})})}),a.jsx(Er,{title:"ファイルをアップロード",children:a.jsx(ft,{size:"small",onClick:()=>{var n;return t.openUploadDialog(((n=e.targets.find(r=>r.id===e.targetId))==null?void 0:n.path)??"")},children:a.jsx(Ti,{})})})]})]}),a.jsx(B,{"data-component-name":"cmp:TemplateTreeBody",sx:{flex:1,overflow:"auto",p:1},children:e.isRootLoading?a.jsx(B,{sx:{display:"flex",justifyContent:"center",p:3},children:a.jsx(ut,{size:24})}):e.rootError?a.jsxs(G,{color:"error",sx:{p:2},children:["読み込みエラー: ",e.rootError.message]}):e.rootEntries.length===0?a.jsx(G,{color:"text.secondary",sx:{p:2},children:"ファイルがありません"}):a.jsx(as,{dense:!0,disablePadding:!0,children:e.rootEntries.map(n=>a.jsx(t5,{entry:n,level:0,useCase:t,state:e},n.path))})}),a.jsx(Hee,{useCase:t,state:e}),a.jsx(Wee,{useCase:t,state:e})]})}function t5({entry:t,level:e,useCase:n,state:r}){const s=r.expandedPaths.has(t.path),i=r.selectedPath===t.path,l=t.type==="directory",u=r.directoryContents.get(t.path),[p,f]=b.useState(!1),m=()=>{l?n.toggleExpand(t.path):n.selectFile(t.path)};return a.jsxs(a.Fragment,{children:[a.jsx(Os,{disablePadding:!0,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),secondaryAction:p&&l&&r.hasEditPermission?a.jsxs(B,{sx:{display:"flex",gap:.5},children:[a.jsx(Er,{title:"サブフォルダを作成",children:a.jsx(ft,{size:"small",onClick:g=>{g.stopPropagation(),n.openCreateFolderDialog(t.path)},children:a.jsx(C2,{fontSize:"small"})})}),a.jsx(Er,{title:"ファイルをアップロード",children:a.jsx(ft,{size:"small",onClick:g=>{g.stopPropagation(),n.openUploadDialog(t.path)},children:a.jsx(Ti,{fontSize:"small"})})})]}):void 0,children:a.jsxs(os,{selected:i,onClick:m,sx:{pl:e*2+1},children:[l&&a.jsx(Un,{sx:{minWidth:24},children:s?a.jsx(Wr,{fontSize:"small"}):a.jsx(Jl,{fontSize:"small"})}),a.jsx(Un,{sx:{minWidth:32},children:l?s?a.jsx(FJ,{color:"primary"}):a.jsx(ic,{color:"primary"}):a.jsx(vc,{color:"action"})}),a.jsx(Zn,{primary:t.name,primaryTypographyProps:{noWrap:!0,sx:{fontSize:"0.875rem"}}})]})}),l&&a.jsx(Co,{in:s,timeout:"auto",unmountOnExit:!0,children:u!=null&&u.isLoading?a.jsx(B,{sx:{display:"flex",justifyContent:"center",py:1},children:a.jsx(ut,{size:16})}):u!=null&&u.error?a.jsx(G,{color:"error",sx:{pl:(e+1)*2+1,py:1,fontSize:"0.75rem"},children:"エラー"}):(u==null?void 0:u.entries.length)===0?a.jsx(G,{color:"text.secondary",sx:{pl:(e+1)*2+1,py:1,fontSize:"0.75rem"},children:"(空)"}):a.jsx(as,{dense:!0,disablePadding:!0,children:u==null?void 0:u.entries.map(g=>a.jsx(t5,{entry:g,level:e+1,useCase:n,state:r},g.path))})})]})}function Hee({useCase:t,state:e}){const[n,r]=b.useState(""),[s,i]=b.useState(!1),l=async()=>{if(n.trim()){i(!0);try{await t.createFolder(n.trim()),r("")}finally{i(!1)}}},u=()=>{t.closeCreateFolderDialog(),r("")};return a.jsxs(Qt,{"data-component-name":"cmp:CreateFolderDialog",open:e.createFolderDialogOpen,onClose:u,children:[a.jsx(Yt,{children:"フォルダを作成"}),a.jsxs(Jt,{children:[a.jsxs(G,{variant:"body2",color:"text.secondary",sx:{mb:2},children:["作成先: ",e.createFolderTargetDir]}),a.jsx(Xe,{autoFocus:!0,fullWidth:!0,label:"フォルダ名",value:n,onChange:p=>r(p.target.value),onKeyDown:p=>{p.key==="Enter"&&n.trim()&&l()}})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:u,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:l,disabled:!n.trim()||s,children:s?a.jsx(ut,{size:20}):"作成"})]})]})}function Wee({useCase:t,state:e}){const[n,r]=b.useState(null),s=async()=>{n&&(await t.uploadFile(n),r(null))},i=()=>{t.closeUploadDialog(),r(null)};return a.jsxs(Qt,{"data-component-name":"cmp:UploadDialog",open:e.uploadDialogOpen,onClose:i,children:[a.jsx(Yt,{children:"ファイルをアップロード"}),a.jsxs(Jt,{children:[a.jsxs(G,{variant:"body2",color:"text.secondary",sx:{mb:2},children:["アップロード先: ",e.uploadTargetDir]}),a.jsxs(pe,{variant:"outlined",component:"label",fullWidth:!0,children:["ファイルを選択",a.jsx("input",{type:"file",hidden:!0,onChange:l=>{var u;return r(((u=l.target.files)==null?void 0:u[0])??null)}})]}),n&&a.jsx(G,{sx:{mt:1},children:n.name}),e.uploadError&&a.jsx(G,{color:"error",sx:{mt:1},children:e.uploadError})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:i,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:s,disabled:!n||e.isUploading,children:e.isUploading?a.jsx(ut,{size:20}):"アップロード"})]})]})}function iO({useCase:t,state:e,showHeader:n=!0}){if(!e.selectedPath)return a.jsxs($t,{"data-component-name":"cmp:TemplateEditorEmptyState",sx:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",p:4},children:[a.jsx(vc,{sx:{fontSize:64,color:"text.disabled",mb:2}}),a.jsx(G,{color:"text.secondary",children:"ファイルを選択してください"})]});const r=e.selectedPath.split("/").pop()??"",s=O2(r),i=M2(r);return e.isFileLoading?a.jsx($t,{"data-component-name":"cmp:TemplateEditorLoading",sx:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:a.jsx(ut,{})}):e.fileError?a.jsx($t,{"data-component-name":"cmp:TemplateEditorError",sx:{height:"100%",p:3},children:a.jsxs(zt,{severity:"error",children:["ファイルの読み込みに失敗しました: ",e.fileError.message]})}):a.jsxs($t,{"data-component-name":"cmp:TemplateEditorPanel",sx:{height:"100%",display:"flex",flexDirection:"column"},children:[n&&a.jsxs(B,{"data-component-name":"cmp:TemplateEditorHeader",sx:{p:2,borderBottom:1,borderColor:"divider",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(G,{variant:"h6",noWrap:!0,children:r}),e.isDirty&&a.jsx(Ht,{label:"未保存",color:"warning",size:"small"})]}),e.hasEditPermission&&a.jsxs(B,{sx:{display:"flex",gap:1},children:[i?a.jsx(pe,{variant:"contained",startIcon:e.isSaving?a.jsx(ut,{size:16}):a.jsx(Ti,{}),onClick:()=>t.openUploadDialog(e.selectedPath.split("/").slice(0,-1).join("/")),disabled:e.isSaving,children:"アップロードして上書き"}):a.jsx(pe,{variant:"contained",startIcon:e.isSaving?a.jsx(ut,{size:16}):a.jsx(na,{}),onClick:()=>t.save(),disabled:!e.isDirty||e.isSaving||!s,children:"保存"}),a.jsx(ft,{color:"error",onClick:()=>{var l;return t.openDeleteDialog(e.selectedPath,((l=e.selectedEntry)==null?void 0:l.type)??"file")},children:a.jsx(zn,{})})]})]}),a.jsxs(B,{"data-component-name":"cmp:TemplateEditorBody",sx:{flex:1,overflow:"auto",p:2},children:[e.saveError&&a.jsx(zt,{severity:"error",sx:{mb:2},children:e.saveError}),s?a.jsx(Xe,{multiline:!0,fullWidth:!0,value:e.editContent,onChange:e.hasEditPermission?l=>t.updateContent(l.target.value):void 0,sx:{"& .MuiInputBase-root":{fontFamily:"monospace",fontSize:"0.875rem"},"& .MuiInputBase-input":{fontFamily:"monospace"}},minRows:20,placeholder:"ファイルの内容がここに表示されます",slotProps:{input:{readOnly:!e.hasEditPermission}}}):i&&e.fileContent?a.jsx(B,{sx:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:400,bgcolor:"grey.100",borderRadius:1},children:a.jsx(B,{component:"img",src:`data:${Lee(r)};base64,${e.fileContent}`,alt:r,sx:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})}):a.jsx(zt,{severity:"info",children:"このファイル形式はテキストとして編集できません。削除のみ可能です。"})]}),a.jsx(qee,{useCase:t,state:e})]})}function qee({useCase:t,state:e}){var i,l;const n=async()=>{await t.confirmDelete()},r=((i=e.deleteTarget)==null?void 0:i.path.split("/").pop())??"",s=((l=e.deleteTarget)==null?void 0:l.type)==="directory";return a.jsxs(Qt,{"data-component-name":"cmp:DeleteConfirmDialog",open:e.deleteDialogOpen,onClose:()=>t.closeDeleteDialog(),children:[a.jsx(Yt,{children:s?"フォルダを削除":"ファイルを削除"}),a.jsx(Jt,{children:a.jsx(Eo,{children:s?`フォルダ「${r}」とその中のすべてのファイルを削除しますか?この操作は取り消せません。`:`ファイル「${r}」を削除しますか?この操作は取り消せません。`})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>t.closeDeleteDialog(),children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:n,disabled:e.isDeleting,children:e.isDeleting?a.jsx(ut,{size:20}):"削除"})]})]})}const Gee=Ss("/templates/")({component:Zee,validateSearch:t=>({file:typeof t.file=="string"?t.file:void 0})});function Zee(){var u;const t=vr(),e=aa(t.breakpoints.down("md")),{templateUseCase:n}=Vee(),r=n.getState(),s=((u=r.selectedPath)==null?void 0:u.split("/").pop())??"ファイル編集",i=r.selectedPath?O2(s):!1,l=r.selectedPath?M2(s):!1;return a.jsx(B,{"data-component-name":"cmp:TemplatePage",sx:{flex:1,overflow:"auto",bgcolor:"background.default"},children:a.jsxs(ji,{maxWidth:"xl",sx:{py:3},children:[a.jsx(no,{items:[{label:"ファイル管理"}]}),e?a.jsxs(a.Fragment,{children:[a.jsx(B,{sx:{height:"calc(100vh - 180px)"},children:a.jsx(sO,{useCase:n,state:r})}),a.jsxs(Cu,{"data-component-name":"cmp:TemplateEditorDrawer",anchor:"right",open:!!r.selectedPath,onClose:()=>n.clearSelection(),PaperProps:{sx:{width:"100%",maxWidth:600,display:"flex",flexDirection:"column"}},children:[a.jsx(Dp,{title:s,icon:a.jsx(vc,{color:"action"}),onClose:()=>n.clearSelection(),componentName:"cmp:TemplateEditorDrawerHeader",actions:r.hasEditPermission?a.jsxs(a.Fragment,{children:[l?a.jsx(pe,{variant:"contained",size:"small",startIcon:r.isSaving?a.jsx(ut,{size:16,color:"inherit"}):a.jsx(Ti,{}),onClick:()=>n.openUploadDialog(r.selectedPath.split("/").slice(0,-1).join("/")),disabled:r.isSaving,children:"上書き"}):a.jsx(pe,{variant:"contained",size:"small",startIcon:r.isSaving?a.jsx(ut,{size:16,color:"inherit"}):a.jsx(na,{}),onClick:()=>n.save(),disabled:!r.isDirty||r.isSaving||!i,children:"保存"}),a.jsx(ft,{color:"error",size:"small",onClick:()=>{var p;return n.openDeleteDialog(r.selectedPath,((p=r.selectedEntry)==null?void 0:p.type)??"file")},children:a.jsx(zn,{})})]}):void 0}),a.jsx(B,{sx:{flex:1,overflow:"auto"},children:a.jsx(iO,{useCase:n,state:r,showHeader:!1})})]})]}):a.jsxs(Et,{"data-component-name":"cmp:TemplateLayout",container:!0,spacing:2,sx:{height:"calc(100vh - 180px)"},children:[a.jsx(Et,{item:!0,xs:12,md:4,lg:3,sx:{height:"100%"},children:a.jsx(sO,{useCase:n,state:r})}),a.jsx(Et,{item:!0,xs:12,md:8,lg:9,sx:{height:"100%"},children:a.jsx(iO,{useCase:n,state:r,showHeader:!0})})]})]})})}let BC=null;function Kee(t){BC=t}function n5(t){return!t||t.startsWith("http://")||t.startsWith("https://")?t:BC?`${BC}/${t}`:t}class Sd{constructor(e){St(this,"baseUrl");this.baseUrl=e??ta().fileUploadUrl}getAuthHeaders(){const e=localStorage.getItem("frelio_github_token");if(!e)throw new Error("Not authenticated");return{Authorization:`Bearer ${e}`}}async fetchFiles(e){oe.debug("WorkerStorageRepositoryImpl.fetchFiles",{year:e});const n=e?`${this.baseUrl}/list?year=${e}`:`${this.baseUrl}/list`,r=await fetch(n,{headers:this.getAuthHeaders()});if(!r.ok)throw new Error("Failed to fetch files");const s=await r.json();return s.baseUrl&&Kee(s.baseUrl),s.baseUrl&&(s.files=s.files.map(i=>({...i,url:`${s.baseUrl}/${i.url}`,...i.variants&&{variants:Object.fromEntries(Object.entries(i.variants).map(([l,u])=>[l,`${s.baseUrl}/${u}`]))}}))),s}async fetchYears(){oe.debug("WorkerStorageRepositoryImpl.fetchYears");const e=await fetch(`${this.baseUrl}/years`,{headers:this.getAuthHeaders()});if(!e.ok)throw new Error("Failed to fetch years");return e.json()}async uploadFile(e,n){oe.info("WorkerStorageRepositoryImpl.uploadFile",{fileName:e.name,uploadedBy:n});const r=new FormData;r.append("file",e),r.append("uploadedBy",n);const s=await fetch(`${this.baseUrl}/upload`,{method:"POST",headers:this.getAuthHeaders(),body:r});if(!s.ok){const i=await s.json();throw new Error(i.error||"Upload failed")}return s.json()}async uploadImageSet(e,n,r,s){oe.info("WorkerStorageRepositoryImpl.uploadImageSet",{originalName:n,uploadedBy:r,presetCount:e.size});const i=new FormData;i.append("uploadedBy",r),i.append("originalName",n),s&&(i.append("width",String(s.width)),i.append("height",String(s.height)));for(const[u,p]of e)i.append(u,p,`${u}.webp`);const l=await fetch(`${this.baseUrl}/upload-set`,{method:"POST",headers:this.getAuthHeaders(),body:i});if(!l.ok){const u=await l.json();throw new Error(u.error||"Upload failed")}return l.json()}async deleteFile(e,n){oe.info("WorkerStorageRepositoryImpl.deleteFile",{uuid:e,year:n});const r=n?`${this.baseUrl}/files/${e}?year=${n}`:`${this.baseUrl}/files/${e}`;if(!(await fetch(r,{method:"DELETE",headers:this.getAuthHeaders()})).ok)throw new Error("Failed to delete file")}async updateFileMetadata(e,n,r){oe.info("WorkerStorageRepositoryImpl.updateFileMetadata",{uuid:e,year:n,metadata:r});const s=await fetch(`${this.baseUrl}/files/${e}`,{method:"PATCH",headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},body:JSON.stringify({year:n,...r})});if(!s.ok){const i=await s.json();throw new Error(i.error||"Update failed")}return s.json()}async rebuildIndex(e){if(oe.info("WorkerStorageRepositoryImpl.rebuildIndex",{year:e}),!(await fetch(`${this.baseUrl}/rebuild/${e}`,{method:"POST",headers:this.getAuthHeaders()})).ok)throw new Error("Failed to rebuild index")}}class zf{constructor(e,n,r,s){St(this,"baseRepo",new Sd);St(this,"queryClient",null);this.filesQuery=e,this.deleteMutation=n,this.rebuildMutation=r,this.updateAltMutation=s}setQueryClient(e){this.queryClient=e}static FilesQueryParams(e){const n=new Sd;return{queryKey:["files",e],queryFn:()=>n.fetchFiles(e??void 0)}}static DeleteMutationParams(e,n,r){const s=new Sd;return{mutationFn:i=>s.deleteFile(i,n??void 0),onSuccess:()=>{e.invalidateQueries({queryKey:["files",n]}),r==null||r()}}}static RebuildMutationParams(e,n){const r=new Sd;return{mutationFn:s=>r.rebuildIndex(s),onSuccess:()=>{e.invalidateQueries({queryKey:["files",n]})}}}static UpdateAltMutationParams(e,n,r){const s=new Sd;return{mutationFn:({uuid:i,alt:l})=>s.updateFileMetadata(i,n??new Date().getFullYear(),{alt:l}),onSuccess:i=>{e.invalidateQueries({queryKey:["files",n]}),r==null||r(i)}}}getData(){return this.filesQuery.data}isLoading(){return this.filesQuery.isLoading}getError(){return this.filesQuery.error}async deleteFile(e){await this.deleteMutation.mutateAsync(e)}isDeleting(){return this.deleteMutation.isPending}async rebuildIndex(e){await this.rebuildMutation.mutateAsync(e)}isRebuilding(){return this.rebuildMutation.isPending}async updateAlt(e,n){return this.updateAltMutation.mutateAsync({uuid:e,alt:n})}isUpdatingAlt(){return this.updateAltMutation.isPending}async uploadFile(e,n){return this.baseRepo.uploadFile(e,n)}async uploadImageSet(e,n,r,s){return this.baseRepo.uploadImageSet(e,n,r,s)}invalidateFiles(e){var n;(n=this.queryClient)==null||n.invalidateQueries({queryKey:["files",e]})}}const oO=30;function Qee(){return Fs(t=>({deleteTarget:null,uploading:!1,uploadError:null,cropDialogOpen:!1,cropImageUrl:null,pendingFile:null,detailTarget:null,editingAlt:"",sortBy:"uploadedAt",sortOrder:"desc",selectedYear:null,displayCount:oO,isDragOver:!1,setDeleteTarget:e=>t({deleteTarget:e}),setUploading:e=>t({uploading:e}),setUploadError:e=>t({uploadError:e}),setCropDialogOpen:e=>t({cropDialogOpen:e}),setCropImageUrl:e=>t({cropImageUrl:e}),setPendingFile:e=>t({pendingFile:e}),setDetailTarget:e=>t({detailTarget:e}),setEditingAlt:e=>t({editingAlt:e}),setSortBy:e=>t({sortBy:e}),setSortOrder:e=>t({sortOrder:e}),setSelectedYear:e=>t({selectedYear:e,displayCount:oO}),setDisplayCount:e=>t({displayCount:e}),setIsDragOver:e=>t({isDragOver:e})}))}class Jee{constructor(){St(this,"store",Qee());St(this,"cachedState",null);St(this,"cachedStoreState",null)}getState(){const e=this.store.getState();return this.cachedStoreState===e&&this.cachedState!==null?this.cachedState:(this.cachedStoreState=e,this.cachedState={deleteTarget:e.deleteTarget,uploading:e.uploading,uploadError:e.uploadError,cropDialogOpen:e.cropDialogOpen,cropImageUrl:e.cropImageUrl,pendingFile:e.pendingFile,detailTarget:e.detailTarget,editingAlt:e.editingAlt,sortBy:e.sortBy,sortOrder:e.sortOrder,selectedYear:e.selectedYear,displayCount:e.displayCount,isDragOver:e.isDragOver},this.cachedState)}setDeleteTarget(e){this.store.getState().setDeleteTarget(e)}setUploading(e){this.store.getState().setUploading(e)}setUploadError(e){this.store.getState().setUploadError(e)}setCropDialogOpen(e){this.store.getState().setCropDialogOpen(e)}setCropImageUrl(e){this.store.getState().setCropImageUrl(e)}setPendingFile(e){this.store.getState().setPendingFile(e)}setDetailTarget(e){this.store.getState().setDetailTarget(e)}setEditingAlt(e){this.store.getState().setEditingAlt(e)}setSortBy(e){this.store.getState().setSortBy(e)}setSortOrder(e){this.store.getState().setSortOrder(e)}setSelectedYear(e){this.store.getState().setSelectedYear(e)}setDisplayCount(e){this.store.getState().setDisplayCount(e)}setIsDragOver(e){this.store.getState().setIsDragOver(e)}openCropDialog(e,n){this.setCropImageUrl(e),this.setPendingFile(n),this.setCropDialogOpen(!0)}closeCropDialog(){const e=this.getState().cropImageUrl;e&&URL.revokeObjectURL(e),this.setCropDialogOpen(!1),this.setCropImageUrl(null),this.setPendingFile(null)}openDetail(e){this.setDetailTarget(e),this.setEditingAlt(e.alt??"")}openDetailByUuid(e,n){const r=n.find(s=>s.uuid===e);r&&this.openDetail(r)}closeDetail(){this.setDetailTarget(null)}loadMore(e){const n=this.getState().displayCount;this.setDisplayCount(n+e)}toggleSortOrder(){const e=this.getState().sortOrder;this.setSortOrder(e==="asc"?"desc":"asc")}subscribe(e){return this.store.subscribe(e)}}class Yee{execute(e,n,r){const s=[...e];return s.sort((i,l)=>{let u=0;switch(n){case"originalName":u=i.originalName.localeCompare(l.originalName,"ja");break;case"size":u=i.size-l.size;break;case"uploadedAt":default:u=new Date(i.uploadedAt).getTime()-new Date(l.uploadedAt).getTime();break}return r==="asc"?u:-u}),s}}const aO=new Set(["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","image/bmp","image/tiff"]),Xee=new Set(["image/jpeg","image/png","image/webp","image/bmp"]),ete=new Set(["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","text/plain","text/csv","application/json"]),tte=new Set(["video/mp4","video/webm","video/ogg","video/quicktime","video/x-msvideo"]),nte=new Set(["audio/mpeg","audio/wav","audio/ogg","audio/webm","audio/aac","audio/flac"]);class rte{getProcessType(e){return aO.has(e)?"image":ete.has(e)?"document":tte.has(e)?"video":nte.has(e)?"audio":"other"}getStrategy(e,n){return e==="image"&&this.isCroppable(n)?"crop-first":"direct-upload"}isCroppable(e){return Xee.has(e)}isImage(e){return aO.has(e)}decide(e){const n=this.getProcessType(e),r=this.getStrategy(n,e),s=r==="crop-first",i=n==="image"&&this.isCroppable(e);return{processType:n,strategy:r,requiresCrop:s,generateImageSet:i}}canUpload(e,n){return this.getProcessType(e)!==void 0}}const ste=30;class ite{constructor(e){St(this,"sortStorageFilesUseCase",new Yee);St(this,"fileTypeDecider",new rte);this.deps=e}getState(){const{repo:e,presenter:n}=this.deps,r=n.getState(),s=e.getData(),i=s?this.sortStorageFilesUseCase.execute(s.files,r.sortBy,r.sortOrder):[],l=i.slice(0,r.displayCount),u=r.displayCount<i.length;return{...r,data:s,isLoading:e.isLoading(),error:e.getError(),sortedFiles:i,displayedFiles:l,hasMore:u,isDeleting:e.isDeleting(),isRebuilding:e.isRebuilding(),isUpdatingAlt:e.isUpdatingAlt(),canEdit:this.deps.canEdit}}initializeYear(){const{repo:e,presenter:n}=this.deps,r=e.getData(),s=n.getState();r&&s.selectedYear===null&&r.availableYears.length>0&&n.setSelectedYear(r.year)}handleFileSelect(e){const{presenter:n}=this.deps;if(this.fileTypeDecider.decide(e.type).requiresCrop){const s=URL.createObjectURL(e);n.openCropDialog(s,e)}else this.uploadFile(e)}async uploadFile(e,n){const{repo:r,presenter:s,githubUser:i}=this.deps;s.setUploading(!0),s.setUploadError(null);try{const l=e instanceof Blob&&!(e instanceof File)?new File([e],n??"cropped-image.jpg",{type:e.type}):e;await r.uploadFile(l,(i==null?void 0:i.login)??"unknown");const u=new Date().getFullYear();r.invalidateFiles(u),s.getState().selectedYear!==u&&s.setSelectedYear(u)}catch(l){s.setUploadError(l.message)}finally{s.setUploading(!1)}}async handleCropComplete(e){var u;const{repo:n,presenter:r,githubUser:s}=this.deps,i=r.getState(),l=((u=i.pendingFile)==null?void 0:u.name)??"image.jpg";r.closeCropDialog(),r.setUploading(!0),r.setUploadError(null);try{const p={width:e.width,height:e.height};await n.uploadImageSet(e.imageSet,l,(s==null?void 0:s.login)??"unknown",p);const f=new Date().getFullYear();n.invalidateFiles(f),i.selectedYear!==f&&r.setSelectedYear(f)}catch(p){r.setUploadError(p.message)}finally{r.setUploading(!1)}}closeCropDialog(){this.deps.presenter.closeCropDialog()}async deleteFile(e){await this.deps.repo.deleteFile(e)}async rebuildIndex(e){await this.deps.repo.rebuildIndex(e)}async updateAlt(e,n){await this.deps.repo.updateAlt(e,n)}setSelectedYear(e){this.deps.presenter.setSelectedYear(e)}setSortBy(e){this.deps.presenter.setSortBy(e)}toggleSortOrder(){this.deps.presenter.toggleSortOrder()}setDragOver(e){this.deps.presenter.setIsDragOver(e)}handleDrop(e){const{presenter:n}=this.deps;if(this.fileTypeDecider.decide(e.type).requiresCrop){const s=URL.createObjectURL(e);n.openCropDialog(s,e)}else this.uploadFile(e)}loadMore(){this.deps.presenter.loadMore(ste)}openDetail(e){this.deps.presenter.openDetail(e),this.deps.navigateToDetail(e.uuid)}closeDetail(){this.deps.presenter.closeDetail(),this.deps.navigateToDetail(void 0)}openDetailByUuid(e,n){this.deps.presenter.openDetailByUuid(e,n)}openDeleteDialog(e){this.deps.presenter.setDeleteTarget(e)}closeDeleteDialog(){this.deps.presenter.setDeleteTarget(null)}clearUploadError(){this.deps.presenter.setUploadError(null)}setEditingAlt(e){this.deps.presenter.setEditingAlt(e)}}const Ed=new Jee,ote=t=>Ed.subscribe(t),lO=()=>Ed.getState();function ate(){const{authUseCase:t}=rr(),{githubUser:e,currentUser:n}=t.getState(),r=ys(),s=ws(n,"canEditStorage"),i=Di({from:"/storage/"}),l=ur(),u=C=>{l({to:"/storage",search:C?{detail:C}:{},replace:!0})};b.useSyncExternalStore(ote,lO,lO);const p=Ed.getState(),f=new zf(jn(zf.FilesQueryParams(p.selectedYear)),Pn(zf.DeleteMutationParams(r,p.selectedYear,()=>Ed.setDeleteTarget(null))),Pn(zf.RebuildMutationParams(r,p.selectedYear)),Pn(zf.UpdateAltMutationParams(r,p.selectedYear,C=>Ed.setDetailTarget(C))));f.setQueryClient(r);const m=new ite({repo:f,presenter:Ed,githubUser:e,navigateToDetail:u,canEdit:s}),g=b.useRef(!1);b.useEffect(()=>{g.current||(g.current=!0,m.initializeYear())},[m]);const y=b.useRef(!1),v=f.getData();return b.useEffect(()=>{!y.current&&i.detail&&(v!=null&&v.files)&&!p.detailTarget&&(m.openDetailByUuid(i.detail,v.files),y.current=!0)},[i.detail,v==null?void 0:v.files,p.detailTarget,m]),{storageUseCase:m}}function UC(t){if(t===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,r)).toFixed(1))+" "+n[r]}function lte(t){return new Date(t).toLocaleDateString("ja-JP",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function cte(t){return new Date(t).toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"})}function Uc(t){return t.startsWith("image/")}function r5(t){return t==="application/pdf"}var VC=function(t,e){return VC=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},VC(t,e)};function ute(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");VC(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var ss=function(){return ss=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},ss.apply(this,arguments)};var c1,cO;function dte(){if(cO)return c1;cO=1;var t=!1,e,n,r,s,i,l,u,p,f,m,g,y,v,C,S;function j(){if(!t){t=!0;var M=navigator.userAgent,T=/(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(M),E=/(Mac OS X)|(Windows)|(Linux)/.exec(M);if(y=/\b(iPhone|iP[ao]d)/.exec(M),v=/\b(iP[ao]d)/.exec(M),m=/Android/i.exec(M),C=/FBAN\/\w+;/i.exec(M),S=/Mobile/i.exec(M),g=!!/Win64/.exec(M),T){e=T[1]?parseFloat(T[1]):T[5]?parseFloat(T[5]):NaN,e&&document&&document.documentMode&&(e=document.documentMode);var k=/(?:Trident\/(\d+.\d+))/.exec(M);l=k?parseFloat(k[1])+4:e,n=T[2]?parseFloat(T[2]):NaN,r=T[3]?parseFloat(T[3]):NaN,s=T[4]?parseFloat(T[4]):NaN,s?(T=/(?:Chrome\/(\d+\.\d+))/.exec(M),i=T&&T[1]?parseFloat(T[1]):NaN):i=NaN}else e=n=r=i=s=NaN;if(E){if(E[1]){var A=/(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(M);u=A?parseFloat(A[1].replace("_",".")):!0}else u=!1;p=!!E[2],f=!!E[3]}else u=p=f=!1}}var D={ie:function(){return j()||e},ieCompatibilityMode:function(){return j()||l>e},ie64:function(){return D.ie()&&g},firefox:function(){return j()||n},opera:function(){return j()||r},webkit:function(){return j()||s},safari:function(){return D.webkit()},chrome:function(){return j()||i},windows:function(){return j()||p},osx:function(){return j()||u},linux:function(){return j()||f},iphone:function(){return j()||y},mobile:function(){return j()||y||v||m||S},nativeApp:function(){return j()||C},android:function(){return j()||m},ipad:function(){return j()||v}};return c1=D,c1}var u1,uO;function pte(){if(uO)return u1;uO=1;var t=!!(typeof window<"u"&&window.document&&window.document.createElement),e={canUseDOM:t,canUseWorkers:typeof Worker<"u",canUseEventListeners:t&&!!(window.addEventListener||window.attachEvent),canUseViewport:t&&!!window.screen,isInWorker:!t};return u1=e,u1}var d1,dO;function fte(){if(dO)return d1;dO=1;var t=pte(),e;t.canUseDOM&&(e=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0);/**
385
+ `,m={branch:{repositoryNameWithOwner:`${s}/${i}`,branchName:r},message:{headline:e},expectedHeadOid:l,fileChanges:{}};return u.length>0&&(m.fileChanges.additions=u),p.length>0&&(m.fileChanges.deletions=p),(await this.graphql(f,{input:m})).createCommitOnBranch.commit.oid}handleApiError(e,n){throw(e===401||e===403)&&Pd.notifyPermissionError(e,n),new lh(e,`GitHub API error: ${e}`,n)}async graphql(e,n){const r=await fetch(zQ,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:n})});r.ok||this.handleApiError(r.status,"GraphQL");const s=await r.json();if(s.errors)throw new Error(`GitHub GraphQL errors: ${JSON.stringify(s.errors)}`);return s.data}async triggerWorkflow(e,n="main"){const[r,s]=Qr().split("/"),i=await fetch(`https://api.github.com/repos/${r}/${s}/actions/workflows/${e}/dispatches`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github.v3+json","Content-Type":"application/json"},body:JSON.stringify({ref:n})});if(!i.ok){const l=await i.text();this.handleApiError(i.status,`ワークフロー実行 ${l}`)}}async getLatestWorkflowRun(e){const[n,r]=Qr().split("/"),s=await fetch(`https://api.github.com/repos/${n}/${r}/actions/workflows/${e}/runs?per_page=1`,{headers:{Authorization:`Bearer ${this.token}`,Accept:"application/vnd.github.v3+json"}});return s.ok||this.handleApiError(s.status,"ワークフロー実行状態取得"),(await s.json()).workflow_runs[0]??null}}const LM="frelio-branch-type",y2="frelio-branch-diff-cache";function n1(t){try{localStorage.setItem(y2,JSON.stringify(t))}catch{}}function $Q(){try{const t=localStorage.getItem(y2);return t?JSON.parse(t):null}catch{return null}}function If(){try{localStorage.removeItem(y2)}catch{}}const NQ={currentBranch:"develop",branchType:"develop",hasDiff:!1,diffCount:0,behindCount:0,conflicts:[],changedContents:[],isLoading:!1,isSyncing:!1,error:null};class FQ{constructor(){St(this,"state",{...NQ});St(this,"listeners",new Set);this.getSavedBranchType()==="personal"&&(this.state.branchType="personal")}getState(){return this.state}getSavedBranchType(){try{if(localStorage.getItem(LM)==="personal")return"personal"}catch{}return"develop"}setBranch(e,n){this.state={...this.state,currentBranch:e,branchType:n};try{localStorage.setItem(LM,n)}catch{}this.notify()}setDiffStatus(e,n,r){this.state={...this.state,hasDiff:e,diffCount:n,behindCount:r},this.notify()}setConflicts(e){this.state={...this.state,conflicts:e},this.notify()}setChangedContents(e){this.state={...this.state,changedContents:e},this.notify()}setLoading(e){this.state={...this.state,isLoading:e},this.notify()}setSyncing(e){this.state={...this.state,isSyncing:e},this.notify()}setError(e){this.state={...this.state,error:e},this.notify()}clearConflicts(){this.state={...this.state,conflicts:[]},this.notify()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){this.listeners.forEach(e=>e())}}const Rm=new FQ,BQ="frelio-cms",mr="develop",zM="main",r1=[3e3,5e3,1e4],UQ=3,s1=[5e3,1e4,15e3,2e4,3e4],VQ=5;function HQ(t){return t.toLowerCase().replace(/[._]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function $M(t){return`${BQ}/${HQ(t)}`}class WQ{constructor(e,n,r){St(this,"syncTimeoutId",null);this.presenter=e,this.gitHubClient=n,this.username=r}getState(){return{...this.presenter.getState(),developBranchName:mr,personalBranchName:$M(this.username)}}getCurrentBranch(){return this.presenter.getState().currentBranch}async switchToDevelop(){oe.info("BranchUseCase.switchToDevelop"),this.presenter.setLoading(!0),this.presenter.setError(null);try{await this.gitHubClient.ensureBranch(mr,zM),this.presenter.setBranch(mr,"develop"),this.presenter.setDiffStatus(!1,0,0),this.presenter.clearConflicts(),oe.info("BranchUseCase.switchToDevelop completed")}catch(e){throw oe.error("BranchUseCase.switchToDevelop failed",{error:e}),this.presenter.setError(e instanceof Error?e:new Error(String(e))),e}finally{this.presenter.setLoading(!1)}}async switchToPersonal(){const e=$M(this.username);oe.info("BranchUseCase.switchToPersonal",{personalBranch:e}),this.presenter.setLoading(!0),this.presenter.setError(null);try{await this.gitHubClient.ensureBranch(mr,zM),await this.gitHubClient.ensureBranch(e,mr),this.presenter.setBranch(e,"personal"),await this.checkDiff(),oe.info("BranchUseCase.switchToPersonal completed",{personalBranch:e})}catch(n){throw oe.error("BranchUseCase.switchToPersonal failed",{error:n}),this.presenter.setError(n instanceof Error?n:new Error(String(n))),n}finally{this.presenter.setLoading(!1)}}async checkDiff(){const e=this.presenter.getState();if(e.branchType==="develop"){this.presenter.setDiffStatus(!1,0,0),If();return}oe.info("BranchUseCase.checkDiff",{branch:e.currentBranch});const n=$Q();if(n){this.presenter.setDiffStatus(n.hasDiff,n.diffCount,n.behindCount),this.presenter.setSyncing(!0),oe.info("BranchUseCase.checkDiff: using cache, syncing",{hasDiff:n.hasDiff,diffCount:n.diffCount,age:Date.now()-n.timestamp}),this.startBackgroundSyncSilent();return}try{const[r,s]=await Promise.all([this.gitHubClient.compareBranches(mr,e.currentBranch),this.gitHubClient.compareBranches(e.currentBranch,mr)]),i=r.files.length>0,l=s.files.length>0?r.behind:0;this.presenter.setDiffStatus(i,r.ahead,l),oe.info("BranchUseCase.checkDiff completed",{ahead:r.ahead,behind:r.behind,aheadFilesCount:r.files.length,behindFilesCount:s.files.length})}catch(r){oe.error("BranchUseCase.checkDiff failed",{error:r}),this.presenter.setDiffStatus(!1,0,0)}}startBackgroundSyncSilent(){this.syncTimeoutId!==null&&(clearTimeout(this.syncTimeoutId),this.syncTimeoutId=null),this.backgroundSyncSilentWithRetry(0)}backgroundSyncSilentWithRetry(e){const n=s1[e]??s1[s1.length-1];this.syncTimeoutId=setTimeout(async()=>{const r=this.presenter.getState();if(r.branchType==="develop"){this.presenter.setSyncing(!1);return}oe.info("BranchUseCase.backgroundSyncSilent: checking",{retry:e});try{const[s,i]=await Promise.all([this.gitHubClient.compareBranches(mr,r.currentBranch),this.gitHubClient.compareBranches(r.currentBranch,mr)]),l=s.files.length>0,u=i.files.length>0?s.behind:0,p=this.presenter.getState();p.hasDiff===l?(this.presenter.setDiffStatus(l,s.ahead,u),this.presenter.setSyncing(!1),If(),oe.info("BranchUseCase.backgroundSyncSilent: synced, cache cleared",{ahead:s.ahead,behind:u})):e<VQ-1?(oe.info("BranchUseCase.backgroundSyncSilent: inconsistent, retrying",{cached:{hasDiff:p.hasDiff,diffCount:p.diffCount},api:{hasDiff:l,ahead:s.ahead},retry:e+1}),this.backgroundSyncSilentWithRetry(e+1)):(this.presenter.setDiffStatus(l,s.ahead,u),this.presenter.setSyncing(!1),If(),oe.warn("BranchUseCase.backgroundSyncSilent: max retries reached, using API value",{ahead:s.ahead,behind:u}))}catch(s){oe.error("BranchUseCase.backgroundSyncSilent: failed",{error:s}),this.presenter.setSyncing(!1)}},n)}async refreshDiff(){await this.checkDiff()}async refreshDiffAfterSave(){const e=this.presenter.getState();if(e.branchType==="develop")return;const n=e.diffCount+1;this.presenter.setDiffStatus(!0,n,e.behindCount),n1({hasDiff:!0,diffCount:n,behindCount:e.behindCount,timestamp:Date.now()}),oe.info("BranchUseCase.refreshDiffAfterSave: optimistic update + cache",{diffCount:n}),this.startBackgroundSync()}async refreshDiffAfterMerge(){this.presenter.getState().branchType!=="develop"&&(this.presenter.setDiffStatus(!1,0,0),n1({hasDiff:!1,diffCount:0,behindCount:0,timestamp:Date.now()}),oe.info("BranchUseCase.refreshDiffAfterMerge: optimistic update + cache (no diff)"),this.startBackgroundSync())}async refreshDiffAfterRebase(){const e=this.presenter.getState();e.branchType!=="develop"&&(this.presenter.setDiffStatus(e.hasDiff,e.diffCount,0),n1({hasDiff:e.hasDiff,diffCount:e.diffCount,behindCount:0,timestamp:Date.now()}),oe.info("BranchUseCase.refreshDiffAfterRebase: optimistic update + cache",{hasDiff:e.hasDiff,diffCount:e.diffCount,behindCount:0}),this.startBackgroundSync())}startBackgroundSync(){this.syncTimeoutId!==null&&(clearTimeout(this.syncTimeoutId),this.syncTimeoutId=null),this.presenter.setSyncing(!0),this.backgroundSyncWithRetry(0)}backgroundSyncWithRetry(e){const n=r1[e]??r1[r1.length-1];this.syncTimeoutId=setTimeout(async()=>{const r=this.presenter.getState();if(r.branchType==="develop"){this.presenter.setSyncing(!1);return}oe.info("BranchUseCase.backgroundSync: checking",{retry:e});try{const[s,i]=await Promise.all([this.gitHubClient.compareBranches(mr,r.currentBranch),this.gitHubClient.compareBranches(r.currentBranch,mr)]),l=s.files.length>0,u=i.files.length>0?s.behind:0,p=this.presenter.getState();p.hasDiff===l?(this.presenter.setDiffStatus(l,s.ahead,u),this.presenter.setSyncing(!1),If(),oe.info("BranchUseCase.backgroundSync: synced, cache cleared",{ahead:s.ahead,behind:u})):e<UQ-1?(oe.info("BranchUseCase.backgroundSync: inconsistent, retrying",{localHasDiff:p.hasDiff,apiHasDiff:l,retry:e+1}),this.backgroundSyncWithRetry(e+1)):(this.presenter.setDiffStatus(l,s.ahead,u),this.presenter.setSyncing(!1),If(),oe.warn("BranchUseCase.backgroundSync: max retries reached, using API value",{ahead:s.ahead,behind:u}))}catch(s){oe.error("BranchUseCase.backgroundSync: failed",{error:s}),this.presenter.setSyncing(!1)}},n)}cancelBackgroundSync(){this.syncTimeoutId!==null&&(clearTimeout(this.syncTimeoutId),this.syncTimeoutId=null,this.presenter.setSyncing(!1))}async rebaseFromDevelop(){const e=this.presenter.getState();if(e.branchType==="develop")return oe.info("BranchUseCase.rebaseFromDevelop: skipped (on develop)"),!1;oe.info("BranchUseCase.rebaseFromDevelop",{branch:e.currentBranch}),this.presenter.setLoading(!0),this.presenter.setError(null);try{const n=await this.gitHubClient.mergeBranches(e.currentBranch,mr,`Merge develop into ${e.currentBranch}`);if(oe.info("BranchUseCase.rebaseFromDevelop: merge result",{sha:n.sha,hasConflict:n.hasConflict}),n.hasConflict){if(oe.warn("BranchUseCase.rebaseFromDevelop: conflict detected"),await this.fetchConflictingContents(),this.presenter.getState().conflicts.length===0){oe.info("BranchUseCase.rebaseFromDevelop: no real conflicts, auto-resolving");const s=await this.gitHubClient.findConflictingFiles(e.currentBranch,mr),i=await Promise.all(s.map(async u=>{const p=await this.gitHubClient.fetchFileOrNull(u,mr);return{path:u,content:p??"",delete:p===null}}));i.length>0&&(await this.gitHubClient.commitFiles("Auto-resolve conflicts: accept develop version",i,e.currentBranch),oe.info("BranchUseCase.rebaseFromDevelop: auto-resolve committed",{count:i.length}));const l=await this.gitHubClient.mergeBranches(e.currentBranch,mr,`Merge develop into ${e.currentBranch}`);return oe.info("BranchUseCase.rebaseFromDevelop: retry merge result",{sha:l.sha,hasConflict:l.hasConflict}),l.hasConflict?(oe.warn("BranchUseCase.rebaseFromDevelop: still has conflict after auto-resolve"),await this.fetchConflictingContents(),!0):(await this.refreshDiffAfterRebase(),oe.info("BranchUseCase.rebaseFromDevelop: auto-resolved and merged"),!1)}return!0}return await this.refreshDiffAfterRebase(),oe.info("BranchUseCase.rebaseFromDevelop completed",{sha:n.sha}),!1}catch(n){throw oe.error("BranchUseCase.rebaseFromDevelop failed",{error:n}),this.presenter.setError(n instanceof Error?n:new Error(String(n))),n}finally{this.presenter.setLoading(!1)}}async fetchConflictingContents(){const e=this.presenter.getState();if(e.branchType==="develop"){this.presenter.setConflicts([]);return}oe.info("BranchUseCase.fetchConflictingContents",{branch:e.currentBranch});try{const r=(await this.gitHubClient.findConflictingFiles(e.currentBranch,mr)).map(l=>{const u=this.parseContentPath(l);return u?{...u,path:l}:null}).filter(l=>l!==null),i=(await Promise.all(r.map(async l=>{try{const[u,p]=await Promise.all([this.gitHubClient.fetchFileOrNull(l.path,e.currentBranch),this.gitHubClient.fetchFileOrNull(l.path,mr)]);return u===p?null:{contentTypeId:l.contentTypeId,contentId:l.contentId,title:l.contentId,path:l.path}}catch{return{contentTypeId:l.contentTypeId,contentId:l.contentId,title:l.contentId,path:l.path}}}))).filter(l=>l!==null);this.presenter.setConflicts(i),oe.info("BranchUseCase.fetchConflictingContents completed",{candidateCount:r.length,realConflictCount:i.length})}catch(n){oe.error("BranchUseCase.fetchConflictingContents failed",{error:n}),this.presenter.setConflicts([])}}async discardConflictingFiles(){const e=this.presenter.getState();if(e.branchType==="develop"){oe.info("BranchUseCase.discardConflictingFiles: skipped (on develop)");return}const n=e.conflicts;if(n.length===0){oe.info("BranchUseCase.discardConflictingFiles: no conflicts");return}oe.info("BranchUseCase.discardConflictingFiles",{branch:e.currentBranch,count:n.length}),this.presenter.setLoading(!0),this.presenter.setError(null);try{const r=await Promise.all(n.map(async s=>{const i=await this.gitHubClient.fetchFileOrNull(s.path,mr);return{path:s.path,content:i??"",delete:i===null}}));await this.gitHubClient.commitFiles("Resolve conflicts by accepting develop version",r,e.currentBranch),this.presenter.clearConflicts(),await this.checkDiff(),oe.info("BranchUseCase.discardConflictingFiles completed")}catch(r){throw oe.error("BranchUseCase.discardConflictingFiles failed",{error:r}),this.presenter.setError(r instanceof Error?r:new Error(String(r))),r}finally{this.presenter.setLoading(!1)}}async discardPersonalChanges(){const e=this.presenter.getState();if(e.branchType==="develop"){oe.info("BranchUseCase.discardPersonalChanges: skipped (on develop)");return}oe.info("BranchUseCase.discardPersonalChanges",{branch:e.currentBranch}),this.presenter.setLoading(!0),this.presenter.setError(null);try{await this.gitHubClient.resetBranch(e.currentBranch,mr),this.presenter.setDiffStatus(!1,0,0),this.presenter.clearConflicts(),oe.info("BranchUseCase.discardPersonalChanges completed")}catch(n){throw oe.error("BranchUseCase.discardPersonalChanges failed",{error:n}),this.presenter.setError(n instanceof Error?n:new Error(String(n))),n}finally{this.presenter.setLoading(!1)}}async fetchChangedContents(){const e=this.presenter.getState();if(e.branchType==="develop"){oe.info("BranchUseCase.fetchChangedContents: skipped (on develop)"),this.presenter.setChangedContents([]);return}oe.info("BranchUseCase.fetchChangedContents",{branch:e.currentBranch}),this.presenter.setLoading(!0);try{const n=await this.gitHubClient.compareBranches(mr,e.currentBranch),r=[];for(const s of n.files){const i=this.parseContentPath(s.filename);i&&r.push({...i,status:s.status==="renamed"?"modified":s.status})}this.presenter.setChangedContents(r),oe.info("BranchUseCase.fetchChangedContents completed",{count:r.length})}catch(n){oe.error("BranchUseCase.fetchChangedContents failed",{error:n}),this.presenter.setChangedContents([])}finally{this.presenter.setLoading(!1)}}parseContentPath(e){if(e.endsWith("_index.json"))return null;const n=e.match(/^frelio-data\/site\/contents\/published\/([^/]+)\/([^/]+)\.json$/);if(n)return{basePath:"published",contentTypeId:n[1],contentId:n[2]};const r=e.match(/^frelio-data\/site\/contents\/private\/([^/]+)\/([^/]+)\.json$/);return r?{basePath:"private",contentTypeId:r[1],contentId:r[2]}:null}async pullContentFromDevelop(e){const n=this.presenter.getState();if(n.branchType==="develop"){oe.info("BranchUseCase.pullContentFromDevelop: skipped (on develop)");return}const r=`${Qi}/${e.basePath}/${e.contentTypeId}/${e.contentId}.json`;oe.info("BranchUseCase.pullContentFromDevelop",{filePath:r}),this.presenter.setLoading(!0),this.presenter.setError(null);try{const s=await this.gitHubClient.fetchFileOrNull(r,mr);s===null?await this.gitHubClient.commitFiles(`Pull from develop: delete ${e.contentId}`,[{path:r,content:"",delete:!0}],n.currentBranch):await this.gitHubClient.commitFiles(`Pull from develop: ${e.contentId}`,[{path:r,content:s,delete:!1}],n.currentBranch),await this.checkDiff(),oe.info("BranchUseCase.pullContentFromDevelop completed")}catch(s){throw oe.error("BranchUseCase.pullContentFromDevelop failed",{error:s}),this.presenter.setError(s instanceof Error?s:new Error(String(s))),s}finally{this.presenter.setLoading(!1)}}async isSameAsDevelop(e){if(this.presenter.getState().branchType==="develop")return!0;const r=`${Qi}/${e.basePath}/${e.contentTypeId}/${e.contentId}.json`;try{const s=await this.gitHubClient.fetchFileOrNull(r,mr);if(s===null)return!1;const i=JSON.parse(s);return JSON.stringify(i)===JSON.stringify(e.content)}catch{return!1}}async mergeToDevelop(){const e=this.presenter.getState();if(e.branchType==="develop")return oe.info("BranchUseCase.mergeToDevelop: skipped (on develop)"),{success:!0,hasConflict:!1};if(!e.hasDiff)return oe.info("BranchUseCase.mergeToDevelop: skipped (no diff)"),{success:!0,hasConflict:!1};oe.info("BranchUseCase.mergeToDevelop",{branch:e.currentBranch}),this.presenter.setLoading(!0),this.presenter.setError(null);try{const n=await this.gitHubClient.mergeBranches(mr,e.currentBranch,`Merge ${e.currentBranch} into develop`);return oe.info("BranchUseCase.mergeToDevelop: merge result",{sha:n.sha,hasConflict:n.hasConflict}),n.hasConflict?(oe.warn("BranchUseCase.mergeToDevelop: conflict detected"),await this.fetchConflictingContents(),{success:!1,hasConflict:!0}):(n.sha?(await this.gitHubClient.resetBranchToCommit(e.currentBranch,n.sha),oe.info("BranchUseCase.mergeToDevelop: fast-forwarded personal branch to merge commit",{sha:n.sha})):(await this.gitHubClient.resetBranch(e.currentBranch,mr),oe.info("BranchUseCase.mergeToDevelop: fast-forwarded personal branch to develop (already merged)")),await this.refreshDiffAfterMerge(),oe.info("BranchUseCase.mergeToDevelop completed",{sha:n.sha}),{success:!0,hasConflict:!1})}catch(n){throw oe.error("BranchUseCase.mergeToDevelop failed",{error:n}),this.presenter.setError(n instanceof Error?n:new Error(String(n))),n}finally{this.presenter.setLoading(!1)}}async initialize(){const e=this.presenter.getSavedBranchType();oe.info("BranchUseCase.initialize",{savedBranchType:e}),e==="personal"?await this.switchToPersonal():await this.switchToDevelop(),oe.info("BranchUseCase.initialize completed",{savedBranchType:e})}}const qQ=t=>Rm.subscribe(t),NM=()=>Rm.getState();function Ei(){const{authUseCase:t}=rr(),{token:e,githubUser:n,allowPersonalBranch:r}=t.getState(),s=b.useRef(!1);b.useSyncExternalStore(qQ,NM,NM);const i=b.useMemo(()=>{if(!e||!n)return null;const l=new At(e);return new WQ(Rm,l,n.login)},[e,n]);return b.useEffect(()=>{if(!(!i||s.current)){if(s.current=!0,!r){i.switchToDevelop();return}i.initialize()}},[i,r]),{branchUseCase:i}}function GQ(){return{users:[],stagingBranches:[Dm()]}}class uu{constructor(e,n){this.queries=e,this.saveMutation=n}static AdminDataQueryParams(e,n){return{queryKey:["adminData",n],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJsonOrDefault(Mh,GQ(),n)},enabled:!!e}}static SaveAdminDataMutationParams(e,n,r){return{mutationFn:async s=>{if(!n)throw new Error("Not authenticated");await new At(n).commitFiles("chore: ユーザー一覧を更新",[{path:Mh,content:JSON.stringify(s,null,2)}],r)},onSuccess:()=>{e.invalidateQueries({queryKey:["adminData",r]})}}}getUsers(){var n;const e=((n=this.queries.adminData.data)==null?void 0:n.users)??[];return pP(e)}isLoading(){return this.queries.adminData.isLoading}getError(){return this.queries.adminData.error}async saveUsers(e){const n=this.queries.adminData.data,r={users:e,stagingBranches:(n==null?void 0:n.stagingBranches)??[Dm()]};await this.saveMutation.mutateAsync(r)}isSaving(){return this.saveMutation.isPending}}const Ry=20;function ZQ(t,e){if(!t)return"不明";const n=e.find(r=>r.githubUsername===t);return(n==null?void 0:n.displayName)??t}function FM(t,e){return{sha:t.sha,shortSha:t.sha.slice(0,7),message:t.message,authorGithubUsername:t.author.login,authorDisplayName:ZQ(t.author.login,e),date:new Date(t.author.date)}}class i1{constructor(e,n,r,s,i,l,u,p){this.queries=e,this.users=n,this.token=r,this.paginationState=s,this.updatePaginationState=i,this.folderPath=l,this.filePath=u,this.branch=p}static FolderCommitsQueryParams(e,n,r){return{queryKey:["activityLog","folder",n,r],queryFn:async()=>!e||!n?{commits:[],hasMore:!1}:new At(e).getCommits(n,r,Ry,1),enabled:!!e&&!!n}}static FileCommitsQueryParams(e,n,r){return{queryKey:["activityLog","file",n,r],queryFn:async()=>!e||!n?{commits:[],hasMore:!1}:new At(e).getCommits(n,r,Ry,1),enabled:!!e&&!!n}}getFolderCommits(){var r;return[...((r=this.queries.folderCommits.data)==null?void 0:r.commits)??[],...this.paginationState.additionalFolderCommits].map(s=>FM(s,this.users))}getFileCommits(){var r;return[...((r=this.queries.fileCommits.data)==null?void 0:r.commits)??[],...this.paginationState.additionalFileCommits].map(s=>FM(s,this.users))}isFolderLoading(){return this.queries.folderCommits.isLoading}isFileLoading(){return this.queries.fileCommits.isLoading}isFolderFetchingMore(){return this.paginationState.isFolderFetchingMore}isFileFetchingMore(){return this.paginationState.isFileFetchingMore}hasFolderMore(){var e;return this.paginationState.folderPage===1?((e=this.queries.folderCommits.data)==null?void 0:e.hasMore)??!1:this.paginationState.folderHasMore}hasFileMore(){var e;return this.paginationState.filePage===1?((e=this.queries.fileCommits.data)==null?void 0:e.hasMore)??!1:this.paginationState.fileHasMore}getFolderError(){return this.queries.folderCommits.error}getFileError(){return this.queries.fileCommits.error}async fetchMoreFolderCommits(){if(!(!this.token||!this.folderPath)&&!this.paginationState.isFolderFetchingMore){this.updatePaginationState({isFolderFetchingMore:!0});try{const e=new At(this.token),n=this.paginationState.folderPage+1,r=await e.getCommits(this.folderPath,this.branch,Ry,n);this.updatePaginationState({folderPage:n,additionalFolderCommits:[...this.paginationState.additionalFolderCommits,...r.commits],folderHasMore:r.hasMore,isFolderFetchingMore:!1})}catch{this.updatePaginationState({isFolderFetchingMore:!1})}}}async fetchMoreFileCommits(){if(!(!this.token||!this.filePath)&&!this.paginationState.isFileFetchingMore){this.updatePaginationState({isFileFetchingMore:!0});try{const e=new At(this.token),n=this.paginationState.filePage+1,r=await e.getCommits(this.filePath,this.branch,Ry,n);this.updatePaginationState({filePage:n,additionalFileCommits:[...this.paginationState.additionalFileCommits,...r.commits],fileHasMore:r.hasMore,isFileFetchingMore:!1})}catch{this.updatePaginationState({isFileFetchingMore:!1})}}}async getFileContentAtCommit(e,n){if(!this.token)throw new Error("Not authenticated");return new At(this.token).fetchFile(n,e)}}const hP="frelio_activity_log_open";function KQ(){try{return localStorage.getItem(hP)==="true"}catch{return!1}}function QQ(t){try{localStorage.setItem(hP,t?"true":"false")}catch{}}function JQ(){return Fs(t=>({isOpen:KQ(),activeTab:"folder",fileContentDialogSha:null,fileContentDialogPath:null,setOpen:e=>{QQ(e),t({isOpen:e})},setActiveTab:e=>t({activeTab:e}),setFileContentDialog:(e,n)=>t({fileContentDialogSha:e,fileContentDialogPath:n})}))}let o1=null;function YQ(){return o1||(o1=JQ()),o1}let ky=null,BM=null;class XQ{constructor(){St(this,"store",YQ())}getState(){const e=this.store.getState();return BM===e&&ky!==null||(BM=e,ky={isOpen:e.isOpen,activeTab:e.activeTab,fileContentDialogSha:e.fileContentDialogSha,fileContentDialogPath:e.fileContentDialogPath}),ky}subscribe(e){return this.store.subscribe(e)}open(){this.store.getState().setOpen(!0)}close(){this.store.getState().setOpen(!1)}toggle(){const e=this.store.getState().isOpen;this.store.getState().setOpen(!e)}setActiveTab(e){this.store.getState().setActiveTab(e)}openFileContentDialog(e,n){this.store.getState().setFileContentDialog(e,n)}closeFileContentDialog(){this.store.getState().setFileContentDialog(null,null)}}class eJ{constructor(e,n,r){this.repository=e,this.presenter=n,this.paths=r}getState(){var n,r;const e=this.presenter.getState();return{isAvailable:this.paths!==null,isOpen:e.isOpen,activeTab:e.activeTab,folderCommits:this.repository.getFolderCommits(),fileCommits:this.repository.getFileCommits(),isFolderLoading:this.repository.isFolderLoading(),isFileLoading:this.repository.isFileLoading(),isFolderFetchingMore:this.repository.isFolderFetchingMore(),isFileFetchingMore:this.repository.isFileFetchingMore(),hasFolderMore:this.repository.hasFolderMore(),hasFileMore:this.repository.hasFileMore(),folderError:this.repository.getFolderError(),fileError:this.repository.getFileError(),fileTabEnabled:((n=this.paths)==null?void 0:n.filePath)!==null&&((r=this.paths)==null?void 0:r.filePath)!==void 0,paths:this.paths,fileContentDialogSha:e.fileContentDialogSha,fileContentDialogPath:e.fileContentDialogPath}}subscribe(e){return this.presenter.subscribe(e)}open(){this.presenter.open()}close(){this.presenter.close()}toggle(){this.presenter.toggle()}setActiveTab(e){this.presenter.setActiveTab(e)}async loadMoreFolderCommits(){await this.repository.fetchMoreFolderCommits()}async loadMoreFileCommits(){await this.repository.fetchMoreFileCommits()}async getFileContentAtCommit(e){var r;const n=(r=this.paths)==null?void 0:r.filePath;if(!n)throw new Error("File path is not available");return this.repository.getFileContentAtCommit(e,n)}openFileContentDialog(e){var r;const n=(r=this.paths)==null?void 0:r.filePath;n&&this.presenter.openFileContentDialog(e,n)}closeFileContentDialog(){this.presenter.closeFileContentDialog()}}function tJ(t,e,n){if(t.startsWith("/storage")||t.startsWith("/login")||t.startsWith("/auth"))return null;if(t==="/")return{folderPath:Ts.DATA_ROOT,filePath:null};if(/^\/contents\/[^/]+\/?$/.test(t)){const r=e.contentTypeId;return r?{folderPath:`${Ts.CONTENTS_PRIVATE}/${r}`,filePath:null}:null}if(/^\/contents\/[^/]+\/[^/]+$/.test(t)){const{contentTypeId:r,contentId:s}=e;return!r||!s?null:{folderPath:`${Ts.CONTENTS_PRIVATE}/${r}`,filePath:`${Ts.CONTENTS_PRIVATE}/${r}/${s}.json`}}if(t==="/content-types"||t==="/content-types/")return{folderPath:Ts.CONTENT_TYPES,filePath:null};if(/^\/content-types\/[^/]+\/edit$/.test(t)){const r=e.contentTypeId;return r?{folderPath:Ts.CONTENT_TYPES,filePath:`${Ts.CONTENT_TYPES}/${r}.json`}:null}if(/^\/content-types\/[^/]+\/views$/.test(t)){const r=e.contentTypeId;return r?{folderPath:Ts.ADMIN_CONTENT_TYPES,filePath:`${Ts.ADMIN_CONTENT_TYPES}/${r}.views.json`}:null}return t==="/templates"||t==="/templates/"?{folderPath:Ts.TEMPLATES,filePath:n??null}:t==="/build-recipes"||t==="/build-recipes/"?{folderPath:`${Ts.ADMIN_ROOT}/recipes`,filePath:`${Ts.ADMIN_ROOT}/recipes/build-data-recipe.json`}:t==="/users"||t==="/users/"?{folderPath:Ts.ADMIN_USERS,filePath:null}:t==="/staging"||t==="/staging/"?{folderPath:Ts.ADMIN_USERS,filePath:null}:{folderPath:Ts.DATA_ROOT,filePath:null}}const v2=new XQ,nJ=t=>v2.subscribe(t),UM=()=>v2.getState(),rJ="develop",EC=new Map;function sJ(t,e){return`${t??""}|${e??""}`}function VM(t){let e=EC.get(t);return e||(e={folderPage:1,filePage:1,additionalFolderCommits:[],additionalFileCommits:[],folderHasMore:!0,fileHasMore:!0,isFolderFetchingMore:!1,isFileFetchingMore:!1},EC.set(t,e)),e}function iJ(t){const e=ox(),n=uc({strict:!1});return b.useMemo(()=>tJ(e.pathname,n,t),[e.pathname,n,t])}function oJ(t){var j;const{authUseCase:e}=rr(),{branchUseCase:n}=Ei(),{token:r}=e.getState(),s=(n==null?void 0:n.getCurrentBranch())??"develop";b.useSyncExternalStore(nJ,UM,UM);const i=iJ(t),u=((j=jn(uu.AdminDataQueryParams(r,rJ)).data)==null?void 0:j.users)??[],p=sJ((i==null?void 0:i.folderPath)??null,(i==null?void 0:i.filePath)??null),f=b.useRef({key:p,state:VM(p)});f.current.key!==p&&(f.current={key:p,state:VM(p)});const m=b.useRef(0),g=b.useMemo(()=>D=>{const T={...f.current.state,...D};f.current.state=T,EC.set(f.current.key,T),m.current+=1},[]),y=jn(i1.FolderCommitsQueryParams(r,(i==null?void 0:i.folderPath)??null,s)),v=jn(i1.FileCommitsQueryParams(r,(i==null?void 0:i.filePath)??null,s)),C=new i1({folderCommits:y,fileCommits:v},u,r,f.current.state,g,(i==null?void 0:i.folderPath)??null,(i==null?void 0:i.filePath)??null,s);return{activityLogUseCase:new eJ(C,v2,i)}}const aJ=ye([a.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),a.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")],"AccessTime"),lJ=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 4c1.93 0 3.5 1.57 3.5 3.5S13.93 13 12 13s-3.5-1.57-3.5-3.5S10.07 6 12 6m0 14c-2.03 0-4.43-.82-6.14-2.88C7.55 15.8 9.68 15 12 15s4.45.8 6.14 2.12C16.43 19.18 14.03 20 12 20"}),"AccountCircle"),mP=ye(a.jsx("path",{d:"M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3z"}),"AccountTree"),Qn=ye(a.jsx("path",{d:"M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"}),"Add"),cJ=ye(a.jsx("path",{d:"m22 5.72-4.6-3.86-1.29 1.53 4.6 3.86zM7.88 3.39 6.6 1.86 2 5.71l1.29 1.53zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9m0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7"}),"Alarm"),uJ=ye(a.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2M9 17H7v-5h2zm4 0h-2v-3h2zm0-5h-2v-2h2zm4 5h-2V7h2z"}),"Analytics"),dJ=ye(a.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2m-7 9h-2V5h2zm0 4h-2v-2h2z"}),"Announcement"),zx=ye(a.jsx("path",{d:"m20 12-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8z"}),"ArrowDownward"),pJ=ye(a.jsx("path",{d:"m7 10 5 5 5-5z"}),"ArrowDropDown"),fJ=ye(a.jsx("path",{d:"m12 4-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"}),"ArrowForward"),x2=ye(a.jsx("path",{d:"m4 12 1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8z"}),"ArrowUpward"),km=ye(a.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-5 14H7v-2h7zm3-4H7v-2h10zm0-4H7V7h10z"}),"Article"),gP=ye(a.jsx("path",{d:"M16.5 6v11.5c0 2.21-1.79 4-4 4s-4-1.79-4-4V5c0-1.38 1.12-2.5 2.5-2.5s2.5 1.12 2.5 2.5v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6H10v9.5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V5c0-2.21-1.79-4-4-4S7 2.79 7 5v12.5c0 3.04 2.46 5.5 5.5 5.5s5.5-2.46 5.5-5.5V6z"}),"AttachFile"),hJ=ye(a.jsx("path",{d:"M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm2 11h-3v3.75c0 1.24-1.01 2.25-2.25 2.25S8.5 17.99 8.5 16.75s1.01-2.25 2.25-2.25c.46 0 .89.14 1.25.38V11h4zm-3-4V3.5L18.5 9z"}),"AudioFile"),mJ=ye(a.jsx("path",{d:"m19 1-5 5v11l5-4.5zM1 6v14.65c0 .25.25.5.5.5.1 0 .15-.05.25-.05C3.1 20.45 5.05 20 6.5 20c1.95 0 4.05.4 5.5 1.5V6c-1.45-1.1-3.55-1.5-5.5-1.5S2.45 4.9 1 6m22 13.5V6c-.6-.45-1.25-.75-2-1v13.5c-1.1-.35-2.3-.5-3.5-.5-1.7 0-4.15.65-5.5 1.5v2c1.35-.85 3.8-1.5 5.5-1.5 1.65 0 3.35.3 4.75 1.05.1.05.15.05.25.05.25 0 .5-.25.5-.5z"}),"AutoStories"),gJ=ye(a.jsx("path",{d:"M18 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2M6 4h5v8l-2.5-1.5L6 12z"}),"Book"),yJ=ye(a.jsx("path",{d:"M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2"}),"Bookmark"),b2=ye(a.jsx("path",{d:"m22.7 19-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4"}),"Build"),vJ=ye(a.jsx("path",{d:"M12 7V3H2v18h20V7zM6 19H4v-2h2zm0-4H4v-2h2zm0-4H4V9h2zm0-4H4V5h2zm4 12H8v-2h2zm0-4H8v-2h2zm0-4H8V9h2zm0-4H8V5h2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8zm-2-8h-2v2h2zm0 4h-2v2h2z"}),"Business"),yP=ye(a.jsx("path",{d:"M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 18H4V8h16z"}),"CalendarToday"),xJ=ye([a.jsx("path",{d:"m12 2-5.5 9h11z"},"0"),a.jsx("circle",{cx:"17.5",cy:"17.5",r:"4.5"},"1"),a.jsx("path",{d:"M3 13.5h8v8H3z"},"2")],"Category"),bJ=ye(a.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2M6 9h12v2H6zm8 5H6v-2h8zm4-6H6V6h12z"}),"Chat"),Ph=ye(a.jsx("path",{d:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"}),"Check"),vP=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8z"}),"CheckCircle"),xP=ye(a.jsx("path",{d:"M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"}),"ChevronLeft"),Jl=ye(a.jsx("path",{d:"M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"}),"ChevronRight"),SJ=ye(a.jsx("path",{d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}),"Clear"),$x=ye(a.jsx("path",{d:"M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}),"Close"),CJ=ye(a.jsx("path",{d:"M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96M17 13l-5 5-5-5h3V9h4v4z"}),"CloudDownload"),Ti=ye(a.jsx("path",{d:"M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96M14 13v4h-4v-4H7l5-5 5 5z"}),"CloudUpload"),S2=ye(a.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"}),"Code"),wJ=ye(a.jsx("path",{d:"M22 16V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2m-11-4 2.03 2.71L16 11l4 5H8zM2 6v14c0 1.1.9 2 2 2h14v-2H4V6z"}),"Collections"),jJ=ye(a.jsx("path",{d:"M21.99 4c0-1.1-.89-2-1.99-2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4zM18 14H6v-2h12zm0-3H6V9h12zm0-3H6V6h12z"}),"Comment"),TJ=ye(a.jsx("path",{d:"M14 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8zm-2 8c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2m4 8H8v-.57c0-.81.48-1.53 1.22-1.85.85-.37 1.79-.58 2.78-.58s1.93.21 2.78.58c.74.32 1.22 1.04 1.22 1.85z"}),"ContactPage"),bP=ye(a.jsx("path",{d:"M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2m0 16H8V7h11z"}),"ContentCopy"),C2=ye(a.jsx("path",{d:"M20 6h-8l-2-2H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2m-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3z"}),"CreateNewFolder"),DJ=ye(a.jsx("path",{d:"M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2m0 14H4v-6h16zm0-10H4V6h16z"}),"CreditCard"),EJ=ye(a.jsx("path",{d:"M19 7H5c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2m0 8H5V9h14z"}),"Crop169"),RJ=ye(a.jsx("path",{d:"M19 6H5c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2m0 10H5V8h14z"}),"Crop32"),kJ=ye(a.jsx("path",{d:"M17 3H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H7V5h10z"}),"CropPortrait"),MJ=ye(a.jsx("path",{d:"M18 4H6c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2m0 14H6V6h12z"}),"CropSquare"),SP=ye(a.jsx("path",{d:"M3 13h8V3H3zm0 8h8v-6H3zm10 0h8V11h-8zm0-18v6h8V3z"}),"Dashboard"),OJ=ye(a.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"}),"DataArray"),zn=ye(a.jsx("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"}),"Delete"),Tp=ye(a.jsx("path",{d:"M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm2 16H8v-2h8zm0-4H8v-2h8zm-3-5V3.5L18.5 9z"}),"Description"),AJ=ye(a.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}),"Download"),wu=ye(a.jsx("path",{d:"M11 18c0 1.1-.9 2-2 2s-2-.9-2-2 .9-2 2-2 2 .9 2 2m-2-8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0-6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m6 4c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"DragIndicator"),Ri=ye(a.jsx("path",{d:"M3 17.25V21h3.75L17.81 9.94l-3.75-3.75zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34a.996.996 0 0 0-1.41 0l-1.83 1.83 3.75 3.75z"}),"Edit"),_J=ye(a.jsx("path",{d:"M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2m0 4-8 5-8-5V6l8 5 8-5z"}),"Email"),IJ=ye(a.jsx("path",{d:"M17 12h-5v5h5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1zm3 18H5V8h14z"}),"Event"),Wr=ye(a.jsx("path",{d:"M16.59 8.59 12 13.17 7.41 8.59 6 10l6 6 6-6z"}),"ExpandMore"),CP=ye(a.jsx("path",{d:"M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-1.99.9-1.99 2v3.8H3.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7s2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11"}),"Extension"),PJ=ye(a.jsx("path",{d:"M9 11.75c-.69 0-1.25.56-1.25 1.25s.56 1.25 1.25 1.25 1.25-.56 1.25-1.25-.56-1.25-1.25-1.25m6 0c-.69 0-1.25.56-1.25 1.25s.56 1.25 1.25 1.25 1.25-.56 1.25-1.25-.56-1.25-1.25-1.25M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8 0-.29.02-.58.05-.86 2.36-1.05 4.23-2.98 5.21-5.37C11.07 8.33 14.05 10 17.42 10c.78 0 1.53-.09 2.25-.26.21.71.33 1.47.33 2.26 0 4.41-3.59 8-8 8"}),"Face"),LJ=ye(a.jsx("path",{d:"m12 21.35-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54z"}),"Favorite"),zJ=ye(a.jsx("path",{d:"M16 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V8zM7 7h5v2H7zm10 10H7v-2h10zm0-4H7v-2h10zm-2-4V5l4 4z"}),"Feed"),$J=ye(a.jsx("path",{d:"M15 2H6c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V7zM6 20V4h8v4h4v12zm10-10v5c0 2.21-1.79 4-4 4s-4-1.79-4-4V8.5c0-1.47 1.26-2.64 2.76-2.49 1.3.13 2.24 1.32 2.24 2.63V15h-2V8.5c0-.28-.22-.5-.5-.5s-.5.22-.5.5V15c0 1.1.9 2 2 2s2-.9 2-2v-5z"}),"FilePresent"),NJ=ye(a.jsx("path",{d:"M14.4 6 14 4H5v17h2v-7h5.6l.4 2h7V6z"}),"Flag"),ic=ye(a.jsx("path",{d:"M10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8z"}),"Folder"),FJ=ye(a.jsx("path",{d:"M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2m0 12H4V8h16z"}),"FolderOpen"),BJ=ye(a.jsx("path",{d:"M21 6h-2v9H6v2c0 .55.45 1 1 1h11l4 4V7c0-.55-.45-1-1-1m-4 6V3c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v14l4-4h10c.55 0 1-.45 1-1"}),"Forum"),UJ=ye(a.jsx("path",{d:"M12 1.27a11 11 0 00-3.48 21.46c.55.09.73-.28.73-.55v-1.84c-3.03.64-3.67-1.46-3.67-1.46-.55-1.29-1.28-1.65-1.28-1.65-.92-.65.1-.65.1-.65 1.1 0 1.73 1.1 1.73 1.1.92 1.65 2.57 1.2 3.21.92a2 2 0 01.64-1.47c-2.47-.27-5.04-1.19-5.04-5.5 0-1.1.46-2.1 1.2-2.84a3.76 3.76 0 010-2.93s.91-.28 3.11 1.1c1.8-.49 3.7-.49 5.5 0 2.1-1.38 3.02-1.1 3.02-1.1a3.76 3.76 0 010 2.93c.83.74 1.2 1.74 1.2 2.94 0 4.21-2.57 5.13-5.04 5.4.45.37.82.92.82 2.02v3.03c0 .27.1.64.73.55A11 11 0 0012 1.27"}),"GitHub"),Nx=ye(a.jsx("path",{d:"M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5s-3 1.34-3 3 1.34 3 3 3m-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5 5 6.34 5 8s1.34 3 3 3m0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5m8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5"}),"Group"),VJ=ye(a.jsx("path",{d:"M12 3c-4.97 0-9 4.03-9 9v7c0 1.1.9 2 2 2h4v-8H5v-1c0-3.87 3.13-7 7-7s7 3.13 7 7v1h-4v8h4c1.1 0 2-.9 2-2v-7c0-4.97-4.03-9-9-9"}),"Headphones"),HJ=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 17h-2v-2h2zm2.07-7.75-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25"}),"Help"),WJ=ye(a.jsx("path",{d:"M11 18h2v-2h-2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8m0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4"}),"HelpOutline"),wP=ye(a.jsx("path",{d:"M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9m-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8z"}),"History"),qJ=ye(a.jsx("path",{d:"M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"}),"Home"),GJ=ye(a.jsx("path",{d:"M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3m12-6h-8v7H3V5H1v15h2v-3h18v3h2v-9c0-2.21-1.79-4-4-4"}),"Hotel"),jP=ye(a.jsx("path",{d:"M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2M8.5 13.5l2.5 3.01L14.5 12l4.5 6H5z"}),"Image"),ZJ=ye(a.jsx("path",{d:"M19 5v14H5V5zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-4.86 8.86-3 3.87L9 13.14 6 17h12z"}),"ImageOutlined"),KJ=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m1 15h-2v-6h2zm0-8h-2V7h2z"}),"Info"),vc=ye(a.jsx("path",{d:"M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm7 7V3.5L18.5 9z"}),"InsertDriveFile"),QJ=ye(a.jsx("path",{d:"M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2m-5 12H9v-2h6zm5-7H4V4l16-.02z"}),"Inventory"),w2=ye(a.jsx("path",{d:"M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6z"}),"KeyboardArrowDown"),TP=ye(a.jsx("path",{d:"M7.41 15.41 12 10.83l4.59 4.58L18 14l-6-6-6 6z"}),"KeyboardArrowUp"),JJ=ye(a.jsx("path",{d:"M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"}),"KeyboardReturn"),ch=ye(a.jsx("path",{d:"M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84L22 12z"}),"Label"),RC=ye(a.jsx("path",{d:"M20 18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2H0v2h24v-2zM4 6h16v10H4z"}),"Laptop"),YJ=ye(a.jsx("path",{d:"M4 6H2v14c0 1.1.9 2 2 2h14v-2H4zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2m-1 9H9V9h10zm-4 4H9v-2h6zm4-8H9V5h10z"}),"LibraryBooks"),j2=ye(a.jsx("path",{d:"M3.9 12c0-1.71 1.39-3.1 3.1-3.1h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4v-1.9H7c-1.71 0-3.1-1.39-3.1-3.1M8 13h8v-2H8zm9-6h-4v1.9h4c1.71 0 3.1 1.39 3.1 3.1s-1.39 3.1-3.1 3.1h-4V17h4c2.76 0 5-2.24 5-5s-2.24-5-5-5"}),"Link"),DP=ye(a.jsx("path",{d:"M3 13h2v-2H3zm0 4h2v-2H3zm0-8h2V7H3zm4 4h14v-2H7zm0 4h14v-2H7zM7 7v2h14V7z"}),"List"),XJ=ye(a.jsx("path",{d:"M19 5v14H5V5zm1.1-2H3.9c-.5 0-.9.4-.9.9v16.2c0 .4.4.9.9.9h16.2c.4 0 .9-.5.9-.9V3.9c0-.5-.5-.9-.9-.9M11 7h6v2h-6zm0 4h6v2h-6zm0 4h6v2h-6zM7 7h2v2H7zm0 4h2v2H7zm0 4h2v2H7z"}),"ListAlt"),eY=ye(a.jsx("path",{d:"M19 3H5c-1.1 0-1.99.9-1.99 2L3 19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-1 11h-4v4h-4v-4H6v-4h4V6h4v4h4z"}),"LocalHospital"),tY=ye(a.jsx("path",{d:"m21.41 11.58-9-9C12.05 2.22 11.55 2 11 2H4c-1.1 0-2 .9-2 2v7c0 .55.22 1.05.59 1.42l9 9c.36.36.86.58 1.41.58s1.05-.22 1.41-.59l7-7c.37-.36.59-.86.59-1.41s-.23-1.06-.59-1.42M5.5 7C4.67 7 4 6.33 4 5.5S4.67 4 5.5 4 7 4.67 7 5.5 6.33 7 5.5 7"}),"LocalOffer"),nY=ye(a.jsx("path",{d:"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7m0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5"}),"LocationOn"),rY=ye(a.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2m-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2m3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1z"}),"Lock"),sY=ye(a.jsx("path",{d:"m20.5 3-.16.03L15 5.1 9 3 3.36 4.9c-.21.07-.36.25-.36.48V20.5c0 .28.22.5.5.5l.16-.03L9 18.9l6 2.1 5.64-1.9c.21-.07.36-.25.36-.48V3.5c0-.28-.22-.5-.5-.5M15 19l-6-2.11V5l6 2.11z"}),"Map"),iY=ye(a.jsx("path",{d:"M12 14c1.66 0 2.99-1.34 2.99-3L15 5c0-1.66-1.34-3-3-3S9 3.34 9 5v6c0 1.66 1.34 3 3 3m5.3-3c0 3-2.54 5.1-5.3 5.1S6.7 14 6.7 11H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c3.28-.48 6-3.3 6-6.72z"}),"Mic"),EP=ye(a.jsx("path",{d:"M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2m0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"}),"MoreVert"),oY=ye(a.jsx("path",{d:"m18 4 2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4z"}),"Movie"),aY=ye(a.jsx("path",{d:"M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3z"}),"MusicNote"),lY=ye(a.jsx("path",{d:"M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"}),"NavigateNext"),cY=ye(a.jsx("path",{d:"m22 3-1.67 1.67L18.67 3 17 4.67 15.33 3l-1.66 1.67L12 3l-1.67 1.67L8.67 3 7 4.67 5.33 3 3.67 4.67 2 3v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2zM11 19H4v-6h7zm9 0h-7v-2h7zm0-4h-7v-2h7zm0-4H4V8h16z"}),"Newspaper"),uY=ye(a.jsx("path",{d:"M3 18h12v-2H3zM3 6v2h18V6zm0 7h18v-2H3z"}),"Notes"),dY=ye(a.jsx("path",{d:"m20.5 10 .5-2h-4l1-4h-2l-1 4h-4l1-4h-2L9 8H5l-.5 2h4l-1 4h-4L3 16h4l-1 4h2l1-4h4l-1 4h2l1-4h4l.5-2h-4l1-4zm-7 4h-4l1-4h4z"}),"Numbers"),ip=ye(a.jsx("path",{d:"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z"}),"OpenInNew"),pY=ye(a.jsx("path",{d:"M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2m0 14H4v-6h16zm0-10H4V6h16z"}),"Payment"),RP=ye(a.jsx("path",{d:"M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5s-3 1.34-3 3 1.34 3 3 3m-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5 5 6.34 5 8s1.34 3 3 3m0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5m8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5"}),"People"),Mm=ye(a.jsx("path",{d:"M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4m0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4"}),"Person"),fY=ye(a.jsx("path",{d:"M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02z"}),"Phone"),hY=ye([a.jsx("circle",{cx:"12",cy:"12",r:"3.2"},"0"),a.jsx("path",{d:"M9 2 7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2h-3.17L15 2zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5"},"1")],"PhotoCamera"),Fx=ye(a.jsx("path",{d:"M20 2H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2m-8.5 7.5c0 .83-.67 1.5-1.5 1.5H9v2H7.5V7H10c.83 0 1.5.67 1.5 1.5zm5 2c0 .83-.67 1.5-1.5 1.5h-2.5V7H15c.83 0 1.5.67 1.5 1.5zm4-3H19v1h1.5V11H19v2h-1.5V7h3zM9 9.5h1v-1H9zM4 6H2v14c0 1.1.9 2 2 2h14v-2H4zm10 5.5h1v-3h-1z"}),"PictureAsPdf"),mY=ye(a.jsx("path",{d:"M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7m0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5"}),"Place"),gY=ye(a.jsx("path",{d:"M8 5v14l11-7z"}),"PlayArrow"),yY=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2M9.5 16.5v-9l7 4.5z"}),"PlayCircle"),kC=ye(a.jsx("path",{d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39"}),"Public"),vY=ye(a.jsx("path",{d:"M18 17H6v-2h12zm0-4H6v-2h12zm0-4H6V7h12zM3 22l1.5-1.5L6 22l1.5-1.5L9 22l1.5-1.5L12 22l1.5-1.5L15 22l1.5-1.5L18 22l1.5-1.5L21 22V2l-1.5 1.5L18 2l-1.5 1.5L15 2l-1.5 1.5L12 2l-1.5 1.5L9 2 7.5 3.5 6 2 4.5 3.5 3 2z"}),"Receipt"),kP=ye(a.jsx("path",{d:"M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4z"}),"Refresh"),xY=ye(a.jsx("path",{d:"M11 9H9V2H7v7H5V2H3v7c0 2.12 1.66 3.84 3.75 3.97V22h2.5v-9.03C11.34 12.84 13 11.12 13 9V2h-2zm5-3v8h2.5v8H21V2c-2.76 0-5 2.24-5 4"}),"Restaurant"),bY=ye(a.jsx("path",{d:"M12 2.5s4.5 2.04 4.5 10.5c0 2.49-1.04 5.57-1.6 7H9.1c-.56-1.43-1.6-4.51-1.6-7C7.5 4.54 12 2.5 12 2.5m2 8.5c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2m-6.31 9.52c-.48-1.23-1.52-4.17-1.67-6.87l-1.13.75c-.56.38-.89 1-.89 1.67V22zM20 22v-5.93c0-.67-.33-1.29-.89-1.66l-1.13-.75c-.15 2.69-1.2 5.64-1.67 6.87z"}),"Rocket"),na=ye(a.jsx("path",{d:"M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3m3-10H5V5h10z"}),"Save"),SY=ye([a.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),a.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")],"Schedule"),CY=ye(a.jsx("path",{d:"M14 9v2h-3V9H8.5V7H11V1H4v6h2.5v2H4v6h2.5v2H4v6h7v-6H8.5v-2H11v-2h3v2h7V9z"}),"Schema"),wY=ye(a.jsx("path",{d:"M5 13.18v4L12 21l7-3.82v-4L12 17zM12 3 1 9l11 6 9-4.91V17h2V9z"}),"School"),Om=ye(a.jsx("path",{d:"M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14"}),"Search"),Bx=ye(a.jsx("path",{d:"M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.09.63-.09.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6"}),"Settings"),jY=ye(a.jsx("path",{d:"M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2M1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2"}),"ShoppingCart"),MP=ye(a.jsx("path",{d:"M12 17.27 18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"}),"Star"),TY=ye(a.jsx("path",{d:"m22 9.24-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28z"}),"StarBorder"),DY=ye(a.jsx("path",{d:"M20 4H4v2h16zm1 10v-2l-1-5H4l-1 5v2h1v6h10v-6h4v6h2v-6zm-9 4H6v-4h6z"}),"Store"),EY=ye(a.jsx("path",{d:"m21.9 8.89-1.05-4.37c-.22-.9-1-1.52-1.91-1.52H5.05c-.9 0-1.69.63-1.9 1.52L2.1 8.89c-.24 1.02-.02 2.06.62 2.88.08.11.19.19.28.29V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-6.94c.09-.09.2-.18.28-.28.64-.82.87-1.87.62-2.89m-2.99-3.9 1.05 4.37c.1.42.01.84-.25 1.17-.14.18-.44.47-.94.47-.61 0-1.14-.49-1.21-1.14L16.98 5zM13 5h1.96l.54 4.52c.05.39-.07.78-.33 1.07-.22.26-.54.41-.95.41-.67 0-1.22-.59-1.22-1.31zM8.49 9.52 9.04 5H11v4.69c0 .72-.55 1.31-1.29 1.31-.34 0-.65-.15-.89-.41-.25-.29-.37-.68-.33-1.07m-4.45-.16L5.05 5h1.97l-.58 4.86c-.08.65-.6 1.14-1.21 1.14-.49 0-.8-.29-.93-.47-.27-.32-.36-.75-.26-1.17M5 19v-6.03c.08.01.15.03.23.03.87 0 1.66-.36 2.24-.95.6.6 1.4.95 2.31.95.87 0 1.65-.36 2.23-.93.59.57 1.39.93 2.29.93.84 0 1.64-.35 2.24-.95.58.59 1.37.95 2.24.95.08 0 .15-.02.23-.03V19z"}),"Storefront"),RY=ye(a.jsx("path",{d:"M16.5 12c1.38 0 2.49-1.12 2.49-2.5S17.88 7 16.5 7 14 8.12 14 9.5s1.12 2.5 2.5 2.5M9 11c1.66 0 2.99-1.34 2.99-3S10.66 5 9 5 6 6.34 6 8s1.34 3 3 3m7.5 3c-1.83 0-5.5.92-5.5 2.75V19h11v-2.25c0-1.83-3.67-2.75-5.5-2.75M9 13c-2.33 0-7 1.17-7 3.5V19h7v-2.25c0-.85.33-2.34 2.37-3.47C10.5 13.1 9.66 13 9 13"}),"SupervisorAccount"),OP=ye(a.jsx("path",{d:"M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 1.01-.25 1.97-.7 2.8l1.46 1.46C19.54 15.03 20 13.57 20 12c0-4.42-3.58-8-8-8m0 14c-3.31 0-6-2.69-6-6 0-1.01.25-1.97.7-2.8L5.24 7.74C4.46 8.97 4 10.43 4 12c0 4.42 3.58 8 8 8v3l4-4-4-4z"}),"Sync"),T2=ye(a.jsx("path",{d:"M2.5 4v3h5v12h3V7h5V4zm19 5h-9v3h3v7h3v-7h3z"}),"TextFields"),kY=ye(a.jsx("path",{d:"M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2M9 11H7V9h2zm4 0h-2V9h2zm4 0h-2V9h2z"}),"Textsms"),MY=ye(a.jsx("path",{d:"M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V8h14zM7 10h5v5H7z"}),"Today"),OY=ye(a.jsx("path",{d:"M17 7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h10c2.76 0 5-2.24 5-5s-2.24-5-5-5m0 8c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3"}),"ToggleOn"),AY=ye(a.jsx("path",{d:"m16 6 2.29 2.29-4.88 4.88-4-4L2 16.59 3.41 18l6-6 4 4 6.3-6.29L22 12V6z"}),"TrendingUp"),_Y=ye(a.jsx("path",{d:"M3 17v2h6v-2zM3 5v2h10V5zm10 16v-2h8v-2h-8v-2h-2v6zM7 9v2H3v2h4v2h2V9zm14 4v-2H11v2zm-6-4h2V7h4V5h-4V3h-2z"}),"Tune"),IY=ye(a.jsx("path",{d:"M14 2H6.01c-1.1 0-2 .89-2 2L4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V8zm-1 7V3.5L18.5 9zm1 5 2-1.06v4.12L14 16v1c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h4c.55 0 1 .45 1 1z"}),"VideoFile"),PY=ye(a.jsx("path",{d:"M17 10.5V7c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1v-3.5l4 4v-11z"}),"Videocam"),AP=ye(a.jsx("path",{d:"M3 14h4v-4H3zm0 5h4v-4H3zM3 9h4V5H3zm5 5h13v-4H8zm0 5h13v-4H8zM8 5v4h13V5z"}),"ViewList"),_P=ye(a.jsx("path",{d:"M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5M12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5m0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3"}),"Visibility"),LY=ye(a.jsx("path",{d:"M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7M2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2m4.31-.78 3.15 3.15.02-.16c0-1.66-1.34-3-3-3z"}),"VisibilityOff"),zY=ye(a.jsx("path",{d:"M3 9v6h4l5 5V4L7 9zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02M14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77"}),"VolumeUp"),IP=ye(a.jsx("path",{d:"M1 21h22L12 2zm12-3h-2v-2h2zm0-4h-2v-4h2z"}),"Warning"),$Y=ye(a.jsx("path",{d:"M20 6h-4V4c0-1.11-.89-2-2-2h-4c-1.11 0-2 .89-2 2v2H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2m-6 0h-4V4h4z"}),"Work");class NY{constructor(e){this.deps=e}getState(){return this.deps.presenter.getState()}isAvailable(){var n,r;return((r=(n=this.deps.authPresenter.getState().currentUser)==null?void 0:n.permissions)==null?void 0:r.canViewUsers)===!0}startSimulation(e,n,r,s){return this.isAvailable()?(this.deps.presenter.startSimulation(e,n,r,s),oe.info("SimulationUseCase.startSimulation",{displayName:r,roleTemplate:n}),!0):(oe.warn("SimulationUseCase.startSimulation: not available"),!1)}stopSimulation(){this.deps.presenter.stopSimulation(),oe.info("SimulationUseCase.stopSimulation")}setTemplate(e){const n=Ih(e);this.deps.presenter.updatePermissions(n,e)}setPermission(e,n){const r=this.deps.presenter.getState();if(!r.virtualPermissions)return;const s={...r.virtualPermissions,[e]:n},i=_h(s);this.deps.presenter.updatePermissions(s,i)}updatePermissions(e){const n=_h(e);this.deps.presenter.updatePermissions(e,n)}getEffectivePermissions(){const e=this.deps.presenter.getState();return e.isActive&&e.virtualPermissions?e.virtualPermissions:this.deps.authPresenter.getState().permissions}getEffectiveRoleTemplate(){const e=this.deps.presenter.getState();return e.isActive&&e.virtualRoleTemplate?e.virtualRoleTemplate:this.deps.authPresenter.getState().roleTemplate}}const FY=t=>Px.subscribe(t),HM=()=>Px.getState();function D2(){return b.useSyncExternalStore(FY,HM,HM),{simulationUseCase:new NY({presenter:Px,authPresenter:Em})}}function PP({open:t,onClose:e,onDiscard:n,onContinue:r,conflicts:s=[],isLoading:i=!1}){const l=ur(),u=async()=>{await n(),e()},p=()=>{r(),e()},f=(m,g)=>{e(),l({to:"/contents/$contentTypeId/$contentId",params:{contentTypeId:m,contentId:g}})};return a.jsxs(Qt,{open:t,onClose:e,maxWidth:"sm",fullWidth:!0,children:[a.jsxs(Yt,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(IP,{color:"warning"}),"コンフリクトが発生しました"]}),a.jsxs(Jt,{children:[a.jsx(zt,{severity:"warning",sx:{mb:2},children:"共有ブランチと個人ブランチで同じファイルが変更されています。"}),s.length>0&&a.jsxs(a.Fragment,{children:[a.jsxs(G,{variant:"subtitle2",gutterBottom:!0,children:["コンフリクトしているコンテンツ (",s.length,"件):"]}),a.jsx(as,{dense:!0,sx:{mb:2,bgcolor:"grey.50",borderRadius:1},children:s.map(m=>a.jsxs(os,{onClick:()=>f(m.contentTypeId,m.contentId),children:[a.jsx(Un,{children:a.jsx(Tp,{fontSize:"small"})}),a.jsx(Zn,{primary:m.contentId,secondary:`${m.contentTypeId}`})]},m.path))}),a.jsx(wo,{sx:{my:2}})]}),a.jsx(G,{variant:"body1",gutterBottom:!0,children:"以下のいずれかを選択してください:"}),a.jsxs(B,{sx:{mt:2},children:[a.jsx(G,{variant:"subtitle2",color:"error.main",gutterBottom:!0,children:"コンフリクトを破棄"}),a.jsx(G,{variant:"body2",color:"text.secondary",sx:{ml:2,mb:2},children:s.length>0?`上記 ${s.length} 件のコンテンツのみ共有ブランチの内容で上書きします。他の変更は保持されます。`:"個人ブランチの変更を破棄し、共有ブランチの内容で上書きします。"}),a.jsx(G,{variant:"subtitle2",color:"info.main",gutterBottom:!0,children:"このまま作業を続ける"}),a.jsx(G,{variant:"body2",color:"text.secondary",sx:{ml:2},children:"コンフリクトを無視して編集を続けます。 後で「共有ブランチに送る」際に再度コンフリクトを解消する必要があります。"})]})]}),a.jsxs(rn,{sx:{px:3,pb:2},children:[a.jsx(pe,{onClick:p,disabled:i,children:"このまま作業を続ける"}),a.jsx(pe,{onClick:u,color:"error",variant:"contained",disabled:i,startIcon:i?a.jsx(ut,{size:16}):void 0,children:s.length>0?"コンフリクトを破棄":"破棄して共有ブランチに戻す"})]})]})}const Ux=t=>Rm.subscribe(t),oc=()=>Rm.getState();function BY({branchUseCase:t}){const[e,n]=b.useState(null);b.useSyncExternalStore(Ux,oc,oc);const r=t.getState(),s=f=>{n(f.currentTarget)},i=()=>{n(null)},l=async()=>{i(),await t.switchToDevelop(),window.location.reload()},u=async()=>{i(),await t.switchToPersonal(),window.location.reload()},p=r.branchType==="develop";return a.jsxs(B,{children:[a.jsx(pe,{variant:"outlined",size:"small",color:p?"info":"success",onClick:s,startIcon:r.isLoading?a.jsx(ut,{size:16}):a.jsx(mP,{}),endIcon:a.jsx(w2,{}),disabled:r.isLoading,sx:{textTransform:"none"},children:p?"共有ブランチ":"個人ブランチ"}),a.jsxs(Cp,{anchorEl:e,open:!!e,onClose:i,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},children:[a.jsxs(nt,{onClick:l,children:[a.jsx(Un,{children:p?a.jsx(Ph,{fontSize:"small"}):a.jsx(Nx,{fontSize:"small"})}),a.jsx(Zn,{primary:"共有ブランチ",secondary:r.developBranchName})]}),a.jsxs(nt,{onClick:u,children:[a.jsx(Un,{children:p?a.jsx(Mm,{fontSize:"small"}):a.jsx(Ph,{fontSize:"small"})}),a.jsx(Zn,{primary:"個人ブランチ",secondary:r.personalBranchName})]})]})]})}function UY({branchUseCase:t,onClick:e}){b.useSyncExternalStore(Ux,oc,oc);const n=t.getState(),r=n.branchType==="develop",s=n.isSyncing?a.jsx(ut,{size:16,color:"inherit"}):r?a.jsx(Nx,{}):a.jsx(Mm,{}),i=a.jsx(Ht,{icon:s,label:r?"共有":"個人",size:"small",color:r?"info":"success",variant:"outlined",onClick:e,sx:{mr:1,cursor:e?"pointer":"default"}});if(n.isSyncing)return a.jsx(Er,{title:"GitHub と同期中...",arrow:!0,children:a.jsx(xv,{badgeContent:n.diffCount,color:"warning",max:99,invisible:!n.hasDiff,children:i})});if(!r&&n.hasDiff)return a.jsx(Er,{title:`共有ブランチより ${n.diffCount} コミット進んでいます`,arrow:!0,children:a.jsx(xv,{badgeContent:n.diffCount,color:"warning",max:99,children:i})});const l=r?"共有ブランチで作業中":"個人ブランチで作業中";return a.jsx(Er,{title:l,arrow:!0,children:i})}function VY({branchUseCase:t}){const[e,n]=b.useState(!1),r=b.useSyncExternalStore(Ux,oc,oc);if(r.branchType==="develop"||!r.hasDiff&&r.behindCount===0)return null;const s=async()=>{await t.rebaseFromDevelop()&&n(!0)},i=async()=>{r.conflicts.length>0?await t.discardConflictingFiles():await t.discardPersonalChanges()},l=()=>{t.getState()};return r.behindCount>0?a.jsxs(a.Fragment,{children:[a.jsxs(zt,{severity:"warning",icon:a.jsx(OP,{}),action:a.jsx(pe,{color:"inherit",size:"small",onClick:s,disabled:r.isLoading,children:"最新を取り込む"}),sx:{mb:2},children:[a.jsxs(bI,{children:["共有ブランチが ",r.behindCount," コミット先に進んでいます"]}),r.hasDiff?`個人ブランチは ${r.diffCount} コミット進んでいます。「最新を取り込む」で共有ブランチの変更を反映できます。反映には数分かかることがあります。`:"「最新を取り込む」で共有ブランチの変更を反映できます。反映には数分かかることがあります。"]}),a.jsx(PP,{open:e,onClose:()=>n(!1),onDiscard:i,onContinue:l,conflicts:r.conflicts,isLoading:r.isLoading})]}):a.jsx(HY,{branchUseCase:t})}function HY({branchUseCase:t}){const e=ur(),[n,r]=b.useState(!1),[s,i]=b.useState(!1),[l,u]=b.useState(!1),p=b.useSyncExternalStore(Ux,oc,oc),f=async()=>{await t.fetchChangedContents(),r(!0)},m=()=>{r(!1)},g=(D,M)=>{r(!1),e({to:"/contents/$contentTypeId/$contentId",params:{contentTypeId:D,contentId:M}})},y=async()=>{i(!1),(await t.mergeToDevelop()).hasConflict&&u(!0)},v=async()=>{await t.discardConflictingFiles(),u(!1)},C=()=>{u(!1)},S=D=>{switch(D){case"added":return a.jsx(Qn,{color:"success",fontSize:"small"});case"modified":return a.jsx(Ri,{color:"info",fontSize:"small"});case"removed":return a.jsx(zn,{color:"error",fontSize:"small"})}},j=D=>{switch(D){case"added":return"追加";case"modified":return"変更";case"removed":return"削除"}};return a.jsxs(a.Fragment,{children:[a.jsxs(zt,{severity:"info",icon:a.jsx(OP,{}),sx:{mb:2},children:[a.jsx(bI,{children:"共有ブランチに反映されていない変更があります"}),a.jsx(B,{sx:{mb:1},children:"個人ブランチで作業中です。完了したら「共有ブランチに反映」で変更を反映してください。反映には数分かかることがあります。"}),a.jsxs(B,{sx:{display:"flex",gap:1,flexWrap:"wrap"},children:[a.jsx(pe,{color:"inherit",size:"small",onClick:f,disabled:p.isLoading,startIcon:a.jsx(Om,{}),variant:"outlined",children:"変更を確認"}),a.jsx(pe,{color:"primary",size:"small",onClick:()=>i(!0),disabled:p.isLoading,variant:"contained",children:"共有ブランチに反映"})]})]}),a.jsx(WY,{open:n,onClose:m,contents:p.changedContents,isLoading:p.isLoading,onNavigate:g,getStatusIcon:S,getStatusLabel:j}),a.jsxs(Qt,{open:s,onClose:()=>i(!1),children:[a.jsx(Yt,{children:"共有ブランチに反映"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{py:1},children:["個人ブランチの変更を共有ブランチに反映しますか?",a.jsx("br",{}),"チームメンバー全員がこの変更を確認できるようになります。"]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>i(!1),disabled:p.isLoading,children:"キャンセル"}),a.jsx(pe,{onClick:y,color:"primary",variant:"contained",disabled:p.isLoading,startIcon:p.isLoading?a.jsx(ut,{size:16}):void 0,children:"反映する"})]})]}),a.jsx(PP,{open:l,onClose:()=>u(!1),onDiscard:v,onContinue:C,conflicts:p.conflicts,isLoading:p.isLoading})]})}function WY({open:t,onClose:e,contents:n,isLoading:r,onNavigate:s,getStatusIcon:i,getStatusLabel:l}){return a.jsxs(Qt,{open:t,onClose:e,maxWidth:"sm",fullWidth:!0,children:[a.jsx(Yt,{children:"変更されたコンテンツ"}),a.jsx(Jt,{children:r?a.jsx(B,{sx:{display:"flex",justifyContent:"center",py:4},children:a.jsx(ut,{})}):n.length===0?a.jsx(B,{sx:{py:2,textAlign:"center",color:"text.secondary"},children:"変更されたコンテンツはありません"}):a.jsxs(a.Fragment,{children:[a.jsxs(B,{sx:{mb:1,color:"text.secondary",fontSize:"0.875rem"},children:[n.length,"件の変更があります"]}),a.jsx(as,{children:n.map(u=>a.jsxs(os,{onClick:()=>s(u.contentTypeId,u.contentId),children:[a.jsx(Un,{children:i(u.status)}),a.jsx(Zn,{primary:u.contentId,secondary:`${u.contentTypeId} / ${u.basePath==="private"?"下書き":"公開済み"} (${l(u.status)})`})]},`${u.basePath}/${u.contentTypeId}/${u.contentId}`))})]})})]})}const qY="/assets/logo-DRV9kVVU.png",WM="develop";function qM(t){switch(t){case"owner":case"admin":return"error";case"developer":return"warning";case"editor":return"primary";case"viewer":return"default";case"custom":default:return"success"}}function GY(){const t=ta().siteTitle,e=ta().productionUrl,{authUseCase:n}=rr(),{branchUseCase:r}=Ei(),{simulationUseCase:s}=D2(),{githubUser:i,currentUser:l,token:u,roleTemplate:p,allowPersonalBranch:f}=n.getState(),m=s.getState(),g=r==null?void 0:r.getState(),y=ur(),v=ys(),[C,S]=b.useState(null),[j,D]=b.useState(!1),[M,T]=b.useState(!1),[E,k]=b.useState(!1),[A,O]=b.useState(""),[I,$]=b.useState("success"),R=jn(uu.AdminDataQueryParams(u,WM)),P=Pn(uu.SaveAdminDataMutationParams(v,u,WM)),z=te=>{S(te.currentTarget)},N=()=>{S(null)},H=()=>{N(),n.logout(),y({to:"/login"})},U=async()=>{N(),await(r==null?void 0:r.switchToDevelop())},L=async()=>{N(),await(r==null?void 0:r.switchToPersonal())},W=()=>{N(),s.stopSimulation()},K=()=>{N(),D(!0)},Q=()=>{D(!1)},le=()=>{N(),T(!0)},F=()=>{T(!1)},J=async()=>{const te=m;if(!te.isActive||!te.virtualPermissions||!te.simulatedGithubUsername){O("シミュレーションがアクティブではありません"),$("error"),k(!0),T(!1);return}const de=R.data;if(!de){O("ユーザーデータを取得できませんでした"),$("error"),k(!0),T(!1);return}const fe=de.users.find(we=>we.githubUsername===te.simulatedGithubUsername);if(!fe){O("対象ユーザーが見つかりません"),$("error"),k(!0),T(!1);return}const Re={...fe,permissions:te.virtualPermissions},Pe=de.users.map(we=>we.githubUsername===te.simulatedGithubUsername?Re:we),$e={...de,users:Pe};try{await P.mutateAsync($e),O("ユーザー設定に反映しました"),$("success")}catch{O("反映に失敗しました"),$("error")}k(!0),T(!1)};if(!i||!l)return null;const ie=(g==null?void 0:g.branchType)==="develop";return a.jsxs(nV,{"data-component-name":"cmp:AppBar",position:"static",color:"default",elevation:1,sx:{bgcolor:"white"},children:[a.jsxs(iK,{children:[a.jsx(ft,{component:gs,to:"/",sx:{mr:1,p:.5},children:a.jsx("img",{src:qY,alt:"ダッシュボード",style:{width:32,height:32}})}),t?a.jsxs(B,{sx:{display:"flex",flexDirection:{xs:"column",sm:"row"},alignItems:{xs:"flex-start",sm:"baseline"},gap:{xs:0,sm:1}},children:[a.jsx(G,{variant:"h6",sx:{lineHeight:1.2},children:t}),e&&a.jsxs(G,{variant:"body2",component:"a",href:e,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.secondary",textDecoration:"none","&:hover":{textDecoration:"underline"},lineHeight:1.2},children:[a.jsx(B,{component:"span",sx:{display:{xs:"none",sm:"inline"}},children:"- "}),e]})]}):a.jsx(G,{variant:"h6",children:"Frelio CMS"}),a.jsx(B,{sx:{flexGrow:1}}),r&&f&&a.jsx(UY,{branchUseCase:r,onClick:z}),a.jsx(ft,{"data-testid":"avatar-menu-button",onClick:z,sx:{p:0},children:a.jsx(o7,{src:i.avatar_url,alt:i.login,sx:{width:32,height:32}})}),a.jsxs(Cp,{anchorEl:C,open:!!C,onClose:N,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[a.jsxs(B,{sx:{px:3,py:1.5},children:[a.jsx(G,{variant:"body1",fontWeight:"bold",children:l.displayName||i.name||i.login}),a.jsxs(G,{variant:"body2",color:"text.secondary",children:["@",i.login]}),p&&a.jsx(Ht,{label:Tv(p),color:qM(p),size:"small",sx:{mt:1}})]}),a.jsx(wo,{}),f&&[a.jsxs(nt,{onClick:U,children:[a.jsx(Un,{children:ie?a.jsx(Ph,{fontSize:"small"}):a.jsx(Nx,{fontSize:"small"})}),a.jsx(Zn,{primary:"共有ブランチ",secondary:g==null?void 0:g.developBranchName})]},"develop"),a.jsxs(nt,{onClick:L,children:[a.jsx(Un,{children:ie?a.jsx(Mm,{fontSize:"small"}):a.jsx(Ph,{fontSize:"small"})}),a.jsx(Zn,{primary:"個人ブランチ",secondary:g==null?void 0:g.personalBranchName})]},"personal"),a.jsx(wo,{},"divider")],a.jsx(nt,{onClick:H,children:"ログアウト"}),m.isActive&&[a.jsx(wo,{},"sim-divider"),a.jsxs(B,{sx:{px:3,py:1.5,bgcolor:"warning.light"},children:[a.jsx(G,{variant:"caption",color:"warning.dark",fontWeight:"bold",children:"UI再現モード"}),a.jsx(G,{variant:"body2",fontWeight:"bold",children:m.simulatedUserDisplayName}),a.jsx(Ht,{label:m.virtualRoleTemplate?Tv(m.virtualRoleTemplate):"",color:m.virtualRoleTemplate?qM(m.virtualRoleTemplate):"default",size:"small",sx:{mt:.5}})]},"sim-info"),a.jsxs(nt,{onClick:K,sx:{color:"warning.main"},children:[a.jsx(Un,{sx:{color:"warning.main"},children:a.jsx(Ri,{fontSize:"small"})}),a.jsx(Zn,{primary:"権限を編集"})]},"sim-edit"),a.jsxs(nt,{onClick:le,sx:{color:"warning.main"},children:[a.jsx(Un,{sx:{color:"warning.main"},children:a.jsx(na,{fontSize:"small"})}),a.jsx(Zn,{primary:"ユーザーに反映"})]},"sim-apply"),a.jsxs(nt,{onClick:W,sx:{color:"warning.main"},children:[a.jsx(Un,{sx:{color:"warning.main"},children:a.jsx($x,{fontSize:"small"})}),a.jsx(Zn,{primary:"UI再現を終了"})]},"sim-stop")]]})]}),a.jsx(ZY,{open:j,onClose:Q,simulationUseCase:s}),a.jsxs(Qt,{"data-component-name":"cmp:ApplyToUserDialog",open:M,onClose:F,children:[a.jsx(Yt,{children:"ユーザーに反映"}),a.jsxs(Jt,{children:[a.jsxs(G,{children:["シミュレーション中の権限を「",m.simulatedUserDisplayName,"」に反映しますか?"]}),a.jsx(G,{variant:"body2",color:"text.secondary",sx:{mt:1},children:"この操作は実際のユーザー設定を更新します。"})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:F,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:J,children:"反映"})]})]}),a.jsx(ea,{open:E,autoHideDuration:4e3,onClose:()=>k(!1),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:()=>k(!1),severity:I,sx:{width:"100%"},children:A})})]})}function ZY({open:t,onClose:e,simulationUseCase:n}){const r=n.getState(),s=r.virtualPermissions,i=r.virtualRoleTemplate;if(!s||!i)return null;const l=p=>{n.setTemplate(p)},u=(p,f)=>{if(n.setPermission(p,f),f){const m=Sv.find(g=>g.edit===p);m&&n.setPermission(m.view,!0)}if(!f){const m=Sv.find(g=>g.view===p);m&&n.setPermission(m.edit,!1)}};return a.jsxs(Qt,{"data-component-name":"cmp:SimulationEditDialog",open:t,onClose:e,maxWidth:"sm",fullWidth:!0,children:[a.jsx(Yt,{children:"権限を編集"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1},children:[a.jsxs(_n,{fullWidth:!0,children:[a.jsx(nr,{children:"ロール"}),a.jsxs(wn,{value:i,label:"ロール",onChange:p=>l(p.target.value),children:[a.jsx(nt,{value:"admin",children:"管理者"}),a.jsx(nt,{value:"developer",children:"開発者"}),a.jsx(nt,{value:"editor",children:"編集者"}),a.jsx(nt,{value:"viewer",children:"閲覧者"}),a.jsx(nt,{value:"custom",children:"カスタム"})]})]}),a.jsxs(_s,{defaultExpanded:i==="custom",sx:{boxShadow:"none",border:1,borderColor:"divider","&:before":{display:"none"}},children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(G,{children:"権限の詳細"})}),a.jsx(Is,{sx:{pt:0},children:a.jsx(Ro,{spacing:2,children:Object.entries(uP).map(([p,f])=>a.jsxs(B,{children:[a.jsx(G,{variant:"subtitle2",color:"text.secondary",sx:{mb:.5},children:f.label}),a.jsx(B,{sx:{display:"flex",flexDirection:"column",ml:1,gap:.5},children:f.pairs.map(m=>a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(G,{variant:"body2",sx:{minWidth:100},children:dP[m.view]}),a.jsx(_r,{control:a.jsx(es,{checked:s[m.view],onChange:g=>u(m.view,g.target.checked),size:"small"}),label:"閲覧",sx:{mr:0}}),a.jsx(_r,{control:a.jsx(es,{checked:s[m.edit],onChange:g=>u(m.edit,g.target.checked),size:"small"}),label:"編集",sx:{mr:0}})]},m.view))})]},p))})})]})]})}),a.jsx(rn,{children:a.jsx(pe,{onClick:e,children:"閉じる"})})]})}function GM(){const{open:t,message:e,severity:n}=b.useSyncExternalStore(Pd.subscribe,Pd.getSnapshot),r=(s,i)=>{i!=="clickaway"&&Pd.dismiss()};return a.jsx(ea,{"data-component-name":"cmp:GlobalSnackbar",open:t,onClose:r,autoHideDuration:n==="error"?null:6e3,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:r,severity:n,variant:"filled",sx:{whiteSpace:"pre-line",maxWidth:600},children:e})})}function KY({useCase:t}){const{activeTab:e,fileTabEnabled:n}=t.getState(),r=(i,l)=>{t.setActiveTab(l)},s=()=>{t.close()};return a.jsxs(B,{"data-component-name":"cmp:ActivityLogHeader",sx:{borderBottom:1,borderColor:"divider"},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",px:2,py:1},children:[a.jsx(G,{variant:"subtitle2",fontWeight:"bold",children:"アクティビティログ"}),a.jsx(Er,{title:"閉じる",children:a.jsx(ft,{size:"small",onClick:s,children:a.jsx(Jl,{fontSize:"small"})})})]}),a.jsxs(_K,{value:e,onChange:r,variant:"fullWidth",sx:{minHeight:36,"& .MuiTab-root":{minHeight:36,py:.5,fontSize:"0.75rem"}},children:[a.jsx(hM,{value:"folder",label:"フォルダ",icon:a.jsx(ic,{sx:{fontSize:16}}),iconPosition:"start",sx:{minHeight:36}}),a.jsx(hM,{value:"file",label:"ファイル",icon:a.jsx(vc,{sx:{fontSize:16}}),iconPosition:"start",disabled:!n,sx:{minHeight:36}})]})]})}function QY(t){const n=new Date().getTime()-t.getTime(),r=Math.floor(n/1e3),s=Math.floor(r/60),i=Math.floor(s/60),l=Math.floor(i/24);return l>0?`${l}日前`:i>0?`${i}時間前`:s>0?`${s}分前`:"今"}function JY({commit:t,showViewButton:e,onViewContent:n}){const r=()=>{n==null||n(t.sha)},s=t.message.split(`
386
+ `)[0];return a.jsxs(B,{"data-component-name":"cmp:ActivityLogItem",sx:{px:2,py:1.5,borderBottom:1,borderColor:"divider","&:hover":{bgcolor:"action.hover"}},children:[a.jsx(G,{variant:"body2",sx:{fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",mb:.5},title:s,children:s}),a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(Ht,{label:t.authorDisplayName,size:"small",sx:{height:20,fontSize:"0.7rem","& .MuiChip-label":{px:1}}}),a.jsx(G,{variant:"caption",color:"text.secondary",children:QY(t.date)}),a.jsx(G,{variant:"caption",color:"text.disabled",sx:{ml:"auto"},children:t.shortSha}),e&&a.jsx(Er,{title:"この時点のファイルを表示",children:a.jsx(ft,{size:"small",onClick:r,sx:{ml:.5},children:a.jsx(_P,{sx:{fontSize:16}})})})]})]})}function ZM({commits:t,isLoading:e,isFetchingMore:n,hasMore:r,error:s,showViewButton:i,onLoadMore:l,onViewContent:u}){return e?a.jsx(B,{"data-component-name":"cmp:ActivityLogList",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",p:3},children:a.jsx(ut,{size:24})}):s?a.jsx(B,{"data-component-name":"cmp:ActivityLogList",sx:{flex:1,p:2},children:a.jsx(zt,{severity:"error",sx:{fontSize:"0.75rem"},children:s.message})}):t.length===0?a.jsx(B,{"data-component-name":"cmp:ActivityLogList",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center",p:3},children:a.jsx(G,{variant:"body2",color:"text.secondary",children:"履歴がありません"})}):a.jsxs(B,{"data-component-name":"cmp:ActivityLogList",sx:{flex:1,overflow:"auto"},children:[t.map(p=>a.jsx(JY,{commit:p,showViewButton:i,onViewContent:u},p.sha)),r&&a.jsx(B,{sx:{p:2,textAlign:"center"},children:a.jsx(pe,{variant:"text",size:"small",onClick:l,disabled:n,startIcon:n?a.jsx(ut,{size:14}):null,children:n?"読み込み中...":"もっと読み込む"})})]})}function KM({useCase:t}){const{fileContentDialogSha:e,fileContentDialogPath:n}=t.getState(),r=e!==null&&n!==null,[s,i]=b.useState(null),[l,u]=b.useState(!1),[p,f]=b.useState(null),[m,g]=b.useState(!1);b.useEffect(()=>{if(!r||!e){i(null),f(null);return}u(!0),f(null),i(null),t.getFileContentAtCommit(e).then(i).catch(f).finally(()=>u(!1))},[r,e,t]);const y=()=>{t.closeFileContentDialog()},v=async()=>{if(s)try{await navigator.clipboard.writeText(s),g(!0),setTimeout(()=>g(!1),2e3)}catch{}},C=(n==null?void 0:n.split("/").pop())??"ファイル",S=(e==null?void 0:e.slice(0,7))??"";return a.jsxs(Qt,{"data-component-name":"cmp:FileContentDialog",open:r,onClose:y,maxWidth:"md",fullWidth:!0,children:[a.jsxs(Yt,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsxs(G,{variant:"h6",component:"span",sx:{flex:1},children:[C,a.jsxs(G,{variant:"caption",color:"text.secondary",sx:{ml:1},children:["@ ",S]})]}),a.jsx(ft,{size:"small",onClick:y,children:a.jsx($x,{})})]}),a.jsxs(Jt,{dividers:!0,children:[l&&a.jsx(B,{sx:{display:"flex",justifyContent:"center",p:4},children:a.jsx(ut,{})}),p&&a.jsxs(zt,{severity:"error",children:["ファイルの読み込みに失敗しました: ",p.message]}),s!==null&&!l&&!p&&a.jsx(B,{component:"pre",sx:{m:0,p:2,bgcolor:"grey.100",borderRadius:1,overflow:"auto",fontSize:"0.8rem",fontFamily:"monospace",whiteSpace:"pre-wrap",wordBreak:"break-all",maxHeight:"60vh"},children:s})]}),a.jsxs(rn,{children:[a.jsx(pe,{startIcon:a.jsx(bP,{}),onClick:v,disabled:!s||l,children:m?"コピーしました":"コピー"}),a.jsx(pe,{onClick:y,children:"閉じる"})]})]})}const a1=320;function QM({useCase:t}){const e=t.getState(),{activeTab:n,folderCommits:r,fileCommits:s,isFolderLoading:i,isFileLoading:l,isFolderFetchingMore:u,isFileFetchingMore:p,hasFolderMore:f,hasFileMore:m,folderError:g,fileError:y,fileTabEnabled:v}=e,C=()=>{t.loadMoreFolderCommits()},S=()=>{t.loadMoreFileCommits()},j=D=>{t.openFileContentDialog(D)};return a.jsxs(a.Fragment,{children:[a.jsx(KY,{useCase:t}),n==="folder"&&a.jsx(ZM,{commits:r,isLoading:i,isFetchingMore:u,hasMore:f,error:g,showViewButton:!1,onLoadMore:C}),n==="file"&&v&&a.jsx(ZM,{commits:s,isLoading:l,isFetchingMore:p,hasMore:m,error:y,showViewButton:!0,onLoadMore:S,onViewContent:j})]})}function YY(){const t=new URL(window.location.href);return t.searchParams.delete("activity_log"),t.pathname+t.search+t.hash}function XY({useCase:t}){const e=vr(),n=aa(e.breakpoints.down("md")),r=ox(),s=Ns(),{isOpen:i}=t.getState(),u=new URLSearchParams(r.searchStr).get("activity_log")==="1",p=n?u:i,f=b.useRef(u);b.useEffect(()=>{n&&f.current!==u&&(u&&!i?t.open():!u&&i&&t.close(),f.current=u)},[n,u,i,t]);const m=()=>{if(n){const g=YY();s.history.push(g)}t.close()};return n?a.jsxs(a.Fragment,{children:[a.jsx(Cu,{"data-component-name":"cmp:ActivityLogPanel",anchor:"right",open:p,onClose:m,PaperProps:{sx:{width:a1,maxWidth:"100vw"}},children:a.jsx(B,{sx:{display:"flex",flexDirection:"column",height:"100%"},children:a.jsx(QM,{useCase:t})})}),a.jsx(KM,{useCase:t})]}):a.jsxs(a.Fragment,{children:[a.jsx(B,{"data-component-name":"cmp:ActivityLogPanel",sx:{width:p?a1:0,minWidth:p?a1:0,height:"100%",overflow:"hidden",transition:"width 0.2s ease-in-out, min-width 0.2s ease-in-out",borderLeft:p?1:0,borderColor:"divider",bgcolor:"background.paper",display:"flex",flexDirection:"column"},children:p&&a.jsx(QM,{useCase:t})}),a.jsx(KM,{useCase:t})]})}function eX(){const t=new URL(window.location.href);return t.searchParams.set("activity_log","1"),t.pathname+t.search+t.hash}function tX(){const t=new URL(window.location.href);return t.searchParams.delete("activity_log"),t.pathname+t.search+t.hash}function nX({useCase:t}){const e=vr(),n=aa(e.breakpoints.down("md")),r=ox(),s=Ns(),{isOpen:i}=t.getState(),u=new URLSearchParams(r.searchStr).get("activity_log")==="1",p=n?u:i,f=()=>{n?p?(s.history.push(tX()),t.close()):(s.history.push(eX()),t.open()):t.toggle()};return a.jsx(Er,{title:p?"アクティビティログを閉じる":"アクティビティログを開く",placement:"left",children:a.jsx(CW,{"data-component-name":"cmp:ActivityLogToggleButton",size:"small",color:"default",onClick:f,sx:{position:"fixed",bottom:24,right:24,zIndex:m=>m.zIndex.speedDial,bgcolor:"background.paper",boxShadow:2,"&:hover":{bgcolor:"action.hover"}},children:p?a.jsx(Jl,{}):a.jsx(wP,{})})})}const Bs=z$({component:rX});function rX(){const{authUseCase:t}=rr(),{githubUser:e,currentUser:n,isInitialized:r}=t.getState(),s=ur(),i=ox();return b.useEffect(()=>{if(!r)return;const u=i.pathname==="/login",p=i.pathname.startsWith("/auth/callback");if(!e&&!u&&!p){s({to:"/login"});return}if(e&&n&&u){s({to:"/"});return}if(n){const f=gQ(i.pathname);f&&!ws(n,f)&&s({to:"/"})}},[r,e,n,s,i.pathname]),r?i.pathname==="/login"||i.pathname.startsWith("/auth/")?a.jsxs(a.Fragment,{children:[a.jsx(bw,{}),a.jsx(GM,{})]}):a.jsxs(a.Fragment,{children:[a.jsx(sX,{}),a.jsx(GM,{})]}):a.jsx(B,{"data-component-name":"cmp:RootLayoutLoading",display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",children:a.jsx(ut,{})})}function sX(){const{activityLogUseCase:t}=oJ(),{isAvailable:e}=t.getState();return a.jsxs(B,{"data-component-name":"cmp:RootLayout",sx:{display:"flex",flexDirection:"column",height:"100vh"},children:[a.jsx(B,{"data-component-name":"cmp:RootLayoutHeader",component:"header",sx:{position:"sticky",top:0,zIndex:n=>n.zIndex.appBar,flexShrink:0},children:a.jsx(GY,{})}),a.jsxs(B,{"data-component-name":"cmp:RootLayoutBody",sx:{flex:1,overflow:"hidden",display:"flex",flexDirection:"row"},children:[a.jsx(B,{"data-component-name":"cmp:RootLayoutMain",component:"main",sx:{flex:1,overflow:"hidden",display:"flex",flexDirection:"column"},children:a.jsx(bw,{})}),e&&a.jsx(XY,{useCase:t})]}),e&&a.jsx(nX,{useCase:t})]})}const iX=Ss("/login")({component:oX});function oX(){const{authUseCase:t}=rr(),{githubUser:e}=t.getState();if(e)return null;const n=()=>{oe.debug("LoginPage","Login button clicked");try{const r=t.getAuthUrl();oe.debug("LoginPage","Redirecting to auth URL"),window.location.href=r}catch(r){oe.error("LoginPage","Error getting auth URL",{error:r})}};return a.jsx(ji,{"data-component-name":"cmp:LoginPage",maxWidth:"sm",children:a.jsx(B,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",children:a.jsxs($t,{"data-component-name":"cmp:LoginForm",elevation:3,sx:{p:4,textAlign:"center",width:"100%"},children:[a.jsx(G,{variant:"h4",component:"h1",gutterBottom:!0,children:"Frelio CMS"}),a.jsx(G,{variant:"body1",color:"text.secondary",sx:{mb:4},children:"GitHub アカウントでログインしてください"}),a.jsx(pe,{variant:"contained",size:"large",startIcon:a.jsx(UJ,{}),onClick:n,sx:{textTransform:"none"},children:"Login with GitHub"})]})})})}const aX={contentTypes:{}};class Pf{constructor(e,n,r,s){this.queryResult=e,this.mergeStagingMutation=n,this.mergeProductionMutation=r,this.directDeployMutation=s}static QueryParams(e,n,r,s){return{queryKey:["dashboard",n,r,s],queryFn:async()=>{if(!e)return{contentTypes:[],metadata:null,branchLastCommit:{develop:null,staging:null,production:null},branchComparisons:{}};const i=new At(e),u=(await i.fetchJsonOrDefault(Bc,{contentTypes:[]},n)).contentTypes,p=await i.fetchJsonOrDefault(kh,aX,n),f={develop:null,staging:null,production:null};try{const g=await i.getLatestCommitForPath("develop",Qi);g&&(f.develop=g.date)}catch{oe.debug("GitHubDashboardRepositoryImpl.QueryParams: failed to get develop branch info")}try{const g=await i.getLatestCommitForPath("staging",Qi);g&&(f.staging=g.date)}catch{oe.debug("GitHubDashboardRepositoryImpl.QueryParams: failed to get staging branch info")}try{const g=await i.getLatestCommitForPath("main",Qi);g&&(f.production=g.date)}catch{oe.debug("GitHubDashboardRepositoryImpl.QueryParams: failed to get main branch info")}const m={};if(r&&s&&s.length>0)for(const g of s)try{const y=await i.compareBranches(g,r),v=y.files.filter(C=>C.filename.startsWith(Qi));m[g]={ahead:v.length>0?y.ahead:0,behind:y.behind}}catch{oe.debug("GitHubDashboardRepositoryImpl.QueryParams: failed to compare branches",{stagingBranch:g,personalBranchName:r})}return{contentTypes:u,metadata:p,branchLastCommit:f,branchComparisons:m}},enabled:!!e,staleTime:0}}static MergeStagingMutationParams(e,n){return{mutationFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).mergeBranches("staging","develop","Merge develop into staging")},onSuccess:()=>{n.invalidateQueries({queryKey:["dashboard"]})}}}static MergeProductionMutationParams(e,n){return{mutationFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).mergeBranches("main","staging","Merge staging into main")},onSuccess:()=>{n.invalidateQueries({queryKey:["dashboard"]})}}}static DirectDeployMutationParams(e,n){return{mutationFn:async()=>{if(!e)throw new Error("Not authenticated");await new At(e).triggerWorkflow("direct-deploy.yml","main")},onSuccess:()=>{n.invalidateQueries({queryKey:["dashboard"]})}}}getContentTypes(){var e;return((e=this.queryResult.data)==null?void 0:e.contentTypes)??[]}isLoading(){return this.queryResult.isLoading}getLastUpdated(){var r;const e=(r=this.queryResult.data)==null?void 0:r.metadata;if(!(e!=null&&e.contentTypes))return null;const n=Object.values(e.contentTypes).map(s=>s.lastUpdatedAt).filter(s=>!!s).map(s=>new Date(s));return n.length===0?null:new Date(Math.max(...n.map(s=>s.getTime())))}getContentTypeMetadata(e){var n,r;return((r=(n=this.queryResult.data)==null?void 0:n.metadata)==null?void 0:r.contentTypes[e])??null}getMetadata(){var e;return((e=this.queryResult.data)==null?void 0:e.metadata)??null}getStagingLastCommit(){var e,n;return((n=(e=this.queryResult.data)==null?void 0:e.branchLastCommit)==null?void 0:n.staging)??null}getProductionLastCommit(){var e,n;return((n=(e=this.queryResult.data)==null?void 0:e.branchLastCommit)==null?void 0:n.production)??null}getDevelopLastCommit(){var e,n;return((n=(e=this.queryResult.data)==null?void 0:e.branchLastCommit)==null?void 0:n.develop)??null}getBranchComparison(e){var n;return((n=this.queryResult.data)==null?void 0:n.branchComparisons[e])??null}async mergeToStaging(){return this.mergeStagingMutation.mutateAsync()}async mergeToProduction(){return this.mergeProductionMutation.mutateAsync()}async triggerDirectDeploy(){await this.directDeployMutation.mutateAsync()}async refetch(){await this.queryResult.refetch()}}function lX(){return Fs(t=>({deployStatus:"idle",deployTarget:null,deployError:null,setDeployStatus:e=>t({deployStatus:e}),setDeployTarget:e=>t({deployTarget:e}),setDeployError:e=>t({deployError:e})}))}class cX{constructor(){St(this,"store");this.store=lX()}getState(){const{deployStatus:e,deployTarget:n,deployError:r}=this.store.getState();return{deployStatus:e,deployTarget:n,deployError:r}}setDeployStatus(e){this.store.getState().setDeployStatus(e)}setDeployTarget(e){this.store.getState().setDeployTarget(e)}setDeployError(e){this.store.getState().setDeployError(e)}startDeploy(e){this.store.setState({deployStatus:"loading",deployTarget:e,deployError:null})}completeDeploy(){this.store.setState({deployStatus:"success"})}failDeploy(e){this.store.setState({deployStatus:"error",deployError:e})}resetDeployState(){this.store.setState({deployStatus:"idle",deployTarget:null,deployError:null})}subscribe(e){return this.store.subscribe(e)}}class uX{constructor(e,n){this.repository=e,this.presenter=n}getState(){return{contentTypes:this.repository.getContentTypes(),isLoading:this.repository.isLoading(),metadata:this.repository.getMetadata(),developLastCommit:this.repository.getDevelopLastCommit(),stagingLastCommit:this.repository.getStagingLastCommit(),productionLastCommit:this.repository.getProductionLastCommit()}}getButtonStates(){var s,i,l;const e=((s=this.repository.getDevelopLastCommit())==null?void 0:s.getTime())??0,n=((i=this.repository.getStagingLastCommit())==null?void 0:i.getTime())??0,r=((l=this.repository.getProductionLastCommit())==null?void 0:l.getTime())??0;return{previewEnabled:e>n,productionEnabled:n>r,directDeployEnabled:e>r}}getContentTypeMetadata(e){return this.repository.getContentTypeMetadata(e)}formatRelativeTime(e){if(!e)return"";const n=typeof e=="string"?new Date(e):e,s=new Date().getTime()-n.getTime(),i=Math.floor(s/(1e3*60)),l=Math.floor(s/(1e3*60*60)),u=Math.floor(s/(1e3*60*60*24));return i<1?"たった今":i<60?`${i}分前`:l<24?`${l}時間前`:u<7?`${u}日前`:n.toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"})}getBranchComparison(e){return this.repository.getBranchComparison(e)}isPreviewEnabled(e){const n=this.repository.getBranchComparison(e);return((n==null?void 0:n.ahead)??0)>0}getDeployState(){return this.presenter.getState()}resetDeployState(){this.presenter.resetDeployState()}async mergeToStaging(){this.presenter.startDeploy("preview");try{const e=await this.repository.mergeToStaging();return e.hasConflict?(this.presenter.failDeploy("コンフリクトが発生しました。手動で解決してください。"),{success:!1,hasConflict:!0}):(this.presenter.completeDeploy(),await this.repository.refetch(),oe.info("DashboardUseCase.mergeToStaging: completed",{sha:e.sha}),{success:!0,hasConflict:!1})}catch(e){const n=e instanceof Error?e.message:String(e);return this.presenter.failDeploy(n),oe.error("DashboardUseCase.mergeToStaging: failed",{error:n}),{success:!1,hasConflict:!1}}}async mergeToProduction(){this.presenter.startDeploy("production");try{const e=await this.repository.mergeToProduction();return e.hasConflict?(this.presenter.failDeploy("コンフリクトが発生しました。手動で解決してください。"),{success:!1,hasConflict:!0}):(this.presenter.completeDeploy(),await this.repository.refetch(),oe.info("DashboardUseCase.mergeToProduction: completed",{sha:e.sha}),{success:!0,hasConflict:!1})}catch(e){const n=e instanceof Error?e.message:String(e);return this.presenter.failDeploy(n),oe.error("DashboardUseCase.mergeToProduction: failed",{error:n}),{success:!1,hasConflict:!1}}}async directDeploy(){this.presenter.startDeploy("direct");try{return await this.repository.triggerDirectDeploy(),this.presenter.completeDeploy(),oe.info("DashboardUseCase.directDeploy: workflow dispatched"),{success:!0}}catch(e){const n=e instanceof Error?e.message:String(e);return this.presenter.failDeploy(n),oe.error("DashboardUseCase.directDeploy: failed",{error:n}),{success:!1}}}}function LP(){const{authUseCase:t}=rr(),{branchUseCase:e}=Ei(),n=ys(),{token:r,githubUser:s,stagingBranches:i}=t.getState(),l=(e==null?void 0:e.getCurrentBranch())??"develop",u=e==null?void 0:e.getState(),p=(u==null?void 0:u.branchType)==="personal",f=(u==null?void 0:u.currentBranch)??"",m=s?cP(s.login,i):[],g=p?m.map(S=>S.branchName):[],y=new Pf(jn(Pf.QueryParams(r,l,p?f:void 0,g)),Pn(Pf.MergeStagingMutationParams(r,n)),Pn(Pf.MergeProductionMutationParams(r,n)),Pn(Pf.DirectDeployMutationParams(r,n))),v=new cX;return{dashboardUseCase:new uX(y,v)}}const dX="modulepreload",pX=function(t){return"/"+t},JM={},fX=function(e,n,r){let s=Promise.resolve();if(n&&n.length>0){let l=function(f){return Promise.all(f.map(m=>Promise.resolve(m).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const u=document.querySelector("meta[property=csp-nonce]"),p=(u==null?void 0:u.nonce)||(u==null?void 0:u.getAttribute("nonce"));s=l(n.map(f=>{if(f=pX(f),f in JM)return;JM[f]=!0;const m=f.endsWith(".css"),g=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${g}`))return;const y=document.createElement("link");if(y.rel=m?"stylesheet":dX,m||(y.as="script"),y.crossOrigin="",y.href=f,p&&y.setAttribute("nonce",p),document.head.appendChild(y),m)return new Promise((v,C)=>{y.addEventListener("load",v),y.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${f}`)))})}))}function i(l){const u=new Event("vite:preloadError",{cancelable:!0});if(u.payload=l,window.dispatchEvent(u),!u.defaultPrevented)throw l}return s.then(l=>{for(const u of l||[])u.status==="rejected"&&i(u.reason);return e().catch(i)})},YM={Article:km,Description:Tp,Folder:ic,Image:jP,Movie:oY,MusicNote:aY,Book:gJ,Feed:zJ,Newspaper:cY,LibraryBooks:YJ,AutoStories:mJ,Notes:uY,TextFields:T2,Email:_J,Chat:bJ,Forum:BJ,Comment:jJ,ContactPage:TJ,Textsms:kY,Phone:fY,Announcement:dJ,Work:$Y,Store:DY,ShoppingCart:jY,Payment:pY,Receipt:vY,CreditCard:DJ,Inventory:QJ,Analytics:uJ,TrendingUp:AY,Business:vJ,Person:Mm,People:RP,Group:Nx,AccountCircle:lJ,Face:PJ,SupervisorAccount:RY,Event:IJ,CalendarToday:yP,Schedule:SY,AccessTime:aJ,Alarm:cJ,Today:MY,Place:mY,Map:sY,Home:qJ,LocationOn:nY,School:wY,LocalHospital:eY,Restaurant:xY,Hotel:GJ,Storefront:EY,PhotoCamera:hY,Videocam:PY,Mic:iY,Headphones:VJ,PlayCircle:yY,VolumeUp:zY,Settings:Bx,Build:b2,Dashboard:SP,Tune:_Y,Code:S2,Extension:CP,AttachFile:gP,CloudUpload:Ti,FilePresent:$J,PictureAsPdf:Fx,CloudDownload:CJ,Star:MP,Favorite:LJ,Flag:NJ,LocalOffer:tY,Label:ch,Category:xJ,Help:HJ,Info:KJ,CheckCircle:vP,Search:Om,Bookmark:yJ,Link:j2,Public:kC,Lock:rY},Lf={};function MC({iconName:t,sx:e}){const[n,r]=b.useState(null),[s,i]=b.useState(!1);if(YM[t]){const l=YM[t];return a.jsx(l,{sx:e})}return b.useEffect(()=>{if(Lf[t]!==void 0){r(Lf[t]);return}i(!0),fX(()=>import("./index-D36XnvJP.js"),[]).then(l=>{const u=l[t];u?(Lf[t]=u,r(u)):(Lf[t]=null,r(null))}).catch(()=>{Lf[t]=null,r(null)}).finally(()=>{i(!1)})},[t]),s?a.jsx(ut,{size:16,sx:e}):n?a.jsx(n,{sx:e}):a.jsx(km,{sx:e})}function Vx({iconName:t,sx:e}){return a.jsx(MC,{iconName:t,sx:e})}const hX=Ss("/")({component:mX});function mX(){const t=ta().productionUrl,e=ta().previewUrl,{authUseCase:n}=rr(),{branchUseCase:r}=Ei(),{simulationUseCase:s}=D2(),{githubUser:i,currentUser:l,permissions:u,stagingBranches:p,allowPersonalBranch:f}=n.getState(),{dashboardUseCase:m}=LP(),g=s.getEffectivePermissions(),y=l!=null&&l.isOwner&&!s.getState().isActive?Cv:g,{contentTypes:v,isLoading:C,stagingLastCommit:S,productionLastCommit:j}=m.getState(),{previewEnabled:D,productionEnabled:M,directDeployEnabled:T}=m.getButtonStates(),[E,k]=b.useState(!1),A=r==null?void 0:r.getState(),O=(A==null?void 0:A.branchType)==="personal",I=i?cP(i.login,p):[],$=(A==null?void 0:A.currentBranch)??"";if(!i||!l)return null;const R=(y==null?void 0:y.canViewDeploy)??!1,P=(y==null?void 0:y.canEditDeploy)??!1,z=(y==null?void 0:y.canViewUsers)||(y==null?void 0:y.canViewStaging),N=(y==null?void 0:y.canViewContentType)||(y==null?void 0:y.canViewBuildRecipes),H=y==null?void 0:y.canViewTemplates,U=y==null?void 0:y.canViewStorage;return a.jsx(B,{"data-component-name":"cmp:DashboardPage",sx:{flex:1,overflow:"auto"},children:a.jsxs(ji,{maxWidth:"lg",sx:{py:3},children:[a.jsxs(B,{sx:{mb:2},children:[a.jsx(G,{variant:"h5",children:"ダッシュボード"}),a.jsx(G,{variant:"caption",color:"text.secondary",children:"repository: @ctime-projects/frelio-demo"})]}),r&&f&&a.jsx(VY,{branchUseCase:r}),a.jsxs(Et,{container:!0,spacing:3,children:[a.jsxs(Et,{item:!0,xs:12,md:6,children:[a.jsxs($t,{"data-component-name":"cmp:ContentSection",sx:{p:2},children:[a.jsxs(B,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:1},children:[a.jsx(G,{variant:"h6",children:"コンテンツ"}),r&&f&&a.jsx(BY,{branchUseCase:r})]}),a.jsx(xX,{contentTypes:v,dashboardUseCase:m,stagingLastCommit:S,isLoading:C,canEditContentType:(y==null?void 0:y.canEditContentType)??!1}),H&&a.jsxs(B,{"data-component-name":"cmp:FileManagementSection",sx:{mt:2,pt:2,borderTop:1,borderColor:"divider"},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"ファイル管理"}),a.jsx(as,{children:a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/templates",children:[a.jsx(Un,{sx:{mr:2},children:a.jsx(ic,{sx:{fontSize:52}})}),a.jsx(Zn,{primary:"テンプレート",secondary:"github内ファイルの管理"})]})})})]})]}),U&&a.jsx(B,{"data-component-name":"cmp:StorageSection",sx:{p:2,mt:3},children:a.jsx(as,{children:a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/storage",children:[a.jsx(Un,{sx:{mr:2},children:a.jsx(ic,{sx:{fontSize:52}})}),a.jsx(Zn,{primary:"ストレージ",secondary:"R2の画像やファイルの管理"})]})})})})]}),R&&a.jsx(Et,{item:!0,xs:12,md:6,children:O&&f?a.jsx(gX,{userStagingBranches:I,personalBranchName:$,dashboardUseCase:m,canEditDeploy:P}):a.jsx(vX,{previewEnabled:D,productionEnabled:M,directDeployEnabled:T,stagingLastCommit:S,productionLastCommit:j,previewUrl:e,productionUrl:t,badgeTooltipOpen:E,setBadgeTooltipOpen:k,dashboardUseCase:m,canEditDeploy:P})}),z&&a.jsx(Et,{item:!0,xs:12,children:a.jsxs($t,{"data-component-name":"cmp:AdminSection",sx:{p:2},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"管理"}),a.jsxs(as,{children:[(y==null?void 0:y.canViewUsers)&&a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/users",children:[a.jsx(Un,{children:a.jsx(RP,{})}),a.jsx(Zn,{primary:"ユーザー管理",secondary:"ユーザーの追加・編集・削除"})]})}),(y==null?void 0:y.canViewStaging)&&a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/staging",children:[a.jsx(Un,{children:a.jsx(mP,{})}),a.jsx(Zn,{primary:"ステージングブランチ管理",secondary:"プレビュー用ブランチの設定"})]})})]})]})}),N&&a.jsx(Et,{item:!0,xs:12,children:a.jsxs($t,{"data-component-name":"cmp:DevelopSection",sx:{p:2},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"開発"}),a.jsxs(as,{children:[(y==null?void 0:y.canViewContentType)&&a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/content-types",children:[a.jsx(Un,{children:a.jsx(CY,{})}),a.jsx(Zn,{primary:"コンテンツタイプ編集",secondary:"フィールド定義・UI設定・ビュー定義"})]})}),(y==null?void 0:y.canViewBuildRecipes)&&a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:"/build-recipes",children:[a.jsx(Un,{children:a.jsx(b2,{})}),a.jsx(Zn,{primary:"ビルドデータレシピ編集",secondary:"コンテンツからJSONへの変換定義"})]})})]})]})})]})]})})}function gX({userStagingBranches:t,personalBranchName:e,dashboardUseCase:n,canEditDeploy:r}){return a.jsxs($t,{"data-component-name":"cmp:PersonalBranchPreviewSection",sx:{p:3},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"プレビュー"}),t.length>0?a.jsx(B,{sx:{display:"flex",flexDirection:"column",gap:3,py:2},children:t.map(s=>a.jsx(yX,{stagingBranch:s,personalBranchName:e,previewEnabled:n.isPreviewEnabled(s.branchName),canEditDeploy:r},s.branchName))}):a.jsx(zt,{severity:"info",sx:{mt:2},children:"個人ブランチ用ステージングブランチは設定されていません"})]})}function yX({stagingBranch:t,personalBranchName:e,previewEnabled:n,canEditDeploy:r}){const s=t.isDefault?ta().previewUrl:t.previewUrl;return a.jsxs(B,{sx:{display:"flex",flexDirection:"column",alignItems:"center",p:2,border:"1px dashed",borderColor:"divider",borderRadius:1},children:[a.jsx(G,{variant:"subtitle1",fontWeight:"bold",gutterBottom:!0,children:t.branchName}),a.jsx(RC,{sx:{fontSize:48,color:"success.main",mb:1}}),a.jsxs(G,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:["frelio-cms/",e,"ブランチを",t.branchName,"ブランチにマージ"]}),a.jsx(pe,{variant:"contained",color:"success",fullWidth:!0,disabled:!r||!n,size:"small",children:"プレビューに反映"}),s&&a.jsx(pe,{variant:"outlined",color:"success",size:"small",startIcon:a.jsx(ip,{}),fullWidth:!0,sx:{mt:1},href:s,target:"_blank",rel:"noopener noreferrer",children:"プレビューを見る"})]})}function vX({previewEnabled:t,productionEnabled:e,directDeployEnabled:n,stagingLastCommit:r,productionLastCommit:s,previewUrl:i,productionUrl:l,badgeTooltipOpen:u,setBadgeTooltipOpen:p,dashboardUseCase:f,canEditDeploy:m}){const{deployStatus:g,deployTarget:y,deployError:v}=f.getDeployState(),C=g==="loading",S=async()=>{await f.mergeToStaging()},j=async()=>{await f.mergeToProduction()},D=async()=>{await f.directDeploy()},M=()=>{f.resetDeployState()},T=()=>{switch(y){case"preview":return"プレビューに反映しました";case"production":return"本番に反映しました";case"direct":return"直接デプロイを開始しました。GitHub Actions で実行中です。";default:return"デプロイが完了しました"}};return a.jsxs($t,{"data-component-name":"cmp:DevelopBranchPreviewSection",sx:{p:3},children:[a.jsx(G,{variant:"h6",gutterBottom:!0,children:"プレビューと本番化"}),a.jsxs(B,{sx:{display:"flex",flexDirection:"column",alignItems:"center",gap:2,py:3},children:[a.jsxs(B,{sx:{display:"flex",flexDirection:"column",alignItems:"center"},children:[a.jsx(RC,{sx:{fontSize:64,color:"info.main",mb:1}}),a.jsx(G,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:"developブランチをstagingブランチにマージ"}),a.jsxs(B,{sx:{position:"relative",width:"100%"},children:[a.jsx(pe,{variant:"contained",color:"info",fullWidth:!0,disabled:!m||!t||C,onClick:S,startIcon:C&&y==="preview"?a.jsx(ut,{size:16,color:"inherit"}):void 0,children:C&&y==="preview"?"反映中...":"プレビューに反映"}),t&&e&&a.jsx(PI,{onClickAway:()=>p(!1),children:a.jsx(Er,{title:a.jsxs(a.Fragment,{children:["プレビューは最新ではありません。",a.jsx("br",{}),"本番を最新にするには、「本番に反映」をする前に「プレビューに反映」を行う必要があります。"]}),arrow:!0,open:u,disableFocusListener:!0,disableHoverListener:!0,disableTouchListener:!0,children:a.jsx(B,{onClick:()=>p(!u),sx:{position:"absolute",top:-8,right:-8,width:20,height:20,borderRadius:"50%",bgcolor:"warning.main",color:"warning.contrastText",display:"flex",alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:"bold",cursor:"pointer"},children:"!"})})})]}),a.jsx(pe,{variant:"outlined",color:"info",size:"small",startIcon:a.jsx(ip,{}),fullWidth:!0,sx:{mt:1},href:i,target:"_blank",rel:"noopener noreferrer",disabled:!i,children:"今のプレビューを見る"}),r&&a.jsxs(G,{variant:"caption",color:"text.secondary",sx:{mt:.5},children:["最終反映: ",f.formatRelativeTime(r)]})]}),a.jsx(zx,{sx:{fontSize:48,color:"grey.400"}}),a.jsxs(B,{sx:{display:"flex",flexDirection:"column",alignItems:"center"},children:[a.jsx(kC,{sx:{fontSize:64,color:"success.main",mb:1}}),a.jsx(G,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:"stagingブランチをmainブランチにマージ"}),a.jsx(pe,{variant:"contained",color:"success",fullWidth:!0,disabled:!m||!e||C,onClick:j,startIcon:C&&y==="production"?a.jsx(ut,{size:16,color:"inherit"}):void 0,children:C&&y==="production"?"反映中...":"本番に反映"}),a.jsx(pe,{variant:"text",color:"success",size:"small",startIcon:a.jsx(ip,{}),fullWidth:!0,sx:{mt:1},href:l,target:"_blank",rel:"noopener noreferrer",disabled:!l,children:"今の本番を見る"}),s&&a.jsxs(G,{variant:"caption",color:"text.secondary",sx:{mt:.5},children:["最終反映: ",f.formatRelativeTime(s)]})]}),a.jsxs(B,{sx:{mt:3,pt:3,borderTop:1,borderColor:"divider",width:"100%",textAlign:"center"},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",justifyContent:"center",gap:1,mb:2},children:[a.jsx(RC,{sx:{fontSize:64,color:"warning.main"}}),a.jsx(fJ,{sx:{fontSize:48,color:"grey.400"}}),a.jsx(kC,{sx:{fontSize:64,color:"warning.main"}})]}),a.jsx(pe,{variant:"outlined",color:"warning",startIcon:C&&y==="direct"?a.jsx(ut,{size:16,color:"inherit"}):a.jsx(gY,{}),disabled:!m||!n||C,onClick:D,children:C&&y==="direct"?"デプロイ中...":"プレビューに反映してそのまま本番化"})]}),a.jsx(B,{sx:{mt:2,textAlign:"center"},children:a.jsx(pe,{component:gs,to:"/deploy-history",variant:"text",size:"small",startIcon:a.jsx(wP,{}),color:"inherit",children:"本番化履歴"})})]}),a.jsx(ea,{open:g==="success",autoHideDuration:5e3,onClose:M,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:M,severity:"success",variant:"filled",children:T()})}),a.jsx(ea,{open:g==="error",autoHideDuration:8e3,onClose:M,anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:M,severity:"error",variant:"filled",children:v??"エラーが発生しました"})})]})}function xX({contentTypes:t,dashboardUseCase:e,stagingLastCommit:n,isLoading:r,canEditContentType:s}){const i=t.filter(y=>(y.displayLocation??"normal")==="normal"),l=t.filter(y=>y.displayLocation==="collapsed"),u=s?t.filter(y=>y.displayLocation==="hidden"):[],p=i.length>0||l.length>0||u.length>0,f=y=>y.some(v=>{const C=e.getContentTypeMetadata(v.id);return C!=null&&C.lastUpdatedAt&&n?new Date(C.lastUpdatedAt).getTime()>n.getTime():!1}),m=f(l),g=f(u);return r?a.jsx(B,{display:"flex",justifyContent:"center",p:2,children:a.jsx(ut,{size:24})}):p?a.jsxs(a.Fragment,{children:[i.length>0&&a.jsx(as,{"data-component-name":"cmp:NormalContentTypeList",children:i.map(y=>a.jsx(OC,{ct:y,dashboardUseCase:e,stagingLastCommit:n},y.id))}),l.length>0&&a.jsx(bX,{contentTypes:l,dashboardUseCase:e,stagingLastCommit:n,hasUnreflected:m}),u.length>0&&a.jsxs(_s,{"data-component-name":"cmp:HiddenContentTypesSection",defaultExpanded:!1,sx:{mt:2,"&:before":{display:"none"},boxShadow:"none",border:"1px dashed",borderColor:"warning.main",borderRadius:1,bgcolor:"warning.lighter"},children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(xv,{variant:"dot",color:"warning",invisible:!g,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(LY,{fontSize:"small",color:"warning"}),a.jsx(G,{variant:"body2",color:"warning.dark",children:"非表示コンテンツ"})]})})}),a.jsx(Is,{sx:{p:0},children:a.jsx(as,{disablePadding:!0,children:u.map(y=>a.jsx(OC,{ct:y,dashboardUseCase:e,stagingLastCommit:n},y.id))})})]})]}):a.jsxs(B,{p:2,textAlign:"center",children:[a.jsx(Tp,{sx:{fontSize:48,color:"grey.400",mb:1}}),a.jsx(G,{color:"text.secondary",children:"コンテンツタイプがまだありません"}),a.jsx(G,{variant:"body2",color:"text.secondary",children:"content-repo に定義を追加してください"})]})}function OC({ct:t,dashboardUseCase:e,stagingLastCommit:n}){const r=e.getContentTypeMetadata(t.id),s=r!=null&&r.lastUpdatedAt?e.formatRelativeTime(r.lastUpdatedAt):null,i=s?`最終更新: ${s}`:"",l=r!=null&&r.lastUpdatedAt&&n?new Date(r.lastUpdatedAt).getTime()>n.getTime():!1;return a.jsx(Os,{disablePadding:!0,children:a.jsxs(os,{component:gs,to:`/contents/${t.id}`,children:[a.jsx(Un,{sx:{mr:2},children:a.jsx(xv,{variant:"dot",color:"warning",invisible:!l,children:a.jsx(Vx,{iconName:t.icon,sx:{fontSize:48}})})}),a.jsx(Zn,{primary:t.label,secondary:i})]})})}function bX({contentTypes:t,dashboardUseCase:e,stagingLastCommit:n,hasUnreflected:r}){const[s,i]=b.useState(!1);return a.jsxs(_s,{"data-component-name":"cmp:CollapsedContentTypesSection",expanded:s,onChange:(l,u)=>i(u),disableGutters:!0,sx:{mt:1,"&:before":{display:"none"},boxShadow:"none",bgcolor:"transparent"},children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{fontSize:"small"}),sx:{minHeight:"auto",p:0,justifyContent:"flex-start","& .MuiAccordionSummary-content":{m:0,flexGrow:0},"& .MuiAccordionSummary-expandIconWrapper":{ml:.5}},children:a.jsxs(B,{sx:{display:"flex",alignItems:"center"},children:[a.jsx(G,{variant:"body2",color:"text.secondary",children:"その他"}),r&&!s&&a.jsx(B,{sx:{width:8,height:8,borderRadius:"50%",bgcolor:"warning.main",ml:.5}})]})}),a.jsx(Is,{sx:{p:0},children:a.jsx(as,{disablePadding:!0,children:t.map(l=>a.jsx(OC,{ct:l,dashboardUseCase:e,stagingLastCommit:n},l.id))})})]})}var xn;(function(t){t.assertEqual=s=>s;function e(s){}t.assertIs=e;function n(s){throw new Error}t.assertNever=n,t.arrayToEnum=s=>{const i={};for(const l of s)i[l]=l;return i},t.getValidEnumValues=s=>{const i=t.objectKeys(s).filter(u=>typeof s[s[u]]!="number"),l={};for(const u of i)l[u]=s[u];return t.objectValues(l)},t.objectValues=s=>t.objectKeys(s).map(function(i){return s[i]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const i=[];for(const l in s)Object.prototype.hasOwnProperty.call(s,l)&&i.push(l);return i},t.find=(s,i)=>{for(const l of s)if(i(l))return l},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function r(s,i=" | "){return s.map(l=>typeof l=="string"?`'${l}'`:l).join(i)}t.joinValues=r,t.jsonStringifyReplacer=(s,i)=>typeof i=="bigint"?i.toString():i})(xn||(xn={}));var AC;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(AC||(AC={}));const pt=xn.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ml=t=>{switch(typeof t){case"undefined":return pt.undefined;case"string":return pt.string;case"number":return isNaN(t)?pt.nan:pt.number;case"boolean":return pt.boolean;case"function":return pt.function;case"bigint":return pt.bigint;case"symbol":return pt.symbol;case"object":return Array.isArray(t)?pt.array:t===null?pt.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?pt.promise:typeof Map<"u"&&t instanceof Map?pt.map:typeof Set<"u"&&t instanceof Set?pt.set:typeof Date<"u"&&t instanceof Date?pt.date:pt.object;default:return pt.unknown}},He=xn.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),SX=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");let To=class zP extends Error{constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const n=e||function(i){return i.message},r={_errors:[]},s=i=>{for(const l of i.issues)if(l.code==="invalid_union")l.unionErrors.map(s);else if(l.code==="invalid_return_type")s(l.returnTypeError);else if(l.code==="invalid_arguments")s(l.argumentsError);else if(l.path.length===0)r._errors.push(n(l));else{let u=r,p=0;for(;p<l.path.length;){const f=l.path[p];p===l.path.length-1?(u[f]=u[f]||{_errors:[]},u[f]._errors.push(n(l))):u[f]=u[f]||{_errors:[]},u=u[f],p++}}};return s(this),r}static assert(e){if(!(e instanceof zP))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,xn.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n={},r=[];for(const s of this.issues)s.path.length>0?(n[s.path[0]]=n[s.path[0]]||[],n[s.path[0]].push(e(s))):r.push(e(s));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};To.create=t=>new To(t);const op=(t,e)=>{let n;switch(t.code){case He.invalid_type:t.received===pt.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case He.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,xn.jsonStringifyReplacer)}`;break;case He.unrecognized_keys:n=`Unrecognized key(s) in object: ${xn.joinValues(t.keys,", ")}`;break;case He.invalid_union:n="Invalid input";break;case He.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${xn.joinValues(t.options)}`;break;case He.invalid_enum_value:n=`Invalid enum value. Expected ${xn.joinValues(t.options)}, received '${t.received}'`;break;case He.invalid_arguments:n="Invalid function arguments";break;case He.invalid_return_type:n="Invalid function return type";break;case He.invalid_date:n="Invalid date";break;case He.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:xn.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case He.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case He.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case He.custom:n="Invalid input";break;case He.invalid_intersection_types:n="Intersection results could not be merged";break;case He.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case He.not_finite:n="Number must be finite";break;default:n=e.defaultError,xn.assertNever(t)}return{message:n}};let $P=op;function CX(t){$P=t}function Dv(){return $P}const Ev=t=>{const{data:e,path:n,errorMaps:r,issueData:s}=t,i=[...n,...s.path||[]],l={...s,path:i};if(s.message!==void 0)return{...s,path:i,message:s.message};let u="";const p=r.filter(f=>!!f).slice().reverse();for(const f of p)u=f(l,{data:e,defaultError:u}).message;return{...s,path:i,message:u}},wX=[];function ot(t,e){const n=Dv(),r=Ev({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===op?void 0:op].filter(s=>!!s)});t.common.issues.push(r)}let ni=class NP{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const s of n){if(s.status==="aborted")return Lt;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const s of n){const i=await s.key,l=await s.value;r.push({key:i,value:l})}return NP.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const s of n){const{key:i,value:l}=s;if(i.status==="aborted"||l.status==="aborted")return Lt;i.status==="dirty"&&e.dirty(),l.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof l.value<"u"||s.alwaysSet)&&(r[i.value]=l.value)}return{status:e.value,value:r}}};const Lt=Object.freeze({status:"aborted"}),Dd=t=>({status:"dirty",value:t}),zs=t=>({status:"valid",value:t}),_C=t=>t.status==="aborted",IC=t=>t.status==="dirty",Lh=t=>t.status==="valid",zh=t=>typeof Promise<"u"&&t instanceof Promise;function Rv(t,e,n,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function FP(t,e,n,r,s){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}var Tt;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Tt||(Tt={}));var Kf,Qf;let ra=class{constructor(e,n,r,s){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const XM=(t,e)=>{if(Lh(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new To(t.common.issues);return this._error=n,this._error}}};function Gt(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:s}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(l,u)=>{var p,f;const{message:m}=t;return l.code==="invalid_enum_value"?{message:m??u.defaultError}:typeof u.data>"u"?{message:(p=m??r)!==null&&p!==void 0?p:u.defaultError}:l.code!=="invalid_type"?{message:u.defaultError}:{message:(f=m??n)!==null&&f!==void 0?f:u.defaultError}},description:s}}let nn=class{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Ml(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:Ml(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ni,ctx:{common:e.parent.common,data:e.data,parsedType:Ml(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(zh(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){var r;const s={common:{issues:[],async:(r=n==null?void 0:n.async)!==null&&r!==void 0?r:!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ml(e)},i=this._parseSync({data:e,path:s.path,parent:s});return XM(s,i)}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ml(e)},s=this._parse({data:e,path:r.path,parent:r}),i=await(zh(s)?s:Promise.resolve(s));return XM(r,i)}refine(e,n){const r=s=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(s):n;return this._refinement((s,i)=>{const l=e(s),u=()=>i.addIssue({code:He.custom,...r(s)});return typeof Promise<"u"&&l instanceof Promise?l.then(p=>p?!0:(u(),!1)):l?!0:(u(),!1)})}refinement(e,n){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof n=="function"?n(r,s):n),!1))}_refinement(e){return new ko({schema:this,typeName:Pt.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Zo.create(this,this._def)}nullable(){return lc.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return vu.create(this,this._def)}promise(){return cp.create(this,this._def)}or(e){return Hh.create([this,e],this._def)}and(e){return Wh.create(this,e,this._def)}transform(e){return new ko({...Gt(this._def),schema:this,typeName:Pt.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Kh({...Gt(this._def),innerType:this,defaultValue:n,typeName:Pt.ZodDefault})}brand(){return new E2({typeName:Pt.ZodBranded,type:this,...Gt(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Qh({...Gt(this._def),innerType:this,catchValue:n,typeName:Pt.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return R2.create(this,e)}readonly(){return Jh.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const jX=/^c[^\s-]{8,}$/i,TX=/^[0-9a-z]+$/,DX=/^[0-9A-HJKMNP-TV-Z]{26}$/,EX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,RX=/^[a-z0-9_-]{21}$/i,kX=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,MX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let l1;const AX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_X=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,IX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BP="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",PX=new RegExp(`^${BP}$`);function UP(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function LX(t){return new RegExp(`^${UP(t)}$`)}function VP(t){let e=`${BP}T${UP(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function zX(t,e){return!!((e==="v4"||!e)&&AX.test(t)||(e==="v6"||!e)&&_X.test(t))}let ap=class Jf extends nn{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==pt.string){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_type,expected:pt.string,received:i.parsedType}),Lt}const r=new ni;let s;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(s=this._getOrReturnCtx(e,s),ot(s,{code:He.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(s=this._getOrReturnCtx(e,s),ot(s,{code:He.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){const l=e.data.length>i.value,u=e.data.length<i.value;(l||u)&&(s=this._getOrReturnCtx(e,s),l?ot(s,{code:He.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):u&&ot(s,{code:He.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")MX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"email",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")l1||(l1=new RegExp(OX,"u")),l1.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"emoji",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")EX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"uuid",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")RX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"nanoid",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")jX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"cuid",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")TX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"cuid2",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")DX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"ulid",code:He.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),ot(s,{validation:"url",code:He.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"regex",code:He.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?VP(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?PX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?LX(i).test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{code:He.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?kX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"duration",code:He.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?zX(e.data,i.version)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"ip",code:He.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?IX.test(e.data)||(s=this._getOrReturnCtx(e,s),ot(s,{validation:"base64",code:He.invalid_string,message:i.message}),r.dirty()):xn.assertNever(i);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(s=>e.test(s),{validation:n,code:He.invalid_string,...Tt.errToObj(r)})}_addCheck(e){return new Jf({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Tt.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Tt.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Tt.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Tt.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Tt.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Tt.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Tt.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Tt.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Tt.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Tt.errToObj(e)})}datetime(e){var n,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(n=e==null?void 0:e.offset)!==null&&n!==void 0?n:!1,local:(r=e==null?void 0:e.local)!==null&&r!==void 0?r:!1,...Tt.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...Tt.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Tt.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Tt.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...Tt.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Tt.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Tt.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Tt.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Tt.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Tt.errToObj(n)})}nonempty(e){return this.min(1,Tt.errToObj(e))}trim(){return new Jf({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Jf({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Jf({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};ap.create=t=>{var e;return new ap({checks:[],typeName:Pt.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...Gt(t)})};function $X(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=n>r?n:r,i=parseInt(t.toFixed(s).replace(".","")),l=parseInt(e.toFixed(s).replace(".",""));return i%l/Math.pow(10,s)}let $h=class PC extends nn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==pt.number){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_type,expected:pt.number,received:i.parsedType}),Lt}let r;const s=new ni;for(const i of this._def.checks)i.kind==="int"?xn.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),ot(r,{code:He.invalid_type,expected:"integer",received:"float",message:i.message}),s.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),s.dirty()):i.kind==="multipleOf"?$X(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),ot(r,{code:He.not_finite,message:i.message}),s.dirty()):xn.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Tt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Tt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Tt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Tt.toString(n))}setLimit(e,n,r,s){return new PC({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Tt.toString(s)}]})}_addCheck(e){return new PC({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Tt.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Tt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Tt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Tt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Tt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Tt.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Tt.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Tt.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Tt.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&xn.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};$h.create=t=>new $h({checks:[],typeName:Pt.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Gt(t)});let Nh=class LC extends nn{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==pt.bigint){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_type,expected:pt.bigint,received:i.parsedType}),Lt}let r;const s=new ni;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),s.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),ot(r,{code:He.not_multiple_of,multipleOf:i.value,message:i.message}),s.dirty()):xn.assertNever(i);return{status:s.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Tt.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Tt.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Tt.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Tt.toString(n))}setLimit(e,n,r,s){return new LC({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Tt.toString(s)}]})}_addCheck(e){return new LC({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Tt.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Tt.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Tt.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Tt.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Tt.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Nh.create=t=>{var e;return new Nh({checks:[],typeName:Pt.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...Gt(t)})};let Fh=class extends nn{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==pt.boolean){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.boolean,received:r.parsedType}),Lt}return zs(e.data)}};Fh.create=t=>new Fh({typeName:Pt.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Gt(t)});let Bh=class HP extends nn{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==pt.date){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_type,expected:pt.date,received:i.parsedType}),Lt}if(isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return ot(i,{code:He.invalid_date}),Lt}const r=new ni;let s;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(s=this._getOrReturnCtx(e,s),ot(s,{code:He.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(s=this._getOrReturnCtx(e,s),ot(s,{code:He.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):xn.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new HP({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Tt.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Tt.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Bh.create=t=>new Bh({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:Pt.ZodDate,...Gt(t)});let kv=class extends nn{_parse(e){if(this._getType(e)!==pt.symbol){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.symbol,received:r.parsedType}),Lt}return zs(e.data)}};kv.create=t=>new kv({typeName:Pt.ZodSymbol,...Gt(t)});let Uh=class extends nn{_parse(e){if(this._getType(e)!==pt.undefined){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.undefined,received:r.parsedType}),Lt}return zs(e.data)}};Uh.create=t=>new Uh({typeName:Pt.ZodUndefined,...Gt(t)});let Vh=class extends nn{_parse(e){if(this._getType(e)!==pt.null){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.null,received:r.parsedType}),Lt}return zs(e.data)}};Vh.create=t=>new Vh({typeName:Pt.ZodNull,...Gt(t)});let lp=class extends nn{constructor(){super(...arguments),this._any=!0}_parse(e){return zs(e.data)}};lp.create=t=>new lp({typeName:Pt.ZodAny,...Gt(t)});let du=class extends nn{constructor(){super(...arguments),this._unknown=!0}_parse(e){return zs(e.data)}};du.create=t=>new du({typeName:Pt.ZodUnknown,...Gt(t)});let Ga=class extends nn{_parse(e){const n=this._getOrReturnCtx(e);return ot(n,{code:He.invalid_type,expected:pt.never,received:n.parsedType}),Lt}};Ga.create=t=>new Ga({typeName:Pt.ZodNever,...Gt(t)});let Mv=class extends nn{_parse(e){if(this._getType(e)!==pt.undefined){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.void,received:r.parsedType}),Lt}return zs(e.data)}};Mv.create=t=>new Mv({typeName:Pt.ZodVoid,...Gt(t)});let vu=class Jy extends nn{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),s=this._def;if(n.parsedType!==pt.array)return ot(n,{code:He.invalid_type,expected:pt.array,received:n.parsedType}),Lt;if(s.exactLength!==null){const l=n.data.length>s.exactLength.value,u=n.data.length<s.exactLength.value;(l||u)&&(ot(n,{code:l?He.too_big:He.too_small,minimum:u?s.exactLength.value:void 0,maximum:l?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&n.data.length<s.minLength.value&&(ot(n,{code:He.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&n.data.length>s.maxLength.value&&(ot(n,{code:He.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((l,u)=>s.type._parseAsync(new ra(n,l,n.path,u)))).then(l=>ni.mergeArray(r,l));const i=[...n.data].map((l,u)=>s.type._parseSync(new ra(n,l,n.path,u)));return ni.mergeArray(r,i)}get element(){return this._def.type}min(e,n){return new Jy({...this._def,minLength:{value:e,message:Tt.toString(n)}})}max(e,n){return new Jy({...this._def,maxLength:{value:e,message:Tt.toString(n)}})}length(e,n){return new Jy({...this._def,exactLength:{value:e,message:Tt.toString(n)}})}nonempty(e){return this.min(1,e)}};vu.create=(t,e)=>new vu({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Pt.ZodArray,...Gt(e)});function bd(t){if(t instanceof to){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=Zo.create(bd(r))}return new to({...t._def,shape:()=>e})}else return t instanceof vu?new vu({...t._def,type:bd(t.element)}):t instanceof Zo?Zo.create(bd(t.unwrap())):t instanceof lc?lc.create(bd(t.unwrap())):t instanceof ac?ac.create(t.items.map(e=>bd(e))):t}let to=class ho extends nn{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=xn.objectKeys(e);return this._cached={shape:e,keys:n}}_parse(e){if(this._getType(e)!==pt.object){const f=this._getOrReturnCtx(e);return ot(f,{code:He.invalid_type,expected:pt.object,received:f.parsedType}),Lt}const{status:r,ctx:s}=this._processInputParams(e),{shape:i,keys:l}=this._getCached(),u=[];if(!(this._def.catchall instanceof Ga&&this._def.unknownKeys==="strip"))for(const f in s.data)l.includes(f)||u.push(f);const p=[];for(const f of l){const m=i[f],g=s.data[f];p.push({key:{status:"valid",value:f},value:m._parse(new ra(s,g,s.path,f)),alwaysSet:f in s.data})}if(this._def.catchall instanceof Ga){const f=this._def.unknownKeys;if(f==="passthrough")for(const m of u)p.push({key:{status:"valid",value:m},value:{status:"valid",value:s.data[m]}});else if(f==="strict")u.length>0&&(ot(s,{code:He.unrecognized_keys,keys:u}),r.dirty());else if(f!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const f=this._def.catchall;for(const m of u){const g=s.data[m];p.push({key:{status:"valid",value:m},value:f._parse(new ra(s,g,s.path,m)),alwaysSet:m in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const f=[];for(const m of p){const g=await m.key,y=await m.value;f.push({key:g,value:y,alwaysSet:m.alwaysSet})}return f}).then(f=>ni.mergeObjectSync(r,f)):ni.mergeObjectSync(r,p)}get shape(){return this._def.shape()}strict(e){return Tt.errToObj,new ho({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var s,i,l,u;const p=(l=(i=(s=this._def).errorMap)===null||i===void 0?void 0:i.call(s,n,r).message)!==null&&l!==void 0?l:r.defaultError;return n.code==="unrecognized_keys"?{message:(u=Tt.errToObj(e).message)!==null&&u!==void 0?u:p}:{message:p}}}:{}})}strip(){return new ho({...this._def,unknownKeys:"strip"})}passthrough(){return new ho({...this._def,unknownKeys:"passthrough"})}extend(e){return new ho({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ho({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Pt.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new ho({...this._def,catchall:e})}pick(e){const n={};return xn.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(n[r]=this.shape[r])}),new ho({...this._def,shape:()=>n})}omit(e){const n={};return xn.objectKeys(this.shape).forEach(r=>{e[r]||(n[r]=this.shape[r])}),new ho({...this._def,shape:()=>n})}deepPartial(){return bd(this)}partial(e){const n={};return xn.objectKeys(this.shape).forEach(r=>{const s=this.shape[r];e&&!e[r]?n[r]=s:n[r]=s.optional()}),new ho({...this._def,shape:()=>n})}required(e){const n={};return xn.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])n[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Zo;)i=i._def.innerType;n[r]=i}}),new ho({...this._def,shape:()=>n})}keyof(){return GP(xn.objectKeys(this.shape))}};to.create=(t,e)=>new to({shape:()=>t,unknownKeys:"strip",catchall:Ga.create(),typeName:Pt.ZodObject,...Gt(e)});to.strictCreate=(t,e)=>new to({shape:()=>t,unknownKeys:"strict",catchall:Ga.create(),typeName:Pt.ZodObject,...Gt(e)});to.lazycreate=(t,e)=>new to({shape:t,unknownKeys:"strip",catchall:Ga.create(),typeName:Pt.ZodObject,...Gt(e)});let Hh=class extends nn{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function s(i){for(const u of i)if(u.result.status==="valid")return u.result;for(const u of i)if(u.result.status==="dirty")return n.common.issues.push(...u.ctx.common.issues),u.result;const l=i.map(u=>new To(u.ctx.common.issues));return ot(n,{code:He.invalid_union,unionErrors:l}),Lt}if(n.common.async)return Promise.all(r.map(async i=>{const l={...n,common:{...n.common,issues:[]},parent:null};return{result:await i._parseAsync({data:n.data,path:n.path,parent:l}),ctx:l}})).then(s);{let i;const l=[];for(const p of r){const f={...n,common:{...n.common,issues:[]},parent:null},m=p._parseSync({data:n.data,path:n.path,parent:f});if(m.status==="valid")return m;m.status==="dirty"&&!i&&(i={result:m,ctx:f}),f.common.issues.length&&l.push(f.common.issues)}if(i)return n.common.issues.push(...i.ctx.common.issues),i.result;const u=l.map(p=>new To(p));return ot(n,{code:He.invalid_union,unionErrors:u}),Lt}}get options(){return this._def.options}};Hh.create=(t,e)=>new Hh({options:t,typeName:Pt.ZodUnion,...Gt(e)});const Aa=t=>t instanceof qh?Aa(t.schema):t instanceof ko?Aa(t.innerType()):t instanceof Gh?[t.value]:t instanceof Am?t.options:t instanceof Zh?xn.objectValues(t.enum):t instanceof Kh?Aa(t._def.innerType):t instanceof Uh?[void 0]:t instanceof Vh?[null]:t instanceof Zo?[void 0,...Aa(t.unwrap())]:t instanceof lc?[null,...Aa(t.unwrap())]:t instanceof E2||t instanceof Jh?Aa(t.unwrap()):t instanceof Qh?Aa(t._def.innerType):[];class Hx extends nn{_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==pt.object)return ot(n,{code:He.invalid_type,expected:pt.object,received:n.parsedType}),Lt;const r=this.discriminator,s=n.data[r],i=this.optionsMap.get(s);return i?n.common.async?i._parseAsync({data:n.data,path:n.path,parent:n}):i._parseSync({data:n.data,path:n.path,parent:n}):(ot(n,{code:He.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Lt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){const s=new Map;for(const i of n){const l=Aa(i.shape[e]);if(!l.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const u of l){if(s.has(u))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(u)}`);s.set(u,i)}}return new Hx({typeName:Pt.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:s,...Gt(r)})}}function zC(t,e){const n=Ml(t),r=Ml(e);if(t===e)return{valid:!0,data:t};if(n===pt.object&&r===pt.object){const s=xn.objectKeys(e),i=xn.objectKeys(t).filter(u=>s.indexOf(u)!==-1),l={...t,...e};for(const u of i){const p=zC(t[u],e[u]);if(!p.valid)return{valid:!1};l[u]=p.data}return{valid:!0,data:l}}else if(n===pt.array&&r===pt.array){if(t.length!==e.length)return{valid:!1};const s=[];for(let i=0;i<t.length;i++){const l=t[i],u=e[i],p=zC(l,u);if(!p.valid)return{valid:!1};s.push(p.data)}return{valid:!0,data:s}}else return n===pt.date&&r===pt.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let Wh=class extends nn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=(i,l)=>{if(_C(i)||_C(l))return Lt;const u=zC(i.value,l.value);return u.valid?((IC(i)||IC(l))&&n.dirty(),{status:n.value,value:u.data}):(ot(r,{code:He.invalid_intersection_types}),Lt)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,l])=>s(i,l)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Wh.create=(t,e,n)=>new Wh({left:t,right:e,typeName:Pt.ZodIntersection,...Gt(n)});let ac=class WP extends nn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==pt.array)return ot(r,{code:He.invalid_type,expected:pt.array,received:r.parsedType}),Lt;if(r.data.length<this._def.items.length)return ot(r,{code:He.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Lt;!this._def.rest&&r.data.length>this._def.items.length&&(ot(r,{code:He.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const i=[...r.data].map((l,u)=>{const p=this._def.items[u]||this._def.rest;return p?p._parse(new ra(r,l,r.path,u)):null}).filter(l=>!!l);return r.common.async?Promise.all(i).then(l=>ni.mergeArray(n,l)):ni.mergeArray(n,i)}get items(){return this._def.items}rest(e){return new WP({...this._def,rest:e})}};ac.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ac({items:t,typeName:Pt.ZodTuple,rest:null,...Gt(e)})};let qP=class $C extends nn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==pt.object)return ot(r,{code:He.invalid_type,expected:pt.object,received:r.parsedType}),Lt;const s=[],i=this._def.keyType,l=this._def.valueType;for(const u in r.data)s.push({key:i._parse(new ra(r,u,r.path,u)),value:l._parse(new ra(r,r.data[u],r.path,u)),alwaysSet:u in r.data});return r.common.async?ni.mergeObjectAsync(n,s):ni.mergeObjectSync(n,s)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof nn?new $C({keyType:e,valueType:n,typeName:Pt.ZodRecord,...Gt(r)}):new $C({keyType:ap.create(),valueType:e,typeName:Pt.ZodRecord,...Gt(n)})}},Ov=class extends nn{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==pt.map)return ot(r,{code:He.invalid_type,expected:pt.map,received:r.parsedType}),Lt;const s=this._def.keyType,i=this._def.valueType,l=[...r.data.entries()].map(([u,p],f)=>({key:s._parse(new ra(r,u,r.path,[f,"key"])),value:i._parse(new ra(r,p,r.path,[f,"value"]))}));if(r.common.async){const u=new Map;return Promise.resolve().then(async()=>{for(const p of l){const f=await p.key,m=await p.value;if(f.status==="aborted"||m.status==="aborted")return Lt;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),u.set(f.value,m.value)}return{status:n.value,value:u}})}else{const u=new Map;for(const p of l){const f=p.key,m=p.value;if(f.status==="aborted"||m.status==="aborted")return Lt;(f.status==="dirty"||m.status==="dirty")&&n.dirty(),u.set(f.value,m.value)}return{status:n.value,value:u}}}};Ov.create=(t,e,n)=>new Ov({valueType:e,keyType:t,typeName:Pt.ZodMap,...Gt(n)});let Av=class NC extends nn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==pt.set)return ot(r,{code:He.invalid_type,expected:pt.set,received:r.parsedType}),Lt;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(ot(r,{code:He.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),n.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(ot(r,{code:He.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),n.dirty());const i=this._def.valueType;function l(p){const f=new Set;for(const m of p){if(m.status==="aborted")return Lt;m.status==="dirty"&&n.dirty(),f.add(m.value)}return{status:n.value,value:f}}const u=[...r.data.values()].map((p,f)=>i._parse(new ra(r,p,r.path,f)));return r.common.async?Promise.all(u).then(p=>l(p)):l(u)}min(e,n){return new NC({...this._def,minSize:{value:e,message:Tt.toString(n)}})}max(e,n){return new NC({...this._def,maxSize:{value:e,message:Tt.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Av.create=(t,e)=>new Av({valueType:t,minSize:null,maxSize:null,typeName:Pt.ZodSet,...Gt(e)});class zd extends nn{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==pt.function)return ot(n,{code:He.invalid_type,expected:pt.function,received:n.parsedType}),Lt;function r(u,p){return Ev({data:u,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Dv(),op].filter(f=>!!f),issueData:{code:He.invalid_arguments,argumentsError:p}})}function s(u,p){return Ev({data:u,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Dv(),op].filter(f=>!!f),issueData:{code:He.invalid_return_type,returnTypeError:p}})}const i={errorMap:n.common.contextualErrorMap},l=n.data;if(this._def.returns instanceof cp){const u=this;return zs(async function(...p){const f=new To([]),m=await u._def.args.parseAsync(p,i).catch(v=>{throw f.addIssue(r(p,v)),f}),g=await Reflect.apply(l,this,m);return await u._def.returns._def.type.parseAsync(g,i).catch(v=>{throw f.addIssue(s(g,v)),f})})}else{const u=this;return zs(function(...p){const f=u._def.args.safeParse(p,i);if(!f.success)throw new To([r(p,f.error)]);const m=Reflect.apply(l,this,f.data),g=u._def.returns.safeParse(m,i);if(!g.success)throw new To([s(m,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new zd({...this._def,args:ac.create(e).rest(du.create())})}returns(e){return new zd({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new zd({args:e||ac.create([]).rest(du.create()),returns:n||du.create(),typeName:Pt.ZodFunction,...Gt(r)})}}let qh=class extends nn{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};qh.create=(t,e)=>new qh({getter:t,typeName:Pt.ZodLazy,...Gt(e)});let Gh=class extends nn{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return ot(n,{received:n.data,code:He.invalid_literal,expected:this._def.value}),Lt}return{status:"valid",value:e.data}}get value(){return this._def.value}};Gh.create=(t,e)=>new Gh({value:t,typeName:Pt.ZodLiteral,...Gt(e)});function GP(t,e){return new Am({values:t,typeName:Pt.ZodEnum,...Gt(e)})}let Am=class FC extends nn{constructor(){super(...arguments),Kf.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return ot(n,{expected:xn.joinValues(r),received:n.parsedType,code:He.invalid_type}),Lt}if(Rv(this,Kf)||FP(this,Kf,new Set(this._def.values)),!Rv(this,Kf).has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return ot(n,{received:n.data,code:He.invalid_enum_value,options:r}),Lt}return zs(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return FC.create(e,{...this._def,...n})}exclude(e,n=this._def){return FC.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Kf=new WeakMap;Am.create=GP;let Zh=class extends nn{constructor(){super(...arguments),Qf.set(this,void 0)}_parse(e){const n=xn.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==pt.string&&r.parsedType!==pt.number){const s=xn.objectValues(n);return ot(r,{expected:xn.joinValues(s),received:r.parsedType,code:He.invalid_type}),Lt}if(Rv(this,Qf)||FP(this,Qf,new Set(xn.getValidEnumValues(this._def.values))),!Rv(this,Qf).has(e.data)){const s=xn.objectValues(n);return ot(r,{received:r.data,code:He.invalid_enum_value,options:s}),Lt}return zs(e.data)}get enum(){return this._def.values}};Qf=new WeakMap;Zh.create=(t,e)=>new Zh({values:t,typeName:Pt.ZodNativeEnum,...Gt(e)});let cp=class extends nn{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==pt.promise&&n.common.async===!1)return ot(n,{code:He.invalid_type,expected:pt.promise,received:n.parsedType}),Lt;const r=n.parsedType===pt.promise?n.data:Promise.resolve(n.data);return zs(r.then(s=>this._def.type.parseAsync(s,{path:n.path,errorMap:n.common.contextualErrorMap})))}};cp.create=(t,e)=>new cp({type:t,typeName:Pt.ZodPromise,...Gt(e)});let ko=class extends nn{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Pt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),s=this._def.effect||null,i={addIssue:l=>{ot(r,l),l.fatal?n.abort():n.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),s.type==="preprocess"){const l=s.transform(r.data,i);if(r.common.async)return Promise.resolve(l).then(async u=>{if(n.value==="aborted")return Lt;const p=await this._def.schema._parseAsync({data:u,path:r.path,parent:r});return p.status==="aborted"?Lt:p.status==="dirty"||n.value==="dirty"?Dd(p.value):p});{if(n.value==="aborted")return Lt;const u=this._def.schema._parseSync({data:l,path:r.path,parent:r});return u.status==="aborted"?Lt:u.status==="dirty"||n.value==="dirty"?Dd(u.value):u}}if(s.type==="refinement"){const l=u=>{const p=s.refinement(u,i);if(r.common.async)return Promise.resolve(p);if(p instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return u};if(r.common.async===!1){const u=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return u.status==="aborted"?Lt:(u.status==="dirty"&&n.dirty(),l(u.value),{status:n.value,value:u.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(u=>u.status==="aborted"?Lt:(u.status==="dirty"&&n.dirty(),l(u.value).then(()=>({status:n.value,value:u.value}))))}if(s.type==="transform")if(r.common.async===!1){const l=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Lh(l))return l;const u=s.transform(l.value,i);if(u instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:u}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(l=>Lh(l)?Promise.resolve(s.transform(l.value,i)).then(u=>({status:n.value,value:u})):l);xn.assertNever(s)}};ko.create=(t,e,n)=>new ko({schema:t,typeName:Pt.ZodEffects,effect:e,...Gt(n)});ko.createWithPreprocess=(t,e,n)=>new ko({schema:e,effect:{type:"preprocess",transform:t},typeName:Pt.ZodEffects,...Gt(n)});let Zo=class extends nn{_parse(e){return this._getType(e)===pt.undefined?zs(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Zo.create=(t,e)=>new Zo({innerType:t,typeName:Pt.ZodOptional,...Gt(e)});let lc=class extends nn{_parse(e){return this._getType(e)===pt.null?zs(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lc.create=(t,e)=>new lc({innerType:t,typeName:Pt.ZodNullable,...Gt(e)});let Kh=class extends nn{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===pt.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Kh.create=(t,e)=>new Kh({innerType:t,typeName:Pt.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Gt(e)});let Qh=class extends nn{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return zh(s)?s.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new To(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new To(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Qh.create=(t,e)=>new Qh({innerType:t,typeName:Pt.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Gt(e)});let _v=class extends nn{_parse(e){if(this._getType(e)!==pt.nan){const r=this._getOrReturnCtx(e);return ot(r,{code:He.invalid_type,expected:pt.nan,received:r.parsedType}),Lt}return{status:"valid",value:e.data}}};_v.create=t=>new _v({typeName:Pt.ZodNaN,...Gt(t)});const NX=Symbol("zod_brand");let E2=class extends nn{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},R2=class ZP extends nn{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?Lt:i.status==="dirty"?(n.dirty(),Dd(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Lt:s.status==="dirty"?(n.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,n){return new ZP({in:e,out:n,typeName:Pt.ZodPipeline})}},Jh=class extends nn{_parse(e){const n=this._def.innerType._parse(e),r=s=>(Lh(s)&&(s.value=Object.freeze(s.value)),s);return zh(n)?n.then(s=>r(s)):r(n)}unwrap(){return this._def.innerType}};Jh.create=(t,e)=>new Jh({innerType:t,typeName:Pt.ZodReadonly,...Gt(e)});function KP(t,e={},n){return t?lp.create().superRefine((r,s)=>{var i,l;if(!t(r)){const u=typeof e=="function"?e(r):typeof e=="string"?{message:e}:e,p=(l=(i=u.fatal)!==null&&i!==void 0?i:n)!==null&&l!==void 0?l:!0,f=typeof u=="string"?{message:u}:u;s.addIssue({code:"custom",...f,fatal:p})}}):lp.create()}const FX={object:to.lazycreate};var Pt;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Pt||(Pt={}));const BX=(t,e={message:`Input not instance of ${t.name}`})=>KP(n=>n instanceof t,e),QP=ap.create,JP=$h.create,UX=_v.create,VX=Nh.create,YP=Fh.create,HX=Bh.create,WX=kv.create,qX=Uh.create,GX=Vh.create,ZX=lp.create,KX=du.create,QX=Ga.create,JX=Mv.create,YX=vu.create,XX=to.create,eee=to.strictCreate,tee=Hh.create,nee=Hx.create,ree=Wh.create,see=ac.create,iee=qP.create,oee=Ov.create,aee=Av.create,lee=zd.create,cee=qh.create,uee=Gh.create,dee=Am.create,pee=Zh.create,fee=cp.create,eO=ko.create,hee=Zo.create,mee=lc.create,gee=ko.createWithPreprocess,yee=R2.create,vee=()=>QP().optional(),xee=()=>JP().optional(),bee=()=>YP().optional(),See={string:(t=>ap.create({...t,coerce:!0})),number:(t=>$h.create({...t,coerce:!0})),boolean:(t=>Fh.create({...t,coerce:!0})),bigint:(t=>Nh.create({...t,coerce:!0})),date:(t=>Bh.create({...t,coerce:!0}))},Cee=Lt;var Tr=Object.freeze({__proto__:null,defaultErrorMap:op,setErrorMap:CX,getErrorMap:Dv,makeIssue:Ev,EMPTY_PATH:wX,addIssueToContext:ot,ParseStatus:ni,INVALID:Lt,DIRTY:Dd,OK:zs,isAborted:_C,isDirty:IC,isValid:Lh,isAsync:zh,get util(){return xn},get objectUtil(){return AC},ZodParsedType:pt,getParsedType:Ml,ZodType:nn,datetimeRegex:VP,ZodString:ap,ZodNumber:$h,ZodBigInt:Nh,ZodBoolean:Fh,ZodDate:Bh,ZodSymbol:kv,ZodUndefined:Uh,ZodNull:Vh,ZodAny:lp,ZodUnknown:du,ZodNever:Ga,ZodVoid:Mv,ZodArray:vu,ZodObject:to,ZodUnion:Hh,ZodDiscriminatedUnion:Hx,ZodIntersection:Wh,ZodTuple:ac,ZodRecord:qP,ZodMap:Ov,ZodSet:Av,ZodFunction:zd,ZodLazy:qh,ZodLiteral:Gh,ZodEnum:Am,ZodNativeEnum:Zh,ZodPromise:cp,ZodEffects:ko,ZodTransformer:ko,ZodOptional:Zo,ZodNullable:lc,ZodDefault:Kh,ZodCatch:Qh,ZodNaN:_v,BRAND:NX,ZodBranded:E2,ZodPipeline:R2,ZodReadonly:Jh,custom:KP,Schema:nn,ZodSchema:nn,late:FX,get ZodFirstPartyTypeKind(){return Pt},coerce:See,any:ZX,array:YX,bigint:VX,boolean:YP,date:HX,discriminatedUnion:nee,effect:eO,enum:dee,function:lee,instanceof:BX,intersection:ree,lazy:cee,literal:uee,map:oee,nan:UX,nativeEnum:pee,never:QX,null:GX,nullable:mee,number:JP,object:XX,oboolean:bee,onumber:xee,optional:hee,ostring:vee,pipeline:yee,preprocess:gee,promise:fee,record:iee,set:aee,strictObject:eee,string:QP,symbol:WX,transformer:eO,tuple:see,undefined:qX,union:tee,unknown:KX,void:JX,NEVER:Cee,ZodIssueCode:He,quotelessJson:SX,ZodError:To});function no({items:t,dropdown:e}){var f;const[n,r]=b.useState(null),s=!!n,i=m=>{r(m.currentTarget)},l=()=>{r(null)},u=m=>{e==null||e.onChange(m),l()},p=(f=e==null?void 0:e.options.find(m=>m.value===e.value))==null?void 0:f.label;return a.jsxs(a.Fragment,{children:[a.jsxs(k7,{"data-component-name":"cmp:Breadcrumb",separator:a.jsx(lY,{fontSize:"small"}),sx:{mb:2},children:[a.jsx(B,{component:gs,to:"/",sx:{display:"flex",alignItems:"center",textDecoration:"none",color:"text.secondary","&:hover":{color:"primary.main"}},children:a.jsx(SP,{fontSize:"small"})}),t.map(m=>m.to?a.jsx(B,{component:gs,to:m.to,sx:{textDecoration:"none",color:"text.secondary","&:hover":{color:"primary.main",textDecoration:"underline"}},children:m.label},m.label):a.jsx(G,{color:"text.secondary",children:m.label},m.label)),e&&a.jsx(pe,{"data-component-name":"cmp:BreadcrumbDropdown",onClick:i,endIcon:a.jsx(pJ,{}),sx:{textTransform:"none",color:"text.secondary",minWidth:"auto",p:0,"&:hover":{bgcolor:"transparent",color:"primary.main"}},children:p})]}),e&&a.jsx(Cp,{anchorEl:n,open:s,onClose:l,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},children:e.options.map(m=>a.jsx(nt,{selected:m.value===e.value,onClick:()=>u(m.value),children:m.label},m.value))})]})}function la({title:t,titleNode:e,titleSx:n,actions:r,mb:s=3}){return a.jsxs(B,{"data-component-name":"cmp:PageHeader",sx:{display:"flex",flexDirection:{xs:"column",sm:"row"},justifyContent:"space-between",alignItems:{xs:"stretch",sm:"center"},gap:2,mb:s},children:[e??a.jsx(G,{variant:"h5",component:"h1",sx:n,children:t}),r&&a.jsx(B,{sx:{display:"flex",gap:2,flexWrap:"wrap",justifyContent:"flex-end",alignItems:"center"},children:r})]})}function Dp({title:t,icon:e,onClose:n,actions:r,componentName:s}){return a.jsxs(B,{"data-component-name":s,sx:{display:"flex",alignItems:"center",gap:1,p:2,borderBottom:1,borderColor:"divider",flexShrink:0},children:[a.jsx(ft,{onClick:n,edge:"start",size:"small",children:a.jsx(xP,{})}),e,a.jsx(G,{variant:"h6",sx:{flex:1},children:t}),r]})}function wee(){return Fs(t=>({dialogMode:null,editingUser:null,deleteDialogOpen:!1,deleteTargetUser:null,formData:{githubUsername:"",displayName:"",selectedTemplate:"viewer",permissions:Ih("viewer"),allowPersonalBranch:!0},validationErrors:[],isSaving:!1,isDeleting:!1,snackbar:{open:!1,message:"",severity:"success"},isFormDirty:!1,closeConfirmDialogOpen:!1,setDialogMode:e=>t({dialogMode:e}),setEditingUser:e=>t({editingUser:e}),setDeleteDialogOpen:e=>t({deleteDialogOpen:e}),setDeleteTargetUser:e=>t({deleteTargetUser:e}),setFormData:e=>t(n=>({formData:{...n.formData,...e}})),setValidationErrors:e=>t({validationErrors:e}),setSaving:e=>t({isSaving:e}),setDeleting:e=>t({isDeleting:e}),setSnackbar:e=>t({snackbar:e}),setFormDirty:e=>t({isFormDirty:e}),setCloseConfirmDialogOpen:e=>t({closeConfirmDialogOpen:e})}))}class jee{constructor(){St(this,"store",wee());St(this,"cachedState",null);St(this,"cachedStoreState",null)}getState(){const e=this.store.getState();return this.cachedStoreState===e&&this.cachedState!==null?this.cachedState:(this.cachedStoreState=e,this.cachedState={dialogMode:e.dialogMode,editingUser:e.editingUser,deleteDialogOpen:e.deleteDialogOpen,deleteTargetUser:e.deleteTargetUser,formData:e.formData,validationErrors:e.validationErrors,isSaving:e.isSaving,isDeleting:e.isDeleting,snackbar:e.snackbar,isFormDirty:e.isFormDirty,closeConfirmDialogOpen:e.closeConfirmDialogOpen},this.cachedState)}openAddDialog(){this.store.getState().setFormData({githubUsername:"",displayName:"",selectedTemplate:"viewer",permissions:Ih("viewer"),allowPersonalBranch:!0}),this.store.getState().setValidationErrors([]),this.store.getState().setFormDirty(!1),this.store.getState().setDialogMode("add")}openEditDialog(e){this.store.getState().setEditingUser(e);const n=g2(e),r=e.permissions??Ih("viewer");this.store.getState().setFormData({githubUsername:e.githubUsername,displayName:e.displayName,selectedTemplate:n,permissions:r,allowPersonalBranch:e.allowPersonalBranch!==!1}),this.store.getState().setValidationErrors([]),this.store.getState().setFormDirty(!1),this.store.getState().setDialogMode("edit")}closeDialog(){this.store.getState().setDialogMode(null),this.store.getState().setEditingUser(null),this.store.getState().setValidationErrors([]),this.store.getState().setFormDirty(!1),this.store.getState().setCloseConfirmDialogOpen(!1)}openDeleteDialog(e){this.store.getState().setDeleteTargetUser(e),this.store.getState().setDeleteDialogOpen(!0)}closeDeleteDialog(){this.store.getState().setDeleteDialogOpen(!1),this.store.getState().setDeleteTargetUser(null)}setFormField(e,n){this.store.getState().setFormData({[e]:n}),this.store.getState().setFormDirty(!0)}setPermission(e,n){const r=this.store.getState().formData.permissions;this.store.getState().setFormData({permissions:{...r,[e]:n}}),this.store.getState().setFormDirty(!0)}setValidationErrors(e){this.store.getState().setValidationErrors(e)}clearValidationErrors(){this.store.getState().setValidationErrors([])}setSaving(e){this.store.getState().setSaving(e)}setDeleting(e){this.store.getState().setDeleting(e)}showSnackbar(e,n){this.store.getState().setSnackbar({open:!0,message:e,severity:n})}hideSnackbar(){this.store.getState().setSnackbar({open:!1,message:"",severity:"success"})}setFormDirty(e){this.store.getState().setFormDirty(e)}openCloseConfirmDialog(){this.store.getState().setCloseConfirmDialogOpen(!0)}closeCloseConfirmDialog(){this.store.getState().setCloseConfirmDialogOpen(!1)}subscribe(e){return this.store.subscribe(e)}}const k2=new jee;class Tee{constructor(e){this.deps=e}getState(){const{repo:e,presenter:n,currentUsername:r}=this.deps,s=n.getState();return{users:e.getUsers(),isLoading:e.isLoading(),error:e.getError(),currentUsername:r,...s}}openAddDialog(){this.deps.presenter.openAddDialog()}openEditDialog(e){this.deps.presenter.openEditDialog(e)}closeDialog(){this.deps.presenter.closeDialog()}openDeleteDialog(e){this.deps.presenter.openDeleteDialog(e)}closeDeleteDialog(){this.deps.presenter.closeDeleteDialog()}setFormField(e,n){this.deps.presenter.setFormField(e,n)}setTemplate(e){const n=Ih(e);this.deps.presenter.setFormField("selectedTemplate",e),this.deps.presenter.setFormField("permissions",n)}setPermission(e,n){this.deps.presenter.setPermission(e,n);const s={...this.deps.presenter.getState().formData.permissions,[e]:n},i=_h(s);this.deps.presenter.setFormField("selectedTemplate",i)}async addUser(){const{repo:e,presenter:n}=this.deps,r=n.getState(),s=e.getUsers(),i={githubUsername:r.formData.githubUsername.trim(),displayName:r.formData.displayName.trim(),permissions:r.formData.permissions,allowPersonalBranch:r.formData.allowPersonalBranch},l=OM(i,s);if(l.length>0)return n.setValidationErrors(l),!1;n.setSaving(!0);try{const u=[...s,i];return await e.saveUsers(u),n.closeDialog(),n.showSnackbar("ユーザーを追加しました","success"),oe.info("UserListUseCase.addUser",{githubUsername:i.githubUsername}),!0}catch(u){return oe.error("UserListUseCase.addUser failed",{error:u}),n.showSnackbar("ユーザーの追加に失敗しました","error"),!1}finally{n.setSaving(!1)}}async updateUser(){const{repo:e,presenter:n}=this.deps,r=n.getState(),s=e.getUsers(),i=r.editingUser;if(!i)return!1;const l={githubUsername:r.formData.githubUsername.trim(),displayName:r.formData.displayName.trim(),permissions:r.formData.permissions,allowPersonalBranch:r.formData.allowPersonalBranch,isOwner:i.isOwner},u=OM(l,s,i.githubUsername);if(u.length>0)return n.setValidationErrors(u),!1;n.setSaving(!0);try{const p=s.map(f=>f.githubUsername===i.githubUsername?l:f);return await e.saveUsers(p),n.closeDialog(),n.showSnackbar("ユーザーを更新しました","success"),oe.info("UserListUseCase.updateUser",{githubUsername:l.githubUsername}),!0}catch(p){return oe.error("UserListUseCase.updateUser failed",{error:p}),n.showSnackbar("ユーザーの更新に失敗しました","error"),!1}finally{n.setSaving(!1)}}async deleteUser(){const{repo:e,presenter:n,currentUsername:r}=this.deps,s=n.getState(),i=e.getUsers(),l=s.deleteTargetUser;if(!l)return!1;if(!AM(l.githubUsername,r))return n.showSnackbar("自分自身は削除できません","error"),n.closeDeleteDialog(),!1;n.setDeleting(!0);try{const u=i.filter(p=>p.githubUsername!==l.githubUsername);return await e.saveUsers(u),n.closeDeleteDialog(),n.showSnackbar("ユーザーを削除しました","success"),oe.info("UserListUseCase.deleteUser",{githubUsername:l.githubUsername}),!0}catch(u){return oe.error("UserListUseCase.deleteUser failed",{error:u}),n.showSnackbar("ユーザーの削除に失敗しました","error"),!1}finally{n.setDeleting(!1)}}hideSnackbar(){this.deps.presenter.hideSnackbar()}getRoleTemplateLabel(e){const n=g2(e);return Tv(n)}canDelete(e){return AM(e.githubUsername,this.deps.currentUsername)}requestCloseDialog(){const{presenter:e}=this.deps;e.getState().isFormDirty?e.openCloseConfirmDialog():e.closeDialog()}cancelCloseDialog(){this.deps.presenter.closeCloseConfirmDialog()}discardAndCloseDialog(){this.deps.presenter.closeDialog()}}const Dee=t=>k2.subscribe(t),tO=()=>k2.getState(),nO="develop";function Eee(){const{authUseCase:t}=rr(),{token:e,githubUser:n,currentUser:r}=t.getState(),s=ys();b.useSyncExternalStore(Dee,tO,tO);const i=new uu({adminData:jn(uu.AdminDataQueryParams(e,nO))},Pn(uu.SaveAdminDataMutationParams(s,e,nO)));return{userListUseCase:new Tee({repo:i,presenter:k2,currentUsername:(n==null?void 0:n.login)??"",currentUser:r})}}const Ree=Tr.object({action:Tr.enum(["add","edit"]).optional(),user:Tr.string().optional()}),kee=Ss("/users/")({component:Mee,validateSearch:Ree});function Mee(){const{authUseCase:t}=rr(),{currentUser:e}=t.getState(),n=ur(),r=ws(e,"canViewUsers"),s=ws(e,"canEditUsers");return b.useEffect(()=>{e&&!r&&n({to:"/"})},[e,r,n]),r?a.jsx(Oee,{canEdit:s}):null}function Oee({canEdit:t}){const{userListUseCase:e}=Eee(),{simulationUseCase:n}=D2(),r=e.getState(),s=vr(),i=aa(s.breakpoints.down("sm")),l=ur(),u=Di({from:"/users/"}),{users:p,isLoading:f,error:m,dialogMode:g,formData:y,validationErrors:v,isSaving:C,deleteDialogOpen:S,deleteTargetUser:j,isDeleting:D,snackbar:M,currentUsername:T,editingUser:E,isFormDirty:k,closeConfirmDialogOpen:A}=r,O=[...p].sort((z,N)=>z.isOwner&&!N.isOwner?-1:!z.isOwner&&N.isOwner?1:z.githubUsername.localeCompare(N.githubUsername));b.useEffect(()=>{if(!f){if(!t){u.action&&l({to:"/users",search:{}});return}if(u.action==="add"&&g!=="add")e.openAddDialog();else if(u.action==="edit"&&u.user&&g!=="edit"){const z=O.find(N=>N.githubUsername===u.user);z&&e.openEditDialog(z)}else!u.action&&g!==null&&e.closeDialog()}},[u.action,u.user,f,O,g,e,t,l]);const I=()=>{l({to:"/users",search:{action:"add"}})},$=z=>{l({to:"/users",search:{action:"edit",user:z.githubUsername}})},R=()=>{k?e.requestCloseDialog():l({to:"/users",search:{}})},P=()=>{e.discardAndCloseDialog(),l({to:"/users",search:{}})};return f?a.jsx(B,{"data-component-name":"cmp:UserListPageLoading",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(ut,{})}):m?a.jsx(B,{"data-component-name":"cmp:UserListPageError",sx:{flex:1,overflow:"auto"},children:a.jsx(ji,{maxWidth:"lg",sx:{py:3},children:a.jsxs(zt,{severity:"error",children:["エラー: ",m.message]})})}):a.jsxs(B,{"data-component-name":"cmp:UserListPage",sx:{flex:1,overflow:"auto"},children:[a.jsxs(ji,{maxWidth:"lg",sx:{py:3},children:[a.jsx(no,{items:[{label:"ユーザー管理"}]}),a.jsx(la,{title:"ユーザー管理",actions:t&&a.jsx(pe,{variant:"contained",startIcon:a.jsx(Qn,{}),onClick:I,children:"ユーザー追加"})}),a.jsxs(zt,{severity:"info",sx:{mb:3},children:["ここに追加するユーザーは",a.jsxs(Ox,{href:`https://github.com/${Qr()}`,target:"_blank",rel:"noopener noreferrer",children:["@",Qr()]}),"で、別途招待をする必要があります。"]}),O.length===0?a.jsx(zt,{severity:"info",children:"ユーザーが登録されていません"}):i?a.jsx(_ee,{users:O,currentUsername:T,userListUseCase:e,onEdit:$,canEdit:t}):a.jsx(Aee,{users:O,currentUsername:T,userListUseCase:e,onEdit:$,canEdit:t})]}),a.jsx(Iee,{open:g!==null,mode:g,formData:y,validationErrors:v,isSaving:C,isOwner:(E==null?void 0:E.isOwner)===!0,isSelf:(E==null?void 0:E.githubUsername)===T,simulationUseCase:n,onClose:R,onSave:async()=>{(g==="add"?await e.addUser():await e.updateUser())&&l({to:"/users",search:{}})},onFieldChange:(z,N)=>e.setFormField(z,N),onTemplateChange:z=>e.setTemplate(z),onPermissionChange:(z,N)=>e.setPermission(z,N)}),a.jsxs(Qt,{"data-component-name":"cmp:CloseConfirmDialog",open:A,onClose:()=>e.cancelCloseDialog(),children:[a.jsx(Yt,{children:"変更を破棄しますか?"}),a.jsx(Jt,{children:a.jsx(G,{children:"保存されていない変更があります。変更を破棄してもよろしいですか?"})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>e.cancelCloseDialog(),children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:P,children:"破棄"})]})]}),a.jsxs(Qt,{"data-component-name":"cmp:DeleteUserDialog",open:S,onClose:()=>e.closeDeleteDialog(),children:[a.jsx(Yt,{children:"ユーザーの削除"}),a.jsxs(Jt,{children:[a.jsxs(G,{children:[j==null?void 0:j.displayName,"(",j==null?void 0:j.githubUsername,")を削除しますか?"]}),a.jsx(G,{variant:"body2",color:"text.secondary",mt:1,children:"この操作は取り消せません。"})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>e.closeDeleteDialog(),children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:()=>e.deleteUser(),disabled:D,children:D?a.jsx(ut,{size:24}):"削除"})]})]}),a.jsx(ea,{open:M.open,autoHideDuration:4e3,onClose:()=>e.hideSnackbar(),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{onClose:()=>e.hideSnackbar(),severity:M.severity,sx:{width:"100%"},children:M.message})})]})}function Aee({users:t,currentUsername:e,userListUseCase:n,onEdit:r,canEdit:s}){return a.jsx($t,{"data-component-name":"cmp:UserTable",children:a.jsxs(wp,{children:[a.jsx(jm,{children:a.jsxs(eo,{children:[a.jsx(Kt,{children:"GitHub ユーザー名"}),a.jsx(Kt,{children:"表示名"}),a.jsx(Kt,{children:"ロール"}),a.jsx(Kt,{children:"個人ブランチ"}),s&&a.jsx(Kt,{width:"120px",children:"操作"})]})}),a.jsx(jp,{children:t.map(i=>a.jsxs(eo,{children:[a.jsxs(Kt,{children:[i.githubUsername,i.githubUsername===e&&a.jsx(Ht,{label:"自分",size:"small",sx:{ml:1}})]}),a.jsx(Kt,{children:i.displayName}),a.jsx(Kt,{children:a.jsx(XP,{user:i})}),a.jsx(Kt,{children:i.allowPersonalBranch!==!1?a.jsx(Ht,{label:"許可",color:"success",size:"small"}):a.jsx(Ht,{label:"不許可",size:"small"})}),s&&a.jsxs(Kt,{children:[a.jsx(ft,{size:"small",onClick:()=>r(i),title:"編集",children:a.jsx(Ri,{})}),a.jsx(ft,{size:"small",onClick:()=>n.openDeleteDialog(i),disabled:!n.canDelete(i),title:n.canDelete(i)?"削除":"自分自身は削除できません",children:a.jsx(zn,{})})]})]},i.githubUsername))})]})})}function _ee({users:t,currentUsername:e,userListUseCase:n,onEdit:r,canEdit:s}){return a.jsx(Ro,{"data-component-name":"cmp:UserCardList",spacing:2,children:t.map(i=>a.jsxs(Su,{"data-component-name":"cmp:UserCard",children:[a.jsxs(Sp,{sx:{pb:1},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[a.jsx(G,{variant:"subtitle1",fontWeight:"bold",children:i.displayName}),i.githubUsername===e&&a.jsx(Ht,{label:"自分",size:"small"})]}),a.jsxs(G,{variant:"body2",color:"text.secondary",sx:{mb:1},children:["@",i.githubUsername]}),a.jsxs(B,{sx:{display:"flex",gap:1,flexWrap:"wrap"},children:[a.jsx(XP,{user:i}),i.allowPersonalBranch!==!1?a.jsx(Ht,{label:"個人ブランチ許可",color:"success",size:"small"}):a.jsx(Ht,{label:"個人ブランチ不許可",size:"small"})]})]}),s&&a.jsxs(s2,{children:[a.jsx(pe,{size:"small",startIcon:a.jsx(Ri,{}),onClick:()=>r(i),children:"編集"}),a.jsx(pe,{size:"small",color:"error",startIcon:a.jsx(zn,{}),onClick:()=>n.openDeleteDialog(i),disabled:!n.canDelete(i),children:"削除"})]})]},i.githubUsername))})}function XP({user:t}){const e=g2(t),n=()=>{switch(e){case"owner":return"error";case"admin":return"error";case"developer":return"warning";case"editor":return"primary";case"viewer":return"default";case"custom":default:return"success"}},r=Tv(e);return a.jsx(Ht,{label:r,color:n(),size:"small"})}function Iee({open:t,mode:e,formData:n,validationErrors:r,isSaving:s,isOwner:i,isSelf:l,simulationUseCase:u,onClose:p,onSave:f,onFieldChange:m,onTemplateChange:g,onPermissionChange:y}){const v=j=>{var D;return(D=r.find(M=>M.field===j))==null?void 0:D.message},C=()=>{u.startSimulation(n.permissions,n.selectedTemplate,n.displayName,n.githubUsername),p(),setTimeout(()=>{const j=document.querySelector('[data-testid="avatar-menu-button"]');j==null||j.click()},100)},S=e==="edit"&&!l;return a.jsxs(Cu,{anchor:"right",open:t,onClose:p,"data-component-name":"cmp:UserEditDrawer",PaperProps:{sx:{width:{xs:"100vw",sm:480},maxWidth:"100vw",display:"flex",flexDirection:"column"}},children:[a.jsx(Dp,{title:e==="add"?"ユーザー追加":"ユーザー編集",icon:a.jsx(Mm,{color:"action"}),onClose:p,actions:a.jsxs(B,{sx:{display:"flex",gap:1},children:[S&&a.jsx(pe,{variant:"outlined",color:"info",onClick:C,size:"small",startIcon:a.jsx(_P,{}),children:"UI再現"}),a.jsx(pe,{variant:"contained",onClick:f,disabled:s,size:"small",children:s?a.jsx(ut,{size:20}):"保存"})]}),componentName:"cmp:UserEditDrawerHeader"}),a.jsxs(B,{"data-component-name":"cmp:UserEditDrawerContent",sx:{flex:1,overflow:"auto",p:2,display:"flex",flexDirection:"column",gap:2},children:[a.jsx(Xe,{label:"GitHub ユーザー名",value:n.githubUsername,onChange:j=>m("githubUsername",j.target.value),error:!!v("githubUsername"),helperText:v("githubUsername"),disabled:e==="edit",fullWidth:!0,required:!0}),a.jsx(Xe,{label:"表示名",value:n.displayName,onChange:j=>m("displayName",j.target.value),error:!!v("displayName"),helperText:v("displayName"),fullWidth:!0,required:!0}),a.jsxs(_n,{fullWidth:!0,error:!!v("selectedTemplate"),disabled:i,children:[a.jsx(nr,{required:!0,children:"ロール"}),a.jsxs(wn,{value:n.selectedTemplate,label:"ロール",onChange:j=>g(j.target.value),children:[i&&a.jsx(nt,{value:"owner",children:"所有者"}),a.jsx(nt,{value:"admin",children:"管理者"}),a.jsx(nt,{value:"developer",children:"開発者"}),a.jsx(nt,{value:"editor",children:"編集者"}),a.jsx(nt,{value:"viewer",children:"閲覧者"}),a.jsx(nt,{value:"custom",children:"カスタム"})]}),i&&a.jsx(Dh,{children:"所有者のロールは変更できません"}),v("selectedTemplate")&&a.jsx(Dh,{children:v("selectedTemplate")})]}),a.jsx(Pee,{permissions:i?Cv:n.permissions,onPermissionChange:y,disabled:i}),a.jsx(_r,{control:a.jsx(Ax,{checked:n.allowPersonalBranch,onChange:j=>m("allowPersonalBranch",j.target.checked)}),label:"個人ブランチの使用を許可"})]})]})}function Pee({permissions:t,onPermissionChange:e,disabled:n}){const r=(s,i)=>{if(e(s,i),i){const l=Sv.find(u=>u.edit===s);l&&e(l.view,!0)}if(!i){const l=Sv.find(u=>u.view===s);l&&e(l.edit,!1)}};return a.jsx(B,{"data-component-name":"cmp:PermissionEditor",sx:{px:2},children:a.jsx(Ro,{spacing:2,children:Object.entries(uP).map(([s,i])=>a.jsxs(B,{children:[a.jsx(G,{variant:"subtitle2",color:"text.secondary",sx:{mb:.5},children:i.label}),a.jsx(B,{sx:{display:"flex",flexDirection:"column",ml:2,gap:.5},children:i.pairs.map(l=>a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(G,{variant:"body2",sx:{minWidth:100},children:dP[l.view]}),a.jsx(_r,{control:a.jsx(es,{checked:t[l.view],onChange:u=>r(l.view,u.target.checked),size:"small",disabled:n}),label:"閲覧",sx:{mr:0}}),a.jsx(_r,{control:a.jsx(es,{checked:t[l.edit],onChange:u=>r(l.edit,u.target.checked),size:"small",disabled:n}),label:"編集",sx:{mr:0}})]},l.view))})]},s))})})}function M2(t){return[".png",".jpg",".jpeg",".gif",".webp",".bmp",".ico"].some(n=>t.toLowerCase().endsWith(n))}function Lee(t){const e=zee(t).toLowerCase();return{".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp",".ico":"image/x-icon"}[e]??"application/octet-stream"}function O2(t){const e=[".html",".htm",".css",".js",".ts",".jsx",".tsx",".json",".xml",".svg",".md",".txt",".yaml",".yml",".toml",".ini",".conf",".sh",".bat",".ps1",".gitignore",".gitkeep",".env"],n=t.toLowerCase();return e.some(r=>n.endsWith(r))}function zee(t){const e=t.lastIndexOf(".");return e>0?t.slice(e):""}class Cl{constructor(e,n,r,s,i,l,u,p,f,m,g){this.token=e,this.basePath=n,this.branch=r,this.rootQuery=s,this.fileQuery=i,this.saveMutation=l,this.deleteMutation=u,this.deleteDirectoryMutation=p,this.uploadMutation=f,this.createFolderMutation=m,this.queryClient=g}static RootEntriesQueryParams(e,n,r){return{queryKey:["fileManager","root",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return(await new At(e).listDirectoryEntries(n,r)).map(l=>({name:l.name,path:`${n}/${l.name}`,type:l.type==="tree"?"directory":"file"}))},enabled:!!e}}static FileContentQueryParams(e,n,r){return{queryKey:["fileManager","file",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");if(!n)return null;const s=new At(e),i=n.split("/").pop()??"";return M2(i)?s.fetchFileBase64OrNull(n,r):s.fetchFileOrNull(n,r)},enabled:!!e&&!!n}}static SaveFileMutationParams(e,n,r){return{mutationFn:async({path:s,content:i})=>{if(!n)throw new Error("Not authenticated");const l=new At(n),u=s.split("/").pop()??"file";await l.commitFiles(`テンプレート更新: ${u}`,[{path:s,content:i}],r)},onSuccess:(s,i)=>{e.invalidateQueries({queryKey:["fileManager","file",i.path,r]})}}}static DeleteFileMutationParams(e,n,r,s){return{mutationFn:async i=>{if(!n)throw new Error("Not authenticated");const l=new At(n),u=i.split("/").pop()??"file";await l.commitFiles(`テンプレート削除: ${u}`,[{path:i,content:"",delete:!0}],s)},onSuccess:()=>{e.invalidateQueries({queryKey:["fileManager","root",r,s]}),e.invalidateQueries({queryKey:["fileManager","directory"]})}}}static DeleteDirectoryMutationParams(e,n,r,s){return{mutationFn:async i=>{if(!n)throw new Error("Not authenticated");const l=new At(n),u=await e5(l,i,s);if(u.length===0)return;const p=i.split("/").pop()??"folder";await l.commitFiles(`テンプレートフォルダ削除: ${p}`,u.map(f=>({path:f,content:"",delete:!0})),s)},onSuccess:()=>{e.invalidateQueries({queryKey:["fileManager","root",r,s]}),e.invalidateQueries({queryKey:["fileManager","directory"]})}}}static UploadFileMutationParams(e,n,r,s){return{mutationFn:async({targetDir:i,fileName:l,content:u})=>{if(!n)throw new Error("Not authenticated");const p=new At(n),f=`${i}/${l}`;await p.commitFiles(`テンプレートアップロード: ${l}`,[{path:f,content:u}],s)},onSuccess:()=>{e.invalidateQueries({queryKey:["fileManager","root",r,s]}),e.invalidateQueries({queryKey:["fileManager","directory"]})}}}static CreateFolderMutationParams(e,n,r,s){return{mutationFn:async({targetDir:i,folderName:l})=>{if(!n)throw new Error("Not authenticated");const u=new At(n),p=`${i}/${l}/.gitkeep`;await u.commitFiles(`テンプレートフォルダ作成: ${l}`,[{path:p,content:""}],s)},onSuccess:()=>{e.invalidateQueries({queryKey:["fileManager","root",r,s]}),e.invalidateQueries({queryKey:["fileManager","directory"]})}}}getRootEntries(){return this.rootQuery.data??[]}isRootLoading(){return this.rootQuery.isLoading}getRootError(){return this.rootQuery.error??null}getFileContent(){return this.fileQuery.data??null}isFileLoading(){return this.fileQuery.isLoading}getFileError(){return this.fileQuery.error??null}async fetchDirectoryEntries(e){if(!this.token)throw new Error("Not authenticated");return(await new At(this.token).listDirectoryEntries(e,this.branch)).map(s=>({name:s.name,path:`${e}/${s.name}`,type:s.type==="tree"?"directory":"file"}))}async saveFile(e,n){await this.saveMutation.mutateAsync({path:e,content:n})}async deleteFile(e){await this.deleteMutation.mutateAsync(e)}async deleteDirectory(e){await this.deleteDirectoryMutation.mutateAsync(e)}async uploadFile(e,n,r){await this.uploadMutation.mutateAsync({targetDir:e,fileName:n,content:r})}async createFolder(e,n){await this.createFolderMutation.mutateAsync({targetDir:e,folderName:n})}isSaving(){return this.saveMutation.isPending}isDeleting(){return this.deleteMutation.isPending||this.deleteDirectoryMutation.isPending}invalidateRoot(){this.queryClient.invalidateQueries({queryKey:["fileManager","root",this.basePath,this.branch]})}invalidateFile(){this.queryClient.invalidateQueries({queryKey:["fileManager","file"]})}invalidateDirectory(e){this.queryClient.invalidateQueries({queryKey:["fileManager","directory",e,this.branch]})}}async function e5(t,e,n){const r=await t.listDirectoryEntries(e,n),s=[];for(const i of r){const l=`${e}/${i.name}`;if(i.type==="blob")s.push(l);else{const u=await e5(t,l,n);s.push(...u)}}return s}function $ee(){return Fs((t,e)=>({targetId:"templates",expandedPaths:[],directoryContentsEntries:[],selectedPath:null,editContent:"",originalContent:"",deleteDialogOpen:!1,deleteTarget:null,uploadDialogOpen:!1,uploadTargetDir:"",createFolderDialogOpen:!1,createFolderTargetDir:"",isUploading:!1,uploadError:null,isSaving:!1,saveError:null,setTargetId:n=>t({targetId:n,expandedPaths:[],directoryContentsEntries:[],selectedPath:null,editContent:"",originalContent:""}),toggleExpand:n=>{const r=e().expandedPaths,s=r.includes(n);t({expandedPaths:s?r.filter(i=>i!==n):[...r,n]})},setExpandedPaths:n=>t({expandedPaths:n}),setDirectoryContents:(n,r)=>{const s=e().directoryContentsEntries,i=s.findIndex(([l])=>l===n);if(i>=0){const l=[...s];l[i]=[n,r],t({directoryContentsEntries:l})}else t({directoryContentsEntries:[...s,[n,r]]})},clearDirectoryContents:()=>t({directoryContentsEntries:[]}),removeDirectoryContents:n=>{const r=e().directoryContentsEntries;t({directoryContentsEntries:r.filter(([s])=>s!==n)})},setSelectedPath:n=>t({selectedPath:n}),setEditContent:n=>t({editContent:n}),setOriginalContent:n=>t({originalContent:n}),setDeleteDialogOpen:n=>t({deleteDialogOpen:n}),setDeleteTarget:n=>t({deleteTarget:n}),setUploadDialogOpen:n=>t({uploadDialogOpen:n}),setUploadTargetDir:n=>t({uploadTargetDir:n}),setCreateFolderDialogOpen:n=>t({createFolderDialogOpen:n}),setCreateFolderTargetDir:n=>t({createFolderTargetDir:n}),setUploading:n=>t({isUploading:n}),setUploadError:n=>t({uploadError:n}),setSaving:n=>t({isSaving:n}),setSaveError:n=>t({saveError:n})}))}class Nee{constructor(){St(this,"store",$ee());St(this,"cachedStoreState",null);St(this,"cachedState",null)}getState(){const e=this.store.getState();return this.cachedStoreState===e&&this.cachedState!==null?this.cachedState:(this.cachedStoreState=e,this.cachedState={targetId:e.targetId,expandedPaths:new Set(e.expandedPaths),directoryContents:new Map(e.directoryContentsEntries),selectedPath:e.selectedPath,editContent:e.editContent,originalContent:e.originalContent,deleteDialogOpen:e.deleteDialogOpen,deleteTarget:e.deleteTarget,uploadDialogOpen:e.uploadDialogOpen,uploadTargetDir:e.uploadTargetDir,createFolderDialogOpen:e.createFolderDialogOpen,createFolderTargetDir:e.createFolderTargetDir,isUploading:e.isUploading,uploadError:e.uploadError,isSaving:e.isSaving,saveError:e.saveError},this.cachedState)}setTargetId(e){this.store.getState().setTargetId(e)}toggleExpand(e){this.store.getState().toggleExpand(e)}setExpandedPaths(e){this.store.getState().setExpandedPaths([...e])}setDirectoryContents(e,n){this.store.getState().setDirectoryContents(e,n)}clearDirectoryContents(){this.store.getState().clearDirectoryContents()}removeDirectoryContents(e){this.store.getState().removeDirectoryContents(e)}setSelectedPath(e){this.store.getState().setSelectedPath(e)}setEditContent(e){this.store.getState().setEditContent(e)}setOriginalContent(e){this.store.getState().setOriginalContent(e)}openDeleteDialog(e,n){this.store.getState().setDeleteTarget({path:e,type:n}),this.store.getState().setDeleteDialogOpen(!0)}closeDeleteDialog(){this.store.getState().setDeleteDialogOpen(!1),this.store.getState().setDeleteTarget(null)}openUploadDialog(e){this.store.getState().setUploadTargetDir(e),this.store.getState().setUploadDialogOpen(!0)}closeUploadDialog(){this.store.getState().setUploadDialogOpen(!1),this.store.getState().setUploadTargetDir(""),this.store.getState().setUploadError(null)}openCreateFolderDialog(e){this.store.getState().setCreateFolderTargetDir(e),this.store.getState().setCreateFolderDialogOpen(!0)}closeCreateFolderDialog(){this.store.getState().setCreateFolderDialogOpen(!1),this.store.getState().setCreateFolderTargetDir("")}setUploading(e){this.store.getState().setUploading(e)}setUploadError(e){this.store.getState().setUploadError(e)}setSaving(e){this.store.getState().setSaving(e)}setSaveError(e){this.store.getState().setSaveError(e)}subscribe(e){return this.store.subscribe(e)}}const Iv=new Nee;class Fee{constructor(e){this.deps=e}getState(){const e=this.deps.presenter.getState(),n=this.deps.repo.getRootEntries(),r=this.findEntry(e.selectedPath,n,e.directoryContents),s=this.deps.repo.getFileContent(),i=(r==null?void 0:r.type)==="file"&&O2(r.name),l=!this.deps.isAuthInitialized||this.deps.repo.isRootLoading();return{targetId:e.targetId,targets:TC,branch:this.deps.branch,rootEntries:n,isRootLoading:l,rootError:this.deps.repo.getRootError(),expandedPaths:e.expandedPaths,directoryContents:e.directoryContents,selectedPath:e.selectedPath,selectedEntry:r,fileContent:s,isFileLoading:this.deps.repo.isFileLoading(),fileError:this.deps.repo.getFileError(),editContent:e.editContent,originalContent:e.originalContent,isDirty:e.editContent!==e.originalContent,canEdit:i,deleteDialogOpen:e.deleteDialogOpen,deleteTarget:e.deleteTarget,uploadDialogOpen:e.uploadDialogOpen,uploadTargetDir:e.uploadTargetDir,createFolderDialogOpen:e.createFolderDialogOpen,createFolderTargetDir:e.createFolderTargetDir,isUploading:e.isUploading,uploadError:e.uploadError,isSaving:this.deps.repo.isSaving()||e.isSaving,saveError:e.saveError,isDeleting:this.deps.repo.isDeleting(),hasEditPermission:this.deps.hasEditPermission}}changeTarget(e){this.deps.presenter.setTargetId(e),this.deps.presenter.clearDirectoryContents()}async toggleExpand(e){if(this.deps.presenter.getState().expandedPaths.has(e)){this.deps.presenter.toggleExpand(e);return}this.deps.presenter.setDirectoryContents(e,{entries:[],isLoading:!0,error:null}),this.deps.presenter.toggleExpand(e);try{const s=await this.deps.repo.fetchDirectoryEntries(e);this.deps.presenter.setDirectoryContents(e,{entries:s,isLoading:!1,error:null})}catch(s){oe.error("Failed to fetch directory entries",{path:e,error:s}),this.deps.presenter.setDirectoryContents(e,{entries:[],isLoading:!1,error:s})}}selectFile(e){this.getState().isDirty,this.deps.presenter.setSelectedPath(e),this.deps.presenter.setEditContent(""),this.deps.presenter.setOriginalContent(""),this.deps.navigateToFile(e)}clearSelection(){this.deps.presenter.setSelectedPath(null),this.deps.presenter.setEditContent(""),this.deps.presenter.setOriginalContent(""),this.deps.navigateToFile(void 0)}onFileContentLoaded(e){this.deps.presenter.setOriginalContent(e),this.deps.presenter.setEditContent(e)}updateContent(e){this.deps.presenter.setEditContent(e)}async save(){const e=this.getState();if(!(!e.selectedPath||!e.isDirty)){this.deps.presenter.setSaving(!0),this.deps.presenter.setSaveError(null);try{await this.deps.repo.saveFile(e.selectedPath,e.editContent),this.deps.presenter.setOriginalContent(e.editContent),oe.info("File saved",{path:e.selectedPath})}catch(n){oe.error("Failed to save file",{path:e.selectedPath,error:n}),this.deps.presenter.setSaveError(n instanceof Error?n.message:"保存に失敗しました")}finally{this.deps.presenter.setSaving(!1)}}}openDeleteDialog(e,n){this.deps.presenter.openDeleteDialog(e,n)}closeDeleteDialog(){this.deps.presenter.closeDeleteDialog()}async confirmDelete(){const e=this.getState();if(e.deleteTarget)try{if(e.deleteTarget.type==="directory"){await this.deps.repo.deleteDirectory(e.deleteTarget.path);const n=new Set(e.expandedPaths);for(const r of n)r.startsWith(e.deleteTarget.path)&&n.delete(r);this.deps.presenter.setExpandedPaths(n),this.deps.presenter.removeDirectoryContents(e.deleteTarget.path)}else await this.deps.repo.deleteFile(e.deleteTarget.path);e.selectedPath===e.deleteTarget.path&&this.clearSelection(),oe.info("Deleted",{path:e.deleteTarget.path,type:e.deleteTarget.type})}catch(n){throw oe.error("Failed to delete",{...e.deleteTarget,error:n}),n}finally{this.closeDeleteDialog()}}openUploadDialog(e){this.deps.presenter.openUploadDialog(e)}closeUploadDialog(){this.deps.presenter.closeUploadDialog()}async uploadFile(e){const n=this.getState();if(n.uploadTargetDir){this.deps.presenter.setUploading(!0),this.deps.presenter.setUploadError(null);try{const r=await Bee(e);if(await this.deps.repo.uploadFile(n.uploadTargetDir,e.name,r),oe.info("File uploaded",{targetDir:n.uploadTargetDir,fileName:e.name}),n.directoryContents.has(n.uploadTargetDir)){const s=await this.deps.repo.fetchDirectoryEntries(n.uploadTargetDir);this.deps.presenter.setDirectoryContents(n.uploadTargetDir,{entries:s,isLoading:!1,error:null})}this.closeUploadDialog()}catch(r){oe.error("Failed to upload file",{error:r}),this.deps.presenter.setUploadError(r instanceof Error?r.message:"アップロードに失敗しました")}finally{this.deps.presenter.setUploading(!1)}}}openCreateFolderDialog(e){this.deps.presenter.openCreateFolderDialog(e)}closeCreateFolderDialog(){this.deps.presenter.closeCreateFolderDialog()}async createFolder(e){const n=this.getState();if(!(!n.createFolderTargetDir||!e))try{if(await this.deps.repo.createFolder(n.createFolderTargetDir,e),oe.info("Folder created",{targetDir:n.createFolderTargetDir,folderName:e}),n.directoryContents.has(n.createFolderTargetDir)){const r=await this.deps.repo.fetchDirectoryEntries(n.createFolderTargetDir);this.deps.presenter.setDirectoryContents(n.createFolderTargetDir,{entries:r,isLoading:!1,error:null})}this.closeCreateFolderDialog()}catch(r){throw oe.error("Failed to create folder",{error:r}),r}}findEntry(e,n,r){if(!e)return null;for(const s of n)if(s.path===e)return s;for(const s of r.values())for(const i of s.entries)if(i.path===e)return i;return null}}function Bee(t){return new Promise((e,n)=>{const r=new FileReader;r.onload=()=>e(r.result),r.onerror=()=>n(r.error),r.readAsText(t)})}const Uee=t=>Iv.subscribe(t),rO=()=>Iv.getState();function Vee(){const{authUseCase:t}=rr(),{branchUseCase:e}=Ei(),n=t.getState(),{token:r,isInitialized:s,currentUser:i}=n,l=(e==null?void 0:e.getCurrentBranch())??"develop",u=ys(),p=ws(i,"canEditTemplates"),f=Di({from:"/templates/"}),m=ur(),g=P=>{m({to:"/templates",search:P?{file:P}:{},replace:!0})},y=b.useSyncExternalStore(Uee,rO,rO),v=b.useMemo(()=>{const P=TC.find(z=>z.id===y.targetId);return(P==null?void 0:P.path)??TC[0].path},[y.targetId]),C=jn(Cl.RootEntriesQueryParams(r,v,l)),S=jn(Cl.FileContentQueryParams(r,y.selectedPath,l)),j=Pn(Cl.SaveFileMutationParams(u,r,l)),D=Pn(Cl.DeleteFileMutationParams(u,r,v,l)),M=Pn(Cl.DeleteDirectoryMutationParams(u,r,v,l)),T=Pn(Cl.UploadFileMutationParams(u,r,v,l)),E=Pn(Cl.CreateFolderMutationParams(u,r,v,l)),k=new Cl(r,v,l,C,S,j,D,M,T,E,u),A=new Fee({repo:k,presenter:Iv,basePath:v,branch:l,isAuthInitialized:s,navigateToFile:g,hasEditPermission:p}),O=k.getFileContent(),I=b.useRef(null),$=b.useRef(null);b.useEffect(()=>{(y.selectedPath!==$.current||O!==null&&I.current===null)&&O!==null&&A.onFileContentLoaded(O),I.current=O,$.current=y.selectedPath},[O,y.selectedPath,A]);const R=b.useRef(!1);return b.useEffect(()=>{!R.current&&f.file&&!y.selectedPath&&(Iv.setSelectedPath(f.file),R.current=!0)},[f.file,y.selectedPath]),{templateUseCase:A}}function sO({useCase:t,state:e}){return a.jsxs($t,{"data-component-name":"cmp:TemplateTreePanel",sx:{height:"100%",display:"flex",flexDirection:"column"},children:[a.jsxs(B,{"data-component-name":"cmp:TemplateTreeHeader",sx:{p:2,borderBottom:1,borderColor:"divider"},children:[a.jsxs(_n,{fullWidth:!0,size:"small",sx:{mb:1},children:[a.jsx(nr,{children:"対象フォルダ"}),a.jsx(wn,{value:e.targetId,label:"対象フォルダ",onChange:n=>t.changeTarget(n.target.value),children:e.targets.map(n=>a.jsx(nt,{value:n.id,children:a.jsxs(B,{children:[a.jsx(G,{variant:"body1",children:n.label}),a.jsx(G,{variant:"caption",color:"text.secondary",children:n.path})]})},n.id))})]}),e.hasEditPermission&&a.jsxs(B,{sx:{display:"flex",gap:1},children:[a.jsx(Er,{title:"フォルダを作成",children:a.jsx(ft,{size:"small",onClick:()=>{var n;return t.openCreateFolderDialog(((n=e.targets.find(r=>r.id===e.targetId))==null?void 0:n.path)??"")},children:a.jsx(C2,{})})}),a.jsx(Er,{title:"ファイルをアップロード",children:a.jsx(ft,{size:"small",onClick:()=>{var n;return t.openUploadDialog(((n=e.targets.find(r=>r.id===e.targetId))==null?void 0:n.path)??"")},children:a.jsx(Ti,{})})})]})]}),a.jsx(B,{"data-component-name":"cmp:TemplateTreeBody",sx:{flex:1,overflow:"auto",p:1},children:e.isRootLoading?a.jsx(B,{sx:{display:"flex",justifyContent:"center",p:3},children:a.jsx(ut,{size:24})}):e.rootError?a.jsxs(G,{color:"error",sx:{p:2},children:["読み込みエラー: ",e.rootError.message]}):e.rootEntries.length===0?a.jsx(G,{color:"text.secondary",sx:{p:2},children:"ファイルがありません"}):a.jsx(as,{dense:!0,disablePadding:!0,children:e.rootEntries.map(n=>a.jsx(t5,{entry:n,level:0,useCase:t,state:e},n.path))})}),a.jsx(Hee,{useCase:t,state:e}),a.jsx(Wee,{useCase:t,state:e})]})}function t5({entry:t,level:e,useCase:n,state:r}){const s=r.expandedPaths.has(t.path),i=r.selectedPath===t.path,l=t.type==="directory",u=r.directoryContents.get(t.path),[p,f]=b.useState(!1),m=()=>{l?n.toggleExpand(t.path):n.selectFile(t.path)};return a.jsxs(a.Fragment,{children:[a.jsx(Os,{disablePadding:!0,onMouseEnter:()=>f(!0),onMouseLeave:()=>f(!1),secondaryAction:p&&l&&r.hasEditPermission?a.jsxs(B,{sx:{display:"flex",gap:.5},children:[a.jsx(Er,{title:"サブフォルダを作成",children:a.jsx(ft,{size:"small",onClick:g=>{g.stopPropagation(),n.openCreateFolderDialog(t.path)},children:a.jsx(C2,{fontSize:"small"})})}),a.jsx(Er,{title:"ファイルをアップロード",children:a.jsx(ft,{size:"small",onClick:g=>{g.stopPropagation(),n.openUploadDialog(t.path)},children:a.jsx(Ti,{fontSize:"small"})})})]}):void 0,children:a.jsxs(os,{selected:i,onClick:m,sx:{pl:e*2+1},children:[l&&a.jsx(Un,{sx:{minWidth:24},children:s?a.jsx(Wr,{fontSize:"small"}):a.jsx(Jl,{fontSize:"small"})}),a.jsx(Un,{sx:{minWidth:32},children:l?s?a.jsx(FJ,{color:"primary"}):a.jsx(ic,{color:"primary"}):a.jsx(vc,{color:"action"})}),a.jsx(Zn,{primary:t.name,primaryTypographyProps:{noWrap:!0,sx:{fontSize:"0.875rem"}}})]})}),l&&a.jsx(Co,{in:s,timeout:"auto",unmountOnExit:!0,children:u!=null&&u.isLoading?a.jsx(B,{sx:{display:"flex",justifyContent:"center",py:1},children:a.jsx(ut,{size:16})}):u!=null&&u.error?a.jsx(G,{color:"error",sx:{pl:(e+1)*2+1,py:1,fontSize:"0.75rem"},children:"エラー"}):(u==null?void 0:u.entries.length)===0?a.jsx(G,{color:"text.secondary",sx:{pl:(e+1)*2+1,py:1,fontSize:"0.75rem"},children:"(空)"}):a.jsx(as,{dense:!0,disablePadding:!0,children:u==null?void 0:u.entries.map(g=>a.jsx(t5,{entry:g,level:e+1,useCase:n,state:r},g.path))})})]})}function Hee({useCase:t,state:e}){const[n,r]=b.useState(""),[s,i]=b.useState(!1),l=async()=>{if(n.trim()){i(!0);try{await t.createFolder(n.trim()),r("")}finally{i(!1)}}},u=()=>{t.closeCreateFolderDialog(),r("")};return a.jsxs(Qt,{"data-component-name":"cmp:CreateFolderDialog",open:e.createFolderDialogOpen,onClose:u,children:[a.jsx(Yt,{children:"フォルダを作成"}),a.jsxs(Jt,{children:[a.jsxs(G,{variant:"body2",color:"text.secondary",sx:{mb:2},children:["作成先: ",e.createFolderTargetDir]}),a.jsx(Xe,{autoFocus:!0,fullWidth:!0,label:"フォルダ名",value:n,onChange:p=>r(p.target.value),onKeyDown:p=>{p.key==="Enter"&&n.trim()&&l()}})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:u,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:l,disabled:!n.trim()||s,children:s?a.jsx(ut,{size:20}):"作成"})]})]})}function Wee({useCase:t,state:e}){const[n,r]=b.useState(null),s=async()=>{n&&(await t.uploadFile(n),r(null))},i=()=>{t.closeUploadDialog(),r(null)};return a.jsxs(Qt,{"data-component-name":"cmp:UploadDialog",open:e.uploadDialogOpen,onClose:i,children:[a.jsx(Yt,{children:"ファイルをアップロード"}),a.jsxs(Jt,{children:[a.jsxs(G,{variant:"body2",color:"text.secondary",sx:{mb:2},children:["アップロード先: ",e.uploadTargetDir]}),a.jsxs(pe,{variant:"outlined",component:"label",fullWidth:!0,children:["ファイルを選択",a.jsx("input",{type:"file",hidden:!0,onChange:l=>{var u;return r(((u=l.target.files)==null?void 0:u[0])??null)}})]}),n&&a.jsx(G,{sx:{mt:1},children:n.name}),e.uploadError&&a.jsx(G,{color:"error",sx:{mt:1},children:e.uploadError})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:i,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:s,disabled:!n||e.isUploading,children:e.isUploading?a.jsx(ut,{size:20}):"アップロード"})]})]})}function iO({useCase:t,state:e,showHeader:n=!0}){if(!e.selectedPath)return a.jsxs($t,{"data-component-name":"cmp:TemplateEditorEmptyState",sx:{height:"100%",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",p:4},children:[a.jsx(vc,{sx:{fontSize:64,color:"text.disabled",mb:2}}),a.jsx(G,{color:"text.secondary",children:"ファイルを選択してください"})]});const r=e.selectedPath.split("/").pop()??"",s=O2(r),i=M2(r);return e.isFileLoading?a.jsx($t,{"data-component-name":"cmp:TemplateEditorLoading",sx:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:a.jsx(ut,{})}):e.fileError?a.jsx($t,{"data-component-name":"cmp:TemplateEditorError",sx:{height:"100%",p:3},children:a.jsxs(zt,{severity:"error",children:["ファイルの読み込みに失敗しました: ",e.fileError.message]})}):a.jsxs($t,{"data-component-name":"cmp:TemplateEditorPanel",sx:{height:"100%",display:"flex",flexDirection:"column"},children:[n&&a.jsxs(B,{"data-component-name":"cmp:TemplateEditorHeader",sx:{p:2,borderBottom:1,borderColor:"divider",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(G,{variant:"h6",noWrap:!0,children:r}),e.isDirty&&a.jsx(Ht,{label:"未保存",color:"warning",size:"small"})]}),e.hasEditPermission&&a.jsxs(B,{sx:{display:"flex",gap:1},children:[i?a.jsx(pe,{variant:"contained",startIcon:e.isSaving?a.jsx(ut,{size:16}):a.jsx(Ti,{}),onClick:()=>t.openUploadDialog(e.selectedPath.split("/").slice(0,-1).join("/")),disabled:e.isSaving,children:"アップロードして上書き"}):a.jsx(pe,{variant:"contained",startIcon:e.isSaving?a.jsx(ut,{size:16}):a.jsx(na,{}),onClick:()=>t.save(),disabled:!e.isDirty||e.isSaving||!s,children:"保存"}),a.jsx(ft,{color:"error",onClick:()=>{var l;return t.openDeleteDialog(e.selectedPath,((l=e.selectedEntry)==null?void 0:l.type)??"file")},children:a.jsx(zn,{})})]})]}),a.jsxs(B,{"data-component-name":"cmp:TemplateEditorBody",sx:{flex:1,overflow:"auto",p:2},children:[e.saveError&&a.jsx(zt,{severity:"error",sx:{mb:2},children:e.saveError}),s?a.jsx(Xe,{multiline:!0,fullWidth:!0,value:e.editContent,onChange:e.hasEditPermission?l=>t.updateContent(l.target.value):void 0,sx:{"& .MuiInputBase-root":{fontFamily:"monospace",fontSize:"0.875rem"},"& .MuiInputBase-input":{fontFamily:"monospace"}},minRows:20,placeholder:"ファイルの内容がここに表示されます",slotProps:{input:{readOnly:!e.hasEditPermission}}}):i&&e.fileContent?a.jsx(B,{sx:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",minHeight:400,bgcolor:"grey.100",borderRadius:1},children:a.jsx(B,{component:"img",src:`data:${Lee(r)};base64,${e.fileContent}`,alt:r,sx:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain"}})}):a.jsx(zt,{severity:"info",children:"このファイル形式はテキストとして編集できません。削除のみ可能です。"})]}),a.jsx(qee,{useCase:t,state:e})]})}function qee({useCase:t,state:e}){var i,l;const n=async()=>{await t.confirmDelete()},r=((i=e.deleteTarget)==null?void 0:i.path.split("/").pop())??"",s=((l=e.deleteTarget)==null?void 0:l.type)==="directory";return a.jsxs(Qt,{"data-component-name":"cmp:DeleteConfirmDialog",open:e.deleteDialogOpen,onClose:()=>t.closeDeleteDialog(),children:[a.jsx(Yt,{children:s?"フォルダを削除":"ファイルを削除"}),a.jsx(Jt,{children:a.jsx(Eo,{children:s?`フォルダ「${r}」とその中のすべてのファイルを削除しますか?この操作は取り消せません。`:`ファイル「${r}」を削除しますか?この操作は取り消せません。`})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>t.closeDeleteDialog(),children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:n,disabled:e.isDeleting,children:e.isDeleting?a.jsx(ut,{size:20}):"削除"})]})]})}const Gee=Ss("/templates/")({component:Zee,validateSearch:t=>({file:typeof t.file=="string"?t.file:void 0})});function Zee(){var u;const t=vr(),e=aa(t.breakpoints.down("md")),{templateUseCase:n}=Vee(),r=n.getState(),s=((u=r.selectedPath)==null?void 0:u.split("/").pop())??"ファイル編集",i=r.selectedPath?O2(s):!1,l=r.selectedPath?M2(s):!1;return a.jsx(B,{"data-component-name":"cmp:TemplatePage",sx:{flex:1,overflow:"auto",bgcolor:"background.default"},children:a.jsxs(ji,{maxWidth:"xl",sx:{py:3},children:[a.jsx(no,{items:[{label:"ファイル管理"}]}),e?a.jsxs(a.Fragment,{children:[a.jsx(B,{sx:{height:"calc(100vh - 180px)"},children:a.jsx(sO,{useCase:n,state:r})}),a.jsxs(Cu,{"data-component-name":"cmp:TemplateEditorDrawer",anchor:"right",open:!!r.selectedPath,onClose:()=>n.clearSelection(),PaperProps:{sx:{width:"100%",maxWidth:600,display:"flex",flexDirection:"column"}},children:[a.jsx(Dp,{title:s,icon:a.jsx(vc,{color:"action"}),onClose:()=>n.clearSelection(),componentName:"cmp:TemplateEditorDrawerHeader",actions:r.hasEditPermission?a.jsxs(a.Fragment,{children:[l?a.jsx(pe,{variant:"contained",size:"small",startIcon:r.isSaving?a.jsx(ut,{size:16,color:"inherit"}):a.jsx(Ti,{}),onClick:()=>n.openUploadDialog(r.selectedPath.split("/").slice(0,-1).join("/")),disabled:r.isSaving,children:"上書き"}):a.jsx(pe,{variant:"contained",size:"small",startIcon:r.isSaving?a.jsx(ut,{size:16,color:"inherit"}):a.jsx(na,{}),onClick:()=>n.save(),disabled:!r.isDirty||r.isSaving||!i,children:"保存"}),a.jsx(ft,{color:"error",size:"small",onClick:()=>{var p;return n.openDeleteDialog(r.selectedPath,((p=r.selectedEntry)==null?void 0:p.type)??"file")},children:a.jsx(zn,{})})]}):void 0}),a.jsx(B,{sx:{flex:1,overflow:"auto"},children:a.jsx(iO,{useCase:n,state:r,showHeader:!1})})]})]}):a.jsxs(Et,{"data-component-name":"cmp:TemplateLayout",container:!0,spacing:2,sx:{height:"calc(100vh - 180px)"},children:[a.jsx(Et,{item:!0,xs:12,md:4,lg:3,sx:{height:"100%"},children:a.jsx(sO,{useCase:n,state:r})}),a.jsx(Et,{item:!0,xs:12,md:8,lg:9,sx:{height:"100%"},children:a.jsx(iO,{useCase:n,state:r,showHeader:!0})})]})]})})}let BC=null;function Kee(t){BC=t}function n5(t){return!t||t.startsWith("http://")||t.startsWith("https://")?t:BC?`${BC}/${t}`:t}class Sd{constructor(e){St(this,"baseUrl");this.baseUrl=e??ta().fileUploadUrl}getAuthHeaders(){const e=localStorage.getItem("frelio_github_token");if(!e)throw new Error("Not authenticated");return{Authorization:`Bearer ${e}`}}async fetchFiles(e){oe.debug("WorkerStorageRepositoryImpl.fetchFiles",{year:e});const n=e?`${this.baseUrl}/list?year=${e}`:`${this.baseUrl}/list`,r=await fetch(n,{headers:this.getAuthHeaders()});if(!r.ok)throw new Error("Failed to fetch files");const s=await r.json();return s.baseUrl&&Kee(s.baseUrl),s.baseUrl&&(s.files=s.files.map(i=>({...i,url:`${s.baseUrl}/${i.url}`,...i.variants&&{variants:Object.fromEntries(Object.entries(i.variants).map(([l,u])=>[l,`${s.baseUrl}/${u}`]))}}))),s}async fetchYears(){oe.debug("WorkerStorageRepositoryImpl.fetchYears");const e=await fetch(`${this.baseUrl}/years`,{headers:this.getAuthHeaders()});if(!e.ok)throw new Error("Failed to fetch years");return e.json()}async uploadFile(e,n){oe.info("WorkerStorageRepositoryImpl.uploadFile",{fileName:e.name,uploadedBy:n});const r=new FormData;r.append("file",e),r.append("uploadedBy",n);const s=await fetch(`${this.baseUrl}/upload`,{method:"POST",headers:this.getAuthHeaders(),body:r});if(!s.ok){const i=await s.json();throw new Error(i.error||"Upload failed")}return s.json()}async uploadImageSet(e,n,r,s){oe.info("WorkerStorageRepositoryImpl.uploadImageSet",{originalName:n,uploadedBy:r,presetCount:e.size});const i=new FormData;i.append("uploadedBy",r),i.append("originalName",n),s&&(i.append("width",String(s.width)),i.append("height",String(s.height)));for(const[u,p]of e)i.append(u,p,`${u}.webp`);const l=await fetch(`${this.baseUrl}/upload-set`,{method:"POST",headers:this.getAuthHeaders(),body:i});if(!l.ok){const u=await l.json();throw new Error(u.error||"Upload failed")}return l.json()}async deleteFile(e,n){oe.info("WorkerStorageRepositoryImpl.deleteFile",{uuid:e,year:n});const r=n?`${this.baseUrl}/files/${e}?year=${n}`:`${this.baseUrl}/files/${e}`;if(!(await fetch(r,{method:"DELETE",headers:this.getAuthHeaders()})).ok)throw new Error("Failed to delete file")}async updateFileMetadata(e,n,r){oe.info("WorkerStorageRepositoryImpl.updateFileMetadata",{uuid:e,year:n,metadata:r});const s=await fetch(`${this.baseUrl}/files/${e}`,{method:"PATCH",headers:{...this.getAuthHeaders(),"Content-Type":"application/json"},body:JSON.stringify({year:n,...r})});if(!s.ok){const i=await s.json();throw new Error(i.error||"Update failed")}return s.json()}async rebuildIndex(e){if(oe.info("WorkerStorageRepositoryImpl.rebuildIndex",{year:e}),!(await fetch(`${this.baseUrl}/rebuild/${e}`,{method:"POST",headers:this.getAuthHeaders()})).ok)throw new Error("Failed to rebuild index")}}class zf{constructor(e,n,r,s){St(this,"baseRepo",new Sd);St(this,"queryClient",null);this.filesQuery=e,this.deleteMutation=n,this.rebuildMutation=r,this.updateAltMutation=s}setQueryClient(e){this.queryClient=e}static FilesQueryParams(e){const n=new Sd;return{queryKey:["files",e],queryFn:()=>n.fetchFiles(e??void 0)}}static DeleteMutationParams(e,n,r){const s=new Sd;return{mutationFn:i=>s.deleteFile(i,n??void 0),onSuccess:()=>{e.invalidateQueries({queryKey:["files",n]}),r==null||r()}}}static RebuildMutationParams(e,n){const r=new Sd;return{mutationFn:s=>r.rebuildIndex(s),onSuccess:()=>{e.invalidateQueries({queryKey:["files",n]})}}}static UpdateAltMutationParams(e,n,r){const s=new Sd;return{mutationFn:({uuid:i,alt:l})=>s.updateFileMetadata(i,n??new Date().getFullYear(),{alt:l}),onSuccess:i=>{e.invalidateQueries({queryKey:["files",n]}),r==null||r(i)}}}getData(){return this.filesQuery.data}isLoading(){return this.filesQuery.isLoading}getError(){return this.filesQuery.error}async deleteFile(e){await this.deleteMutation.mutateAsync(e)}isDeleting(){return this.deleteMutation.isPending}async rebuildIndex(e){await this.rebuildMutation.mutateAsync(e)}isRebuilding(){return this.rebuildMutation.isPending}async updateAlt(e,n){return this.updateAltMutation.mutateAsync({uuid:e,alt:n})}isUpdatingAlt(){return this.updateAltMutation.isPending}async uploadFile(e,n){return this.baseRepo.uploadFile(e,n)}async uploadImageSet(e,n,r,s){return this.baseRepo.uploadImageSet(e,n,r,s)}invalidateFiles(e){var n;(n=this.queryClient)==null||n.invalidateQueries({queryKey:["files",e]})}}const oO=30;function Qee(){return Fs(t=>({deleteTarget:null,uploading:!1,uploadError:null,cropDialogOpen:!1,cropImageUrl:null,pendingFile:null,detailTarget:null,editingAlt:"",sortBy:"uploadedAt",sortOrder:"desc",selectedYear:null,displayCount:oO,isDragOver:!1,setDeleteTarget:e=>t({deleteTarget:e}),setUploading:e=>t({uploading:e}),setUploadError:e=>t({uploadError:e}),setCropDialogOpen:e=>t({cropDialogOpen:e}),setCropImageUrl:e=>t({cropImageUrl:e}),setPendingFile:e=>t({pendingFile:e}),setDetailTarget:e=>t({detailTarget:e}),setEditingAlt:e=>t({editingAlt:e}),setSortBy:e=>t({sortBy:e}),setSortOrder:e=>t({sortOrder:e}),setSelectedYear:e=>t({selectedYear:e,displayCount:oO}),setDisplayCount:e=>t({displayCount:e}),setIsDragOver:e=>t({isDragOver:e})}))}class Jee{constructor(){St(this,"store",Qee());St(this,"cachedState",null);St(this,"cachedStoreState",null)}getState(){const e=this.store.getState();return this.cachedStoreState===e&&this.cachedState!==null?this.cachedState:(this.cachedStoreState=e,this.cachedState={deleteTarget:e.deleteTarget,uploading:e.uploading,uploadError:e.uploadError,cropDialogOpen:e.cropDialogOpen,cropImageUrl:e.cropImageUrl,pendingFile:e.pendingFile,detailTarget:e.detailTarget,editingAlt:e.editingAlt,sortBy:e.sortBy,sortOrder:e.sortOrder,selectedYear:e.selectedYear,displayCount:e.displayCount,isDragOver:e.isDragOver},this.cachedState)}setDeleteTarget(e){this.store.getState().setDeleteTarget(e)}setUploading(e){this.store.getState().setUploading(e)}setUploadError(e){this.store.getState().setUploadError(e)}setCropDialogOpen(e){this.store.getState().setCropDialogOpen(e)}setCropImageUrl(e){this.store.getState().setCropImageUrl(e)}setPendingFile(e){this.store.getState().setPendingFile(e)}setDetailTarget(e){this.store.getState().setDetailTarget(e)}setEditingAlt(e){this.store.getState().setEditingAlt(e)}setSortBy(e){this.store.getState().setSortBy(e)}setSortOrder(e){this.store.getState().setSortOrder(e)}setSelectedYear(e){this.store.getState().setSelectedYear(e)}setDisplayCount(e){this.store.getState().setDisplayCount(e)}setIsDragOver(e){this.store.getState().setIsDragOver(e)}openCropDialog(e,n){this.setCropImageUrl(e),this.setPendingFile(n),this.setCropDialogOpen(!0)}closeCropDialog(){const e=this.getState().cropImageUrl;e&&URL.revokeObjectURL(e),this.setCropDialogOpen(!1),this.setCropImageUrl(null),this.setPendingFile(null)}openDetail(e){this.setDetailTarget(e),this.setEditingAlt(e.alt??"")}openDetailByUuid(e,n){const r=n.find(s=>s.uuid===e);r&&this.openDetail(r)}closeDetail(){this.setDetailTarget(null)}loadMore(e){const n=this.getState().displayCount;this.setDisplayCount(n+e)}toggleSortOrder(){const e=this.getState().sortOrder;this.setSortOrder(e==="asc"?"desc":"asc")}subscribe(e){return this.store.subscribe(e)}}class Yee{execute(e,n,r){const s=[...e];return s.sort((i,l)=>{let u=0;switch(n){case"originalName":u=i.originalName.localeCompare(l.originalName,"ja");break;case"size":u=i.size-l.size;break;case"uploadedAt":default:u=new Date(i.uploadedAt).getTime()-new Date(l.uploadedAt).getTime();break}return r==="asc"?u:-u}),s}}const aO=new Set(["image/jpeg","image/png","image/gif","image/webp","image/svg+xml","image/bmp","image/tiff"]),Xee=new Set(["image/jpeg","image/png","image/webp","image/bmp"]),ete=new Set(["application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","text/plain","text/csv","application/json"]),tte=new Set(["video/mp4","video/webm","video/ogg","video/quicktime","video/x-msvideo"]),nte=new Set(["audio/mpeg","audio/wav","audio/ogg","audio/webm","audio/aac","audio/flac"]);class rte{getProcessType(e){return aO.has(e)?"image":ete.has(e)?"document":tte.has(e)?"video":nte.has(e)?"audio":"other"}getStrategy(e,n){return e==="image"&&this.isCroppable(n)?"crop-first":"direct-upload"}isCroppable(e){return Xee.has(e)}isImage(e){return aO.has(e)}decide(e){const n=this.getProcessType(e),r=this.getStrategy(n,e),s=r==="crop-first",i=n==="image"&&this.isCroppable(e);return{processType:n,strategy:r,requiresCrop:s,generateImageSet:i}}canUpload(e,n){return this.getProcessType(e)!==void 0}}const ste=30;class ite{constructor(e){St(this,"sortStorageFilesUseCase",new Yee);St(this,"fileTypeDecider",new rte);this.deps=e}getState(){const{repo:e,presenter:n}=this.deps,r=n.getState(),s=e.getData(),i=s?this.sortStorageFilesUseCase.execute(s.files,r.sortBy,r.sortOrder):[],l=i.slice(0,r.displayCount),u=r.displayCount<i.length;return{...r,data:s,isLoading:e.isLoading(),error:e.getError(),sortedFiles:i,displayedFiles:l,hasMore:u,isDeleting:e.isDeleting(),isRebuilding:e.isRebuilding(),isUpdatingAlt:e.isUpdatingAlt(),canEdit:this.deps.canEdit}}initializeYear(){const{repo:e,presenter:n}=this.deps,r=e.getData(),s=n.getState();r&&s.selectedYear===null&&r.availableYears.length>0&&n.setSelectedYear(r.year)}handleFileSelect(e){const{presenter:n}=this.deps;if(this.fileTypeDecider.decide(e.type).requiresCrop){const s=URL.createObjectURL(e);n.openCropDialog(s,e)}else this.uploadFile(e)}async uploadFile(e,n){const{repo:r,presenter:s,githubUser:i}=this.deps;s.setUploading(!0),s.setUploadError(null);try{const l=e instanceof Blob&&!(e instanceof File)?new File([e],n??"cropped-image.jpg",{type:e.type}):e;await r.uploadFile(l,(i==null?void 0:i.login)??"unknown");const u=new Date().getFullYear();r.invalidateFiles(u),s.getState().selectedYear!==u&&s.setSelectedYear(u)}catch(l){s.setUploadError(l.message)}finally{s.setUploading(!1)}}async handleCropComplete(e){var u;const{repo:n,presenter:r,githubUser:s}=this.deps,i=r.getState(),l=((u=i.pendingFile)==null?void 0:u.name)??"image.jpg";r.closeCropDialog(),r.setUploading(!0),r.setUploadError(null);try{const p={width:e.width,height:e.height};await n.uploadImageSet(e.imageSet,l,(s==null?void 0:s.login)??"unknown",p);const f=new Date().getFullYear();n.invalidateFiles(f),i.selectedYear!==f&&r.setSelectedYear(f)}catch(p){r.setUploadError(p.message)}finally{r.setUploading(!1)}}closeCropDialog(){this.deps.presenter.closeCropDialog()}async deleteFile(e){await this.deps.repo.deleteFile(e)}async rebuildIndex(e){await this.deps.repo.rebuildIndex(e)}async updateAlt(e,n){await this.deps.repo.updateAlt(e,n)}setSelectedYear(e){this.deps.presenter.setSelectedYear(e)}setSortBy(e){this.deps.presenter.setSortBy(e)}toggleSortOrder(){this.deps.presenter.toggleSortOrder()}setDragOver(e){this.deps.presenter.setIsDragOver(e)}handleDrop(e){const{presenter:n}=this.deps;if(this.fileTypeDecider.decide(e.type).requiresCrop){const s=URL.createObjectURL(e);n.openCropDialog(s,e)}else this.uploadFile(e)}loadMore(){this.deps.presenter.loadMore(ste)}openDetail(e){this.deps.presenter.openDetail(e),this.deps.navigateToDetail(e.uuid)}closeDetail(){this.deps.presenter.closeDetail(),this.deps.navigateToDetail(void 0)}openDetailByUuid(e,n){this.deps.presenter.openDetailByUuid(e,n)}openDeleteDialog(e){this.deps.presenter.setDeleteTarget(e)}closeDeleteDialog(){this.deps.presenter.setDeleteTarget(null)}clearUploadError(){this.deps.presenter.setUploadError(null)}setEditingAlt(e){this.deps.presenter.setEditingAlt(e)}}const Ed=new Jee,ote=t=>Ed.subscribe(t),lO=()=>Ed.getState();function ate(){const{authUseCase:t}=rr(),{githubUser:e,currentUser:n}=t.getState(),r=ys(),s=ws(n,"canEditStorage"),i=Di({from:"/storage/"}),l=ur(),u=C=>{l({to:"/storage",search:C?{detail:C}:{},replace:!0})};b.useSyncExternalStore(ote,lO,lO);const p=Ed.getState(),f=new zf(jn(zf.FilesQueryParams(p.selectedYear)),Pn(zf.DeleteMutationParams(r,p.selectedYear,()=>Ed.setDeleteTarget(null))),Pn(zf.RebuildMutationParams(r,p.selectedYear)),Pn(zf.UpdateAltMutationParams(r,p.selectedYear,C=>Ed.setDetailTarget(C))));f.setQueryClient(r);const m=new ite({repo:f,presenter:Ed,githubUser:e,navigateToDetail:u,canEdit:s}),g=b.useRef(!1);b.useEffect(()=>{g.current||(g.current=!0,m.initializeYear())},[m]);const y=b.useRef(!1),v=f.getData();return b.useEffect(()=>{!y.current&&i.detail&&(v!=null&&v.files)&&!p.detailTarget&&(m.openDetailByUuid(i.detail,v.files),y.current=!0)},[i.detail,v==null?void 0:v.files,p.detailTarget,m]),{storageUseCase:m}}function UC(t){if(t===0)return"0 B";const e=1024,n=["B","KB","MB","GB"],r=Math.floor(Math.log(t)/Math.log(e));return parseFloat((t/Math.pow(e,r)).toFixed(1))+" "+n[r]}function lte(t){return new Date(t).toLocaleDateString("ja-JP",{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function cte(t){return new Date(t).toLocaleDateString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit"})}function Uc(t){return t.startsWith("image/")}function r5(t){return t==="application/pdf"}var VC=function(t,e){return VC=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(n[s]=r[s])},VC(t,e)};function ute(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");VC(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var ss=function(){return ss=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},ss.apply(this,arguments)};var c1,cO;function dte(){if(cO)return c1;cO=1;var t=!1,e,n,r,s,i,l,u,p,f,m,g,y,v,C,S;function j(){if(!t){t=!0;var M=navigator.userAgent,T=/(?:MSIE.(\d+\.\d+))|(?:(?:Firefox|GranParadiso|Iceweasel).(\d+\.\d+))|(?:Opera(?:.+Version.|.)(\d+\.\d+))|(?:AppleWebKit.(\d+(?:\.\d+)?))|(?:Trident\/\d+\.\d+.*rv:(\d+\.\d+))/.exec(M),E=/(Mac OS X)|(Windows)|(Linux)/.exec(M);if(y=/\b(iPhone|iP[ao]d)/.exec(M),v=/\b(iP[ao]d)/.exec(M),m=/Android/i.exec(M),C=/FBAN\/\w+;/i.exec(M),S=/Mobile/i.exec(M),g=!!/Win64/.exec(M),T){e=T[1]?parseFloat(T[1]):T[5]?parseFloat(T[5]):NaN,e&&document&&document.documentMode&&(e=document.documentMode);var k=/(?:Trident\/(\d+.\d+))/.exec(M);l=k?parseFloat(k[1])+4:e,n=T[2]?parseFloat(T[2]):NaN,r=T[3]?parseFloat(T[3]):NaN,s=T[4]?parseFloat(T[4]):NaN,s?(T=/(?:Chrome\/(\d+\.\d+))/.exec(M),i=T&&T[1]?parseFloat(T[1]):NaN):i=NaN}else e=n=r=i=s=NaN;if(E){if(E[1]){var A=/(?:Mac OS X (\d+(?:[._]\d+)?))/.exec(M);u=A?parseFloat(A[1].replace("_",".")):!0}else u=!1;p=!!E[2],f=!!E[3]}else u=p=f=!1}}var D={ie:function(){return j()||e},ieCompatibilityMode:function(){return j()||l>e},ie64:function(){return D.ie()&&g},firefox:function(){return j()||n},opera:function(){return j()||r},webkit:function(){return j()||s},safari:function(){return D.webkit()},chrome:function(){return j()||i},windows:function(){return j()||p},osx:function(){return j()||u},linux:function(){return j()||f},iphone:function(){return j()||y},mobile:function(){return j()||y||v||m||S},nativeApp:function(){return j()||C},android:function(){return j()||m},ipad:function(){return j()||v}};return c1=D,c1}var u1,uO;function pte(){if(uO)return u1;uO=1;var t=!!(typeof window<"u"&&window.document&&window.document.createElement),e={canUseDOM:t,canUseWorkers:typeof Worker<"u",canUseEventListeners:t&&!!(window.addEventListener||window.attachEvent),canUseViewport:t&&!!window.screen,isInWorker:!t};return u1=e,u1}var d1,dO;function fte(){if(dO)return d1;dO=1;var t=pte(),e;t.canUseDOM&&(e=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0);/**
387
387
  * Checks if an event is supported in the current execution environment.
388
388
  *
389
389
  * NOTE: This will not work correctly for non-generic events such as `change`,
@@ -501,4 +501,4 @@ GitHub OAuth App に組織へのアクセス権を付与してください:
501
501
  1. https://github.com/settings/applications を開く
502
502
  2. この OAuth App をクリック
503
503
  3. 「Organization access」で対象の組織の「Grant」をクリック`):n.setError(`ログイン処理中にエラーが発生しました: ${p}`)}}}const lae=new oae;function cae(){const t=ur(),{authUseCase:e}=rr(),n=new aae({presenter:lae,login:s=>e.login(s),navigate:s=>t({to:s})}),r=b.useRef(!1);return b.useEffect(()=>{if(r.current)return;r.current=!0;const s=new URLSearchParams(window.location.search);n.handleCallback(s)},[n]),{authCallbackUseCase:n}}const uae=Ss("/auth/callback")({component:dae});function dae(){const{authCallbackUseCase:t}=cae(),{error:e}=t.getState();return e?a.jsx(ji,{"data-component-name":"cmp:AuthCallbackPage",maxWidth:"sm",children:a.jsx(B,{display:"flex",justifyContent:"center",alignItems:"center",minHeight:"100vh",children:a.jsxs(zt,{"data-component-name":"cmp:AuthCallbackError",severity:"error",sx:{width:"100%"},action:a.jsx(pe,{color:"inherit",size:"small",onClick:()=>t.navigateToLogin(),children:"ログインに戻る"}),children:[a.jsx(G,{variant:"subtitle1",gutterBottom:!0,children:"ログインエラー"}),a.jsx(G,{variant:"body2",sx:{whiteSpace:"pre-line"},children:e})]})})}):a.jsxs(B,{"data-component-name":"cmp:AuthCallbackLoading",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",minHeight:"100vh",children:[a.jsx(ut,{}),a.jsx(G,{sx:{mt:2},children:"ログイン中..."})]})}class mo{constructor(e,n,r){this.queries=e,this.rebuildMutation=n,this.searchMutation=r}static ContentTypeQueryParams(e,n,r){return{queryKey:["content-type",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJson(Kl(n),r)},enabled:!!e}}static UiQueryParams(e,n,r){return{queryKey:["content-type-ui",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJson(Ld(n),r)},enabled:!!e}}static ViewsQueryParams(e,n,r){return{queryKey:["content-type-views",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJsonOrDefault(sc(n),null,r)},enabled:!!e}}static ViewIndexQueryParams(e,n,r,s,i,l){const u=Ql(r,n,s,i);return{queryKey:["view-index",r,n,u,l],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJsonOrDefault(u,[],l)},enabled:!!e}}static RebuildIndexMutationParams(e,n,r,s){return{mutationFn:async()=>{if(!n)throw new Error("Not authenticated");const i=new At(n);oe.info("RebuildIndex: start",{contentTypeId:r,branch:s});const l=await i.fetchJsonOrDefault(sc(r),null,s),[u,p]=await Promise.all([mo.loadAllContents(i,"published",r,s),mo.loadAllContents(i,"private",r,s)]),f=[],m=(l==null?void 0:l.views)??[];for(const g of m){const y=Ql("published",r,g.id,(l==null?void 0:l.defaultViewId)??null),v=u.map(C=>DC(C,g.columns));f.push({path:y,content:JSON.stringify(v,null,2)})}for(const g of m){const y=Ql("private",r,g.id,(l==null?void 0:l.defaultViewId)??null),v=p.map(C=>DC(C,g.columns));f.push({path:y,content:JSON.stringify(v,null,2)})}if(m.length===0){const g=u.map(S=>({contentId:S.contentId,status:S.status,createdAt:S.createdAt,updatedAt:S.updatedAt,title:S.title,publishedAt:S.publishedAt,createdBy:S.createdBy,updatedBy:S.updatedBy})),y=p.map(S=>({contentId:S.contentId,status:S.status,createdAt:S.createdAt,updatedAt:S.updatedAt,title:S.title,publishedAt:S.publishedAt,createdBy:S.createdBy,updatedBy:S.updatedBy})),v=Ah("published",r),C=Ah("private",r);(g.length>0||await i.fetchFileOrNull(v,s))&&f.push({path:v,content:JSON.stringify(g,null,2)}),(y.length>0||await i.fetchFileOrNull(C,s))&&f.push({path:C,content:JSON.stringify(y,null,2)})}return f.length>0&&await i.commitFiles(`chore: インデックスを再生成 (${r})`,f,s),oe.info("RebuildIndex: done",{contentTypeId:r,contentsCount:u.length,privateCount:p.length,viewCount:m.length}),{contentsCount:u.length,privateCount:p.length}},onSuccess:()=>{e.invalidateQueries({queryKey:["view-index","published",r]}),e.invalidateQueries({queryKey:["view-index","private",r]})}}}static async loadAllContents(e,n,r,s){var p;const i=QK(n,r),l=await e.listDirectory(i,s),u=[];for(const f of l){const m=`${i}/${f}`,g=f.replace(".json","");try{const y=await e.fetchJson(m,s),v=new Date().toISOString(),C=y.createdBy??"unknown";u.push({contentId:y.contentId??g,title:y.title??((p=y.data)==null?void 0:p.title)??g,status:y.status??(n==="published"?"published":"draft"),createdAt:y.createdAt??v,updatedAt:y.updatedAt??v,publishedAt:y.publishedAt??null,createdBy:C,updatedBy:y.updatedBy??C,data:y.data??{}})}catch(y){oe.warn("RebuildIndex: failed to read file",{filePath:m,error:y})}}return u}static SearchCodeMutationParams(e,n){return{mutationFn:async r=>{if(!e)throw new Error("Not authenticated");return(await new At(e).searchCode(r,"data/contents")).items.filter(u=>{const p=u.path.split("/");return p.length>=4&&p[3]===n}).map(u=>u.name.replace(".json","")).filter(u=>!u.startsWith("_"))}}}getContentType(){return this.queries.contentType.data}getContentTypeLabel(){var e;return(e=this.queries.ui.data)==null?void 0:e.label}getUi(){return this.queries.ui.data}getViews(){return this.queries.views.data}getPublishedIndex(){return this.queries.publishedIndex.data??[]}getPrivateIndex(){return this.queries.privateIndex.data??[]}isLoading(){return this.queries.contentType.isLoading||this.queries.ui.isLoading||this.queries.views.isLoading||this.queries.publishedIndex.isLoading||this.queries.privateIndex.isLoading}getError(){return this.queries.contentType.error||this.queries.ui.error||this.queries.views.error||this.queries.publishedIndex.error||this.queries.privateIndex.error}isRebuilding(){var e;return((e=this.rebuildMutation)==null?void 0:e.isPending)??!1}async rebuildIndex(){if(!this.rebuildMutation)throw new Error("Rebuild mutation not initialized");return this.rebuildMutation.mutateAsync()}async searchGitHub(e){if(!this.searchMutation)throw new Error("Search mutation not initialized");return this.searchMutation.mutateAsync(e)}}function pae(){return Fs(t=>({sortOverride:null,visibilityFilter:"all",searchQuery:"",searchResultIds:null,isSearching:!1,searchError:null,searchMode:fae(),setSortOverride:e=>t({sortOverride:e}),setVisibilityFilter:e=>t({visibilityFilter:e}),setSearchQuery:e=>t({searchQuery:e}),setSearchResultIds:e=>t({searchResultIds:e,isSearching:!1}),setSearchLoading:e=>t({isSearching:e}),setSearchError:e=>t({searchError:e,isSearching:!1}),setSearchMode:e=>t({searchMode:e,searchResultIds:null,searchQuery:"",searchError:null}),clearSearch:()=>t({searchQuery:"",searchResultIds:null,isSearching:!1,searchError:null})}))}function J5(t,e){return`frelio_sort_${t}_${e}`}const Y5="frelio_search_mode";function fae(){try{const t=localStorage.getItem(Y5);if(t==="local"||t==="github")return t}catch{}return"local"}function hae(t){try{localStorage.setItem(Y5,t)}catch{}}function mae(t,e){try{const n=J5(t,e),r=localStorage.getItem(n);if(r){const s=JSON.parse(r);if(s.field&&(s.direction==="asc"||s.direction==="desc"))return s}}catch{}return null}function gae(t,e,n){try{const r=J5(t,e);n?localStorage.setItem(r,JSON.stringify(n)):localStorage.removeItem(r)}catch{}}class yae{constructor(){St(this,"store",pae());St(this,"cachedState",null);St(this,"cachedStoreState",null);St(this,"currentContentTypeId",null);St(this,"currentViewId",null);St(this,"searchCache",new Map);St(this,"lastSearchTime",0)}getState(){const e=this.store.getState();return this.cachedStoreState===e&&this.cachedState!==null?this.cachedState:(this.cachedStoreState=e,this.cachedState={sortOverride:e.sortOverride,visibilityFilter:e.visibilityFilter,searchQuery:e.searchQuery,searchResultIds:e.searchResultIds,isSearching:e.isSearching,searchError:e.searchError,searchMode:e.searchMode},this.cachedState)}initializeSort(e,n,r){if(this.currentContentTypeId=e,this.currentViewId=n,r)this.store.getState().setSortOverride(r);else{const s=mae(e,n);this.store.getState().setSortOverride(s)}}setSortOverride(e){this.store.getState().setSortOverride(e),this.currentContentTypeId&&this.currentViewId&&gae(this.currentContentTypeId,this.currentViewId,e)}handleSortClick(e){const n=this.getState().sortOverride;(n==null?void 0:n.field)===e?this.setSortOverride({field:e,direction:n.direction==="asc"?"desc":"asc"}):this.setSortOverride({field:e,direction:"desc"})}resetSort(){this.setSortOverride(null)}setVisibilityFilter(e){this.store.getState().setVisibilityFilter(e)}setSearchQuery(e){this.store.getState().setSearchQuery(e)}setSearchResultIds(e){this.store.getState().setSearchResultIds(e)}setSearchLoading(e){this.store.getState().setSearchLoading(e)}setSearchError(e){this.store.getState().setSearchError(e)}setSearchMode(e){this.store.getState().setSearchMode(e),hae(e)}clearSearch(){this.store.getState().clearSearch()}subscribe(e){return this.store.subscribe(e)}getSearchCache(e,n){var r;return((r=this.searchCache.get(e))==null?void 0:r.get(n))??null}setSearchCache(e,n,r){this.searchCache.has(e)||this.searchCache.set(e,new Map),this.searchCache.get(e).set(n,r)}clearSearchCache(e){this.searchCache.delete(e)}getLastSearchTime(){return this.lastSearchTime}setLastSearchTime(e){this.lastSearchTime=e}}function vae(t,e){return!e||e.length===0?t:t.filter(n=>e.every(r=>{const s=n[r.field];switch(r.operator){case"eq":return s===r.value;case"neq":return s!==r.value;case"in":return r.value.includes(s);case"nin":return!r.value.includes(s);case"contains":return Array.isArray(s)?s.includes(r.value):String(s).includes(String(r.value));case"startsWith":return String(s).startsWith(String(r.value));case"endsWith":return String(s).endsWith(String(r.value));default:return!0}}))}function xae(t,e,n){const r=n??e;return r?[...t].sort((s,i)=>{const l=s[r.field],u=i[r.field];if(l==null&&u==null)return 0;if(l==null)return 1;if(u==null)return-1;if(typeof l=="string"&&typeof u=="string"){const p=l.localeCompare(u);return r.direction==="asc"?p:-p}return typeof l=="number"&&typeof u=="number"?r.direction==="asc"?l-u:u-l:0}):t}function bae(t,e,n,r){const s=vae(t,e);return xae(s,n,r)}const Sae=bae,pA=6e3;class Cae{constructor(e){this.deps=e}getState(){const{repo:e,presenter:n,searchView:r}=this.deps,s=n.getState(),i=e.getViews(),l=r??(i==null?void 0:i.defaultViewId)??"all",u=(i==null?void 0:i.views.find(T=>T.id===l))??(i==null?void 0:i.views[0]),p=[{field:"title",label:"タイトル"},{field:"updatedAt",label:"更新日",width:"150px"},{field:"publishedAt",label:"公開日",width:"150px"}],f=[{field:"createdAt",label:"作成日",width:"150px"},{field:"status",label:"状態",width:"100px"}],m=(u==null?void 0:u.columns)??p,g=new Set(m.map(T=>T.field)),y=f.filter(T=>!g.has(T.field)),v=[...m,...y],C=(u==null?void 0:u.defaultSort)??{field:"createdAt",direction:"desc"},S=e.getPublishedIndex(),j=e.getPrivateIndex();let D;switch(s.visibilityFilter){case"public":D=S;break;case"private":const T=new Set(S.map(A=>A.contentId));D=j.filter(A=>!T.has(A.contentId));break;case"all":default:const E=new Set(S.map(A=>A.contentId)),k=j.filter(A=>!E.has(A.contentId));D=[...S,...k];break}let M=Sae(D,(u==null?void 0:u.filters)??[],(u==null?void 0:u.defaultSort)??C,s.sortOverride);if(s.searchResultIds!==null){const T=new Set(s.searchResultIds);M=M.filter(E=>T.has(E.contentId))}return{contentType:e.getContentType(),contentTypeLabel:e.getContentTypeLabel(),viewsDef:i,selectedViewId:l,activeView:u,columns:v,defaultSort:C,filteredEntries:M,allEntries:D,sortOverride:s.sortOverride,visibilityFilter:s.visibilityFilter,isLoading:e.isLoading(),error:e.getError(),isRebuilding:e.isRebuilding(),searchQuery:s.searchQuery,isSearching:s.isSearching,searchError:s.searchError,searchMode:s.searchMode}}changeView(e){const{presenter:n,contentTypeId:r,navigate:s}=this.deps;n.resetSort(),s("/contents/$contentTypeId",{contentTypeId:r},{view:e})}setVisibilityFilter(e){this.deps.presenter.setVisibilityFilter(e)}handleSortClick(e){const{presenter:n,contentTypeId:r,navigate:s,searchView:i}=this.deps,l=n.getState().sortOverride,u=(l==null?void 0:l.field)===e?{field:e,direction:l.direction==="asc"?"desc":"asc"}:{field:e,direction:"desc"};n.handleSortClick(e);const p={};i&&(p.view=i),p.sort=u.field,p.order=u.direction,s("/contents/$contentTypeId",{contentTypeId:r},p)}async rebuildIndex(){await this.deps.repo.rebuildIndex()}setSearchQuery(e){this.deps.presenter.setSearchQuery(e)}setSearchLoading(e){this.deps.presenter.setSearchLoading(e)}setSearchResultIds(e){this.deps.presenter.setSearchResultIds(e)}setSearchError(e){this.deps.presenter.setSearchError(e)}setSearchMode(e){this.deps.presenter.setSearchMode(e)}clearSearch(){this.deps.presenter.clearSearch()}async search(e){const{presenter:n}=this.deps;if(!e.trim()){this.clearSearch();return}this.setSearchQuery(e),n.getState().searchMode==="local"?this.searchLocal(e):await this.searchGitHub(e)}searchLocal(e){const n=e.toLowerCase(),s=this.getState().allEntries.filter(i=>i.title&&String(i.title).toLowerCase().includes(n)||i.contentId.toLowerCase().includes(n)?!0:Object.values(i).some(l=>l==null?!1:typeof l=="string"?l.toLowerCase().includes(n):Array.isArray(l)?l.some(u=>String(u).toLowerCase().includes(n)):String(l).toLowerCase().includes(n))).map(i=>i.contentId);this.setSearchResultIds(s)}async searchGitHub(e){const{repo:n,presenter:r,contentTypeId:s}=this.deps,i=r.getSearchCache(s,e);if(i){this.setSearchResultIds(i);return}const l=Date.now(),u=r.getLastSearchTime(),p=l-u;if(p<pA){const f=Math.ceil((pA-p)/1e3);this.setSearchError(`レート制限中です。${f}秒後にお試しください。`);return}this.setSearchLoading(!0);try{r.setLastSearchTime(Date.now());const f=await n.searchGitHub(e);r.setSearchCache(s,e,f),this.setSearchResultIds(f)}catch(f){this.setSearchError(f instanceof Error?f.message:"検索に失敗しました")}}onContentTypeChange(){const{presenter:e,contentTypeId:n}=this.deps;e.clearSearchCache(n),this.clearSearch()}}const Jv=new yae;function wae(){return b.useSyncExternalStore(t=>Jv.subscribe(t),()=>Jv.getState())}function jae(){var A;const{authUseCase:t}=rr(),{branchUseCase:e}=Ei(),{token:n}=t.getState(),r=(e==null?void 0:e.getCurrentBranch())??"develop",s=ur(),i=ys(),{contentTypeId:l}=uc({from:"/contents/$contentTypeId/"}),u=Di({from:"/contents/$contentTypeId/"}),p=u.view,f=u.sort,m=u.order;wae();const g=jn(mo.ViewsQueryParams(n,l,r)),y=g.isSuccess||g.data!==void 0,v=((A=g.data)==null?void 0:A.defaultViewId)??null,C=p??v??"default",S=b.useRef(null);b.useEffect(()=>{const O=`${l}_${C}`;if(S.current!==O){S.current=O;const I=f&&m?{field:f,direction:m}:null;Jv.initializeSort(l,C,I)}},[l,C,f,m]);const j=Pn(mo.RebuildIndexMutationParams(i,n,l,r)),D=Pn(mo.SearchCodeMutationParams(n,l)),M=mo.ViewIndexQueryParams(n,l,"published",C,v,r),T=mo.ViewIndexQueryParams(n,l,"private",C,v,r),E=new mo({contentType:jn(mo.ContentTypeQueryParams(n,l,r)),ui:jn(mo.UiQueryParams(n,l,r)),views:g,publishedIndex:jn({...M,enabled:M.enabled&&y}),privateIndex:jn({...T,enabled:T.enabled&&y})},j,D),k=new Cae({repo:E,presenter:Jv,contentTypeId:l,searchView:p,navigate:(O,I,$)=>s({to:O,params:I,search:$})});return b.useEffect(()=>{k.onContentTypeChange()},[l]),{contentListUseCase:k}}const X5=Ss("/contents/$contentTypeId/")({component:Tae,validateSearch:t=>({view:typeof t.view=="string"?t.view:void 0,sort:typeof t.sort=="string"?t.sort:void 0,order:t.order==="asc"||t.order==="desc"?t.order:void 0})});function e4({field:t,value:e}){if(t==="status")return a.jsx(n4,{status:e});if(t==="publishedAt"||t==="updatedAt"||t==="createdAt")return a.jsx(a.Fragment,{children:e?cte(e):"—"});if(t==="tags"&&Array.isArray(e))return a.jsxs(Ro,{direction:"row",spacing:.5,flexWrap:"wrap",useFlexGap:!0,children:[e.slice(0,3).map(n=>a.jsx(Ht,{label:n,size:"small",variant:"outlined"},String(n))),e.length>3&&a.jsx(Ht,{label:`+${e.length-3}`,size:"small",variant:"outlined"})]});if(e&&typeof e=="object"&&"url"in e){const n=e;return n.url?a.jsx(B,{component:"img",src:n5(n.url),alt:n.originalName??"",sx:{maxWidth:150,maxHeight:80,objectFit:"cover",borderRadius:1}}):a.jsx(a.Fragment,{children:"—"})}return e&&typeof e=="object"?a.jsx(a.Fragment,{children:"—"}):a.jsx(a.Fragment,{children:e??"—"})}function Tae(){const t=vr(),e=aa(t.breakpoints.down("md")),{contentListUseCase:n}=jae(),r=n.getState(),{contentType:s,contentTypeLabel:i,viewsDef:l,selectedViewId:u,activeView:p,columns:f,defaultSort:m,filteredEntries:g,sortOverride:y,visibilityFilter:v,isLoading:C,error:S,isRebuilding:j,searchQuery:D,isSearching:M,searchError:T,searchMode:E}=r,{contentTypeId:k}=X5.useParams();return C?a.jsx(B,{"data-component-name":"cmp:ContentListPageLoading",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(ut,{})}):S?a.jsx(B,{"data-component-name":"cmp:ContentListPageError",sx:{flex:1,overflow:"auto",p:3},children:a.jsxs(zt,{severity:"error",children:["Error: ",S.message]})}):a.jsxs(B,{"data-component-name":"cmp:ContentListPage",sx:{flex:1,overflow:"auto"},children:[a.jsx(Mx,{"data-component-name":"cmp:RebuildingBackdrop",open:j,sx:{color:"#fff",zIndex:A=>A.zIndex.drawer+1},children:a.jsxs(B,{display:"flex",flexDirection:"column",alignItems:"center",gap:2,children:[a.jsx(ut,{color:"inherit"}),a.jsx(G,{children:"インデックスを再生成中..."})]})}),a.jsxs(B,{sx:{p:3},children:[a.jsx(no,{items:[{label:`${i??k}一覧`}]}),a.jsx(la,{title:`${i??k} 一覧`,actions:a.jsx(pe,{variant:"contained",startIcon:a.jsx(Qn,{}),component:gs,to:`/contents/${k}/new`,children:"新規作成"})}),a.jsxs(B,{"data-component-name":"cmp:ContentListToolbar",display:"flex",alignItems:"center",gap:2,mb:2,flexWrap:"wrap",children:[a.jsx(Dae,{searchQuery:D,isSearching:M,searchError:T,searchMode:E,onSearch:A=>n.search(A),onClear:()=>n.clearSearch(),onModeChange:A=>n.setSearchMode(A)}),a.jsx(Eae,{value:v,onChange:A=>n.setVisibilityFilter(A)}),l&&l.views.length>1&&a.jsx(yc,{value:u,exclusive:!0,onChange:(A,O)=>O&&n.changeView(O),size:"small",children:l.views.map(A=>a.jsx(ts,{value:A.id,children:A.label},A.id))}),a.jsx(Rae,{isRebuilding:j,onRebuild:()=>n.rebuildIndex()})]}),g.length===0?a.jsx(zt,{severity:"info",children:"表示できるコンテンツがありません"}):e?a.jsx(kae,{entries:g,contentTypeId:k,columns:f}):a.jsx(Mae,{entries:g,contentTypeId:k,columns:f,sortOverride:y,defaultSort:(p==null?void 0:p.defaultSort)??m,onSortClick:A=>n.handleSortClick(A)})]})]})}function Dae({searchQuery:t,isSearching:e,searchError:n,searchMode:r,onSearch:s,onClear:i,onModeChange:l}){const[u,p]=b.useState(t),[f,m]=b.useState(null),g=S=>{S.key==="Enter"&&(S.preventDefault(),s(u))},y=()=>{p(""),i()},v=()=>{s(u)},C=S=>{l(S),m(null)};return a.jsxs(B,{display:"flex",alignItems:"flex-start",gap:.5,children:[a.jsx(Xe,{size:"small",placeholder:r==="local"?"インデックス内を検索...":"GitHub全文検索...",value:u,onChange:S=>p(S.target.value),onKeyDown:g,sx:{minWidth:220},InputProps:{endAdornment:a.jsxs(c2,{position:"end",children:[u&&a.jsx(ft,{size:"small",onClick:y,edge:"end",children:a.jsx(SJ,{fontSize:"small"})}),a.jsx(ft,{size:"small",onClick:v,disabled:e,edge:"end",title:"検索",children:e?a.jsx(ut,{size:20}):a.jsx(Om,{})})]})},error:!!n,helperText:n}),a.jsx(ft,{size:"small",onClick:S=>m(S.currentTarget),title:"検索オプション",children:a.jsx(EP,{})}),a.jsxs(Cp,{anchorEl:f,open:!!f,onClose:()=>m(null),children:[a.jsx(nt,{disabled:!0,sx:{opacity:1,fontWeight:"bold",fontSize:"0.75rem",py:.5},children:"検索対象"}),a.jsx(wo,{}),a.jsx(nt,{selected:r==="local",onClick:()=>C("local"),children:a.jsx(Zn,{primary:"ローカル",secondary:"現在のブランチのインデックス"})}),a.jsx(nt,{selected:r==="github",onClick:()=>C("github"),children:a.jsx(Zn,{primary:"GitHub",secondary:"デフォルトブランチの全文検索"})})]})]})}function Eae({value:t,onChange:e}){return a.jsxs(yc,{value:t,exclusive:!0,onChange:(n,r)=>r&&e(r),size:"small",children:[a.jsx(ts,{value:"all",children:"すべて"}),a.jsx(ts,{value:"public",children:"公開"}),a.jsx(ts,{value:"private",children:"非公開"})]})}function Rae({isRebuilding:t,onRebuild:e}){const[n,r]=b.useState(!1),s=()=>{r(!1),e()};return a.jsxs(a.Fragment,{children:[a.jsx(ft,{size:"small",onClick:()=>r(!0),disabled:t,title:"インデックスを再生成",children:t?a.jsx(ut,{size:20}):a.jsx(kP,{})}),a.jsxs(Qt,{"data-component-name":"cmp:RebuildIndexDialog",open:n,onClose:()=>r(!1),children:[a.jsx(Yt,{children:"インデックスの再生成"}),a.jsx(Jt,{children:a.jsx(Eo,{children:"ビューのインデックスを再生成しますか?"})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>r(!1),children:"キャンセル"}),a.jsx(pe,{onClick:s,variant:"contained",autoFocus:!0,children:"再生成"})]})]})]})}function t4({contentTypeId:t,contentId:e}){const n=ur(),[r,s]=b.useState(null),i=()=>{s(null),n({to:`/contents/${t}/new`,search:{duplicateFrom:e}})};return a.jsxs(a.Fragment,{children:[a.jsx(ft,{"data-component-name":"cmp:RowActionMenuButton",size:"small",onClick:l=>{l.stopPropagation(),s(l.currentTarget)},children:a.jsx(EP,{fontSize:"small"})}),a.jsx(Cp,{"data-component-name":"cmp:RowActionMenu",anchorEl:r,open:!!r,onClose:()=>s(null),children:a.jsxs(nt,{onClick:i,children:[a.jsx(bP,{fontSize:"small",sx:{mr:1}}),a.jsx(Zn,{children:"複製"})]})})]})}function kae({entries:t,contentTypeId:e,columns:n}){return a.jsx(Ro,{"data-component-name":"cmp:MobileList",spacing:2,children:t.map(r=>a.jsx(Su,{"data-component-name":"cmp:ContentCard",children:a.jsxs(B,{display:"flex",alignItems:"stretch",children:[a.jsx(_I,{component:gs,to:`/contents/${e}/${r.contentId}`,sx:{flex:1},children:a.jsxs(Sp,{children:[a.jsxs(B,{display:"flex",justifyContent:"space-between",alignItems:"center",mb:1,children:[a.jsx(G,{variant:"subtitle1",fontWeight:"bold",noWrap:!0,sx:{flex:1,mr:1},children:r.title??r.contentId}),a.jsx(n4,{status:r.status})]}),n.filter(s=>s.field!=="title"&&s.field!=="status").slice(0,2).map(s=>a.jsxs(G,{variant:"body2",color:"text.secondary",children:[s.label,": ",a.jsx(e4,{field:s.field,value:r[s.field]})]},`${r.contentId}-${s.field}`))]})}),a.jsx(B,{display:"flex",alignItems:"center",px:.5,children:a.jsx(t4,{contentTypeId:e,contentId:r.contentId})})]})},r.contentId))})}function Mae({entries:t,contentTypeId:e,columns:n,sortOverride:r,defaultSort:s,onSortClick:i}){const l=ur(),u=r??s;return a.jsx($t,{"data-component-name":"cmp:DesktopTable",children:a.jsxs(wp,{children:[a.jsx(jm,{children:a.jsxs(eo,{children:[n.map(p=>a.jsx(Kt,{width:p.width,children:p.sortable!==!1?a.jsx(gK,{active:u.field===p.field,direction:u.field===p.field?u.direction:"desc",onClick:()=>i(p.field),children:p.label}):p.label},p.field)),a.jsx(Kt,{width:48},"__actions")]})}),a.jsx(jp,{children:t.map(p=>a.jsxs(eo,{hover:!0,sx:{cursor:"pointer"},onClick:()=>l({to:`/contents/${e}/${p.contentId}`}),children:[n.map(f=>a.jsx(Kt,{children:a.jsx(e4,{field:f.field,value:p[f.field]})},f.field)),a.jsx(Kt,{onClick:f=>f.stopPropagation(),children:a.jsx(t4,{contentTypeId:e,contentId:p.contentId})},"__actions")]},p.contentId))})]})})}function n4({status:t}){const e=()=>{switch(t){case"published":return"公開";case"unpublished":return"非公開";case"draft":default:return"下書き"}},n=()=>{switch(t){case"published":return"success";case"unpublished":return"warning";case"draft":default:return"default"}};return a.jsx(Ht,{label:e(),color:n(),size:"small"})}var Vm=t=>t.type==="checkbox",Kc=t=>t instanceof Date,Js=t=>t==null;const r4=t=>typeof t=="object";var qr=t=>!Js(t)&&!Array.isArray(t)&&r4(t)&&!Kc(t),s4=t=>qr(t)&&t.target?Vm(t.target)?t.target.checked:t.target.value:t,Oae=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,i4=(t,e)=>t.has(Oae(e)),Aae=t=>{const e=t.constructor&&t.constructor.prototype;return qr(e)&&e.hasOwnProperty("isPrototypeOf")},W2=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Br(t){if(t instanceof Date)return new Date(t);const e=typeof FileList<"u"&&t instanceof FileList;if(W2&&(t instanceof Blob||e))return t;const n=Array.isArray(t);if(!n&&!(qr(t)&&Aae(t)))return t;const r=n?[]:Object.create(Object.getPrototypeOf(t));for(const s in t)Object.prototype.hasOwnProperty.call(t,s)&&(r[s]=Br(t[s]));return r}var ob=t=>/^\w*$/.test(t),yr=t=>t===void 0,q2=t=>Array.isArray(t)?t.filter(Boolean):[],G2=t=>q2(t.replace(/["|']|\]/g,"").split(/\.|\[/)),rt=(t,e,n)=>{if(!e||!qr(t))return n;const r=(ob(e)?[e]:G2(e)).reduce((s,i)=>Js(s)?s:s[i],t);return yr(r)||r===t?yr(t[e])?n:t[e]:r},gi=t=>typeof t=="boolean",As=t=>typeof t=="function",Bn=(t,e,n)=>{let r=-1;const s=ob(e)?[e]:G2(e),i=s.length,l=i-1;for(;++r<i;){const u=s[r];let p=n;if(r!==l){const f=t[u];p=qr(f)||Array.isArray(f)?f:isNaN(+s[r+1])?{}:[]}if(u==="__proto__"||u==="constructor"||u==="prototype")return;t[u]=p,t=t[u]}};const Yv={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change"},xo={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},Ma={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},o4=We.createContext(null);o4.displayName="HookFormControlContext";const Z2=()=>We.useContext(o4);var a4=(t,e,n,r=!0)=>{const s={defaultValues:e._defaultValues};for(const i in t)Object.defineProperty(s,i,{get:()=>{const l=i;return e._proxyFormState[l]!==xo.all&&(e._proxyFormState[l]=!r||xo.all),n&&(n[l]=!0),t[l]}});return s};const K2=typeof window<"u"?We.useLayoutEffect:We.useEffect;function _ae(t){const e=Z2(),{control:n=e,disabled:r,name:s,exact:i}=t||{},[l,u]=We.useState(n._formState),p=We.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return K2(()=>n._subscribe({name:s,formState:p.current,exact:i,callback:f=>{!r&&u({...n._formState,...f})}}),[s,r,i]),We.useEffect(()=>{p.current.isValid&&n._setValid(!0)},[n]),We.useMemo(()=>a4(l,n,p.current,!1),[l,n])}var vi=t=>typeof t=="string",ow=(t,e,n,r,s)=>vi(t)?(r&&e.watch.add(t),rt(n,t,s)):Array.isArray(t)?t.map(i=>(r&&e.watch.add(i),rt(n,i))):(r&&(e.watchAll=!0),n),aw=t=>Js(t)||!r4(t);function bo(t,e,n=new WeakSet){if(aw(t)||aw(e))return Object.is(t,e);if(Kc(t)&&Kc(e))return Object.is(t.getTime(),e.getTime());const r=Object.keys(t),s=Object.keys(e);if(r.length!==s.length)return!1;if(n.has(t)||n.has(e))return!0;n.add(t),n.add(e);for(const i of r){const l=t[i];if(!s.includes(i))return!1;if(i!=="ref"){const u=e[i];if(Kc(l)&&Kc(u)||qr(l)&&qr(u)||Array.isArray(l)&&Array.isArray(u)?!bo(l,u,n):!Object.is(l,u))return!1}}return!0}function Iae(t){const e=Z2(),{control:n=e,name:r,defaultValue:s,disabled:i,exact:l,compute:u}=t||{},p=We.useRef(s),f=We.useRef(u),m=We.useRef(void 0),g=We.useRef(n),y=We.useRef(r);f.current=u;const[v,C]=We.useState(()=>{const E=n._getWatch(r,p.current);return f.current?f.current(E):E}),S=We.useCallback(E=>{const k=ow(r,n._names,E||n._formValues,!1,p.current);return f.current?f.current(k):k},[n._formValues,n._names,r]),j=We.useCallback(E=>{if(!i){const k=ow(r,n._names,E||n._formValues,!1,p.current);if(f.current){const A=f.current(k);bo(A,m.current)||(C(A),m.current=A)}else C(k)}},[n._formValues,n._names,i,r]);K2(()=>((g.current!==n||!bo(y.current,r))&&(g.current=n,y.current=r,j()),n._subscribe({name:r,formState:{values:!0},exact:l,callback:E=>{j(E.values)}})),[n,l,r,j]),We.useEffect(()=>n._removeUnmounted());const D=g.current!==n,M=y.current,T=We.useMemo(()=>{if(i)return null;const E=!D&&!bo(M,r);return D||E?S():null},[i,D,r,M,S]);return T!==null?T:v}function Pae(t){const e=Z2(),{name:n,disabled:r,control:s=e,shouldUnregister:i,defaultValue:l,exact:u=!0}=t,p=i4(s._names.array,n),f=We.useMemo(()=>rt(s._formValues,n,rt(s._defaultValues,n,l)),[s,n,l]),m=Iae({control:s,name:n,defaultValue:f,exact:u}),g=_ae({control:s,name:n,exact:u}),y=We.useRef(t),v=We.useRef(void 0),C=We.useRef(s.register(n,{...t.rules,value:m,...gi(t.disabled)?{disabled:t.disabled}:{}}));y.current=t;const S=We.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!rt(g.errors,n)},isDirty:{enumerable:!0,get:()=>!!rt(g.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!rt(g.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!rt(g.validatingFields,n)},error:{enumerable:!0,get:()=>rt(g.errors,n)}}),[g,n]),j=We.useCallback(E=>C.current.onChange({target:{value:s4(E),name:n},type:Yv.CHANGE}),[n]),D=We.useCallback(()=>C.current.onBlur({target:{value:rt(s._formValues,n),name:n},type:Yv.BLUR}),[n,s._formValues]),M=We.useCallback(E=>{const k=rt(s._fields,n);k&&k._f&&E&&(k._f.ref={focus:()=>As(E.focus)&&E.focus(),select:()=>As(E.select)&&E.select(),setCustomValidity:A=>As(E.setCustomValidity)&&E.setCustomValidity(A),reportValidity:()=>As(E.reportValidity)&&E.reportValidity()})},[s._fields,n]),T=We.useMemo(()=>({name:n,value:m,...gi(r)||g.disabled?{disabled:g.disabled||r}:{},onChange:j,onBlur:D,ref:M}),[n,r,g.disabled,j,D,M,m]);return We.useEffect(()=>{const E=s._options.shouldUnregister||i,k=v.current;k&&k!==n&&!p&&s.unregister(k),s.register(n,{...y.current.rules,...gi(y.current.disabled)?{disabled:y.current.disabled}:{}});const A=(O,I)=>{const $=rt(s._fields,O);$&&$._f&&($._f.mount=I)};if(A(n,!0),E){const O=Br(rt(s._options.defaultValues,n,y.current.defaultValue));Bn(s._defaultValues,n,O),yr(rt(s._formValues,n))&&Bn(s._formValues,n,O)}return!p&&s.register(n),v.current=n,()=>{(p?E&&!s._state.action:E)?s.unregister(n):A(n,!1)}},[n,s,p,i]),We.useEffect(()=>{s._setDisabledField({disabled:r,name:n})},[r,n,s]),We.useMemo(()=>({field:T,formState:g,fieldState:S}),[T,g,S])}const uo=t=>t.render(Pae(t)),Lae=We.createContext(null);Lae.displayName="HookFormContext";var Q2=(t,e,n,r,s)=>e?{...n[t],types:{...n[t]&&n[t].types?n[t].types:{},[r]:s||!0}}:{},hh=t=>Array.isArray(t)?t:[t],fA=()=>{let t=[];return{get observers(){return t},next:s=>{for(const i of t)i.next&&i.next(s)},subscribe:s=>(t.push(s),{unsubscribe:()=>{t=t.filter(i=>i!==s)}}),unsubscribe:()=>{t=[]}}};function l4(t,e){const n={};for(const r in t)if(t.hasOwnProperty(r)){const s=t[r],i=e[r];if(s&&qr(s)&&i){const l=l4(s,i);qr(l)&&(n[r]=l)}else t[r]&&(n[r]=i)}return n}var Rs=t=>qr(t)&&!Object.keys(t).length,J2=t=>t.type==="file",Xv=t=>{if(!W2)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},c4=t=>t.type==="select-multiple",Y2=t=>t.type==="radio",zae=t=>Y2(t)||Vm(t),E1=t=>Xv(t)&&t.isConnected;function $ae(t,e){const n=e.slice(0,-1).length;let r=0;for(;r<n;)t=yr(t)?r++:t[e[r++]];return t}function Nae(t){for(const e in t)if(t.hasOwnProperty(e)&&!yr(t[e]))return!1;return!0}function Ur(t,e){const n=Array.isArray(e)?e:ob(e)?[e]:G2(e),r=n.length===1?t:$ae(t,n),s=n.length-1,i=n[s];return r&&delete r[i],s!==0&&(qr(r)&&Rs(r)||Array.isArray(r)&&Nae(r))&&Ur(t,n.slice(0,-1)),t}var Fae=t=>{for(const e in t)if(As(t[e]))return!0;return!1};function u4(t){return Array.isArray(t)||qr(t)&&!Fae(t)}function lw(t,e={}){for(const n in t){const r=t[n];u4(r)?(e[n]=Array.isArray(r)?[]:{},lw(r,e[n])):yr(r)||(e[n]=!0)}return e}function wd(t,e,n){n||(n=lw(e));for(const r in t){const s=t[r];if(u4(s))yr(e)||aw(n[r])?n[r]=lw(s,Array.isArray(s)?[]:{}):wd(s,Js(e)?{}:e[r],n[r]);else{const i=e[r];n[r]=!bo(s,i)}}return n}const hA={value:!1,isValid:!1},mA={value:!0,isValid:!0};var d4=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!yr(t[0].attributes.value)?yr(t[0].value)||t[0].value===""?mA:{value:t[0].value,isValid:!0}:mA:hA}return hA},p4=(t,{valueAsNumber:e,valueAsDate:n,setValueAs:r})=>yr(t)?t:e?t===""?NaN:t&&+t:n&&vi(t)?new Date(t):r?r(t):t;const gA={isValid:!1,value:null};var f4=t=>Array.isArray(t)?t.reduce((e,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:e,gA):gA;function yA(t){const e=t.ref;return J2(e)?e.files:Y2(e)?f4(t.refs).value:c4(e)?[...e.selectedOptions].map(({value:n})=>n):Vm(e)?d4(t.refs).value:p4(yr(e.value)?t.ref.value:e.value,t)}var Bae=(t,e,n,r)=>{const s={};for(const i of t){const l=rt(e,i);l&&Bn(s,i,l._f)}return{criteriaMode:n,names:[...t],fields:s,shouldUseNativeValidation:r}},ex=t=>t instanceof RegExp,Ff=t=>yr(t)?t:ex(t)?t.source:qr(t)?ex(t.value)?t.value.source:t.value:t,vA=t=>({isOnSubmit:!t||t===xo.onSubmit,isOnBlur:t===xo.onBlur,isOnChange:t===xo.onChange,isOnAll:t===xo.all,isOnTouch:t===xo.onTouched});const xA="AsyncFunction";var Uae=t=>!!t&&!!t.validate&&!!(As(t.validate)&&t.validate.constructor.name===xA||qr(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===xA)),Vae=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate),bA=(t,e,n)=>!n&&(e.watchAll||e.watch.has(t)||[...e.watch].some(r=>t.startsWith(r)&&/^\.\w+/.test(t.slice(r.length))));const mh=(t,e,n,r)=>{for(const s of n||Object.keys(t)){const i=rt(t,s);if(i){const{_f:l,...u}=i;if(l){if(l.refs&&l.refs[0]&&e(l.refs[0],s)&&!r)return!0;if(l.ref&&e(l.ref,l.name)&&!r)return!0;if(mh(u,e))break}else if(qr(u)&&mh(u,e))break}}};function SA(t,e,n){const r=rt(t,n);if(r||ob(n))return{error:r,name:n};const s=n.split(".");for(;s.length;){const i=s.join("."),l=rt(e,i),u=rt(t,i);if(l&&!Array.isArray(l)&&n!==i)return{name:n};if(u&&u.type)return{name:i,error:u};if(u&&u.root&&u.root.type)return{name:`${i}.root`,error:u.root};s.pop()}return{name:n}}var Hae=(t,e,n,r)=>{n(t);const{name:s,...i}=t;return Rs(i)||Object.keys(i).length>=Object.keys(e).length||Object.keys(i).find(l=>e[l]===(!r||xo.all))},Wae=(t,e,n)=>!t||!e||t===e||hh(t).some(r=>r&&(n?r===e:r.startsWith(e)||e.startsWith(r))),qae=(t,e,n,r,s)=>s.isOnAll?!1:!n&&s.isOnTouch?!(e||t):(n?r.isOnBlur:s.isOnBlur)?!t:(n?r.isOnChange:s.isOnChange)?t:!0,Gae=(t,e)=>!q2(rt(t,e)).length&&Ur(t,e),Zae=(t,e,n)=>{const r=hh(rt(t,n));return Bn(r,"root",e[n]),Bn(t,n,r),t};function CA(t,e,n="validate"){if(vi(t)||Array.isArray(t)&&t.every(vi)||gi(t)&&!t)return{type:n,message:vi(t)?t:"",ref:e}}var md=t=>qr(t)&&!ex(t)?t:{value:t,message:""},wA=async(t,e,n,r,s,i)=>{const{ref:l,refs:u,required:p,maxLength:f,minLength:m,min:g,max:y,pattern:v,validate:C,name:S,valueAsNumber:j,mount:D}=t._f,M=rt(n,S);if(!D||e.has(S))return{};const T=u?u[0]:l,E=z=>{s&&T.reportValidity&&(T.setCustomValidity(gi(z)?"":z||""),T.reportValidity())},k={},A=Y2(l),O=Vm(l),I=A||O,$=(j||J2(l))&&yr(l.value)&&yr(M)||Xv(l)&&l.value===""||M===""||Array.isArray(M)&&!M.length,R=Q2.bind(null,S,r,k),P=(z,N,H,U=Ma.maxLength,L=Ma.minLength)=>{const W=z?N:H;k[S]={type:z?U:L,message:W,ref:l,...R(z?U:L,W)}};if(i?!Array.isArray(M)||!M.length:p&&(!I&&($||Js(M))||gi(M)&&!M||O&&!d4(u).isValid||A&&!f4(u).isValid)){const{value:z,message:N}=vi(p)?{value:!!p,message:p}:md(p);if(z&&(k[S]={type:Ma.required,message:N,ref:T,...R(Ma.required,N)},!r))return E(N),k}if(!$&&(!Js(g)||!Js(y))){let z,N;const H=md(y),U=md(g);if(!Js(M)&&!isNaN(M)){const L=l.valueAsNumber||M&&+M;Js(H.value)||(z=L>H.value),Js(U.value)||(N=L<U.value)}else{const L=l.valueAsDate||new Date(M),W=le=>new Date(new Date().toDateString()+" "+le),K=l.type=="time",Q=l.type=="week";vi(H.value)&&M&&(z=K?W(M)>W(H.value):Q?M>H.value:L>new Date(H.value)),vi(U.value)&&M&&(N=K?W(M)<W(U.value):Q?M<U.value:L<new Date(U.value))}if((z||N)&&(P(!!z,H.message,U.message,Ma.max,Ma.min),!r))return E(k[S].message),k}if((f||m)&&!$&&(vi(M)||i&&Array.isArray(M))){const z=md(f),N=md(m),H=!Js(z.value)&&M.length>+z.value,U=!Js(N.value)&&M.length<+N.value;if((H||U)&&(P(H,z.message,N.message),!r))return E(k[S].message),k}if(v&&!$&&vi(M)){const{value:z,message:N}=md(v);if(ex(z)&&!M.match(z)&&(k[S]={type:Ma.pattern,message:N,ref:l,...R(Ma.pattern,N)},!r))return E(N),k}if(C){if(As(C)){const z=await C(M,n),N=CA(z,T);if(N&&(k[S]={...N,...R(Ma.validate,N.message)},!r))return E(N.message),k}else if(qr(C)){let z={};for(const N in C){if(!Rs(z)&&!r)break;const H=CA(await C[N](M,n),T,N);H&&(z={...H,...R(N,H.message)},E(H.message),r&&(k[S]=z))}if(!Rs(z)&&(k[S]={ref:T,...z},!r))return k}}return E(!0),k};const Kae={mode:xo.onSubmit,reValidateMode:xo.onChange,shouldFocusError:!0};function Qae(t={}){let e={...Kae,...t},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:As(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},r={},s=qr(e.defaultValues)||qr(e.values)?Br(e.defaultValues||e.values)||{}:{},i=e.shouldUnregister?{}:Br(s),l={action:!1,mount:!1,watch:!1,keepIsValid:!1},u={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},p,f=0;const m={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={...m};let y={...g};const v={array:fA(),state:fA()},C=e.criteriaMode===xo.all,S=Z=>q=>{clearTimeout(f),f=setTimeout(Z,q)},j=async Z=>{if(!l.keepIsValid&&!e.disabled&&(g.isValid||y.isValid||Z)){let q;e.resolver?(q=Rs((await I()).errors),D()):q=await R(r,!0),q!==n.isValid&&v.state.next({isValid:q})}},D=(Z,q)=>{!e.disabled&&(g.isValidating||g.validatingFields||y.isValidating||y.validatingFields)&&((Z||Array.from(u.mount)).forEach(se=>{se&&(q?Bn(n.validatingFields,se,q):Ur(n.validatingFields,se))}),v.state.next({validatingFields:n.validatingFields,isValidating:!Rs(n.validatingFields)}))},M=(Z,q=[],se,xe,ee=!0,ne=!0)=>{if(xe&&se&&!e.disabled){if(l.action=!0,ne&&Array.isArray(rt(r,Z))){const he=se(rt(r,Z),xe.argA,xe.argB);ee&&Bn(r,Z,he)}if(ne&&Array.isArray(rt(n.errors,Z))){const he=se(rt(n.errors,Z),xe.argA,xe.argB);ee&&Bn(n.errors,Z,he),Gae(n.errors,Z)}if((g.touchedFields||y.touchedFields)&&ne&&Array.isArray(rt(n.touchedFields,Z))){const he=se(rt(n.touchedFields,Z),xe.argA,xe.argB);ee&&Bn(n.touchedFields,Z,he)}(g.dirtyFields||y.dirtyFields)&&(n.dirtyFields=wd(s,i)),v.state.next({name:Z,isDirty:z(Z,q),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else Bn(i,Z,q)},T=(Z,q)=>{Bn(n.errors,Z,q),v.state.next({errors:n.errors})},E=Z=>{n.errors=Z,v.state.next({errors:n.errors,isValid:!1})},k=(Z,q,se,xe)=>{const ee=rt(r,Z);if(ee){const ne=rt(i,Z,yr(se)?rt(s,Z):se);yr(ne)||xe&&xe.defaultChecked||q?Bn(i,Z,q?ne:yA(ee._f)):U(Z,ne),l.mount&&!l.action&&j()}},A=(Z,q,se,xe,ee)=>{let ne=!1,he=!1;const je={name:Z};if(!e.disabled){if(!se||xe){(g.isDirty||y.isDirty)&&(he=n.isDirty,n.isDirty=je.isDirty=z(),ne=he!==je.isDirty);const ze=bo(rt(s,Z),q);he=!!rt(n.dirtyFields,Z),ze?Ur(n.dirtyFields,Z):Bn(n.dirtyFields,Z,!0),je.dirtyFields=n.dirtyFields,ne=ne||(g.dirtyFields||y.dirtyFields)&&he!==!ze}if(se){const ze=rt(n.touchedFields,Z);ze||(Bn(n.touchedFields,Z,se),je.touchedFields=n.touchedFields,ne=ne||(g.touchedFields||y.touchedFields)&&ze!==se)}ne&&ee&&v.state.next(je)}return ne?je:{}},O=(Z,q,se,xe)=>{const ee=rt(n.errors,Z),ne=(g.isValid||y.isValid)&&gi(q)&&n.isValid!==q;if(e.delayError&&se?(p=S(()=>T(Z,se)),p(e.delayError)):(clearTimeout(f),p=null,se?Bn(n.errors,Z,se):Ur(n.errors,Z)),(se?!bo(ee,se):ee)||!Rs(xe)||ne){const he={...xe,...ne&&gi(q)?{isValid:q}:{},errors:n.errors,name:Z};n={...n,...he},v.state.next(he)}},I=async Z=>(D(Z,!0),await e.resolver(i,e.context,Bae(Z||u.mount,r,e.criteriaMode,e.shouldUseNativeValidation))),$=async Z=>{const{errors:q}=await I(Z);if(D(Z),Z)for(const se of Z){const xe=rt(q,se);xe?Bn(n.errors,se,xe):Ur(n.errors,se)}else n.errors=q;return q},R=async(Z,q,se={valid:!0})=>{for(const xe in Z){const ee=Z[xe];if(ee){const{_f:ne,...he}=ee;if(ne){const je=u.array.has(ne.name),ze=ee._f&&Uae(ee._f);ze&&g.validatingFields&&D([ne.name],!0);const ke=await wA(ee,u.disabled,i,C,e.shouldUseNativeValidation&&!q,je);if(ze&&g.validatingFields&&D([ne.name]),ke[ne.name]&&(se.valid=!1,q||t.shouldUseNativeValidation))break;!q&&(rt(ke,ne.name)?je?Zae(n.errors,ke,ne.name):Bn(n.errors,ne.name,ke[ne.name]):Ur(n.errors,ne.name))}!Rs(he)&&await R(he,q,se)}}return se.valid},P=()=>{for(const Z of u.unMount){const q=rt(r,Z);q&&(q._f.refs?q._f.refs.every(se=>!E1(se)):!E1(q._f.ref))&&Pe(Z)}u.unMount=new Set},z=(Z,q)=>!e.disabled&&(Z&&q&&Bn(i,Z,q),!bo(F(),s)),N=(Z,q,se)=>ow(Z,u,{...l.mount?i:yr(q)?s:vi(Z)?{[Z]:q}:q},se,q),H=Z=>q2(rt(l.mount?i:s,Z,e.shouldUnregister?rt(s,Z,[]):[])),U=(Z,q,se={})=>{const xe=rt(r,Z);let ee=q;if(xe){const ne=xe._f;ne&&(!ne.disabled&&Bn(i,Z,p4(q,ne)),ee=Xv(ne.ref)&&Js(q)?"":q,c4(ne.ref)?[...ne.ref.options].forEach(he=>he.selected=ee.includes(he.value)):ne.refs?Vm(ne.ref)?ne.refs.forEach(he=>{(!he.defaultChecked||!he.disabled)&&(Array.isArray(ee)?he.checked=!!ee.find(je=>je===he.value):he.checked=ee===he.value||!!ee)}):ne.refs.forEach(he=>he.checked=he.value===ee):J2(ne.ref)?ne.ref.value="":(ne.ref.value=ee,ne.ref.type||v.state.next({name:Z,values:Br(i)})))}(se.shouldDirty||se.shouldTouch)&&A(Z,ee,se.shouldTouch,se.shouldDirty,!0),se.shouldValidate&&le(Z)},L=(Z,q,se)=>{for(const xe in q){if(!q.hasOwnProperty(xe))return;const ee=q[xe],ne=Z+"."+xe,he=rt(r,ne);(u.array.has(Z)||qr(ee)||he&&!he._f)&&!Kc(ee)?L(ne,ee,se):U(ne,ee,se)}},W=(Z,q,se={})=>{const xe=rt(r,Z),ee=u.array.has(Z),ne=Br(q);Bn(i,Z,ne),ee?(v.array.next({name:Z,values:Br(i)}),(g.isDirty||g.dirtyFields||y.isDirty||y.dirtyFields)&&se.shouldDirty&&v.state.next({name:Z,dirtyFields:wd(s,i),isDirty:z(Z,ne)})):xe&&!xe._f&&!Js(ne)?L(Z,ne,se):U(Z,ne,se),bA(Z,u)?v.state.next({...n,name:Z,values:Br(i)}):v.state.next({name:l.mount?Z:void 0,values:Br(i)})},K=async Z=>{l.mount=!0;const q=Z.target;let se=q.name,xe=!0;const ee=rt(r,se),ne=ze=>{xe=Number.isNaN(ze)||Kc(ze)&&isNaN(ze.getTime())||bo(ze,rt(i,se,ze))},he=vA(e.mode),je=vA(e.reValidateMode);if(ee){let ze,ke;const Be=q.type?yA(ee._f):s4(Z),xt=Z.type===Yv.BLUR||Z.type===Yv.FOCUS_OUT,vt=!Vae(ee._f)&&!e.resolver&&!rt(n.errors,se)&&!ee._f.deps||qae(xt,rt(n.touchedFields,se),n.isSubmitted,je,he),kt=bA(se,u,xt);Bn(i,se,Be),xt?(!q||!q.readOnly)&&(ee._f.onBlur&&ee._f.onBlur(Z),p&&p(0)):ee._f.onChange&&ee._f.onChange(Z);const Ge=A(se,Be,xt),gt=!Rs(Ge)||kt;if(!xt&&v.state.next({name:se,type:Z.type,values:Br(i)}),vt)return(g.isValid||y.isValid)&&(e.mode==="onBlur"?xt&&j():xt||j()),gt&&v.state.next({name:se,...kt?{}:Ge});if(!xt&&kt&&v.state.next({...n}),e.resolver){const{errors:dn}=await I([se]);if(D([se]),ne(Be),xe){const $n=SA(n.errors,r,se),dr=SA(dn,r,$n.name||se);ze=dr.error,se=dr.name,ke=Rs(dn)}}else D([se],!0),ze=(await wA(ee,u.disabled,i,C,e.shouldUseNativeValidation))[se],D([se]),ne(Be),xe&&(ze?ke=!1:(g.isValid||y.isValid)&&(ke=await R(r,!0)));xe&&(ee._f.deps&&(!Array.isArray(ee._f.deps)||ee._f.deps.length>0)&&le(ee._f.deps),O(se,ke,ze,Ge))}},Q=(Z,q)=>{if(rt(n.errors,q)&&Z.focus)return Z.focus(),1},le=async(Z,q={})=>{let se,xe;const ee=hh(Z);if(e.resolver){const ne=await $(yr(Z)?Z:ee);se=Rs(ne),xe=Z?!ee.some(he=>rt(ne,he)):se}else Z?(xe=(await Promise.all(ee.map(async ne=>{const he=rt(r,ne);return await R(he&&he._f?{[ne]:he}:he)}))).every(Boolean),!(!xe&&!n.isValid)&&j()):xe=se=await R(r);return v.state.next({...!vi(Z)||(g.isValid||y.isValid)&&se!==n.isValid?{}:{name:Z},...e.resolver||!Z?{isValid:se}:{},errors:n.errors}),q.shouldFocus&&!xe&&mh(r,Q,Z?ee:u.mount),xe},F=(Z,q)=>{let se={...l.mount?i:s};return q&&(se=l4(q.dirtyFields?n.dirtyFields:n.touchedFields,se)),yr(Z)?se:vi(Z)?rt(se,Z):Z.map(xe=>rt(se,xe))},J=(Z,q)=>({invalid:!!rt((q||n).errors,Z),isDirty:!!rt((q||n).dirtyFields,Z),error:rt((q||n).errors,Z),isValidating:!!rt(n.validatingFields,Z),isTouched:!!rt((q||n).touchedFields,Z)}),ie=Z=>{const q=Z?hh(Z):void 0;q==null||q.forEach(se=>Ur(n.errors,se)),q?q.forEach(se=>{v.state.next({name:se,errors:n.errors})}):v.state.next({errors:{}})},te=(Z,q,se)=>{const xe=(rt(r,Z,{_f:{}})._f||{}).ref,ee=rt(n.errors,Z)||{},{ref:ne,message:he,type:je,...ze}=ee;Bn(n.errors,Z,{...ze,...q,ref:xe}),v.state.next({name:Z,errors:n.errors,isValid:!1}),se&&se.shouldFocus&&xe&&xe.focus&&xe.focus()},de=(Z,q)=>As(Z)?v.state.subscribe({next:se=>"values"in se&&Z(N(void 0,q),se)}):N(Z,q,!0),fe=Z=>v.state.subscribe({next:q=>{Wae(Z.name,q.name,Z.exact)&&Hae(q,Z.formState||g,tt,Z.reRenderRoot)&&Z.callback({values:{...i},...n,...q,defaultValues:s})}}).unsubscribe,Re=Z=>(l.mount=!0,y={...y,...Z.formState},fe({...Z,formState:{...m,...Z.formState}})),Pe=(Z,q={})=>{for(const se of Z?hh(Z):u.mount)u.mount.delete(se),u.array.delete(se),q.keepValue||(Ur(r,se),Ur(i,se)),!q.keepError&&Ur(n.errors,se),!q.keepDirty&&Ur(n.dirtyFields,se),!q.keepTouched&&Ur(n.touchedFields,se),!q.keepIsValidating&&Ur(n.validatingFields,se),!e.shouldUnregister&&!q.keepDefaultValue&&Ur(s,se);v.state.next({values:Br(i)}),v.state.next({...n,...q.keepDirty?{isDirty:z()}:{}}),!q.keepIsValid&&j()},$e=({disabled:Z,name:q})=>{if(gi(Z)&&l.mount||Z||u.disabled.has(q)){const ee=u.disabled.has(q)!==!!Z;Z?u.disabled.add(q):u.disabled.delete(q),ee&&l.mount&&!l.action&&j()}},we=(Z,q={})=>{let se=rt(r,Z);const xe=gi(q.disabled)||gi(e.disabled);return Bn(r,Z,{...se||{},_f:{...se&&se._f?se._f:{ref:{name:Z}},name:Z,mount:!0,...q}}),u.mount.add(Z),se?$e({disabled:gi(q.disabled)?q.disabled:e.disabled,name:Z}):k(Z,!0,q.value),{...xe?{disabled:q.disabled||e.disabled}:{},...e.progressive?{required:!!q.required,min:Ff(q.min),max:Ff(q.max),minLength:Ff(q.minLength),maxLength:Ff(q.maxLength),pattern:Ff(q.pattern)}:{},name:Z,onChange:K,onBlur:K,ref:ee=>{if(ee){we(Z,q),se=rt(r,Z);const ne=yr(ee.value)&&ee.querySelectorAll&&ee.querySelectorAll("input,select,textarea")[0]||ee,he=zae(ne),je=se._f.refs||[];if(he?je.find(ze=>ze===ne):ne===se._f.ref)return;Bn(r,Z,{_f:{...se._f,...he?{refs:[...je.filter(E1),ne,...Array.isArray(rt(s,Z))?[{}]:[]],ref:{type:ne.type,name:Z}}:{ref:ne}}}),k(Z,!1,void 0,ne)}else se=rt(r,Z,{}),se._f&&(se._f.mount=!1),(e.shouldUnregister||q.shouldUnregister)&&!(i4(u.array,Z)&&l.action)&&u.unMount.add(Z)}}},be=()=>e.shouldFocusError&&mh(r,Q,u.mount),Ae=Z=>{gi(Z)&&(v.state.next({disabled:Z}),mh(r,(q,se)=>{const xe=rt(r,se);xe&&(q.disabled=xe._f.disabled||Z,Array.isArray(xe._f.refs)&&xe._f.refs.forEach(ee=>{ee.disabled=xe._f.disabled||Z}))},0,!1))},Ne=(Z,q)=>async se=>{let xe;se&&(se.preventDefault&&se.preventDefault(),se.persist&&se.persist());let ee=Br(i);if(v.state.next({isSubmitting:!0}),e.resolver){const{errors:ne,values:he}=await I();D(),n.errors=ne,ee=Br(he)}else await R(r);if(u.disabled.size)for(const ne of u.disabled)Ur(ee,ne);if(Ur(n.errors,"root"),Rs(n.errors)){v.state.next({errors:{}});try{await Z(ee,se)}catch(ne){xe=ne}}else q&&await q({...n.errors},se),be(),setTimeout(be);if(v.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Rs(n.errors)&&!xe,submitCount:n.submitCount+1,errors:n.errors}),xe)throw xe},Ie=(Z,q={})=>{rt(r,Z)&&(yr(q.defaultValue)?W(Z,Br(rt(s,Z))):(W(Z,q.defaultValue),Bn(s,Z,Br(q.defaultValue))),q.keepTouched||Ur(n.touchedFields,Z),q.keepDirty||(Ur(n.dirtyFields,Z),n.isDirty=q.defaultValue?z(Z,Br(rt(s,Z))):z()),q.keepError||(Ur(n.errors,Z),g.isValid&&j()),v.state.next({...n}))},Fe=(Z,q={})=>{const se=Z?Br(Z):s,xe=Br(se),ee=Rs(Z),ne=ee?s:xe;if(q.keepDefaultValues||(s=se),!q.keepValues){if(q.keepDirtyValues){const he=new Set([...u.mount,...Object.keys(wd(s,i))]);for(const je of Array.from(he)){const ze=rt(n.dirtyFields,je),ke=rt(i,je),Be=rt(ne,je);ze&&!yr(ke)?Bn(ne,je,ke):!ze&&!yr(Be)&&W(je,Be)}}else{if(W2&&yr(Z))for(const he of u.mount){const je=rt(r,he);if(je&&je._f){const ze=Array.isArray(je._f.refs)?je._f.refs[0]:je._f.ref;if(Xv(ze)){const ke=ze.closest("form");if(ke){ke.reset();break}}}}if(q.keepFieldsRef)for(const he of u.mount)W(he,rt(ne,he));else r={}}i=e.shouldUnregister?q.keepDefaultValues?Br(s):{}:Br(ne),v.array.next({values:{...ne}}),v.state.next({values:{...ne}})}u={mount:q.keepDirtyValues?u.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!g.isValid||!!q.keepIsValid||!!q.keepDirtyValues||!e.shouldUnregister&&!Rs(ne),l.watch=!!e.shouldUnregister,l.keepIsValid=!!q.keepIsValid,l.action=!1,q.keepErrors||(n.errors={}),v.state.next({submitCount:q.keepSubmitCount?n.submitCount:0,isDirty:ee?!1:q.keepDirty?n.isDirty:!!(q.keepDefaultValues&&!bo(Z,s)),isSubmitted:q.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:ee?{}:q.keepDirtyValues?q.keepDefaultValues&&i?wd(s,i):n.dirtyFields:q.keepDefaultValues&&Z?wd(s,Z):q.keepDirty?n.dirtyFields:{},touchedFields:q.keepTouched?n.touchedFields:{},errors:q.keepErrors?n.errors:{},isSubmitSuccessful:q.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:s})},ct=(Z,q)=>Fe(As(Z)?Z(i):Z,{...e.resetOptions,...q}),Me=(Z,q={})=>{const se=rt(r,Z),xe=se&&se._f;if(xe){const ee=xe.refs?xe.refs[0]:xe.ref;ee.focus&&setTimeout(()=>{ee.focus(),q.shouldSelect&&As(ee.select)&&ee.select()})}},tt=Z=>{n={...n,...Z}},it={control:{register:we,unregister:Pe,getFieldState:J,handleSubmit:Ne,setError:te,_subscribe:fe,_runSchema:I,_updateIsValidating:D,_focusError:be,_getWatch:N,_getDirty:z,_setValid:j,_setFieldArray:M,_setDisabledField:$e,_setErrors:E,_getFieldArray:H,_reset:Fe,_resetDefaultValues:()=>As(e.defaultValues)&&e.defaultValues().then(Z=>{ct(Z,e.resetOptions),v.state.next({isLoading:!1})}),_removeUnmounted:P,_disableForm:Ae,_subjects:v,_proxyFormState:g,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(Z){l=Z},get _defaultValues(){return s},get _names(){return u},set _names(Z){u=Z},get _formState(){return n},get _options(){return e},set _options(Z){e={...e,...Z}}},subscribe:Re,trigger:le,register:we,handleSubmit:Ne,watch:de,setValue:W,getValues:F,reset:ct,resetField:Ie,clearErrors:ie,unregister:Pe,setError:te,setFocus:Me,getFieldState:J};return{...it,formControl:it}}function Jae(t={}){const e=We.useRef(void 0),n=We.useRef(void 0),[r,s]=We.useState({isDirty:!1,isValidating:!1,isLoading:As(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,isReady:!1,defaultValues:As(t.defaultValues)?void 0:t.defaultValues});if(!e.current)if(t.formControl)e.current={...t.formControl,formState:r},t.defaultValues&&!As(t.defaultValues)&&t.formControl.reset(t.defaultValues,t.resetOptions);else{const{formControl:l,...u}=Qae(t);e.current={...u,formState:r}}const i=e.current.control;return i._options=t,K2(()=>{const l=i._subscribe({formState:i._proxyFormState,callback:()=>s({...i._formState}),reRenderRoot:!0});return s(u=>({...u,isReady:!0})),i._formState.isReady=!0,l},[i]),We.useEffect(()=>i._disableForm(t.disabled),[i,t.disabled]),We.useEffect(()=>{t.mode&&(i._options.mode=t.mode),t.reValidateMode&&(i._options.reValidateMode=t.reValidateMode)},[i,t.mode,t.reValidateMode]),We.useEffect(()=>{t.errors&&(i._setErrors(t.errors),i._focusError())},[i,t.errors]),We.useEffect(()=>{t.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,t.shouldUnregister]),We.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),We.useEffect(()=>{var l;t.values&&!bo(t.values,n.current)?(i._reset(t.values,{keepFieldsRef:!0,...i._options.resetOptions}),!((l=i._options.resetOptions)===null||l===void 0)&&l.keepIsValid||i._setValid(),n.current=t.values,s(u=>({...u}))):i._resetDefaultValues()},[i,t.values]),We.useEffect(()=>{i._state.mount||(i._setValid(),i._state.mount=!0),i._state.watch&&(i._state.watch=!1,i._subjects.state.next({...i._formState})),i._removeUnmounted()}),e.current.formState=We.useMemo(()=>a4(r,i),[i,r]),e.current}function Yae({open:t,message:e="処理中..."}){return a.jsx(Mx,{open:t,sx:{color:"#fff",zIndex:n=>n.zIndex.modal+1,backgroundColor:"rgba(0, 0, 0, 0.7)"},children:a.jsxs(Ro,{alignItems:"center",spacing:2,children:[a.jsx(ut,{color:"inherit"}),a.jsx(G,{variant:"body1",children:e})]})})}class Xae{constructor(e){this.repository=e}async execute(e){const{file:n,uploadedBy:r}=e;return oe.info("UploadStorageFileUseCase.execute",{fileName:n.name,uploadedBy:r}),this.repository.uploadFile(n,r)}async executeImageSet(e){const{imageSet:n,originalName:r,uploadedBy:s,dimensions:i}=e;return oe.info("UploadStorageFileUseCase.executeImageSet",{originalName:r,uploadedBy:s}),this.repository.uploadImageSet(n,r,s,i)}}class ele{constructor(e){this.repository=e}async execute(e){const{uuid:n,year:r}=e;oe.info("DeleteStorageFileUseCase.execute",{uuid:n,year:r}),await this.repository.deleteFile(n,r)}}class tle{constructor(e){this.repository=e}async execute(e){const{year:n}=e;return oe.debug("FetchStorageFilesUseCase.execute",{year:n}),this.repository.fetchFiles(n)}async fetchYears(){return oe.debug("FetchStorageFilesUseCase.fetchYears"),this.repository.fetchYears()}}class nle{constructor(e){this.repository=e}async execute(e){const{uuid:n,year:r,alt:s}=e;return oe.info("UpdateStorageFileMetadataUseCase.execute",{uuid:n,year:r,alt:s}),this.repository.updateFileMetadata(n,r,{alt:s})}}class rle{constructor(){St(this,"repository");St(this,"uploadUseCase");St(this,"deleteUseCase");St(this,"fetchUseCase");St(this,"updateMetadataUseCase");this.repository=new Sd,this.uploadUseCase=new Xae(this.repository),this.deleteUseCase=new ele(this.repository),this.fetchUseCase=new tle(this.repository),this.updateMetadataUseCase=new nle(this.repository)}async uploadFile(e,n){return this.uploadUseCase.execute({file:e,uploadedBy:n})}async uploadImageSet(e,n,r,s){return this.uploadUseCase.executeImageSet({imageSet:e,originalName:n,uploadedBy:r,dimensions:s})}async deleteFile(e,n){return this.deleteUseCase.execute({uuid:e,year:n})}async fetchFiles(e){return this.fetchUseCase.execute({year:e})}async fetchYears(){return this.fetchUseCase.fetchYears()}async updateFileMetadata(e,n,r){return this.updateMetadataUseCase.execute({uuid:e,year:n,alt:r})}async rebuildIndex(e){return this.repository.rebuildIndex(e)}}let R1=null;function X2(){return R1||(R1=new rle),R1}const Ly=30;function h4({open:t,onClose:e,onSelect:n,accept:r="all",uploadedBy:s,aspectRatio:i,currentSelectedUuid:l}){const u=vr(),p=aa(u.breakpoints.down("sm")),f=ys(),m=b.useRef(null),g=X2(),[y,v]=b.useState(null),[C,S]=b.useState(null),[j,D]=b.useState("uploadedAt"),[M,T]=b.useState("desc"),[E,k]=b.useState(Ly),[A,O]=b.useState(!1),[I,$]=b.useState(null),[R,P]=b.useState(!1),[z,N]=b.useState(null),[H,U]=b.useState(null),[L,W]=b.useState(!1),[K,Q]=b.useState(null),[le,F]=b.useState(""),J=jn({queryKey:["files",C],queryFn:()=>g.fetchFiles(C??void 0),enabled:t}),ie=Pn({mutationFn:({uuid:q,alt:se})=>g.updateFileMetadata(q,C??new Date().getFullYear(),se),onSuccess:()=>{f.invalidateQueries({queryKey:["files",C]}),Q(null)}}),te=J.data;b.useEffect(()=>{te&&C===null&&te.availableYears.length>0&&S(te.year)},[te,C]),b.useEffect(()=>{t||(v(null),k(Ly),$(null))},[t]),b.useEffect(()=>{if(t&&l&&(te!=null&&te.files)){const q=te.files.find(se=>se.uuid===l);q&&v(q)}},[t,l,te==null?void 0:te.files]);const de=b.useMemo(()=>te!=null&&te.files?te.files.filter(q=>r==="image"?Uc(q.contentType):!0):[],[te==null?void 0:te.files,r]),fe=b.useMemo(()=>{const q=[...de];return q.sort((se,xe)=>{if(l){if(se.uuid===l)return-1;if(xe.uuid===l)return 1}let ee=0;switch(j){case"originalName":ee=se.originalName.localeCompare(xe.originalName,"ja");break;case"size":ee=se.size-xe.size;break;case"uploadedAt":default:ee=new Date(se.uploadedAt).getTime()-new Date(xe.uploadedAt).getTime();break}return M==="asc"?ee:-ee}),q},[de,j,M,l]),Re=fe.slice(0,E),Pe=E<fe.length,$e=q=>te!=null&&te.baseUrl&&q.startsWith(te.baseUrl+"/")?q.slice(te.baseUrl.length+1):q,we=()=>{if(y){const q=y.variants?Object.fromEntries(Object.entries(y.variants).map(([se,xe])=>[se,$e(xe)])):void 0;n({uuid:y.uuid,url:$e(y.url),originalName:y.originalName,alt:y.alt,size:y.size,width:y.width,height:y.height,...q&&{variants:q}}),v(null),e()}},be=()=>{v(null),e()},Ae=q=>{S(q),k(Ly)},Ne=(q,se)=>{se!==null&&D(se)},Ie=()=>{T(q=>q==="asc"?"desc":"asc")},Fe=q=>{var xe;const se=(xe=q.target.files)==null?void 0:xe[0];if(se){if(m.current&&(m.current.value=""),Uc(se.type)){const ee=URL.createObjectURL(se);N(ee),U(se),P(!0)}else if(r==="image"){$("画像ファイルを選択してください");return}}},ct=async q=>{P(!1),z&&URL.revokeObjectURL(z);const se=(H==null?void 0:H.name)??"image.jpg";N(null),U(null),O(!0),$(null);try{const xe={width:q.width,height:q.height},ee=await g.uploadImageSet(q.imageSet,se,s,xe),ne=new Date().getFullYear();f.invalidateQueries({queryKey:["files",ne]}),C!==ne&&S(ne),n({uuid:ee.uuid,url:ee.url,originalName:ee.originalName,size:ee.size,width:ee.width,height:ee.height,variants:ee.variants}),e()}catch(xe){$(xe.message)}finally{O(!1)}},Me=()=>{P(!1),z&&URL.revokeObjectURL(z),N(null),U(null)},tt=i&&i!=="free"?i:null,Ve=q=>{q.preventDefault(),q.stopPropagation(),W(!0)},it=q=>{q.preventDefault(),q.stopPropagation(),W(!1)},Z=q=>{q.preventDefault(),q.stopPropagation(),W(!1);const se=q.dataTransfer.files[0];if(se)if(Uc(se.type)){const xe=URL.createObjectURL(se);N(xe),U(se),P(!0)}else r==="image"&&$("画像ファイルをドロップしてください")};return a.jsxs(a.Fragment,{children:[a.jsxs(Qt,{open:t,onClose:be,maxWidth:"md",fullWidth:!0,fullScreen:p,children:[a.jsxs(Yt,{sx:{py:p?1.5:2,pr:6},children:[r==="image"?"画像を選択":"ファイルを選択",a.jsx(ft,{onClick:be,sx:{position:"absolute",right:8,top:8},children:a.jsx($x,{})})]}),a.jsxs(Jt,{sx:{p:p?1:2,position:"relative"},onDragOver:Ve,onDragLeave:it,onDrop:Z,children:[L&&a.jsx(B,{sx:{position:"absolute",inset:0,bgcolor:"rgba(25, 118, 210, 0.1)",border:"2px dashed",borderColor:"primary.main",borderRadius:1,zIndex:10,display:"flex",alignItems:"center",justifyContent:"center"},children:a.jsxs(B,{sx:{textAlign:"center"},children:[a.jsx(Ti,{sx:{fontSize:64,color:"primary.main"}}),a.jsx(G,{variant:"h6",color:"primary",children:"ここにドロップ"})]})}),a.jsxs(B,{sx:{display:"flex",flexDirection:{xs:"column",sm:"row"},alignItems:{xs:"stretch",sm:"center"},gap:1,mb:2},children:[te&&te.availableYears.length>0&&a.jsx(_n,{size:"small",sx:{minWidth:100},children:a.jsx(wn,{value:C??te.year,onChange:q=>Ae(q.target.value),children:te.availableYears.map(q=>a.jsxs(nt,{value:q,children:[q,"年"]},q))})}),a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:.5},children:[a.jsxs(yc,{value:j,exclusive:!0,onChange:Ne,size:"small",children:[a.jsx(ts,{value:"uploadedAt",children:"日時"}),a.jsx(ts,{value:"originalName",children:"名前"}),a.jsx(ts,{value:"size",children:"サイズ"})]}),a.jsx(ts,{value:"order",selected:!1,onChange:Ie,size:"small",title:M==="asc"?"昇順":"降順",children:M==="asc"?a.jsx(x2,{fontSize:"small"}):a.jsx(zx,{fontSize:"small"})})]}),a.jsxs(pe,{variant:"outlined",startIcon:A?a.jsx(ut,{size:20}):a.jsx(Ti,{}),component:"label",disabled:A,sx:{ml:{sm:"auto"}},children:[A?"アップロード中...":"アップロード",a.jsx("input",{ref:m,type:"file",accept:r==="image"?"image/*":"*/*",hidden:!0,onChange:Fe})]})]}),I&&a.jsx(zt,{severity:"error",sx:{mb:2},onClose:()=>$(null),children:I}),J.isLoading?a.jsx(B,{sx:{display:"flex",justifyContent:"center",py:4},children:a.jsx(ut,{})}):J.error?a.jsx(zt,{severity:"error",children:"ファイル一覧の取得に失敗しました"}):fe.length===0?a.jsx(zt,{severity:"info",children:r==="image"?"画像ファイルがありません":"ファイルがありません"}):a.jsxs(a.Fragment,{children:[a.jsx(Et,{container:!0,spacing:1,children:Re.map(q=>a.jsx(Et,{item:!0,xs:4,sm:3,md:2,children:a.jsxs(Su,{sx:{border:(y==null?void 0:y.uuid)===q.uuid?"2px solid":"2px solid transparent",borderColor:(y==null?void 0:y.uuid)===q.uuid?"primary.main":"transparent",position:"relative"},children:[a.jsxs(_I,{onClick:()=>v(q),children:[a.jsx(B,{sx:{height:100,display:"flex",alignItems:"center",justifyContent:"center",bgcolor:"grey.100"},children:Uc(q.contentType)?a.jsx(II,{component:"img",image:q.url,alt:q.originalName,sx:{height:"100%",objectFit:"contain"}}):r5(q.contentType)?a.jsx(Fx,{sx:{fontSize:48,color:"error.main"}}):a.jsx(vc,{sx:{fontSize:48,color:"grey.500"}})}),a.jsxs(B,{sx:{p:.5},children:[a.jsx(G,{variant:"caption",noWrap:!0,display:"block",title:q.originalName,children:q.originalName}),a.jsx(G,{variant:"caption",color:"text.secondary",children:UC(q.size)})]})]}),(y==null?void 0:y.uuid)===q.uuid&&a.jsx(vP,{sx:{position:"absolute",top:4,right:4,color:"primary.main",bgcolor:"white",borderRadius:"50%"}}),Uc(q.contentType)&&a.jsx(ft,{size:"small",onClick:se=>{se.stopPropagation(),Q(q),F(q.alt??"")},title:"代替テキストを編集",sx:{position:"absolute",bottom:4,right:4,bgcolor:"rgba(255, 255, 255, 0.9)","&:hover":{bgcolor:"primary.light",color:"white"},width:24,height:24},children:a.jsx(Ri,{sx:{fontSize:14}})})]})},q.uuid))}),Pe&&a.jsx(B,{sx:{display:"flex",justifyContent:"center",mt:2},children:a.jsxs(pe,{variant:"text",onClick:()=>k(q=>q+Ly),children:["もっと読み込む (",fe.length-E," 件)"]})})]})]}),a.jsxs(rn,{sx:{px:2,pb:2},children:[a.jsx(pe,{onClick:be,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:we,disabled:!y,children:"選択"})]})]}),z&&a.jsx(A2,{open:R,imageUrl:z,onClose:Me,onComplete:ct,fixedAspectRatio:tt}),a.jsxs(Qt,{open:!!K,onClose:()=>Q(null),maxWidth:"sm",fullWidth:!0,children:[a.jsx(Yt,{children:"代替テキストを編集"}),a.jsx(Jt,{children:a.jsx(B,{sx:{pt:1},children:a.jsx(Xe,{label:"代替テキスト (alt)",fullWidth:!0,value:le,onChange:q=>F(q.target.value),placeholder:"画像の説明を入力",helperText:"スクリーンリーダーや画像が表示できない場合に使用されます",autoFocus:!0})})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>Q(null),children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:()=>{K&&ie.mutate({uuid:K.uuid,alt:le})},disabled:ie.isPending,children:ie.isPending?"保存中...":"保存"})]})]})]})}function sle({value:t,warnLength:e}){const n=(t==null?void 0:t.length)??0,r=n>e;return a.jsxs(G,{variant:"caption",sx:{color:r?"warning.main":"text.secondary",fontWeight:r?600:400},children:[r&&"⚠ ",n," / ",e," 文字",r&&` (${n-e} 文字超過)`]})}const ile=/\[([^\]]+)\]\((https?:\/\/[^)]+)\)/g,k1=/(https?:\/\/[^\s<>"{}|\\^`[\]]+)/g;function ole(t){const e=[];let n=0;const r=[...t.matchAll(ile)];for(const i of r){const l=i.index,u=l+i[0].length;l>n&&e.push({type:"text",content:t.slice(n,l)}),e.push({type:"link",text:i[1],url:i[2]}),n=u}n<t.length&&e.push({type:"text",content:t.slice(n)});const s=[];for(const i of e)if(i.type==="link")s.push(i);else{const l=i.content.split(k1);for(const u of l)k1.test(u)?(k1.lastIndex=0,s.push({type:"link",text:u,url:u})):u&&s.push({type:"text",content:u})}return s}function m4({text:t}){if(!t)return null;const e=ole(t);return a.jsx(a.Fragment,{children:e.map((n,r)=>n.type==="link"?a.jsx(Ox,{href:n.url,target:"_blank",rel:"noopener noreferrer",sx:{wordBreak:"break-all"},children:n.text},r):a.jsx(b.Fragment,{children:n.content},r))})}function vo({label:t,children:e,required:n=!1,description:r,error:s,warnLength:i,labelSuffix:l,disabled:u=!1}){const p=!!s;return a.jsxs(_n,{fullWidth:!0,error:p,disabled:u,children:[a.jsxs(B,{sx:{display:"flex",justifyContent:"space-between",alignItems:"baseline",mb:.5},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"baseline",gap:1},children:[a.jsx(FI,{required:n,children:t}),l]}),i&&a.jsx(sle,{value:i.value,warnLength:i.limit})]}),e,(s||r)&&a.jsx(Dh,{error:p,sx:{mx:0},children:s||a.jsx(m4,{text:r})})]})}function g4({label:t,value:e,onChange:n,required:r,description:s,uploadedBy:i,aspectRatio:l,disabled:u=!1}){const p=ys(),f=X2(),[m,g]=b.useState(!1),[y,v]=b.useState(!1),C=b.useRef(0),[S,j]=b.useState(!1),[D,M]=b.useState(null),[T,E]=b.useState(null),[k,A]=b.useState(!1),[O,I]=b.useState(null),$=()=>{n(null)},R=W=>{W.preventDefault(),W.stopPropagation(),C.current++,C.current===1&&v(!0)},P=W=>{W.preventDefault(),W.stopPropagation()},z=W=>{W.preventDefault(),W.stopPropagation(),C.current--,C.current===0&&v(!1)},N=W=>{W.preventDefault(),W.stopPropagation(),C.current=0,v(!1);const K=W.dataTransfer.files[0];if(!K)return;if(!Uc(K.type)){I("画像ファイルをドロップしてください");return}const Q=URL.createObjectURL(K);M(Q),E(K),j(!0),I(null)},H=async W=>{j(!1),D&&URL.revokeObjectURL(D);const K=(T==null?void 0:T.name)??"image.jpg";M(null),E(null),A(!0),I(null);try{const Q={width:W.width,height:W.height},le=await f.uploadImageSet(W.imageSet,K,i,Q),F=new Date().getFullYear();p.invalidateQueries({queryKey:["files",F]}),n({uuid:le.uuid,url:le.url,originalName:le.originalName,size:le.size,width:le.width,height:le.height,variants:le.variants})}catch(Q){I(Q.message)}finally{A(!1)}},U=()=>{j(!1),D&&URL.revokeObjectURL(D),M(null),E(null)},L=l&&l!=="free"?l:null;return a.jsxs(vo,{label:t,required:r,description:s,disabled:u,children:[a.jsx(B,{sx:{position:"relative",width:"100%",height:200,borderRadius:1,overflow:"hidden",border:y?"2px dashed":"1px solid",borderColor:y?"primary.main":"divider",bgcolor:y?"action.hover":"grey.100",transition:"border-color 0.2s, background-color 0.2s"},onDragEnter:R,onDragOver:P,onDragLeave:z,onDrop:N,children:k?a.jsxs(B,{sx:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:1},children:[a.jsx(ut,{size:32}),a.jsx(G,{variant:"body2",color:"text.secondary",children:"アップロード中..."})]}):e&&typeof e=="object"&&e.url?a.jsxs(a.Fragment,{children:[a.jsx(B,{sx:{width:"100%",height:"100%",cursor:"pointer","&:hover":{opacity:.9}},onClick:()=>g(!0),children:a.jsx("img",{src:n5(e.url),alt:e.originalName,style:{width:"100%",height:"100%",objectFit:"cover",display:"block"}})}),a.jsx(ft,{size:"small",onClick:W=>{W.stopPropagation(),$()},sx:{position:"absolute",top:4,right:4,bgcolor:"rgba(0,0,0,0.5)",color:"white","&:hover":{bgcolor:"rgba(0,0,0,0.7)"}},children:a.jsx(zn,{fontSize:"small"})}),a.jsx(G,{variant:"caption",sx:{position:"absolute",bottom:0,left:0,right:0,bgcolor:"rgba(0,0,0,0.5)",color:"white",px:1,py:.5,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",pointerEvents:"none"},children:e.originalName}),y&&a.jsx(B,{sx:{position:"absolute",inset:0,bgcolor:"rgba(25, 118, 210, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:a.jsx(Ti,{sx:{fontSize:48,color:"primary.main"}})})]}):a.jsx(B,{sx:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer","&:hover":{bgcolor:"grey.200"}},onClick:()=>g(!0),children:a.jsx(B,{sx:{textAlign:"center"},children:y?a.jsxs(a.Fragment,{children:[a.jsx(Ti,{sx:{fontSize:48,color:"primary.main"}}),a.jsx(G,{variant:"body2",color:"primary",children:"ここにドロップ"})]}):a.jsxs(a.Fragment,{children:[a.jsx(wJ,{sx:{fontSize:48,color:"primary.main"}}),a.jsx(G,{variant:"body2",color:"primary",children:"画像を選択"}),a.jsx(G,{variant:"caption",color:"text.secondary",children:"またはドラッグ&ドロップ"})]})})})}),O&&a.jsx(zt,{severity:"error",sx:{mt:1},onClose:()=>I(null),children:O}),a.jsx(h4,{open:m,onClose:()=>g(!1),onSelect:n,accept:"image",uploadedBy:i,aspectRatio:l,currentSelectedUuid:e==null?void 0:e.uuid}),D&&a.jsx(A2,{open:S,imageUrl:D,onClose:U,onComplete:H,fixedAspectRatio:L})]})}function ale(t,e){return t.startsWith("application/pdf")||e.endsWith(".pdf")?a.jsx(Fx,{sx:{fontSize:48,color:"error.main"}}):t.startsWith("video/")?a.jsx(IY,{sx:{fontSize:48,color:"secondary.main"}}):t.startsWith("audio/")?a.jsx(hJ,{sx:{fontSize:48,color:"warning.main"}}):t.includes("javascript")||t.includes("json")||t.includes("xml")||t.includes("html")||t.includes("css")||e.match(/\.(js|ts|jsx|tsx|json|xml|html|css|py|rb|go|rs)$/)?a.jsx(S2,{sx:{fontSize:48,color:"info.main"}}):t.includes("document")||t.includes("word")||t.includes("text")||e.match(/\.(doc|docx|txt|md|rtf)$/)?a.jsx(Tp,{sx:{fontSize:48,color:"primary.main"}}):a.jsx(vc,{sx:{fontSize:48,color:"grey.500"}})}function y4({label:t,value:e,onChange:n,required:r,description:s,uploadedBy:i,disabled:l=!1}){const u=ys(),p=X2(),[f,m]=b.useState(!1),[g,y]=b.useState(!1),v=b.useRef(0),[C,S]=b.useState(!1),[j,D]=b.useState(null),M=()=>{n(null)},T=I=>{I.preventDefault(),I.stopPropagation(),v.current++,v.current===1&&y(!0)},E=I=>{I.preventDefault(),I.stopPropagation()},k=I=>{I.preventDefault(),I.stopPropagation(),v.current--,v.current===0&&y(!1)},A=async I=>{I.preventDefault(),I.stopPropagation(),v.current=0,y(!1);const $=I.dataTransfer.files[0];if($){S(!0),D(null);try{const R=await p.uploadFile($,i),P=new Date().getFullYear();u.invalidateQueries({queryKey:["files",P]}),n({uuid:R.uuid,url:R.url,originalName:R.originalName})}catch(R){D(R.message)}finally{S(!1)}}},O=I=>{var P;const $=((P=I.split(".").pop())==null?void 0:P.toLowerCase())??"";return{pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",txt:"text/plain",md:"text/markdown",json:"application/json",xml:"application/xml",html:"text/html",css:"text/css",js:"application/javascript",ts:"application/typescript",mp4:"video/mp4",mp3:"audio/mpeg",wav:"audio/wav"}[$]??"application/octet-stream"};return a.jsxs(vo,{label:t,required:r,description:s,disabled:l,children:[a.jsx(B,{sx:{position:"relative",width:"100%",height:200,borderRadius:1,overflow:"hidden",border:g?"2px dashed":"1px solid",borderColor:g?"primary.main":"divider",bgcolor:g?"action.hover":"grey.100",transition:"border-color 0.2s, background-color 0.2s"},onDragEnter:T,onDragOver:E,onDragLeave:k,onDrop:A,children:C?a.jsxs(B,{sx:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",flexDirection:"column",gap:1},children:[a.jsx(ut,{size:32}),a.jsx(G,{variant:"body2",color:"text.secondary",children:"アップロード中..."})]}):e&&typeof e=="object"&&e.url?a.jsxs(a.Fragment,{children:[a.jsx(B,{sx:{width:"100%",height:"100%",cursor:"pointer",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:1,"&:hover":{bgcolor:"grey.200"}},onClick:()=>m(!0),children:ale(O(e.originalName),e.originalName)}),a.jsx(ft,{size:"small",onClick:I=>{I.stopPropagation(),M()},sx:{position:"absolute",top:4,right:4,bgcolor:"rgba(0,0,0,0.5)",color:"white","&:hover":{bgcolor:"rgba(0,0,0,0.7)"}},children:a.jsx(zn,{fontSize:"small"})}),a.jsx(G,{variant:"caption",sx:{position:"absolute",bottom:0,left:0,right:0,bgcolor:"rgba(0,0,0,0.5)",color:"white",px:1,py:.5,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",pointerEvents:"none",textAlign:"center"},children:e.originalName}),g&&a.jsx(B,{sx:{position:"absolute",inset:0,bgcolor:"rgba(25, 118, 210, 0.3)",display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},children:a.jsx(Ti,{sx:{fontSize:48,color:"primary.main"}})})]}):a.jsx(B,{sx:{width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer","&:hover":{bgcolor:"grey.200"}},onClick:()=>m(!0),children:a.jsx(B,{sx:{textAlign:"center"},children:g?a.jsxs(a.Fragment,{children:[a.jsx(Ti,{sx:{fontSize:48,color:"primary.main"}}),a.jsx(G,{variant:"body2",color:"primary",children:"ここにドロップ"})]}):a.jsxs(a.Fragment,{children:[a.jsx(vc,{sx:{fontSize:48,color:"primary.main"}}),a.jsx(G,{variant:"body2",color:"primary",children:"ファイルを選択"}),a.jsx(G,{variant:"caption",color:"text.secondary",children:"またはドラッグ&ドロップ"})]})})})}),j&&a.jsx(zt,{severity:"error",sx:{mt:1},onClose:()=>D(null),children:j}),a.jsx(h4,{open:f,onClose:()=>m(!1),onSelect:n,accept:"all",uploadedBy:i,currentSelectedUuid:e==null?void 0:e.uuid})]})}class M1{constructor(e){this.queries=e}static ContentsQueryParams(e,n,r){return{queryKey:["contents",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJsonOrDefault(Ah("published",n),[],r)},enabled:!!e&&!!n}}static PrivateQueryParams(e,n,r){return{queryKey:["private",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJsonOrDefault(Ah("private",n),[],r)},enabled:!!e&&!!n}}getContents(){return this.queries.contents.data??[]}getPrivate(){return this.queries.private.data??[]}isLoading(){return this.queries.contents.isLoading||this.queries.private.isLoading}isError(){return this.queries.contents.isError||this.queries.private.isError}}function lle(){const[t,e]=b.useState(!1),[n,r]=b.useState(""),[s,i]=b.useState([]),l=b.useCallback(()=>({dialogOpen:t,searchQuery:n,tempSelection:s}),[t,n,s]),u=b.useCallback(m=>{i(m),r(""),e(!0)},[]),p=b.useCallback(()=>{e(!1)},[]),f=b.useCallback((m,g)=>{i(g?y=>y.includes(m)?y.filter(v=>v!==m):[...y,m]:[m])},[]);return{getState:l,openDialog:u,closeDialog:p,setSearchQuery:r,setTempSelection:i,toggleSelection:f}}class cle{toArray(e){return e?Array.isArray(e)?e:[e]:[]}fromArray(e,n){return n?e:e[0]??null}confirmSelection(e,n){return n?e.length>0?e:[]:e[0]??null}removeItem(e,n,r){const i=this.toArray(e).filter(l=>l!==n);return r?i:i[0]??null}clearAll(e){return e?[]:null}toggleSelection(e,n,r){const s=e.includes(n);return r?s?e.filter(i=>i!==n):[...e,n]:s?[]:[n]}isValidSelection(e,n){return n?Array.isArray(e):e===null||typeof e=="string"}isEmpty(e){return e?Array.isArray(e)?e.length===0:!1:!0}}class ule{constructor(e){St(this,"selectionDecider",new cle);this.deps=e}getState(){const{repo:e,presenter:n,value:r,multiple:s,targetContentType:i}=this.deps,l=n.getState(),u=e.getContents(),p=e.getPrivate(),f=new Set(u.map(j=>j.contentId)),m=p.filter(j=>!f.has(j.contentId)),g=[...u,...m].sort((j,D)=>j.title.localeCompare(D.title,"ja")),y=l.searchQuery,v=y.trim()?g.filter(j=>j.title.toLowerCase().includes(y.toLowerCase())||j.contentId.toLowerCase().includes(y.toLowerCase())):g,C=new Map;g.forEach(j=>C.set(j.contentId,j.title));const S=this.selectionDecider.toArray(r);return{allContents:g,filteredContents:v,contentIdToTitle:C,selectedContentIds:S,isLoading:e.isLoading(),isError:e.isError(),dialogOpen:l.dialogOpen,searchQuery:l.searchQuery,tempSelection:l.tempSelection,targetContentType:i,multiple:s}}openDialog(){const e=this.getState();this.deps.presenter.openDialog(e.selectedContentIds)}closeDialog(){this.deps.presenter.closeDialog()}setSearchQuery(e){this.deps.presenter.setSearchQuery(e)}toggleSelection(e){this.deps.presenter.toggleSelection(e,this.deps.multiple)}confirm(){const{onChange:e,multiple:n}=this.deps,r=this.deps.presenter.getState().tempSelection,s=this.selectionDecider.confirmSelection(r,n);e(s),this.deps.presenter.closeDialog()}removeItem(e){const{onChange:n,multiple:r,value:s}=this.deps,i=this.selectionDecider.removeItem(s,e,r);n(i)}clearAll(){const{onChange:e,multiple:n}=this.deps,r=this.selectionDecider.clearAll(n);e(r)}}function dle(t){const{targetContentType:e,value:n,onChange:r,multiple:s}=t,{authUseCase:i}=rr(),{branchUseCase:l}=Ei(),{token:u}=i.getState(),p=(l==null?void 0:l.getCurrentBranch())??"develop",f=new M1({contents:jn(M1.ContentsQueryParams(u,e,p)),private:jn(M1.PrivateQueryParams(u,e,p))}),m=lle();return{relationFieldUseCase:new ule({repo:f,presenter:m,value:n,onChange:r,multiple:s,targetContentType:e})}}function ple({label:t,value:e,onChange:n,required:r,description:s,targetContentType:i,multiple:l,disabled:u=!1}){const{relationFieldUseCase:p}=dle({targetContentType:i,value:e,onChange:n,multiple:l}),{filteredContents:f,contentIdToTitle:m,selectedContentIds:g,isLoading:y,isError:v,dialogOpen:C,searchQuery:S,tempSelection:j}=p.getState();return a.jsxs(vo,{label:t,required:r,description:s,disabled:u,children:[a.jsxs(B,{children:[g.length>0?a.jsx(B,{sx:{display:"flex",flexWrap:"wrap",gap:1,mb:1},children:g.map(D=>a.jsx(Ht,{label:m.get(D)??D,onDelete:()=>p.removeItem(D),icon:a.jsx(j2,{}),variant:"outlined"},D))}):a.jsx(G,{variant:"body2",color:"primary",sx:{mb:1},children:"未選択"}),a.jsxs(B,{sx:{display:"flex",gap:1},children:[a.jsx(pe,{variant:"outlined",size:"small",onClick:()=>p.openDialog(),disabled:!i,children:"選択"}),g.length>0&&a.jsx(pe,{variant:"text",size:"small",color:"error",onClick:()=>p.clearAll(),children:"クリア"})]}),!i&&a.jsx(zt,{severity:"warning",sx:{mt:1},children:"targetContentType が設定されていません"})]}),a.jsxs(Qt,{open:C,onClose:()=>p.closeDialog(),maxWidth:"sm",fullWidth:!0,children:[a.jsxs(Yt,{children:[t,"を選択",l&&"(複数可)"]}),a.jsxs(Jt,{dividers:!0,children:[a.jsx(Xe,{fullWidth:!0,size:"small",placeholder:"タイトルまたはIDで検索...",value:S,onChange:D=>p.setSearchQuery(D.target.value),InputProps:{startAdornment:a.jsx(c2,{position:"start",children:a.jsx(Om,{})})},sx:{mb:2}}),y&&a.jsx(B,{sx:{display:"flex",justifyContent:"center",py:4},children:a.jsx(ut,{})}),v&&a.jsx(zt,{severity:"error",children:"コンテンツの取得に失敗しました"}),!y&&!v&&a.jsx(a.Fragment,{children:f.length===0?a.jsx(G,{color:"text.secondary",sx:{py:2,textAlign:"center"},children:S?"該当するコンテンツがありません":"コンテンツがありません"}):a.jsx(as,{sx:{maxHeight:400,overflow:"auto"},children:f.map(D=>{const M=j.includes(D.contentId);return a.jsxs(os,{onClick:()=>p.toggleSelection(D.contentId),selected:M,children:[a.jsx(Un,{children:l?a.jsx(es,{edge:"start",checked:M,tabIndex:-1,disableRipple:!0}):a.jsx(PG,{edge:"start",checked:M,tabIndex:-1,disableRipple:!0})}),a.jsx(Zn,{primary:D.title,secondary:a.jsxs(B,{component:"span",sx:{display:"flex",gap:1,alignItems:"center"},children:[a.jsx(G,{variant:"caption",color:"text.secondary",children:D.contentId}),a.jsx(Ht,{label:D.status==="published"?"公開":"下書き",size:"small",color:D.status==="published"?"success":"default",sx:{height:20,fontSize:"0.7rem"}})]})})]},D.contentId)})})})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>p.closeDialog(),children:"キャンセル"}),a.jsx(pe,{onClick:()=>p.confirm(),variant:"contained",children:"決定"})]})]})]})}function fle({label:t,value:e,onChange:n,required:r,description:s,itemType:i,minItems:l,maxItems:u,uploadedBy:p,disabled:f=!1}){const m=e??[],g=()=>{if(u&&m.length>=u)return;const T=i==="text"?"":null;n([...m,T])},y=T=>{l&&m.length<=l||n(m.filter((E,k)=>k!==T))},v=T=>{if(T===0)return;const E=[...m];[E[T-1],E[T]]=[E[T],E[T-1]],n(E)},C=T=>{if(T===m.length-1)return;const E=[...m];[E[T],E[T+1]]=[E[T+1],E[T]],n(E)},S=(T,E)=>{const k=[...m];k[T]=E,n(k)},j=(T,E)=>{switch(i){case"text":return a.jsx(Xe,{value:T??"",onChange:k=>S(E,k.target.value),size:"small",fullWidth:!0,placeholder:`アイテム ${E+1}`});case"image":return a.jsx(g4,{label:"",value:T,onChange:k=>S(E,k),uploadedBy:p});case"file":return a.jsx(y4,{label:"",value:T,onChange:k=>S(E,k),uploadedBy:p});default:return a.jsx(Xe,{value:String(T??""),onChange:k=>S(E,k.target.value),size:"small",fullWidth:!0})}},D=!u||m.length<u,M=!l||m.length>l;return a.jsx(vo,{label:t,required:r,description:s,disabled:f,labelSuffix:u?a.jsxs(G,{component:"span",variant:"caption",color:"text.secondary",children:["(",m.length,"/",u,")"]}):void 0,children:a.jsxs(B,{children:[m.length===0?a.jsx(G,{variant:"body2",color:"primary",sx:{mb:1},children:"アイテムがありません"}):a.jsx(Ro,{spacing:1,sx:{mb:1},children:m.map((T,E)=>a.jsxs($t,{variant:"outlined",sx:{p:1,display:"flex",alignItems:"flex-start",gap:1},children:[a.jsx(B,{sx:{flex:1},children:j(T,E)}),a.jsxs(Ro,{direction:"row",spacing:.5,sx:{flexShrink:0},children:[a.jsx(ft,{size:"small",onClick:()=>v(E),disabled:E===0,title:"上へ移動",children:a.jsx(TP,{fontSize:"small"})}),a.jsx(ft,{size:"small",onClick:()=>C(E),disabled:E===m.length-1,title:"下へ移動",children:a.jsx(w2,{fontSize:"small"})}),a.jsx(ft,{size:"small",onClick:()=>y(E),disabled:!M,color:"error",title:"削除",children:a.jsx(zn,{fontSize:"small"})})]})]},E))}),a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(Qn,{}),onClick:g,disabled:!D,children:"追加"}),u&&m.length>=u&&a.jsx(G,{variant:"caption",color:"text.secondary",sx:{ml:1},children:"最大数に達しました"})]})})}function hle({open:t,draftAge:e,onRecover:n,onDiscard:r}){return a.jsxs(Qt,{open:t,onClose:r,children:[a.jsx(Yt,{children:"前回の変更を復元しますか?"}),a.jsx(Jt,{children:a.jsxs(Eo,{children:["保存されていない編集内容が見つかりました(",e,")。 この変更を復元しますか?"]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:r,children:"破棄する"}),a.jsx(pe,{onClick:n,variant:"contained",children:"復元する"})]})]})}function mle({contentTypeId:t,contentId:e,content:n,basePath:r,onPulled:s,disabled:i=!1}){const{branchUseCase:l}=Ei(),u=l==null?void 0:l.getState(),[p,f]=b.useState(!1),[m,g]=b.useState(!1),[y,v]=b.useState(null),[C,S]=b.useState(null),[j,D]=b.useState(!1),M=b.useRef(null);if(b.useEffect(()=>{if(!l||!u||u.branchType==="develop")return;const I=JSON.stringify(n);if(M.current===I)return;M.current=I,(async()=>{D(!0);try{const R=await l.isSameAsDevelop({contentTypeId:t,contentId:e,content:n,basePath:r});S(R)}catch{S(!1)}finally{D(!1)}})()},[l,u,t,e,n,r]),!u||u.branchType==="develop")return null;const T=()=>{v(null),f(!0)},E=async()=>{if(l){g(!0),v(null);try{await l.pullContentFromDevelop({contentTypeId:t,contentId:e,basePath:r}),f(!1),s==null||s()}catch(I){v(I instanceof Error?I.message:"エラーが発生しました")}finally{g(!1)}}},k=i||m||j||C===!0,A=j?a.jsx(ut,{size:16}):C?a.jsx(Ph,{}):m?a.jsx(ut,{size:16}):a.jsx(AJ,{}),O=C?"最新":"共有ブランチから取り込む";return a.jsxs(a.Fragment,{children:[a.jsx(Er,{title:C?"共有ブランチと同じ内容です":"",children:a.jsx("span",{children:a.jsx(pe,{variant:"outlined",color:C?"inherit":"secondary",startIcon:A,onClick:T,disabled:k,children:O})})}),a.jsxs(Qt,{open:p,onClose:()=>f(!1),children:[a.jsx(Yt,{children:"共有ブランチから取り込む"}),a.jsxs(Jt,{children:[a.jsxs(Eo,{children:["このコンテンツを共有ブランチの内容で上書きしますか?",a.jsx("br",{}),a.jsx("strong",{children:"個人ブランチでの変更は失われます。"})]}),y&&a.jsx(zt,{severity:"error",sx:{mt:2},children:y})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>f(!1),disabled:m,children:"キャンセル"}),a.jsx(pe,{onClick:E,color:"warning",variant:"contained",disabled:m,startIcon:m?a.jsx(ut,{size:16}):void 0,children:"上書きして取り込む"})]})]})]})}const v4="fieldGroup:";function gle(t){try{const e=localStorage.getItem(`${v4}${t}`);return e===null?!1:e==="true"}catch{return!1}}function yle(t,e){try{localStorage.setItem(`${v4}${t}`,String(e))}catch{}}function vle({name:t,children:e}){const[n,r]=b.useState(()=>gle(t));return b.useEffect(()=>{yle(t,n)},[t,n]),a.jsxs(_s,{expanded:n,onChange:(s,i)=>r(i),sx:{mt:3,mb:2,"&:before":{display:"none"},boxShadow:"none",border:"1px solid",borderColor:"divider",borderRadius:1,"&.Mui-expanded":{margin:0,mt:3,mb:2}},children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),sx:{backgroundColor:"grey.50",borderRadius:n?"4px 4px 0 0":1,minHeight:48,"&.Mui-expanded":{minHeight:48}},children:a.jsx(G,{variant:"subtitle1",fontWeight:600,children:t})}),a.jsx(Is,{sx:{pt:2},children:a.jsx(B,{sx:{display:"flex",flexDirection:"column",gap:2},children:e})})]})}const jA=(t,e,n)=>{if(t&&"reportValidity"in t){const r=rt(n,e);t.setCustomValidity(r&&r.message||""),t.reportValidity()}},cw=(t,e)=>{for(const n in e.fields){const r=e.fields[n];r&&r.ref&&"reportValidity"in r.ref?jA(r.ref,n,t):r&&r.refs&&r.refs.forEach(s=>jA(s,n,t))}},TA=(t,e)=>{e.shouldUseNativeValidation&&cw(t,e);const n={};for(const r in t){const s=rt(e.fields,r),i=Object.assign(t[r]||{},{ref:s&&s.ref});if(xle(e.names||Object.keys(t),r)){const l=Object.assign({},rt(n,r));Bn(l,"root",i),Bn(n,r,l)}else Bn(n,r,i)}return n},xle=(t,e)=>{const n=DA(e);return t.some(r=>DA(r).match(`^${n}\\.\\d+`))};function DA(t){return t.replace(/\]|\[/g,"")}function x4(t,e,n){function r(u,p){var f;Object.defineProperty(u,"_zod",{value:u._zod??{},enumerable:!1}),(f=u._zod).traits??(f.traits=new Set),u._zod.traits.add(t),e(u,p);for(const m in l.prototype)m in u||Object.defineProperty(u,m,{value:l.prototype[m].bind(u)});u._zod.constr=l,u._zod.def=p}const s=(n==null?void 0:n.Parent)??Object;class i extends s{}Object.defineProperty(i,"name",{value:t});function l(u){var p;const f=n!=null&&n.Parent?new i:this;r(f,u),(p=f._zod).deferred??(p.deferred=[]);for(const m of f._zod.deferred)m();return f}return Object.defineProperty(l,"init",{value:r}),Object.defineProperty(l,Symbol.hasInstance,{value:u=>{var p,f;return n!=null&&n.Parent&&u instanceof n.Parent?!0:(f=(p=u==null?void 0:u._zod)==null?void 0:p.traits)==null?void 0:f.has(t)}}),Object.defineProperty(l,"name",{value:t}),l}class ble extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Sle={};function b4(t){return Sle}function Cle(t,e){return typeof e=="bigint"?e.toString():e}const S4=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function zy(t){return typeof t=="string"?t:t==null?void 0:t.message}function C4(t,e,n){var s,i,l,u,p,f;const r={...t,path:t.path??[]};if(!t.message){const m=zy((l=(i=(s=t.inst)==null?void 0:s._zod.def)==null?void 0:i.error)==null?void 0:l.call(i,t))??zy((u=e==null?void 0:e.error)==null?void 0:u.call(e,t))??zy((p=n.customError)==null?void 0:p.call(n,t))??zy((f=n.localeError)==null?void 0:f.call(n,t))??"Invalid input";r.message=m}return delete r.inst,delete r.continue,e!=null&&e.reportInput||delete r.input,r}const w4=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Cle,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},wle=x4("$ZodError",w4),j4=x4("$ZodError",w4,{Parent:Error}),jle=t=>(e,n,r,s)=>{const i=r?Object.assign(r,{async:!1}):{async:!1},l=e._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new ble;if(l.issues.length){const u=new((s==null?void 0:s.Err)??t)(l.issues.map(p=>C4(p,i,b4())));throw S4(u,s==null?void 0:s.callee),u}return l.value},Tle=jle(j4),Dle=t=>async(e,n,r,s)=>{const i=r?Object.assign(r,{async:!0}):{async:!0};let l=e._zod.run({value:n,issues:[]},i);if(l instanceof Promise&&(l=await l),l.issues.length){const u=new((s==null?void 0:s.Err)??t)(l.issues.map(p=>C4(p,i,b4())));throw S4(u,s==null?void 0:s.callee),u}return l.value},Ele=Dle(j4);function EA(t,e){try{var n=t()}catch(r){return e(r)}return n&&n.then?n.then(void 0,e):n}function Rle(t,e){for(var n={};t.length;){var r=t[0],s=r.code,i=r.message,l=r.path.join(".");if(!n[l])if("unionErrors"in r){var u=r.unionErrors[0].errors[0];n[l]={message:u.message,type:u.code}}else n[l]={message:i,type:s};if("unionErrors"in r&&r.unionErrors.forEach(function(m){return m.errors.forEach(function(g){return t.push(g)})}),e){var p=n[l].types,f=p&&p[r.code];n[l]=Q2(l,e,n,s,f?[].concat(f,r.message):r.message)}t.shift()}return n}function kle(t,e){for(var n={};t.length;){var r=t[0],s=r.code,i=r.message,l=r.path.join(".");if(!n[l])if(r.code==="invalid_union"&&r.errors.length>0){var u=r.errors[0][0];n[l]={message:u.message,type:u.code}}else n[l]={message:i,type:s};if(r.code==="invalid_union"&&r.errors.forEach(function(m){return m.forEach(function(g){return t.push(g)})}),e){var p=n[l].types,f=p&&p[r.code];n[l]=Q2(l,e,n,s,f?[].concat(f,r.message):r.message)}t.shift()}return n}function Mle(t,e,n){if(n===void 0&&(n={}),(function(r){return"_def"in r&&typeof r._def=="object"&&"typeName"in r._def})(t))return function(r,s,i){try{return Promise.resolve(EA(function(){return Promise.resolve(t[n.mode==="sync"?"parse":"parseAsync"](r,e)).then(function(l){return i.shouldUseNativeValidation&&cw({},i),{errors:{},values:n.raw?Object.assign({},r):l}})},function(l){if((function(u){return Array.isArray(u==null?void 0:u.issues)})(l))return{values:{},errors:TA(Rle(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}};if((function(r){return"_zod"in r&&typeof r._zod=="object"})(t))return function(r,s,i){try{return Promise.resolve(EA(function(){return Promise.resolve((n.mode==="sync"?Tle:Ele)(t,r,e)).then(function(l){return i.shouldUseNativeValidation&&cw({},i),{errors:{},values:n.raw?Object.assign({},r):l}})},function(l){if((function(u){return u instanceof wle})(l))return{values:{},errors:TA(kle(l.issues,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}};throw new Error("Invalid input: not a Zod schema")}function Ole(t,e){const n={};for(const r of t){const s=e.find(l=>l.key===r.key);let i=Ale(r,s);s!=null&&s.required||(i=i.optional()),n[r.key]=i}return Tr.object(n)}function Ale(t,e){switch(t.type){case"text":case"html":case"markdown":return RA(e);case"number":return _le(e);case"boolean":return Tr.boolean();case"date":return RA(e);case"image":case"file":return Tr.object({uuid:Tr.string(),url:Tr.string(),originalName:Tr.string()}).nullable();case"select":return Ile(t,e);case"relation":return t.multiple?Tr.array(Tr.string()):Tr.string().nullable();case"array":return Tr.array(Tr.unknown());case"label":return Tr.unknown().optional();default:return Tr.unknown()}}function RA(t){let e=Tr.string();if(t!=null&&t.required&&(e=e.min(1,"この項目は必須です")),t!=null&&t.pattern){const n=new RegExp(t.pattern),r=t.patternMessage??`パターン「${t.pattern}」に一致しません`;e=e.regex(n,r)}return e}function _le(t){return Tr.preprocess(e=>{if(e===""||e===null||e===void 0)return;const n=Number(e);return isNaN(n)?e:n},t!=null&&t.required?Tr.number({invalid_type_error:"数値を入力してください"}):Tr.number().optional())}function Ile(t,e){var r,s;const n=((s=(r=t.options)==null?void 0:r.choices)==null?void 0:s.map(i=>i.value))??[];if(n.length>0){const i=e!=null&&e.required?n:["",...n];return Tr.enum(i)}return Tr.string()}function Ple(t,e,n){const r={};for(const s of t){const i=e.find(l=>l.key===s.key);if(n&&s.key in n){r[s.key]=n[s.key];continue}if((i==null?void 0:i.defaultValue)!==void 0&&i.defaultValue!==null){r[s.key]=i.defaultValue;continue}r[s.key]=Lle(s)}return r}function Lle(t){switch(t.type){case"text":case"html":case"markdown":case"date":case"select":return"";case"number":return"";case"boolean":return!1;case"image":case"file":return null;case"relation":return t.multiple?[]:null;case"array":return[];case"label":return;default:return null}}class zle{constructor(e){this.deps=e}async saveContent(e){var r;const n=await this.deps.saveUseCase.execute(e,this.deps.branch);return await((r=this.deps.branchUseCase)==null?void 0:r.refreshDiffAfterSave()),n}async setStatusContent(e){var n;await this.deps.setStatusUseCase.execute(e,this.deps.branch),await((n=this.deps.branchUseCase)==null?void 0:n.refreshDiffAfterSave())}async deleteContent(e){var n;await this.deps.deleteUseCase.execute(e,this.deps.branch),await((n=this.deps.branchUseCase)==null?void 0:n.refreshDiffAfterSave())}async fetchContent(e,n,r){return this.deps.fetchUseCase.execute(e,n,r??this.deps.branch)}}class $le{constructor(e){this.client=e}async fetchIndex(e,n,r){oe.debug("GitHubContentRepositoryImpl.fetchIndex",{basePath:e,contentTypeId:n,branch:r});const s=Ah(e,n);return this.client.fetchJsonOrDefault(s,[],r)}async fetchViewIndex(e,n,r,s){oe.debug("GitHubContentRepositoryImpl.fetchViewIndex",{basePath:e,contentTypeId:n,viewId:r,branch:s});const i=Ql(e,n,r,null);return this.client.fetchJsonOrDefault(i,[],s)}async fetchContent(e,n,r,s){oe.debug("GitHubContentRepositoryImpl.fetchContent",{basePath:e,contentTypeId:n,contentId:r,branch:s});const i=Oh(e,n,r),l=await this.client.fetchFileOrNull(i,s);return l?JSON.parse(l):null}async commitFiles(e,n,r){return oe.info("GitHubContentRepositoryImpl.commitFiles",{message:e,fileCount:n.length,branch:r}),this.client.commitFiles(e,n,r)}async fetchContentType(e,n){oe.debug("GitHubContentRepositoryImpl.fetchContentType",{contentTypeId:e,branch:n});const r=Kl(e),s=await this.client.fetchFileOrNull(r,n);return s?JSON.parse(s):null}async fetchViews(e,n){oe.debug("GitHubContentRepositoryImpl.fetchViews",{contentTypeId:e,branch:n});const r=sc(e),s=await this.client.fetchFileOrNull(r,n);return s?JSON.parse(s):null}async fetchJson(e,n){return oe.debug("GitHubContentRepositoryImpl.fetchJson",{path:e,branch:n}),this.client.fetchJson(e,n)}}function ej(t,e){return{readJson:async n=>{try{return await t.fetchJson(n,e)}catch{return null}}}}function T4(t){const{contentId:e,title:n,status:r,formData:s,existingContent:i,createdBy:l,updatedBy:u,now:p,publishedAt:f}=t;return{contentId:e,title:n,status:r,data:s,createdAt:(i==null?void 0:i.createdAt)??p,updatedAt:p,publishedAt:f??(i==null?void 0:i.publishedAt)??null,createdBy:(i==null?void 0:i.createdBy)??l,updatedBy:u}}function Nle(){return crypto.randomUUID()}class tj{decide(e,n,r,s){const i=e??"draft";switch(n){case"save":return this.decideSave(i);case"publish":return this.decidePublish(i,r);case"unpublish":return this.decideUnpublish(i);case"delete":return this.decideDelete(i);case"setStatus":if(!s)throw new Error("setStatus action requires params with targetStatus");return this.decideSetStatus(i,s.targetStatus,r)}}decideSave(e){return{newStatus:e,basePath:this.getBasePath(e),publishedAt:void 0,deleteSourcePath:!1,sourceBasePath:null}}decidePublish(e,n){const r=e!=="published";return{newStatus:"published",basePath:"published",publishedAt:n,deleteSourcePath:r,sourceBasePath:r?"private":null}}decideUnpublish(e){const n=e==="published";return{newStatus:"draft",basePath:"private",publishedAt:null,deleteSourcePath:n,sourceBasePath:n?"published":null}}decideDelete(e){return{newStatus:e,basePath:this.getBasePath(e),publishedAt:void 0,deleteSourcePath:!1,sourceBasePath:null}}decideSetStatus(e,n,r){if(e===n)return{newStatus:n,basePath:this.getBasePath(n),publishedAt:void 0,deleteSourcePath:!1,sourceBasePath:null};const s=this.getBasePath(e),i=this.getBasePath(n),l=s!==i;let u;return n==="published"?u=r:e==="published"?u=null:u=void 0,{newStatus:n,basePath:i,publishedAt:u,deleteSourcePath:l,sourceBasePath:l?s:null}}getBasePath(e){return e==="published"?"published":"private"}canExecute(e,n){switch(n){case"save":return!0;case"publish":return!0;case"unpublish":return e==="published";case"delete":return!0;case"setStatus":return!0}}}class Fle{constructor(e){St(this,"statusDecider",new tj);this.contentRepository=e}async execute(e,n){const{contentTypeId:r,contentId:s,formData:i,existingContent:l,createdBy:u,targetStatus:p}=e;oe.info("SaveContentUseCase.execute",{contentTypeId:r,contentId:s,branch:n,targetStatus:p});const f=new Date().toISOString(),m=s??Nle(),y=s===null&&p?this.statusDecider.decide(null,"setStatus",f,{targetStatus:p}):this.statusDecider.decide((l==null?void 0:l.status)??null,"save",f),v=T4({contentId:m,title:i.title||"Untitled",status:y.newStatus,formData:i,existingContent:l,createdBy:u,updatedBy:u,now:f}),C=ej(this.contentRepository,n),S=[{path:Oh(y.basePath,r,m),content:JSON.stringify(v,null,2)}],j=await sP(C,{basePath:y.basePath,contentTypeId:r,content:v});S.push(...j);const D=await lP(C,{contentTypeId:r,updatedBy:u,oldStatus:(l==null?void 0:l.status)??null,newStatus:y.newStatus});return S.push(D),await this.contentRepository.commitFiles(`保存: ${r}/${m}`,S,n),oe.info("SaveContentUseCase.execute completed",{contentId:m,branch:n}),{contentId:m}}}class Ble{constructor(e){St(this,"statusDecider",new tj);this.contentRepository=e}async execute(e,n){const{contentTypeId:r,contentId:s,status:i}=e;oe.info("DeleteContentUseCase.execute",{contentTypeId:r,contentId:s,status:i,branch:n});const l=this.statusDecider.getBasePath(i),u=ej(this.contentRepository,n),p=[{path:Oh(l,r,s),content:"",delete:!0}],f=await iP(u,{basePath:l,contentTypeId:r,contentId:s});p.push(...f);const m=await oQ(u,{contentTypeId:r,deletedBy:"system",deletedStatus:i});p.push(m),await this.contentRepository.commitFiles(`削除: ${r}/${s}`,p,n),oe.info("DeleteContentUseCase.execute completed",{contentId:s,branch:n})}}class Ule{constructor(e){this.contentRepository=e}async execute(e,n,r){oe.debug("FetchContentUseCase.execute",{contentTypeId:e,contentId:n,branch:r});const s=await this.contentRepository.fetchIndex("published",e,r),i=await this.contentRepository.fetchIndex("private",e,r),l=s.some(p=>p.contentId===n),u=i.some(p=>p.contentId===n);if(l){const p=await this.contentRepository.fetchContent("published",e,n,r);if(p)return p}if(u){const p=await this.contentRepository.fetchContent("private",e,n,r);if(p)return p}throw oe.warn("FetchContentUseCase.execute","Content not found",{contentTypeId:e,contentId:n,branch:r}),new Error("Content not found")}}class Vle{constructor(e){St(this,"statusDecider",new tj);this.contentRepository=e}async execute(e,n){const{contentTypeId:r,contentId:s,formData:i,existingContent:l,createdBy:u,targetStatus:p}=e;oe.info("SetContentVisibilityUseCase.execute",{contentTypeId:r,contentId:s,targetStatus:p,branch:n});const f=new Date().toISOString(),m=this.statusDecider.decide((l==null?void 0:l.status)??null,"setStatus",f,{targetStatus:p}),g=m.publishedAt===void 0?(l==null?void 0:l.publishedAt)??null:m.publishedAt,y=T4({contentId:s,title:i.title||"Untitled",status:m.newStatus,formData:i,existingContent:l,createdBy:u,updatedBy:u,now:f,publishedAt:g}),v=ej(this.contentRepository,n),C=[{path:Oh(m.basePath,r,s),content:JSON.stringify(y,null,2)}],S=await sP(v,{basePath:m.basePath,contentTypeId:r,content:y});if(C.push(...S),m.deleteSourcePath&&m.sourceBasePath){const M=await iP(v,{basePath:m.sourceBasePath,contentTypeId:r,contentId:s});C.push(...M),C.push({path:Oh(m.sourceBasePath,r,s),content:"",delete:!0})}const j=await lP(v,{contentTypeId:r,updatedBy:u,oldStatus:(l==null?void 0:l.status)??null,newStatus:m.newStatus});C.push(j);const D=this.getCommitMessage(p,r,s);await this.contentRepository.commitFiles(D,C,n),oe.info("SetContentVisibilityUseCase.execute completed",{contentId:s,targetStatus:p,branch:n})}getCommitMessage(e,n,r){switch(e){case"published":return`公開: ${n}/${r}`;case"unpublished":return`非公開化: ${n}/${r}`;case"draft":return`下書き化: ${n}/${r}`}}}function Hle(t){const{isProcessing:e}=t;return d_({shouldBlockFn:()=>e,withResolver:!1,disabled:!e}),b.useEffect(()=>{if(!e)return;const n=r=>(r.preventDefault(),r.returnValue="","");return window.addEventListener("beforeunload",n),()=>window.removeEventListener("beforeunload",n)},[e]),{isLocked:e}}const Wle="frelio_draft_";function qle(t,e){return`${Wle}${t}_${e}`}function Gle(t){const e=new Date(t),r=new Date().getTime()-e.getTime(),s=Math.floor(r/6e4);if(s<1)return"たった今";if(s<60)return`${s}分前`;const i=Math.floor(s/60);return i<24?`${i}時間前`:`${Math.floor(i/24)}日前`}function Zle(t){const{contentTypeId:e,contentId:n,debounceMs:r=2e3}=t,s=qle(e,n),i=b.useRef(null),[l,u]=b.useState(!1),[p,f]=b.useState(null);b.useEffect(()=>{try{const C=localStorage.getItem(s);if(C){const S=JSON.parse(C);f(S),u(!0)}}catch{localStorage.removeItem(s)}},[s]);const m=b.useCallback(C=>{i.current&&clearTimeout(i.current),i.current=setTimeout(()=>{const S={data:C,savedAt:new Date().toISOString()};try{localStorage.setItem(s,JSON.stringify(S)),f(S)}catch(j){oe.error("useLocalDraft.saveDraft","Failed to save draft to localStorage",{error:j})}},r)},[s,r]),g=b.useCallback(()=>{i.current&&clearTimeout(i.current),localStorage.removeItem(s),f(null),u(!1)},[s]),y=b.useCallback(()=>(u(!1),(p==null?void 0:p.data)??null),[p]),v=b.useCallback(()=>{g(),u(!1)},[g]);return b.useEffect(()=>()=>{i.current&&clearTimeout(i.current)},[]),{savedDraft:p,saveDraft:m,clearDraft:g,hasDraft:p!==null,draftAge:p?Gle(p.savedAt):null,showRecoveryDialog:l,acceptDraft:y,rejectDraft:v}}class $y{constructor(e){this.queries=e}static ContentTypeQueryParams(e,n,r){return{queryKey:["content-type",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJson(Kl(n),r)},enabled:!!e}}static UiQueryParams(e,n,r){return{queryKey:["content-type-ui",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");return new At(e).fetchJson(Ld(n),r)},enabled:!!e}}static ContentQueryParams(e,n,r,s,i,l){return{queryKey:["content",n,r,i],queryFn:()=>l(n,r,i),enabled:!!e&&!s}}getContentType(){return this.queries.contentType.data}getUiMeta(){return this.queries.ui.data}getContentData(){return this.queries.content.data}isLoading(){return this.queries.contentType.isLoading||this.queries.ui.isLoading||this.queries.content.isLoading}getError(){return this.queries.contentType.error||this.queries.ui.error||this.queries.content.error}async refetchContent(){await this.queries.content.refetch()}}class kd{constructor(e){this.mutations=e}static SaveMutationParams(e,n){return{mutationFn:n,onMutate:()=>{e.presenter.setMessage(null)},onSuccess:async r=>{e.localDraft.clearDraft(),e.unsavedGuard.setJustSaved(),e.queryClient.invalidateQueries({queryKey:["view-index","published",e.contentTypeId]}),e.queryClient.invalidateQueries({queryKey:["view-index","private",e.contentTypeId]}),e.isNew?e.navigate({to:`/contents/${e.contentTypeId}`,ignoreBlocker:!0}):(await e.refetchContent(),e.presenter.setMessage({type:"success",text:"保存しました"}))},onError:r=>{e.presenter.setMessage({type:"error",text:`保存に失敗しました: ${r.message}`})}}}static DeleteMutationParams(e,n){return{mutationFn:n,onMutate:()=>{e.presenter.setMessage(null)},onSuccess:()=>{e.localDraft.clearDraft(),e.unsavedGuard.setJustSaved(),e.queryClient.invalidateQueries({queryKey:["view-index","published",e.contentTypeId]}),e.queryClient.invalidateQueries({queryKey:["view-index","private",e.contentTypeId]}),e.navigate({to:`/contents/${e.contentTypeId}`,ignoreBlocker:!0})},onError:r=>{e.presenter.setMessage({type:"error",text:`削除に失敗しました: ${r.message}`})}}}static SetStatusMutationParams(e,n){return{mutationFn:n,onMutate:()=>{e.presenter.setMessage(null)},onSuccess:async(r,s)=>{e.localDraft.clearDraft(),e.unsavedGuard.setJustSaved(),e.queryClient.invalidateQueries({queryKey:["view-index","published",e.contentTypeId]}),e.queryClient.invalidateQueries({queryKey:["view-index","private",e.contentTypeId]}),await e.refetchContent();const i=kd.getStatusChangeMessage(s.targetStatus);e.presenter.setMessage({type:"success",text:i})},onError:r=>{e.presenter.setMessage({type:"error",text:`ステータス変更に失敗しました: ${r.message}`})}}}static getStatusChangeMessage(e){switch(e){case"published":return"公開しました";case"unpublished":return"非公開にしました";case"draft":return"下書きにしました"}}async save(e){await this.mutations.save.mutateAsync(e)}isSaving(){return this.mutations.save.isPending}async delete(){await this.mutations.delete.mutateAsync()}isDeleting(){return this.mutations.delete.isPending}async setStatus(e){await this.mutations.setStatus.mutateAsync(e)}isSettingStatus(){return this.mutations.setStatus.isPending}isProcessing(){return this.isSaving()||this.isDeleting()||this.isSettingStatus()}}const ui=Zre(t=>({deleteDialogOpen:!1,message:null,pendingStatus:null,editorMode:"ui",jsonEditText:"",jsonIsDirty:!1,tabSwitchDialogOpen:!1,pendingTabSwitch:null,openDeleteDialog:()=>t({deleteDialogOpen:!0}),closeDeleteDialog:()=>t({deleteDialogOpen:!1}),setMessage:e=>t({message:e}),clearMessage:()=>t({message:null}),setPendingStatus:e=>t({pendingStatus:e}),clearPendingStatus:()=>t({pendingStatus:null}),setEditorMode:e=>t({editorMode:e}),setJsonEditText:e=>t({jsonEditText:e}),setJsonIsDirty:e=>t({jsonIsDirty:e}),openTabSwitchDialog:e=>t({tabSwitchDialogOpen:!0,pendingTabSwitch:e}),closeTabSwitchDialog:()=>t({tabSwitchDialogOpen:!1,pendingTabSwitch:null})}));class Kle{getState(){const e=ui.getState();return{deleteDialogOpen:e.deleteDialogOpen,message:e.message,pendingStatus:e.pendingStatus,editorMode:e.editorMode,jsonEditText:e.jsonEditText,jsonIsDirty:e.jsonIsDirty,tabSwitchDialogOpen:e.tabSwitchDialogOpen,pendingTabSwitch:e.pendingTabSwitch}}subscribe(e){return ui.subscribe(e)}openDeleteDialog(){ui.getState().openDeleteDialog()}closeDeleteDialog(){ui.getState().closeDeleteDialog()}setMessage(e){ui.getState().setMessage(e)}clearMessage(){ui.getState().clearMessage()}setPendingStatus(e){ui.getState().setPendingStatus(e)}clearPendingStatus(){ui.getState().clearPendingStatus()}setEditorMode(e){ui.getState().setEditorMode(e)}setJsonEditText(e){ui.getState().setJsonEditText(e)}setJsonIsDirty(e){ui.getState().setJsonIsDirty(e)}openTabSwitchDialog(e){ui.getState().openTabSwitchDialog(e)}closeTabSwitchDialog(){ui.getState().closeTabSwitchDialog()}}class Qle{constructor(e){this.deps=e}getState(){const{repo:e,mutationRepo:n,presenter:r,form:s,localDraft:i,unsavedGuard:l,contentTypeId:u,contentId:p,isNew:f,githubUser:m,canEdit:g}=this.deps,y=r.getState(),v=e.getContentData(),C=f?y.pendingStatus??"draft":(v==null?void 0:v.status)??"draft",S=f?e.isLoading()&&!e.getContentType():e.isLoading(),j=n.isSaving(),D=n.isDeleting(),M=n.isSettingStatus(),T=j||D||M,E=D?"削除中...":M?"ステータス変更中...":"保存中...";return{contentTypeId:u,contentId:p,isNew:f,contentType:e.getContentType(),uiMeta:e.getUiMeta(),contentData:v,isLoading:S,error:e.getError(),deleteDialogOpen:y.deleteDialogOpen,message:y.message,currentStatus:C,isDirty:s.formState.isDirty,isValid:s.formState.isValid,isSaving:j,isDeleting:D,isSettingStatus:M,isProcessing:T,processingMessage:E,form:s,unsavedGuard:l,localDraft:i,uploadedBy:(m==null?void 0:m.login)??"unknown",editorMode:y.editorMode,jsonEditText:y.jsonEditText,jsonIsDirty:y.jsonIsDirty,tabSwitchDialogOpen:y.tabSwitchDialogOpen,pendingTabSwitch:y.pendingTabSwitch,canEdit:g}}save(){const{form:e,mutationRepo:n}=this.deps;e.handleSubmit(r=>{n.save({formData:r})})()}setStatus(e){const{form:n,mutationRepo:r,presenter:s,isNew:i}=this.deps;i?s.setPendingStatus(e):n.handleSubmit(l=>{r.setStatus({formData:l,targetStatus:e})})()}delete(){const{mutationRepo:e,presenter:n}=this.deps;e.delete(),n.closeDeleteDialog()}recoverDraft(){const{localDraft:e,form:n}=this.deps,r=e.acceptDraft();r&&n.reset(r)}openDeleteDialog(){this.deps.presenter.openDeleteDialog()}closeDeleteDialog(){this.deps.presenter.closeDeleteDialog()}clearMessage(){this.deps.presenter.clearMessage()}getUserDisplayName(e){const n=this.deps.users.find(r=>r.githubUsername===e);return(n==null?void 0:n.displayName)??e}prepareJsonForMode(e){const{presenter:n,repo:r,form:s,isNew:i,githubUser:l,contentTypeId:u,contentId:p}=this.deps,{jsonEditText:f}=n.getState(),m=r.getContentData();if(e==="json"&&!f){if(i){const g=s.getValues(),y=new Date().toISOString(),v={contentId:p==="new"?"(自動生成)":p,title:g.title||"",status:"draft",data:this.extractDataFields(g),createdAt:y,updatedAt:y,publishedAt:null,createdBy:(l==null?void 0:l.login)??"unknown",updatedBy:(l==null?void 0:l.login)??"unknown"};n.setJsonEditText(JSON.stringify(v,null,2))}else m&&n.setJsonEditText(JSON.stringify(m,null,2));n.setJsonIsDirty(!1)}n.setEditorMode(e)}extractDataFields(e){const{title:n,...r}=e;return r}updateJsonText(e){this.deps.presenter.setJsonEditText(e),this.deps.presenter.setJsonIsDirty(!0)}formatJson(){const{presenter:e}=this.deps,{jsonEditText:n}=e.getState();try{const r=JSON.parse(n),s=JSON.stringify(r,null,2);e.setJsonEditText(s)}catch{e.setMessage({type:"error",text:"JSONのフォーマットに失敗しました(構文エラー)"})}}resetJson(){const{presenter:e,repo:n,form:r,isNew:s,githubUser:i,contentId:l}=this.deps,u=n.getContentData();if(s){const p=r.getValues(),f=new Date().toISOString(),m={contentId:l==="new"?"(自動生成)":l,title:p.title||"",status:"draft",data:this.extractDataFields(p),createdAt:f,updatedAt:f,publishedAt:null,createdBy:(i==null?void 0:i.login)??"unknown",updatedBy:(i==null?void 0:i.login)??"unknown"};e.setJsonEditText(JSON.stringify(m,null,2))}else u&&e.setJsonEditText(JSON.stringify(u,null,2));e.setJsonIsDirty(!1),e.setMessage({type:"info",text:"JSONを元に戻しました"})}async saveFromJson(){const{presenter:e,mutationRepo:n,form:r,isNew:s,contentId:i}=this.deps,{jsonEditText:l}=e.getState(),u=Na(l);if(!u.success)return e.setMessage({type:"error",text:`JSONの構文エラー: ${u.error}`}),!1;const p=u.data,f={title:p.title,...p.data};try{return r.reset(f,{keepDirty:!1}),await n.save({formData:f}),e.setJsonIsDirty(!1),e.setMessage({type:"success",text:"コンテンツを保存しました"}),oe.info("ContentEditUseCase.saveFromJson",{contentId:i}),!0}catch(m){const g=m instanceof Error?m.message:String(m);return e.setMessage({type:"error",text:`保存に失敗しました: ${g}`}),oe.error("ContentEditUseCase.saveFromJson failed",{error:m}),!1}}cancelTabSwitch(){this.deps.presenter.closeTabSwitchDialog()}discardAndSwitchTab(){const{presenter:e}=this.deps,{pendingTabSwitch:n}=e.getState();n&&(e.setJsonIsDirty(!1),e.closeTabSwitchDialog(),this.prepareJsonForMode(n))}async saveAndSwitchTab(){const{presenter:e}=this.deps,{pendingTabSwitch:n,editorMode:r}=e.getState();if(n){if(r==="json"){if(!await this.saveFromJson())return}else this.save();e.closeTabSwitchDialog(),this.prepareJsonForMode(n)}}}const po=new Kle;function Jle(t){const{authUseCase:e}=rr(),{branchUseCase:n}=Ei(),{token:r,githubUser:s,users:i,currentUser:l}=e.getState(),u=ws(l,"canEditContent"),p=(n==null?void 0:n.getCurrentBranch())??"develop",f=ys(),m=ur(),{contentTypeId:g,contentId:y}=uc({from:"/contents/$contentTypeId/$contentId"}),v=y==="new",C=t==null?void 0:t.duplicateFrom;b.useSyncExternalStore(po.subscribe.bind(po),()=>JSON.stringify(po.getState()));const S=b.useMemo(()=>{if(!r)return null;const J=new At(r),ie=new $le(J);return new zle({saveUseCase:new Fle(ie),setStatusUseCase:new Vle(ie),deleteUseCase:new Ble(ie),fetchUseCase:new Ule(ie),branchUseCase:n,branch:p})},[r,n,p]),j=jn($y.ContentTypeQueryParams(r,g,p)),D=jn($y.UiQueryParams(r,g,p)),M=b.useCallback(async(J,ie,te)=>{if(!S)throw new Error("Not authenticated");return S.fetchContent(J,ie,te)},[S]),T=jn($y.ContentQueryParams(r,g,y,v,p,M)),E=jn({queryKey:["content",g,C,p,"duplicate-source"],queryFn:()=>M(g,C,p),enabled:!!r&&v&&!!C}),k=new $y({contentType:j,ui:D,content:T}),A=k.getContentType(),O=k.getUiMeta(),I=k.getContentData(),$=b.useMemo(()=>!A||!O?null:Ole(A.fields,O.fields),[A,O]),R=Jae({defaultValues:{},resolver:$?Mle($):void 0,mode:"onBlur"}),{formState:{isDirty:P}}=R,z=Zle({contentTypeId:g,contentId:y}),N=Um({isDirty:P}),H=b.useCallback(async()=>{await k.refetchContent()},[k]),U=b.useMemo(()=>({queryClient:f,contentTypeId:g,isNew:v,presenter:po,localDraft:z,unsavedGuard:N,navigate:J=>m({to:J.to,ignoreBlocker:J.ignoreBlocker}),refetchContent:H}),[f,g,v,z,N,m,H]),L=b.useCallback(async J=>{if(!s||!S)throw new Error("Not authenticated");const ie=po.getState().pendingStatus,te=await S.saveContent({contentTypeId:g,contentId:v?null:y,formData:J.formData,existingContent:I??null,createdBy:s.login,targetStatus:v?ie??void 0:void 0});return v&&ie&&po.clearPendingStatus(),{contentId:te.contentId}},[s,S,g,y,v,I]),W=b.useCallback(async()=>{if(!S)throw new Error("Not authenticated");await S.deleteContent({contentTypeId:g,contentId:y,status:(I==null?void 0:I.status)??"draft"})},[S,g,y,I==null?void 0:I.status]),K=b.useCallback(async J=>{if(!s||!S)throw new Error("Not authenticated");await S.setStatusContent({contentTypeId:g,contentId:y,formData:J.formData,existingContent:I??null,createdBy:s.login,targetStatus:J.targetStatus})},[s,S,g,y,I]),Q=new kd({save:Pn(kd.SaveMutationParams(U,L)),delete:Pn(kd.DeleteMutationParams({...U,contentTypeId:g},W)),setStatus:Pn(kd.SetStatusMutationParams({...U,contentTypeId:g},K))});Hle({isProcessing:Q.isProcessing()});const le=new Qle({repo:k,mutationRepo:Q,presenter:po,form:R,localDraft:z,unsavedGuard:N,contentTypeId:g,contentId:y,isNew:v,githubUser:s,users:i,canEdit:u}),F=b.useRef(!1);return b.useEffect(()=>{if(!A||!O||F.current||!v&&!I||v&&C&&!E.data)return;let J;if(!v&&I)J={...I.data,title:I.title};else if(v&&C&&E.data){const te=E.data;J={...te.data,title:te.title};for(const de of A.fields)de.useAsUrl&&J[de.key]!==void 0&&(J[de.key]="")}const ie=Ple(A.fields,O.fields,J);R.reset(ie),F.current=!0,setTimeout(()=>{R.trigger()},0)},[A,O,I,v,R,C,E.data]),b.useEffect(()=>{if(!P)return;const J=R.watch(ie=>{z.saveDraft(ie)});return()=>J.unsubscribe()},[P,R,z]),b.useEffect(()=>{po.clearMessage(),po.clearPendingStatus(),po.setJsonEditText(""),po.setJsonIsDirty(!1)},[y]),{contentEditUseCase:le}}function Yle(t,e,n=[]){const r=new Map(e.map(f=>[f.key,f])),s=new Map(t.map(f=>[f.key,f])),i=new Set(t.filter(f=>{const m=r.get(f.key);return!(m!=null&&m.hidden)}).map(f=>f.key)),l=new Set(n.flatMap(f=>f.fieldKeys)),u=[],p=[];for(const f of t)!l.has(f.key)&&i.has(f.key)&&p.push({field:f,uiField:r.get(f.key)});p.length>0&&u.push({id:null,label:null,fields:p});for(const f of n){const m=[];for(const g of f.fieldKeys){const y=s.get(g);y&&i.has(g)&&m.push({field:y,uiField:r.get(g)})}m.length>0&&u.push({id:f.id,label:f.label,fields:m})}return u}function Xle(t,e){switch(e){case"trim":return t.trim();case"lowercase":return t.toLowerCase();case"uppercase":return t.toUpperCase();case"slug":return ece(t);case"phone":return tce(t);case"postalCode":return nce(t);default:return t}}function ece(t){return t.toLowerCase().trim().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"").replace(/-+/g,"-").replace(/^-|-$/g,"")}function tce(t){const e=t.replace(/\D/g,"");return e.length===11&&/^0[5789]0/.test(e)?`${e.slice(0,3)}-${e.slice(3,7)}-${e.slice(7)}`:e.length===10&&/^0[1-9]/.test(e)?/^0[36]/.test(e)?`${e.slice(0,2)}-${e.slice(2,6)}-${e.slice(6)}`:`${e.slice(0,3)}-${e.slice(3,6)}-${e.slice(6)}`:e.length===10&&/^0(120|800)/.test(e)?`${e.slice(0,4)}-${e.slice(4,7)}-${e.slice(7)}`:t}function nce(t){const e=t.replace(/\D/g,"");return e.length===7?`${e.slice(0,3)}-${e.slice(3)}`:t}const rce=["ui","json"],sce=Ss("/contents/$contentTypeId/$contentId")({component:oce,validateSearch:t=>({mode:rce.includes(t.mode)?t.mode:void 0,duplicateFrom:typeof t.duplicateFrom=="string"?t.duplicateFrom:void 0})}),ice=[{label:"UI編集",value:"ui"},{label:"JSON編集",value:"json"}];function oce(){const t=ur(),e=Di({from:"/contents/$contentTypeId/$contentId"}),n=e.mode??"ui",{contentEditUseCase:r}=Jle({duplicateFrom:e.duplicateFrom}),{contentTypeId:s,contentId:i,isNew:l,contentType:u,uiMeta:p,contentData:f,isLoading:m,error:g,deleteDialogOpen:y,message:v,currentStatus:C,isDirty:S,isValid:j,isSaving:D,isDeleting:M,isSettingStatus:T,isProcessing:E,processingMessage:k,form:A,unsavedGuard:O,localDraft:I,uploadedBy:$,jsonEditText:R,jsonIsDirty:P,tabSwitchDialogOpen:z,canEdit:N}=r.getState();b.useEffect(()=>{r.prepareJsonForMode(n)},[r,n,f]);const H=le=>{r.setStatus(le)},U=(p==null?void 0:p.label)??s,W={value:n,options:ice,onChange:le=>{t({to:".",search:{...e,mode:le==="ui"?void 0:le},replace:!0})}},Q=`frelio-data/site/contents/${C==="published"?"published":"private"}/${s}/${i}.json`;return m?a.jsx(B,{"data-component-name":"cmp:ContentEditPageLoading",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(ut,{})}):g?a.jsx(B,{"data-component-name":"cmp:ContentEditPageError",sx:{flex:1,overflow:"auto",p:3},children:a.jsxs(zt,{severity:"error",children:["Error: ",g.message]})}):n==="json"?a.jsxs(B,{"data-component-name":"cmp:ContentEditPage",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[a.jsx(B,{sx:{px:3,pt:2,flexShrink:0},children:a.jsx(no,{items:[{label:`${U}一覧`,to:`/contents/${s}`},{label:l?"新規作成":`${U}詳細`}],dropdown:W})}),a.jsxs(B,{"data-component-name":"cmp:JsonEditorContainer",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",maxWidth:"xl",mx:"auto",width:"100%"},children:[a.jsx(rm,{filePath:l?"(新規作成)":Q,isSaving:D,isDirty:P,onFormat:N?()=>r.formatJson():void 0,onReset:N?()=>r.resetJson():void 0,onSave:N?()=>r.saveFromJson():void 0,readOnly:!N}),a.jsx(B,{"data-component-name":"cmp:JsonEditorWrapper",sx:{flex:1,overflow:"hidden",pb:1},children:a.jsx(nm,{value:R,onChange:N?le=>r.updateJsonText(le):void 0,height:"100%",readOnly:!N})})]}),a.jsx(nb,{open:z,onStay:()=>r.cancelTabSwitch(),onDiscard:()=>r.discardAndSwitchTab(),onSaveAndSwitch:()=>r.saveAndSwitchTab()}),v&&a.jsx(zt,{severity:v.type==="info"?"info":v.type,sx:{position:"fixed",bottom:16,left:"50%",transform:"translateX(-50%)",zIndex:1400},onClose:()=>r.clearMessage(),children:v.text})]}):a.jsxs(B,{"data-component-name":"cmp:ContentEditPage",sx:{flex:1,overflow:"auto",p:3},children:[a.jsx(no,{items:[{label:`${U}一覧`,to:`/contents/${s}`},{label:l?"新規作成":`${U}詳細`}],dropdown:W}),a.jsx(la,{titleNode:a.jsx(G,{variant:"h5",component:"h1",sx:{wordBreak:"break-word",overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical",minWidth:0,flex:1},children:l?"新規作成":String(A.watch("title")||"Untitled")}),actions:N?a.jsxs(a.Fragment,{children:[!l&&a.jsx(pe,{variant:"outlined",color:"error",startIcon:a.jsx(zn,{}),onClick:()=>r.openDeleteDialog(),disabled:M,children:"削除"}),a.jsx(pe,{variant:"outlined",startIcon:a.jsx(na,{}),onClick:()=>r.save(),disabled:D||!S||!j,children:D?"保存中...":"保存"}),a.jsxs(_n,{size:"small",sx:{minWidth:120},children:[a.jsx(nr,{id:"status-select-label",children:"ステータス"}),a.jsxs(wn,{labelId:"status-select-label",value:C,label:"ステータス",onChange:le=>H(le.target.value),disabled:T,children:[a.jsx(nt,{value:"draft",children:"下書き"}),a.jsx(nt,{value:"unpublished",children:"非公開"}),a.jsx(nt,{value:"published",children:"公開"})]})]}),!l&&r.getState().contentData&&a.jsx(mle,{contentTypeId:s,contentId:r.getState().contentId,content:r.getState().contentData,basePath:C==="published"?"published":"private",onPulled:()=>{O.setJustSaved(),window.location.reload()},disabled:D||T})]}):a.jsx(G,{variant:"body2",color:"text.secondary",children:"閲覧のみ"})}),v&&a.jsx(zt,{severity:v.type,sx:{mb:2},onClose:()=>r.clearMessage(),children:v.text}),a.jsxs(Qt,{"data-component-name":"cmp:DeleteContentDialog",open:y,onClose:()=>r.closeDeleteDialog(),children:[a.jsx(Yt,{children:"コンテンツを削除"}),a.jsx(Jt,{children:a.jsxs(Eo,{children:["「",String(A.watch("title")||"Untitled"),"」を削除しますか?この操作は取り消せません。"]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>r.closeDeleteDialog(),children:"キャンセル"}),a.jsx(pe,{color:"error",onClick:()=>r.delete(),disabled:M,children:M?"削除中...":"削除"})]})]}),!l&&r.getState().contentData&&a.jsx(cce,{contentData:r.getState().contentData,getUserDisplayName:le=>r.getUserDisplayName(le)}),a.jsx("form",{"data-component-name":"cmp:ContentEditForm",children:a.jsx(Ro,{"data-component-name":"cmp:FieldList",spacing:3,children:u&&p&&a.jsx(ace,{fields:u.fields,uiFields:p.fields,uiGroups:p.groups??[],form:A,uploadedBy:$,readOnly:!N,isNew:l})})}),a.jsx(sb,{open:O.isBlocked,onStay:O.reset,onLeave:O.proceed}),a.jsx(hle,{open:I.showRecoveryDialog,draftAge:I.draftAge,onRecover:()=>r.recoverDraft(),onDiscard:I.rejectDraft}),a.jsx(Yae,{open:E,message:k})]})}function ace({fields:t,uiFields:e,uiGroups:n,form:r,uploadedBy:s,readOnly:i=!1,isNew:l}){const u=vr(),p=aa(u.breakpoints.down("sm")),f=Yle(t,e,n),m=g=>{const y=[];return g.forEach(({field:v,uiField:C})=>{const S=(C==null?void 0:C.columns)??12,j=(C==null?void 0:C.break)??!1;y.push(a.jsx(Et,{item:!0,xs:12,md:S,children:a.jsx(lce,{field:v,uiField:C,form:r,uploadedBy:s,forceReadOnly:i,isNew:l})},v.key)),j&&!p&&y.push(a.jsx(Et,{item:!0,xs:12,sx:{p:"0 !important",height:0}},`${v.key}-break`))}),y};return a.jsx(Ro,{spacing:3,children:f.map((g,y)=>g.id===null?a.jsx(B,{sx:{overflow:"hidden"},children:a.jsx(Et,{container:!0,spacing:3,children:m(g.fields)})},"ungrouped"):a.jsx(vle,{name:g.label??g.id,children:a.jsx(B,{sx:{overflow:"hidden"},children:a.jsx(Et,{container:!0,spacing:3,children:m(g.fields)})})},g.id??`group-${y}`))})}function lce({field:t,uiField:e,form:n,uploadedBy:r,forceReadOnly:s=!1,isNew:i}){const l=(e==null?void 0:e.label)??t.key,u=(e==null?void 0:e.required)??!1,p=(e==null?void 0:e.description)??void 0,f=(e==null?void 0:e.placeholder)??void 0,m=!i&&(t.useAsUrl??!1),g=s||((e==null?void 0:e.readOnly)??!1)||m,y=e==null?void 0:e.warnLength,v=m?a.jsx(Er,{title:"URL に使用されるフィールドのため、新規作成以降は変更できません。変更したい場合はコンテンツを複製してください。",arrow:!0,children:a.jsx(ft,{size:"small",sx:{p:0,ml:.5},children:a.jsx(WJ,{sx:{fontSize:16,color:"text.secondary"}})})}):void 0,C=e==null?void 0:e.autoFormat,S=n.formState.errors[t.key],j=!!S,D=j?S.message:void 0,M=async(T,E)=>{if(C&&typeof T=="string"){const k=Xle(T,C);k!==T&&E(k)}await n.trigger(t.key)};switch(t.type){case"text":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:"",render:({field:T})=>a.jsx(vo,{label:l,labelSuffix:v,required:u,description:p,error:D,warnLength:y?{value:String(T.value??""),limit:y}:void 0,disabled:g,children:a.jsx(Xe,{...T,placeholder:f,fullWidth:!0,size:"small",disabled:g,error:j,value:T.value??"",onBlur:E=>{T.onBlur(),M(E.target.value,T.onChange)}})})});case"html":case"markdown":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:"",render:({field:T})=>a.jsx(vo,{label:l,labelSuffix:v,required:u,description:p??(t.type==="markdown"?"Markdown形式で入力":"HTML形式で入力"),error:D,warnLength:y?{value:String(T.value??""),limit:y}:void 0,disabled:g,children:a.jsx(Xe,{...T,placeholder:f,fullWidth:!0,multiline:!0,minRows:6,size:"small",disabled:g,error:j,value:T.value??""})})});case"number":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:"",render:({field:T})=>a.jsx(vo,{label:l,labelSuffix:v,required:u,description:p,error:D,disabled:g,children:a.jsx(Xe,{...T,type:"number",placeholder:f,fullWidth:!0,size:"small",disabled:g,error:j,value:T.value??"",onChange:E=>T.onChange(E.target.value?Number(E.target.value):"")})})});case"boolean":return a.jsx(vo,{label:l,labelSuffix:v,description:p,error:D,disabled:g,children:a.jsx(uo,{name:t.key,control:n.control,defaultValue:!1,render:({field:T})=>a.jsx(Ax,{checked:!!T.value,onChange:E=>T.onChange(E.target.checked),disabled:g})})});case"date":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:"",render:({field:T})=>a.jsx(vo,{label:l,labelSuffix:v,required:u,description:p,error:D,disabled:g,children:a.jsx(Xe,{...T,type:"date",fullWidth:!0,size:"small",disabled:g,error:j,value:T.value??""})})});case"select":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:"",render:({field:T})=>{var E,k;return a.jsx(vo,{label:l,labelSuffix:v,required:u,description:p,error:D,disabled:g,children:a.jsxs(wn,{...T,value:T.value??"",disabled:g,size:"small",fullWidth:!0,error:j,children:[a.jsx(nt,{value:"",children:a.jsx("em",{children:"選択してください"})}),(k=(E=t.options)==null?void 0:E.choices)==null?void 0:k.map(A=>a.jsx(nt,{value:A.value,children:A.label},A.value))]})})}});case"image":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:null,render:({field:T})=>a.jsx(g4,{label:l,value:T.value,onChange:T.onChange,required:u,description:p??void 0,uploadedBy:r,aspectRatio:e==null?void 0:e.aspectRatio,disabled:g})});case"file":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:null,render:({field:T})=>a.jsx(y4,{label:l,value:T.value,onChange:T.onChange,required:u,description:p??void 0,uploadedBy:r,disabled:g})});case"relation":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:t.multiple?[]:null,render:({field:T})=>{var E;return a.jsx(ple,{label:l,value:T.value,onChange:T.onChange,required:u,description:p??void 0,targetContentType:((E=t.options)==null?void 0:E.targetContentType)??"",multiple:t.multiple,disabled:g})}});case"array":return a.jsx(uo,{name:t.key,control:n.control,defaultValue:[],render:({field:T})=>{var E,k,A;return a.jsx(fle,{label:l,value:T.value??[],onChange:T.onChange,required:u,description:p??void 0,itemType:((E=t.options)==null?void 0:E.itemType)??"text",minItems:(k=t.options)==null?void 0:k.minItems,maxItems:(A=t.options)==null?void 0:A.maxItems,uploadedBy:r,disabled:g})}});case"label":return a.jsxs($t,{variant:"outlined",sx:{p:2,bgcolor:"grey.50",borderStyle:"dashed"},children:[a.jsx(G,{variant:"subtitle1",fontWeight:600,sx:{color:(e==null?void 0:e.labelColor)??"text.primary",mb:p?.5:0},children:l}),p&&a.jsx(G,{variant:"body1",sx:{color:e!=null&&e.labelColor?e.labelColor:"text.secondary","& a":{color:"primary.main"}},children:a.jsx(m4,{text:p})})]});default:return a.jsx(uo,{name:t.key,control:n.control,defaultValue:"",render:({field:T})=>a.jsx(vo,{label:`${l} (${t.type})`,description:`Field type "${t.type}" is not fully implemented yet`,error:D,children:a.jsx(Xe,{...T,fullWidth:!0,size:"small",error:j,value:T.value??""})})})}}function cce({contentData:t,getUserDisplayName:e}){const n=r=>{if(!r)return"-";try{return new Date(r).toLocaleString("ja-JP",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"})}catch{return r}};return a.jsx(B,{sx:{mb:3},children:a.jsxs(_s,{disableGutters:!0,elevation:0,sx:{"&:before":{display:"none"},bgcolor:"transparent",width:"fit-content"},children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{fontSize:"small"}),sx:{minHeight:"auto",p:0,justifyContent:"flex-start","& .MuiAccordionSummary-content":{m:0,flexGrow:0}},children:a.jsxs(G,{variant:"caption",color:"text.secondary",children:["作成日 ",n(t.createdAt)]})}),a.jsx(Is,{sx:{p:0,pt:1},children:a.jsxs(B,{sx:{display:"grid",gridTemplateColumns:{xs:"1fr",sm:"1fr 1fr 1fr"},gap:2},children:[a.jsxs(B,{children:[a.jsx(G,{variant:"caption",color:"text.secondary",children:"更新日"}),a.jsx(G,{variant:"body2",children:n(t.updatedAt)})]}),a.jsxs(B,{children:[a.jsx(G,{variant:"caption",color:"text.secondary",children:"作成者"}),a.jsx(G,{variant:"body2",children:t.createdBy?e(t.createdBy):"-"})]}),a.jsxs(B,{children:[a.jsx(G,{variant:"caption",color:"text.secondary",children:"更新者"}),a.jsx(G,{variant:"body2",children:t.updatedBy?e(t.updatedBy):"-"})]})]})})]})})}const kA=[{value:"eq",label:"="},{value:"neq",label:"!="},{value:"in",label:"in"},{value:"nin",label:"not in"},{value:"contains",label:"含む"},{value:"startsWith",label:"前方一致"},{value:"endsWith",label:"後方一致"}],uce=[{key:"contentId",type:"text"},{key:"status",type:"select"},{key:"createdAt",type:"date"},{key:"updatedAt",type:"date"},{key:"publishedAt",type:"date"},{key:"createdBy",type:"text"},{key:"updatedBy",type:"text"}];function dce({column:t,index:e,columnsLength:n,onUpdateColumn:r,onRemoveColumn:s}){const{attributes:i,listeners:l,setNodeRef:u,transform:p,transition:f,isDragging:m}=eb({id:t.field}),g={transform:sa.Transform.toString(p),transition:f,opacity:m?.5:1};return a.jsxs(B,{ref:u,style:g,sx:{display:"flex",alignItems:"center",gap:1,p:1,borderBottom:1,borderColor:"divider",bgcolor:"background.paper","&:last-child":{borderBottom:0}},children:[a.jsx(B,{sx:{display:"flex",alignItems:"center",justifyContent:"center",width:32,height:32,cursor:"grab",touchAction:"none","&:active":{cursor:"grabbing"}},...i,...l,children:a.jsx(wu,{fontSize:"small",color:"action"})}),a.jsx(Ht,{label:t.field,size:"small",variant:"outlined",sx:{minWidth:80}}),a.jsx(Xe,{size:"small",variant:"standard",value:t.label,onChange:y=>r(e,{label:y.target.value}),placeholder:"ラベル",sx:{flex:1,minWidth:80}}),a.jsx(Xe,{size:"small",variant:"standard",value:t.width??"",onChange:y=>r(e,{width:y.target.value||void 0}),placeholder:"幅",sx:{width:60}}),a.jsx(ft,{size:"small",onClick:()=>s(e),disabled:n<=1,children:a.jsx(zn,{fontSize:"small"})})]})}function pce({column:t}){return a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,p:1,bgcolor:"background.paper",boxShadow:3,borderRadius:1},children:[a.jsx(wu,{fontSize:"small",color:"action"}),a.jsx(Ht,{label:t.field,size:"small",variant:"outlined"}),a.jsx(G,{variant:"body2",children:t.label})]})}function fce({view:t,availableFields:e,open:n,onClose:r,onUpdate:s,onAddColumn:i,onUpdateColumn:l,onRemoveColumn:u,onReorderColumns:p,onAddFilter:f,onUpdateFilter:m,onRemoveFilter:g,onSetDefaultSort:y}){var H;const[v,C]=b.useState(""),[S,j]=b.useState(""),[D,M]=b.useState("eq"),[T,E]=b.useState(""),[k,A]=b.useState(null),O=Lm(Do(Tu,{activationConstraint:{distance:8}}),Do(v5,{activationConstraint:{delay:100,tolerance:8}}),Do(ju,{coordinateGetter:Fm}));if(!t)return null;const I=[...e.map(U=>({key:U.key,type:U.type})),...uce],$=I.filter(U=>!t.columns.some(L=>L.field===U.key)),R=()=>{v&&(i({field:v,label:v,sortable:!0}),C(""))},P=()=>{S&&(f({field:S,operator:D,value:T}),j(""),M("eq"),E(""))},z=U=>{const L=t.columns.find(W=>W.field===U.active.id);A(L??null)},N=U=>{const{active:L,over:W}=U;if(A(null),!W||L.id===W.id)return;const K=t.columns.findIndex(le=>le.field===L.id),Q=t.columns.findIndex(le=>le.field===W.id);K!==-1&&Q!==-1&&p(K,Q)};return a.jsx(Cu,{anchor:"right",open:n,onClose:r,PaperProps:{sx:{width:{xs:"100%",sm:500}}},children:a.jsxs(B,{sx:{height:"100%",display:"flex",flexDirection:"column"},children:[a.jsx(Dp,{title:"ビュー編集",onClose:r,componentName:"cmp:ViewEditorDrawerHeader"}),a.jsxs(B,{sx:{flex:1,overflow:"auto",p:2},children:[a.jsxs(B,{"data-component-name":"cmp:ViewBasicSettings",sx:{mb:3},children:[a.jsx(G,{variant:"subtitle2",gutterBottom:!0,children:"基本設定"}),a.jsx(Xe,{fullWidth:!0,size:"small",label:"ビューID",value:t.id,disabled:!0,sx:{mb:2}}),a.jsx(Xe,{fullWidth:!0,size:"small",label:"ラベル",value:t.label,onChange:U=>s({label:U.target.value})})]}),a.jsx(wo,{sx:{my:2}}),a.jsxs(B,{"data-component-name":"cmp:ViewColumnSettings",sx:{mb:3},children:[a.jsx(G,{variant:"subtitle2",gutterBottom:!0,children:"列設定(ドラッグで並び替え)"}),a.jsx($t,{variant:"outlined",sx:{mb:2},children:a.jsxs($m,{sensors:O,collisionDetection:Kx,onDragStart:z,onDragEnd:N,children:[a.jsx(Nm,{items:t.columns.map(U=>U.field),strategy:V2,children:t.columns.map((U,L)=>a.jsx(dce,{column:U,index:L,columnsLength:t.columns.length,onUpdateColumn:l,onRemoveColumn:u},U.field))}),a.jsx(B2,{children:k?a.jsx(pce,{column:k}):null})]})}),a.jsxs(B,{sx:{display:"flex",gap:1},children:[a.jsxs(_n,{size:"small",sx:{flex:1},children:[a.jsx(nr,{children:"フィールド追加"}),a.jsx(wn,{value:v,label:"フィールド追加",onChange:U=>C(U.target.value),children:$.map(U=>a.jsx(nt,{value:U.key,children:U.key},U.key))})]}),a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Qn,{}),onClick:R,disabled:!v,children:"追加"})]})]}),a.jsx(wo,{sx:{my:2}}),a.jsxs(B,{"data-component-name":"cmp:ViewSortSettings",sx:{mb:3},children:[a.jsx(G,{variant:"subtitle2",gutterBottom:!0,children:"デフォルトソート"}),a.jsxs(B,{sx:{display:"flex",gap:1},children:[a.jsxs(_n,{size:"small",sx:{flex:1},children:[a.jsx(nr,{children:"フィールド"}),a.jsxs(wn,{value:((H=t.defaultSort)==null?void 0:H.field)??"",label:"フィールド",onChange:U=>{var L;U.target.value?y({field:U.target.value,direction:((L=t.defaultSort)==null?void 0:L.direction)??"desc"}):y(void 0)},children:[a.jsx(nt,{value:"",children:"なし"}),t.columns.map(U=>a.jsx(nt,{value:U.field,children:U.label},U.field))]})]}),t.defaultSort&&a.jsxs(_n,{size:"small",sx:{width:120},children:[a.jsx(nr,{children:"方向"}),a.jsxs(wn,{value:t.defaultSort.direction,label:"方向",onChange:U=>y({...t.defaultSort,direction:U.target.value}),children:[a.jsx(nt,{value:"asc",children:"昇順"}),a.jsx(nt,{value:"desc",children:"降順"})]})]})]})]}),a.jsx(wo,{sx:{my:2}}),a.jsxs(B,{"data-component-name":"cmp:ViewFilterSettings",children:[a.jsx(G,{variant:"subtitle2",gutterBottom:!0,children:"フィルター"}),t.filters&&t.filters.length>0&&a.jsx($t,{variant:"outlined",sx:{mb:2},children:t.filters.map((U,L)=>a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,p:1,borderBottom:1,borderColor:"divider","&:last-child":{borderBottom:0}},children:[a.jsx(Ht,{label:U.field,size:"small",variant:"outlined"}),a.jsx(wn,{size:"small",variant:"standard",value:U.operator,onChange:W=>m(L,{operator:W.target.value}),sx:{minWidth:80},children:kA.map(W=>a.jsx(nt,{value:W.value,children:W.label},W.value))}),a.jsx(Xe,{size:"small",variant:"standard",value:String(U.value??""),onChange:W=>m(L,{value:W.target.value}),sx:{flex:1}}),a.jsx(ft,{size:"small",onClick:()=>g(L),children:a.jsx(zn,{fontSize:"small"})})]},L))}),a.jsxs(B,{sx:{display:"flex",gap:1,flexWrap:"wrap"},children:[a.jsxs(_n,{size:"small",sx:{minWidth:120},children:[a.jsx(nr,{children:"フィールド"}),a.jsx(wn,{value:S,label:"フィールド",onChange:U=>j(U.target.value),children:I.map(U=>a.jsx(nt,{value:U.key,children:U.key},U.key))})]}),a.jsxs(_n,{size:"small",sx:{minWidth:100},children:[a.jsx(nr,{children:"演算子"}),a.jsx(wn,{value:D,label:"演算子",onChange:U=>M(U.target.value),children:kA.map(U=>a.jsx(nt,{value:U.value,children:U.label},U.value))})]}),a.jsx(Xe,{size:"small",label:"値",value:T,onChange:U=>E(U.target.value),sx:{width:100}}),a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Qn,{}),onClick:P,disabled:!S,children:"追加"})]})]})]})]})})}function hce({open:t,existingIds:e,onClose:n,onSubmit:r}){const[s,i]=b.useState(""),[l,u]=b.useState(""),p=()=>{i(""),u(""),n()},f=()=>{!s.trim()||!l.trim()||(r({id:s.trim(),label:l.trim()}),p())},m=s.trim()!==""&&!e.includes(s.trim()),g=l.trim()!=="",y=m&&g;return a.jsxs(Qt,{open:t,onClose:p,maxWidth:"xs",fullWidth:!0,children:[a.jsx(Yt,{children:"ビューを追加"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1},children:[a.jsx(Xe,{autoFocus:!0,label:"ビューID",value:s,onChange:v=>i(v.target.value.replace(/[^a-zA-Z0-9_-]/g,"")),placeholder:"例: published, drafts",helperText:e.includes(s.trim())?"このIDは既に使用されています":"英数字、ハイフン、アンダースコアのみ",error:s.trim()!==""&&e.includes(s.trim()),fullWidth:!0}),a.jsx(Xe,{label:"ラベル",value:l,onChange:v=>u(v.target.value),placeholder:"例: 公開済み、下書き一覧",fullWidth:!0})]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:p,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:f,disabled:!y,children:"追加"})]})]})}function mce({open:t,viewLabel:e,onClose:n,onDelete:r}){return a.jsxs(Qt,{open:t,onClose:n,maxWidth:"xs",fullWidth:!0,children:[a.jsx(Yt,{children:"ビューを削除"}),a.jsx(Jt,{children:a.jsxs(Eo,{children:["ビュー「",e,"」を削除しますか?この操作は元に戻せません。"]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:n,children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:r,children:"削除"})]})]})}function gce({useCase:t,editorMode:e,canEdit:n=!0}){const r=t.getState();b.useEffect(()=>{t.prepareJsonForMode(e)},[t,e,r.editingViews.length]);const{contentTypeId:s,editingViews:i,defaultViewId:l,selectedViewId:u,selectedView:p,availableFields:f,isSaving:m,isDirty:g,message:y,addViewDialogOpen:v,deleteViewDialogOpen:C,unsavedGuard:S,jsonViewsText:j,jsonViewsIsDirty:D,tabSwitchDialogOpen:M}=r,T=()=>a.jsxs(B,{"data-component-name":"cmp:JsonViewsEditorContainer",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",maxWidth:"xl",mx:"auto",width:"100%"},children:[a.jsx(rm,{filePath:`frelio-data/admin/content_types/${s}.views.json`,isSaving:m,isDirty:D,onFormat:n?()=>t.formatJson():void 0,onReset:n?()=>t.resetJson():void 0,onSave:n?()=>t.saveFromJson():void 0,readOnly:!n}),a.jsx(B,{"data-component-name":"cmp:JsonViewsEditorWrapper",sx:{flex:1,overflow:"hidden",pb:1},children:a.jsx(nm,{value:j,onChange:n?k=>t.updateJsonViewsText(k):void 0,height:"100%",readOnly:!n})})]}),E=()=>a.jsx(B,{"data-component-name":"cmp:UiEditorContainer",sx:{flex:1,overflow:"auto"},children:a.jsxs(ji,{maxWidth:"md",sx:{py:3},children:[a.jsx(la,{title:"ビュー設定",actions:n&&a.jsx(pe,{variant:"contained",startIcon:m?a.jsx(ut,{size:20,color:"inherit"}):a.jsx(na,{}),onClick:()=>t.save(),disabled:!g||m,children:m?"保存中...":"保存"})}),a.jsx($t,{sx:{p:2,mb:3},children:a.jsxs(_n,{fullWidth:!0,size:"small",disabled:!n,children:[a.jsx(nr,{children:"デフォルトビュー"}),a.jsx(wn,{value:l,label:"デフォルトビュー",onChange:k=>t.setDefaultView(k.target.value),children:i.map(k=>a.jsx(nt,{value:k.id,children:k.label},k.id))})]})}),a.jsx(B,{"data-component-name":"cmp:ViewsList",sx:{display:"flex",flexDirection:"column",gap:2},children:i.map(k=>{const A=k.id===l;return a.jsxs($t,{"data-component-name":"cmp:ViewCard",sx:{p:2,display:"flex",alignItems:"center",gap:2,...A&&{borderLeft:4,borderColor:"primary.main"}},children:[a.jsx(ft,{size:"small",onClick:n?()=>t.setDefaultView(k.id):void 0,color:A?"primary":"default",title:A?"デフォルトビュー":"デフォルトに設定",disabled:!n,children:A?a.jsx(MP,{}):a.jsx(TY,{})}),a.jsxs(B,{sx:{flex:1},children:[a.jsx(G,{variant:"subtitle1",fontWeight:"medium",children:k.label}),a.jsxs(B,{sx:{display:"flex",gap:1,mt:.5,flexWrap:"wrap"},children:[a.jsx(Ht,{label:`ID: ${k.id}`,size:"small",variant:"outlined"}),a.jsx(Ht,{label:`${k.columns.length} 列`,size:"small"}),k.filters&&k.filters.length>0&&a.jsx(Ht,{label:`${k.filters.length} フィルター`,size:"small",color:"info"}),k.defaultSort&&a.jsx(Ht,{label:`ソート: ${k.defaultSort.field} (${k.defaultSort.direction})`,size:"small",color:"secondary"})]})]}),n&&a.jsxs(B,{sx:{display:"flex",gap:1},children:[a.jsx(ft,{size:"small",onClick:()=>t.selectView(k.id),title:"編集",children:a.jsx(Ri,{})}),a.jsx(ft,{size:"small",onClick:()=>{t.selectView(k.id),t.openDeleteViewDialog()},title:"削除",disabled:i.length<=1,children:a.jsx(zn,{})})]})]},k.id)})}),n&&a.jsx(B,{sx:{display:"flex",justifyContent:"center",mt:3},children:a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddViewDialog(),children:"ビューを追加"})})]})});return a.jsxs(B,{"data-component-name":"cmp:ViewsEditor",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e==="ui"&&E(),e==="json"&&T(),a.jsx(fce,{view:p,availableFields:f,open:u!==null&&!C,onClose:()=>t.clearSelection(),onUpdate:k=>t.updateCurrentView(k),onAddColumn:k=>t.addColumn(k),onUpdateColumn:(k,A)=>t.updateColumn(k,A),onRemoveColumn:k=>t.removeColumn(k),onReorderColumns:(k,A)=>t.reorderColumns(k,A),onAddFilter:k=>t.addFilter(k),onUpdateFilter:(k,A)=>t.updateFilter(k,A),onRemoveFilter:k=>t.removeFilter(k),onSetDefaultSort:k=>t.setDefaultSort(k)}),a.jsx(hce,{open:v,existingIds:i.map(k=>k.id),onClose:()=>t.closeAddViewDialog(),onSubmit:k=>t.addView(k)}),a.jsx(mce,{open:C,viewLabel:(p==null?void 0:p.label)??"",onClose:()=>t.closeDeleteViewDialog(),onDelete:()=>t.deleteCurrentView()}),a.jsx(sb,{open:(S==null?void 0:S.isBlocked)??!1,onStay:()=>S==null?void 0:S.reset(),onLeave:()=>S==null?void 0:S.proceed()}),a.jsx(nb,{open:M,onStay:()=>t.cancelTabSwitch(),onDiscard:()=>t.discardAndSwitchTab(),onSaveAndSwitch:()=>t.saveAndSwitchTab()}),a.jsx(ea,{open:y!==null,autoHideDuration:4e3,onClose:()=>t.clearMessage(),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{severity:(y==null?void 0:y.type)??"info",onClose:()=>t.clearMessage(),children:y==null?void 0:y.text})})]})}class Bf{constructor(e,n,r,s,i,l,u){this.viewsQuery=e,this.contentTypeQuery=n,this.contentTypeUiQuery=r,this.saveMutation=s,this.queryClient=i,this.branch=l,this.contentTypeId=u}static ViewsQueryParams(e,n,r){return{queryKey:["contentTypeViews",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");const i=await new At(e).fetchFileOrNull(sc(n),r);return i?JSON.parse(i):null},enabled:!!e&&!!n}}static ContentTypeQueryParams(e,n,r){return{queryKey:["contentType",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");const i=await new At(e).fetchFileOrNull(Kl(n),r);return i?JSON.parse(i):null},enabled:!!e&&!!n}}static ContentTypeUiQueryParams(e,n,r){return{queryKey:["contentTypeUi",n,r],queryFn:async()=>{if(!e)throw new Error("Not authenticated");const i=await new At(e).fetchFileOrNull(Ld(n),r);return i?JSON.parse(i):null},enabled:!!e&&!!n}}static SaveViewsMutationParams(e,n,r,s){return{mutationFn:async i=>{if(!n)throw new Error("Not authenticated");await new At(n).commitFiles(`ビュー更新: ${s}`,[{path:sc(s),content:JSON.stringify(i.contentTypeViews,null,2)}],r)},onSuccess:()=>{e.invalidateQueries({queryKey:["contentTypeViews",s,r]})}}}getContentTypeViews(){return this.viewsQuery.data??void 0}getContentType(){return this.contentTypeQuery.data??void 0}getContentTypeUi(){return this.contentTypeUiQuery.data??void 0}isLoading(){return this.viewsQuery.isLoading||this.contentTypeQuery.isLoading||this.contentTypeUiQuery.isLoading}getError(){return this.viewsQuery.error??this.contentTypeQuery.error??this.contentTypeUiQuery.error??null}async saveViews(e){await this.saveMutation.mutateAsync(e)}isSaving(){return this.saveMutation.isPending}invalidateQueries(){this.queryClient.invalidateQueries({queryKey:["contentTypeViews",this.contentTypeId,this.branch]})}}const MA={editingViews:[],defaultViewId:"",selectedViewId:null,addViewDialogOpen:!1,deleteViewDialogOpen:!1,message:null,isDirty:!1,editorMode:"ui",jsonViewsText:"",jsonViewsIsDirty:!1,tabSwitchDialogOpen:!1,pendingTabSwitch:null};function yce(){return Fs((t,e)=>({...MA,setEditingViews:n=>t({editingViews:n}),setDefaultViewId:n=>t({defaultViewId:n,isDirty:!0}),addView:n=>{const r=e().editingViews;t({editingViews:[...r,n],selectedViewId:n.id,isDirty:!0})},updateView:(n,r)=>{const i=e().editingViews.map(l=>l.id===n?{...l,...r}:l);t({editingViews:i,isDirty:!0})},removeView:n=>{const r=e().editingViews,s=e().defaultViewId,i=r.filter(p=>p.id!==n),l=e().selectedViewId;let u=s;s===n&&i.length>0&&(u=i[0].id),t({editingViews:i,defaultViewId:u,selectedViewId:l===n?null:l,isDirty:!0})},reorderViews:(n,r)=>{const s=e().editingViews;if(n<0||n>=s.length||r<0||r>=s.length)return;const i=[...s],[l]=i.splice(n,1);i.splice(r,0,l),t({editingViews:i,isDirty:!0})},setSelectedViewId:n=>t({selectedViewId:n}),setAddViewDialogOpen:n=>t({addViewDialogOpen:n}),setDeleteViewDialogOpen:n=>t({deleteViewDialogOpen:n}),setMessage:n=>t({message:n}),setDirty:n=>t({isDirty:n}),setEditorMode:n=>t({editorMode:n}),setJsonViewsText:n=>t({jsonViewsText:n}),setJsonViewsIsDirty:n=>t({jsonViewsIsDirty:n}),setTabSwitchDialogOpen:n=>t({tabSwitchDialogOpen:n}),setPendingTabSwitch:n=>t({pendingTabSwitch:n}),reset:()=>t(MA)}))}class vce{constructor(e){this.store=e}getState(){const e=this.store.getState();return{editingViews:e.editingViews,defaultViewId:e.defaultViewId,selectedViewId:e.selectedViewId,addViewDialogOpen:e.addViewDialogOpen,deleteViewDialogOpen:e.deleteViewDialogOpen,message:e.message,isDirty:e.isDirty,editorMode:e.editorMode,jsonViewsText:e.jsonViewsText,jsonViewsIsDirty:e.jsonViewsIsDirty,tabSwitchDialogOpen:e.tabSwitchDialogOpen,pendingTabSwitch:e.pendingTabSwitch}}setEditingViews(e){this.store.getState().setEditingViews(e)}setDefaultViewId(e){this.store.getState().setDefaultViewId(e)}addView(e){this.store.getState().addView(e)}updateView(e,n){this.store.getState().updateView(e,n)}removeView(e){this.store.getState().removeView(e)}reorderViews(e,n){this.store.getState().reorderViews(e,n)}setSelectedViewId(e){this.store.getState().setSelectedViewId(e)}openAddViewDialog(){this.store.getState().setAddViewDialogOpen(!0)}closeAddViewDialog(){this.store.getState().setAddViewDialogOpen(!1)}openDeleteViewDialog(){this.store.getState().setDeleteViewDialogOpen(!0)}closeDeleteViewDialog(){this.store.getState().setDeleteViewDialogOpen(!1)}setMessage(e){this.store.getState().setMessage(e)}clearMessage(){this.store.getState().setMessage(null)}setDirty(e){this.store.getState().setDirty(e)}setEditorMode(e){this.store.getState().setEditorMode(e)}setJsonViewsText(e){this.store.getState().setJsonViewsText(e)}setJsonViewsIsDirty(e){this.store.getState().setJsonViewsIsDirty(e)}openTabSwitchDialog(e){this.store.getState().setPendingTabSwitch(e),this.store.getState().setTabSwitchDialogOpen(!0)}closeTabSwitchDialog(){this.store.getState().setTabSwitchDialogOpen(!1),this.store.getState().setPendingTabSwitch(null)}reset(){this.store.getState().reset()}subscribe(e){return this.store.subscribe(e)}}const xce=yce(),fo=new vce(xce);class bce{constructor(e,n,r,s){this.repo=e,this.presenter=n,this.contentTypeId=r,this.unsavedGuard=s}getState(){const e=this.presenter.getState(),n=e.selectedViewId!==null?e.editingViews.find(l=>l.id===e.selectedViewId)??null:null,r=this.repo.getContentType(),s=this.repo.getContentTypeUi(),i=(r==null?void 0:r.fields)??[];return{contentTypeId:this.contentTypeId,editingLabel:(s==null?void 0:s.label)??this.contentTypeId,editingViews:e.editingViews,defaultViewId:e.defaultViewId,originalViews:this.repo.getContentTypeViews(),availableFields:i,selectedViewId:e.selectedViewId,selectedView:n,isLoading:this.repo.isLoading(),isSaving:this.repo.isSaving(),isDirty:e.isDirty,error:this.repo.getError(),message:e.message,addViewDialogOpen:e.addViewDialogOpen,deleteViewDialogOpen:e.deleteViewDialogOpen,unsavedGuard:this.unsavedGuard??null,editorMode:e.editorMode,jsonViewsText:e.jsonViewsText,jsonViewsIsDirty:e.jsonViewsIsDirty,tabSwitchDialogOpen:e.tabSwitchDialogOpen,pendingTabSwitch:e.pendingTabSwitch}}initializeFromData(e){this.presenter.setEditingViews(e.views),this.presenter.setDefaultViewId(e.defaultViewId),this.presenter.setDirty(!1),oe.info("ViewDefinitionEditorUseCase.initializeFromData",{contentTypeId:this.contentTypeId,viewCount:e.views.length})}selectView(e){this.presenter.setSelectedViewId(e)}clearSelection(){this.presenter.setSelectedViewId(null)}addView(e){const n={id:e.id,label:e.label,columns:[{field:"title",label:"タイトル",width:"50%",sortable:!0},{field:"status",label:"ステータス",sortable:!0},{field:"updatedAt",label:"更新日時",sortable:!0}]};this.presenter.addView(n),this.presenter.closeAddViewDialog(),oe.info("ViewDefinitionEditorUseCase.addView",{id:e.id,label:e.label})}updateCurrentView(e){const{selectedViewId:n}=this.presenter.getState();n!==null&&this.presenter.updateView(n,e)}updateViewLabel(e,n){this.presenter.updateView(e,{label:n})}deleteCurrentView(){const{selectedViewId:e,editingViews:n}=this.presenter.getState();if(e!==null){if(n.length<=1){this.presenter.setMessage({type:"error",text:"少なくとも1つのビューが必要です"});return}this.presenter.removeView(e),this.presenter.closeDeleteViewDialog(),oe.info("ViewDefinitionEditorUseCase.deleteCurrentView",{viewId:e})}}setDefaultView(e){this.presenter.setDefaultViewId(e),oe.info("ViewDefinitionEditorUseCase.setDefaultView",{viewId:e})}addColumn(e){const{selectedViewId:n,editingViews:r}=this.presenter.getState();if(n===null)return;const s=r.find(l=>l.id===n);if(!s)return;const i=[...s.columns,e];this.presenter.updateView(n,{columns:i})}updateColumn(e,n){const{selectedViewId:r,editingViews:s}=this.presenter.getState();if(r===null)return;const i=s.find(u=>u.id===r);if(!i)return;const l=i.columns.map((u,p)=>p===e?{...u,...n}:u);this.presenter.updateView(r,{columns:l})}removeColumn(e){const{selectedViewId:n,editingViews:r}=this.presenter.getState();if(n===null)return;const s=r.find(l=>l.id===n);if(!s)return;const i=s.columns.filter((l,u)=>u!==e);this.presenter.updateView(n,{columns:i})}reorderColumns(e,n){const{selectedViewId:r,editingViews:s}=this.presenter.getState();if(r===null)return;const i=s.find(p=>p.id===r);if(!i)return;const l=[...i.columns],[u]=l.splice(e,1);l.splice(n,0,u),this.presenter.updateView(r,{columns:l})}addFilter(e){const{selectedViewId:n,editingViews:r}=this.presenter.getState();if(n===null)return;const s=r.find(l=>l.id===n);if(!s)return;const i=[...s.filters??[],e];this.presenter.updateView(n,{filters:i})}updateFilter(e,n){const{selectedViewId:r,editingViews:s}=this.presenter.getState();if(r===null)return;const i=s.find(u=>u.id===r);if(!i||!i.filters)return;const l=i.filters.map((u,p)=>p===e?{...u,...n}:u);this.presenter.updateView(r,{filters:l})}removeFilter(e){const{selectedViewId:n,editingViews:r}=this.presenter.getState();if(n===null)return;const s=r.find(l=>l.id===n);if(!s||!s.filters)return;const i=s.filters.filter((l,u)=>u!==e);this.presenter.updateView(n,{filters:i.length>0?i:void 0})}setDefaultSort(e){const{selectedViewId:n}=this.presenter.getState();n!==null&&this.presenter.updateView(n,{defaultSort:e})}openAddViewDialog(){this.presenter.openAddViewDialog()}closeAddViewDialog(){this.presenter.closeAddViewDialog()}openDeleteViewDialog(){this.presenter.openDeleteViewDialog()}closeDeleteViewDialog(){this.presenter.closeDeleteViewDialog()}clearMessage(){this.presenter.clearMessage()}requestTabSwitch(e){const{editorMode:n,jsonViewsIsDirty:r,isDirty:s}=this.presenter.getState();if(n===e)return;let i=!1;n==="ui"?i=s:i=r,i?this.presenter.openTabSwitchDialog(e):this.switchTab(e)}switchTab(e){const{editorMode:n,editingViews:r,defaultViewId:s}=this.presenter.getState();if(e==="json"&&n==="ui"){const i=this.extractViews(r,s),l=JSON.stringify(i,null,2);this.presenter.setJsonViewsText(l),this.presenter.setJsonViewsIsDirty(!1)}if(e==="ui"&&n==="json"){const{jsonViewsText:i}=this.presenter.getState(),l=Na(i);if(!l.success){this.presenter.setMessage({type:"error",text:`JSONの構文エラー: ${l.error}`});return}this.applyJsonToUiState(l.data)}this.presenter.setEditorMode(e),this.presenter.closeTabSwitchDialog()}discardAndSwitchTab(){const{pendingTabSwitch:e,editorMode:n}=this.presenter.getState();e&&(n==="json"&&this.presenter.setJsonViewsIsDirty(!1),this.switchTab(e))}async saveAndSwitchTab(){const{pendingTabSwitch:e,editorMode:n}=this.presenter.getState();if(e){if(n==="json"){if(!await this.saveFromJson())return}else await this.save();this.switchTab(e)}}cancelTabSwitch(){this.presenter.closeTabSwitchDialog()}updateJsonViewsText(e){this.presenter.setJsonViewsText(e),this.presenter.setJsonViewsIsDirty(!0)}applyJsonToUiState(e){this.presenter.setEditingViews(e.views),this.presenter.setDefaultViewId(e.defaultViewId),this.presenter.setDirty(!0),this.presenter.setJsonViewsIsDirty(!1),oe.info("ViewDefinitionEditorUseCase.applyJsonToUiState",{viewCount:e.views.length})}async saveFromJson(){var s;const{jsonViewsText:e}=this.presenter.getState(),n=Na(e);if(!n.success)return this.presenter.setMessage({type:"error",text:`JSONの構文エラー: ${n.error}`}),!1;const r=Yoe(n.data);if(!r.success)return this.presenter.setMessage({type:"error",text:`バリデーションエラー:
504
- ${iw(r.errors)}`}),!1;try{return await this.repo.saveViews({contentTypeViews:r.data}),this.presenter.setJsonViewsIsDirty(!1),this.presenter.setDirty(!1),(s=this.unsavedGuard)==null||s.setJustSaved(),this.presenter.setMessage({type:"success",text:"ビュー設定を保存しました"}),oe.info("ViewDefinitionEditorUseCase.saveFromJson",{contentTypeId:this.contentTypeId}),!0}catch(i){const l=i instanceof Error?i.message:String(i);return this.presenter.setMessage({type:"error",text:`保存に失敗しました: ${l}`}),oe.error("ViewDefinitionEditorUseCase.saveFromJson failed",{error:i}),!1}}formatJson(){const{jsonViewsText:e}=this.presenter.getState();try{const n=JSON.parse(e),r=JSON.stringify(n,null,2);this.presenter.setJsonViewsText(r)}catch{this.presenter.setMessage({type:"error",text:"JSONのフォーマットに失敗しました(構文エラー)"})}}resetJson(){const{editingViews:e,defaultViewId:n}=this.presenter.getState(),r=this.extractViews(e,n),s=JSON.stringify(r,null,2);this.presenter.setJsonViewsText(s),this.presenter.setJsonViewsIsDirty(!1),this.presenter.setMessage({type:"info",text:"JSONをUI状態から再生成しました"})}prepareJsonForMode(e){const{editingViews:n,defaultViewId:r,jsonViewsText:s}=this.presenter.getState(),i=n.length>0;if(e==="json"&&!s&&i){const l=this.extractViews(n,r),u=JSON.stringify(l,null,2);this.presenter.setJsonViewsText(u),this.presenter.setJsonViewsIsDirty(!1)}this.presenter.setEditorMode(e)}async save(){var s;const{editingViews:e,defaultViewId:n}=this.presenter.getState(),r=this.extractViews(e,n);try{await this.repo.saveViews({contentTypeViews:r}),this.presenter.setDirty(!1),(s=this.unsavedGuard)==null||s.setJustSaved(),this.presenter.setMessage({type:"success",text:"ビュー設定を保存しました"}),oe.info("ViewDefinitionEditorUseCase.save",{contentTypeId:this.contentTypeId})}catch(i){const l=i instanceof Error?i.message:String(i);this.presenter.setMessage({type:"error",text:`保存に失敗しました: ${l}`}),oe.error("ViewDefinitionEditorUseCase.save failed",{error:i})}}extractViews(e,n){return{defaultViewId:n,views:e.map(r=>({id:r.id,label:r.label,columns:r.columns,...r.defaultSort&&{defaultSort:r.defaultSort},...r.filters&&r.filters.length>0&&{filters:r.filters}}))}}reset(){this.presenter.reset()}}function Sce(){const{authUseCase:t}=rr(),{branchUseCase:e}=Ei(),{token:n}=t.getState(),r=(e==null?void 0:e.getCurrentBranch())??"develop",s=ys(),l=uc({strict:!1}).contentTypeId??"";b.useSyncExternalStore(fo.subscribe.bind(fo),()=>JSON.stringify(fo.getState()));const u=jn(Bf.ViewsQueryParams(n,l,r)),p=jn(Bf.ContentTypeQueryParams(n,l,r)),f=jn(Bf.ContentTypeUiQueryParams(n,l,r)),m=Pn(Bf.SaveViewsMutationParams(s,n,r,l)),g=new Bf(u,p,f,m,s,r,l),y=fo.getState().isDirty,v=Um({isDirty:y}),C=new bce(g,fo,l,v),S=b.useRef(null),j=u.data;b.useEffect(()=>{S.current!==l&&j&&(S.current!==null&&S.current!==l&&fo.reset(),fo.setEditingViews(j.views),fo.setDefaultViewId(j.defaultViewId),fo.setDirty(!1),S.current=l)},[j,l]);const D=b.useRef(r);return b.useEffect(()=>{D.current!==r&&(S.current=null,fo.reset(),D.current=r)},[r]),b.useEffect(()=>()=>{fo.reset(),S.current=null},[]),{viewDefinitionEditorUseCase:C}}const Cce=["ui","json"],wce=Ss("/content-types/$contentTypeId/views")({component:Tce,validateSearch:t=>({mode:Cce.includes(t.mode)?t.mode:void 0})}),jce=[{label:"UI編集",value:"ui"},{label:"JSON",value:"json"}];function Tce(){const t=ur(),e=Di({from:"/content-types/$contentTypeId/views"}),n=e.mode??"ui",{authUseCase:r}=rr(),{currentUser:s}=r.getState(),i=ws(s,"canViewContentType"),l=ws(s,"canEditContentType"),{viewDefinitionEditorUseCase:u}=Sce(),{isLoading:p,error:f,contentTypeId:m,editingLabel:g}=u.getState();if(b.useEffect(()=>{s&&!i&&t({to:"/"})},[s,i,t]),!i)return null;if(p)return a.jsx(B,{"data-component-name":"cmp:ViewsEditPage",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(ut,{})});if(f)return a.jsx(B,{"data-component-name":"cmp:ViewsEditPage",sx:{flex:1,overflow:"auto",p:3},children:a.jsxs(zt,{severity:"error",children:["エラー: ",f.message]})});const v={value:n,options:jce,onChange:C=>{t({to:".",search:{...e,mode:C==="ui"?void 0:C},replace:!0})}};return a.jsxs(B,{"data-component-name":"cmp:ViewsEditPage",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[a.jsx(B,{sx:{px:3,pt:2,flexShrink:0},children:a.jsx(no,{items:[{label:"コンテンツタイプ編集",to:"/content-types"},{label:g||m,to:`/content-types/${m}/edit`},{label:"ビュー編集"}],dropdown:v})}),a.jsx(gce,{useCase:u,editorMode:n,canEdit:l})]})}const Dce={bg:"#F5F5F5",border:"#9E9E9E"};function Ece(t){return Dce}function Rce(t,e){const n=new Map(t.map(u=>[u.key,u])),r=new Set,s=[],i=new Set(e.flatMap(u=>u.fieldKeys)),l=t.filter(u=>!i.has(u.key));if(l.length>0){s.push({id:null,label:null,fields:l,color:null});for(const u of l)r.add(u.key)}for(const u of e){const p=[];for(const f of u.fieldKeys){const m=n.get(f);m&&!r.has(f)&&(p.push(m),r.add(f))}s.push({id:u.id,label:u.label,fields:p,color:Ece(u.id)})}return s}function O1(t,e){for(const n of e)if(n.fieldKeys.includes(t))return n.id;return null}const kce={text:T2,html:S2,markdown:km,number:dY,boolean:OY,date:yP,image:jP,file:gP,select:DP,relation:j2,array:OJ,label:ch};function Ru(t){return kce[t]??T2}const Mp={text:"テキスト",html:"HTML",markdown:"Markdown",number:"数値",boolean:"真偽値",date:"日付",image:"画像",file:"ファイル",select:"セレクト",relation:"リレーション",array:"配列",label:"ラベル"},ab=["text","html","markdown","number","boolean","date","image","file","select","relation","array","label"],Ny=[3,4,6,8,12];function D4({field:t,onEdit:e,onDelete:n,onToggleBreak:r,onChangeColumns:s}){const{attributes:i,listeners:l,setNodeRef:u,isDragging:p}=eb({id:t.key}),f={},m=Ru(t.type),g=Ny.indexOf(t.columns),y=g>0,v=g<Ny.length-1,C=j=>{j.stopPropagation(),y&&(s==null||s(Ny[g-1]))},S=j=>{j.stopPropagation(),v&&(s==null||s(Ny[g+1]))};return a.jsxs(Su,{ref:u,style:f,"data-component-name":"cmp:FieldCard",sx:{height:160,display:"flex",flexDirection:"column",opacity:p?.3:1,boxShadow:p?0:1,cursor:"default","&:hover":{boxShadow:p?0:3}},children:[a.jsxs(Sp,{sx:{flex:1,pb:1},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[a.jsx(B,{...i,...l,sx:{display:"flex",alignItems:"center",cursor:"grab",color:"text.disabled","&:active":{cursor:"grabbing"},"&:hover":{color:"text.secondary"}},children:a.jsx(wu,{fontSize:"small"})}),a.jsx(m,{fontSize:"small",color:"action"}),a.jsx(G,{variant:"caption",fontFamily:"monospace",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.key})]}),a.jsx(G,{variant:"subtitle1",fontWeight:600,sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",mb:t.description?0:1,...t.type==="label"&&t.labelColor&&{color:t.labelColor}},children:t.label}),t.description&&a.jsx(G,{variant:"caption",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",mb:1},children:t.description}),a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:.5,flexWrap:"wrap"},children:[a.jsx(Ht,{label:Mp[t.type],size:"small",variant:"outlined",sx:{height:22,fontSize:"0.7rem"}}),t.required&&a.jsx(Ht,{label:"必須",size:"small",color:"error",sx:{height:22,fontSize:"0.7rem"}}),t.multiple&&a.jsx(Ht,{label:"複数",size:"small",color:"info",sx:{height:22,fontSize:"0.7rem"}})]})]}),a.jsxs(s2,{sx:{justifyContent:"space-between",pt:0},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center"},children:[a.jsx(ft,{size:"small",onClick:C,disabled:!y,sx:{p:.25},children:a.jsx(xP,{fontSize:"small"})}),a.jsx(G,{variant:"caption",sx:{minWidth:24,textAlign:"center",fontWeight:600,color:"text.secondary"},children:t.columns}),a.jsx(ft,{size:"small",onClick:S,disabled:!v,sx:{p:.25},children:a.jsx(Jl,{fontSize:"small"})})]}),a.jsxs(B,{sx:{display:"flex"},children:[a.jsx(Er,{title:t.break?"改行あり":"改行なし",children:a.jsx(ft,{size:"small",onClick:r,sx:{color:t.break?"primary.main":"text.disabled"},children:a.jsx(JJ,{fontSize:"small"})})}),a.jsx(Er,{title:"編集",children:a.jsx(ft,{size:"small",onClick:e,children:a.jsx(Ri,{fontSize:"small"})})}),a.jsx(Er,{title:"削除",children:a.jsx(ft,{size:"small",onClick:n,color:"error",children:a.jsx(zn,{fontSize:"small"})})})]})]})]})}function Mce({field:t}){const e=Ru(t.type);return a.jsx(Su,{"data-component-name":"cmp:FieldCardOverlay",sx:{width:280,boxShadow:8,cursor:"grabbing"},children:a.jsxs(Sp,{sx:{pb:1},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[a.jsx(B,{sx:{display:"flex",alignItems:"center",color:"text.disabled"},children:a.jsx(wu,{fontSize:"small"})}),a.jsx(e,{fontSize:"small",color:"action"}),a.jsx(G,{variant:"caption",fontFamily:"monospace",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.key})]}),a.jsx(G,{variant:"subtitle1",fontWeight:600,sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",mb:t.description?0:1,...t.type==="label"&&t.labelColor&&{color:t.labelColor}},children:t.label}),t.description&&a.jsx(G,{variant:"caption",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",mb:1},children:t.description}),a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:.5,flexWrap:"wrap"},children:[a.jsx(Ht,{label:Mp[t.type],size:"small",variant:"outlined",sx:{height:22,fontSize:"0.7rem"}}),t.required&&a.jsx(Ht,{label:"必須",size:"small",color:"error",sx:{height:22,fontSize:"0.7rem"}}),t.multiple&&a.jsx(Ht,{label:"複数",size:"small",color:"info",sx:{height:22,fontSize:"0.7rem"}})]})]})})}function Oce({field:t,isNewField:e,onUpdate:n}){return a.jsxs(_s,{defaultExpanded:!0,"data-component-name":"cmp:FieldBasicSettings",children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(G,{fontWeight:500,children:"基本設定"})}),a.jsx(Is,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsx(Xe,{label:"キー",value:t.key,onChange:r=>n({key:r.target.value}),disabled:!e,required:!0,fullWidth:!0,size:"small",helperText:e?"英数字とアンダースコアのみ使用可能":"キーは変更できません",inputProps:{pattern:"^[a-zA-Z][a-zA-Z0-9_]*$",style:{fontFamily:"monospace"}}}),a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"タイプ"}),a.jsx(wn,{value:t.type,label:"タイプ",onChange:r=>{const s=r.target.value,i=Ace(s);n({type:s,options:i,...s!=="text"&&{useAsUrl:!1}})},children:ab.map(r=>{const s=Ru(r);return a.jsx(nt,{value:r,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(s,{fontSize:"small"}),a.jsx("span",{children:Mp[r]})]})},r)})})]}),t.type==="relation"&&a.jsx(_r,{control:a.jsx(es,{checked:t.multiple,onChange:r=>n({multiple:r.target.checked})}),label:"複数値を許可"}),a.jsxs(B,{children:[a.jsx(_r,{control:a.jsx(es,{checked:t.useAsUrl??!1,onChange:r=>n({useAsUrl:r.target.checked}),disabled:t.type!=="text"}),label:"URL として使用(変更不可)"}),t.useAsUrl&&a.jsx(G,{variant:"caption",color:"text.secondary",sx:{ml:4,display:"block"},children:"コンテンツ作成後、このフィールドの値は変更できなくなります。 詳細レシピの出力パスにはこのフィールドのみ指定可能です。"})]})]})})]})}function Ace(t){switch(t){case"select":return{choices:[]};case"relation":return{targetContentType:""};case"array":return{itemType:"text",itemFields:[],minItems:0,maxItems:void 0};default:return}}const _ce=[{value:"",label:"なし"},{value:"trim",label:"トリム(前後の空白削除)"},{value:"lowercase",label:"小文字に変換"},{value:"uppercase",label:"大文字に変換"},{value:"slug",label:"スラッグ形式"},{value:"phone",label:"電話番号形式"},{value:"postalCode",label:"郵便番号形式"}];function Ice({field:t,onUpdate:e}){return a.jsxs(_s,{defaultExpanded:!0,"data-component-name":"cmp:FieldUiSettings",children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(G,{fontWeight:500,children:"UI設定"})}),a.jsx(Is,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsx(Xe,{label:"ラベル",value:t.label,onChange:n=>e({label:n.target.value}),required:!0,fullWidth:!0,size:"small"}),a.jsxs(B,{sx:{display:"flex",gap:3},children:[a.jsx(_r,{control:a.jsx(es,{checked:t.required,onChange:n=>e({required:n.target.checked}),size:"small"}),label:"必須"}),a.jsx(_r,{control:a.jsx(es,{checked:t.readOnly,onChange:n=>e({readOnly:n.target.checked}),size:"small"}),label:"読み取り専用"}),a.jsx(_r,{control:a.jsx(es,{checked:t.hidden,onChange:n=>e({hidden:n.target.checked}),size:"small"}),label:"非表示"})]}),a.jsx(Xe,{label:"プレースホルダー",value:t.placeholder??"",onChange:n=>e({placeholder:n.target.value||null}),fullWidth:!0,size:"small"}),a.jsx(Xe,{label:"説明",value:t.description??"",onChange:n=>e({description:n.target.value||null}),fullWidth:!0,size:"small",multiline:!0,rows:2,helperText:"URLは自動リンク化されます"}),a.jsxs(B,{children:[a.jsxs(G,{variant:"body2",gutterBottom:!0,children:["カラム数: ",t.columns,"/12"]}),a.jsx(QI,{value:t.columns,onChange:(n,r)=>e({columns:r}),min:1,max:12,step:1,marks:[{value:1,label:"1"},{value:6,label:"6"},{value:12,label:"12"}],valueLabelDisplay:"auto"})]}),a.jsx(_r,{control:a.jsx(es,{checked:t.break,onChange:n=>e({break:n.target.checked}),size:"small"}),label:"このフィールドの後で改行"}),a.jsx(Xe,{label:"文字数警告の閾値",type:"number",value:t.warnLength??"",onChange:n=>e({warnLength:n.target.value?parseInt(n.target.value):null}),fullWidth:!0,size:"small",helperText:"この文字数を超えると警告が表示されます",slotProps:{htmlInput:{min:0}}}),a.jsx(Xe,{label:"正規表現パターン",value:t.pattern??"",onChange:n=>e({pattern:n.target.value||null}),fullWidth:!0,size:"small",helperText:"バリデーション用の正規表現(例: ^[a-z]+$)",slotProps:{input:{sx:{fontFamily:"monospace"}}}}),a.jsx(Xe,{label:"パターン不一致時のメッセージ",value:t.patternMessage??"",onChange:n=>e({patternMessage:n.target.value||null}),fullWidth:!0,size:"small",disabled:!t.pattern}),t.type!=="label"&&a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"自動フォーマット"}),a.jsx(wn,{value:t.autoFormat??"",label:"自動フォーマット",onChange:n=>e({autoFormat:n.target.value||null}),children:_ce.map(n=>a.jsx(nt,{value:n.value,children:n.label},n.value))})]}),t.type==="label"&&a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"文字色"}),a.jsxs(wn,{value:t.labelColor??"",label:"文字色",onChange:n=>e({labelColor:n.target.value||null}),children:[a.jsx(nt,{value:"",children:"デフォルト"}),a.jsx(nt,{value:"#1976D2",children:"青"}),a.jsx(nt,{value:"#388E3C",children:"緑"}),a.jsx(nt,{value:"#F57C00",children:"オレンジ"}),a.jsx(nt,{value:"#D32F2F",children:"赤"}),a.jsx(nt,{value:"#7B1FA2",children:"紫"}),a.jsx(nt,{value:"#616161",children:"グレー"})]})]})]})})]})}function Pce({choices:t,onChange:e}){const[n,r]=b.useState(""),[s,i]=b.useState(""),l=Lm(Do(Tu,{activationConstraint:{distance:8}}),Do(ju,{coordinateGetter:Fm})),u=g=>{const{active:y,over:v}=g;if(!v||y.id===v.id)return;const C=t.findIndex(j=>j.value===y.id),S=t.findIndex(j=>j.value===v.id);if(C!==-1&&S!==-1){const j=[...t],[D]=j.splice(C,1);j.splice(S,0,D),e(j)}},p=()=>{!n.trim()||!s.trim()||t.some(g=>g.value===s.trim())||(e([...t,{label:n.trim(),value:s.trim()}]),r(""),i(""))},f=g=>{const y=t.filter((v,C)=>C!==g);e(y)},m=(g,y)=>{const v=[...t];v[g]={...v[g],...y},e(v)};return a.jsxs(B,{"data-component-name":"cmp:ChoicesEditor",children:[a.jsx(G,{variant:"body2",gutterBottom:!0,children:"選択肢"}),t.length===0?a.jsx(G,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"選択肢がありません"}):a.jsx($m,{sensors:l,collisionDetection:Kx,onDragEnd:u,children:a.jsx(Nm,{items:t.map(g=>g.value),strategy:V2,children:a.jsx(as,{disablePadding:!0,sx:{mb:2},children:t.map((g,y)=>a.jsx(Lce,{choice:g,index:y,onUpdate:v=>m(y,v),onDelete:()=>f(y)},g.value))})})}),a.jsxs(B,{sx:{display:"flex",gap:1,alignItems:"flex-start"},children:[a.jsx(Xe,{label:"ラベル",value:n,onChange:g=>r(g.target.value),size:"small",sx:{flex:1}}),a.jsx(Xe,{label:"値",value:s,onChange:g=>i(g.target.value),size:"small",sx:{flex:1},slotProps:{input:{sx:{fontFamily:"monospace"}}}}),a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Qn,{}),onClick:p,disabled:!n.trim()||!s.trim(),sx:{flexShrink:0},children:"追加"})]})]})}function Lce({choice:t,onUpdate:e,onDelete:n}){const{attributes:r,listeners:s,setNodeRef:i,transform:l,transition:u,isDragging:p}=eb({id:t.value}),f={transform:sa.Transform.toString(l),transition:u,opacity:p?.5:1};return a.jsxs(Os,{ref:i,style:f,sx:{px:0,gap:1},secondaryAction:a.jsx(ft,{size:"small",onClick:n,color:"error",children:a.jsx(zn,{fontSize:"small"})}),children:[a.jsx(B,{...r,...s,sx:{display:"flex",alignItems:"center",cursor:"grab",color:"text.secondary","&:active":{cursor:"grabbing"}},children:a.jsx(wu,{fontSize:"small"})}),a.jsx(Xe,{value:t.label,onChange:m=>e({label:m.target.value}),size:"small",sx:{flex:1},placeholder:"ラベル"}),a.jsx(Xe,{value:t.value,onChange:m=>e({value:m.target.value}),size:"small",sx:{flex:1},placeholder:"値",slotProps:{input:{sx:{fontFamily:"monospace"}}}})]})}function zce(t){return{key:t.key,type:t.type,multiple:t.multiple,options:t.options,label:t.key,required:!1,defaultValue:E4(t.type),placeholder:null,description:null,warnLength:null,columns:12,break:!1,hidden:!1,readOnly:!1,pattern:null,patternMessage:null,autoFormat:null}}function $ce(t){return{key:t.key,type:t.type,multiple:t.multiple,...t.options&&{options:t.options}}}function E4(t){switch(t){case"boolean":return!1;case"array":return[];case"image":case"file":case"relation":return null;default:return""}}function Nce({itemFields:t,contentTypeList:e,onChange:n}){var E;const[r,s]=b.useState(()=>t.map(k=>zce(k))),[i,l]=b.useState(null),[u,p]=b.useState(!1),[f,m]=b.useState(null),g=Lm(Do(Tu,{activationConstraint:{distance:8}}),Do(ju,{coordinateGetter:Fm})),y=b.useCallback(k=>{n(k.map($ce))},[n]),v=b.useCallback(k=>{i!==null&&s(A=>{const O=[...A];return O[i]={...O[i],...k},y(O),O})},[i,y]),C=b.useCallback(k=>{s(A=>{const O=[...A];return O[k]={...O[k],break:!O[k].break},y(O),O})},[y]),S=b.useCallback((k,A)=>{s(O=>{const I=[...O];return I[k]={...I[k],columns:A},y(I),I})},[y]),j=b.useCallback((k,A,O,I)=>{const $={key:k,type:A,multiple:I,options:Bce(A),label:O,required:!1,defaultValue:E4(A),placeholder:null,description:null,warnLength:null,columns:12,break:!1,hidden:!1,readOnly:!1,pattern:null,patternMessage:null,autoFormat:null};s(R=>{const P=[...R,$];return y(P),P}),l(r.length),p(!1)},[r.length,y]),D=b.useCallback(k=>{s(A=>{const O=A.filter((I,$)=>$!==k);return y(O),O}),i===k?l(null):i!==null&&i>k&&l(i-1),m(null)},[i,y]),M=b.useCallback(k=>{const{active:A,over:O}=k;if(!O||A.id===O.id)return;const I=r.findIndex(R=>R.key===A.id),$=r.findIndex(R=>R.key===O.id);I!==-1&&$!==-1&&s(R=>{const P=[...R],[z]=P.splice(I,1);return P.splice($,0,z),y(P),i!==null&&(i===I?l($):I<i&&$>=i?l(i-1):I>i&&$<=i&&l(i+1)),P})},[r,i,y]),T=i!==null?r[i]:null;return a.jsxs(B,{"data-component-name":"cmp:ItemFieldsEditor",sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsxs(B,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsxs(G,{variant:"subtitle2",color:"text.secondary",children:["アイテムフィールド (",r.length,")"]}),a.jsx(pe,{size:"small",startIcon:a.jsx(Qn,{}),onClick:()=>p(!0),children:"追加"})]}),r.length===0?a.jsx(B,{sx:{py:4,border:"1px dashed",borderColor:"divider",borderRadius:1,textAlign:"center"},children:a.jsx(G,{color:"text.secondary",variant:"body2",children:"フィールドがありません"})}):a.jsx($m,{sensors:g,collisionDetection:Kx,onDragEnd:M,children:a.jsx(Nm,{items:r.map(k=>k.key),strategy:Xx,children:a.jsx(Qk,{container:!0,spacing:1.5,children:r.map((k,A)=>a.jsx(Qk,{size:{xs:12,sm:6},children:a.jsx(D4,{field:k,onEdit:()=>l(A),onDelete:()=>m(A),onToggleBreak:()=>C(A),onChangeColumns:O=>S(A,O)})},k.key))})})}),a.jsx(R4,{field:T,isNewField:!1,contentTypeList:e,open:i!==null,onClose:()=>l(null),onUpdate:v}),a.jsx(Fce,{open:u,existingKeys:r.map(k=>k.key),onClose:()=>p(!1),onSubmit:j}),a.jsxs(Qt,{open:f!==null,onClose:()=>m(null),children:[a.jsx(Yt,{children:"フィールドを削除"}),a.jsx(Jt,{children:a.jsxs(G,{children:["フィールド「",f!==null?(E=r[f])==null?void 0:E.key:"","」を削除しますか?"]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>m(null),children:"キャンセル"}),a.jsx(pe,{color:"error",variant:"contained",onClick:()=>f!==null&&D(f),children:"削除"})]})]})]})}function Fce({open:t,existingKeys:e,onClose:n,onSubmit:r}){const[s,i]=b.useState(""),[l,u]=b.useState("text"),[p,f]=b.useState(""),[m,g]=b.useState(!1),y=()=>{!s.trim()||!p.trim()||e.includes(s.trim())||(r(s.trim(),l,p.trim(),m),i(""),u("text"),f(""),g(!1))},v=s.trim()&&!e.includes(s.trim()),C=p.trim();return a.jsxs(Qt,{open:t,onClose:n,maxWidth:"sm",fullWidth:!0,children:[a.jsx(Yt,{children:"フィールドを追加"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1},children:[a.jsx(Xe,{label:"キー",value:s,onChange:S=>i(S.target.value),required:!0,fullWidth:!0,size:"small",error:!!s&&!v,helperText:s&&!v?"既に存在するキーです":"英数字とアンダースコアのみ",slotProps:{input:{sx:{fontFamily:"monospace"}}}}),a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"タイプ"}),a.jsx(wn,{value:l,label:"タイプ",onChange:S=>u(S.target.value),children:ab.map(S=>{const j=Ru(S);return a.jsx(nt,{value:S,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(j,{fontSize:"small"}),a.jsx("span",{children:Mp[S]})]})},S)})})]}),a.jsx(Xe,{label:"ラベル",value:p,onChange:S=>f(S.target.value),required:!0,fullWidth:!0,size:"small"}),a.jsx(_r,{control:a.jsx(es,{checked:m,onChange:S=>g(S.target.checked)}),label:"複数値を許可"})]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:n,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:y,disabled:!v||!C,children:"追加"})]})]})}function Bce(t){switch(t){case"select":return{choices:[]};case"relation":return{targetContentType:""};case"array":return{itemType:"text",itemFields:[],minItems:0,maxItems:void 0};default:return}}function Uce({field:t,contentTypeList:e,onUpdate:n}){var p;const[r,s]=b.useState(!1),i=t.options??{itemType:"text",itemFields:[],minItems:0,maxItems:void 0},l=f=>{n({options:{...i,...f}})},u=f=>{l({itemFields:f})};return a.jsxs(B,{"data-component-name":"cmp:ArrayFieldOptions",sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"アイテムタイプ"}),a.jsx(wn,{value:i.itemType??"text",label:"アイテムタイプ",onChange:f=>l({itemType:f.target.value}),children:ab.map(f=>{const m=Ru(f);return a.jsx(nt,{value:f,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(m,{fontSize:"small"}),a.jsx("span",{children:Mp[f]})]})},f)})})]}),a.jsxs(B,{sx:{display:"flex",gap:2},children:[a.jsx(Xe,{label:"最小件数",type:"number",value:i.minItems??0,onChange:f=>l({minItems:f.target.value?parseInt(f.target.value):0}),size:"small",fullWidth:!0,slotProps:{htmlInput:{min:0}}}),a.jsx(Xe,{label:"最大件数",type:"number",value:i.maxItems??"",onChange:f=>l({maxItems:f.target.value?parseInt(f.target.value):void 0}),size:"small",fullWidth:!0,placeholder:"無制限",slotProps:{htmlInput:{min:0}}})]}),a.jsxs(B,{children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[a.jsx(G,{variant:"body2",children:"アイテムフィールド"}),a.jsx(Ht,{label:`${((p=i.itemFields)==null?void 0:p.length)??0} 件`,size:"small",variant:"outlined"})]}),a.jsx(G,{variant:"caption",color:"text.secondary",sx:{display:"block",mb:1},children:"配列内の各アイテムが持つフィールドを定義します(オブジェクト配列の場合)"}),a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Ri,{}),onClick:()=>s(!0),children:"アイテムフィールドを編集"})]}),a.jsxs(Qt,{open:r,onClose:()=>s(!1),maxWidth:"lg",fullWidth:!0,"data-component-name":"cmp:ItemFieldsDialog",children:[a.jsxs(Yt,{children:["アイテムフィールドの編集: ",t.label]}),a.jsx(Jt,{sx:{height:"70vh",display:"flex",flexDirection:"column"},children:a.jsx(Nce,{itemFields:i.itemFields??[],contentTypeList:e,onChange:u})}),a.jsx(rn,{children:a.jsx(pe,{onClick:()=>s(!1),children:"閉じる"})})]})]})}const Vce=[{value:null,label:"指定なし"},{value:"free",label:"自由"},{value:"16:9",label:"16:9"},{value:"4:3",label:"4:3"},{value:"3:2",label:"3:2"},{value:"1:1",label:"1:1"}];function Hce({field:t,contentTypeList:e,onUpdate:n}){if(["text","html","markdown","number","boolean","date","file"].includes(t.type))return null;const s=()=>{var i,l;switch(t.type){case"image":return a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"アスペクト比"}),a.jsx(wn,{value:t.aspectRatio??null,label:"アスペクト比",onChange:u=>{const p=u.target.value;n({aspectRatio:p})},children:Vce.map(u=>a.jsx(nt,{value:u.value??"",children:u.label},u.value??"null"))})]});case"select":return a.jsx(Pce,{choices:((i=t.options)==null?void 0:i.choices)??[],onChange:u=>n({options:{...t.options,choices:u}})});case"relation":return a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"参照先コンテンツタイプ"}),a.jsxs(wn,{value:((l=t.options)==null?void 0:l.targetContentType)??"",label:"参照先コンテンツタイプ",onChange:u=>n({options:{...t.options,targetContentType:u.target.value}}),children:[a.jsx(nt,{value:"",children:a.jsx("em",{children:"選択してください"})}),e.map(u=>a.jsxs(nt,{value:u.id,children:[u.label," (",u.id,")"]},u.id))]})]});case"array":return a.jsx(Uce,{field:t,contentTypeList:e,onUpdate:n});default:return null}};return a.jsxs(_s,{defaultExpanded:!0,"data-component-name":"cmp:FieldTypeOptions",children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(G,{fontWeight:500,children:"タイプ固有オプション"})}),a.jsx(Is,{children:a.jsx(B,{sx:{display:"flex",flexDirection:"column",gap:2},children:s()})})]})}function Wce({field:t,isNewField:e,contentTypeList:n,onUpdate:r}){return a.jsxs(B,{"data-component-name":"cmp:FieldEditorPanelContent",sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsx(Oce,{field:t,isNewField:e,onUpdate:r}),a.jsx(Ice,{field:t,onUpdate:r}),a.jsx(Hce,{field:t,contentTypeList:n,onUpdate:r})]})}function R4({field:t,isNewField:e,contentTypeList:n,open:r,onClose:s,onUpdate:i}){const l=t?Ru(t.type):null;return a.jsxs(Cu,{anchor:"right",open:r,onClose:s,"data-component-name":"cmp:FieldEditorDrawer",PaperProps:{sx:{width:{xs:"100vw",sm:"70vw"},maxWidth:1e3,display:"flex",flexDirection:"column"}},children:[a.jsx(Dp,{title:(t==null?void 0:t.label)||"フィールド編集",icon:l&&a.jsx(l,{color:"action"}),onClose:s,componentName:"cmp:FieldEditorDrawerHeader"}),a.jsx(B,{"data-component-name":"cmp:FieldEditorDrawerContent",sx:{flex:1,overflow:"auto",p:2},children:t&&a.jsx(Wce,{field:t,isNewField:e,contentTypeList:n,onUpdate:i})})]})}function qce(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g,"_").replace(/^_+|_+$/g,"")}function Gce(){return`label-${Math.random().toString(36).substring(2,8)}`}function Zce({open:t,existingKeys:e,onClose:n,onSubmit:r}){const[s,i]=b.useState(""),[l,u]=b.useState(!1),[p,f]=b.useState("text"),[m,g]=b.useState(""),[y,v]=b.useState(!1);b.useEffect(()=>{t&&(i(""),u(!1),f("text"),g(""),v(!1))},[t]);const C=E=>{g(E),!l&&p!=="label"&&i(qce(E))},S=E=>{i(E),u(!0)},j=()=>{T&&r({key:s.trim(),type:p,label:m.trim(),multiple:y})},D=!e.includes(s.trim()),M=p==="label"?/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(s.trim()):/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s.trim()),T=s.trim()&&m.trim()&&D&&M;return a.jsxs(Qt,{open:t,onClose:n,maxWidth:"sm",fullWidth:!0,"data-component-name":"cmp:AddFieldDialog",children:[a.jsx(Yt,{children:"フィールドを追加"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1},children:[a.jsx(Xe,{label:"ラベル",value:m,onChange:E=>C(E.target.value),required:!0,fullWidth:!0,size:"small",autoFocus:!0}),a.jsx(Xe,{label:"キー",value:s,onChange:E=>S(E.target.value),required:!0,fullWidth:!0,size:"small",error:!!s&&(!D||!M),helperText:s&&!D?"既に存在するキーです":s&&!M?"英字で始まり、英数字とアンダースコアのみ使用可能":"ラベルから自動生成されます",slotProps:{input:{sx:{fontFamily:"monospace"}}}}),a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"タイプ"}),a.jsx(wn,{value:p,label:"タイプ",onChange:E=>{const k=E.target.value;f(k),k==="label"&&!l&&i(Gce()),k!=="relation"&&v(!1)},children:ab.map(E=>{const k=Ru(E);return a.jsx(nt,{value:E,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(k,{fontSize:"small"}),a.jsx("span",{children:Mp[E]})]})},E)})})]}),p==="relation"&&a.jsx(_r,{control:a.jsx(es,{checked:y,onChange:E=>v(E.target.checked)}),label:"複数値を許可"})]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:n,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:j,disabled:!T,children:"追加"})]})]})}function Kce({open:t,fieldKey:e,fieldType:n,onClose:r,onDelete:s}){const i=n==="label";return a.jsxs(Qt,{open:t,onClose:r,maxWidth:"xs",fullWidth:!0,"data-component-name":"cmp:DeleteFieldDialog",children:[a.jsx(Yt,{children:i?"ラベルの削除":"フィールドの削除"}),a.jsxs(Jt,{children:[a.jsxs(Eo,{children:[i?"ラベル":"フィールド"," ",a.jsx(G,{component:"span",fontWeight:"bold",fontFamily:"monospace",children:e})," ","を削除しますか?"]}),!i&&a.jsx(Eo,{sx:{mt:1,color:"error.main"},children:"この操作は元に戻せません。既存のコンテンツからもこのフィールドのデータが失われます。"})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:r,children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:s,children:"削除"})]})]})}function Qce({open:t,groupName:e,fieldCount:n,onClose:r,onConfirm:s}){const[i,l]=b.useState(!1);b.useEffect(()=>{t&&l(!1)},[t]);const u=()=>{s(i)};return a.jsxs(Qt,{open:t,onClose:r,maxWidth:"sm",fullWidth:!0,"data-component-name":"cmp:DeleteGroupDialog",children:[a.jsxs(Yt,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(IP,{color:"warning"}),"グループを削除"]}),a.jsxs(Jt,{children:[a.jsxs(G,{gutterBottom:!0,children:["グループ「",a.jsx("strong",{children:e}),"」を削除しますか?"]}),n>0&&a.jsxs(B,{sx:{mt:2,p:2,bgcolor:"grey.100",borderRadius:1},children:[a.jsxs(G,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:["このグループには ",n," 件のフィールドが含まれています。"]}),a.jsx(_r,{control:a.jsx(es,{checked:i,onChange:p=>l(p.target.checked),color:"error"}),label:a.jsx(G,{variant:"body2",color:"error.main",children:"フィールドも一緒に削除する"})}),a.jsx(G,{variant:"caption",color:"text.secondary",display:"block",sx:{mt:1},children:"チェックしない場合、フィールドはグループから外れて未分類になります。"})]}),n===0&&a.jsx(G,{variant:"body2",color:"text.secondary",sx:{mt:1},children:"このグループは空です。"})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:r,children:"キャンセル"}),a.jsx(pe,{onClick:u,color:"error",variant:"contained",children:"削除"})]})]})}function Jce({name:t,color:e,canMoveUp:n,canMoveDown:r,onMoveUp:s,onMoveDown:i,onRename:l,onDelete:u}){const[p,f]=b.useState(!1),[m,g]=b.useState(t),y=b.useRef(null);b.useEffect(()=>{p&&y.current&&(y.current.focus(),y.current.select())},[p]),b.useEffect(()=>{g(t)},[t]);const v=()=>{g(t),f(!0)},C=()=>{const j=m.trim();j&&j!==t&&(l==null||l(j)),f(!1)},S=j=>{j.key==="Enter"?C():j.key==="Escape"&&(g(t),f(!1))};return a.jsxs(B,{"data-component-name":"cmp:GroupHeader",sx:{display:"flex",alignItems:"center",gap:1,mb:1,mt:2,px:1.5,py:.75,bgcolor:e.bg,borderLeft:4,borderColor:e.border,borderRadius:"0 4px 4px 0"},children:[a.jsx(ic,{fontSize:"small",sx:{color:e.border}}),p?a.jsx(Xe,{inputRef:y,value:m,onChange:j=>g(j.target.value),onBlur:C,onKeyDown:S,size:"small",variant:"standard",sx:{flex:1,maxWidth:200,"& .MuiInputBase-input":{fontSize:"0.875rem",fontWeight:600,py:0}}}):a.jsx(Er,{title:"クリックして編集",children:a.jsx(G,{variant:"subtitle2",fontWeight:600,onClick:v,sx:{cursor:"pointer","&:hover":{textDecoration:"underline"}},children:t})}),a.jsxs(B,{sx:{ml:"auto",display:"flex",gap:.5},children:[a.jsx(Er,{title:"上に移動",children:a.jsx("span",{children:a.jsx(ft,{size:"small",disabled:!n,onClick:s,sx:{p:.25},children:a.jsx(TP,{fontSize:"small"})})})}),a.jsx(Er,{title:"下に移動",children:a.jsx("span",{children:a.jsx(ft,{size:"small",disabled:!r,onClick:i,sx:{p:.25},children:a.jsx(w2,{fontSize:"small"})})})}),a.jsx(Er,{title:"グループを削除",children:a.jsx(ft,{size:"small",onClick:u,sx:{p:.25,color:"error.main"},children:a.jsx(zn,{fontSize:"small"})})})]})]})}function Yce({groupId:t,color:e,isOver:n}){const{setNodeRef:r}=T5({id:`empty-group:${t}`});return a.jsx(B,{ref:r,"data-group":t,"data-droppable-group":t,sx:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:80,bgcolor:n?wt((e==null?void 0:e.bg)??"#e3f2fd",.8):wt((e==null?void 0:e.bg)??"#f5f5f5",.4),border:"2px dashed",borderColor:n?"primary.main":(e==null?void 0:e.border)??"divider",borderRadius:1,p:2,transition:"all 0.2s ease"},children:a.jsx(G,{color:n?"primary.main":"text.secondary",variant:"body2",children:n?"ここにドロップしてグループに追加":"フィールドをここにドラッグしてグループに追加"})})}function Xce({useCase:t,editorMode:e,canEdit:n=!0}){const r=t.getState();b.useEffect(()=>{t.prepareJsonForMode(e)},[t,e,r.editingId]);const{contentTypeId:s,editingLabel:i,editingFields:l,editingGroups:u,selectedFieldKey:p,selectedField:f,isSaving:m,isDirty:g,message:y,addFieldDialogOpen:v,deleteFieldDialogOpen:C,contentTypeList:S,unsavedGuard:j,jsonSchemaText:D,jsonUiText:M,jsonSchemaIsDirty:T,jsonUiIsDirty:E,tabSwitchDialogOpen:k}=r,A=Rce(l,u),[O,I]=b.useState(null),[$,R]=b.useState(null),P=O?l.find(be=>be.key===O):null,[z,N]=b.useState(!1),[H,U]=b.useState(""),[L,W]=b.useState(!1),[K,Q]=b.useState(null),le=(be,Ae,Ne)=>{Q({id:be,label:Ae,fieldCount:Ne}),W(!0)},F=()=>{W(!1),Q(null)},J=be=>{K&&t.removeGroup(K.id,be),F()},ie=Lm(Do(Tu,{activationConstraint:{distance:3}}),Do(ju,{coordinateGetter:Fm})),te=be=>{I(be.active.id)},de=be=>{var Ae;R((Ae=be.over)==null?void 0:Ae.id)},fe=be=>{const{active:Ae,over:Ne}=be;if(I(null),R(null),!Ne)return;const Ie=Ae.id,Fe=Ne.id;if(Ie===Fe)return;if(Fe.startsWith("empty-group:")){const tt=Fe.replace("empty-group:",""),Ve=O1(Ie,u);t.moveFieldToGroup(Ie,Ve,tt,0);return}const ct=O1(Fe,u),Me=O1(Ie,u);if(Me!==ct){const tt=A.find(Ve=>Ve.id===ct);if(tt){const Ve=tt.fields.findIndex(it=>it.key===Fe);t.moveFieldToGroup(Ie,Me,ct,Ve)}else t.moveFieldToGroup(Ie,Me,ct)}else if(ct!==null){const tt=A.find(Ve=>Ve.id===ct);if(tt){const Ve=tt.fields.findIndex(Z=>Z.key===Ie),it=tt.fields.findIndex(Z=>Z.key===Fe);Ve!==-1&&it!==-1&&t.reorderFieldInGroup(ct,Ve,it)}}else t.reorderUngroupedFields(Ie,Fe)},Re=be=>{const Ae=be.fields.map(Ne=>Ne.key);if(be.fields.length===0&&be.id!==null){const Ne=$===`empty-group:${be.id}`;return a.jsx(Yce,{groupId:be.id,color:be.color,isOver:Ne})}return a.jsx(Nm,{items:Ae,strategy:Xx,children:a.jsx(B,{"data-group":be.id??"__ungrouped__",sx:{display:"grid",gridTemplateColumns:"repeat(12, 1fr)",gap:2,...be.id&&be.color&&{bgcolor:wt(be.color.bg,.4),p:1.5,borderRadius:1}},children:be.fields.map((Ne,Ie)=>{const Fe=$===Ne.key&&O!==Ne.key,ct=Ie>0?be.fields[Ie-1]:null,Me=(ct==null?void 0:ct.break)===!0;return a.jsxs(B,{"data-field-key":Ne.key,sx:{gridColumnStart:{xs:1,sm:Me?1:"auto"},gridColumnEnd:{xs:"span 12",sm:`span ${Ne.columns}`},position:"relative"},children:[Fe&&a.jsx(B,{sx:{position:"absolute",left:-8,top:0,bottom:0,width:4,bgcolor:"primary.main",borderRadius:1,zIndex:10}}),a.jsx(D4,{field:Ne,onEdit:n?()=>t.selectField(Ne.key):void 0,onDelete:n?()=>{t.selectField(Ne.key),t.openDeleteFieldDialog()}:void 0,onToggleBreak:n?()=>t.toggleFieldBreak(Ne.key):void 0,onChangeColumns:n?tt=>t.changeFieldColumns(Ne.key,tt):void 0})]},Ne.key)})})})},Pe=()=>a.jsxs(B,{"data-component-name":"cmp:JsonSchemaEditorContainer",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",maxWidth:"xl",mx:"auto",width:"100%"},children:[a.jsx(rm,{filePath:`frelio-data/site/content_types/${s}.json`,isSaving:m,isDirty:T,onFormat:n?()=>t.formatJson():void 0,onReset:n?()=>t.resetJson():void 0,onSave:n?()=>t.saveFromJson():void 0,readOnly:!n}),a.jsx(B,{"data-component-name":"cmp:JsonSchemaEditorWrapper",sx:{flex:1,overflow:"hidden",pb:1},children:a.jsx(nm,{value:D,onChange:n?be=>t.updateJsonSchemaText(be):void 0,height:"100%",readOnly:!n})})]}),$e=()=>a.jsxs(B,{"data-component-name":"cmp:JsonUiEditorContainer",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",maxWidth:"xl",mx:"auto",width:"100%"},children:[a.jsx(rm,{filePath:`frelio-data/admin/content_types/${s}.ui.json`,isSaving:m,isDirty:E,onFormat:n?()=>t.formatJson():void 0,onReset:n?()=>t.resetJson():void 0,onSave:n?()=>t.saveFromJson():void 0,readOnly:!n}),a.jsx(B,{"data-component-name":"cmp:JsonUiEditorWrapper",sx:{flex:1,overflow:"hidden",pb:1},children:a.jsx(nm,{value:M,onChange:n?be=>t.updateJsonUiText(be):void 0,height:"100%",readOnly:!n})})]}),we=()=>a.jsx(B,{"data-component-name":"cmp:UiEditorContainer",sx:{flex:1,overflow:"auto"},children:a.jsxs(ji,{maxWidth:"xl",sx:{py:3},children:[a.jsx(la,{title:i||"コンテンツタイプ編集",actions:n&&a.jsx(pe,{variant:"contained",startIcon:m?a.jsx(ut,{size:20,color:"inherit"}):a.jsx(na,{}),onClick:()=>t.save(),disabled:!g||m,children:m?"保存中...":"保存"})}),l.length===0?a.jsxs(B,{"data-component-name":"cmp:EmptyFieldsPlaceholder",sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",py:8,border:"2px dashed",borderColor:"divider",borderRadius:2},children:[a.jsx(G,{color:"text.secondary",gutterBottom:!0,children:"フィールドがありません"}),n&&a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddFieldDialog(),children:"最初のフィールドを追加"})]}):a.jsxs($m,{sensors:ie,collisionDetection:Dne,onDragStart:te,onDragOver:de,onDragEnd:fe,children:[a.jsx(B,{"data-component-name":"cmp:FieldGroups",children:A.map((be,Ae)=>{const Ne=A.filter(ct=>ct.id!==null).length,Ie=be.id===null,Fe=Ne>0;return a.jsxs(B,{"data-component-name":"cmp:FieldGroupSection",sx:{mb:2},children:[be.id&&be.label&&be.color&&a.jsx(Jce,{name:be.label,color:be.color,canMoveUp:n&&Ae>1,canMoveDown:n&&Ae<Ne,onMoveUp:n?()=>t.moveGroupUp(be.id):void 0,onMoveDown:n?()=>t.moveGroupDown(be.id):void 0,onRename:n?ct=>t.renameGroup(be.id,ct):void 0,onDelete:n?()=>le(be.id,be.label,be.fields.length):void 0}),Re(be),n&&Ie&&Fe&&a.jsxs(B,{"data-component-name":"cmp:AddFieldButtons",sx:{display:"flex",justifyContent:"center",gap:1,mt:2,mb:2},children:[a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddFieldDialog(),children:"フィールド追加"}),a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(ch,{}),onClick:()=>t.addLabel(),children:"ラベル追加"})]}),n&&be.id&&a.jsxs(B,{"data-component-name":"cmp:AddFieldToGroupButtons",sx:{display:"flex",flexDirection:"column",alignItems:"center",gap:1,mt:2,py:1},children:[a.jsx(G,{variant:"caption",color:"text.secondary",children:"このグループに"}),a.jsxs(B,{sx:{display:"flex",gap:1},children:[a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddFieldDialogForGroup(be.id),children:"フィールド追加"}),a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(ch,{}),onClick:()=>t.addLabelToGroup(be.id),children:"ラベル追加"})]})]})]},be.id??"__ungrouped__")})}),a.jsx(B2,{children:P?a.jsx(Mce,{field:P}):null})]}),n&&u.length===0&&l.length>0&&a.jsxs(B,{"data-component-name":"cmp:AddFieldButtons",sx:{display:"flex",justifyContent:"center",gap:1,mt:2,mb:4},children:[a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddFieldDialog(),children:"フィールド追加"}),a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(ch,{}),onClick:()=>t.addLabel(),children:"ラベル追加"})]}),n&&a.jsx(B,{"data-component-name":"cmp:AddGroupButton",sx:{display:"flex",justifyContent:"center",py:2},children:a.jsx(pe,{variant:"outlined",startIcon:a.jsx(C2,{}),onClick:()=>N(!0),children:"グループ追加"})})]})});return a.jsxs(B,{"data-component-name":"cmp:ContentTypeEditor",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e==="ui"&&we(),e==="json-schema"&&Pe(),e==="json-ui"&&$e(),a.jsx(R4,{field:f,isNewField:!1,contentTypeList:S,open:p!==null,onClose:()=>t.clearSelection(),onUpdate:be=>t.updateCurrentField(be)}),a.jsx(Zce,{open:v,existingKeys:l.map(be=>be.key),onClose:()=>{t.closeAddFieldDialog(),t.clearPendingGroupId()},onSubmit:be=>{const Ae=t.getPendingGroupId();Ae?(t.addFieldToGroup(be,Ae),t.clearPendingGroupId()):t.addField(be)}}),a.jsx(Kce,{open:C,fieldKey:(f==null?void 0:f.key)??"",fieldType:f==null?void 0:f.type,onClose:()=>t.closeDeleteFieldDialog(),onDelete:()=>t.deleteCurrentField()}),a.jsxs(Qt,{open:z,onClose:()=>{N(!1),U("")},maxWidth:"xs",fullWidth:!0,children:[a.jsx(Yt,{children:"グループを追加"}),a.jsx(Jt,{children:a.jsx(Xe,{autoFocus:!0,margin:"dense",label:"グループ名",fullWidth:!0,value:H,onChange:be=>U(be.target.value),onKeyDown:be=>{be.key==="Enter"&&H.trim()&&(t.addGroup(H.trim()),N(!1),U(""))}})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>{N(!1),U("")},children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:()=>{H.trim()&&(t.addGroup(H.trim()),N(!1),U(""))},disabled:!H.trim(),children:"追加"})]})]}),a.jsx(Qce,{open:L,groupName:(K==null?void 0:K.label)??"",fieldCount:(K==null?void 0:K.fieldCount)??0,onClose:F,onConfirm:J}),a.jsx(sb,{open:(j==null?void 0:j.isBlocked)??!1,onStay:()=>j==null?void 0:j.reset(),onLeave:()=>j==null?void 0:j.proceed()}),a.jsx(nb,{open:k,onStay:()=>t.cancelTabSwitch(),onDiscard:()=>t.discardAndSwitchTab(),onSaveAndSwitch:()=>t.saveAndSwitchTab()}),a.jsx(ea,{open:y!==null,autoHideDuration:4e3,onClose:()=>t.clearMessage(),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{severity:(y==null?void 0:y.type)??"info",onClose:()=>t.clearMessage(),children:y==null?void 0:y.text})})]})}const eue=["ui","json-schema","json-ui"],tue=Ss("/content-types/$contentTypeId/edit")({component:rue,validateSearch:t=>({field:typeof t.field=="string"?t.field:void 0,mode:eue.includes(t.mode)?t.mode:void 0})}),nue=[{label:"UI編集",value:"ui"},{label:"JSON(スキーマ)",value:"json-schema"},{label:"JSON(UI)",value:"json-ui"}];function rue(){const t=ur(),e=Di({from:"/content-types/$contentTypeId/edit"}),n=e.mode??"ui",{authUseCase:r}=rr(),{currentUser:s}=r.getState(),i=ws(s,"canViewContentType"),l=ws(s,"canEditContentType"),{contentTypeEditorUseCase:u}=lie(),{isLoading:p,error:f,editingLabel:m,contentTypeId:g}=u.getState();if(b.useEffect(()=>{s&&!i&&t({to:"/"})},[s,i,t]),!i)return null;if(p)return a.jsx(B,{"data-component-name":"cmp:ContentTypeEditPage",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(ut,{})});if(f)return a.jsx(B,{"data-component-name":"cmp:ContentTypeEditPage",sx:{flex:1,overflow:"auto",p:3},children:a.jsxs(zt,{severity:"error",children:["エラー: ",f.message]})});const v={value:n,options:nue,onChange:C=>{t({to:".",search:{...e,mode:C==="ui"?void 0:C},replace:!0})}};return a.jsxs(B,{"data-component-name":"cmp:ContentTypeEditPage",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[a.jsx(B,{sx:{px:3,pt:2,flexShrink:0},children:a.jsx(no,{items:[{label:"コンテンツタイプ編集",to:"/content-types"},{label:m||g}],dropdown:v})}),a.jsx(Xce,{useCase:u,editorMode:n,canEdit:l})]})}const sue=iX.update({id:"/login",path:"/login",getParentRoute:()=>Bs}),iue=hX.update({id:"/",path:"/",getParentRoute:()=>Bs}),oue=kee.update({id:"/users/",path:"/users/",getParentRoute:()=>Bs}),aue=Gee.update({id:"/templates/",path:"/templates/",getParentRoute:()=>Bs}),lue=Lte.update({id:"/storage/",path:"/storage/",getParentRoute:()=>Bs}),cue=Gte.update({id:"/staging/",path:"/staging/",getParentRoute:()=>Bs}),uue=nne.update({id:"/deploy-history/",path:"/deploy-history/",getParentRoute:()=>Bs}),due=hie.update({id:"/content-types/",path:"/content-types/",getParentRoute:()=>Bs}),pue=nae.update({id:"/build-recipes/",path:"/build-recipes/",getParentRoute:()=>Bs}),fue=uae.update({id:"/auth/callback",path:"/auth/callback",getParentRoute:()=>Bs}),hue=X5.update({id:"/contents/$contentTypeId/",path:"/contents/$contentTypeId/",getParentRoute:()=>Bs}),mue=sce.update({id:"/contents/$contentTypeId/$contentId",path:"/contents/$contentTypeId/$contentId",getParentRoute:()=>Bs}),gue=wce.update({id:"/content-types/$contentTypeId/views",path:"/content-types/$contentTypeId/views",getParentRoute:()=>Bs}),yue=tue.update({id:"/content-types/$contentTypeId/edit",path:"/content-types/$contentTypeId/edit",getParentRoute:()=>Bs}),vue={IndexRoute:iue,LoginRoute:sue,AuthCallbackRoute:fue,BuildRecipesIndexRoute:pue,ContentTypesIndexRoute:due,DeployHistoryIndexRoute:uue,StagingIndexRoute:cue,StorageIndexRoute:lue,TemplatesIndexRoute:aue,UsersIndexRoute:oue,ContentTypesContentTypeIdEditRoute:yue,ContentTypesContentTypeIdViewsRoute:gue,ContentsContentTypeIdContentIdRoute:mue,ContentsContentTypeIdIndexRoute:hue},xue=Bs._addFileChildren(vue)._addFileTypes(),bue=new xN({defaultOptions:{queries:{staleTime:1e3*60*5,retry:1}}}),Sue=W$({routeTree:xue,basepath:"/admin/".replace(/\/$/,"")||"/"});wQ().then(()=>{Kz.createRoot(document.getElementById("root")).render(a.jsx(We.StrictMode,{children:a.jsx(bN,{client:bue,children:a.jsxs(k6,{theme:WK,children:[a.jsx(bH,{}),a.jsx(Z$,{router:Sue})]})})}))});export{Wr as $,aJ as A,gJ as B,xJ as C,yP as D,Ti as E,gP as F,wJ as G,S2 as H,jJ as I,TJ as J,bP as K,C2 as L,km as M,DJ as N,EJ as O,RJ as P,kJ as Q,MJ as R,SP as S,OJ as T,zn as U,Tp as V,AJ as W,wu as X,Ri as Y,_J as Z,IJ as _,lJ as a,Om as a$,CP as a0,PJ as a1,LJ as a2,zJ as a3,$J as a4,NJ as a5,ic as a6,FJ as a7,BJ as a8,UJ as a9,iY as aA,EP as aB,oY as aC,aY as aD,lY as aE,cY as aF,uY as aG,dY as aH,ip as aI,pY as aJ,RP as aK,Mm as aL,fY as aM,hY as aN,Fx as aO,mY as aP,gY as aQ,yY as aR,kC as aS,vY as aT,kP as aU,xY as aV,bY as aW,na as aX,SY as aY,CY as aZ,wY as a_,Nx as aa,VJ as ab,HJ as ac,WJ as ad,wP as ae,qJ as af,GJ as ag,jP as ah,ZJ as ai,KJ as aj,vc as ak,QJ as al,w2 as am,TP as an,JJ as ao,ch as ap,RC as aq,YJ as ar,j2 as as,DP as at,XJ as au,eY as av,tY as aw,nY as ax,rY as ay,sY as az,mP as b,Bx as b0,jY as b1,MP as b2,TY as b3,DY as b4,EY as b5,RY as b6,OP as b7,T2 as b8,kY as b9,MY as ba,OY as bb,AY as bc,_Y as bd,IY as be,PY as bf,AP as bg,_P as bh,LY as bi,zY as bj,IP as bk,$Y as bl,ye as c,Qn as d,cJ as e,uJ as f,dJ as g,zx as h,pJ as i,a as j,fJ as k,x2 as l,hJ as m,mJ as n,yJ as o,b2 as p,vJ as q,b as r,bJ as s,Ph as t,vP as u,xP as v,Jl as w,SJ as x,$x as y,CJ as z};
504
+ ${iw(r.errors)}`}),!1;try{return await this.repo.saveViews({contentTypeViews:r.data}),this.presenter.setJsonViewsIsDirty(!1),this.presenter.setDirty(!1),(s=this.unsavedGuard)==null||s.setJustSaved(),this.presenter.setMessage({type:"success",text:"ビュー設定を保存しました"}),oe.info("ViewDefinitionEditorUseCase.saveFromJson",{contentTypeId:this.contentTypeId}),!0}catch(i){const l=i instanceof Error?i.message:String(i);return this.presenter.setMessage({type:"error",text:`保存に失敗しました: ${l}`}),oe.error("ViewDefinitionEditorUseCase.saveFromJson failed",{error:i}),!1}}formatJson(){const{jsonViewsText:e}=this.presenter.getState();try{const n=JSON.parse(e),r=JSON.stringify(n,null,2);this.presenter.setJsonViewsText(r)}catch{this.presenter.setMessage({type:"error",text:"JSONのフォーマットに失敗しました(構文エラー)"})}}resetJson(){const{editingViews:e,defaultViewId:n}=this.presenter.getState(),r=this.extractViews(e,n),s=JSON.stringify(r,null,2);this.presenter.setJsonViewsText(s),this.presenter.setJsonViewsIsDirty(!1),this.presenter.setMessage({type:"info",text:"JSONをUI状態から再生成しました"})}prepareJsonForMode(e){const{editingViews:n,defaultViewId:r,jsonViewsText:s}=this.presenter.getState(),i=n.length>0;if(e==="json"&&!s&&i){const l=this.extractViews(n,r),u=JSON.stringify(l,null,2);this.presenter.setJsonViewsText(u),this.presenter.setJsonViewsIsDirty(!1)}this.presenter.setEditorMode(e)}async save(){var s;const{editingViews:e,defaultViewId:n}=this.presenter.getState(),r=this.extractViews(e,n);try{await this.repo.saveViews({contentTypeViews:r}),this.presenter.setDirty(!1),(s=this.unsavedGuard)==null||s.setJustSaved(),this.presenter.setMessage({type:"success",text:"ビュー設定を保存しました"}),oe.info("ViewDefinitionEditorUseCase.save",{contentTypeId:this.contentTypeId})}catch(i){const l=i instanceof Error?i.message:String(i);this.presenter.setMessage({type:"error",text:`保存に失敗しました: ${l}`}),oe.error("ViewDefinitionEditorUseCase.save failed",{error:i})}}extractViews(e,n){return{defaultViewId:n,views:e.map(r=>({id:r.id,label:r.label,columns:r.columns,...r.defaultSort&&{defaultSort:r.defaultSort},...r.filters&&r.filters.length>0&&{filters:r.filters}}))}}reset(){this.presenter.reset()}}function Sce(){const{authUseCase:t}=rr(),{branchUseCase:e}=Ei(),{token:n}=t.getState(),r=(e==null?void 0:e.getCurrentBranch())??"develop",s=ys(),l=uc({strict:!1}).contentTypeId??"";b.useSyncExternalStore(fo.subscribe.bind(fo),()=>JSON.stringify(fo.getState()));const u=jn(Bf.ViewsQueryParams(n,l,r)),p=jn(Bf.ContentTypeQueryParams(n,l,r)),f=jn(Bf.ContentTypeUiQueryParams(n,l,r)),m=Pn(Bf.SaveViewsMutationParams(s,n,r,l)),g=new Bf(u,p,f,m,s,r,l),y=fo.getState().isDirty,v=Um({isDirty:y}),C=new bce(g,fo,l,v),S=b.useRef(null),j=u.data;b.useEffect(()=>{S.current!==l&&j&&(S.current!==null&&S.current!==l&&fo.reset(),fo.setEditingViews(j.views),fo.setDefaultViewId(j.defaultViewId),fo.setDirty(!1),S.current=l)},[j,l]);const D=b.useRef(r);return b.useEffect(()=>{D.current!==r&&(S.current=null,fo.reset(),D.current=r)},[r]),b.useEffect(()=>()=>{fo.reset(),S.current=null},[]),{viewDefinitionEditorUseCase:C}}const Cce=["ui","json"],wce=Ss("/content-types/$contentTypeId/views")({component:Tce,validateSearch:t=>({mode:Cce.includes(t.mode)?t.mode:void 0})}),jce=[{label:"UI編集",value:"ui"},{label:"JSON",value:"json"}];function Tce(){const t=ur(),e=Di({from:"/content-types/$contentTypeId/views"}),n=e.mode??"ui",{authUseCase:r}=rr(),{currentUser:s}=r.getState(),i=ws(s,"canViewContentType"),l=ws(s,"canEditContentType"),{viewDefinitionEditorUseCase:u}=Sce(),{isLoading:p,error:f,contentTypeId:m,editingLabel:g}=u.getState();if(b.useEffect(()=>{s&&!i&&t({to:"/"})},[s,i,t]),!i)return null;if(p)return a.jsx(B,{"data-component-name":"cmp:ViewsEditPage",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(ut,{})});if(f)return a.jsx(B,{"data-component-name":"cmp:ViewsEditPage",sx:{flex:1,overflow:"auto",p:3},children:a.jsxs(zt,{severity:"error",children:["エラー: ",f.message]})});const v={value:n,options:jce,onChange:C=>{t({to:".",search:{...e,mode:C==="ui"?void 0:C},replace:!0})}};return a.jsxs(B,{"data-component-name":"cmp:ViewsEditPage",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[a.jsx(B,{sx:{px:3,pt:2,flexShrink:0},children:a.jsx(no,{items:[{label:"コンテンツタイプ編集",to:"/content-types"},{label:g||m,to:`/content-types/${m}/edit`},{label:"ビュー編集"}],dropdown:v})}),a.jsx(gce,{useCase:u,editorMode:n,canEdit:l})]})}const Dce={bg:"#F5F5F5",border:"#9E9E9E"};function Ece(t){return Dce}function Rce(t,e){const n=new Map(t.map(u=>[u.key,u])),r=new Set,s=[],i=new Set(e.flatMap(u=>u.fieldKeys)),l=t.filter(u=>!i.has(u.key));if(l.length>0){s.push({id:null,label:null,fields:l,color:null});for(const u of l)r.add(u.key)}for(const u of e){const p=[];for(const f of u.fieldKeys){const m=n.get(f);m&&!r.has(f)&&(p.push(m),r.add(f))}s.push({id:u.id,label:u.label,fields:p,color:Ece(u.id)})}return s}function O1(t,e){for(const n of e)if(n.fieldKeys.includes(t))return n.id;return null}const kce={text:T2,html:S2,markdown:km,number:dY,boolean:OY,date:yP,image:jP,file:gP,select:DP,relation:j2,array:OJ,label:ch};function Ru(t){return kce[t]??T2}const Mp={text:"テキスト",html:"HTML",markdown:"Markdown",number:"数値",boolean:"真偽値",date:"日付",image:"画像",file:"ファイル",select:"セレクト",relation:"リレーション",array:"配列",label:"ラベル"},ab=["text","html","markdown","number","boolean","date","image","file","select","relation","array","label"],Ny=[3,4,6,8,12];function D4({field:t,onEdit:e,onDelete:n,onToggleBreak:r,onChangeColumns:s}){const{attributes:i,listeners:l,setNodeRef:u,isDragging:p}=eb({id:t.key}),f={},m=Ru(t.type),g=Ny.indexOf(t.columns),y=g>0,v=g<Ny.length-1,C=j=>{j.stopPropagation(),y&&(s==null||s(Ny[g-1]))},S=j=>{j.stopPropagation(),v&&(s==null||s(Ny[g+1]))};return a.jsxs(Su,{ref:u,style:f,"data-component-name":"cmp:FieldCard",sx:{height:160,display:"flex",flexDirection:"column",opacity:p?.3:1,boxShadow:p?0:1,cursor:"default","&:hover":{boxShadow:p?0:3}},children:[a.jsxs(Sp,{sx:{flex:1,pb:1},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[a.jsx(B,{...i,...l,sx:{display:"flex",alignItems:"center",cursor:"grab",color:"text.disabled","&:active":{cursor:"grabbing"},"&:hover":{color:"text.secondary"}},children:a.jsx(wu,{fontSize:"small"})}),a.jsx(m,{fontSize:"small",color:"action"}),a.jsx(G,{variant:"caption",fontFamily:"monospace",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.key})]}),a.jsx(G,{variant:"subtitle1",fontWeight:600,sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",mb:t.description?0:1,...t.type==="label"&&t.labelColor&&{color:t.labelColor}},children:t.label}),t.description&&a.jsx(G,{variant:"caption",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",mb:1},children:t.description}),a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:.5,flexWrap:"wrap"},children:[a.jsx(Ht,{label:Mp[t.type],size:"small",variant:"outlined",sx:{height:22,fontSize:"0.7rem"}}),t.required&&a.jsx(Ht,{label:"必須",size:"small",color:"error",sx:{height:22,fontSize:"0.7rem"}}),t.multiple&&a.jsx(Ht,{label:"複数",size:"small",color:"info",sx:{height:22,fontSize:"0.7rem"}})]})]}),a.jsxs(s2,{sx:{justifyContent:"space-between",pt:0},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center"},children:[a.jsx(ft,{size:"small",onClick:C,disabled:!y,sx:{p:.25},children:a.jsx(xP,{fontSize:"small"})}),a.jsx(G,{variant:"caption",sx:{minWidth:24,textAlign:"center",fontWeight:600,color:"text.secondary"},children:t.columns}),a.jsx(ft,{size:"small",onClick:S,disabled:!v,sx:{p:.25},children:a.jsx(Jl,{fontSize:"small"})})]}),a.jsxs(B,{sx:{display:"flex"},children:[a.jsx(Er,{title:t.break?"改行あり":"改行なし",children:a.jsx(ft,{size:"small",onClick:r,sx:{color:t.break?"primary.main":"text.disabled"},children:a.jsx(JJ,{fontSize:"small"})})}),a.jsx(Er,{title:"編集",children:a.jsx(ft,{size:"small",onClick:e,children:a.jsx(Ri,{fontSize:"small"})})}),a.jsx(Er,{title:"削除",children:a.jsx(ft,{size:"small",onClick:n,color:"error",children:a.jsx(zn,{fontSize:"small"})})})]})]})]})}function Mce({field:t}){const e=Ru(t.type);return a.jsx(Su,{"data-component-name":"cmp:FieldCardOverlay",sx:{width:280,boxShadow:8,cursor:"grabbing"},children:a.jsxs(Sp,{sx:{pb:1},children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[a.jsx(B,{sx:{display:"flex",alignItems:"center",color:"text.disabled"},children:a.jsx(wu,{fontSize:"small"})}),a.jsx(e,{fontSize:"small",color:"action"}),a.jsx(G,{variant:"caption",fontFamily:"monospace",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.key})]}),a.jsx(G,{variant:"subtitle1",fontWeight:600,sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",mb:t.description?0:1,...t.type==="label"&&t.labelColor&&{color:t.labelColor}},children:t.label}),t.description&&a.jsx(G,{variant:"caption",color:"text.secondary",sx:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",display:"block",mb:1},children:t.description}),a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:.5,flexWrap:"wrap"},children:[a.jsx(Ht,{label:Mp[t.type],size:"small",variant:"outlined",sx:{height:22,fontSize:"0.7rem"}}),t.required&&a.jsx(Ht,{label:"必須",size:"small",color:"error",sx:{height:22,fontSize:"0.7rem"}}),t.multiple&&a.jsx(Ht,{label:"複数",size:"small",color:"info",sx:{height:22,fontSize:"0.7rem"}})]})]})})}function Oce({field:t,isNewField:e,onUpdate:n}){return a.jsxs(_s,{defaultExpanded:!0,"data-component-name":"cmp:FieldBasicSettings",children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(G,{fontWeight:500,children:"基本設定"})}),a.jsx(Is,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsx(Xe,{label:"キー",value:t.key,onChange:r=>n({key:r.target.value}),disabled:!e,required:!0,fullWidth:!0,size:"small",helperText:e?"英数字とアンダースコアのみ使用可能":"キーは変更できません",inputProps:{pattern:"^[a-zA-Z][a-zA-Z0-9_]*$",style:{fontFamily:"monospace"}}}),a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"タイプ"}),a.jsx(wn,{value:t.type,label:"タイプ",onChange:r=>{const s=r.target.value,i=Ace(s);n({type:s,options:i,...s!=="text"&&{useAsUrl:!1}})},children:ab.map(r=>{const s=Ru(r);return a.jsx(nt,{value:r,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(s,{fontSize:"small"}),a.jsx("span",{children:Mp[r]})]})},r)})})]}),t.type==="relation"&&a.jsx(_r,{control:a.jsx(es,{checked:t.multiple,onChange:r=>n({multiple:r.target.checked})}),label:"複数値を許可"}),a.jsxs(B,{children:[a.jsx(_r,{control:a.jsx(es,{checked:t.useAsUrl??!1,onChange:r=>n({useAsUrl:r.target.checked}),disabled:t.type!=="text"}),label:"URL として使用(変更不可)"}),t.useAsUrl&&a.jsx(G,{variant:"caption",color:"text.secondary",sx:{ml:4,display:"block"},children:"コンテンツ作成後、このフィールドの値は変更できなくなります。 詳細レシピの出力パスにはこのフィールドのみ指定可能です。"})]})]})})]})}function Ace(t){switch(t){case"select":return{choices:[]};case"relation":return{targetContentType:""};case"array":return{itemType:"text",itemFields:[],minItems:0,maxItems:void 0};default:return}}const _ce=[{value:"",label:"なし"},{value:"trim",label:"トリム(前後の空白削除)"},{value:"lowercase",label:"小文字に変換"},{value:"uppercase",label:"大文字に変換"},{value:"slug",label:"スラッグ形式"},{value:"phone",label:"電話番号形式"},{value:"postalCode",label:"郵便番号形式"}];function Ice({field:t,onUpdate:e}){return a.jsxs(_s,{defaultExpanded:!0,"data-component-name":"cmp:FieldUiSettings",children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(G,{fontWeight:500,children:"UI設定"})}),a.jsx(Is,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsx(Xe,{label:"ラベル",value:t.label,onChange:n=>e({label:n.target.value}),required:!0,fullWidth:!0,size:"small"}),a.jsxs(B,{sx:{display:"flex",gap:3},children:[a.jsx(_r,{control:a.jsx(es,{checked:t.required,onChange:n=>e({required:n.target.checked}),size:"small"}),label:"必須"}),a.jsx(_r,{control:a.jsx(es,{checked:t.readOnly,onChange:n=>e({readOnly:n.target.checked}),size:"small"}),label:"読み取り専用"}),a.jsx(_r,{control:a.jsx(es,{checked:t.hidden,onChange:n=>e({hidden:n.target.checked}),size:"small"}),label:"非表示"})]}),a.jsx(Xe,{label:"プレースホルダー",value:t.placeholder??"",onChange:n=>e({placeholder:n.target.value||null}),fullWidth:!0,size:"small"}),a.jsx(Xe,{label:"説明",value:t.description??"",onChange:n=>e({description:n.target.value||null}),fullWidth:!0,size:"small",multiline:!0,rows:2,helperText:"URLは自動リンク化されます"}),a.jsxs(B,{children:[a.jsxs(G,{variant:"body2",gutterBottom:!0,children:["カラム数: ",t.columns,"/12"]}),a.jsx(QI,{value:t.columns,onChange:(n,r)=>e({columns:r}),min:1,max:12,step:1,marks:[{value:1,label:"1"},{value:6,label:"6"},{value:12,label:"12"}],valueLabelDisplay:"auto"})]}),a.jsx(_r,{control:a.jsx(es,{checked:t.break,onChange:n=>e({break:n.target.checked}),size:"small"}),label:"このフィールドの後で改行"}),a.jsx(Xe,{label:"文字数警告の閾値",type:"number",value:t.warnLength??"",onChange:n=>e({warnLength:n.target.value?parseInt(n.target.value):null}),fullWidth:!0,size:"small",helperText:"この文字数を超えると警告が表示されます",slotProps:{htmlInput:{min:0}}}),a.jsx(Xe,{label:"正規表現パターン",value:t.pattern??"",onChange:n=>e({pattern:n.target.value||null}),fullWidth:!0,size:"small",helperText:"バリデーション用の正規表現(例: ^[a-z]+$)",slotProps:{input:{sx:{fontFamily:"monospace"}}}}),a.jsx(Xe,{label:"パターン不一致時のメッセージ",value:t.patternMessage??"",onChange:n=>e({patternMessage:n.target.value||null}),fullWidth:!0,size:"small",disabled:!t.pattern}),t.type!=="label"&&a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"自動フォーマット"}),a.jsx(wn,{value:t.autoFormat??"",label:"自動フォーマット",onChange:n=>e({autoFormat:n.target.value||null}),children:_ce.map(n=>a.jsx(nt,{value:n.value,children:n.label},n.value))})]}),t.type==="label"&&a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"文字色"}),a.jsxs(wn,{value:t.labelColor??"",label:"文字色",onChange:n=>e({labelColor:n.target.value||null}),children:[a.jsx(nt,{value:"",children:"デフォルト"}),a.jsx(nt,{value:"#1976D2",children:"青"}),a.jsx(nt,{value:"#388E3C",children:"緑"}),a.jsx(nt,{value:"#F57C00",children:"オレンジ"}),a.jsx(nt,{value:"#D32F2F",children:"赤"}),a.jsx(nt,{value:"#7B1FA2",children:"紫"}),a.jsx(nt,{value:"#616161",children:"グレー"})]})]})]})})]})}function Pce({choices:t,onChange:e}){const[n,r]=b.useState(""),[s,i]=b.useState(""),l=Lm(Do(Tu,{activationConstraint:{distance:8}}),Do(ju,{coordinateGetter:Fm})),u=g=>{const{active:y,over:v}=g;if(!v||y.id===v.id)return;const C=t.findIndex(j=>j.value===y.id),S=t.findIndex(j=>j.value===v.id);if(C!==-1&&S!==-1){const j=[...t],[D]=j.splice(C,1);j.splice(S,0,D),e(j)}},p=()=>{!n.trim()||!s.trim()||t.some(g=>g.value===s.trim())||(e([...t,{label:n.trim(),value:s.trim()}]),r(""),i(""))},f=g=>{const y=t.filter((v,C)=>C!==g);e(y)},m=(g,y)=>{const v=[...t];v[g]={...v[g],...y},e(v)};return a.jsxs(B,{"data-component-name":"cmp:ChoicesEditor",children:[a.jsx(G,{variant:"body2",gutterBottom:!0,children:"選択肢"}),t.length===0?a.jsx(G,{variant:"body2",color:"text.secondary",sx:{mb:2},children:"選択肢がありません"}):a.jsx($m,{sensors:l,collisionDetection:Kx,onDragEnd:u,children:a.jsx(Nm,{items:t.map(g=>g.value),strategy:V2,children:a.jsx(as,{disablePadding:!0,sx:{mb:2},children:t.map((g,y)=>a.jsx(Lce,{choice:g,index:y,onUpdate:v=>m(y,v),onDelete:()=>f(y)},g.value))})})}),a.jsxs(B,{sx:{display:"flex",gap:1,alignItems:"flex-start"},children:[a.jsx(Xe,{label:"ラベル",value:n,onChange:g=>r(g.target.value),size:"small",sx:{flex:1}}),a.jsx(Xe,{label:"値",value:s,onChange:g=>i(g.target.value),size:"small",sx:{flex:1},slotProps:{input:{sx:{fontFamily:"monospace"}}}}),a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Qn,{}),onClick:p,disabled:!n.trim()||!s.trim(),sx:{flexShrink:0},children:"追加"})]})]})}function Lce({choice:t,onUpdate:e,onDelete:n}){const{attributes:r,listeners:s,setNodeRef:i,transform:l,transition:u,isDragging:p}=eb({id:t.value}),f={transform:sa.Transform.toString(l),transition:u,opacity:p?.5:1};return a.jsxs(Os,{ref:i,style:f,sx:{px:0,gap:1},secondaryAction:a.jsx(ft,{size:"small",onClick:n,color:"error",children:a.jsx(zn,{fontSize:"small"})}),children:[a.jsx(B,{...r,...s,sx:{display:"flex",alignItems:"center",cursor:"grab",color:"text.secondary","&:active":{cursor:"grabbing"}},children:a.jsx(wu,{fontSize:"small"})}),a.jsx(Xe,{value:t.label,onChange:m=>e({label:m.target.value}),size:"small",sx:{flex:1},placeholder:"ラベル"}),a.jsx(Xe,{value:t.value,onChange:m=>e({value:m.target.value}),size:"small",sx:{flex:1},placeholder:"値",slotProps:{input:{sx:{fontFamily:"monospace"}}}})]})}function zce(t){return{key:t.key,type:t.type,multiple:t.multiple,options:t.options,label:t.key,required:!1,defaultValue:E4(t.type),placeholder:null,description:null,warnLength:null,columns:12,break:!1,hidden:!1,readOnly:!1,pattern:null,patternMessage:null,autoFormat:null}}function $ce(t){return{key:t.key,type:t.type,multiple:t.multiple,...t.options&&{options:t.options}}}function E4(t){switch(t){case"boolean":return!1;case"array":return[];case"image":case"file":case"relation":return null;default:return""}}function Nce({itemFields:t,contentTypeList:e,onChange:n}){var E;const[r,s]=b.useState(()=>t.map(k=>zce(k))),[i,l]=b.useState(null),[u,p]=b.useState(!1),[f,m]=b.useState(null),g=Lm(Do(Tu,{activationConstraint:{distance:8}}),Do(ju,{coordinateGetter:Fm})),y=b.useCallback(k=>{n(k.map($ce))},[n]),v=b.useCallback(k=>{i!==null&&s(A=>{const O=[...A];return O[i]={...O[i],...k},y(O),O})},[i,y]),C=b.useCallback(k=>{s(A=>{const O=[...A];return O[k]={...O[k],break:!O[k].break},y(O),O})},[y]),S=b.useCallback((k,A)=>{s(O=>{const I=[...O];return I[k]={...I[k],columns:A},y(I),I})},[y]),j=b.useCallback((k,A,O,I)=>{const $={key:k,type:A,multiple:I,options:Bce(A),label:O,required:!1,defaultValue:E4(A),placeholder:null,description:null,warnLength:null,columns:12,break:!1,hidden:!1,readOnly:!1,pattern:null,patternMessage:null,autoFormat:null};s(R=>{const P=[...R,$];return y(P),P}),l(r.length),p(!1)},[r.length,y]),D=b.useCallback(k=>{s(A=>{const O=A.filter((I,$)=>$!==k);return y(O),O}),i===k?l(null):i!==null&&i>k&&l(i-1),m(null)},[i,y]),M=b.useCallback(k=>{const{active:A,over:O}=k;if(!O||A.id===O.id)return;const I=r.findIndex(R=>R.key===A.id),$=r.findIndex(R=>R.key===O.id);I!==-1&&$!==-1&&s(R=>{const P=[...R],[z]=P.splice(I,1);return P.splice($,0,z),y(P),i!==null&&(i===I?l($):I<i&&$>=i?l(i-1):I>i&&$<=i&&l(i+1)),P})},[r,i,y]),T=i!==null?r[i]:null;return a.jsxs(B,{"data-component-name":"cmp:ItemFieldsEditor",sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsxs(B,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[a.jsxs(G,{variant:"subtitle2",color:"text.secondary",children:["アイテムフィールド (",r.length,")"]}),a.jsx(pe,{size:"small",startIcon:a.jsx(Qn,{}),onClick:()=>p(!0),children:"追加"})]}),r.length===0?a.jsx(B,{sx:{py:4,border:"1px dashed",borderColor:"divider",borderRadius:1,textAlign:"center"},children:a.jsx(G,{color:"text.secondary",variant:"body2",children:"フィールドがありません"})}):a.jsx($m,{sensors:g,collisionDetection:Kx,onDragEnd:M,children:a.jsx(Nm,{items:r.map(k=>k.key),strategy:Xx,children:a.jsx(Qk,{container:!0,spacing:1.5,children:r.map((k,A)=>a.jsx(Qk,{size:{xs:12,sm:6},children:a.jsx(D4,{field:k,onEdit:()=>l(A),onDelete:()=>m(A),onToggleBreak:()=>C(A),onChangeColumns:O=>S(A,O)})},k.key))})})}),a.jsx(R4,{field:T,isNewField:!1,contentTypeList:e,open:i!==null,onClose:()=>l(null),onUpdate:v}),a.jsx(Fce,{open:u,existingKeys:r.map(k=>k.key),onClose:()=>p(!1),onSubmit:j}),a.jsxs(Qt,{open:f!==null,onClose:()=>m(null),children:[a.jsx(Yt,{children:"フィールドを削除"}),a.jsx(Jt,{children:a.jsxs(G,{children:["フィールド「",f!==null?(E=r[f])==null?void 0:E.key:"","」を削除しますか?"]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>m(null),children:"キャンセル"}),a.jsx(pe,{color:"error",variant:"contained",onClick:()=>f!==null&&D(f),children:"削除"})]})]})]})}function Fce({open:t,existingKeys:e,onClose:n,onSubmit:r}){const[s,i]=b.useState(""),[l,u]=b.useState("text"),[p,f]=b.useState(""),[m,g]=b.useState(!1),y=()=>{!s.trim()||!p.trim()||e.includes(s.trim())||(r(s.trim(),l,p.trim(),m),i(""),u("text"),f(""),g(!1))},v=s.trim()&&!e.includes(s.trim()),C=p.trim();return a.jsxs(Qt,{open:t,onClose:n,maxWidth:"sm",fullWidth:!0,children:[a.jsx(Yt,{children:"フィールドを追加"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1},children:[a.jsx(Xe,{label:"キー",value:s,onChange:S=>i(S.target.value),required:!0,fullWidth:!0,size:"small",error:!!s&&!v,helperText:s&&!v?"既に存在するキーです":"英数字とアンダースコアのみ",slotProps:{input:{sx:{fontFamily:"monospace"}}}}),a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"タイプ"}),a.jsx(wn,{value:l,label:"タイプ",onChange:S=>u(S.target.value),children:ab.map(S=>{const j=Ru(S);return a.jsx(nt,{value:S,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(j,{fontSize:"small"}),a.jsx("span",{children:Mp[S]})]})},S)})})]}),a.jsx(Xe,{label:"ラベル",value:p,onChange:S=>f(S.target.value),required:!0,fullWidth:!0,size:"small"}),a.jsx(_r,{control:a.jsx(es,{checked:m,onChange:S=>g(S.target.checked)}),label:"複数値を許可"})]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:n,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:y,disabled:!v||!C,children:"追加"})]})]})}function Bce(t){switch(t){case"select":return{choices:[]};case"relation":return{targetContentType:""};case"array":return{itemType:"text",itemFields:[],minItems:0,maxItems:void 0};default:return}}function Uce({field:t,contentTypeList:e,onUpdate:n}){var p;const[r,s]=b.useState(!1),i=t.options??{itemType:"text",itemFields:[],minItems:0,maxItems:void 0},l=f=>{n({options:{...i,...f}})},u=f=>{l({itemFields:f})};return a.jsxs(B,{"data-component-name":"cmp:ArrayFieldOptions",sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"アイテムタイプ"}),a.jsx(wn,{value:i.itemType??"text",label:"アイテムタイプ",onChange:f=>l({itemType:f.target.value}),children:ab.map(f=>{const m=Ru(f);return a.jsx(nt,{value:f,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(m,{fontSize:"small"}),a.jsx("span",{children:Mp[f]})]})},f)})})]}),a.jsxs(B,{sx:{display:"flex",gap:2},children:[a.jsx(Xe,{label:"最小件数",type:"number",value:i.minItems??0,onChange:f=>l({minItems:f.target.value?parseInt(f.target.value):0}),size:"small",fullWidth:!0,slotProps:{htmlInput:{min:0}}}),a.jsx(Xe,{label:"最大件数",type:"number",value:i.maxItems??"",onChange:f=>l({maxItems:f.target.value?parseInt(f.target.value):void 0}),size:"small",fullWidth:!0,placeholder:"無制限",slotProps:{htmlInput:{min:0}}})]}),a.jsxs(B,{children:[a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1,mb:1},children:[a.jsx(G,{variant:"body2",children:"アイテムフィールド"}),a.jsx(Ht,{label:`${((p=i.itemFields)==null?void 0:p.length)??0} 件`,size:"small",variant:"outlined"})]}),a.jsx(G,{variant:"caption",color:"text.secondary",sx:{display:"block",mb:1},children:"配列内の各アイテムが持つフィールドを定義します(オブジェクト配列の場合)"}),a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Ri,{}),onClick:()=>s(!0),children:"アイテムフィールドを編集"})]}),a.jsxs(Qt,{open:r,onClose:()=>s(!1),maxWidth:"lg",fullWidth:!0,"data-component-name":"cmp:ItemFieldsDialog",children:[a.jsxs(Yt,{children:["アイテムフィールドの編集: ",t.label]}),a.jsx(Jt,{sx:{height:"70vh",display:"flex",flexDirection:"column"},children:a.jsx(Nce,{itemFields:i.itemFields??[],contentTypeList:e,onChange:u})}),a.jsx(rn,{children:a.jsx(pe,{onClick:()=>s(!1),children:"閉じる"})})]})]})}const Vce=[{value:null,label:"指定なし"},{value:"free",label:"自由"},{value:"16:9",label:"16:9"},{value:"4:3",label:"4:3"},{value:"3:2",label:"3:2"},{value:"1:1",label:"1:1"}];function Hce({field:t,contentTypeList:e,onUpdate:n}){if(["text","html","markdown","number","boolean","date","file"].includes(t.type))return null;const s=()=>{var i,l;switch(t.type){case"image":return a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"アスペクト比"}),a.jsx(wn,{value:t.aspectRatio??null,label:"アスペクト比",onChange:u=>{const p=u.target.value;n({aspectRatio:p})},children:Vce.map(u=>a.jsx(nt,{value:u.value??"",children:u.label},u.value??"null"))})]});case"select":return a.jsx(Pce,{choices:((i=t.options)==null?void 0:i.choices)??[],onChange:u=>n({options:{...t.options,choices:u}})});case"relation":return a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"参照先コンテンツタイプ"}),a.jsxs(wn,{value:((l=t.options)==null?void 0:l.targetContentType)??"",label:"参照先コンテンツタイプ",onChange:u=>n({options:{...t.options,targetContentType:u.target.value}}),children:[a.jsx(nt,{value:"",children:a.jsx("em",{children:"選択してください"})}),e.map(u=>a.jsxs(nt,{value:u.id,children:[u.label," (",u.id,")"]},u.id))]})]});case"array":return a.jsx(Uce,{field:t,contentTypeList:e,onUpdate:n});default:return null}};return a.jsxs(_s,{defaultExpanded:!0,"data-component-name":"cmp:FieldTypeOptions",children:[a.jsx(Ps,{expandIcon:a.jsx(Wr,{}),children:a.jsx(G,{fontWeight:500,children:"タイプ固有オプション"})}),a.jsx(Is,{children:a.jsx(B,{sx:{display:"flex",flexDirection:"column",gap:2},children:s()})})]})}function Wce({field:t,isNewField:e,contentTypeList:n,onUpdate:r}){return a.jsxs(B,{"data-component-name":"cmp:FieldEditorPanelContent",sx:{display:"flex",flexDirection:"column",gap:2},children:[a.jsx(Oce,{field:t,isNewField:e,onUpdate:r}),a.jsx(Ice,{field:t,onUpdate:r}),a.jsx(Hce,{field:t,contentTypeList:n,onUpdate:r})]})}function R4({field:t,isNewField:e,contentTypeList:n,open:r,onClose:s,onUpdate:i}){const l=t?Ru(t.type):null;return a.jsxs(Cu,{anchor:"right",open:r,onClose:s,"data-component-name":"cmp:FieldEditorDrawer",PaperProps:{sx:{width:{xs:"100vw",sm:"70vw"},maxWidth:1e3,display:"flex",flexDirection:"column"}},children:[a.jsx(Dp,{title:(t==null?void 0:t.label)||"フィールド編集",icon:l&&a.jsx(l,{color:"action"}),onClose:s,componentName:"cmp:FieldEditorDrawerHeader"}),a.jsx(B,{"data-component-name":"cmp:FieldEditorDrawerContent",sx:{flex:1,overflow:"auto",p:2},children:t&&a.jsx(Wce,{field:t,isNewField:e,contentTypeList:n,onUpdate:i})})]})}function qce(t){return t.toLowerCase().replace(/[^\w\s]/g,"").replace(/\s+/g,"_").replace(/^_+|_+$/g,"")}function Gce(){return`label-${Math.random().toString(36).substring(2,8)}`}function Zce({open:t,existingKeys:e,onClose:n,onSubmit:r}){const[s,i]=b.useState(""),[l,u]=b.useState(!1),[p,f]=b.useState("text"),[m,g]=b.useState(""),[y,v]=b.useState(!1);b.useEffect(()=>{t&&(i(""),u(!1),f("text"),g(""),v(!1))},[t]);const C=E=>{g(E),!l&&p!=="label"&&i(qce(E))},S=E=>{i(E),u(!0)},j=()=>{T&&r({key:s.trim(),type:p,label:m.trim(),multiple:y})},D=!e.includes(s.trim()),M=p==="label"?/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(s.trim()):/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s.trim()),T=s.trim()&&m.trim()&&D&&M;return a.jsxs(Qt,{open:t,onClose:n,maxWidth:"sm",fullWidth:!0,"data-component-name":"cmp:AddFieldDialog",children:[a.jsx(Yt,{children:"フィールドを追加"}),a.jsx(Jt,{children:a.jsxs(B,{sx:{display:"flex",flexDirection:"column",gap:2,pt:1},children:[a.jsx(Xe,{label:"ラベル",value:m,onChange:E=>C(E.target.value),required:!0,fullWidth:!0,size:"small",autoFocus:!0}),a.jsx(Xe,{label:"キー",value:s,onChange:E=>S(E.target.value),required:!0,fullWidth:!0,size:"small",error:!!s&&(!D||!M),helperText:s&&!D?"既に存在するキーです":s&&!M?"英字で始まり、英数字とアンダースコアのみ使用可能":"ラベルから自動生成されます",slotProps:{input:{sx:{fontFamily:"monospace"}}}}),a.jsxs(_n,{fullWidth:!0,size:"small",children:[a.jsx(nr,{children:"タイプ"}),a.jsx(wn,{value:p,label:"タイプ",onChange:E=>{const k=E.target.value;f(k),k==="label"&&!l&&i(Gce()),k!=="relation"&&v(!1)},children:ab.map(E=>{const k=Ru(E);return a.jsx(nt,{value:E,children:a.jsxs(B,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(k,{fontSize:"small"}),a.jsx("span",{children:Mp[E]})]})},E)})})]}),p==="relation"&&a.jsx(_r,{control:a.jsx(es,{checked:y,onChange:E=>v(E.target.checked)}),label:"複数値を許可"})]})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:n,children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:j,disabled:!T,children:"追加"})]})]})}function Kce({open:t,fieldKey:e,fieldType:n,onClose:r,onDelete:s}){const i=n==="label";return a.jsxs(Qt,{open:t,onClose:r,maxWidth:"xs",fullWidth:!0,"data-component-name":"cmp:DeleteFieldDialog",children:[a.jsx(Yt,{children:i?"ラベルの削除":"フィールドの削除"}),a.jsxs(Jt,{children:[a.jsxs(Eo,{children:[i?"ラベル":"フィールド"," ",a.jsx(G,{component:"span",fontWeight:"bold",fontFamily:"monospace",children:e})," ","を削除しますか?"]}),!i&&a.jsx(Eo,{sx:{mt:1,color:"error.main"},children:"この操作は元に戻せません。既存のコンテンツからもこのフィールドのデータが失われます。"})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:r,children:"キャンセル"}),a.jsx(pe,{variant:"contained",color:"error",onClick:s,children:"削除"})]})]})}function Qce({open:t,groupName:e,fieldCount:n,onClose:r,onConfirm:s}){const[i,l]=b.useState(!1);b.useEffect(()=>{t&&l(!1)},[t]);const u=()=>{s(i)};return a.jsxs(Qt,{open:t,onClose:r,maxWidth:"sm",fullWidth:!0,"data-component-name":"cmp:DeleteGroupDialog",children:[a.jsxs(Yt,{sx:{display:"flex",alignItems:"center",gap:1},children:[a.jsx(IP,{color:"warning"}),"グループを削除"]}),a.jsxs(Jt,{children:[a.jsxs(G,{gutterBottom:!0,children:["グループ「",a.jsx("strong",{children:e}),"」を削除しますか?"]}),n>0&&a.jsxs(B,{sx:{mt:2,p:2,bgcolor:"grey.100",borderRadius:1},children:[a.jsxs(G,{variant:"body2",color:"text.secondary",gutterBottom:!0,children:["このグループには ",n," 件のフィールドが含まれています。"]}),a.jsx(_r,{control:a.jsx(es,{checked:i,onChange:p=>l(p.target.checked),color:"error"}),label:a.jsx(G,{variant:"body2",color:"error.main",children:"フィールドも一緒に削除する"})}),a.jsx(G,{variant:"caption",color:"text.secondary",display:"block",sx:{mt:1},children:"チェックしない場合、フィールドはグループから外れて未分類になります。"})]}),n===0&&a.jsx(G,{variant:"body2",color:"text.secondary",sx:{mt:1},children:"このグループは空です。"})]}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:r,children:"キャンセル"}),a.jsx(pe,{onClick:u,color:"error",variant:"contained",children:"削除"})]})]})}function Jce({name:t,color:e,canMoveUp:n,canMoveDown:r,onMoveUp:s,onMoveDown:i,onRename:l,onDelete:u}){const[p,f]=b.useState(!1),[m,g]=b.useState(t),y=b.useRef(null);b.useEffect(()=>{p&&y.current&&(y.current.focus(),y.current.select())},[p]),b.useEffect(()=>{g(t)},[t]);const v=()=>{g(t),f(!0)},C=()=>{const j=m.trim();j&&j!==t&&(l==null||l(j)),f(!1)},S=j=>{j.key==="Enter"?C():j.key==="Escape"&&(g(t),f(!1))};return a.jsxs(B,{"data-component-name":"cmp:GroupHeader",sx:{display:"flex",alignItems:"center",gap:1,mb:1,mt:2,px:1.5,py:.75,bgcolor:e.bg,borderLeft:4,borderColor:e.border,borderRadius:"0 4px 4px 0"},children:[a.jsx(ic,{fontSize:"small",sx:{color:e.border}}),p?a.jsx(Xe,{inputRef:y,value:m,onChange:j=>g(j.target.value),onBlur:C,onKeyDown:S,size:"small",variant:"standard",sx:{flex:1,maxWidth:200,"& .MuiInputBase-input":{fontSize:"0.875rem",fontWeight:600,py:0}}}):a.jsx(Er,{title:"クリックして編集",children:a.jsx(G,{variant:"subtitle2",fontWeight:600,onClick:v,sx:{cursor:"pointer","&:hover":{textDecoration:"underline"}},children:t})}),a.jsxs(B,{sx:{ml:"auto",display:"flex",gap:.5},children:[a.jsx(Er,{title:"上に移動",children:a.jsx("span",{children:a.jsx(ft,{size:"small",disabled:!n,onClick:s,sx:{p:.25},children:a.jsx(TP,{fontSize:"small"})})})}),a.jsx(Er,{title:"下に移動",children:a.jsx("span",{children:a.jsx(ft,{size:"small",disabled:!r,onClick:i,sx:{p:.25},children:a.jsx(w2,{fontSize:"small"})})})}),a.jsx(Er,{title:"グループを削除",children:a.jsx(ft,{size:"small",onClick:u,sx:{p:.25,color:"error.main"},children:a.jsx(zn,{fontSize:"small"})})})]})]})}function Yce({groupId:t,color:e,isOver:n}){const{setNodeRef:r}=T5({id:`empty-group:${t}`});return a.jsx(B,{ref:r,"data-group":t,"data-droppable-group":t,sx:{display:"flex",alignItems:"center",justifyContent:"center",minHeight:80,bgcolor:n?wt((e==null?void 0:e.bg)??"#e3f2fd",.8):wt((e==null?void 0:e.bg)??"#f5f5f5",.4),border:"2px dashed",borderColor:n?"primary.main":(e==null?void 0:e.border)??"divider",borderRadius:1,p:2,transition:"all 0.2s ease"},children:a.jsx(G,{color:n?"primary.main":"text.secondary",variant:"body2",children:n?"ここにドロップしてグループに追加":"フィールドをここにドラッグしてグループに追加"})})}function Xce({useCase:t,editorMode:e,canEdit:n=!0}){const r=t.getState();b.useEffect(()=>{t.prepareJsonForMode(e)},[t,e,r.editingId]);const{contentTypeId:s,editingLabel:i,editingFields:l,editingGroups:u,selectedFieldKey:p,selectedField:f,isSaving:m,isDirty:g,message:y,addFieldDialogOpen:v,deleteFieldDialogOpen:C,contentTypeList:S,unsavedGuard:j,jsonSchemaText:D,jsonUiText:M,jsonSchemaIsDirty:T,jsonUiIsDirty:E,tabSwitchDialogOpen:k}=r,A=Rce(l,u),[O,I]=b.useState(null),[$,R]=b.useState(null),P=O?l.find(be=>be.key===O):null,[z,N]=b.useState(!1),[H,U]=b.useState(""),[L,W]=b.useState(!1),[K,Q]=b.useState(null),le=(be,Ae,Ne)=>{Q({id:be,label:Ae,fieldCount:Ne}),W(!0)},F=()=>{W(!1),Q(null)},J=be=>{K&&t.removeGroup(K.id,be),F()},ie=Lm(Do(Tu,{activationConstraint:{distance:3}}),Do(ju,{coordinateGetter:Fm})),te=be=>{I(be.active.id)},de=be=>{var Ae;R((Ae=be.over)==null?void 0:Ae.id)},fe=be=>{const{active:Ae,over:Ne}=be;if(I(null),R(null),!Ne)return;const Ie=Ae.id,Fe=Ne.id;if(Ie===Fe)return;if(Fe.startsWith("empty-group:")){const tt=Fe.replace("empty-group:",""),Ve=O1(Ie,u);t.moveFieldToGroup(Ie,Ve,tt,0);return}const ct=O1(Fe,u),Me=O1(Ie,u);if(Me!==ct){const tt=A.find(Ve=>Ve.id===ct);if(tt){const Ve=tt.fields.findIndex(it=>it.key===Fe);t.moveFieldToGroup(Ie,Me,ct,Ve)}else t.moveFieldToGroup(Ie,Me,ct)}else if(ct!==null){const tt=A.find(Ve=>Ve.id===ct);if(tt){const Ve=tt.fields.findIndex(Z=>Z.key===Ie),it=tt.fields.findIndex(Z=>Z.key===Fe);Ve!==-1&&it!==-1&&t.reorderFieldInGroup(ct,Ve,it)}}else t.reorderUngroupedFields(Ie,Fe)},Re=be=>{const Ae=be.fields.map(Ne=>Ne.key);if(be.fields.length===0&&be.id!==null){const Ne=$===`empty-group:${be.id}`;return a.jsx(Yce,{groupId:be.id,color:be.color,isOver:Ne})}return a.jsx(Nm,{items:Ae,strategy:Xx,children:a.jsx(B,{"data-group":be.id??"__ungrouped__",sx:{display:"grid",gridTemplateColumns:"repeat(12, 1fr)",gap:2,...be.id&&be.color&&{bgcolor:wt(be.color.bg,.4),p:1.5,borderRadius:1}},children:be.fields.map((Ne,Ie)=>{const Fe=$===Ne.key&&O!==Ne.key,ct=Ie>0?be.fields[Ie-1]:null,Me=(ct==null?void 0:ct.break)===!0;return a.jsxs(B,{"data-field-key":Ne.key,sx:{gridColumnStart:{xs:1,sm:Me?1:"auto"},gridColumnEnd:{xs:"span 12",sm:`span ${Ne.columns}`},position:"relative"},children:[Fe&&a.jsx(B,{sx:{position:"absolute",left:-8,top:0,bottom:0,width:4,bgcolor:"primary.main",borderRadius:1,zIndex:10}}),a.jsx(D4,{field:Ne,onEdit:n?()=>t.selectField(Ne.key):void 0,onDelete:n?()=>{t.selectField(Ne.key),t.openDeleteFieldDialog()}:void 0,onToggleBreak:n?()=>t.toggleFieldBreak(Ne.key):void 0,onChangeColumns:n?tt=>t.changeFieldColumns(Ne.key,tt):void 0})]},Ne.key)})})})},Pe=()=>a.jsxs(B,{"data-component-name":"cmp:JsonSchemaEditorContainer",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",maxWidth:"xl",mx:"auto",width:"100%"},children:[a.jsx(rm,{filePath:`frelio-data/site/content_types/${s}.json`,isSaving:m,isDirty:T,onFormat:n?()=>t.formatJson():void 0,onReset:n?()=>t.resetJson():void 0,onSave:n?()=>t.saveFromJson():void 0,readOnly:!n}),a.jsx(B,{"data-component-name":"cmp:JsonSchemaEditorWrapper",sx:{flex:1,overflow:"hidden",pb:1},children:a.jsx(nm,{value:D,onChange:n?be=>t.updateJsonSchemaText(be):void 0,height:"100%",readOnly:!n})})]}),$e=()=>a.jsxs(B,{"data-component-name":"cmp:JsonUiEditorContainer",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",maxWidth:"xl",mx:"auto",width:"100%"},children:[a.jsx(rm,{filePath:`frelio-data/admin/content_types/${s}.ui.json`,isSaving:m,isDirty:E,onFormat:n?()=>t.formatJson():void 0,onReset:n?()=>t.resetJson():void 0,onSave:n?()=>t.saveFromJson():void 0,readOnly:!n}),a.jsx(B,{"data-component-name":"cmp:JsonUiEditorWrapper",sx:{flex:1,overflow:"hidden",pb:1},children:a.jsx(nm,{value:M,onChange:n?be=>t.updateJsonUiText(be):void 0,height:"100%",readOnly:!n})})]}),we=()=>a.jsx(B,{"data-component-name":"cmp:UiEditorContainer",sx:{flex:1,overflow:"auto"},children:a.jsxs(ji,{maxWidth:"xl",sx:{py:3},children:[a.jsx(la,{title:i||"コンテンツタイプ編集",actions:n&&a.jsx(pe,{variant:"contained",startIcon:m?a.jsx(ut,{size:20,color:"inherit"}):a.jsx(na,{}),onClick:()=>t.save(),disabled:!g||m,children:m?"保存中...":"保存"})}),l.length===0?a.jsxs(B,{"data-component-name":"cmp:EmptyFieldsPlaceholder",sx:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",py:8,border:"2px dashed",borderColor:"divider",borderRadius:2},children:[a.jsx(G,{color:"text.secondary",gutterBottom:!0,children:"フィールドがありません"}),n&&a.jsx(pe,{variant:"outlined",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddFieldDialog(),children:"最初のフィールドを追加"})]}):a.jsxs($m,{sensors:ie,collisionDetection:Dne,onDragStart:te,onDragOver:de,onDragEnd:fe,children:[a.jsx(B,{"data-component-name":"cmp:FieldGroups",children:A.map((be,Ae)=>{const Ne=A.filter(ct=>ct.id!==null).length,Ie=be.id===null,Fe=Ne>0;return a.jsxs(B,{"data-component-name":"cmp:FieldGroupSection",sx:{mb:2},children:[be.id&&be.label&&be.color&&a.jsx(Jce,{name:be.label,color:be.color,canMoveUp:n&&Ae>1,canMoveDown:n&&Ae<Ne,onMoveUp:n?()=>t.moveGroupUp(be.id):void 0,onMoveDown:n?()=>t.moveGroupDown(be.id):void 0,onRename:n?ct=>t.renameGroup(be.id,ct):void 0,onDelete:n?()=>le(be.id,be.label,be.fields.length):void 0}),Re(be),n&&Ie&&Fe&&a.jsxs(B,{"data-component-name":"cmp:AddFieldButtons",sx:{display:"flex",justifyContent:"center",gap:1,mt:2,mb:2},children:[a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddFieldDialog(),children:"フィールド追加"}),a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(ch,{}),onClick:()=>t.addLabel(),children:"ラベル追加"})]}),n&&be.id&&a.jsxs(B,{"data-component-name":"cmp:AddFieldToGroupButtons",sx:{display:"flex",flexDirection:"column",alignItems:"center",gap:1,mt:2,py:1},children:[a.jsx(G,{variant:"caption",color:"text.secondary",children:"このグループに"}),a.jsxs(B,{sx:{display:"flex",gap:1},children:[a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddFieldDialogForGroup(be.id),children:"フィールド追加"}),a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(ch,{}),onClick:()=>t.addLabelToGroup(be.id),children:"ラベル追加"})]})]})]},be.id??"__ungrouped__")})}),a.jsx(B2,{children:P?a.jsx(Mce,{field:P}):null})]}),n&&u.length===0&&l.length>0&&a.jsxs(B,{"data-component-name":"cmp:AddFieldButtons",sx:{display:"flex",justifyContent:"center",gap:1,mt:2,mb:4},children:[a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(Qn,{}),onClick:()=>t.openAddFieldDialog(),children:"フィールド追加"}),a.jsx(pe,{variant:"outlined",size:"small",startIcon:a.jsx(ch,{}),onClick:()=>t.addLabel(),children:"ラベル追加"})]}),n&&a.jsx(B,{"data-component-name":"cmp:AddGroupButton",sx:{display:"flex",justifyContent:"center",py:2},children:a.jsx(pe,{variant:"outlined",startIcon:a.jsx(C2,{}),onClick:()=>N(!0),children:"グループ追加"})})]})});return a.jsxs(B,{"data-component-name":"cmp:ContentTypeEditor",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[e==="ui"&&we(),e==="json-schema"&&Pe(),e==="json-ui"&&$e(),a.jsx(R4,{field:f,isNewField:!1,contentTypeList:S,open:p!==null,onClose:()=>t.clearSelection(),onUpdate:be=>t.updateCurrentField(be)}),a.jsx(Zce,{open:v,existingKeys:l.map(be=>be.key),onClose:()=>{t.closeAddFieldDialog(),t.clearPendingGroupId()},onSubmit:be=>{const Ae=t.getPendingGroupId();Ae?(t.addFieldToGroup(be,Ae),t.clearPendingGroupId()):t.addField(be)}}),a.jsx(Kce,{open:C,fieldKey:(f==null?void 0:f.key)??"",fieldType:f==null?void 0:f.type,onClose:()=>t.closeDeleteFieldDialog(),onDelete:()=>t.deleteCurrentField()}),a.jsxs(Qt,{open:z,onClose:()=>{N(!1),U("")},maxWidth:"xs",fullWidth:!0,children:[a.jsx(Yt,{children:"グループを追加"}),a.jsx(Jt,{children:a.jsx(Xe,{autoFocus:!0,margin:"dense",label:"グループ名",fullWidth:!0,value:H,onChange:be=>U(be.target.value),onKeyDown:be=>{be.key==="Enter"&&H.trim()&&(t.addGroup(H.trim()),N(!1),U(""))}})}),a.jsxs(rn,{children:[a.jsx(pe,{onClick:()=>{N(!1),U("")},children:"キャンセル"}),a.jsx(pe,{variant:"contained",onClick:()=>{H.trim()&&(t.addGroup(H.trim()),N(!1),U(""))},disabled:!H.trim(),children:"追加"})]})]}),a.jsx(Qce,{open:L,groupName:(K==null?void 0:K.label)??"",fieldCount:(K==null?void 0:K.fieldCount)??0,onClose:F,onConfirm:J}),a.jsx(sb,{open:(j==null?void 0:j.isBlocked)??!1,onStay:()=>j==null?void 0:j.reset(),onLeave:()=>j==null?void 0:j.proceed()}),a.jsx(nb,{open:k,onStay:()=>t.cancelTabSwitch(),onDiscard:()=>t.discardAndSwitchTab(),onSaveAndSwitch:()=>t.saveAndSwitchTab()}),a.jsx(ea,{open:y!==null,autoHideDuration:4e3,onClose:()=>t.clearMessage(),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:a.jsx(zt,{severity:(y==null?void 0:y.type)??"info",onClose:()=>t.clearMessage(),children:y==null?void 0:y.text})})]})}const eue=["ui","json-schema","json-ui"],tue=Ss("/content-types/$contentTypeId/edit")({component:rue,validateSearch:t=>({field:typeof t.field=="string"?t.field:void 0,mode:eue.includes(t.mode)?t.mode:void 0})}),nue=[{label:"UI編集",value:"ui"},{label:"JSON(スキーマ)",value:"json-schema"},{label:"JSON(UI)",value:"json-ui"}];function rue(){const t=ur(),e=Di({from:"/content-types/$contentTypeId/edit"}),n=e.mode??"ui",{authUseCase:r}=rr(),{currentUser:s}=r.getState(),i=ws(s,"canViewContentType"),l=ws(s,"canEditContentType"),{contentTypeEditorUseCase:u}=lie(),{isLoading:p,error:f,editingLabel:m,contentTypeId:g}=u.getState();if(b.useEffect(()=>{s&&!i&&t({to:"/"})},[s,i,t]),!i)return null;if(p)return a.jsx(B,{"data-component-name":"cmp:ContentTypeEditPage",sx:{flex:1,display:"flex",justifyContent:"center",alignItems:"center"},children:a.jsx(ut,{})});if(f)return a.jsx(B,{"data-component-name":"cmp:ContentTypeEditPage",sx:{flex:1,overflow:"auto",p:3},children:a.jsxs(zt,{severity:"error",children:["エラー: ",f.message]})});const v={value:n,options:nue,onChange:C=>{t({to:".",search:{...e,mode:C==="ui"?void 0:C},replace:!0})}};return a.jsxs(B,{"data-component-name":"cmp:ContentTypeEditPage",sx:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden"},children:[a.jsx(B,{sx:{px:3,pt:2,flexShrink:0},children:a.jsx(no,{items:[{label:"コンテンツタイプ編集",to:"/content-types"},{label:m||g}],dropdown:v})}),a.jsx(Xce,{useCase:u,editorMode:n,canEdit:l})]})}const sue=iX.update({id:"/login",path:"/login",getParentRoute:()=>Bs}),iue=hX.update({id:"/",path:"/",getParentRoute:()=>Bs}),oue=kee.update({id:"/users/",path:"/users/",getParentRoute:()=>Bs}),aue=Gee.update({id:"/templates/",path:"/templates/",getParentRoute:()=>Bs}),lue=Lte.update({id:"/storage/",path:"/storage/",getParentRoute:()=>Bs}),cue=Gte.update({id:"/staging/",path:"/staging/",getParentRoute:()=>Bs}),uue=nne.update({id:"/deploy-history/",path:"/deploy-history/",getParentRoute:()=>Bs}),due=hie.update({id:"/content-types/",path:"/content-types/",getParentRoute:()=>Bs}),pue=nae.update({id:"/build-recipes/",path:"/build-recipes/",getParentRoute:()=>Bs}),fue=uae.update({id:"/auth/callback",path:"/auth/callback",getParentRoute:()=>Bs}),hue=X5.update({id:"/contents/$contentTypeId/",path:"/contents/$contentTypeId/",getParentRoute:()=>Bs}),mue=sce.update({id:"/contents/$contentTypeId/$contentId",path:"/contents/$contentTypeId/$contentId",getParentRoute:()=>Bs}),gue=wce.update({id:"/content-types/$contentTypeId/views",path:"/content-types/$contentTypeId/views",getParentRoute:()=>Bs}),yue=tue.update({id:"/content-types/$contentTypeId/edit",path:"/content-types/$contentTypeId/edit",getParentRoute:()=>Bs}),vue={IndexRoute:iue,LoginRoute:sue,AuthCallbackRoute:fue,BuildRecipesIndexRoute:pue,ContentTypesIndexRoute:due,DeployHistoryIndexRoute:uue,StagingIndexRoute:cue,StorageIndexRoute:lue,TemplatesIndexRoute:aue,UsersIndexRoute:oue,ContentTypesContentTypeIdEditRoute:yue,ContentTypesContentTypeIdViewsRoute:gue,ContentsContentTypeIdContentIdRoute:mue,ContentsContentTypeIdIndexRoute:hue},xue=Bs._addFileChildren(vue)._addFileTypes(),bue=new xN({defaultOptions:{queries:{staleTime:1e3*60*5,retry:1}}}),Sue=W$({routeTree:xue,basepath:"/".replace(/\/$/,"")||"/"});wQ().then(()=>{Kz.createRoot(document.getElementById("root")).render(a.jsx(We.StrictMode,{children:a.jsx(bN,{client:bue,children:a.jsxs(k6,{theme:WK,children:[a.jsx(bH,{}),a.jsx(Z$,{router:Sue})]})})}))});export{Wr as $,aJ as A,gJ as B,xJ as C,yP as D,Ti as E,gP as F,wJ as G,S2 as H,jJ as I,TJ as J,bP as K,C2 as L,km as M,DJ as N,EJ as O,RJ as P,kJ as Q,MJ as R,SP as S,OJ as T,zn as U,Tp as V,AJ as W,wu as X,Ri as Y,_J as Z,IJ as _,lJ as a,Om as a$,CP as a0,PJ as a1,LJ as a2,zJ as a3,$J as a4,NJ as a5,ic as a6,FJ as a7,BJ as a8,UJ as a9,iY as aA,EP as aB,oY as aC,aY as aD,lY as aE,cY as aF,uY as aG,dY as aH,ip as aI,pY as aJ,RP as aK,Mm as aL,fY as aM,hY as aN,Fx as aO,mY as aP,gY as aQ,yY as aR,kC as aS,vY as aT,kP as aU,xY as aV,bY as aW,na as aX,SY as aY,CY as aZ,wY as a_,Nx as aa,VJ as ab,HJ as ac,WJ as ad,wP as ae,qJ as af,GJ as ag,jP as ah,ZJ as ai,KJ as aj,vc as ak,QJ as al,w2 as am,TP as an,JJ as ao,ch as ap,RC as aq,YJ as ar,j2 as as,DP as at,XJ as au,eY as av,tY as aw,nY as ax,rY as ay,sY as az,mP as b,Bx as b0,jY as b1,MP as b2,TY as b3,DY as b4,EY as b5,RY as b6,OP as b7,T2 as b8,kY as b9,MY as ba,OY as bb,AY as bc,_Y as bd,IY as be,PY as bf,AP as bg,_P as bh,LY as bi,zY as bj,IP as bk,$Y as bl,ye as c,Qn as d,cJ as e,uJ as f,dJ as g,zx as h,pJ as i,a as j,fJ as k,x2 as l,hJ as m,mJ as n,yJ as o,b2 as p,vJ as q,b as r,bJ as s,Ph as t,vP as u,xP as v,Jl as w,SJ as x,$x as y,CJ as z};