Add Player Workshop 2.0.0
This commit is contained in:
1 parent
193f82a729
commit
17b06810c8
11 files changed
+494
-1
No files matched your search
+46
@@ -0,0 +1,46 @@
|
||||
# Install Player Workshop 2.0.0
|
||||
|
||||
## 1. Before you start
|
||||
|
||||
- Back up the world you plan to use. Test on a duplicate world before running setup in your campaign.
|
||||
- Use Foundry **14.371** with the official **D&D5e 6.1.2** system for the first test.
|
||||
- Use the Gitea route if Foundry can download from your LAN repository. If the repo requires sign-in or the Foundry host cannot reach it, use the manual route instead.
|
||||
|
||||
## 2. Install or update
|
||||
|
||||
### Gitea
|
||||
|
||||
1. Open or clone `CheddahBoxMB/player-workshop` on your Gitea server. Extract the ZIP into the root of the repository on `main`, so `module.json`, `README.md`, `INSTALL.md`, `scripts/`, and `tests/` are side by side. Commit those files and push `main`.
|
||||
2. In Gitea, open **Releases → New Release**. Select or create tag `v2.0.0` at the commit you pushed. Upload this exact `player-workshop.zip` as the release attachment and publish the release. If `v2.0.0` was already published with different bytes, use the manual install for this copy or follow the README to create a new version and tag.
|
||||
3. From the Foundry host, confirm both URLs below are reachable without signing in. These addresses come from the supplied manifest. If your Gitea address or repo path differs, edit `url`, `manifest`, and `download` in `module.json` before committing and build the release ZIP from that commit as described in the README.
|
||||
|
||||
```sh
|
||||
curl -fsSL 'http://192.168.100.15:3000/CheddahBoxMB/player-workshop/raw/branch/main/module.json'
|
||||
curl -fsSL -o /tmp/player-workshop.zip 'http://192.168.100.15:3000/CheddahBoxMB/player-workshop/releases/download/v2.0.0/player-workshop.zip'
|
||||
unzip -t /tmp/player-workshop.zip
|
||||
```
|
||||
|
||||
4. In Foundry **Setup → Add-on Modules → Install Module**, paste the raw `module.json` URL from the first command into **Manifest URL** and install. If you already have an earlier release installed from that manifest, use its update button.
|
||||
|
||||
### Manual install
|
||||
|
||||
1. Stop Foundry. Find its configured **User Data** directory, then open `Data/modules/` under it.
|
||||
2. If `player-workshop/` already exists, move the old folder somewhere outside `Data/modules/` as a backup.
|
||||
3. Create `player-workshop/` and extract this ZIP into that folder. The final path must be `Data/modules/player-workshop/module.json`.
|
||||
4. Start Foundry and confirm **Player Workshop 2.0.0** appears under **Add-on Modules**.
|
||||
|
||||
## 3. Set up a world
|
||||
|
||||
1. Launch the duplicate world as **Gamemaster**. Open **Game Settings → Manage Modules**, enable **Player Workshop**, and save. Run the first test with Player Workshop as the only add-on enabled in the test world.
|
||||
2. Go to **Game Settings → Configure Settings → Player Workshop → Open setup**.
|
||||
3. Select **Provision this world (no actor moves)** for a new or test world. Select **Organize named Phandelver characters** only for the original campaign when you intend to move the eight named actors and replace their ownership. On the duplicate campaign, you can preview that action and cancel to inspect its planned changes.
|
||||
4. Review the preview and confirm. After the completion dialog, refresh GM and player clients. Players can use **Player Vault** from the Actors sidebar or the module's settings menu.
|
||||
|
||||
## 4. Test on a duplicate world
|
||||
|
||||
- [ ] As GM, run generic provisioning twice. Confirm a single Testing Grounds scene, four homebrew compendia, and no duplicate personal folders. If you intend to use named setup, test it on a duplicate of the actual campaign and compare the eight actor IDs and ownership entries before and after.
|
||||
- [ ] As a regular Player and as a Trusted Player, create a PC and an item using the normal sidebars. Confirm auto-filing and explicit Owner access. Try opening and editing the other player's test document and confirm its privacy. Open the PC's normal D&D5e sheet and try advancement there.
|
||||
- [ ] Upload a portrait or token image and assign it. Enter Testing Grounds and place an owned token. Publish an item to a community pack. As GM, approve a snapshot and confirm the approved compendium is locked after approval.
|
||||
- [ ] Export a character ZIP containing an embedded spell, effects, and artwork. As another player in a provisioned duplicate world, import the ZIP and inspect ownership, level, HP, inventory, spell/effect links, and images. If you use Tokenizer or another character builder, enable it after the standalone test and try its normal workflow.
|
||||
|
||||
If setup stops midway, the browser console records completed steps. Restore the world backup to roll back folders, documents, permissions, and artwork together. Replacing the module files alone only restores the previous module code.
|
||||
@@ -1,2 +1,48 @@
|
||||
# player-workshop
|
||||
# Player Workshop 2.0.0
|
||||
|
||||
Player Workshop is a standalone Foundry VTT module for player-owned D&D characters, homebrew, and artwork. GM setup creates a shared Testing Grounds scene and personal folders. Players use the normal D&D5e sheets for character creation and advancement, and **Player Vault** for organization, artwork, publishing, and exports.
|
||||
|
||||
- **Target** — Foundry VTT 14.371 and D&D5e 6.1.2. The manifest declares Foundry v14 starting at 14.371 and D&D5e 6.1.x starting at 6.1.2.
|
||||
- **Dependencies** — Foundry and the official D&D5e system. There are no required add-on modules, forks, npm packages, or external services. Players can open the published Tokenizer module separately if installed.
|
||||
- **Author** — CheddahBoxMB.
|
||||
- **Install and update** — Follow [INSTALL.md](INSTALL.md) for Gitea, manual installation, and the test-world checklist.
|
||||
|
||||
## At the table
|
||||
|
||||
Open **Player Vault** from the Actors sidebar or the Player Workshop settings menu. The vault lists world actors and items for which your account has explicit Owner access. After GM setup, new root-level PCs and items created by provisioned players are filed in their personal folders. Players can also organize owned actors, upload and assign images, and place their own tokens in Testing Grounds using Foundry's native permissions.
|
||||
|
||||
**Publish Homebrew** creates a separate copy of a player-owned NPC or item in a shared compendium. The GM can use **Approve Homebrew** to place a snapshot in an approved compendium. Accessible homebrew can be dragged onto a sheet. If a character builder supports selecting world compendia, its source selector is another way to access those packs.
|
||||
|
||||
**Export Foundry JSON** uses Foundry's native export and keeps artwork as path references. **Export one ZIP** and **Export vault ZIP** include eligible local artwork alongside document JSON. Reopen Workshop ZIPs in a compatible world with Player Workshop enabled and provisioned. ZIP imports create new owned copies, remap supported world Actor and Item references, and retain embedded IDs for items and effects. Artwork from modules, systems, or remote URLs stays external. The ZIP manifest lists image warnings and active modules from the source world. A failed import may leave completed copies and uploaded images in place. Only import archives from sources you trust.
|
||||
|
||||
GM setup enables creation of actors, items, and journals, file browsing and uploads, and token configuration, creation, and deletion for the Player and Trusted Player roles. It disables region and playlist creation, manual rolls, and settings changes for those roles. The default script macro policy preserves existing permissions. Token permissions apply across accessible scenes. Artwork folders organize files and use Foundry's shared file storage. Only the named Phandelver setup moves existing characters and changes their individual ownership.
|
||||
|
||||
## Repository and releases
|
||||
|
||||
`module.json`, `scripts/`, `tests/`, `README.md`, and `INSTALL.md` live at the root of `main`. Keep `module.json` at the root of the installation ZIP as well. The checked-in source contains a world-specific character mapping, so keep this edition on the campaign LAN or in access-controlled Git storage.
|
||||
|
||||
Run the checks from the repository root with Node.js 24:
|
||||
|
||||
```sh
|
||||
node --test tests/*.mjs
|
||||
for file in scripts/*.mjs tests/*.mjs; do node --check "$file" || exit 1; done
|
||||
```
|
||||
|
||||
For future releases, update `version` and the version in `download` in `module.json`, commit, and tag that commit. Keep the `manifest` URL pointed to `main`. Build from the tag so the release ZIP matches Git. Replace `vX.Y.Z` with the actual tag:
|
||||
|
||||
```sh
|
||||
mkdir -p ../player-workshop-release
|
||||
git archive --format=zip --output=../player-workshop-release/player-workshop.zip vX.Y.Z
|
||||
unzip -t ../player-workshop-release/player-workshop.zip
|
||||
```
|
||||
|
||||
Upload `player-workshop.zip` as a Gitea release attachment and verify the raw manifest and ZIP URLs from the Foundry host. Use the ZIP attached to this package for the initial `v2.0.0` release.
|
||||
|
||||
## Validation for this build
|
||||
|
||||
All 15 Node tests pass. The checks cover setup planning and reruns, routing, ownership, ZIP round trips, validation of incoming archive data, and embedded ID options on vault import. The release ZIP was checked after extraction, including all eight JavaScript files and the root manifest. The regression test for imported IDs fails against the previous build and passes with this one. A live Foundry test on a duplicate world remains pending. See [INSTALL.md](INSTALL.md#4-test-on-a-duplicate-world) for the GM and player checks.
|
||||
|
||||
- [Foundry VTT 14.371](https://foundryvtt.com/releases/14.371)
|
||||
- [Official D&D5e system](https://foundryvtt.com/packages/dnd5e)
|
||||
- [Foundry module manifest and archive](https://foundryvtt.com/article/module-development/)
|
||||
- [Foundry v14 document creation options](https://foundryvtt.com/api/v14/interfaces/foundry.abstract.types.DatabaseCreateOperation.html)
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"id": "player-workshop",
|
||||
"title": "Player Workshop",
|
||||
"description": "Player-owned character workshop, artwork, homebrew publishing, portable ZIP archives and GM-controlled setup.",
|
||||
"version": "2.0.0",
|
||||
"authors": [
|
||||
{
|
||||
"name": "CheddahBoxMB"
|
||||
}
|
||||
],
|
||||
"compatibility": {
|
||||
"minimum": "14.371",
|
||||
"maximum": "14"
|
||||
},
|
||||
"relationships": {
|
||||
"systems": [
|
||||
{
|
||||
"id": "dnd5e",
|
||||
"type": "system",
|
||||
"compatibility": {
|
||||
"minimum": "6.1.2",
|
||||
"maximum": "6.1.999"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"esmodules": [
|
||||
"scripts/main.mjs"
|
||||
],
|
||||
"url": "http://192.168.100.15:3000/CheddahBoxMB/player-workshop",
|
||||
"manifest": "http://192.168.100.15:3000/CheddahBoxMB/player-workshop/raw/branch/main/module.json",
|
||||
"download": "http://192.168.100.15:3000/CheddahBoxMB/player-workshop/releases/download/v2.0.0/player-workshop.zip"
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Small ZIP32 STORE codec; no external dependencies. Accepts only this module's uncompressed format.
|
||||
const enc=new TextEncoder(), dec=new TextDecoder('utf-8',{fatal:true});
|
||||
export const MAX_BYTES=64*1024*1024, MAX_FILES=1000;
|
||||
const table=Uint32Array.from({length:256},(_,i)=>{for(let j=0;j<8;j++)i=i&1?0xedb88320^(i>>>1):i>>>1;return i>>>0;});
|
||||
export function crc32(bytes){let c=0xffffffff;for(const b of bytes)c=table[(c^b)&255]^(c>>>8);return (c^0xffffffff)>>>0;}
|
||||
const safe=p=>/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/.test(p)&&!p.split('/').some(x=>x==='.'||x==='..');
|
||||
export function zip(files){const parts=[],central=[];let offset=0,bytes=0;if(files.size>MAX_FILES)throw Error('Too many files');for(const [name,input] of files){if(!safe(name))throw Error('Unsafe archive path');const n=enc.encode(name), b=typeof input==='string'?enc.encode(input):new Uint8Array(input);bytes+=b.length;if(bytes>MAX_BYTES)throw Error('Archive exceeds 64 MiB');const crc=crc32(b),h=new Uint8Array(30+n.length),v=new DataView(h.buffer);v.setUint32(0,0x04034b50,true);v.setUint16(4,20,true);v.setUint16(6,0x800,true);v.setUint32(14,crc,true);v.setUint32(18,b.length,true);v.setUint32(22,b.length,true);v.setUint16(26,n.length,true);h.set(n,30);const c=new Uint8Array(46+n.length),w=new DataView(c.buffer);w.setUint32(0,0x02014b50,true);w.setUint16(4,20,true);w.setUint16(6,20,true);w.setUint16(8,0x800,true);w.setUint32(16,crc,true);w.setUint32(20,b.length,true);w.setUint32(24,b.length,true);w.setUint16(28,n.length,true);w.setUint32(42,offset,true);c.set(n,46);central.push(c);parts.push(h,b);offset+=h.length+b.length;}const size=central.reduce((a,c)=>a+c.length,0),end=new Uint8Array(22),v=new DataView(end.buffer);v.setUint32(0,0x06054b50,true);v.setUint16(8,files.size,true);v.setUint16(10,files.size,true);v.setUint32(12,size,true);v.setUint32(16,offset,true);return new Blob([...parts,...central,end],{type:'application/zip'});}
|
||||
export function unzip(input){const b=new Uint8Array(input),v=new DataView(b.buffer,b.byteOffset,b.byteLength);if(b.length>MAX_BYTES+1024*1024||b.length<22)throw Error('Invalid archive size');const end=b.length-22;if(v.getUint32(end,true)!==0x06054b50||v.getUint16(end+4,true)||v.getUint16(end+6,true)||v.getUint16(end+20,true))throw Error('Only Player Workshop ZIP archives are accepted');const count=v.getUint16(end+10,true), start=v.getUint32(end+16,true), size=v.getUint32(end+12,true);if(count>MAX_FILES||v.getUint16(end+8,true)!==count||start+size!==end)throw Error('Invalid ZIP directory');let p=start,total=0;const files=new Map();for(let i=0;i<count;i++){if(p+46>end||v.getUint32(p,true)!==0x02014b50)throw Error('Invalid ZIP entry');const flags=v.getUint16(p+8,true),method=v.getUint16(p+10,true),crc=v.getUint32(p+16,true),len=v.getUint32(p+20,true),plain=v.getUint32(p+24,true),nl=v.getUint16(p+28,true),ex=v.getUint16(p+30,true),co=v.getUint16(p+32,true),o=v.getUint32(p+42,true);if((flags&~0x800)||method||len!==plain||p+46+nl+ex+co>end||o+30>start||v.getUint32(o,true)!==0x04034b50)throw Error('Unsupported or corrupt ZIP entry');const name=dec.decode(b.subarray(p+46,p+46+nl));const ln=v.getUint16(o+26,true),lx=v.getUint16(o+28,true),from=o+30+ln+lx;if(!safe(name)||files.has(name)||from+len>start||dec.decode(b.subarray(o+30,o+30+ln))!==name||v.getUint16(o+8,true)!==0||v.getUint32(o+18,true)!==len||v.getUint32(o+22,true)!==len)throw Error('Unsafe ZIP entry');const data=b.slice(from,from+len);if(crc32(data)!==crc)throw Error('CRC mismatch');total+=len;if(total>MAX_BYTES)throw Error('Archive too large');files.set(name,data);p+=46+nl+ex+co;}if(p!==end)throw Error('Invalid ZIP directory length');return files;}
|
||||
export function parseJSON(bytes){if(!bytes)throw Error('Missing manifest');return JSON.parse(dec.decode(bytes),(k,v)=>{if(['__proto__','constructor','prototype'].includes(k))throw Error('Unsafe object key');return v;});}
|
||||
@@ -0,0 +1,166 @@
|
||||
export const ID = 'player-workshop';
|
||||
export const PLAYERS = ['Austin','Derrick','Micah','Steve'];
|
||||
export const ROWS = [
|
||||
['Austin','Akupara Kurma','Active Campaign','Austin'],
|
||||
['Austin','Valkar Thruthborn','Player Workshop','Austin','Retired & Deceased'],
|
||||
['Derrick','DabuNaeNae','Active Campaign','Derrick'],
|
||||
['Micah','Sothok the Grim','Active Campaign','Micah'],
|
||||
['Steve','Badger Stouthands','Active Campaign','Steve'],
|
||||
['Jason','Jake the Hobo','DM Characters','Jason'],
|
||||
['Jason','Alyndra Arabella','DM Characters','Former Player Characters'],
|
||||
['Jason','Tekla Himmel','DM Characters','Former Player Characters']
|
||||
];
|
||||
export const PACKS = [
|
||||
['Homebrew – Community Items','player-homebrew-items','Item',true],
|
||||
['Homebrew – Community Creatures','player-homebrew-creatures','Actor',true],
|
||||
['Homebrew – DM Approved Items','dm-approved-homebrew-items','Item',false],
|
||||
['Homebrew – DM Approved Creatures','dm-approved-homebrew-creatures','Actor',false]
|
||||
];
|
||||
export const ENABLE = ['ACTOR_CREATE','ITEM_CREATE','FILES_BROWSE','FILES_UPLOAD','TOKEN_CONFIGURE','JOURNAL_CREATE','TOKEN_CREATE','TOKEN_DELETE'];
|
||||
export const DISABLE = ['REGION_CREATE','PLAYLIST_CREATE','MANUAL_ROLLS','SETTINGS_MODIFY'];
|
||||
const clone = x => JSON.parse(JSON.stringify(x));
|
||||
const values = c => Array.from(c.values());
|
||||
const parentId = f => f.folder?.id ?? f.toObject().folder ?? null;
|
||||
const equal = (a,b) => JSON.stringify(Object.entries(a).sort()) === JSON.stringify(Object.entries(b).sort());
|
||||
export function lookup(game,type,path) {
|
||||
let parent = null, folder = null;
|
||||
for(const name of path) {
|
||||
const hits = values(game.folders).filter(f=>f.type===type && f.name===name && parentId(f)===parent);
|
||||
if(hits.length>1) throw Error(`Ambiguous folder: ${type}/${path.join('/')}`);
|
||||
if(!hits.length) return null;
|
||||
folder=hits[0]; parent=folder.id;
|
||||
}
|
||||
return folder;
|
||||
}
|
||||
export function exact(collection,name) {
|
||||
const hits=values(collection).filter(d=>d.name===name);
|
||||
if(hits.length!==1) throw Error(`Expected exactly one '${name}', found ${hits.length}.`);
|
||||
return hits[0];
|
||||
}
|
||||
export function folderPlan(names=PLAYERS, campaign=true) {
|
||||
const out=[];
|
||||
function add(type,path) {
|
||||
for(let i=1;i<=path.length;i++) {
|
||||
const p=path.slice(0,i);
|
||||
if(!out.some(f=>f.type===type && JSON.stringify(f.path)===JSON.stringify(p)))out.push({type,path:p});
|
||||
}
|
||||
}
|
||||
if(campaign)for(const r of ROWS)add('Actor',r.slice(2));
|
||||
for(const n of names){
|
||||
for(const s of ['Test Characters','Backup Characters','Retired & Deceased'])add('Actor',['Player Workshop',n,s]);
|
||||
add('Item',['Player Homebrew Drafts',n]);
|
||||
}
|
||||
add('Compendium',['Player Homebrew']);
|
||||
return out;
|
||||
}
|
||||
export function desiredPermissions(current, constants, scriptPolicy='preserve') {
|
||||
const macro=constants.USER_PERMISSIONS.MACRO_SCRIPT?'MACRO_SCRIPT':constants.USER_PERMISSIONS.SCRIPT_MACRO?'SCRIPT_MACRO':null;
|
||||
const enable=[...ENABLE,...(macro&&scriptPolicy==='enable'?[macro]:[])],disable=[...DISABLE,...(macro&&scriptPolicy==='disable'?[macro]:[])];
|
||||
const result=clone(current), roles=constants.USER_ROLES;
|
||||
for(const key of [...enable,...disable]) {
|
||||
const def=constants.USER_PERMISSIONS[key];
|
||||
if(!def || !Array.isArray(result[key]) || !result[key].every(Number.isInteger)) throw Error(`Unexpected permission format: ${key}`);
|
||||
const set=new Set(result[key]);
|
||||
for(const role of [roles.PLAYER,roles.TRUSTED])enable.includes(key)?set.add(role):set.delete(role);
|
||||
for(const role of def.requiredRoles ?? [])set.add(role);
|
||||
result[key]=[...set].sort((a,b)=>a-b);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
export function packOwnership(shared) {return {PLAYER:shared?'OWNER':'OBSERVER',TRUSTED:shared?'OWNER':'OBSERVER',ASSISTANT:'OWNER',GAMEMASTER:'OWNER'};}
|
||||
export function preflight(game,constants,{campaign=true,scriptPolicy="preserve"}={}) {
|
||||
const roles=constants.USER_ROLES;
|
||||
if(game.user.role!==roles.GAMEMASTER) throw Error('Sign in as Gamemaster (not Assistant GM).');
|
||||
if(game.release.generation!==14 || game.system.id!=='dnd5e')throw Error('Requires Foundry v14 and dnd5e.');
|
||||
const names=campaign?PLAYERS:playerNames(game,constants);
|
||||
const users=Object.fromEntries(names.map(n=>[n,exact(game.users,n)]));
|
||||
if(campaign){
|
||||
users.Jason=exact(game.users,'Jason');
|
||||
for(const n of PLAYERS)if(users[n].role!==(n==='Austin'?roles.TRUSTED:roles.PLAYER))throw Error(`Check User Management: unexpected role for ${n}.`);
|
||||
if(users.Jason.role!==roles.ASSISTANT)throw Error('Check Jason’s Assistant GM role.');
|
||||
}
|
||||
const folders=folderPlan(names,campaign);
|
||||
for(const f of folders)lookup(game,f.type,f.path);
|
||||
const actors=campaign?ROWS.map(([name,actor,...path])=>({name,actor:exact(game.actors,actor),path,ownership:{default:0,[users[name].id]:3,[users.Jason.id]:3}})):[];
|
||||
for(const [label,id,type] of PACKS) {
|
||||
const p=game.packs.get(`world.${id}`);
|
||||
if(p && (p.title!==label || p.documentName!==type))throw Error(`Pack ID collision: world.${id}`);
|
||||
if(values(game.packs).some(other=>other.title===label && other.collection!==`world.${id}`))throw Error(`Pack label collision: ${label}`);
|
||||
}
|
||||
const permissions=desiredPermissions(game.permissions,constants,scriptPolicy);
|
||||
return {users,folders,actors,permissions,names,scriptPolicy};
|
||||
}
|
||||
export function playerNames(game,constants) {
|
||||
const names=values(game.users).filter(u=>[constants.USER_ROLES.PLAYER,constants.USER_ROLES.TRUSTED].includes(u.role)).map(u=>u.name);
|
||||
if(new Set(names).size!==names.length)throw Error("Duplicate player names; rename before setup.");
|
||||
if(new Set(names.map(safeName)).size!==names.length)throw Error("Player artwork folder names collide; rename before setup.");
|
||||
return names;
|
||||
}
|
||||
export function safeName(n){return String(n).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,80)||"Player";}
|
||||
export function artPaths(worldId,names=PLAYERS) {
|
||||
if(!/^[a-zA-Z0-9_-]+$/.test(worldId))throw Error('Unexpected world ID; artwork setup stopped.');
|
||||
const root=`worlds/${worldId}/PlayerAssets`;
|
||||
return [root,...names.map(safeName).flatMap(n=>[`${root}/${n}`,...['Portraits','Tokens','Homebrew'].map(s=>`${root}/${n}/${s}`)])];
|
||||
}
|
||||
function normalizePath(path){return decodeURI(String(path)).replace(/^\/+|\/+$/g,'');}
|
||||
export async function directoryExists(picker,path) {
|
||||
const parent=path.slice(0,path.lastIndexOf('/'));
|
||||
const result=await picker.browse('data',parent);
|
||||
if(!Array.isArray(result?.dirs))throw Error(`Cannot list artwork directory ${parent}`);
|
||||
return result.dirs.some(d=>normalizePath(d)===normalizePath(path));
|
||||
}
|
||||
export async function applyPlan(game,constants,api,plan,log) {
|
||||
const {Folder,Compendium,Picker}=api;
|
||||
for(const f of plan.folders) {
|
||||
if(lookup(game,f.type,f.path))continue;
|
||||
const parent=f.path.length>1?lookup(game,f.type,f.path.slice(0,-1)):null;
|
||||
if(f.path.length>1 && !parent)throw Error('Parent folder missing');
|
||||
await Folder.create({name:f.path.at(-1),type:f.type,folder:parent?.id??null});
|
||||
if(!lookup(game,f.type,f.path))throw Error(`Folder verification failed: ${f.path.join('/')}`);
|
||||
log.push(`Created folder ${f.type}/${f.path.join('/')}`);
|
||||
}
|
||||
for(const {actor,path,ownership} of plan.actors) {
|
||||
const folder=lookup(game,'Actor',path);
|
||||
const current=actor.toObject().ownership ?? {};
|
||||
if(actor.folder?.id===folder.id && equal(current,ownership))continue;
|
||||
const patch={folder:folder.id};
|
||||
for(const key of Object.keys(current))if(!(key in ownership))patch[`ownership.-=${key}`]=null;
|
||||
for(const [key,level] of Object.entries(ownership))patch[`ownership.${key}`]=level;
|
||||
await actor.update(patch);
|
||||
if(actor.folder?.id!==folder.id || !equal(actor.toObject().ownership,ownership))throw Error(`Actor ownership/folder verification failed: ${actor.name}`);
|
||||
log.push(`Organized ${actor.name}`);
|
||||
}
|
||||
const cf=lookup(game,'Compendium',['Player Homebrew']);
|
||||
for(const [label,id,type,shared] of PACKS) {
|
||||
let pack=game.packs.get(`world.${id}`);
|
||||
if(!pack){pack=await Compendium.createCompendium({label,name:id,type,package:'world',system:game.system.id});log.push(`Created pack ${label}`);}
|
||||
if(pack?.collection!==`world.${id}` || pack.documentName!==type)throw Error(`Unexpected pack identity: ${label}`);
|
||||
const ownership=packOwnership(shared);
|
||||
if(pack.locked===shared || !equal(pack.ownership,ownership)){await pack.configure({locked:!shared,ownership});log.push(`Configured ${label}`);}
|
||||
if(pack.folder?.id!==cf.id){await pack.setFolder(cf.id);log.push(`Filed ${label}`);}
|
||||
if(pack.locked!==!shared || !equal(pack.ownership,ownership) || pack.folder?.id!==cf.id)throw Error(`Pack verification failed: ${label}`);
|
||||
}
|
||||
for(const path of artPaths(game.world.id,plan.names)){
|
||||
if(await directoryExists(Picker,path))continue;
|
||||
const result=await Picker.createDirectory('data',path);
|
||||
if(result?.error || !await directoryExists(Picker,path))throw Error(`Could not create ${path}`);
|
||||
log.push(`Created artwork directory ${path}`);
|
||||
}
|
||||
const updated=desiredPermissions(game.permissions,constants,plan.scriptPolicy);
|
||||
if(!equal(game.permissions,updated)){
|
||||
await game.settings.set('core','permissions',updated);
|
||||
log.push('Updated player role permissions');
|
||||
const saved=game.settings.get('core','permissions');
|
||||
for(const k of [...ENABLE,...DISABLE])if(JSON.stringify(saved[k]?.slice().sort())!==JSON.stringify(updated[k].slice().sort()))throw Error(`Permission verification failed: ${k}`);
|
||||
}
|
||||
}
|
||||
// Convenience only: no server-side ACL enforcement. World documents only.
|
||||
export function routeNew(game,doc,data,options,userId) {
|
||||
if(!game.settings.get(ID,'routing') || game.user.id!==userId || game.user.isGM)return;
|
||||
if(doc.parent || doc.pack || options?.pack || data?.folder || doc.folder)return;
|
||||
if(doc.documentName!=='Actor' && doc.documentName!=='Item')return;
|
||||
if(doc.documentName==='Actor' && doc.type!=='character')return;
|
||||
const path=doc.documentName==='Actor'?['Player Workshop',game.user.name,'Test Characters']:['Player Homebrew Drafts',game.user.name];
|
||||
const folder=lookup(game,doc.documentName,path);
|
||||
if(folder)doc.updateSource({folder:folder.id, ...(data?.ownership?{}:{ownership:{default:0,[game.user.id]:3}})});
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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)=>`<ul>${items.map(x=>`<li>${esc(x)}</li>`).join('')}</ul>`;
|
||||
const html=`<p><strong>World:</strong> ${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.</p><details open><summary>Character moves and ownership (${plan.actors.length} actors)</summary>${list(plan.actors.map(a=>`${a.actor.name}: ${a.actor.folder?.name??'(root)'} → ${a.path.join('/')} | owner ${a.name}; Jason retains owner; other player access removed`))}</details><details><summary>Folders (${plan.folders.length})</summary>${list(plan.folders.map(f=>`${lookup(game,f.type,f.path)?'Reuse':'Create'} ${f.type}/${f.path.join('/')}`))}</details><details><summary>Homebrew packs (4)</summary>${list(PACKS.map(p=>`${p[0]}: ${p[3]?'both player roles can edit':'players read only'}`))}</details><details><summary>Artwork directories (${paths.length})</summary>${list(paths)}</details><details><summary>Permissions</summary>${list([...ENABLE.map(k=>`Enable ${k}`),...DISABLE.map(k=>`Disable ${k}`)])}</details><p>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.</p>`;
|
||||
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:`<p>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.</p><details><summary>Change log</summary>${list(log)}</details>`,ok:{label:'Close'},rejectClose:false});
|
||||
}catch(error){console.error(`${ID}: setup stopped`,log,error);ui.notifications.error(`Player Workshop stopped: ${error.message}. ${log.length} completed steps; check console. No automatic rollback.`);}
|
||||
finally{busy=false;}
|
||||
}
|
||||
Hooks.once('init',()=>{
|
||||
if(game.release.generation!==14 || game.system.id!=='dnd5e')return;
|
||||
game.settings.register(ID,'routing',{name:'Automatically file new personal characters and homebrew',hint:'Routes root-level new world characters and items for provisioned players. Existing documents and explicit folder selections are not moved.',scope:'world',config:true,type:Boolean,default:false,restricted:true});
|
||||
game.settings.register(ID,'scriptPolicy',{name:'Player script macro policy',hint:'Applied only when setup runs. Preserve existing settings by default; enable or disable explicitly after checking your automation.',scope:'world',config:true,type:String,choices:{preserve:'Preserve current permissions',enable:'Enable for players',disable:'Disable for players'},default:'preserve',restricted:true});
|
||||
class WorkshopMenu extends foundry.applications.api.DialogV2 {
|
||||
constructor(options={}){super({...options,window:{title:'Player Workshop'},content:'<p>Prepare your existing campaign for player-owned characters, homebrew and artwork. Review every proposed change before applying.</p><p>Sign in as Gamemaster. Back up your world first.</p>',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:'<p>Manage and export your owned content.</p>',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);
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import {zip,unzip,parseJSON,MAX_BYTES} from './archive.mjs';
|
||||
export const FORMAT='player-workshop-vault/1';
|
||||
const copy=x=>JSON.parse(JSON.stringify(x));
|
||||
export const IMAGE=/\.(png|jpe?g|webp|gif|avif)$/i;
|
||||
export function walk(x,fn){if(typeof x==='string')return fn(x);if(Array.isArray(x))return x.map(y=>walk(y,fn));if(x&&typeof x==='object'){for(const k of Object.keys(x))x[k]=walk(x[k],fn);}return x;}
|
||||
export function own(doc,user){return !!doc&&!doc.parent&&!doc.pack&&(doc.toObject().ownership?.[user.id]===3);}
|
||||
export function snapshot(doc){const d=copy(doc.toObject());delete d.folder;delete d.ownership; if(d._stats){delete d._stats.createdTime;delete d._stats.modifiedTime;delete d._stats.lastModifiedBy;}return {kind:doc.documentName,uuid:doc.uuid,data:d};}
|
||||
export function cleanImport(data,userId,newId){const d=copy(data);d._id=newId;d.folder=null;d.ownership={default:0,[userId]:3};delete d._stats;if(d.flags?.['player-workshop'])delete d.flags['player-workshop'];return d;}
|
||||
export function replaceRefs(s,map){if(map.has(s))return map.get(s);return s.replace(/\b(?:Actor|Item)\.[A-Za-z0-9]{16}(?=\.|\b)/g,m=>map.get(m)??m);}
|
||||
export async function makeArchive({docs,assets=[],canBundle,readAsset,metadata}){const records=docs.map(snapshot),files=new Map(),paths=new Set(assets),warnings=[];if(records.length>250)throw Error('Export at most 250 documents at a time');for(const r of records)walk(r.data,s=>{if(IMAGE.test(s))paths.add(s);return s;});const bundled=[];let total=0;for(const path of paths){if(!canBundle(path)){warnings.push(`External image retained: ${path}`);continue;}try{const b=await readAsset(path);if(!b?.byteLength||total+b.byteLength>MAX_BYTES-1024*1024)throw Error('size limit');const ext=path.match(IMAGE)?.[1]?.toLowerCase();if(!ext)continue;const name=`art/${bundled.length}.${ext}`;files.set(name,new Uint8Array(b));bundled.push({path,name});total+=b.byteLength;}catch(e){warnings.push(`Image not bundled: ${path} (${e.message})`);}}const manifest={format:FORMAT,...metadata,records,assets:bundled,warnings};files.set('manifest.json',JSON.stringify(manifest,null,2));for(const [i,r] of records.entries())files.set(`documents/${i}-${r.kind}.json`,JSON.stringify(r.data,null,2));return {blob:zip(files),warnings};}
|
||||
export function readArchive(buffer){const files=unzip(buffer),m=parseJSON(files.get('manifest.json'));if(!m||m.format!==FORMAT||m.system!=='dnd5e'||!Array.isArray(m.records)||m.records.length>250||!Array.isArray(m.assets)||m.assets.length>1000)throw Error('Unsupported vault format');const ids=new Set(),paths=new Set(),assetNames=new Set();for(const r of m.records){if(!['Actor','Item'].includes(r.kind)||!r.data||typeof r.data.name!=='string'||!r.data.type||typeof r.uuid!=='string'||!new RegExp(`^${r.kind}\\.[A-Za-z0-9]{16}$`).test(r.uuid)||ids.has(r.uuid))throw Error('Invalid or duplicate document');ids.add(r.uuid);}for(const a of m.assets){if(typeof a.path!=='string'||!/^art\/\d+\.(png|jpe?g|webp|gif|avif)$/i.test(a.name)||!files.has(a.name)||paths.has(a.path)||assetNames.has(a.name)||files.get(a.name).length>16*1024*1024||!files.get(a.name).length)throw Error('Invalid asset');paths.add(a.path);assetNames.add(a.name);}return {manifest:m,files};}
|
||||
@@ -0,0 +1,27 @@
|
||||
import {ID,lookup,safeName,PACKS} from './core.mjs';
|
||||
import {own,snapshot,cleanImport,walk,replaceRefs,makeArchive,readArchive,IMAGE} from './portable.mjs';
|
||||
const dialog=()=>foundry.applications.api.DialogV2;
|
||||
const picker=()=>foundry.applications.apps.FilePicker;
|
||||
const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const random=()=>foundry.utils.randomID();
|
||||
const root=()=>`worlds/${game.world.id}/PlayerAssets/${safeName(game.user.name)}`;
|
||||
const types=['Portraits','Tokens','Homebrew'];
|
||||
const folders=(kind)=>kind==='Actor'?['Player Workshop',game.user.name,'Test Characters']:['Player Homebrew Drafts',game.user.name];
|
||||
function owned(){return [...game.actors,...game.items].filter(d=>own(d,game.user));}
|
||||
function getDoc(uuid){const [kind,id]=String(uuid).split('.');const d=(kind==='Actor'?game.actors:kind==='Item'?game.items:null)?.get(id);if(!own(d,game.user))throw Error('You must explicitly own this world document.');return d;}
|
||||
function options(arr){return arr.map(([v,label])=>`<option value="${esc(v)}">${esc(label)}</option>`).join('');}
|
||||
const field=(label,name,opts)=>`<div class="form-group"><label>${esc(label)}</label><select name="${name}">${options(opts)}</select></div>`;
|
||||
async function ask(title,html,read,label='Continue'){return dialog().prompt({window:{title},position:{width:560},content:html,ok:{label,callback:(_event,_button,d)=>read(d.element)},rejectClose:false});}
|
||||
const select=(el,n)=>el.querySelector(`[name="${n}"]`)?.value;
|
||||
function download(blob,name){const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=name;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),30000);}
|
||||
function localPath(s){try{const p=decodeURI(s);return !/[:?#\\]/.test(p)&&!p.startsWith('/')&&!p.split('/').some(x=>x==='.'||x==='..')?p:null;}catch{return null;}}
|
||||
async function listArt(){const out=[];for(const sub of types){try{const r=await picker().browse('data',`${root()}/${sub}`);for(const p of r.files??[])if(IMAGE.test(p)&&localPath(p)?.startsWith(`${root()}/${sub}/`))out.push(p);}catch(e){console.warn(ID,'Art directory not available',sub,e);}}return out;}
|
||||
async function upload(file,sub){if(!types.includes(sub)||!IMAGE.test(file.name)||!file.size||file.size>16*1024*1024)throw Error('Use an image (PNG/JPG/WebP/GIF/AVIF), maximum 16 MiB.');const ext=file.name.match(IMAGE)[1].toLowerCase(),name=`${random()}.${ext}`;const result=await picker().upload('data',`${root()}/${sub}`,new File([file],name,{type:file.type}),{}, {notify:false});if(result?.error||!result?.path)throw Error(result?.error??'File upload did not return a path. Ask the GM to run Workshop setup.');return result.path;}
|
||||
async function artwork(){const files=await listArt();const docs=owned();const rows=files.map(p=>`<option value="${esc(p)}">${esc(p.split('/').at(-2)+' / '+p.split('/').at(-1))}</option>`).join('');const data=await ask('My Artwork',`<p>Upload new images or assign an existing personal image. Files stay on the server when unassigned. Tokenizer can still be opened from the normal actor sheet.</p><div class="form-group"><label>Image file</label><input type="file" name="upload" accept="image/png,image/jpeg,image/webp,image/gif,image/avif"></div>${field('Folder','sub',types.map(t=>[t,t]))}<div class="form-group"><label>Existing image</label><select name="existing"><option value="">None</option>${rows}</select></div>${field('Action','action',[['upload','Upload only'],['portrait','Assign portrait / item image'],['token','Assign prototype token'],['download','Download existing image']])}${field('My document','doc',[['','None'],...docs.map(d=>[d.uuid,d.name])])}`,el=>({file:el.querySelector('input[type=file]').files[0],sub:select(el,'sub'),existing:select(el,'existing'),action:select(el,'action'),doc:select(el,'doc')}));if(!data)return;const d=['portrait','token'].includes(data.action)?getDoc(data.doc):null;if(data.action==='token'&&d.documentName!=='Actor')throw Error('Token artwork requires an actor.');const path=data.file?await upload(data.file,data.sub):data.existing;if(!path)throw Error('Choose an image.');if(data.action==='download'){const r=await fetch(path,{credentials:'same-origin'});if(!r.ok)throw Error('Image could not be downloaded.');download(await r.blob(),path.split('/').at(-1));}else if(d){await d.update(data.action==='token'?{'prototypeToken.texture.src':path,'prototypeToken.randomImg':false}:{img:path});}ui.notifications.info('Artwork action complete.');}
|
||||
async function exportVault(all){const docs=owned();const selection=all?await ask('Export entire vault','<p>Export all explicitly owned world actors, items and personal artwork. External licensed assets are not bundled.</p><label><input type="checkbox" name="other"> Include other referenced local images that I have rights to transfer (not system/module assets).</label>',el=>({docs,allArt:true,other:el.querySelector('[name=other]').checked}),'Export ZIP'):await ask('Export personal content',`${field('Document','doc',docs.map(d=>[d.uuid,`${d.documentName}: ${d.name}`]))}<label><input type="checkbox" name="other"> Include other local image files referenced by this document that I have rights to transfer (not system/module assets).</label><p>Embedded spells, inventory and features are included. External sources and linked documents may still require the original compendiums.</p>`,el=>({docs:[getDoc(select(el,'doc'))],allArt:false,other:el.querySelector('[name=other]').checked}),'Export ZIP');if(!selection)return;const selected=selection.docs;if(!selected.length&&!selection.allArt)throw Error('No documents selected');const {blob,warnings}=await makeArchive({docs:selected,assets:selection.allArt?await listArt():[],canBundle:s=>{const p=localPath(s);return !!p&&(p.startsWith(root()+'/')||(selection.other&&!/^(modules|systems|icons|ui|fonts)\//i.test(p)));},readAsset:async s=>{const r=await fetch(s,{credentials:'same-origin',redirect:'error'});if(!r.ok)throw Error(`HTTP ${r.status}`);if(Number(r.headers.get('content-length'))>16*1024*1024)throw Error('Image too large');const b=await r.arrayBuffer();if(b.byteLength>16*1024*1024)throw Error('Image too large');return b;},metadata:{system:game.system.id,systemVersion:game.system.version,foundry:game.version,exported:new Date().toISOString(),requiredModules:[...game.modules.values()].filter(m=>m.active&&m.id!==ID).map(m=>({id:m.id,version:m.version}))}});download(blob,`${safeName(all?game.user.name+'-vault':selected[0].name)}.zip`);ui.notifications.info(`Export complete. ${warnings.length} image references not bundled; see manifest.`);}
|
||||
async function nativeExport(){const docs=owned();if(!docs.length)throw Error('No personal documents to export.');const id=await ask('Export Foundry JSON',field('Document','doc',docs.map(d=>[d.uuid,`${d.documentName}: ${d.name}`]))+'<p>Standard Foundry JSON can be imported in another world without Player Workshop. Artwork and external dependencies are not bundled.</p>',el=>select(el,'doc'),'Export JSON');if(id){const d=getDoc(id);await d.exportToJSON();}}
|
||||
async function importVault(){const file=await ask('Import personal vault',`<p>Import a ZIP previously created by Player Workshop. New copies will be created; nothing is overwritten. Import only archives you trust. Embedded effects and module data may execute in the destination system. GM must allow document creation and uploads.</p><input type="file" accept=".zip,application/zip" name="archive">`,el=>el.querySelector('input[type=file]').files[0],'Inspect archive');if(!file)return;if(file.size>65*1024*1024)throw Error('Archive too large');const {manifest:m,files}=readArchive(await file.arrayBuffer());const missing=(m.requiredModules??[]).filter(x=>!game.modules.get(x.id)?.active).map(x=>x.id);const versionMismatch=m.systemVersion!==game.system.version;const warnings=Array.isArray(m.warnings)?m.warnings:[];if(!await dialog().confirm({window:{title:'Confirm import'},content:`<p>${m.records.length} new documents; ${m.assets.length} images. Original system: ${esc(m.systemVersion)}; current: ${esc(game.system.version)}.</p>${versionMismatch?'<p><strong>System version differs; compatibility is not guaranteed.</strong></p>':''}<p>Source-world modules not active here (informational, not required): ${esc(missing.join(', ')||'None')}</p><p>${warnings.length} original image warnings. External compendium and unselected document references may remain unresolved. Imports go to your personal workshop or the world root if no workshop exists.</p>`,rejectClose:false}))return;const map=new Map();for(const r of m.records)map.set(r.uuid,`${r.kind}.${random()}`);for(const a of m.assets){const ext=a.name.split('.').at(-1);const b=files.get(a.name);const p=await upload(new File([b],`import.${ext}`,{type:`image/${ext==='jpg'?'jpeg':ext}`}), 'Homebrew');map.set(a.path,p);}const created=[];try{for(const r of [...m.records].sort((a,b)=>Number(a.kind==='Actor')-Number(b.kind==='Actor'))){const id=map.get(r.uuid).split('.')[1];const data=walk(cleanImport(r.data,game.user.id,id),s=>replaceRefs(s,map));data.folder=lookup(game,r.kind,folders(r.kind))?.id??null;const d=await CONFIG[r.kind].documentClass.create(data,{keepId:true,keepEmbeddedIds:true});if(!d||d.id!==id||!own(d,game.user))throw Error(`Could not verify ownership/ID for ${r.data.name}`);created.push(d.name);}}catch(e){throw Error(`Import stopped after ${created.length} document(s). Uploaded files and completed copies remain. ${e.message}`);}ui.notifications.info(`Imported ${created.length} document(s). Review character sheets and source references.`);}
|
||||
async function publish(){const docs=owned().filter(d=>d.documentName==='Item'||d.type==='npc');if(!docs.length)throw Error('Create a world Item or NPC first.');const choice=await ask('Publish homebrew',`${field('Original','doc',docs.map(d=>[d.uuid,d.name]))}<div class="form-group"><label>Version</label><input name="version" value="1.0" maxlength="40"></div><p>Creates a new community copy. Your original stays private and editable. Community packs are collaborative; the DM can approve a separate snapshot. Only publish content you may share.</p>`,el=>({doc:select(el,'doc'),version:el.querySelector('[name=version]').value}),'Publish copy');if(!choice)return;const d=getDoc(choice.doc),pack=game.packs.get(`world.player-homebrew-${d.documentName==='Item'?'items':'creatures'}`);if(!pack||pack.locked)throw Error('Community pack is missing or locked. Ask GM to run setup.');const data=cleanImport(snapshot(d).data,game.user.id,random());data.ownership={default:2,[game.user.id]:3};data.flags??={};data.flags[ID]={homebrew:true,author:game.user.name,authorId:game.user.id,version:choice.version||'1.0',status:'published',original:d.uuid};if(data.system?.source&&typeof data.system.source==='object')data.system.source.book='Homebrew';const out=await CONFIG[d.documentName].documentClass.create(data,{pack:pack.collection,keepId:true,keepEmbeddedIds:true});if(!out)throw Error('Publication failed.');ui.notifications.info(`Published ${out.name}; your original is unchanged.`);}
|
||||
async function approve(){if(game.user.role!==CONST.USER_ROLES.GAMEMASTER)throw Error('Gamemaster only');const packs=PACKS.filter(p=>p[3]).map(p=>game.packs.get(`world.${p[1]}`)).filter(Boolean);const entries=[];for(const p of packs)for(const d of await p.getDocuments())entries.push(d);if(!entries.length)throw Error('No published homebrew found.');const uuid=await ask('Approve homebrew',field('Community creation','doc',entries.map(d=>[d.uuid,`${d.name} (${d.documentName})`]))+'<p>Creates a locked approved copy; community content stays available to all characters.</p>',el=>select(el,'doc'),'Approve copy');if(!uuid)return;const source=entries.find(d=>d.uuid===uuid);const pack=game.packs.get(`world.dm-approved-homebrew-${source.documentName==='Item'?'items':'creatures'}`);if(!pack)throw Error('Approved pack missing');const data=cleanImport(source.toObject(),game.user.id,random());data.ownership={default:2};data.flags??={};data.flags[ID]={...(source.getFlag(ID,'homebrew')?source.flags[ID]:{}),homebrew:true,status:'approved',approvedBy:game.user.name,communitySource:source.uuid};const was=pack.locked;try{if(was)await pack.configure({locked:false});const out=await CONFIG[source.documentName].documentClass.create(data,{pack:pack.collection,keepId:true,keepEmbeddedIds:true});if(!out)throw Error('Approval failed');}finally{if(was)await pack.configure({locked:true});}ui.notifications.info('Approved homebrew copy created.');}
|
||||
async function move(){const docs=owned().filter(d=>d.documentName==='Actor');const v=await ask('Organize my characters',field('Character','doc',docs.map(d=>[d.uuid,d.name]))+field('Destination','dest',['Test Characters','Backup Characters','Retired & Deceased'].map(x=>[x,x])),el=>({doc:select(el,'doc'),dest:select(el,'dest')}),'Move');if(!v)return;const d=getDoc(v.doc);if(!['Test Characters','Backup Characters','Retired & Deceased'].includes(v.dest))throw Error('Invalid folder');const f=lookup(game,'Actor',['Player Workshop',game.user.name,v.dest]);if(!f)throw Error('Ask GM to provision your workshop.');await d.update({folder:f.id});}
|
||||
export async function openVault(){const docs=owned();const list=docs.map(d=>`<li>${esc(d.name)} — ${esc(d.documentName)} (${esc(d.folder?.name??'root')})</li>`).join('');const action=await dialog().wait({window:{title:'Player Vault — '+game.user.name},position:{width:660},content:`<p>Personal ownership: ${docs.filter(d=>d.documentName==='Actor').length} actors, ${docs.filter(d=>d.documentName==='Item').length} items.</p><details><summary>My documents</summary><ul>${list}</ul></details><p>Homebrew is available to all characters. DM approval is a campaign convention, not a sheet lock. Shared copies may be edited by the community.</p>`,buttons:[['open','Open my document'],['move','Organize characters'],['art','My artwork'],['publish','Publish homebrew'],['json','Export Foundry JSON'],['one','Export one ZIP'],['all','Export vault ZIP'],['import','Import vault'],...(game.user.role===CONST.USER_ROLES.GAMEMASTER?[['approve','Approve homebrew']]:[]),['close','Close']].map(([action,label])=>({action,label,callback:()=>action})),rejectClose:false});try{switch(action){case 'open':{if(!docs.length)throw Error('Create a character or item first.');const id=await ask('Open personal document',field('Document','doc',docs.map(d=>[d.uuid,d.name])),el=>select(el,'doc'),'Open');if(id)getDoc(id).sheet.render(true);break;}case 'move':await move();break;case 'art':await artwork();break;case 'publish':await publish();break;case 'json':await nativeExport();break;case 'one':await exportVault(false);break;case 'all':await exportVault(true);break;case 'import':await importVault();break;case 'approve':await approve();break;}}catch(e){console.error(ID,e);ui.notifications.error(`Player Workshop: ${e.message}`);}}
|
||||
@@ -0,0 +1,25 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {ID,PLAYERS,ROWS,PACKS,ENABLE,DISABLE,lookup,preflight,applyPlan,routeNew,artPaths,desiredPermissions} from '../scripts/core.mjs';
|
||||
function fixture(){
|
||||
const roles={PLAYER:1,TRUSTED:2,ASSISTANT:3,GAMEMASTER:4};
|
||||
const constants={USER_ROLES:roles,USER_PERMISSIONS:Object.fromEntries([...ENABLE,...DISABLE].map(k=>[k,{requiredRoles:[4]}]))};
|
||||
const users=new Map([...PLAYERS,'Jason','Gamemaster'].map((name,i)=>[name,{id:`u${i}`,name,role:name==='Austin'?2:name==='Jason'?3:name==='Gamemaster'?4:1}]));
|
||||
const folders=new Map(), packs=new Map(), actors=new Map();let seq=0;const mutations=[];
|
||||
const game={user:users.get('Gamemaster'),release:{generation:14},system:{id:'dnd5e'},world:{id:'the-phandelver'},users,folders,packs,actors,permissions:{...Object.fromEntries([...ENABLE,...DISABLE].map(k=>[k,[2,3,4]])),OTHER:[1,4]},settings:{get(ns,k){return ns===ID?true:game.permissions;},async set(ns,k,v){game.permissions=v;mutations.push(k);}}};
|
||||
const Folder={async create(data){const f={...data,id:`f${++seq}`,folder:folders.get(data.folder),toObject(){return {...data};}};folders.set(f.id,f);mutations.push('folder');return f;}};
|
||||
for(const [,name] of ROWS){const actor={id:`a${++seq}`,name,folder:null,ownership:{default:2,old:3},system:{hp:55},toObject(){return {ownership:{...this.ownership}};},async update(p){this.folder=folders.get(p.folder);for(const [k,v] of Object.entries(p)){if(k.startsWith('ownership.-='))delete this.ownership[k.slice(12)];else if(k.startsWith('ownership.'))this.ownership[k.slice(10)]=v;}mutations.push('actor');}};actors.set(actor.id,actor);}
|
||||
const official={title:'Official',collection:'dnd5e.official',locked:true,ownership:{PLAYER:'OBSERVER'}};packs.set(official.collection,official);
|
||||
const Compendium={async createCompendium({label,name,type}){const p={title:label,collection:`world.${name}`,documentName:type,locked:true,ownership:{},folder:null,async configure(c){Object.assign(this,c);mutations.push('configure');},async setFolder(id){this.folder=folders.get(id);mutations.push('file');}};packs.set(p.collection,p);mutations.push('pack');return p;}};
|
||||
const dirs=new Set(['worlds/the-phandelver']);
|
||||
const Picker={async browse(_source,path){if(!dirs.has(path))throw Error('missing directory');return {dirs:[...dirs].filter(d=>d.slice(0,d.lastIndexOf('/'))===path)};},async createDirectory(_source,path){assert(!dirs.has(path));dirs.add(path);mutations.push('dir');return {};}};
|
||||
return {game,constants,api:{Folder,Compendium,Picker},official,dirs,mutations};
|
||||
}
|
||||
test('preflight read-only; full apply; repeat makes zero mutations',async()=>{const f=fixture();const {game,constants,api,mutations}=f;const old=JSON.stringify(f.official);const active=await api.Folder.create({name:'Active Campaign',type:'Actor',folder:null});mutations.length=0;const plan=preflight(game,constants);assert.equal(mutations.length,0);await applyPlan(game,constants,api,plan,[]);assert.equal(lookup(game,'Actor',['Active Campaign']).id,active.id);assert.equal(game.packs.size,5);assert.equal(f.dirs.size,18);assert.equal(JSON.stringify(f.official),old);for(const row of plan.actors){assert.deepEqual(row.actor.ownership,row.ownership);assert.equal(row.actor.system.hp,55);}assert.deepEqual(game.permissions.OTHER,[1,4]);mutations.length=0;await applyPlan(game,constants,api,preflight(game,constants),[]);assert.deepEqual(mutations,[]);});
|
||||
test('missing or duplicate actor blocks before writes',()=>{const f=fixture();const actor=[...f.game.actors.values()][0];f.game.actors.delete(actor.id);assert.throws(()=>preflight(f.game,f.constants),/Expected exactly one/);f.game.actors.set(actor.id,actor);f.game.actors.set('dupe',{...actor,id:'dupe'});assert.throws(()=>preflight(f.game,f.constants),/found 2/);assert.equal(f.mutations.length,0);});
|
||||
test('wrong user role, system or core version blocks',()=>{const f=fixture();f.game.users.get('Austin').role=1;assert.throws(()=>preflight(f.game,f.constants),/Austin/);f.game.users.get('Austin').role=2;f.game.release.generation=13;assert.throws(()=>preflight(f.game,f.constants),/v14/);f.game.release.generation=14;f.game.user=f.game.users.get('Jason');assert.throws(()=>preflight(f.game,f.constants),/Gamemaster/);});
|
||||
test('pack collisions block before writes',()=>{const f=fixture();f.game.packs.set('world.player-homebrew-items',{title:'Different',documentName:'Item'});assert.throws(()=>preflight(f.game,f.constants),/collision/);assert.equal(f.mutations.length,0);});
|
||||
test('ambiguous folders block',async()=>{const f=fixture();for(let i=0;i<2;i++)await f.api.Folder.create({name:'Active Campaign',type:'Actor',folder:null});assert.throws(()=>preflight(f.game,f.constants),/Ambiguous/);});
|
||||
test('permissions preserve unrelated roles and keys, disable and enable both player roles',()=>{const f=fixture();const p=desiredPermissions(f.game.permissions,f.constants);for(const k of ENABLE)assert.deepEqual(p[k],[1,2,3,4]);for(const k of DISABLE)assert.deepEqual(p[k],[3,4]);assert.deepEqual(p.OTHER,[1,4]);});
|
||||
test('auto-file only root world character/item; skip explicit folders, embedded, compendium, NPC, GM',async()=>{const f=fixture();await applyPlan(f.game,f.constants,f.api,preflight(f.game,f.constants),[]);f.game.user=f.game.users.get('Austin');let result;const doc={documentName:'Actor',type:'character',updateSource(x){result=x;}};routeNew(f.game,doc,{}, {},f.game.user.id);assert.equal(result.folder,lookup(f.game,'Actor',['Player Workshop','Austin','Test Characters']).id);result=null;for(const [d,data,opt,uid] of [[doc,{folder:'other'},{},f.game.user.id],[{...doc,parent:{}},{},{},f.game.user.id],[{...doc,pack:'world.pack'},{},{},f.game.user.id],[{...doc,type:'npc'},{},{},f.game.user.id],[doc,{},{},'different']]){routeNew(f.game,d,data,opt,uid);assert.equal(result,null);}routeNew(f.game,{...doc,documentName:'Item'},{},{},f.game.user.id);assert.equal(result.folder,lookup(f.game,'Item',['Player Homebrew Drafts','Austin']).id);});
|
||||
test('unsafe world path rejected',()=>assert.throws(()=>artPaths('../evil'),/Unexpected/));
|
||||
@@ -0,0 +1,59 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {makeArchive} from '../scripts/portable.mjs';
|
||||
import {openVault} from '../scripts/vault.mjs';
|
||||
|
||||
test('vault import requests stable embedded IDs and remaps the actor in embedded UUIDs', async t => {
|
||||
const actorId = 'ABCDEFGHIJKLMNOP';
|
||||
const itemId = '1234567890abcdef';
|
||||
const newId = 'ZYXWVUTSRQPONMLK';
|
||||
const user = {id: 'recipient', name: 'Recipient', role: 1};
|
||||
const sourceActor = {
|
||||
documentName: 'Actor',
|
||||
uuid: `Actor.${actorId}`,
|
||||
toObject: () => ({
|
||||
_id: actorId,
|
||||
name: 'Hero',
|
||||
type: 'character',
|
||||
items: [{_id: itemId, name: 'Spell', type: 'spell'}],
|
||||
system: {details: {biography: {value: `@UUID[Actor.${actorId}.Item.${itemId}]{Spell}`}}}
|
||||
})
|
||||
};
|
||||
const {blob} = await makeArchive({docs: [sourceActor], metadata: {system: 'dnd5e', systemVersion: '6.1.2'}});
|
||||
const calls = [];
|
||||
const DialogV2 = {
|
||||
wait: async () => 'import',
|
||||
confirm: async () => true,
|
||||
prompt: async ({ok}) => ok.callback(null, null, {
|
||||
element: {querySelector: () => ({files: [blob]})}
|
||||
})
|
||||
};
|
||||
const create = async (data, options) => {
|
||||
calls.push({data, options});
|
||||
return {id: data._id, toObject: () => data};
|
||||
};
|
||||
const globals = {
|
||||
CONST: {USER_ROLES: {GAMEMASTER: 4}},
|
||||
CONFIG: {Actor: {documentClass: {create}}},
|
||||
game: {user, system: {version: '6.1.2'}, folders: new Map(), actors: [], items: []},
|
||||
foundry: {applications: {api: {DialogV2}}, utils: {randomID: () => newId}},
|
||||
ui: {notifications: {info: () => {}, error: message => assert.fail(message)}}
|
||||
};
|
||||
for (const [key, value] of Object.entries(globals)) {
|
||||
const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
|
||||
Object.defineProperty(globalThis, key, {value, configurable: true});
|
||||
t.after(() => {
|
||||
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
||||
else delete globalThis[key];
|
||||
});
|
||||
}
|
||||
|
||||
await openVault();
|
||||
|
||||
assert.equal(calls.length, 1);
|
||||
const [{data, options}] = calls;
|
||||
assert.deepEqual(options, {keepId: true, keepEmbeddedIds: true});
|
||||
assert.deepEqual(data.ownership, {default: 0, [user.id]: 3});
|
||||
assert.equal(data.items[0]._id, itemId);
|
||||
assert.equal(data.system.details.biography.value, `@UUID[Actor.${newId}.Item.${itemId}]{Spell}`);
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {zip,unzip,parseJSON} from '../scripts/archive.mjs';
|
||||
import {own,snapshot,cleanImport,replaceRefs,makeArchive,readArchive} from '../scripts/portable.mjs';
|
||||
const uid='user1', id='ABCDEFGHIJKLMNOP', iid='1234567890abcdef';
|
||||
const actor={uuid:`Actor.${id}`,documentName:'Actor',toObject:()=>({_id:id,name:'Hero',type:'character',ownership:{default:0,[uid]:3},folder:'a',img:'worlds/demo/PlayerAssets/Me/Portraits/hero.webp',items:[{_id:iid,name:'Spell',type:'spell'}],system:{details:{note:`@UUID[Item.${iid}]{Custom}`}}})};
|
||||
test('ownership only explicitly owned world documents',()=>{assert(own(actor,{id:uid}));assert(!own(actor,{id:'other'}));assert(!own({...actor,pack:'world.pack'},{id:uid}));assert(!own({...actor,parent:{}},{id:uid}));});
|
||||
test('snapshot preserves embedded data, removes source ownership; import reassigns owner',()=>{const snap=snapshot(actor);assert.equal(snap.data.items[0]._id,iid);assert(!('ownership' in snap.data));assert(!('folder' in snap.data));const data=cleanImport(snap.data,'new-user','new-id');assert.deepEqual(data.ownership,{default:0,'new-user':3});assert.equal(data._id,'new-id');});
|
||||
test('ZIP archive round trip with bundled art and separate JSON',async()=>{const {blob,warnings}=await makeArchive({docs:[actor],canBundle:()=>true,readAsset:async()=>new Uint8Array([1,2,3]).buffer,metadata:{system:'dnd5e',systemVersion:'6.1.2'}});assert.equal(warnings.length,0);const {manifest,files}=readArchive(await blob.arrayBuffer());assert.equal(manifest.records[0].uuid,actor.uuid);assert.equal(manifest.assets.length,1);assert.deepEqual([...files.get('art/0.webp')],[1,2,3]);assert.equal(parseJSON(files.get('documents/0-Actor.json')).name,'Hero');});
|
||||
test('external art reported; source references remapped',async()=>{const {blob,warnings}=await makeArchive({docs:[actor],canBundle:()=>false,readAsset:async()=>{throw Error('should not read');},metadata:{system:'dnd5e'}});assert.equal(warnings.length,1);assert.equal(readArchive(await blob.arrayBuffer()).manifest.assets.length,0);assert.equal(replaceRefs(`@UUID[Item.${iid}]{Custom}`,new Map([[`Item.${iid}`,'Item.NEW']])), '@UUID[Item.NEW]{Custom}');});
|
||||
test('bad paths, corrupted CRC and prototype keys rejected',async()=>{assert.throws(()=>zip(new Map([['../bad','bad']])),/Unsafe/);const b=new Uint8Array(await zip(new Map([['manifest.json','abc']])).arrayBuffer());b[30+'manifest.json'.length]^=1;assert.throws(()=>unzip(b),/CRC/);assert.throws(()=>parseJSON(new TextEncoder().encode('{"__proto__":{"x":1}}')),/Unsafe/);});
|
||||
test('duplicate record or invalid archive format blocked',async()=>{const snap=snapshot(actor),m={format:'player-workshop-vault/1',system:'dnd5e',records:[snap,snap],assets:[]};const b=await zip(new Map([['manifest.json',JSON.stringify(m)]])).arrayBuffer();assert.throws(()=>readArchive(b),/duplicate/);});
|
||||
Reference in new issue
Block a user