import {ID,PACKS,ENABLE,DISABLE,preflight,applyPlan,artPaths,lookup,routeNew} from './core.mjs'; import {openVault} from './vault.mjs'; let busy=false; const esc=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); function apis(){ const a={Folder:CONFIG.Folder.documentClass,Compendium:foundry.documents.collections.CompendiumCollection,Picker:foundry.applications.apps.FilePicker}; if(!a.Folder?.create || !a.Compendium?.createCompendium || !a.Picker?.browse || !a.Picker?.createDirectory)throw Error('Required Foundry APIs unavailable.'); return a; } async function run(campaign){ if(busy)return; busy=true;const log=[]; try { const api=apis();checkSandbox();const scriptPolicy=game.settings.get(ID,'scriptPolicy');const plan=preflight(game,CONST,{campaign,scriptPolicy}); const paths=artPaths(game.world.id,plan.names); const listed=await api.Picker.browse('data',`worlds/${game.world.id}`); if(!Array.isArray(listed?.dirs))throw Error('World art directory not readable.'); const list=(items)=>`
World: ${esc(game.world.id)}. Back up first; have other users log out. This changes only the listed actors, folders, new world packs and selected player permissions.
Token creation/deletion applies on accessible scenes. Shared packs are collaboratively editable. A blank shared testing scene will be created if not already provisioned. Script macro policy: ${esc(scriptPolicy)}. Art folders are not private. Setup can stop partway on an API error; restore backup for full rollback.
`; if(!await foundry.applications.api.DialogV2.confirm({window:{title:'Player Workshop — review changes'},position:{width:640},content:html,rejectClose:false,modal:true}))return; const fresh=preflight(game,CONST,{campaign,scriptPolicy}); if(JSON.stringify(fresh.actors.map(a=>a.actor.id))!==JSON.stringify(plan.actors.map(a=>a.actor.id)))throw Error('Actor identities changed during preview. Reopen setup.'); checkSandbox(); await applyPlan(game,CONST,api,fresh,log); await ensureSandbox(log); await game.settings.set(ID,'routing',true); console.info(`${ID}: setup complete`,log); await foundry.applications.api.DialogV2.prompt({window:{title:'Player Workshop — complete'},content:`Setup completed. ${log.length} changes recorded. Automatic filing enabled for newly created root-level personal characters and items. Refresh all clients and test as a player.
Prepare your existing campaign for player-owned characters, homebrew and artwork. Review every proposed change before applying.
Sign in as Gamemaster. Back up your world first.
',buttons:[{action:'review',label:'Provision this world (no actor moves)',default:true,callback:()=>{void run(false);}},{action:'campaign',label:'Organize named Phandelver characters',callback:()=>{void run(true);}},{action:'cancel',label:'Cancel'}]});} } game.settings.registerMenu(ID,'setup',{name:'Player Workshop setup',label:'Open setup',hint:'Preview and apply the named campaign setup. No changes are applied on module activation.',icon:'fas fa-folder-tree',type:WorkshopMenu,restricted:true}); class VaultMenu extends foundry.applications.api.DialogV2 {constructor(options={}){super({...options,window:{title:'Player Vault'},content:'Manage and export your owned content.
',buttons:[{action:'open',label:'Open my vault',default:true,callback:()=>{void openVault();}},{action:'cancel',label:'Cancel'}]});}} game.settings.registerMenu(ID,'vault',{name:'Player Vault',label:'Open Player Vault',hint:'Characters, homebrew, artwork and portable exports',icon:'fas fa-box-archive',type:VaultMenu,restricted:false}); for(const type of ['Actor','Item'])Hooks.on(`preCreate${type}`,(doc,data,options,userId)=>{try{routeNew(game,doc,data,options,userId);}catch(e){console.warn(`${ID}: automatic filing skipped`,e);}}); }); function checkSandbox(){ const matches=[...game.scenes].filter(s=>s.name==='Player Workshop — Testing Grounds'); if(matches.length>1)throw Error('Ambiguous testing scene name.'); if(matches.length&&!matches[0].getFlag(ID,'sandbox'))throw Error('Existing testing scene name collision; rename it before setup.');return matches[0]; } async function ensureSandbox(log){ if(checkSandbox())return; const scene=await CONFIG.Scene.documentClass.create({name:'Player Workshop — Testing Grounds',navigation:true,active:false,ownership:{default:2},width:2400,height:1600,padding:0.1,backgroundColor:'#30363d',tokenVision:false,grid:{type:1,size:100,distance:5,units:'ft'},flags:{[ID]:{sandbox:true}}}); if(!scene||scene.active)throw Error('Testing scene creation failed or activated unexpectedly.');log.push('Created testing scene'); } Hooks.on('renderActorDirectory',(_app,html)=>{ const root=html instanceof HTMLElement?html:html?.[0];if(game.release.generation!==14||game.system.id!=='dnd5e'||!root||root.querySelector('[data-player-workshop-vault]'))return; const header=root.querySelector('.directory-header')??root.querySelector('header');if(!header)return; const b=document.createElement('button');b.type='button';b.dataset.playerWorkshopVault='1';b.textContent='Player Vault';b.addEventListener('click',()=>void openVault());header.append(b); });