Anything in plain view is observed by you. If a creature takes measures to avoid detection, such as by using Stealth to @UUID[Compendium.pf2e.actionspf2e.Item.XMcnh4cSI32tljXa]{Hide}, it can become @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} or @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} instead of observed. If you have another precise sense instead of or in addition to sight, you might be able to observe a creature or object using that sense instead. You can observe a creature only with precise senses. When @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seeking} a creature using only imprecise senses, it remains hidden, rather than observed.
"},duration:{value:0},group:"detection",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"observed",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G"}},effects:[]},{_id:"3uh1r86TzbQvosxv",img:"systems/pf2e/icons/conditions/doomed.webp",name:"Doomed",system:{description:{value:`A powerful force has gripped your soul, calling you closer to death. Doomed always includes a value. The @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} value at which you die is reduced by your doomed value. If your maximum dying value is reduced to 0, you instantly die. When you die, you're no longer doomed.
-Your doomed value decreases by 1 each time you get a full night's rest.
`},duration:{value:0},group:"death",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"doomed",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.3uh1r86TzbQvosxv"}},effects:[]},{_id:"4D2KBtexWXa6oUMR",img:"systems/pf2e/icons/conditions/drained.webp",name:"Drained",system:{description:{value:`When a creature successfully drains you of blood or life force, you become less healthy. Drained always includes a value. You take a status penalty equal to your drained value on Constitution-based checks, such as Fortitude saves. You also lose a number of Hit Points equal to your level (minimum 1) times the drained value, and your maximum Hit Points are reduced by the same amount. For example, if you're hit by an effect that inflicts drained 3 and you're a 3rd-level character, you lose 9 Hit Points and reduce your maximum Hit Points by 9. Losing these Hit Points doesn't count as taking damage.
-Each time you get a full night's rest, your drained value decreases by 1. This increases your maximum Hit Points, but you don't immediately recover the lost Hit Points.
`},duration:{value:0},group:"abilities",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"con-based",slug:"drained",type:"status",value:"-1 * @item.badge.value"},{key:"FlatModifier",selector:"hp",slug:"drained",type:"status",value:"min(-1 * @actor.level,-1) * @item.badge.value"},{key:"LoseHitPoints",reevaluateOnUpdate:!0,value:"max(1,@actor.level) * @item.badge.value"}],value:{isValued:!0,value:1},slug:"drained",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.4D2KBtexWXa6oUMR"}},effects:[]},{_id:"6dNUvdb1dhToNDj3",img:"systems/pf2e/icons/conditions/broken.webp",name:"Broken",system:{description:{value:`Broken is a condition that affects objects. An object is broken when damage has reduced its Hit Points below its Broken Threshold. A broken object can't be used for its normal function, nor does it grant bonuses-with the exception of armor. Broken armor still grants its item bonus to AC, but it also imparts a status penalty to AC depending on its category: -1 for broken light armor, -2 for broken medium armor, or -3 for broken heavy armor.
-A broken item still imposes penalties and limitations normally incurred by carrying, holding, or wearing it. For example, broken armor would still impose its Dexterity modifier cap, check penalty, and so forth.
-If an effect makes an item broken automatically and the item has more HP than its Broken Threshold, that effect also reduces the item's current HP to the Broken Threshold.
`},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"broken",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.6dNUvdb1dhToNDj3"}},effects:[]},{_id:"6uEgoh53GbXuHpTF",img:"systems/pf2e/icons/conditions/paralyzed.webp",name:"Paralyzed",system:{description:{value:"Your body is frozen in place. You have the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} condition and can't act except to @UUID[Compendium.pf2e.actionspf2e.Item.1OagaWtBpVXExToo]{Recall Knowledge} and use actions that require only the use of your mind (as determined by the GM). Your senses still function, but only in the areas you can perceive without moving your body, so you can't @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} while paralyzed.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"paralyzed",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.6uEgoh53GbXuHpTF"}},effects:[]},{_id:"9evPzg9E6muFcoSk",img:"systems/pf2e/icons/conditions/unnoticed.webp",name:"Unnoticed",system:{description:{value:"If you are unnoticed by a creature, that creature has no idea you are present at all. When you're unnoticed, you're also @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} by the creature. This condition matters for abilities that can be used only against targets totally unaware of your presence.
"},duration:{value:0},group:"detection",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"unnoticed",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9evPzg9E6muFcoSk"}},effects:[]},{_id:"9PR9y0bi4JPKnHPR",img:"systems/pf2e/icons/conditions/deafened.webp",name:"Deafened",system:{description:{value:"You can't hear. You automatically critically fail Perception checks that require you to be able to hear. You take a -2 status penalty to Perception checks for initiative and checks that involve sound but also rely on other senses. If you perform an action with the auditory trait, you must succeed at a DC 5 flat check or the action is lost; attempt the check after spending the action but before any effects are applied. You are immune to auditory effects.
"},duration:{value:0},group:"senses",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"perception-initiative",slug:"deafened",type:"status",value:-2},{key:"Immunity",type:"auditory"}],value:{isValued:!1,value:null},slug:"deafened",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR"}},effects:[]},{_id:"9qGBRpbX9NEwtAAr",img:"systems/pf2e/icons/conditions/controlled.webp",name:"Controlled",system:{description:{value:"Someone else is making your decisions for you, usually because you're being commanded or magically dominated. The controller dictates how you act and can make you use any of your actions, including attacks, reactions, or even @UUID[Compendium.pf2e.actionspf2e.Item.A72nHGUtNXgY5Ey9]{Delay}. The controller usually does not have to spend their own actions when controlling you.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"controlled",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9qGBRpbX9NEwtAAr"}},effects:[]},{_id:"AdPVz7rbaVSRxHFg",img:"systems/pf2e/icons/conditions/fascinated.webp",name:"Fascinated",system:{description:{value:"You are compelled to focus your attention on something, distracting you from whatever else is going on around you. You take a -2 status penalty to Perception and skill checks, and you can't use actions with the concentrate trait unless they or their intended consequences are related to the subject of your fascination (as determined by the GM). For instance, you might be able to @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} and @UUID[Compendium.pf2e.actionspf2e.Item.1OagaWtBpVXExToo]{Recall Knowledge} about the subject, but you likely couldn't cast a spell targeting a different creature. This condition ends if a creature uses hostile actions against you or any of your allies.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["perception","skill-check"],slug:"fascinated",type:"status",value:-2}],value:{isValued:!1,value:null},slug:"fascinated",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.AdPVz7rbaVSRxHFg"}},effects:[]},{_id:"AJh5ex99aV6VTggg",img:"systems/pf2e/icons/conditions/off-guard.webp",name:"Off-Guard",system:{description:{value:`You're distracted or otherwise unable to focus your full attention on defense. You take a -2 circumstance penalty to AC. Some effects give you the off-guard condition only to certain creatures or against certain attacks. Others-especially conditions-can make you universally off-guard against everything. If a rule doesn't specify that the condition applies only to certain circumstances, it applies to all of them; for example, many effects simply say "The target is off-guard."
`},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"ac",slug:"off-guard",type:"circumstance",value:-2}],value:{isValued:!1,value:null},slug:"off-guard",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}},effects:[]},{_id:"D5mg6Tc7Jzrj6ro7",img:"systems/pf2e/icons/conditions/encumbered.webp",name:"Encumbered",system:{description:{value:"You are carrying more weight than you can manage. While you're encumbered, you're @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} and take a 10-foot penalty to all your Speeds. As with all penalties to your Speed, this can't reduce your Speed below 5 feet.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"speed",slug:"encumbered",value:-10},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm"}],value:{isValued:!1,value:null},slug:"encumbered",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.D5mg6Tc7Jzrj6ro7"}},effects:[]},{_id:"dfCMdR4wnpbYNTix",img:"systems/pf2e/icons/conditions/stunned.webp",name:"Stunned",system:{description:{value:`You've become senseless. You can't act while stunned. Stunned usually includes a value, which indicates how many total actions you lose, possibly over multiple turns, from being stunned. Each time you regain actions (such as at the start of your turn), reduce the number you regain by your stunned value, then reduce your stunned value by the number of actions you lost. For example, if you were stunned 4, you would lose all 3 of your actions on your turn, reducing you to stunned 1; on your next turn, you would lose 1 more action, and then be able to use your remaining 2 actions normally. Stunned might also have a duration instead of a value, such as "stunned for 1 minute." In this case, you lose all your actions for the listed duration.
-Stunned overrides @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed}. If the duration of your stunned condition ends while you are slowed, you count the actions lost to the stunned condition toward those lost to being slowed. So, if you were stunned 1 and slowed 2 at the beginning of your turn, you would lose 1 action from stunned, and then lose only 1 additional action by being slowed, so you would still have 1 action remaining to use that turn.
`},duration:{value:0},group:null,overrides:["slowed"],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"stunned",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix"}},effects:[]},{_id:"DmAIPqOBomZ7H95W",img:"systems/pf2e/icons/conditions/concealed.webp",name:"Concealed",system:{description:{value:"While you are concealed from a creature, such as in a thick fog, you are difficult for that creature to see. You can still be @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed}, but you're tougher to target. A creature that you're concealed from must succeed at a @Check[type:flat|dc:5] check when targeting you with an attack, spell, or other effect. Area effects aren't subject to this flat check. If the check fails, the attack, spell, or effect doesn't affect you.
"},duration:{value:0},group:"senses",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"concealed",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W"}},effects:[]},{_id:"dTwPJuKgBQCMxixg",img:"systems/pf2e/icons/conditions/petrified.webp",name:"Petrified",system:{description:{value:"You have been turned to stone. You can't act, nor can you sense anything. You become an object with a Bulk double your normal Bulk (typically 12 for a petrified Medium creature or 6 for a petrified Small creature), AC 9, Hardness 8, and the same current Hit Points you had when alive. You don't have a Broken Threshold. When you're turned back into flesh, you have the same number of Hit Points you had as a statue. If the statue is destroyed, you immediately die. While petrified, your mind and body are in stasis, so you don't age or notice the passing of time.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"petrified",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.dTwPJuKgBQCMxixg"}},effects:[]},{_id:"e1XGnhKNSQIm5IXg",img:"systems/pf2e/icons/conditions/stupefied.webp",name:"Stupefied",system:{description:{value:"Your thoughts and instincts are clouded. Stupefied always includes a value. You take a status penalty equal to this value on Intelligence-, Wisdom-, and Charisma-based checks and DCs, including Will saving throws, spell attack rolls, spell DCs, and skill checks that use these ability scores. Any time you attempt to @UUID[Compendium.pf2e.actionspf2e.Item.aBQ8ajvEBByv45yz]{Cast a Spell} while stupefied, the spell is disrupted unless you succeed at a flat check with a DC equal to 5 + your stupefied value.
"},duration:{value:0},group:"abilities",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["cha-based","int-based","wis-based"],slug:"stupefied",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"stupefied",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg"}},effects:[]},{_id:"eIcWbB5o3pP6OIMe",img:"systems/pf2e/icons/conditions/immobilized.webp",name:"Immobilized",system:{description:{value:"You can't use any action with the move trait. If you're immobilized by something holding you in place and an external force would move you out of your space, the force must succeed at a check against either the DC of the effect holding you in place or the relevant defense (usually Fortitude DC) of the monster holding you in place.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"immobilized",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}},effects:[]},{_id:"fBnFDH2MTzgFijKf",img:"systems/pf2e/icons/conditions/unconscious.webp",name:"Unconscious",system:{description:{value:`You're sleeping, or you've been knocked out. You can't act. You take a -4 status penalty to AC, Perception, and Reflex saves, and you have the @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} and @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} conditions. When you gain this condition, you fall @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} and drop items you are wielding or holding unless the effect states otherwise or the GM determines you're in a position in which you wouldn't.
-If you're unconscious because you're @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying}, you can't wake up while you have 0 Hit Points. If you are restored to 1 Hit Point or more via healing, you lose the dying and unconscious conditions and can act normally on your next turn.
-If you are unconscious and at 0 Hit Points, but not dying, you naturally return to 1 Hit Point and awaken after sufficient time passes. The GM determines how long you remain unconscious, from a minimum of 10 minutes to several hours. If you receive healing during this time, you lose the unconscious condition and can act normally on your next turn.
-If you're unconscious and have more than 1 Hit Point (typically because you are asleep or unconscious due to an effect), you wake up in one of the following ways. Each causes you to lose the unconscious condition.
+}`)}}class Migration724CraftingMaxItemLevel extends MigrationBase{static{__name(this,"Migration724CraftingMaxItemLevel")}static{__name2(this,"Migration724CraftingMaxItemLevel")}static version=.724;pathPattern=/^data\.crafting\.entries\.([-a-z]+)\.maxItemLevel$/i;async updateItem(source){if(source.type!=="feat")return;if(source.system.slug==="advanced-alchemy"){const rules=source.system.rules;for(const rule of rules)rule.predicate={all:["self:class:alchemist"]},rule.key==="CraftingEntry"&&(delete rule.name,rule.label="PF2E.TraitAlchemist")}else if(source.system.slug?.endsWith("-dedication")&&source.system.slug!=="alchemist-dedication"){const rules=source.system.rules.filter(r=>r.key==="CraftingEntry");for(const rule of rules){delete rule.name;const i18nKey=sluggify(source.system.slug.replace(/-dedication$/,""),{camel:"bactrian"});rule.label=`PF2E.SpecificRule.DedicationCraftingEntry.${i18nKey}`}}const aeLikes=source.system.rules.filter(r=>r.key==="ActiveEffectLike");for(const rule of aeLikes){if(typeof rule.path!="string")continue;const selector=this.pathPattern.exec(rule.path)?.[1]??null;if(selector){const predicate=rule.predicate=foundry.utils.mergeObject({all:[]},isObject(rule.predicate)?rule.predicate:{}),slug=sluggify(selector);predicate.all=Array.from(new Set([...predicate.all,`crafting:entry:${slug}`]))}}}}class Migration725QuickClimbREs extends MigrationBase{static{__name(this,"Migration725QuickClimbREs")}static{__name2(this,"Migration725QuickClimbREs")}static version=.725;quickClimb=[{key:"BaseSpeed",predicate:{all:["self:skill:ath:rank:4"]},selector:"climb",value:"@actor.attributes.speed.value"},{key:"Note",predicate:{all:["action:climb"]},selector:"athletics",text:'r.key==="Strike"&&!Array.isArray(r.options));strikeRE&&(strikeRE.options=["animal-instinct"])}}class Migration764PanacheVivaciousREs extends MigrationBase{static{__name(this,"Migration764PanacheVivaciousREs")}static{__name2(this,"Migration764PanacheVivaciousREs")}static version=.764;async updateItem(source){source.type==="feat"&&(source.system.slug==="panache"?source.system.rules=[]:source.system.slug==="vivacious-speed"&&(source.system.rules=this.#vivaciousRules))}get#vivaciousRules(){return[{key:"FlatModifier",predicate:{all:["self:effect:panache"]},selector:"speed",slug:"vivacious-full",type:"status",value:{brackets:[{end:2,value:5},{end:6,start:3,value:10},{end:10,start:7,value:15},{end:14,start:11,value:20},{end:18,start:15,value:25},{start:19,value:30}]}},{key:"FlatModifier",predicate:{not:["self:effect:panache"]},selector:"speed",slug:"vivacious-half",type:"status",value:{brackets:[{end:10,start:3,value:5},{end:18,start:11,value:10},{start:19,value:15}]}}]}}class Migration765ChoiceOwnedItemTypes extends MigrationBase{static{__name(this,"Migration765ChoiceOwnedItemTypes")}static{__name2(this,"Migration765ChoiceOwnedItemTypes")}static version=.765;async updateItem(source){for(const rule of source.system.rules)rule.key==="ChoiceSet"&&"choices"in rule&&isObject(rule.choices)&&rule.choices.ownedItems&&!rule.choices.types&&(rule.choices.types=["weapon"])}}class Migration766WipeURLSources extends MigrationBase{static{__name(this,"Migration766WipeURLSources")}static{__name2(this,"Migration766WipeURLSources")}static version=.766;async updateItem(source){(!("game"in globalThis)||source.flags.core?.sourceId?.startsWith("Compendium.pf2e."))&&"source"in source.system&&isObject(source.system.source)&&typeof source.system.source.value=="string"&&source.system.source.value.startsWith("http")&&(source.system.source.value="")}}class Migration767ConvertVoluntaryFlaws extends MigrationBase{static{__name(this,"Migration767ConvertVoluntaryFlaws")}static{__name2(this,"Migration767ConvertVoluntaryFlaws")}static version=.767;async updateItem(source){if(source.type!=="ancestry")return;const system=source.system,oldFlaws=Object.values(system.voluntaryFlaws??{}).map(b=>b.selected).filter(a=>!!a),oldBoosts=Object.values(system.voluntaryBoosts??{}).map(b=>b.selected).filter(a=>!!a);(oldBoosts.length||oldFlaws.length)&&(system.voluntary={boost:oldBoosts.at(0)||null,flaws:oldFlaws}),system.voluntaryBoosts&&(delete system.voluntaryBoosts,delete system["-=voluntaryBoosts"]),system.voluntaryFlaws&&(delete system.voluntaryFlaws,delete system.voluntaryFlaws)}}class Migration768AddNewAuras extends MigrationBase{static{__name(this,"Migration768AddNewAuras")}static{__name2(this,"Migration768AddNewAuras")}static version=.768;#auraOfLife={effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.FPuICuxBLiDaEbDX"}],key:"Aura",radius:15,slug:"aura-of-life"};#enlightenedPresence={effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.XM1AA8z5cHm8sJXM"}],key:"Aura",radius:15,slug:"enlightened-presence",traits:["emotion","mental"]};#eternalBlessing=[{domain:"all",key:"RollOption",option:"eternal-blessing-active",toggleable:!0,value:!0},{effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.spell-effects.Gqy7K6FnbLtwGpud"}],key:"Aura",predicate:{all:["eternal-blessing-active"]},radius:15,slug:"eternal-blessing",traits:["enchantment","mental"]}];#marshalsAura={effects:[{affects:"allies",events:["enter"],uuid:"Compendium.pf2e.feat-effects.Ru4BNABCZ0hUbX7S"}],key:"Aura",radius:10,slug:"marshals-aura",traits:["emotion","mental","visual"]};async updateItem(source){if(!(source.type!=="feat"||source.system.rules.length>0))switch(source.system.slug){case"aura-of-life":source.system.rules=[foundry.utils.deepClone(this.#auraOfLife)];break;case"enlightened-presence":source.system.rules=[foundry.utils.deepClone(this.#enlightenedPresence)];break;case"eternal-blessing":source.system.rules=foundry.utils.deepClone(this.#eternalBlessing);break;case"marshal-dedication":source.system.rules=[foundry.utils.deepClone(this.#marshalsAura)];break}}}class Migration769NoUniversalistFocusPool extends MigrationBase{static{__name(this,"Migration769NoUniversalistFocusPool")}static{__name2(this,"Migration769NoUniversalistFocusPool")}static version=.769;async updateItem(source){if(source.type==="feat"&&source.system.slug==="arcane-school"){const rule=source.system.rules.find(r=>r.key==="ActiveEffectLike"&&r.path==="system.resources.focus.max");rule&&(rule.predicate={not:["feature:universalist"]})}}}class Migration770REDataToSystem extends MigrationBase{static{__name(this,"Migration770REDataToSystem")}static{__name2(this,"Migration770REDataToSystem")}static version=.77;async updateActor(source){source.system=recursiveReplaceString(source.system,value=>value.replace(/@(actor|item)\.data\.data./g,"@$1.system.").replace(/@(actor|item)\.data./g,"@$1."))}async updateItem(source){source.system=recursiveReplaceString(source.system,value=>value.replace(/^data\.data\./,"system.").replace(/^data\./,"system.").replace(/"data\.data\./g,'"system.').replace(/"data\./g,'"system.').replace(/@(actor|item)\.data\.data./g,"@$1.system.").replace(/@(actor|item)\.data./g,"@$1.").replace(/\b(actor|item|rule)\|data\.data\./g,"$1|system.").replace(/\b(actor|item|rule)\|data\./g,"$1|system."))}}class Migration771SpellVariantsToSystem extends MigrationBase{static{__name(this,"Migration771SpellVariantsToSystem")}static{__name2(this,"Migration771SpellVariantsToSystem")}static version=.771;async updateItem(source){if(source.type==="spell"){for(const overlayData of Object.values(source.system.overlays??{}))if(overlayData.overlayType==="override"){const maybeWithData=overlayData;maybeWithData.data&&(delete Object.assign(maybeWithData,{system:maybeWithData.data}).data,maybeWithData["-=data"]=null)}}}}class Migration772V10EmbeddedSpellData extends MigrationBase{static{__name(this,"Migration772V10EmbeddedSpellData")}static{__name2(this,"Migration772V10EmbeddedSpellData")}static version=.772;async preUpdateItem(source){if(source.type==="consumable"&&source.system.spell){const embeddedSpell=source.system.spell;embeddedSpell.data?.data?(source.system.spell=embeddedSpell.data,source.system.spell.system=embeddedSpell.data.data,source.system.spell.system.location.heightenedLevel=Number(embeddedSpell.data.heightenedLevel)||source.system.spell.system.level.value,embeddedSpell.data["-=data"]=null,delete embeddedSpell.data.data):embeddedSpell.data?.system?(source.system.spell=embeddedSpell.data,source.system.spell.system.location.heightenedLevel=Number(embeddedSpell.data.heightenedLevel)||source.system.spell.system.level.value):embeddedSpell.data===null&&(source.system.spell=null)}}}class Migration773ReligiousSymbolUsage extends MigrationBase{static{__name(this,"Migration773ReligiousSymbolUsage")}static{__name2(this,"Migration773ReligiousSymbolUsage")}static version=.773;async updateItem(source){source.type==="equipment"&&source.system.slug?.startsWith("religious-symbol")&&(source.system.usage.value="held-in-one-hand")}}class Migration774UnpersistCraftingEntries extends MigrationBase{static{__name(this,"Migration774UnpersistCraftingEntries")}static{__name2(this,"Migration774UnpersistCraftingEntries")}static version=.774;munitionsCrafterPredicate={all:["item:trait:alchemical"],any:["item:trait:bomb","item:subtype:ammo"]};async updateActor(source){if(source.type==="character"){const craftingData=source.system.crafting??{},craftingEntries=craftingData.entries??{},rules=source.items.flatMap(i=>i.system.rules);for(const rule of rules)rule.key!=="CraftingEntry"||typeof rule.selector!="string"||rule.selector.length===0||!rule.requiredTraits||(rule.preparedFormulas=craftingEntries[rule.selector]?.actorPreparedFormulas??[]);delete craftingData.entries,craftingData["-=entries"]=null}}async updateItem(source){const rules=source.system.rules,craftingEntryRules=rules.filter(r=>r.key==="CraftingEntry"&&Array.isArray(r.requiredTraits)),newCraftingEntryRules=craftingEntryRules.map(craftingEntryRule=>(craftingEntryRule.craftableItems=craftingEntryRule.selector==="munitionsCrafter"?this.munitionsCrafterPredicate:this.generatePredicateFromRequiredTraits(craftingEntryRule.requiredTraits||[]),delete craftingEntryRule.requiredTraits,craftingEntryRule));for(const craftingEntryRule of craftingEntryRules){const index=rules.indexOf(craftingEntryRule);rules.splice(index,1,newCraftingEntryRules.shift()),delete craftingEntryRule.requiredTraits}const craftingEntryAELikes=rules.filter(r=>r.key==="ActiveEffectLike"&&typeof r.path=="string"&&r.path.startsWith("system.crafting.entries.")),newCraftingEntryAELikes=craftingEntryAELikes.map(craftingEntryAELike=>(craftingEntryAELike.phase="beforeDerived",craftingEntryAELike));for(const craftingEntryAELike of craftingEntryAELikes){const index=rules.indexOf(craftingEntryAELike);rules.splice(index,1,newCraftingEntryAELikes.shift())}}generatePredicateFromRequiredTraits(requiredTraits){return requiredTraits.length===1?{all:requiredTraits[0].map(trait=>`item:trait:${trait}`)}:{any:requiredTraits.map(traits=>({and:traits.map(trait=>`item:trait:${trait}`)}))}}}class Migration775AgileFinesseRanged extends MigrationBase{static{__name(this,"Migration775AgileFinesseRanged")}static{__name2(this,"Migration775AgileFinesseRanged")}static version=.775;#findDamageDiceRE(source){return source.system.rules.find(r=>r.key==="DamageDice")??null}#isClassFeature(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"}async updateItem(source){switch(source.type){case"action":{if(source.system.slug==="sneak-attack"){const damageDiceRE=this.#findDamageDiceRE(source);isObject(damageDiceRE)&&damageDiceRE.predicate&&Array.isArray(damageDiceRE.predicate.all)&&damageDiceRE.predicate.all.some(s=>s instanceof Object&&"or"in s)&&(damageDiceRE.predicate=this.#sneakAttackPredicate)}break}case"feat":switch(source.system.slug){case"athletic-strategist":{const index=source.system.rules.findIndex(r=>r.key==="FlatModifier");index!==-1&&(source.system.rules[index]=this.#athleticStrategist);break}case"devise-a-stratagem":{const index=source.system.rules.findIndex(r=>r.key==="FlatModifier");index!==-1&&(source.system.rules[index]=this.#deviseAStratagem);break}case"ruffian":{const damageDiceRE=this.#findDamageDiceRE(source);damageDiceRE&&(damageDiceRE.predicate=this.#ruffianPredicate);break}case"shadow-sneak-attack":case"sneak-attack":case"sneak-attacker":{const damageDiceRE=this.#findDamageDiceRE(source);if(damageDiceRE){const predicate=this.#sneakAttackPredicate;this.#isClassFeature(source)&&predicate.all?.unshift("class:rogue"),damageDiceRE.predicate=predicate}break}}}}get#athleticStrategist(){return{ability:"int",key:"FlatModifier",predicate:{all:["class:investigator","devise-a-stratagem",{or:["action:disarm","action:grapple","action:shove","action:trip"]}],any:["weapon:trait:agile","weapon:trait:finesse",{and:["weapon:ranged",{not:"weapon:thrown-melee"}]},"weapon:base:sap"]},selector:"athletics",type:"ability"}}get#deviseAStratagem(){return{ability:"int",key:"FlatModifier",predicate:{all:["class:investigator","devise-a-stratagem"],any:["weapon:trait:agile","weapon:trait:finesse",{and:["weapon:ranged",{not:"weapon:thrown-melee"}]},"weapon:base:sap"]},selector:"attack-roll",type:"ability"}}get#ruffianPredicate(){return{all:["target:condition:flat-footed","weapon:category:simple",{nor:[{and:["weapon:ranged",{not:"weapon:thrown-melee"}]},"weapon:trait:agile","weapon:trait:finesse"]}]}}get#sneakAttackPredicate(){return{all:["target:condition:flat-footed"],any:["weapon:trait:agile","weapon:trait:finesse",{and:["weapon:ranged",{not:"weapon:thrown-melee"}]}]}}}class Migration776SlugifyConditionOverrides extends MigrationBase{static{__name(this,"Migration776SlugifyConditionOverrides")}static{__name2(this,"Migration776SlugifyConditionOverrides")}static version=.776;async updateItem(source){if(source.type!=="condition")return;const{system}=source;Array.isArray(system.overrides)&&system.overrides.every(o=>typeof o=="string")&&(system.overrides=system.overrides.map(o=>sluggify(o)))}}class Migration777HandOfTheApprentice extends MigrationBase{static{__name(this,"Migration777HandOfTheApprentice")}static{__name2(this,"Migration777HandOfTheApprentice")}static version=.777;async updateItem(source){if(source.type==="feat"&&source.system.slug==="hand-of-the-apprentice"){const rule={key:"ActiveEffectLike",mode:"add",path:"system.resources.focus.max",value:1};source.system.rules=[rule]}}}class Migration778RenameRetiredPackRefs extends MigrationBase{static{__name(this,"Migration778RenameRetiredPackRefs")}static{__name2(this,"Migration778RenameRetiredPackRefs")}static version=.778;async updateItem(source){const rename=__name2(text=>text.replace(/\bpf2e\.consumable-effects\b/g,"pf2e.equipment-effects").replace(/\bpf2e\.exploration-effects\b/g,"pf2e.other-effects").replace(/\bpf2e\.feature-effects\b/g,"pf2e.feat-effects").replace(/\bpf2e\.equipment-effects\.I9lfZUiCwMiGogVi\b/g,"pf2e.other-effects.I9lfZUiCwMiGogVi").replace(/\bpf2e\.equipment-effects\.Cover\b/g,"pf2e.other-effects.Effect: Cover"),"rename");source.system.rules=recursiveReplaceString(source.system.rules,rename),source.system.description=recursiveReplaceString(source.system.description,rename)}}class Migration779EliteWeak extends MigrationBase{static{__name(this,"Migration779EliteWeak")}static{__name2(this,"Migration779EliteWeak")}static version=.779;async updateActor(source){if(!(source.type==="npc"&&source.system.traits.traits?.value))return;const traits=source.system.traits.traits,adjustment=traits.value.includes("elite")?"elite":traits.value.includes("weak")?"weak":null;adjustment&&(source.system.attributes.adjustment=adjustment,traits.value=traits.value.filter(trait=>trait!=="elite"&&trait!=="weak"))}}class Migration780NumifySpeeds extends MigrationBase{static{__name(this,"Migration780NumifySpeeds")}static{__name2(this,"Migration780NumifySpeeds")}static version=.78;async updateActor(source){if(source.type!=="npc"&&source.type!=="character")return;const speeds=source.system.attributes.speed;speeds.value=this.#updateSpeed(speeds.value),Array.isArray(speeds.otherSpeeds)||(speeds.otherSpeeds=[]);for(const movementType of speeds.otherSpeeds)movementType.value=this.#updateSpeed(movementType.value)}#updateSpeed(speed){const numifiedValue=parseInt(String(speed),10);return Number.isNaN(numifiedValue)?25:numifiedValue}}class Migration781SuppressNoCrowbar extends MigrationBase{static{__name(this,"Migration781SuppressNoCrowbar")}static{__name2(this,"Migration781SuppressNoCrowbar")}static version=.781;get#suppressNoCrowbar(){return{key:"AdjustModifier",selector:"athletics",slug:"no-crowbar",suppress:!0}}async updateItem(source){if(!source.system.slug)return;const isCrowbar=source.type==="equipment"&&/^crowbar(?:-levered)?$/.test(source.system.slug),isForcedEntry=source.type==="feat"&&source.system.slug==="forced-entry";(isCrowbar||isForcedEntry)&&!source.system.rules.some(r=>r.key==="AdjustModifier")&&source.system.rules.push(this.#suppressNoCrowbar)}}class Migration782UnnestActorTraits extends MigrationBase{static{__name(this,"Migration782UnnestActorTraits")}static{__name2(this,"Migration782UnnestActorTraits")}static version=.782;async updateActor(source){const traits=source.system.traits;traits&&traits.traits&&Array.isArray(traits.traits.value)&&(traits.value=traits.traits.value,delete traits.traits,traits["-=traits"]=null)}}class Migration783RemoveClassSkillAELikes extends MigrationBase{static{__name(this,"Migration783RemoveClassSkillAELikes")}static{__name2(this,"Migration783RemoveClassSkillAELikes")}static version=.783;async updateItem(source){source.type==="class"&&(source.system.rules=source.system.rules.filter(r=>!(r.key==="ActiveEffectLike"&&typeof r.path=="string"&&/^system.skills\.[a-z]{3}\.rank$/.test(r.path)&&r.value===1)))}}class Migration784CompBrowserPackSetting extends MigrationBase{static{__name(this,"Migration784CompBrowserPackSetting")}static{__name2(this,"Migration784CompBrowserPackSetting")}static version=.784;async migrate(){const savedSettings=game.settings.get("pf2e","compendiumBrowserPacks");if(savedSettings instanceof String){const settings=JSON.parse(savedSettings.toString());await game.settings.set("pf2e","compendiumBrowserPacks",settings);const browser=game?.pf2e?.compendiumBrowser;browser&&(browser.settings=settings,browser.initCompendiumList())}}}class Migration785ABCKitItemUUIDs extends MigrationBase{static{__name(this,"Migration785ABCKitItemUUIDs")}static{__name2(this,"Migration785ABCKitItemUUIDs")}static version=.785;async updateItem(source){switch(source.type){case"ancestry":case"background":case"class":case"kit":this.#convertToUUIDs(Object.values(source.system.items))}}#convertToUUIDs(references){for(const reference of references)reference.id&&reference.pack?reference.uuid=`Compendium.${reference.pack}.${reference.id}`:reference.id&&(reference.uuid=`Item.${reference.id}`),delete reference.id,delete reference.pack,reference["-=id"]=null,reference["-=pack"]=null,reference.items&&this.#convertToUUIDs(Object.values(reference.items))}}class Migration786RemoveIdentifiedData extends MigrationBase{static{__name(this,"Migration786RemoveIdentifiedData")}static{__name2(this,"Migration786RemoveIdentifiedData")}static version=.786;async updateItem(source){if(!isPhysicalData(source))return;const identification=source.system.identification??{};identification.identified&&(identification["-=identified"]=null)}}class Migration787ResolvablesToSystem extends MigrationBase{static{__name(this,"Migration787ResolvablesToSystem")}static{__name2(this,"Migration787ResolvablesToSystem")}static version=.787;async updateItem(source){source.system=recursiveReplaceString(source.system,value=>value.replace(/@(weapon|spell)\.data\.data./g,"@$1.system.").replace(/@(weapon|spell)\.data./g,"@$1."))}}class Migration788UpdateTanglefootBags extends MigrationBase{static{__name(this,"Migration788UpdateTanglefootBags")}static{__name2(this,"Migration788UpdateTanglefootBags")}static version=.788;async updateItem(source){if(source.type==="weapon"&&source.system.slug?.startsWith("tanglefoot-bag-"))switch(source.system.damage.dice=0,source.system.slug){case"tanglefoot-bag-lesser":{source.system.rules=this.#getRules("Lesser");return}case"tanglefoot-bag-moderate":{source.system.rules=this.#getRules("Moderate");return}case"tanglefoot-bag-greater":{source.system.rules=this.#getRules("Greater");return}case"tanglefoot-bag-major":{source.system.rules=this.#getRules("Major");return}}}#getRules(type){return[{key:"Note",outcome:["success"],selector:"{item|_id}-attack",text:`PF2E.BombNotes.TanglefootBag.${type}.success`,title:"TYPES.Item.effect"},{key:"Note",outcome:["criticalSuccess"],selector:"{item|_id}-attack",text:`PF2E.BombNotes.TanglefootBag.${type}.criticalSuccess`,title:"TYPES.Item.effect"}]}}class Migration789UpdatePreciseStrike extends MigrationBase{static{__name(this,"Migration789UpdatePreciseStrike")}static{__name2(this,"Migration789UpdatePreciseStrike")}static version=.789;async updateItem(source){if(source.type==="feat"){if(source.system.slug==="precise-strike")source.system.rules=this.#preciseStrikeRules;else if(source.system.slug==="finishing-precision"){const rules=source.system.rules.filter(r=>r.key==="GrantItem");source.system.rules=[...rules,...this.#finishingPrecisionRules]}}}get#preciseStrikeRules(){return[{domain:"damage-roll",key:"RollOption",label:"PF2E.SpecificRule.PreciseStrike.Finisher",option:"finisher",toggleable:!0},{damageCategory:"precision",key:"FlatModifier",predicate:{all:["class:swashbuckler","self:effect:panache",{or:["weapon:melee",{and:["feat:flying-blade","weapon:thrown","target:range-increment:1"]}]}],any:["weapon:trait:agile","weapon:trait:finesse"],not:["finisher"]},selector:"strike-damage",slug:"precise-strike",value:{brackets:[{end:4,value:2},{end:8,start:5,value:3},{end:12,start:9,value:4},{end:16,start:13,value:5},{start:17,value:6}]}},{category:"precision",dieSize:"d6",key:"DamageDice",predicate:{all:["class:swashbuckler","self:effect:panache","finisher",{or:["weapon:melee",{and:["feat:flying-blade","weapon:thrown","target:range-increment:1"]}]}],any:["weapon:trait:agile","weapon:trait:finesse"]},selector:"strike-damage",slug:"finisher",value:{brackets:[{end:4,value:{diceNumber:2}},{end:8,start:5,value:{diceNumber:3}},{end:12,start:9,value:{diceNumber:4}},{end:16,start:13,value:{diceNumber:5}},{start:17,value:{diceNumber:6}}]}}]}get#finishingPrecisionRules(){return[{damageCategory:"precision",key:"FlatModifier",predicate:{all:["self:effect:panache",{or:["weapon:melee",{and:["feat:flying-blade","weapon:thrown","target:range-increment:1"]}]}],any:["weapon:trait:agile","weapon:trait:finesse"],not:["finisher"]},selector:"strike-damage",slug:"finishing-precision",value:1},{category:"precision",diceNumber:1,dieSize:"d6",key:"DamageDice",predicate:{all:["self:effect:panache","finisher",{or:["weapon:melee",{and:["feat:flying-blade","weapon:thrown","target:range-increment:1"]}]}],any:["weapon:trait:agile","weapon:trait:finesse"]},selector:"strike-damage",slug:"finishing-precision"}]}}class Migration790MultipleClassDCs extends MigrationBase{static{__name(this,"Migration790MultipleClassDCs")}static{__name2(this,"Migration790MultipleClassDCs")}static version=.79;#otherClassDCs=new Map([["call-implement","thaumaturge"],["eerie-proclamation","ranger"],["stunning-fist","monk"],["ring-bell","thaumaturge"]]);#isClassFeature(source){return source.type==="feat"&&"featType"in source.system&&isObject(source.system.featType)&&source.system.featType.value==="classfeature"}async updateActor(source){if(source.type!=="character")return;const customModifiers=source.system.customModifiers??{};customModifiers?.class&&(customModifiers["-=class"]=null)}async updateItem(source){if(this.#isClassFeature(source)){const classSlug=source.system.traits.value.at(0);if(!classSlug)return;const aeLikes=source.system.rules.filter(r=>r.key==="ActiveEffectLike");for(const aeLike of aeLikes)aeLike.path==="system.attributes.classDC.rank"&&(aeLike.path=`system.proficiencies.classDCs.${classSlug}.rank`)}const itemSlug=source.system.slug??"";if(this.#otherClassDCs.has(itemSlug)){const oldClassDCPattern=/\bsystem\.attributes\.classDC\b/,classSlug=this.#otherClassDCs.get(itemSlug),{description}=source.system;description.value=description.value.replace(oldClassDCPattern,`system.proficiencies.classDCs.${classSlug}`);const notes=source.system.rules.filter(r=>r.key==="Note"&&typeof r.text=="string");for(const note of notes)note.text=note.text.replace(oldClassDCPattern,`system.proficiencies.classDCs.${classSlug}`)}}}class Migration791RuffianHands extends MigrationBase{static{__name(this,"Migration791RuffianHands")}static{__name2(this,"Migration791RuffianHands")}static version=.791;async updateItem(source){if(!(source.type!=="feat"||!source.system.slug))switch(source.system.slug){case"ruffian":{source.system.rules.some(r=>r.key==="CriticalSpecialization")||source.system.rules.push(this.#critSpec);break}case"healing-hands":{const hands=this.#hands;hands.predicate={all:["item:slug:heal"]},source.system.rules=[hands];break}case"harming-hands":{const hands=this.#hands;hands.predicate={all:["item:slug:harm"]},source.system.rules=[hands];break}}}get#critSpec(){return{key:"CriticalSpecialization",predicate:{all:["target:condition:flat-footed","weapon:category:simple",{lte:["weapon:damage:die:faces",8]}]}}}get#hands(){return{key:"DamageDice",override:{dieSize:"d10"},selector:"spell-damage"}}}class Migration792RemoveTokenAELikes extends MigrationBase{static{__name(this,"Migration792RemoveTokenAELikes")}static{__name2(this,"Migration792RemoveTokenAELikes")}static version=.792;async updateItem(source){const rules=source.system.rules;for(const rule of[...rules])rule.key==="ActiveEffectLike"&&typeof rule.path=="string"&&/^token\./.test(rule.path)&&rules.splice(rules.indexOf(rule),1)}}class Migration793MakePredicatesArrays extends MigrationBase{static{__name(this,"Migration793MakePredicatesArrays")}static{__name2(this,"Migration793MakePredicatesArrays")}static version=.793;#convertLegacyData(predicate){const keys2=Object.keys(predicate);return keys2.length===0?[]:keys2.length===1&&Array.isArray(predicate.all)?foundry.utils.deepClone(predicate.all):keys2.length===1&&Array.isArray(predicate.any)&&predicate.any.length===1?foundry.utils.deepClone(predicate.any):foundry.utils.deepClone([predicate.all??[],Array.isArray(predicate.any)?{or:predicate.any}:[],Array.isArray(predicate.not)?predicate.not.length===1?{not:predicate.not[0]}:{nor:predicate.not}:[]].flat())}async updateActor(source){if("customModifiers"in source.system){isObject(source.system.customModifiers)||(source.system.customModifiers={});for(const modifier of Object.values(source.system.customModifiers).flat())modifier.predicate&&=[]}}async updateItem(source){const rules=source.system.rules;for(const rule of rules){if(this.#isOldRawPredicate(rule.predicate)&&(rule.predicate=this.#convertLegacyData(rule.predicate)),this.#isOldRawPredicate(rule.definition)&&(rule.definition=this.#convertLegacyData(rule.definition)),this.#isOldRawPredicate(rule.allowedDrops)&&(rule.allowedDrops={label:rule.allowedDrops.label??void 0,predicate:this.#convertLegacyData(rule.allowedDrops)}),this.#isOldRawPredicate(rule.predicate)&&(rule.predicate=this.#convertLegacyData(rule.predicate)),this.#isArrayChoiceSet(rule))for(const choice of rule.choices)this.#isOldRawPredicate(choice.predicate)&&(choice.predicate=this.#convertLegacyData(choice.predicate));else this.#isObjectChoiceSet(rule)?(this.#isOldRawPredicate(rule.choices.predicate)&&(rule.choices.predicate=this.#convertLegacyData(rule.choices.predicate)),this.#isOldRawPredicate(rule.choices.postFilter)&&(rule.choices.postFilter=this.#convertLegacyData(rule.choices.postFilter))):this.#isOldRawPredicate(rule.craftableItems)&&(rule.craftableItems=this.#convertLegacyData(rule.craftableItems));this.#isOldRawPredicate(rule.disabledIf)&&(rule.disabledIf=this.#convertLegacyData(rule.disabledIf))}}#isOldRawPredicate(predicate){return!predicate||Array.isArray(predicate)||isObject(predicate)&&Array.isArray(predicate.predicate)?!1:predicate instanceof Object}#isArrayChoiceSet(rule){return rule.key==="ChoiceSet"&&Array.isArray(rule.choices)}#isObjectChoiceSet(rule){return rule.key==="ChoiceSet"&&isObject(rule.choices)&&!Array.isArray(rule.choices)}}class Migration794AddWildShapeChoices extends MigrationBase{static{__name(this,"Migration794AddWildShapeChoices")}static{__name2(this,"Migration794AddWildShapeChoices")}static version=.794;#shapeFeats=new Set(["VaIHQzOE5ibmbtqU","OWedlrKGsVZVkSnT","wNHUryoRzlfDCFAd","F0MYBfiyOD8YHq5t","I9rSWQyueWHQyNxe","p0jZhb8PSswUsZaz","Le30algCdKIsxmeK","54JzsYCx3uoj7Wlz"].map(id=>`Compendium.pf2e.feats-srd.${id}`));async updateItem(source){const sourceId=source.flags.core?.sourceId;if(source.type==="feat"&&sourceId&&this.#shapeFeats.has(sourceId)){const fromPack=await fromUuid(sourceId);fromPack instanceof FeatPF2e&&(source.system.rules=fromPack.toObject().system.rules)}}}class Migration795CleanupFlatFootedToggle extends MigrationBase{static{__name(this,"Migration795CleanupFlatFootedToggle")}static{__name2(this,"Migration795CleanupFlatFootedToggle")}static version=.795;get#flatFootedToggle(){return{key:"RollOption",domain:"all",label:"PF2E.SpecificRule.TOTMToggle.FlatFooted",option:"target:condition:flat-footed",toggleable:"totm"}}async updateActor(source){source.flags.pf2e?.rollOptions&&(source.flags.pf2e["-=rollOptions"]=null)}async updateItem(source){if(source.type==="feat"||source.type==="action"&&source.system.slug==="sneak-attack")switch(source.system.slug){case"sneak-attack":case"laughing-shadow":case"shadow-sneak-attack":case"butterflys-sting":case"game-hunter-dedication":source.system.rules.some(r=>this.#isFlatFootedToggle(r))||source.system.rules.push(this.#flatFootedToggle)}}#isFlatFootedToggle(rule){return rule.key==="RollOption"&&rule.option==="target:condition:flat-footed"&&rule.toggleable==="totm"}}class Migration796ItemGrantsToObjects extends MigrationBase{static{__name(this,"Migration796ItemGrantsToObjects")}static{__name2(this,"Migration796ItemGrantsToObjects")}static version=.796;async updateActor(source){for(const item of source.items){const systemFlags=item.flags.pf2e;!systemFlags?.itemGrants||!Array.isArray(systemFlags.itemGrants)||(systemFlags.itemGrants=systemFlags.itemGrants.reduce((grantsObject,grant)=>{if(typeof grant=="string"||grant instanceof Object){const[flag,grantSource]=this.#convertToEntry(source,item,grant);if(flag!==null){const modifiedFlag=this.#modifyFlag(grantsObject,flag);grantsObject[modifiedFlag]=grantSource}}return grantsObject},{}))}}#convertToEntry(actor,granter,grantedData){const grantedId=grantedData instanceof Object?grantedData.id:grantedData;return actor.items.some(i=>i._id===grantedId)?[sluggify(granter.name,{camel:"dromedary"}),{id:grantedId}]:[null,null]}#modifyFlag(grantedItems,flag){const pattern=new RegExp(`^${flag}\\d*$`),nthGrant=Object.keys(grantedItems).filter(g=>pattern.test(g)).length;return nthGrant===0?flag:`${flag}${nthGrant+1}`}}class Migration797MetagameSetting extends MigrationBase{static{__name(this,"Migration797MetagameSetting")}static{__name2(this,"Migration797MetagameSetting")}static version=.797;visibilitySettings=["showDC","showResults"];settings=[...this.visibilitySettings,"tokenSetsNameVisibility","secretDamage","secretCondition","partyVision"];async migrate(){for(const setting of this.settings){const storage=game.settings.storage.get("world"),newKey=`metagame_${setting}`,oldValue=storage.getItem(`pf2e.metagame.${setting}`)??null,existingValueRaw=storage.getItem(`pf2e.${newKey}`)??null;if(oldValue!==null&&existingValueRaw!==null){const newValue=this.visibilitySettings.includes(setting)?!["gm","owner"].includes(oldValue):oldValue;game.settings.set("pf2e",newKey,newValue)}}}}class Migration798WeaponToItemStatements extends MigrationBase{static{__name(this,"Migration798WeaponToItemStatements")}static{__name2(this,"Migration798WeaponToItemStatements")}static version=.798;async updateItem(source){const rules=source.system.rules;for(const rule of rules)for(const property of["predicate","definition"]){const predicate=rule[property];Array.isArray(predicate)&&(rule[property]=recursiveReplaceString(predicate,s=>s.replace(/^weapon:/,"item:")))}}}class Migration799RMRecallKnowledgeDuplicates extends MigrationBase{static{__name(this,"Migration799RMRecallKnowledgeDuplicates")}static{__name2(this,"Migration799RMRecallKnowledgeDuplicates")}static version=.799;#oldIdsPattern=new RegExp("pf2e\\.actionspf2e\\.(?:".concat(["KygTSeDvsFoSO6HW","B0Eu3EfwIa9kyDEA","SeUolRoPzorFUAaI","eT1jXYvz2YH70Ovp","B2BpIZFHoF9Kjzpx","LZgjpWd0pL3vK9Q1","KUfLlXDWTcAWhl8l"].join("|")).concat(")"),"g");async updateItem(source){source.system.description.value??="",source.system.description.value=source.system.description.value.replace(this.#oldIdsPattern,"pf2e.actionspf2e.1OagaWtBpVXExToo")}}class Migration800SelfEffectPanacheRage extends MigrationBase{static{__name(this,"Migration800SelfEffectPanacheRage")}static{__name2(this,"Migration800SelfEffectPanacheRage")}static version=.8;async updateItem(source,actorSource){if(!(actorSource?._id==="bpTQfx4UixMV3Fja"||actorSource?.flags.core?.sourceId==="Compendium.pf2e.extinction-curse-bestiary.Actor.bpTQfx4UixMV3Fja"))for(const rule of source.system.rules)rule.predicate&&Array.isArray(rule.predicate)&&(rule.predicate=recursiveReplaceString(rule.predicate,s=>s.replace(/^(rage|panache)$/,"self:effect:$1")))}}class Migration801ColorDarkvision extends MigrationBase{static{__name(this,"Migration801ColorDarkvision")}static{__name2(this,"Migration801ColorDarkvision")}static version=.801;get#colorDarkvision(){return{key:"ActiveEffectLike",path:"flags.pf2e.colorDarkvision",mode:"override",value:!0}}async updateItem(source){if(!source.system.slug)return;const isFetchling=source.type==="ancestry"&&source.system.slug==="fetchling",isResonantLight=source.type==="feat"&&source.system.slug==="resonant-reflection-reflection-of-light",getsColorDarkvision=isFetchling||isResonantLight,rules=source.system.rules;getsColorDarkvision&&!rules.some(r=>r.path==="flags.pf2e.colorDarkvision")&&source.system.rules.push(this.#colorDarkvision)}}class Migration802StripFeatActionCategory extends MigrationBase{static{__name(this,"Migration802StripFeatActionCategory")}static{__name2(this,"Migration802StripFeatActionCategory")}static version=.802;async updateItem(source){if(source.type!=="feat")return;const feat=source.system;feat.actionCategory&&(delete feat.actionCategory,feat["-=actionCategory"]=null)}}class Migration803NormalizeSpellArea extends MigrationBase{static{__name(this,"Migration803NormalizeSpellArea")}static{__name2(this,"Migration803NormalizeSpellArea")}static version=.803;#AREA_TYPES=new Set(["burst","cone","cube","emanation","line","square"]);async updateItem(source){if(source.type!=="spell")return;const area=source.system.area;area&&(area.value=Number(area.value),"areaType"in area&&this.#isAreaType(area.areaType)&&(area.type=area.areaType,delete area.areaType,area["-=areaType"]=null)),area?.value&&this.#isAreaType(area.type)||(source.system.area=null),"areasize"in source.system&&isObject(source.system.areasize)&&(this.#hasDetails(source.system.areasize.value)&&area&&(area.details=source.system.areasize.value),delete source.system.areasize,source.system["-=areasize"]=null)}#isAreaType(areaType){return typeof areaType=="string"&&areaType.length>0&&this.#AREA_TYPES.has(areaType)}#hasDetails(details){return typeof details=="string"&&details.trim().length>0&&!/^\d+-foot (?:burst|cone|cube|emanation|line|square)$/.test(details)}}class Migration804RemoveConsumableProperties extends MigrationBase{static{__name(this,"Migration804RemoveConsumableProperties")}static{__name2(this,"Migration804RemoveConsumableProperties")}static version=.804;async updateItem(source){if(source.type!=="consumable")return;const system=source.system;system.uses&&delete system.uses,system.autoUse&&(delete system.autoUse,system["-=autoUse"]=null),isObject$1(system.charges)&&"_deprecated"in system.charges&&(delete system.charges._deprecated,system.charges["-=deprecated"]=null),isObject$1(system.consume)&&"_deprecated"in system.consume&&(delete system.consume._deprecated,system.consume["-=deprecated"]=null)}}class Migration805InlineDamageRolls extends MigrationBase{static{__name(this,"Migration805InlineDamageRolls")}static{__name2(this,"Migration805InlineDamageRolls")}static version=.805;#pattern=/\[\[\/r .+?\]\]\]?(?:\{[^}]+\})?/g;#damageTypeLabelPattern=(()=>{const dicePattern="[0-9]{1,2}d[0-9]{1,2}(?:\\s*[-+]\\s*[0-9]{1,3})?",typesUnion=["acid","bleed","bludgeoning","chaotic","cold","electricity","evil","fire","force","good","lawful","mental","negative","piercing","poison","positive","slashing","sonic","untyped"].join("|");return new RegExp(`^${dicePattern} (?:${typesUnion})(?: damage)?$`,"i")})();#updateDamageFormula(text){const skipStrings=["splash","precision","persistent","d20","#"];return text.replace(this.#pattern,match=>{const labelEndsWithDamage=match.toLowerCase().endsWith("damage}");if(skipStrings.some(s=>match.includes(s)))return match;const customLabel=/\{([^}]+)\}$/.exec(match)?.at(1),expressions=match.replace(/\{[^}]+\}$/,"").match(/\{[^}]+\}\[\w+\]/g)??[];if(expressions.length===0)return match;const instances=expressions.map(i=>i.trim().replace(/^\{([^}]+)\}\[([a-z]+)\]$/i,["+","-","*","/"].some(o=>i.includes(o))?"($1)[$2]":"$1[$2]").toLowerCase()),reassembled=instances.length===1?`[[/r ${instances[0]}]]`:`[[/r {${instances.join(",")}}]]`;return customLabel&&!this.#damageTypeLabelPattern.test(customLabel)?`${reassembled}{${customLabel}}`:labelEndsWithDamage?`${reassembled} damage`:reassembled})}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>this.#updateDamageFormula(s))}}class Migration806TorchImprovisedOtherTags extends MigrationBase{static{__name(this,"Migration806TorchImprovisedOtherTags")}static{__name2(this,"Migration806TorchImprovisedOtherTags")}static version=.806;async updateItem(source){if(source.type==="equipment"&&source.system.slug==="torch"){const torchStrikeRE=source.system.rules.find(r=>r.key==="Strike"&&r.otherTags===void 0);torchStrikeRE&&(delete torchStrikeRE.traits,torchStrikeRE.otherTags=["improvised"])}}}class Migration807RMActivatedEffectFields extends MigrationBase{static{__name(this,"Migration807RMActivatedEffectFields")}static{__name2(this,"Migration807RMActivatedEffectFields")}static version=.807;async updateItem(source){if(source.type==="consumable")for(const property of["activation","duration","range","target","uses"])property in source.system&&(delete source.system[property],source.system[`-=${property}`]=null)}}class Migration808CountDamageDice extends MigrationBase{static{__name(this,"Migration808CountDamageDice")}static{__name2(this,"Migration808CountDamageDice")}static version=.808;async updateItem(source){source.system=recursiveReplaceString(source.system,s=>s.replace(/\(?\b1\s*\+\s*@(item|weapon)(?:.system)?.runes.striking\)?/g,"@$1.system.damage.dice"))}}class Migration809AutomatonEnhancements extends MigrationBase{static{__name(this,"Migration809AutomatonEnhancements")}static{__name2(this,"Migration809AutomatonEnhancements")}static version=.809;get#automatonEnhancements(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.automaton.enhancements",priority:10,value:{greater:[],lesser:[]}}}async updateItem(source){const isAutomaton=source.type==="ancestry"&&source.system.slug==="automaton",rules=source.system.rules;isAutomaton&&!rules.some(r=>r.path==="flags.pf2e.automaton.enhancements")&&source.system.rules.push(this.#automatonEnhancements)}}class Migration810LootDescriptionValue extends MigrationBase{static{__name(this,"Migration810LootDescriptionValue")}static{__name2(this,"Migration810LootDescriptionValue")}static version=.81;async updateActor(source){if(source.type==="loot"){const details=source.system.details;details.description instanceof Object&&(details.description=String(details.description.value??""))}}}class Migration811InlineDamageRollsPersistent extends MigrationBase{static{__name(this,"Migration811InlineDamageRollsPersistent")}static{__name2(this,"Migration811InlineDamageRollsPersistent")}static version=.811;#conditionPattern=/(?<=\]\]|})(\s*@(?:UUID|Compendium)\[(?:Compendium\.)?pf2e\.conditionitems\.(?:Persistent Damage|lDVqvLKA6eF3Df60)\]\{[^}]+})/g;#pattern=/\[\[\/r ([^[\]]+(\[.*?\])?)\]\](\{\dd\d[^{}]*\})?/g;#updateDamageFormula(text){return text.replace(this.#conditionPattern," damage").replace(this.#pattern,(match,formula)=>{if(!match.includes("persistent"))return match;const hashStyle=formula.match(/([^#]+)#\s*persistent ([^#]+)/);if(hashStyle){const expression=hashStyle[1].trim(),damageType=hashStyle[2].trim(),expressionCleaned=["+","-","*","/"].some(o=>expression.includes(o))?`(${expression})`:expression;return match.replace(formula,`${expressionCleaned}[persistent,${damageType}]`)}const expressions=formula.match(/\{[^}]+\}\[[\w,]+\]/g)??[];if(expressions.length){const withoutLabel=match.replace(/\{\dd\d[^{}]*\}$/,""),instances=expressions.map(i=>i.replace(/^\{([^}]+)\}\[([a-z,]+)\]$/,["+","-","*","/"].some(o=>i.includes(o))?"($1)[$2]":"$1[$2]")),reassembled=instances.length===1?instances[0]:`{${instances.join(",")}}`;return withoutLabel.replace(formula,reassembled)}return match})}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>this.#updateDamageFormula(s))}}class Migration812RestructureIWR extends MigrationBase{static{__name(this,"Migration812RestructureIWR")}static{__name2(this,"Migration812RestructureIWR")}static version=.812;async updateActor(source){const traits=source.system.traits;if(!traits||source.type==="familiar")return;const{attributes}=source.system;if("ci"in traits&&("game"in globalThis||delete traits.ci,traits["-=ci"]=null),"di"in traits){const oldData=traits.di;if("game"in globalThis||delete traits.di,traits["-=di"]=null,isObject$1(oldData)&&"value"in oldData&&Array.isArray(oldData.value)&&oldData.value.length>0){const immunities=oldData.value.map(i=>this.#normalizeType(String(i))).filter(i=>setHasElement(IMMUNITY_TYPES,i)).map(i=>({type:i}));immunities.length>0&&(attributes.immunities=immunities)}}if("dv"in traits){const oldData=traits.dv;if("game"in globalThis||delete traits.dv,traits["-=dv"]=null,Array.isArray(oldData)&&oldData.length>0){const weaknesses=this.#getWR(oldData,WEAKNESS_TYPES).map(data=>{const weakness=pick(data,["type","value"]),exceptions=this.#parseExceptions(String(data.exceptions??"")).exceptions.filter(e=>setHasElement(WEAKNESS_TYPES,e));return exceptions.length>0&&(weakness.exceptions=exceptions),weakness});weaknesses.length>0&&(attributes.weaknesses=weaknesses)}}if("dr"in traits){const oldData=traits.dr;if("game"in globalThis||delete traits.dr,traits["-=dr"]=null,Array.isArray(oldData)&&oldData.length>0){const resistances=this.#getWR(oldData,RESISTANCE_TYPES).map(data=>{const resistance=pick(data,["type","value"]),parsed=this.#parseExceptions(String(data.exceptions??"")),exceptions=parsed.exceptions.filter(e=>setHasElement(RESISTANCE_TYPES,e));exceptions.length>0&&(resistance.exceptions=exceptions);const doubleVs=parsed.doubleVs.filter(e=>setHasElement(RESISTANCE_TYPES,e));return doubleVs.length>0&&(resistance.doubleVs=doubleVs),resistance});resistances.length>0&&(attributes.resistances=resistances)}}}async updateItem(source){if(source.type==="weapon"){const material=source.system.preciousMaterial??{};material.value=typeof material.value=="string"?sluggify(material.value):null,source.system.preciousMaterialGrade&&(source.system.preciousMaterialGrade.value||=null)}const iwrREs=source.system.rules.filter(r=>typeof r.key=="string"&&["Immunity","Weakness","Resistance"].includes(r.key)&&"type"in r&&typeof r.type=="string");for(const rule of iwrREs)if(rule.type=rule.type.startsWith("{")?rule.type:this.#normalizeType(rule.type),typeof rule.except=="string"){const exceptions=this.#parseExceptions(rule.except).exceptions.filter(exception=>rule.key==="Immunity"?setHasElement(IMMUNITY_TYPES,exception):rule.key==="Weakness"?setHasElement(WEAKNESS_TYPES,exception):setHasElement(RESISTANCE_TYPES,exception));exceptions.length>0&&(rule.exceptions=exceptions),delete rule.except}const adjustStrikeREs=source.system.rules.filter(r=>r.key==="AdjustStrike"&&typeof r.value=="string");for(const rule of adjustStrikeREs)rule.value=rule.value.startsWith("{")||["property-runes","weapon-traits"].includes(rule.property)?rule.value:this.#normalizeType(rule.value)}#getWR(maybeWR,typeSet){return maybeWR.filter(r=>isObject$1(r)&&typeof r.type=="string"&&typeof r.value=="number").map(wr=>(wr.type=this.#normalizeType(wr.type),wr.value=Math.abs(wr.value),wr)).filter(r=>setHasElement(typeSet,r.type))}#oldENmappings={"PF2E.ResistanceException.Bludgeoning":"except bludgeoning","PF2E.ResistanceException.ForceGhostTouchDoubleNonMagical":"except force, or ghost touch; double resistance vs. non-magical","PF2E.ResistanceException.ForceGhostTouchNegativeDoubleNonMagical":"except force, ghost touch, or negative; double resistance vs. non-magical","PF2E.ResistanceException.ForceGhostTouchPositiveDoubleNonMagical":"except force, ghost touch, or positive; double resistance vs. non-magical"};#parseExceptions(text){const normalized=(this.#oldENmappings[text]??text).toLowerCase().replace("PF2E.TraitForce","force").replace("PF2E.TraitPositive","positive").replace("cold iron","cold-iron").replace("critical hits","critical-hits").replace("ghost touch","ghost-touch").replace("nonmagical","non-magical").replace("weapons shedding bright light","weapons-shedding-bright-light").replace("unarmed","unarmed-attacks").replace(/\bexcept\b/,"").trim().replace(/\s+/," ");if(!normalized)return{exceptions:[],doubleVs:[]};const doubleIndex=normalized.indexOf("double"),exceptions=(doubleIndex===-1?normalized:normalized.slice(0,doubleIndex)).split(/[,\s]+/).map(d=>sluggify(d)),doubleVs=normalized.slice(doubleIndex).split(/[,\s]+/).map(d=>sluggify(d));return{exceptions,doubleVs}}#normalizeType(text){switch(text=text.trim(),text){case"all":case"All":return"all-damage";case"arrow":return"arrow-vulnerability";case"axe":return"axe-vulnerability";case"coldiron":return"cold-iron";case"nonlethal":return"nonlethal-attacks";case"nonmagical-attacks":return"non-magical";case"protean anatomy":return"protean-anatomy";case"unarmed":return"unarmed-attacks";default:return sluggify(text)}}}class Migration813NormalizeColdIron extends MigrationBase{static{__name(this,"Migration813NormalizeColdIron")}static{__name2(this,"Migration813NormalizeColdIron")}static version=.813;async updateItem(source){switch(source.type){case"melee":{const traits=source.system.traits;traits.value=traits.value.map(t=>t.replace(/^coldiron$/i,"cold-iron"));return}case"armor":case"weapon":{const preciousMaterial=source.system.preciousMaterial;if(typeof preciousMaterial?.value!="string")return;preciousMaterial.value&&=preciousMaterial.value.replace(/^coldiron$/i,"cold-iron"),source.type==="weapon"&&this.#updateWeaponMaterialData(source);return}}const choiceSets=source.system.rules.filter(r=>r.key==="ChoiceSet"&&"choices"in r&&Array.isArray(r.choices)&&r.choices.every(c=>isObject(c)&&"value"in c&&typeof c.value=="string"));for(const choiceSet of choiceSets)this.#updateChoiceSet(choiceSet)}#updateWeaponMaterialData(source){if(source.type!=="weapon"||!isObject(source.system.specific))return;const specificData=source.system.specific;specificData.value||(delete specificData.material,delete specificData.price,delete specificData.runes,specificData["-=material"]=null,specificData["-=price"]=null,specificData["-=runes"]=null);const material=specificData.material;material?.precious?(material.precious.type&&=material.precious.type.replace(/^coldiron$/i,"cold-iron"),delete material.base,material["-=base"]=null):typeof material?.type=="string"&&typeof material.grade=="string"&&(material.precious={type:material.type.replace(/^coldiron$/i,"cold-iron"),grade:material.grade},delete material.type,delete material.grade,material["-=type"]=null,material["-=grade"]=null)}#updateChoiceSet(choiceSet){for(const choice of choiceSet.choices)/coldiron/i.test(String(choice.value))&&(choice.value="cold-iron");/coldiron/i.test(String(choiceSet.selection))&&(choiceSet.selection="cold-iron")}}class Migration814CalculatedExpandedSplash extends MigrationBase{static{__name(this,"Migration814CalculatedExpandedSplash")}static{__name2(this,"Migration814CalculatedExpandedSplash")}static version=.814;async updateItem(source){if(source.type==="feat")switch(source.system.slug){case"calculated-splash":{const rules=[{key:"AdjustModifier",mode:"upgrade",predicate:[{not:"feat:expanded-splash"}],relabel:"{item|name}",selector:"alchemical-bomb-damage",slug:"splash",value:"@actor.abilities.int.mod"}];source.system.rules=rules;return}case"expanded-splash":{const rules=[{damageCategory:"splash",key:"FlatModifier",predicate:["item:trait:splash"],selector:"alchemical-bomb-damage",value:"@actor.abilities.int.mod"},{key:"Note",predicate:["item:trait:splash"],selector:"alchemical-bomb-damage",text:"The bomb deals splash damage to every creature within 10 feet of the target.",title:"{item|name}"}];source.system.rules=rules}}}}class Migration815ConsumableDataCleanup extends MigrationBase{static{__name(this,"Migration815ConsumableDataCleanup")}static{__name2(this,"Migration815ConsumableDataCleanup")}static version=.815;consumableKeys=new Set(["autoDestroy","baseItem","bulk","charges","consumableType","consume","containerId","description","equipped","equippedBulk","hardness","hp","identification","level","negateBulk","preciousMaterial","preciousMaterialGrade","price","quantity","rules","schema","size","slug","source","spell","stackGroup","temporary","traits","usage","weight"]);async updateItem(source){if(source.type!=="consumable")return;const systemData=source.system;for(const key of Object.keys(systemData)){const value=systemData[key];this.consumableKeys.has(key)?isObject(value)&&"_deprecated"in value&&(delete value._deprecated,value["-=_deprecated"]=null):(delete systemData[key],systemData[`-=${key}`]=null)}}}class Migration816AlchemistResearchFields extends MigrationBase{static{__name(this,"Migration816AlchemistResearchFields")}static{__name2(this,"Migration816AlchemistResearchFields")}static version=.816;get#bomberSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.alchemist",value:{fieldDiscovery:"Compendium.pf2e.classfeatures.8QAFgy9U8PxEa7Dw",greaterFieldDiscovery:"Compendium.pf2e.classfeatures.RGs4uR3CAvgbtBAA",perpetualInfusions:"Compendium.pf2e.classfeatures.DFQDtT1Van4fFEHi",perpetualPerfection:"Compendium.pf2e.classfeatures.xO90iBD8XNGyaCkz",perpetualPotency:"Compendium.pf2e.classfeatures.8rEVg03QJ71ic3PP"}}}get#chirurgeonSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.alchemist",value:{fieldDiscovery:"Compendium.pf2e.classfeatures.qC0Iz6SlG2i9gv6g",greaterFieldDiscovery:"Compendium.pf2e.classfeatures.JJcaVijwRt9dsnac",perpetualInfusions:"Compendium.pf2e.classfeatures.fzvIe6FwwCuIdnjX",perpetualPerfection:"Compendium.pf2e.classfeatures.YByJ9O7oe8wxfbqs",perpetualPotency:"Compendium.pf2e.classfeatures.VS5vkqUQu4n7E28Y"}}}get#mutagenistSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.alchemist",value:{fieldDiscovery:"Compendium.pf2e.classfeatures.V4Jt7eDnJBLv5bDj",greaterFieldDiscovery:"Compendium.pf2e.classfeatures.1BKdOJ0HNL6Eg3xw",perpetualInfusions:"Compendium.pf2e.classfeatures.Dug1oaVYejLmYEFt",perpetualPerfection:"Compendium.pf2e.classfeatures.CGetAmSbv06fW7GT",perpetualPotency:"Compendium.pf2e.classfeatures.mZFqRLYOQEqKA8ri"}}}get#toxicologistSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.alchemist",value:{fieldDiscovery:"Compendium.pf2e.classfeatures.6zo2PJGYoig7nFpR",greaterFieldDiscovery:"Compendium.pf2e.classfeatures.tnqyQrhrZeDtDvcO",perpetualInfusions:"Compendium.pf2e.classfeatures.LlZ5R50z9j8jysZL",perpetualPerfection:"Compendium.pf2e.classfeatures.3R19zS7gERhEX87F",perpetualPotency:"Compendium.pf2e.classfeatures.JOdbVu14phvdjhaY"}}}async updateItem(source){if(!(source.type!=="feat"||!source.system.slug)&&!source.system.rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="flags.pf2e.alchemist"))switch(source.system.slug){case"bomber":{source.system.rules.push(this.#bomberSetFlags);break}case"chirurgeon":{source.system.rules.push(this.#chirurgeonSetFlags);break}case"mutagenist":{source.system.rules.push(this.#mutagenistSetFlags);break}case"toxicologist":{source.system.rules.push(this.#toxicologistSetFlags);break}}}}class Migration817FieldDiscoveryPredicates extends MigrationBase{static{__name(this,"Migration817FieldDiscoveryPredicates")}static{__name2(this,"Migration817FieldDiscoveryPredicates")}static version=.817;async updateItem(source){const aeLikes=source.system.rules.filter(r=>r.key==="ActiveEffectLike"&&"path"in r&&typeof r.path=="string"&&/^system.crafting.entries.\w+.fieldDiscovery$/.test(r.path)&&"value"in r&&typeof r.value=="string");for(const rule of aeLikes)switch(rule.value){case"bomb":rule.value=["item:base:alchemical-bomb"];break;case"elixir":rule.value=["item:trait:elixir","item:trait:healing"];break;case"mutagen":rule.value=["item:trait:mutagen"];break;case"poison":rule.value=["item:trait:alchemical","item:trait:poison"];break;default:rule.value=[`item:trait:${rule.value}`]}}}class Migration818BasicUndeadNegativeHealing extends MigrationBase{static{__name(this,"Migration818BasicUndeadNegativeHealing")}static{__name2(this,"Migration818BasicUndeadNegativeHealing")}static version=.818;#needsRE(source){return source.system.slug==="basic-undead-benefits"&&!source.system.rules.some(r=>r.key==="ActiveEffectLike"&&"path"in r&&r.path==="system.attributes.hp.negativeHealing")}async updateItem(source){if(source.type==="feat"&&this.#needsRE(source)){const rule={key:"ActiveEffectLike",mode:"override",path:"system.attributes.hp.negativeHealing",value:!0};source.system.rules.push(rule)}}}class Migration819SpinTaleAdventureSpecific extends MigrationBase{static{__name(this,"Migration819SpinTaleAdventureSpecific")}static{__name2(this,"Migration819SpinTaleAdventureSpecific")}static version=.819;async updateItem(source){if(source.type==="feat"){const oldSpinTale="Compendium.pf2e.adventure-specific-actions.Spin Tale",newSpinTale="Compendium.pf2e.actionspf2e.Spin Tale",oldSpinTaleId="Compendium.pf2e.adventure-specific-actions.5gahZQXf3UVwATSC",newSpinTaleId="Compendium.pf2e.actionspf2e.hPZQ5vA9QHEPtjFW";source.system.description.value=source.system.description.value.replace(oldSpinTale,newSpinTale),source.system.description.value=source.system.description.value.replace(oldSpinTaleId,newSpinTaleId)}}}class Migration820RemoveUnusedTraitsData extends MigrationBase{static{__name(this,"Migration820RemoveUnusedTraitsData")}static{__name2(this,"Migration820RemoveUnusedTraitsData")}static version=.82;async updateItem(source){source.system.traits;const systemSource=source.system;systemSource.traits&&("custom"in systemSource.traits&&(delete systemSource.traits.custom,systemSource.traits["-=custom"]=null),(source.type==="spellcastingEntry"||source.type==="condition")&&(delete systemSource.traits,systemSource["-=traits"]=null))}}class Migration821InlineDamageRolls extends MigrationBase{static{__name(this,"Migration821InlineDamageRolls")}static{__name2(this,"Migration821InlineDamageRolls")}static version=.821;#splashPattern1=/\[\[(\/b?r)\s*{([^}]*)}\[splash,\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g;#splashPattern2=/\[\[(\/b?r)\s*([^[]*)\[splash,\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g;#damagePatternSingle=/\[\[(\/b?r)\s*{([^}]*)}\[\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g;#damagePatternPair=/\[\[(\/b?r)\s*{([^}]*)}\[\s*([^\]]*)\]\s*[+,]\s*{([^}]*)}\[\s*([^\]]*)\]\s*(#[^\]]*)?\]\]/g;#cleanFormula(formula){return formula=formula.replace(/\s+/g,""),["+","-","*","/"].some(o=>formula.includes(o))?`(${formula})`:formula}#buildSplashFormula(roll,formula,damage,tag){return formula=this.#cleanFormula(formula),damage=damage.trim(),tag=tag?.trim()??"",tag.length>0?`[[${roll} (${formula}[splash])[${damage}] ${tag}]]`:`[[${roll} (${formula}[splash])[${damage}]]]`}#buildDamageFormula(roll,parts,tag){if(tag=tag?.trim()??"",parts.length===1){const formula=this.#cleanFormula(parts[0].formula),damage=parts[0].damage.trim();return tag.length>0?`[[${roll} ${formula}[${damage}] ${tag}]]`:`[[${roll} ${formula}[${damage}]]]`}else if(parts.length>1){const assembled=parts.map(p=>{const formula=this.#cleanFormula(p.formula),damage=p.damage.trim();return`${formula}[${damage}]`}).join(",");return tag.length>0?`[[${roll} {${assembled}} ${tag}]]`:`[[${roll} {${assembled}}]]`}else return""}#updateDamageFormula(text){return text=text.replace(this.#splashPattern1,(_,roll,formula,damage,tag)=>this.#buildSplashFormula(roll,formula,damage,tag)),text=text.replace(this.#splashPattern2,(_,roll,formula,damage,tag)=>this.#buildSplashFormula(roll,formula,damage,tag)),text=text.replace(this.#damagePatternSingle,(_,roll,formula,damage,tag)=>this.#buildDamageFormula(roll,[{formula,damage}],tag)),text=text.replace(this.#damagePatternPair,(_,roll,formula1,damage1,formula2,damage2,tag)=>this.#buildDamageFormula(roll,[{formula:formula1,damage:damage1},{formula:formula2,damage:damage2}],tag)),text}async updateActor(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>this.#updateDamageFormula(s))}async updateJournalEntry(source){source.pages=recursiveReplaceString(source.pages,s=>this.#updateDamageFormula(s))}}class Migration822BladeAllyConsolidation extends MigrationBase{static{__name(this,"Migration822BladeAllyConsolidation")}static{__name2(this,"Migration822BladeAllyConsolidation")}static version=.822;#rename(text){return text.replace(/\bfeat-effects\.Effect: Blade Ally Anarchic Rune\b/g,"equipment-srd.Anarchic").replace(/\bfeat-effects\.xLXFK4mtzgAF4zvx\b/g,"equipment-srd.65YL6nk1jIzCWutt").replace(/\bfeat-effects\.Effect: Blade Ally Axiomatic Rune\b/g,"equipment-srd.Axiomatic").replace(/\bfeat-effects\.ZzE6jPbCyUqEqhcb\b/g,"equipment-srd.6xu6dPIaUZ7edKEB").replace(/\bfeat-effects\.Effect: Blade Ally Disrupting Rune\b/g,"equipment-srd.Disrupting").replace(/\bfeat-effects\.eippbzuocVM6ftcj\b/g,"equipment-srd.LwQb7ryTC8FlOXgX").replace(/\bfeat-effects\.Effect: Blade Ally Fearsome Rune\b/g,"equipment-srd.Fearsome").replace(/\bfeat-effects\.6LgJB4ypaSTWSJLu\b/g,"equipment-srd.P6v2AtJw7AUwaDzf").replace(/\bfeat-effects\.Effect: Blade Ally Flaming Rune\b/g,"equipment-srd.Flaming").replace(/\bfeat-effects\.YxYr18vleIt2t3RS\b/g,"equipment-srd.XszNvxnymWYRaoTp").replace(/\bfeat-effects\.Effect: Blade Ally Holy Rune\b/g,"equipment-srd.Holy").replace(/\bfeat-effects\.l98IthkklgLDJXIo\b/g,"equipment-srd.DH0kB9Wbr5pDeunX").replace(/\bfeat-effects\.Effect: Blade Ally Keen Rune\b/g,"equipment-srd.Keen").replace(/\bfeat-effects\.Gf7h44DcTB43464h\b/g,"equipment-srd.hg3IogR8ue2IWwgS").replace(/\bfeat-effects\.Effect: Blade Ally Unholy Rune\b/g,"equipment-srd.Unholy").replace(/\bfeat-effects\.rGSc2PtvU3mgm18S\b/g,"equipment-srd.gmMrJREf4JSHd2dZ").replace(/\bfeat-effects\.Effect: Blade Ally Ghost Touch Rune\b/g,"equipment-srd.Ghost Touch").replace(/\bfeat-effects\.Rgio0hasm2epEMfh\b/g,"equipment-srd.JQdwHECogcTzdd8R").replace(/\bfeat-effects\.Effect: Blade Ally Disrupting Rune (Greater)\b/g,"equipment-srd.Disrupting (Greater)").replace(/\bfeat-effects\.HjfIXg5btodThCTW\b/g,"equipment-srd.oVrVzML63VFvVfKk")}async updateItem(source){source.system.description.value.includes("feat-effects")&&(source.system.description.value=this.#rename(source.system.description.value))}}class Migration823HeritageAncestrySlug extends MigrationBase{static{__name(this,"Migration823HeritageAncestrySlug")}static{__name2(this,"Migration823HeritageAncestrySlug")}static version=.823;async updateItem(source){if(source.type!=="heritage"||!source.system.ancestry||source.system.ancestry.slug)return;const ancestry=await fromUuid(source.system.ancestry.uuid);source.system.ancestry.slug=ancestry instanceof AncestryPF2e?ancestry.slug??sluggify(ancestry.name):sluggify(source.system.ancestry.name)}}class Migration824SneakAttackDamageSource extends MigrationBase{static{__name(this,"Migration824SneakAttackDamageSource")}static{__name2(this,"Migration824SneakAttackDamageSource")}static version=.824;async updateItem(source){if(source.type==="feat")switch(source.system.slug){case"sneak-attack":{const rules=[{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.number",predicate:["class:rogue"],value:"ternary(lt(@actor.level, 5), 1, ternary(lt(@actor.level, 11), 2, ternary(lt(@actor.level, 17), 3, 4)))"},{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.faces",predicate:["class:rogue"],value:6},{category:"precision",diceNumber:"@actor.flags.pf2e.sneakAttackDamage.number",dieSize:"d{actor|flags.pf2e.sneakAttackDamage.faces}",key:"DamageDice",predicate:["target:condition:flat-footed",{or:["item:trait:agile","item:trait:finesse",{and:["item:ranged",{not:"item:thrown-melee"}]}]}],selector:"strike-damage"},{domain:"all",key:"RollOption",label:"PF2E.SpecificRule.TOTMToggle.FlatFooted",option:"target:condition:flat-footed",toggleable:"totm"}];source.system.rules=rules;return}case"ruffian":{const rules=[{category:"precision",diceNumber:"@actor.flags.pf2e.sneakAttackDamage.number",dieSize:"d{actor|flags.pf2e.sneakAttackDamage.faces}",key:"DamageDice",label:"PF2E.SpecificRule.SneakAttack",predicate:["target:condition:flat-footed","item:category:simple",{nor:[{and:["item:ranged",{not:"item:thrown-melee"}]},"item:trait:agile","item:trait:finesse"]}],selector:"strike-damage"},{key:"ActiveEffectLike",mode:"upgrade",path:"system.martial.medium.rank",value:1},{key:"ActiveEffectLike",mode:"upgrade",path:"system.skills.itm.rank",value:1},{key:"CriticalSpecialization",predicate:["target:condition:flat-footed","item:category:simple",{lte:["item:damage:die:faces",8]}]}];source.system.rules=rules;return}case"sneak-attacker":{const rules=[{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.number",value:1},{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.faces",value:"ternary(lt(@actor.level, 6), 4, 6)"},{key:"GrantItem",uuid:"Compendium.pf2e.classfeatures.Sneak Attack"}];source.system.rules=rules;return}case"butterflys-sting":{const rules=[{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.number",value:1},{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.sneakAttackDamage.faces",value:6},{key:"GrantItem",uuid:"Compendium.pf2e.classfeatures.Sneak Attack"},{domain:"all",key:"RollOption",label:"PF2E.SpecificRule.TOTMToggle.FlatFooted",option:"target:condition:flat-footed",toggleable:"totm"}];source.system.rules=rules;return}case"magical-trickster":{const rules=[{category:"precision",diceNumber:"@actor.flags.pf2e.sneakAttackDamage.number",dieSize:"d{actor|flags.pf2e.sneakAttackDamage.faces}",key:"DamageDice",predicate:["item:trait:attack","target:condition:flat-footed"],selector:"spell-damage"}];source.system.rules=rules;return}}}}class Migration825KhakkharaFengHuoLun extends MigrationBase{static{__name(this,"Migration825KhakkharaFengHuoLun")}static{__name2(this,"Migration825KhakkharaFengHuoLun")}static version=.825;async updateItem(source){if(source.img.endsWith("icons/equipment/weapons/khakkara.webp")&&(source.img=source.img.replace("khakkara.webp","khakkhara.webp")),source.type==="weapon"){const fixBaseItemAndSlug=__name2((oldId,newId)=>{source.system.baseItem===oldId&&(source.system.baseItem=newId),source.system.slug===oldId&&(source.system.slug=newId)},"fixBaseItemAndSlug");fixBaseItemAndSlug("khakkara","khakkhara"),fixBaseItemAndSlug("wind-and-fire-wheel","feng-huo-lun")}else if(source.type==="feat"){const oldLink="@UUID[Compendium.pf2e.equipment-srd.Khakkara]",newLink="@UUID[Compendium.pf2e.equipment-srd.Khakkhara]";source.system.description.value=source.system.description.value.replace(oldLink,newLink);for(const rule of source.system.rules)rule.key==="ActiveEffectLike"&&"path"in rule&&rule.path==="system.martial.weapon-base-khakkara.rank"&&(rule.path="system.martial.weapon-base-khakkhara.rank")}}}class Migration826GutConditionData extends MigrationBase{static{__name(this,"Migration826GutConditionData")}static{__name2(this,"Migration826GutConditionData")}static version=.826;async updateItem(source){if(source.type!=="condition")return;const system=source.system,topLevel=["active","base","removable","hud","modifiers","sources","alsoApplies"];for(const key of topLevel)key in system&&(delete system[key],system[`-=${key}`]=null);const valueData=system.value;for(const key of["immutable","modifiers"])key in valueData&&(delete valueData[key],valueData[`-=${key}`]=null);const durationData=system.duration;for(const key of["perpetual","text"])key in durationData&&(delete durationData[key],durationData[`-=${key}`]=null);system.group||=null}}class Migration827FixTVShieldTraits extends MigrationBase{static{__name(this,"Migration827FixTVShieldTraits")}static{__name2(this,"Migration827FixTVShieldTraits")}static version=.827;async updateItem(source){if(source.type!=="armor")return;const traits=source.system.traits;switch(source.system.slug){case"dart-shield":{traits.value=["launching-dart"];return}case"klar":{traits.value=["integrated-1d6-s-versatile-p"];return}case"meteor-shield":{traits.value=["shield-throw-30"];return}case"razor-disc":{traits.value=["integrated-1d6-s","shield-throw-20"];return}}}}class Migration828PruneInvalidTraits extends MigrationBase{static{__name(this,"Migration828PruneInvalidTraits")}static{__name2(this,"Migration828PruneInvalidTraits")}static version=.828;async updateActor(source){const traits=source.system.traits;if(traits)switch(source.type){case"character":case"npc":{traits.value=traits.value.filter(t=>t in creatureTraits);return}case"hazard":{traits.value=traits.value.filter(t=>t in hazardTraits);return}case"vehicle":{traits.value=traits.value.filter(t=>t in vehicleTraits);return}}}async updateItem(source){const traits=source.system.traits;if(!(!traits?.value||!Array.isArray(traits.value)))switch(traits.value=traits.value.filter(t=>typeof t=="string"),source.type){case"action":{traits.value=traits.value.map(t=>t.replace(/^audible$/,"auditory").replace(/^concentration$/,"concentrate").replace(/^(interact|manipulation)$/i,"manipulate").replace(/^vocal$/,"verbal")).filter(t=>t.startsWith("hb_")||t in actionTraits);return}case"affliction":case"effect":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in actionTraits||t in spellTraits);return}case"ancestry":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in creatureTraits||["animal"].includes(t));return}case"armor":{traits.value=traits.value.map(t=>source.system.slug?.includes("helmsmans")?t.replace(/^shield-throw$/,"shield-throw-30"):source.system.slug?.includes("klar")?t.replace(/^integrated$/,"integrated-1d6-s-versatile-p"):t).filter(t=>t.startsWith("hb_")||t in armorTraits);return}case"backpack":case"equipment":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in equipmentTraits);return}case"consumable":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in consumableTraits);return}case"class":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in classTraits);return}case"feat":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in featTraits);return}case"melee":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in npcAttackTraits);return}case"spell":{traits.value=traits.value.map(t=>t.replace(/^audible$/,"auditory")).filter(t=>t.startsWith("hb_")||t in spellTraits);return}case"weapon":{traits.value=traits.value.filter(t=>t.startsWith("hb_")||t in weaponTraits);return}}}}class Migration829RMRitualEntries extends MigrationBase{static{__name(this,"Migration829RMRitualEntries")}static{__name2(this,"Migration829RMRitualEntries")}static version=.829;async updateActor(source){for(const item of source.items.filter(i=>i.type==="spellcastingEntry"))item.system.prepared.value==="ritual"&&(source.items.splice(source.items.indexOf(item),1),source.type==="npc"&&(source.system.spellcasting??={},source.system.spellcasting.rituals={dc:item.system.spelldc.dc}))}async updateItem(source){!("category"in source.system)||!isObject(source.system.category)||typeof source.system.category.value!="string"||source.type==="spell"&&source.system.category.value==="ritual"&&source.system.location&&(source.system.location.value=null)}}class Migration830BarbarianRework extends MigrationBase{static{__name(this,"Migration830BarbarianRework")}static{__name2(this,"Migration830BarbarianRework")}static version=.83;async updateItem(source){source.system.description.value=this.#removeLinks(source.system.description.value);for(const rule of source.system.rules)rule.key==="ActiveEffectLike"&&"path"in rule&&(rule.path==="system.custom.modifiers.barbarian-dedication-count"||rule.path==="flags.pf2e.rollOptions.all.barbarian-dedication")&&(rule.path="flags.pf2e.barbarian.archetypeFeatCount"),rule.key==="FlatModifier"&&rule.value==="3 * @actor.system.custom.modifiers.barbarian-dedication-count"&&(rule.value="3 * @actor.flags.pf2e.barbarian.archetypeFeatCount")}#removeLinks(text){return text.replace("@UUID[Compendium.pf2e.classfeatures.vlRvOQS1HZZqSyh7]{Ape}","Ape").replace("@UUID[Compendium.pf2e.classfeatures.uGY2yddm8mZx8Yo2]{Bear}","Bear").replace("@UUID[Compendium.pf2e.classfeatures.31sPXwmEbbcvgsM9]{Bull}","Bull").replace("@UUID[Compendium.pf2e.classfeatures.vCNtX2LwlemhA3tu]{Cat}","Cat").replace("@UUID[Compendium.pf2e.classfeatures.RQUJgDjJODO775qb]{Deer}","Deer").replace("@UUID[Compendium.pf2e.classfeatures.CXZwt1e6ManeBaFV]{Frog}","Frog").replace("@UUID[Compendium.pf2e.classfeatures.OJmI1L4dhQfz8vze]{Shark}","Shark").replace("@UUID[Compendium.pf2e.classfeatures.pIYWMCNnYDQfSRQh]{Snake}","Snake").replace("@UUID[Compendium.pf2e.classfeatures.xX6KnYYgHlPGoTG6]{Wolf}","Wolf").replace("@UUID[Compendium.pf2e.classfeatures.VNbDNiWjARtGQQAs]{Black}","Black").replace("@UUID[Compendium.pf2e.classfeatures.RiOww9KMu06D7wtW]{Blue}","Blue").replace("@UUID[Compendium.pf2e.classfeatures.IezPDYlweTtwCqkT]{Green}","Green").replace("@UUID[Compendium.pf2e.classfeatures.hyHgLQCDMSrR4RfE]{Red}","Red").replace("@UUID[Compendium.pf2e.classfeatures.2esqOHCn4GcZ4zYD]{White}","White").replace("@UUID[Compendium.pf2e.classfeatures.b5rvKZQCfpgBenKJ]{Brass}","Brass").replace("@UUID[Compendium.pf2e.classfeatures.kdzIxHpzeRbdRqQA]{Bronze}","Bronze").replace("@UUID[Compendium.pf2e.classfeatures.1ZugTzJHsa94AZRW]{Copper}","Copper").replace("@UUID[Compendium.pf2e.classfeatures.3lxIGMbsPZLNEXQ7]{Gold}","Gold").replace("@UUID[Compendium.pf2e.classfeatures.Z2eWkfXblU0QxFx1]{Silver}","Silver").replace("@UUID[Compendium.pf2e.classfeatures.Ape Animal Instinct]{Ape}","Ape").replace("@UUID[Compendium.pf2e.classfeatures.Bear Animal Instinct]{Bear}","Bear").replace("@UUID[Compendium.pf2e.classfeatures.Bull Animal Instinct]{Bull}","Bull").replace("@UUID[Compendium.pf2e.classfeatures.Cat Animal Instinct]{Cat}","Cat").replace("@UUID[Compendium.pf2e.classfeatures.Deer Animal Instinct]{Deer}","Deer").replace("@UUID[Compendium.pf2e.classfeatures.Frog Animal Instinct]{Frog}","Frog").replace("@UUID[Compendium.pf2e.classfeatures.Shark Animal Instinct]{Shark}","Shark").replace("@UUID[Compendium.pf2e.classfeatures.Snake Animal Instinct]{Snake}","Snake").replace("@UUID[Compendium.pf2e.classfeatures.Wolf Animal Instinct]{Wolf}","Wolf").replace("@UUID[Compendium.pf2e.classfeatures.Black Dragon Instinct]{Black}","Black").replace("@UUID[Compendium.pf2e.classfeatures.Blue Dragon Instinct]{Blue}","Blue").replace("@UUID[Compendium.pf2e.classfeatures.Green Dragon Instinct]{Green}","Green").replace("@UUID[Compendium.pf2e.classfeatures.Red Dragon Instinct]{Red}","Red").replace("@UUID[Compendium.pf2e.classfeatures.White Dragon Instinct]{White}","White").replace("@UUID[Compendium.pf2e.classfeatures.Brass Dragon Instinct]{Brass}","Brass").replace("@UUID[Compendium.pf2e.classfeatures.Bronze Dragon Instinct]{Bronze}","Bronze").replace("@UUID[Compendium.pf2e.classfeatures.Copper Dragon Instinct]{Copper}","Copper").replace("@UUID[Compendium.pf2e.classfeatures.Gold Dragon Instinct]{Gold}","Gold").replace("@UUID[Compendium.pf2e.classfeatures.Silver Dragon Instinct]{Silver}","Silver")}}class Migration831ClericDoctrines extends MigrationBase{static{__name(this,"Migration831ClericDoctrines")}static{__name2(this,"Migration831ClericDoctrines")}static version=.831;get#cloisteredClericSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.cleric",value:{firstDoctrine:"Compendium.pf2e.classfeatures.aiwxBj5MjnafCMyn",secondDoctrine:"Compendium.pf2e.classfeatures.sa7BWfnyCswAvBVa",thirdDoctrine:"Compendium.pf2e.classfeatures.s8WEmc4GGZSHSC7q",fourthDoctrine:"Compendium.pf2e.classfeatures.vxOf4LXZcqUG3P7a",fifthDoctrine:"Compendium.pf2e.classfeatures.n9W8MjjRgPpUTvWf",finalDoctrine:"Compendium.pf2e.classfeatures.DgGefatQ4v6xT6f9"}}}get#warpriestSetFlags(){return{key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.cleric",value:{firstDoctrine:"Compendium.pf2e.classfeatures.xxkszluN9icAiTO4",secondDoctrine:"Compendium.pf2e.classfeatures.D34mPo29r1J3DPaX",thirdDoctrine:"Compendium.pf2e.classfeatures.Zp81uTBItG1xlH4O",fourthDoctrine:"Compendium.pf2e.classfeatures.px3gVYp7zlEQIpcl",fifthDoctrine:"Compendium.pf2e.classfeatures.kmimy4VOaoEOgOiQ",finalDoctrine:"Compendium.pf2e.classfeatures.N1ugDqZlslxbp3Uy"}}}async updateItem(source){if(!(source.type!=="feat"||!source.system.slug)&&!source.system.rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="flags.pf2e.cleric"))switch(source.system.slug){case"cloistered-cleric":{source.system.rules.push(this.#cloisteredClericSetFlags);break}case"warpriest":{source.system.rules.push(this.#warpriestSetFlags);break}}}}class Migration832ChoiceSetFlags extends MigrationBase{static{__name(this,"Migration832ChoiceSetFlags")}static{__name2(this,"Migration832ChoiceSetFlags")}static version=.832;async updateItem(source){const choiceSets=source.system.rules.filter(r=>r.key==="ChoiceSet"&&"flag"in r&&typeof r.flag=="string");for(const choiceSet of choiceSets){const originalFlag=choiceSet.flag;if(choiceSet.flag=sluggify(choiceSet.flag,{camel:"dromedary"}),choiceSet.flag!==originalFlag){console.log(`${originalFlag} ->> ${choiceSet.flag}`);const pattern=new RegExp(String.raw`\brulesSelections\.${originalFlag}\b`,"g");source.system.rules=source.system.rules.map(r=>r.key==="ChoiceSet"?r:recursiveReplaceString(r,s=>s.replace(pattern,`rulesSelections.${choiceSet.flag}`)))}}}}class Migration833AddRogueToysFixPrecision extends MigrationBase{static{__name(this,"Migration833AddRogueToysFixPrecision")}static{__name2(this,"Migration833AddRogueToysFixPrecision")}static version=.833;async updateItem(source){if(source.type!=="feat")return;const flatFootedId="game"in globalThis?"AJh5ex99aV6VTggg":"Flat-Footed";switch(source.system.slug){case"surprise-attack":{const rules=[{key:"EphemeralEffect",predicate:["encounter:round:1",{lt:["self:participant:initiative:rank","target:participant:initiative:rank"]},{or:["self:participant:initiative:stat:deception","self:participant:initiative:stat:stealth"]}],selectors:["strike-attack-roll","spell-attack-roll","strike-damage","attack-spell-damage"],uuid:`Compendium.pf2e.conditionitems.Item.${flatFootedId}`}];source.system.rules=rules;break}case"dread-striker":{const rules=[{key:"EphemeralEffect",predicate:["target:condition:frightened"],selectors:["strike-attack-roll","spell-attack-roll","strike-damage","attack-spell-damage"],uuid:`Compendium.pf2e.conditionitems.Item.${flatFootedId}`}];source.system.rules=rules;break}case"precision":{if(source.system.rules.some(r=>"damageType"in r&&r.damageType==="precision")){const rules=[{domain:"all",key:"RollOption",label:"PF2E.SpecificRule.Ranger.HuntersEdge.FirstAttack",option:"first-attack",toggleable:!0},{category:"precision",diceNumber:"ternary(lt(@actor.level, 11), 1, ternary(lt(@actor.level, 19), 2, 3))",dieSize:"d8",key:"DamageDice",predicate:["first-attack"],selector:"strike-damage"}];source.system.rules=rules}break}}}}const FEAT_CATEGORIES=new Set(["ancestry","bonus","class","general","skill"]),FEATURE_CATEGORIES=new Set(["ancestryfeature","classfeature","curse","deityboon","pfsboon"]),FEAT_OR_FEATURE_CATEGORIES=new Set(["ancestry","ancestryfeature","bonus","class","classfeature","curse","deityboon","general","pfsboon","skill"]);class Migration834FeatCategories extends MigrationBase{static{__name(this,"Migration834FeatCategories")}static{__name2(this,"Migration834FeatCategories")}static version=.834;#updateCategoryData(system){const{traits}=system;if("featType"in system&&isObject(system.featType)){const category=system.featType.value;delete system.featType,"game"in globalThis&&(system["-=featType"]=null),category==="archetype"?(system.category=system.traits.value.includes("skill")?"skill":"class",traits.value.includes("archetype")||(traits.value.push("archetype"),traits.value.sort())):setHasElement(FEAT_OR_FEATURE_CATEGORIES,category)&&(system.category=category)}setHasElement(FEAT_OR_FEATURE_CATEGORIES,system.category)||(system.category="bonus"),system.category==="skill"&&!traits.value.includes("archetype")&&!traits.value.includes("general")&&(system.traits.value.push("general"),system.traits.value.sort())}async updateItem(source){source.type==="feat"&&this.#updateCategoryData(source.system);const choiceSets=source.system.rules.filter(r=>r.key==="ChoiceSet");for(const rule of choiceSets)isObject(rule.allowedDrops)&&"predicate"in rule.allowedDrops&&Array.isArray(rule.allowedDrops.predicate)&&(rule.allowedDrops.predicate=recursiveReplaceString(rule.allowedDrops.predicate,s=>s.replace(/\bfeat(?:ure)?-type\b/,"category"))),isObject(rule.choices)&&"query"in rule.choices&&typeof rule.choices.query=="string"&&(rule.choices.query=rule.choices.query.replace('"featType.value":"archetype"','"category":"class"').replace("featType.value","category"))}}class Migration835InitiativeLongform extends MigrationBase{static{__name(this,"Migration835InitiativeLongform")}static{__name2(this,"Migration835InitiativeLongform")}static version=.835;async updateActor(actor){if(!("initiative"in actor.system.attributes))return;const initiative=actor.system.attributes.initiative;if(!initiative||!initiative.ability)return;const ability=initiative.ability;objectHasKey(SKILL_DICTIONARY,ability)?initiative.statistic=SKILL_DICTIONARY[ability]:initiative.statistic="perception",delete initiative.ability,initiative["-=ability"]=null}}class Migration836EnergizingConsolidation extends MigrationBase{static{__name(this,"Migration836EnergizingConsolidation")}static{__name2(this,"Migration836EnergizingConsolidation")}static version=.836;#rename(text){const newEffectEnergizingRune="equipment-effects.R5ywXEYZFV1WBe8t";return text.replace("equipment-effects.ClsVhp5baFRjZQ23",newEffectEnergizingRune).replace("equipment-effects.68xcDyxsNgD3JddD",newEffectEnergizingRune).replace("equipment-effects.9BsFdrEc7hkPWgSd",newEffectEnergizingRune).replace("equipment-effects.ascxqSlMEN9R6OOy",newEffectEnergizingRune).replace("equipment-effects.4RnEUeYEzC919GZR",newEffectEnergizingRune)}async updateItem(source){source.system.description.value.includes("equipment-effects")&&(source.system.description.value=this.#rename(source.system.description.value))}}class Migration837MoveHazardBookSources extends MigrationBase{static{__name(this,"Migration837MoveHazardBookSources")}static{__name2(this,"Migration837MoveHazardBookSources")}static version=.837;async updateActor(source){if(source.type==="hazard"&&isObject(source.system.source)){const value=typeof source.system.source.value=="string"?source.system.source.value:"",author=typeof source.system.source.author=="string"?source.system.source.author:"";source.system.details.source={value,author},"game"in globalThis?source.system["-=source"]=null:delete source.system.source}}}class Migration838StrikeAttackRollSelector extends MigrationBase{static{__name(this,"Migration838StrikeAttackRollSelector")}static{__name2(this,"Migration838StrikeAttackRollSelector")}static version=.838;async updateItem(source){Array.isArray(source.system.rules)||(source.system.rules=[]);for(const rule of source.system.rules)"selector"in rule&&(rule.selector==="mundane-attack"?rule.selector="strike-attack-roll":Array.isArray(rule.selector)&&(rule.selector=rule.selector.map(s=>s==="mundane-attack"?"strike-attack-roll":s)))}}class Migration839ActionCategories extends MigrationBase{static{__name(this,"Migration839ActionCategories")}static{__name2(this,"Migration839ActionCategories")}static version=.839;async updateItem(source,actorSource){if(source.type!=="action")return;const system=source.system;if(system.actionCategory){const npcCategories=["offensive","defensive","interaction"],oldValue=system.actionCategory.value||null,mustBeNull=oldValue&&npcCategories.includes(oldValue)&&actorSource&&actorSource.type!=="npc";system.category=mustBeNull?null:oldValue,delete system.actionCategory,system["-=actionCategory"]=null}}}class Migration840ArrayWrapPredicates extends MigrationBase{static{__name(this,"Migration840ArrayWrapPredicates")}static{__name2(this,"Migration840ArrayWrapPredicates")}static version=.84;#wrapPredicate(predicate){if(Array.isArray(predicate))return predicate;const arrayWrapped=[predicate];return predicate&&PredicatePF2e.isValid(arrayWrapped)?arrayWrapped:void 0}async updateItem(source){for(const rule of source.system.rules)"predicate"in rule&&(rule.predicate=this.#wrapPredicate(rule.predicate)),"definition"in rule&&(rule.definition=this.#wrapPredicate(rule.definition))}}class Migration841V11UUIDFormat extends MigrationBase{static{__name(this,"Migration841V11UUIDFormat")}static{__name2(this,"Migration841V11UUIDFormat")}static version=.841;#replaceUUID(uuid,explicitDocType){if(typeof uuid!="string"||!uuid.startsWith("Compendium."))return uuid;const documentType=(()=>{if(explicitDocType)return explicitDocType;if("game"in globalThis){const{collection}=foundry.utils.parseUuid(uuid)??{};return collection instanceof CompendiumCollection?collection.metadata.type??null:null}return null})();if(!documentType)return uuid;const parts=uuid.split(/\.(?! )/);if(parts.length!==4)return uuid;const[head,scope,pack,id]=parts;return`${head}.${scope}.${pack}.${documentType}.${id}`}#replaceUUIDsInLinks(text){return typeof text!="string"?text:Array.from(text.matchAll(/(?<=@UUID\[)[^\]]+(?=\])/g)).reduce((replaced,[link])=>replaced.replace(link,s=>this.#replaceUUID(s)),text)}async updateActor(source){if(source.flags.core?.sourceId&&(source.flags.core.sourceId=this.#replaceUUID(source.flags.core.sourceId,"Actor")),source.type==="character"){if(isObject(source.system.crafting)&&Array.isArray(source.system.crafting.formulas))for(const formula of source.system.crafting.formulas)formula.uuid=this.#replaceUUID(formula.uuid,"Item")}else if(source.type==="npc"){const{details}=source.system;details.publicNotes&&=this.#replaceUUIDsInLinks(details.publicNotes),details.privateNotes&&=this.#replaceUUIDsInLinks(details.privateNotes)}else if(source.type==="hazard"){const{details}=source.system;details.reset&&=this.#replaceUUIDsInLinks(details.reset),details.description&&=this.#replaceUUIDsInLinks(details.description),details.routine&&=this.#replaceUUIDsInLinks(details.routine),details.disable&&=this.#replaceUUIDsInLinks(details.disable)}}async updateItem(source){if(source.flags.core?.sourceId&&(source.flags.core.sourceId=this.#replaceUUID(source.flags.core.sourceId,"Item")),source.system.rules=source.system.rules.map(rule=>("text"in rule&&typeof rule.text=="string"&&(rule.text=this.#replaceUUIDsInLinks(rule.text)),recursiveReplaceString(rule,s=>this.#replaceUUID(s,"Item")))),itemIsOfType(source,"ancestry","background","class","kit")){const items=source.system.items;for(const entry of Object.values(items))if(entry.uuid=this.#replaceUUID(entry.uuid,"Item"),isObject(entry.items))for(const subentry of Object.values(entry.items))subentry.uuid=this.#replaceUUID(subentry.uuid,"Item")}else if(source.type==="heritage")source.system.ancestry?.uuid&&(source.system.ancestry.uuid=this.#replaceUUID(source.system.ancestry.uuid,"Item"));else if(source.type==="deity")for(const[key,spell]of Object.entries(source.system.spells))source.system.spells[Number(key)]=this.#replaceUUID(spell);const{description}=source.system;description.value??="",description.value=this.#replaceUUIDsInLinks(description.value),description.value=description.value.replace(/Compendium\.pf2e\.journals\.(?!JournalEntry)/g,"Compendium.pf2e.journals.JournalEntry."),description.gm&&=this.#replaceUUIDsInLinks(description.gm)}async updateJournalEntry(source){for(const page of source.pages)page.text.content&&=this.#replaceUUIDsInLinks(page.text.content)}}class Migration842NumifyNumericSettings extends MigrationBase{static{__name(this,"Migration842NumifyNumericSettings")}static{__name2(this,"Migration842NumifyNumericSettings")}static version=.842;async migrate(){for(const setting of["staminaVariant","worldClock.timeConvention"]){const value=game.settings.storage.get("world").getItem(`pf2e.${setting}`);value!==null&&typeof value!="number"&&await game.settings.set("pf2e",setting,Number(value))}}}class Migration843RMArmorCustomModifiers extends MigrationBase{static{__name(this,"Migration843RMArmorCustomModifiers")}static{__name2(this,"Migration843RMArmorCustomModifiers")}static version=.843;async updateActor(source){if(source.type==="character"&&source.system.customModifiers?.armor){const customModifiers=source.system.customModifiers;customModifiers["-=armor"]=null}}}class Migration844DeityDomainUUIDs extends MigrationBase{static{__name(this,"Migration844DeityDomainUUIDs")}static{__name2(this,"Migration844DeityDomainUUIDs")}static version=.844;#updateUUIDs(text){return this.#idMap.reduce((oldText,data)=>{const pattern=new RegExp(String.raw`\bCompendium\.pf2e\.domains\.(?:JournalEntry?\.)?(?:${data.oldId}|${data.name})\](?:\{[^}]+})?`,"g");return oldText.replace(pattern,`Compendium.pf2e.journals.JournalEntry.EEZvDB1Z7ezwaxIr.JournalEntryPage.${data.pageId}]{${data.name}}`)},text)}async updateActor(source){source.type==="npc"&&(source.system.details.publicNotes&&=this.#updateUUIDs(source.system.details.publicNotes))}async updateItem(source){source.system.description.gm&&=this.#updateUUIDs(source.system.description.gm),source.system.description.value&&=this.#updateUUIDs(source.system.description.value)}#idMap=[{oldId:"0cbxczrql4MwAHwV",name:"Glyph Domain",pageId:"9g1dNytABTpmmGkG"},{oldId:"1BU8deh48XZFclWl",name:"Healing Domain",pageId:"A7vErdGAweYsFcW8"},{oldId:"1NHV4ujqoR2JVWpY",name:"Travel Domain",pageId:"bTujFcUut9RX4GCy"},{oldId:"1aoUqGYDrdpnPWio",name:"Family Domain",pageId:"SAnmegCTIqGW9S7S"},{oldId:"41qaGiMit8nDP4xv",name:"Abomination Domain",pageId:"qMS6QepvY7UQQjcr"},{oldId:"6klWznsb0f2bNg3T",name:"Void Domain",pageId:"xLxrtbsj4acqgsyC"},{oldId:"8ITGLquhimrr9CNv",name:"Indulgence Domain",pageId:"GiuzDTtkQAgtGW6n"},{oldId:"8pPvbTMZLIsvCwQk",name:"Darkness Domain",pageId:"CM9ZqWwl7myKn2X1"},{oldId:"9blxcDLIRPWenK5f",name:"Plague Domain",pageId:"hGoWOjdsUz16oJUm"},{oldId:"9tsJg13xeJLGzzGV",name:"Undeath Domain",pageId:"RIlgBuWGfHC1rzYu"},{oldId:"AaY3BmDItGry4oac",name:"Decay Domain",pageId:"cAxBEZsej32riaY5"},{oldId:"B40VxP6oZ0mIR4PS",name:"Fate Domain",pageId:"EC2eB0JglDG5j1gT"},{oldId:"BlovCvjhk4Ag07w2",name:"Dreams Domain",pageId:"0wCEUwABKPdKPj8e"},{oldId:"FJ9D4qpeRhJvjHai",name:"Star Domain",pageId:"6bDpXy7pQdGrd2og"},{oldId:"HYe7Yv1fYUANVVI3",name:"Death Domain",pageId:"798PFdS8FmefcOl0"},{oldId:"HpZ4NQIqBRcFihyE",name:"Wealth Domain",pageId:"mJBp4KIszuqrmnp5"},{oldId:"J7K7kHoIE69558Su",name:"Freedom Domain",pageId:"5MjSsuKOLBoiL8FB"},{oldId:"KXFxeEyD6MmJ3a6V",name:"Naga Domain",pageId:"QzsUe3Rt3SifTQvb"},{oldId:"KzuJAIWdjwoPjHkc",name:"Secrecy Domain",pageId:"S1gyomjojgtCdxc3"},{oldId:"M7koZH0zimcMgRDb",name:"Destruction Domain",pageId:"AOQZjqgfafqqtHOB"},{oldId:"MRHDhBQvgJhDZ1zq",name:"Cities Domain",pageId:"QSk78hQR3zskMlq2"},{oldId:"MktBsoHR9HsKrbbr",name:"Zeal Domain",pageId:"DI3MYGIK8iEycanU"},{oldId:"NA4v0iwIPgkde8DP",name:"Ambition Domain",pageId:"yaMJsfYZmWJLqbFE"},{oldId:"NEI4MDBGNjEtOEIy",name:"Introspection Domain",pageId:"qjnUXickBOBDBu2N"},{oldId:"O1qeC0mIufSf3wv5",name:"Passion Domain",pageId:"ajCEExOaxuB4C1tY"},{oldId:"OsM8NfP408uB6yTi",name:"Wyrmkin Domain",pageId:"nuywscaiVGXLQpZ1"},{oldId:"PrFvU65ewfst69Mp",name:"Water Domain",pageId:"U8WVR6EDfmUaMCbu"},{oldId:"TpFgfwcWrfT8zVMP",name:"Pain Domain",pageId:"FtW1gtbHgO0KofPl"},{oldId:"WrmaTmOHojfhiENF",name:"Truth Domain",pageId:"lgsJz7mZ1OTe340e"},{oldId:"X7MkBRJGUIp91k6f",name:"Sorrow Domain",pageId:"5TqEbLR9QT3gJGe3"},{oldId:"Xs6XznYHOZyQ0hJl",name:"Tyranny Domain",pageId:"T0JHj79aGphlZ4Mt"},{oldId:"Y2kOBQydrsSqGCyn",name:"Magic Domain",pageId:"DS95vr2zmTsjsMhU"},{oldId:"YQ6IT8DgEpqvOREx",name:"Might Domain",pageId:"MOVMHZU1SfkhNN1K"},{oldId:"ZAx1RUB376BjNdlF",name:"Repose Domain",pageId:"CbsAiY68e8n5vVVN"},{oldId:"Ze2hoTyOQHbaQ6jD",name:"Air Domain",pageId:"T2y0vuYibZCL7CH0"},{oldId:"ZyFTUCbA0zYrzynD",name:"Creation Domain",pageId:"ydbCjJ9PPmRzZhDN"},{oldId:"a0fe0kFowMMwUFZa",name:"Nightmares Domain",pageId:"R20JXF43vU5RQyUj"},{oldId:"c9odhpRoKId5dXmn",name:"Perfection Domain",pageId:"Czi3XXuNOSE7ISpd"},{oldId:"dnljU1twPjH4KFgO",name:"Swarm Domain",pageId:"rd0jQwvTK4jpv95o"},{oldId:"fVfFKKvGocG2JM5q",name:"Toil Domain",pageId:"EQfZepZX6rxxBRqG"},{oldId:"fqr2OnTww3bAq0ae",name:"Sun Domain",pageId:"CkBvj5y1lAm1jnsc"},{oldId:"giUsAWI9NbpdeUzl",name:"Knowledge Domain",pageId:"0GwpYEjCHWyfQvgg"},{oldId:"i4UU3qCjIMwejIQF",name:"Delirium Domain",pageId:"tuThzOCvMLbRVba8"},{oldId:"jWmGQxJvKh5y5zfB",name:"Protection Domain",pageId:"Dx47K8wpx8KZUa9S"},{oldId:"l2EFJssJKu7rG77m",name:"Luck Domain",pageId:"L11XsA5G89xVKlDw"},{oldId:"mBvjWSvg7UYdS9TL",name:"Moon Domain",pageId:"Y3DFBCWiM9GBIlfl"},{oldId:"p5Q5RGl1lKgs5DZZ",name:"Soul Domain",pageId:"rtobUemb6vF2Yu3Y"},{oldId:"rIDXRIdb9m2E3qC6",name:"Earth Domain",pageId:"zkiLWWYzzqoxmN2J"},{oldId:"rIZ7OoG8c4Cct42M",name:"Vigil Domain",pageId:"StXN6IHR6evRaeXF"},{oldId:"udASTZy5jJWFCt5w",name:"Time Domain",pageId:"3P0NWwP3s7bIiidH"},{oldId:"unN0otycQZanf3va",name:"Duty Domain",pageId:"uGQKjk2w4whzomky"},{oldId:"uy8GUGIOmEUNqIhH",name:"Trickery Domain",pageId:"xJtbGqoz3BcCjUik"},{oldId:"v4SDXgCuPdZqhMeL",name:"Fire Domain",pageId:"egSErNozlL3HRK1y"},{oldId:"wCPGej4ZwdKCNtym",name:"Change Domain",pageId:"7xrNAgAnBqBgE3yM"},{oldId:"wPtGuF1bh4wvKE6Q",name:"Confidence Domain",pageId:"flmxRzGxN2rRNyxZ"},{oldId:"xYx8UD0JnFyBHGhJ",name:"Nature Domain",pageId:"wBhgIgt47v9uspp3"},{oldId:"y3TTKFLPbP09HZUW",name:"Cold Domain",pageId:"jq9O1tl76g2AzLOh"},{oldId:"ywn4ODaUt382Z3Nz",name:"Lightning Domain",pageId:"Kca7UPuMm44tOo9n"},{oldId:"zec5N7EnDJANGHmy",name:"Dust Domain",pageId:"6qTjtFWaBO5b60zJ"}]}class Migration845EmptySpellConsumables extends MigrationBase{static{__name(this,"Migration845EmptySpellConsumables")}static{__name2(this,"Migration845EmptySpellConsumables")}static version=.845;async preUpdateItem(source){if(source.type==="consumable"){const spell=source.system.spell;isObject(spell)&&!["_id","name","type","system"].every(p=>p in spell)&&(source.system.spell=null)}}}class Migration846SpellSchoolOptional extends MigrationBase{static{__name(this,"Migration846SpellSchoolOptional")}static{__name2(this,"Migration846SpellSchoolOptional")}static version=.846;async updateItem(source){if(source.type!=="spell")return;const system=source.system;if(system.school){const traits=system.traits;traits.value=uniq(compact([...source.system.traits.value,system.school.value])),system["-=school"]=null,delete system.school}}}class Migration847TempHPRuleEvents extends MigrationBase{static{__name(this,"Migration847TempHPRuleEvents")}static{__name2(this,"Migration847TempHPRuleEvents")}static version=.847;async updateItem(source){const rules=source.system.rules.filter(r=>r.key==="TempHP");for(const rule of rules)rule.onCreate!==void 0&&(rule.events??={},rule.events.onCreate=rule.onCreate,delete rule.onCreate),rule.onTurnStart!==void 0&&(rule.events??={},rule.events.onTurnStart=rule.onTurnStart,delete rule.onTurnStart)}}class Migration848NumericArmorProperties extends MigrationBase{static{__name(this,"Migration848NumericArmorProperties")}static{__name2(this,"Migration848NumericArmorProperties")}static version=.848;#oldToNew=[["armor","acBonus"],["dex","dexCap"],["check","checkPenalty"],["speed","speedPenalty"],["strength","strength"]];async updateItem(source){if(source.type==="armor")for(const[oldKey,newKey]of this.#oldToNew){const oldProperty=source.system[oldKey],newProperty=isObject(source.system[newKey])?0:source.system[newKey]??0;if(isObject(oldProperty)&&newProperty===0)if(delete source.system[oldKey],oldKey==="strength"){const value=Number(oldProperty.value)||null;source.system[newKey]=value===null?null:Math.max(Math.floor((value-10)/2),0)}else tupleHasValue(["checkPenalty","speedPenalty"],newKey)?(source.system[newKey]=Number(oldProperty.value)||0,source.system[`-=${oldKey}`]=null):(source.system[newKey]=Number(oldProperty.value)||0,source.system[`-=${oldKey}`]=null)}}}class Migration849DeleteBrokenThreshold extends MigrationBase{static{__name(this,"Migration849DeleteBrokenThreshold")}static{__name2(this,"Migration849DeleteBrokenThreshold")}static version=.849;async updateItem(source){const hitPoints="hp"in source.system&&isObject(source.system.hp)?source.system.hp:null;isObject(hitPoints)&&"brokenThreshold"in hitPoints&&(delete hitPoints.brokenThreshold,hitPoints["-=brokenThreshold"]=null)}}class Migration850FlatFootedToOffGuard extends MigrationBase{static{__name(this,"Migration850FlatFootedToOffGuard")}static{__name2(this,"Migration850FlatFootedToOffGuard")}static version=.85;#oldNamePattern=new RegExp(/\bFlat-Footed\b/g);#newName="Off-Guard";#imgPattern=/(?<=systems\/pf2e\/icons\/conditions(?:-2)?\/)flat-?footed.webp$/i;#aToAnUUIDPatern=/\ba(?= @UUID\[Compendium\.pf2e\.conditionitems\.Item\.(?:Flat-Footed|AJh5ex99aV6VTggg)\])/g;#replace(text){return text.replace(this.#imgPattern,"off-guard.webp").replace(/^flat-footed$/,"off-guard").replace(/(?<=[:.])flat-footed\b/g,"off-guard").replace(/\.Flat-Footed\b/g,".Off-Guard").replace(/\bFlatFooted\b/g,"OffGuard").replace(/\.flatFootable\b/g,".offGuardable").replace(this.#oldNamePattern,"Off-Guard").replace(/\bflatfooted\b/g,"flat-footed").replace(/\ba flat-footed\b/g,"an off-guard").replace(this.#aToAnUUIDPatern,"an").replace(/\bFlat-footed\b/g,"Off-guard").replace(/\bflat-footed\b/g,"off-guard")}async updateActor(source){source.type==="hazard"&&(source.system.details.routine&&=this.#replace(source.system.details.routine)),"attributes"in source.system&&isObject$1(source.system.attributes)&&"immunities"in source.system.attributes&&(source.system.attributes.immunities=recursiveReplaceString(source.system.attributes.immunities,s=>this.#replace(s)))}async updateItem(source){source.name=source.name.replace(this.#oldNamePattern,this.#newName),source.img=source.img.replace(this.#imgPattern,"off-guard.webp"),source.system=recursiveReplaceString(source.system,s=>this.#replace(s))}async updateJournalEntry(source){source.name!=="Remaster Changes"&&(source.name=source.name.replace(this.#oldNamePattern,this.#newName),"img"in source&&typeof source.img=="string"&&(source.img=source.img.replace(this.#imgPattern,"off-guard.webp")),source.pages=recursiveReplaceString(source.pages,s=>this.#replace(s)),"content"in source&&typeof source.content=="string"&&(source.content=this.#replace(source.content)))}}class Migration851JustInnovationId extends MigrationBase{static{__name(this,"Migration851JustInnovationId")}static{__name2(this,"Migration851JustInnovationId")}static version=.851;async updateItem(source){if(source.type!=="feat")return;source.system.rules=source.system.rules.map(r=>recursiveReplaceString(r,s=>s.replace("flags.pf2e.armorInnovationId","flags.pf2e.innovationId")));const hasAELike=source.system.rules.some(r=>r.key==="ActiveEffectLike"&&r.path==="flags.pf2e.innovationId");if(source.system.slug==="weapon-innovation"&&!hasAELike){const reSource={key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.innovationId",value:"{item|flags.pf2e.itemGrants.weaponInnovation.id}"};source.system.rules.push(reSource)}else if(source.system.slug==="construct-innovation"&&!hasAELike){const reSource={key:"ActiveEffectLike",mode:"override",path:"flags.pf2e.innovationId",value:null};source.system.rules.push(reSource)}else if(source.system.slug==="inventor-weapon-expertise"&&!source.system.rules.some(r=>r.key==="CriticalSpecialization")){const reSource={key:"CriticalSpecialization",predicate:["feature:weapon-innovation","item:id:{actor|flags.pf2e.innovationId}"]};source.system.rules.push(reSource)}}}class Migration852AbilityScoresToModifiers extends MigrationBase{static{__name(this,"Migration852AbilityScoresToModifiers")}static{__name2(this,"Migration852AbilityScoresToModifiers")}static version=.852;async updateActor(source){if(source.type!=="character")return;if(source.system.abilities&&Object.keys(source.system.abilities).length>0){const abilityObjects=Object.values(source.system.abilities);for(const data of abilityObjects)typeof data.value=="number"&&(data.mod=Math.min(Math.max(Math.trunc((data.value-10)/2),-5),10)||0,delete data.value,data["-=value"]=null)}else if(source.system.abilities){const systemData=source.system;delete systemData.abilities,systemData["-=abilities"]=null}const build=source.system.build??{};build.abilities&&(build.attributes=build.abilities,delete build.abilities,build["-=abilities"]=null)}async updateItem(source){const apexRules=source.system.rules.filter(r=>r.key==="ActiveEffectLike"&&typeof r.path=="string"&&/^system\.abilities\..+\.value$/.test(r.path)&&typeof r.value=="number");for(const rule of apexRules)switch(rule.path=rule.path.replace(/\.value$/,".mod"),rule.mode){case"add":case"remove":case"subtract":rule.value=Math.min(Math.max(Math.trunc(rule.value/2),-5),10)||0;break;case"downgrade":case"override":case"upgrade":rule.value=Math.min(Math.max(Math.trunc((rule.value-10)/2),-5),10)||0;break}const otherRules=source.system.rules.filter(r=>"value"in r&&typeof r.value=="string"&&/\.abilities\.[a-z]{3}\.value\b/.test(r.value));for(const rule of otherRules)rule.value=rule.value.replace(/(?:floor\()?\(?@actor.abilities.([a-z]{3})\.value ?- ?10\) ?\/ ?2\)?/,"@actor.abilities.$1.mod").replace(/\s+/g," ").trim();if(source.system.slug==="thaumaturges-investiture"){source.system.rules=source.system.rules.filter(r=>r.key!=="ActiveEffectLike");const bracketedAELike={key:"ActiveEffectLike",mode:"upgrade",path:"system.resources.investiture.max",value:{brackets:[{end:4,start:4,value:14},{end:5,start:5,value:16},{end:6,start:6,value:18},{start:7,value:20}],field:"system.abilities.cha.mod"}};source.system.rules.push(bracketedAELike)}}}class Migration853RemasterLanguages extends MigrationBase{static{__name(this,"Migration853RemasterLanguages")}static{__name2(this,"Migration853RemasterLanguages")}static version=.853;#OLD_TO_NEW_LANGUAGES=new Map([["aquan","thalassic"],["auran","sussuran"],["ignan","pyric"],["sylvan","fey"],["terran","petran"]]);async updateActor(source){const languages=source.system.traits?.languages??{};languages?.value&&(languages.value=languages.value.map(l=>this.#OLD_TO_NEW_LANGUAGES.get(l)??l).sort())}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>this.#OLD_TO_NEW_LANGUAGES.get(s)??s),source.type==="ancestry"&&Array.isArray(source.system.additionalLanguages?.value)&&source.system.additionalLanguages.value.sort()}}class Migration854BracketedAbilityScoresToModifiers extends MigrationBase{static{__name(this,"Migration854BracketedAbilityScoresToModifiers")}static{__name2(this,"Migration854BracketedAbilityScoresToModifiers")}static version=.854;async updateItem(source){const aeLikes=source.system.rules.filter(r=>r.key==="ActiveEffectLike"&&typeof r.path=="string"&&/^system\.abilities\..+\.value$/.test(r.path)&&isObject(r.value)&&typeof r.value.field=="string"&&/^actor\|system\.abilities\.[a-z]{3}\.value$/.test(r.value.field)&&Array.isArray(r.value.brackets)&&r.value.brackets.every(b=>isObject(b)&&typeof b.value=="number"));for(const aeLike of aeLikes){aeLike.path=aeLike.path.replace(/\.value$/,".mod"),aeLike.value.field&&=aeLike.value.field.replace(/\.value$/,".mod");for(const bracket of aeLike.value.brackets)typeof bracket.start=="number"&&(bracket.start=Math.trunc((bracket.start-10)/2)),typeof bracket.end=="number"&&(bracket.end=Math.trunc((bracket.end-10)/2)),bracket.value=bracket.value/2}}}class Migration855ApexEquipmentSystemData extends MigrationBase{static{__name(this,"Migration855ApexEquipmentSystemData")}static{__name2(this,"Migration855ApexEquipmentSystemData")}static version=.855;async updateItem(source){if(source.type!=="equipment"||!source.system.traits.value.includes("apex"))return;const attributeModPattern=/^system\.abilities\.([a-z]{3})\.mod$/,isApexRE=__name2(r=>r.key==="ActiveEffectLike"&&attributeModPattern.test(String(r.path)),"isApexRE"),apexAttribute=source.system.rules.flatMap(r=>isApexRE(r)?attributeModPattern.exec(String(r.path))?.at(1):[]).shift();setHasElement(ATTRIBUTE_ABBREVIATIONS,apexAttribute)&&(source.system.apex??={attribute:apexAttribute},source.system.rules=source.system.rules.filter(r=>!isApexRE(r)))}}class Migration856NoSystemDotCustom extends MigrationBase{static{__name(this,"Migration856NoSystemDotCustom")}static{__name2(this,"Migration856NoSystemDotCustom")}static version=.856;async updateItem(source){source.system.rules=source.system.rules.map(r=>recursiveReplaceString(r,s=>s.replace(/\bsystem\.custom\.(?:modifiers\.)?([-a-z]+)/,(_match,group1)=>`flags.pf2e.${sluggify(group1,{camel:"dromedary"})}`)))}}class Migration857WeaponSpecializationRE extends MigrationBase{static{__name(this,"Migration857WeaponSpecializationRE")}static{__name2(this,"Migration857WeaponSpecializationRE")}static version=.857;async updateItem(source){const slug=source.system.slug??sluggify(source.name);source.type!=="feat"||!slug.includes("weapon-specialization")||slug.includes("eidolon-weapon-specialization")||source.system.rules.some(r=>r.slug==="weapon-specialization")||(slug.includes("greater-weapon-specialization")?source.system.rules.unshift({key:"AdjustModifier",mode:"multiply",relabel:"PF2E.GreaterWeaponSpecialization",selector:"strike-damage",slug:"weapon-specialization",value:2}):source.system.rules.unshift({hideIfDisabled:!0,key:"FlatModifier",label:"PF2E.WeaponSpecialization",predicate:[{gte:["item:proficiency:rank",2]}],selector:"strike-damage",slug:"weapon-specialization",value:2},{key:"AdjustModifier",mode:"upgrade",predicate:["item:proficiency:rank:3"],priority:0,selector:"strike-damage",slug:"weapon-specialization",value:3},{key:"AdjustModifier",mode:"upgrade",predicate:["item:proficiency:rank:4"],priority:0,selector:"strike-damage",slug:"weapon-specialization",value:4}))}}class Migration858FakeWeaponSpecialization extends MigrationBase{static{__name(this,"Migration858FakeWeaponSpecialization")}static{__name2(this,"Migration858FakeWeaponSpecialization")}static version=.858;#testHasOption(source){return source.system.rules.some(r=>r.key==="RollOption"&&"option"in r&&["feature:greater-weapon-specialization","feature:weapon-specialization"].includes(String(r.option)))}async updateItem(source){if(source.type!=="feat")return;const slug=source.system.slug??sluggify(source.name);slug==="greater-weapon-specialization-barbarian"&&!this.#testHasOption(source)?source.system.rules.push({domain:"all",key:"RollOption",option:"feature:greater-weapon-specialization"}):slug==="psychic-weapon-specialization"&&!this.#testHasOption(source)&&source.system.rules.push({domain:"all",key:"RollOption",option:"feature:weapon-specialization"})}}class Migration859MaterialTypeGrade extends MigrationBase{static{__name(this,"Migration859MaterialTypeGrade")}static{__name2(this,"Migration859MaterialTypeGrade")}static version=.859;#PRECIOUS_MATERIAL_TYPES=new Set([...PRECIOUS_MATERIAL_TYPES].filter(t=>t.replace("duskwood","darkwood").replace("dawnsilver","mithral")));#hasOldMaterialData(source){return"preciousMaterial"in source.system&&isObject(source.system.preciousMaterial)&&"preciousMaterialGrade"in source.system&&isObject(source.system.preciousMaterialGrade)}async updateItem(source){if(itemIsOfType(source,"physical")&&this.#hasOldMaterialData(source)){const{preciousMaterial,preciousMaterialGrade}=source.system,type=this.#PRECIOUS_MATERIAL_TYPES.has(String(preciousMaterial?.value))?preciousMaterial?.value??null:null,grade=setHasElement(PRECIOUS_MATERIAL_GRADES,preciousMaterialGrade?.value)?preciousMaterialGrade?.value??null:null;source.system.material={type,grade},"game"in globalThis?(source.system["-=preciousMaterial"]=null,source.system["-=preciousMaterialGrade"]=null):(delete source.system.preciousMaterial,delete source.system.preciousMaterialGrade)}}}class Migration860RMGroup extends MigrationBase{static{__name(this,"Migration860RMGroup")}static{__name2(this,"Migration860RMGroup")}static version=.86;async updateItem(source){itemIsOfType(source,"armor","condition","weapon")||!("group"in source.system)||("game"in globalThis?source.system["-=group"]=null:delete source.system.group)}}class Migration861AuraColorsToAppearance extends MigrationBase{static{__name(this,"Migration861AuraColorsToAppearance")}static{__name2(this,"Migration861AuraColorsToAppearance")}static version=.861;async updateItem(source){const auraREs=source.system.rules.filter(r=>r.key==="Aura"&&"colors"in r&&isObject(r.colors));for(const rule of auraREs)rule.appearance={},typeof rule.colors?.border=="string"&&(rule.appearance.border={color:rule.colors.border}),typeof rule.colors?.fill=="string"&&(rule.appearance.highlight={color:rule.colors.fill}),delete rule.colors}}class Migration862SpecificMagicArmor extends MigrationBase{static{__name(this,"Migration862SpecificMagicArmor")}static{__name2(this,"Migration862SpecificMagicArmor")}static version=.862;#resilientRuneValues=new Map([["",0],["resilient",1],["greaterResilient",3],["majorResilient",3]]);async updateItem(source){if(source.type!=="armor"||source.system.category==="shield")return;switch(source.system.slug){case"power-suit":source.system.baseItem="power-suit";break;case"subterfuge-suit":source.system.baseItem;break;case"clothing-explorers":source.system.slug="explorers-clothing",source.name.endsWith("Clothing (Explorer's)")&&(source.name="Explorer's Clothing")}source.system.slug==="power-suit"&&(source.system.baseItem??="power-suit"),source.system.slug==="subterfuge-suit"&&(source.system.baseItem??="subterfuge-suit");const isMagical=!!("potencyRune"in source.system&&isObject$1(source.system.potencyRune)&&source.system.potencyRune.value||"resiliencyRune"in source.system&&isObject$1(source.system.resiliencyRune)&&source.system.resiliencyRune.value);if(!!(source.system.baseItem&&source.system.slug)&&isMagical&&source.system.baseItem!==source.system.slug){const system=source.system;system.specific??={value:!0,material:source.system.material??null,runes:{potency:"potencyRune"in source.system&&isObject$1(source.system.potencyRune)&&source.system.potencyRune.value?Number(source.system.potencyRune?.value)||1:0,resilient:"resiliencyRune"in source.system&&isObject$1(source.system.resiliencyRune)&&source.system.resiliencyRune.value?this.#resilientRuneValues.get(String(source.system.resiliencyRune?.value??""))||1:0,property:[]}}}}}class Migration863FixMisspelledOrganaizationsProperty extends MigrationBase{static{__name(this,"Migration863FixMisspelledOrganaizationsProperty")}static{__name2(this,"Migration863FixMisspelledOrganaizationsProperty")}static version=.863;async updateActor(source){if(source.type!=="character")return;const biography=source.system.details.biography;biography.organaizations!==void 0&&(biography.organizations=biography.organaizations,delete biography.organaizations,biography["-=organaizations"]=null)}}class Migration864RemoveWeaponMAP extends MigrationBase{static{__name(this,"Migration864RemoveWeaponMAP")}static{__name2(this,"Migration864RemoveWeaponMAP")}static version=.864;async updateItem(source){if(source.type==="weapon"&&isObject(source.system.MAP)){const mapValue=-1*Number(source.system.MAP.value);if(mapValue<0&&mapValue!==-5){const rule={key:"MultipleAttackPenalty",selector:"{item|id}-attack",value:mapValue};source.system.rules.push(rule)}"game"in globalThis?source.system["-=MAP"]=null:delete source.system.MAP}}}class Migration865VitalityVoid extends MigrationBase{static{__name(this,"Migration865VitalityVoid")}static{__name2(this,"Migration865VitalityVoid")}static version=.865;#replaceStrings(data){return recursiveReplaceString(data,s=>s.replace(/^positive$/,"vitality").replace(/^negative$/,"void").replace(/^versatile-positive$/,"versatile-vitality").replace(/^versatile-negative$/,"versatile-void").replace(/\bpositive\]/g,"vitality]").replace(/\bnegative\]/g,"void]").replace(/\[positive\b/g,"[vitality").replace(/\[negative\b/g,"[void").replace(/\bRollFlavor\.positive\b/g,"RollFlavor.vitality").replace(/\bRollFlavor\.negative\b/g,"RollFlavor.void").replace(/\bTraitPositive\b/g,"TraitVitality").replace(/\bTraitNegative\b/g,"TraitVoid").replace(/\bTraitVersatilePositive\b/g,"TraitVersatileVitality").replace(/\bTraitVersatileNegative\b/g,"TraitVersatileVoid").replace(/\bnegative negative damage\b/,"void damage"))}async updateActor(source){source.system=this.#replaceStrings(source.system),source.flags=this.#replaceStrings(source.flags)}async updateItem(source){source.system=this.#replaceStrings(source.system),source.flags=this.#replaceStrings(source.flags)}}class Migration866LinkToActorSizeAgain extends MigrationBase{static{__name(this,"Migration866LinkToActorSizeAgain")}static{__name2(this,"Migration866LinkToActorSizeAgain")}static version=.866;async updateActor(actorSource){SIZE_LINKABLE_ACTOR_TYPES.has(actorSource.type)||actorSource.prototypeToken.flags.pf2e&&(actorSource.prototypeToken.flags.pf2e.linkToActorSize=!1,actorSource.prototypeToken.flags.pf2e.autoscale=!1)}async updateToken(tokenSource,actor){!actor||SIZE_LINKABLE_ACTOR_TYPES.has(actor.type)||foundry.utils.mergeObject(tokenSource.flags,{pf2e:{linkToActorSize:!1,autoscale:!1}})}}class Migration867DamageRollDomainFix extends MigrationBase{static{__name(this,"Migration867DamageRollDomainFix")}static{__name2(this,"Migration867DamageRollDomainFix")}static version=.867;async updateItem(source){for(const rule of source.system.rules??[])"domain"in rule&&rule.domain==="damage-roll"&&(rule.domain="damage")}}class Migration868StrikeRERange extends MigrationBase{static{__name(this,"Migration868StrikeRERange")}static{__name2(this,"Migration868StrikeRERange")}static version=.868;async updateItem(source){const strikeREs=source.system.rules.filter(r=>r.key==="Strike");for(const rule of strikeREs)typeof rule.maxRange=="number"&&rule.range!==rule.maxRange/6?rule.range={max:rule.maxRange}:typeof rule.range=="number"&&(rule.range={increment:rule.range}),delete rule.maxRange}}class Migration869RefreshMightyBulwark extends MigrationBase{static{__name(this,"Migration869RefreshMightyBulwark")}static{__name2(this,"Migration869RefreshMightyBulwark")}static version=.869;get#mightyBulwarkRules(){return[{key:"FlatModifier",predicate:["armor:trait:bulwark"],selector:"reflex",value:4},{key:"AdjustModifier",predicate:["armor:trait:bulwark"],selector:"reflex",slug:"dex",suppress:!0},{key:"AdjustModifier",selector:"reflex",slug:"bulwark",suppress:!0}]}async updateItem(source){if(source.type==="feat"&&source.system.slug==="mighty-bulwark")source.system.rules=this.#mightyBulwarkRules;else for(const rule of source.system.rules)"option"in rule&&rule.option==="self:armor:strength-requirement-met"&&(rule.option="armor:strength-requirement-met")}}class Migration870MartialToProficiencies extends MigrationBase{static{__name(this,"Migration870MartialToProficiencies")}static{__name2(this,"Migration870MartialToProficiencies")}static version=.87;#defensePathPattern=new RegExp(String.raw`system\.martial\.(?:${Array.from(ARMOR_CATEGORIES).join("|")})\.`);async updateActor(source){if(source.type!=="character")return;const systemSource=source.system,oldData=isObject(systemSource.martial)&&Object.keys(systemSource.martial).length>0?systemSource.martial:{};for(const[key,data]of Object.entries(oldData))!data.rank||["simple","unarmed","unarmored"].includes(key)&&data.rank===1||(systemSource.proficiencies??={},setHasElement(ARMOR_CATEGORIES,key)?(systemSource.proficiencies.defenses??={},systemSource.proficiencies.defenses[key]={rank:data.rank}):(systemSource.proficiencies.attacks??={},systemSource.proficiencies.attacks[key]={custom:data.custom,rank:data.rank}));"game"in globalThis&&"martial"in systemSource?systemSource["-=martial"]=null:delete systemSource.martial}async updateItem(source){source.system.rules=source.system.rules.map(r=>recursiveReplaceString(r,text=>{const key=this.#defensePathPattern.test(text)?"defenses":"attacks";return text.replace(/\bsystem\.martial\./g,`system.proficiencies.${key}.`)}))}}class Migration871MigrateRollActionMacroParams extends MigrationBase{static{__name(this,"Migration871MigrateRollActionMacroParams")}static{__name2(this,"Migration871MigrateRollActionMacroParams")}static version=.871;async updateMacro(source){if(source.type!=="script")return;const matches=source.command.matchAll(/game\.pf2e\.rollActionMacro\("(.+)".*"(.+)"\)/gm);for(const match of matches){if(match.length<3)continue;const[current,itemId,slug]=match;source.command=source.command.replace(current,`game.pf2e.rollActionMacro({ itemId: "${itemId}", slug: "${slug}" })`)}}}class Migration872MoveSchemaProperty extends MigrationBase{static{__name(this,"Migration872MoveSchemaProperty")}static{__name2(this,"Migration872MoveSchemaProperty")}static version=.872;#mvSchema(systemData){const migrations=systemData._migration??={version:null,previous:null};"schema"in systemData&&(systemData["-=schema"]=null,isObject(systemData.schema)&&typeof systemData.schema.version=="number"&&(migrations.version=systemData.schema.version))}async updateActor(source){this.#mvSchema(source.system)}async updateItem(source){this.#mvSchema(source.system)}}class Migration873RemoveBonusBulkLimit extends MigrationBase{static{__name(this,"Migration873RemoveBonusBulkLimit")}static{__name2(this,"Migration873RemoveBonusBulkLimit")}static version=.873;async updateActor(source){if(source.type!=="character"&&source.type!=="npc")return;const data=source.system;"bonusLimitBulk"in data.attributes&&(delete data.attributes.bonusLimitBulk,data.attributes["-=bonusLimitBulk"]=null),"bonusEncumbranceBulk"in data.attributes&&(delete data.attributes.bonusEncumbranceBulk,data.attributes["-=bonusEncumbranceBulk"]=null)}async updateItem(source){source.system.rules=recursiveReplaceString(source.system.rules,text=>text.replace(/^system\.attributes\.bonusEncumbranceBulk$/,"inventory.bulk.encumberedAfterAddend").replace(/^system\.attributes\.bonusLimitBulk$/,"inventory.bulk.maxAddend"))}}class Migration874MoveStaminaStuff extends MigrationBase{static{__name(this,"Migration874MoveStaminaStuff")}static{__name2(this,"Migration874MoveStaminaStuff")}static version=.874;async updateActor(source){if(source.type!=="character")return;const variantEnabled="game"in globalThis&&game.settings.storage.get("world").find(s=>s.key==="pf2e.staminaVariant")?.value!=='"0"'&&game.settings.get("pf2e","staminaVariant"),systemSource=source.system;if(isObject(systemSource.attributes.sp)){const value=Math.floor(Number(systemSource.attributes.sp.value))||0;value>0&&variantEnabled&&(systemSource.attributes.hp.sp={value}),delete systemSource.attributes.sp,systemSource.attributes["-=sp"]=null}if(isObject(systemSource.attributes.resolve)){const value=Math.floor(Number(systemSource.attributes.resolve.value))||0;value>0&&variantEnabled&&(systemSource.resources.resolve={value}),delete systemSource.attributes.resolve,systemSource.attributes["-=resolve"]=null}}async updateItem(source){source.system.rules=recursiveReplaceString(source.system.rules,text=>text.replace(/^system\.attributes\.sp\.max$/,"system.attributes.hp.sp.max").replace(/^system\.attributes\.resolve.max$/,"system.resources.resolve.max"))}async migrate(){const staminaVariant=game.settings.storage.get("world").find(s=>s.key==="pf2e.staminaVariant");["1",'"1"'].includes(staminaVariant?._source.value??"")?await game.settings.set("pf2e","staminaVariant",!0):staminaVariant&&await game.settings.set("pf2e","staminaVariant",!1),game.settings.storage.get("world").find(s=>s.key==="pf2e.proficiencyVariant")?._source.value==='"ProficiencyWithoutLevel"'?await game.settings.set("pf2e","proficiencyVariant",!0):staminaVariant&&await game.settings.set("pf2e","proficiencyVariant",!1)}}class Migration875SetInnovationIdEarly extends MigrationBase{static{__name(this,"Migration875SetInnovationIdEarly")}static{__name2(this,"Migration875SetInnovationIdEarly")}static version=.875;async updateItem(source){if(source.type!=="feat"||!["armor-innovation","weapon-innovation"].includes(source.system.slug??""))return;const aeLike=source.system.rules.find(r=>r.key==="ActiveEffectLike"&&r.path==="flags.pf2e.innovationId");aeLike&&(aeLike.priority=5)}}class Migration876FeatLevelTaken extends MigrationBase{static{__name(this,"Migration876FeatLevelTaken")}static{__name2(this,"Migration876FeatLevelTaken")}static version=.876;async updateItem(source,actorSource){if(source.type!=="feat"||!setHasElement(FEAT_CATEGORIES,source.system.category))return;const location=source.system.location??"",background=actorSource?.items.find(i=>i.type==="background");if(location===background?._id)source.system.level.taken=1;else{const levelString=/^.+-(\d+)$/.exec(location)?.[1]??"NaN";levelString&&(source.system.level.taken=Number(levelString)||void 0)}const{category,traits}=source.system;category==="skill"&&!traits.value.includes("skill")?traits.value.push("skill"):category==="general"&&!traits.value.includes("general")&&traits.value.push("general"),traits.value.sort()}}class Migration877PublicationData extends MigrationBase{static{__name(this,"Migration877PublicationData")}static{__name2(this,"Migration877PublicationData")}static version=.877;#setPublicationData(systemSource,oldData){const title=typeof oldData.value=="string"?oldData.value.trim():"",authors=typeof oldData.author=="string"?oldData.author.trim():"",license=title==="Pathfinder Player Core"?"ORC":"OGL",remaster=["Pathfinder Player Core","Pathfinder Rage of Elements"].includes(title),publication={title,authors,license,remaster};isObject$1(systemSource.details)?systemSource.details.publication=publication:systemSource.publication=publication}async updateActor(source){source.type!=="hazard"&&source.type!=="npc"&&source.type!=="vehicle"||(source.type==="vehicle"&&isObject$1(source.system.source)?(this.#setPublicationData(source.system,source.system.source),"game"in globalThis?source.system["-=source"]=null:delete source.system.source):(source.type==="hazard"||source.type==="npc")&&isObject$1(source.system.details.source)&&(this.#setPublicationData(source.system,source.system.details.source),"game"in globalThis?source.system.details["-=source"]=null:delete source.system.details.source))}async updateItem(source){if("details"in source.system&&isObject$1(source.system.details)){const oldDataInWrongPlace=source.system.details.source;isObject$1(oldDataInWrongPlace)&&typeof oldDataInWrongPlace.value=="string"&&(source.system.source={value:oldDataInWrongPlace.value.trim()}),"game"in globalThis?source.system["-=details"]=null:delete source.system.details}isObject$1(source.system.source)?(this.#setPublicationData(source.system,source.system.source),"game"in globalThis?source.system["-=source"]=null:delete source.system.source):!source.system.publication&&!("game"in globalThis)&&this.#setPublicationData(source.system,{})}}class Migration878TakeABreather extends MigrationBase{static{__name(this,"Migration878TakeABreather")}static{__name2(this,"Migration878TakeABreather")}static version=.878;async updateMacro(source){source.type==="script"&&source.command.includes("console.log(resolve, sp)")&&(source.command="game.pf2e.actions.takeABreather();")}}class Migration879DeviseAStratagemAndFriends extends MigrationBase{static{__name(this,"Migration879DeviseAStratagemAndFriends")}static{__name2(this,"Migration879DeviseAStratagemAndFriends")}static version=.879;async updateItem(source){if(source.type==="action"&&source.system.slug==="devise-a-stratagem"){const rules=[{domain:"all",key:"RollOption",option:"target:mark:devise-a-stratagem",toggleable:"totm"},{ability:"int",key:"FlatModifier",predicate:["class:investigator","target:mark:devise-a-stratagem",{or:["item:trait:agile","item:trait:finesse",{and:["item:ranged",{not:"item:thrown-melee"}]},"item:base:sap"]}],selector:"strike-attack-roll",type:"ability"}];source.system.rules=rules}else if(source.type==="feat"&&source.system.slug==="athletic-strategist"){const rule={ability:"int",key:"FlatModifier",predicate:["class:investigator","target:mark:devise-a-stratagem",{or:["action:disarm","action:grapple","action:shove","action:trip"]},{or:["item:trait:agile","item:trait:finesse",{and:["item:ranged",{not:"item:thrown-melee"}]},"item:base:sap",{and:["feat:takedown-expert","item:group:club","item:hands-held:1"]}]}],selector:"athletics",type:"ability"};source.system.rules=[rule]}else if(source.type==="feat"&&source.system.slug==="ongoing-strategy"){const rule={damageCategory:"precision",key:"FlatModifier",predicate:["class:investigator",{not:"check:substitution:devise-a-stratagem"},{or:["item:trait:agile","item:trait:finesse",{and:["item:ranged",{not:"item:thrown-melee"}]},"item:base:sap",{and:["feat:takedown-expert","item:group:club","item:hands-held:1"]}]}],selector:"strike-damage",value:{brackets:[{end:4,value:1},{end:8,start:5,value:2},{end:12,start:9,value:3},{end:16,start:13,value:4},{start:17,value:5}]}};source.system.rules=[rule]}else if(source.type==="feat"&&source.system.slug==="shared-stratagem"){const rule={key:"Note",predicate:["target:mark:devise-a-stratagem"],selector:"strike-attack-roll",text:"PF2E.SpecificRule.Investigator.SharedStratagem.Note",title:"{item|name}",outcome:["success","criticalSuccess"]};source.system.rules=[rule]}else if(source.type==="feat"&&source.system.slug==="takedown-expert"){const rule={ability:"int",key:"FlatModifier",predicate:["class:investigator","target:mark:devise-a-stratagem","item:hands-held:1"],selector:"club-group-attack-roll",type:"ability"};source.system.rules=[rule]}}}class UserPF2e extends User{static{__name(this,"UserPF2e")}static{__name2(this,"UserPF2e")}prepareData(){super.prepareData(),canvas.ready&&canvas.tokens.controlled.length>0&&game.pf2e.effectPanel.refresh()}prepareBaseData(){super.prepareBaseData(),this.flags=foundry.utils.mergeObject({pf2e:{settings:{showEffectPanel:!0,showCheckDialogs:!0,showDamageDialogs:!0,searchPackContents:!1,monochromeDarkvision:!0}}},this.flags)}get settings(){return this.flags.pf2e.settings}getActiveTokens(){return!canvas.ready||canvas.tokens.controlled.length===0?compact([game.user.character?.getActiveTokens(!0,!0).shift()]):canvas.tokens.controlled.map(t=>t.document)}clearTargets(){this.updateTokenTargets()}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),game.user.id!==userId)return;const keys2=Object.keys(foundry.utils.flattenObject(changed));keys2.includes("flags.pf2e.settings.showEffectPanel")&&game.pf2e.effectPanel.refresh(),keys2.includes("flags.pf2e.settings.monochromeDarkvision")&&canvas.ready&&(canvas.scene?.reset(),canvas.perception.update({initializeVision:!0,refreshLighting:!0},!0))}}class Migration880SplitShowDialogsSettings extends MigrationBase{static{__name(this,"Migration880SplitShowDialogsSettings")}static{__name2(this,"Migration880SplitShowDialogsSettings")}static version=.88;async migrate(){const userUpdates=game.users.contents.flatMap(user=>{const settings=user._source.flags.pf2e?.settings;return typeof settings?.showRollDialogs=="boolean"?(settings.showCheckDialogs=settings.showRollDialogs,settings.showDamageDialogs=settings.showRollDialogs,settings["-=showRollDialogs"]=null,{_id:user.id,"flags.pf2e.settings":settings}):[]});await UserPF2e.updateDocuments(userUpdates)}}class Migration881NoHBPrefix extends MigrationBase{static{__name(this,"Migration881NoHBPrefix")}static{__name2(this,"Migration881NoHBPrefix")}static version=.881;async updateActor(source){const traits=source.system.traits;if(traits?.value&&Array.isArray(traits.value)&&(traits.value=traits.value.filter(t=>typeof t=="string").map(t=>t.replace(/^hb_/,""))),source.type==="character"&&source.system.proficiencies?.attacks){const attacks=source.system.proficiencies.attacks;for(const[key,value]of Object.entries(attacks))key.includes("hb_")&&(attacks[key.replace("hb_","")]=value,attacks[`-=${key}`]=null)}}async updateItem(source){source.system=recursiveReplaceString(source.system,t=>t.replace(/^hb_/,""))}}class Migration882SpellDataReorganization extends MigrationBase{static{__name(this,"Migration882SpellDataReorganization")}static{__name2(this,"Migration882SpellDataReorganization")}static version=.882;#SCHOOL_TRAITS=new Set(["abjuration","conjuration","divination","enchantment","evocation","necromancy","transmutation"]);#DAMAGE_TYPES=new Set([...DAMAGE_TYPES,"good","evil","lawful","chaotic"]);#ensureTraitsPresence(system){return foundry.utils.mergeObject({value:[]},system.traits??{value:[]})}#migrateRule(rule){if("type"in rule){if(typeof rule.type=="string"&&this.#SCHOOL_TRAITS.has(rule.type))return[];Array.isArray(rule.type)&&(rule.type=rule.type.filter(t=>!this.#SCHOOL_TRAITS.has(t)))}return"traits"in rule&&Array.isArray(rule.traits)&&(rule.traits=rule.traits.filter(t=>!this.#SCHOOL_TRAITS.has(t))),Array.isArray(rule.predicate)&&(rule.predicate=rule.predicate.filter(s=>!this.#SCHOOL_TRAITS.has(s))),rule}async updateActor(source){const traits=source.system.traits??{value:[]};Array.isArray(traits.value)&&(traits.value=uniq(compact(traits.value).filter(t=>!this.#SCHOOL_TRAITS.has(t))).sort()),source.system.attributes.immunities=source.system.attributes.immunities?.filter(i=>!this.#SCHOOL_TRAITS.has(i.type)),source.system.attributes.weaknesses=source.system.attributes.weaknesses?.filter(i=>!this.#SCHOOL_TRAITS.has(i.type)),source.system.attributes.resistances=source.system.attributes.resistances?.filter(i=>!this.#SCHOOL_TRAITS.has(i.type))}async updateItem(source,actorSource,{topLevel=!0}={}){topLevel&&source.system?.rules&&(source.system.rules=source.system.rules.flatMap(r=>r&&this.#migrateRule(r)));const traits=source.system?.traits??{value:[]};if(Array.isArray(traits.value)&&(traits.value=uniq(compact(traits.value).filter(t=>!this.#SCHOOL_TRAITS.has(t)).map(t=>t==="metamagic"?"spellshape":t).sort())),source.type!=="spell")return;const system=source.system??{};isObject(system.traditions)&&"value"in system.traditions&&Array.isArray(system.traditions.value)&&(system.traits=this.#ensureTraitsPresence(system),system.traits.traditions=[...system.traditions.value].sort()),"traditions"in system&&(system["-=traditions"]=null),system.category?.value==="focus"&&(system.traits=this.#ensureTraitsPresence(system)).value.push("focus"),isObject(system.components)&&(system.components.verbal&&(system.traits=this.#ensureTraitsPresence(system)).value.push("concentrate"),(system.components.material||system.components.somatic)&&(system.traits=this.#ensureTraitsPresence(system)).value.push("manipulate")),"components"in system&&(system["-=components"]=null),isObject(system.materials)&&typeof system.materials.value=="string"?system.requirements=system.materials.value:topLevel&&(system.requirements||=""),"materials"in system&&(system["-=materials"]=null),topLevel&&(system.duration={value:system.duration?.value??"",sustained:isObject(system.sustained)?!!system.sustained.value||system.duration?.value?.includes("sustained")||!1:system.duration?.sustained??!1}),"sustained"in system&&(system["-=sustained"]=null),isObject(system.hasCounteractCheck)?system.counteraction=!!system.hasCounteractCheck.value:topLevel&&(system.counteraction??=!1),"hasCounteractCheck"in system&&(system["-=hasCounteractCheck"]=null),isObject(system.save)&&typeof system.save?.value=="string"&&tupleHasValue(SAVE_TYPES,system.save.value)&&(system.defense={save:{statistic:system.save.value,basic:!!system.save.basic}}),topLevel&&(system.defense??=null),"save"in system&&(system["-=save"]=null);const oldSpellDamage=foundry.utils.deepClone(system.damage);if(isObject(oldSpellDamage)&&isObject$1(oldSpellDamage?.value)){system.damage={};for(const[key,partial]of Object.entries(oldSpellDamage?.value)){if(topLevel&&["lay-on-hands","touch-of-corruption"].includes(source.system?.slug??""))break;if(!isObject$1(partial))continue;const typeData=isObject$1(partial.type)?partial.type:{},damageType=this.#DAMAGE_TYPES.has(String(typeData.value))?typeData.value:topLevel?"untyped":void 0,damageCategory=setHasElement(DAMAGE_CATEGORIES_UNIQUE,typeData.subtype)?typeData.subtype:topLevel?null:void 0;system.damage[key]={applyMod:typeof partial.applyMod=="boolean"?partial.applyMod:void 0,formula:typeof partial.value=="string"?partial.value:topLevel?"":void 0,type:damageType,category:damageCategory,materials:Array.isArray(typeData.categories)?typeData.categories:topLevel?[]:void 0}}const damageWithDeletions=system.damage;for(const[key,oldValue]of Object.entries(oldSpellDamage))(key==="value"||!isObject(oldValue))&&(damageWithDeletions[`-=${key}`]=null)}if(isObject(system.spellType)){if(system.spellType.value==="attack"&&!system.traits?.value?.includes("attack"))(system.traits=this.#ensureTraitsPresence(system)).value.push("attack");else if(system.spellType.value==="heal")for(const[key,damagePartial]of Object.entries(system.damage??{}))key!=="value"&&isObject(damagePartial)&&(damagePartial.kinds=["healing"]);for(const[key,damagePartial]of Object.entries(system.damage??{}))key!=="value"&&isObject(damagePartial)&&(damagePartial.kinds??=["damage"])}if("spellType"in system&&(system["-=spellType"]=null),isObject(system.category)&&"value"in system.category&&system.category.value==="ritual"){const primaryCheck=isObject(system.primarycheck)&&typeof system.primarycheck.value=="string"?system.primarycheck.value.trim():"",secondaryChecks=isObject(system.secondarycheck)&&typeof system.secondarycheck.value=="string"?system.secondarycheck.value.trim():"",secondaryCasters=isObject(system.secondarycasters)&&Number(system.secondarycasters.value)||0;system.ritual={primary:{check:primaryCheck},secondary:{checks:secondaryChecks,casters:secondaryCasters}}}"category"in system&&(system["-=category"]=null),"primarycheck"in system&&(system["-=primarycheck"]=null),"secondarycheck"in system&&(system["-=secondarycheck"]=null),"secondarycasters"in system&&(system["-=secondarycasters"]=null);const oldKeys=["ability","areatype","damageType","prepared","rarity","spellCategorie","usage"];for(const key of oldKeys)key in system&&(system[`-=${key}`]=null);if(isObject(system.heightening)&&system.heightening.type==="fixed")for(const spellPartial of Object.values(system.heightening.levels??{}))await this.updateItem({name:source.name,type:"spell",system:spellPartial},actorSource,{topLevel:!1});for(const overlay of Object.values(system?.overlays??{}))overlay.overlayType==="override"&&await this.updateItem({name:overlay.name??source.name,type:"spell",system:overlay.system??{}},actorSource,{topLevel:!1})}}class Migration883BanishAlignment extends MigrationBase{static{__name(this,"Migration883BanishAlignment")}static{__name2(this,"Migration883BanishAlignment")}static version=.883;#ALIGNMENTS=new Set(["good","evil","lawful","chaotic"]);#migrateRule(rule){return"traits"in rule&&Array.isArray(rule.traits)&&(rule.traits=rule.traits.filter(t=>!this.#ALIGNMENTS.has(t))),Array.isArray(rule.predicate)&&(rule.predicate=rule.predicate.filter(s=>!this.#ALIGNMENTS.has(s))),rule}async updateActor(source){const details=source.system.details;if(isObject(details.alignment)&&typeof details.alignment.value=="string"){const traits=source.system.traits??{value:[]};switch(details.alignment.value){case"LG":traits.value.push("lawful","good");break;case"NG":traits.value.push("good");break;case"CG":traits.value.push("chaotic","good");break;case"LE":traits.value.push("lawful","evil");break;case"NE":traits.value.push("evil");break;case"CE":traits.value.push("chaotic","evil");break;case"LN":traits.value.push("lawful");break;case"CN":traits.value.push("chaotic");break}if(source.type==="npc"){if(traits.value.includes("celestial")&&traits.value.includes("good")){traits.value.push("holy");for(const item of source.items.filter(i=>i.type==="melee"))item.system.traits.value.includes("holy")||(item.system.traits.value.push("holy"),item.system.traits.value.sort())}else if(["fiend","rakshasa","undead"].some(t=>traits.value.includes(t))&&traits.value.includes("evil")&&(traits.value.push("unholy"),traits.value.includes("fiend")||traits.value.includes("rakshasa")))for(const item of source.items.filter(i=>i.type==="melee"))item.system.traits.value.includes("unholy")||(item.system.traits.value.push("unholy"),item.system.traits.value.sort())}traits.value=uniq(traits.value.sort())}"alignment"in details&&(details["-=alignment"]=null)}async updateItem(source){if(source.system.rules=source.system.rules.flatMap(r=>this.#migrateRule(r)),source.type==="deity"){const system=source.system;if("alignment"in system){const{alignment}=system;if(isObject$1(alignment)&&"follower"in alignment&&Array.isArray(alignment.follower)){const followers=alignment.follower.filter(a=>typeof a=="string"),modal=system.category==="philosophy"?null:["asmodeus","iomedae","rovagug","urgathoa"].includes(system.slug??"")?"must":"can",what=modal===null||system.slug==="pharasma"?null:system.slug==="gorum"?["holy","unholy"]:followers.some(f=>f.includes("G"))?followers.some(f=>f.includes("E"))?["holy","unholy"]:["holy"]:followers.some(f=>f.includes("E"))?["unholy"]:null;system.sanctification=modal===null||what===null?null:{modal,what}}system["-=alignment"]=null}"ability"in system&&(system.attribute=Array.isArray(system.ability)?uniq(system.ability.filter(a=>setHasElement(ATTRIBUTE_ABBREVIATIONS,a)).sort()):[],system["-=ability"]=null)}else if(source.type==="feat"&&["the-tenets-of-evil","the-tenets-of-good"].includes(source.system.slug??"")){const rule={key:"ActorTraits",add:source.system.slug==="the-tenets-of-good"?["holy"]:["unholy"]};source.system.rules=[rule]}}}class Migration884UnifiedSpellcasting extends MigrationBase{static{__name(this,"Migration884UnifiedSpellcasting")}static{__name2(this,"Migration884UnifiedSpellcasting")}static version=.884;async updateActor(source){if(source.type!=="character")return;const profs=source.system.proficiencies??null;profs?.traditions&&(profs["-=traditions"]=null)}async updateItem(source){source.system.rules=recursiveReplaceString(source.system.rules,value=>value.replace(/^system\.proficiencies\.traditions\.(.*)\.(\w+)$/,"system.proficiencies.spellcasting.$2"))}}class Migration885ConvertAlignmentDamage extends MigrationBase{static{__name(this,"Migration885ConvertAlignmentDamage")}static{__name2(this,"Migration885ConvertAlignmentDamage")}static version=.885;#ALIGNMENTS=new Set(["good","evil","lawful","chaotic"]);#ALIGNMENT_VERSATILE_TRAITS=Array.from(this.#ALIGNMENTS).map(dt=>`versatile-${dt}`);#migrateRule(rule){if("type"in rule){if(rule.key==="Immunity"&&typeof rule.type=="string"&&this.#ALIGNMENTS.has(rule.type))return[];if(["Weakness","Resistance"].includes(String(rule.key))&&typeof rule.type=="string"){if(["lawful","chaotic"].includes(rule.type))return[];Array.isArray(rule.predicate)&&(rule.predicate=rule.predicate.filter(s=>typeof s!="string"||!/^self:trait:(?:good|evil|lawful|chaotic)$/.test(s))),rule.type==="good"&&(rule.type="holy"),rule.type==="evil"&&(rule.type="unholy")}else Array.isArray(rule.type)&&(rule.type=rule.type.flatMap(t=>["lawful","chaotic"].includes(t)?[]:t==="good"?"holy":t==="evil"?"unholy":t))}return"deactivatedBy"in rule&&Array.isArray(rule.deactivatedBy)&&(rule.deactivatedBy=rule.deactivatedBy.flatMap(db=>["lawful","chaotic"].includes(db)?[]:db==="good"?"holy":db==="evil"?"unholy":db)),"damageType"in rule&&typeof rule.damageType=="string"&&(rule.damageType=this.#ALIGNMENTS.has(rule.damageType)?"spirit":rule.damageType),rule}async updateActor(source){const traits=source.type==="character"?{value:[]}:source.system.traits??{value:[]},iwrKeys=["immunities","weaknesses","resistances"],iwr=pick(source.system.attributes,iwrKeys);for(const key of iwrKeys){iwr[key]=iwr[key]?.filter(i=>!["chaotic","lawful"].includes(i.type));for(const obj of[...iwr[key]??[]])obj.type=obj.type.replace("good","holy").replace("evil","unholy"),obj.exceptions=obj.exceptions?.filter(e=>isObject(e)||!["chaotic","lawful"].includes(e)).map(e=>e==="evil"?"unholy":e==="good"?"holy":e),obj.type==="holy"?(traits.value.push(key==="immunities"?"holy":"unholy"),key==="immunities"&&iwr.immunities?.splice(iwr.immunities.indexOf(obj),1)):obj.type==="unholy"&&(traits.value.push(key==="immunities"?"unholy":"holy"),key==="immunities"&&iwr.immunities?.splice(iwr.immunities.indexOf(obj),1))}foundry.utils.mergeObject(source.system.attributes,iwr),traits.value=uniq(traits.value.sort()),traits.value.includes("holy")&&traits.value.includes("unholy")&&(traits.value=traits.value.filter(t=>!["holy","unholy"].includes(t)))}async updateItem(source,actorSource){if(source.system.rules=source.system.rules.flatMap(r=>this.#migrateRule(r)),source.type==="weapon"){const traits=source.system.traits;traits.value=compact(traits.value.map(t=>this.#ALIGNMENT_VERSATILE_TRAITS.includes(t)?"versatile-spirit":t)),this.#ALIGNMENTS.has(source.system.damage.damageType)&&(source.system.damage.damageType="spirit"),traits.value=traits.value.map(t=>t==="sanctified"?traits.value.includes("good")?"holy":"unholy":t),traits.value=uniq(traits.value.sort())}else if(source.type==="melee"){const traits=source.system.traits,actorTraits=actorSource?.system.traits??{value:[]};traits.value=compact(traits.value.map(t=>this.#ALIGNMENT_VERSATILE_TRAITS.includes(t)?"versatile-spirit":t)),traits.value.some(t=>t==="good")?(traits.value.push("holy"),actorTraits.value.push("holy")):traits.value.some(t=>t==="evil")&&(traits.value.push("unholy"),actorTraits.value.push("unholy"));const partials=source.system.damageRolls;for(const[key,partial]of Object.entries(partials)){if(!isObject(partial))continue;const damageType=partial.damageType;["chaotic","lawful"].includes(damageType)?partial.damageType="spirit":damageType==="good"?(actorTraits.value.push("holy"),/^\d+$/.test(partial.damage)?partials[`-=${key}`]=null:partial.damageType="spirit"):damageType==="evil"&&(traits.value.push("unholy"),/^\d+$/.test(partial.damage)?partials[`-=${key}`]=null:partial.damageType="spirit")}traits.value=uniq(traits.value.sort()),actorTraits.value=uniq(actorTraits.value.sort())}else if(source.type==="spell"){const damage=Object.values(source.system.damage).filter(d=>isObject(d)&&typeof d.type=="string"),traits=source.system.traits;for(const partial of damage){const damageType=partial.type;this.#ALIGNMENTS.has(damageType)&&(partial.type="spirit"),damageType==="good"?traits.value.push("holy"):damageType==="evil"&&traits.value.push("unholy")}if(traits.value=uniq(traits.value.sort()),source.system.slug==="divine-decree"){const system=source.system,damage2=Object.values(system.damage).shift();isObject(damage2)&&(damage2.type="spirit"),system["-=overlays"]=null}else try{const overlayPartials=compact(Object.values(source.system.overlays??{}).filter(o=>isObject(o)&&o.overlayType==="override").map(o=>(o.system??={})?.damage).flatMap(p=>isObject(p)?Object.values(p):[]).flat());for(const partial of overlayPartials)this.#ALIGNMENTS.has(partial.type??"")&&(partial.type="spirit")}catch(error){error instanceof Error&&console.error(error.message)}}const{description}=source.system;if(actorSource?.type==="npc"&&source.type==="action"&&source.system.actionType.value!=="passive"){const hasGoodInlineRoll=/\[good\b/.test(description.value)||/\bgood\]/.test(description.value),hasEvilInlineRoll=/\[evil\b/.test(description.value)||/\bevil\]/.test(description.value);hasGoodInlineRoll&&actorSource.system.traits.value.includes("holy")?source.system.traits.value.push("holy"):hasEvilInlineRoll&&actorSource.system.traits.value.includes("unholy")&&source.system.traits.value.push("unholy"),source.system.traits.value=uniq(source.system.traits.value.sort())}description.value=description.value.replace(/\[(?:good|evil|lawful|chaotic)\b/g,"[spirit").replace(/\b(?:good|evil|lawful|chaotic)\]/g,"spirit]").replace(/\b(\dd\d) (?:good|evil|lawful|chaotic)\b/g,"$1 spirit")}}class Migration886CrossbowGroup extends MigrationBase{static{__name(this,"Migration886CrossbowGroup")}static{__name2(this,"Migration886CrossbowGroup")}static version=.886;async updateItem(source){if(source.type==="weapon"&&source.system.group==="bow"){const otherTags=source.system.traits.otherTags??[],slug=source.system.slug??sluggify(source.name);(otherTags.includes("crossbow")||slug.includes("crossbow"))&&(source.system.group="crossbow",otherTags.includes("crossbow")&&otherTags.splice(otherTags.indexOf("crossbow"),1))}source.system.rules=recursiveReplaceString(source.system.rules,s=>s.replace(/\btag:crossbow\b/,"group:crossbow"))}}class Migration887RedirectSpellLinks extends MigrationBase{static{__name(this,"Migration887RedirectSpellLinks")}static{__name2(this,"Migration887RedirectSpellLinks")}static version=.887;#spells=[{from:{_id:"kl2q6JvBZwed4B6v",name:"Dancing Lights"},to:{_id:"WBmvzNDfpwka3qT4",name:"Light"}},{from:{_id:"hkfH9Z53hPzcOwNB",name:"Veil"},to:{_id:"i35dpZFI7jZcRoBo",name:"Illusory Disguise"}},{from:{_id:"l4LFwY7iuzX6sDXr",name:"Commune with Nature"},to:{_id:"7DN13ILADW2N9Z1t",name:"Commune"}},{from:{_id:"OyFCwQuw8XRazsNr",name:"Remove Curse"},to:{_id:"SUKaxVZW2TlM8lu0",name:"Cleanse Affliction"}},{from:{_id:"RneiyehRO6f7LP44",name:"Remove Disease"},to:{_id:"SUKaxVZW2TlM8lu0",name:"Cleanse Affliction"}},{from:{_id:"c2bTWBNO1BYX4Zfg",name:"Misdirection"},to:{_id:"PRrZ7anETWPm90YY",name:"Disguise Magic"}}];async updateItem(source){for(const spell of this.#spells){const{from,to}=spell;if("game"in globalThis){const isolatedUUID=new RegExp(String.raw`^Compendium\.pf2e\.spells-srd\.(?:Item\.)?${from._id}$`);source.system=recursiveReplaceString(source.system,s=>s.replace(isolatedUUID,`Compendium.pf2e.spells-srd.Item.${to._id}`));const{description}=source.system;description.value=description.value.replace(`@UUID[Compendium.pf2e.spells-srd.Item.${from._id}]{${from.name}}`,`@UUID[Compendium.pf2e.spells-srd.Item.${to._id}]{${to.name}}`),description.gm&&=description.gm.replace(`@UUID[Compendium.pf2e.spells-srd.Item.${from._id}]{${from.name}}`,`@UUID[Compendium.pf2e.spells-srd.Item.${to._id}]{${to.name}}`)}else{const isolatedUUID=new RegExp(String.raw`^Compendium\.pf2e\.spells-srd\.Item\.${from.name}$`);source.system=recursiveReplaceString(source.system,s=>s.replace(isolatedUUID,`Compendium.pf2e.spells-srd.Item.${to.name}`));const{description}=source.system;description.value=description.value.replaceAll(`@UUID[Compendium.pf2e.spells-srd.Item.${from.name}]`,`@UUID[Compendium.pf2e.spells-srd.Item.${to.name}]`),description.gm&&=description.gm.replaceAll(`@UUID[Compendium.pf2e.spells-srd.Item.${from.name}]`,`@UUID[Compendium.pf2e.spells-srd.Item.${to.name}]`)}}}async updateJournalEntry(source){for(const spell of this.#spells){const{from,to}=spell;for(const page of source.pages)page.text.content&&=page.text.content.replace(`@UUID[Compendium.pf2e.spells-srd.Item.${from._id}]{${from.name}}`,`@UUID[Compendium.pf2e.spells-srd.Item.${to._id}]{${to.name}}`),page.text.content&&=page.text.content.replace(`@UUID[Compendium.pf2e.spells-srd.Item.${from.name}]`,`@UUID[Compendium.pf2e.spells-srd.Item.${to.name}]`)}}}class Migration888RemasterLanguagesHeritages extends MigrationBase{static{__name(this,"Migration888RemasterLanguagesHeritages")}static{__name2(this,"Migration888RemasterLanguagesHeritages")}static version=.888;#LANGUAGE_RENAMES={abyssal:"chthonian",celestial:"empyrean",gnoll:"kholo",infernal:"diabolic"};#TRAITS_RENAMES={aasimar:"nephilim","half-elf":"aiuvarin","half-orc":"dromaar",gnoll:"gnoll",ifrit:"naari",tiefling:"nephilim"};async updateActor(source){if(source.type==="character"||source.type==="npc"){const traits=source.system.traits;traits.value=traits.value.map(t=>this.#TRAITS_RENAMES[t]??t).sort();const{languages}=traits;isObject(languages)&&Array.isArray(languages.value)&&(languages.value=languages.value.map(l=>this.#LANGUAGE_RENAMES[l]??l).sort())}}async updateItem(source){if(source.system.slug==="bloodline-genie")return;source.system=recursiveReplaceString(source.system,s=>this.#TRAITS_RENAMES[s]??this.#LANGUAGE_RENAMES[s]??s);const traits=source.system.traits??{value:[]};if(traits.value=traits.value?.map(t=>t==="kholo"?"gnoll":t),source.type==="ancestry"){const languages=source.system.languages,additionalLanguages=source.system.languages;languages.value=languages.value.map(l=>l==="gnoll"?"kholo":l),languages.value.sort(),additionalLanguages.value=additionalLanguages.value.map(l=>l==="gnoll"?"kholo":l),additionalLanguages.value.sort()}}}class Migration889RemoveFocusMaxIncreases extends MigrationBase{static{__name(this,"Migration889RemoveFocusMaxIncreases")}static{__name2(this,"Migration889RemoveFocusMaxIncreases")}static version=.889;async updateItem(source){source.type==="feat"&&["clarity-of-focus","psi-cantrips-and-amps","psychic-dedication","psi-development"].includes(source.system.slug??"")||(source.system.rules=source.system.rules.filter(r=>!("path"in r&&r.path==="system.resources.focus.max")))}}class Migration890RMClassItemClassDC extends MigrationBase{static{__name(this,"Migration890RMClassItemClassDC")}static{__name2(this,"Migration890RMClassItemClassDC")}static version=.89;async updateItem(source){if(source.type==="class"&&"classDC"in source.system){const system=source.system;system["-=classDC"]=null}}}class Migration891DruidicToWildsong extends MigrationBase{static{__name(this,"Migration891DruidicToWildsong")}static{__name2(this,"Migration891DruidicToWildsong")}static version=.891;async updateActor(source){source.system=recursiveReplaceString(source.system,s=>s.replace(/^druidic$/,"wildsong").replace(/^Druidic$/,"Wildsong"))}async updateItem(source){source.system=recursiveReplaceString(source.system,s=>s.replace(/^druidic$/,"wildsong").replace(/^Druidic$/,"Wildsong")),source.system.traits?.value?.sort()}}class Migration892ChoiceSetREAdjustNameValue extends MigrationBase{static{__name(this,"Migration892ChoiceSetREAdjustNameValue")}static{__name2(this,"Migration892ChoiceSetREAdjustNameValue")}static version=.892;async updateItem(source){for(const rule of source.system.rules)rule.key==="ChoiceSet"&&"adjustName"in rule&&typeof rule.adjustName=="string"&&(rule.adjustName=rule.adjustName==="true")}}class Migration893NoHBPrefixSettings extends MigrationBase{static{__name(this,"Migration893NoHBPrefixSettings")}static{__name2(this,"Migration893NoHBPrefixSettings")}static version=.893;async migrate(){for(const key of HOMEBREW_TRAIT_KEYS){const tags=game.settings.get("pf2e",`homebrew.${key}`);if(tags.length===0)continue;const updatedTags=tags.flatMap(tag=>isObject$1(tag)&&typeof tag.id=="string"?(tag.id=tag.id.replace(/^hb_/,""),tag):[]);await game.settings.set("pf2e",`homebrew.${key}`,updatedTags)}}}class Migration894NoLayOnHandsVsUndead extends MigrationBase{static{__name(this,"Migration894NoLayOnHandsVsUndead")}static{__name2(this,"Migration894NoLayOnHandsVsUndead")}static version=.894;async updateActor(source){source.items=source.items.filter(i=>i.type!=="spell"||(i.system.slug??sluggify(i.name))!=="lay-on-hands-vs-undead")}async updateItem(source){const{description}=source.system;source.type==="effect"?description.value=description.value.replace(/@UUID\[Compendium\.pf2e\.spells-srd\.Item\.(?:Lay on Hands \(Vs\. Undead\)|IxyD7YdRbSSucxZp)\]/g,"game"in globalThis?"@UUID[Compendium.pf2e.spells-srd.Item.zNN9212H2FGfM7VS]":"@UUID[Compendium.pf2e.spells-srd.Item.Lay on Hands]"):description.value=description.value.replace(/(?:)?@UUID\[Compendium.pf2e.spells-srd\.(?:Item\.)?(?:Lay on Hands \(Vs\. Undead\)|IxyD7YdRbSSucxZp)\](?:<\/em>)?<\/p>\n?/g,""),source.type==="spell"&&source.system.slug==="lay-on-hands"&&(source.system.overlays??={a33QUFoKgoOprovO:{_id:"a33QUFoKgoOprovO",name:"Lay on Hands (Vs. Undead)",overlayType:"override",sort:2,system:{damage:{"37YW4ZGhxx7Y2mdI":{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"vitality"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{"37YW4ZGhxx7Y2mdI":"1d6"},interval:1,type:"interval"}}},uLuOg62dVyxvbW66:{_id:"uLuOg62dVyxvbW66",name:"Lay on Hands (Healing)",overlayType:"override",sort:1,system:{damage:{b39tbePoPlJSzLku:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"vitality"}},heightening:{damage:{b39tbePoPlJSzLku:"6"},interval:1,type:"interval"}}}},source.system.overlays?.uLuOg62dVyxvbW66?.overlayType==="override"&&source.system.overlays.uLuOg62dVyxvbW66.system?.damage?.b39tbePoPlJSzLku&&(source.system.overlays.uLuOg62dVyxvbW66.system.damage.b39tbePoPlJSzLku.kinds=["healing"]))}}class Migration895FixVariantSpellTraits extends MigrationBase{static{__name(this,"Migration895FixVariantSpellTraits")}static{__name2(this,"Migration895FixVariantSpellTraits")}static version=.895;async updateItem(source){if(source.type==="spell")switch(source.system.slug){case"harm":case"heal":this.#fixHarmHeal(source);break;case"elemental-annihilation-wave":case"horizon-thunder-sphere":this.#removeOverlayTraits(source);break;default:this.#fixOtherVariants(source)}}#fixHarmHeal(source){const damage=source.system.damage[0];isObject$1(damage)&&(damage.kinds=["damage","healing"]),source.system.slug==="heal"?source.system.traits.value=["healing","manipulate","vitality"]:source.system.traits.value=["manipulate","void"];const variants=isObject$1(source.system.overlays)?Object.values(source.system.overlays).filter(o=>isObject$1(o)&&isObject$1(o.system?.traits)&&Array.isArray(o.system?.traits.value)):[];for(const variant of variants){if(!variant.system?.traits)continue;const system=variant.system;system.time?.value==="1"?system["-=traits"]=null:(system.traits=source.system.slug==="heal"?{value:["concentrate","healing","manipulate","vitality"]}:{value:["concentrate","manipulate","void"]},system.damage?.["0"]?.formula?.includes("+")?(system.damage[0].kinds=["healing"],system.defense=null):system.time?.value==="2"&&!system.damage?.["0"]&&(system.damage={0:{kinds:["damage"]}}))}}#removeOverlayTraits(source){source.system.traits.value=uniq([...source.system.traits.value,"concentrate","manipulate"]).sort();for(const overlay of Object.values(source.system.overlays??{})){const overlaySystem=overlay.system??{};overlaySystem["-=traits"]=null}}#fixOtherVariants(source){for(const partial of Object.values(source.system.damage).filter(p=>isObject$1(p)))typeof partial.type=="string"&&(partial.type==="healing"||partial.type,partial.type||="untyped");for(const overlay of Object.values(source.system.overlays??{})){const overlaySystem=overlay.system??{};if(overlaySystem.traits?.value&&Array.isArray(overlaySystem.traits.value)){if(!compact(overlaySystem.traits.value).every(t=>["concentrate","manipulate"].includes(t)))continue;overlaySystem.traits.value=uniq([...overlaySystem.traits.value,...source.system.traits.value].sort()),equals(overlaySystem.traits.value,uniq(source.system.traits.value.sort()))&&(overlaySystem["-=traits"]=null)}}}}class Migration896HealingDomains extends MigrationBase{static{__name(this,"Migration896HealingDomains")}static{__name2(this,"Migration896HealingDomains")}static version=.896;async updateItem(source){if(["effect","feat"].includes(source.type))switch(source.system.slug){case"harming-hands":case"healing-hands":{const rule={key:"DamageDice",override:{dieSize:"d10"},predicate:[source.system.slug==="healing-hands"?"item:slug:heal":"item:slug:harm"],selector:["spell-damage","spell-healing"]};source.system.rules=[rule];break}case"effect-curse-of-outpouring-life":{const rule=source.system.rules.find(r=>r.key==="DamageDice");rule&&(rule.selector="spell-healing")}}}}class Migration897ClearLayOnHandsDamage extends MigrationBase{static{__name(this,"Migration897ClearLayOnHandsDamage")}static{__name2(this,"Migration897ClearLayOnHandsDamage")}static version=.897;async updateItem(source){if(source.type!=="spell"||!["lay-on-hands","touch-of-corruption"].includes(source.system.slug??""))return;if(source.system.defense=null,"heightening"in source.system){const system=source.system;system["-=heightening"]=null}const damage=source.system.damage;if(Object.keys(damage).length>0)for(const[key,partial]of Object.entries(damage))partial&&(damage[`-=${key}`]=null);for(const overlay of Object.values(source.system.overlays??{})){if(!isObject$1(overlay)||!isObject$1(overlay.system?.damage))continue;const damagePartials=Object.values(overlay.system?.damage??{});for(const partial of damagePartials.filter(p=>isObject$1(p)))partial?.formula==="6"?partial.kinds=["healing"]:partial.kinds=["damage"]}source.system.slug==="lay-on-hands"?source.system.overlays??={a33QUFoKgoOprovO:{_id:"a33QUFoKgoOprovO",name:"Lay on Hands (Vs. Undead)",overlayType:"override",sort:2,system:{damage:{"37YW4ZGhxx7Y2mdI":{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"vitality"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{"37YW4ZGhxx7Y2mdI":"1d6"},interval:1,type:"interval"}}},uLuOg62dVyxvbW66:{_id:"uLuOg62dVyxvbW66",name:"Lay on Hands (Healing)",overlayType:"override",sort:1,system:{damage:{b39tbePoPlJSzLku:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"vitality"}},heightening:{damage:{b39tbePoPlJSzLku:"6"},interval:1,type:"interval"}}}}:source.system.overlays??={"2a6Vm4mIjBgrzlO2":{_id:"2a6Vm4mIjBgrzlO2",name:"Touch of Corruption (Vs. Living)",overlayType:"override",sort:2,system:{damage:{Esn7klJ9WRsIFnrE:{applyMod:!1,category:null,formula:"1d6",kinds:["damage"],materials:[],type:"void"}},defense:{save:{basic:!0,statistic:"fortitude"}},heightening:{damage:{Esn7klJ9WRsIFnrE:"1d6"},interval:1,type:"interval"}}},gHIOzknAtexc6GUE:{_id:"gHIOzknAtexc6GUE",name:"Touch of Corruption (Healing)",overlayType:"override",sort:1,system:{damage:{cM137DAlBX1LcWAX:{applyMod:!1,category:null,formula:"6",kinds:["healing"],materials:[],type:"untyped"}},heightening:{damage:{cM137DAlBX1LcWAX:"6"},interval:1,type:"interval"}}}}}}class Migration898NoHBAgain extends MigrationBase{static{__name(this,"Migration898NoHBAgain")}static{__name2(this,"Migration898NoHBAgain")}static version=.898;async updateActor(source){source.system.attributes&&=recursiveReplaceString(source.system.attributes,s=>s.replace(/\bhb_/g,""))}async updateItem(source){source.system.rules=source.system.rules.filter(r=>isObject$1(r)).map(r=>recursiveReplaceString(r,s=>s.replace(/\bhb_/g,"")))}}class Migration899ArmorShieldToShieldShield extends MigrationBase{static{__name(this,"Migration899ArmorShieldToShieldShield")}static{__name2(this,"Migration899ArmorShieldToShieldShield")}static version=.899;#KEYS_TO_REMOVE=["category","checkPenalty","dexCap","group","potencyRune","propertyRune1","propertyRune2","propertyRune3","propertyRune4","resiliencyRune","strength","unequippedBulk"];#BASE_SHIELD_TYPES=new Set(["buckler","casters-targe","dart-shield","fortress-shield","gauntlet-buckler","harnessed-shield","heavy-rondache","hide-shield","klar","meteor-shield","razor-disc","salvo-shield","steel-shield","swordstealer-shield","tower-shield","wooden-shield"]);#SPECIFIC_BASE_ITEMS={"amaranthine-pavise":"tower-shield","arrow-catching-shield":"wooden-shield","broadleaf-shield-greater":null,"broadleaf-shield-major":null,"broadleaf-shield-true":null,"broadleaf-shield":null,"burr-shield":"wooden-shield","clockwork-shield-greater":"steel-shield","clockwork-shield":"steel-shield","cursebreak-bulwark":"tower-shield","dragonslayers-shield":"steel-shield","duelists-beacon":"buckler","exploding-shield":"wooden-shield","floating-shield-greater":"buckler","floating-shield":"buckler","force-shield":"steel-shield","forge-warden":"steel-shield","glamorous-buckler":"buckler","guardian-shield":"steel-shield","helmsmans-recourse-greater":"meteor-shield","helmsmans-recourse-major":"meteor-shield","helmsmans-recourse":"meteor-shield","highhelm-war-shield-greater":"razor-disc","highhelm-war-shield-lesser":"razor-disc","highhelm-war-shield-moderate":"razor-disc","jawbreaker-shield":null,"krakens-guard":"steel-shield","limestone-shield":"tower-shield","lions-shield":"steel-shield","martyrs-shield":"steel-shield","medusas-scream-greater":"steel-shield","medusas-scream":"steel-shield","nethysian-bulwark":"steel-shield","pillow-shield":"steel-shield","rampart-shield":"tower-shield","reflecting-shield":"buckler","reforging-shield":"steel-shield","sanguine-klar-greater":"klar","sanguine-klar":"klar","sapling-shield-greater":"buckler","sapling-shield-lesser":"buckler","sapling-shield-major":"buckler","sapling-shield-minor":"buckler","sapling-shield-moderate":"buckler","sapling-shield-true":"buckler","scale-of-igroon":null,"shining-shield":"wooden-shield","silkspinners-shield":"buckler","spellguard-shield":"steel-shield","spined-shield":"steel-shield","staff-storing-shield-greater":"wooden-shield","staff-storing-shield-major":"wooden-shield","staff-storing-shield-true":"wooden-shield","staff-storing-shield":"wooden-shield","starfall-shield":"heavy-rondache","sturdy-shield-greater":"steel-shield","sturdy-shield-lesser":"steel-shield","sturdy-shield-major":"steel-shield","sturdy-shield-minor":"steel-shield","sturdy-shield-moderate":"steel-shield","sturdy-shield-supreme":"steel-shield","turnabout-shield":"salvo-shield","warding-escutcheon-greater":"tower-shield","warding-escutcheon":"tower-shield","wovenwood-shield-greater":"wooden-shield","wovenwood-shield-lesser":"wooden-shield","wovenwood-shield-major":"wooden-shield","wovenwood-shield-minor":"wooden-shield","wovenwood-shield-moderate":"wooden-shield","wovenwood-shield-true":"wooden-shield"};async updateItem(source){if(isPhysicalData(source)&&source.type!=="backpack"){const system2=source.system;"negateBulk"in system2&&(system2["-=negateBulk"]=null)}if(this.#migrateRules(source),source.type!=="armor")return;const category=source.system.category;category!=="shield"&&(source.system.checkPenalty||=0,source.system.dexCap||=0),source.system.speedPenalty||=0;const system=source.system;if("potency"in system&&(system["-=potency"]=null),category==="shield"){source.img=source.img.replace(/\barmor\.svg$/,"shield.svg"),system.baseItem=this.#BASE_SHIELD_TYPES.has(source.system.slug??"")?source.system.slug:null,system.traits.value=system.traits.value.map(t=>t==="hefty-14"?"hefty-2":t),system.traits.integrated=system.traits.value.some(t=>t.startsWith("integrated"))?{runes:{potency:0,striking:0,property:[]},versatile:null}:null,system.usage={value:"held-in-one-hand"},system.runes={reinforcing:0},this.#validateOrRemoveMaterial(system),this.#setSpecificShieldData(system),source.type="shield";for(const key of this.#KEYS_TO_REMOVE)key in system&&(system[`-=${key}`]=null)}}#migrateRules(source){const shieldAlterations=source.system.rules.filter(r=>r.key==="ItemAlteration"&&r.itemType==="armor"&&Array.isArray(r.predicate)&&r.predicate.includes("item:category:shield"));for(const rule of shieldAlterations)rule.itemType="shield",rule.predicate=rule.predicate.filter(s=>s!=="item:category:shield")}#validateOrRemoveMaterial(system){if(!system.material.type){system.material.grade=null;return}if(!system.material.grade){system.material.type=null;return}const baseItem=system.baseItem??"",{type}=system.material,BUCKLERS=["buckler","casters-targe","dart-shield","gauntlet-buckler","heavy-rondache","klar"],bucklerMaterials=["abysium","adamantine","cold-iron","darkwood","djezet","inubrix","mithral","noqual","orichalcum","siccatite","silver"],MATERIALS={buckler:bucklerMaterials,towerShield:["darkwood"],shield:[...bucklerMaterials,"keep-stone"]};["tower-shield","fortress-shield"].includes(baseItem)&&!MATERIALS.towerShield.includes(type)||BUCKLERS.includes(baseItem)&&!MATERIALS.buckler.includes(type)?(system.material.type=null,system.material.grade=null):MATERIALS.shield.includes(type)||(system.material.type=null,system.material.grade=null)}#setSpecificShieldData(system){if(system.baseItem||!system.slug)return;const setSpecific=__name2(()=>{system.specific={material:foundry.utils.deepClone(system.material),runes:{reinforcing:0},integrated:system.traits.integrated?foundry.utils.deepClone({runes:system.traits.integrated.runes}):null}},"setSpecific");switch(system.slug){case"indestructible-shield":system.baseItem="steel-shield",system.material={type:"adamantine",grade:"high"},setSpecific();break;case"kizidhars-shield":system.baseItem="wooden-shield",system.material={type:"duskwood",grade:"standard"},setSpecific();break;case"lodestone-shield":system.baseItem="steel-shield",system.material={type:"cold-iron",grade:"standard"},setSpecific();break;default:system.baseItem=this.#SPECIFIC_BASE_ITEMS[system.slug??""]??null,system.slug in this.#SPECIFIC_BASE_ITEMS&&setSpecific()}}}class Migration900ClassSpellcastingProficiency extends MigrationBase{static{__name(this,"Migration900ClassSpellcastingProficiency")}static{__name2(this,"Migration900ClassSpellcastingProficiency")}static version=.9;async updateActor(source){if(source.type==="character"&&source.system.proficiencies){const proficiencies=source.system.proficiencies;"spellcasting"in proficiencies&&(proficiencies["-=spellcasting"]=null)}}async updateItem(source){if(source.type==="class"){const aeLikeIncrease=source.system.rules.find(r=>r.key==="ActiveEffectLike"&&r.path==="system.proficiencies.spellcasting.rank");aeLikeIncrease?(source.system.spellcasting=Math.max(1,source.system.spellcasting??0),source.system.rules.splice(source.system.rules.indexOf(aeLikeIncrease),1)):["sorcerer","summoner","witch"].includes(source.system.slug??"")?source.system.spellcasting=1:source.system.spellcasting=Math.max(0,source.system.spellcasting??0)}if(source.type==="feat"){const baseRule={key:"ActiveEffectLike",mode:"upgrade",path:"system.proficiencies.spellcasting.rank"};switch(source.system.slug){case"bloodline":case"patron":source.system.rules=source.system.rules.filter(r=>r.path!=="system.proficiencies.spellcasting.rank");break;case"expert-spellcaster":source.system.rules=[{...baseRule,value:2}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break;case"expert-spellcasting":source.system.rules=[{...baseRule,value:2}];break;case"master-spellcaster":source.system.rules=[{...baseRule,value:3}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break;case"master-spellcasting":source.system.rules=[{...baseRule,value:3}];break;case"legendary-spellcaster":source.system.rules=[{...baseRule,value:4}],source.system.publication={...source.system.publication??{},license:"ORC",remaster:!0,title:"Pathfinder Player Core"};break}}}}class Migration901ReorganizeBulkData extends MigrationBase{static{__name(this,"Migration901ReorganizeBulkData")}static{__name2(this,"Migration901ReorganizeBulkData")}static version=.901;async updateItem(source){if(this.#migrateRules(source),!isPhysicalData(source))return;const system=source.system;if(system.bulk??={value:0},"equippedBulk"in system&&(["armor","backpack"].includes(source.type)&&(system.bulk.value=this.#bulkStringToNumber(system.equippedBulk)),system["-=equippedBulk"]=null,system.slug==="sack"?(system.usage={value:"held-in-one-hand"},system.bulk.value=.1):/bag-of-(?:devouring|holding|weasels)|spacious-pouch/.test(system.slug??"")?system.bulk.value=1:system.slug==="sleeves-of-storage"&&(system.bulk.value=.1)),"weight"in system){if(source.type==="backpack"){const usage=system.usage?.value??"";source.system.bulk.heldOrStowed=["held-in-one-hand","held-in-two-hands"].includes(usage)?Math.max(system.bulk.value,this.#bulkStringToNumber(system.weight)):this.#bulkStringToNumber(system.weight)}else source.type!=="armor"&&(source.system.bulk.value=this.#bulkStringToNumber(system.weight));system["-=weight"]=null}"bulkCapacity"in system&&(source.type==="backpack"&&(source.system.bulk.capacity=isObject$1(system.bulkCapacity)&&Math.floor(Math.abs(Number(system.bulkCapacity.value)))||0),system["-=bulkCapacity"]=null),"negateBulk"in system&&(source.type==="backpack"&&(source.system.bulk.ignored=isObject$1(system.negateBulk)&&Math.floor(Math.abs(Number(system.negateBulk.value)))||0),system["-=negateBulk"]=null)}#migrateRules(source){const itemAlterations=source.system.rules.filter(r=>r.key==="ItemAlteration"&&typeof r.property=="string");for(const rule of itemAlterations)(rule.itemType==="armor"&&rule.property==="bulk-worn"||rule.itemType!=="armor"&&rule.property==="bulk-value")&&(rule.property="bulk");source.system.rules=source.system.rules.filter(r=>r.key==="ItemAlteration"&&typeof r.property=="string"?!["bulk-worn","bulk-value"].includes(r.property):!0)}#bulkStringToNumber(bulkObject){if(!isObject$1(bulkObject))return 0;const bulkString=String(bulkObject.value||"-").toLocaleUpperCase("en");switch(bulkString){case"-":return 0;case"L":return .1;default:{const numericValue=Number(bulkString);return Number.isInteger(numericValue)?Math.abs(numericValue):0}}}}class Migration902DuskwoodDawnsilver extends MigrationBase{static{__name(this,"Migration902DuskwoodDawnsilver")}static{__name2(this,"Migration902DuskwoodDawnsilver")}static version=.902;#replaceStrings(data){return recursiveReplaceString(data,s=>s.replace(/\bdarkwood\b/g,"duskwood").replace(/Darkwood\b/g,"Duskwood").replace(/\bmithral\b/g,"dawnsilver").replace(/Mithral\b/g,"Dawnsilver").replace(/\bdawnsilver(.)tree\b/g,"mithral$1tree").replace(/\bDawnsilver Tree\b/g,"Mithral Tree").replace(/\bdawnsilver(.)golem/g,"mithral$1golem").replace(/\bDawnsilver(.)golem/g,"Mithral$1golem"))}async updateActor(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}async updateItem(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}}class Migration903PhysicalNumericData extends MigrationBase{static{__name(this,"Migration903PhysicalNumericData")}static{__name2(this,"Migration903PhysicalNumericData")}static version=.903;async updateItem(source){if(source.type==="armor")source.system.dexCap||=0,source.system.strength||=source.system.category==="unarmored"?null:0;else if(source.type==="backpack"){const slug=source.system.slug??"";/bag-of-(?:devouring|holding|weasels)|spacious-pouch/.test(slug)&&(source.system.bulk.value||=1)}}}class Migration904UndercommonToSakvroth extends MigrationBase{static{__name(this,"Migration904UndercommonToSakvroth")}static{__name2(this,"Migration904UndercommonToSakvroth")}static version=.904;#replaceStrings(data){return recursiveReplaceString(data,s=>s.replace(/\bundercommon\b/g,"sakvroth").replace(/\bUndercommon\b/g,"Sakvroth"))}async updateActor(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}async updateItem(source){source.system=this.#replaceStrings(source.system),source.flags.pf2e&&=this.#replaceStrings(source.flags.pf2e)}}class Migration905UnpersistUsage extends MigrationBase{static{__name(this,"Migration905UnpersistUsage")}static{__name2(this,"Migration905UnpersistUsage")}static version=.905;async updateItem(source){if(!isPhysicalData(source)){"usage"in source.system&&(source.system["-=usage"]=null);return}itemIsOfType(source,"armor","shield","treasure")&&"usage"in source.system?source.system["-=usage"]=null:source.system.usage?.value===""&&(source.system.usage.value="carried")}}const CONSUMABLE_CATEGORIES=new Set(["ammo","catalyst","drug","elixir","fulu","gadget","mutagen","oil","other","poison","potion","scroll","snare","talisman","toolkit","wand"]),DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES=new Set(["ammo","elixir","oil","other","poison","potion","snare"]),DAMAGE_ONLY_CONSUMABLE_CATEGORIES=new Set(["ammo","snare"]),AMMO_STACK_GROUPS=new Set(["arrows","blowgunDarts","bolts","rounds5","rounds10","slingBullets","sprayPellets","woodenTaws"]);class Migration906LimitStackGroup extends MigrationBase{static{__name(this,"Migration906LimitStackGroup")}static{__name2(this,"Migration906LimitStackGroup")}static version=.906;async updateItem(source){if((!isPhysicalData(source)||!itemIsOfType(source,"consumable","treasure"))&&"stackGroup"in source.system)source.system["-=stackGroup"]=null;else if(source.type==="consumable"){const category="consumableType"in source.system&&isObject$1(source.system.consumableType)?String(source.system.consumableType.value):source.system.category;source.system.stackGroup=category==="ammo"&&setHasElement(AMMO_STACK_GROUPS,source.system.stackGroup)?source.system.stackGroup:null}else source.type==="treasure"&&(source.system.stackGroup=["coins","gems"].includes(source.system.stackGroup??"")?source.system.stackGroup:null);!("game"in globalThis)&&"stackGroup"in source.system&&!source.system.stackGroup&&(source.system["-=stackGroup"]=null)}}class Migration907RestructureArmorWeaponRunes extends MigrationBase{static{__name(this,"Migration907RestructureArmorWeaponRunes")}static{__name2(this,"Migration907RestructureArmorWeaponRunes")}static version=.907;#RESILIENT_RUNE_CONVERSION=new Map([["resilient",1],["greaterResilient",2],["majorResilient",3]]);#STRIKING_RUNE_CONVERSION=new Map([["striking",1],["greaterStriking",2],["majorStriking",3]]);#RUNE_DELETIONS=["potencyRune","resiliencyRune","strikingRune","propertyRune1","propertyRune2","propertyRune3","propertyRune4"];#cleanupSpecificData(system){const specificData=system.specific;isObject$1(specificData)&&("price"in specificData&&(specificData["-=price"]=null),specificData.value===!0?(specificData["-=value"]=null,specificData.runes=foundry.utils.deepClone(system.runes),isObject$1(specificData.material)&&"precious"in specificData.material?(specificData.material["-=precious"]=null,specificData.material=foundry.utils.mergeObject(specificData.material,foundry.utils.deepClone(system.material))):specificData.material=foundry.utils.deepClone(system.material)):"value"in specificData&&(system.specific=null))}#getRuneValue(system,key){if(!isObject$1(system))throw ErrorPF2e("Unexpected system data");const runeObject=system[key];return isObject$1(runeObject)?runeObject.value:null}async updateItem(source){if(itemIsOfType(source,"armor","weapon")&&(source.type==="armor"?source.system.runes??={potency:0,resilient:0,property:[]}:source.type==="weapon"&&(source.system.runes??={potency:0,striking:0,property:[]}),"potencyRune"in source.system&&isObject$1(source.system.potencyRune))){const potencyRune=Number(source.system.potencyRune.value)||0;source.system.runes.potency=tupleHasValue([1,2,3,4],potencyRune)?potencyRune:0}if(source.type==="armor"){if("resiliencyRune"in source.system&&isObject$1(source.system.resiliencyRune)){const resilientRune=String(source.system.resiliencyRune.value),numericValue=this.#RESILIENT_RUNE_CONVERSION.get(resilientRune)??0;source.system.runes.resilient=numericValue}for(const runeKey of["propertyRune1","propertyRune2","propertyRune3","propertyRune4"]){if(!(runeKey in source.system))continue;const runeValue=this.#getRuneValue(source.system,runeKey);setHasElement(ARMOR_PROPERTY_RUNE_TYPES,runeValue)&&(source.system.runes.property.push(runeValue),source.system.runes.property=uniq(compact(source.system.runes.property)),source.system.runes.property.length=Math.min(source.system.runes.property.length,4))}this.#cleanupSpecificData(source.system)}else if(source.type==="weapon"){if("strikingRune"in source.system&&isObject$1(source.system.strikingRune)){const strikingRune=String(source.system.strikingRune.value),numericValue=this.#STRIKING_RUNE_CONVERSION.get(strikingRune)??0;source.system.runes.striking=numericValue}for(const runeKey of["propertyRune1","propertyRune2","propertyRune3","propertyRune4"]){if(!(runeKey in source.system))continue;const runeValue=this.#getRuneValue(source.system,runeKey);setHasElement(WEAPON_PROPERTY_RUNE_TYPES,runeValue)&&(source.system.runes.property.push(runeValue),source.system.runes.property=uniq(compact(source.system.runes.property)),source.system.runes.property.length=Math.min(source.system.runes.property.length,4))}this.#cleanupSpecificData(source.system)}for(const deletion of this.#RUNE_DELETIONS)deletion in source.system&&(source.system[`-=${deletion}`]=null)}}class Migration908TrueGangUp extends MigrationBase{static{__name(this,"Migration908TrueGangUp")}static{__name2(this,"Migration908TrueGangUp")}static version=.908;async updateItem(source){if((source.system.slug??"")==="gang-up"&&source.type==="feat"){const rule={key:"ActiveEffectLike",mode:"add",path:"system.attributes.flanking.canGangUp",value:!0};source.system.rules=[rule]}}}class Migration909RefineConsumableData extends MigrationBase{static{__name(this,"Migration909RefineConsumableData")}static{__name2(this,"Migration909RefineConsumableData")}static version=.909;async updateItem(source){if(source.type!=="consumable")return;const system=source.system,autoDestroy=isObject$1(system.autoDestroy)?!!system.autoDestroy.value:system.uses?.autoDestroy??!0;if("autoDestroy"in system&&(system["-=autoDestroy"]=null),"charges"in system){if(isObject$1(system.charges)){const value=Math.min(Math.max(Math.floor(Number(system.charges.value)||0),0),9999),max=Math.min(Math.max(Math.floor(Number(system.charges.max)||0),0),9999);system.uses={value,max,autoDestroy},system.uses.max===0&&(system.uses.value=1,system.uses.max=1)}system["-=charges"]=null}if("consumableType"in system){if(isObject$1(system.consumableType)){const category=system.consumableType.value==="tool"?"toolkit":system.consumableType.value;system.category=setHasElement(CONSUMABLE_CATEGORIES,category)?category:"other"}system["-=consumableType"]=null}if(system.slug==="fang-snare"&&(system.category="snare"),"consume"in system){if(isObject$1(system.consume)){const traits=source.system.traits.value,formula=typeof system.consume.value=="string"&&system.consume.value.trim()||null,type=formula?this.#determineDamageType(system.category,traits,system.description.value):null,kind=DAMAGE_ONLY_CONSUMABLE_CATEGORIES.has(system.category)||!["vitality","void","untyped"].includes(type??"")?"damage":"healing";system.damage=formula===null||type===null?null:{formula,kind,type}}system["-=consume"]=null}DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES.has(system.category)||(system.damage=null)}#determineDamageType(category,traits,description){const damageTypes2=Array.from(DAMAGE_TYPES),fromTraits=damageTypes2.find(t=>traits.includes(t)),fromDescription=!fromTraits&&category==="snare"?damageTypes2.find(t=>new RegExp(String.raw`\b${t}\b`).test(description)):null;return fromTraits??fromDescription??"untyped"}}class Migration910EdictsAnathemaArrays extends MigrationBase{static{__name(this,"Migration910EdictsAnathemaArrays")}static{__name2(this,"Migration910EdictsAnathemaArrays")}static version=.91;async updateActor(source){if(source.type!=="character")return;const biography=source.system.details.biography;biography.edicts=compact(typeof biography.edicts=="string"?[biography.edicts]:biography.edicts??[]),biography.anathema=compact(typeof biography.anathema=="string"?[biography.anathema]:biography.anathema??[])}}class Migration911CoinBulk extends MigrationBase{static{__name(this,"Migration911CoinBulk")}static{__name2(this,"Migration911CoinBulk")}static version=.911;async updateItem(source){source.type==="treasure"&&source.system.stackGroup==="coins"&&(source.system.bulk.value=1)}}const Migrations=Object.freeze(Object.defineProperty({__proto__:null,Migration634PurgeMartialItems,Migration635NumifyACAndQuantity,Migration636NumifyArmorData,Migration637CleanMeleeItems,Migration638SpellComponents,Migration639NormalizeLevelAndPrice,Migration640CantripsAreNotZeroLevel,Migration641SovereignSteelValue,Migration642TrackSchemaVersion,Migration643HazardLevel,Migration644SpellcastingCategory,Migration645TokenImageSize,Migration646UpdateInlineLinks,Migration647FixPCSenses,Migration648RemoveInvestedProperty,Migration649FocusToActor,Migration650StringifyWeaponProperties,Migration651EphemeralFocusPool,Migration652KillHalcyonTradition,Migration653AEstoREs,Migration654ActionTypeAndCount,Migration655CreatureTokenSizes,Migration656OtherFocusPoolSources,Migration657RemoveSetProperty,Migration658MonkUnarmoredProficiency,Migration659MultipleDamageRows,Migration660DerivedSpellTraits,Migration661NumifyVehicleDimensions,Migration662LinkToActorSizeDefaults,Migration663FixSpellDamage,Migration664DeleteCUBConditions,Migration665HandwrapsCorrections,Migration666UsageAndStowingContainers,Migration667HPSubProperties,Migration668ArmorSpeedPenalty,Migration669NPCAttackEffects,Migration670AncestryVision,Migration670NoCustomTrait,Migration671NoPCItemsOnNonPCs,Migration672RemoveNPCBaseProperties,Migration673RemoveBulwarkREs,Migration674StableHomebrewTagIDs,Migration675FlatModifierAEsToREs,Migration676ReplaceItemsWithRELikeAEs,Migration677RuleValueDataRefs,Migration678SeparateNPCAttackTraits,Migration679TowerShieldSpeedPenalty,Migration680SetWeaponHands,Migration681GiantLanguageToJotun,Migration682BiographyFields,Migration683FlavorTextToPublicNotes,Migration684RationsToConsumable,Migration685FixMeleeUsageTraits,Migration686HeroPointsToResources,Migration687FamiliarityAEsToREs,Migration688ClampSpellLevel,Migration689EncumberanceActiveEffects,Migration690InitiativeTiebreakItems,Migration691WeaponRangeAbilityCategoryGroup,Migration692CraftingEntryFeatReplacement,Migration693ArmorCategoryGroup,Migration694RetireSystemTokenSettings,Migration695SummonToSummoned,Migration696FlatAbilityModifiers,Migration697WeaponReachTrait,Migration698RemoveDerivedActorTraits,Migration699ItemDescriptionEmptyString,Migration700SingleClassFeatures,Migration701ModifierNameToSlug,Migration702REFormulasAtInstanceLevel,Migration703SpellDamageStructure,Migration704MartialProficiencyRE,Migration705GunslingerCatchUp,Migration706FormulasAtInstanceLevelEverythingElse,Migration707BracketedFormulasAtInstanceLevel,Migration708SpecificRuleLabel,Migration709REFormulasAtInstanceLevelRedux,Migration710RarityToString,Migration711HeritageItems,Migration712ActorShieldStructure,Migration713FistToStrikeRE,Migration714RangeIncrementREs,Migration715DangerousSorcery,Migration716StrikeDamageSelector,Migration717TakeFeatLimits,Migration718CarryType,Migration719ShrugFlanking,Migration720UpdateSpellDescriptions,Migration721SetReloadValues,Migration722CraftingSystemData,Migration723CumulativeItemBonuses,Migration724CraftingMaxItemLevel,Migration725QuickClimbREs,Migration726JournalSetting,Migration727TrimSelfRollOptions,Migration728FlattenPhysicalProperties,Migration729CumulativeItemBonusCleanup,Migration730DeruneHandwraps,Migration731TogglePropertyToRollOption,Migration732FixDedicationFeatTypes,Migration733ItemBonusFromEquipment,Migration734SpellLocationPropsAndSignature,Migration735FirearmAmmoAlchemical,Migration736RemoveBrokenThreshold,Migration737NormalizeRuleElementKeys,Migration738UpdateLaughingShadow,Migration739RecoveryCheckDC,Migration740MaxTakable,Migration741RollOptionToggleToItem,Migration742RMAbilityBoostLevels,Migration743FixWeaknessStructure,Migration744MigrateSpellHeighten,Migration745EffectTargetToChoiceSet,Migration746StandardizePricing,Migration747FixedHeightening,Migration748BatchConsumablePricing,Migration749AssuranceREs,Migration750FixCorruptedPrice,Migration751ResetRollOptions,Migration752StrikeVsWeaponTraits,Migration753WeaponReloadTimes,Migration754MightyBulwarkAdjustModifiers,Migration755GrantIdsToData,Migration756RMStoredResourceMaxes,Migration757HillockHalfling,Migration758PrunePCAttributes,Migration759CritSpecRE,Migration760SeparateNoteTitle,Migration761ShotRules,Migration762UpdateBackgroundItems,Migration763RestoreAnimalStrikeOptions,Migration764PanacheVivaciousREs,Migration765ChoiceOwnedItemTypes,Migration766WipeURLSources,Migration767ConvertVoluntaryFlaws,Migration768AddNewAuras,Migration769NoUniversalistFocusPool,Migration770REDataToSystem,Migration771SpellVariantsToSystem,Migration772V10EmbeddedSpellData,Migration773ReligiousSymbolUsage,Migration774UnpersistCraftingEntries,Migration775AgileFinesseRanged,Migration776SlugifyConditionOverrides,Migration777HandOfTheApprentice,Migration778RenameRetiredPackRefs,Migration779EliteWeak,Migration780NumifySpeeds,Migration781SuppressNoCrowbar,Migration782UnnestActorTraits,Migration783RemoveClassSkillAELikes,Migration784CompBrowserPackSetting,Migration785ABCKitItemUUIDs,Migration786RemoveIdentifiedData,Migration787ResolvablesToSystem,Migration788UpdateTanglefootBags,Migration789UpdatePreciseStrike,Migration790MultipleClassDCs,Migration791RuffianHands,Migration792RemoveTokenAELikes,Migration793MakePredicatesArrays,Migration794AddWildShapeChoices,Migration795CleanupFlatFootedToggle,Migration796ItemGrantsToObjects,Migration797MetagameSetting,Migration798WeaponToItemStatements,Migration799RMRecallKnowledgeDuplicates,Migration800SelfEffectPanacheRage,Migration801ColorDarkvision,Migration802StripFeatActionCategory,Migration803NormalizeSpellArea,Migration804RemoveConsumableProperties,Migration805InlineDamageRolls,Migration806TorchImprovisedOtherTags,Migration807RMActivatedEffectFields,Migration808CountDamageDice,Migration809AutomatonEnhancements,Migration810LootDescriptionValue,Migration811InlineDamageRollsPersistent,Migration812RestructureIWR,Migration813NormalizeColdIron,Migration814CalculatedExpandedSplash,Migration815ConsumableDataCleanup,Migration816AlchemistResearchFields,Migration817FieldDiscoveryPredicates,Migration818BasicUndeadNegativeHealing,Migration819SpinTaleAdventureSpecific,Migration820RemoveUnusedTraitsData,Migration821InlineDamageRolls,Migration822BladeAllyConsolidation,Migration823HeritageAncestrySlug,Migration824SneakAttackDamageSource,Migration825KhakkharaFengHuoLun,Migration826GutConditionData,Migration827FixTVShieldTraits,Migration828PruneInvalidTraits,Migration829RMRitualEntries,Migration830BarbarianRework,Migration831ClericDoctrines,Migration832ChoiceSetFlags,Migration833AddRogueToysFixPrecision,Migration834FeatCategories,Migration835InitiativeLongform,Migration836EnergizingConsolidation,Migration837MoveHazardBookSources,Migration838StrikeAttackRollSelector,Migration839ActionCategories,Migration840ArrayWrapPredicates,Migration841V11UUIDFormat,Migration842NumifyNumericSettings,Migration843RMArmorCustomModifiers,Migration844DeityDomainUUIDs,Migration845EmptySpellConsumables,Migration846SpellSchoolOptional,Migration847TempHPRuleEvents,Migration848NumericArmorProperties,Migration849DeleteBrokenThreshold,Migration850FlatFootedToOffGuard,Migration851JustInnovationId,Migration852AbilityScoresToModifiers,Migration853RemasterLanguages,Migration854BracketedAbilityScoresToModifiers,Migration855ApexEquipmentSystemData,Migration856NoSystemDotCustom,Migration857WeaponSpecializationRE,Migration858FakeWeaponSpecialization,Migration859MaterialTypeGrade,Migration860RMGroup,Migration861AuraColorsToAppearance,Migration862SpecificMagicArmor,Migration863FixMisspelledOrganaizationsProperty,Migration864RemoveWeaponMAP,Migration865VitalityVoid,Migration866LinkToActorSizeAgain,Migration867DamageRollDomainFix,Migration868StrikeRERange,Migration869RefreshMightyBulwark,Migration870MartialToProficiencies,Migration871MigrateRollActionMacroParams,Migration872MoveSchemaProperty,Migration873RemoveBonusBulkLimit,Migration874MoveStaminaStuff,Migration875SetInnovationIdEarly,Migration876FeatLevelTaken,Migration877PublicationData,Migration878TakeABreather,Migration879DeviseAStratagemAndFriends,Migration880SplitShowDialogsSettings,Migration881NoHBPrefix,Migration882SpellDataReorganization,Migration883BanishAlignment,Migration884UnifiedSpellcasting,Migration885ConvertAlignmentDamage,Migration886CrossbowGroup,Migration887RedirectSpellLinks,Migration888RemasterLanguagesHeritages,Migration889RemoveFocusMaxIncreases,Migration890RMClassItemClassDC,Migration891DruidicToWildsong,Migration892ChoiceSetREAdjustNameValue,Migration893NoHBPrefixSettings,Migration894NoLayOnHandsVsUndead,Migration895FixVariantSpellTraits,Migration896HealingDomains,Migration897ClearLayOnHandsDamage,Migration898NoHBAgain,Migration899ArmorShieldToShieldShield,Migration900ClassSpellcastingProficiency,Migration901ReorganizeBulkData,Migration902DuskwoodDawnsilver,Migration903PhysicalNumericData,Migration904UndercommonToSakvroth,Migration905UnpersistUsage,Migration906LimitStackGroup,Migration907RestructureArmorWeaponRunes,Migration908TrueGangUp,Migration909RefineConsumableData,Migration910EdictsAnathemaArrays,Migration911CoinBulk},Symbol.toStringTag,{value:"Module"}));class MigrationList{static{__name(this,"MigrationList")}static{__name2(this,"MigrationList")}static#list=Object.values(Migrations);static get latestVersion(){return Math.max(...this.#list.map(M=>M.version))}static constructAll(){return this.#list.map(M=>new M)}static constructFromVersion(version){const minVersion=Number(version)||MigrationRunner.RECOMMENDED_SAFE_VERSION;return this.#list.filter(M=>M.version>minVersion).map(M=>new M)}static constructRange(min,max=1/0){return this.#list.filter(M=>M.version>=min&&M.version<=max).map(M=>new M)}}class WeaponDamagePF2e{static{__name(this,"WeaponDamagePF2e")}static{__name2(this,"WeaponDamagePF2e")}static async fromNPCAttack({attack,actor,context}){const{baseDamage}=attack,secondaryInstances=Object.values(attack.system.damageRolls).map(this.npcDamageToWeaponDamage).filter(d=>!equals(d,baseDamage)),damageDice=[],modifiers=[],labelFromCategory={null:"",persistent:"",precision:"PF2E.Damage.Precision",splash:"PF2E.WeaponSplashDamageLabel"};for(const instance of secondaryInstances){const{damageType}=instance;instance.dice>0&&instance.die&&damageDice.push(new DamageDicePF2e({slug:"base",label:labelFromCategory[instance.category??"null"],selector:"damage",diceNumber:instance.dice,dieSize:instance.die,damageType:instance.damageType,category:instance.category})),instance.modifier&&modifiers.push(new ModifierPF2e({label:labelFromCategory[instance.category??"null"],modifier:instance.modifier,damageType,damageCategory:instance.category}))}return WeaponDamagePF2e.calculate({weapon:attack,actor,damageDice,modifiers,context})}static async calculate({weapon,actor,damageDice=[],modifiers=[],weaponPotency=null,context}){const{baseDamage}=weapon,{options}=context,domains=context.domains;if(baseDamage.die===null&&baseDamage.modifier>0)baseDamage.dice=0;else if(!weapon.dealsDamage)return null;const weaponTraits2=weapon.system.traits.value,materialTraits=weapon.isOfType("melee")?weapon.system.traits.value.filter(t=>t in CONFIG.PF2E.materialDamageEffects):[];for(const trait of weaponTraits2)options.add(trait);const isMelee=!!weapon.isMelee;if(options.add(isMelee?"melee":"ranged"),actor.isOfType("character")&&weapon.isOfType("weapon")){const attributeDomains=ATTRIBUTE_ABBREVIATIONS.map(a=>`${a}-damage`),domain=domains.find(d=>attributeDomains.has(d)),strengthModValue=actor.abilities.str.mod,modifierValue=domain==="str-damage"?strengthModValue<0||!weaponTraits2.some(t=>t==="propulsive")?strengthModValue:Math.floor(strengthModValue/2):null;if(typeof modifierValue=="number"){const strModifier=createAttributeModifier({actor,attribute:"str",domains,max:modifierValue});modifiers.push(strModifier)}}for(const rule of actor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);const splashDamage=weapon.isOfType("weapon")?Number(weapon.system.splashDamage?.value):0;if(splashDamage>0){const modifier=new ModifierPF2e({slug:"splash",label:"PF2E.WeaponSplashDamageLabel",modifier:splashDamage,damageCategory:"splash",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"splash")});modifiers.push(modifier)}if(weapon.isOfType("weapon")){weaponTraits2.includes("kickback")&&modifiers.push(new ModifierPF2e({slug:"kickback",label:CONFIG.PF2E.weaponTraits.kickback,modifier:1,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"kickback")}));const handsHeld=weapon.system.equipped.handsHeld??0,baseDieFaces=Number(baseDamage.die?.replace("d","")??"NaN"),twoHandSize=weaponTraits2.find(t=>t.startsWith("two-hand-"))?.replace("two-hand-",""),twoHandFaces=Number(twoHandSize?.replace("d","")??"NaN");if(handsHeld===2&&setHasElement(DAMAGE_DIE_FACES,twoHandSize)&&twoHandFaces>baseDieFaces&&(baseDamage.die=twoHandSize),weaponTraits2.find(t=>t.startsWith("scatter-"))&&baseDamage.die){const modifier=new ModifierPF2e({slug:"scatter",label:"PF2E.Damage.Scatter",modifier:baseDamage.dice,damageCategory:"splash",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"scatter")});modifiers.push(modifier)}const bonusDamage=Number(weapon.system.bonusDamage?.value);bonusDamage>0&&modifiers.push(new ModifierPF2e({label:"PF2E.WeaponBonusDamageLabel",modifier:bonusDamage}));const customDamage=weapon.system.property1,normalDice=customDamage.dice??0;if(normalDice>0){const damageType=customDamage.damageType||null;damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"custom",label:"PF2E.WeaponCustomDamageLabel",diceNumber:normalDice,dieSize:customDamage.die,damageType}))}const critDice=customDamage.critDice??0;if(critDice>0){const damageType=customDamage.critDamageType||null;damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"custom-critical",label:"PF2E.WeaponCustomDamageLabel",diceNumber:critDice,dieSize:customDamage.critDie,damageType,critical:!0}))}}const potency=weaponPotency?.bonus??0,strikingSynthetic=domains.flatMap(key=>actor.synthetics.striking[key]??[]).filter(wp=>wp.predicate.test(options)).reduce((highest,current)=>highest&&highest.bonus>current.bonus?highest:current,null);strikingSynthetic&&baseDamage.die&&(weapon.isOfType("melee")||strikingSynthetic.bonus>weapon.system.runes.striking)&&(damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:"striking",label:strikingSynthetic.label,diceNumber:strikingSynthetic.bonus})),weapon.isOfType("weapon")&&(weapon.system.damage.dice-=weapon.system.runes.striking,weapon.system.runes.striking=0));const critSpecEffect=(()=>{const critSpecs=actor.synthetics.criticalSpecalizations,standard=critSpecs.standard.reduceRight((result,cs)=>result??cs?.(weapon,options),null),alternate=critSpecs.alternate.reduceRight((result,cs)=>result??cs?.(weapon,options),null);return standard?alternate??standard:[]})();critSpecEffect.length>0&&options.add("critical-specialization"),modifiers.push(...critSpecEffect.filter(e=>e instanceof ModifierPF2e)),damageDice.push(...critSpecEffect.filter(e=>e instanceof DamageDicePF2e));const propertyRunes=weapon.system.runes.property;damageDice.push(...getPropertyRuneDice(propertyRunes,options));const propertyRuneAdjustments=getPropertyRuneModifierAdjustments(propertyRunes),ignoredResistances=propertyRunes.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.ignoredResistances??[]);if(weaponTraits2.some(t=>t==="backstabber")&&options.has("target:condition:off-guard")){const modifier=new ModifierPF2e({label:CONFIG.PF2E.weaponTraits.backstabber,slug:"backstabber",modifier:potency>2?2:1,damageCategory:"precision",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"backstabber")});modifiers.push(modifier)}const traitLabels=CONFIG.PF2E.weaponTraits,deadlyTraits=weaponTraits2.filter(t=>t.startsWith("deadly-")),strikingDice=(()=>{if(weapon.isOfType("weapon")){const weaponStrikingDice=weapon.system.damage.dice-weapon._source.system.damage.dice;return strikingSynthetic&&strikingSynthetic.bonus>weaponStrikingDice?strikingSynthetic.bonus:weaponStrikingDice}else return strikingSynthetic?.bonus??0})();for(const slug of deadlyTraits){const diceNumber=(()=>{const baseNumber=Number(/-(\d)d\d{1,2}$/.exec(slug)?.at(1))||1;return strikingDice>1?strikingDice*baseNumber:baseNumber})();damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug,label:traitLabels[slug],damageType:baseDamage.damageType,diceNumber,dieSize:/-\d?(d\d{1,2})$/.exec(slug)?.at(1)??baseDamage.die,critical:!0}))}for(const trait of weaponTraits2.filter(t=>t.startsWith("fatal-d"))){const dieSize=trait.substring(trait.indexOf("-")+1);damageDice.push(new DamageDicePF2e({selector:`${weapon.id}-damage`,slug:trait,label:traitLabels[trait],damageType:baseDamage.damageType,diceNumber:1,dieSize,critical:!0,enabled:!0,override:{dieSize}}))}const runeNotes=propertyRunes.flatMap(r=>(RUNE_DATA.weapon.property[r].damage?.notes??[]).map(d=>new RollNotePF2e({selector:"strike-damage",...d})));context.notes=[runeNotes,critSpecEffect.filter(e=>e instanceof RollNotePF2e)].flat();const material=objectHasKey(CONFIG.PF2E.materialDamageEffects,weapon.system.material.type)?weapon.system.material.type:null,materials=new Set([materialTraits,material??[]].flat());for(const adjustment of actor.synthetics.strikeAdjustments)adjustment.adjustDamageRoll?.(weapon,{materials});for(const option of Array.from(materials).map(m=>`item:material:${m}`))options.add(option);for(const modifier of modifiers){const propRuneAdjustments=propertyRuneAdjustments.filter(a=>a.slug===modifier.slug);modifier.adjustments.push(...propRuneAdjustments)}const baseUncategorized=(()=>{const diceNumber=baseDamage.die?baseDamage.dice:0;return diceNumber>0||baseDamage.modifier>0?{diceNumber,dieSize:baseDamage.die,modifier:baseDamage.modifier,damageType:baseDamage.damageType,category:"category"in baseDamage&&baseDamage.category==="persistent"?"persistent":null,materials:Array.from(materials)}:null})(),basePersistent=(()=>baseDamage.persistent?.faces?{diceNumber:baseDamage.persistent.number,dieSize:`d${baseDamage.persistent.faces}`,damageType:baseDamage.persistent.type,category:"persistent"}:baseDamage.persistent?.number?{modifier:baseDamage.persistent.number,damageType:baseDamage.persistent.type,category:"persistent"}:null)();if(!(baseUncategorized||basePersistent||splashDamage))return null;const base=compact([baseUncategorized,basePersistent]),extractOptions={test:options,resolvables:{weapon,target:context.target?.actor??null},injectables:{weapon}},extracted=processDamageCategoryStacking(base,{modifiers:[modifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:options}),testedModifiers=extracted.modifiers;damageDice.push(...extracted.dice);const formulaData={base,dice:damageDice,maxIncreases:1,modifiers:testedModifiers,ignoredResistances};formulaData.base[0].diceNumber||formulaData.base[0].modifier||(formulaData.dice=formulaData.dice.filter(d=>![null,"precision"].includes(d.category)),formulaData.modifiers=formulaData.modifiers.filter(m=>![null,"precision"].includes(m.category)));const excludeFrom=weapon.isOfType("weapon")?weapon:null;if(this.#excludeDamage({actor,weapon:excludeFrom,modifiers:[...testedModifiers,...damageDice],options}),!context.skipDialog&&!await new DamageModifierDialog({formulaData,context}).resolve())return null;const computedFormulas={criticalFailure:null,failure:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.FAILURE),success:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.SUCCESS),criticalSuccess:createDamageFormula(formulaData,DEGREE_OF_SUCCESS.CRITICAL_SUCCESS)};return{name:`${game.i18n.localize("PF2E.DamageRoll")}: ${weapon.name}`,materials:Array.from(materials),modifiers:[...modifiers,...damageDice],damage:{...formulaData,formula:mapValues(computedFormulas,formula=>formula?.formula??null),breakdown:mapValues(computedFormulas,formula=>formula?.breakdown??[])}}}static#excludeDamage({actor,modifiers,weapon,options}){if(!weapon)return;const notIgnored=modifiers.filter(modifier=>!modifier.ignored);for(const rule of actor.rules)rule.applyDamageExclusion?.(weapon,notIgnored);for(const modifier of notIgnored)modifier.ignored=!modifier.predicate.test(options)}static npcDamageToWeaponDamage(instance){const terms=parseTermsFromSimpleFormula(instance.damage),die=terms.find(t=>t.dice)?.dice,modifier=terms.find(t=>t.modifier)?.modifier??0;return{dice:die?.number??0,die:die?.faces?`d${die.faces}`:null,modifier,damageType:instance.damageType,persistent:null,category:instance.category}}}async function resetActors(actors,options={}){actors??=[game.actors.contents,game.scenes.contents.flatMap(s=>s.tokens.contents).flatMap(t=>t.actor??[])].flat(),actors=uniq(Array.from(actors));for(const actor of actors)actor.reset(),options.sheets&&actor.render();if(game.pf2e.effectPanel.refresh(),game.settings.get("pf2e","automation.effectExpiration")&&!game.settings.get("pf2e","automation.removeExpiredEffects")){const scenes=uniq(Array.from(actors).flatMap(a=>a.getActiveTokens(!1,!0)).flatMap(t=>t.scene));for(const scene of scenes)scene.reset(),scene.isView&&canvas.perception.update({initializeVision:!0},!0)}if(options.tokens)for(const token of uniq(Array.from(actors).flatMap(a=>a.getActiveTokens(!0,!0))))token.simulateUpdate()}__name(resetActors,"resetActors"),__name2(resetActors,"resetActors");function userColorForActor(actor){return(game.users.find(u=>u.character===actor)??game.users.players.find(u=>actor.testUserPermission(u,"OWNER"))??actor.primaryUpdater)?.color??"#43dfdf"}__name(userColorForActor,"userColorForActor"),__name2(userColorForActor,"userColorForActor");async function migrateActorSource(source){source.effects=[],["flags","items","system"].some(k=>k in source)||(source.system={_migration:{version:MigrationRunnerBase.LATEST_SCHEMA_VERSION}});const lowestSchemaVersion=Math.min(source.system?._migration?.version??MigrationRunnerBase.LATEST_SCHEMA_VERSION,...(source.items??[]).map(i=>i?.system?._migration?.version??MigrationRunnerBase.LATEST_SCHEMA_VERSION)),tokenDefaults=foundry.utils.deepClone(game.settings.get("core","defaultToken")),actor=new ActorProxyPF2e(foundry.utils.mergeObject({prototypeToken:tokenDefaults},source));return await MigrationRunner.ensureSchemaVersion(actor,MigrationList.constructFromVersion(lowestSchemaVersion)),actor.toObject()}__name(migrateActorSource,"migrateActorSource"),__name2(migrateActorSource,"migrateActorSource");async function checkAreaEffects(){if(!canvas.ready||game.user!==this.primaryUpdater||this.isOfType("party"))return;const thisTokens=this.getActiveTokens(!0,!0),toDelete2=[],toKeep=[];for(const effect of this.itemTypes.effect){const auraData=effect.flags.pf2e.aura;if(!auraData?.removeOnExit)continue;const auraActor=await fromUuid(auraData.origin),aura=(auraActor?.getActiveTokens(!0,!0).shift()??null)?.auras.get(auraData.slug),auraEffectData=auraActor?.auras.get(auraData.slug)?.effects.find(e=>e.uuid===effect.sourceId&&auraAffectsActor(e,auraActor,this));for(const token of thisTokens)auraEffectData&&aura?.containsToken(token)?toKeep.push(effect.id):toDelete2.push(effect.id);thisTokens.length===0&&toDelete2.push(effect.id)}const finalToDelete=toDelete2.filter(id=>!toKeep.includes(id));finalToDelete.length>0&&await this.deleteEmbeddedDocuments("Item",finalToDelete)}__name(checkAreaEffects,"checkAreaEffects"),__name2(checkAreaEffects,"checkAreaEffects");function auraAffectsActor(data,origin,actor){return data.includesSelf&&origin===actor||data.affects==="allies"&&actor.isAllyOf(origin)||data.affects==="enemies"&&actor.isEnemyOf(origin)||data.affects==="all"&&actor!==origin}__name(auraAffectsActor,"auraAffectsActor"),__name2(auraAffectsActor,"auraAffectsActor");function setHitPointsRollOptions(actor){const hp=actor.hitPoints;if(!hp)return;actor.flags.pf2e.rollOptions.all[`hp-remaining:${hp.value}`]=!0;const percentRemaining=Math.floor(hp.value/hp.max*100);actor.flags.pf2e.rollOptions.all[`hp-percent:${percentRemaining}`]=!0}__name(setHitPointsRollOptions,"setHitPointsRollOptions"),__name2(setHitPointsRollOptions,"setHitPointsRollOptions");function calculateMAPs(item,{domains,options}){const slugAndLabel={slug:"multiple-attack-penalty",label:"PF2E.MultipleAttackPenalty"},baseMap=item.isOfType("action","melee","weapon")&&item.traits.has("agile")?{...slugAndLabel,map1:-4,map2:-8}:{...slugAndLabel,map1:-5,map2:-10},optionSet=options instanceof Set?options:new Set(options),maps=item.actor?.synthetics.multipleAttackPenalties??{},fromSynthetics=domains.flatMap(d=>maps[d]??[]).filter(p=>p.predicate?.test(optionSet)??!0).map(p=>({slug:baseMap.slug,label:p.label,map1:p.penalty,map2:p.penalty*2}));return[baseMap,...fromSynthetics].reduce((lowest,p)=>p.map1>lowest.map1?p:lowest)}__name(calculateMAPs,"calculateMAPs"),__name2(calculateMAPs,"calculateMAPs");function createEncounterRollOptions(actor){const encounter=game.ready?game.combat:null;if(!encounter?.started)return{};const participants=encounter.combatants.contents.filter(c=>typeof c.initiative=="number").sort((a,b)=>b.initiative-a.initiative),participant=actor.combatant;if(typeof participant?.initiative!="number"||!participants.includes(participant))return{};const initiativeRoll=Math.trunc(participant.initiative),initiativeRank=participants.indexOf(participant)+1,{initiativeStatistic}=participant.flags.pf2e,threat=encounter.metrics?.threat,numericThreat={trivial:0,low:1,moderate:2,severe:3,extreme:4}[threat??"trivial"],entries=[["encounter",!0],[`encounter:threat:${numericThreat}`,!!threat],[`encounter:threat:${threat}`,!!threat],[`encounter:round:${encounter.round}`,!0],[`encounter:turn:${Number(encounter.turn)+1}`,!0],["self:participant:own-turn",encounter.combatant===participant],[`self:participant:initiative:roll:${initiativeRoll}`,!0],[`self:participant:initiative:rank:${initiativeRank}`,!0],[`self:participant:initiative:stat:${initiativeStatistic}`,!!initiativeStatistic]].filter(([,value])=>!!value);return Object.fromEntries(entries)}__name(createEncounterRollOptions,"createEncounterRollOptions"),__name2(createEncounterRollOptions,"createEncounterRollOptions");function isOffGuardFromFlanking(target,origin,originRollOptions){if(!target.isOfType("creature"))return!1;const{flanking}=target.attributes;return flanking.flankable&&(typeof flanking.offGuardable=="number"?origin.level>flanking.offGuardable:flanking.offGuardable)&&!target.attributes.immunities.some(i=>i.test(["item:type:condition","item:slug:off-guard",...originRollOptions]))}__name(isOffGuardFromFlanking,"isOffGuardFromFlanking"),__name2(isOffGuardFromFlanking,"isOffGuardFromFlanking");function getStrikeAttackDomains(weapon,proficiencyRank,baseRollOptions){const unarmedOrWeapon=weapon.category==="unarmed"?"unarmed":"weapon",meleeOrRanged=weapon.isMelee?"melee":"ranged",weaponSlug=weapon.slug??sluggify(weapon.name),domains=[weapon.baseType?`${weapon.baseType}-base-attack-roll`:[],weapon.group?`${weapon.group}-group-attack-roll`:[],weapon.system.traits.otherTags.map(t=>`${t}-tag-attack-roll`),`${weapon.id}-attack`,`${weaponSlug}-attack`,`${weaponSlug}-attack-roll`,`${unarmedOrWeapon}-attack-roll`,`${meleeOrRanged}-attack-roll`,`${meleeOrRanged}-strike-attack-roll`,"strike-attack-roll","attack-roll","attack","check","all"].flat();if(typeof proficiencyRank=="number"){const proficiencies=["untrained","trained","expert","master","legendary"];domains.push(`${proficiencies[proficiencyRank]}-attack`)}const{actor}=weapon;if(actor.isOfType("character","npc")){const defaultAttributeModifier=createAttributeModifier({actor,attribute:weapon.defaultAttribute,domains}),rollOptions=[...baseRollOptions,actor.getRollOptions(domains),weapon.getRollOptions("item")].flat(),weaponTraits2=weapon.traits,alternativeAttributeModifier=actor.isOfType("character")?weaponTraits2.has("finesse")?createAttributeModifier({actor,attribute:"dex",domains}):weaponTraits2.has("brutal")||weaponTraits2.has("propulsive")?createAttributeModifier({actor,attribute:"str",domains}):null:null,attributeModifier=compact([defaultAttributeModifier,alternativeAttributeModifier,...extractModifiers(weapon.actor.synthetics,domains,{resolvables:{weapon},test:rollOptions})]).filter(m=>m.type==="ability"&&m.enabled).reduce((best,candidate)=>candidate.modifier>best.modifier?candidate:best);domains.push(`${attributeModifier.ability}-attack`,`${attributeModifier.ability}-based`)}return uniq(domains)}__name(getStrikeAttackDomains,"getStrikeAttackDomains"),__name2(getStrikeAttackDomains,"getStrikeAttackDomains");function getStrikeDamageDomains(weapon,proficiencyRank){const meleeOrRanged=weapon.isMelee?"melee":"ranged",slug=weapon.slug??sluggify(weapon.name),{actor,traits}=weapon,unarmedOrWeapon=traits.has("unarmed")?"unarmed":"weapon",domains=[`${weapon.id}-damage`,`${slug}-damage`,`${meleeOrRanged}-strike-damage`,`${meleeOrRanged}-damage`,`${unarmedOrWeapon}-damage`,"attack-damage","strike-damage","damage"];if(weapon.group&&domains.push(`${weapon.group}-weapon-group-damage`),weapon.baseType&&domains.push(`${weapon.baseType}-base-type-damage`),typeof proficiencyRank=="number"){const proficiencies=["untrained","trained","expert","master","legendary"];domains.push(`${proficiencies[proficiencyRank]}-damage`)}const baseType=CONFIG.PF2E.equivalentWeapons[weapon.baseType??""]??weapon.baseType;if(baseType&&!domains.includes(`${baseType}-damage`)&&domains.push(`${baseType}-damage`),actor.isOfType("character","npc")){const attributeModifier=[weapon.isMelee||weapon.isThrown&&!traits.has("splash")||traits.has("propulsive")?createAttributeModifier({actor,attribute:"str",domains}):null,...extractModifiers(actor.synthetics,domains,{resolvables:{weapon},test:[...actor.getRollOptions(domains),...weapon.getRollOptions("item")]}).filter(m=>!m.ignored&&m.type==="ability")].reduce((best,candidate)=>candidate&&best?candidate.value>best.value?candidate:best:candidate??best);attributeModifier&&domains.push(`${attributeModifier.ability}-damage`)}return uniq(domains)}__name(getStrikeDamageDomains,"getStrikeDamageDomains"),__name2(getStrikeDamageDomains,"getStrikeDamageDomains");function strikeFromMeleeItem(item){const{actor,isMelee}=item;if(!actor.isOfType("npc","hazard"))throw ErrorPF2e("Attempted to create melee-item strike statistic for non-NPC/hazard");const meleeOrRanged=isMelee?"melee":"ranged",baseOptions=new Set(compact(["self:action:slug:strike",meleeOrRanged,...item.system.traits.value])),domains=getStrikeAttackDomains(item,actor.isOfType("npc")?1:null,baseOptions),{synthetics}=actor,modifiers=[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:item.attackModifier,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,"base")})];modifiers.push(...extractModifiers(synthetics,domains)),modifiers.push(...AttackTraitHelpers.createAttackModifiers({item}));const attackEffects=CONFIG.PF2E.attackEffects,additionalEffects=item.attackEffects.map(tag=>{const items=actor.items.contents,label=attackEffects[tag]??items.find(i=>(i.slug??sluggify(i.name))===tag)?.name??tag;return{tag,label}});for(const adjustment of synthetics.strikeAdjustments)adjustment.adjustWeapon?.(item);const initialRollOptions=new Set([...baseOptions,...actor.getRollOptions(domains),...item.getRollOptions("item")]),attackSlug=item.slug??sluggify(item.name),statistic=new StatisticModifier(attackSlug,modifiers,initialRollOptions),actionTraits2=compact(["attack",item.baseType==="alchemical-bomb"?"manipulate":null]),strikeAdjustments=[actor.synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(item.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(item,actionTraits2);const strike=foundry.utils.mergeObject(statistic,{label:item.name,type:"strike",glyph:getActionGlyph({type:"action",value:1}),description:item.description,sourceId:item.id,attackRollType:item.isRanged?"PF2E.NPCAttackRanged":"PF2E.NPCAttackMelee",additionalEffects,item,weapon:item,options:Array.from(baseOptions),traits:[actionTraits2.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),item.system.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits))].flat(),variants:[],ready:!0,success:"",criticalSuccess:""});strike.breakdown=strike.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.value)}`).join(", ");const maps=calculateMAPs(item,{domains,options:initialRollOptions}),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,maps.slug)}),"createMapModifier"),labels=[`${game.i18n.localize("PF2E.WeaponStrikeLabel")} ${signedInteger(strike.totalModifier)}`,...["map1","map2"].map(prop=>{const modifier=createMapModifier(prop);adjustModifiers([modifier],baseOptions);const penalty=modifier.ignored?0:modifier.value;return game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(strike.totalModifier+penalty),penalty})})];strike.variants=[null,...["map1","map2"].map(createMapModifier)].map((map2,mapIncreases)=>({label:labels[mapIncreases],roll:async(params={})=>{params.options??=[];const context=await actor.getCheckContext({item,viewOnly:params.getFormula??!1,statistic:strike,target:{token:params.target??game.user.targets.first()??null},defense:"armor",domains,options:new Set([...baseOptions,...params.options]),traits:actionTraits2});if(context.self.item.isRanged&&typeof context.target?.distance=="number"){const maxRange=item.range?.max??10;if(context.target.distance>maxRange)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null}const otherModifiers=[map2??[],context.self.modifiers].flat(),title=game.i18n.format(item.isMelee?"PF2E.Action.Strike.MeleeLabel":"PF2E.Action.Strike.RangedLabel",{weapon:item.name}),notes=[actor.isOfType("npc")?await actor.getAttackEffects(item):[],extractNotes(context.self.actor.synthetics.rollNotes,domains)].flat(),rollTwice=params.rollTwice||extractRollTwice(context.self.actor.synthetics.rollTwice,domains,context.options),substitutions=extractRollSubstitutions(context.self.actor.synthetics.rollSubstitutions,domains,context.options),dosAdjustments=extractDegreeOfSuccessAdjustments(context.self.actor.synthetics,domains),check=new CheckModifier("strike",context.self.statistic??strike,otherModifiers),checkContext={type:"attack-roll",identifier:`${item.id}.${attackSlug}.${meleeOrRanged}`,action:"strike",title,actor:context.self.actor,token:context.self.token,item:context.self.item,target:context.target,damaging:context.self.item.dealsDamage,domains,options:context.options,traits:context.traits,notes,dc:params.dc??context.dc,mapIncreases,rollTwice,substitutions,dosAdjustments},roll=await CheckPF2e.roll(check,checkContext,params.event);if(roll)for(const rule of context.self.actor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context:checkContext,domains,rollOptions:context.options});return roll}})),strike.roll=strike.attack=strike.variants[0].roll;const damageRoll=__name2(outcome=>async(params={})=>{const domains2=getStrikeDamageDomains(item,actor.isOfType("npc")?1:null),targetToken=params.target??game.user.targets.first()??null,context=await actor.getDamageRollContext({item,statistic:strike,target:{token:targetToken},viewOnly:params.getFormula??!1,domains:domains2,checkContext:params.checkContext,outcome,traits:actionTraits2,options:new Set([...baseOptions,...params.options??[]])});if(!context.self.item.dealsDamage&&!params.getFormula)return ui.notifications.warn("PF2E.ErrorMessage.WeaponNoDamage",{localize:!0}),null;const{self,target}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options:context.options,domains:domains2,traits:context.traits,...eventToRollParams(params.event,{type:"damage"})};typeof params.mapIncreases=="number"&&(damageContext.mapIncreases=params.mapIncreases,damageContext.options.add(`map:increases:${params.mapIncreases}`)),params.getFormula&&(damageContext.skipDialog=!0);const damage=await WeaponDamagePF2e.fromNPCAttack({attack:context.self.item,actor:context.self.actor,context:damageContext});if(!damage)return null;if(params.getFormula){const formula=damage.damage.formula[outcome];return formula?new DamageRoll(formula).formula:""}else return DamagePF2e.roll(damage,damageContext,params.callback)},"damageRoll");return strike.damage=damageRoll("success"),strike.critical=damageRoll("criticalSuccess"),strike}__name(strikeFromMeleeItem,"strikeFromMeleeItem"),__name2(strikeFromMeleeItem,"strikeFromMeleeItem");function getRangeIncrement(attackItem,distance){if(!attackItem.isOfType("action","melee","weapon"))return null;const{increment}=attackItem.range??{};return increment&&typeof distance=="number"?Math.max(Math.ceil(distance/increment),1):null}__name(getRangeIncrement,"getRangeIncrement"),__name2(getRangeIncrement,"getRangeIncrement");function calculateRangePenalty(actor,increment,selectors,rollOptions){if(!increment||increment===1)return null;const slug="range-penalty",modifier=new ModifierPF2e({label:"PF2E.RangePenalty",slug,type:"untyped",modifier:Math.max((increment-1)*-2,-12),predicate:[{nor:["ignore-range-penalty",{gte:["ignore-range-penalty",increment]}]}],adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,selectors,slug)});return modifier.test(rollOptions),modifier}__name(calculateRangePenalty,"calculateRangePenalty"),__name2(calculateRangePenalty,"calculateRangePenalty");function isReallyPC(actor){const traits=actor.traits;return actor.isOfType("character")&&!(traits.has("minion")||traits.has("eidolon"))}__name(isReallyPC,"isReallyPC"),__name2(isReallyPC,"isReallyPC");function findMatchingCheckContext(actor,params){if(params.viewOnly||!params.target?.token)return null;const paramsItem=params.item;return paramsItem?.isOfType("melee","weapon")?game.messages.contents.slice(-3).reverse().find(message=>{if(!message.rolls.some(r=>r instanceof CheckRoll)||message.actor?.uuid!==actor.uuid||params.target?.token!==message.target?.token.object)return!1;const messageItem=message.item;if(!messageItem?.isOfType("melee","weapon"))return!1;const paramsItemSlug=paramsItem.slug??sluggify(paramsItem.name),messageItemSlug=messageItem.slug??sluggify(messageItem.name);return paramsItemSlug===messageItemSlug&¶msItem.uuid===messageItem.uuid&¶msItem.isMelee===messageItem.isMelee})?.flags.pf2e.context??null:null}__name(findMatchingCheckContext,"findMatchingCheckContext"),__name2(findMatchingCheckContext,"findMatchingCheckContext");class Statistic extends BaseStatistic{static{__name(this,"Statistic")}static{__name2(this,"Statistic")}attribute=null;rank=null;proficient=!0;base=null;lore;config;#check;#dc;constructor(actor,data,config={}){data.modifiers??=[];const domains=data.domains??=[],attributeModifier=actor.isOfType("character")&&data.attribute?data.modifiers.find(m=>m.type==="ability"&&m.ability===data.attribute)??createAttributeModifier({actor,attribute:data.attribute,domains}):null;data.attribute&&domains.push(`${data.attribute}-based`);const proficiencyModifier=actor.isOfType("character")?typeof data.rank=="number"?createProficiencyModifier({actor,rank:data.rank,domains}):data.rank==="untrained-level"?createProficiencyModifier({actor,rank:0,domains,addLevel:!0}):null:null,baseModifiers=compact([attributeModifier,proficiencyModifier]),activeSlugs=new Set(baseModifiers.map(m=>m.slug));data.modifiers=data.modifiers.filter(m=>!activeSlugs.has(m.slug)),data.modifiers.unshift(...baseModifiers),super(actor,data),this.attribute=data.attribute??null,typeof data.lore=="boolean"&&(this.lore=data.lore),this.rank=data.rank==="untrained-level"?0:data.rank??null,this.config=config,this.proficient=data.proficient===void 0?this.rank===null||this.rank>0:!!data.proficient,data.filter&&(this.modifiers=this.modifiers.filter(data.filter)),this.data.dc??={domains:[`${this.slug}-dc`]}}get attributeModifier(){return this.actor.isOfType("npc")?this.attribute?createAttributeModifier({actor:this.actor,attribute:this.attribute,domains:this.domains}):null:this.modifiers.find(m=>m.type==="ability"&&m.enabled&&m.ability===this.attribute)??null}get check(){return this.#check??=new StatisticCheck(this,this.data,this.config)}get dc(){return this.#dc??=new StatisticDifficultyClass(this,this.data,this.config)}get mod(){return this.check.mod}get ability(){return foundry.utils.logCompatibilityWarning("`Statistic#ability` is deprecated. Use `Statistic#attribute` instead.",{since:"5.5.0",until:"6.0.0"}),this.attribute}createRollOptions(domains=this.domains,args={}){const{item,extraRollOptions,origin,target}=args,rollOptions=[];return domains.length>0&&rollOptions.push(...super.createRollOptions(domains)),typeof this.rank=="number"&&rollOptions.push(PROFICIENCY_RANK_OPTION[this.rank]),this.data.rollOptions&&rollOptions.push(...this.data.rollOptions),item&&(rollOptions.push(...item.getRollOptions("item")),item.actor&&item.actor.uuid!==this.actor.uuid&&rollOptions.push(...item.actor.getSelfRollOptions("origin")),(item.system.traits?.value??[]).includes("attack")&&rollOptions.push("trait:attack")),origin?rollOptions.push(...origin.getSelfRollOptions("origin")):target&&rollOptions.push(...target.getSelfRollOptions("target")),extraRollOptions&&rollOptions.push(...extraRollOptions),new Set(rollOptions)}withRollOptions(options){const newOptions=foundry.utils.mergeObject(this.config??{},options??{},{inplace:!1});return new Statistic(this.actor,foundry.utils.deepClone(this.data),newOptions)}extend(data){function maybeMergeArrays(arr1,arr2){if(!(!arr1&&!arr2))return[...new Set([arr1??[],arr2??[]].flat())]}__name(maybeMergeArrays,"maybeMergeArrays"),__name2(maybeMergeArrays,"maybeMergeArrays");const result=foundry.utils.mergeObject(foundry.utils.deepClone(this.data),data);result.domains=maybeMergeArrays(this.domains,data.domains),result.modifiers=maybeMergeArrays(this.data.modifiers,data.modifiers),result.rollOptions=maybeMergeArrays(this.data.rollOptions,data.rollOptions),result.check&&this.data.check&&(result.check.domains=maybeMergeArrays(this.data.check.domains,data.check?.domains),result.check.modifiers=maybeMergeArrays(this.data.check.modifiers,data.check?.modifiers)),result.dc&&this.data.dc&&(result.dc.domains=maybeMergeArrays(this.data.dc.domains,data.dc?.domains),result.dc.modifiers=maybeMergeArrays(this.data.dc.modifiers,data.dc?.modifiers));const extended=new Statistic(this.actor,result,this.config);return extended.base=this,extended}roll(args={}){return this.check.roll(args)}getChatData(options={}){const{check,dc}=this.withRollOptions(options),{map1,map2}=options.item?calculateMAPs(options.item,{domains:check?.domains??[],options:check?.createRollOptions(options)??[]}):{map1:-5,map2:-10};return{slug:this.slug,label:this.label,rank:this.rank,check:{mod:check.mod,breakdown:check.breakdown,label:check.label,map1,map2},dc:{value:dc.value,breakdown:dc.breakdown}}}getTraceData(options={}){const{check,dc}=this,valueProp=options.value??"mod",[label,value,totalModifier,breakdown,modifiers]=valueProp==="mod"?[this.label,check.mod,check.mod,check.breakdown,check.modifiers]:[dc.label||this.label,dc.value,dc.value-10,dc.breakdown,dc.modifiers];return{slug:this.slug,label,value,totalModifier,dc:dc.value,breakdown,modifiers:modifiers.map(m=>m.toObject())}}}class StatisticCheck{static{__name(this,"StatisticCheck")}static{__name2(this,"StatisticCheck")}parent;type;label;domains;mod;modifiers;constructor(parent,data,config={}){this.parent=parent,this.type=data.check?.type??"check",data.check=foundry.utils.mergeObject(data.check??{},{type:this.type});const checkDomains=new Set(compact(["check",data.check.domains].flat()));this.type==="attack-roll"?(checkDomains.add("attack"),checkDomains.add("attack-roll"),checkDomains.add(`${this.parent.slug}-attack-roll`)):(checkDomains.add(`${this.parent.slug}-check`),this.type==="flat-check"&&(checkDomains.delete("check"),checkDomains.add("flat-check"))),data.check.domains=Array.from(checkDomains),this.domains=uniq(compact([data.domains,data.check.domains].flat())),this.label=this.#determineLabel(data);const{modifierAdjustments}=parent.actor.synthetics,parentModifiers=parent.modifiers.map(modifier=>{const clone=modifier.clone();return clone.adjustments.push(...extractModifierAdjustments(modifierAdjustments,data.check?.domains??[],clone.slug)),clone}),checkOnlyModifiers=[data.check?.modifiers??[],extractModifiers(parent.actor.synthetics,data.check?.domains??[])].flat().map(modifier=>(modifier.adjustments.push(...extractModifierAdjustments(parent.actor.synthetics.modifierAdjustments,parent.domains,this.parent.slug)),modifier)),rollOptions=parent.createRollOptions(this.domains,config);this.modifiers=[...parentModifiers,...checkOnlyModifiers.map(modifier=>modifier.clone({test:rollOptions}))],this.type==="flat-check"&&this.modifiers.length>0&&(console.error(ErrorPF2e("Flat checks cannot have modifiers.").message),this.modifiers=[]),this.mod=new StatisticModifier(this.label,this.modifiers,rollOptions).totalModifier}get actor(){return this.parent.actor}#determineLabel(data){const parentLabel=this.parent.label;if(data.check?.label)return game.i18n.localize(data.check?.label);if(this.domains.includes("spell-attack-roll"))return game.i18n.format("PF2E.SpellAttackWithTradition",{tradition:parentLabel});switch(this.type){case"skill-check":return game.i18n.format("PF2E.SkillCheckWithName",{skillName:parentLabel});case"saving-throw":return game.i18n.format("PF2E.SavingThrowWithName",{saveName:parentLabel});case"perception-check":return game.i18n.format("PF2E.PerceptionCheck");default:return parentLabel}}createRollOptions(args={}){return this.parent.createRollOptions(this.domains,args)}async roll(args={}){args.dc=typeof args.dc=="number"?{value:Math.trunc(args.dc)||0}:args.dc??null;const{rollMode,skipDialog}=(()=>{if(isObject(args)){const event2=args.event?.originalEvent??args.event;if(event2 instanceof MouseEvent){const{rollMode:rollMode2,skipDialog:skipDialog2}=args;return foundry.utils.mergeObject({rollMode:rollMode2,skipDialog:skipDialog2},eventToRollParams(event2,{type:"check"}))}}return args})(),{domains}=this,token=args.token??this.actor.getActiveTokens(!1,!0).shift(),item=args.item??null,{origin}=args,targetToken=origin?null:(args.target?.getActiveTokens()??Array.from(game.user.targets)).find(t=>t.actor?.isOfType("army","creature","hazard"))??null,rollContext=await(()=>{const isValidAttacker=targetToken?.actor?.isOfType("army")?this.actor.isOfType("army"):this.actor.isOfType("creature","hazard"),isTargetedCheck=this.domains.includes("spell-attack-roll")&&item?.isOfType("spell")||!["flat-check","saving-throw"].includes(this.type)&&!!(args.dc?.slug||"statistic"in(args.dc??{}))&&(!item||item.isOfType("action","campaignFeature","feat","weapon"));return isValidAttacker&&isTargetedCheck?this.actor.getCheckContext({item:item?.isOfType("action","melee","spell","weapon")?item:null,domains,statistic:this,target:targetToken,defense:args.dc?.slug??"armor",melee:args.melee,options:new Set(args.extraRollOptions??[])}):null})(),selfActor=rollContext?.self.actor??this.actor,targetActor=origin?null:rollContext?.target?.actor??args.target??null,dc=typeof args.dc?.value=="number"?args.dc:rollContext?.dc??null,extraModifiers=this.type==="flat-check"?[]:compact([args.modifiers,rollContext?.self.modifiers].flat()),extraRollOptions=[...args.extraRollOptions??[],...rollContext?.options??[],`check:statistic:${this.parent.slug}`,`check:type:${this.type.replace(/-check$/,"")}`];this.parent.base&&extraRollOptions.push(`check:statistic:base:${this.parent.base.slug}`);const options=this.createRollOptions({...args,origin,target:targetActor,extraRollOptions}),notes=[...extractNotes(selfActor.synthetics.rollNotes,domains),...args.extraRollNotes??[]];for(const rule of selfActor.rules.filter(r=>!r.ignored))rule.beforeRoll?.(domains,options);const dosAdjustments=dc?extractDegreeOfSuccessAdjustments(selfActor.synthetics,domains):[];if((options.has("incapacitation")||options.has("item:trait:incapacitation"))&&dc){const effectLevel=item?.isOfType("spell")?2*item.rank:item?.isOfType("physical")?item.level:origin?.level??selfActor.level,amount=this.type==="saving-throw"&&selfActor.level>effectLevel?DEGREE_ADJUSTMENT_AMOUNTS.INCREASE:targetActor&&targetActor.level>effectLevel&&["attack-roll","spell-attack-roll","skill-check"].includes(this.type)?DEGREE_ADJUSTMENT_AMOUNTS.LOWER:null;amount&&dosAdjustments.push({adjustments:{all:{label:"PF2E.TraitIncapacitation",amount}}})}const mapIncreases=Math.clamped((args.attackNumber??1)-1,0,2);if(mapIncreases!==0)if(!item)console.warn("Missing item argument while calculating MAP during check");else{const maps=calculateMAPs(item,{domains,options}),penalty=maps[`map${mapIncreases}`];extraModifiers.push(new ModifierPF2e(maps.label,penalty,"untyped"))}const traits=args.traits?.map(t=>typeof t=="string"?t:t.name).filter(t=>t in CONFIG.PF2E.actionTraits)??[];for(const trait of traits)options.add(trait);if(args.action){options.add(`self:action:slug:${sluggify(args.action)}`);for(const trait of traits)options.add(`self:action:trait:${trait}`)}const context={actor:selfActor,token,item,type:this.type,identifier:args.identifier,domains,target:rollContext?.target??null,dc,notes,options,action:args.action,damaging:args.damaging,rollMode,skipDialog,rollTwice:args.rollTwice||extractRollTwice(selfActor.synthetics.rollTwice,domains,options),substitutions:extractRollSubstitutions(selfActor.synthetics.rollSubstitutions,domains,options),dosAdjustments,traits,title:args.title?.trim()||args.label?.trim()||this.label,createMessage:args.createMessage??!0};typeof args.attackNumber=="number"&&(context.mapIncreases=mapIncreases,context.options?.add(`map:increases:${mapIncreases}`));const check=new CheckModifier(this.parent.slug,{modifiers:this.modifiers},extraModifiers),roll=await CheckPF2e.roll(check,context,null,args.callback);if(roll)for(const rule of selfActor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context,domains,rollOptions:options});return roll}get breakdown(){return this.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", ")}}class StatisticDifficultyClass{static{__name(this,"StatisticDifficultyClass")}static{__name2(this,"StatisticDifficultyClass")}parent;domains;label;modifiers;options;constructor(parent,data,options={}){this.parent=parent,this.domains=uniq(compact([data.domains,data.dc?.domains].flat())),this.label=data.dc?.label,this.options=parent.createRollOptions(this.domains,options);const{modifierAdjustments}=parent.actor.synthetics,parentModifiers=parent.modifiers.map(modifier=>{const clone=modifier.clone();return clone.adjustments.push(...extractModifierAdjustments(modifierAdjustments,data.dc?.domains??[],clone.slug)),clone}),dcOnlyModifiers=[data.dc?.modifiers??[],extractModifiers(parent.actor.synthetics,data.dc?.domains??[])].flat().map(modifier=>(modifier.adjustments.push(...extractModifierAdjustments(parent.actor.synthetics.modifierAdjustments,parent.domains,this.parent.slug)),modifier));this.modifiers=[...new StatisticModifier("",[...parentModifiers,...dcOnlyModifiers.map(m=>m.clone())],this.options).modifiers]}get value(){return 10+new StatisticModifier("",this.modifiers.map(m=>m.clone()),this.options).totalModifier}get breakdown(){const enabledMods=this.modifiers.filter(m=>m.enabled);return[game.i18n.localize("PF2E.DCBase")].concat(enabledMods.map(m=>`${m.label} ${signedInteger(m.modifier)}`)).join(", ")}toString(){return String(this.value)}}class ArmorStatistic extends Statistic{static{__name(this,"ArmorStatistic")}static{__name2(this,"ArmorStatistic")}details;get item(){return this.actor.isOfType("character")?this.actor.wornArmor:null}constructor(actor,data={}){data.rank??=1;const attribute=actor.isOfType("creature")?data.attribute??"dex":null,domains=attribute?["all",`${attribute}-based`]:["all"],fullData={...data,label:"TYPES.Item.armor",slug:"armor",attribute,domains,proficient:data.rank>0,dc:{label:"PF2E.ArmorClassLabel",domains:["ac"],modifiers:[]}};super(actor,fullData),this.details=data.details??"";const dcModifiers=[...this.dc.modifiers,...this.#createBonusesAndPenalties()].map(m=>m.clone());this.dc.modifiers=[...new StatisticModifier("",dcModifiers,this.dc.options).modifiers]}#createBonusesAndPenalties(){const{actor}=this,armor=actor.isOfType("character")?actor.wornArmor:null,armorSlug=armor?.baseType??armor?.slug??sluggify(armor?.name??""),itemBonus=armor?new ModifierPF2e({label:armor.name,type:"item",slug:armorSlug,modifier:armor.acBonus,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","ac"],armorSlug)}):null;return compact([itemBonus,createShoddyPenalty(actor,armor,this.dc.domains),this.#createShieldBonus()])}#createShieldBonus(){const{actor}=this;if(!actor.isOfType("character","npc"))return null;const shieldData=actor.system.attributes.shield,slug="raised-shield";return shieldData.raised&&!shieldData.broken?new ModifierPF2e({label:shieldData.name,slug,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,["all","dex-based","ac"],slug),type:"circumstance",modifier:shieldData.ac}):null}getTraceData(){return{...super.getTraceData({value:"dc"}),details:this.details,breakdown:this.dc.breakdown}}}class HitPointsStatistic extends BaseStatistic{static{__name(this,"HitPointsStatistic")}static{__name2(this,"HitPointsStatistic")}value;max;#baseMax;temp;negativeHealing;unrecoverable;details;constructor(actor,{baseMax=0}={}){const modifiers=actor.isOfType("character")?[createAttributeModifier({actor,attribute:"con",domains:["hp","con-based"]})]:[];super(actor,{slug:"hp",label:"PF2E.HitPointsHeader",domains:actor.isOfType("character","npc")?["con-based","hp"]:["hp"],modifiers}),this.#baseMax=baseMax,this.max=baseMax+new StatisticModifier("",this.modifiers.map(m=>m.clone())).totalModifier,this.value=Math.clamped(actor.system.attributes.hp.value,0,this.max),this.temp=actor.system.attributes.hp.temp,this.negativeHealing=actor.system.attributes.hp.negativeHealing,this.unrecoverable=actor.system.attributes.hp.unrecoverable,this.details=actor.system.attributes.hp.details||""}get breakdown(){return compact([this.#baseMax>0?game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base:this.#baseMax}):null,...this.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`)]).join(", ")}getTraceData(){return{slug:this.slug,label:this.label,value:this.value,max:this.max,temp:this.temp,breakdown:this.breakdown,negativeHealing:this.negativeHealing,unrecoverable:this.unrecoverable,details:this.details,modifiers:this.modifiers.map(m=>m.toObject())}}}const TRICK_MAGIC_SKILLS=["arcana","nature","occultism","religion"],TrickMagicTradition={arcana:"arcane",nature:"primal",occultism:"occult",religion:"divine"},traditionSkills={arcane:"arcana",divine:"religion",occult:"occultism",primal:"nature"};class TrickMagicItemEntry{static{__name(this,"TrickMagicItemEntry")}static{__name2(this,"TrickMagicItemEntry")}id;actor;skill;statistic;attribute;get ability(){return foundry.utils.logCompatibilityWarning("`TrickMagicItemEntry#ability` is deprecated. Use `TrickMagicItemEntry#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}tradition;constructor(actor,skill){if(!actor.isOfType("character"))throw ErrorPF2e("Trick magic entries may only be constructed with PCs");this.actor=actor,this.skill=skill,this.id=`trick-${this.skill}`;const attributes=actor.abilities,{attribute}=["int","wis","cha"].map(attribute2=>({attribute:attribute2,mod:attributes[attribute2].mod})).reduce((highest,next)=>next.mod>highest.mod?next:highest);this.attribute=attribute;const tradition=this.tradition=TrickMagicTradition[skill],selectors=[`${attribute}-based`,"all","spell-attack-dc"],attackSelectors=[`${tradition}-spell-attack`,"spell-attack","spell-attack-roll","attack","attack-roll"],saveSelectors=[`${tradition}-spell-dc`,"spell-dc"],skillRank=actor.skills[skill].rank,trickRank=skillRank===4?2:skillRank===3?1:0;this.statistic=new Statistic(actor,{slug:`trick-${tradition}`,label:CONFIG.PF2E.magicTraditions[tradition],attribute,rank:trickRank||"untrained-level",modifiers:extractModifiers(actor.synthetics,selectors),domains:selectors,check:{type:"attack-roll",modifiers:extractModifiers(actor.synthetics,attackSelectors),domains:attackSelectors},dc:{modifiers:extractModifiers(actor.synthetics,saveSelectors),domains:saveSelectors}})}get name(){return game.i18n.localize("PF2E.TrickMagicItemPopup.Title")}get sort(){return 0}get category(){return"items"}get spells(){return null}get isFlexible(){return!1}get isFocusPool(){return!1}get isInnate(){return!1}get isPrepared(){return!1}get isRitual(){return!1}get isSpontaneous(){return!1}canCast(){return!0}async cast(spell,options={}){const{rollMode,message}=options,castLevel=spell.computeCastRank(spell.rank);if(message!==!1)try{spell.trickMagicEntry=this,await spell.toMessage(void 0,{rollMode,data:{castLevel}})}finally{spell.trickMagicEntry=null}}async getSheetData(){return{id:this.id,name:this.name,statistic:this.statistic.getChatData(),tradition:this.tradition,category:"items",hasCollection:!1,sort:0,levels:[],usesSpellProficiency:!1,spellPrepList:null}}}const CANTRIP_DECK_ID="tLa4bewBhyqzi6Ow",scrollCompendiumIds={1:"RjuupS9xyXDLgyIr",2:"Y7UD64foDbDMV9sx",3:"ZmefGBXGJF3CFDbn",4:"QSQZJ5BC3DeHv153",5:"tjLvRWklAylFhBHQ",6:"4sGIy77COooxhQuC",7:"fomEZZ4MxVVK3uVu",8:"iPki3yuoucnj7bIt",9:"cFHomF3tty8Wi1e5",10:"o1XIHJ4MJyroAHfF"},SPELL_CONSUMABLE_NAME_TEMPLATES={cantripDeck5:"PF2E.Item.Physical.FromSpell.CantripDeck5",scroll:"PF2E.Item.Physical.FromSpell.Scroll",wand:"PF2E.Item.Physical.FromSpell.Wand"},wandCompendiumIds={1:"UJWiN0K3jqVjxvKk",2:"vJZ49cgi8szuQXAD",3:"wrDmWkGxmwzYtfiA",4:"Sn7v9SsbEDMUIwrO",5:"5BF7zMnrPYzyigCs",6:"kiXh4SUWKr166ZeM",7:"nmXPj9zuMRQBNT60",8:"Qs8RgNH6thRPv2jt",9:"Fgv722039TVM5JTc"};function getIdForSpellConsumable(type,heightenedLevel){switch(type){case"cantripDeck5":return CANTRIP_DECK_ID;case"scroll":return scrollCompendiumIds[heightenedLevel]??null;default:return wandCompendiumIds[heightenedLevel]??null}}__name(getIdForSpellConsumable,"getIdForSpellConsumable"),__name2(getIdForSpellConsumable,"getIdForSpellConsumable");function getNameForSpellConsumable(type,spellName,heightenedLevel){const templateId=SPELL_CONSUMABLE_NAME_TEMPLATES[type]||`${type} of {name} (Level {level})`;return game.i18n.format(templateId,{name:spellName,level:heightenedLevel})}__name(getNameForSpellConsumable,"getNameForSpellConsumable"),__name2(getNameForSpellConsumable,"getNameForSpellConsumable");function isSpellConsumable(itemId){return itemId===CANTRIP_DECK_ID||Object.values(scrollCompendiumIds).includes(itemId)||Object.values(wandCompendiumIds).includes(itemId)}__name(isSpellConsumable,"isSpellConsumable"),__name2(isSpellConsumable,"isSpellConsumable");async function createConsumableFromSpell(spell,{type,heightenedLevel=spell.baseRank,mystified=!1}){const pack=game.packs.find(p=>p.collection==="pf2e.equipment-srd"),itemId=getIdForSpellConsumable(type,heightenedLevel),consumable=await pack?.getDocument(itemId??"");if(!(consumable instanceof ConsumablePF2e))throw ErrorPF2e("Failed to retrieve consumable item");const consumableSource={...consumable.toObject(),_id:null},{traits}=consumableSource.system;traits.value=uniq([...traits.value,...spell.traits]),traits.rarity=spell.rarity,traits.value.includes("magical")&&traits.value.some(t=>setHasElement(MAGIC_TRADITIONS,t))&&traits.value.splice(traits.value.indexOf("magical"),1),traits.value.sort(),consumableSource.name=getNameForSpellConsumable(type,spell.name,heightenedLevel);const description=consumableSource.system.description.value;return consumableSource.system.description.value=(()=>{const paragraphElement=document.createElement("p");paragraphElement.append(spell.sourceId?`@UUID[${spell.sourceId}]{${spell.name}}`:spell.description);const containerElement=document.createElement("div"),hrElement=document.createElement("hr");return containerElement.append(paragraphElement,hrElement),hrElement.insertAdjacentHTML("afterend",description),containerElement.innerHTML})(),type!=="cantripDeck5"&&(consumableSource.system.spell=spell.clone({"system.location.heightenedLevel":heightenedLevel}).toObject()),mystified&&(consumableSource.system.identification.status="unidentified"),consumableSource}__name(createConsumableFromSpell,"createConsumableFromSpell"),__name2(createConsumableFromSpell,"createConsumableFromSpell");function calculateTrickMagicItemCheckDC(item,options={pwol:!1}){const level=Number(item.level),saveDC=calculateDC(level,options),traditions=item.system.spell?.system.traits.traditions??[],skills=[...item.system.traits.value,...traditions].filter(t=>setHasElement(MAGIC_TRADITIONS,t)).map(tradition=>[traditionSkills[tradition],saveDC]);return Object.fromEntries(skills)}__name(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC"),__name2(calculateTrickMagicItemCheckDC,"calculateTrickMagicItemCheckDC");async function preImportJSON(document2,json2){const source=JSON.parse(json2);if(!isObject(source)||("data"in source&&("items"in source?ActorPF2e.migrateData(source):ItemPF2e.migrateData(source)),!isObject(source.system)))return null;const sourceSchemaVersion=Number(source.system?._migration?.version)||0,worldSchemaVersion=MigrationRunnerBase.LATEST_SCHEMA_VERSION;if(foundry.utils.isNewerVersion(sourceSchemaVersion,worldSchemaVersion))return ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.CantImportTooHighVersion",{sourceName:game.i18n.localize("DOCUMENT.Actor"),sourceSchemaVersion,worldSchemaVersion})),null;const newDoc=new document2.constructor(source,{parent:document2.parent}),migrations=MigrationList.constructFromVersion(newDoc.schemaVersion);return await MigrationRunner.ensureSchemaVersion(newDoc,migrations),JSON.stringify(newDoc.toObject())}__name(preImportJSON,"preImportJSON"),__name2(preImportJSON,"preImportJSON");function combatantAndTokenDoc(document2){return document2 instanceof CombatantPF2e?{combatant:document2,tokenDoc:document2.token}:{combatant:document2.combatant,tokenDoc:document2}}__name(combatantAndTokenDoc,"combatantAndTokenDoc"),__name2(combatantAndTokenDoc,"combatantAndTokenDoc");async function processGrantDeletions(item,pendingItems){const{actor}=item,granter=actor.items.get(item.flags.pf2e.grantedBy?.id??""),parentGrant=Object.values(granter?.flags.pf2e.itemGrants??{}).find(g=>g.id===item.id),grants=Object.values(item.flags.pf2e.itemGrants);if(granter&&parentGrant?.onDelete==="restrict"&&!pendingItems.includes(granter)){ui.notifications.warn(game.i18n.format("PF2E.Item.RemovalPrevented",{item:item.name,preventer:granter.name})),pendingItems.splice(pendingItems.indexOf(item),1);return}for(const grant of grants){const grantee=actor.items.get(grant.id);if(grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="restrict"&&!pendingItems.includes(grantee)){ui.notifications.warn(game.i18n.format("PF2E.Item.RemovalPrevented",{item:item.name,preventer:grantee.name})),pendingItems.splice(pendingItems.indexOf(item),1);return}}granter&&parentGrant?.onDelete==="cascade"&&!pendingItems.includes(granter)&&(pendingItems.push(granter),await processGrantDeletions(granter,pendingItems));for(const grant of grants){const grantee=actor.items.get(grant.id);grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="cascade"&&!pendingItems.includes(grantee)&&(pendingItems.push(grantee),await processGrantDeletions(grantee,pendingItems))}const[key]=Object.entries(granter?.flags.pf2e.itemGrants??{}).find(([,g])=>g===parentGrant)??[null];granter&&key&&!pendingItems.includes(granter)&&await granter.update({[`flags.pf2e.itemGrants.-=${key}`]:null},{render:!1});for(const grant of grants){const grantee=actor.items.get(grant.id);grantee?.flags.pf2e.grantedBy?.id===item.id&&grantee.flags.pf2e.grantedBy.onDelete==="detach"&&!pendingItems.includes(grantee)&&await grantee.update({"flags.pf2e.-=grantedBy":null},{render:!1})}}__name(processGrantDeletions,"processGrantDeletions"),__name2(processGrantDeletions,"processGrantDeletions");class ItemPF2e extends Item{static{__name(this,"ItemPF2e")}static{__name2(this,"ItemPF2e")}static getDefaultArtwork(itemData){return{img:`systems/pf2e/icons/default-icons/${itemData.type}.svg`}}get slug(){return this.system.slug}get sourceId(){return this.flags.core?.sourceId??null}get schemaVersion(){return Number(this.system._migration?.version??this.system.schema?.version)||null}get description(){return this.system.description.value.trim()}get grantedBy(){return this.actor?.items.get(this.flags.pf2e.grantedBy?.id??"")??null}get inMemoryOnly(){return!this.collection.has(this.id)}static fromDropData(data,options){if("uuid"in data&&UUIDUtils.isItemUUID(data.uuid)){const item=fromUuidSync(data.uuid);item instanceof ItemPF2e&&item.parent&&!item.sourceId&&(item._source.flags=foundry.utils.mergeObject(item._source.flags,{core:{sourceId:item.uuid}}),item.flags=foundry.utils.mergeObject(item.flags,{core:{sourceId:item.uuid}}))}return super.fromDropData(data,options)}isOfType(...types){return types.some(t=>t==="physical"?setHasElement(PHYSICAL_ITEM_TYPES,this.type):this.type===t)}async delete(context={}){return this.actor?(await this.actor.deleteEmbeddedDocuments("Item",[this.id],context),this):super.delete(context)}getRollOptions(prefix=this.type){if(prefix.length===0)throw ErrorPF2e("`prefix` must be at least one character long");const slug=this.slug??sluggify(this.name),{value:traits=[],otherTags}=this.system.traits,traitOptions=(()=>{const damageType=Object.keys(CONFIG.PF2E.damageTypes).join("|"),diceOrNumber=/-(?:[0-9]*d)?[0-9]+(?:-min)?$/,versatile=new RegExp(`-(?:b|p|s|${damageType})$`),deannotated=traits.filter(t=>diceOrNumber.test(t)||versatile.test(t)).map(t=>t.replace(diceOrNumber,"").replace(versatile,""));return[traits,deannotated].flat().map(t=>`trait:${t}`)})(),options=[`${prefix}:id:${this.id}`,`${prefix}:${slug}`,`${prefix}:slug:${slug}`,...traitOptions.map(t=>`${prefix}:${t}`),...otherTags.map(t=>`${prefix}:tag:${t}`)];(this.isOfType("spell")||traits.some(t=>["magical",...MAGIC_TRADITIONS].includes(t)))&&options.push(`${prefix}:magical`);const level=this.isOfType("spell")?this.rank:this.system.level?.value??null;typeof level=="number"&&options.push(`${prefix}:level:${level}`);const itemType=this.isOfType("feat")&&this.isFeature?"feature":this.type;return prefix!==itemType&&options.unshift(`${prefix}:type:${itemType}`),options}getRollData(){return{...this.actor?.getRollData()??{actor:null},item:this}}async toMessage(event2,options={}){if(!this.actor)throw ErrorPF2e(`Cannot create message for unowned item ${this.name}`);const template=`systems/pf2e/templates/chat/${sluggify(this.type)}-card.hbs`,token=this.actor.token,nearestItem=htmlClosest(event2?.target,".item"),rollOptions=options.data??{...nearestItem?.dataset??{}},templateData={actor:this.actor,tokenId:token?`${token.parent?.id}.${token.id}`:null,item:this,data:await this.getChatData(void 0,rollOptions)},originalEvent=event2 instanceof MouseEvent?event2:event2?.originalEvent,rollMode=options.rollMode??eventToRollMode(originalEvent),chatData=ChatMessagePF2e.applyRollMode({type:CONST.CHAT_MESSAGE_TYPES.OTHER,speaker:ChatMessagePF2e.getSpeaker({actor:this.actor,token:this.actor.getActiveTokens(!1,!0).at(0)}),content:await renderTemplate(template,templateData),flags:{pf2e:{origin:this.getOriginData()}}},rollMode);return options.create??!0?ChatMessagePF2e.create(chatData,{rollMode,renderSheet:!1}):new ChatMessagePF2e(chatData,{rollMode})}async toChat(event2){return this.toMessage(event2,{create:!0})}_initialize(options){this.rules=[],super._initialize(options)}prepareData(){this.parent&&!this.parent.flags?.pf2e||super.prepareData()}prepareBaseData(){super.prepareBaseData();const{flags}=this;flags.pf2e=foundry.utils.mergeObject(flags.pf2e??{},{rulesSelections:{}}),this.system.slug||=null,isObject(flags.pf2e.grantedBy)&&(flags.pf2e.grantedBy.onDelete??=this.isOfType("physical")?"detach":"cascade");const grants=flags.pf2e.itemGrants??={};for(const grant of Object.values(grants))isObject(grant)&&(grant.onDelete??="detach")}prepareRuleElements(options={}){if(!this.actor)throw ErrorPF2e("Rule elements may only be prepared from embedded items");return this.rules=this.actor.canHostRuleElements?RuleElements.fromOwnedItem({...options,parent:this}):[]}async refreshFromCompendium(options={name:!0,notify:!0}){if(!this.isOwned)throw ErrorPF2e("This utility may only be used on owned items");if(!this.sourceId?.startsWith("Compendium."))throw ErrorPF2e(`Item "${this.name}" has no compendium source.`);options.name??=!0,options.notify??=!0;const currentSource=this.toObject();if(currentSource.system.rules.some(r=>typeof r.key=="string"&&["ChoiceSet","GrantItem"].includes(r.key))){ui.notifications.warn("PF2E.Item.RefreshFromCompendium.Tooltip.Disabled",{localize:!0});return}const latestSource=(await fromUuid(this.sourceId))?.toObject();if(latestSource){if(latestSource.type!==this.type){ui.notifications.error(`The compendium source for "${this.name}" is of a different type than what is present on this actor.`);return}}else{ui.notifications.warn(game.i18n.format("PF2E.Item.RefreshFromCompendium.SourceNotFound",{item:this.name,sourceId:this.sourceId}));return}const updates={name:options.name?latestSource.name:currentSource.name,img:latestSource.img,system:foundry.utils.deepClone(latestSource.system)};if(updates.system.level&¤tSource.type==="feat"&&(updates.system.level={value:updates.system.level.value,taken:currentSource.system.level.taken}),isPhysicalData(currentSource)){if(foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.containerId":currentSource.system.containerId,"system.equipped":currentSource.system.equipped,"system.material":currentSource.system.material,"system.quantity":currentSource.system.quantity,"system.size":currentSource.system.size})),itemIsOfType(currentSource,"armor","shield","weapon")&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.runes":currentSource.system.runes})),currentSource.type==="consumable"&¤tSource.system.spell?.system?.traits&&tupleHasValue(["scroll","wand"],currentSource.system.category)&&latestSource.type==="consumable"&&!latestSource.system.spell){const spellSourceId=currentSource.system.spell.flags.core?.sourceId??"",refreshedSpell=await fromUuid(currentSource.system.spell.flags.core?.sourceId??"");if(refreshedSpell instanceof ItemPF2e&&refreshedSpell.isOfType("spell")){const spellConsumableData=await createConsumableFromSpell(refreshedSpell,{type:currentSource.system.category,heightenedLevel:currentSource.system.spell.system.location.heightenedLevel});foundry.utils.mergeObject(updates,{name:spellConsumableData.name,system:{spell:spellConsumableData.system.spell}})}else{ui.notifications.warn(game.i18n.format("PF2E.Item.RefreshFromCompendium.SourceNotFound",{item:currentSource.system.spell.name,sourceId:spellSourceId}));return}}}else itemIsOfType(currentSource,"campaignFeature","feat","spell")&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.location":currentSource.system.location}));currentSource.type==="feat"&¤tSource.system.level.taken&&foundry.utils.mergeObject(updates,foundry.utils.expandObject({"system.level.taken":currentSource.system.level.taken})),await this.update(updates,{diff:!1,recursive:!1}),options.notify&&ui.notifications.info(`Item "${this.name}" has been refreshed.`)}getOriginData(){return{actor:this.actor?.uuid,uuid:this.uuid,type:this.type}}async processChatData(htmlOptions={},data){if(data.properties=data.properties?.filter(property=>property!==null)??[],isItemSystemData(data)){const chatData=foundry.utils.duplicate(data);return htmlOptions.rollData=foundry.utils.mergeObject(this.getRollData(),htmlOptions.rollData??{}),chatData.description.value=await TextEditor.enrichHTML(chatData.description.value,{...htmlOptions,async:!0}),chatData}return data}async getChatData(htmlOptions={},_rollOptions={}){if(!this.actor)throw ErrorPF2e(`Cannot retrieve chat data for unowned item ${this.name}`);const systemData={...this.system,traits:this.traitChatData()};return this.processChatData(htmlOptions,foundry.utils.deepClone(systemData))}traitChatData(dictionary={},traits=this.system.traits.value??[]){return traits.map(trait=>{const label=game.i18n.localize(dictionary[trait]??trait),traitDescriptions2=CONFIG.PF2E.traitsDescriptions;return{value:trait,label,description:traitDescriptions2[trait]}}).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang))}static async createDialog(data={},context={}){const omittedTypes=["condition","spellcastingEntry","lore"];omittedTypes.push("affliction","book"),game.settings.get("pf2e","campaignType")!=="kingmaker"&&omittedTypes.push("campaignFeature");const original=game.system.documentTypes.Item;try{return game.system.documentTypes.Item=difference(original,omittedTypes),super.createDialog(data,{...context,classes:[...context.classes??[],"dialog-item-create"]})}finally{game.system.documentTypes.Item=original}}async importFromJSON(json2){const processed=await preImportJSON(this,json2);return processed?super.importFromJSON(processed):this}toDragData(){return{...super.toDragData(),itemType:this.type}}static async createDocuments(data=[],context={}){const sources=data.map(d=>d instanceof ItemPF2e?d.toObject():d);for(const source of[...sources]){if(source.effects=[],!Object.keys(source).some(k=>k.startsWith("flags")||k.startsWith("system"))){source.system={_migration:{version:MigrationRunnerBase.LATEST_SCHEMA_VERSION}};continue}const item=new CONFIG.Item.documentClass(source);await MigrationRunner.ensureSchemaVersion(item,MigrationList.constructFromVersion(item.schemaVersion)),data.splice(data.indexOf(source),1,item.toObject())}const actor=context.parent;if(!actor)return super.createDocuments(sources,context);if(sources.some(s=>!actor.checkItemValidity(s)))return[];const effectSources=sources.filter(s=>["affliction","condition","effect"].includes(s.type));for(const source of effectSources){const effect=new CONFIG.PF2E.Item.documentClasses[source.type](foundry.utils.deepClone(source),{parent:actor}),isUnaffected=effect.isOfType("condition")&&!actor.isAffectedBy(effect),isImmune=actor.isImmuneTo(effect);if((isUnaffected||isImmune)&&(sources.splice(sources.indexOf(source),1),!(effect.isOfType("effect")&&effect.fromAura))){const locKey=isUnaffected?"PF2E.Damage.IWR.ActorIsUnaffected":"PF2E.Damage.IWR.ActorIsImmune",message=game.i18n.format(locKey,{actor:actor.name,effect:effect.name});ui.notifications.info(message)}}const preCreateDeletions=["ancestry","background","class","heritage","deity"].filter(type=>sources.some(s=>s.type===type)).flatMap(type=>actor.itemTypes[type]);if(preCreateDeletions.length){const idsToDelete=preCreateDeletions.map(i=>i.id);await actor.deleteEmbeddedDocuments("Item",idsToDelete,{render:!1})}const items=await(async()=>{async function getSimpleGrants(item){const granted=await item.createGrantedItems?.({size:context.parent?.size})??[];if(!granted.length)return[];const reparented=granted.map(i=>i.parent?i:new CONFIG.Item.documentClass(i._source,{parent:actor}));return[...reparented,...(await Promise.all(reparented.map(getSimpleGrants))).flat()]}__name(getSimpleGrants,"getSimpleGrants"),__name2(getSimpleGrants,"getSimpleGrants");const items2=sources.map(source=>(context.keepId||context.keepEmbeddedIds||(source._id=foundry.utils.randomID()),new CONFIG.Item.documentClass(source,{parent:actor})));for(const item of[...items2]){const grants=await getSimpleGrants(item);grants.length&&(context.keepId=!0,items2.push(...grants))}return items2})(),outputSources=items.map(i=>i._source);for(const item of items){item.prepareActorData?.();const itemSource=item._source,rules=item.prepareRuleElements({suppressWarnings:!0});for(const rule of rules){const ruleSource=itemSource.system.rules[rules.indexOf(rule)];await rule.preCreate?.({itemSource,ruleSource,pendingItems:outputSources,tempItems:items,context})}}if(outputSources.some(i=>i.type==="class")){const classFeatures=outputSources.filter(i=>i.type==="feat"&&typeof i.system?.level?.value=="number"&&i.system.category==="classfeature"&&!i.flags?.pf2e?.grantedBy);for(const feature of classFeatures)feature.sort=classFeatures.indexOf(feature)*100*(feature.system.level?.value??1)}const nonKits=outputSources.filter(source=>source.type!=="kit");return super.createDocuments(nonKits,context)}static async deleteDocuments(ids=[],context={}){ids=Array.from(new Set(ids));const actor=context.parent;if(actor){const items=ids.flatMap(id=>actor.items.get(id)??[]),containers=items.filter(i=>i.isOfType("backpack"));for(const container of containers)await container.ejectContents();for(const item of[...items]){for(const rule of item.rules)await rule.preDelete?.({pendingItems:items,context});await processGrantDeletions(item,items)}ids=Array.from(new Set(items.map(i=>i.id))).filter(id=>actor.items.has(id))}return super.deleteDocuments(ids,context)}async _preCreate(data,options,user){if(this._source.system.traits.value?.sort(),this.actor?.isOfType("character")&&this.isOfType("ancestry","background","class","feat","heritage")){const hpMaxDifference=this.actor.clone({items:[...this.actor.items.toObject(),data]}).hitPoints.max-this.actor.hitPoints.max;if(hpMaxDifference!==0){const newHitPoints=this.actor.hitPoints.value+hpMaxDifference;await this.actor.update({"system.attributes.hp.value":newHitPoints},{render:!1,allowHPOverage:!0})}}return this._source.system.rules=this._source.system.rules.filter(r=>!r.removeUponCreate),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(changed.system?.description?.value===null&&(changed.system.description.value=""),changed.system?.level&&"value"in changed.system.level&&(changed.system.level.value=Math.max(0,Math.trunc(Number(changed.system.level.value)||0))),typeof changed.system?.slug=="string"&&(changed.system.slug=sluggify(changed.system.slug)||null),changed.system?.traits&&(Array.isArray(changed.system.traits.value)&&changed.system.traits.value.sort(),Array.isArray(changed.system.traits.otherTags)&&(changed.system.traits.otherTags=changed.system.traits.otherTags.map(t=>sluggify(t)).sort())),this.actor?.isOfType("character")&&this.isOfType("ancestry","background","class","feat","heritage")){const actorClone=this.actor.clone();actorClone.items.get(this.id,{strict:!0}).updateSource(changed,options),actorClone.reset();const hpMaxDifference=actorClone.hitPoints.max-this.actor.hitPoints.max;if(hpMaxDifference!==0){const newHitPoints=this.actor.hitPoints.value+hpMaxDifference;await this.actor.update({"system.attributes.hp.value":newHitPoints},{render:!1,allowHPOverage:!0})}}for(const rule of this.rules)await rule.preUpdate?.(changed);return super._preUpdate(changed,options,user)}_onCreate(data,options,userId){if(super._onCreate(data,options,userId),!(this.actor&&game.user.id===userId))return;this.actor.reset();const actorUpdates={};for(const rule of this.rules)rule.onCreate?.(actorUpdates);const updateKeys=Object.keys(actorUpdates);updateKeys.length>0&&!updateKeys.every(k=>k==="_id")&&this.actor.update(actorUpdates)}_onUpdate(data,options,userId){super._onUpdate(data,options,userId),game.ready&&game.items.get(this.id)===this&&ui.items.render()}_onDelete(options,userId){if(super._onDelete(options,userId),!(this.actor&&game.user.id===userId)||!(this.actor.isOfType("creature")&&this.canUserModify(game.user,"update")))return;const actorUpdates={};for(const rule of this.rules)rule.onDelete?.(actorUpdates);if(this.actor.isOfType("npc")&&["action","consumable"].includes(this.type)){const slug=this.slug??sluggify(this.name);if(this.actor.isToken){const promises=[];for(const item of this.actor.itemTypes.melee){const attackEffects=item.system.attackEffects.value;if(attackEffects.includes(slug)){const updatedEffects=attackEffects.filter(effect=>effect!==slug);promises.push(item.update({"system.attackEffects.value":updatedEffects}))}}promises.length>0&&Promise.allSettled(promises)}else{const itemUpdates=[];for(const attack of this.actor.itemTypes.melee){const attackEffects=attack.system.attackEffects.value;if(attackEffects.includes(slug)){const updatedEffects=attackEffects.filter(effect=>effect!==slug);itemUpdates.push({_id:attack.id,system:{attackEffects:{value:updatedEffects}}})}}itemUpdates.length>0&&foundry.utils.mergeObject(actorUpdates,{items:itemUpdates})}}const updateKeys=Object.keys(actorUpdates);updateKeys.length>0&&!updateKeys.every(k=>k==="_id")&&this.actor.update(actorUpdates)}}const ItemProxyPF2e=new Proxy(ItemPF2e,{construct(_target,args){const type=args[0]?.type==="armor"&&args[0].system?.category==="shield"?"shield":args[0]?.type,ItemClass=CONFIG.PF2E.Item.documentClasses[type]??ItemPF2e;return new ItemClass(...args)}}),DURATION_UNITS={rounds:6,minutes:60,hours:3600,days:86400};function calculateRemainingDuration(effect,durationData){if(durationData.unit==="encounter"){const isExpired=effect.system.expired;return{expired:!!isExpired,remaining:isExpired?0:1/0}}else if(durationData.unit==="unlimited"||!("start"in effect.system))return{expired:!1,remaining:1/0};const start=effect.system.start.value,{combatant}=game.combat??{},{unit,expiry}=durationData,duration=durationData.value*(DURATION_UNITS[durationData.unit]??0),addend=!combatant&&duration===0&&unit==="rounds"&&["turn-end","round-end"].includes(expiry??"")?1:0,remaining=start+duration+addend-game.time.worldTime,result={remaining,expired:remaining<=0};if(remaining===0&&combatant?.actor){const startInitiative=effect.system.start.initiative??0,currentInitiative=combatant.initiative??0,fightyActor=effect.actor?.isOfType("familiar")?effect.actor.master??effect.actor:effect.actor,atTurnStart=__name2(()=>startInitiative===currentInitiative&&combatant.actor===(effect.origin??fightyActor),"atTurnStart");result.expired=expiry==="turn-start"?atTurnStart():expiry==="turn-end"?currentInitiativestart:!1}return result}__name(calculateRemainingDuration,"calculateRemainingDuration"),__name2(calculateRemainingDuration,"calculateRemainingDuration");class AbstractEffectPF2e extends ItemPF2e{static{__name(this,"AbstractEffectPF2e")}static{__name2(this,"AbstractEffectPF2e")}get origin(){const originUUID=this.system.context?.origin.actor;if(!originUUID||originUUID===this.actor?.uuid)return this.actor;if(originUUID.startsWith("Scene.")){const tokenUUID=originUUID.replace(/\.Actor\..+$/,""),tokenDoc=fromUuidSync(tokenUUID);if(!(tokenDoc instanceof TokenDocumentPF2e))return null;const descriptor=Object.getOwnPropertyDescriptor(tokenDoc,"delta");return descriptor?.value instanceof ActorDelta?descriptor.value.syntheticActor??null:null}const actor=fromUuidSync(originUUID);return actor instanceof ActorPF2e?actor:null}get isIdentified(){return!0}get isLocked(){return!1}get fromSpell(){return this.system.fromSpell}get totalDuration(){const{duration}=this.system;return["unlimited","encounter"].includes(duration.unit)?1/0:duration.value*(DURATION_UNITS[duration.unit]??0)}get remainingDuration(){return calculateRemainingDuration(this,this.system.duration)}getRollOptions(prefix=this.type){const{origin}=this,originRollOptions=!!origin?.flags?.pf2e?.rollOptions?origin.getSelfRollOptions("origin").map(o=>`${prefix}:${o}`)??[]:[],{badge}=this,itemOrigin=this.grantedBy?.getRollOptions(`${prefix}:granter`)??[];return[...super.getRollOptions(prefix),...itemOrigin,...Object.entries({[`badge:type:${badge?.type}`]:!!badge,[`badge:value:${badge?.value}`]:!!badge,"from-spell":this.fromSpell}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`),...originRollOptions]}prepareBaseData(){super.prepareBaseData();const slug=this.slug??sluggify(this.name);this.rollOptionSlug=slug.replace(/^(?:[a-z]+-)?(?:effect|stance)-/,""),this.system.fromSpell??=!1}prepareActorData(){const actor=this.actor;if(!actor)throw ErrorPF2e("prepareActorData called from unembedded item");actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}`]=!0;const badge=this.badge;if(typeof badge?.value=="number"){const values=actor.items.filter(i=>i instanceof AbstractEffectPF2e&&i.rollOptionSlug===this.rollOptionSlug).map(effect=>effect.badge?.value).filter(value=>typeof value=="number");badge.value>=Math.max(...values)&&(actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}:${badge.value}`]=!0)}}_preCreate(data,options,user){return data.system.fromSpell??=(()=>{if((this.slug??sluggify(this.name)).startsWith("spell-effect-"))return!0;const originItem=fromUuidSync(this.system.context?.origin.item??"");return originItem instanceof ItemPF2e&&(originItem.isOfType("spell")||originItem.isOfType("affliction","condition","effect")&&originItem.fromSpell)})(),super._preCreate(data,options,user)}_onCreate(data,options,userId){super._onCreate(data,options,userId),this.handleChange({create:this})}_onDelete(options,userId){super._onDelete(options,userId),this.handleChange({delete:{name:this._source.name}})}handleChange(change){const skipFloatyText=this.isOfType("condition")&&!game.user.isGM&&!this.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition"),auraNotInCombat=this.flags.pf2e.aura&&!game.combat?.started,identified=game.user.isGM||this.isIdentified;if(!(skipFloatyText||!identified||auraNotInCombat)){if(this.isLocked||this.actor?.getActiveTokens().shift()?.showFloatyText(change),this.isOfType("condition"))for(const token of this.actor?.getActiveTokens()??[])token._onApplyStatusEffect(this.rollOptionSlug,!1);game.pf2e.StatusEffects.refresh()}}}var define_CONDITION_SOURCES_default=[{_id:"1wQY3JYyhMYeeV2G",img:"systems/pf2e/icons/conditions/observed.webp",name:"Observed",system:{description:{value:"Anything in plain view is observed by you. If a creature takes measures to avoid detection, such as by using Stealth to @UUID[Compendium.pf2e.actionspf2e.Item.XMcnh4cSI32tljXa]{Hide}, it can become @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} or @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} instead of observed. If you have another precise sense besides sight, you might be able to observe a creature or object using that sense instead. You can observe a creature with only your precise senses. When @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seeking} a creature using only imprecise senses, it remains hidden, rather than observed.
"},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"observed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G"}},effects:[]},{_id:"3uh1r86TzbQvosxv",img:"systems/pf2e/icons/conditions/doomed.webp",name:"Doomed",system:{description:{value:`Your soul has been gripped by a powerful force that calls you closer to death. Doomed always includes a value. The @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} value at which you die is reduced by your doomed value. If your maximum dying value is reduced to 0, you instantly die. When you die, you're no longer doomed.
+Your doomed value decreases by 1 each time you get a full night's rest.
`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"doomed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.3uh1r86TzbQvosxv"}},effects:[]},{_id:"4D2KBtexWXa6oUMR",img:"systems/pf2e/icons/conditions/drained.webp",name:"Drained",system:{description:{value:`Your health and vitality have been depleted as you've lost blood, life force, or some other essence. Drained always includes a value. You take a status penalty equal to your drained value on Constitution-based checks, such as Fortitude saves. You also lose a number of Hit Points equal to your level (minimum 1) times the drained value, and your maximum Hit Points are reduced by the same amount. For example, if you become drained 3 and you're a 3rd-level character, you lose 9 Hit Points and reduce your maximum Hit Points by 9. Losing these Hit Points doesn't count as taking damage.
+Each time you get a full night's rest, your drained value decreases by 1. This increases your maximum Hit Points, but you don't immediately recover the lost Hit Points.
`},duration:{value:0},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"con-based",slug:"drained",type:"status",value:"-1 * @item.badge.value"},{key:"FlatModifier",selector:"hp",slug:"drained",type:"status",value:"min(-1 * @actor.level,-1) * @item.badge.value"},{key:"LoseHitPoints",reevaluateOnUpdate:!0,value:"max(1,@actor.level) * @item.badge.value"}],value:{isValued:!0,value:1},slug:"drained",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.4D2KBtexWXa6oUMR"}},effects:[]},{_id:"6dNUvdb1dhToNDj3",img:"systems/pf2e/icons/conditions/broken.webp",name:"Broken",system:{description:{value:`Broken is a condition that affects only objects. An object is broken when damage has reduced its Hit Points to equal or less than its Broken Threshold. A broken object can't be used for its normal function, nor does it grant bonuses\u2014with the exception of armor. Broken armor still grants its item bonus to AC, but it also imparts a status penalty to AC depending on its category: \u20131 for broken light armor, \u20132 for broken medium armor, or \u20133 for broken heavy armor.
+A broken item still imposes penalties and limitations normally incurred by carrying, holding, or wearing it. For example, broken armor would still impose its Dexterity modifier cap, check penalty, and so forth. If an effect makes an item broken automatically and the item has more HP than its Broken Threshold, that effect also reduces the item's current HP to the Broken Threshold.
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"broken",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.6dNUvdb1dhToNDj3"}},effects:[]},{_id:"6uEgoh53GbXuHpTF",img:"systems/pf2e/icons/conditions/paralyzed.webp",name:"Paralyzed",system:{description:{value:"You're frozen in place. You have the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} condition and can't act except to @UUID[Compendium.pf2e.actionspf2e.Item.1OagaWtBpVXExToo]{Recall Knowledge} and use actions that require only your mind (as determined by the GM). Your senses still function, but only in the areas you can perceive without moving, so you can't @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek}.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"paralyzed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.6uEgoh53GbXuHpTF"}},effects:[]},{_id:"9evPzg9E6muFcoSk",img:"systems/pf2e/icons/conditions/unnoticed.webp",name:"Unnoticed",system:{description:{value:"If you're unnoticed by a creature, that creature has no idea you're present. When you're unnoticed, you're also @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected}. This matters for abilities that can be used only against targets totally unaware of your presence.
"},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"unnoticed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9evPzg9E6muFcoSk"}},effects:[]},{_id:"9PR9y0bi4JPKnHPR",img:"systems/pf2e/icons/conditions/deafened.webp",name:"Deafened",system:{description:{value:"You can't hear. You automatically critically fail Perception checks that require you to be able to hear. You take a \u20132 status penalty to Perception checks for initiative and checks that involve sound but also rely on other senses. If you perform an action that has the auditory trait, you must succeed at a @Check[type:flat|showDC:all|dc:5] or the action is lost; attempt the check after spending the action but before any effects are applied. You are immune to auditory effects while deafened.
"},duration:{value:0},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"perception-initiative",slug:"deafened",type:"status",value:-2},{key:"Immunity",type:"auditory"}],value:{isValued:!1,value:null},slug:"deafened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR"}},effects:[]},{_id:"9qGBRpbX9NEwtAAr",img:"systems/pf2e/icons/conditions/controlled.webp",name:"Controlled",system:{description:{value:"You have been commanded, magically dominated, or otherwise had your will subverted. The controller dictates how you act and can make you use any of your actions, including attacks, reactions, or even @UUID[Compendium.pf2e.actionspf2e.Item.A72nHGUtNXgY5Ey9]{Delay}. The controller usually doesn't have to spend their own actions when controlling you.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"controlled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.9qGBRpbX9NEwtAAr"}},effects:[]},{_id:"AdPVz7rbaVSRxHFg",img:"systems/pf2e/icons/conditions/fascinated.webp",name:"Fascinated",system:{description:{value:"You're compelled to focus your attention on something, distracting you from whatever else is going on around you. You take a \u20132 status penalty to Perception and skill checks, and you can't use concentrate actions unless they (or their intended consequences) are related to the subject of your fascination, as determined by the GM. For instance, you might be able to @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} and @UUID[Compendium.pf2e.actionspf2e.Item.1OagaWtBpVXExToo]{Recall Knowledge} about the subject, but you likely couldn't cast a spell targeting a different creature. This condition ends if a creature uses hostile actions against you or any of your allies.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["perception","skill-check"],slug:"fascinated",type:"status",value:-2}],value:{isValued:!1,value:null},slug:"fascinated",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.AdPVz7rbaVSRxHFg"}},effects:[]},{_id:"AJh5ex99aV6VTggg",img:"systems/pf2e/icons/conditions/off-guard.webp",name:"Off-Guard",system:{active:!1,description:{value:`You're distracted or otherwise unable to focus your full attention on defense. You take a \u20132 circumstance penalty to AC. Some effects give you the off-guard condition only to certain creatures or against certain attacks. Others\u2014especially conditions\u2014can make you off-guard against everything. If a rule doesn't specify that the condition applies only to certain circumstances, it applies to all of them, such as "The target is off-guard."
`},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:"ac",slug:"off-guard",type:"circumstance",value:-2}],traits:{},value:{isValued:!1,value:null},slug:"off-guard",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}},effects:[]},{_id:"D5mg6Tc7Jzrj6ro7",img:"systems/pf2e/icons/conditions/encumbered.webp",name:"Encumbered",system:{description:{value:"You are carrying more weight than you can manage. While you're encumbered, you're @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} and take a 10-foot penalty to all your Speeds. As with all penalties to your Speed, this can't reduce your Speed below 5 feet.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"speed",slug:"encumbered",value:-10},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm"}],value:{isValued:!1,value:null},slug:"encumbered",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.D5mg6Tc7Jzrj6ro7"}},effects:[]},{_id:"dfCMdR4wnpbYNTix",img:"systems/pf2e/icons/conditions/stunned.webp",name:"Stunned",system:{description:{value:`You've become senseless. You can't act. Stunned usually includes a value, which indicates how many total actions you lose, possibly over multiple turns, from being stunned. Each time you regain actions, reduce the number you regain by your stunned value, then reduce your stunned value by the number of actions you lost. For example, if you were stunned 4, you would lose all 3 of your actions on your turn, reducing you to stunned 1; on your next turn, you would lose 1 more action, and then be able to use your remaining 2 actions normally. Stunned might also have a duration instead, such as "stunned for 1 minute," causing you to lose all your actions for the duration.
+Stunned overrides @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed}. If the duration of your stunned condition ends while you are slowed, you count the actions lost to the stunned condition toward those lost to being slowed. So, if you were stunned 1 and slowed 2 at the beginning of your turn, you would lose 1 action from stunned, and then lose only 1 additional action by being slowed, so you would still have 1 action remaining to use that turn.
`},duration:{value:0},group:null,overrides:["slowed"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"stunned",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix"}},effects:[]},{_id:"DmAIPqOBomZ7H95W",img:"systems/pf2e/icons/conditions/concealed.webp",name:"Concealed",system:{description:{value:"You are difficult for one or more creatures to see due to thick fog or some other obscuring feature. You can be concealed to some creatures but not others. While concealed, you can still be @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed}, but you're tougher to target. A creature that you're concealed from must succeed at a @Check[type:flat|showDC:all|dc:5] when targeting you with an attack, spell, or other effect. If the check fails, you aren't affected. Area effects aren't subject to this flat check.
"},duration:{value:0},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"concealed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W"}},effects:[]},{_id:"dTwPJuKgBQCMxixg",img:"systems/pf2e/icons/conditions/petrified.webp",name:"Petrified",system:{description:{value:"You have been turned to stone. You can't act, nor can you sense anything. You become an object with a Bulk double your normal Bulk (typically 12 for a petrified Medium creature or 6 for a petrified Small creature), AC 9, Hardness 8, and the same current Hit Points you had when alive. You don't have a Broken Threshold. When the petrified condition ends, you have the same number of Hit Points you had as a statue. If the statue is destroyed, you immediately die. While petrified, your mind and body are in stasis, so you don't age or notice the passing of time.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"petrified",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.dTwPJuKgBQCMxixg"}},effects:[]},{_id:"e1XGnhKNSQIm5IXg",img:"systems/pf2e/icons/conditions/stupefied.webp",name:"Stupefied",system:{active:!1,description:{value:"Your thoughts and instincts are clouded. Stupefied always includes a value. You take a status penalty equal to this value on Intelligence-, Wisdom-, and Charisma-based checks and DCs, including Will saving throws, spell attack modifiers, spell DCs, and skill checks that use these attribute modifiers. Any time you attempt to @UUID[Compendium.pf2e.actionspf2e.Item.aBQ8ajvEBByv45yz]{Cast a Spell} while stupefied, the spell is disrupted unless you succeed at a @Check[type:flat|showDC:all|dc:resolve(5+@item.badge.value)] with a DC equal to 5 + your stupefied value.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:["cha-based","int-based","wis-based"],slug:"stupefied",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"stupefied",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg"}},effects:[]},{_id:"eIcWbB5o3pP6OIMe",img:"systems/pf2e/icons/conditions/immobilized.webp",name:"Immobilized",system:{description:{value:"You are incapable of movement. You can't use any actions that have the move trait. If you're immobilized by something holding you in place and an external force would move you out of your space, the force must succeed at a check against either the DC of the effect holding you in place or the relevant defense (usually Fortitude DC) of the monster holding you in place.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"immobilized",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}},effects:[]},{_id:"fBnFDH2MTzgFijKf",img:"systems/pf2e/icons/conditions/unconscious.webp",name:"Unconscious",system:{description:{value:`You're sleeping or have been knocked out. You can't act. You take a \u20134 status penalty to AC, Perception, and Reflex saves, and you have the @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} and @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} conditions. When you gain this condition, you fall @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} and drop items you're holding unless the effect states otherwise or the GM determines you're positioned so you wouldn't.
+If you're unconscious because you're @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying}, you can't wake up while you have 0 Hit Points. If you are restored to 1 Hit Point or more, you lose the dying and unconscious conditions and can act normally on your next turn.
+If you are unconscious and at 0 Hit Points, but not dying, you return to 1 Hit Point and awaken after sufficient time passes. The GM determines how long you remain unconscious, from a minimum of 10 minutes to several hours. If you are healed, you lose the unconscious condition and can act normally on your next turn.
+If you're unconscious and have more than 1 Hit Point (typically because you are asleep or unconscious due to an effect), you wake up in one of the following ways.
-- You take damage, provided the damage doesn't reduce you to 0 Hit Points. If the damage reduces you to 0 Hit Points, you remain unconscious and gain the dying condition as normal.
+- You take damage, though if the damage reduces you to 0 Hit Points, you remain unconscious and gain the dying condition as normal.
- You receive healing, other than the natural healing you get from resting.
- Someone shakes you awake with an @UUID[Compendium.pf2e.actionspf2e.Item.pvQ5rY2zrtPI614F]{Interact} action.
-- There's loud noise going on around you-though this isn't automatic. At the start of your turn, you automatically attempt a Perception check against the noise's DC (or the lowest DC if there is more than one noise), waking up if you succeed. If creatures are attempting to stay quiet around you, this Perception check uses their Stealth DCs. Some magical effects make you sleep so deeply that they don't allow you to attempt this Perception check.
+- Loud noise around you might wake you. At the start of your turn, you automatically attempt a Perception check against the noise's DC (or the lowest DC if there is more than one noise), waking up if you succeed. If creatures are attempting to stay quiet around you, this Perception check uses their Stealth DCs. Some effects make you sleep so deeply that they don't allow you this Perception check.
- If you are simply asleep, the GM decides you wake up either because you have had a restful night's sleep or something disrupted that rest.
-
`},duration:{value:0},group:"death",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["ac","perception","reflex"],slug:"unconscious",type:"status",value:-4},{key:"GrantItem",onDeleteActions:{grantee:"restrict"},uuid:"Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{allowDuplicate:!1,key:"GrantItem",onDeleteActions:{grantee:"restrict",granter:"detach"},uuid:"Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60"}],value:{isValued:!1,value:null},slug:"unconscious",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf"}},effects:[]},{_id:"fesd1n5eVhpCSS18",img:"systems/pf2e/icons/conditions/sickened.webp",name:"Sickened",system:{description:{value:`You feel ill. Sickened always includes a value. You take a status penalty equal to this value on all your checks and DCs. You can't willingly ingest anything-including elixirs and potions-while sickened.
-You can spend a single action retching in an attempt to recover, which lets you immediately attempt a Fortitude save against the DC of the effect that made you sickened. On a success, you reduce your sickened value by 1 (or by 2 on a critical success).
`},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"all",slug:"sickened",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"sickened",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fesd1n5eVhpCSS18"}},effects:[]},{_id:"fuG8dgthlDWfWjIA",img:"systems/pf2e/icons/conditions/indifferent.webp",name:"Indifferent",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is indifferent to a character doesn't really care one way or the other about that character. Assume a creature's attitude to a given character is indifferent unless specified otherwise.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","unfriendly","hostile"],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"indifferent",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fuG8dgthlDWfWjIA"}},effects:[]},{_id:"HL2l2VRSaQHu9lUw",img:"systems/pf2e/icons/conditions/fatigued.webp",name:"Fatigued",system:{description:{value:`You're tired and can't summon much energy. You take a -1 status penalty to AC and saving throws. While exploring, you can't choose an exploration activity.
-You recover from fatigue after a full night's rest.
`},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["ac","saving-throw"],slug:"fatigued",type:"status",value:-1}],value:{isValued:!1,value:null},slug:"fatigued",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.HL2l2VRSaQHu9lUw"}},effects:[]},{_id:"I1ffBVISxLr2gC4u",img:"systems/pf2e/icons/conditions/unfriendly.webp",name:"Unfriendly",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is unfriendly to a character dislikes and specifically distrusts that character. The unfriendly creature won't accept @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from the character.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","indifferent","hostile"],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"unfriendly",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.I1ffBVISxLr2gC4u"}},effects:[]},{_id:"i3OJZU2nk64Df3xm",img:"systems/pf2e/icons/conditions/clumsy.webp",name:"Clumsy",system:{description:{value:"Your movements become clumsy and inexact. Clumsy always includes a value. You take a status penalty equal to the condition value to Dexterity-based checks and DCs, including AC, Reflex saves, ranged attack rolls, and skill checks using Acrobatics, Stealth, and Thievery.
"},duration:{value:0},group:"abilities",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"dex-based",slug:"clumsy",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"clumsy",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm"}},effects:[]},{_id:"iU0fEDdBp3rXpTMC",img:"systems/pf2e/icons/conditions/hidden.webp",name:"Hidden",system:{description:{value:`While you're hidden from a creature, that creature knows the space you're in but can't tell precisely where you are. You typically become hidden by using Stealth to @UUID[Compendium.pf2e.actionspf2e.Item.XMcnh4cSI32tljXa]{Hide}. When @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seeking} a creature using only imprecise senses, it remains hidden, rather than @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed}. A creature you're hidden from is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} to you, and it must succeed at a @Check[type:flat|dc:11] check when targeting you with an attack, spell, or other effect or it fails affect you. Area effects aren't subject to this flat check.
-A creature might be able to use the seek action to try to observe you.
`},duration:{value:0},group:"detection",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"hidden",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC"}},effects:[]},{_id:"j91X7x0XSomq8d60",img:"systems/pf2e/icons/conditions/prone.webp",name:"Prone",system:{description:{value:`You're lying on the ground. You are @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and take a -2 circumstance penalty to attack rolls. The only move actions you can use while you're prone are @UUID[Compendium.pf2e.actionspf2e.Item.Tj055UcNm6UEgtCg]{Crawl} and @UUID[Compendium.pf2e.actionspf2e.Item.OdIUybJ3ddfL7wzj]{Stand}. Standing up ends the prone condition. You can @UUID[Compendium.pf2e.actionspf2e.Item.ust1jJSCZQUhBZIz]{Take Cover} while prone to hunker down and gain cover against ranged attacks, even if you don't have an object to get behind, gaining a +4 circumstance bonus to AC against ranged attacks (but you remain off-guard).
-If you would be knocked prone while you're @UUID[Compendium.pf2e.actionspf2e.Item.pprgrYQ1QnIDGZiy]{Climbing} or @UUID[Compendium.pf2e.actionspf2e.Item.cS9nfDRGD83bNU1p]{Flying}, you fall. You can't be knocked prone when @UUID[Compendium.pf2e.actionspf2e.Item.c8TGiZ48ygoSPofx]{Swimming}.
`},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"attack-roll",slug:"prone",type:"circumstance",value:-2},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"prone",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60"}},effects:[]},{_id:"kWc1fhmv9LBiTuei",img:"systems/pf2e/icons/conditions/grabbed.webp",name:"Grabbed",system:{description:{value:"You're held in place by another creature, giving you the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} conditions. If you attempt a manipulate action while grabbed, you must succeed at a @Check[type:flat|dc:5] check or it is lost; roll the check after spending the action, but before any effects are applied.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}],value:{isValued:!1,value:null},slug:"grabbed",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei"}},effects:[]},{_id:"lDVqvLKA6eF3Df60",img:"systems/pf2e/icons/conditions/persistent-damage.webp",name:"Persistent Damage",system:{description:{value:'Persistent damage comes from effects like acid, being on fire, or many other situations. It appears as "X persistent [type] damage," where "X" is the amount of damage dealt and "[type]" is the damage type. Like normal damage, it can be doubled or halved based on the results of an attack roll or saving throw. Instead of taking persistent damage immediately, you take it at the end of each of your turns as long as you have the condition, rolling any damage dice anew each time. After you take persistent damage, roll a @Check[type:flat|dc:15] check to see if you recover from the persistent damage. If you succeed, the condition ends.
'},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"persistent-damage",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60"}},effects:[]},{_id:"MIRkyAjyBeXivMa7",img:"systems/pf2e/icons/conditions/enfeebled.webp",name:"Enfeebled",system:{description:{value:"You're physically weakened. Enfeebled always includes a value. When you are enfeebled, you take a status penalty equal to the condition value to Strength-based rolls and DCs, including Strength-based melee attack rolls, Strength-based damage rolls, and Athletics checks.
"},duration:{value:0},group:"abilities",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["str-based","str-damage"],slug:"enfeebled",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"enfeebled",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7"}},effects:[]},{_id:"nlCjDvLMf2EkV2dl",img:"systems/pf2e/icons/conditions/quickened.webp",name:"Quickened",system:{description:{value:"You gain 1 additional action at the start of your turn each round. Many effects that make you quickened specify the types of actions you can use with this additional action. If you become quickened from multiple sources, you can use the extra action you've been granted for any single action allowed by any of the effects that made you quickened. Because quickened has its effect at the start of your turn, you don't immediately gain actions if you become quickened during your turn.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"quickened",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.nlCjDvLMf2EkV2dl"}},effects:[]},{_id:"sDPxOjQ9kx2RZE8D",img:"systems/pf2e/icons/conditions/fleeing.webp",name:"Fleeing",system:{description:{value:"You're forced to run away due to fear or some other compulsion. On your turn, you must spend each of your actions trying to escape the source of the fleeing condition as expediently as possible (such as by using move actions to flee, or opening doors barring your escape). The source is usually the effect or caster that gave you the condition, though some effects might define something else as the source. You can't @UUID[Compendium.pf2e.actionspf2e.Item.A72nHGUtNXgY5Ey9]{Delay} or @UUID[Compendium.pf2e.actionspf2e.Item.dLgAMt3TbkmLkUqE]{Ready} while fleeing.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"fleeing",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.sDPxOjQ9kx2RZE8D"}},effects:[]},{_id:"TBSHQspnbcqxsmjL",img:"systems/pf2e/icons/conditions/frightened.webp",name:"Frightened",system:{description:{value:"You're gripped by fear and struggle to control your nerves. The frightened condition always includes a value. You take a status penalty equal to this value to all your checks and DCs. Unless specified otherwise, at the end of each of your turns, the value of your frightened condition decreases by 1.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"all",slug:"frightened",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"frightened",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL"}},effects:[]},{_id:"TkIyaNPgTZFBCCuh",img:"systems/pf2e/icons/conditions/dazzled.webp",name:"Dazzled",system:{description:{value:"Your eyes are overstimulated. If vision is your only precise sense, all creatures and objects are @UUID[Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W]{Concealed} from you.
"},duration:{value:0},group:"senses",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"dazzled",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh"}},effects:[]},{_id:"ud7gTLwPeklzYSXG",img:"systems/pf2e/icons/conditions/hostile.webp",name:"Hostile",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is hostile to a character actively seeks to harm that character. It doesn't necessarily attack, but it won't accept @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from the character.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","indifferent","unfriendly"],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"hostile",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.ud7gTLwPeklzYSXG"}},effects:[]},{_id:"v44P3WUcU1j0115l",img:"systems/pf2e/icons/conditions/helpful.webp",name:"Helpful",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is helpful to a character wishes to actively aid that character. It will accept reasonable @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from that character, as long as such requests aren't at the expense of the helpful creature's goals or quality of life. If the character or one of their allies uses a hostile action against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
"},duration:{value:0},group:"attitudes",overrides:["friendly","indifferent","unfriendly","hostile"],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"helpful",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.v44P3WUcU1j0115l"}},effects:[]},{_id:"v66R7FdOf11l94im",img:"systems/pf2e/icons/conditions/friendly.webp",name:"Friendly",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is friendly to a character likes that character. The character can attempt to @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Make a Request} of a friendly creature, and the friendly creature is likely to agree to a simple and safe request that doesn't cost it much to fulfill. If the character or one of their allies uses hostile actions against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
"},duration:{value:0},group:"attitudes",overrides:["helpful","indifferent","unfriendly","hostile"],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"friendly",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.v66R7FdOf11l94im"}},effects:[]},{_id:"VcDeM8A5oI6VqhbM",img:"systems/pf2e/icons/conditions/restrained.webp",name:"Restrained",system:{description:{value:"You're tied up and can barely move, or a creature has you pinned. You have the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} conditions, and you can't use any actions with the attack or manipulate traits except to attempt to @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escape} or @UUID[Compendium.pf2e.actionspf2e.Item.SjmKHgI7a5Z9JzBx]{Force Open} your bonds. Restrained overrides @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}.
"},duration:{value:0},group:null,overrides:["grabbed"],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}],value:{isValued:!1,value:null},slug:"restrained",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM"}},effects:[]},{_id:"VRSef5y1LmL2Hkjf",img:"systems/pf2e/icons/conditions/undetected.webp",name:"Undetected",system:{description:{value:`When you are undetected by a creature, that creature cannot see you at all, has no idea what space you occupy, and can't target you, though you still can be affected by abilities that target an area. When you're undetected by a creature, that creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} to you.
-A creature you're undetected by can guess which square you're in to try targeting you. It must pick a square and attempt an attack. This works like targeting a hidden creature (requiring a @Check[type:flat|dc:11] check), but the flat check and attack roll are rolled in secret by the GM, who doesn't reveal whether the attack missed due to failing the flat check, failing the attack roll, or choosing the wrong square.
-A creature can use the @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} action to try to find you.
`},duration:{value:0},group:"detection",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"undetected",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf"}},effects:[]},{_id:"XgEqL1kFApUbl5Z2",img:"systems/pf2e/icons/conditions/blinded.webp",name:"Blinded",system:{description:{value:"You can't see. All normal terrain is difficult terrain to you. You can't detect anything using vision. You automatically critically fail Perception checks that require you to be able to see, and if vision is your only precise sense, you take a -4 status penalty to Perception checks. You are immune to visual effects. Blinded overrides @UUID[Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh]{Dazzled}.
"},duration:{value:0},group:"senses",overrides:["dazzled"],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"perception",slug:"blinded",type:"status",value:-4},{key:"Immunity",type:"visual"}],value:{isValued:!1,value:null},slug:"blinded",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2"}},effects:[]},{_id:"xYTAsEpcJE1Ccni3",img:"systems/pf2e/icons/conditions/slowed.webp",name:"Slowed",system:{description:{value:"You have fewer actions. Slowed always includes a value. When you regain your actions at the start of your turn, reduce the number of actions you regain by your slowed value. Because slowed has its effect at the start of your turn, you don't immediately lose actions if you become slowed during your turn.
"},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"slowed",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3"}},effects:[]},{_id:"yblD8fOR1J8rDwEQ",img:"systems/pf2e/icons/conditions/confused.webp",name:"Confused",system:{description:{value:`You don't have your wits about you, and you attack wildly. You are @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard}, you don't treat anyone as your ally (though they might still treat you as theirs), and you can't Delay, Ready, or use reactions.
-You use all your actions to Strike or cast offensive cantrips, though the GM can have you use other actions to facilitate attack, such as draw a weapon, move so that a target is in reach, and so forth. Your targets are determined randomly by the GM. If you have no other viable targets, you target yourself, automatically hitting but not scoring a critical hit. If it's impossible for you to attack or cast spells, you babble incoherently, wasting your actions.
-Each time you take damage from an attack or spell, you can attempt a @Check[type:flat|dc:11] to recover from your confusion and end the condition.
`},duration:{value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"confused",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.yblD8fOR1J8rDwEQ"}},effects:[]},{_id:"Yl48xTdMh3aeQYL2",img:"systems/pf2e/icons/conditions/wounded.webp",name:"Wounded",system:{description:{value:`You have been seriously injured. If you lose the @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} condition and do not already have the wounded condition, you become wounded 1. If you already have the wounded condition when you lose the dying condition, your wounded condition value increases by 1. If you gain the dying condition while wounded, increase your dying condition value by your wounded value.
-The wounded condition ends if someone successfully restores Hit Points to you with @UUID[Compendium.pf2e.actionspf2e.Item.1kGNdIIhuglAjIp9]{Treat Wounds}, or if you are restored to full Hit Points and rest for 10 minutes.
`},duration:{value:0},group:"death",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"wounded",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2"}},effects:[]},{_id:"yZRUzMqrMmfLu0V1",img:"systems/pf2e/icons/conditions/dying.webp",name:"Dying",system:{description:{value:`You are bleeding out or otherwise at death's door. While you have this condition, you are @UUID[Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf]{Unconscious}. Dying always includes a value, and if it ever reaches dying 4, you die. If you're dying, you must attempt a recovery check at the start of your turn each round to determine whether you get better or worse. Your dying condition increases by 1 if you take damage while dying, or by 2 if you take damage from an enemy's critical hit or a critical failure on your save.
-If you lose the dying condition by succeeding at a recovery check and are still at 0 Hit Points, you remain unconscious, but you can wake up as described in that condition. You lose the dying condition automatically and wake up if you ever have 1 Hit Point or more. Any time you lose the dying condition, you gain the @UUID[Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2]{Wounded 1} condition, or increase your wounded condition value by 1 if you already have that condition.
`},duration:{value:0},group:"death",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"GrantItem",onDeleteActions:{grantee:"restrict"},uuid:"Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf"}],value:{isValued:!0,value:1},slug:"dying",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1"}},effects:[]},{_id:"zJxUflt9np0q4yML",img:"systems/pf2e/icons/conditions/invisible.webp",name:"Invisible",system:{description:{value:"While invisible, you can't be seen. You're @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} to everyone. Creatures can @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} to attempt to detect you; if a creature succeeds at its Perception check against your Stealth DC, you become @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} to that creature until you @UUID[Compendium.pf2e.actionspf2e.Item.VMozDqMMuK5kpoX4]{Sneak} to become undetected again. If you become invisible while someone can already see you, you start out hidden to the observer (instead of undetected) until you successfully sneak. You can't become @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed} while invisible except via special abilities or magic.
"},duration:{value:0},group:"senses",overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Core Rulebook"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"invisible",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.zJxUflt9np0q4yML"}},effects:[]},{_id:"axtAzam8kiKbTD2c",img:"systems/pf2e/icons/conditions/malevolence.webp",name:"Malevolence",system:{active:!1,description:{value:`As the malevolence begins to take its hold on creatures, their body, minds, and souls become increasingly haunted by the supernatural force infesting Xarwin Manor. Malevolence is a special condition that can affect PCs who play in this adventure. The malevolence condition always includes a value. You take a status penalty equal to this value to all saving throws against effects generated by haunts and against all curse and possession effects. The malevolence condition can be reduced by restoration.
+`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["ac","perception","reflex"],slug:"unconscious",type:"status",value:-4},{key:"GrantItem",onDeleteActions:{grantee:"restrict"},uuid:"Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{allowDuplicate:!1,key:"GrantItem",onDeleteActions:{grantee:"restrict",granter:"detach"},uuid:"Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60"}],value:{isValued:!1,value:null},slug:"unconscious",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf"}},effects:[]},{_id:"fesd1n5eVhpCSS18",img:"systems/pf2e/icons/conditions/sickened.webp",name:"Sickened",system:{description:{value:`You feel ill. Sickened always includes a value. You take a status penalty equal to this value on all your checks and DCs. You can't willingly ingest anything\u2014including elixirs and potions\u2014while sickened.
+You can spend a single action retching in an attempt to recover, which lets you immediately attempt a Fortitude save against the DC of the effect that made you sickened. On a success, you reduce your sickened value by 1 (or by 2 on a critical success).
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"all",slug:"sickened",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"sickened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fesd1n5eVhpCSS18"}},effects:[]},{_id:"fuG8dgthlDWfWjIA",img:"systems/pf2e/icons/conditions/indifferent.webp",name:"Indifferent",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is indifferent to a character doesn't really care one way or the other about that character. Assume a creature's attitude to a given character is indifferent unless specified otherwise.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"indifferent",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.fuG8dgthlDWfWjIA"}},effects:[]},{_id:"HL2l2VRSaQHu9lUw",img:"systems/pf2e/icons/conditions/fatigued.webp",name:"Fatigued",system:{description:{value:`You're tired and can't summon much energy. You take a \u20131 status penalty to AC and saving throws. You can't use exploration activities performed while traveling.
+You recover from fatigue after a full night's rest.
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:["ac","saving-throw"],slug:"fatigued",type:"status",value:-1}],value:{isValued:!1,value:null},slug:"fatigued",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.HL2l2VRSaQHu9lUw"}},effects:[]},{_id:"I1ffBVISxLr2gC4u",img:"systems/pf2e/icons/conditions/unfriendly.webp",name:"Unfriendly",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is unfriendly to a character dislikes and distrusts that character. The unfriendly creature won't accept @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from the character.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","indifferent","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"unfriendly",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.I1ffBVISxLr2gC4u"}},effects:[]},{_id:"i3OJZU2nk64Df3xm",img:"systems/pf2e/icons/conditions/clumsy.webp",name:"Clumsy",system:{description:{value:"Your movements become clumsy and inexact. Clumsy always includes a value. You take a status penalty equal to the condition value to Dexterity-based checks and DCs, including AC, Reflex saves, ranged attack rolls, and skill checks using Acrobatics, Stealth, and Thievery.
"},duration:{value:0},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"dex-based",slug:"clumsy",type:"status",value:"-@item.badge.value"}],value:{isValued:!0,value:1},slug:"clumsy",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm"}},effects:[]},{_id:"iU0fEDdBp3rXpTMC",img:"systems/pf2e/icons/conditions/hidden.webp",name:"Hidden",system:{description:{value:`While you're hidden from a creature, that creature knows the space you're in but can't tell precisely where you are. You typically become hidden by using Stealth to @UUID[Compendium.pf2e.actionspf2e.Item.XMcnh4cSI32tljXa]{Hide}. When @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seeking} a creature using only imprecise senses, it remains hidden, rather than @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed}. A creature you're hidden from is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} to you, and it must succeed at a @Check[type:flat|showDC:all|dc:11] when targeting you with an attack, spell, or other effect or it fails to affect you. Area effects aren't subject to this flat check.
+A creature might be able to use the seek action to try to observe you.
`},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"hidden",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC"}},effects:[]},{_id:"j91X7x0XSomq8d60",img:"systems/pf2e/icons/conditions/prone.webp",name:"Prone",system:{description:{value:`You're lying on the ground. You are @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and take a \u20132 circumstance penalty to attack rolls. The only move actions you can use while you're prone are @UUID[Compendium.pf2e.actionspf2e.Item.Tj055UcNm6UEgtCg]{Crawl} and @UUID[Compendium.pf2e.actionspf2e.Item.OdIUybJ3ddfL7wzj]{Stand}. Standing up ends the prone condition. You can @UUID[Compendium.pf2e.actionspf2e.Item.ust1jJSCZQUhBZIz]{Take Cover} while prone to hunker down and gain greater cover against ranged attacks, even if you don't have an object to get behind, which grants you a +4 circumstance bonus to AC against ranged attacks (but you remain off-guard).
+If you would be knocked prone while you're @UUID[Compendium.pf2e.actionspf2e.Item.pprgrYQ1QnIDGZiy]{Climbing} or @UUID[Compendium.pf2e.actionspf2e.Item.cS9nfDRGD83bNU1p]{Flying}, you fall. You can't be knocked prone when @UUID[Compendium.pf2e.actionspf2e.Item.c8TGiZ48ygoSPofx]{Swimming}.
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"attack-roll",slug:"prone",type:"circumstance",value:-2},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"prone",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60"}},effects:[]},{_id:"kWc1fhmv9LBiTuei",img:"systems/pf2e/icons/conditions/grabbed.webp",name:"Grabbed",system:{description:{value:"You're held in place by another creature, giving you the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} conditions. If you attempt a manipulate action while grabbed, you must succeed at a @Check[type:flat|showDC:all|dc:5] or it is lost; roll the check after spending the action, but before any effects are applied.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}],value:{isValued:!1,value:null},slug:"grabbed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei"}},effects:[]},{_id:"lDVqvLKA6eF3Df60",img:"systems/pf2e/icons/conditions/persistent-damage.webp",name:"Persistent Damage",system:{description:{value:'You are taking damage from an ongoing effect, such as from being lit on fire. This appears as "X persistent [type] damage," where "X" is the amount of damage dealt and "[type]" is the damage type. Like normal damage, it can be doubled or halved based on the results of an attack roll or saving throw. Instead of taking persistent damage immediately, you take it at the end of each of your turns as long as you have the condition, rolling any damage dice anew each time. After you take persistent damage, roll a @Check[type:flat|showDC:all|dc:15] to see if you recover from the persistent damage. If you succeed, the condition ends.
'},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"persistent-damage",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60"}},effects:[]},{_id:"MIRkyAjyBeXivMa7",img:"systems/pf2e/icons/conditions/enfeebled.webp",name:"Enfeebled",system:{active:!1,description:{value:"You're physically weakened. Enfeebled always includes a value. When you are enfeebled, you take a status penalty equal to the condition value to Strength-based rolls and DCs, including Strength-based melee attack rolls, Strength-based damage rolls, and Athletics checks.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"abilities",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:["str-based","str-damage"],slug:"enfeebled",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"enfeebled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7"}},effects:[]},{_id:"nlCjDvLMf2EkV2dl",img:"systems/pf2e/icons/conditions/quickened.webp",name:"Quickened",system:{description:{value:"You're able to act more quickly. You gain 1 additional action at the start of your turn each round. Many effects that make you quickened require you use this extra action only in certain ways. If you become quickened from multiple sources, you can use the extra action you've been granted for any single action allowed by any of the effects that made you quickened. Because quickened has its effect at the start of your turn, you don't immediately gain actions if you become quickened during your turn.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"quickened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.nlCjDvLMf2EkV2dl"}},effects:[]},{_id:"sDPxOjQ9kx2RZE8D",img:"systems/pf2e/icons/conditions/fleeing.webp",name:"Fleeing",system:{active:!1,description:{value:"You're forced to run away due to fear or some other compulsion. On your turn, you must spend each of your actions trying to escape the source of the fleeing condition as expediently as possible (such as by using move actions to flee, or opening doors barring your escape). The source is usually the effect or creature that gave you the condition, though some effects might define something else as the source. You can't @UUID[Compendium.pf2e.actionspf2e.Item.A72nHGUtNXgY5Ey9]{Delay} or @UUID[Compendium.pf2e.actionspf2e.Item.dLgAMt3TbkmLkUqE]{Ready} while fleeing.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"fleeing",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.sDPxOjQ9kx2RZE8D"}},effects:[]},{_id:"TBSHQspnbcqxsmjL",img:"systems/pf2e/icons/conditions/frightened.webp",name:"Frightened",system:{active:!1,description:{value:"You're gripped by fear and struggle to control your nerves. The frightened condition always includes a value. You take a status penalty equal to this value to all your checks and DCs. Unless specified otherwise, at the end of each of your turns, the value of your frightened condition decreases by 1.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",selector:"all",slug:"frightened",type:"status",value:"-@item.badge.value"}],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"frightened",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL"}},effects:[]},{_id:"TkIyaNPgTZFBCCuh",img:"systems/pf2e/icons/conditions/dazzled.webp",name:"Dazzled",system:{active:!1,description:{value:"Your eyes are overstimulated or your vision is swimming. If vision is your only precise sense, all creatures and objects are @UUID[Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W]{Concealed} from you.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"dazzled",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh"}},effects:[]},{_id:"ud7gTLwPeklzYSXG",img:"systems/pf2e/icons/conditions/hostile.webp",name:"Hostile",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose on a PC. A creature hostile to a character actively seeks to harm that character. It doesn't necessarily attack, but it won't accept @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from the character.
"},duration:{value:0},group:"attitudes",overrides:["helpful","friendly","indifferent","unfriendly"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"hostile",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.ud7gTLwPeklzYSXG"}},effects:[]},{_id:"v44P3WUcU1j0115l",img:"systems/pf2e/icons/conditions/helpful.webp",name:"Helpful",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is helpful to a character wishes to actively aid that character. It will accept reasonable @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from that character, as long as such requests aren't at the expense of the helpful creature's goals or quality of life. If the character (or one of their allies) uses a hostile action against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
"},duration:{value:0},group:"attitudes",overrides:["friendly","indifferent","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"helpful",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.v44P3WUcU1j0115l"}},effects:[]},{_id:"v66R7FdOf11l94im",img:"systems/pf2e/icons/conditions/friendly.webp",name:"Friendly",system:{description:{value:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose this condition on a PC. A creature that is friendly to a character likes that character. It is likely to agree to @UUID[Compendium.pf2e.actionspf2e.Item.DCb62iCBrJXy0Ik6]{Requests} from that character as long as they are simple, safe, and don't cost too much to fulfill. If the character (or one of their allies) uses hostile actions against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
"},duration:{value:0},group:"attitudes",overrides:["helpful","indifferent","unfriendly","hostile"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"friendly",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.v66R7FdOf11l94im"}},effects:[]},{_id:"VcDeM8A5oI6VqhbM",img:"systems/pf2e/icons/conditions/restrained.webp",name:"Restrained",system:{description:{value:"You're tied up and can barely move, or a creature has you pinned. You have the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} and @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} conditions, and you can't use any attack or manipulate actions except to attempt to @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escape} or @UUID[Compendium.pf2e.actionspf2e.Item.SjmKHgI7a5Z9JzBx]{Force Open} your bonds. Restrained overrides @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}.
"},duration:{value:0},group:null,overrides:["grabbed"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe"}],value:{isValued:!1,value:null},slug:"restrained",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM"}},effects:[]},{_id:"VRSef5y1LmL2Hkjf",img:"systems/pf2e/icons/conditions/undetected.webp",name:"Undetected",system:{description:{value:`When you are undetected by a creature, that creature can't see you at all, has no idea what space you occupy, and can't target you, though you still can be affected by abilities that target an area. When you're undetected by a creature, that creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} to you.
+A creature you're undetected by can guess which square you're in to try targeting you. It must pick a square and attempt an attack. This works like targeting a @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} creature (requiring a @Check[type:flat|showDC:all|dc:11|traits:secret]), but the flat check and attack roll are rolled in secret by the GM, who doesn't reveal whether the attack missed due to failing the flat check, failing the attack roll, or choosing the wrong square. They can @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} to try to find you.
`},duration:{value:0},group:"detection",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!1,value:null},slug:"undetected",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf"}},effects:[]},{_id:"XgEqL1kFApUbl5Z2",img:"systems/pf2e/icons/conditions/blinded.webp",name:"Blinded",system:{description:{value:"You can't see. All normal terrain is difficult terrain to you. You can't detect anything using vision. You automatically critically fail Perception checks that require you to be able to see, and if vision is your only precise sense, you take a \u20134 status penalty to Perception checks. You are immune to visual effects. Blinded overrides @UUID[Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh]{Dazzled}.
"},duration:{value:0},group:"senses",overrides:["dazzled"],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"FlatModifier",selector:"perception",slug:"blinded",type:"status",value:-4},{key:"Immunity",type:"visual"}],value:{isValued:!1,value:null},slug:"blinded",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2"}},effects:[]},{_id:"xYTAsEpcJE1Ccni3",img:"systems/pf2e/icons/conditions/slowed.webp",name:"Slowed",system:{description:{value:"You have fewer actions. Slowed always includes a value. When you regain your actions, reduce the number of actions regained by your slowed value. Because you regain actions at the start of your turn, you don't immediately lose actions if you become slowed during your turn.
"},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[],value:{isValued:!0,value:1},slug:"slowed",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3"}},effects:[]},{_id:"yblD8fOR1J8rDwEQ",img:"systems/pf2e/icons/conditions/confused.webp",name:"Confused",system:{description:{value:`You don't have your wits about you, and you attack wildly. You are @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard}, you don't treat anyone as your ally (though they might still treat you as theirs), and you can't Delay, Ready, or use reactions.
+You use all your actions to Strike or cast offensive cantrips, though the GM can have you use other actions to facilitate attack, such as draw a weapon, move so target is in reach, and so forth. Your targets are determined randomly by the GM. If you have no other viable targets, you target yourself, automatically hitting but not scoring a critical hit. If it's impossible for you to attack or cast spells, you babble incoherently, wasting your actions.
+Each time you take damage from an attack or spell, you can attempt a @Check[type:flat|showDC:all|dc:11] to recover from your confusion and end the condition.
`},duration:{value:0},group:null,overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"ActiveEffectLike",mode:"override",path:"system.attributes.flanking.canFlank",value:!1},{inMemoryOnly:!0,key:"GrantItem",uuid:"Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg"}],value:{isValued:!1,value:null},slug:"confused",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.yblD8fOR1J8rDwEQ"}},effects:[]},{_id:"Yl48xTdMh3aeQYL2",img:"systems/pf2e/icons/conditions/wounded.webp",name:"Wounded",system:{active:!1,description:{value:`You have been seriously injured. If you lose the @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} condition and do not already have the wounded condition, you become wounded 1. If you already have the wounded condition when you lose the dying condition, your wounded condition value increases by 1. If you gain the dying condition while wounded, increase your dying condition value by your wounded value.
+The wounded condition ends if someone successfully restores Hit Points to you using @UUID[Compendium.pf2e.actionspf2e.Item.1kGNdIIhuglAjIp9]{Treat Wounds}, or if you are restored to full Hit Points by any means and rest for 10 minutes.
`},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{immutable:!1,isValued:!0,value:1},slug:"wounded",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2"}},effects:[]},{_id:"yZRUzMqrMmfLu0V1",img:"systems/pf2e/icons/conditions/dying.webp",name:"Dying",system:{description:{value:`You are bleeding out or otherwise at death's door. While you have this condition, you are @UUID[Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf]{Unconscious}. Dying always includes a value, and if it ever reaches dying 4, you die. When you're dying, you must attempt a recovery check at the start of your turn each round to determine whether you get better or worse. Your dying condition increases by 1 if you take damage while dying, or by 2 if you take damage from an enemy's critical hit or a critical failure on your save.
+If you lose the dying condition by succeeding at a recovery check and are still at 0 Hit Points, you remain unconscious, but you can wake up as described in that condition. You lose the dying condition automatically and wake up if you ever have 1 Hit Point or more. Any time you lose the dying condition, you gain the @UUID[Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2]{Wounded 1} condition, or increase your wounded condition value by 1 if you already have that condition.
`},duration:{value:0},group:"death",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},rules:[{key:"GrantItem",onDeleteActions:{grantee:"restrict"},uuid:"Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf"}],value:{isValued:!0,value:1},slug:"dying",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1"}},effects:[]},{_id:"zJxUflt9np0q4yML",img:"systems/pf2e/icons/conditions/invisible.webp",name:"Invisible",system:{active:!1,description:{value:"You can't be seen. You're @UUID[Compendium.pf2e.conditionitems.Item.VRSef5y1LmL2Hkjf]{Undetected} to everyone. Creatures can @UUID[Compendium.pf2e.actionspf2e.Item.BlAOM2X92SI6HMtJ]{Seek} to detect you; if a creature succeeds at its Perception check against your Stealth DC, you become @UUID[Compendium.pf2e.conditionitems.Item.iU0fEDdBp3rXpTMC]{Hidden} to that creature until you @UUID[Compendium.pf2e.actionspf2e.Item.VMozDqMMuK5kpoX4]{Sneak} to become undetected again. If you become invisible while someone can already see you, you start out hidden to them (instead of undetected) until you successfully Sneak. You can't become @UUID[Compendium.pf2e.conditionitems.Item.1wQY3JYyhMYeeV2G]{Observed} while invisible except via special abilities or magic.
"},duration:{expiry:null,perpetual:!1,text:"",unit:"unlimited",value:-1},group:"senses",overrides:[],publication:{license:"ORC",remaster:!0,title:"Pathfinder Player Core"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[],traits:{},value:{isValued:!1,value:null},slug:"invisible",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.conditionitems.Item.zJxUflt9np0q4yML"}},effects:[]},{_id:"axtAzam8kiKbTD2c",img:"systems/pf2e/icons/conditions/malevolence.webp",name:"Malevolence",system:{active:!1,description:{value:`As the malevolence begins to take its hold on creatures, their body, minds, and souls become increasingly haunted by the supernatural force infesting Xarwin Manor. Malevolence is a special condition that can affect PCs who play in this adventure. The malevolence condition always includes a value. You take a status penalty equal to this value to all saving throws against effects generated by haunts and against all curse and possession effects. The malevolence condition can be reduced by restoration.
The malevolence can never increase above a value of 4. If an effect would increase a creature's malevolence value higher than 4, the creature is instead @UUID[Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg]{Stupefied 1} for 24 hours as the malevolence consumes a few of their random, short-term memories. A creature that has a malevolence 4 won't voluntarily leave the Xarwin Manor grounds.
-Each time you get a full night's rest in a region not influenced by the malevolence condition, the value of your malevolence decreases by 1.
`},duration:{perpetual:!1,text:"",value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Adventure: Malevolence"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",predicate:[{or:["origin:trait:haunt","curse","possession"]}],selector:"saving-throw",slug:"malevolence",type:"status",value:"-@item.badge.value"}],value:{immutable:!1,isValued:!0,value:1},slug:"malevolence",_migration:{version:.88,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.campaign-effects.Item.axtAzam8kiKbTD2c"}},effects:[]}]);let ConditionManager=_ConditionManager;const EXPIRING_CONDITIONS=new Set(["frightened","sickened","drained","doomed","stunned","unconscious"]),_AfflictionPF2e=class extends AbstractEffectPF2e{static{__name(this,"_AfflictionPF2e")}constructor(source,context){throw super(source,context),ErrorPF2e("Affliction items are not available in production builds")}get badge(){return{type:"counter",value:this.stage,min:this.onsetDuration?0:1,max:this.maxStage,label:this.stage===0?game.i18n.localize("PF2E.Item.Affliction.OnsetLabel"):game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage})}}get stage(){return this.system.stage}get stageData(){return Object.values(this.system.stages).at(this.stage-1)??null}get maxStage(){return Object.keys(this.system.stages).length||1}async increase(){if(this.stage===this.maxStage)return;const stage=Math.min(this.maxStage,this.system.stage+1);await this.update({system:{stage}})}async decrease(){const stage=this.system.stage-1;if(stage===0){await this.delete();return}await this.update({system:{stage}})}get onsetDuration(){return this.system.onset?this.system.onset.value*(DURATION_UNITS[this.system.onset.unit]??0):0}get remainingStageDuration(){const stageDuration=this.stageData?.duration??{unit:"unlimited"};return calculateRemainingDuration(this,{...stageDuration,expiry:"turn-end"})}prepareBaseData(){super.prepareBaseData(),this.system.stage=Math.clamped(this.system.stage,this.badge.min,this.maxStage);for(const stage of Object.values(this.system.stages))for(const condition of Object.values(stage.conditions))condition.linked??=!0}getStageDamage(stage){const stageData=Object.values(this.system.stages).at(stage-1),base=[];for(const data of Object.values(stageData?.damage??{})){const{formula,type:damageType,category}=data,terms=parseTermsFromSimpleFormula(formula);base.push({terms,damageType,category:category??null})}if(!base.length)return null;try{const{formula,breakdown}=createDamageFormula({base,modifiers:[],dice:[],ignoredResistances:[]}),roll=new DamageRoll(formula),stageLabel=game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage});return{template:{name:`${this.name} - ${stageLabel}`,damage:{roll,breakdown},materials:[],traits:this.system.traits.value,modifiers:[]},context:{type:"damage-roll",sourceType:"save",outcome:"failure",domains:[],options:new Set,self:null}}}catch(err){console.error(err)}return null}async handleStageChange(){const actor=this.actor;if(!actor)return;const itemsToDelete=this.getLinkedItems().map(i=>i.id);await actor.deleteEmbeddedDocuments("Item",itemsToDelete);const currentStage=this.stageData;if(!currentStage)return;const conditionsToAdd=[],conditionsToUpdate={};for(const data of Object.values(currentStage.conditions??{})){const value=data.value??1,existing=(()=>{const allExisting=actor.conditions.bySlug(data.slug,{temporary:!1}),byAffliction=allExisting.find(i=>i.appliedBy===this);return byAffliction||(data.linked?null:maxBy(allExisting.filter(i=>!i.appliedBy&&!i.isLocked),c=>c.active?1/0:c.value??0))})();if(existing){existing.system.value.isValued&&(conditionsToUpdate[existing.id]={value,linked:!!data.linked});continue}const condition=ConditionManager.getCondition(data.slug);condition.updateSource({"flags.pf2e.grantedBy.id":this.id}),data.linked&&condition.updateSource({"system.references.parent.id":this.id}),condition.system.value.isValued&&value>1&&condition.updateSource({"system.value.value":data.value}),conditionsToAdd.push(condition)}const additions=conditionsToAdd.map(c=>c.toObject());await actor.createEmbeddedDocuments("Item",additions),await actor.updateEmbeddedDocuments("Item",Object.entries(conditionsToUpdate).map(([_id,data])=>({_id,"system.value.value":data.value,"flags.pf2e.grantedBy.id":this.id,...data.linked?{"system.references.parent.id":this.id}:{}}))),this.system.onset||await this.createStageMessage()}getLinkedItems(){return this.actor?this.actor.items.filter(i=>i.isOfType("condition")&&!EXPIRING_CONDITIONS.has(i.slug)&&i.flags.pf2e.grantedBy?.id===this.id&&i.system.references.parent?.id===this.id):[]}async createStageMessage(){if(!this.actor)return;const damage=this.getStageDamage(this.stage);if(damage){const{template,context}=damage;await DamagePF2e.roll(template,context)}}async _preCreate(data,options,user){if(this.isOwned){const initiative=this.origin?.combatant?.initiative??game.combat?.combatant?.initiative??null;this._source.system.start={value:game.time.worldTime+this.onsetDuration,initiative}}else data.system.stage=data.system.onset?0:1;return super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const duration=changed.system?.duration;if(typeof duration?.unit=="string"&&!["unlimited","encounter"].includes(duration.unit)&&duration.value===-1&&(duration.value=1),!this.actor){const hasOnset=changed.system&&"-=onset"in changed.system?!1:!!(changed.system?.onset??this.system.onset);changed.system??={},changed.system.stage=hasOnset?0:1}return super._preUpdate(changed,options,user)}_onCreate(data,options,userId){super._onCreate(data,options,userId),game.user===this.actor?.primaryUpdater&&this.handleStageChange()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.system?.stage&&game.user===this.actor?.primaryUpdater&&this.handleStageChange()}async rollRecovery(){if(!this.actor)return;const save=this.actor.saves?.[this.system.save.type];save&&(((await save.roll({dc:{value:this.system.save.value},extraRollOptions:this.getRollOptions("item")}))?.degreeOfSuccess??0)>=DegreeOfSuccess.SUCCESS?this.decrease():this.increase())}prepareActorData(){super.prepareActorData();const actor=this.actor;if(!actor)throw ErrorPF2e("prepareActorData called from unembedded item");this.system.onset&&(actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}:onset`]=!0)}};__name2(_AfflictionPF2e,"AfflictionPF2e");let AfflictionPF2e=_AfflictionPF2e;const _ConditionPF2e=class extends AbstractEffectPF2e{static{__name(this,"_ConditionPF2e")}get badge(){return this.system.persistent?{type:"formula",value:this.system.persistent.formula,label:null}:typeof this.system.value.value=="number"?{type:"counter",min:0,max:1/0,label:null,value:this.system.value.value}:null}get origin(){const grantingItem=this.actor?.items.get(this.flags.pf2e.grantedBy?.id??"");return grantingItem?.isOfType("affliction","effect")?grantingItem.origin:null}get key(){return this.system.persistent?`persistent-damage-${this.system.persistent.damageType}`:this.slug}get appliedBy(){const appliedById=this.system.references.parent?.id??this.flags.pf2e.grantedBy?.id??"";return this.actor?.items.get(appliedById)??this.actor?.conditions.get(appliedById)??null}get value(){return this.system.value.value}get isLocked(){const parentId=this.system.references.parent?.id??"";if(this.actor?.items.has(parentId)||this.actor?.conditions.has(parentId)||super.isLocked)return!0;const granterId=this.flags.pf2e.grantedBy?.id??"",granter=this.actor?.items.get(granterId)??this.actor?.conditions.get(granterId);return Object.values(granter?.flags.pf2e.itemGrants??{}).find(g=>g.id===this.id)?.onDelete==="restrict"}get isInHUD(){return this.slug in CONFIG.PF2E.statusEffects.conditions}get breakdown(){if(!this.active)return null;const list=uniq(compact(this.actor?.conditions.bySlug(this.slug).map(condition=>{const{appliedBy}=condition;return!appliedBy?.isOfType("condition")||appliedBy?.active?appliedBy:null})??[])).map(p=>reduceItemName(p.name)).sort((a,b)=>a.localeCompare(b,game.i18n.lang)).join(", ");return list?game.i18n.format("PF2E.EffectPanel.AppliedBy",{"condition-list":list}):null}get readonly(){return this.actor&&this.id?!this.actor.items.has(this.id):!1}getRollOptions(prefix=this.type){const options=super.getRollOptions(prefix);if(this.system.persistent){const{damageType}=this.system.persistent;options.push(`damage:type:${damageType}`,`${prefix}:damage:type:${damageType}`);const category=DamageCategorization.fromDamageType(damageType);category&&options.push(`damage:category:${category}`,`${prefix}:damage:category:${category}`)}return options.sort()}async increase(){await this.actor?.increaseCondition(this)}async decrease(){await this.actor?.decreaseCondition(this)}async onEndTurn(options={}){const{actor}=this,token=options?.token??actor?.token;!this.active||!actor||this.system.persistent&&(await this.system.persistent.damage.clone().evaluate({async:!0})).toMessage({speaker:ChatMessagePF2e.getSpeaker({actor,token}),flavor:`${this.name}`},{rollMode:"roll"})}async rollRecovery(){if(this.actor&&this.system.persistent){const{dc,damageType}=this.system.persistent;((await new Statistic(this.actor,{slug:"pd-recovery",label:game.i18n.format("PF2E.Item.Condition.PersistentDamage.Chat.RecoverLabel",{name:this.name}),check:{type:"flat-check"},domains:[]}).roll({dc:{value:dc},extraRollOptions:this.getRollOptions("item"),skipDialog:!0}))?.degreeOfSuccess??0)>=DegreeOfSuccess.SUCCESS&&this.actor.decreaseCondition(`persistent-damage-${damageType}`)}}prepareBaseData(){super.prepareBaseData(),this.active=!0;const systemData=this.system;systemData.value.value=systemData.value.isValued?Number(systemData.value.value)||1:null,systemData.duration=mergeObject(systemData.duration,{value:-1,unit:"unlimited",expiry:null}),typeof this.badge?.value=="number"&&(this.name=`${this.name} ${this.badge.value}`);const folder=CONFIG.PF2E.statusEffects.iconDir;if(this.img=`${folder}${this.slug}.webp`,systemData.persistent){const{formula,damageType}=systemData.persistent,fullFormula=`(${formula})[persistent,${damageType}]`,critRule=game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice",roll=new DamageRoll(fullFormula,{},{evaluatePersistent:!0,critRule}),dc=game.user.isGM&&systemData.persistent.dc!==15?systemData.persistent.dc:null,localizationKey=`PF2E.Item.Condition.PersistentDamage.${dc!==null?"NameWithDC":"Name"}`;this.name=game.i18n.format(localizationKey,{formula,damageType:game.i18n.localize(CONFIG.PF2E.damageRollFlavors[damageType]??damageType),dc}),systemData.persistent.damage=roll,systemData.persistent.expectedValue=roll.expectedValue,this.img=PERSISTENT_DAMAGE_IMAGES[damageType]??this.img}}prepareSiblingData(){if(!this.actor)throw ErrorPF2e("prepareSiblingData may only be called from an embedded item");if(!this.active)return;const deactivate=__name2(condition=>{condition.active=!1,condition.system.references.overriddenBy.push({id:this.id,type:"condition"})},"deactivate"),conditions=this.actor.conditions.active;if(this.system.overrides.length>0){const overridden=conditions.filter(c=>this.system.overrides.includes(c.key));for(const condition of overridden)deactivate(condition)}const ofSameType=conditions.filter(c=>c!==this&&c.key===this.key);for(const condition of ofSameType)if(condition.slug==="persistent-damage"){const thisValue=this.system.persistent?.expectedValue??0,otherValue=condition.system.persistent?.expectedValue??0;thisValue>=otherValue&&deactivate(condition)}else(this.value===condition.value&&(!this.isLocked||condition.isLocked)||this.value&&condition.value&&this.value>condition.value)&&deactivate(condition)}prepareActorData(){if(super.prepareActorData(),this.actor.conditions.set(this.id,this),this.active&&this.system.persistent){const{damageType}=this.system.persistent;this.actor.rollOptions.all[`self:condition:persistent-damage:${damageType}`]=!0}}prepareRuleElements(options){return this.active?super.prepareRuleElements(options):[]}async _preUpdate(changed,options,user){return options.conditionValue=this.value,super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),!game.user.isGM&&!this.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition"))return;const[priorValue,newValue]=[options.conditionValue,this.value];if(!!priorValue&&!!newValue&&priorValue!==newValue&&!this.system.references.parent?.id){const change=newValue>priorValue?{create:this}:{delete:this};this.actor?.getActiveTokens().shift()?.showFloatyText(change)}game.pf2e.StatusEffects.refresh()}};__name2(_ConditionPF2e,"ConditionPF2e");let ConditionPF2e=_ConditionPF2e;const _EffectPF2e=class extends AbstractEffectPF2e{static{__name(this,"_EffectPF2e")}get badge(){return this.system.badge}get level(){return this.system.level.value}get traits(){return new Set(this.system.traits.value)}get isExpired(){return this.system.expired}get isAura(){return this.rules.some(r=>r.key==="Aura"&&!r.ignored)}get isIdentified(){return!this.system.unidentified}get fromAura(){return!!this.flags.pf2e.aura}prepareBaseData(){super.prepareBaseData();const{system}=this;["unlimited","encounter"].includes(system.duration.unit)?system.duration.expiry=null:system.duration.expiry||="turn-start",system.expired=this.remainingDuration.expired;const{badge}=this.system;badge&&(badge.type==="formula"?badge.label=null:(badge.min=badge.labels?1:badge.min??1,badge.max=badge.labels?.length??badge.max??1/0,badge.value=Math.clamped(badge.value,badge.min,badge.max),badge.label=badge.labels?.at(badge.value-1)?.trim()||null))}prepareRuleElements(options){if(game.settings.get("pf2e","automation.effectExpiration")&&this.isExpired&&this.actor?.items.has(this.id))for(const rule of this.system.rules)rule.ignored=!0;return super.prepareRuleElements(options)}async increase(){const badge=this.system.badge;if(badge?.type==="counter"&&!this.isExpired){const value=badge.value+1;await this.update({system:{badge:{value}}})}}async decrease(){if(this.system.badge?.type!=="counter"||this.isExpired){await this.delete();return}const value=this.system.badge.value-1;await this.update({system:{badge:{value}}})}getRollOptions(prefix=this.type){const slug=this.slug??sluggify(this.name),trimmedSlug=slug.replace(/^(?:spell-)?(?:effect|stance)-/,""),options=super.getRollOptions(prefix);return options.findSplice(o=>o===`${prefix}:${slug}`,`${prefix}:${trimmedSlug}`),options}async evaluateFormulaBadge(badge){const{actor}=this;if(!actor)throw ErrorPF2e("A formula badge can only be evaluated if part of an embedded effect");const roll=await new Roll(badge.value,this.getRollData()).evaluate({async:!0}),reevaluate=badge.reevaluate?{formula:badge.value,event:badge.reevaluate}:null,token=actor.getActiveTokens(!1,!0).shift(),speaker=ChatMessagePF2e.getSpeaker({actor,token});return roll.toMessage({flavor:reduceItemName(this.name),speaker}),{type:"value",value:roll.total,labels:badge.labels,reevaluate}}async _preCreate(data,options,user){if(this.isOwned){const initiative=this.origin?.combatant?.initiative??game.combat?.combatant?.initiative??null;this._source.system.start={value:game.time.worldTime,initiative}}const badge=data.system.badge;return this.actor&&badge?.type==="formula"&&badge.evaluate&&(this._source.system.badge=await this.evaluateFormulaBadge(badge)),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const duration=changed.system?.duration;duration?.unit==="unlimited"?duration.expiry=null:typeof duration?.unit=="string"&&!["unlimited","encounter"].includes(duration.unit)&&(duration.expiry||="turn-start",duration.value===-1&&(duration.value=1));const currentBadge=this.system.badge,badgeChange=changed.system?.badge??null;if(badgeChange){const badgeTypeChanged=badgeChange?.type&&badgeChange.type!==currentBadge?.type,labels="labels"in badgeChange&&Array.isArray(badgeChange.labels)?badgeChange.labels:currentBadge?.labels;if(badgeTypeChanged)badgeChange.value=1;else if(currentBadge?.type==="counter"){const[minValue,maxValue]=(()=>{const configuredMin=Number(badgeChange.min??currentBadge.min),configuredMax=Number(badgeChange.max??currentBadge.max);return labels?[1,Math.min(labels.length,configuredMax)]:[configuredMin,configuredMax]})();if(typeof badgeChange.value=="number"&&badgeChange.value0}get handsHeld(){return this.system.equipped.carryType==="held"?this.system.equipped.handsHeld??1:0}get isWorn(){return this.system.equipped.carryType==="worn"}get price(){return this.system.price}get assetValue(){return CoinsPF2e.fromPrice(this.price,this.quantity)}get identificationStatus(){return this.system.identification.status}get isIdentified(){return this.system.identification.status==="identified"}get isAlchemical(){return this.traits.has("alchemical")}get isMagical(){const traits=this.traits;return["magical","arcane","primal","divine","occult"].some(t=>traits.has(t))}get isInvested(){return this.traits.has("invested")?this.isEquipped&&this.isIdentified&&this.system.equipped.invested===!0:null}get isCursed(){return this.traits.has("cursed")}get isTemporary(){return this.system.temporary}get isShoddy(){return this.system.traits.otherTags.includes("shoddy")}get isDamaged(){return this.system.hp.value>0&&this.system.hp.valuec.id===this.system.containerId)??null}get bulk(){const{value,per}=this.system.bulk,bulkRelevantQuantity=Math.floor(this.quantity/per),actorSize=this.actor?.isOfType("creature")?this.actor.size:null;return new Bulk({light:value}).convertToSize(this.size,actorSize??this.size).times(bulkRelevantQuantity)}get activations(){return Object.values(this.system.activations??{}).map(action2=>{const components=[];return action2.components.cast&&components.push(game.i18n.localize("PF2E.Item.Activation.Cast")),action2.components.command&&components.push(game.i18n.localize("PF2E.Item.Activation.Command")),action2.components.envision&&components.push(game.i18n.localize("PF2E.Item.Activation.Envision")),action2.components.interact&&components.push(game.i18n.localize("PF2E.Item.Activation.Interact")),{componentsLabel:components.join(", "),...action2}})}getRollOptions(prefix=this.type){const baseOptions=super.getRollOptions(prefix),{material}=this.system,physicalItemOptions=Object.entries({equipped:this.isEquipped,[`rarity:${this.rarity}`]:!0,uninvested:this.isInvested===!1,[`material:${material.type}`]:!!material.type}).filter(([_key,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`);return[baseOptions,physicalItemOptions].flat().sort()}_initialize(options){this._container=null,super._initialize(options)}prepareBaseData(){super.prepareBaseData();const systemData=this.system;systemData.containerId||=null,systemData.material.type||=null,systemData.material.grade||=null,systemData.stackGroup||=null,systemData.equippedBulk.value||=null,systemData.baseItem??=sluggify(systemData.stackGroup??"")||null,systemData.hp.brokenThreshold=Math.floor(systemData.hp.max/2),this.isEmbedded||(systemData.hp.value=Math.min(systemData.hp.value,systemData.hp.max)),typeof systemData.price.value=="string"&&(systemData.price.value=CoinsPF2e.fromString(systemData.price.value)),systemData.traits.value.includes("infused")&&(systemData.temporary=!0),systemData.price.value=new CoinsPF2e(systemData.temporary?{}:systemData.price.value),systemData.price.per=Math.max(1,systemData.price.per??1),this.system.usage=getUsageDetails(systemData.usage.value);const{equipped,usage}=this.system;equipped.handsHeld??=0,equipped.carryType??="worn",usage.type==="worn"&&usage.where&&(equipped.inSlot??=!1),this.actor?.isOfType("loot")&&(equipped.carryType="worn",equipped.inSlot=!1),systemData.bulk=organizeBulkData(this),this._container?.id!==this.system.containerId&&(this._container=null)}prepareDerivedData(){super.prepareDerivedData(),this.name=game.pf2e.system.generateItemName(this),this.system.identification.identified??={name:this.name,img:this.img,data:{description:{value:this.description}}};const{level,rarity,price}=computeLevelRarityPrice(this);this.system.level.value=level,this.system.traits.rarity=rarity,this.system.price.value=price;const mystifiedData=this.getMystifiedData(this.identificationStatus);this.name=mystifiedData.name,this.img=mystifiedData.img,this.system.description.value=mystifiedData.data.description.value,this.system.identification.unidentified=this.getMystifiedData("unidentified")}prepareSiblingData(){this.actor&&(this.isStowed&&(this.system.equipped.carryType="stowed",delete this.system.equipped.inSlot),this._container&&!this.actor.items.has(this._container.id)&&(this._container=this.system.containerId=null))}onPrepareSynthetics(){this.system.hp.value=Math.min(this.system.hp.value,this.system.hp.max)}isStackableWith(item){if(!(this!==item&&this.type===item.type&&this.name===item.name&&this.isIdentified===item.isIdentified&&![this,item].some(i=>i.isHeld||i.isOfType("backpack"))))return!1;const thisData=this.toObject().system,otherData=item.toObject().system;return thisData.quantity=otherData.quantity,thisData.equipped=otherData.equipped,thisData.containerId=otherData.containerId,thisData._migration=otherData._migration,thisData.identification=otherData.identification,equals(thisData,otherData)}async stackWith(targetItem){if(this.isStackableWith(targetItem)){const stackQuantity=this.quantity+targetItem.quantity;await this.delete({render:!1})&&await targetItem.update({"system.quantity":stackQuantity})}}async move({relativeTo,sortBefore,toContainer,toStack,render=!0}){if(!this.actor)throw ErrorPF2e("Tried to move an unonwned item!");if(toStack)return this.stackWith(toStack);const containerResolved=toContainer??relativeTo?.container,mainContainerUpdate=(()=>{if(containerResolved&&!isCycle(this,containerResolved)){const equipped={carryType:containerResolved.stowsItems?"stowed":"worn",handsHeld:0,inSlot:!1};return{system:{containerId:containerResolved?.id,equipped}}}return!containerResolved&&this.isInContainer?{system:{containerId:null,equipped:{carryType:"worn",handsHeld:0,inSlot:!1}}}:null})(),inventory=this.actor.inventory,siblings=(containerResolved?.contents.contents??inventory.contents).sort(sortBy(i=>i.sort));if(!sortBefore&&!siblings.length&&mainContainerUpdate){await this.update(mainContainerUpdate);return}const updates=SortingHelpers.performIntegerSort(this,{target:relativeTo,siblings,sortBefore}).map(s=>{const baseUpdate={_id:s.target.id,...s.update};return mainContainerUpdate&&s.target.id===this.id?mergeObject(baseUpdate,mainContainerUpdate):baseUpdate}),stowedOrUnstowed=!this.container&&!!containerResolved||this.container&&!containerResolved;await this.actor.updateEmbeddedDocuments("Item",updates,{render:stowedOrUnstowed||render})}getMystifiedData(status,_options){const mystifiedData=this.system.identification[status],name2=mystifiedData.name||this.generateUnidentifiedName(),img=mystifiedData.img||getUnidentifiedPlaceholderImage(this),description=mystifiedData.data.description.value||(()=>{if(status==="identified")return this.description;const itemType=this.generateUnidentifiedName({typeOnly:!0}),caseCorrect=__name2(noun=>game.i18n.lang.toLowerCase()==="de"?noun:noun.toLowerCase(),"caseCorrect");return game.i18n.format("PF2E.identification.UnidentifiedDescription",{item:caseCorrect(itemType)})})();return{name:name2,img,data:{description:{value:description}}}}async getChatData(){const{type,grade}=this.system.material,material=type&&grade?game.i18n.format("PF2E.Item.Weapon.MaterialAndRunes.MaterialOption",{type:game.i18n.localize(CONFIG.PF2E.preciousMaterials[type]),grade:game.i18n.localize(CONFIG.PF2E.preciousMaterialGrades[grade])}):null;return{rarity:{name:this.rarity,label:CONFIG.PF2E.rarityTraits[this.rarity],description:CONFIG.PF2E.traitsDescriptions[this.rarity]},description:{value:this.description},material}}async setIdentificationStatus(status){this.identificationStatus!==status&&await this.update({"system.identification.status":status,"system.identification.unidentified":this.getMystifiedData("unidentified")})}generateUnidentifiedName({typeOnly=!1}={}){const itemType=game.i18n.localize(`TYPES.Item.${this.type}`);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}traitChatData(dictionary){const traitData=super.traitChatData(dictionary);for(const trait of traitData)if(trait.mystified=!this.isIdentified&&MystifiedTraits.has(trait.value),trait.excluded=trait.mystified&&!game.user.isGM,trait.excluded)delete trait.description;else if(trait.mystified){const gmNote=game.i18n.localize("PF2E.identification.TraitGMNote");trait.description=trait.description?`${gmNote}
+Each time you get a full night's rest in a region not influenced by the malevolence condition, the value of your malevolence decreases by 1.
`},duration:{perpetual:!1,text:"",value:0},group:null,overrides:[],publication:{license:"OGL",remaster:!1,title:"Pathfinder Adventure: Malevolence"},references:{children:[],immunityFrom:[],overriddenBy:[],overrides:[]},removable:!1,rules:[{key:"FlatModifier",predicate:[{or:["origin:trait:haunt","curse","possession"]}],selector:"saving-throw",slug:"malevolence",type:"status",value:"-@item.badge.value"}],value:{immutable:!1,isValued:!0,value:1},slug:"malevolence",_migration:{version:.911,previous:null}},type:"condition",flags:{core:{sourceId:"Compendium.pf2e.campaign-effects.Item.axtAzam8kiKbTD2c"}},effects:[]}];class ConditionManager{static{__name(this,"ConditionManager")}static{__name2(this,"ConditionManager")}static#initialized=!1;static conditions=new Map;static CONDITION_SOURCES=define_CONDITION_SOURCES_default;static get conditionsSlugs(){return[...this.conditions.keys()].filter(k=>!k.startsWith("Compendium."))}static async initialize(force=!1){if(this.#initialized||(this.conditions=new Map(this.CONDITION_SOURCES?.flatMap(source=>{const condition=new ConditionPF2e(source,{pack:"pf2e.conditionitems"});return[[condition.slug,condition],[condition.uuid,condition]]})??[]),delete this.CONDITION_SOURCES),(!this.#initialized||force)&&game.i18n.lang!=="en"&&game.modules.get("babele")?.active){const localize=localizer("PF2E.condition");for(const condition of this.conditions.values())condition.name=condition._source.name=localize(`${condition.slug}.name`),condition.system.description.value=condition._source.system.description.value=localize(`${condition.slug}.rules`)}this.#initialized=!0}static getCondition(slug,modifications={}){if(slug=sluggify(slug),!setHasElement(CONDITION_SLUGS,slug))return null;const condition=ConditionManager.conditions.get(slug)?.clone(modifications);if(!condition)throw ErrorPF2e("Unexpected failure looking up condition");return condition}static async updateConditionValue(itemId,actorOrToken,value){const actor=actorOrToken instanceof ActorPF2e?actorOrToken:actorOrToken.actor,condition=actor?.items.get(itemId);condition?.isOfType("condition")&&(value===0?await condition.delete():actor?.isOfType("creature")&&(tupleHasValue(["dying","wounded","doomed"],condition.slug)&&(value=Math.min(value,actor.attributes[condition.slug].max)),await condition.update({"system.value.value":value})))}}const EXPIRING_CONDITIONS=new Set(["frightened","sickened","drained","doomed","stunned","unconscious"]);class AfflictionPF2e extends AbstractEffectPF2e{static{__name(this,"AfflictionPF2e")}static{__name2(this,"AfflictionPF2e")}constructor(source,context){throw super(source,context),ErrorPF2e("Affliction items are not available in production builds")}get badge(){return{type:"counter",value:this.stage,min:1,max:this.maxStage,label:this.onset?game.i18n.localize("PF2E.Item.Affliction.OnsetLabel"):game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage})}}get stage(){return this.system.stage}get stageData(){return Object.values(this.system.stages).at(this.stage-1)??null}get maxStage(){return Object.keys(this.system.stages).length||1}async increase(){if(this.onset)await this.update({system:{"-=onset":null}});else if(this.stage!==this.maxStage){const stage=Math.min(this.maxStage,this.system.stage+1);await this.update({system:{stage}})}}async decrease(){const stage=this.system.stage-1;if(stage===0){await this.delete();return}await this.update({system:{stage}})}get onset(){return!!this.system.onset?.active}get onsetDuration(){return this.system.onset?this.system.onset.value*(DURATION_UNITS[this.system.onset.unit]??0):0}get remainingStageDuration(){const stageDuration=this.stageData?.duration??{unit:"unlimited"};return calculateRemainingDuration(this,{...stageDuration,expiry:"turn-end"})}prepareBaseData(){super.prepareBaseData(),this.system.stage=Math.clamped(this.system.stage,this.badge.min,this.maxStage);for(const stage of Object.values(this.system.stages))for(const condition of Object.values(stage.conditions))condition.linked??=!0}getStageDamage(stage){const stageData=Object.values(this.system.stages).at(stage-1),base=[];for(const data of Object.values(stageData?.damage??{})){const{formula,type:damageType,category}=data,terms=parseTermsFromSimpleFormula(formula);base.push({terms,damageType,category:category??null})}if(!base.length)return null;try{const{formula,breakdown}=createDamageFormula({base,modifiers:[],dice:[],ignoredResistances:[]}),roll=new DamageRoll(formula),stageLabel=game.i18n.format("PF2E.Item.Affliction.Stage",{stage:this.stage}),template={name:`${this.name} - ${stageLabel}`,damage:{roll,breakdown},materials:[],modifiers:[]},context={type:"damage-roll",sourceType:"save",outcome:"failure",domains:[],options:new Set,self:null,traits:this.system.traits.value};return{template,context}}catch(err){console.error(err)}return null}async handleStageChange(){const actor=this.actor;if(!actor)return;const itemsToDelete=this.getLinkedItems().map(i=>i.id);await actor.deleteEmbeddedDocuments("Item",itemsToDelete);const currentStage=this.stageData;if(!currentStage)return;const conditionsToAdd=[],conditionsToUpdate={};for(const data of Object.values(currentStage.conditions??{})){const value=data.value??1,existing=(()=>{const allExisting=actor.conditions.bySlug(data.slug,{temporary:!1}),byAffliction=allExisting.find(i=>i.appliedBy===this);return byAffliction||(data.linked?null:maxBy(allExisting.filter(i=>!i.appliedBy&&!i.isLocked),c=>c.active?1/0:c.value??0))})();if(existing){existing.system.value.isValued&&(conditionsToUpdate[existing.id]={value,linked:!!data.linked});continue}const condition=ConditionManager.getCondition(data.slug);condition.updateSource({"flags.pf2e.grantedBy.id":this.id}),data.linked&&condition.updateSource({"system.references.parent.id":this.id}),condition.system.value.isValued&&value>1&&condition.updateSource({"system.value.value":data.value}),conditionsToAdd.push(condition)}const additions=conditionsToAdd.map(c=>c.toObject());await actor.createEmbeddedDocuments("Item",additions),await actor.updateEmbeddedDocuments("Item",Object.entries(conditionsToUpdate).map(([_id,data])=>({_id,"system.value.value":data.value,"flags.pf2e.grantedBy.id":this.id,...data.linked?{"system.references.parent.id":this.id}:{}}))),this.system.onset||await this.createStageMessage()}getLinkedItems(){return this.actor?this.actor.items.filter(i=>i.isOfType("condition")&&!EXPIRING_CONDITIONS.has(i.slug)&&i.flags.pf2e.grantedBy?.id===this.id&&i.system.references.parent?.id===this.id):[]}async createStageMessage(){if(!this.actor)return;const damage=this.getStageDamage(this.stage);if(damage){const{template,context}=damage;await DamagePF2e.roll(template,context)}}async _preCreate(data,options,user){if(this.isOwned){const initiative=this.origin?.combatant?.initiative??game.combat?.combatant?.initiative??null;this._source.system.start={value:game.time.worldTime+this.onsetDuration,initiative}}else data.system.stage=1,data.system.onset&&(data.system.onset.active=!0);return super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const duration=changed.system?.duration;return typeof duration?.unit=="string"&&!["unlimited","encounter"].includes(duration.unit)&&duration.value===-1&&(duration.value=1),super._preUpdate(changed,options,user)}_onCreate(data,options,userId){super._onCreate(data,options,userId),game.user===this.actor?.primaryUpdater&&this.handleStageChange()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.system?.stage&&game.user===this.actor?.primaryUpdater&&this.handleStageChange()}async rollRecovery(){if(!this.actor)return;const save=this.actor.saves?.[this.system.save.type];save&&(((await save.roll({dc:{value:this.system.save.value},extraRollOptions:this.getRollOptions("item")}))?.degreeOfSuccess??0)>=DegreeOfSuccess.SUCCESS?this.decrease():this.increase())}prepareActorData(){super.prepareActorData();const actor=this.actor;if(!actor)throw ErrorPF2e("prepareActorData called from unembedded item");this.onset&&(actor.rollOptions.all[`self:${this.type}:${this.rollOptionSlug}:onset`]=!0)}}class ConditionPF2e extends AbstractEffectPF2e{static{__name(this,"ConditionPF2e")}static{__name2(this,"ConditionPF2e")}get badge(){return this.system.persistent?{type:"formula",value:this.system.persistent.formula,label:null}:typeof this.system.value.value=="number"?{type:"counter",min:0,max:1/0,label:null,value:this.system.value.value}:null}get origin(){const grantingItem=this.actor?.items.get(this.flags.pf2e.grantedBy?.id??"");return grantingItem?.isOfType("affliction","effect")?grantingItem.origin:null}get key(){return this.system.persistent?`persistent-damage-${this.system.persistent.damageType}`:this.slug}get appliedBy(){const appliedById=this.system.references.parent?.id??this.flags.pf2e.grantedBy?.id??"";return this.actor?.items.get(appliedById)??this.actor?.conditions.get(appliedById)??null}get value(){return this.system.value.value}get isLocked(){const parentId=this.system.references.parent?.id??"";if(this.actor?.items.has(parentId)||this.actor?.conditions.has(parentId)||super.isLocked)return!0;const granterId=this.flags.pf2e.grantedBy?.id??"",granter=this.actor?.items.get(granterId)??this.actor?.conditions.get(granterId);return Object.values(granter?.flags.pf2e.itemGrants??{}).find(g=>g.id===this.id)?.onDelete==="restrict"}get isInHUD(){return this.slug in CONFIG.PF2E.statusEffects.conditions}get breakdown(){if(!this.active)return null;const list=uniq(compact(this.actor?.conditions.bySlug(this.slug).map(condition=>{const{appliedBy}=condition;return!appliedBy?.isOfType("condition")||appliedBy?.active?appliedBy:null})??[])).map(p=>reduceItemName(p.name)).sort((a,b)=>a.localeCompare(b,game.i18n.lang)).join(", ");return list?game.i18n.format("PF2E.EffectPanel.AppliedBy",{"condition-list":list}):null}get readonly(){return this.actor&&this.id?!this.actor.items.has(this.id):!1}getRollOptions(prefix=this.type){const options=super.getRollOptions(prefix);if(this.system.persistent){const{damageType}=this.system.persistent;options.push(`damage:type:${damageType}`,`${prefix}:damage:type:${damageType}`);const category=DamageCategorization.fromDamageType(damageType);category&&options.push(`damage:category:${category}`,`${prefix}:damage:category:${category}`)}return options}async increase(){await this.actor?.increaseCondition(this)}async decrease(){await this.actor?.decreaseCondition(this)}async onEndTurn(options={}){const{actor}=this,token=options?.token??actor?.token;!this.active||!actor||this.system.persistent&&await this.system.persistent.damage.clone().toMessage({speaker:ChatMessagePF2e.getSpeaker({actor,token}),flavor:`${this.name}`},{rollMode:"roll"})}async rollRecovery(){if(this.actor&&this.system.persistent){const{dc,damageType}=this.system.persistent;((await new Statistic(this.actor,{slug:"pd-recovery",label:game.i18n.format("PF2E.Item.Condition.PersistentDamage.Chat.RecoverLabel",{name:this.name}),check:{type:"flat-check"},domains:[]}).roll({dc:{value:dc},extraRollOptions:this.getRollOptions("item"),skipDialog:!0}))?.degreeOfSuccess??0)>=DegreeOfSuccess.SUCCESS&&this.actor.decreaseCondition(`persistent-damage-${damageType}`)}}prepareBaseData(){super.prepareBaseData(),this.active=!0;const systemData=this.system;systemData.value.value=systemData.value.isValued?Number(systemData.value.value)||1:null,systemData.duration=foundry.utils.mergeObject(systemData.duration,{value:-1,unit:"unlimited",expiry:null}),typeof this.badge?.value=="number"&&(this.name=`${this.name} ${this.badge.value}`);const folder=CONFIG.PF2E.statusEffects.iconDir;if(this.img=`${folder}${this.slug}.webp`,systemData.persistent){const{formula,damageType}=systemData.persistent,fullFormula=`(${formula})[persistent,${damageType}]`,critRule=game.settings.get("pf2e","critRule")==="doubledamage"?"double-damage":"double-dice",roll=new DamageRoll(fullFormula,{},{evaluatePersistent:!0,critRule}),dc=game.user.isGM&&systemData.persistent.dc!==15?systemData.persistent.dc:null,localizationKey=`PF2E.Item.Condition.PersistentDamage.${dc!==null?"NameWithDC":"Name"}`;this.name=game.i18n.format(localizationKey,{formula,damageType:game.i18n.localize(CONFIG.PF2E.damageRollFlavors[damageType]??damageType),dc}),systemData.persistent.damage=roll,systemData.persistent.expectedValue=roll.expectedValue,this.img=PERSISTENT_DAMAGE_IMAGES[damageType]??this.img}}prepareSiblingData(){if(!this.actor)throw ErrorPF2e("prepareSiblingData may only be called from an embedded item");if(!this.active)return;const deactivate=__name2(condition=>{condition.active=!1,condition.system.references.overriddenBy.push({id:this.id,type:"condition"})},"deactivate"),conditions=this.actor.conditions.active;if(this.system.overrides.length>0){const overridden=conditions.filter(c=>this.system.overrides.includes(c.key));for(const condition of overridden)deactivate(condition)}const ofSameType=conditions.filter(c=>c!==this&&c.key===this.key);for(const condition of ofSameType)if(condition.slug==="persistent-damage"){const thisValue=this.system.persistent?.expectedValue??0,otherValue=condition.system.persistent?.expectedValue??0;thisValue>=otherValue&&deactivate(condition)}else(this.value===condition.value&&(!this.isLocked||condition.isLocked)||this.value&&condition.value&&this.value>condition.value)&&deactivate(condition)}prepareActorData(){if(super.prepareActorData(),this.active&&this.system.persistent){const{damageType}=this.system.persistent;this.actor.rollOptions.all[`self:condition:persistent-damage:${damageType}`]=!0}}prepareRuleElements(options){return this.active?super.prepareRuleElements(options):[]}async _preUpdate(changed,options,user){return options.conditionValue=this.value,super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){if(super._onUpdate(changed,options,userId),!game.user.isGM&&!this.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition"))return;const[priorValue,newValue]=[options.conditionValue,this.value];if(!!priorValue&&!!newValue&&priorValue!==newValue&&!this.system.references.parent?.id){const change=newValue>priorValue?{create:this}:{delete:this};this.actor?.getActiveTokens().shift()?.showFloatyText(change)}game.pf2e.StatusEffects.refresh()}}class EffectPF2e extends AbstractEffectPF2e{static{__name(this,"EffectPF2e")}static{__name2(this,"EffectPF2e")}get badge(){return this.system.badge}get level(){return this.system.level.value}get traits(){return new Set(this.system.traits.value)}get isExpired(){return this.system.expired}get isAura(){return this.rules.some(r=>r.key==="Aura"&&!r.ignored)}get isIdentified(){return!this.system.unidentified}get fromAura(){return!!this.flags.pf2e.aura}prepareBaseData(){super.prepareBaseData();const{system}=this;["unlimited","encounter"].includes(system.duration.unit)?system.duration.expiry=null:system.duration.expiry||="turn-start",system.expired=this.remainingDuration.expired;const{badge}=this.system;badge&&(badge.type==="formula"?badge.label=null:(badge.min=badge.labels?1:badge.min??1,badge.max=badge.labels?.length??badge.max??1/0,badge.value=Math.clamped(badge.value,badge.min,badge.max),badge.label=badge.labels?.at(badge.value-1)?.trim()||null))}prepareRuleElements(options){if(game.settings.get("pf2e","automation.effectExpiration")&&this.isExpired&&this.actor?.items.has(this.id))for(const rule of this.system.rules)rule.ignored=!0;return super.prepareRuleElements(options)}async increase(){const badge=this.system.badge;if(badge?.type==="counter"&&!this.isExpired){const value=badge.value+1;await this.update({system:{badge:{value}}})}}async decrease(){if(this.system.badge?.type!=="counter"||this.isExpired){await this.delete();return}const value=this.system.badge.value-1;await this.update({system:{badge:{value}}})}getRollOptions(prefix=this.type){const slug=this.slug??sluggify(this.name),trimmedSlug=slug.replace(/^(?:spell-)?(?:effect|stance)-/,""),options=super.getRollOptions(prefix);return options.findSplice(o=>o===`${prefix}:${slug}`,`${prefix}:${trimmedSlug}`),options}async evaluateFormulaBadge(badge){const{actor}=this;if(!actor)throw ErrorPF2e("A formula badge can only be evaluated if part of an embedded effect");const roll=await new Roll(badge.value,this.getRollData()).evaluate({async:!0}),reevaluate=badge.reevaluate?{formula:badge.value,event:badge.reevaluate}:null,token=actor.getActiveTokens(!1,!0).shift(),speaker=ChatMessagePF2e.getSpeaker({actor,token});return roll.toMessage({flavor:reduceItemName(this.name),speaker}),{type:"value",value:roll.total,labels:badge.labels,reevaluate}}async _preCreate(data,options,user){if(this.isOwned){const initiative=this.origin?.combatant?.initiative??game.combat?.combatant?.initiative??null;this._source.system.start={value:game.time.worldTime,initiative}}const badge=data.system.badge;return this.actor&&badge?.type==="formula"&&badge.evaluate&&(this._source.system.badge=await this.evaluateFormulaBadge(badge)),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const duration=changed.system?.duration;duration?.unit==="unlimited"?duration.expiry=null:typeof duration?.unit=="string"&&!["unlimited","encounter"].includes(duration.unit)&&(duration.expiry||="turn-start",duration.value===-1&&(duration.value=1));const currentBadge=this.system.badge,badgeChange=changed.system?.badge??null;if(badgeChange){const badgeTypeChanged=badgeChange?.type&&badgeChange.type!==currentBadge?.type,labels="labels"in badgeChange&&Array.isArray(badgeChange.labels)?badgeChange.labels:currentBadge?.labels;if(badgeTypeChanged)badgeChange.value=1;else if(currentBadge?.type==="counter"){const[minValue,maxValue]=(()=>{const configuredMin=Number(badgeChange.min??currentBadge.min),configuredMax=Number(badgeChange.max??currentBadge.max);return labels?[1,Math.min(labels.length,configuredMax)]:[configuredMin,configuredMax]})();if(typeof badgeChange.value=="number"&&badgeChange.value0}get handsHeld(){return this.system.equipped.carryType==="held"?this.system.equipped.handsHeld??1:0}get isWorn(){return this.system.equipped.carryType==="worn"}get price(){return this.system.price}get assetValue(){return CoinsPF2e.fromPrice(this.price,this.quantity)}get identificationStatus(){return this.system.identification.status}get isIdentified(){return this.system.identification.status==="identified"}get isAlchemical(){return this.traits.has("alchemical")}get isMagical(){const traits=this.traits;return["magical","arcane","primal","divine","occult"].some(t=>traits.has(t))}get isInvested(){return this.traits.has("invested")?this.isEquipped&&this.isIdentified&&this.system.equipped.invested===!0:null}get isCursed(){return this.traits.has("cursed")}get isTemporary(){return this.system.temporary}get isShoddy(){return this.system.traits.otherTags.includes("shoddy")}get isDamaged(){return this.system.hp.value>0&&this.system.hp.value0&&!this.isDestroyed&&hitPoints.value<=hitPoints.brokenThreshold}get isDestroyed(){const{hitPoints}=this;return hitPoints.max>0&&hitPoints.value===0}get material(){return foundry.utils.deepClone(this.system.material)}get isSpecific(){return!1}get isInContainer(){return!!this.container}get isStowed(){return!!this.container?.system.stowing}get container(){return this.system.containerId===null?this._container=null:this._container??=this.actor?.itemTypes.backpack.find(c=>c.id===this.system.containerId)??null}get bulk(){const{per}=this.system.bulk,bulkRelevantQuantity=Math.floor(this.quantity/per),actorSize=this.actor?.isOfType("creature")?this.actor.size:null;return new Bulk(this.system.bulk.value).convertToSize(this.size,actorSize??this.size).times(bulkRelevantQuantity)}get activations(){return Object.values(this.system.activations??{}).map(action2=>{const components=[];return action2.components.cast&&components.push(game.i18n.localize("PF2E.Item.Activation.Cast")),action2.components.command&&components.push(game.i18n.localize("PF2E.Item.Activation.Command")),action2.components.envision&&components.push(game.i18n.localize("PF2E.Item.Activation.Envision")),action2.components.interact&&components.push(game.i18n.localize("PF2E.Item.Activation.Interact")),{componentsLabel:components.join(", "),...action2}})}getRollOptions(prefix=this.type){const rollOptions=super.getRollOptions(prefix),{material}=this.system;return rollOptions.push(...Object.entries({equipped:this.isEquipped,[`hands-held:${this.handsHeld}`]:this.handsHeld>0,[`rarity:${this.rarity}`]:!0,uninvested:this.isInvested===!1,[`material:${material.type}`]:!!material.type}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}_initialize(options){this._container=null,super._initialize(options)}prepareBaseData(){super.prepareBaseData(),this.system.containerId||=null,this.system.material.type||=null,this.system.material.grade||=null,this.system.material.effects??=[],this.system.stackGroup??=null,this.system.hp.brokenThreshold=Math.floor(this.system.hp.max/2),typeof this.system.price.value=="string"&&(this.system.price.value=CoinsPF2e.fromString(this.system.price.value)),this.system.traits.value.includes("infused")&&(this.system.temporary=!0),this.system.price.value=new CoinsPF2e(this.system.temporary?{}:this.system.price.value),this.system.price.per=Math.max(1,this.system.price.per??1),this.system.usage=getUsageDetails(this.system.usage?.value??"carried");const{equipped,usage}=this.system;equipped.handsHeld??=0,equipped.carryType??="worn",usage.type==="worn"&&usage.where&&(equipped.inSlot??=!1),this.actor?.isOfType("loot")&&(equipped.carryType="worn",equipped.inSlot=!1),this.system.bulk=prepareBulkData(this),this._container?.id!==this.system.containerId&&(this._container=null)}prepareDerivedData(){super.prepareDerivedData(),this.name=game.pf2e.system.generateItemName(this),this.system.identification.identified??={name:this.name,img:this.img,data:{description:{value:this.description}}};const{level,rarity,price}=computeLevelRarityPrice(this);this.system.level.value=level,this.system.traits.rarity=rarity,this.system.price.value=price;const mystifiedData=this.getMystifiedData(this.identificationStatus);this.name=mystifiedData.name,this.img=mystifiedData.img,this.system.description.value=mystifiedData.data.description.value,this.system.identification.unidentified=this.getMystifiedData("unidentified"),this.isEmbedded||(this.system.hp.value=Math.clamped(this.system.hp.value,0,this.system.hp.max))}prepareSiblingData(){this.actor&&(this.isStowed&&(this.system.equipped.carryType="stowed",delete this.system.equipped.inSlot),this._container&&!this.actor.items.has(this._container.id)&&(this._container=this.system.containerId=null))}onPrepareSynthetics(){this.system.hp.value=Math.clamped(this.system.hp.value,0,this.system.hp.max)}isStackableWith(item){if(!(this!==item&&this.type===item.type&&this.name===item.name&&this.isIdentified===item.isIdentified&&![this,item].some(i=>i.isHeld||i.isOfType("backpack"))))return!1;const thisData=this.toObject().system,otherData=item.toObject().system;return thisData.quantity=otherData.quantity,thisData.equipped=otherData.equipped,thisData.containerId=otherData.containerId,thisData._migration=otherData._migration,thisData.identification=otherData.identification,equals(thisData,otherData)}async stackWith(targetItem){if(this.isStackableWith(targetItem)){const stackQuantity=this.quantity+targetItem.quantity;await this.delete({render:!1})&&await targetItem.update({"system.quantity":stackQuantity})}}async move({relativeTo,sortBefore,toContainer,toStack,render=!0}){if(!this.actor)throw ErrorPF2e("Tried to move an unonwned item!");if(toStack)return this.stackWith(toStack);const containerResolved=toContainer??relativeTo?.container,mainContainerUpdate=(()=>{if(containerResolved&&!isCycle(this,containerResolved)){const equipped={carryType:containerResolved.stowsItems?"stowed":"worn",handsHeld:0,inSlot:!1};return{system:{containerId:containerResolved?.id,equipped}}}return!containerResolved&&this.isInContainer?{system:{containerId:null,equipped:{carryType:"worn",handsHeld:0,inSlot:!1}}}:null})(),inventory=this.actor.inventory,siblings=(containerResolved?.contents.contents??inventory.contents).sort((a,b)=>a.sort-b.sort);if(!sortBefore&&!siblings.length&&mainContainerUpdate){await this.update(mainContainerUpdate);return}const updates=SortingHelpers.performIntegerSort(this,{target:relativeTo,siblings,sortBefore}).map(s=>{const baseUpdate={_id:s.target.id,...s.update};return mainContainerUpdate&&s.target.id===this.id?foundry.utils.mergeObject(baseUpdate,mainContainerUpdate):baseUpdate}),stowedOrUnstowed=!this.container&&!!containerResolved||this.container&&!containerResolved;await this.actor.updateEmbeddedDocuments("Item",updates,{render:stowedOrUnstowed||render})}getMystifiedData(status,_options){const mystifiedData=this.system.identification[status],name2=mystifiedData.name||this.generateUnidentifiedName(),img=mystifiedData.img||getUnidentifiedPlaceholderImage(this),description=mystifiedData.data.description.value||(()=>{if(status==="identified")return this.description;const itemType=this.generateUnidentifiedName({typeOnly:!0}),caseCorrect=__name2(noun=>game.i18n.lang.toLowerCase()==="de"?noun:noun.toLowerCase(),"caseCorrect");return game.i18n.format("PF2E.identification.UnidentifiedDescription",{item:caseCorrect(itemType)})})();return{name:name2,img,data:{description:{value:description}}}}async getChatData(){const{type,grade}=this.system.material,material=type&&grade?game.i18n.format("PF2E.Item.Weapon.MaterialAndRunes.MaterialOption",{type:game.i18n.localize(CONFIG.PF2E.preciousMaterials[type]),grade:game.i18n.localize(CONFIG.PF2E.preciousMaterialGrades[grade])}):null;return{rarity:{name:this.rarity,label:CONFIG.PF2E.rarityTraits[this.rarity],description:CONFIG.PF2E.traitsDescriptions[this.rarity]},description:{value:this.description},material}}async setIdentificationStatus(status){this.identificationStatus!==status&&await this.update({"system.identification.status":status,"system.identification.unidentified":this.getMystifiedData("unidentified")})}generateUnidentifiedName({typeOnly=!1}={}){const itemType=game.i18n.localize(`TYPES.Item.${this.type}`);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}traitChatData(dictionary){const traitData=super.traitChatData(dictionary);for(const trait of traitData)if(trait.mystified=!this.isIdentified&&MystifiedTraits.has(trait.value),trait.excluded=trait.mystified&&!game.user.isGM,trait.excluded)delete trait.description;else if(trait.mystified){const gmNote=game.i18n.localize("PF2E.identification.TraitGMNote");trait.description=trait.description?`${gmNote}
-${game.i18n.localize(trait.description)}`:gmNote}return traitData}async _preCreate(data,options,user){return this._source.system.equipped={carryType:"worn"},this.system.usage.type==="worn"&&!!this.system.usage.where&&this.actor?.isOfType("character")&&(this._source.system.equipped.inSlot=!1),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(typeof changed.system?.hp?.value=="number"?changed.system.hp.value=Math.clamped(changed.system.hp.value,0,this.system.hp.max):typeof changed.system?.hp?.max=="number"&&changed.system.hp.maxr.key==="ItemAlteration"&&r.property==="hp-max"&&r.itemType===this.type)??!1;if(actor&&hasHpChangeRules&&changed.system?.equipped?.carryType){const postUpdateHPMax=(()=>{const actorSource=actor.toObject(),itemSource=actorSource.items.find(i=>i._id===this.id)??{system:{}};itemSource.system=mergeObject(itemSource.system,deepClone(changed.system));const itemClone=new ActorProxyPF2e(actorSource).items.get(this.id,{strict:!0});return itemClone.isOfType("armor")?itemClone.system.hp.max:this.system.hp.max})();if(postUpdateHPMax!==this.system.hp.max){changed.system.hp??=deepClone(this._source.system.hp);const floorOrCeil=postUpdateHPMax>this.system.hp.max?Math.floor:Math.ceil;changed.system.hp.value=floorOrCeil(Math.clamped(this.system.hp.value*(postUpdateHPMax/this.system.hp.max),0,postUpdateHPMax))}}return super._preUpdate(changed,options,user)}};__name2(_PhysicalItemPF2e,"PhysicalItemPF2e");let PhysicalItemPF2e=_PhysicalItemPF2e;const _PhysicalItemSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_PhysicalItemSheetPF2e")}async getData(options){const sheetData=await super.getData(options),{item}=this,basePrice=new CoinsPF2e(item._source.system.price.value),priceAdjustment=(()=>{const baseCopperValue=basePrice.copperValue,derivedCopperValue=item.system.price.value.copperValue;return derivedCopperValue>baseCopperValue?"higher":derivedCopperValue{const basePrice2=new CoinsPF2e(baseData.system.price.value).scale(baseData.system.quantity).copperValue,derivedPrice=item.assetValue.copperValue;return basePrice2!==derivedPrice?game.i18n.format(hintText,{property:game.i18n.localize("PF2E.PriceLabel"),value:item.price.value.toString()}):null})();return{...sheetData,itemType:game.i18n.localize("PF2E.ItemTitle"),hasSidebar:!0,baseLevel:baseData.system.level.value,adjustedLevelHint,basePrice,priceAdjustment,adjustedPriceHint,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,bulkTypes:CONFIG.PF2E.bulkTypes,frequencies:CONFIG.PF2E.frequencies,sizes:CONFIG.PF2E.actorSizes,stackGroups:CONFIG.PF2E.stackGroups,usages:CONFIG.PF2E.usages,isPhysical:!0,activations,bulkDisabled:!!sheetData.data?.stackGroup?.trim()}}render(force,options){return!this.item.isIdentified&&!game.user.isGM?(ui.notifications.warn(this.item.description),this):super.render(force,options)}prepareMaterials(valuationData){const preciousMaterials2=CONFIG.PF2E.preciousMaterials,materials=Object.entries(valuationData).reduce((result,[materialKey,materialData])=>{const validGrades=[...PRECIOUS_MATERIAL_GRADES].filter(grade=>!!materialData[grade]);return validGrades.length&&(result[materialKey]={label:game.i18n.localize(preciousMaterials2[materialKey]),grades:Object.fromEntries(validGrades.map(grade=>[grade,{value:JSON.stringify({type:materialKey,grade}),label:game.i18n.localize(CONFIG.PF2E.preciousMaterialGrades[grade])}]))}),result},{});return{value:JSON.stringify(this.item.material),materials}}activateListeners($html){super.activateListeners($html),$html.find("[data-action=activation-add]").on("click",event=>{event.preventDefault();const id=randomID(16),action2={id,actionCost:{value:1,type:"action"},components:{command:!1,envision:!1,interact:!1,cast:!1},description:{value:""},traits:{value:[],custom:""}};this.item.update({[`system.activations.${id}`]:action2})}),$html.find("[data-action=activation-delete]").on("click",event=>{event.preventDefault();const id=$(event.target).closest("[data-activation-id]").attr("data-activation-id");Object.values(this.item.system.activations??[]).length===1&&id&&id in(this.item.system.activations??{})?this.item.update({"system.-=activations":null}):this.item.update({[`system.activations.-=${id}`]:null})}),$html.find("[data-action=activation-frequency-add]").on("click",event=>{const id=$(event.target).closest("[data-activation-id]").attr("data-activation-id");if(id&&id in(this.item.system.activations??{})){const per=CONFIG.PF2E.frequencies.day;this.item.update({[`system.activations.${id}.frequency`]:{value:1,max:1,per}})}}),$html.find("[data-action=activation-frequency-delete]").on("click",event=>{const id=$(event.target).closest("[data-activation-id]").attr("data-activation-id");id&&id in(this.item.system.activations??{})&&this.item.update({[`system.activations.${id}.-=frequency`]:null})})}async _updateObject(event,formData){const[materialType,materialGrade]=[formData["system.material.type"],formData["system.material.grade"]],typeIsValid=materialType===void 0||typeof materialType=="string"&&materialType in CONFIG.PF2E.preciousMaterials,gradeIsValid=materialGrade===void 0||typeof materialGrade=="string"&&materialGrade in CONFIG.PF2E.preciousMaterialGrades;(!typeIsValid||!gradeIsValid)&&(formData["system.material.type"]=null,formData["system.material.grade"]=null),"system.price.value"in formData&&(formData["system.price.value"]=CoinsPF2e.fromString(String(formData["system.price.value"])));const expanded=expandObject(formData);for(const action2 of Object.values(expanded.system?.activations??[])){const actionCost=action2.actionCost;if(actionCost){const isAction=actionCost.type==="action";actionCost.value||(actionCost.value=isAction?actionCost.value||1:null)}}return super._updateObject(event,flattenObject(expanded))}};__name2(_PhysicalItemSheetPF2e,"PhysicalItemSheetPF2e");let PhysicalItemSheetPF2e=_PhysicalItemSheetPF2e;const _ArmorPF2e=class extends PhysicalItemPF2e{static{__name(this,"_ArmorPF2e")}isStackableWith(item){return this.isEquipped||item.isEquipped?!1:super.isStackableWith(item)}get isShield(){return this.system.category==="shield"}get isArmor(){return!this.isShield}get isBarding(){return["light-barding","heavy-barding"].includes(this.category)}get baseType(){return this.system.baseItem??null}get group(){return this.system.group||null}get category(){return this.system.category}get dexCap(){return this.isShield?null:this.system.dexCap}get strength(){return this.isShield?null:this.system.strength}get checkPenalty(){return this.isShield?null:this.system.checkPenalty||null}get speedPenalty(){return this.system.speedPenalty||null}get acBonus(){return this.system.acBonus}get hitPoints(){return deepClone(this.system.hp)}get hardness(){return this.system.hardness}get isSpecific(){return this.system.specific?.value??!1}get isBroken(){const{hitPoints}=this;return hitPoints.max>0&&!this.isDestroyed&&hitPoints.value<=hitPoints.brokenThreshold}get isDestroyed(){const{hitPoints}=this;return hitPoints.max>0&&hitPoints.value===0}get isRaised(){return this.isShield&&this.actor?.isOfType("character","npc")?this.id===this.actor.attributes.shield.itemId&&this.actor.attributes.shield.raised:!1}getRollOptions(prefix="armor"){return[super.getRollOptions(prefix),Object.entries({[`category:${this.category}`]:!0,[`group:${this.group}`]:!!this.group,[`base:${this.baseType}`]:!!this.baseType,"rune:potency":this.system.runes.potency>0,"rune:resilient":this.system.runes.resilient>0}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`),this.system.runes.property.map(r=>`${prefix}:rune:property:${sluggify(r)}`)].flat().sort()}prepareBaseData(){super.prepareBaseData(),this.system.potencyRune.value||=null,this.system.resiliencyRune.value||=null,this.prepareRunes();const baseTraits=this.system.traits.value,fromRunes=this.system.runes.potency||this.system.runes.resilient?["invested","abjuration"]:[],hasTraditionTraits=baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t)),magicTraits=fromRunes.length>0&&!hasTraditionTraits?["magical"]:[];this.system.traits.value=uniq([baseTraits,fromRunes,magicTraits].flat()).sort()}prepareDerivedData(){super.prepareDerivedData();const potencyRune=this.isArmor&&this.isInvested&&!AutomaticBonusProgression.isEnabled(this.actor)?this.system.runes.potency:0,baseArmor=Number(this.system.acBonus)||0;this.system.acBonus=this.isShield&&(this.isBroken||this.isDestroyed)?0:baseArmor+potencyRune}prepareRunes(){AutomaticBonusProgression.cleanupRunes(this);const{potencyRune,resiliencyRune,propertyRune1,propertyRune2,propertyRune3,propertyRune4}=this.system,runes=this.system.runes={potency:potencyRune.value??0,resilient:resilientRuneValues.get(resiliencyRune.value)??0,property:prunePropertyRunes([propertyRune1.value,propertyRune2.value,propertyRune3.value,propertyRune4.value],RUNE_DATA.armor.property),effects:[]},maxPropertySlots=getPropertySlots(this);runes.property.length=Math.min(runes.property.length,maxPropertySlots)}prepareActorData(){const{actor}=this;if(!actor)throw ErrorPF2e("This method may only be called from embedded items");if(this.isEquipped){if(this.isArmor)for(const rollOption of this.getRollOptions("armor"))actor.rollOptions.all[rollOption]=!0;this.setActorShieldData()}}onPrepareSynthetics(){super.onPrepareSynthetics(),this.setActorShieldData()}setActorShieldData(){const{actor}=this;if(!(this.isShield&&this.isEquipped&&actor?.heldShield===this)||!actor.isOfType("character","npc"))return;const{attributes}=actor;if(attributes.shield.itemId!==null)return;const{hitPoints}=this;attributes.shield={itemId:this.id,name:this.name,ac:this.acBonus,hp:hitPoints,hardness:this.hardness,brokenThreshold:hitPoints.brokenThreshold,raised:!1,broken:this.isBroken,destroyed:this.isDestroyed,icon:this.img},actor.rollOptions.all["self:shield:equipped"]=!0,this.isDestroyed?actor.rollOptions.all["self:shield:destroyed"]=!0:this.isBroken&&(actor.rollOptions.all["self:shield:broken"]=!0)}async getChatData(htmlOptions={}){const properties=[this.isArmor?CONFIG.PF2E.armorCategories[this.category]:CONFIG.PF2E.weaponCategories.martial,`${addSign(this.acBonus)} ${game.i18n.localize("PF2E.ArmorArmorLabel")}`,this.isArmor?`${this.system.dexCap||0} ${game.i18n.localize("PF2E.ArmorDexLabel")}`:null,this.isArmor?`${this.system.checkPenalty||0} ${game.i18n.localize("PF2E.ArmorCheckLabel")}`:null,this.speedPenalty?`${this.system.speedPenalty} ${game.i18n.localize("PF2E.ArmorSpeedLabel")}`:null];return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.armorTraits),properties})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const base=this.baseType?CONFIG.PF2E.baseArmorTypes[this.baseType]:null,group=this.group?CONFIG.PF2E.armorGroups[this.group]:null,fallback=this.isShield?"PF2E.ArmorTypeShield":"TYPES.Item.armor",itemType=game.i18n.localize(base??group??fallback);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}async _preCreate(data,options,user){const{category}=this._source.system;return this._source.system.usage.value=category==="shield"?"held-in-one-hand":"wornarmor",super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(changed.system?.category){const usage={value:changed.system.category==="shield"?"held-in-one-hand":"wornarmor"};changed.system=mergeObject(changed.system,{usage})}changed.system?.acBonus!==void 0&&(changed.system.acBonus||=0),changed.system?.group!==void 0&&(changed.system.group||=null);const changedSpecific=changed.system?.specific??{};return changedSpecific.value===!0?(changedSpecific.material=deepClone(this._source.system.material),changedSpecific.runes={potency:Number(this._source.system.potencyRune.value)||0,resilient:resilientRuneValues.get(this._source.system.resiliencyRune.value)||0}):changedSpecific.value===!1&&(changedSpecific["-=material"]=null,changedSpecific["-=runes"]=null),super._preUpdate(changed,options,user)}};__name2(_ArmorPF2e,"ArmorPF2e");let ArmorPF2e=_ArmorPF2e;const _BookPF2e=class extends PhysicalItemPF2e{static{__name(this,"_BookPF2e")}};__name2(_BookPF2e,"BookPF2e");let BookPF2e=_BookPF2e;const _InventoryBulk=class _InventoryBulk2{static{__name(this,"_InventoryBulk")}constructor(actor){__privateAdd(this,_actorStrength),__publicField(this,"actor"),__privateAdd(this,_value,null),__publicField(this,"encumberedAfterAddend",0),__publicField(this,"maxAddend",0),this.actor=actor}get encumberedAfter(){return Math.floor(__privateGet(this,_actorStrength,actorStrength_get)+5+this.encumberedAfterAddend)}get encumberedAfterBreakdown(){const addend=this.encumberedAfterAddend,stat=game.i18n.localize(CONFIG.PF2E.abilities.str);return`5 + ${__privateGet(this,_actorStrength,actorStrength_get)} (${stat})`+(addend?` + ${addend}`:"")}get max(){return Math.floor(__privateGet(this,_actorStrength,actorStrength_get)+10+this.maxAddend)}get maxBreakdown(){const addend=this.maxAddend,stat=game.i18n.localize(CONFIG.PF2E.abilities.str);return`10 + ${__privateGet(this,_actorStrength,actorStrength_get)} (${stat})`+(addend?` + ${addend}`:"")}get value(){return __privateGet(this,_value)?__privateGet(this,_value):(__privateSet(this,_value,_InventoryBulk2.computeTotalBulk(this.actor.inventory.filter(i=>!i.isInContainer),this.actor.size)),__privateGet(this,_value))}get encumberedPercentage(){const totalTimes10=this.value.toLightBulk(),encumberedAtTimes10=this.encumberedAfter*10+10;return Math.floor(totalTimes10/encumberedAtTimes10*100)}get maxPercentage(){const totalTimes10=this.value.toLightBulk(),limitTimes10=this.max*10+10;return Math.floor(totalTimes10/limitTimes10*100)}get maxPercentageInteger(){return this.maxPercentage>100?100:this.maxPercentage}get isEncumbered(){return this.value.normal>this.encumberedAfter}get isOverMax(){return this.value.normal>this.max}get bulk(){return this.value.normal}static computeTotalBulk(items,actorSize){items=__privateMethod(this,_flattenNonStowing,flattenNonStowing_fn).call(this,items);const nonStackingItems=items.filter(i=>i.isOfType("backpack")||i.system.bulk.per===1&&i.system.baseItem),nonStackingIds=new Set(nonStackingItems.map(i=>i.id)),stackingItems=items.filter(i=>!nonStackingIds.has(i.id)),baseBulk=nonStackingItems.map(i=>i.bulk).reduce((first,second)=>first.plus(second),new Bulk),stackingBehaviors=stackingItems.map(item=>({per:item.system.bulk.per,item,group:item.system.baseItem,bulk:new Bulk({light:item.system.bulk.value}).convertToSize(item.size,actorSize)})),bulks=[...groupBy(stackingBehaviors,d=>`${d.group}-${d.per}-${d.bulk.toLightBulk()}`).values()].map(dataEntries=>{const{bulk,per}=dataEntries[0],quantity=dataEntries.map(entry=>entry.item.quantity).reduce((sum2,value)=>sum2+value,0),bulkRelevantQuantity=Math.floor(quantity/per);return bulk.times(bulkRelevantQuantity)});return baseBulk.plus(bulks.reduce((first,second)=>first.plus(second),new Bulk))}};_value=new WeakMap,_actorStrength=new WeakSet,actorStrength_get=__name2(function(){return this.actor.isOfType("character","npc")?this.actor.abilities.str.mod:1/0},"#actorStrength"),_flattenNonStowing=new WeakSet,flattenNonStowing_fn=__name2(function(items){return items.map(item=>item.isOfType("backpack")&&!item.stowsItems?__privateMethod(this,_flattenNonStowing,flattenNonStowing_fn).call(this,item.contents.contents):item).flat()},"#flattenNonStowing"),__privateAdd(_InventoryBulk,_flattenNonStowing),__name2(_InventoryBulk,"InventoryBulk");let InventoryBulk=_InventoryBulk;const _ActorInventory=class extends DelegatedCollection{static{__name(this,"_ActorInventory")}actor;bulk;constructor(actor,entries){super(entries?.map(entry=>[entry.id,entry])),this.actor=actor,this.bulk=new InventoryBulk(this.actor)}get coins(){return this.filter(i=>i.isOfType("treasure")&&i.isCoinage).map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e)}get totalWealth(){return this.filter(item=>game.user.isGM||item.isIdentified).map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e)}get invested(){return this.actor.isOfType("character")?{value:this.filter(item=>!!item.isInvested).length,max:this.actor.system.resources.investiture.max}:null}findStackableItem(item){const testItem=item instanceof PhysicalItemPF2e?item.clone():new ItemProxyPF2e(deepClone(item));if(!testItem.isOfType("physical"))return null;const stackCandidates=this.filter(i=>!i.isInContainer&&i.isStackableWith(testItem));if(stackCandidates.length===0)return null;if(stackCandidates.length>1){const notEquipped=stackCandidates.filter(item2=>!item2.isEquipped);return notEquipped.length>0?notEquipped[0]:stackCandidates[0]}else return stackCandidates[0]}async addCoins(coins,{combineStacks=!0}={}){const topLevelCoins=this.actor.itemTypes.treasure.filter(item=>combineStacks&&item.isCoinage),coinsByDenomination=groupBy(topLevelCoins,item=>item.denomination);for(const denomination of DENOMINATIONS){const quantity=coins[denomination]??0;if(quantity>0){const item=coinsByDenomination.get(denomination)?.at(0);if(item)await item.update({"system.quantity":item.quantity+quantity});else{const compendiumId=coinCompendiumIds[denomination],pack=game.packs.find(p=>p.collection==="pf2e.equipment-srd");if(!pack)throw ErrorPF2e("Unexpected error retrieving equipment compendium");const item2=(await pack.getDocument(compendiumId))?.clone();item2?.isOfType("treasure")&&(item2.updateSource({"system.quantity":quantity}),await this.actor.createEmbeddedDocuments("Item",[item2.toObject()]))}}}}async removeCoins(coins,{byValue=!0}={}){const coinsToRemove=new CoinsPF2e(coins),actorCoins=this.coins,coinsToAdd=new CoinsPF2e;if(byValue){let valueToRemoveInCopper=coinsToRemove.copperValue;if(valueToRemoveInCopper>actorCoins.copperValue)return!1;if(valueToRemoveInCopper%10>actorCoins.cp)coinsToAdd.cp=10,coinsToRemove.cp=valueToRemoveInCopper%10,valueToRemoveInCopper+=10-coinsToRemove.cp;else{coinsToRemove.cp=valueToRemoveInCopper%10,valueToRemoveInCopper-=coinsToRemove.cp;const newCopper=actorCoins.cp-coinsToRemove.cp,extraCopper=Math.min(valueToRemoveInCopper/10,Math.trunc(newCopper/10))*10;coinsToRemove.cp+=extraCopper,valueToRemoveInCopper-=extraCopper}if(valueToRemoveInCopper/10%10>actorCoins.sp)coinsToAdd.sp=10,coinsToRemove.sp=valueToRemoveInCopper/10%10,valueToRemoveInCopper+=100-coinsToRemove.sp*10;else{coinsToRemove.sp=valueToRemoveInCopper/10%10,valueToRemoveInCopper-=coinsToRemove.sp*10;const newSilver=actorCoins.sp-coinsToRemove.sp,extraSilver=Math.min(valueToRemoveInCopper/100,Math.trunc(newSilver/10))*10;coinsToRemove.sp+=extraSilver,valueToRemoveInCopper-=extraSilver*10}if(valueToRemoveInCopper/100%10>actorCoins.gp)coinsToAdd.gp=10,coinsToRemove.gp=valueToRemoveInCopper/100%10,valueToRemoveInCopper+=1e3-coinsToRemove.gp*100;else{coinsToRemove.gp=valueToRemoveInCopper/100%10,valueToRemoveInCopper-=coinsToRemove.gp*100;const newGold=actorCoins.gp-coinsToRemove.gp,extraGold=Math.min(valueToRemoveInCopper/1e3,Math.trunc(newGold/10))*10;coinsToRemove.gp+=extraGold,valueToRemoveInCopper-=extraGold*100}coinsToRemove.pp=valueToRemoveInCopper/1e3}const coinsToPull=actorCoins.add(coinsToAdd);if(!(coinsToRemove.pp<=coinsToPull.pp&&coinsToRemove.gp<=coinsToPull.gp&&coinsToRemove.sp<=coinsToPull.sp&&coinsToRemove.cp<=coinsToPull.cp))return!1;Object.values(coinsToAdd).some(value=>value!==0)&&await this.addCoins(coinsToAdd);const topLevelCoins=this.actor.itemTypes.treasure.filter(item=>item.isCoinage),coinsByDenomination=groupBy(topLevelCoins,item=>item.denomination);for(const denomination of DENOMINATIONS){let quantityToRemove=coinsToRemove[denomination];const coinItems=coinsByDenomination.get(denomination);if(quantityToRemove&&coinItems){const itemsToUpdate=[],itemsToDelete=[];for(const item of coinItems){if(quantityToRemove===0)break;if(item.quantity>quantityToRemove){itemsToUpdate.push({_id:item.id,"system.quantity":item.quantity-quantityToRemove}),quantityToRemove=0;break}else quantityToRemove-=item.quantity,itemsToDelete.push(item.id)}itemsToUpdate.length>0&&await this.actor.updateEmbeddedDocuments("Item",itemsToUpdate),itemsToDelete.length>0&&await this.actor.deleteEmbeddedDocuments("Item",itemsToDelete),quantityToRemove>0&&console.warn("Attempted to remove more coinage than exists")}}return!0}async sellAllTreasure(){const treasures=this.actor.itemTypes.treasure.filter(item=>!item.isCoinage),treasureIds=treasures.map(item=>item.id),coins=treasures.map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e);await this.actor.deleteEmbeddedDocuments("Item",treasureIds),await this.actor.inventory.addCoins(coins)}async add(item,options={}){if(options.stack&&item.isOfType("physical")){const stackableItem=this.findStackableItem(item._source);if(stackableItem){await stackableItem.update({"system.quantity":stackableItem.quantity+item.quantity});return}}await this.actor.createEmbeddedDocuments("Item",[item.toObject()])}};__name2(_ActorInventory,"ActorInventory");let ActorInventory=_ActorInventory;const _ContainerPF2e=class extends PhysicalItemPF2e{static{__name(this,"_ContainerPF2e")}contents=new Collection;get stowsItems(){return this.system.stowing}get isCollapsed(){return this.system.collapsed}get capacity(){return{value:InventoryBulk.computeTotalBulk(this.contents.contents,this.actor?.size??"med"),max:weightToBulk(this.system.bulkCapacity.value)||new Bulk}}get capacityPercentage(){const{value,max}=this.capacity;return Math.min(100,Math.floor(value.toLightBulk()/max.toLightBulk()*100))}get bulk(){const reduction=!this.traits.has("extradimensional")||!hasExtraDimensionalParent(this)?weightToBulk(this.system.negateBulk.value):new Bulk;return super.bulk.plus(this.capacity.value.minus(reduction??new Bulk))}prepareSiblingData(){this.contents=new Collection(this.actor.inventory.filter(i=>i.container?.id===this.id).map(item=>[item.id,item]))}async ejectContents(){if(!this.actor)return;const updates=this.contents.map(i=>({_id:i.id,"system.containerId":this.container?.id??null}));await this.actor.updateEmbeddedDocuments("Item",updates,{render:!1})}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.equipmentTraits)})}};__name2(_ContainerPF2e,"ContainerPF2e");let ContainerPF2e=_ContainerPF2e;const _EquipmentPF2e=class extends PhysicalItemPF2e{static{__name(this,"_EquipmentPF2e")}get otherTags(){return new Set(this.system.traits.otherTags)}prepareBaseData(){super.prepareBaseData(),this.system.apex&&(this.traits.has("apex")?this.isInvested||(this.system.apex.selected=!1):delete this.system.apex)}prepareSiblingData(){if(super.prepareSiblingData(),!this.system.apex)return;const otherApexData=this.actor.itemTypes.equipment.flatMap(e=>e===this?[]:e.system.apex??[]);if(this.system.apex.selected||this.isInvested&&otherApexData.every(d=>!d.selected)){this.system.apex.selected=!0;for(const data of otherApexData)data.selected=!1}}prepareActorData(){const{actor}=this;actor?.isOfType("character")&&this.system.apex?.selected&&(actor.system.build.attributes.apex?this.system.apex.selected=!1:actor.system.build.attributes.apex=this.system.apex.attribute)}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.equipmentTraits)})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const identificationConfig=CONFIG.PF2E.identification,slotType=/book\b/.test(this.slug??"")?"Book":/\bring\b/.test(this.slug??"")?"Ring":this.system.usage.value?.replace(/^worn/,"").capitalize()??"",itemType=objectHasKey(identificationConfig.UnidentifiedType,slotType)?game.i18n.localize(identificationConfig.UnidentifiedType[slotType]):game.i18n.localize(identificationConfig.UnidentifiedType.Object);return typeOnly?itemType:game.i18n.format(identificationConfig.UnidentifiedItem,{item:itemType})}async _preCreate(data,options,user){return delete this._source.system.apex?.selected,super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const changedTraits=changed.system?.traits?.value;return!(this._source.system.traits.value.includes("apex")&&(!Array.isArray(changedTraits)||changedTraits.includes("apex")))&&this._source.system.apex&&(delete changed.system?.apex,changed.system??={},changed.system=mergeObject(changed.system,{"-=apex":null})),super._preUpdate(changed,options,user)}};__name2(_EquipmentPF2e,"EquipmentPF2e");let EquipmentPF2e=_EquipmentPF2e;const _TreasurePF2e=class extends PhysicalItemPF2e{static{__name(this,"_TreasurePF2e")}get isCoinage(){return this.system.stackGroup==="coins"}get denomination(){if(!this.isCoinage)return null;const options=DENOMINATIONS.filter(denomination=>!!this.price.value[denomination]);return options.length===1?options[0]:null}prepareBaseData(){super.prepareBaseData(),this.isCoinage&&(this.system.size="med")}async getChatData(htmlOptions={}){const systemData=this.system,traits=this.traitChatData({});return this.processChatData(htmlOptions,{...systemData,traits})}};__name2(_TreasurePF2e,"TreasurePF2e");let TreasurePF2e=_TreasurePF2e;const _WeaponPF2e=class _WeaponPF2e2 extends PhysicalItemPF2e{static{__name(this,"_WeaponPF2e")}altUsageType=null;get isEquipped(){const{category,slug,traits}=this.system;return category==="unarmed"&&slug!=="handwraps-of-mighty-blows"?!0:super.isEquipped||this.handsHeld===1&&traits.value.some(t=>/^jousting-d\d{1,2}$/.test(t))}isStackableWith(item){if(this.category==="unarmed"||!item.isOfType("weapon")||item.category==="unarmed")return!1;const equippedButStackable=["bomb","dart"].includes(this.group??"");return(this.isEquipped||item.isEquipped)&&!equippedButStackable?!1:super.isStackableWith(item)}get baseType(){return this.system.baseItem}get group(){return this.system.group}get category(){return this.system.category}get defaultAttribute(){return this.system.attribute??(this.isRanged?"dex":"str")}get hands(){return{worngloves:"0","held-in-one-hand":"1","held-in-one-plus-hands":"1+","held-in-two-hands":"2"}[this.system.usage.value]??"1"}get maxRange(){return this.system.maxRange??(this.system.range?this.system.range*6:null)}get range(){const rangeIncrement=this.system.range,maxRange=this.system.maxRange;return maxRange?{increment:null,max:maxRange}:rangeIncrement?{increment:rangeIncrement,max:rangeIncrement*6}:null}get reload(){return this.system.reload.value||null}get isSpecific(){return this.system.specific?.value??!1}get isMelee(){return!this.isRanged}get isRanged(){return!!this.system.range}get isThrown(){return this.isRanged&&(this.baseType==="alchemical-bomb"||this.system.traits.value.includes("thrown"))}get isThrowable(){return this.isThrown||this.system.traits.value.some(t=>t.startsWith("thrown"))||!!this.system.meleeUsage?.traits.some(t=>t.startsWith("thrown"))}get isOversized(){return this.category!=="unarmed"&&!!this.parent?.system.traits?.size.isSmallerThan(this.size,{smallIsMedium:!0})}get baseDamage(){return{...deepClone(this.system.damage),damageType:this.system.traits.toggles.versatile.selection??this.system.traits.toggles.modular.selection??this.system.damage.damageType}}get dealsDamage(){const{baseDamage}=this;return baseDamage.dice>0||baseDamage.modifier>0||this.system.splashDamage.value>0||!!baseDamage.persistent?.number}get requiresAmmo(){return this.isRanged&&!this.isThrown&&![null,"-"].includes(this.reload)}get ammo(){const ammo=this.actor?.items.get(this.system.selectedAmmoId??"");return ammo?.isOfType("consumable","weapon")&&ammo.quantity>0?ammo:null}get otherTags(){return new Set(this.system.traits.otherTags)}isAmmoFor(weapon){return this.system.usage.canBeAmmo&&!weapon.system.traits.value.includes("repeating")}getRollOptions(prefix=this.type){const{baseDamage}=this,damage={category:DamageCategorization.fromDamageType(baseDamage.damageType),type:baseDamage.damageType,dice:{number:baseDamage.die?baseDamage.dice:0,faces:Number(baseDamage.die?.replace(/^d/,""))}},{actor}=this,isDeityFavored=!!(this.baseType&&actor?.isOfType("character")&&actor.deity?.favoredWeapons.includes(this.baseType)),thrownMelee=this.isThrown&&this.altUsageType==="thrown",baseTypeRollOptions=(()=>{const equivalentBases=CONFIG.PF2E.equivalentWeapons;return[this.baseType??[],equivalentBases[this.baseType??""]??[]].flat().reduce((types,t)=>({...types,[`base:${t}`]:!0}),{})})(),{persistent}=this.system.damage,propertyRunes=mapToObj(this.system.runes.property,p=>[`rune:property:${sluggify(p)}`,!0]),ammunitionRollOptions=(ammunition=>{const rollOptions={};if(ammunition){rollOptions[`ammo:id:${ammunition.id}`]=!0,rollOptions[`ammo:slug:${ammunition.slug}`]=!0,rollOptions[`ammo:level:${ammunition.level}`]=!0,rollOptions[`ammo:material:type:${ammunition.material.type}`]=!!ammunition.material.type,rollOptions[`ammo:material:grade:${ammunition.material.grade}`]=!!ammunition.material.grade;for(const trait of ammunition.traits)rollOptions[`ammo:trait:${trait}`]=!0}return rollOptions})(this.ammo),bulk=(()=>{const unitBulk=this.bulk.times(1/this.quantity);return unitBulk.isNegligible?"negligible":unitBulk.isLight?"light":unitBulk.toString()})(),rangeIncrement=this.range?.increment;return[super.getRollOptions(prefix),Object.entries({[`category:${this.category}`]:!0,[`group:${this.group}`]:!!this.group,...baseTypeRollOptions,[`base:${this.baseType}`]:!!this.baseType,[`bulk:${bulk}`]:!0,[`hands-held:${this.handsHeld}`]:this.isEquipped&&this.handsHeld>0,[`usage:hands:${this.hands}`]:this.hands!=="0",[`range-increment:${rangeIncrement}`]:!!rangeIncrement,[`reload:${this.reload}`]:!!this.reload,[`damage:type:${damage.type}`]:!0,[`damage:category:${damage.category}`]:!!damage.category,[`damage:die:number:${damage.dice.number}`]:!!damage.dice.faces,[`damage:die:faces:${damage.dice.faces}`]:!!damage.dice.faces,[`damage-dice:${damage.dice.number}`]:!!damage.dice.faces,[`damage:persistent:${persistent?.type}`]:!!persistent,"deity-favored":isDeityFavored,oversized:this.isOversized,melee:this.isMelee,ranged:this.isRanged,thrown:this.isThrown,"thrown-melee":thrownMelee,...propertyRunes,...ammunitionRollOptions}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`)].flat().sort()}prepareBaseData(){super.prepareBaseData();const systemData=this.system;systemData.category||="simple",systemData.group||=null,systemData.baseItem||=null,systemData.bonusDamage.value||=0,systemData.splashDamage.value||=0,systemData.potencyRune.value||=null,systemData.strikingRune.value||=null,systemData.propertyRune1.value||=null,systemData.propertyRune2.value||=null,systemData.propertyRune3.value||=null,systemData.propertyRune4.value||=null,systemData.graspingAppendage=["fist","claw"].includes(this.baseType??"")?!0:this.category==="unarmed"?!!systemData.graspingAppendage:!1,setHasElement(ATTRIBUTE_ABBREVIATIONS,systemData.attribute)||(systemData.attribute=null);const reloadValue=systemData.reload.value||=null;systemData.reload.label=reloadValue?game.i18n.format("PF2E.Item.Weapon.Reload.LabelN",{value:CONFIG.PF2E.weaponReload[reloadValue]}):null,systemData.selectedAmmoId||=null,systemData.damage.die||=null,systemData.damage.modifier??=0,!systemData.damage.die&&systemData.damage.dice>0&&(systemData.damage.modifier||=systemData.damage.dice),this.isThrown&&!tupleHasValue(["-","0"],this.system.reload.value)&&(this.system.reload.value="-"),systemData.category==="unarmed"&&!systemData.traits.value.includes("unarmed")&&systemData.traits.value.push("unarmed");const traitSet=this.traits,mandatoryRanged=setHasElement(MANDATORY_RANGED_GROUPS,systemData.group)||traitSet.has("thrown");if(mandatoryRanged){this.system.range??=10;const{otherTags}=systemData.traits;this.group==="bow"&&setHasElement(CROSSBOW_WEAPONS,this.baseType)&&!otherTags.includes("crossbow")&&systemData.traits.otherTags.push("crossbow")}this.system.meleeUsage&&(this.system.meleeUsage.traits??=[],this.system.meleeUsage.traitToggles??={modular:null,versatile:null}),systemData.traits.toggles=new WeaponTraitToggles(this);const traitsArray=systemData.traits.value;systemData.category==="unarmed"&&!traitsArray.includes("unarmed")&&systemData.traits.value.push("unarmed"),!mandatoryRanged&&traitsArray.some(t=>/^thrown-\d+$/.test(t))&&(this.system.range=null),systemData.reload.consume=this.isMelee?null:this.reload!==null,systemData.usage.canBeAmmo=this._source.system.usage.canBeAmmo??!1,this.flags.pf2e.comboMeleeUsage??=!1,this.prepareRunes();const baseTraits=this.system.traits.value,{runes}=this.system,hasRunes=runes.potency>0||runes.striking>0||runes.property.length>0,magicTraits=baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t))?["evocation"]:hasRunes?["evocation","magical"]:[];this.system.traits.value=uniq([baseTraits,magicTraits].flat()).sort(),this.flags.pf2e.attackItemBonus=this.system.runes.potency||this.system.bonus.value||0}prepareRunes(){AutomaticBonusProgression.cleanupRunes(this);const{potencyRune,strikingRune,propertyRune1,propertyRune2,propertyRune3,propertyRune4}=this.system,strikingRuneDice=new Map([["striking",1],["greaterStriking",2],["majorStriking",3]]),runes=this.system.runes={potency:potencyRune.value??0,striking:strikingRuneDice.get(strikingRune.value)??0,property:prunePropertyRunes([propertyRune1.value,propertyRune2.value,propertyRune3.value,propertyRune4.value],RUNE_DATA.weapon.property),effects:[]},maxPropertySlots=getPropertySlots(this);runes.property.length=Math.min(runes.property.length,maxPropertySlots);const{actor}=this,inherentDiceNumber=this.system.damage.die?this._source.system.damage.dice:0,strikingDice=AutomaticBonusProgression.isEnabled(actor)?AutomaticBonusProgression.getStrikingDice(actor?.level??0):this.system.runes.striking;this.system.damage.dice=inherentDiceNumber===1&&!this.flags.pf2e.battleForm?inherentDiceNumber+strikingDice:this.system.damage.dice}prepareDerivedData(){super.prepareDerivedData(),this.system.usage.canBeAmmo&&!this.isThrowable&&(this.system.usage.canBeAmmo=!1)}prepareSiblingData(){super.prepareSiblingData();const ammoRules=this.ammo?.system.rules.map(r=>({label:this.ammo?.name,...deepClone(r)}))??[];this.system.rules.push(...ammoRules)}async getChatData(htmlOptions={}){const traits=this.traitChatData(CONFIG.PF2E.weaponTraits),chatData=await super.getChatData(),rangeLabel=createActionRangeLabel(this.range),properties=compact([CONFIG.PF2E.weaponCategories[this.category],this.system.reload.label,rangeLabel]);return this.processChatData(htmlOptions,{...chatData,traits,properties})}getMystifiedData(status,{source=!1}={}){const mystifiedData=super.getMystifiedData(status);return source&&(mystifiedData.name=this._source.name),mystifiedData}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const base=this.baseType?CONFIG.PF2E.baseWeaponTypes[this.baseType]:null,group=this.group?CONFIG.PF2E.weaponGroups[this.group]:null,itemType=game.i18n.localize(base??group??"TYPES.Item.weapon");return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}getAltUsages({recurse=!0}={}){const meleeUsage=this.toMeleeUsage();return[this.toThrownUsage()??[],meleeUsage??[],recurse?meleeUsage?.toThrownUsage()??[]:[]].flat()}clone(data,context){const clone=super.clone(data,context);return context?.altUsage&&clone instanceof _WeaponPF2e2&&(clone.altUsageType=context.altUsage),clone}toThrownUsage(){const traits=this._source.system.traits.value,thrownTrait=traits.find(t=>/^thrown-\d{1,3}$/.test(t));if(this.isRanged||!thrownTrait)return null;const range=Number(/(\d{1,3})$/.exec(thrownTrait).at(1)),newTraits=deepClone(traits);newTraits.splice(newTraits.indexOf(thrownTrait),1,"thrown");const overlay={system:{range,traits:{value:newTraits}}};return this.clone(overlay,{keepId:!0,altUsage:"thrown"})}toMeleeUsage(){const{meleeUsage}=this.system;if(!meleeUsage||this.flags.pf2e.comboMeleeUsage)return null;const traitToggles={module:{selection:meleeUsage.traitToggles.modular},versatile:{selection:meleeUsage.traitToggles.versatile}},overlay={system:{damage:{damageType:meleeUsage.damage.type,dice:1,die:meleeUsage.damage.die},group:meleeUsage.group,range:null,reload:{value:null},traits:{value:meleeUsage.traits.concat("combination"),toggles:traitToggles},selectedAmmoId:null},flags:{pf2e:{comboMeleeUsage:!0}}};return this.clone(overlay,{keepId:!0,altUsage:"melee"})}toNPCAttacks({keepId=!1}={}){const{actor}=this;if(!actor.isOfType("npc"))throw ErrorPF2e("Melee items can only be generated for NPCs");const baseDamage=(()=>{const weaponDamage=this.baseDamage,ability=this.range?.increment&&!this.isThrown?"dex":"str",actorLevel=actor.system.details.level.base,dice=this.flags.pf2e.fixedAttack?weaponDamage.dice:[1,2,3,4].reduce((closest,dice2)=>Math.abs(dice2-Math.round((actorLevel+2)/4)){const fromAbility=actor.abilities[ability].mod,totalModifier=this.flags.pf2e.fixedAttack?weaponDamage.modifier:fromAbility+(actor.level>1?dice:0),sign=totalModifier<0?"-":"+";return totalModifier===0?"":[sign,Math.abs(totalModifier)].join("")})();return{damage:weaponDamage.die?`${dice}${weaponDamage.die}${constant}`:dice.toString(),damageType:weaponDamage.damageType,category:null}})(),fromPropertyRunes=this.system.runes.property.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.dice??[]).map(d=>({damage:`${d.diceNumber}${d.dieSize}`,damageType:d.damageType??baseDamage.damageType,category:d.category??null})),reachTraitToNPCReach={tiny:null,sm:"reach-10",med:"reach-10",lg:"reach-15",huge:"reach-20",grg:"reach-25"},toAttackTraits=__name2(traits=>{const{increment:rangeIncrement,max:maxRange}=this.range??{},newTraits=traits.flatMap(t=>t==="reach"?reachTraitToNPCReach[this.size]??[]:t==="thrown"&&setHasElement(THROWN_RANGES,rangeIncrement)?`thrown-${rangeIncrement}`:t).filter(t=>!(t in CONFIG.PF2E.creatureTraits)&&!setHasElement(MAGIC_TRADITIONS,t)&&!setHasElement(MAGIC_SCHOOLS,t)&&!(t.startsWith("thrown")&&!this.isThrown)&&!(["grapple","finesse","shove","trip"].includes(t)&&this.isRanged)&&!(t==="brutal"&&this.isMelee)&&!(t==="combination"&&(this.isMelee||this.isThrown))&&!(t==="critical-fusion"&&this.isThrown)&&!["artifact","cursed"].includes(t));if(rangeIncrement&&!this.isThrown){const prefix=maxRange===rangeIncrement*6?"range-increment":"range";newTraits.push(`${prefix}-${rangeIncrement}`)}const sizeToReach=SIZE_TO_REACH[actor.size];this.isMelee&&sizeToReach!==5&&!newTraits.some(t=>t.startsWith("reach"))&&newTraits.push(`reach-${sizeToReach}`);const reloadTrait=`reload-${this.reload}`;return objectHasKey(CONFIG.PF2E.npcAttackTraits,reloadTrait)&&newTraits.push(reloadTrait),newTraits.sort()},"toAttackTraits"),persistentDamage=(()=>{const{persistent}=this.system.damage;return persistent?{damage:persistent.faces?`${persistent.number}d${persistent.faces}`:persistent.number.toString(),damageType:persistent.type,category:"persistent"}:[]})(),splashDamage=this.system.splashDamage.value?{damage:this.system.splashDamage.value.toString(),damageType:this.system.damage.damageType,category:"splash"}:[],source={_id:keepId?this.id:null,name:this._source.name,type:"melee",system:{slug:this.slug??sluggify(this._source.name),weaponType:{value:this.isMelee?"melee":"ranged"},bonus:{value:this.flags.pf2e.fixedAttack||Math.round(1.5*this.actor.level+7)},damageRolls:[baseDamage,splashDamage,fromPropertyRunes,persistentDamage].flat().reduce((rolls,roll)=>mergeObject(rolls,{[randomID()]:roll}),{}),traits:{value:toAttackTraits(this.system.traits.value)},rules:deepClone(this._source.system.rules)},flags:{pf2e:{linkedWeapon:this.id}}},attack=new MeleePF2e(source,{parent:this.actor});return attack.category=this.category,attack.group=this.group,attack.baseType=this.baseType,[attack,...this.getAltUsages({recurse:!1}).flatMap(u=>u.toNPCAttacks())]}async consumeAmmo(){const{ammo}=this;if(ammo?.isOfType("consumable"))return ammo.consume();if(ammo?.isOfType("weapon")){if(!ammo.system.usage.canBeAmmo)throw ErrorPF2e("attempted to consume weapon not usable as ammunition");await ammo.update({"system.quantity":Math.max(ammo.quantity-1,0)})}}_preUpdate(changed,options,user){const traits=changed.system?.traits??{};return"value"in traits&&Array.isArray(traits.value)&&(traits.value=traits.value.filter(t=>t in CONFIG.PF2E.weaponTraits)),changed.system?.group!==void 0&&(changed.system.group||=null),super._preUpdate(changed,options,user)}_onDelete(options,userId){if(super._onDelete(options,userId),game.user.id===userId){const updates=this.actor?.itemTypes.melee.filter(a=>a.flags.pf2e.linkedWeapon===this.id).map(a=>({_id:a.id,"flags.pf2e.-=linkedWeapon":null}))??[];this.actor?.updateEmbeddedDocuments("Item",updates)}}};__name2(_WeaponPF2e,"WeaponPF2e");let WeaponPF2e=_WeaponPF2e;const _ABCItemPF2e=class extends ItemPF2e{static{__name(this,"_ABCItemPF2e")}get rarity(){return this.system.traits.rarity}getLinkedItems(){if(!this.actor||!objectHasKey(this.actor.itemTypes,this.type))return[];const existingABCIds=this.actor.itemTypes[this.type].map(i=>i.id);return this.actor.itemTypes.feat.filter(f=>existingABCIds.includes(f.system.location??""))}async createGrantedItems(options={}){const entries=Object.values(this.system.items);if(!entries.filter(entry=>!!entry.uuid).length)return[];const items=(await UUIDUtils.fromUUIDs(entries.map(e=>e.uuid))).map(i=>i.clone()),level=options.level??this.parent?.level;return items.flatMap(item=>{if(item instanceof FeatPF2e){if(item.category==="classfeature"){const level2=entries.find(e=>item.sourceId===e.uuid)?.level??item.level;item.updateSource({"system.level.value":level2})}return level!==void 0&&levelboost.value.length===1).map(boost=>boost.selected).filter(boost=>!!boost)}get lockedFlaws(){return Object.values(this.system.flaws).map(flaw=>flaw.selected).filter(flaw=>!!flaw)}getLinkedItems(){return this.actor?Array.from(new Set([...super.getLinkedItems(),...this.actor.itemTypes.feat.filter(f=>f.category==="ancestryfeature")])):[]}prepareBaseData(){super.prepareBaseData();for(const boost of Object.values(this.system.boosts))boost.value.length===1&&(boost.selected=boost.value[0]);for(const flaw of Object.values(this.system.flaws))flaw.value.length===1&&(flaw.selected=flaw.value[0])}prepareActorData(){const{actor}=this;if(!actor.isOfType("character")){console.error("PF2e System | Only a character can have an ancestry");return}actor.ancestry=this,actor.system.attributes.ancestryhp=this.hitPoints,this.logAutoChange("system.attributes.ancestryhp",this.hitPoints),actor.system.traits.size.value=this.size,this.logAutoChange("system.traits.size.value",this.size);const reach=SIZE_TO_REACH[this.size];actor.system.attributes.reach={base:reach,manipulate:reach},actor.system.attributes.speed.value=this.speed;const{build}=actor.system;if(this.system.alternateAncestryBoosts)build.attributes.boosts.ancestry.push(...this.system.alternateAncestryBoosts);else for(const target of["boosts","flaws"])for(const ability of Object.values(this.system[target]))ability.selected&&build.attributes[target].ancestry.push(ability.selected);if(this.system.voluntary){const{boost,flaws}=this.system.voluntary;boost&&build.attributes.boosts.ancestry.push(boost),build.attributes.flaws.ancestry.push(...flaws)}const innateLanguages=this.system.languages.value;for(const language of innateLanguages)language in CONFIG.PF2E.languages&&!actor.system.traits.languages.value.includes(language)&&actor.system.traits.languages.value.push(language);const{senses:senses2}=actor.system.traits,{vision}=this.system;if(!(vision==="normal"||senses2.some(sense=>sense.type===vision))){senses2.push(new CreatureSensePF2e({type:vision,value:"",source:this.name}));const senseRollOptions=actor.rollOptions.sense??={};senseRollOptions[`self:${sluggify(vision)}:from-ancestry`]=!0}actor.system.traits.value.push(...this.traits);const slug=this.slug??sluggify(this.name);actor.system.details.ancestry={name:this.name,trait:slug,adopted:null,versatile:null,countsAs:[slug]},actor.rollOptions.all[`self:ancestry:${slug}`]=!0;for(const trait of this.traits)actor.rollOptions.all[`self:trait:${trait}`]=!0}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),`${prefix}:rarity:${this.rarity}`]}};__name2(_AncestryPF2e,"AncestryPF2e");let AncestryPF2e=_AncestryPF2e;const _BackgroundPF2e=class extends ABCItemPF2e{static{__name(this,"_BackgroundPF2e")}get traits(){return new Set(this.system.traits.value)}prepareSiblingData(){if(Object.keys(this.system.items).length>0)return;const grantedSkillFeat=Object.values(this.flags.pf2e.itemGrants).flatMap(g=>this.actor.items.get(g.id)??[]).find(i=>i.isOfType("feat")&&i.category==="skill");grantedSkillFeat&&(this.system.items.GRANT={uuid:grantedSkillFeat.sourceId??grantedSkillFeat.uuid,img:grantedSkillFeat.img,name:grantedSkillFeat.name,level:1},grantedSkillFeat.system.level.taken=1,grantedSkillFeat.system.location=this.id)}prepareActorData(){if(!this.actor.isOfType("character")){console.error("Only a character can have a background");return}this.actor.background=this;const{build}=this.actor.system,boosts=Object.values(this.system.boosts);for(const boost of boosts)boost.selected&&build.attributes.boosts.background.push(boost.selected);const{trainedSkills}=this.system;if(trainedSkills.value.length===1){const key=trainedSkills.value[0],skill=this.actor.system.skills[key];skill.rank=Math.max(skill.rank,1)}}};__name2(_BackgroundPF2e,"BackgroundPF2e");let BackgroundPF2e=_BackgroundPF2e;const _ClassPF2e=class extends ABCItemPF2e{static{__name(this,"_ClassPF2e")}get attacks(){return this.system.attacks}get defenses(){return this.system.defenses}get classDC(){return this.system.classDC}get hpPerLevel(){return this.system.hp}get perception(){return this.system.perception}get savingThrows(){return this.system.savingThrows}get grantedFeatSlots(){const actorLevel=this.actor?.level??0,system=this.system,ancestryLevels=deepClone(system.ancestryFeatLevels.value);if(game.settings.get("pf2e","ancestryParagonVariant")){ancestryLevels.unshift({id:"ancestry-bonus",level:1,label:"1"});for(let level=3;level<=actorLevel;level+=4){const index=(level+1)/2;ancestryLevels.splice(index,0,level)}}return{ancestry:ancestryLevels,class:[...system.classFeatLevels.value],skill:[...system.skillFeatLevels.value],general:[...system.generalFeatLevels.value]}}getLinkedItems(){const{actor}=this;return actor?Array.from(new Set([...super.getLinkedItems(),...actor.itemTypes.feat.filter(f=>f.category==="classfeature"&&!(f.flags.pf2e.grantedBy&&actor.items.has(f.flags.pf2e.grantedBy.id)))])):[]}async createGrantedItems(options={}){const hasChoiceSet=__name2(f=>f.system.rules.some(re=>re.key==="ChoiceSet"),"hasChoiceSet");return(await super.createGrantedItems(options)).sort((a,b)=>{const[aLevel,bLevel]=[a.system.level.value,b.system.level.value];if(aLevel!==bLevel)return aLevel-bLevel;const[aHasSet,bHasSet]=[hasChoiceSet(a),hasChoiceSet(b)];return aHasSet!==bHasSet?aHasSet?-1:1:a.name.localeCompare(b.name,game.i18n.lang)})}prepareBaseData(){super.prepareBaseData();const{keyAbility}=this.system;keyAbility.selected??=keyAbility.value.length===1?keyAbility.value[0]:null}prepareActorData(){if(!this.actor?.isOfType("character")){console.error("Only a character can have a class");return}this.actor.class=this;const{attributes,build,details,proficiencies,saves,skills}=this.actor.system,slug=this.slug??sluggify(this.name);build.attributes.keyOptions=[...this.system.keyAbility.value],build.attributes.boosts.class=this.system.keyAbility.selected,attributes.classhp=this.hpPerLevel,attributes.perception.rank=Math.max(attributes.perception.rank,this.perception),this.logAutoChange("system.attributes.perception.rank",this.perception),details.keyability.value=(build.attributes.manual?details.keyability.value:build.attributes.boosts.class)??"str";const classDCs=proficiencies.classDCs;classDCs[slug]={label:this.name,rank:this.classDC,ability:details.keyability.value,primary:!0},this.logAutoChange(`system.proficiencies.classDCs.${slug}.rank`,this.classDC);const{attacks,defenses}=proficiencies;for(const category of WEAPON_CATEGORIES)attacks[category].rank=Math.max(attacks[category].rank,this.attacks[category]),this.logAutoChange(`system.proficiencies.attacks.${category}.rank`,this.attacks[category]);const nonBarding=Array.from(ARMOR_CATEGORIES).filter(c=>!["light-barding","heavy-barding"].includes(c));for(const category of nonBarding)defenses[category].rank=Math.max(defenses[category].rank,this.defenses[category]),this.logAutoChange(`system.proficiencies.defenses.${category}.rank`,this.defenses[category]);for(const saveType of SAVE_TYPES)saves[saveType].rank=Math.max(saves[saveType].rank,this.savingThrows[saveType]),this.logAutoChange(`system.saves.${saveType}.rank`,this.savingThrows[saveType]);for(const trainedSkill of this.system.trainedSkills.value)setHasElement(SKILL_ABBREVIATIONS,trainedSkill)&&(skills[trainedSkill].rank=Math.max(skills[trainedSkill].rank,1));details.class={name:this.name,trait:slug},this.actor.rollOptions.all[`class:${slug}`]=!0}};__name2(_ClassPF2e,"ClassPF2e");let ClassPF2e=_ClassPF2e;const _AbilityItemPF2e=class extends ItemPF2e{static{__name(this,"_AbilityItemPF2e")}range=null;get traits(){return new Set(this.system.traits.value)}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}prepareBaseData(){super.prepareBaseData(),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max),this.system.selfEffect??=null,this.system.actionType.value==="passive"&&(this.system.selfEffect=null)}getRollOptions(prefix=this.type){const options=super.getRollOptions(prefix);return(this.frequency||this.system.deathNote)&&options.push(`${prefix}:frequency:limited`),options}async getChatData(htmlOptions={}){const systemData=this.system,properties=[getActionTypeLabel(this.actionCost?.type,this.actionCost?.value)??[]].flat(),traits=this.traitChatData(CONFIG.PF2E.featTraits);return this.processChatData(htmlOptions,{...systemData,properties,traits})}async _preCreate(data,options,user){return this.parent||this._source.system.frequency&&this.updateSource({"system.frequency.-=value":null}),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){return typeof changed.system?.category=="string"&&(changed.system.category||=null),normalizeActionChangeData(this,changed),super._preUpdate(changed,options,user)}};__name2(_AbilityItemPF2e,"AbilityItemPF2e");let AbilityItemPF2e=_AbilityItemPF2e;const _TrickMagicItemPopup=class{static{__name(this,"_TrickMagicItemPopup")}constructor(item){if(__privateAdd(this,_initialize),__privateAdd(this,_handleTrickItem),__publicField(this,"item"),__publicField(this,"checkDC"),__privateAdd(this,_localize2,localizer("PF2E.TrickMagicItemPopup")),!item.isOfType("consumable"))throw ErrorPF2e("Unexpected item used for Trick Magic Item");if(!item.actor?.isOfType("character"))throw ErrorPF2e(__privateGet(this,_localize2).call(this,"InvalidActor"));this.item=item,this.actor=item.actor,this.checkDC=calculateTrickMagicItemCheckDC(item),__privateMethod(this,_initialize,initialize_fn).call(this)}};_localize2=new WeakMap,_initialize=new WeakSet,initialize_fn=__name2(async function(){const buttons=TRICK_MAGIC_SKILLS.filter(skill=>skill in this.checkDC).map(value=>({value,label:game.i18n.localize(`PF2E.Skill${value.capitalize()}`),modifier:this.actor.skills[value].check.mod})).reduce((accumulated,skill)=>{const button={icon:'',label:`${skill.label} (${skill.modifier<0?"":"+"}${skill.modifier})`,callback:()=>__privateMethod(this,_handleTrickItem,handleTrickItem_fn).call(this,skill.value)};return{...accumulated,[skill.value]:button}},{});new Dialog({title:__privateGet(this,_localize2).call(this,"Title"),content:`${__privateGet(this,_localize2).call(this,"Label")}
`,buttons},{classes:["dialog","trick-magic-item"],width:"auto"}).render(!0)},"#initialize"),_handleTrickItem=new WeakSet,handleTrickItem_fn=__name2(function(skill){this.actor.skills[skill].check.roll({extraRollOptions:["action:trick-magic-item"],dc:{value:this.checkDC[skill]??0},item:this.item});const trick=new TrickMagicItemEntry(this.actor,skill);this.item.castEmbeddedSpell(trick)},"#handleTrickItem"),__name2(_TrickMagicItemPopup,"TrickMagicItemPopup");let TrickMagicItemPopup=_TrickMagicItemPopup;const _ConsumablePF2e=class extends PhysicalItemPF2e{static{__name(this,"_ConsumablePF2e")}get otherTags(){return new Set(this.system.traits.otherTags)}get category(){return this.system.consumableType.value}get isAmmunition(){return this.category==="ammo"}get uses(){return{value:this.system.charges.value,max:this.system.charges.max}}get autoDestroy(){return this.system.autoDestroy.value}get embeddedSpell(){if(!this.actor)throw ErrorPF2e(`No owning actor found for "${this.name}" (${this.id})`);return this.system.spell?new SpellPF2e(deepClone(this.system.spell),{parent:this.actor,fromConsumable:!0}):null}get formula(){return this.system.consume.value.trim()||null}prepareBaseData(){if(super.prepareBaseData(),!!this.isAmmunition){for(const rule of this.system.rules)if(rule.key==="RollOption"&&"toggleable"in rule&&rule.toggleable){console.warn("Toggleable RollOption rule elements may not be added to ammunition"),this.system.rules=[];break}else if(["GrantItem","ChoiceSet"].includes(String(rule.key))){console.warn(`${rule.key} rule elements may not be added to ammunition`),this.system.rules=[];break}}}prepareRuleElements(){const rules=super.prepareRuleElements();for(const rule of rules)rule.ignored=!0;return rules}async getChatData(htmlOptions={},rollOptions={}){const traits=this.traitChatData(CONFIG.PF2E.consumableTraits),[consumableType,isUsable]=this.isIdentified?[game.i18n.localize(CONFIG.PF2E.consumableTypes[this.category]),!0]:[this.generateUnidentifiedName({typeOnly:!0}),!["other","scroll","talisman","tool","wand"].includes(this.category)],usesLabel=game.i18n.localize("PF2E.ConsumableChargesLabel"),fromFormula=!!rollOptions.fromFormula;return this.processChatData(htmlOptions,{...await super.getChatData(),traits,properties:this.isIdentified&&this.uses.max>1?[`${this.uses.value}/${this.uses.max} ${usesLabel}`]:[],usesCharges:this.uses.max>0,hasCharges:this.uses.max>0&&this.uses.value>0,consumableType,isUsable:fromFormula?!1:isUsable})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const liquidOrSubstance=__name2(()=>this.traits.has("inhaled")||this.traits.has("contact")?"PF2E.identification.UnidentifiedType.Substance":"PF2E.identification.UnidentifiedType.Liquid","liquidOrSubstance"),itemType=game.i18n.localize(["drug","elixir","mutagen","oil","poison","potion"].includes(this.category)?liquidOrSubstance():["scroll","snare","ammo"].includes(this.category)?CONFIG.PF2E.consumableTypes[this.category]:"PF2E.identification.UnidentifiedType.Object");return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),...Object.entries({[`category:${this.category}`]:!0}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`)]}isAmmoFor(weapon){if(!this.isAmmunition)return!1;if(!(weapon instanceof WeaponPF2e))return console.warn("Cannot load a consumable into a non-weapon"),!1;const{max}=this.uses;return weapon.system.traits.value.includes("repeating")?max>1:max<=1}async consume(){const{actor}=this;if(!actor)return;const{value,max}=this.uses;if(["scroll","wand"].includes(this.category)&&this.system.spell)if(actor.spellcasting.canCastConsumable(this))this.castEmbeddedSpell();else if(actor.itemTypes.feat.some(feat=>feat.slug==="trick-magic-item"))new TrickMagicItemPopup(this);else{const formatParams={actor:actor.name,spell:this.name},message=game.i18n.format("PF2E.LackCastConsumableCapability",formatParams);ui.notifications.warn(message);return}else if(this.category!=="ammo"){const key=max>1&&value===1?"UseExhausted":max>1?"UseMulti":"UseSingle",content=game.i18n.format(`PF2E.ConsumableMessage.${key}`,{name:this.name,current:value-1}),flags={pf2e:{origin:{sourceId:this.flags.core?.sourceId,uuid:this.uuid,type:this.type}}},speaker=ChatMessage.getSpeaker({actor});if(this.formula){const damageType=this.traits.has("vitality")?"vitality":this.traits.has("void")?"void":"untyped";new DamageRoll(`${this.formula}[${damageType}]`).toMessage({speaker,flavor:content,flags})}else ChatMessage.create({speaker,content,flags})}if(this.autoDestroy&&value<=1){const{quantity}=this,isPreservedAmmo=this.category==="ammo"&&this.system.rules.length>0;quantity<=1&&!isPreservedAmmo?await this.delete():await this.update({"system.quantity":Math.max(quantity-1,0),"system.charges.value":max})}else await this.update({"system.charges.value":Math.max(value-1,0)})}async castEmbeddedSpell(trickMagicItemData){const{actor}=this,spell=this.embeddedSpell;if(!actor||!spell)return;const entry=(()=>trickMagicItemData||actor.spellcasting.filter(e=>e instanceof SpellcastingEntryPF2e&&e.canCast(spell,{origin:this})).reduce((previous,current)=>{const previousDC=previous.statistic.dc.value;return current.statistic.dc.value>previousDC?current:previous}))();if(entry){const systemData=spell.system;entry instanceof SpellcastingEntryPF2e&&(systemData.location.value=entry.id),entry.cast(spell,{consume:!1})}}};__name2(_ConsumablePF2e,"ConsumablePF2e");let ConsumablePF2e=_ConsumablePF2e;const _DeityPF2e=class extends ItemPF2e{static{__name(this,"_DeityPF2e")}get category(){return this.system.category}get alignment(){return this.system.alignment.own}get favoredWeapons(){return[...this.system.weapons]}prepareBaseData(){if(super.prepareBaseData(),this.category==="philosophy"){const systemData=this.system;systemData.domains={primary:[],alternate:[]},systemData.font=[],systemData.spells={},systemData.weapons=[]}}prepareActorData(){if(!this.actor.isOfType("character")){this.delete({render:!1});return}this.actor.deity=this;const{deities}=this.actor.system.details,systemData=this.system;deities.primary={alignment:deepClone(systemData.alignment),skill:deepClone(systemData.skill),weapons:deepClone(systemData.weapons)};for(const domain of this.system.domains.primary){const label=CONFIG.PF2E.deityDomains[domain]?.label;deities.domains[domain]=label??domain;const apocryphaKey=`${domain}-apocryphal`;if(objectHasKey(CONFIG.PF2E.deityDomains,apocryphaKey)){const apocrypha=CONFIG.PF2E.deityDomains[apocryphaKey];deities.domains[apocryphaKey]=apocrypha.label}}const slug=this.slug??sluggify(this.name),prefix="deity:primary",actorRollOptions=this.actor.rollOptions;actorRollOptions.all.deity=!0,actorRollOptions.all[`${prefix}:${slug}`]=!0;for(const baseType of this.favoredWeapons)actorRollOptions.all[`${prefix}:favored-weapon:${baseType}`]=!0;this.alignment&&(actorRollOptions.all[`${prefix}:alignment:${this.alignment.toLowerCase()}`]=!0);const followerAlignments=(this.system.alignment.follower.length>0?this.system.alignment.follower:Array.from(ALIGNMENTS)).map(a=>a.toLowerCase());for(const alignment of followerAlignments)actorRollOptions.all[`${prefix}:alignment:follower:${alignment}`]=!0;actorRollOptions.all[`self:deity:${slug}`]=!0}setFavoredWeaponRank(){if(!this.actor.isOfType("character"))return;const favoredWeaponRank=this.actor.flags.pf2e.favoredWeaponRank;if(favoredWeaponRank>0){const attacks=this.actor.system.proficiencies.attacks;for(const baseType of this.favoredWeapons)attacks[`weapon-base-${baseType}`]={label:CONFIG.PF2E.baseWeaponTypes[baseType],rank:Math.max(Number(attacks[`weapon-base-${baseType}`]?.rank)||0,favoredWeaponRank)}}}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),`${prefix}:category:${this.category}`].sort()}};__name2(_DeityPF2e,"DeityPF2e");let DeityPF2e=_DeityPF2e;function featCanHaveKeyOptions(feat){if(feat.category!=="classfeature"||feat.level!==1||feat.traits.size>1)return!1;const{grantedBy}=feat;return!grantedBy||grantedBy.isOfType("feat")&&grantedBy.category==="classfeature"}__name(featCanHaveKeyOptions,"featCanHaveKeyOptions"),__name2(featCanHaveKeyOptions,"featCanHaveKeyOptions");const _FeatPF2e=class extends ItemPF2e{static{__name(this,"_FeatPF2e")}get category(){return this.system.category}get level(){return this.system.level.value}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}get isFeature(){return setHasElement(FEATURE_CATEGORIES,this.category)}get isFeat(){return setHasElement(FEAT_CATEGORIES,this.category)}get onlyLevel1(){return this.system.onlyLevel1}get maxTakable(){return this.system.maxTakable}prepareBaseData(){super.prepareBaseData(),this.group=null,this.system.level.taken??=null,this.system.location||=null;const traits=this.system.traits.value;this.category==="general"&&!traits.includes("general")&&traits.push("general"),this.category==="skill"&&(traits.includes("skill")||traits.push("skill"),!traits.includes("general")&&!traits.includes("archetype")&&traits.push("general")),traits.includes("dedication")&&(this.system.category="class",traits.includes("archetype")||traits.push("archetype")),this.system.traits.value.includes("lineage")&&(this.system.onlyLevel1=!0),this.system.maxTakable??=1/0,this.system.onlyLevel1&&(this.system.maxTakable=1),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max),this.system.subfeatures=mergeObject({keyOptions:[]},this.system.subfeatures??{}),this.system.selfEffect??=null,this.system.actionType.value==="passive"&&(this.system.selfEffect=null)}prepareActorData(){const{actor}=this,prefix=this.isFeature?"feature":"feat",slug=this.slug??sluggify(this.name);actor.rollOptions.all[`${prefix}:${slug}`]=!0;const{subfeatures}=this.system;featCanHaveKeyOptions(this)||(subfeatures.keyOptions=[]),actor.isOfType("character")&&subfeatures.keyOptions.length>0&&(actor.system.build.attributes.keyOptions=uniq([...actor.system.build.attributes.keyOptions,...subfeatures.keyOptions]))}prepareSiblingData(){this.grants=Object.values(this.flags.pf2e.itemGrants).flatMap(grant=>{const item=this.actor?.items.get(grant.id);return item?.isOfType("feat")&&!item.system.location||item?.isOfType("heritage")?[item]:[]});for(const grant of this.grants.filter(g=>g.isOfType("feat")))grant.system.level.taken=this.system.level.taken}async getChatData(htmlOptions={}){const levelLabel=game.i18n.format("PF2E.LevelN",{level:this.level}),actionTypeLabel=getActionTypeLabel(this.actionCost?.type,this.actionCost?.value),properties=actionTypeLabel?[levelLabel,actionTypeLabel]:[levelLabel],traits=this.traitChatData(CONFIG.PF2E.featTraits);return this.processChatData(htmlOptions,{...this.system,properties,traits})}getRollOptions(prefix="feat"){return prefix=prefix==="feat"&&this.isFeature?"feature":prefix,compact([...super.getRollOptions(prefix).filter(o=>!o.endsWith("level:0")),`${prefix}:category:${this.category}`,this.isFeat?`${prefix}:rarity:${this.rarity}`:null,this.frequency?`${prefix}:frequency:limited`:null])}async _preCreate(data,options,user){return this.parent||(this._source.system.location=null,delete this._source.system.level.taken,this._source.system.frequency&&delete this._source.system.frequency.value),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){typeof changed.system?.location=="string"&&(changed.system.location||=null),normalizeActionChangeData(this,changed);const traits=changed.system?.traits?.value;return this.isFeature&&changed.system?(changed.system.onlyLevel1=!1,changed.system.maxTakable=1,this.category!=="ancestry"&&Array.isArray(traits)&&traits.findSplice(t=>t==="lineage")):(Array.isArray(traits)&&traits.includes("lineage")||changed.system?.onlyLevel1)&&mergeObject(changed,{system:{maxTakable:1}}),super._preUpdate(changed,options,user)}_onCreate(data,options,userId){if(super._onCreate(data,options,userId),!(this.isOwner&&this.actor?.isOfType("character")&&this.isFeat))return;const actorItemNames={actor:this.actor.name,item:this.name};if(this.onlyLevel1&&this.actor.level>1){const formatParams={...actorItemNames,actorLevel:this.actor.level},warning=game.i18n.format("PF2E.Item.Feat.Warning.TakenAfterLevel1",formatParams);ui.notifications.warn(warning)}if(this.flags.pf2e.grantedBy)return;const slug=this.slug??sluggify(this.name),timesTaken=this.actor.itemTypes.feat.filter(f=>f.slug===slug).length,{maxTakable}=this;if(maxTakable===1&×Taken>1)ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.TakenMoreThanOnce",actorItemNames));else if(timesTaken>maxTakable){const formatParams={...actorItemNames,maxTakable,timesTaken};ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.TakenMoreThanMax",formatParams))}}};__name2(_FeatPF2e,"FeatPF2e");let FeatPF2e=_FeatPF2e;const _HeritagePF2e=class extends ItemPF2e{static{__name(this,"_HeritagePF2e")}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get isVersatile(){return!this.system.ancestry}prepareActorData(){if(!this.actor.isOfType("character"))throw ErrorPF2e("heritage embedded on non-character");(this.actor.itemTypes.heritage.length===1||!this.grantedBy)&&(this.actor.heritage=this),this.actor.system.traits.value.push(...this.traits);const slug=this.slug??sluggify(this.name);this.actor.system.details.heritage={name:this.name,trait:slug in CONFIG.PF2E.ancestryTraits?slug:null},this.isVersatile&&this.actor.system.details.ancestry?.countsAs.push(slug),this.actor.rollOptions.all[`heritage:${slug}`]=!0,this.actor.rollOptions.all[`self:heritage:${slug}`]=!0}getRollOptions(prefix=this.type){const ancestryOrVersatile=this.system.ancestry?`ancestry:${this.system.ancestry.slug}`:"versatile";return[...super.getRollOptions(prefix),`${prefix}:${ancestryOrVersatile}`]}};__name2(_HeritagePF2e,"HeritagePF2e");let HeritagePF2e=_HeritagePF2e;const KINGDOM_CATEGORY_DATA={"army-tactic":{behavior:"feat",levelLabel:"PF2E.Kingmaker.Feature.Tactic"},"army-war-action":{behavior:"activity"},"kingdom-feat":{behavior:"feat"},"kingdom-feature":{behavior:"feature"},"kingdom-activity":{behavior:"activity"}},KINGMAKER_CATEGORY_TYPES=Object.keys(KINGDOM_CATEGORY_DATA),KINGMAKER_CATEGORIES=mapToObj(KINGMAKER_CATEGORY_TYPES,type=>[type,`PF2E.Kingmaker.Feature.Categories.${type}`]),_CampaignFeaturePF2e=class extends ItemPF2e{static{__name(this,"_CampaignFeaturePF2e")}get category(){return this.system.category}get level(){return this.behavior!=="activity"?this.system.level?.value??0:null}get traits(){return new Set(this.system.traits.value)}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}get isAction(){return this.behavior==="activity"}get isFeature(){return this.behavior==="feature"}get isFeat(){return this.behavior==="feat"}prepareBaseData(){super.prepareBaseData();const categoryData=KINGDOM_CATEGORY_DATA[this.category]??Object.values(KINGDOM_CATEGORY_DATA)[0];this.behavior=categoryData.behavior,this.group=null,this.levelLabel=categoryData.levelLabel??(this.isFeat?"PF2E.Item.Feat.LevelLabel":"PF2E.LevelLabel"),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max)}prepareActorData(){const prefix=this.isFeature?"feature":this.isFeat?"feat":null;if(prefix){const slug=this.slug??sluggify(this.name);this.actor.rollOptions.all[`${prefix}:${slug}`]=!0}}prepareSiblingData(){const itemGrants=this.flags.pf2e.itemGrants;this.grants=Object.values(itemGrants).flatMap(grant=>{const item=this.actor?.items.get(grant.id);return item?.isOfType("campaignFeature")?[item]:[]})}getRollOptions(prefix=null){return prefix??=this.isFeature?"feature":this.isFeat?"feat":"action",compact([...super.getRollOptions(prefix).filter(o=>!o.endsWith("level:0")),`${prefix}:category:${this.category}`,this.isAction?`action:${this.slug}`:null])}async _preCreate(data,options,user){return this.parent||(this.updateSource({"system.location":null}),this._source.system.frequency&&this.updateSource({"system.frequency.-=value":null})),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(typeof changed.system?.location=="string"&&(changed.system.location||=null),normalizeActionChangeData(this,changed),changed.system&&changed.system.category){const system=changed.system,category=tupleHasValue(KINGMAKER_CATEGORY_TYPES,changed.system.category)?changed.system.category:KINGMAKER_CATEGORY_TYPES[0];if(KINGDOM_CATEGORY_DATA[category].behavior==="activity")system["-=level"]=null;else{const level=system.level?.value??this.system.level?.value??0;system.level={value:level}}}await super._preUpdate(changed,options,user)}};__name2(_CampaignFeaturePF2e,"CampaignFeaturePF2e");let CampaignFeaturePF2e=_CampaignFeaturePF2e;const _KitPF2e=class _KitPF2e2 extends ItemPF2e{static{__name(this,"_KitPF2e")}get entries(){return Object.values(this.system.items)}get price(){return{value:new CoinsPF2e(this.system.price.value),per:this.system.price.per??1}}async createGrantedItems(options={}){const size=new ActorSizePF2e({value:options.size??"med",smallIsMedium:!0}).value,entries=options.entries??this.entries,itemUUIDs=entries.map(e=>e.uuid),items=await UUIDUtils.fromUUIDs(itemUUIDs);if(entries.length!==items.length)throw ErrorPF2e(`Some items from ${this.name} were not found`);return items.every(i=>i instanceof ItemPF2e&&!i.parent)?items.reduce(async(promise,item,index)=>{const prepared=await promise,clone=item.clone({_id:randomID(),system:{size}},{keepId:!0}),entry=entries[index];if(clone.isOfType("physical")&&clone.updateSource({"system.quantity":entry.quantity,"system.containerId":options.containerId}),clone.isOfType("backpack")&&entry.items){const contents=await this.createGrantedItems({entries:Object.values(entry.items),containerId:clone.id,size});prepared.push(clone,...contents)}else if(clone instanceof _KitPF2e2){const inflatedKit=await clone.createGrantedItems({containerId:options.containerId,size});prepared.push(...inflatedKit)}else clone instanceof PhysicalItemPF2e&&prepared.push(clone);return prepared},[]):[]}async _preUpdate(changed,options,user){if(!changed.system)return await super._preUpdate(changed,options,user);if(isObject(changed.system.price)){const price=changed.system.price;for(const denomination of DENOMINATIONS)price[denomination]===0&&(price["-=denomination"]=null)}return super._preUpdate(changed,options,user)}};__name2(_KitPF2e,"KitPF2e");let KitPF2e=_KitPF2e;const _LorePF2e=class extends ItemPF2e{static{__name(this,"_LorePF2e")}};__name2(_LorePF2e,"LorePF2e");let LorePF2e=_LorePF2e;const _DicePF2e=class{static{__name(this,"_DicePF2e")}_rolled;terms;static async d20Roll({event,item=null,parts,data,template,title,speaker,flavor,onClose,dialogOptions,rollMode=game.settings.get("core","rollMode"),rollType=""}){const userSettingQuickD20Roll=!game.user.settings.showCheckDialogs,_roll=__name2(async(rollParts,adv,$form)=>{let flav=flavor instanceof Function?flavor(rollParts,data):title;adv===1?(rollParts[0]=["2d20kh"],flav=game.i18n.format("PF2E.Roll.FortuneTitle",{title})):adv===-1&&(rollParts[0]=["2d20kl"],flav=game.i18n.format("PF2E.Roll.MisfortuneTitle",{title})),$form&&(data.itemBonus=$form.find("[name=itemBonus]").val()),(!data.itemBonus||data.itemBonus===0)&&rollParts.indexOf("@itemBonus")!==-1&&rollParts.splice(rollParts.indexOf("@itemBonus"),1),$form&&(data.statusBonus=$form.find("[name=statusBonus]").val()),(!data.statusBonus||data.statusBonus===0)&&rollParts.indexOf("@statusBonus")!==-1&&rollParts.splice(rollParts.indexOf("@statusBonus"),1),$form&&(data.circumstanceBonus=$form.find("[name=circumstanceBonus]").val()),(!data.circumstanceBonus||data.circumstanceBonus===0)&&rollParts.indexOf("@circumstanceBonus")!==-1&&rollParts.splice(rollParts.indexOf("@circumstanceBonus"),1);const roll=await new Roll(rollParts.join("+"),data).roll({async:!0}),origin=item?{uuid:item.uuid,type:item.type}:null;return roll.toMessage({speaker,flavor:flav,flags:{pf2e:{context:{type:rollType},origin}}},{rollMode:$form?$form.find("[name=rollMode]").val():rollMode}),roll},"_roll");if(parts.unshift("1d20"),userSettingQuickD20Roll&&!event.altKey&&!(event.ctrlKey||event.metaKey)&&!event.shiftKey||!userSettingQuickD20Roll&&event.shiftKey)return _roll(parts,0);if(event.ctrlKey||event.metaKey)return rollMode="blindroll",_roll(parts,0);if(event.shiftKey||!userSettingQuickD20Roll){parts.indexOf("@circumstanceBonus")===-1&&(parts=parts.concat(["@circumstanceBonus"])),parts.indexOf("@itemBonus")===-1&&(parts=parts.concat(["@itemBonus"])),parts.indexOf("@statusBonus")===-1&&(parts=parts.concat(["@statusBonus"])),template=template||"systems/pf2e/templates/chat/roll-dialog.hbs";const dialogData={data,rollMode,formula:parts.join(" + "),rollModes:CONFIG.Dice.rollModes},content=await renderTemplate(template,dialogData);let roll;return new Promise(resolve=>{new Dialog({title,content,buttons:{advantage:{label:game.i18n.localize("PF2E.Roll.Fortune"),callback:async html=>{roll=await _roll(parts,1,html)}},normal:{label:game.i18n.localize("PF2E.Roll.Normal"),callback:async html=>{roll=await _roll(parts,0,html)}},disadvantage:{label:game.i18n.localize("PF2E.Roll.Misfortune"),callback:async html=>{roll=await _roll(parts,-1,html)}}},default:game.i18n.localize("PF2E.Roll.Normal"),close:html=>{onClose&&onClose(html,parts,data),resolve(roll)}},dialogOptions).render(!0)})}else return _roll(parts,0)}alter(add2,multiply){const rgx=new RegExp(DiceTerm.REGEXP,"g");if(this._rolled)throw ErrorPF2e("You may not alter a Roll which has already been rolled");return this.terms=this.terms?.map(t=>t.replace(rgx,(_match,nd,d,mods)=>(nd=nd*(multiply||1)+(add2||0),mods=mods||"",`${nd}d${d}${mods}`))),this}};__name2(_DicePF2e,"DicePF2e");let DicePF2e=_DicePF2e;function simplifyFormula(formula){if(formula==="0")return formula;const fixedFormula=formula.replace(/^\s*-\s+/,"-").replace(/\s*\+\s*-\s*/g," - "),roll=new Roll(fixedFormula);if(!roll.terms.every(t=>[" - "," + "].includes(t.expression)||t instanceof Die||t instanceof NumericTerm))return fixedFormula;const terms=parseTermsFromSimpleFormula(roll);return createSimpleFormula(terms)}__name(simplifyFormula,"simplifyFormula"),__name2(simplifyFormula,"simplifyFormula");const _MeleePF2e=class extends ItemPF2e{static{__name(this,"_MeleePF2e")}get traits(){return new Set(this.system.traits.value)}get isMelee(){return this.system.weaponType.value==="melee"}get isRanged(){return this.system.weaponType.value==="ranged"}get isThrown(){return this.isRanged&&this.system.traits.value.some(t=>t.startsWith("thrown"))}get defaultAttribute(){const{traits}=this;return this.isMelee?traits.has("finesse")?"dex":"str":traits.has("brutal")?"str":"dex"}get attackModifier(){return Number(this.system.bonus.value)||0}get reach(){if(this.isRanged)return null;const reachTrait=this.system.traits.value.find(t=>/^reach-\d+$/.test(t));return reachTrait?Number(reachTrait.replace("reach-","")):SIZE_TO_REACH[this.actor?.size??"med"]}get range(){if(this.isMelee)return null;const specifiedMaxRange=(()=>{const rangeTrait=this.system.traits.value.find(t=>/^range-\d+$/.test(t)),range=Number(rangeTrait?.replace(/\D/g,"")||"NaN");return Number.isInteger(range)?range:null})(),rangeIncrement=(()=>{if(specifiedMaxRange)return null;const incrementTrait=this.system.traits.value.find(t=>/^(?:range-increment|thrown)-\d+$/.test(t));return Number(incrementTrait?.replace(/\D/g,""))||10})();return specifiedMaxRange?{increment:null,max:specifiedMaxRange}:rangeIncrement?{increment:rangeIncrement,max:rangeIncrement*6}:null}get baseDamage(){const partials=Object.values(this.system.damageRolls),instance=partials.find(p=>!p.category)??partials.at(0);return instance?WeaponDamagePF2e.npcDamageToWeaponDamage(instance):{dice:0,die:null,modifier:0,damageType:"untyped",persistent:null,category:null}}get dealsDamage(){const{baseDamage}=this;return baseDamage.dice>0||baseDamage.modifier>0||!!baseDamage.persistent?.number||Object.values(this.system.damageRolls).some(d=>d.category==="splash")}get attackEffects(){return this.system.attackEffects.value}get isMagical(){const{traits}=this;return["magical","arcane","primal","divine","occult"].some(t=>traits.has(t))}get linkedWeapon(){const item=this.actor?.items.get(this.flags.pf2e.linkedWeapon??"");return item?.isOfType("weapon")?item:null}_initialize(options){this.category=this.group=this.baseType=null,super._initialize(options)}prepareBaseData(){super.prepareBaseData(),this.system.material={type:null,grade:null},this.system.runes={property:[]};for(const attackDamage of Object.values(this.system.damageRolls))attackDamage.category||=null,attackDamage.damageType==="bleed"&&(attackDamage.category="persistent")}prepareSiblingData(){const{linkedWeapon}=this,isUnarmed=this.traits.has("unarmed");this.category=isUnarmed?"unarmed":linkedWeapon?.category??null,this.group=isUnarmed?"brawling":this.linkedWeapon?.group??null,this.baseType=tupleHasValue(["claw","fist","jaws"],this.slug)?this.slug:this.linkedWeapon?.baseType??null}prepareActorData(){if(!this.actor?.isOfType("npc"))return;const damageInstances=Object.values(this.system.damageRolls);for(const instance of Object.values(this.system.damageRolls)){try{instance.damage=new Roll(instance.damage)._formula}catch{const message=`Unable to parse damage formula on NPC attack ${this.name}`;console.warn(`PF2e System | ${message}`),instance.damage="1d4"}const{isElite,isWeak}=this.actor;if((isElite||isWeak)&&damageInstances.indexOf(instance)===0){const adjustment=isElite?2:-2;instance.damage=simplifyFormula(`${instance.damage} + ${adjustment}`)}else instance.damage=new Roll(instance.damage)._formula}}getRollOptions(prefix=this.type){const baseOptions=super.getRollOptions(prefix),{damageType}=this.baseDamage,damageCategory=DamageCategorization.fromDamageType(damageType),rangeIncrement=this.range?.increment,propertyRunes=mapToObj(this.system.runes.property,p=>[`rune:property:${sluggify(p)}`,!0]),otherOptions=Object.entries({equipped:!0,melee:this.isMelee,ranged:this.isRanged,thrown:this.isThrown,[`category:${this.category}`]:!!this.category,[`group:${this.group}`]:!!this.group,[`base:${this.baseType}`]:!!this.baseType,[`range-increment:${rangeIncrement}`]:!!rangeIncrement,[`damage:type:${damageType}`]:!0,[`damage:category:${damageCategory}`]:!!damageCategory,...propertyRunes}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`);return[baseOptions,otherOptions].flat().sort()}async toMessage(_event,{create=!0}={}){if(!create)return;const strike=this.actor?.system.actions?.find(s=>s.item===this);return strike?game.pf2e.rollActionMacro({itemId:this.id,slug:strike.slug}):void 0}};__name2(_MeleePF2e,"MeleePF2e");let MeleePF2e=_MeleePF2e;const _SpellOverlayCollection=class extends Collection{static{__name(this,"_SpellOverlayCollection")}constructor(spell,entries){super(Object.entries(entries??{})),this.spell=spell}get overrideVariants(){return[...this.entries()].reduce((result,[overlayId,data])=>{if(data.overlayType==="override"){const spell=this.spell.loadVariant({overlayIds:[overlayId]});if(spell)return[...result,spell]}return result},[])}getType(overlayId){return this.get(overlayId,{strict:!0}).overlayType}async create(overlayType,options={renderSheet:!1}){const id=randomID();switch(overlayType){case"override":if(await this.spell.update({[`system.overlays.${id}`]:{_id:id,sort:this.overrideVariants.length+1,overlayType:"override"}}),options.renderSheet){const variantSpell=this.spell.loadVariant({overlayIds:[id]});variantSpell&&variantSpell.sheet.render(!0)}break}}async updateOverride(variantSpell,data,options){variantSpell.updateSource(data,options);const variantSource=variantSpell.toObject(),originSource=this.spell.toObject(),difference2=diffObject(originSource,variantSource);return Object.keys(difference2).length===0||(delete difference2.system?.description,difference2.overlayType="override",await this.spell.update({[`system.overlays.-=${variantSpell.id}`]:null},{render:!1}),await this.spell.update({[`system.overlays.${variantSpell.id}`]:difference2}),variantSpell.sheet.rendered&&variantSpell.sheet.render(!0)),variantSpell}async deleteOverlay(overlayId){this.verifyOverlayId(overlayId),await this.spell.update({[`system.overlays.-=${overlayId}`]:null}),this.delete(overlayId)}verifyOverlayId(overlayId){if(!this.has(overlayId))throw ErrorPF2e(`Spell ${this.spell.name} (${this.spell.uuid}) does not have an overlay with id: ${overlayId}`)}};__name2(_SpellOverlayCollection,"SpellOverlayCollection");let SpellOverlayCollection=_SpellOverlayCollection;const _SpellPF2e=class _SpellPF2e2 extends ItemPF2e{static{__name(this,"_SpellPF2e")}isFromConsumable;trickMagicEntry=null;constructor(data,context={}){super(data,context),this.isFromConsumable=!!context.fromConsumable}get baseRank(){return this.system.level.value}get baseLevel(){return this.baseRank}get rank(){if(!this.actor)return this.baseRank;const isAutoHeightened=this.isCantrip||this.isFocusSpell,fixedHeightenedRank=this.system.location.autoHeightenLevel||this.spellcasting?.system?.autoHeightenLevel.value||null;return(isAutoHeightened?fixedHeightenedRank||Math.ceil(this.actor.level/2)||null:this.system.location.heightenedLevel||null)||this.baseRank}get level(){return this.rank}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get castingTraits(){const{components}=this;return[getActionIcon(this.system.time.value,null)===null?"exploration":[],components.verbal?"concentrate":[],["focus","material","somatic"].some(c=>components[c])?"manipulate":[]].flat()}get school(){return this.system.traits.value.find(t=>setHasElement(MAGIC_SCHOOLS,t))??null}get traditions(){return this.spellcasting?.tradition?new Set([this.spellcasting.tradition]):new Set(this.system.traditions.value)}get spellcasting(){const spellcastingId=this.system.location.value;return this.trickMagicEntry?this.trickMagicEntry:this.actor?.spellcasting.find(e=>e.id===spellcastingId)??null}get isAttack(){return this.traits.has("attack")||this.system.spellType.value==="attack"}get isCantrip(){return this.traits.has("cantrip")&&!this.isRitual}get isFocusSpell(){return this.system.category.value==="focus"}get isRitual(){return this.system.category.value==="ritual"}get attribute(){return this.spellcasting?.attribute??"cha"}get ability(){return foundry.utils.logCompatibilityWarning("`SpellPF2e#ability` is deprecated. Use `SpellPF2e#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}get components(){const components=this.system.components,results=[];return components.focus&&results.push(game.i18n.localize("PF2E.SpellComponentShortF")),components.material&&results.push(game.i18n.localize("PF2E.SpellComponentShortM")),components.somatic&&results.push(game.i18n.localize("PF2E.SpellComponentShortS")),components.verbal&&results.push(game.i18n.localize("PF2E.SpellComponentShortV")),{...components,value:results.join("")}}get unlimited(){return this.isCantrip}get isVariant(){return!!this.original}get hasVariants(){return this.overlays.size>0}get area(){if(!this.system.area)return null;const size=Number(this.system.area.value),unit=game.i18n.localize("PF2E.Foot"),shape=game.i18n.localize(CONFIG.PF2E.areaTypes[this.system.area.type]),label=game.i18n.format("PF2E.Item.Spell.Area",{size,unit,shape});return{...this.system.area,label}}get range(){return null}get damageKinds(){return new Set(this.system.spellType.value==="heal"?this.system.save.value?["damage","healing"]:["healing"]:["damage"])}get uuid(){return this.isVariant?this.original.uuid:super.uuid}computeCastRank(slotRank){return(this.isCantrip||this.isFocusSpell)&&this.actor?this.rank:Math.max(this.baseRank,slotRank??this.rank)}getRollData(rollOptions={}){const spellLevel=Number(rollOptions?.castLevel)||null,castLevel=Math.max(this.baseRank,spellLevel||this.rank);if(spellLevel&&castLevel!==this.rank)return this.clone({"system.location.heightenedLevel":castLevel}).getRollData();const rollData=super.getRollData();return this.actor?.isOfType("character","npc")&&(rollData.mod=this.actor.abilities[this.attribute].mod),rollData.castLevel=castLevel,rollData.heighten=Math.max(0,castLevel-this.baseRank),rollData}async getDamage(params={skipDialog:!0}){if(!Object.keys(this.system.damage.value).length||!this.actor||!this.spellcasting?.statistic)return null;const castLevel=this.rank,rollData=this.getRollData({castLevel}),base=[];for(const[id,damage]of Object.entries(this.system.damage.value??{})){if(!DamageRoll.validate(damage.value))return console.error(`Failed to parse damage formula "${damage.value}"`),null;const terms=parseTermsFromSimpleFormula(damage.value,{rollData}),heightening=this.system.heightening;if(heightening?.type==="interval"&&heightening.interval){const scalingFormula=heightening.damage[id],partCount=Math.floor((castLevel-this.baseRank)/heightening.interval);if(scalingFormula&&partCount>0){const scalingTerms=parseTermsFromSimpleFormula(scalingFormula,{rollData});for(let i=0;i0&&!base.length&&this.actor.isOfType("npc")&&this.actor.attributes.adjustment){const value=this.unlimited?2:4;terms.push({dice:null,modifier:this.actor.isElite?value:-value})}const damageType=damage.type.value,category=damage.type.subtype||null,materials=damage.type.categories;base.push({terms:combinePartialTerms(terms),damageType,category,materials})}if(!base.length)return null;const{attribute,isAttack}=this,checkStatistic=this.spellcasting.statistic,spellTraits2=this.traits,domains=compact(["damage","spell-damage",`${this.id}-damage`,isAttack?["attack-damage","attack-spell-damage"]:null,checkStatistic.base?`${checkStatistic.base.slug}-damage`:null]).flat(),contextData=await this.actor.getDamageRollContext({target:isAttack?params.target:null,item:this,statistic:checkStatistic.check,domains,options:new Set(["action:cast-a-spell",...spellTraits2]),checkContext:null,outcome:null,viewOnly:!isAttack||!params.target}),context={type:"damage-roll",sourceType:isAttack?"attack":"save",outcome:isAttack?"success":null,domains,options:contextData.options,self:contextData.self,target:contextData.target??null,rollMode:params.rollMode},modifiers=[],damageDice=[],{actor}=contextData.self;if(actor.system.abilities){const attributes=actor.system.abilities,attributeModifiers=Object.entries(this.system.damage.value).filter(([,d])=>d.applyMod).map(([k,d])=>new ModifierPF2e({label:CONFIG.PF2E.abilities[attribute],slug:`ability-${k}`,type:"untyped",modifier:attributes[attribute].mod,damageType:d.type.value,damageCategory:d.type.subtype||null,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,`ability-${k}`)})),extractOptions={resolvables:{spell:this,target:contextData.target?.actor??null},test:contextData.options},extracted=processDamageCategoryStacking(base,{modifiers:[attributeModifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:contextData.options});modifiers.push(...extracted.modifiers),damageDice.push(...extracted.dice)}const formulaData={base,modifiers,dice:damageDice,ignoredResistances:[],kinds:this.damageKinds};if(!params.skipDialog&&!await new DamageModifierDialog({formulaData,context}).resolve())return null;const{formula,breakdown}=createDamageFormula(formulaData),roll=new DamageRoll(formula);return{template:{name:this.name,damage:{roll,breakdown},materials:Array.from(roll.materials),traits:this.castingTraits,modifiers},context}}loadVariant(options={}){if(this.original)return this.original.loadVariant(options);const{castLevel,overlayIds}=options,appliedOverlays=new Map,heightenEntries=this.getHeightenLayers(castLevel),overlays=overlayIds?.map(id=>({id,data:this.overlays.get(id,{strict:!0})}))??[],overrides=(()=>{if(!heightenEntries.length&&!overlays.length)return castLevel!==this.rank?mergeObject(this.toObject(),{system:{location:{heightenedLevel:castLevel}}}):null;let source=this.toObject();if(overlays.map(overlay=>overlay.data.overlayType).filter(type=>type==="override").length>1)throw ErrorPF2e(`Error loading variant of Spell ${this.name} (${this.uuid}). Cannot apply multiple override overlays.`);for(const{id,data}of overlays){switch(data.overlayType){case"override":{delete source.system.overlays,source.system.rules=[],source=mergeObject(source,data,{overwrite:!0});break}}appliedOverlays.set(data.overlayType,id)}for(const overlay of heightenEntries)mergeObject(source.system,overlay.system);const currentRank=source.system.location.heightenedLevel??source.system.level.value;return castLevel&&castLevel!==currentRank&&(source.system.location.heightenedLevel=castLevel),source})();if(!overrides)return null;const fromConsumable=this.isFromConsumable,variant=new _SpellPF2e2(overrides,{parent:this.actor,fromConsumable});return variant.original=this,variant.appliedOverlays=appliedOverlays,variant.trickMagicEntry=this.trickMagicEntry,variant.system.traits.value=Array.from(new Set([...variant.traits,...variant.traditions])),variant}getHeightenLayers(rank){const heightening=this.system.heightening;return heightening?.type!=="fixed"?[]:Object.entries(heightening.levels).map(([rank2,system])=>({level:Number(rank2),system})).filter(system=>!rank||rank>=system.level).sort((first,second)=>first.level-second.level)}createTemplate(message){const templateConversion={burst:"circle",cone:"cone",cube:"rect",emanation:"circle",line:"ray",rect:"rect",square:"rect"},{area}=this.system;if(!area)throw ErrorPF2e("Attempted to create template with non-area spell");const areaType=templateConversion[area.type],templateData={t:areaType,distance:Number(area.value)/5*(canvas.dimensions?.distance??0),fillColor:game.user.color,flags:{pf2e:{messageId:message?.id,origin:{name:this.name,slug:this.slug,traits:deepClone(this.system.traits.value),...this.getOriginData()}}}};switch(areaType){case"ray":templateData.width=CONFIG.MeasuredTemplate.defaults.width*(canvas.dimensions?.distance??1);break;case"cone":templateData.angle=CONFIG.MeasuredTemplate.defaults.angle;break;case"rect":{const distance=templateData.distance??0;templateData.distance=Math.hypot(distance,distance),templateData.width=distance,templateData.direction=45;break}}const templateDoc=new MeasuredTemplateDocumentPF2e(templateData,{parent:canvas.scene});return new MeasuredTemplatePF2e(templateDoc)}placeTemplate(message){this.createTemplate(message).drawPreview()}prepareBaseData(){super.prepareBaseData(),this.system.location.value||=null,this.isEmbedded||this.system.traits.value.push(...this.system.traditions.value),this.system.level.value=Math.clamped(this.system.level.value,1,10)||1,this.system.area?.value?(this.system.area.value=Number(this.system.area.value)||5,this.system.area.type||="burst"):this.system.area=null,this.isRitual&&(this.system.location.value="rituals");for(const formula of Object.values(this.system.damage.value))formula.value=formula.value?.trim()||"0";if(this.system.heightening?.type==="fixed")for(const heighten of Object.values(this.system.heightening.levels))for(const formula of Object.values(heighten.damage?.value??{}))formula.value=formula.value?.trim()||"0";else if(this.system.heightening?.type==="interval")for(const key of Object.keys(this.system.heightening.damage))this.system.heightening.damage[key]=this.system.heightening.damage[key]?.trim()||"0";this.overlays=new SpellOverlayCollection(this,this.system.overlays)}prepareSiblingData(){this.system.traits.value.push(...this.traditions),this.spellcasting?.isInnate&&mergeObject(this.system.location,{uses:{value:1,max:1}},{overwrite:!1})}getRollOptions(prefix=this.type){const options=new Set(["magical",`${prefix}:rank:${this.rank}`]);!!(this.spellcasting?.isPrepared||this.spellcasting?.isSpontaneous)&&!this.isCantrip&&!this.isFromConsumable&&options.add(`${prefix}:spell-slot`),this.system.duration.value||options.add(`${prefix}:duration:0`),this.unlimited||options.add(`${prefix}:frequency:limited`);const damageValues=Object.values(this.system.damage.value);for(const damage of damageValues){damage.type&&(options.add(`${prefix}:damage:${damage.type.value}`),options.add(`${prefix}:damage:type:${damage.type.value}`));const category=DamageCategorization.fromDamageType(damage.type.value);category&&options.add(`${prefix}:damage:category:${category}`),damage.type.subtype==="persistent"&&options.add(`${prefix}:damage:persistent:${damage.type.value}`)}const isAreaEffect=!!this.system.area?.value;isAreaEffect&&options.add("area-effect"),damageValues.length>0&&this.system.spellType.value!=="heal"&&(options.add("damaging-effect"),isAreaEffect&&options.add("area-damage"));for(const trait of this.traits)options.add(trait);const spellcastingOptions=this.spellcasting?.getRollOptions?.("spellcasting")??[];for(const option of spellcastingOptions)options.add(option);return super.getRollOptions(prefix).concat([...options])}async toMessage(event,{create=!0,data,rollMode}={}){const domData=htmlClosest(event?.currentTarget,".item")?.dataset,castData=mergeObject(data??{},domData??{}),castLevel=Number(castData.castLevel??"");if(castLevel&&castLevel!==this.rank)return this.loadVariant({castLevel})?.toMessage(event,{create,data,rollMode});const message=await super.toMessage(event,{create:!1,data:castData,rollMode});if(!message)return;const messageSource=message.toObject(),flags=messageSource.flags.pf2e,entry=this.spellcasting;if(entry?.statistic){const tradition=Array.from(this.traditions).at(0);if(flags.casting={id:entry.id,tradition:entry.tradition??tradition??"arcane"},this.system.spellType.value==="save"||this.system.save.value!==""){const dc=entry.statistic.withRollOptions({item:this}).dc;flags.context={type:"spell-cast",domains:dc.domains,options:[...dc.options],rollMode}}}return flags.isFromConsumable=this.isFromConsumable,create?ChatMessagePF2e.create(messageSource,{renderSheet:!1}):(message.updateSource(messageSource),message)}async getChatData(htmlOptions={},rollOptions={}){if(!this.actor)throw ErrorPF2e(`Cannot retrieve chat data for unowned spell ${this.name}`);const slotRank=Number(rollOptions.slotLevel)||this.rank,castLevel=Number(rollOptions.castLevel)||this.computeCastRank(slotRank);if(!this.isVariant){const variant=this.loadVariant({castLevel});if(variant)return variant.getChatData(htmlOptions,rollOptions)}const variants=this.overlays.overrideVariants.map(variant=>({actions:getActionIcon(variant.system.time.value,null),name:variant.name,overlayIds:[...variant.appliedOverlays.values()],sort:variant.sort})).sort((a,b)=>a.sort-b.sort),rollData=htmlOptions.rollData??this.getRollData({castLevel});rollData.item??=this;const localize=game.i18n.localize.bind(game.i18n),systemData=this.system,options={...htmlOptions,rollData},description=await TextEditor.enrichHTML(this.description,{...options,async:!0}),spellcasting=this.spellcasting;if(!spellcasting)return console.warn(`PF2e System | Orphaned spell ${this.name} (${this.id}) on actor ${this.actor.name} (${this.actor.id})`),{...systemData};const statistic=spellcasting?.statistic;if(!statistic&&!this.isRitual)return console.warn(`PF2e System | Spell ${this.name} is missing a statistic to cast with (${this.id}) on actor ${this.actor.name} (${this.actor.id})`),{...systemData};const statisticChatData=statistic?.getChatData({item:this}),spellDC=statisticChatData?.dc.value,isSave=systemData.spellType.value==="save"||!!systemData.save.value,damage=await this.getDamage(),hasDamage=!!damage,saveType=systemData.save.value?game.i18n.localize(CONFIG.PF2E.saves[systemData.save.value]):null,saveKey=systemData.save.basic?"PF2E.SaveDCLabelBasic":"PF2E.SaveDCLabel",saveLabel=(()=>{if(!(spellDC&&saveType))return null;const localized=game.i18n.format(saveKey,{dc:spellDC,type:saveType}),tempElement=createHTMLElement("div",{innerHTML:localized}),visibility=game.settings.get("pf2e","metagame_showDC")?"all":"owner";return TextEditorPF2e.convertXMLNode(tempElement,"dc",{visibility,whose:null}),tempElement.innerHTML})(),{damageKinds}=this,damageLabel=damageKinds.has("damage")?damageKinds.has("healing")?"PF2E.Damage.Kind.Both.Roll.Verb":"PF2E.Damage.Kind.Damage.Roll.Verb":"PF2E.Damage.Kind.Healing.Roll.Verb",{baseRank}=this,heightened=castLevel-baseRank,rankLabel=(()=>{const type=this.isCantrip?localize("PF2E.TraitCantrip"):localize(CONFIG.PF2E.spellCategories[this.system.category.value]);return game.i18n.format("PF2E.ItemLevel",{type,level:castLevel})})(),area=this.area,properties=compact([heightened?game.i18n.format("PF2E.SpellLevelBase",{level:ordinalString(baseRank)}):null,heightened?game.i18n.format("PF2E.SpellLevelHeightened",{heightened}):null,this.isRitual?null:`${localize("PF2E.SpellComponentsLabel")}: ${this.components.value}`,systemData.range.value?`${localize("PF2E.SpellRangeLabel")}: ${systemData.range.value}`:null,systemData.target.value?`${localize("PF2E.SpellTargetLabel")}: ${systemData.target.value}`:null,area?game.i18n.format("PF2E.SpellArea",{area:area.label}):null,systemData.time.value?`${localize("PF2E.SpellTimeLabel")}: ${systemData.time.value}`:null,systemData.duration.value?`${localize("PF2E.SpellDurationLabel")}: ${systemData.duration.value}`:null]),spellTraits2=this.traitChatData(CONFIG.PF2E.spellTraits),original=this.original??this,item=this.isFromConsumable?JSON.stringify(original.toObject(!1)):void 0;return{...systemData,description:{value:description},isAttack:this.isAttack,isSave,check:this.isAttack&&statisticChatData?statisticChatData.check:void 0,save:{...statisticChatData?.dc??{},type:systemData.save.value,label:saveLabel},hasDamage,castLevel,rankLabel,damageLabel,formula:damage?.template.damage.roll.formula,properties,spellTraits:spellTraits2,traits:spellTraits2,actionTraits:this.castingTraits.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),item,area,variants}}async rollAttack(event,attackNumber=1,context={}){const statistic=this.spellcasting?.statistic;if(statistic)context.extraRollOptions=uniq(compact(["action:cast-a-spell",context.extraRollOptions].flat())),await statistic.check.roll({...eventToRollParams(event,{type:"check"}),...context,action:"cast-a-spell",item:this,traits:this.castingTraits,attackNumber});else throw ErrorPF2e("Spell points to location that is not a spellcasting type")}async rollDamage(event,mapIncreases){const element=htmlClosest(event.currentTarget,"*[data-cast-level]"),castLevel=Number(element?.dataset.castLevel)||this.rank;if(!this.isVariant){const variant=this.loadVariant({castLevel});if(variant)return variant.rollDamage(event)}const targetToken=Array.from(game.user.targets).find(t=>t.actor?.isOfType("creature","hazard","vehicle"))?.document??null,spellDamage=await this.getDamage({target:targetToken,...eventToRollParams(event,{type:"damage"})});if(!spellDamage)return null;const{template,context}=spellDamage;return typeof mapIncreases=="number"&&(context.mapIncreases=mapIncreases,context.options.add(`map:increases:${mapIncreases}`)),DamagePF2e.roll(template,context)}async rollCounteract(event){if(event=event instanceof Event?event:event?.originalEvent,!this.actor?.isOfType("character","npc"))return null;if(!this.spellcasting?.statistic?.attribute)return console.warn(ErrorPF2e(`Spell ${this.name} (${this.uuid}) is missing a statistic with which to counteract.`).message),null;const localize=localizer("PF2E.Item.Spell.Counteract"),statistic=new Statistic(this.actor,{slug:"counteract",label:localize("Label"),attribute:this.spellcasting.attribute,rank:this.spellcasting.statistic.rank??0}),domain="counteract-check",notes=[new RollNotePF2e({selector:domain,text:localize("Hint")}),...DEGREE_OF_SUCCESS_STRINGS.map(degreeString=>{const counteractRank={criticalFailure:0,failure:this.rank,success:this.rank+1,criticalSuccess:this.rank+3}[degreeString];return new RollNotePF2e({selector:domain,title:`PF2E.Check.Result.Degree.Check.${degreeString}`,text:localize(degreeString,{rank:counteractRank}),outcome:[degreeString]})})],traits=this.system.traits.value,{check}=statistic.extend({domains:[domain],rollOptions:traits});return check.roll({...eventToRollParams(event,{type:"check"}),label:game.i18n.localize("PF2E.Check.Specific.Counteract"),extraRollNotes:notes,traits})}getOriginData(){const flag=super.getOriginData();return flag.castLevel=this.rank,this.isVariant&&this.appliedOverlays&&(flag.variant={overlays:[...this.appliedOverlays.values()]}),flag}async update(data,options={}){return this.original&&this.appliedOverlays.has("override")&&this.sheet.rendered?this.original.overlays.updateOverride(this,data,options):super.update(data,options)}async _preCreate(data,options,user){return this._source.system.location.value||=null,this._source.system.category.value==="ritual"&&(this._source.system.location.value=null),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const result=await super._preUpdate(changed,options,user);if(result===!1)return result;const diff=options.diff??=!0;if(changed.system?.level){const{level}=changed.system;level.value=Math.clamped(Math.trunc(Number(level.value)||1),1,10)}const uses=changed.system?.location?.uses;if(uses){const currentUses=uses.value??this.system.location.uses?.value??1,currentMax=uses.max??this.system.location.uses?.max;uses.value=Math.clamped(Number(currentUses),0,Number(currentMax))}const newLocation=changed.system?.location?.value,locationChanged=typeof newLocation=="string"&&newLocation!==this.system.location.value;if(diff&&(!this.actor||locationChanged)){const system=changed.system??={},locationUpdates=system.location=this.actor?system.location??{}:{value:""},keys2=Object.keys(this.system.location).filter(k=>k!=="value"&&!(k in locationUpdates));for(const key of keys2)locationUpdates[`-=${key}`]=null}}};__name2(_SpellPF2e,"SpellPF2e");let SpellPF2e=_SpellPF2e;const _RitualSpellcasting=class{static{__name(this,"_RitualSpellcasting")}actor;spells;constructor(actor,rituals){this.actor=actor,this.spells=new SpellCollection(this);for(const ritual of rituals)this.spells.set(ritual.id,ritual)}get id(){return"rituals"}get name(){return game.i18n.localize("PF2E.Actor.Creature.Spellcasting.Rituals")}get sort(){return Math.max(0,...this.actor.itemTypes.spellcastingEntry.map(e=>e.sort))+10}get category(){return"ritual"}get tradition(){return null}get isFlexible(){return!1}get isFocusPool(){return!1}get isInnate(){return!1}get isPrepared(){return!1}get isRitual(){return!0}get isSpontaneous(){return!1}canCast(spell){return spell.isRitual}async cast(spell,options={}){if(!spell.isRitual)throw ErrorPF2e("Attempted to cast non-ritual from `RitualSpellcasting`");await spell.toMessage(void 0,{rollMode:options.rollMode})}async getSheetData(){return{id:this.id,name:this.name,statistic:null,tradition:null,category:this.category,isRitual:!0,hasCollection:!0,sort:this.sort,...await this.spells.getSpellData()}}};__name2(_RitualSpellcasting,"RitualSpellcasting");let RitualSpellcasting=_RitualSpellcasting;const _SpellCollection=class extends Collection{static{__name(this,"_SpellCollection")}constructor(entry){if(!entry.actor)throw ErrorPF2e("a spell collection must have an associated actor");super(),__privateAdd(this,_assertEntryIsDocument),__privateAdd(this,_getRitualData),__publicField(this,"entry"),__publicField(this,"actor"),this.entry=entry,this.actor=entry.actor}get id(){return this.entry.id}get highestRank(){const highestSpell=Math.max(...this.map(s=>s.rank)),actorSpellRank=Math.ceil((this.actor?.level??0)/2);return Math.min(10,Math.max(highestSpell,actorSpellRank))}async addSpell(spell,options={}){const{actor}=this;if(!actor.isOfType("creature"))throw ErrorPF2e("Spellcasting entries can only exist on creatures");const canHeighten=!(spell.isCantrip||spell.isFocusSpell||spell.isRitual)&&(this.entry.isSpontaneous||this.entry.isInnate),heightenedRank=canHeighten?options.slotLevel??spell.rank:spell.baseRank;if(spell.system.location.value===this.id&&spell.rank===heightenedRank)return null;if(spell.isFocusSpell&&!this.entry.isFocusPool){const focusTypeLabel=game.i18n.format("PF2E.SpellFocusLabel");return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.WrongSpellType",{spellType:focusTypeLabel})),null}if(spell.baseRank>heightenedRank&&this.id===spell.system.location?.value){const targetRankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(heightenedRank)}),baseLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(spell.baseRank)});ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetRankLabel,baseLevel:baseLabel}))}const heightenedUpdate=canHeighten&&heightenedRank>=spell.baseRank?{"system.location.heightenedLevel":heightenedRank}:{};if(spell.actor===actor)return spell.update({"system.location.value":this.id,...heightenedUpdate});{const source=spell.clone({"system.location.value":this.id,...heightenedUpdate}).toObject(),created=(await actor.createEmbeddedDocuments("Item",[source])).shift();return created instanceof SpellPF2e?created:null}}async prepareSpell(spell,slotRank,spellSlot){if(__privateMethod(this,_assertEntryIsDocument,assertEntryIsDocument_fn).call(this,this.entry),spell.baseRank>slotRank&&!(slotRank===0&&spell.isCantrip)){const targetRankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(slotRank)}),baseLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(spell.baseRank)});return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetRankLabel,baseLevel:baseLabel})),this.entry}CONFIG.debug.hooks&&console.debug(`PF2e System | Updating location for spell ${spell.name} to match spellcasting entry ${this.id}`);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}`,updates={[key]:{id:spell.id}},slot=this.entry.system.slots[`slot${slotRank}`].prepared[spellSlot];return slot&&(slot.prepared!==void 0&&(updates[`${key}.-=prepared`]=null),slot.name!==void 0&&(updates[`${key}.-=name`]=null)),this.entry.update(updates)}unprepareSpell(slotRank,spellSlot){__privateMethod(this,_assertEntryIsDocument,assertEntryIsDocument_fn).call(this,this.entry),CONFIG.debug.hooks===!0&&console.debug(`PF2e System | Updating spellcasting entry ${this.id} to remove spellslot ${spellSlot} for spell rank ${slotRank}`);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}`;return this.entry.update({[key]:{name:game.i18n.localize("PF2E.SpellSlotEmpty"),id:null,prepared:!1,expended:!1}})}setSlotExpendedState(slotRank,spellSlot,isExpended){__privateMethod(this,_assertEntryIsDocument,assertEntryIsDocument_fn).call(this,this.entry);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}.expended`;return this.entry.update({[key]:isExpended})}async getSpellData(){const{actor}=this;if(!actor.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries can only exist on characters and npcs");if(this.entry instanceof RitualSpellcasting)return __privateMethod(this,_getRitualData,getRitualData_fn).call(this);__privateMethod(this,_assertEntryIsDocument,assertEntryIsDocument_fn).call(this,this.entry);const results=[],spells=this.contents.sort((s1,s2)=>(s1.sort||0)-(s2.sort||0)),signatureSpells=spells.filter(s=>s.system.location.signature),isFlexible=this.entry.isFlexible;if(this.entry.isPrepared&&this.entry instanceof SpellcastingEntryPF2e)for(let rank=0;rank<=this.highestRank;rank++){const data=this.entry.system.slots[`slot${rank}`],active=[];if((this.entry.system.showSlotlessLevels.value||data.max>0)&&(rank===0||!isFlexible)){const maxPrepared=Math.max(data.max,0);active.push(...Array(maxPrepared).fill(null));for(const[key,value]of Object.entries(data.prepared)){const spell=value.id?this.get(value.id):null;spell&&(active[Number(key)]={castLevel:spell.computeCastRank(rank),spell,expended:!!value.expended})}}results.push({label:rank===0?"PF2E.Actor.Creature.Spellcasting.Cantrips":game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,uses:{value:rank>0&&isFlexible?data.value||0:void 0,max:data.max},isCantrip:rank===0,active})}else if(this.entry.isFocusPool){const cantrips=spells.filter(spell=>spell.isCantrip),leveled=spells.filter(spell=>!spell.isCantrip);if(cantrips.length){const active=cantrips.map(spell=>({spell}));results.push({label:"PF2E.Actor.Creature.Spellcasting.Cantrips",level:0,isCantrip:!0,active})}if(leveled.length){const active=leveled.map(spell=>({spell}));results.push({label:actor.type==="character"?"PF2E.Focus.Spells":"PF2E.Focus.Pool",level:Math.max(1,Math.ceil(actor.level/2)),isCantrip:!1,uses:actor.system.resources.focus??{value:0,max:0},active})}}else{const alwaysShowHeader=!this.entry.isRitual,spellsByLevel=groupBy(spells,spell=>spell.isCantrip?0:spell.rank);for(let rank=0;rank<=this.highestRank;rank++){const data=this.entry.system.slots[`slot${rank}`],spells2=spellsByLevel.get(rank)??[];if(alwaysShowHeader||spells2.length){const uses=this.entry.isSpontaneous&&rank!==0?{value:data.value,max:data.max}:void 0,active=spells2.map(spell=>({spell,expended:this.entry.isInnate&&!spell.system.location.uses?.value,uses:this.entry.isInnate&&!spell.unlimited?spell.system.location.uses:void 0})),hideForSpontaneous=this.entry.isSpontaneous&&uses?.max===0&&active.length===0,hideForInnate=this.entry.isInnate&&active.length===0;if(!this.entry.system.showSlotlessLevels.value&&(hideForSpontaneous||hideForInnate))continue;results.push({label:rank===0?"PF2E.Actor.Creature.Spellcasting.Cantrips":game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,isCantrip:rank===0,uses,active})}}}if(this.entry.isSpontaneous||isFlexible){for(const spell of signatureSpells)for(const result of results){if(spell.baseRank>result.level||!this.entry.system.showSlotlessLevels.value&&result.uses?.max===0)continue;const existing=result.active.find(a=>a?.spell.id===spell.id);if(existing)existing.signature=!0;else if(result.uses?.max){const castLevel=result.level;result.active.push({spell,castLevel,signature:!0,virtual:!0})}}for(const result of results)if(result.level>0&&result.uses?.value===0&&result.uses.max>0)for(const slot of result.active)slot&&(slot.expended=!0)}const flexibleAvailable=(()=>{if(!isFlexible)return null;const totalSlots=results.filter(result=>!result.isCantrip).map(rank=>rank.uses?.max||0).reduce((first,second)=>first+second,0);return{value:signatureSpells.length,max:totalSlots}})();return{levels:results,flexibleAvailable,spellPrepList:this.getSpellPrepList(spells)}}getSpellPrepList(spells){if(!this.entry.isPrepared)return{};const spellPrepList={},spellsByRank=groupBy(spells,spell=>spell.isCantrip?0:spell.baseRank);for(let rank=0;rank<=this.highestRank;rank++)spellPrepList[rank]=spellsByRank.get(rank)?.map(spell=>({spell,signature:this.entry.isFlexible&&spell.system.location.signature}))??[];return Object.values(spellPrepList).some(s=>!!s.length)?spellPrepList:null}};_assertEntryIsDocument=new WeakSet,assertEntryIsDocument_fn=__name2(function(entry){if(!(entry instanceof ItemPF2e))throw ErrorPF2e("`this#entry` is not a `SpellcastingEntryPF2e`")},"#assertEntryIsDocument"),_getRitualData=new WeakSet,getRitualData_fn=__name2(async function(){const groupedByRank=groupBy(Array.from(this.values()),s=>s.rank);return{levels:Array.from(groupedByRank.entries()).sort(([a],[b])=>a-b).map(([rank,spells])=>({label:game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,isCantrip:!1,active:spells.map(spell=>({spell}))})),spellPrepList:null}},"#getRitualData"),__name2(_SpellCollection,"SpellCollection");let SpellCollection=_SpellCollection;const _SpellcastingEntryPF2e=class extends ItemPF2e{static{__name(this,"_SpellcastingEntryPF2e")}get attribute(){return this.system.ability.value||"cha"}get ability(){return foundry.utils.logCompatibilityWarning("`SpellcastingEntryPF2e#ability` is deprecated. Use `SpellcastingEntryPF2e#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}get tradition(){const defaultTradition=this.system.prepared.value==="items"?null:"arcane",tradition=this.system.tradition.value;return setHasElement(MAGIC_TRADITIONS,tradition)?tradition:defaultTradition}get category(){return this.system.prepared.value}get rank(){return this.system.proficiency.value??0}get isPrepared(){return this.system.prepared.value==="prepared"}get isFlexible(){return this.isPrepared&&!!this.system.prepared.flexible}get isSpontaneous(){return this.system.prepared.value==="spontaneous"}get isInnate(){return this.system.prepared.value==="innate"}get isFocusPool(){return this.system.prepared.value==="focus"}get isRitual(){return!1}get highestLevel(){return this.spells?.highestRank??0}get showSlotlessLevels(){return this.system.showSlotlessLevels.value}prepareBaseData(){super.prepareBaseData(),this.system.proficiency.slug||=this.system.tradition.value,this.system.proficiency.value=Math.max(1,this.system.proficiency.value),this.system.prepared.flexible??=!1,this.system.prepared.validItems||=null,this.actor&&(this.statistic=new Statistic(this.actor,{slug:this.slug??sluggify(this.name),label:"PF2E.Actor.Creature.Spellcasting.InvalidProficiency",check:{type:"check"}}))}prepareSiblingData(){if(!this.actor||this.system.prepared.value==="items")this.spells=null;else{this.spells=new SpellCollection(this);const spells=this.actor.itemTypes.spell.filter(i=>i.system.location.value===this.id);for(const spell of spells)this.spells.set(spell.id,spell);this.actor.spellcasting.collections.set(this.spells.id,this.spells)}}prepareActorData(){const actor=this.actor,tradition=this.tradition;if(actor.isOfType("character")&&!this.isInnate&&tradition){const proficiency=actor.system.proficiencies.traditions[tradition],rank=this.system.proficiency.value;proficiency.rank=Math.max(rank,proficiency.rank)}}prepareStatistic(){const actor=this.actor;if(!actor)return;const{attribute,tradition}=this,slug=this.slug??sluggify(`${this.name}-spellcasting`),baseDomains=["all",`${attribute}-based`,"spell-attack-dc"],checkDomains=[`${tradition}-spell-attack`,"spell-attack","spell-attack-roll","attack","attack-roll"],dcDomains=[`${tradition}-spell-dc`,"spell-dc"];if(actor.isOfType("character")){if(this.isInnate){const allRanks=Object.values(actor.traditions).map(t=>t.rank??0);this.system.proficiency.value=Math.max(1,this.rank,...allRanks)}const baseStat=actor.getStatistic(this.system.proficiency.slug);if(!baseStat)return;this.system.ability.value=baseStat.attribute??this.system.ability.value,this.system.proficiency.value=Math.max(this.rank,baseStat.rank??0),this.statistic=baseStat.extend({slug,attribute:this.attribute,rank:this.rank,rollOptions:this.getRollOptions("spellcasting"),domains:baseDomains,check:{type:"attack-roll",domains:checkDomains},dc:{domains:dcDomains}})}else if(actor.isOfType("npc")){const adjustment=actor.isElite?2:actor.isWeak?-2:0,baseMod=Number(this.system?.spelldc?.value??0)+adjustment,baseDC=Number(this.system?.spelldc?.dc??0)+adjustment;this.statistic=new Statistic(actor,{slug,attribute:this.attribute,label:CONFIG.PF2E.magicTraditions[tradition??"arcane"],domains:baseDomains,rollOptions:this.getRollOptions("spellcasting"),check:{type:"attack-roll",domains:checkDomains,modifiers:[new ModifierPF2e("PF2E.ModifierTitle",baseMod,"untyped")]},dc:{domains:dcDomains,modifiers:[new ModifierPF2e("PF2E.ModifierTitle",baseDC-10,"untyped")]}})}else throw ErrorPF2e(`Actor type ${actor.type} does not support spellcasting entries`);const stat=actor.isOfType("npc")?{value:this.statistic.dc.value}:{value:this.statistic.dc.value,rank:this.statistic.rank??0},attributes=actor.system.attributes;stat.value>attributes.classOrSpellDC.value&&(attributes.classOrSpellDC=stat),(!attributes.spellDC||stat.value>attributes.spellDC.value)&&(attributes.spellDC=stat)}getLinkedItems(){return this.actor?.itemTypes.spell.filter(i=>i.system.location.value===this.id)??[]}canCast(spell,{origin}={}){if(this.system.prepared.value==="items")return origin?this.system.prepared.validItems==="scroll"?origin.traits.has("scroll"):!0:!1;const isSpellcastingFeature=this.isPrepared||this.isSpontaneous;if(origin&&!isSpellcastingFeature||!this.spells)return!1;const matchesTradition=this.tradition&&spell.traditions.has(this.tradition),isInSpellList=this.spells.some(s=>s.slug===spell.slug);return matchesTradition||isInSpellList}async cast(spell,options={}){const consume=options.consume??!0,message=options.message??!0,slotRank=options.level??spell.rank,valid=!consume||spell.isCantrip||await this.consume(spell,slotRank,options.slot);if(message&&valid){const castRank=spell.computeCastRank(slotRank);await spell.toMessage(void 0,{rollMode:options.rollMode,data:{castLevel:castRank}})}}async consume(spell,rank,slot){const actor=this.actor;if(!actor?.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries require an actor");if(this.isRitual)return!0;if(spell.isVariant&&(spell=spell.original),this.isFocusPool&&actor.isOfType("character","npc")){const currentPoints=actor.system.resources.focus?.value??0;return currentPoints>0?(await actor.update({"system.resources.focus.value":currentPoints-1}),!0):(ui.notifications.warn(game.i18n.localize("PF2E.Focus.NotEnoughFocusPointsError")),!1)}const rankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),slotKey=goesToEleven(rank)?`slot${rank}`:"slot0";if(this.system.slots===null||!this.spells)return!1;if(this.isPrepared&&!this.isFlexible){const preparedData=this.system.slots[slotKey].prepared;if(slot??=Number(Object.entries(preparedData).filter(([_,slot2])=>slot2.id===spell.id&&!slot2.expended).at(0)?.[0]),!Number.isInteger(slot))throw ErrorPF2e("Slot not given for prepared spell, and no alternative slot was found");return preparedData[slot].expended??!1?(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotExpendedError",{name:spell.name})),!1):(await this.spells.setSlotExpendedState(rank,slot,!0),!0)}if(this.isInnate){const remainingUses=spell.system.location.uses?.value||0;return remainingUses<=0?(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotExpendedError",{name:spell.name})),!1):(await spell.update({"system.location.uses.value":remainingUses-1}),!0)}const slots=this.system.slots[slotKey];return slots.value>0?(await this.update({[`system.slots.${slotKey}.value`]:slots.value-1}),!0):(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotNotEnoughError",{name:spell.name,level:rankLabel})),!1)}async addSpell(spell,options){return this.spells?.addSpell(spell,options)??null}async prepareSpell(spell,slotRank,spellSlot){return this.spells?.prepareSpell(spell,slotRank,spellSlot)??null}async unprepareSpell(spellLevel,slotRank){return this.spells?.unprepareSpell(spellLevel,slotRank)??null}async setSlotExpendedState(slotRank,spellSlot,isExpended){return this.spells?.setSlotExpendedState(slotRank,spellSlot,isExpended)??null}async getSheetData(){if(!this.actor?.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries can only exist on characters and npcs");const spellCollectionData=await this.spells?.getSpellData()??{levels:[],spellPrepList:null};return{id:this.id,name:this.name,sort:this.sort,attribute:this.attribute,statistic:this.statistic.getChatData(),tradition:this.tradition,category:this.system.prepared.value,isPrepared:this.isPrepared,isSpontaneous:this.isSpontaneous,isFlexible:this.isFlexible,isInnate:this.isInnate,isFocusPool:this.isFocusPool,isRitual:this.isRitual,hasCollection:!!this.spells,showSlotlessLevels:this.showSlotlessLevels,...spellCollectionData}}getRollOptions(prefix="spellcasting"){return[`${prefix}:${this.attribute}`,`${prefix}:${this.tradition}`,`${prefix}:${this.system.prepared.value}`]}async _preUpdate(changed,options,user){if(changed.system?.slots)for(const key of[0,1,2,3,4,5,6,7,8,9,10]){const slotKey=`slot${key}`,slotData=changed.system.slots[slotKey];if(slotData&&("max"in slotData&&(slotData.max=Math.max(Number(slotData.max)||0,0)),"value"in slotData)){const max="max"in slotData?Number(slotData?.max)||0:this.system.slots[slotKey].max;slotData.value=Math.clamped(Number(slotData.value),0,max)}}return super._preUpdate(changed,options,user)}getSpellData(){return this.getSheetData()}};__name2(_SpellcastingEntryPF2e,"SpellcastingEntryPF2e");let SpellcastingEntryPF2e=_SpellcastingEntryPF2e;function applyIWR(actor,roll,rollOptions){if(actor.isDead)return{finalDamage:0,applications:[],persistent:[]};if(!game.settings.get("pf2e","automation.iwr"))return{finalDamage:roll.total,applications:[],persistent:roll.instances.filter(i=>i.persistent&&!i.options.evaluatePersistent)};const{immunities,weaknesses,resistances}=actor.attributes,instances=roll.instances,persistent=[],ignoredResistances=(roll.options.ignoredResistances??[]).map(ir=>new Resistance({type:ir.type,value:ir.max??1/0})),nonDamageWeaknesses=weaknesses.filter(w=>NON_DAMAGE_WEAKNESSES.has(w.type)&&instances.some(i=>w.test([...i.formalDescription,...rollOptions]))),damageWeaknesses=weaknesses.filter(w=>!nonDamageWeaknesses.includes(w)),applications=instances.flatMap(instance=>{const formalDescription=new Set([...instance.formalDescription,...rollOptions]),wasIncreased=instance.total<=0&&typeof roll.options.increasedFrom=="number",isFirst=instances.indexOf(instance)===0,instanceTotal=wasIncreased&&isFirst?1:Math.max(instance.total,0);if(!actor.isAffectedBy(instance.type))return[{category:"unaffected",type:instance.type,adjustment:-1*instanceTotal}];const immunity=immunities.find(i=>i.test(formalDescription));if(immunity)return[{category:"immunity",type:immunity.label,adjustment:-1*instanceTotal}];const critImmunity=immunities.find(i=>i.type==="critical-hits"),critImmunityApplies=roll.options.degreeOfSuccess===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS&&!!critImmunity?.test([...formalDescription,"damage:component:critical"]),critImmuneTotal=critImmunityApplies&&roll.options.degreeOfSuccess===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS?instance.critImmuneTotal:instanceTotal,instanceApplications=[];critImmunity&&critImmuneTotali.type==="precision"),precisionDamage=Math.min(instance.componentTotal("precision"),critImmuneTotal);if(precisionDamage>0&&precisionImmunity?.test([...formalDescription,"damage:component:precision"])){const adjustedPrecisionDamage=critImmunityApplies?Math.floor(precisionDamage/2):precisionDamage,adjustment2=-1*Math.min(critImmuneTotal,adjustedPrecisionDamage);instanceApplications.push({category:"immunity",type:precisionImmunity.applicationLabel,adjustment:adjustment2})}const afterImmunities=Math.max(instanceTotal+instanceApplications.reduce((sum2,a)=>sum2+a.adjustment,0),0);if(instance.persistent&&!instance.options.evaluatePersistent&&persistent.push(instance),afterImmunities===0)return instanceApplications;const mainWeaknesses=damageWeaknesses.filter(w=>w.test(formalDescription)),splashWeakness=instance.componentTotal("splash")?weaknesses.find(w=>w.type==="splash-damage")??null:null,precisionWeakness=precisionDamage>0?weaknesses.find(r=>r.type==="precision"):null,highestWeakness=compact([...mainWeaknesses,precisionWeakness,splashWeakness]).reduce((highest,w)=>w&&!highest||w&&highest&&w.value>highest.value?w:highest,null);highestWeakness&&instanceApplications.push({category:"weakness",type:highestWeakness.applicationLabel,adjustment:highestWeakness.value});const afterWeaknesses=afterImmunities+(highestWeakness?.value??0),applicableResistances=resistances.filter(r=>r.test(formalDescription)).map(r=>({label:r.applicationLabel,value:r.getDoubledValue(formalDescription),ignored:ignoredResistances.some(ir=>ir.test(formalDescription))})),precisionResistance=(()=>{const resistance=precisionDamage>0?resistances.find(r=>r.type==="precision"):null;return resistance?{label:resistance.applicationLabel,value:Math.min(resistance.value,precisionDamage),ignored:!1}:null})();precisionResistance&&applicableResistances.push(precisionResistance);const highestResistance=applicableResistances.filter(r=>!r.ignored).reduce((highest,r)=>r&&!highest||r&&highest&&r.value>highest.value?r:highest,null),highestIgnored=applicableResistances.filter(r=>r.ignored).reduce((highest,r)=>r&&!highest||r&&highest&&r.value>highest.value?r:highest,null);return highestResistance?.value?instanceApplications.push({category:"resistance",type:highestResistance.label,adjustment:-1*Math.min(afterWeaknesses,highestResistance.value),ignored:!1}):highestIgnored&&instanceApplications.push({category:"resistance",type:ignoredResistances.find(ir=>ir.test(formalDescription)).typeLabel,adjustment:0,ignored:!0}),instanceApplications}).concat(...nonDamageWeaknesses.map(w=>({category:"weakness",type:w.typeLabel,adjustment:w.value}))).sort((a,b)=>{if(a.category===b.category)return 0;switch(a.category){case"unaffected":return-1;case"immunity":return b.type==="unaffected"?1:-1;case"weakness":return["unaffected","immunity"].includes(b.category)?1:-1;default:return 1}}),adjustment=applications.reduce((sum2,a)=>sum2+a.adjustment,0);return{finalDamage:Math.max(roll.total+adjustment,0),applications,persistent}}__name(applyIWR,"applyIWR"),__name2(applyIWR,"applyIWR");const _ActorConditions=class extends DelegatedCollection{static{__name(this,"_ActorConditions")}constructor(){super(...arguments),__privateAdd(this,_slugMap,new Collection)}get active(){return this.filter(c=>c.active)}get stored(){return this.filter(c=>!c.inMemoryOnly)}get clumsy(){return this.bySlug("clumsy",{active:!0}).shift()??null}get doomed(){return this.bySlug("doomed",{active:!0}).shift()??null}get drained(){return this.bySlug("drained",{active:!0}).shift()??null}get dying(){return this.bySlug("dying",{active:!0}).shift()??null}get enfeebled(){return this.bySlug("enfeebled",{active:!0}).shift()??null}get frightened(){return this.bySlug("frightened",{active:!0}).shift()??null}get sickened(){return this.bySlug("sickened",{active:!0}).shift()??null}get slowed(){return this.bySlug("slowed",{active:!0}).shift()??null}get stunned(){return this.bySlug("stunned",{active:!0}).shift()??null}get stupefied(){return this.bySlug("stupefied",{active:!0}).shift()??null}get wounded(){return this.bySlug("wounded",{active:!0}).shift()??null}get(key,{strict=!1,active=null,temporary=null}={}){const condition=super.get(key,{strict});if(!(active===!0&&!condition?.active)&&!(active===!1&&condition?.active)&&!(temporary===!0&&condition?.actor.items.has(key))&&!(temporary===!1&&!condition?.actor.items.has(key)))return condition}set(id,condition){super.set(id,condition);const listBySlug=__privateGet(this,_slugMap).get(condition.slug)??[];return listBySlug.push(condition),__privateGet(this,_slugMap).set(condition.slug,listBySlug),this}every(condition){return this.contents.every(condition)}flatMap(transformer){return this.contents.flatMap(transformer)}delete(){return!1}bySlug(slug,{active=null,temporary=null}={}){return(__privateGet(this,_slugMap).get(slug)??[]).filter(condition=>{const activeFilterSatisfied=active===!0?condition.active:active===!1?!condition.active:!0,temporaryFilterSatisfied=temporary===!0?!condition.actor.items.has(condition.id):temporary===!1?condition.actor.items.has(condition.id):!0;return activeFilterSatisfied&&temporaryFilterSatisfied})}};_slugMap=new WeakMap,__name2(_ActorConditions,"ActorConditions");let ActorConditions=_ActorConditions;var VisionLevels=(VisionLevels2=>(VisionLevels2[VisionLevels2.BLINDED=0]="BLINDED",VisionLevels2[VisionLevels2.NORMAL=1]="NORMAL",VisionLevels2[VisionLevels2.LOWLIGHT=2]="LOWLIGHT",VisionLevels2[VisionLevels2.DARKVISION=3]="DARKVISION",VisionLevels2))(VisionLevels||{});const _ItemTransfer=class _ItemTransfer2{static{__name(this,"_ItemTransfer")}constructor(source,target,quantity,containerId){__privateAdd(this,_getActor),__privateAdd(this,_getSource),__privateAdd(this,_getTarget),__privateAdd(this,_sendMessage),__privateAdd(this,_messageFlavor),__privateAdd(this,_templatePaths,{flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"}),this.source=source,this.target=target,this.quantity=quantity,this.containerId=containerId}async request(){var _a;const gamemaster=game.users.find(u=>u.isGM&&u.active);if(!gamemaster){const source=__privateMethod(this,_getSource,getSource_fn).call(this),target=__privateMethod(this,_getTarget,getTarget_fn).call(this),loot=[source,target].find(a=>a?.isLootableBy(game.user)&&!a.isOwner);if(!loot)throw ErrorPF2e("Unexpected missing actor");ui.notifications.error(game.i18n.format("PF2E.loot.GMSupervisionError",{loot:__privateMethod(_a=_ItemTransfer2,_tokenName,tokenName_fn).call(_a,loot)}));return}console.debug(`PF2e System | Requesting item transfer from GM ${gamemaster.name}`),game.socket.emit("system.pf2e",{request:"itemTransfer",data:this})}async enact(requester){if(!game.user.isGM)throw ErrorPF2e("Unauthorized item transfer");console.debug("PF2e System | Enacting item transfer");const sourceActor=__privateMethod(this,_getSource,getSource_fn).call(this),sourceItem=sourceActor?.inventory.find(i=>i.id===this.source.itemId),targetActor=__privateMethod(this,_getTarget,getTarget_fn).call(this);if(!(sourceActor?.isLootableBy(game.user)&&sourceItem&&targetActor?.isLootableBy(game.user)))throw ErrorPF2e("Failed sanity check during item transfer");const targetItem=await sourceActor.transferItemToActor(targetActor,sourceItem,this.quantity,this.containerId),sourceIsLoot=sourceActor.isOfType("loot")&&sourceActor.system.lootSheetType==="Loot";!sourceItem&&sourceIsLoot||__privateMethod(this,_sendMessage,sendMessage_fn).call(this,requester,sourceActor,targetActor,targetItem)}};_templatePaths=new WeakMap,_getActor=new WeakSet,getActor_fn=__name2(function(tokenId,actorId){return typeof tokenId=="string"?canvas.tokens.placeables.find(t=>t.id===tokenId)?.actor??null:game.actors.get(actorId)??null},"#getActor"),_getSource=new WeakSet,getSource_fn=__name2(function(){return __privateMethod(this,_getActor,getActor_fn).call(this,this.source.tokenId,this.source.actorId)},"#getSource"),_getTarget=new WeakSet,getTarget_fn=__name2(function(){return __privateMethod(this,_getActor,getActor_fn).call(this,this.target.tokenId,this.target.actorId)},"#getTarget"),_tokenName=new WeakSet,tokenName_fn=__name2(function(document2){return"items"in document2?document2.isOfType("party")?game.i18n.localize("PF2E.loot.PartyStash"):document2.token?document2.token.name:document2.prototypeToken?.name??document2.name:document2.character?canvas.tokens.placeables.find(t=>t.actor?.id===document2.id)?.name??document2.character?.name:document2.name},"#tokenName"),_sendMessage=new WeakSet,sendMessage_fn=__name2(async function(requester,sourceActor,targetActor,item){var _a;const localize=localizer("PF2E.loot");if(!item)if(sourceActor.isOfType("loot")&&sourceActor.system.lootSheetType==="Merchant"){const message=localize("InsufficientFundsMessage"),content2=await renderTemplate(__privateGet(this,_templatePaths).content,{imgPath:targetActor.img,message:game.i18n.format(message,{buyer:targetActor.name})}),flavor2=await __privateMethod(this,_messageFlavor,messageFlavor_fn).call(this,sourceActor,targetActor,localize("BuySubtitle"));await ChatMessage.create({user:requester.id,speaker:{alias:__privateMethod(_a=_ItemTransfer,_tokenName,tokenName_fn).call(_a,targetActor)},type:CONST.CHAT_MESSAGE_TYPES.EMOTE,flavor:flavor2,content:content2});return}else throw ErrorPF2e("Unexpected item-transfer failure");const[speaker,subtitle,formatArgs]=(()=>{var _a2,_b,_c,_d,_e,_f,_g,_h,_i,_j,_k,_l,_m,_n,_o,_p,_q,_r,_s,_t,_u,_v;const isMerchant=__name2(actor=>actor.isOfType("loot")&&actor.isMerchant,"isMerchant"),isWhat=__name2(actor=>({isCharacter:actor.testUserPermission(requester,"OWNER")&&actor.isOfType("character"),isMerchant:isMerchant(actor),isNPC:actor.isOfType("npc")&&actor.isLootableBy(requester)&&!actor.testUserPermission(requester,"OWNER"),isLoot:(actor.isOfType("party")||actor.isOfType("loot"))&&actor.isLootableBy(requester)&&!actor.testUserPermission(requester,"OWNER")&&!isMerchant(actor)}),"isWhat"),source=isWhat(sourceActor),target=isWhat(targetActor);if(source.isCharacter&&target.isLoot)return[__privateMethod(_a2=_ItemTransfer,_tokenName,tokenName_fn).call(_a2,sourceActor),localize("DepositSubtitle"),[localize("DepositMessage"),{depositor:__privateMethod(_b=_ItemTransfer,_tokenName,tokenName_fn).call(_b,sourceActor),container:__privateMethod(_c=_ItemTransfer,_tokenName,tokenName_fn).call(_c,targetActor)}]];if(source.isCharacter&&target.isMerchant)return[__privateMethod(_d=_ItemTransfer,_tokenName,tokenName_fn).call(_d,sourceActor),localize("GiveSubtitle"),[localize("GiveMessage"),{giver:__privateMethod(_e=_ItemTransfer,_tokenName,tokenName_fn).call(_e,sourceActor),recipient:__privateMethod(_f=_ItemTransfer,_tokenName,tokenName_fn).call(_f,targetActor)}]];if(source.isCharacter&&target.isNPC)return[__privateMethod(_g=_ItemTransfer,_tokenName,tokenName_fn).call(_g,sourceActor),localize("PlantSubtitle"),[localize("PlantMessage"),{planter:__privateMethod(_h=_ItemTransfer,_tokenName,tokenName_fn).call(_h,sourceActor),corpse:__privateMethod(_i=_ItemTransfer,_tokenName,tokenName_fn).call(_i,targetActor)}]];if(source.isLoot&&target.isCharacter)return[__privateMethod(_j=_ItemTransfer,_tokenName,tokenName_fn).call(_j,targetActor),localize("TakeSubtitle"),[localize("TakeMessage"),{taker:__privateMethod(_k=_ItemTransfer,_tokenName,tokenName_fn).call(_k,targetActor),container:__privateMethod(_l=_ItemTransfer,_tokenName,tokenName_fn).call(_l,sourceActor)}]];if(source.isNPC&&target.isCharacter)return[__privateMethod(_m=_ItemTransfer,_tokenName,tokenName_fn).call(_m,targetActor),localize("LootSubtitle"),[localize("LootMessage"),{looter:__privateMethod(_n=_ItemTransfer,_tokenName,tokenName_fn).call(_n,targetActor),corpse:__privateMethod(_o=_ItemTransfer,_tokenName,tokenName_fn).call(_o,sourceActor)}]];if([source,target].every(actor=>actor.isLoot||actor.isNPC))return[requester.character?.name??requester.name,localize("TransferSubtitle"),[localize("TransferMessage"),{transferrer:requester.character?.name??requester.name,fromContainer:__privateMethod(_p=_ItemTransfer,_tokenName,tokenName_fn).call(_p,sourceActor),toContainer:__privateMethod(_q=_ItemTransfer,_tokenName,tokenName_fn).call(_q,targetActor)}]];if(source.isLoot&&target.isMerchant)return[requester.character?.name??requester.name,localize("GiveSubtitle"),[localize("GiveMessage"),{seller:requester.character?.name??requester.name,buyer:__privateMethod(_r=_ItemTransfer,_tokenName,tokenName_fn).call(_r,targetActor)}]];if(source.isMerchant&&target.isCharacter)return[__privateMethod(_s=_ItemTransfer,_tokenName,tokenName_fn).call(_s,sourceActor),localize("SellSubtitle"),[localize("SellMessage"),{seller:__privateMethod(_t=_ItemTransfer,_tokenName,tokenName_fn).call(_t,sourceActor),buyer:__privateMethod(_u=_ItemTransfer,_tokenName,tokenName_fn).call(_u,targetActor)}]];if(source.isMerchant&&target.isLoot)return[requester.character?.name??requester.name,localize("SellSubtitle"),[localize("SellMessage"),{seller:__privateMethod(_v=_ItemTransfer,_tokenName,tokenName_fn).call(_v,sourceActor),buyer:requester.character?.name??requester.name}]];throw ErrorPF2e("Unexpected item-transfer failure")})(),formatProperties=formatArgs[1];if(!formatProperties)throw ErrorPF2e("Unexpected item-transfer failure");formatProperties.quantity=this.quantity,formatProperties.item=item.name;const content=await renderTemplate(__privateGet(this,_templatePaths).content,{imgPath:item.img,message:game.i18n.format(...formatArgs).replace(/\b1 × /,"")}),flavor=await __privateMethod(this,_messageFlavor,messageFlavor_fn).call(this,sourceActor,targetActor,subtitle);await ChatMessage.create({user:requester.id,speaker:{alias:speaker},type:CONST.CHAT_MESSAGE_TYPES.EMOTE,flavor,content})},"#sendMessage"),_messageFlavor=new WeakSet,messageFlavor_fn=__name2(async function(sourceActor,targetActor,subtitle){const glyph=getActionGlyph(sourceActor.isOfType("loot")&&targetActor.isOfType("loot")?2:1),action2={title:"PF2E.Actions.Interact.Title",subtitle,glyph},traits=[{name:"manipulate",label:CONFIG.PF2E.featTraits.manipulate,description:CONFIG.PF2E.traitsDescriptions.manipulate}];return await renderTemplate(__privateGet(this,_templatePaths).flavor,{action:action2,traits})},"#messageFlavor"),__privateAdd(_ItemTransfer,_tokenName),__name2(_ItemTransfer,"ItemTransfer");let ItemTransfer=_ItemTransfer;const _ActorSpellcasting=class extends Collection{static{__name(this,"_ActorSpellcasting")}constructor(actor,entries){super(entries.map(entry=>[entry.id,entry])),this.actor=actor;for(const entry of entries)entry.spells&&this.collections.set(entry.spells.id,entry.spells)}collections=new Collection;get regular(){return this.filter(e=>e instanceof SpellcastingEntryPF2e)}get ritual(){const ritualCasting=this.collections.get("rituals")?.entry;return ritualCasting instanceof RitualSpellcasting?ritualCasting:null}get spellcastingFeatures(){return this.regular.filter(e=>e.isPrepared||e.isSpontaneous)}canCastConsumable(item){const spell=item.embeddedSpell;return!!spell&&this.some(e=>e.canCast(spell,{origin:item}))}refocus(options={}){if(!options.all)throw ErrorPF2e("Actors do not currently support regular refocusing");if(this.actor.isOfType("character","npc")){const focus=this.actor.system.resources.focus,rechargeFocus=focus?.max&&focus.value{if(!(entry instanceof SpellcastingEntryPF2e))return[];if(entry.isFocusPool||!entry.spells)return[];if(entry.isInnate)return entry.spells.map(spell=>{const value=spell.system.location.uses?.max??1;return{_id:spell.id,"system.location.uses.value":value}});const slots=entry.system.slots;let updated=!1;for(const slot of Object.values(slots))if(entry.isPrepared&&!entry.isFlexible)for(const preparedSpell of Object.values(slot.prepared))preparedSpell.expended&&(preparedSpell.expended=!1,updated=!0);else slot.valueu.active),primaryPlayer=this.isToken?null:activeUsers.find(u=>u.character?.id===this.id);return primaryPlayer||(game.users.filter(u=>this.canUserModify(u,"update")).sort((a,b)=>a.id>b.id?1:-1).shift()??null)}get abilities(){return null}get attributes(){return this.system.attributes}get hitPoints(){const{hp}=this.system.attributes;return hp?{value:hp.value,max:hp.max,temp:hp.temp,unrecoverable:hp.unrecoverable,negativeHealing:hp.negativeHealing}:null}get traits(){return new Set(this.system.traits?.value??[])}get level(){return this.system.details.level.value}get size(){return this.system.traits?.size.value??"med"}get dimensions(){const size=this.system.traits?.size??new ActorSizePF2e({value:"med"});return{length:size.length,width:size.width,height:Math.min(size.length,size.width)}}get canSee(){return!0}get canAct(){return!0}get canAttack(){return!1}get isDead(){const deathIcon=game.settings.get("pf2e","deathIcon");if(this.token)return this.token.overlayEffect===deathIcon;const tokens=this.getActiveTokens(!0,!0);return tokens.length>0&&tokens.every(t=>t.overlayEffect===deathIcon)}get modeOfBeing(){const{traits}=this,isPC=isReallyPC(this);return traits.has("undead")&&!traits.has("eidolon")?"undead":traits.has("construct")&&!isPC&&!traits.has("eidolon")?"construct":"living"}get visionLevel(){return VisionLevels.NORMAL}get emitsSound(){return!1}get rollOptions(){return this.flags.pf2e.rollOptions}get heldShield(){return null}get hardness(){return 0}get canHostRuleElements(){return!0}get alliance(){return this.system.details.alliance}get combatant(){return game.combat?.combatants.find(c=>c.actor?.uuid===this.uuid)??null}get temporaryEffects(){const fromConditions=this.conditions.active.map(c=>new TokenEffect(c)),fromEffects=this.itemTypes.effect.filter(e=>e.system.tokenIcon?.show&&(e.isIdentified||game.user.isGM)).map(e=>new TokenEffect(e));return[super.temporaryEffects,fromConditions,fromEffects,this.synthetics.tokenEffectIcons].flat()}isOfType(...types){return types.some(t=>t==="creature"?tupleHasValue(CREATURE_ACTOR_TYPES,this.type):this.type===t)}isAllyOf(actor){return this.alliance!==null&&this!==actor&&this.alliance===actor.alliance}isEnemyOf(actor){return this.alliance!==null&&actor.alliance!==null&&this.alliance!==actor.alliance}isImmuneTo(effect){if(!game.settings.get("pf2e","automation.iwr"))return!1;const item=typeof effect=="string"?null:"parent"in effect?effect:new ItemProxyPF2e(effect),statements=new Set(item?item.getRollOptions("item"):["item:type:condition",`item:slug:${effect}`]);return this.attributes.immunities.some(i=>i.test(statements))}isAffectedBy(damage){const damageType=objectHasKey(CONFIG.PF2E.damageTypes,damage)?damage:damage.isOfType("condition")?damage.system.persistent?.damageType??null:null;if(!setHasElement(UNAFFECTED_TYPES,damageType))return!0;const{traits}=this;return{good:traits.has("evil"),evil:traits.has("good"),lawful:traits.has("chaotic"),chaotic:traits.has("lawful"),vitality:!!this.attributes.hp?.negativeHealing,void:!(this.modeOfBeing==="construct"||this.attributes.hp?.negativeHealing),bleed:this.modeOfBeing==="living",spirit:!(this.modeOfBeing==="undead"&&traits.has("mindless")||this.itemTypes.effect.some(e=>e.traits.has("possession")))}[damageType]}getStatistic(slug){return["armor","ac"].includes(slug)?this.armorClass?.parent??null:tupleHasValue(SAVE_TYPES,slug)?this.saves?.[slug]??null:this.skills&&objectHasKey(this.skills,slug)?this.skills[slug]??null:this.synthetics.statistics.get(slug)??null}getSelfRollOptions(prefix="self"){const{rollOptions}=this;return Object.keys(rollOptions.all).flatMap(o=>o.startsWith("self:")&&rollOptions.all[o]?o.replace(/^self/,prefix):[])}getReach(_options){return 0}getContextualClone(rollOptions,ephemeralEffects=[]){const rollOptionsAll=rollOptions.reduce((options,option)=>({...options,[option]:!0}),{}),applicableEffects=ephemeralEffects.filter(e=>!this.isImmuneTo(e));return this.clone({items:[deepClone(this._source.items),applicableEffects].flat(),flags:{pf2e:{rollOptions:{all:rollOptionsAll}}}},{keepId:!0})}async applyAreaEffects(aura,origin){if(game.user!==this.primaryUpdater||this.isOfType("party")||!this.allowedItemTypes.includes("effect")||origin.token.hidden)return;const toCreate=[],rollOptions=aura.effects.some(e=>e.predicate.length>0)?new Set([...origin.actor.getRollOptions(),...this.getSelfRollOptions("target")]):new Set([]);for(const data of aura.effects.filter(e=>e.predicate.test(rollOptions)))if(!this.itemTypes.effect.some(e=>e.sourceId===data.uuid)&&auraAffectsActor(data,origin.actor,this)){const effect=await fromUuid(data.uuid);if(!(effect instanceof ItemPF2e&&effect.isOfType("affliction","effect"))){console.warn(`Effect from ${data.uuid} not found`);continue}const flags={core:{sourceId:effect.uuid},pf2e:{aura:{slug:aura.slug,origin:origin.actor.uuid,removeOnExit:data.removeOnExit}}},source=mergeObject(effect.toObject(),{flags});source.system.level.value=aura.level??source.system.level.value,source.system.duration.unit="unlimited",source.system.duration.expiry=null,source.system.traits.value.length===0&&source.system.traits.value.push(...aura.traits),source.system.context={target:null,origin:{actor:origin.actor.uuid,token:origin.token.uuid,item:null,spellcasting:null},roll:null};for(const alteration of data.alterations)alteration.applyTo(source);toCreate.push(source)}toCreate.length>0&&await this.createEmbeddedDocuments("Item",toCreate)}static async createDialog(data={},context={}){const omittedTypes=[],original=game.system.documentTypes.Actor;try{if(game.system.documentTypes.Actor=difference(original,omittedTypes),context.types){const validTypes=context.types??[];validTypes.includes("creature")&&validTypes.push(...CREATURE_ACTOR_TYPES),game.system.documentTypes.Actor=game.system.documentTypes.Actor.filter(type=>tupleHasValue(validTypes,type))}return super.createDialog(data,context)}finally{game.system.documentTypes.Actor=original}}static async createDocuments(data=[],context={}){const sources=data.map(d=>d instanceof _ActorPF2e2?d.toObject():d);for(const source of[...sources]){const linkable=SIZE_LINKABLE_ACTOR_TYPES.has(source.type),linkToActorSize=linkable&&(source.prototypeToken?.flags?.pf2e?.linkToActorSize??!0),autoscale=linkable&&(source.prototypeToken?.flags?.pf2e?.autoscale??(linkToActorSize&&game.settings.get("pf2e","tokens.autoscale"))),merged=mergeObject(source,{ownership:source.ownership??{default:CONST.DOCUMENT_OWNERSHIP_LEVELS.NONE},prototypeToken:{flags:{pf2e:{linkToActorSize,autoscale}}}}),dimensionMap={familiar:.5,vehicle:2};switch(merged.prototypeToken.height??=dimensionMap[source.type]??1,merged.prototypeToken.width??=merged.prototypeToken.height,merged.type){case"character":case"familiar":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!0};break;case"loot":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!1};break;case"party":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!0,range:1};break}const migrated=await migrateActorSource(source);sources.splice(sources.indexOf(source),1,migrated)}return super.createDocuments(sources,context)}static async updateDocuments(updates=[],context={}){for(const changed of updates)await processPreUpdateActorHooks(changed,{pack:context.pack??null});return super.updateDocuments(updates,context)}_initialize(options){this.constructed??=!1,this.signature??=UUIDv5(this.uuid,"e9fa1461-0edc-4791-826e-08633f1c6ef7"),this._itemTypes=null,this.rules=[],this.initiative=null,this.armorClass=null,this.conditions=new ActorConditions,this.auras=new Map;const preparationWarnings=new Set;this.synthetics={criticalSpecalizations:{standard:[],alternate:[]},damageDice:{damage:[]},degreeOfSuccessAdjustments:{},dexterityModifierCaps:[],modifierAdjustments:{all:[],damage:[]},modifiers:{all:[],damage:[]},movementTypes:{},multipleAttackPenalties:{},ephemeralEffects:{},rollNotes:{},rollSubstitutions:{},rollTwice:{},senses:[],statistics:new Map,strikeAdjustments:[],strikes:new Map,striking:{},tokenMarks:new Map,toggles:[],tokenEffectIcons:[],tokenOverrides:{},weaponPotency:{},preparationWarnings:{add:warning=>preparationWarnings.add(warning),flush:foundry.utils.debounce(()=>{for(const warning of preparationWarnings)console.warn(warning);preparationWarnings.clear()},10)}},super._initialize(options),game._documentsReady&&this.synthetics.preparationWarnings.flush()}_initializeSource(source,options){const initialized=super._initializeSource(source,options);if(options?.pack&&initialized._id){const uuid=`Compendium.${options.pack}.${initialized._id}`,art=game.pf2e.system.moduleArt.map.get(uuid)??{};return mergeObject(initialized,art)}return initialized}prepareData(){super.prepareData();const spellcasting=this.itemTypes.spellcastingEntry,traditionBased=spellcasting.filter(s=>setHasElement(MAGIC_TRADITIONS,s.system.proficiency.slug)),nonTraditionBased=spellcasting.filter(s=>!traditionBased.includes(s));for(const entry of traditionBased)entry.prepareStatistic();for(const rule of this.rules)rule.afterPrepareData?.();for(const entry of nonTraditionBased)entry.prepareStatistic();if(this.attributes.flanking.offGuardable&&this.isImmuneTo("off-guard")&&(this.attributes.flanking.offGuardable=!1),this.preparePrototypeToken(),this.constructed&&canvas.ready){const thisTokenIsControlled=canvas.tokens.controlled.some(t=>t.document===this.parent||t.document.actorLink&&t.actor===this);(game.user.character===this||thisTokenIsControlled)&&game.pf2e.effectPanel.refresh()}}prepareBaseData(){super.prepareBaseData(),this.system.autoChanges={},this.system.attributes.flanking={canFlank:!1,canGangUp:[],flankable:!1,offGuardable:!1};const{attributes,details}=this.system;attributes.hp&&=mergeObject(attributes.hp,{negativeHealing:!1,unrecoverable:0}),attributes.immunities=attributes.immunities?.map(i=>new Immunity(i))??[],attributes.weaknesses=attributes.weaknesses?.map(w=>new Weakness(w))??[],attributes.resistances=attributes.resistances?.map(r=>new Resistance(r))??[],details.level.value=Math.floor(details.level.value)||0;const traits=this.system.traits;traits?.size&&(traits.size=new ActorSizePF2e(traits.size)),this.flags.pf2e=mergeObject(this.flags.pf2e??{},{rollOptions:{all:{[`self:type:${this.type}`]:!0,[`self:signature:${this.signature}`]:!0,...createEncounterRollOptions(this)}},trackedItems:{}})}prepareEmbeddedDocuments(){for(const item of this.items)item.reset();const physicalItems=this.items.filter(i=>i.isOfType("physical"));this.inventory=new ActorInventory(this,physicalItems),this.spellcasting=(()=>{const rituals=this.itemTypes.spell.filter(s=>s.isRitual).sort((a,b)=>a.sort-b.sort),spellcastingEntries=[this.itemTypes.spellcastingEntry,rituals.length>0?new RitualSpellcasting(this,rituals):[]].flat();return new ActorSpellcasting(this,spellcastingEntries)})();for(const effect of this.itemTypes.effect)game.pf2e.effectTracker.register(effect);this.prepareDataFromItems()}prepareDataFromItems(){for(const item of this.items)item.prepareSiblingData?.(),item.prepareActorData?.();this.rules=this.prepareRuleElements()}prepareRuleElements(){return sortBy$1(this.items.contents,i=>i instanceof AbstractEffectPF2e).flatMap(item=>item.prepareRuleElements()).filter(rule=>!rule.ignored).sort((elementA,elementB)=>elementA.priority-elementB.priority)}prepareSynthetics(){for(const rule of this.rules.filter(r=>!r.ignored))try{rule.beforePrepareData?.()}catch(error){const ruleName=game.i18n.localize(`PF2E.RuleElement.${rule.key}`);console.error(`PF2e | Failed to execute onBeforePrepareData on rule element ${ruleName}.`,error)}for(const item of this.items)item.onPrepareSynthetics?.()}prepareDerivedData(){const{rollOptions}=this;for(const trait of this.traits)rollOptions.all[`self:trait:${trait}`]=!0}preparePrototypeToken(){this.prototypeToken.flags=mergeObject({pf2e:{linkToActorSize:SIZE_LINKABLE_ACTOR_TYPES.has(this.type)}},this.prototypeToken.flags),TokenDocumentPF2e.assignDefaultImage(this.prototypeToken),TokenDocumentPF2e.prepareSize(this.prototypeToken)}async getRollContext(params){const[selfToken,targetToken]=canvas.ready&&!params.viewOnly?[canvas.tokens.controlled.find(t=>t.actor===this)??this.getActiveTokens().shift()??null,params.target?.token??params.target?.actor?.getActiveTokens().shift()??null]:[null,null],isAttackAction=["attack","attack-roll","attack-damage"].some(d=>params.domains.includes(d)),isMelee=!!(params.melee||params.item?.isOfType("weapon","melee")&¶ms.item.isMelee),reach=isMelee&¶ms.item?.isOfType("action","weapon","melee")?this.getReach({action:"attack",weapon:params.item}):this.getReach({action:"attack"}),isFlankingAttack=!!(isAttackAction&&isMelee&&typeof reach=="number"&&targetToken?.actor&&selfToken?.isFlanking(targetToken,{reach})),originEphemeralEffects=await extractEphemeralEffects({affects:"origin",origin:this,target:params.target?.actor??targetToken?.actor??null,item:params.item??null,domains:params.domains,options:[...params.options,...params.item?.getRollOptions("item")??[]]}),tokenMarkOption=(()=>{const tokenMark=targetToken?this.synthetics.tokenMarks.get(targetToken.document.uuid):null;return tokenMark?`target:mark:${tokenMark}`:null})(),selfActor=params.viewOnly||!targetToken?.actor?this:this.getContextualClone(compact([Array.from(params.options),targetToken.actor.getSelfRollOptions("target"),tokenMarkOption,isFlankingAttack?"self:flanking":null].flat()),originEphemeralEffects),isStrike=params.statistic instanceof StatisticModifier,strikeActions=isStrike?selfActor.system.actions?.flatMap(a=>[a,a.altUsages??[]].flat())??[]:[],statistic=params.viewOnly?params.statistic:isStrike?strikeActions.find(action2=>params.item?.id!==action2.item.id||params?.item.name!==action2.item.name?!1:params.item.isOfType("melee")&&action2.item.isOfType("melee")?!0:params.item.isOfType("weapon")&&action2.item.isOfType("weapon")&¶ms.item.isMelee===action2.item.isMelee)??params.statistic:params.statistic,selfItem=(()=>{if(selfActor===this)return params.item??null;if(statistic&&"item"in statistic&&statistic.item instanceof ItemPF2e&&statistic.item.isOfType("action","melee","spell","weapon"))return statistic.item;const itemClone=selfActor.items.get(params.item?.id??"");return itemClone?.isOfType("melee","weapon")?itemClone:params.item??null})(),itemOptions=selfItem?.getRollOptions("item")??[],traitSlugs=[isAttackAction?"attack":[],isStrike&&selfItem?.isOfType("weapon")&&selfItem.baseType==="alchemical-bomb"?"manipulate":[]].flat();if(selfItem?.isOfType("weapon","melee"))for(const adjustment of this.synthetics.strikeAdjustments)adjustment.adjustTraits?.(selfItem,traitSlugs);const traits=traitSlugs.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),distance=selfToken&&targetToken?selfToken.distanceTo(targetToken):null,[originDistance,targetDistance]=typeof distance=="number"?[`origin:distance:${distance}`,`target:distance:${distance}`]:[null,null],getTargetRollOptions=__name2(actor=>{const targetOptions=actor?.getSelfRollOptions("target")??[];return targetToken&&(targetOptions.push("target"),tokenMarkOption&&targetOptions.push(tokenMarkOption)),targetOptions.sort()},"getTargetRollOptions"),targetRollOptions=getTargetRollOptions(targetToken?.actor),targetEphemeralEffects=await extractEphemeralEffects({affects:"target",origin:selfActor,target:targetToken?.actor??null,item:selfItem,domains:params.domains,options:[...params.options,...itemOptions,...targetRollOptions]});if(isFlankingAttack&&isOffGuardFromFlanking(targetToken.actor,selfActor)){const name2=game.i18n.localize("PF2E.Item.Condition.Flanked"),condition=game.pf2e.ConditionManager.getCondition("off-guard",{name:name2});targetEphemeralEffects.push(condition.toObject())}const targetActor=params.viewOnly?null:(params.target?.actor??targetToken?.actor)?.getContextualClone([...selfActor.getSelfRollOptions("origin"),...params.options,...itemOptions,...originDistance?[originDistance]:[]],targetEphemeralEffects)??null,rollOptions=new Set(compact([...params.options,...selfActor.getRollOptions(params.domains),...targetActor?getTargetRollOptions(targetActor):targetRollOptions,...itemOptions,isAttackAction?"attack":null]).sort());targetDistance&&rollOptions.add(targetDistance);const rangeIncrement=selfItem?getRangeIncrement(selfItem,distance):null;rangeIncrement&&rollOptions.add(`target:range-increment:${rangeIncrement}`);const self={actor:selfActor,token:selfToken?.document??null,statistic,item:selfItem,modifiers:[]},target=targetActor&&targetToken&&distance!==null?{actor:targetActor,token:targetToken.document,distance,rangeIncrement}:null;return{options:rollOptions,self,target,traits}}async getCheckContext(params){const context=await this.getRollContext(params),targetActor=context.target?.actor,rangeIncrement=context.target?.rangeIncrement??null,rangePenalty=calculateRangePenalty(this,rangeIncrement,params.domains,context.options);rangePenalty&&context.self.modifiers.push(rangePenalty);const dcData=(()=>{const{domains,defense}=params,scope=domains.includes("attack")?"attack":"check",statistic=targetActor?.getStatistic(defense)?.dc;return statistic?{scope,statistic,slug:defense,value:statistic.value}:null})();return{...context,dc:dcData}}async getDamageRollContext(params){params.checkContext??=findMatchingCheckContext(this,params),params.outcome&¶ms.options.add(`check:outcome:${sluggify(params.outcome)}`);const substitution=params.checkContext?.substitutions.find(s=>s.selected);return substitution&¶ms.options.add(`check:substitution:${substitution.slug}`),this.getRollContext(params)}async toggleRollOption(domain,option,itemId=null,value,suboption=null){return value=typeof itemId=="boolean"?itemId:value??!this.rollOptions[domain]?.[option],typeof itemId=="string"?this.items.get(itemId,{strict:!0}).rules.find(r=>r instanceof RollOptionRuleElement&&r.domain===domain&&r.option===option)?.toggle(value,suboption)??null:this.rules.find(r=>r instanceof RollOptionRuleElement&&r.domain===domain&&r.option===option)?.toggle(value,suboption)??null}async modifyTokenAttribute(attribute,value,isDelta=!1,isBar){const token=this.getActiveTokens(!0,!0).shift(),{hitPoints}=this;if(!!(attribute==="attributes.hp"&&hitPoints&&(isDelta||value===0&&token?.combatant))&&token){const damage=isDelta?-1*value:hitPoints.value-value;return this.applyDamage({damage,token})}return super.modifyTokenAttribute(attribute,value,isDelta,isBar)}async applyDamage({damage,token,item,rollOptions=new Set,skipIWR=!1,shieldBlockRequest=!1,breakdown=[],notes=[]}){const{hitPoints}=this;if(!hitPoints)return this;const result=typeof damage=="number"?{finalDamage:Math.trunc(damage),applications:[],persistent:[]}:skipIWR?{finalDamage:damage.total,applications:[],persistent:[]}:applyIWR(this,damage,rollOptions),{finalDamage}=result,localize=localizer("PF2E.Actor.ApplyDamage"),actorShield=this.isOfType("character","npc")?this.attributes.shield:null,shieldBlock=actorShield&&shieldBlockRequest?(()=>actorShield.broken?(ui.notifications.warn(game.i18n.format("PF2E.Actions.RaiseAShield.ShieldIsBroken",{actor:token.name,shield:actorShield.name})),!1):actorShield.destroyed?(ui.notifications.warn(game.i18n.format("PF2E.Actions.RaiseAShield.ShieldIsDestroyed",{actor:token.name,shield:actorShield.name})),!1):actorShield.raised?!0:(ui.notifications.warn(localize("ShieldNotRaised",{actor:token.name})),!1))():!1,shieldHardness=shieldBlock?actorShield?.hardness??0:0,damageAbsorbedByShield=finalDamage>0?Math.min(shieldHardness,finalDamage):0,{heldShield}=this,blockingShield=heldShield?.id===actorShield?.itemId?heldShield:null,currentShieldHP=blockingShield?blockingShield._source.system.hp.value:actorShield?.hp.value??0,shieldDamage=shieldBlock?Math.min(currentShieldHP,Math.abs(finalDamage)-damageAbsorbedByShield):0,baseActorHardness=this.hardness,effectiveActorHardness=(()=>{const damageHasAdamantine=typeof damage=="number"?!1:damage.materials.has("adamantine"),materialGrade=item?.isOfType("weapon")&&item.system.material.type==="adamantine"?item.system.material.grade??"standard":"standard",itemHardness={low:0,standard:10,high:13}[materialGrade];return damageHasAdamantine&&itemHardness>=baseActorHardness?Math.floor(baseActorHardness/2):baseActorHardness})(),damageAbsorbedByActor=finalDamage>0?Math.min(finalDamage-damageAbsorbedByShield,effectiveActorHardness):0;if(damageAbsorbedByActor>0){const typeLabel=effectiveActorHardness===baseActorHardness?"PF2E.Damage.Hardness.Full":"PF2E.Damage.Hardness.Half";result.applications.push({category:"reduction",type:game.i18n.localize(typeLabel),adjustment:-1*damageAbsorbedByActor})}const hpUpdate=this.calculateHealthDelta({hp:hitPoints,sp:this.isOfType("character")?this.attributes.hp.sp:null,delta:finalDamage-damageAbsorbedByShield-damageAbsorbedByActor}),hpDamage=hpUpdate.totalApplied,preUpdateSource=this.toObject();blockingShield&&shieldDamage>0&&await blockingShield.update({"system.hp.value":Math.max(blockingShield._source.system.hp.value-shieldDamage,0)},{render:hpDamage===0});const instantDeath=(()=>{if(hpUpdate.totalApplied===0||hpUpdate.totalAppliedi.type==="death-effects")?localize("InstantDeath.DeathEffect"):this.isOfType("npc")&&this.modeOfBeing==="undead"?localize("InstantDeath.Destroyed"):hpUpdate.totalApplied>=(hitPoints.max+staminaMax)*2?localize("InstantDeath.MassiveDamage"):rollOptions.has("item:type:spell")&&rollOptions.has("item:slug:disintegrate")?localize("InstantDeath.FinePowder"):null})();if(hpDamage!==0){const updated=await this.update(hpUpdate.updates,{damageTaken:hpDamage}),setting=game.settings.get("pf2e","automation.actorsDeadAtZero"),deadAtZero=this.isOfType("npc")&&["npcsOnly","both"].includes(setting)||this.isOfType("character")&&setting==="both"&&!!instantDeath;updated.isDead&&deadAtZero&&(hpDamage>=0&&!token.combatant?.isDefeated||hpDamage<0&&token.combatant?.isDefeated)&&token.combatant?.toggleDefeated()}const hpStatement=(()=>finalDamage-damageAbsorbedByActor===0?localize("TakesNoDamage"):finalDamage>0?damageAbsorbedByShield>0?hpDamage>0?localize("DamagedForNShield"):localize("ShieldAbsorbsAll"):localize("DamagedForN"):hpDamage<0?localize("HealedForN"):localize("AtFullHealth"))(),updatedShield=this.isOfType("character","npc")?this.attributes.shield:null,shieldStatement=updatedShield&&shieldDamage>0?updatedShield.broken?localize("ShieldDamagedForNBroken"):updatedShield.destroyed?localize("ShieldDamagedForNDestroyed"):localize("ShieldDamagedForN"):null,statements=(()=>{const concatenated=compact([hpStatement,shieldStatement,instantDeath]).map(s=>game.i18n.format(s,{actor:token.name.replace(/[<>]/g,""),hpDamage:Math.abs(hpDamage),absorbedDamage:damageAbsorbedByShield,shieldDamage})).join(" "),tempElem=document.createElement("div");return tempElem.innerHTML=concatenated,TextEditorPF2e.convertXMLNode(tempElem,"actor",{whose:null,classes:["target-name"]}),tempElem.innerHTML})(),deparenthesize=__name2(formula=>formula.replace(/^\(([^)]+)\)$/,"$1"),"deparenthesize"),persistentDamage=result.persistent.map(instance=>{const condition=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject();return condition.system.persistent={formula:deparenthesize(instance.head.expression),damageType:instance.type,dc:15},condition}),persistentCreated=persistentDamage.length>0?await this.createEmbeddedDocuments("Item",persistentDamage):[],canUndoDamage=!!(hpDamage||shieldDamage||persistentCreated.length),content=await renderTemplate("systems/pf2e/templates/chat/damage/damage-taken.hbs",{breakdown,notes,statements,persistent:persistentCreated.map(p=>p.system.persistent.damage.formula),iwr:{applications:result.applications,visibility:this.hasPlayerOwner?"all":"gm"},canUndoDamage}),flavor=await(async()=>{if(breakdown.length||notes.length)return renderTemplate("systems/pf2e/templates/chat/damage/damage-taken-flavor.hbs",{breakdown,notes})})(),appliedDamage=canUndoDamage?{uuid:this.uuid,isHealing:hpDamage<0,shield:shieldDamage!==0?{id:actorShield?.itemId??"",damage:shieldDamage}:null,persistent:persistentCreated.map(c=>c.id),updates:Object.entries(hpUpdate.updates).map(([path,newValue])=>{const preUpdateValue=getProperty(preUpdateSource,path);if(typeof preUpdateValue=="number"){const difference2=preUpdateValue-newValue;return difference2===0?[]:{path,value:difference2}}return[]}).flat()}:null;return await ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({token}),flags:{pf2e:{appliedDamage}},flavor,content,type:CONST.CHAT_MESSAGE_TYPES.OTHER,whisper:game.settings.get("pf2e","metagame_secretDamage")&&!token.actor?.hasPlayerOwner?ChatMessagePF2e.getWhisperRecipients("GM").map(u=>u.id):[]}),this}async undoDamage(appliedDamage){const{updates,shield,persistent}=appliedDamage,actorUpdates={};for(const update of updates){const currentValue=getProperty(this,update.path);typeof currentValue=="number"&&(actorUpdates[update.path]=currentValue+update.value)}if(shield){const item=this.inventory.get(shield.id);item&&(actorUpdates.items=[{_id:shield.id,"system.hp.value":item.hitPoints.value+shield.damage}])}const updateCount=Object.keys(actorUpdates).length;if(persistent.length&&await this.deleteEmbeddedDocuments("Item",persistent,{render:updateCount===0}),updateCount){const{hitPoints}=this,damageTaken=hitPoints&&typeof actorUpdates["system.attributes.hp.value"]=="number"?hitPoints.value-actorUpdates["system.attributes.hp.value"]:0;this.update(actorUpdates,{damageTaken,damageUndo:!0})}}isLootableBy(user){return this.canUserModify(user,"update")}async transferItemToActor(targetActor,item,quantity,containerId,newStack=!1){if(!(item instanceof PhysicalItemPF2e))throw ErrorPF2e("Only physical items (with quantities) can be transfered between actors");const container=targetActor.inventory.get(containerId??"");if(!(!container||container instanceof ContainerPF2e))throw ErrorPF2e("containerId refers to a non-container");if(__name2((source,target)=>{const bothAreOwned=source.isOwner&&target.isOwner,sourceIsOwnedOrLoot=source.isLootableBy(game.user),targetIsOwnedOrLoot=target.isLootableBy(game.user);return!bothAreOwned&&sourceIsOwnedOrLoot&&targetIsOwnedOrLoot},"gmMustTransfer")(this,targetActor)){const source={tokenId:this.token?.id,actorId:this.id,itemId:item.id},target={tokenId:targetActor.token?.id,actorId:targetActor.id};return await new ItemTransfer(source,target,quantity,container?.id).request(),null}if(!this.canUserModify(game.user,"update"))return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.CantMoveItemSource")),null;if(!targetActor.canUserModify(game.user,"update"))return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.CantMoveItemDestination")),null;quantity=Math.min(quantity,item.quantity);const newQuantity=item.quantity-quantity;newQuantity<1?await item.delete():await item.update({"system.quantity":newQuantity});const newItemData=item.toObject();return newItemData.system.quantity=quantity,newItemData.system.equipped.carryType="worn",hasInvestedProperty(newItemData)&&(newItemData.system.equipped.invested=item.traits.has("invested")?!1:null),targetActor.addToInventory(newItemData,container,newStack)}async addToInventory(itemSource,container,newStack){const stackItem=this.inventory.findStackableItem(itemSource);if(!newStack&&stackItem&&stackItem.type!=="backpack"){const stackQuantity=stackItem.quantity+itemSource.system.quantity;return await stackItem.update({"system.quantity":stackQuantity}),stackItem}const result=await ItemPF2e.create(itemSource,{parent:this});if(!result)return null;const movedItem=this.inventory.get(result.id);return movedItem?(await this.stowOrUnstow(movedItem,container),movedItem):null}async stowOrUnstow(item,container){if(!container)await item.update({"system.containerId":null,"system.equipped.carryType":"worn","system.equipped.handsHeld":0,"system.equipped.inSlot":!1});else if(!isCycle(item,container)){const carryType=container.stowsItems?"stowed":"worn";await item.update({"system.containerId":container.id,"system.equipped.carryType":carryType,"system.equipped.handsHeld":0,"system.equipped.inSlot":!1})}}calculateHealthDelta(args){const updates={},{hp,sp,delta}=args,appliedToTemp=(()=>{if(!hp.temp||delta<=0)return 0;const applied=Math.min(hp.temp,delta);return updates["system.attributes.hp.temp"]=Math.max(hp.temp-applied,0),applied})(),appliedToSP=(()=>{if(!(!!sp&&game.settings.get("pf2e","staminaVariant"))||delta<=0)return 0;const remaining=delta-appliedToTemp,applied=Math.min(sp.value,remaining);return updates["system.attributes.hp.sp.value"]=Math.max(sp.value-applied,0),applied})(),appliedToHP=(()=>{const remaining=delta-appliedToTemp-appliedToSP;return updates["system.attributes.hp.value"]=Math.clamped(hp.value-remaining,0,hp.max),remaining})(),totalApplied=appliedToTemp+appliedToSP+appliedToHP;return{updates,totalApplied}}getRollOptions(domains=[]){const withAll=Array.from(new Set(["all",...domains])),{rollOptions}=this,toReturn=new Set;for(const domain of withAll)for(const[option,value]of Object.entries(rollOptions[domain]??{}))value&&toReturn.add(option);return Array.from(toReturn).sort()}getRollData(){const rollData={actor:this};for(const prop of["abilities","attributes","details","skills","saves"])Object.defineProperty(rollData,prop,{get:()=>(foundry.utils.logCompatibilityWarning(`@${prop} is deprecated`,{since:"5.0.1",until:"6"}),objectHasKey(this.system,prop)?deepClone(this.system[prop]):null)});return rollData}getCondition(slugOrKey,{all=!1}={}){const conditions=this.conditions.filter(c=>c.key===slugOrKey||c.slug===slugOrKey);return all?conditions.sort((conditionA,conditionB)=>{const[valueA,valueB]=[conditionA.value??0,conditionB.value??0];return valueA>valueB?-1:valueAc.active)??null}hasCondition(...slugs){return slugs.some(s=>this.conditions.bySlug(s,{active:!0}).length>0)}async decreaseCondition(conditionSlug,{forceRemove}={forceRemove:!1}){const condition=typeof conditionSlug=="string"?this.getCondition(conditionSlug):conditionSlug;if(!condition)return;if(condition.slug==="persistent-damage"){const matching=this.conditions.stored.filter(c=>c.key===condition.key).map(c=>c.id);await this.deleteEmbeddedDocuments("Item",matching);return}const currentValue=condition._source.system.value.value,newValue=typeof currentValue=="number"?Math.max(currentValue-1,0):null;newValue!==null&&!forceRemove?await game.pf2e.ConditionManager.updateConditionValue(condition.id,this,newValue):await this.deleteEmbeddedDocuments("Item",[condition.id])}async increaseCondition(conditionSlug,{max=Number.MAX_SAFE_INTEGER,value}={}){if(conditionSlug==="persistent-damage")return await new PersistentDamageDialog(this).render(!0),null;const existing=(()=>{if(typeof conditionSlug!="string")return conditionSlug;const conditions=this.itemTypes.condition;return value?conditions.find(c=>c.slug===conditionSlug&&!c.isLocked):conditions.find(c=>c.slug===conditionSlug&&c.active)})();if(existing){const newValue=(()=>{const currentValue=existing._source.system.value.value;if(currentValue===null)return null;const addend=value??1;return Math.clamped(currentValue+addend,1,max)})();return newValue?(await game.pf2e.ConditionManager.updateConditionValue(existing.id,this,newValue),existing):null}else if(typeof conditionSlug=="string"){const conditionSource=game.pf2e.ConditionManager.getCondition(conditionSlug).toObject(),conditionValue=typeof conditionSource.system.value.value=="number"&&max?Math.clamped(conditionSource.system.value.value,value??1,max):null;return conditionSource.system.value.value=conditionValue,(await this.createEmbeddedDocuments("Item",[conditionSource])).shift()??null}return null}async toggleCondition(conditionSlug){if(!setHasElement(CONDITION_SLUGS,conditionSlug))throw ErrorPF2e(`Unrecognized condition: ${conditionSlug}`);this.hasCondition(conditionSlug)?await this.decreaseCondition(conditionSlug,{forceRemove:!0}):await this.increaseCondition(conditionSlug)}async importFromJSON(json2){const processed=await preImportJSON(this,json2);return processed?super.importFromJSON(processed):this}_applyDefaultTokenSettings(data,options){const diff=super._applyDefaultTokenSettings(data,options);return this._source.prototypeToken.texture.src===CONST.DEFAULT_TOKEN&&(this._source.prototypeToken.texture.src=_ActorPF2e2.getDefaultArtwork(data).texture.src),diff}async _preUpdate(changed,options,user){const changedHP=changed.system?.attributes?.hp,currentHP=this.hitPoints;if(!options.damageTaken&&this.hasPlayerOwner&&typeof changedHP?.value=="number"&¤tHP){const damageTaken=-1*(changedHP.value-currentHP.value),levelChanged=!!changed.system?.details&&"level"in changed.system.details;damageTaken&&!levelChanged&&(options.damageTaken=damageTaken)}return super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const hideFromUser=!this.hasPlayerOwner&&!game.user.isGM&&game.settings.get("pf2e","metagame_secretDamage");if(options.damageTaken&&!hideFromUser){const tokens=this.getActiveTokens();for(const token of tokens)token.showFloatyText(-1*options.damageTaken)}if(canvas.ready&&changed.system?.details&&"alliance"in changed.system.details)for(const token of this.getActiveTokens(!0,!0))token.reset();const currentHP=this.hitPoints?.value??0,hpChange=Number(changed.system?.attributes?.hp?.value)||0;if(currentHP>0&&hpChange>0&&this.isDead){const{combatant}=this;if(combatant)combatant.toggleDefeated({to:!1});else for(const tokenDoc of this.getActiveTokens(!1,!0))tokenDoc.update({overlayEffect:""})}}_updateDependentTokens(update,options){if(game.release.build>305)return super._updateDependentTokens(update,options);const tokens=game.scenes.map(s=>s.tokens.filter(t=>t.actorId===this.id)).flat();for(const token of tokens)token._onUpdateBaseActor(update,options)}_onDelete(options,userId){for(const effect of this.itemTypes.effect)game.pf2e.effectTracker.unregister(effect);super._onDelete(options,userId)}_onEmbeddedDocumentChange(){super._onEmbeddedDocumentChange(),this.synthetics.preparationWarnings.flush()}};__name2(_ActorPF2e,"ActorPF2e");let ActorPF2e=_ActorPF2e;const ActorProxyPF2e=new Proxy(ActorPF2e,{construct(_target2,args){return new CONFIG.PF2E.Actor.documentClasses[args[0].type](...args)}}),_CreaturePF2e=class extends ActorPF2e{static{__name(this,"_CreaturePF2e")}get creatureTypes(){return this.system.traits.value.filter(t=>t in CONFIG.PF2E.creatureTypes).sort()}get alignment(){return this.system.details.alignment.value}get rarity(){return this.system.traits.rarity}get allowedItemTypes(){return[...super.allowedItemTypes,"affliction"]}getReach({action:action2="interact",weapon=null}={}){const baseReach=this.attributes.reach.base,weaponReach=weapon?.isOfType("melee")?weapon.reach:null;if(action2==="interact"||this.type==="familiar")return baseReach;if(typeof weaponReach=="number")return weaponReach;{const traitsFromItems=(weapon?[{item:weapon,ready:!0}]:this.system.actions??[]).filter(a=>a.ready).map(a=>new Set(a.item.system.traits?.value??[]));if(traitsFromItems.length===0)return baseReach;const reaches=traitsFromItems.map(traits=>{if(setHasElement(traits,"reach"))return baseReach+5;const reachNPattern=/^reach-\d{1,3}$/;return Number([...traits].find(t=>reachNPattern.test(t))?.replace("reach-",""))||baseReach});return Math.max(...reaches)}}get visionLevel(){const{senses:senses2}=this.system.traits;if(!(Array.isArray(senses2)&&senses2.every(s=>isObject(s)&&"type"in s&&typeof s.type=="string")))return VisionLevels.NORMAL;const senseTypes=new Set(senses2.map(sense=>sense.type));return this.getCondition("blinded")?VisionLevels.BLINDED:senseTypes.has("darkvision")||senseTypes.has("greaterDarkvision")?VisionLevels.DARKVISION:senseTypes.has("lowLightVision")?VisionLevels.LOWLIGHT:VisionLevels.NORMAL}get hasDarkvision(){return this.visionLevel===VisionLevels.DARKVISION&&!this.hasCondition("blinded")}get hasLowLightVision(){return this.visionLevel>=VisionLevels.LOWLIGHT&&!this.hasCondition("blinded")}get canSee(){return canvas.scene?this.visionLevel===VisionLevels.BLINDED?!1:canvas.scene.lightLevel>LightLevels.DARKNESS||this.hasDarkvision:!0}get canAct(){const traits=this.system.traits.value;return(!this.isDead||traits.some(t=>t==="eidolon"))&&!this.hasCondition("paralyzed","stunned","unconscious")}get canAttack(){return this.type!=="familiar"&&this.canAct}get isDead(){const{hitPoints}=this;return hitPoints.max>0&&hitPoints.value===0&&!this.hasCondition("dying","unconscious")?!0:!!(this.token??this.getActiveTokens(!1,!0).shift())?.hasStatusEffect("dead")}get emitsSound(){return this.system.attributes.emitsSound}get isSpellcaster(){const{itemTypes}=this;return itemTypes.spellcastingEntry.length>0&&itemTypes.spell.length>0}get wornArmor(){return this.itemTypes.armor.find(armor=>armor.isEquipped&&armor.isArmor)??null}get heldShield(){const heldShields=this.itemTypes.armor.filter(armor=>armor.isEquipped&&armor.isShield);return heldShields.length===0?null:heldShields.slice(0,-1).reduce((bestShield,shield)=>{if(bestShield===shield)return bestShield;const withBetterAC=bestShield.acBonus>shield.acBonus?bestShield:shield.acBonus>bestShield.acBonus?shield:null,withMoreHP=bestShield.hitPoints.value>shield.hitPoints.value?bestShield:shield.hitPoints.value>bestShield.hitPoints.value?shield:null,withBetterHardness=bestShield.hardness>shield.hardness?bestShield:shield.hardness>bestShield.hardness?shield:null;return withBetterAC??withMoreHP??withBetterHardness??bestShield},heldShields.slice(-1)[0])}getStatistic(slug){return slug==="perception"?this.perception:tupleHasValue(["spell","spell-attack"],slug)?this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).sort((a,b)=>b.mod-a.mod).shift()??null:slug==="spell-dc"?this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).sort((a,b)=>b.dc.value-a.dc.value).shift()??null:this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).find(s=>s.slug===slug)??super.getStatistic(slug)}_initialize(options){this.parties??=new Set,super._initialize(options)}prepareData(){super.prepareData();for(const party of this.parties)party.reset({actor:!0})}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e.rollOptions.all["self:creature"]=!0;const attributes=this.system.attributes;attributes.hardness??={value:0},attributes.flanking.canFlank=!0,attributes.flanking.flankable=!0,attributes.flanking.offGuardable=!0,attributes.reach={base:0,manipulate:0},attributes.speed=mergeObject({total:0,value:0},attributes.speed??{}),attributes.initiative&&(attributes.initiative.tiebreakPriority=this.hasPlayerOwner?2:1);const customModifiers=this.system.customModifiers??={};for(const selector of Object.keys(customModifiers))customModifiers[selector]=customModifiers[selector].map(rawModifier=>new ModifierPF2e(rawModifier));this.isOfType("character","npc")&&(this.system.attributes.shield={itemId:null,name:game.i18n.localize("PF2E.ArmorTypeShield"),ac:0,hp:{value:0,max:0},brokenThreshold:0,hardness:0,raised:!1,broken:!1,destroyed:!1,icon:"systems/pf2e/icons/actions/raise-a-shield.webp"}),attributes.doomed={value:0,max:3},attributes.dying={value:0,max:4,recoveryDC:10},attributes.wounded={value:0,max:3},setImmunitiesFromTraits(this)}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.();for(const changeEntries of Object.values(this.system.autoChanges))changeEntries.sort((a,b)=>Number(a.level)>Number(b.level)?1:-1);this.rollOptions.all[`self:mode:${this.modeOfBeing}`]=!0}prepareDerivedData(){super.prepareDerivedData();const{attributes}=this,reachFromSize=SIZE_TO_REACH[this.size];attributes.reach.base=Math.max(attributes.reach.base,reachFromSize),attributes.reach.manipulate=Math.max(attributes.reach.manipulate,attributes.reach.base,reachFromSize);const alignmentTraits2=(()=>{const{alignment}=this;return[["LG","NG","CG"].includes(alignment)?"good":[],["LE","NE","CE"].includes(alignment)?"evil":[],["LG","LN","LE"].includes(alignment)?"lawful":[],["CG","CN","CE"].includes(alignment)?"chaotic":[]].flat()})(),{rollOptions}=this;for(const trait of alignmentTraits2)this.system.traits.value.push(trait),rollOptions.all[`self:trait:${trait}`]=!0;this.isSpellcaster&&(rollOptions.all["self:caster"]=!0),this.hitPoints.negativeHealing&&(rollOptions.all["self:negative-healing"]=!0),rollOptions.all["self:armored"]=!!this.wornArmor&&this.wornArmor.category!=="unarmored",attributes.shield?.raised&&!attributes.shield.broken&&!attributes.shield.destroyed&&(this.rollOptions.all["self:shield:raised"]=!0),this.system.attributes.emitsSound=!this.isDead,this.prepareSynthetics();const sizeIndex=SIZES.indexOf(this.size),sizeSlug=SIZE_SLUGS[sizeIndex];rollOptions.all[`self:size:${sizeIndex}`]=!0,rollOptions.all[`self:size:${sizeSlug}`]=!0,attributes.wounded.max=Math.max(0,attributes.dying.max-1),attributes.doomed.max=attributes.dying.max;for(const conditionSlug of["doomed","wounded","dying"]){const condition=this.conditions.bySlug(conditionSlug,{active:!0}).at(0),status=attributes[conditionSlug];conditionSlug==="dying"&&(status.max-=attributes.doomed.value),status.value=Math.min(condition?.value??0,status.max)}imposeEncumberedCondition(this)}prepareSynthetics(){super.prepareSynthetics();for(const[selector,modifiers]of Object.entries(this.system.customModifiers))(this.synthetics.modifiers[selector]??=[]).push(...modifiers.map(m=>()=>m))}async adjustCarryType(item,{carryType,handsHeld=0,inSlot=!1}){const{usage}=item.system;if(carryType==="stowed"){const container=item.actor.itemTypes.backpack.find(c=>c!==item.container&&!isCycle(item,c));container&&await item.actor.stowOrUnstow(item,container)}else{const equipped={carryType,handsHeld:carryType==="held"?handsHeld:0,inSlot:usage.type==="worn"&&usage.where?inSlot:void 0},updates=[];if(isEquipped(usage,equipped)&&item instanceof ArmorPF2e&&item.isArmor){const wornArmors=this.itemTypes.armor.filter(a=>a!==item&&a.isEquipped&&a.isArmor);for(const armor of wornArmors)updates.push({_id:armor.id,system:{equipped:{inSlot:!1}}})}updates.push({_id:item.id,system:{containerId:null,equipped}}),await this.updateEmbeddedDocuments("Item",updates)}}async addCustomModifier(stat,label,value,type){if(stat=stat==="armor"?"ac":stat,!this.isOfType("character","npc"))return;if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");if(label.length===0)throw ErrorPF2e("A custom modifier's label must be a non-empty string");const modifiers=(this.toObject().system.customModifiers??{})[stat]??[];if(!modifiers.some(m=>m.label===label)){const modifierType=setHasElement(MODIFIER_TYPES,type)?type:"untyped",modifier=new ModifierPF2e({label,modifier:value,type:modifierType,custom:!0}).toObject();await this.update({[`system.customModifiers.${stat}`]:[...modifiers,modifier]})}}async removeCustomModifier(stat,slug){if(stat=stat==="armor"?"ac":stat,stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");const modifiers=(this.toObject().system.customModifiers??{})[stat]??[];if(modifiers.length!==0)if(typeof slug=="string"){const withRemoved=modifiers.filter(m=>m.slug!==slug);await this.update({[`system.customModifiers.${stat}`]:withRemoved})}else throw ErrorPF2e("Custom modifiers can only be removed by slug (string) or index (number)")}async rollRecovery(event){const{dying}=this.attributes;if(!dying?.value)return null;const localize=localizer("PF2E.Recovery"),recoveryDC=dying.recoveryDC,dc={label:localize("rollingDescription",{dying:dying.value,dc:"{dc}"}),value:recoveryDC+dying.value,visible:!0},notes=[new RollNotePF2e({selector:"all",text:localize("critSuccess"),outcome:["criticalSuccess"]}),new RollNotePF2e({selector:"all",text:localize("success"),outcome:["success"]}),new RollNotePF2e({selector:"all",text:localize("failure"),outcome:["failure"]}),new RollNotePF2e({selector:"all",text:localize("critFailure"),outcome:["criticalFailure"]})];return new Statistic(this,{slug:"dying-recovery",label:"PF2E.Check.Specific.Recovery",check:{type:"flat-check"}}).roll({...eventToRollParams(event,{type:"check"}),dc,extraRollNotes:notes})}prepareSenses(data,synthetics){const preparedSenses=data.map(datum=>new CreatureSensePF2e(datum));for(const{sense,predicate,force}of synthetics.senses){if(predicate&&!predicate.test(this.getRollOptions(["all","sense"])))continue;const existing=preparedSenses.find(oldSense=>oldSense.type===sense.type);existing?force?preparedSenses.findSplice(oldSense=>oldSense===existing,sense):(sense.isMoreAcuteThan(existing)&&(existing.acuity=sense.acuity),sense.hasLongerRangeThan(existing)&&(existing.value=sense.value)):preparedSenses.push(sense)}return preparedSenses}prepareSpeed(movementType){const systemData=this.system;if(movementType==="land"){const domains=["speed","all-speeds",`${movementType}-speed`],rollOptions=this.getRollOptions(domains),landSpeed=systemData.attributes.speed;landSpeed.value=Number(landSpeed.value)||0;const fromSynthetics=(this.synthetics.movementTypes[movementType]??[]).flatMap(d=>d()??[]);landSpeed.value=Math.max(landSpeed.value,...fromSynthetics.map(s=>s.value));const modifiers=extractModifiers(this.synthetics,domains),stat=mergeObject(new StatisticModifier(`${movementType}-speed`,modifiers,rollOptions),landSpeed,{overwrite:!1}),typeLabel=game.i18n.localize("PF2E.SpeedTypesLand"),otherData={type:"land",label:game.i18n.format("PF2E.SpeedLabel",{type:typeLabel})};this.rollOptions.all["speed:land"]=!0;const merged=mergeObject(stat,otherData);return Object.defineProperties(merged,{total:{get(){return stat.value+stat.totalModifier}},breakdown:{get(){return[`${game.i18n.format("PF2E.SpeedBaseLabel",{type:typeLabel})} ${stat.value}`,...stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.signedValue}`)].join(", ")}}}),merged}else{const fastest=(()=>{const{otherSpeeds}=systemData.attributes.speed,existing=otherSpeeds.filter(s=>s.type===movementType),fromSynthetics=(this.synthetics.movementTypes[movementType]??[]).map(d=>d()??[]).flat();return[...existing,...fromSynthetics]})().reduce((best,speed2)=>best?speed2?.value>best.value?speed2:best:speed2,null);if(!fastest)return null;const domains=fastest.derivedFromLand?[`${movementType}-speed`]:["speed","all-speeds",`${movementType}-speed`],rollOptions=this.getRollOptions(domains),label=game.i18n.localize(CONFIG.PF2E.speedTypes[movementType]),speed={type:movementType,label,value:fastest.value};fastest.source&&(speed.source=fastest.source),this.rollOptions.all[`speed:${movementType}`]=!0;const modifiers=extractModifiers(this.synthetics,domains),stat=new StatisticModifier(`${movementType}-speed`,modifiers,rollOptions),merged=mergeObject(stat,speed,{overwrite:!1});return Object.defineProperties(merged,{total:{get(){return speed.value+stat.totalModifier}},breakdown:{get(){return[`${game.i18n.format("PF2E.SpeedBaseLabel",{type:speed.label})} ${speed.value}`].concat(stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`)).join(", ")}}}),merged}}deleteEmbeddedDocuments(embeddedName,ids,context){if(embeddedName==="Item"){const linked=ids.map(id=>this.items.get(id)).flatMap(item=>item?.getLinkedItems?.()??[]);ids.push(...linked.map(item=>item.id))}return super.deleteEmbeddedDocuments(embeddedName,[...new Set(ids)],context)}async _preUpdate(changed,options,user){const currentHP=this.hitPoints,changedHP=changed.system?.attributes?.hp;typeof changedHP?.value=="number"&&(changedHP.value=options.allowHPOverage?Math.max(0,changedHP.value):Math.clamped(changedHP.value,0,Math.max(currentHP.max-currentHP.unrecoverable,0)));const focusUpdate=changed.system?.resources?.focus;if(focusUpdate&&this.system.resources){typeof focusUpdate.max=="number"&&(focusUpdate.max=Math.clamped(focusUpdate.max,0,3));const updatedPoints=Number(focusUpdate.value??this.system.resources.focus?.value)||0,enforcedMax=(Number(focusUpdate.max)||this.system.resources.focus?.max)??0;focusUpdate.value=Math.clamped(updatedPoints,0,enforcedMax),this.isToken&&(options.diff=!1)}return super._preUpdate(changed,options,user)}_onDelete(options,userId){super._onDelete(options,userId);for(const party of this.parties){const updater=party.primaryUpdater;game.user===updater?party.removeMembers(this.uuid):updater||(party.reset(),ui.actors.render())}}};__name2(_CreaturePF2e,"CreaturePF2e");let CreaturePF2e=_CreaturePF2e;const _CharacterFeats=class extends Collection{static{__name(this,"_CharacterFeats")}constructor(actor){super(),__privateAdd(this,_findBestLocation),__publicField(this,"bonus"),this.actor=actor;const classFeatSlots=actor.class?.grantedFeatSlots;this.bonus=new FeatGroup(actor,{id:"bonus",label:"PF2E.FeatBonusHeader"}),this.createGroup({id:"ancestryfeature",label:"PF2E.FeaturesAncestryHeader",supported:["ancestryfeature"]}),this.createGroup({id:"classfeature",label:"PF2E.FeaturesClassHeader",supported:["classfeature"]});const ancestryTraitsFilter=actor.system.details.ancestry?.countsAs.map(t=>getVanillaOrHomebrewTrait(t)).flatMap(t=>t?`traits-${t}`:[])??[];this.createGroup({id:"ancestry",label:"PF2E.FeatAncestryHeader",featFilter:ancestryTraitsFilter,supported:["ancestry"],slots:classFeatSlots?.ancestry??[]});const classSlug=actor.class?actor.class.slug??sluggify(actor.class.name):null,classTrait=getVanillaOrHomebrewTrait(classSlug),classFeatFilter=classTrait?this.actor.level<2?[`traits-${classTrait}`]:this.actor.itemTypes.feat.some(f=>f.traits.has("dedication"))?[`traits-${classTrait}`,"traits-archetype"]:[`traits-${classTrait}`,"traits-dedication"]:[];this.createGroup({id:"class",label:"PF2E.FeatClassHeader",featFilter:classFeatFilter,supported:["class"],slots:classFeatSlots?.class??[]});const evenLevels=new Array(actor.level).fill(0).map((_,idx)=>idx+1).filter(idx=>idx%2===0);game.settings.get("pf2e","dualClassVariant")&&this.createGroup({id:"dualclass",label:"PF2E.FeatDualClassHeader",supported:["class"],slots:[1,...evenLevels]}),game.settings.get("pf2e","freeArchetypeVariant")&&this.createGroup({id:"archetype",label:"PF2E.FeatArchetypeHeader",supported:["class"],slots:evenLevels,featFilter:this.actor.itemTypes.feat.some(f=>f.traits.has("dedication"))?["traits-archetype"]:["traits-dedication"]});const backgroundSkillFeats=actor.background&&Object.keys(actor.background.system.items??{}).length>0?{id:actor.background.id,level:1,label:game.i18n.localize("PF2E.FeatBackgroundShort")}:null;this.createGroup({id:"skill",label:"PF2E.FeatSkillHeader",supported:["skill"],slots:compact([backgroundSkillFeats,classFeatSlots?.skill].flat())}),this.createGroup({id:"general",label:"PF2E.FeatGeneralHeader",supported:["general","skill"],slots:classFeatSlots?.general??[]}),game.settings.get("pf2e","campaignFeats")&&this.createGroup({id:"campaign",label:"PF2E.FeatCampaignHeader"})}createGroup(options){return this.set(options.id,new FeatGroup(this.actor,options))}async insertFeat(feat,slotData){const alreadyHasFeat=this.actor.items.has(feat.id);if(isBoonOrCurse(feat))return alreadyHasFeat?[]:this.actor.createEmbeddedDocuments("Item",[feat.toObject()]);const groupId=slotData?.groupId??"",{group,slotId}=this.get(groupId)?.isFeatValid(feat)?{group:this.get(groupId),slotId:slotData?.slotId??null}:__privateMethod(this,_findBestLocation,findBestLocation_fn).call(this,feat,{requested:groupId}),isFeatValidInSlot=!!group?.isFeatValid(feat);if(groupId!=="bonus"&&!group){const badGroup=this.get(groupId);if(badGroup)return ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.InvalidCategory",{item:feat.name,category:game.i18n.format(badGroup.label)})),[]}return alreadyHasFeat&&feat.system.location&&!isFeatValidInSlot?this.actor.updateEmbeddedDocuments("Item",[{_id:feat.id,"system.location":null}]):group?.insertFeat(feat,slotId)??this.bonus.insertFeat(feat)}assignToSlots(){const groupsBySlot=this.contents.filter(g=>g.slotted).reduce((previous,current)=>{for(const slot of Object.keys(current.slots))previous[slot]=current;return previous},{}),feats=this.actor.itemTypes.feat.sort((f1,f2)=>f1.sort-f2.sort);for(const feat of feats.filter(f=>!isBoonOrCurse(f))){if(feat.flags.pf2e.grantedBy&&!feat.system.location){const granter=this.actor.items.get(feat.flags.pf2e.grantedBy.id);if(granter?.isOfType("feat")&&granter.grants.includes(feat))continue}const location=feat.system.location??"";(groupsBySlot[location]??this.get(location)??this.get(feat.category))?.assignFeat(feat)||this.bonus.assignFeat(feat)}this.get("classfeature").feats.sort((a,b)=>(a.feat?.level||0)-(b.feat?.level||0))}};_findBestLocation=new WeakSet,findBestLocation_fn=__name2(function(feat,{requested}){if(feat.isFeature)return{group:this.get(feat.category)??null,slotId:null};if(requested==="bonus")return{group:null,slotId:null};const validGroups=this.filter(c=>c.isFeatValid(feat)&&!c.isFull),group=validGroups.at(0);if(validGroups.length===1&&group){const slotId=group.slotted?Object.values(group.slots).find(slot=>!slot?.feat)?.id??null:null;return{group,slotId}}return{group:null,slotId:null}},"#findBestLocation"),__name2(_CharacterFeats,"CharacterFeats");let CharacterFeats=_CharacterFeats;const _FeatGroup=class{static{__name(this,"_FeatGroup")}constructor(actor,options){__privateAdd(this,_getChildSlots),__publicField(this,"actor"),__publicField(this,"id"),__publicField(this,"label"),__publicField(this,"feats",[]),__publicField(this,"slotted",!1),__publicField(this,"featFilter"),__publicField(this,"supported",[]),__publicField(this,"slots",{}),this.actor=actor;const maxLevel=options.level??actor.level;if(this.id=options.id,this.label=options.label,this.supported=options.supported??[],this.featFilter=Array.from(new Set([this.supported.map(s=>`category-${s}`),options.featFilter??[]].flat())),options.slots){this.slotted=!0;for(const slotOption of options.slots){const slotData=typeof slotOption=="number"?{id:`${this.id}-${slotOption}`,level:slotOption,label:slotOption.toString()}:typeof slotOption=="string"?{id:`${this.id}-${sluggify(slotOption)}`,level:null,label:slotOption}:slotOption;if(typeof slotData.level=="number"&&slotData.level>maxLevel)continue;const slot={...slotData,level:slotData.level??null,children:[]};this.feats.push(slot),this.slots[slot.id]=slot}}}get isFull(){return this.slotted&&Object.values(this.slots).every(s=>!!s?.feat)}assignFeat(feat){const slotId=feat.isOfType("feat")&&feat.system.location===this.id?feat.system.level.taken?.toString()??"":feat.system.location??"",slot=this.slots[slotId];if(!slot&&this.slotted)return!1;if(slot?.feat)return console.debug(`PF2e System | Multiple feats with same index: ${feat.name}, ${slot.feat.name}`),!1;const childSlots=__privateMethod(this,_getChildSlots,getChildSlots_fn).call(this,feat);if(slot)slot.feat=feat,slot.children=childSlots;else{const label=feat.category==="classfeature"?feat.system.level?.value.toString()??null:null;this.feats.push({feat,label,children:childSlots})}return feat.group=this,!0}isFeatValid(feat){return this.supported.length===0||tupleHasValue(this.supported,feat.category)}async insertFeat(feat,slotId=null){const slot=this.slots[slotId??""],location=this.slotted||this.id==="bonus"?slot?.id??null:this.id,existing=this.actor.items.filter(i=>isFeatLike(i)&&i.system.location===location),isFeatValidInSlot=this.isFeatValid(feat),alreadyHasFeat=this.actor.items.has(feat.id),changed=[];if(!alreadyHasFeat&&(isFeatValidInSlot||!location)){const source=mergeObject(feat.toObject(),{system:{location}});changed.push(...await this.actor.createEmbeddedDocuments("Item",[source]));const label=game.i18n.localize(this.label);ui.notifications.info(game.i18n.format("PF2E.Item.Feat.Info.Added",{item:feat.name,category:label}))}const locationUpdates=this.slotted?existing.map(f=>({_id:f.id,"system.location":null,..."taken"in(feat._source.system.level??{})?{"system.level.-=taken":null}:{}})):[];return alreadyHasFeat&&isFeatValidInSlot&&locationUpdates.push({_id:feat.id,"system.location":location,...slot?.level&&feat.isOfType("feat")?{"system.level.taken":slot.level}:{}}),locationUpdates.length>0&&changed.push(...await this.actor.updateEmbeddedDocuments("Item",locationUpdates)),changed}};_getChildSlots=new WeakSet,getChildSlots_fn=__name2(function(feat){return feat?.isOfType("feat")?feat.grants.map(grant=>({id:grant.id,label:null,level:grant.system.level?.taken??null,feat:grant,children:__privateMethod(this,_getChildSlots,getChildSlots_fn).call(this,grant)})):[]},"#getChildSlots"),__name2(_FeatGroup,"FeatGroup");let FeatGroup=_FeatGroup;function getVanillaOrHomebrewTrait(slug){return(slug??"")in CONFIG.PF2E.featTraits?slug:`hb_${slug}`in CONFIG.PF2E.featTraits?`hb_${slug}`:null}__name(getVanillaOrHomebrewTrait,"getVanillaOrHomebrewTrait"),__name2(getVanillaOrHomebrewTrait,"getVanillaOrHomebrewTrait");function isBoonOrCurse(feat){return["pfsboon","deityboon","curse"].includes(feat.category)}__name(isBoonOrCurse,"isBoonOrCurse"),__name2(isBoonOrCurse,"isBoonOrCurse");function isFeatLike(item){return"category"in item&&"location"in item.system&&"isFeat"in item&&"isFeature"in item}__name(isFeatLike,"isFeatLike"),__name2(isFeatLike,"isFeatLike");const CHARACTER_SHEET_TABS=["character","actions","inventory","spellcasting","crafting","proficiencies","feats","effects","biography","pfs"],_CharacterPF2e=class extends CreaturePF2e{static{__name(this,"_CharacterPF2e")}get allowedItemTypes(){const buildItems=["ancestry","heritage","background","class","deity","feat"];return[...super.allowedItemTypes,...buildItems,"physical","spellcastingEntry","spell","action","lore"]}get keyAttribute(){return this.system.details.keyability.value||"str"}get keyAbility(){return foundry.utils.logCompatibilityWarning("`CharacterPF2e#keyAbility` is deprecated. Use `CharacterPF2e#keyAttribute` instead.",{since:"5.2.0",until:"6.0.0"}),this.keyAttribute}get abilities(){return deepClone(this.system.abilities)}get handsFree(){const heldItems=this.inventory.filter(i=>i.isHeld);return Math.clamped(2-sumBy(heldItems,i=>i.traits.has("free-hand")?0:i.handsHeld),0,2)}get handsReallyFree(){const heldItems=this.inventory.filter(i=>i.isHeld);return Math.clamped(2-sumBy(heldItems,i=>i.handsHeld),0,2)}get hitPoints(){return{...super.hitPoints,recoveryMultiplier:this.system.attributes.hp.recoveryMultiplier,recoveryAddend:this.system.attributes.hp.recoveryAddend}}get heroPoints(){return deepClone(this.system.resources.heroPoints)}getStatistic(slug){if(tupleHasValue(["class","class-dc","classDC"],slug))return this.classDC;if(setHasElement(MAGIC_TRADITIONS,slug))return this.traditions[slug];if(slug==="class-spell"){const highestClass=Object.values(this.classDCs).sort((a,b)=>b.mod-a.mod).shift(),highestSpell=this.spellcasting.contents.flatMap(s=>s.statistic??[]).sort((a,b)=>b.mod-a.mod).shift();return compact([highestClass,highestSpell]).sort((a,b)=>b.mod-a.mod).shift()??null}return this.classDCs[slug]??super.getStatistic(slug)}async getCraftingFormulas(){const{formulas}=this.system.crafting;formulas.sort((a,b)=>(a.sort??0)-(b.sort??0));const formulaMap=new Map(formulas.map(data=>[data.uuid,data]));return(await UUIDUtils.fromUUIDs(formulas.map(f=>f.uuid))).filter(i=>i instanceof ItemPF2e&&i.isOfType("physical")).map(item=>{const{dc,batchSize,deletable}=formulaMap.get(item.uuid)??{deletable:!1};return new CraftingFormula(item,{dc,batchSize,deletable})})}async getCraftingEntries(formulas){const craftingFormulas=formulas??await this.getCraftingFormulas();return Object.values(this.system.crafting.entries).filter(entry=>CraftingEntry.isValid(entry)).map(entry=>new CraftingEntry(this,craftingFormulas,entry))}async getCraftingEntry(selector){const craftingFormulas=await this.getCraftingFormulas(),craftingEntryData=this.system.crafting.entries[selector];return CraftingEntry.isValid(craftingEntryData)?new CraftingEntry(this,craftingFormulas,craftingEntryData):null}async performDailyCrafting(){const entries=(await this.getCraftingEntries()).filter(e=>e.isDailyPrep),reagentCost=entries.filter(e=>e.isAlchemical).reduce((sum2,entry)=>sum2+entry.reagentCost,0),reagentValue=(this.system.resources.crafting.infusedReagents.value||0)-reagentCost;if(reagentValue<0){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MissingReagents"));return}else await this.update({"system.resources.crafting.infusedReagents.value":reagentValue});for(const item of this.inventory)item.system.temporary&&await item.delete();for(const entry of entries)for(const formula of entry.preparedCraftingFormulas){const itemSource=formula.item.toObject();itemSource.system.quantity=formula.quantity,itemSource.system.temporary=!0,itemSource.system.size=this.ancestry?.size==="tiny"?"tiny":"med",entry.isAlchemical&&(itemSource.type==="consumable"||itemSource.type==="weapon"||itemSource.type==="equipment")&&itemSource.system.traits.value.push("infused"),await this.addToInventory(itemSource)}}_initialize(options){this.familiar??=null,super._initialize(options)}prepareData(){super.prepareData(),game.ready&&this.familiar&&game.actors.has(this.familiar.id)&&this.familiar.reset({fromMaster:!0})}prepareBaseData(){super.prepareBaseData(),this.parties.size||(this.system.exploration=[]);const{flags}=this;flags.pf2e.favoredWeaponRank=0,flags.pf2e.freeCrafting??=!1,flags.pf2e.quickAlchemy??=!1,flags.pf2e.sheetTabs=mergeObject(CHARACTER_SHEET_TABS.reduce((tabs,tab)=>({...tabs,[tab]:!0}),{}),flags.pf2e.sheetTabs??{}),flags.pf2e.showBasicUnarmed??=!0;const isGradual=game.settings.get("pf2e","gradualBoostsVariant"),allowedBoosts=[1,5,10,15,20].reduce((result,level)=>{const allowed=(()=>this.level===0&&level===1?4:isGradual?4-Math.clamped(level-this.level,0,4):this.level>=level?4:0)();return result[level]=allowed,result},{}),manualAttributes=Object.keys(this.system.abilities??{}).length>0;this.system.abilities=mapToObj(Array.from(ATTRIBUTE_ABBREVIATIONS),a=>[a,mergeObject({mod:0},this.system.abilities?.[a]??{})]);const systemData=this.system,existingBoosts=systemData.build?.attributes?.boosts,isABP=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this);systemData.build={attributes:{manual:manualAttributes,keyOptions:[],boosts:{ancestry:[],background:[],class:null,1:existingBoosts?.[1]?.slice(0,allowedBoosts[1])??[],5:existingBoosts?.[5]?.slice(0,allowedBoosts[5])??[],10:existingBoosts?.[10]?.slice(0,allowedBoosts[10])??[],15:existingBoosts?.[15]?.slice(0,allowedBoosts[15])??[],20:existingBoosts?.[20]?.slice(0,allowedBoosts[20])??[]},allowedBoosts,flaws:{ancestry:[]},apex:isABP?systemData.build?.attributes?.apex??null:null}},systemData.saves=mergeObject(mapToObj(SAVE_TYPES,t=>[t,{rank:0,ability:SAVING_THROW_DEFAULT_ATTRIBUTES[t]}]),systemData.saves??{});const{details}=this.system;for(const property of["ancestry","heritage","background","class","deity"])this[property]=null,property==="deity"?details.deities={primary:null,secondary:null,domains:{}}:property!=="background"&&(details[property]=null);details.alliance=ALLIANCES.has(details.alliance)?details.alliance:this.hasPlayerOwner?"party":"opposition";const attributes=this.system.attributes;attributes.ac={},attributes.polymorphed=!1,attributes.battleForm=!1,attributes.classDC=null,attributes.spellDC=null,attributes.classOrSpellDC={rank:0,value:0};const perception=attributes.perception??={ability:"wis",rank:0};perception.ability="wis",perception.rank??=0;const hitPoints=this.system.attributes.hp;hitPoints.recoveryMultiplier=1,hitPoints.recoveryAddend=0,attributes.ancestryhp=0,attributes.classhp=0;const{skills}=this.system;for(const key of SKILL_ABBREVIATIONS){const skill=skills[key];skill.ability=SKILL_EXPANDED[SKILL_DICTIONARY[key]].attribute,skill.armor=["dex","str"].includes(skill.ability)}attributes.familiarAbilities={value:0},systemData.proficiencies={...systemData.proficiencies,classDCs:{},traditions:Array.from(MAGIC_TRADITIONS).reduce((accumulated,t)=>({...accumulated,[t]:{rank:0}}),{})};const{resources}=this.system;resources.heroPoints.max=3,resources.investiture={value:0,max:10},resources.focus=mergeObject({value:0,max:0},resources.focus??{}),resources.focus.max=0,resources.focus.cap=3,resources.crafting=mergeObject({infusedReagents:{value:0,max:0}},resources.crafting??{}),resources.crafting.infusedReagents.max=0,this.system.traits.size=new ActorSizePF2e({value:"med"});const attacks=systemData.proficiencies.attacks??={};for(const category of WEAPON_CATEGORIES)attacks[category]={rank:attacks[category]?.rank??0,custom:!!attacks[category]?.custom,immutable:!!attacks[category]?.custom};const homebrewCategories=game.settings.get("pf2e","homebrew.weaponCategories").map(tag=>tag.id);for(const category of homebrewCategories)attacks[category]??={rank:0,custom:!!attacks[category]?.custom,immutable:!!attacks[category]?.custom};const defenses=systemData.proficiencies.defenses??={};for(const category of ARMOR_CATEGORIES)defenses[category]={rank:defenses[category]?.rank??0,immutable:["light-barding","heavy-barding"].includes(category)};systemData.crafting=mergeObject({formulas:[],entries:{}},systemData.crafting??{});for(const formula of this.system.crafting.formulas)formula.deletable=!0;this.rollOptions.all[`self:level:${this.level}`]=!0}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const attribute of Object.values(this.system.abilities))attribute.mod=Math.trunc(attribute.mod)||0;this.setNumericRollOptions(),this.deity?.setFavoredWeaponRank()}prepareDataFromItems(){super.prepareDataFromItems(),this.setAttributeModifiers()}prepareDerivedData(){super.prepareDerivedData(),imposeOversizedWeaponCondition(this);const systemData=this.system,{synthetics}=this;if(game.pf2e.variantRules.AutomaticBonusProgression.concatModifiers(this),systemData.details.xp.pct=Math.min(Math.round(systemData.details.xp.value*100/systemData.details.xp.max),99.5),systemData.pfs.levelBump){const params={slug:"level-bump",label:"PF2E.PFS.LevelBump",modifier:1};this.synthetics.modifiers.all.push(()=>new ModifierPF2e(params)),this.synthetics.modifiers.damage.push(()=>new ModifierPF2e(params))}{const ancestryHP=systemData.attributes.ancestryhp,classHP=systemData.attributes.classhp,hitPoints=systemData.attributes.hp,modifiers=[new ModifierPF2e("PF2E.AncestryHP",ancestryHP,"untyped")];if(game.settings.get("pf2e","staminaVariant")){const halfClassHp=Math.floor(classHP/2);systemData.attributes.hp.sp={value:systemData.attributes.hp.sp?.value??0,max:(halfClassHp+systemData.abilities.con.mod)*this.level},systemData.resources.resolve={value:systemData.resources.resolve?.value??0,max:systemData.abilities[systemData.details.keyability.value].mod},modifiers.push(new ModifierPF2e("PF2E.ClassHP",halfClassHp*this.level,"untyped"))}else{modifiers.push(new ModifierPF2e("PF2E.ClassHP",classHP*this.level,"untyped")),delete systemData.resources.resolve;const conHP=systemData.abilities.con.mod*Math.max(this.level,1);modifiers.push(new ModifierPF2e({slug:"hp-con",label:"PF2E.AbilityCon",ability:"con",type:"ability",modifier:conHP,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,["con-based"],"hp-con")}))}const hpRollOptions=this.getRollOptions(["hp"]);modifiers.push(...extractModifiers(synthetics,["hp"],{test:hpRollOptions}));const perLevelRollOptions=this.getRollOptions(["hp-per-level"]);modifiers.push(...extractModifiers(synthetics,["hp-per-level"],{test:perLevelRollOptions}).map(clone=>(clone.modifier*=this.level,clone)));const stat=mergeObject(new StatisticModifier("hp",modifiers),hitPoints,{overwrite:!1});if(systemData.pfs.levelBump){const hitPointsBump=Math.max(10,stat.totalModifier*.1);stat.push(new ModifierPF2e("PF2E.PFS.LevelBump",hitPointsBump,"untyped"))}stat.max=stat.totalModifier,stat.value=Math.min(stat.value,stat.max),stat.breakdown=stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", "),systemData.attributes.hp=stat,setHitPointsRollOptions(this)}this.prepareFeats(),this.prepareSaves(),this.prepareMartialProficiencies(),this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",attribute:"wis",rank:systemData.attributes.perception.rank,domains:["perception","wis-based","all"],check:{type:"perception-check"}}),systemData.attributes.perception=mergeObject(systemData.attributes.perception,this.perception.getTraceData({value:"mod"})),this.skills=this.prepareSkills(),this.system.traits.senses=this.prepareSenses(this.system.traits.senses,synthetics),this.traditions=Array.from(MAGIC_TRADITIONS).reduce((traditions,tradition)=>(traditions[tradition]=new Statistic(this,{slug:tradition,label:CONFIG.PF2E.magicTraditions[tradition],rank:systemData.proficiencies.traditions[tradition].rank,domains:["all","spell-attack-dc"],check:{type:"check",domains:[`${tradition}-spell-attack`]},dc:{domains:[`${tradition}-spell-dc`]}}),traditions),{}),this.classDC=null,this.classDCs={};for(const[slug,classDC]of Object.entries(systemData.proficiencies.classDCs)){const statistic=this.prepareClassDC(slug,classDC);systemData.proficiencies.classDCs[slug]=mergeObject(classDC,statistic.getTraceData({value:"dc"})),this.classDCs[slug]=statistic,classDC.primary&&(this.classDC=statistic)}systemData.attributes.classDC=Object.values(systemData.proficiencies.classDCs).find(c=>c.primary)??null,systemData.attributes.classDC&&(systemData.attributes.classOrSpellDC=pick$1(systemData.attributes.classDC,["rank","value"]));const armorStatistic=this.createArmorStatistic();this.armorClass=armorStatistic.dc,systemData.attributes.ac=armorStatistic.getTraceData();const{heldShield}=this;if(heldShield?.speedPenalty){const speedPenalty=new ModifierPF2e(heldShield.name,heldShield.speedPenalty,"untyped");speedPenalty.predicate.push({not:"self:shield:ignore-speed-penalty"}),this.synthetics.modifiers.speed??=[],this.synthetics.modifiers.speed.push(()=>speedPenalty)}const speeds=systemData.attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]),systemData.actions=this.prepareStrikes(),this.flags.pf2e.highestWeaponDamageDice=Math.max(...systemData.actions.filter(s=>s.ready).map(s=>s.item.system.damage.dice),0),this.initiative=new ActorInitiative(this),this.system.attributes.initiative=this.initiative.getTraceData();const{focus,crafting}=this.system.resources;focus.max=Math.floor(Math.clamped(focus.max,0,focus.cap)),crafting.infusedReagents.max=Math.floor(crafting.infusedReagents.max)||0,crafting.infusedReagents.value=Math.clamped(crafting.infusedReagents.value,0,crafting.infusedReagents.max),focus.max===0&&this.spellcasting.regular.some(entry=>entry.isFocusPool)&&(focus.max=1),systemData.attributes.familiarAbilities.value>0&&(this.rollOptions.all["self:has-familiar"]=!0)}setAttributeModifiers(){const{build}=this.system;if(!build.attributes.manual){for(const section of["ancestry","background","class",1,5,10,15,20]){const boosts=build.attributes.boosts[section];if(typeof boosts=="string"){const ability=this.system.abilities[boosts];ability.mod+=ability.mod>=4?.5:1}else if(Array.isArray(boosts))for(const abbrev of boosts){const ability=this.system.abilities[abbrev];ability.mod+=ability.mod>=4?.5:1}const flaws=section==="ancestry"?build.attributes.flaws[section]:[];for(const abbrev of flaws){const ability=this.system.abilities[abbrev];ability.mod-=1}}const isABP=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this);if(build.attributes.apex&&(!isABP||this.level>=17)){const attribute=this.system.abilities[build.attributes.apex];attribute.mod=Math.max(attribute.mod+1,4)}}for(const ability of Object.values(this.system.abilities))ability.mod=Math.clamped(ability.mod,-5,10),ability.base=Math.trunc(ability.mod)}setNumericRollOptions(){const rollOptionsAll=this.rollOptions.all,perceptionRank=this.system.attributes.perception.rank;rollOptionsAll[`perception:rank:${perceptionRank}`]=!0;for(const key of ATTRIBUTE_ABBREVIATIONS){const mod=this.abilities[key].mod;rollOptionsAll[`attribute:${key}:mod:${mod}`]=!0}for(const key of SKILL_ABBREVIATIONS){const rank=this.system.skills[key].rank;rollOptionsAll[`skill:${key}:rank:${rank}`]=!0}for(const key of WEAPON_CATEGORIES){const rank=this.system.proficiencies.attacks[key].rank;rollOptionsAll[`attack:${key}:rank:${rank}`]=!0}for(const key of ARMOR_CATEGORIES){const rank=this.system.proficiencies.defenses[key].rank;rollOptionsAll[`defense:${key}:rank:${rank}`]=!0}for(const key of SAVE_TYPES){const rank=this.system.saves[key].rank;rollOptionsAll[`save:${key}:rank:${rank}`]=!0}const{handsFree,handsReallyFree}=this;this.attributes.handsFree=handsFree,rollOptionsAll[`hands-free:${handsFree}`]=!0,rollOptionsAll[`hands-free:but-really:${handsReallyFree}`]=!0}createArmorStatistic(){const{synthetics,wornArmor}=this;this.system.proficiencies.defenses["light-barding"].rank||=this.traits.has("animal")&&!isReallyPC(this)?Math.max(this.system.proficiencies.defenses["light-barding"].rank,1):0;const modifiers=[],dexCapSources=[{value:1/0,source:""},...synthetics.dexterityModifierCaps];wornArmor&&dexCapSources.push({value:Number(wornArmor.dexCap??0),source:wornArmor.name});const dexCap=dexCapSources.reduce((lowest,candidate)=>lowest.value>candidate.value?candidate:lowest),dexModifier=createAttributeModifier({actor:this,attribute:"dex",domains:["all","ac","dex-based"],max:dexCap.value}),attributeModifier=modifiers.filter(m=>m.type==="ability"&&!!m.ability).reduce((best,modifier)=>modifier.modifier>best.modifier?modifier:best,dexModifier),proficiency=Object.entries(this.system.proficiencies.defenses).filter(([key,proficiency2])=>wornArmor?wornArmor.category===key?!0:proficiency2.definition?.test(wornArmor.getRollOptions("item"))??!1:key==="unarmored").map(([_k,v])=>v).reduce((best,p)=>p.rank>best.rank?p:best,{rank:0});return new ArmorStatistic(this,{rank:proficiency.rank,attribute:attributeModifier.ability,modifiers:[attributeModifier]})}prepareSaves(){const systemData=this.system,{wornArmor}=this,saves={};for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),modifiers=[],selectors=[saveType,`${save.ability}-based`,"saving-throw","all"];if(wornArmor?.system.resiliencyRune.value){const resilientBonus=getResilientBonus(wornArmor.system);resilientBonus>0&&wornArmor.isInvested&&modifiers.push(new ModifierPF2e(wornArmor.name,resilientBonus,"item"))}if(saveType==="reflex"&&wornArmor?.traits.has("bulwark")){const slug="bulwark",bulwarkModifier=new ModifierPF2e({slug,type:"untyped",label:CONFIG.PF2E.armorTraits.bulwark,modifier:3,predicate:["damaging-effect"],adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,selectors,slug)});modifiers.push(bulwarkModifier),(this.synthetics.modifierAdjustments[saveType]??=[]).push({slug:"dex",test:options=>new PredicatePF2e("damaging-effect").test(options),suppress:!0})}const stat=new Statistic(this,{slug:saveType,label:saveName,attribute:save.ability,rank:save.rank,modifiers,domains:selectors,check:{type:"saving-throw"}});saves[saveType]=stat,this.system.saves[saveType]=mergeObject(this.system.saves[saveType],stat.getTraceData())}this.saves=saves}prepareSkills(){const systemData=this.system,{synthetics,wornArmor}=this,skills=Array.from(SKILL_ABBREVIATIONS).reduce((builtSkills,shortForm)=>{const skill=systemData.skills[shortForm],longForm=SKILL_DICTIONARY[shortForm],label=CONFIG.PF2E.skillList[longForm]??longForm,domains=[longForm,`${skill.ability}-based`,"skill-check",`${skill.ability}-skill-check`,"all"],modifiers=[],strengthRequirement=wornArmor?.strength;if(typeof strengthRequirement=="number"&&this.system.abilities.str.mod>=strengthRequirement)for(const selector of["skill-check","initiative"]){const rollOptions=this.rollOptions[selector]??={};rollOptions["armor:strength-requirement-met"]=!0}if(skill.armor&&typeof wornArmor?.checkPenalty=="number"){const slug="armor-check-penalty",armorCheckPenalty=new ModifierPF2e({slug,label:"PF2E.ArmorCheckPenalty",modifier:wornArmor.checkPenalty,type:"untyped",adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,slug)});armorCheckPenalty.predicate.push({nor:["attack","armor:ignore-check-penalty"]}),["acrobatics","athletics"].includes(longForm)?armorCheckPenalty.predicate.push({nor:["armor:strength-requirement-met","armor:trait:flexible"]}):longForm==="stealth"&&wornArmor.traits.has("noisy")?armorCheckPenalty.predicate.push({nand:["armor:strength-requirement-met","armor:ignore-noisy-penalty"]}):armorCheckPenalty.predicate.push({not:"armor:strength-requirement-met"}),modifiers.push(armorCheckPenalty)}longForm==="athletics"&&modifiers.push(createForceOpenPenalty(this,domains));const statistic=new Statistic(this,{slug:longForm,label,rank:skill.rank,attribute:skill.ability,domains,modifiers,lore:!1,check:{type:"skill-check"}});return builtSkills[longForm]=statistic,this.system.skills[shortForm]=mergeObject(this.system.skills[shortForm],statistic.getTraceData()),builtSkills},{});for(const loreItem of this.itemTypes.lore){const longForm=sluggify(loreItem.name),rank=loreItem.system.proficient.value,domains=[longForm,"int-based","skill-check","lore-skill-check","int-skill-check","all"],statistic=new Statistic(this,{slug:longForm,label:loreItem.name,rank,attribute:"int",domains,lore:!0,check:{type:"skill-check"}});skills[longForm]=statistic,this.system.skills[longForm]={armor:!1,ability:"int",rank,lore:!0,itemID:loreItem.id,...statistic.getTraceData()}}return skills}prepareSpeed(movementType){const statistic=super.prepareSpeed(movementType);if(!statistic)return null;const{wornArmor}=this,basePenalty=wornArmor?.speedPenalty??0,strength=this.system.abilities.str.mod,requirement=wornArmor?.strength??strength,penaltyValue=strength>=requirement?Math.min(basePenalty+5,0):basePenalty,derivedFromLand=!!("derivedFromLand"in statistic&&statistic.derivedFromLand),modifierName=wornArmor?.name??"PF2E.ArmorSpeedLabel",slug="armor-speed-penalty",armorPenalty=penaltyValue&&!derivedFromLand?new ModifierPF2e({slug,label:modifierName,modifier:penaltyValue,type:"untyped",predicate:new PredicatePF2e({not:"armor:ignore-speed-penalty"}),adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,["all-speeds","speed",`${movementType}-speed`],slug)}):null;armorPenalty&&(statistic.push(armorPenalty),statistic.calculateTotal(new Set(this.getRollOptions(["all-speeds","speed",`${movementType}-speed`]))));const hinderingPenalty=createHinderingPenalty(this);return hinderingPenalty&&statistic.push(hinderingPenalty),statistic}prepareFeats(){this.pfsBoons=[],this.deityBoonsCurses=[],this.feats=new CharacterFeats(this);const campaignFeatSections=game.settings.get("pf2e","campaignFeatSections");for(const section of campaignFeatSections)this.feats.createGroup(section);this.feats.assignToSlots();const feats=this.itemTypes.feat.filter(f=>["pfsboon","deityboon","curse"].includes(f.category)).sort((f1,f2)=>f1.sort-f2.sort);for(const feat of feats)feat.category==="pfsboon"?this.pfsBoons.push(feat):this.deityBoonsCurses.push(feat)}prepareClassDC(slug,classDC){classDC.ability??="str",classDC.rank??=0,classDC.primary??=!1;const classNames=CONFIG.PF2E.classTraits;return classDC.label=classDC.label??classNames[slug]??slug.titleCase(),new Statistic(this,{slug,label:classDC.label,attribute:classDC.ability,rank:classDC.rank,domains:["class",slug,`${classDC.ability}-based`,"all"],check:{type:"check"}})}prepareStrikes({includeBasicUnarmed=!0}={}){const{itemTypes,synthetics}=this,handwrapsSlug="handwraps-of-mighty-blows",handwraps=itemTypes.weapon.find(w=>w.slug===handwrapsSlug&&w.category==="unarmed"&&w.isEquipped),unarmedRunes=(()=>{const{potencyRune,strikingRune,propertyRune1,propertyRune2,propertyRune3,propertyRune4}=handwraps?._source.system??{};return handwraps?.isInvested?deepClone({potencyRune,strikingRune,propertyRune1,propertyRune2,propertyRune3,propertyRune4}):null})(),basicUnarmed=includeBasicUnarmed?(()=>{const source={_id:"xxPF2ExUNARMEDxx",name:game.i18n.localize("PF2E.WeaponTypeUnarmed"),type:"weapon",img:"icons/skills/melee/unarmed-punch-fist.webp",system:{slug:"basic-unarmed",category:"unarmed",baseItem:null,bonus:{value:0},damage:{dice:1,die:"d4",damageType:"bludgeoning"},equipped:{carryType:"worn",inSlot:!0,handsHeld:0},group:"brawling",traits:{value:["agile","finesse","nonlethal","unarmed"]},usage:{value:"worngloves"},...unarmedRunes??{}}};return new WeaponPF2e(source,{parent:this})})():null;if(unarmedRunes)for(const[slug,weapon]of synthetics.strikes.entries()){weapon.category==="unarmed"&&synthetics.strikes.set(slug,weapon.clone({system:unarmedRunes},{keepId:!0}));const clone=synthetics.strikes.get(slug);clone.name=clone._source.name}const ammos=[...itemTypes.consumable.filter(i=>i.category==="ammo"&&!i.isStowed),...itemTypes.weapon.filter(w=>w.system.usage.canBeAmmo)],homebrewCategoryTags=game.settings.get("pf2e","homebrew.weaponCategories"),offensiveCategories=[...WEAPON_CATEGORIES,...homebrewCategoryTags.map(tag=>tag.id)],weapons=[itemTypes.weapon.filter(w=>w.slug!==handwrapsSlug),Array.from(synthetics.strikes.values()),basicUnarmed??[]].flat(),{handsReallyFree}=this;return weapons.map(w=>this.prepareStrike(w,{categories:offensiveCategories,handsReallyFree,ammos})).sort((a,b)=>a.label.toLocaleLowerCase(game.i18n.lang).replace(/[-0-9\s]/g,"").localeCompare(b.label.toLocaleLowerCase(game.i18n.lang).replace(/[-0-9\s]/gi,""),game.i18n.lang)).sort((a,b)=>a.slug==="basic-unarmed"?1:b.slug==="basic-unarmed"?-1:0).sort((a,b)=>a.ready!==b.ready?(a.ready?0:1)-(b.ready?0:1):0)}prepareStrike(weapon,{categories,handsReallyFree,ammos=[]}){const{synthetics}=this,modifiers=[],systemData=this.system,strikeAdjustments=[synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(weapon.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustWeapon?.(weapon);const weaponRollOptions=weapon.getRollOptions("item"),weaponTraits2=weapon.traits,{proficiencies}=systemData,categoryRank=proficiencies.attacks[weapon.category]?.rank??0,groupRank=proficiencies.attacks[`weapon-group-${weapon.group}`]?.rank??0,baseWeapon=CONFIG.PF2E.equivalentWeapons[weapon.baseType??""]??weapon.baseType,baseWeaponRank=proficiencies.attacks[`weapon-base-${baseWeapon}`]?.rank??0,equivalentCategories=Object.values(proficiencies.attacks).flatMap(p=>p&&"sameAs"in p&&(p.definition?.test(weaponRollOptions)??!0)?`item:category:${p.sameAs}`:[]),weaponProficiencyOptions=new Set(weaponRollOptions.concat(equivalentCategories)),syntheticRanks=compact(Object.values(proficiencies.attacks)).filter(p=>p.immutable&&(p.definition?.test(weaponProficiencyOptions)??!0)).map(p=>p.rank),proficiencyRank=Math.max(categoryRank,groupRank,baseWeaponRank,...syntheticRanks),meleeOrRanged=weapon.isMelee?"melee":"ranged",baseOptions=new Set(["action:strike",`item:proficiency:rank:${proficiencyRank}`,PROFICIENCY_RANK_OPTION[proficiencyRank],...weaponTraits2,meleeOrRanged]),attackDomains=getStrikeAttackDomains(weapon,proficiencyRank,baseOptions),{defaultAttribute}=weapon;modifiers.push(createAttributeModifier({actor:this,attribute:defaultAttribute,domains:attackDomains})),weapon.isMelee&&weaponTraits2.has("finesse")&&modifiers.push(createAttributeModifier({actor:this,attribute:"dex",domains:attackDomains})),weapon.isRanged&&weaponTraits2.has("brutal")&&modifiers.push(createAttributeModifier({actor:this,attribute:"str",domains:attackDomains})),modifiers.push(createProficiencyModifier({actor:this,rank:proficiencyRank,domains:attackDomains}));const initialRollOptions=new Set([...baseOptions,...this.getRollOptions(attackDomains),...weaponRollOptions]),ABP=game.pf2e.variantRules.AutomaticBonusProgression;if(weapon.group==="bomb"&&!ABP.isEnabled(this)){const attackBonus=Number(weapon.system.bonus?.value)||0;attackBonus!==0&&modifiers.push(new ModifierPF2e("PF2E.ItemBonusLabel",attackBonus,"item"))}const weaponPotency=(()=>{const potency=attackDomains.flatMap(key=>deepClone(synthetics.weaponPotency[key]??[])).filter(wp=>wp.predicate.test(initialRollOptions));return weapon.system.runes.potency&&potency.push({label:"PF2E.Item.Weapon.Rune.Potency",bonus:weapon.system.runes.potency,type:"item",predicate:new PredicatePF2e}),potency.length>0?potency.reduce((highest,current)=>highest.bonus>current.bonus?highest:current):null})();weaponPotency&&(modifiers.push(new ModifierPF2e(weaponPotency.label,weaponPotency.bonus,weaponPotency.type)),!weapon.isMagical&&(weaponPotency.type==="item"||!ABP.isEnabled(weapon.actor))&&weapon.system.traits.value.push("magical"),weapon.flags.pf2e.attackItemBonus=weaponPotency.bonus);const shoddyPenalty=createShoddyPenalty(this,weapon,attackDomains);shoddyPenalty&&modifiers.push(shoddyPenalty),modifiers.push(...PCAttackTraitHelpers.createAttackModifiers({item:weapon,domains:attackDomains}),...extractModifiers(synthetics,attackDomains,{injectables:{weapon},resolvables:{weapon}}));const auxiliaryActions=[],isRealItem=this.items.has(weapon.id);if(weapon.system.traits.toggles.modular.options.length>0&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Interact",purpose:"Modular"})),isRealItem&&weapon.category!=="unarmed"){const traitsArray=weapon.system.traits.value,hasFatalAimTrait=traitsArray.some(t=>t.startsWith("fatal-aim")),hasTwoHandTrait=traitsArray.some(t=>t.startsWith("two-hand")),{usage}=weapon.system,canWield2H=usage.type==="held"&&usage.hands===2||hasFatalAimTrait||hasTwoHandTrait;switch(weapon.carryType){case"held":{weapon.handsHeld===2?auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Release",purpose:"Grip",hands:1})):weapon.handsHeld===1&&canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Interact",purpose:"Grip",hands:2})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Interact",purpose:"Sheathe",hands:0})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Release",purpose:"Drop",hands:0}));break}case"worn":{canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Interact",purpose:"Draw",hands:2})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Interact",purpose:"Draw",hands:1}));break}case"stowed":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Interact",purpose:"Retrieve",hands:1}));break}case"dropped":{canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Interact",purpose:"PickUp",hands:2})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"Interact",purpose:"PickUp",hands:1}));break}}}const weaponSlug=weapon.slug??sluggify(weapon.name),flavor=this.getStrikeDescription(weapon),rollOptions=[...this.getRollOptions(attackDomains),...weaponRollOptions,...weaponTraits2,meleeOrRanged],strikeStat=new StatisticModifier(weaponSlug,modifiers,rollOptions),altUsages=weapon.getAltUsages().map(w=>this.prepareStrike(w,{categories,handsReallyFree})),versatileLabel=__name2(damageType=>{switch(damageType){case"bludgeoning":return CONFIG.PF2E.weaponTraits["versatile-b"];case"piercing":return CONFIG.PF2E.weaponTraits["versatile-p"];case"slashing":return CONFIG.PF2E.weaponTraits["versatile-s"];default:return CONFIG.PF2E.weaponTraits[`versatile-${damageType}`]??CONFIG.PF2E.damageTypes[damageType]}},"versatileLabel"),handsAvailable=!weapon.system.graspingAppendage||handsReallyFree>0,ready2=weapon.isEquipped&&handsAvailable||weapon.isThrown&&weapon.reload==="0"&&weapon.isWorn&&handsReallyFree>0,action2=mergeObject(strikeStat,{label:weapon.name,quantity:weapon.quantity,ready:ready2,domains:attackDomains,visible:weapon.slug!=="basic-unarmed"||this.flags.pf2e.showBasicUnarmed,glyph:"A",item:weapon,type:"strike",...flavor,options:Array.from(baseOptions),traits:[],handsAvailable,weaponTraits:Array.from(weaponTraits2).map(t=>traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits)).sort((a,b)=>a.label.localeCompare(b.label)),variants:[],selectedAmmoId:weapon.system.selectedAmmoId,altUsages,auxiliaryActions,versatileOptions:weapon.system.traits.toggles.versatile.options.map(o=>({value:o,selected:weapon.system.traits.toggles.versatile.selection===o,label:versatileLabel(o),glyph:DAMAGE_TYPE_ICONS[o]}))});if(action2.versatileOptions.length>0&&action2.versatileOptions.unshift({value:weapon.system.damage.damageType,selected:weapon.system.traits.toggles.versatile.selection===null,label:CONFIG.PF2E.damageTypes[weapon.system.damage.damageType],glyph:DAMAGE_TYPE_ICONS[weapon.system.damage.damageType]}),weapon.requiresAmmo){const compatible=ammos.filter(a=>a.isAmmoFor(weapon)),incompatible=ammos.filter(a=>!a.isAmmoFor(weapon)),{ammo}=weapon,selected=ammo?{id:ammo.id,compatible:ammo.isAmmoFor(weapon)}:null;action2.ammunition={compatible,incompatible,selected}}const actionTraits2=["attack",weapon.baseType==="alchemical-bomb"?"manipulate":[]].flat();for(const adjustment of synthetics.strikeAdjustments)adjustment.adjustTraits?.(weapon,actionTraits2);action2.traits=actionTraits2.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),action2.breakdown=action2.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", ");const maps=calculateMAPs(weapon,{domains:attackDomains,options:initialRollOptions}),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,attackDomains,maps.slug)}),"createMapModifier"),createMapLabel=__name2(prop=>{const modifier=createMapModifier(prop);adjustModifiers([modifier],new Set(rollOptions));const penalty=modifier.ignored?0:modifier.value;return game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(action2.totalModifier+penalty),penalty})},"createMapLabel"),labels=[()=>signedInteger(action2.totalModifier),()=>createMapLabel("map1"),()=>createMapLabel("map2")],checkModifiers=[(statistic,otherModifiers)=>new CheckModifier("strike",statistic,otherModifiers),(statistic,otherModifiers)=>new CheckModifier("strike-map1",statistic,[...otherModifiers,createMapModifier("map1")]),(statistic,otherModifiers)=>new CheckModifier("strike-map2",statistic,[...otherModifiers,createMapModifier("map2")])];action2.variants=[0,1,2].map(mapIncreases=>({get label(){return labels[mapIncreases]()},roll:async(params={})=>{if(params.options??=[],params.consumeAmmo??=weapon.requiresAmmo,weapon.requiresAmmo&¶ms.consumeAmmo&&!weapon.ammo)return ui.notifications.warn(game.i18n.format("PF2E.Strike.Ranged.NoAmmo",{weapon:weapon.name,actor:this.name})),null;const context=await this.getCheckContext({item:weapon,domains:attackDomains,statistic:action2,target:{token:params.target??game.user.targets.first()??null},defense:"armor",options:new Set([...baseOptions,...params.options]),viewOnly:params.getFormula});if(context.self.item.isRanged&&typeof context.target?.distance=="number"){const maxRange=context.self.item.range?.max??10;if(context.target.distance>maxRange)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null}for(const rule of this.rules.filter(r=>!r.ignored))rule.beforeRoll?.(attackDomains,context.options);const dc=params.dc??context.dc,notes=extractNotes(context.self.actor.synthetics.rollNotes,attackDomains),rollTwice=params.rollTwice||extractRollTwice(context.self.actor.synthetics.rollTwice,attackDomains,context.options),substitutions=extractRollSubstitutions(context.self.actor.synthetics.rollSubstitutions,attackDomains,context.options),dosAdjustments=[getPropertyRuneDegreeAdjustments(context.self.item),extractDegreeOfSuccessAdjustments(context.self.actor.synthetics,attackDomains)].flat(),title=game.i18n.format(weapon.isMelee?"PF2E.Action.Strike.MeleeLabel":"PF2E.Action.Strike.RangedLabel",{weapon:weapon.name}),checkContext={type:"attack-roll",identifier:`${weapon.id}.${weaponSlug}.${meleeOrRanged}`,action:"strike",title,actor:context.self.actor,token:context.self.token,target:context.target,item:context.self.item,altUsage:params.altUsage??null,damaging:context.self.item.dealsDamage,domains:attackDomains,options:context.options,notes,dc,traits:context.traits,rollTwice,substitutions,dosAdjustments,mapIncreases};if(params.consumeAmmo&&!this.consumeAmmo(context.self.item,params))return null;const check=checkModifiers[mapIncreases](context.self.statistic??action2,context.self.modifiers),roll=await CheckPF2e.roll(check,checkContext,params.event,params.callback);if(roll)for(const rule of context.self.actor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context:checkContext,domains:attackDomains,rollOptions:context.options});return roll}})),action2.attack=action2.roll=action2.variants[0].roll;for(const method of["damage","critical"])action2[method]=async(params={})=>{const domains=getStrikeDamageDomains(weapon,proficiencyRank);params.options=new Set(params.options??[]);const targetToken=params.target??game.user.targets.first()??null,context=await this.getDamageRollContext({item:weapon,viewOnly:params.getFormula??!1,statistic:action2,target:{token:targetToken},domains,outcome:method==="damage"?"success":"criticalSuccess",options:new Set([...baseOptions,...params.options]),checkContext:params.checkContext});if(!context.self.item.dealsDamage)return params.getFormula?"":(ui.notifications.warn("PF2E.ErrorMessage.WeaponNoDamage",{localize:!0}),null);const outcome=method==="damage"?"success":"criticalSuccess",{self,target,options}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options,domains,...eventToRollParams(params.event,{type:"damage"})};typeof params.mapIncreases=="number"&&(damageContext.mapIncreases=params.mapIncreases,damageContext.options.add(`map:increases:${params.mapIncreases}`)),params.getFormula&&(damageContext.skipDialog=!0);const damage=await WeaponDamagePF2e.calculate({weapon:context.self.item,actor:context.self.actor,actionTraits:context.traits,weaponPotency,context:damageContext});if(!damage)return null;if(params.getFormula){const formula=damage.damage.formula[outcome];return formula?new DamageRoll(formula).formula:""}else return DamagePF2e.roll(damage,damageContext,params.callback)};return action2}getStrikeDescription(weapon){const flavor={description:"PF2E.Strike.Default.Description",criticalSuccess:"PF2E.Strike.Default.CriticalSuccess",success:"PF2E.Strike.Default.Success"},traits=weapon.traits;return traits.has("unarmed")?(flavor.description="PF2E.Strike.Unarmed.Description",flavor.success="PF2E.Strike.Unarmed.Success"):[...traits].some(trait=>trait.startsWith("thrown-")||trait==="combination")?(flavor.description="PF2E.Strike.Combined.Description",flavor.success="PF2E.Strike.Combined.Success"):weapon.isMelee?(flavor.description="PF2E.Strike.Melee.Description",flavor.success="PF2E.Strike.Melee.Success"):(flavor.description="PF2E.Strike.Ranged.Description",flavor.success="PF2E.Strike.Ranged.Success"),flavor}async getRollContext(params){const context=await super.getRollContext(params);return params.statistic instanceof StatisticModifier&&context.self.item?.isOfType("weapon")&&PCAttackTraitHelpers.adjustWeapon(context.self.item),context}consumeAmmo(weapon,params){const ammo=weapon.ammo;if(ammo){if(ammo.quantity<1)return ui.notifications.warn(game.i18n.localize("PF2E.ErrorMessage.NotEnoughAmmo")),!1;{const existingCallback=params.callback;return params.callback=async roll=>{existingCallback?.(roll),await weapon.consumeAmmo()},!0}}else return!0}prepareMartialProficiencies(){for(const key of["attacks","defenses"]){const proficiencies=this.system.proficiencies[key],linkedProficiencies=Object.values(proficiencies).filter(p=>!!p?.sameAs&&p.sameAs in proficiencies);for(const proficiency of linkedProficiencies){const category=proficiencies[proficiency.sameAs??""];proficiency.rank=(()=>{const maxRankIndex=PROFICIENCY_RANKS.indexOf(proficiency.maxRank??"legendary");return Math.min(category?.rank??0,maxRankIndex)})()}const allProficiencies=Object.entries(proficiencies);for(const[_key,proficiency]of allProficiencies){if(!proficiency)continue;const duplicates=allProficiencies.flatMap(([k,p])=>p&&proficiency!==p&&proficiency.rank>=p.rank&&"definition"in proficiency&&"definition"in p&&proficiency.sameAs===p.sameAs&&equals(p.definition??[],[...proficiency.definition??[]])?k:[]);for(const duplicate2 of duplicates)delete proficiencies[duplicate2];const proficiencyBonus=createProficiencyModifier({actor:this,rank:proficiency.rank,domains:[]});proficiency.value=proficiencyBonus.value,proficiency.breakdown=`${proficiencyBonus.label} ${signedInteger(proficiencyBonus.value)}`}}}async toggleInvested(itemId){const item=this.inventory.get(itemId);if(!item?.traits.has("invested"))throw ErrorPF2e("Unexpected error toggling item investment");const invested=item.isInvested;if(!invested&&!item.isEquipped){const newCarryType=item.system.usage.type==="carried"?"worn":item.system.usage.type;await this.adjustCarryType(item,{carryType:newCarryType,handsHeld:item.system.usage.hands,inSlot:!0})}return!!await item.update({"system.equipped.invested":!invested})}async addAttackProficiency(key){const currentProficiencies=this.system.proficiencies.attacks;if(key in currentProficiencies)return;const newProficiency={rank:1,custom:!0};await this.update({[`system.proficiencies.attacks.${key}`]:newProficiency})}async _preUpdate(changed,options,user){const systemData=this.system;if(typeof changed.system?.resources?.crafting?.infusedReagents?.value=="number"&&(changed.system.resources.crafting.infusedReagents.value=Math.max(0,Math.floor(changed.system.resources.crafting.infusedReagents.value))||0),changed.system?.details?.level||changed.system?.build?.attributes){const level=changed.system?.details?.level;typeof level?.value=="number"&&(level.value=Math.clamped(Number(level.value)||0,0,30)||0);const hpMaxDifference=this.clone(changed).hitPoints.max-this.hitPoints.max;if(hpMaxDifference!==0){options.allowHPOverage=!0;const currentHP=this.hitPoints.value,newHP=Math.max(currentHP+hpMaxDifference,currentHP===0?0:1);changed.system=mergeObject(changed.system??{},{attributes:{hp:{value:newHP}}})}}game.settings.get("pf2e","staminaVariant")&&(changed.system?.attributes?.hp?.sp&&(changed.system.attributes.hp.sp.value=Math.floor(Math.clamped(changed.system.attributes.hp.sp?.value??0,0,systemData.attributes.hp.sp?.max??0))||0),changed.system?.resources?.resolve&&(changed.system.resources.resolve.value=Math.floor(Math.clamped(changed.system.resources.resolve.value??0,0,systemData.resources.resolve?.max??0))||0));const xp=changed.system?.details?.xp??{};typeof xp.value=="number"&&(xp.value=Math.max(xp.value,0)),typeof xp.max=="number"&&(xp.max=Math.max(xp.max,1));const newLevel=changed.system?.details?.level?.value??this.level,actorClass=this.class;if(actorClass&&newLevel!==this.level){const current=this.itemTypes.feat.filter(feat=>feat.category==="classfeature");if(newLevel>this.level){const classFeaturesToCreate=(await actorClass.createGrantedItems({level:newLevel})).filter(feature=>feature.system.level.value>this.level&&!current.some(currentFeature=>currentFeature.sourceId===feature.flags.core?.sourceId)).map(i=>i.toObject());await this.createEmbeddedDocuments("Item",classFeaturesToCreate,{keepId:!0,render:!1})}else if(newLevelf.level>newLevel&&!f.grantedBy).map(f=>f.id);await this.deleteEmbeddedDocuments("Item",classFeaturestoDelete,{render:!1})}}for(const property of["playerNumber","characterNumber"])if(typeof changed.system?.pfs?.[property]=="number"){const[min,max]=property==="playerNumber"?[1,9999999]:[2001,9999];changed.system.pfs[property]=Math.clamped(changed.system.pfs[property]||0,min,max)}else changed.system?.pfs&&changed.system.pfs[property]!==null&&(changed.system.pfs[property]=this.system.pfs[property]??null);return super._preUpdate(changed,options,user)}async toggleAttributeManagement(){if(Object.keys(this._source.system.abilities??{}).length===0){const baseAbilities=Array.from(ATTRIBUTE_ABBREVIATIONS).reduce((accumulated,abbrev)=>({...accumulated,[abbrev]:{value:10}}),{});await this.update({"system.abilities":baseAbilities})}else await this.update({"system.-=abilities":null})}};__name2(_CharacterPF2e,"CharacterPF2e");let CharacterPF2e=_CharacterPF2e;const _FamiliarPF2e=class extends CreaturePF2e{static{__name(this,"_FamiliarPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"action"]}get master(){if(!game.ready||!this.system.master.id)return null;const master=game.actors.get(this.system.master.id??"");return master?.isOfType("character")?(master.familiar??=this,master):null}get masterAttributeModifier(){return this.system.master.ability||="cha",this.master?.system.abilities[this.system.master.ability].mod??0}get masterAbilityModifier(){return this.masterAttributeModifier}get combatant(){return this.master?.combatant??null}reset({fromMaster=!1}={}){super.reset(),fromMaster&&this.sheet.render()}prepareBaseData(){const systemData=this.system;systemData.details.level={value:0},systemData.traits={value:["minion"],senses:[{type:"lowLightVision",label:CONFIG.PF2E.senses.lowLightVision,value:""}],size:new ActorSizePF2e({value:"tiny"})},super.prepareBaseData();const isItemBonus=new PredicatePF2e(["bonus:type:item"]);this.synthetics.modifierAdjustments.all.push({slug:null,test:options=>isItemBonus.test(options),suppress:!0}),systemData.details.alignment={value:"N"},systemData.attributes.flanking.canFlank=!1,systemData.attributes.perception={},systemData.attributes.speed={value:25,label:game.i18n.localize("PF2E.SpeedTypesLand"),otherSpeeds:[]},systemData.skills={},systemData.saves={fortitude:{},reflex:{},will:{}},systemData.traits=mergeObject(systemData.traits,{dv:[],di:[],dr:[]});const{master}=this;systemData.details.level.value=master?.level??0,this.rollOptions.all[`self:level:${this.level}`]=!0,systemData.details.alliance=master?.alliance??"party",master&&(this.flags.pf2e.rollOptions.all=mergeObject(this.flags.pf2e.rollOptions.all,createEncounterRollOptions(master)))}prepareRuleElements(){return this.master?super.prepareRuleElements():[]}prepareDerivedData(){super.prepareDerivedData();const{master}=this,systemData=this.system,{attributes,traits}=systemData;traits.value=[...this.traits].sort();const{level,masterAttributeModifier}=this,masterLevel=game.settings.get("pf2e","proficiencyVariant")?0:level,{synthetics}=this,speeds=attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]);const hitPoints=new HitPointsStatistic(this,{baseMax:level*5});this.system.attributes.hp=hitPoints.getTraceData(),setHitPointsRollOptions(this);const masterModifier=master?new ModifierPF2e({label:"PF2E.Actor.Familiar.Master.ArmorClass",slug:"base",modifier:master.armorClass.modifiers.filter(m=>m.enabled&&!["status","circumstance"].includes(m.type)).reduce((total,modifier)=>total+modifier.value,0)}):null,statistic=new ArmorStatistic(this,{modifiers:compact([masterModifier])});this.armorClass=statistic.dc,systemData.attributes.ac=statistic.getTraceData(),this.saves=SAVE_TYPES.reduce((partialSaves,saveType)=>{const source=master?.saves[saveType]?.modifiers.filter(m=>!["status","circumstance"].includes(m.type))??[],totalMod=applyStackingRules(source),attribute=CONFIG.PF2E.savingThrowDefaultAttributes[saveType],selectors=[saveType,`${attribute}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:game.i18n.localize(CONFIG.PF2E.saves[saveType]),domains:selectors,modifiers:[new ModifierPF2e(`PF2E.MasterSavingThrow.${saveType}`,totalMod,"untyped")],check:{type:"saving-throw"}});return{...partialSaves,[saveType]:stat}},{}),this.system.saves=SAVE_TYPES.reduce((partial,saveType)=>({...partial,[saveType]:this.saves[saveType].getTraceData()}),{}),traits.senses=this.prepareSenses(this.system.traits.senses,synthetics),this.attackStatistic=new Statistic(this,{slug:"attack-roll",label:"PF2E.Familiar.AttackRoll",modifiers:[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped")],check:{type:"attack-roll"}}),this.system.attack=this.attackStatistic.getTraceData();{const domains=["perception","wis-based","all"],modifiers=[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped"),new ModifierPF2e(`PF2E.MasterAbility.${systemData.master.ability}`,masterAttributeModifier,"untyped")];this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",domains,modifiers,check:{type:"perception-check"}}),systemData.attributes.perception=mergeObject(systemData.attributes.perception,this.perception.getTraceData({value:"mod"}))}this.skills=Array.from(SKILL_ABBREVIATIONS).reduce((builtSkills,shortForm)=>{const longForm=SKILL_DICTIONARY[shortForm],modifiers=[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped")];if(["acr","ste"].includes(shortForm)){const label2=`PF2E.MasterAbility.${systemData.master.ability}`;modifiers.push(new ModifierPF2e(label2,masterAttributeModifier,"untyped"))}const attribute=SKILL_EXPANDED[longForm].attribute,domains=[longForm,`${attribute}-based`,"skill-check","all"],label=CONFIG.PF2E.skills[shortForm]??longForm,statistic2=new Statistic(this,{slug:longForm,label,attribute,domains,modifiers,lore:!1,check:{type:"skill-check"}});return builtSkills[longForm]=statistic2,this.system.skills[shortForm]=statistic2.getTraceData(),builtSkills},{})}_onDelete(options,userId){this.master&&(this.master.familiar=null),super._onDelete(options,userId)}};__name2(_FamiliarPF2e,"FamiliarPF2e");let FamiliarPF2e=_FamiliarPF2e;const identifySkills=new Map([["aberration",["occultism"]],["animal",["nature"]],["astral",["occultism"]],["beast",["arcana","nature"]],["celestial",["religion"]],["construct",["arcana","crafting"]],["dragon",["arcana"]],["elemental",["arcana","nature"]],["ethereal",["occultism"]],["fey",["nature"]],["fiend",["religion"]],["fungus",["nature"]],["humanoid",["society"]],["monitor",["religion"]],["ooze",["occultism"]],["plant",["nature"]],["spirit",["occultism"]],["undead",["religion"]]]);function toKnowledgeDC(dc,rarity,loreAdjustment="normal"){const rarityAdjustment=rarityToDCAdjustment(rarity),start=combineDCAdjustments(rarityAdjustment,loreAdjustment),progression=createDifficultyScale(dc,start);return{dc:adjustDC(dc,start),progression,start}}__name(toKnowledgeDC,"toKnowledgeDC"),__name2(toKnowledgeDC,"toKnowledgeDC");function creatureIdentificationDCs(creature,{proficiencyWithoutLevel=!1}={}){const{level,rarity}=creature,dc=calculateDC(level,{proficiencyWithoutLevel}),traits=creature.system.traits.value;return{skills:Array.from(new Set(traits.flatMap(t=>identifySkills.get(t)??[]))),standard:toKnowledgeDC(dc,rarity,"normal"),lore:[toKnowledgeDC(dc,rarity,"easy"),toKnowledgeDC(dc,rarity,"very-easy")]}}__name(creatureIdentificationDCs,"creatureIdentificationDCs"),__name2(creatureIdentificationDCs,"creatureIdentificationDCs");const _NPCPF2e=class extends CreaturePF2e{static{__name(this,"_NPCPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"physical","spellcastingEntry","spell","action","melee","lore"]}get baseLevel(){return this._source.system.details.level.value}get abilities(){return deepClone(this.system.abilities)}get description(){return this.system.details.publicNotes}get hardness(){return Math.abs(this.system.attributes.hardness?.value??0)}get isElite(){return this.attributes.adjustment==="elite"}get isWeak(){return this.attributes.adjustment==="weak"}get identificationDCs(){const proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant");return creatureIdentificationDCs(this,{proficiencyWithoutLevel})}get isLootable(){const npcsAreLootable=game.settings.get("pf2e","automation.lootableNPCs");return this.isDead&&(npcsAreLootable||this.flags.pf2e.lootable)}get visible(){return super.visible&&this.prototypeToken.actorLink||this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}canUserModify(user,action2){return super.canUserModify(user,action2)||action2==="update"&&this.isLootable}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e.lootable??=!1;const systemData=this.system;systemData.actions=[];for(const key of SAVE_TYPES)systemData.saves[key].ability=CONFIG.PF2E.savingThrowDefaultAttributes[key];const{attributes,details}=systemData;attributes.perception.ability="wis",attributes.reach={base:SIZE_TO_REACH[this.size],manipulate:SIZE_TO_REACH[this.size]},details.alliance===void 0&&(details.alliance=this.hasPlayerOwner?"party":"opposition"),attributes.hp.negativeHealing=systemData.traits.value.includes("undead"),attributes.flanking.flankable=!systemData.traits.value.includes("troop");const{level}=details;level.base=Math.clamped(level.value,-1,100),level.value=this.isElite?level.base+1:this.isWeak?level.base-1:level.base,this.rollOptions.all[`self:level:${level.value}`]=!0,attributes.spellDC=null,attributes.classDC=(()=>{const proficiencyWithoutLevel=game.settings.get("pf2e","proficiencyVariant"),levelBasedDC=calculateDC(level.base,{proficiencyWithoutLevel,rarity:this.rarity});return{value:this.isElite?levelBasedDC+2:this.isWeak?levelBasedDC-2:levelBasedDC}})(),attributes.classOrSpellDC={value:attributes.classDC.value},this.system.spellcasting=mergeObject({rituals:{dc:0}},this.system.spellcasting??{})}prepareDerivedData(){super.prepareDerivedData();const{system}=this,{synthetics}=this,{modifierAdjustments}=synthetics,baseLevel=this.system.details.level.base;this.synthetics.modifiers.hp??=[],this.isElite?(modifierAdjustments.all.push({slug:"base",getNewValue:base=>base+2,test:()=>!0}),this.synthetics.modifiers.hp.push(()=>new ModifierPF2e("PF2E.NPC.Adjustment.EliteLabel",this.getHpAdjustment(baseLevel,"elite"),"untyped"))):this.isWeak&&(modifierAdjustments.all.push({slug:"base",getNewValue:base=>base-2,test:()=>!0}),this.synthetics.modifiers.hp.push(()=>new ModifierPF2e("PF2E.NPC.Adjustment.WeakLabel",this.getHpAdjustment(baseLevel,"weak")*-1,"untyped"))),system.details.level.base=baseLevel;for(const ability of Object.values(this.system.abilities))ability.mod=Math.trunc(Number(ability.mod))||0;{const base=system.attributes.hp.max,modifiers=[extractModifiers(this.synthetics,["hp"],{test:this.getRollOptions(["hp"])}),extractModifiers(this.synthetics,["hp-per-level"],{test:this.getRollOptions(["hp-per-level"])}).map(modifier=>(modifier.modifier*=this.level,modifier))].flat(),hpData=deepClone(system.attributes.hp),stat=mergeObject(new StatisticModifier("hp",modifiers),hpData,{overwrite:!1});stat.base=base,stat.max=stat.max+stat.totalModifier,stat.value=Math.min(stat.value,stat.max),stat.breakdown=[game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base}),...stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`)].join(", "),system.attributes.hp=stat,setHitPointsRollOptions(this)}const speeds=system.attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]);const armorStatistic=new ArmorStatistic(this,{modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.attributes.ac.value-10,adjustments:extractModifierAdjustments(modifierAdjustments,["all","ac","dex-based"],"base")})],details:system.attributes.ac.details});this.armorClass=armorStatistic.dc,this.system.attributes.ac=armorStatistic.getTraceData(),this.prepareSaves();{const domains=["perception","wis-based","all"];this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",attribute:"wis",domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.attributes.perception.value,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"perception-check"}}),system.attributes.perception=mergeObject(system.attributes.perception,this.perception.getTraceData({value:"mod"}))}this.skills=this.prepareSkills();const generatedMelee=Array.from(synthetics.strikes.values()).flatMap(w=>w.toNPCAttacks({keepId:!0}));for(const item of[...this.itemTypes.melee,...generatedMelee])system.actions.push(strikeFromMeleeItem(item));this.initiative=new ActorInitiative(this),this.system.attributes.initiative=this.initiative.getTraceData()}prepareSaves(){const systemData=this.system,{modifierAdjustments}=this.synthetics,saves={};for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),base=save.value,ability=save.ability,domains=[saveType,`${ability}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:saveName,domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"saving-throw"}});saves[saveType]=stat,mergeObject(this.system.saves[saveType],stat.getTraceData()),systemData.saves[saveType].base=base}this.saves=saves}prepareSkills(){const{system}=this,{modifierAdjustments}=this.synthetics;system.skills={};function createTrace(stat,item){const{attribute,shortForm}=objectHasKey(SKILL_EXPANDED,stat.slug)?SKILL_EXPANDED[stat.slug]:{attribute:"int",shortForm:stat.slug};system.skills[shortForm]={...stat.getTraceData(),base:item?.system.mod.value,isLore:!!stat.lore,itemID:item?.id,ability:attribute,visible:stat.proficient,variants:Object.values(item?.system.variants??{})}}__name(createTrace,"createTrace"),__name2(createTrace,"createTrace");const skills={};for(const skill of SKILL_LONG_FORMS){const{attribute,shortForm}=SKILL_EXPANDED[skill],domains=[skill,`${attribute}-based`,"skill-check",`${attribute}-skill-check`,"all"],name2=game.i18n.localize(`PF2E.Skill${SKILL_DICTIONARY[shortForm].capitalize()}`),statistic=new Statistic(this,{slug:skill,label:name2,attribute,domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.abilities[attribute].mod,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],lore:!1,proficient:!1,check:{type:"skill-check"}});skills[skill]=statistic,createTrace(statistic)}for(const item of this.itemTypes.lore){const skill=sluggify(item.name),attribute=objectHasKey(SKILL_EXPANDED,skill)?SKILL_EXPANDED[skill].attribute:"int",label=objectHasKey(CONFIG.PF2E.skillList,skill)?CONFIG.PF2E.skillList[skill]:item.name,base=item.system.mod.value,domains=[skill,`${attribute}-based`,"skill-check","lore-skill-check",`${attribute}-skill-check`,"all"],statistic=new Statistic(this,{slug:skill,label,attribute,lore:!objectHasKey(SKILL_EXPANDED,skill),domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"skill-check"}});skills[skill]=statistic,createTrace(statistic,item)}return skills}async getAttackEffects(attack){const notes=[];attack.description&¬es.push(new RollNotePF2e({selector:"all",visibility:"gm",text:attack.description}));const formatItemName=__name2(item=>{if(item.isOfType("consumable")){const button=createHTMLElement("button",{dataset:{action:"consume",item:item.id}});return button.style.width="auto",button.style.lineHeight="14px",button.innerHTML=game.i18n.localize("PF2E.ConsumableUseLabel"),`${item.name} - ${game.i18n.localize("TYPES.Item.consumable")} (${item.quantity}) ${button.outerHTML}`}return item.name},"formatItemName"),formatNoteText=__name2(item=>{const rollData=item.getRollData();return TextEditor.enrichHTML(item.description,{rollData,async:!0})},"formatNoteText");for(const attackEffect of attack.attackEffects){const item=this.items.find(i=>i.type!=="melee"&&(i.slug??sluggify(i.name))===sluggify(attackEffect));if(item){const note=new RollNotePF2e({selector:"all",visibility:"gm",title:formatItemName(item),text:await formatNoteText(item)});notes.push(note)}else{const packItem=(await game.packs.get("pf2e.bestiary-ability-glossary-srd",{strict:!0}).getDocuments({system:{slug:attackEffect}}))[0];if(packItem instanceof ItemPF2e){const note=new RollNotePF2e({selector:"all",visibility:"gm",title:formatItemName(packItem),text:await formatNoteText(packItem)});notes.push(note)}}}return notes}getHpAdjustment(level,adjustment){if(adjustment==="elite"){if(level>=20)return 30;if(level<=19&&level>=5)return 20;if(level<=4&&level>=2)return 15;if(level<=1)return 10}else if(adjustment==="weak"){if(level>=21)return 30;if(level<=20&&level>=6)return 20;if(level<=5&&level>=3)return 15;if(level===1||level===2)return 10}return 0}async applyAdjustment(adjustment){const{isElite,isWeak}=this;if(isElite&&adjustment==="elite"||isWeak&&adjustment==="weak"||!isElite&&!isWeak&&!adjustment)return;const currentHPAdjustment=(()=>isElite?this.getHpAdjustment(this.baseLevel,"elite"):isWeak?this.getHpAdjustment(this.baseLevel,"weak"):0)(),newHPAdjustment=this.getHpAdjustment(this.baseLevel,adjustment),currentHP=this.system.attributes.hp.value,maxHP=this.system.attributes.hp.max,newHP=(()=>{if(isElite){if(adjustment==="weak")return currentHP-currentHPAdjustment-newHPAdjustment;if(!adjustment)return currentHP-currentHPAdjustment}else if(isWeak){if(adjustment==="elite")return this.system.attributes.hp.max=maxHP+currentHPAdjustment+newHPAdjustment,currentHP+currentHPAdjustment+newHPAdjustment;if(!adjustment)return this.system.attributes.hp.max=maxHP+currentHPAdjustment,currentHP+currentHPAdjustment}else{if(adjustment==="elite")return this.system.attributes.hp.max=currentHP+newHPAdjustment,currentHP+newHPAdjustment;if(adjustment==="weak")return currentHP-newHPAdjustment}return currentHP})();await this.update({"system.attributes.hp.value":Math.max(0,newHP),"system.attributes.adjustment":adjustment})}variantClone(params){const source=this._source,changes={name:params.name??this.name,system:{details:{publicNotes:params.description??source.system.details.publicNotes}},img:params.img?.actor??source.img,prototypeToken:{texture:{src:params.img?.token??source.prototypeToken.texture.src}}};return this.clone(changes,{save:params.save,keepId:params.keepId})}};__name2(_NPCPF2e,"NPCPF2e");let NPCPF2e=_NPCPF2e;const _HazardPF2e=class extends ActorPF2e{static{__name(this,"_HazardPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"action","melee"]}get rarity(){return this.system.traits.rarity}get isComplex(){return this.system.details.isComplex}get hardness(){return Math.abs(this.system.attributes.hardness)}get hasDefenses(){return!!(this.hitPoints?.max||this.attributes.ac.value)}get canAttack(){return this.itemTypes.melee.length>0}get emitsSound(){const{emitsSound}=this.system.attributes;return!this.isDead&&typeof emitsSound=="boolean"?emitsSound:!!game.combats.active?.started&&game.combats.active.combatants.some(c=>c.actor===this)}isAffectedBy(effect){const damageType=objectHasKey(CONFIG.PF2E.damageTypes,effect)?effect:isObject(effect)?effect.system.persistent?.damageType??null:null;if(!this.system.attributes.hasHealth&&damageType)return!1;const{weaknesses,resistances}=this.system.attributes;return damageType&&["vitality","void"].includes(damageType)?weaknesses.some(w=>w.type===damageType)||resistances.some(r=>r.type===damageType):super.isAffectedBy(effect)}prepareBaseData(){super.prepareBaseData();const{attributes,details}=this.system;if(attributes.hp.negativeHealing=!1,attributes.hp.brokenThreshold=Math.floor(attributes.hp.max/2),attributes.hasHealth=attributes.hp.max>0,attributes.immunities.some(i=>i.type==="object-immunities")||attributes.immunities.unshift(new Immunity({type:"object-immunities",source:"TYPES.Actor.hazard"})),this.isComplex){attributes.stealth.value??=0;const partialAttributes=this.system.attributes;partialAttributes.initiative={statistic:"stealth",tiebreakPriority:this.hasPlayerOwner?2:1}}details.alliance=null}prepareDerivedData(){super.prepareDerivedData();const{system}=this;if(this.prepareSynthetics(),setHitPointsRollOptions(this),this.skills={stealth:new Statistic(this,{slug:"stealth",label:CONFIG.PF2E.skillList.stealth,domains:["stealth","dex-based","skill-check","dex-skill-check","all"],modifiers:[new ModifierPF2e({label:"PF2E.ModifierTitle",slug:"base",type:"untyped",modifier:system.attributes.stealth.value??0})],check:{type:"skill-check"}})},system.attributes.initiative&&(this.initiative=new ActorInitiative(this),system.attributes.initiative=this.initiative.getTraceData()),this.hasDefenses){const baseModifier=new ModifierPF2e({slug:"base",label:"PF2E.BaseModifier",modifier:system.attributes.ac.value-10}),statistic=new ArmorStatistic(this,{rank:1,modifiers:[baseModifier]});this.armorClass=statistic.dc,system.attributes.ac=statistic.getTraceData()}this.saves=this.prepareSaves(),this.system.actions=this.itemTypes.melee.map(m=>strikeFromMeleeItem(m))}prepareData(){super.prepareData();const weaknessesAndResistances=new Set([this.system.attributes.weaknesses.map(w=>w.type),this.system.attributes.resistances.map(r=>r.type)].flat()),objectImmunities=this.system.attributes.immunities.find(i=>i.type==="object-immunities");for(const wrType of["bleed","mental","poison","spirit"])weaknessesAndResistances.has(wrType)&&objectImmunities?.exceptions.push(wrType)}prepareSaves(){const{system}=this;return SAVE_TYPES.reduce((saves,saveType)=>{const save=system.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),base=save.value,ability=CONFIG.PF2E.savingThrowDefaultAttributes[saveType];if(!base)return saves;const selectors=[saveType,`${ability}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:saveName,domains:selectors,modifiers:[new ModifierPF2e("PF2E.BaseModifier",base,"untyped"),...extractModifiers(this.synthetics,selectors)],check:{type:"saving-throw"}});return mergeObject(this.system.saves[saveType],stat.getTraceData()),saves[saveType]=stat,saves},{})}};__name2(_HazardPF2e,"HazardPF2e");let HazardPF2e=_HazardPF2e;const _LootPF2e=class extends ActorPF2e{static{__name(this,"_LootPF2e")}armorClass=null;get allowedItemTypes(){return["physical"]}get isLoot(){return this.system.lootSheetType==="Loot"}get isMerchant(){return this.system.lootSheetType==="Merchant"}get hiddenWhenEmpty(){return this.isLoot&&this.system.hiddenWhenEmpty}get canHostRuleElements(){return!1}get canAct(){return!1}isAffectedBy(){return!1}get visible(){return this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}canUserModify(user,action2){return action2==="update"?this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED:super.canUserModify(user,action2)}async transferItemToActor(targetActor,item,quantity,containerId,newStack=!1){if(!(this.isOwner&&targetActor.isOwner))return super.transferItemToActor(targetActor,item,quantity,containerId,newStack);if(this.isMerchant&&item.isOfType("physical")){const itemValue=CoinsPF2e.fromPrice(item.price,quantity);if(await targetActor.inventory.removeCoins(itemValue))return await item.actor.inventory.addCoins(itemValue),super.transferItemToActor(targetActor,item,quantity,containerId,newStack);if(this.isLoot)throw ErrorPF2e("Loot transfer failed");return null}return super.transferItemToActor(targetActor,item,quantity,containerId,newStack)}async toggleTokenHiding(){if(!this.hiddenWhenEmpty||!this.isOwner)return;const hiddenStatus=this.items.size===0,promises=game.scenes.map(s=>[s,s.tokens.filter(t=>t.actor===this)]).map(([scene,tokenDocs])=>scene.updateEmbeddedDocuments("Token",tokenDocs.map(tokenDoc=>({_id:tokenDoc.id,hidden:hiddenStatus}))));await Promise.allSettled(promises)}prepareDerivedData(){this.rules=[],super.prepareDerivedData()}_onCreate(data,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onCreate(data,options,userId)}_onUpdate(changed,options,userId){game.user.id===userId&&changed.system?.hiddenWhenEmpty!==void 0&&this.toggleTokenHiding(),super._onUpdate(changed,options,userId)}_onCreateDescendantDocuments(parent,collection,documents,result,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onCreateDescendantDocuments(parent,collection,documents,result,options,userId)}_onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId)}};__name2(_LootPF2e,"LootPF2e");let LootPF2e=_LootPF2e;const{DataModel:DataModel$1}=foundry.abstract,_InvalidCampaign=class extends DataModel$1{static{__name(this,"_InvalidCampaign")}type="invalid";actor;options;constructor(actor,options){super(),this.actor=actor,this.options=options}static defineSchema(){return{}}createSidebarButtons(){const icon=createHTMLElement("a",{children:[fontAwesomeIcon("warning",{fixedWidth:!0})]});return icon.title=game.i18n.localize("PF2E.Actor.Party.InvalidCampaign.Hint"),game.user.isGM?icon.addEventListener("click",()=>{new Dialog({title:game.i18n.format("PF2E.Actor.Party.InvalidCampaign.Title",{party:this.actor.name}),content:game.i18n.format(`PF2E.Actor.Party.InvalidCampaign.Message.${this.options.reason}`,{current:this.actor.system.campaign?.type??"",...this.options}),buttons:{yes:{icon:fontAwesomeIcon("trash").outerHTML,label:game.i18n.localize("Yes"),callback:async()=>{await this.actor.update({"system.-=campaign":null}),ui.sidebar.render()}},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}}}).render(!0)}):icon.style.pointerEvents="none",[icon]}};__name2(_InvalidCampaign,"InvalidCampaign");let InvalidCampaign=_InvalidCampaign;function resolveKingdomBoosts(entry,choices){const notFreeBoosts=entry.boosts.filter(b=>b!=="free");return uniq([notFreeBoosts,choices].flat()).filter(b=>b!==entry.flaw).slice(0,entry.boosts.length)}__name(resolveKingdomBoosts,"resolveKingdomBoosts"),__name2(resolveKingdomBoosts,"resolveKingdomBoosts");function calculateKingdomCollectionData(kingdom){const commodityTypes=["luxuries","lumber","ore","stone"];return{formula:`${kingdom.resources.dice.number}d${kingdom.resources.dice.faces}`,commodities:mapToObj(commodityTypes,type=>{const value=kingdom.resources.workSites[type];return[type,value.value+value.resource*2]})}}__name(calculateKingdomCollectionData,"calculateKingdomCollectionData"),__name2(calculateKingdomCollectionData,"calculateKingdomCollectionData");const KINGDOM_ABILITIES=["culture","economy","loyalty","stability"],KINGDOM_LEADERSHIP=["ruler","counselor","general","emissary","magister","treasurer","viceroy","warden"],KINGDOM_COMMODITIES=["food","luxuries","lumber","ore","stone"],KINGDOM_SKILLS=["agriculture","arts","boating","defense","engineering","exploration","folklore","industry","intrigue","magic","politics","scholarship","statecraft","trade","warfare","wilderness"],KINGDOM_LEADERSHIP_ABILITIES={ruler:"loyalty",counselor:"culture",general:"stability",emissary:"loyalty",magister:"culture",treasurer:"economy",viceroy:"economy",warden:"stability"},KINGDOM_SKILL_ABILITIES={agriculture:"stability",arts:"culture",boating:"economy",defense:"stability",engineering:"stability",exploration:"economy",folklore:"culture",industry:"economy",intrigue:"loyalty",magic:"culture",politics:"loyalty",scholarship:"culture",statecraft:"loyalty",trade:"economy",warfare:"loyalty",wilderness:"stability"},KINGDOM_ABILITY_LABELS=mapToObj(KINGDOM_ABILITIES,a=>[a,`PF2E.Kingmaker.Abilities.${a}`]),KINGDOM_COMMODITY_LABELS=mapToObj(KINGDOM_COMMODITIES,c=>[c,`PF2E.Kingmaker.Kingdom.Commodity.${c}`]),KINGDOM_RUIN_LABELS={culture:"PF2E.Kingmaker.Kingdom.Ruin.corruption",economy:"PF2E.Kingmaker.Kingdom.Ruin.crime",stability:"PF2E.Kingmaker.Kingdom.Ruin.decay",loyalty:"PF2E.Kingmaker.Kingdom.Ruin.strife"},KINGDOM_SKILL_LABELS=mapToObj(KINGDOM_SKILLS,a=>[a,`PF2E.Kingmaker.Skills.${a}`]),CONTROL_DC_BY_LEVEL=[14,15,16,18,20,22,23,24,26,27,28,30,31,32,34,35,36,38,39,40],KINGDOM_SIZE_DATA={1:{faces:4,type:"territory",controlMod:0,storage:4},10:{faces:6,type:"province",controlMod:1,storage:8},25:{faces:8,type:"state",controlMod:2,storage:12},50:{faces:10,type:"country",controlMod:3,storage:16},100:{faces:12,type:"dominion",controlMod:4,storage:20}},KINGDOM_SETTLEMENT_TYPES=["village","town","city","metropolis"],KINGDOM_SETTLEMENT_TYPE_LABELS=mapToObj(KINGDOM_SETTLEMENT_TYPES,size=>[size,`PF2E.Kingmaker.Settlement.Type.${size}`]),KINGDOM_SETTLEMENT_TYPE_DATA={village:{blocks:1,population:[0,400],level:[1,1],consumption:1,maxItemBonus:1,influence:0},town:{blocks:4,population:[401,2e3],level:[2,4],consumption:2,maxItemBonus:1,influence:1},city:{blocks:9,population:[2001,25e3],level:[5,9],consumption:4,maxItemBonus:2,influence:2},metropolis:{blocks:1/0,population:[25001,1/0],level:[10,1/0],consumption:6,maxItemBonus:3,influence:3}},vacancyLabel=__name2(role=>game.i18n.format("PF2E.Kingmaker.Kingdom.VacantRole",{role:game.i18n.localize(`PF2E.Kingmaker.Kingdom.LeadershipRole.${role}`)}),"vacancyLabel"),VACANCY_PENALTIES={ruler:()=>({modifiers:{"kingdom-check":[{slug:"vacancy-ruler",label:vacancyLabel("ruler"),modifier:-1}],"control-dc":[{slug:"vacancy-ruler",label:vacancyLabel("ruler"),modifier:2}]}}),counselor:()=>({modifiers:{"culture-based":[{slug:"vacancy",label:vacancyLabel("counselor"),modifier:-1}]}}),general:()=>({modifiers:{warfare:[{slug:"vacancy",label:vacancyLabel("general"),modifier:0}]},adjustments:{warfare:[{slug:"vacancy",test:()=>!0,relabel:vacancyLabel("general"),getNewValue:()=>-4}]}}),emissary:()=>({modifiers:{"loyalty-based":[{slug:"vacancy",label:vacancyLabel("emissary"),modifier:-1}]}}),magister:()=>({modifiers:{warfare:[{slug:"vacancy",label:vacancyLabel("magister"),modifier:0}]},adjustments:{warfare:[{slug:"vacancy",test:()=>!0,relabel:vacancyLabel("magister"),getNewValue:()=>-4}]}}),treasurer:()=>({modifiers:{"economy-based":[{slug:"vacancy",label:vacancyLabel("treasurer"),modifier:-1}]}}),viceroy:()=>({modifiers:{"stability-based":[{slug:"vacancy",label:vacancyLabel("viceroy"),modifier:-1}]}}),warden:()=>({modifiers:{"kingdom-check":[{slug:"vacancy",label:vacancyLabel("warden"),modifier:0}]},adjustments:{"kingdom-check":[{slug:"vacancy",test:options=>[...options].includes("region"),relabel:vacancyLabel("warden"),getNewValue:()=>-4}]}})};function getKingdomCHGData(){const localize=localizer("PF2E.Kingmaker");return{charter:{conquest:{name:localize("Charter.conquest.Name"),description:localize("Charter.conquest.Description"),img:"/icons/weapons/swords/sword-guard-steel-green.webp",boosts:["loyalty","free"],flaw:"culture"},expansion:{name:localize("Charter.expansion.Name"),description:localize("Charter.expansion.Description"),img:"/icons/skills/trades/woodcutting-logging-axe-stump.webp",boosts:["culture","free"],flaw:"stability"},exploration:{name:localize("Charter.exploration.Name"),description:localize("Charter.exploration.Description"),img:"/icons/tools/navigation/map-chart-tan.webp",boosts:["stability","free"],flaw:"economy"},grant:{name:localize("Charter.grant.Name"),description:localize("Charter.grant.Description"),img:"/icons/skills/trades/academics-merchant-scribe.webp",boosts:["economy","free"],flaw:"loyalty"},open:{name:localize("Charter.open.Name"),description:localize("Charter.open.Description"),img:"/icons/sundries/documents/document-sealed-brown-red.webp",boosts:["free"],flaw:null}},heartland:{forestOrSwamp:{name:localize("Heartland.forestOrSwamp.Name"),description:localize("Heartland.forestOrSwamp.Description"),img:"/icons/environment/wilderness/tree-oak.webp",boosts:["culture"]},hillOrPlain:{name:localize("Heartland.hillOrPlain.Name"),description:localize("Heartland.hillOrPlain.Description"),img:"/icons/environment/creatures/horses.webp",boosts:["loyalty"]},lakeOrRiver:{name:localize("Heartland.lakeOrRiver.Name"),description:localize("Heartland.lakeOrRiver.Description"),img:"/icons/environment/settlement/bridge-stone.webp",boosts:["economy"]},mountainOrRuins:{name:localize("Heartland.mountainOrRuins.Name"),description:localize("Heartland.mountainOrRuins.Description"),img:"/icons/environment/wilderness/cave-entrance-mountain.webp",boosts:["stability"]}},government:{despotism:{name:localize("Government.despotism.Name"),description:localize("Government.despotism.Description"),img:"/icons/environment/settlement/pyramid.webp",boosts:["stability","economy","free"],skills:["intrigue","warfare"],feat:"Compendium.pf2e.kingmaker-features.Item.WGpkcIChjIk1i0q0"},feudalism:{name:localize("Government.feudalism.Name"),description:localize("Government.feudalism.Description"),img:"/icons/environment/settlement/watchtower-cliff.webp",boosts:["stability","culture","free"],skills:["defense","trade"],feat:"Compendium.pf2e.kingmaker-features.Item.JYY8vQxPe9AIGTvv"},oligarchy:{name:localize("Government.oligarchy.Name"),description:localize("Government.oligarchy.Description"),img:"/icons/environment/settlement/house-manor.webp",boosts:["loyalty","economy","free"],skills:["arts","industry"],feat:"Compendium.pf2e.kingmaker-features.Item.9dkyZ7r1z7loOxI7"},republic:{name:localize("Government.republic.Name"),description:localize("Government.republic.Description"),img:"/icons/environment/settlement/gazebo.webp",boosts:["stability","economy","free"],skills:["engineering","politics"],feat:"Compendium.pf2e.kingmaker-features.Item.BChcBEZpcqMnLISC"},thaumocracy:{name:localize("Government.thaumocracy.Name"),description:localize("Government.thaumocracy.Description"),img:"/icons/environment/settlement/wizard-castle.webp",boosts:["economy","culture","free"],skills:["folklore","magic"],feat:"Compendium.pf2e.kingmaker-features.Item.nDDEbrWj2JouxlRw"},yeomanry:{name:localize("Government.yeomanry.Name"),description:localize("Government.yeomanry.Description"),img:"/icons/environment/settlement/house-farmland-small.webp",boosts:["loyalty","culture","free"],skills:["agriculture","wilderness"],feat:"Compendium.pf2e.kingmaker-features.Item.WFng3pxgEAdpdy1p"}}}}__name(getKingdomCHGData,"getKingdomCHGData"),__name2(getKingdomCHGData,"getKingdomCHGData");const KINGDOM_TRAITS=["commerce","leadership","region","civic","army"],_KingdomSheetPF2e=class extends ActorSheetPF2e{static{__name(this,"_KingdomSheetPF2e")}constructor(actor,options){super(actor,options),__privateAdd(this,_prepareSettlement),__privateAdd(this,_activateSettlementEvents),__privateAdd(this,_getFeatSlotData2),__publicField(this,"selectedFilter",null),__publicField(this,"focusElement",null),__privateAdd(this,_editingSettlements,{})}get kingdom(){const campaign=this.actor.campaign;if(!(campaign instanceof Kingdom))throw this.close(),ErrorPF2e("Only actors with kingdom data is supported");return campaign}get title(){return this.kingdom.name}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"kingdom"],width:720,height:620,template:"systems/pf2e/templates/actors/party/kingdom/sheet.hbs",scrollY:[...options.scrollY,".tab.active",".tab.active .content",".sidebar"],tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fas fa-eye",onclick:()=>{const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:this.actor.uuid,options:{campaign:!0,tab:this._tabs[0].active}})}}),buttons}async getData(options){const data=await super.getData(options),kingdom=this.kingdom,settlementEntries=pipe(Object.entries(this.kingdom.settlements),filter(entry=>!!entry[1]),sortBy$1(entry=>entry[1].sort));return{...data,actor:this.actor,kingdom:this.kingdom,nationTypeLabel:game.i18n.localize(`PF2E.Kingmaker.Kingdom.NationType.${kingdom.nationType}`),abilities:KINGDOM_ABILITIES.map(slug=>({...this.kingdom.abilities[slug],slug,label:game.i18n.localize(KINGDOM_ABILITY_LABELS[slug]),ruinLabel:game.i18n.localize(KINGDOM_RUIN_LABELS[slug])})),commodities:KINGDOM_COMMODITIES.map(type=>({...kingdom.resources.commodities[type],type,label:game.i18n.localize(KINGDOM_COMMODITY_LABELS[type]),workSites:{label:game.i18n.localize(`PF2E.Kingmaker.WorkSites.${type}.Name`),description:game.i18n.localize(`PF2E.Kingmaker.WorkSites.${type}.Description`),hasResource:["lumber","ore","stone"].includes(type),value:kingdom.resources.workSites[type].value,resource:kingdom.resources.workSites[type].resource}})),resourceDice:{...kingdom.resources.dice,icon:fontAwesomeIcon(`dice-d${kingdom.resources.dice.faces}`).outerHTML,bonusAdjustment:getAdjustment(kingdom.resources.dice.bonus,kingdom._source.resources.dice.bonus).adjustmentClass,penaltyAdjustment:getAdjustment(kingdom.resources.dice.penalty,kingdom._source.resources.dice.penalty).adjustmentClass},leadership:KINGDOM_LEADERSHIP.map(slug=>{const data2=this.kingdom.leadership[slug],document2=fromUuidSync(data2.uuid??""),actor=document2 instanceof ActorPF2e?document2:null;return{...data2,slug,label:game.i18n.localize(`PF2E.Kingmaker.Kingdom.LeadershipRole.${slug}`),actor,img:actor?.prototypeToken.texture.src??actor?.img??ActorPF2e.DEFAULT_ICON,abilityLabel:game.i18n.localize(KINGDOM_ABILITY_LABELS[KINGDOM_LEADERSHIP_ABILITIES[slug]]),penaltyLabel:game.i18n.localize(`PF2E.Kingmaker.Kingdom.VacancyPenalty.${slug}`)}}),actions:sortBy$1(kingdom.activities,a=>a.name).map(item=>({item,traits:createSheetTags(CONFIG.PF2E.kingmakerTraits,item.system.traits.value.filter(t=>t!=="downtime"))})),skills:sortBy$1(Object.values(this.kingdom.skills),s=>s.label),feats:[kingdom.features,kingdom.feats,kingdom.bonusFeats],actionFilterChoices:KINGDOM_TRAITS.map(trait=>({label:game.i18n.localize(CONFIG.PF2E.kingmakerTraits[trait]),value:trait,selected:!1})),settlements:await Promise.all(settlementEntries.map(async([id,data2])=>__privateMethod(this,_prepareSettlement,prepareSettlement_fn).call(this,id,data2))),eventText:await TextEditor.enrichHTML(kingdom.event.text,{async:!0,rollData:this.actor.getRollData()}),settlementTypes:KINGDOM_SETTLEMENT_TYPE_LABELS,abilityLabels:KINGDOM_ABILITY_LABELS,skillLabels:KINGDOM_SKILL_LABELS}}activateListeners($html){super.activateListeners($html);const html=$html[0];this.focusElement&&(htmlQuery(html,this.focusElement)?.focus(),this.focusElement=null);for(const openSheetLink of htmlQueryAll(html,"[data-action=open-sheet]")){const actorUUID=htmlClosest(openSheetLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");openSheetLink.addEventListener("click",()=>actor?.sheet.render(!0))}for(const button of htmlQueryAll(html,"[data-action=builder]")){const tab=button.dataset.tab??null;button.addEventListener("click",()=>{new KingdomBuilder(this.kingdom).render(!0,{tab})})}const{fame}=this.kingdom.resources,famePips=htmlQuery(html,"[data-action=adjust-fame]");famePips?.addEventListener("click",async()=>{const newValue=Math.min(fame.value+1,fame.max);await this.kingdom.update({"resources.fame.value":newValue})}),famePips?.addEventListener("contextmenu",async event=>{event.preventDefault();const newValue=Math.max(fame.value-1,0);await this.kingdom.update({"resources.fame.value":newValue})});for(const leader of htmlQueryAll(html,".leader[data-role]")){const{role,uuid}=leader.dataset;if(htmlQuery(leader,"[data-action=remove-leader]")?.addEventListener("click",()=>{this.kingdom.update({[`leadership.${role}`]:null})}),uuid)for(const clickable of htmlQueryAll(leader,"[data-action=open-sheet]"))clickable.addEventListener("click",()=>fromUuid(uuid).then(a=>a?.sheet.render(!0)));const vacantEl=htmlQuery(leader,".vacant[title]");if(vacantEl){const lines=vacantEl.title.split(/;\s*/).map(l=>createHTMLElement("li",{children:[l]})),content=createHTMLElement("ul",{children:lines});$(vacantEl).tooltipster({content,contentAsHTML:!0,side:"right",theme:"crb-hover"})}}for(const rollableStat of htmlQueryAll(html,".rollable")){const statSlug=htmlClosest(rollableStat,"[data-statistic]")?.dataset.statistic;statSlug&&rollableStat.addEventListener("click",event=>{this.actor.getStatistic(statSlug)?.roll(eventToRollParams(event,{type:"check"}))})}htmlQuery(html,"[data-action=collect]")?.addEventListener("click",async()=>{ChatMessagePF2e.create({speaker:{...ChatMessagePF2e.getSpeaker(this.actor),alias:this.kingdom.name},content:await renderTemplate("systems/pf2e/templates/actors/party/kingdom/collection.hbs",{...calculateKingdomCollectionData(this.kingdom)})})}),this.filterActions(this.selectedFilter,{instant:!0}),htmlQuery(html,".filters")?.addEventListener("click",event=>{const filterButton=htmlClosest(event.target,".choice");filterButton&&this.filterActions(filterButton.dataset.slug??null)}),$html.find("[data-tooltip-content]").tooltipster({trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["right","bottom"],theme:"crb-hover",minWidth:120});for(const customModifierEl of htmlQueryAll(html,".modifiers-tooltip")){const stat=customModifierEl.dataset.stat;if(!stat)continue;for(const removeButton of htmlQueryAll(customModifierEl,"[data-action=remove-modifier]")){const slug=removeButton.dataset.slug??"";removeButton.addEventListener("click",()=>{this.kingdom.removeCustomModifier(stat,slug)})}const modifierValueEl=htmlQuery(customModifierEl,".add-modifier input[type=number]");htmlQuery(customModifierEl,"[data-action=increment]")?.addEventListener("click",()=>{modifierValueEl?.stepUp()}),htmlQuery(customModifierEl,"[data-action=decrement]")?.addEventListener("click",()=>{modifierValueEl?.stepDown()}),htmlQuery(customModifierEl,"[data-action=create-custom-modifier]")?.addEventListener("click",()=>{const modifier=modifierValueEl?.valueAsNumber||1,type=htmlQuery(customModifierEl,".add-modifier-type")?.value??"",label=htmlQuery(customModifierEl,".add-modifier-name")?.value?.trim()??game.i18n.localize(`PF2E.ModifierType.${type}`);if(!setHasElement(MODIFIER_TYPES,type)){ui.notifications.error("Type is required.");return}this.kingdom.addCustomModifier(stat,{label,modifier,type})})}htmlQuery(html,"[data-action=add-settlement]")?.addEventListener("click",()=>{const id=randomID(16);__privateGet(this,_editingSettlements)[id]=!0,this.focusElement=`[name="settlements.${id}.name"]`,this.kingdom.update({[`settlements.${id}`]:{}})});for(const settlementElement of htmlQueryAll(html,".settlement"))__privateMethod(this,_activateSettlementEvents,activateSettlementEvents_fn).call(this,settlementElement);for(const link of htmlQueryAll(html,"[data-action=browse-feats]")){const maxLevel=Number(link.dataset.level)||this.kingdom.level;link.addEventListener("click",async()=>{const compendiumTab=game.pf2e.compendiumBrowser.tabs.campaignFeature,filter2=await compendiumTab.getFilterData(),levels=filter2.sliders.level;levels.values.max=Math.min(maxLevel,levels.values.upperLimit),levels.isExpanded=levels.values.max!==levels.values.upperLimit,filter2.checkboxes.category.options["kingdom-feat"].selected=!0,filter2.checkboxes.category.selected.push("kingdom-feat"),filter2.checkboxes.category.isExpanded=!0,compendiumTab.open(filter2)})}htmlQuery(html,"[data-action=random-event]")?.addEventListener("click",()=>{new Statistic(this.actor,{slug:"random-event",label:"Random Kingdom Event",check:{type:"flat-check"}}).roll({dc:this.kingdom.event.dc})}),htmlQuery(html,"[data-action=reset-event-dc]")?.addEventListener("click",()=>{this.kingdom.update({event:{dc:16}})});const settlementList=htmlQuery(html,".settlement-list");settlementList&&Sortable.create(settlementList,{...SORTABLE_DEFAULTS,handle:".drag-handle",onEnd:event=>{const settlements=this.kingdom.settlements,settlementsWithIds=Object.entries(settlements).map(([id,value])=>({id,...value})),settlement=settlementsWithIds.find(s=>s.id===event.item.dataset.settlementId),newIndex=event.newDraggableIndex;if(!settlement||newIndex===void 0){this.render();return}const siblings=sortBy$1(settlementsWithIds.filter(s=>s!==settlement),s=>s.sort);siblings.splice(newIndex,0,settlement);const updates=mapToObj.indexed(siblings,(s,index)=>[`settlements.${s.id}.sort`,index]);this.kingdom.update(updates)}})}filterActions(trait,options={}){const html=this.element.get(0),duration=.4;this.selectedFilter=trait;const animateElement=__name2((element,visible)=>{options.instant?element.hidden=!visible:visible&&element.hidden?gsap.fromTo(element,{height:0,opacity:0,hidden:!1},{height:"auto",opacity:1,duration}):!visible&&!element.hidden&&gsap.to(element,{height:0,duration,opacity:0,paddingTop:0,paddingBottom:0,margin:0,clearProps:"all",onComplete:()=>{element.hidden=!0,this.itemRenderer.toggleSummary(element,{visible:!1,instant:!0})}})},"animateElement");for(const action2 of this.kingdom.activities){const element=htmlQuery(html,`[data-item-id="${action2.id}"]`),visible=!trait||tupleHasValue(action2.system.traits.value,trait);element&&animateElement(element,visible)}for(const summary of htmlQueryAll(html,".phase-summary"))animateElement(summary,summary.dataset.phase===trait);for(const choice of htmlQueryAll(html,".filters .choice")){const active=choice.dataset.slug?choice.dataset.slug===trait:trait===null;choice.classList.toggle("active",active)}const actionsList=htmlQuery(html,".actions-list");actionsList&&(actionsList.scrollTop=0)}async _onDropItem(event,data){const item=await ItemPF2e.fromDropData(data);if(!item)throw ErrorPF2e("Unable to create item from drop data!");if(this.actor.uuid===item.parent?.uuid)return super._onDropItem(event,data);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const slotData=__privateMethod(this,_getFeatSlotData2,getFeatSlotData_fn2).call(this,event)??{groupId:"bonus",slotId:null};return(slotData.groupId==="bonus"?this.kingdom.bonusFeats:this.kingdom.feats).insertFeat(item,slotData.slotId)}return super._onDropItem(event,data)}async _onSortItem(event,itemSource){const item=this.actor.items.get(itemSource._id);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const featSlot=__privateMethod(this,_getFeatSlotData2,getFeatSlotData_fn2).call(this,event);if(!featSlot)return[];const group=featSlot.groupId==="bonus"?this.kingdom.bonusFeats:this.kingdom.feats,resorting=item.group===group&&!group?.slotted;if(group?.slotted&&!featSlot.slotId)return[];if(!resorting)return group.insertFeat(item,featSlot.slotId)}return super._onSortItem(event,itemSource)}async _onDropActor(event,data){await super._onDropActor(event,data);const actor=fromUuidSync(data.uuid),closestLeader=htmlClosest(event.target,".leader[data-role]");if(actor instanceof CreaturePF2e&&closestLeader){const role=String(closestLeader.dataset.role),uuid=actor.uuid;this.kingdom.update({leadership:{[role]:{uuid}}})}}_disableFields(form){for(const gmOnlyField of htmlQueryAll(form,"input, textarea, [data-access=owner]"))gmOnlyField instanceof HTMLTextAreaElement?gmOnlyField.readOnly=!0:(gmOnlyField instanceof HTMLInputElement||gmOnlyField instanceof HTMLButtonElement)&&(gmOnlyField.disabled=!0)}async _updateObject(_event,formData){if(!this.actor.id)return;const data=expandObject(formData);for(const abilitySlug of KINGDOM_ABILITIES){const ability=data.abilities?.[abilitySlug];ability?.penalty&&(ability.penalty=-Math.abs(ability.penalty))}return this.kingdom.update(data)}};_editingSettlements=new WeakMap,_prepareSettlement=new WeakSet,prepareSettlement_fn=__name2(async function(id,settlement){const data=KINGDOM_SETTLEMENT_TYPE_DATA[settlement.type],levelRange=data.level[1]===1/0?`${data.level[0]}+`:data.level[0]===data.level[1]?String(data.level[0]):data.level.join("-"),populationRange=data.population[1]===1/0?`${data.population[0]}+`:data.population.join("-");return{...settlement,id,description:await TextEditor.enrichHTML(settlement.description,{async:!0,rollData:this.actor.getRollData()}),editing:__privateGet(this,_editingSettlements)[id]??!1,blocks:data.blocks===1/0?"10+":data.blocks,populationRange,levelRange,typeLabel:KINGDOM_SETTLEMENT_TYPE_LABELS[settlement.type],storage:KINGDOM_COMMODITIES.map(type=>({type,value:settlement.storage[type],label:game.i18n.localize(KINGDOM_COMMODITY_LABELS[type])}))}},"#prepareSettlement"),_activateSettlementEvents=new WeakSet,activateSettlementEvents_fn=__name2(function(settlementElement){const id=settlementElement.dataset.settlementId??null;if(id===null)return;const rerenderSettlement=__name2(async()=>{const settlement=this.kingdom.settlements[id];if(!settlement)return;const newHTML=await renderTemplate("systems/pf2e/templates/actors/party/kingdom/partials/settlement.hbs",{...await this.getData(),settlement:await __privateMethod(this,_prepareSettlement,prepareSettlement_fn).call(this,id,settlement)}),newElement=createHTMLElement("div",{innerHTML:newHTML}).firstElementChild;newElement instanceof HTMLElement&&(newElement.classList.toggle("expanded",settlementElement.classList.contains("expanded")),settlementElement.replaceWith(newElement),__superGet(_KingdomSheetPF2e.prototype,this,"activateListeners").call(this,$(newElement)),__privateMethod(this,_activateSettlementEvents,activateSettlementEvents_fn).call(this,newElement),__privateGet(this,_editingSettlements)[id]&&!newElement.classList.contains("expanded")&&this.itemRenderer.toggleSummary(newElement,{visible:!0}))},"rerenderSettlement");htmlQuery(settlementElement,"[data-action=edit-settlement]")?.addEventListener("click",()=>{__privateGet(this,_editingSettlements)[id]=!0,rerenderSettlement()}),htmlQuery(settlementElement,"[data-action=finish-settlement]")?.addEventListener("click",async()=>{__privateGet(this,_editingSettlements)[id]=!1,await this.saveEditor(`settlements.${id}.description`),rerenderSettlement()}),htmlQuery(settlementElement,"[data-action=delete-settlement]")?.addEventListener("click",async event=>{const settlement=this.kingdom.settlements[id];if(!settlement)return;(event?.ctrlKey||await Dialog.confirm({title:game.i18n.localize("PF2E.DeleteItemTitle"),content:`${game.i18n.format("PF2E.DeleteQuestion",{name:`"${settlement.name}"`})}
`}))&&this.kingdom.update({[`settlements.-=${id}`]:null})})},"#activateSettlementEvents"),_getFeatSlotData2=new WeakSet,getFeatSlotData_fn2=__name2(function(event){const groupId=event.target?.closest("[data-category-id]")?.dataset.categoryId,slotId=event.target?.closest("[data-slot-id]")?.dataset.slotId;return typeof groupId=="string"?{slotId,groupId}:null},"#getFeatSlotData"),__name2(_KingdomSheetPF2e,"KingdomSheetPF2e");let KingdomSheetPF2e=_KingdomSheetPF2e;const KINGDOM_BUILD_CATEGORIES=["charter","heartland","government"],KINGDOM_BOOST_LEVELS=[1,5,10,15,20],_KingdomBuilder=class _KingdomBuilder2 extends FormApplication{static{__name(this,"_KingdomBuilder")}constructor(kingdom){super(kingdom),__privateAdd(this,_prepareAbilityBuilder),__publicField(this,"selected",{charter:null,heartland:null,government:null}),kingdom.actor.apps[this.appId]=this}static get defaultOptions(){return{...super.defaultOptions,classes:["sheet","kingdom-builder"],title:game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.Title"),template:"systems/pf2e/templates/actors/party/kingdom/builder.hbs",width:560,height:"auto",submitOnChange:!0,closeOnSubmit:!1,tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}static showToPlayers(options){const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:options.uuid,options:{campaign:"builder",tab:options.tab}})}get id(){return`kingdom-builder-${this.actor.id}`}get kingdom(){return this.object}get actor(){return this.object.actor}get isEditable(){return this.actor.isOwner}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&(buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fa-solid fa-eye",onclick:()=>{_KingdomBuilder2.showToPlayers({uuid:this.actor.uuid,tab:this._tabs[0].active})}}),this.kingdom.active==="building"&&buttons.unshift({label:"PF2E.Kingmaker.KingdomBuilder.CancelCreation",class:"cancel",icon:"fa-solid fa-times",onclick:async()=>{await this.kingdom.update({active:!1})}})),buttons}async getData(){const database=getKingdomCHGData(),getActiveForCategory=__name2(category=>{const active=this.kingdom.build[category];return active?active?.id??Object.entries(database[category]).find(([_,entry])=>entry?.name===active.name)?.[0]??null:null},"getActiveForCategory");for(const category of KINGDOM_BUILD_CATEGORIES)this.selected[category]??=getActiveForCategory(category);const categories=await pipe(KINGDOM_BUILD_CATEGORIES,map(async category=>{const selected=this.selected[category],entries=database[category],buildEntry=entries[selected??""]??Object.values(entries)[0],featItem=await(async()=>{try{return buildEntry?.feat?await fromUuid(buildEntry.feat):null}catch(ex){return console.error(ex),null}})(),result={selected,active:getActiveForCategory(category),buildEntry,featLink:featItem?await TextEditor.enrichHTML(featItem.link,{async:!0}):null,stale:!equals(buildEntry,this.kingdom.build[category])};return[category,result]}),items=>Promise.all(items).then(result=>fromPairs(result))),{build}=this.kingdom,finished=!!(build.charter&&build.heartland&&build.government);return{options:{editable:this.isEditable},kingdom:this.kingdom,database,categories,abilityLabels:KINGDOM_ABILITY_LABELS,skillLabels:KINGDOM_SKILL_LABELS,build:__privateMethod(this,_prepareAbilityBuilder,prepareAbilityBuilder_fn).call(this),finished}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const categoryEl of htmlQueryAll(html,"[data-category]")){const category=categoryEl.dataset.category??null;if(!tupleHasValue(KINGDOM_BUILD_CATEGORIES,category))continue;for(const choiceElement of htmlQueryAll(categoryEl,".choice"))choiceElement.addEventListener("click",evt=>{const slug=htmlClosest(evt.target,"[data-slug]")?.dataset.slug;category&&objectHasKey(this.selected,category)&&(this.selected[category]=slug??null,this.render())});const saveCategory=__name2(async()=>{const database=getKingdomCHGData(),id=this.selected[category]??"",selected=database[category][id];selected&&(this.selected[category]=null,await this.kingdom.update({[`build.${category}`]:{id,...selected},[`build.boosts.${category}`]:[]}))},"saveCategory");htmlQuery(categoryEl,"[data-action=set]")?.addEventListener("click",()=>{saveCategory()}),htmlQuery(categoryEl,"[data-action=save-and-continue]")?.addEventListener("click",async event=>{event.preventDefault(),event.stopPropagation(),await saveCategory();const activeTab=this._tabs[0].active,idx=KINGDOM_BUILD_CATEGORIES.indexOf(activeTab),newTab=KINGDOM_BUILD_CATEGORIES[idx+1]??"ability";this._tabs[0].activate(newTab,{triggerCallback:!0})})}for(const button of htmlQueryAll(html,".ability-builder [data-section] .boost")){const sectionId=htmlClosest(button,"[data-section]")?.dataset.section,ability=htmlClosest(button,"[data-ability]")?.dataset.ability;!tupleHasValue(KINGDOM_ABILITIES,ability)||!tupleHasValue(KINGDOM_BUILD_CATEGORIES,sectionId)||button.addEventListener("click",()=>{const object=this.kingdom[sectionId],current=this.kingdom.build.boosts[sectionId],maxBoosts=object?.boosts.length;if(!object)return;const boosts=(current.includes(ability)?current.filter(a=>a!==ability):[...current,ability]).filter(a=>!object.boosts.includes(a)&&object.flaw!==a).slice(0,maxBoosts);this.kingdom.update({[`build.boosts.${sectionId}`]:boosts})})}for(const button of htmlQueryAll(html,".ability-builder [data-level] .boost")){const level=Number(htmlClosest(button,"[data-level]")?.dataset.level),ability=htmlClosest(button,"[data-ability]")?.dataset.ability;!tupleHasValue(KINGDOM_ABILITIES,ability)||!tupleHasValue(KINGDOM_BOOST_LEVELS,level)||button.addEventListener("click",()=>{const current=this.kingdom.build.boosts[level],boosts=(current.includes(ability)?current.filter(a=>a!==ability):[...current,ability]).slice(0,2);this.kingdom.update({[`build.boosts.${level}`]:boosts})})}htmlQuery(html,"[data-action=complete]")?.addEventListener("click",async()=>{this.close(),await this.kingdom.update({active:!0}),await this.kingdom.importActivities(),new KingdomSheetPF2e(this.actor).render(!0)})}async _updateObject(_event,formData){if(this.actor.id)return this.object.update(formData)}async _render(force,options){if(this.kingdom.active===!1){this.close({force:!0});return}await super._render(force,options),options?.tab&&this._tabs.at(0)?.activate(options.tab,{triggerCallback:!0})}};_prepareAbilityBuilder=new WeakSet,prepareAbilityBuilder_fn=__name2(function(){function createButtons(){return Array.from(KINGDOM_ABILITIES).reduce((accumulated,ability)=>(accumulated[ability]={ability},accumulated),{})}__name(createButtons,"createButtons"),__name2(createButtons,"createButtons");const choices=this.kingdom.build.boosts,mainBoosts=mapToObj(KINGDOM_BUILD_CATEGORIES,prop=>{const buildItem=this.kingdom[prop];if(!buildItem)return[prop,null];const buttons=createButtons(),selectedChoices=objectHasKey(choices,prop)?choices[prop]:[],boosts=resolveKingdomBoosts(buildItem,selectedChoices),remaining=Math.max(0,buildItem.boosts.length-boosts.length);for(const ability of KINGDOM_ABILITIES){const selected=boosts.includes(ability);ability===buildItem.flaw?buttons[ability].flaw={selected:!0,locked:!0}:(selected||buildItem.boosts.includes("free"))&&(buttons[ability].boost={selected,locked:buildItem.boosts.includes(ability),disabled:!selected&&!remaining})}return[prop,{buttons,remaining}]}),levelBoosts=mapToObj(KINGDOM_BOOST_LEVELS,level=>{const eligible=this.kingdom.level>=level,buttons=createButtons(),boosts=this.kingdom.build.boosts[level],remaining=eligible?Math.max(0,2-boosts.length):0;for(const ability of KINGDOM_ABILITIES){const selected=boosts.includes(ability)&&eligible;buttons[ability].boost={selected,disabled:!selected&&!remaining}}return[level,{buttons,remaining,eligible}]});return{...mainBoosts,levelBoosts}},"#prepareAbilityBuilder"),__name2(_KingdomBuilder,"KingdomBuilder");let KingdomBuilder=_KingdomBuilder;const{fields}=foundry.data;function buildKingdomCHGSchema(){return{id:new fields.StringField({required:!1,initial:void 0,blank:!1}),name:new fields.StringField({required:!0,nullable:!1,blank:!1}),img:new fields.StringField({required:!0,nullable:!1}),description:new fields.StringField({required:!0,nullable:!1}),boosts:new fields.ArrayField(new fields.StringField({choices:[...KINGDOM_ABILITIES,"free"],nullable:!1}))}}__name(buildKingdomCHGSchema,"buildKingdomCHGSchema"),__name2(buildKingdomCHGSchema,"buildKingdomCHGSchema");const KINGDOM_BUILD_SCHEMA={manual:new fields.BooleanField({required:!0,nullable:!1,initial:!1}),charter:new fields.SchemaField({...buildKingdomCHGSchema(),flaw:new fields.StringField({choices:KINGDOM_ABILITIES,required:!0,nullable:!0})},{nullable:!0,initial:null}),heartland:new fields.SchemaField(buildKingdomCHGSchema(),{nullable:!0,initial:null}),government:new fields.SchemaField({...buildKingdomCHGSchema(),skills:new fields.ArrayField(new fields.StringField({required:!0,nullable:!1,choices:KINGDOM_SKILLS})),feat:new fields.StringField({required:!0,nullable:!0})},{nullable:!0,initial:null}),skills:new fields.SchemaField(mapToObj(KINGDOM_SKILLS,skill=>{const schema=new fields.SchemaField({rank:new fields.NumberField({initial:0,min:0,max:4,required:!0,nullable:!1})});return[skill,schema]})),boosts:new fields.SchemaField(mapToObj(["charter","heartland","government","1","5","10","15","20"],category=>{const schema=new fields.ArrayField(new fields.StringField({choices:KINGDOM_ABILITIES,nullable:!1}));return[category,schema]}))},KINGDOM_RESOURCES_SCHEMA={dice:new fields.SchemaField({number:new fields.NumberField,faces:new fields.NumberField,bonus:new fields.NumberField({required:!0,nullable:!1,initial:0}),penalty:new fields.NumberField({required:!0,nullable:!1,initial:0})}),fame:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:3})}),commodities:new fields.SchemaField(mapToObj(KINGDOM_COMMODITIES,type=>{const schema=new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:0})});return[type,schema]})),points:new fields.NumberField({min:0,required:!1,nullable:!1,initial:0}),workSites:new fields.SchemaField(mapToObj(["food","luxuries","lumber","ore","stone"],type=>{const schema=new fields.SchemaField({value:new fields.NumberField({required:!1,nullable:!1,min:0,initial:0}),resource:new fields.NumberField({required:!1,nullable:!1,min:0,initial:0})});return[type,schema]}))},KINGDOM_SETTLEMENT_SCHEMA={name:new fields.StringField({required:!0,blank:!0,nullable:!1,initial:""}),type:new fields.StringField({required:!1,nullable:!1,choices:KINGDOM_SETTLEMENT_TYPES,initial:"village"}),level:new fields.NumberField({min:1,initial:1,max:30,nullable:!1}),overcrowded:new fields.BooleanField,description:new fields.StringField({required:!1,nullable:!1,blank:!0,initial:""}),sort:new fields.IntegerSortField,consumption:new fields.SchemaField({base:new fields.NumberField({required:!1,nullable:!1,initial:0}),reduction:new fields.NumberField({required:!1,nullable:!1,initial:0}),total:new fields.NumberField({required:!1,nullable:!1,initial:0})}),storage:new fields.SchemaField(mapToObj(["food","luxuries","lumber","ore","stone"],type=>{const schema=new fields.NumberField({required:!1,nullable:!1,min:0,initial:0});return[type,schema]}))},KINGDOM_SCHEMA={type:new fields.StringField({choices:["kingmaker"],required:!0,nullable:!1,initial:"kingmaker"}),active:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["building"],initial:void 0}),new StrictBooleanField({initial:!1,required:!1,nullable:!1})],{required:!1,nullable:!1,initial:!1}),name:new fields.StringField({required:!0,nullable:!1,initial:""}),img:new fields.FilePathField({categories:["IMAGE"],required:!0,nullable:!1,initial:"systems/pf2e/icons/default-icons/kingdom.svg"}),capital:new fields.StringField({initial:"",required:!0}),size:new fields.NumberField({initial:1,min:1,required:!0,nullable:!1}),level:new fields.NumberField({required:!0,nullable:!1,min:1,max:20,initial:1}),xp:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:1e3})}),aspiration:new fields.StringField({choices:["fame","infamy"],required:!0,nullable:!1,initial:"fame"}),abilities:new fields.SchemaField(mapToObj(KINGDOM_ABILITIES,ability=>{const schema=new fields.SchemaField({value:new fields.NumberField({initial:10,required:!1,nullable:!1}),mod:new fields.NumberField({initial:0,required:!1,nullable:!1}),ruin:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:10})}),penalty:new fields.NumberField({initial:0,required:!1,nullable:!1})});return[ability,schema]})),build:new fields.SchemaField(KINGDOM_BUILD_SCHEMA),customModifiers:new fields.ObjectField({initial:{}}),leadership:new fields.SchemaField(mapToObj(KINGDOM_LEADERSHIP,role=>{const schema=new fields.SchemaField({uuid:new fields.StringField({required:!1,nullable:!0,initial:null}),vacant:new fields.BooleanField({initial:!0}),invested:new fields.BooleanField({required:!1,initial:!1})});return[role,schema]})),resources:new fields.SchemaField(KINGDOM_RESOURCES_SCHEMA),settlements:new RecordField(new fields.StringField({required:!0,nullable:!1,blank:!1}),new fields.SchemaField(KINGDOM_SETTLEMENT_SCHEMA,{required:!0}),{required:!1,nullable:!1,initial:{}}),consumption:new fields.SchemaField({base:new fields.NumberField({required:!1,nullable:!1,initial:0}),settlement:new fields.NumberField({min:0,initial:0}),army:new fields.NumberField({min:0,initial:0}),value:new fields.NumberField({min:0,initial:0})}),unrest:new fields.SchemaField({value:new fields.NumberField({integer:!0,min:0,max:99,required:!1,nullable:!1,initial:0}),anarchyThreshold:new fields.NumberField({integer:!0,required:!1,nullable:!1,initial:20})}),event:new fields.SchemaField({dc:new fields.NumberField({required:!1,nullable:!1,min:0,max:20,initial:16}),text:new fields.StringField({required:!1,nullable:!1,blank:!0,initial:""})}),module:new fields.ObjectField({required:!1,initial:{}})},{DataModel}=foundry.abstract,_Kingdom=class extends DataModel{static{__name(this,"_Kingdom")}static defineSchema(){return KINGDOM_SCHEMA}get actor(){return this.parent}get extraItemTypes(){return["campaignFeature","effect"]}get activities(){return this.actor.itemTypes.campaignFeature.filter(k=>k.category==="kingdom-activity")}get charter(){return this.build.charter}get heartland(){return this.build.heartland}get government(){return this.build.government}createSidebarButtons(){if(!this.active&&!game.user.isGM)return[];const hoverIcon=this.active==="building"?"wrench":this.active?null:"plus",icon=createHTMLElement("a",{classes:["create-button"],children:compact([fontAwesomeIcon("crown"),hoverIcon?fontAwesomeIcon(hoverIcon):null]),dataset:{tooltip:game.i18n.localize(`PF2E.Kingmaker.SIDEBAR.${this.active===!0?"OpenSheet":"CreateKingdom"}`)}});return icon.addEventListener("click",async event=>{if(event.stopPropagation(),!this.active)await Dialog.confirm({title:game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.Title"),content:`${game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.ActivationMessage")}
`})&&(await this.update({active:"building"}),KingdomBuilder.showToPlayers({uuid:this.actor.uuid}),new KingdomBuilder(this).render(!0));else{const type=this.active===!0?null:"builder";this.renderSheet({type})}}),[icon]}async collect(){const{formula,commodities}=calculateKingdomCollectionData(this),roll=await new Roll(formula).evaluate({async:!0});await roll.toMessage({flavor:game.i18n.localize("PF2E.Kingmaker.Kingdom.Resources.Points"),speaker:{...ChatMessagePF2e.getSpeaker(this.actor),alias:this.name}},{rollMode:"publicroll"}),this.update({resources:{points:roll.total,commodities:mapValues$1(commodities,(incoming,type)=>{const current=this.resources.commodities[type];return{value:Math.min(current.value+incoming,current.max)}})}})}async addCustomModifier(stat,data){if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");if(data.label.length===0)throw ErrorPF2e("A custom modifier's label must be a non-empty string");const modifiers=(this.toObject().customModifiers??{})[stat]??[];if(!modifiers.some(m=>m.label===data.label)){data.type=setHasElement(MODIFIER_TYPES,data.type)?data.type:"untyped";const modifier=new ModifierPF2e({...data,custom:!0}).toObject();await this.update({[`customModifiers.${stat}`]:[...modifiers,modifier]})}}async removeCustomModifier(stat,slug){if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");const modifiers=(this.toObject().customModifiers??{})[stat]??[];if(modifiers.length!==0)if(typeof slug=="string"){const withRemoved=modifiers.filter(m=>m.slug!==slug);await this.update({[`customModifiers.${stat}`]:withRemoved})}else throw ErrorPF2e("Custom modifiers can only be removed by slug (string) or index (number)")}async update(data){const expanded=expandObject(data),updateData=mergeObject(expanded,expanded.system?.campaign??{});delete updateData.system,await this.actor.update({"system.campaign":updateData}),updateData.level&&await this.updateFeatures(updateData.level)}prepareBaseData(){const{synthetics}=this.actor,{build}=this;if(!build.manual){for(const ability of KINGDOM_ABILITIES)this.abilities[ability].value=10;for(const category of["charter","heartland","government"]){const data=build[category],chosen=build.boosts[category];if(!data)continue;"flaw"in data&&data.flaw&&(this.abilities[data.flaw].value-=2);const activeBoosts=resolveKingdomBoosts(data,chosen);for(const ability of activeBoosts)this.abilities[ability].value+=this.abilities[ability].value>=18?1:2}const activeLevels=[1,5,10,15,20].filter(l=>this.level>=l);for(const level of activeLevels){const chosen=build.boosts[level].slice(0,2);for(const ability of chosen)this.abilities[ability].value+=this.abilities[ability].value>=18?1:2}}for(const ability of KINGDOM_ABILITIES)this.abilities[ability].mod=(this.abilities[ability].value-10)/2;if(build.government&&build.government.skills.length>0)for(const skill of build.government.skills)build.skills[skill].rank=Math.max(1,build.skills[skill].rank);const customModifiers=this.customModifiers??={};for(const selector of Object.keys(customModifiers)){const modifiers=customModifiers[selector]=customModifiers[selector].map(rawModifier=>new ModifierPF2e(rawModifier));(synthetics.modifiers[selector]??=[]).push(...modifiers.map(m=>()=>m))}const sizeData=Object.entries(KINGDOM_SIZE_DATA).findLast(([size])=>this.size>=Number(size))?.[1]??KINGDOM_SIZE_DATA[1];this.nationType=sizeData.type,this.resources.dice.faces=sizeData.faces,sizeData.controlMod&&(synthetics.modifiers["control-dc"]??=[]).push(()=>new ModifierPF2e({slug:"size",label:"Size Modifier",modifier:sizeData.controlMod}));for(const ability of KINGDOM_ABILITIES){const penalty=this.abilities[ability].penalty;penalty&&(synthetics.modifiers[`${ability}-based`]??=[]).push(()=>new ModifierPF2e({slug:"ruin",type:"item",label:KINGDOM_RUIN_LABELS[ability],modifier:penalty}))}for(const role of KINGDOM_LEADERSHIP){const data=this.leadership[role],actor=fromUuidSync(data.uuid??"");if(actor instanceof ActorPF2e?actor.hasPlayerOwner||(data.vacant=!1):data.vacant=!0,data.vacant){const penalties=VACANCY_PENALTIES[role]();for(const[selector,entries]of Object.entries(penalties.adjustments??{}))(synthetics.modifierAdjustments[selector]??=[]).push(...entries);for(const[selector,entries]of Object.entries(penalties.modifiers??{}))(synthetics.modifiers[selector]??=[]).push(...entries.map(e=>()=>new ModifierPF2e(e)))}if(data.invested){const ability=KINGDOM_LEADERSHIP_ABILITIES[role];(synthetics.modifiers[`${ability}-skill-check`]??=[]).push(()=>new ModifierPF2e({slug:"invested",label:"PF2E.Kingmaker.Kingdom.Invested",type:"status",modifier:1}))}}if(this.unrest.value>0){const modifier=-([1,5,10,15].findLastIndex(t=>this.unrest.value>=t)+1);(synthetics.modifiers["kingdom-check"]??=[]).push(()=>new ModifierPF2e({slug:"unrest",label:"PF2E.Kingmaker.Kingdom.Unrest",type:"status",modifier}))}const settlements=compact(Object.values(this.settlements));for(const settlement of settlements){if(!settlement)continue;const typeData=KINGDOM_SETTLEMENT_TYPE_DATA[settlement.type];settlement.consumption.base=typeData.consumption,settlement.consumption.total=Math.max(0,typeData.consumption-settlement.consumption.reduction)}for(const[type,value]of Object.entries(this.resources.commodities)){const settlementStorage=sumBy(settlements,s=>s.storage[type]);value.max=sizeData.storage+settlementStorage}}prepareDerivedData(){const{synthetics}=this.actor,{consumption,resources}=this;resources.dice.number=Math.max(0,this.level+4+resources.dice.bonus-resources.dice.penalty);const settlements=compact(Object.values(this.settlements));consumption.settlement=sumBy(settlements,s=>s.consumption.total);const computedConsumption=consumption.base+consumption.settlement+consumption.army-this.resources.workSites.food.value;consumption.value=Math.max(0,computedConsumption);const controlMod=CONTROL_DC_BY_LEVEL[Math.clamped(this.level-1,0,19)]-10;this.control=new Statistic(this.actor,{slug:"control",label:"PF2E.Kingmaker.Kingdom.ControlDC",domains:["control-dc"],modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:controlMod})]}),this.skills=mapToObj(KINGDOM_SKILLS,skill=>{const ability=KINGDOM_SKILL_ABILITIES[skill],abilityMod=this.abilities[ability].mod,rank=this.build.skills[skill].rank,domains=["kingdom-check",`${ability}-based`,`${ability}-skill-check`,skill],statistic=new Statistic(this.actor,{slug:skill,rank,label:KINGDOM_SKILL_LABELS[skill],domains,modifiers:[new ModifierPF2e({slug:ability,label:KINGDOM_ABILITY_LABELS[ability],modifier:abilityMod,type:"ability",adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,ability)}),createProficiencyModifier({actor:this.actor,rank,domains,level:this.level})],check:{type:"skill-check"}});return[skill,statistic]});const evenLevels=new Array(this.level).fill(0).map((_,idx)=>idx+1).filter(idx=>idx%2===0);this.features=new FeatGroup(this.actor,{id:"features",label:"Kingdom Features",level:this.level}),this.feats=new FeatGroup(this.actor,{id:"kingdom",label:"Kingdom Feats",slots:[{id:"government",label:"G"},...evenLevels],featFilter:["traits-kingdom"],level:this.level}),this.bonusFeats=new FeatGroup(this.actor,{id:"bonus",label:"PF2E.FeatBonusHeader",featFilter:["traits-kingdom"],level:this.level});const allFeatures=this.actor.itemTypes.campaignFeature,features=sortBy$1(allFeatures.filter(f=>f.isFeature),f=>f.level??1,f=>f.name),feats=sortBy$1(allFeatures.filter(f=>f.isFeat),f=>f.sort);for(const feature of features)this.features.assignFeat(feature);for(const feat of feats)this.feats.assignFeat(feat)||this.bonusFeats.assignFeat(feat)}getRollOptions(){const prefix="kingdom";return compact([this.unrest.value?`${prefix}:unrest:${this.unrest.value}`:null])}getRollData(){return{kingdom:this}}async importActivities({skipDialog=!1}={}){const pack=game.packs.get("pf2e.kingmaker-features");if(!pack)throw ErrorPF2e("Could not load kingdom features compendium");await this.updateFeatures(this.level);const documents=(await pack.getDocuments({type:"campaignFeature"})).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature")).filter(d=>d.system.category==="kingdom-activity"),actor=this.actor,createData=documents.filter(d=>!actor.items.some(i=>i.sourceId===d.uuid)).map(d=>d.toObject()),incomingDataByUUID=mapToObj(documents,d=>[d.uuid,d.toObject(!0)]),updateData=compact(actor.itemTypes.campaignFeature.map(d=>{const incoming=d.sourceId&&incomingDataByUUID[d.sourceId];if(!incoming)return null;const data=pick$1(incoming,["name","img","system"]),diff=diffObject(d.toObject(!0),data);return isEmpty(diff)?null:{_id:d.id,...diff}}));!updateData.length&&!createData.length||!skipDialog&&!await Dialog.confirm({title:game.i18n.localize("PF2E.Kingmaker.Kingdom.ImportDialog.Title"),content:game.i18n.format("PF2E.Kingmaker.Kingdom.ImportDialog.Content",{added:createData.length,updated:updateData.length})})||(await this.actor.updateEmbeddedDocuments("Item",updateData),await this.actor.createEmbeddedDocuments("Item",createData))}async updateFeatures(level){const featuresToDelete=this.actor.itemTypes.campaignFeature.filter(f=>f.isFeature).filter(f=>(f.level??0)>level).map(f=>f.id),featuresToAdd=await(async()=>{const pack=game.packs.get("pf2e.kingmaker-features");return pack?(await pack.getDocuments({type:"campaignFeature"})).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature")).filter(d=>d.system.category==="kingdom-feature").filter(d=>level>=(d.level??0)).filter(d=>!this.actor.items.some(i=>i.sourceId===d.uuid)).map(i=>i.toObject()):(console.error("PF2E System | Could not load kingdom features compendium"),[])})();await this.actor.deleteEmbeddedDocuments("Item",featuresToDelete),await this.actor.createEmbeddedDocuments("Item",featuresToAdd)}getStatistic(slug){return this.skills&&objectHasKey(this.skills,slug)?this.skills[slug]??null:null}renderSheet(options={}){options.type==="builder"?new KingdomBuilder(this).render(!0):new KingdomSheetPF2e(this.actor).render(!0,{tab:options.tab})}_preUpdate(changed){const actor=this.actor,feat=changed.build?.government?.feat;feat&&(console.log("Replacing feat"),fromUuid(feat).then(async f=>{if(!(f instanceof CampaignFeaturePF2e))return;const currentGovernmentFeat=actor.itemTypes.campaignFeature.find(f2=>f2.system.location==="government"),newFeat=f.clone({"system.location":"government"});await currentGovernmentFeat?.delete(),await actor.createEmbeddedDocuments("Item",[newFeat.toObject()])}))}};__name2(_Kingdom,"Kingdom");let Kingdom=_Kingdom;const _PartyPF2e=class extends ActorPF2e{static{__name(this,"_PartyPF2e")}armorClass=null;get active(){return game.actors.party===this}get baseAllowedItemTypes(){return["physical"]}get allowedItemTypes(){return[...this.baseAllowedItemTypes,...this.campaign?.extraItemTypes??[]]}get canAct(){return!1}canUserModify(user,action2){return super.canUserModify(user,action2)||action2==="update"&&this.members.some(m=>m.canUserModify(user,action2))}isAffectedBy(){return!1}validate(options){if(!super.validate(options))return!1;const changes=options?.changes??{};return!(changes.system?.campaign&&!this.campaign?.validate({...options,changes:changes.system.campaign}))}updateSource(data,options){if(!this.campaign)return super.updateSource(data,options);const expanded=expandObject(data??{}),campaignDiff=expanded?.system?.campaign?this.campaign.updateSource(expanded.system.campaign,options):{},diff=super.updateSource(data,options);return isEmpty(campaignDiff)?diff:mergeObject(diff,campaignDiff)}prepareRuleElements(){return this.items.contents.filter(item=>!item.isOfType("physical")).flatMap(item=>item.prepareRuleElements()).filter(rule=>!rule.ignored).sort((elementA,elementB)=>elementA.priority-elementB.priority)}_initialize(options){super._initialize(options),Object.defineProperty(this.system,"campaign",{writable:!0,enumerable:!1})}prepareBaseData(){this.system.details.level={value:0},super.prepareBaseData(),this.members=this.system.details.members.map(m=>fromUuidSync(m.uuid)).filter(a=>a instanceof ActorPF2e&&a.isOfType("creature")).sort(sortBy(a=>a.name));for(const member of this.members)member?.parties.add(this);const campaignType=game.settings.get("pf2e","campaignType");if(campaignType!=="none"){const typeMatches=this.system.campaign?.type===campaignType;if(this.system.campaign&&!typeMatches)this.campaign=new InvalidCampaign(this,{campaignType,reason:"mismatch"});else try{this.campaign?.type!==campaignType?this.campaign=new Kingdom(deepClone(this._source.system.campaign),{parent:this}):(Kingdom.cleanData(this.campaign._source),this.campaign.reset()),this.campaign.prepareBaseData?.(),this.system.campaign=this.campaign}catch(err){console.error(err),this.campaign=new InvalidCampaign(this,{campaignType,reason:"error"})}}else this.campaign=null;const partyLevel=Math.round(meanBy(this.members.filter(m=>m.isOfType("character")),m=>m.level));this.system.details.level.value=partyLevel}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){super.prepareDerivedData();const travelSpeed=Math.min(...this.members.map(m=>m.attributes.speed.total));this.attributes.speed={total:travelSpeed},this.prepareSynthetics(),this.campaign?.prepareDerivedData?.()}async addMembers(...membersToAdd){const existing=this.system.details.members.filter(d=>this.members.some(m=>m.uuid===d.uuid)),existingUUIDs=new Set(existing.map(data=>data.uuid)),newMembers=membersToAdd.filter(a=>a.uuid.startsWith("Actor.")&&!existingUUIDs.has(a.uuid));for(const member of newMembers){const allianceUpdate=member.isOfType("character","npc")?{"system.details.alliance":member._source.system.details.alliance??"party"}:{};await member.update({folder:null,...allianceUpdate})}const members=[...existing,...newMembers.map(m=>({uuid:m.uuid}))];await this.update({system:{details:{members}}}),await resetActors(newMembers)}async removeMembers(...remove2){const uuids=remove2.map(d=>typeof d=="string"?d:d.uuid),members=this.system.details.members.filter(d=>this.members.some(m=>m.uuid===d.uuid)).filter(m=>!tupleHasValue(uuids,m.uuid));await this.update({system:{details:{members}}})}async addToCombat(options={}){const promises=this.members.map(a=>CombatantPF2e.fromActor(a,!0,{combat:options.combat}));return(await Promise.all(promises)).filter(c=>!!c)}getRollOptions(domains){return super.getRollOptions(domains).concat(this.campaign?.getRollOptions?.()??[])}getRollData(){return mergeObject(super.getRollData(),this.campaign?.getRollData?.()??{})}reset({actor=!1}={}){actor?this._resetAndRerenderDebounced():super.reset()}getStatistic(slug){const statistic=super.getStatistic(slug);return statistic||(this.campaign?.getStatistic?.(slug)??null)}_resetAndRerenderDebounced=foundry.utils.debounce(()=>{super.reset(),this.sheet.render(!1,{actor:!0})},50);async _preUpdate(changed,options,user){const members=this.members,newMemberUUIDs=changed?.system?.details?.members?.map(m=>m?.uuid);if(newMemberUUIDs){const deletedMembers=members.filter(m=>m?.uuid&&!newMemberUUIDs.includes(m.uuid));options.removedMembers=deletedMembers.map(m=>m.uuid)}return changed.system?.campaign&&this.campaign&&this.campaign.type!=="invalid"&&(changed.system.campaign.type=this.campaign.type,this.campaign._preUpdate?.(changed.system.campaign)),super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const removedCreatures=(options.removedMembers??[]).map(uuid=>fromUuidSync(uuid)).filter(a=>a instanceof ActorPF2e&&a.isOfType("creature"));for(const actor of removedCreatures)actor.parties.delete(this);if(resetActors(removedCreatures),changed.system?.details?.members&&game.combat)for(const encounter of game.combats)encounter.reset(),ui.combat.render();game.ready&&changed.system?.campaign&&game.actors.get(this.id)===this&&ui.actors.render()}_onDelete(options,userId){super._onDelete(options,userId);for(const member of this.members)member.parties.delete(this);resetActors(this.members),ui.actors.saveActivePartyFolderState()}};__name2(_PartyPF2e,"PartyPF2e");let PartyPF2e=_PartyPF2e;const _VehiclePF2e=class extends ActorPF2e{static{__name(this,"_VehiclePF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"physical","action"]}get dimensions(){return{length:this.system.details.space.long,width:this.system.details.space.wide,height:this.system.details.space.high}}get hardness(){return this.system.attributes.hardness}getTokenDimensions(dimensions=this.dimensions){return{width:Math.max(Math.round(dimensions.width/5),1),height:Math.max(Math.round(dimensions.length/5),1)}}prepareBaseData(){super.prepareBaseData(),this.system.details.alliance=null;const{size}=this.system.traits,{dimensions}=this;if(size.length=dimensions.length,size.width=dimensions.width,this.prototypeToken.flags?.pf2e?.linkToActorSize){const{width,height}=this.getTokenDimensions();this.prototypeToken.width=width,this.prototypeToken.height=height}}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){if(super.prepareDerivedData(),this.prepareSynthetics(),this.hasCondition("broken"))for(const selector of["ac","saving-throw"]){const modifiers=this.synthetics.modifiers[selector]??=[],brokenModifier=new ModifierPF2e({slug:"broken",label:"PF2E.ConditionTypeBroken",modifier:-2,adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,[selector],"broken")});modifiers.push(()=>brokenModifier)}const{attributes}=this,hitPoints=new HitPointsStatistic(this,{baseMax:attributes.hp.max});attributes.hp=mergeObject(hitPoints.getTraceData(),{brokenThreshold:Math.floor(hitPoints.max/2)}),setHitPointsRollOptions(this);const armorStatistic=new ArmorStatistic(this,{modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:this.system.attributes.ac.value-10,adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,["all","ac"],"base")})]});this.armorClass=armorStatistic.dc,this.system.attributes.ac=armorStatistic.getTraceData(),this.prepareSaves()}prepareSaves(){const{synthetics}=this,slug="fortitude",domains=[slug,"saving-throw","all"],modifiers=[new ModifierPF2e({label:"PF2E.ModifierTitle",slug,type:"untyped",modifier:this.system.saves.fortitude.value}),...extractModifiers(synthetics,domains)],fortitude=new Statistic(this,{slug:"fortitude",label:CONFIG.PF2E.saves.fortitude,modifiers,domains,check:{type:"saving-throw"}});this.saves={fortitude},this.system.saves.fortitude=mergeObject(this.system.saves.fortitude,fortitude.getTraceData())}async _preUpdate(changed,options,user){const result=await super._preUpdate(changed,options,user);if(result===!1)return result;if(this.prototypeToken.flags?.pf2e?.linkToActorSize){const{space}=this.system.details,spaceUpdates={width:changed.system?.details?.space?.wide??space.wide,length:changed.system?.details?.space?.long??space.long},tokenDimensions=this.getTokenDimensions(spaceUpdates);if(changed.prototypeToken=mergeObject(changed.prototypeToken??{},tokenDimensions),canvas.scene){const updates=this.getActiveTokens().filter(token=>token.document.linkToActorSize).map(token=>({_id:token.id,...tokenDimensions}));await TokenDocumentPF2e.updateDocuments(updates,{parent:canvas.scene})}}}};__name2(_VehiclePF2e,"VehiclePF2e");let VehiclePF2e=_VehiclePF2e;function extractModifiers(synthetics,selectors,options={}){const{modifierAdjustments,modifiers:syntheticModifiers}=synthetics,modifiers=Array.from(new Set(selectors)).flatMap(s=>syntheticModifiers[s]??[]).flatMap(d=>d(options)??[]);for(const modifier of modifiers)modifier.adjustments=extractModifierAdjustments(modifierAdjustments,selectors,modifier.slug);return modifiers}__name(extractModifiers,"extractModifiers"),__name2(extractModifiers,"extractModifiers");function extractModifierAdjustments(adjustmentsRecord,selectors,slug){return Array.from(new Set(selectors.flatMap(s=>adjustmentsRecord[s]??[]))).filter(a=>[slug,null].includes(a.slug))}__name(extractModifierAdjustments,"extractModifierAdjustments"),__name2(extractModifierAdjustments,"extractModifierAdjustments");function extractNotes(rollNotes,selectors){return selectors.flatMap(s=>(rollNotes[s]??[]).map(n=>n.clone()))}__name(extractNotes,"extractNotes"),__name2(extractNotes,"extractNotes");function extractDamageDice(deferredDice,selectors,options){return selectors.flatMap(s=>deferredDice[s]??[]).flatMap(d=>d(options)??[])}__name(extractDamageDice,"extractDamageDice"),__name2(extractDamageDice,"extractDamageDice");function processDamageCategoryStacking(base,options){const{dice}=options,groupedModifiers=groupBy$1(options.modifiers,m=>m.category==="persistent"?"persistent":"main"),modifiers=[...new StatisticModifier("damage",groupedModifiers.main??[],options.test).modifiers,...new StatisticModifier("persistent",groupedModifiers.persistent??[],options.test).modifiers],allPersistent=base.length>0&&base.every(b=>b.category==="persistent");return{modifiers:allPersistent?modifiers.filter(m=>m.category==="persistent"):modifiers,dice:allPersistent?dice.filter(m=>m.category==="persistent"):dice}}__name(processDamageCategoryStacking,"processDamageCategoryStacking"),__name2(processDamageCategoryStacking,"processDamageCategoryStacking");async function extractEphemeralEffects({affects,origin,target,item,domains,options}){if(!(origin&&target))return[];const[effectsFrom,effectsTo]=affects==="target"?[origin,target]:[target,origin],fullOptions=[...options,effectsFrom.getRollOptions(domains),effectsTo.getSelfRollOptions(affects)].flat(),resolvables=item?item.isOfType("spell")?{spell:item}:{weapon:item}:{};return(await Promise.all(domains.flatMap(s=>effectsFrom.synthetics.ephemeralEffects[s]?.[affects]??[]).map(d=>d({test:fullOptions,resolvables})))).flatMap(e=>e??[])}__name(extractEphemeralEffects,"extractEphemeralEffects"),__name2(extractEphemeralEffects,"extractEphemeralEffects");function extractRollTwice(rollTwices,selectors,options){const twices=selectors.flatMap(s=>rollTwices[s]??[]).filter(rt=>rt.predicate?.test(options)??!0);return twices.length===0||twices.some(rt=>rt.keep==="higher")&&twices.some(rt=>rt.keep==="lower")?!1:twices.at(0)?.keep==="higher"?"keep-higher":"keep-lower"}__name(extractRollTwice,"extractRollTwice"),__name2(extractRollTwice,"extractRollTwice");function extractRollSubstitutions(substitutions,domains,rollOptions){return domains.flatMap(d=>deepClone(substitutions[d]??[])).filter(s=>s.predicate?.test(rollOptions)??!0)}__name(extractRollSubstitutions,"extractRollSubstitutions"),__name2(extractRollSubstitutions,"extractRollSubstitutions");function extractDegreeOfSuccessAdjustments(synthetics,selectors){return Object.values(pick(synthetics.degreeOfSuccessAdjustments,selectors)).flat()}__name(extractDegreeOfSuccessAdjustments,"extractDegreeOfSuccessAdjustments"),__name2(extractDegreeOfSuccessAdjustments,"extractDegreeOfSuccessAdjustments");function isBracketedValue(value){return isObject(value)&&Array.isArray(value.brackets)}__name(isBracketedValue,"isBracketedValue"),__name2(isBracketedValue,"isBracketedValue");async function processPreUpdateActorHooks(changed,{pack}){const actorId=String(changed._id),actor=pack?await game.packs.get(pack)?.getDocument(actorId):game.actors.get(actorId);if(!(actor instanceof ActorPF2e))return;const rules=actor.rules.filter(r=>!!r.preUpdateActor);if(rules.length===0)return;actor.flags.pf2e.rollOptions=actor.clone(changed,{keepId:!0}).flags.pf2e.rollOptions;const createDeletes=(await Promise.all(rules.map(r=>actor.items.has(r.item.id)?r.preUpdateActor():new Promise(()=>({create:[],delete:[]}))))).reduce((combined,cd)=>({create:[...combined.create,...cd.create],delete:Array.from(new Set([...combined.delete,...cd.delete]))}),{create:[],delete:[]});createDeletes.delete=createDeletes.delete.filter(id=>actor.items.has(id)),await actor.createEmbeddedDocuments("Item",createDeletes.create,{keepId:!0,render:!1}),await actor.deleteEmbeddedDocuments("Item",createDeletes.delete,{render:!1})}__name(processPreUpdateActorHooks,"processPreUpdateActorHooks"),__name2(processPreUpdateActorHooks,"processPreUpdateActorHooks");const PROFICIENCY_RANK_OPTION=["proficiency:untrained","proficiency:trained","proficiency:expert","proficiency:master","proficiency:legendary"];function ensureProficiencyOption(options,rank){rank>=0&&options.add(`skill:rank:${rank}`).add(PROFICIENCY_RANK_OPTION[rank])}__name(ensureProficiencyOption,"ensureProficiencyOption"),__name2(ensureProficiencyOption,"ensureProficiencyOption");const MODIFIER_TYPES=new Set(["ability","circumstance","item","potency","proficiency","status","untyped"]),_ModifierPF2e=class _ModifierPF2e2{static{__name(this,"_ModifierPF2e")}constructor(...args){__publicField(this,"slug"),__publicField(this,"label"),__publicField(this,"modifier"),__privateAdd(this,_originalValue,void 0),__publicField(this,"type"),__publicField(this,"ability"),__publicField(this,"adjustments"),__publicField(this,"force"),__publicField(this,"enabled"),__publicField(this,"ignored"),__publicField(this,"rule"),__publicField(this,"source"),__publicField(this,"custom"),__publicField(this,"damageType"),__publicField(this,"damageCategory"),__publicField(this,"predicate"),__publicField(this,"critical"),__publicField(this,"traits"),__publicField(this,"hideIfDisabled"),__publicField(this,"kind");const params=__name2(args2=>typeof args2[0]=="string","isLegacyParams")(args)?{label:args[0],modifier:args[1],type:args[2]??"untyped",enabled:args[3],ignored:args[4],source:args[5]}:args[0];if(this.label=game.i18n.localize(params.label??params.name),this.slug=sluggify(params.slug??this.label),__privateSet(this,_originalValue,this.modifier=params.modifier),this.type=setHasElement(MODIFIER_TYPES,params.type)?params.type:"untyped",this.ability=params.ability??null,this.force=params.force??!1,this.adjustments=deepClone(params.adjustments??[]),this.enabled=params.enabled??!0,this.ignored=params.ignored??!1,this.custom=params.custom??!1,this.source=params.source??null,this.predicate=new PredicatePF2e(params.predicate??[]),this.traits=deepClone(params.traits??[]),this.hideIfDisabled=params.hideIfDisabled??!1,this.modifier=params.modifier,this.rule=params.rule??null,Object.defineProperty(this,"rule",{enumerable:!1}),this.damageType=objectHasKey(CONFIG.PF2E.damageTypes,params.damageType)?params.damageType:null,this.damageCategory=this.damageType==="bleed"?"persistent":params.damageCategory??null,this.critical=this.damageCategory==="splash"?!!params.critical:params.critical??null,this.kind=(()=>this.modifier>=0&&!["ability","untyped"].includes(this.type)?"bonus":this.modifier<0&&this.type!=="ability"?"penalty":"modifier")(),this.force&&this.type==="untyped")throw ErrorPF2e("A forced modifier must have a type")}get category(){return this.damageCategory}get value(){return this.kind==="penalty"&&this.modifier===0?-this.modifier:this.modifier}get signedValue(){return this.modifier===0&&this.kind==="penalty"?signedInteger(-this.modifier):signedInteger(this.modifier)}clone(options={}){const clone=this.modifier===__privateGet(this,_originalValue)?new _ModifierPF2e2(this):new _ModifierPF2e2({...this,modifier:__privateGet(this,_originalValue)});return options.test&&clone.test(options.test),clone}getRollOptions(){const options=["slug","type","value"].map(p=>`${this.kind}:${p}:${this[p]}`);return this.type==="ability"&&this.ability&&options.push(`modifier:ability:${this.ability}`),new Set(options)}test(options){if(this.predicate.length===0)return;const rollOptions=this.rule?[...options,...this.rule.item.getRollOptions("parent")]:options;this.ignored=!this.predicate.test(rollOptions)}toObject(){return duplicate({...this,item:void 0})}toString(){return this.label}};_originalValue=new WeakMap,__name2(_ModifierPF2e,"ModifierPF2e");let ModifierPF2e=_ModifierPF2e;function createAttributeModifier({actor,attribute,domains,max}){const withAttributeBased=domains.includes(`${attribute}-based`)?domains:[...domains,`${attribute}-based`],modifierValue=actor.abilities[attribute].mod,cappedValue=Math.min(modifierValue,max??modifierValue);return new ModifierPF2e({slug:attribute,label:CONFIG.PF2E.abilities[attribute],modifier:cappedValue,type:"ability",ability:attribute,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,withAttributeBased,attribute)})}__name(createAttributeModifier,"createAttributeModifier"),__name2(createAttributeModifier,"createAttributeModifier");function createProficiencyModifier({actor,rank,domains,level,addLevel}){rank=Math.clamped(rank,0,4),addLevel??=rank>0;const pwolVariant=game.settings.get("pf2e","proficiencyVariant"),baseBonuses=pwolVariant?[game.settings.get("pf2e","proficiencyUntrainedModifier"),game.settings.get("pf2e","proficiencyTrainedModifier"),game.settings.get("pf2e","proficiencyExpertModifier"),game.settings.get("pf2e","proficiencyMasterModifier"),game.settings.get("pf2e","proficiencyLegendaryModifier")]:[0,2,4,6,8],addedLevel=addLevel&&!pwolVariant?level??actor.level:0,bonus=baseBonuses[rank]+addedLevel;return new ModifierPF2e({slug:"proficiency",label:`PF2E.ProficiencyLevel${rank}`,modifier:bonus,type:"proficiency",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"proficiency")})}__name(createProficiencyModifier,"createProficiencyModifier"),__name2(createProficiencyModifier,"createProficiencyModifier");const HIGHER_BONUS=__name2((a,b)=>a.modifier>=b.modifier,"HIGHER_BONUS"),LOWER_PENALTY=__name2((a,b)=>a.modifier<=b.modifier,"LOWER_PENALTY");function applyStacking(best,modifier,isBetter){const existing=best[modifier.type];return existing===void 0?(modifier.enabled=!0,best[modifier.type]=modifier,modifier.modifier):isBetter(modifier,existing)?(existing.enabled=!1,modifier.enabled=!0,best[modifier.type]=modifier,modifier.modifier-existing.modifier):(modifier.enabled=!1,0)}__name(applyStacking,"applyStacking"),__name2(applyStacking,"applyStacking");function applyStackingRules(modifiers){let total=0;const highestBonus={},lowestPenalty={},abilityModifiers=modifiers.filter(m=>m.type==="ability"&&!m.ignored),bestAbility=abilityModifiers.reduce((best,modifier)=>best===null||modifier.force?modifier:best.force?best:modifier.modifier>best.modifier?modifier:best,null);for(const modifier of abilityModifiers)modifier.ignored=modifier!==bestAbility;for(const modifier of modifiers){if(modifier.ignored){modifier.enabled=!1;continue}if(modifier.type==="untyped"){modifier.enabled=!0,total+=modifier.modifier;continue}modifier.modifier<0?total+=applyStacking(lowestPenalty,modifier,LOWER_PENALTY):total+=applyStacking(highestBonus,modifier,HIGHER_BONUS)}return total}__name(applyStackingRules,"applyStackingRules"),__name2(applyStackingRules,"applyStackingRules");const _StatisticModifier=class{static{__name(this,"_StatisticModifier")}slug;_modifiers;breakdown="";notes;constructor(slug,modifiers=[],rollOptions=new Set){rollOptions=rollOptions instanceof Set?rollOptions:new Set(rollOptions),this.slug=slug;const seen=modifiers.reduce((result,modifier)=>((!result[modifier.slug]?.enabled||Math.abs(modifier.modifier)>Math.abs(result[modifier.slug].modifier))&&(result[modifier.slug]=modifier),result),{});this._modifiers=Object.values(seen),this.calculateTotal(rollOptions)}get modifiers(){return[...this._modifiers]}push(modifier){const existingIdx=this._modifiers.findIndex(o=>o.slug===modifier.slug),existing=this._modifiers[existingIdx];return existing?Math.abs(modifier.modifier)>Math.abs(existing.modifier)&&(this._modifiers[existingIdx]=modifier,this.calculateTotal()):(this._modifiers.push(modifier),this.calculateTotal()),this._modifiers.length}unshift(modifier){return this._modifiers.find(o=>o.slug===modifier.slug)===void 0&&(this._modifiers.unshift(modifier),this.calculateTotal()),this._modifiers.length}delete(modifierSlug){const toDelete2=typeof modifierSlug=="object"?modifierSlug:this._modifiers.find(modifier=>modifier.slug===modifierSlug),wasDeleted=toDelete2&&this._modifiers.includes(toDelete2)?!!this._modifiers.findSplice(modifier=>modifier===toDelete2):!1;return wasDeleted&&this.calculateTotal(),wasDeleted}calculateTotal(rollOptions=new Set){if(rollOptions.size>0){for(const modifier of this._modifiers)modifier.test(rollOptions);adjustModifiers(this._modifiers,rollOptions)}applyStackingRules(this._modifiers),this.totalModifier=this._modifiers.filter(m=>m.enabled).reduce((total,m)=>total+m.modifier,0)}};__name2(_StatisticModifier,"StatisticModifier");let StatisticModifier=_StatisticModifier;function adjustModifiers(modifiers,rollOptions){for(const modifier of[...modifiers].sort((a,b)=>Math.abs(b.value)-Math.abs(a.value))){const adjustments=modifier.adjustments.filter(a=>a.test([...rollOptions,...modifier.getRollOptions()]));if(adjustments.some(a=>a.suppress)){modifier.ignored=!0;continue}const resolvedAdjustment=adjustments.reduce((resolved,adjustment)=>{const newValue=adjustment.getNewValue?.(resolved.value)??resolved.value;return newValue!==resolved.value&&(resolved.value=newValue,resolved.relabel=adjustment.relabel??null),resolved},{value:modifier.modifier,relabel:null});modifier.modifier=resolvedAdjustment.value,resolvedAdjustment.relabel&&(modifier.label=game.i18n.localize(resolvedAdjustment.relabel)),modifier.damageType=adjustments.reduce((damageType,adjustment)=>adjustment.getDamageType?.(damageType)??damageType,modifier.damageType)}}__name(adjustModifiers,"adjustModifiers"),__name2(adjustModifiers,"adjustModifiers");const _CheckModifier=class extends StatisticModifier{static{__name(this,"_CheckModifier")}constructor(slug,statistic,modifiers=[],rollOptions=new Set){const baseModifiers=statistic.modifiers.map(m=>"clone"in m?m.clone():new ModifierPF2e(m));super(slug,baseModifiers.concat(modifiers),rollOptions)}};__name2(_CheckModifier,"CheckModifier");let CheckModifier=_CheckModifier;const _DamageDicePF2e=class _DamageDicePF2e2{static{__name(this,"_DamageDicePF2e")}selector;slug;label;diceNumber;dieSize;critical;category;damageType;override;ignored;enabled;custom;predicate;constructor(params){if(params.selector)this.selector=params.selector;else throw ErrorPF2e("`selector` is mandatory");if(this.label=game.i18n.localize(params.label??""),this.slug=sluggify(params.slug??this.label),!this.slug)throw ErrorPF2e("A DiceModifier must have a slug");this.diceNumber=params.diceNumber??0,this.dieSize=params.dieSize??null,this.damageType=params.damageType??null,this.category=params.category??null,this.override=params.override??null,this.custom=params.custom??!1,this.category=tupleHasValue(["persistent","precision","splash"],params.category)?params.category:this.damageType==="bleed"?"persistent":null,this.critical=this.category==="splash"?!!params.critical:params.critical??null,this.predicate=params.predicate instanceof PredicatePF2e?params.predicate:new PredicatePF2e(params.predicate??[]),this.enabled=params.enabled??this.predicate.test([]),this.ignored=params.ignored??!this.enabled}test(options){this.enabled=this.predicate.test(options),this.ignored=!this.enabled}clone(){return new _DamageDicePF2e2(this)}toObject(){return{...this,predicate:deepClone([...this.predicate])}}};__name2(_DamageDicePF2e,"DamageDicePF2e");let DamageDicePF2e=_DamageDicePF2e;function isCheckContextFlag(flag){return!!flag&&!tupleHasValue(["damage-roll","spell-cast"],flag.type)}__name(isCheckContextFlag,"isCheckContextFlag"),__name2(isCheckContextFlag,"isCheckContextFlag");async function createSelfEffectMessage(item){if(!item.system.selfEffect)throw ErrorPF2e(["Only actions with self-applied effects can be passed to `ActorPF2e#useAction`.","Support will be expanded at a later time."].join(" "));const{actor,actionCost}=item,token=actor.getActiveTokens(!0,!0).shift()??null,speaker=ChatMessagePF2e.getSpeaker({actor,token}),flavor=await renderTemplate("systems/pf2e/templates/chat/action/flavor.hbs",{action:{glyph:getActionGlyph(actionCost),title:item.name},item,traits:item.system.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits))}),previewLength=100,descriptionPreview=(()=>{if(item.actor.pack)return null;const tempDiv=document.createElement("div"),documentTypes=[...CONST.DOCUMENT_LINK_TYPES,"Compendium","UUID"],linkPattern=new RegExp(`@(${documentTypes.join("|")})\\[([^#\\]]+)(?:#([^\\]]+))?](?:{([^}]+)})?`,"g");return tempDiv.innerHTML=item.description.replace(linkPattern,(_match,...args)=>args[3]),tempDiv.innerText.slice(0,previewLength)})(),description={full:descriptionPreview&&descriptionPreview.length!!t.actor).map(t=>t.document);if(tokens.length===0){ui.notifications.error("PF2E.UI.errorTargetToken",{localize:!0});return}const shieldBlockRequest=CONFIG.PF2E.chatDamageButtonShieldToggle,roll=message.rolls.at(rollIndex);if(!(roll instanceof DamageRoll))throw ErrorPF2e("Unexpected error retrieving damage roll");let damage=multiplier<0?multiplier*roll.total+addend:roll.alter(multiplier,addend);const messageRollOptions=[...message.flags.pf2e.context?.options??[]],originRollOptions=messageRollOptions.filter(o=>o.startsWith("self:")).map(o=>o.replace(/^self/,"origin")),messageItem=message.item;for(const token of tokens){if(!token.actor)continue;messageRollOptions.some(o=>o.startsWith("target"))||messageRollOptions.push(...token.actor.getSelfRollOptions("target"));const domain=multiplier>0?"damage-received":"healing-received",ephemeralEffects=multiplier>0?await extractEphemeralEffects({affects:"target",origin:message.actor,target:token.actor,item:message.item,domains:[domain],options:messageRollOptions}):[],contextClone=token.actor.getContextualClone(originRollOptions,ephemeralEffects),applicationRollOptions=new Set([...messageRollOptions.filter(o=>!/^(?:self|target):/.test(o)),...originRollOptions,...contextClone.getSelfRollOptions()]),outcome=message.flags.pf2e.context?.outcome,breakdown=[],rolls=[];if(typeof damage=="number"&&damage<0){const critical=outcome==="criticalSuccess",resolvables=(()=>messageItem?.isOfType("spell")?{spell:messageItem}:messageItem?.isOfType("weapon")?{weapon:messageItem}:{})(),damageDice=extractDamageDice(contextClone.synthetics.damageDice,[domain],{resolvables,test:applicationRollOptions}).filter(d=>(d.critical===null||d.critical===critical)&&d.predicate.test(applicationRollOptions));for(const dice of damageDice){const formula=`${dice.diceNumber}${dice.dieSize}[${dice.label}]`,roll2=await new Roll(formula).evaluate({async:!0});roll2._formula=`${dice.diceNumber}${dice.dieSize}`,await roll2.toMessage({flags:{pf2e:{suppressDamageButtons:!0}},flavor:dice.label,speaker:ChatMessage.getSpeaker({token})}),breakdown.push(`${dice.label} ${dice.diceNumber}${dice.dieSize}`),rolls.push(roll2)}rolls.length&&(damage-=rolls.map(roll2=>roll2.total).reduce((previous,current)=>previous+current));const modifiers=extractModifiers(contextClone.synthetics,[domain],{resolvables}).filter(m=>(m.critical===null||m.critical===critical)&&m.predicate.test(applicationRollOptions));damage-=applyStackingRules(modifiers??[]),breakdown.push(...modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`))}const hasDamage=typeof damage=="number"?damage!==0:damage.total!==0,notes=(()=>hasDamage?extractNotes(contextClone.synthetics.rollNotes,[domain]).filter(n=>(!outcome||n.outcome.length===0||n.outcome.includes(outcome))&&n.predicate.test(applicationRollOptions)).map(note=>note.text):[])();await contextClone.applyDamage({damage,token,item:message.item,skipIWR:multiplier<=0,rollOptions:applicationRollOptions,shieldBlockRequest,breakdown,notes})}toggleOffShieldBlock(message.id)}__name(applyDamageFromMessage,"applyDamageFromMessage"),__name2(applyDamageFromMessage,"applyDamageFromMessage");async function shiftAdjustDamage(message,multiplier,rollIndex){var _a;const content=await renderTemplate("systems/pf2e/templates/chat/damage/adjustment-dialog.hbs"),AdjustmentDialog=(_a=class extends Dialog{static{__name(this,"_a")}activateListeners($html){super.activateListeners($html),$html[0].querySelector("input")?.focus()}},__name2(_a,"AdjustmentDialog"),_a);new AdjustmentDialog({title:game.i18n.localize("PF2E.UI.shiftModifyDamageTitle"),content,buttons:{ok:{label:game.i18n.localize("PF2E.OK"),callback:async $dialog=>{const adjustment=(Number($dialog[0].querySelector("input")?.value)||0)*Math.sign(multiplier);applyDamageFromMessage({message,multiplier,addend:adjustment,promptModifier:!1,rollIndex})}},cancel:{label:"Cancel"}},default:"ok",close:()=>{toggleOffShieldBlock(message.id)}}).render(!0)}__name(shiftAdjustDamage,"shiftAdjustDamage"),__name2(shiftAdjustDamage,"shiftAdjustDamage");function toggleOffShieldBlock(messageId){for(const app of["#chat-log","#chat-popout"]){const selector=`${app} > li.chat-message[data-message-id="${messageId}"] button[data-action=shield-block]`;htmlQuery(document.body,selector)?.classList.remove("shield-activated")}CONFIG.PF2E.chatDamageButtonShieldToggle=!1}__name(toggleOffShieldBlock,"toggleOffShieldBlock"),__name2(toggleOffShieldBlock,"toggleOffShieldBlock");function toggleClearTemplatesButton(message){if(!message||!canvas.ready)return;const selector=`li[data-message-id="${message.id}"] button[data-action=spell-template-clear]`;for(const chatLogDOM of htmlQueryAll(document.body,"#chat-log, #chat-popout")){const clearTemplatesButton=htmlQuery(chatLogDOM,selector);if(!clearTemplatesButton)continue;const hasMeasuredTemplates=!!canvas.scene?.templates.some(t=>t.message===message&&t.isOwner);clearTemplatesButton.classList.toggle("hidden",!hasMeasuredTemplates)}}__name(toggleClearTemplatesButton,"toggleClearTemplatesButton"),__name2(toggleClearTemplatesButton,"toggleClearTemplatesButton");const CanvasReady={listen:()=>{Hooks.once("canvasReady",async()=>{await game.pf2e.ConditionManager.initialize();const tokenActors=canvas.scene?.tokens.contents.flatMap(t=>t.actor??[])??[];for(const actor of tokenActors)for(const effect of actor.itemTypes.effect.filter(e=>e.fromAura))game.pf2e.effectTracker.register(effect)}),Hooks.on("canvasReady",()=>{if(game.pf2e.effectPanel.render(!0),!!canvas.scene){game.ready&&canvas.scene.reset(),CONFIG.MeasuredTemplate.defaults.angle=canvas.scene.hasHexGrid?60:90;for(const token of canvas.tokens.placeables.filter(t=>t.visible))token.renderFlags.set({redrawEffects:!0});for(const message of game.messages.contents.slice(-1*CONFIG.ChatMessage.batchSize/2))toggleClearTemplatesButton(message)}})}},CloseCombatTrackerConfig={listen:()=>{Hooks.on("closeCombatTrackerConfig",async(_app,$html)=>{const newIcon=String($html.find('input[name="deathIcon"]').val()).trim();newIcon&&newIcon!==game.settings.get("pf2e","deathIcon")&&await game.settings.set("pf2e","deathIcon",newIcon);const currentDeadAtZero=game.settings.get("pf2e","automation.actorsDeadAtZero"),newDeadAtZero=String($html.find('select[name="actorsDeadAtZero"]').val());currentDeadAtZero!==newDeadAtZero&&await game.settings.set("pf2e","automation.actorsDeadAtZero",newDeadAtZero)})}},CloseWorldClockSettings={listen:()=>{Hooks.on("closeWorldClockSettings",()=>{game.user.isGM&&game.socket.emit("system.pf2e",{request:"refreshSceneControls",data:{layer:"TokenLayer"}})})}},isDice3D=__name2(obj=>obj instanceof Object&&["addSystem","addDicePreset","addTexture","addColorset"].every(m=>m in obj),"isDice3D"),DiceSoNiceReady={listen:()=>{Hooks.once("diceSoNiceReady",dice3d=>{if(isDice3D(dice3d)){dice3d.addSystem({id:"basic",name:"Dicefinder Basic",colorset:"basic"});for(const faces of[4,6,8,10,12])dice3d.addDicePreset({type:`d${faces}`,labels:[...Array(faces)].map((_value2,idx)=>String(idx+1)),system:"basic",colorset:"basic"});dice3d.addDicePreset({type:"d20",labels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","systems/pf2e/dice/basic/nat20.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"d100",labels:[...Array(10)].map((_value2,idx)=>String((idx+1)*10)),system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"df",labels:["-","","+"],system:"basic",colorset:"basic"}),dice3d.addTexture("PFred",{name:"Pathfinder Red",composite:"source-over",source:"systems/pf2e/dice/texture/texture.webp"}).then(()=>{dice3d.addColorset({name:"basic",description:"Dicefinder Basic",category:"Pathfinder 2e",texture:"PFred",material:"metal",foreground:"#f9b96e",outline:"none",edge:"#f9b96e",visibility:"hidden"})}),dice3d.addSystem({id:"campaign",name:"Dicefinder Campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d4",labels:["systems/pf2e/dice/campaign/d4/d4-1.webp","systems/pf2e/dice/campaign/d4/d4-2.webp","systems/pf2e/dice/campaign/d4/d4-3.webp","systems/pf2e/dice/campaign/d4/d4-4.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d6",labels:["systems/pf2e/dice/campaign/d6/d6-1.webp","systems/pf2e/dice/campaign/d6/d6-2.webp","systems/pf2e/dice/campaign/d6/d6-3.webp","systems/pf2e/dice/campaign/d6/d6-4.webp","systems/pf2e/dice/campaign/d6/d6-5.webp","systems/pf2e/dice/campaign/d6/d6-6.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"df",labels:["systems/pf2e/dice/campaign/df/dfm.webp","systems/pf2e/dice/campaign/df/df.webp","systems/pf2e/dice/campaign/df/dfp.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d8",labels:["systems/pf2e/dice/campaign/d8/d8-1.webp","systems/pf2e/dice/campaign/d8/d8-2.webp","systems/pf2e/dice/campaign/d8/d8-3.webp","systems/pf2e/dice/campaign/d8/d8-4.webp","systems/pf2e/dice/campaign/d8/d8-5.webp","systems/pf2e/dice/campaign/d8/d8-6.webp","systems/pf2e/dice/campaign/d8/d8-7.webp","systems/pf2e/dice/campaign/d8/d8-P.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d10",labels:["systems/pf2e/dice/campaign/d10/d10-1.webp","systems/pf2e/dice/campaign/d10/d10-2.webp","systems/pf2e/dice/campaign/d10/d10-3.webp","systems/pf2e/dice/campaign/d10/d10-4.webp","systems/pf2e/dice/campaign/d10/d10-5.webp","systems/pf2e/dice/campaign/d10/d10-6.webp","systems/pf2e/dice/campaign/d10/d10-7.webp","systems/pf2e/dice/campaign/d10/d10-8.webp","systems/pf2e/dice/campaign/d10/d10-9.webp","systems/pf2e/dice/campaign/d10/d10-10.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d12",labels:["systems/pf2e/dice/campaign/d12/d12-1.webp","systems/pf2e/dice/campaign/d12/d12-2.webp","systems/pf2e/dice/campaign/d12/d12-3.webp","systems/pf2e/dice/campaign/d12/d12-4.webp","systems/pf2e/dice/campaign/d12/d12-5.webp","systems/pf2e/dice/campaign/d12/d12-6.webp","systems/pf2e/dice/campaign/d12/d12-7.webp","systems/pf2e/dice/campaign/d12/d12-8.webp","systems/pf2e/dice/campaign/d12/d12-9.webp","systems/pf2e/dice/campaign/d12/d12-10.webp","systems/pf2e/dice/campaign/d12/d12-11.webp","systems/pf2e/dice/campaign/d12/d12-12.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d100",labels:["systems/pf2e/dice/campaign/d100/d100-10.webp","systems/pf2e/dice/campaign/d100/d100-20.webp","systems/pf2e/dice/campaign/d100/d100-30.webp","systems/pf2e/dice/campaign/d100/d100-40.webp","systems/pf2e/dice/campaign/d100/d100-50.webp","systems/pf2e/dice/campaign/d100/d100-60.webp","systems/pf2e/dice/campaign/d100/d100-70.webp","systems/pf2e/dice/campaign/d100/d100-80.webp","systems/pf2e/dice/campaign/d100/d100-90.webp","systems/pf2e/dice/campaign/d100/d100-100.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d20",labels:["systems/pf2e/dice/campaign/d20/d20-1.webp","systems/pf2e/dice/campaign/d20/d20-2.webp","systems/pf2e/dice/campaign/d20/d20-3.webp","systems/pf2e/dice/campaign/d20/d20-4.webp","systems/pf2e/dice/campaign/d20/d20-5.webp","systems/pf2e/dice/campaign/d20/d20-6.webp","systems/pf2e/dice/campaign/d20/d20-7.webp","systems/pf2e/dice/campaign/d20/d20-8.webp","systems/pf2e/dice/campaign/d20/d20-9.webp","systems/pf2e/dice/campaign/d20/d20-10.webp","systems/pf2e/dice/campaign/d20/d20-11.webp","systems/pf2e/dice/campaign/d20/d20-12.webp","systems/pf2e/dice/campaign/d20/d20-13.webp","systems/pf2e/dice/campaign/d20/d20-14.webp","systems/pf2e/dice/campaign/d20/d20-15.webp","systems/pf2e/dice/campaign/d20/d20-16.webp","systems/pf2e/dice/campaign/d20/d20-17.webp","systems/pf2e/dice/campaign/d20/d20-18.webp","systems/pf2e/dice/campaign/d20/d20-19.webp","systems/pf2e/dice/campaign/d20/d20-20.webp"],system:"campaign",colorset:"campaign"}),dice3d.addTexture("stoneD4",{name:"Pathfinder Stone (D4)",composite:"source-over",source:"systems/pf2e/dice/texture/d4.webp"}).then(()=>{dice3d.addColorset({name:"campaign",description:"Dicefinder Campaign",category:"Pathfinder 2e",texture:"stoneD4",material:"stone",foreground:"#5c2f00",outline:"none",edge:"#f9b96e",visibility:"hidden"})}),dice3d.addSystem({id:"darkmode",name:"Dicefinder Dark Mode",colorset:"darkmode"});for(const faces of[4,6,8,10,12])dice3d.addDicePreset({type:`d${faces}`,labels:[...Array(faces)].map((_value2,idx)=>String(idx+1)),system:"darkmode",colorset:"darkmode"});dice3d.addDicePreset({type:"d100",labels:[...Array(10)].map((_value2,idx)=>String((idx+1)*10)),system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"df",labels:["-","","+"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"d20",labels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","systems/pf2e/dice/basic/nat20.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addTexture("darkModeBlack",{name:"Dark Mode Black",composite:"source-over",source:"systems/pf2e/dice/texture/transparent.webp"}).then(()=>{dice3d.addColorset({name:"darkmode",description:"Dicefinder Dark Mode",category:"Pathfinder 2e",texture:"darkModeBlack",material:"metal",foreground:"#f9b96e",outline:"none",edge:"#f9b96e",visibility:"hidden"})})}})}},DropCanvasData={listen:()=>{Hooks.on("dropCanvasData",(_canvas,data)=>{const actor=[...canvas.tokens.placeables].sort((a,b)=>b.document.sort-a.document.sort).find(token=>{const maximumX=token.x+(token.hitArea?.right??0),maximumY=token.y+(token.hitArea?.bottom??0);return data.x>=token.x&&data.y>=token.y&&data.x<=maximumX&&data.y<=maximumY})?.actor;if(actor&&data.type==="Item")return actor.sheet.emulateItemDrop(data),!1;if(actor&&data.type==="PersistentDamage"&&"formula"in data){const instances=new DamageRoll(String(data.formula)).instances.filter(i=>i.persistent),baseConditionSource=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject(),conditions=instances.map(i=>mergeObject(baseConditionSource,{system:{persistent:{formula:i.head.expression,damageType:i.type,dc:15}}}));return actor.createEmbeddedDocuments("Item",conditions),!1}return!0})}},nouislider_min="",dayInSeconds=Duration.fromObject({hours:24}).as("seconds");function darknessLevelAtTime(time){const secondsElapsed=time.diff(time.startOf("day")).as("seconds"),radians=2*Math.PI*(secondsElapsed/dayInSeconds),lightnessLevel=-1*Math.cos(radians),rad18degrees=Math.toRadians(18);return 1-(lightnessLevel>0?1:lightnessLevel<-rad18degrees?0:Math.sin((lightnessLevel+rad18degrees)/rad18degrees*Math.PI/2))}__name(darknessLevelAtTime,"darknessLevelAtTime"),__name2(darknessLevelAtTime,"darknessLevelAtTime");function intervalToTransition(interval,compactInterval){const currentDarkness=canvas.darknessLevel,targetDarkness=darknessLevelAtTime(interval.end),darknessDiff=Math.abs((currentDarkness??targetDarkness)-targetDarkness),proportionOfDay=compactInterval.length("seconds")/dayInSeconds,darkTimeMean=(darknessDiff*.5+proportionOfDay)/2;return{target:targetDarkness,duration:darkTimeMean*6e3,interval}}__name(intervalToTransition,"intervalToTransition"),__name2(intervalToTransition,"intervalToTransition");async function runAnimation(transition){if(!canvas.lighting||canvas.darknessLevel===transition.target)return;const duration=Math.min(Math.trunc(100*transition.duration)/100,6e3);await canvas.effects.animateDarkness(transition.target,{duration}),game.user.isGM&&await canvas.scene.update({darkness:transition.target})}__name(runAnimation,"runAnimation"),__name2(runAnimation,"runAnimation");async function animateDarkness(timeDiff){if(!this.syncDarkness)return;const newTime=this.worldTime,oldTime=newTime.minus({seconds:timeDiff}),fullInterval=Interval.fromDateTimes(oldTime,newTime);if(!fullInterval.isValid){await runAnimation({target:darknessLevelAtTime(newTime),duration:100,interval:fullInterval});return}const compactInterval=(()=>{if(fullInterval.length("hours")>24){const adjustedOldTime=newTime.minus({hours:24});return Interval.fromDateTimes(adjustedOldTime,newTime)}return fullInterval})(),transitionTimes=[4.75,18].map(hour=>compactInterval.start.set({hour,minute:0,second:0})).concat([4.75,18].map(hour=>compactInterval.end.set({hour,minute:0,second:0}))).filter(dateTime=>compactInterval.contains(dateTime)).concat([compactInterval.start,compactInterval.end]).sort((dtA,dtB)=>dtAdtB?1:0),transitions=transitionTimes.reduce((pairs,dateTime)=>{const index=transitionTimes.indexOf(dateTime);if(index===0)return[];const before=transitionTimes[index-1];return[...pairs,[before,dateTime]]},[]).map(pair=>Interval.fromDateTimes(pair[0],pair[1])).filter(interval=>interval.length()>0).map(interval=>intervalToTransition(interval,compactInterval));for(const transition of transitions)await runAnimation(transition)}__name(animateDarkness,"animateDarkness"),__name2(animateDarkness,"animateDarkness");var TimeChangeMode=(TimeChangeMode2=>(TimeChangeMode2[TimeChangeMode2.ADVANCE=0]="ADVANCE",TimeChangeMode2[TimeChangeMode2.RETRACT=1]="RETRACT",TimeChangeMode2))(TimeChangeMode||{});const _TimeOfDay=class _TimeOfDay2{static{__name(this,"_TimeOfDay")}constructor(hour,minute,second){this.hour=hour,this.minute=minute,this.second=second}diffSeconds(worldTime,mode){const targetTime=worldTime.set(this),targetDayDifference=_TimeOfDay2.diffDays(worldTime,targetTime,mode);return worldTime.plus({day:targetDayDifference}).set(this).diff(worldTime,"seconds").seconds}static diffDays(currentTime,targetTime,mode){return currentTime>=targetTime&&mode===0?1:currentTime<=targetTime&&mode===1?-1:0}};__name2(_TimeOfDay,"TimeOfDay"),__publicField(_TimeOfDay,"DAWN",new _TimeOfDay(4,58,54)),__publicField(_TimeOfDay,"NOON",new _TimeOfDay(12,0,0)),__publicField(_TimeOfDay,"DUSK",new _TimeOfDay(18,34,6)),__publicField(_TimeOfDay,"MIDNIGHT",new _TimeOfDay(0,0,0));let TimeOfDay=_TimeOfDay;const _WorldClock=class _WorldClock2 extends Application{static{__name(this,"_WorldClock")}ctrlKeyDown=!1;animateDarkness=animateDarkness;constructor(){super();const settingValue=game.settings.get("pf2e","worldClock.worldCreatedOn"),defaultValue=game.settings.settings.get("pf2e.worldClock.worldCreatedOn")?.default;typeof settingValue=="string"&&settingValue===defaultValue?game.settings.set("pf2e","worldClock.worldCreatedOn",settingValue):DateTime.fromISO(settingValue).isValid||game.settings.set("pf2e","worldClock.worldCreatedOn",defaultValue)}get dateTheme(){return game.settings.get("pf2e","worldClock.dateTheme")}get timeConvention(){const setting=game.settings.get("pf2e","worldClock.timeConvention");if(setting!==24&&setting!==12)throw Error("PF2e System | Unrecognized time convention");return setting}get syncDarkness(){const sceneSetting=canvas.scene?.flags.pf2e.syncDarkness??"default";return{enabled:!0,disabled:!1,default:game.settings.get("pf2e","worldClock.syncDarkness")}[sceneSetting]}get worldCreatedOn(){const value=game.settings.get("pf2e","worldClock.worldCreatedOn");return DateTime.fromISO(value).toUTC()}get worldTime(){return this.worldCreatedOn.plus({seconds:game.time.worldTime})}static get defaultOptions(){return mergeObject(super.defaultOptions,{id:"world-clock",width:400,template:"systems/pf2e/templates/system/world-clock.hbs",title:"PF2E.WorldClock.Title"})}get era(){switch(this.dateTheme){case"AR":return game.i18n.localize(CONFIG.PF2E.worldClock.AR.Era);case"AD":return this.worldTime.toFormat("G");default:return""}}get year(){const yearOffset=(()=>{switch(this.dateTheme){case"AR":return CONFIG.PF2E.worldClock.AR.yearOffset;case"AD":return CONFIG.PF2E.worldClock.AD.yearOffset;default:return 0}})();return this.worldTime.year+yearOffset}get month(){switch(this.dateTheme){case"AR":{const months=CONFIG.PF2E.worldClock.AR.Months,month=this.worldTime.setLocale("en-US").monthLong;return game.i18n.localize(months[month])}default:return this.worldTime.monthLong}}get weekday(){switch(this.dateTheme){case"AR":{const weekdays=CONFIG.PF2E.worldClock.AR.Weekdays,weekday=this.worldTime.setLocale("en-US").weekdayLong;return game.i18n.localize(weekdays[weekday])}default:return this.worldTime.weekdayLong}}getData(options){const date=this.dateTheme==="CE"?this.worldTime.toLocaleString(DateTime.DATE_HUGE):game.i18n.format(CONFIG.PF2E.worldClock.Date,{era:this.era,year:this.year,month:this.month,day:ordinalString(this.worldTime.day),weekday:this.weekday}),time=this.timeConvention===24?this.worldTime.toFormat("HH:mm:ss"):this.worldTime.toLocaleString(DateTime.TIME_WITH_SECONDS),sign=this.ctrlKeyDown?"-":"+";return{date,time,options,user:game.user,sign}}_getHeaderButtons(){return(game.user.isGM?[{label:"PF2E.SETTINGS.Settings",class:"configure-settings",icon:"fas fa-cog",onclick:()=>{const menu=game.settings.menus.get("pf2e.worldClock");if(!menu)throw ErrorPF2e("PF2e System | World Clock Settings application not found");new menu.type().render(!0)}}]:[]).concat(...super._getHeaderButtons())}static calculateIncrement(wordTime,interval,intervalMode){const mode=intervalMode==="+"?TimeChangeMode.ADVANCE:TimeChangeMode.RETRACT;switch(interval){case"dawn":return TimeOfDay.DAWN.diffSeconds(wordTime,mode);case"noon":return TimeOfDay.NOON.diffSeconds(wordTime,mode);case"dusk":return TimeOfDay.DUSK.diffSeconds(wordTime,mode);case"midnight":return TimeOfDay.MIDNIGHT.diffSeconds(wordTime,mode);default:{const sign=mode===TimeChangeMode.ADVANCE?1:-1;return Number(interval)*sign}}}activateListeners($html){super.activateListeners($html),$html.find("button[data-advance-time]").on("click",event=>{const $button=$(event.currentTarget),advanceTime=$button.data("advanceTime")??"0",advanceMode=$button.data("advanceMode")??"+",increment=_WorldClock2.calculateIncrement(this.worldTime,advanceTime,advanceMode);increment!==0&&game.time.advance(increment)}),$html.find("button[name=advance], button[name=retract]").on("click",event=>{const value=$html.find('input[type=number][name="diff-value"]').val(),unit=$html.find('select[name="diff-unit"]').val(),increment=($(event.currentTarget).attr("name")==="advance"?1:-1)*Number(value)*Number(unit);game.time.advance(increment)});for(const eventName of["keydown.pf2e.world-clock","keyup.pf2e.world-clock"])$(document).off(eventName),$(document).on(eventName,event=>{const{originalEvent}=event;if(!(originalEvent instanceof KeyboardEvent))return;const ctrlKeys=KeyboardManager.CONTROL_KEY_STRING==="\u2318"?["Control","Meta"]:["Control"];if(originalEvent.repeat||!ctrlKeys.includes(originalEvent.key)||!(event.ctrlKey||this.ctrlKeyDown))return;const retractTime=this.ctrlKeyDown=event.type==="keydown",{Advance,Retract,TimeOfDay:TimeOfDay2}=CONFIG.PF2E.worldClock.Button,advanceButtons=Array.from($html.get(0)?.querySelectorAll("button[data-advance-time]")??[]);for(const button of advanceButtons){const{advanceMode,advanceTime}=button.dataset,nextMode=advanceMode==="+"?"-":"+";button.dataset.advanceMode=nextMode;const sign=button.querySelector(".sign");if(sign&&(sign.innerHTML=nextMode),tupleHasValue(["dawn","noon","dusk","midnight"],advanceTime)){const timeOfDayKeys=nextMode==="+"?TimeOfDay2.Advance:TimeOfDay2.Retract;button.title=timeOfDayKeys[advanceTime.titleCase()]}}$html.find("button[name=advance], button[name=retract]").attr("name",retractTime?"retract":"advance").text(game.i18n.localize(retractTime?Retract:Advance))})}async close(options){$(document).off("keydown.pf2e.world-clock").off("keyup.pf2e.world-clock"),await super.close(options)}static createSyncedMessage(){const managedBy=document.createElement("span");managedBy.classList.add("managed"),managedBy.innerHTML=" ".concat(game.i18n.localize("PF2E.SETTINGS.WorldClock.SyncDarknessScene.ManagedBy"));const anchor=document.createElement("a"),wtLink=managedBy.querySelector("wt");return anchor.innerText=wtLink?.innerHTML??"",anchor.setAttribute("href",""),anchor.addEventListener("click",event=>{event.preventDefault(),event.stopPropagation();const menu=game.settings.menus.get("pf2e.worldClock");if(!menu)throw ErrorPF2e("World Clock Settings application not found");new menu.type().render(!0)}),wtLink?.replaceWith(anchor),managedBy}};__name2(_WorldClock,"WorldClock");let WorldClock=_WorldClock;const _SceneDarknessAdjuster=class extends Application{static{__name(this,"_SceneDarknessAdjuster")}constructor(){super(...arguments),__privateAdd(this,_slider,void 0),__privateAdd(this,_noRefreshHook,!1)}static get defaultOptions(){return{...super.defaultOptions,id:"darkness-adjuster",title:"CONTROLS.AdjustSceneDarkness",template:"systems/pf2e/templates/system/scene-darkness-adjuster.hbs",width:400,height:45,minimizable:!1}}async getData(options={}){return{...await super.getData(options),darknessSyncedToTime:!!game.scenes.viewed?.darknessSyncedToTime}}async render(force=!1,options={}){if(!game.scenes.viewed)return this;const bounds=ui.controls.element[0]?.querySelector("li[data-tool=darkness-adjuster]")?.getBoundingClientRect();return bounds?(options.left=bounds.right+6,options.top=bounds.top-3,this.rendered?super.render(force,options):(await super.render(force,options),await $("#darkness-adjuster").hide(0).fadeIn().promise(),this)):this}async close(options){return this.rendered?(await $("#darkness-adjuster").fadeOut().promise(),super.close(options)):super.close(options)}activateListeners($html){if(!game.scenes.viewed)return;const slider=$html[0].querySelector(".slider");if(__privateSet(this,_slider,noUiSlider.create(slider,{range:{min:0,max:1},start:[.25,game.scenes.viewed.darkness,.75],connect:[!0,!1,!1,!0],behaviour:"snap-unconstrained-snap",pips:{mode:PipsMode.Range,density:5},step:.05})),game.scenes.viewed?.darknessSyncedToTime){const synchronized=document.createElement("div");synchronized.className="message";const message=WorldClock.createSyncedMessage();synchronized.append(message),slider.append(synchronized)}slider.querySelectorAll(".noUi-origin").forEach((thumb,index)=>{index!==1&&$(thumb).attr({disabled:"disabled"}),game.scenes.viewed?.darknessSyncedToTime&&thumb.setAttribute("disabled","true")}),__privateGet(this,_slider).on("slide",(values,thumbNumber)=>{thumbNumber===1&&canvas.scene&&(__privateSet(this,_noRefreshHook,!0),canvas.colorManager.initialize({darknessLevel:Number(values[1])}),canvas.app.ticker.add(()=>{__privateSet(this,_noRefreshHook,!1)}))}),__privateGet(this,_slider).on("change",async(values,thumbNumber)=>{if(canvas.scene&&thumbNumber===1){const newValue=Number(values[1]);await canvas.scene.update({darkness:newValue},{animateDarkness:Math.round(5e3*Math.abs(canvas.scene.darkness-newValue))})}}),slider.querySelectorAll(".noUi-handle").forEach((handle,index)=>{const decoration={0:["threshold_bright-light",fontAwesomeIcon("sun")],1:["darkness-level",null],2:["threshold_darkness",fontAwesomeIcon("moon",{fixedWidth:!0})]},$handle=$(handle),[cssClass,icon]=decoration[index];icon&&$handle.append(icon),$handle.addClass(cssClass)}),slider.querySelectorAll(".noUi-connect").forEach((connect,index)=>{const classes={0:"range_bright-light",1:"range_darkness"};connect.classList.add(classes[index])})}onLightingRefresh(darkness){if(!this.rendered||__privateGet(this,_noRefreshHook))return;const sliderValues=__privateGet(this,_slider)?.get();if(__privateGet(this,_slider)&&Array.isArray(sliderValues)){const currentValue=sliderValues[1],stepValue=Math.round(darkness*20)/20;stepValue!==currentValue&&(sliderValues[1]=stepValue,__privateGet(this,_slider).set(sliderValues))}}};_slider=new WeakMap,_noRefreshHook=new WeakMap,__name2(_SceneDarknessAdjuster,"SceneDarknessAdjuster"),__publicField(_SceneDarknessAdjuster,"instance",new _SceneDarknessAdjuster);let SceneDarknessAdjuster=_SceneDarknessAdjuster;const GetSceneControlButtons={listen:()=>{Hooks.on("getSceneControlButtons",controls=>{controls.find(c=>c.name==="token")?.tools?.push({name:"worldclock",title:"CONTROLS.WorldClock",icon:"fas fa-clock",button:!0,visible:game.settings.get("pf2e","worldClock.showClockButton")&&(game.user.isGM||game.settings.get("pf2e","worldClock.playersCanView")),onClick:()=>{game.pf2e.worldClock.rendered?game.pf2e.worldClock.close({force:!0}):game.pf2e.worldClock.render(!0)}});const lightingControls=controls.find(c=>c.name==="lighting"),lightingTools=lightingControls?.tools,dayTool=lightingTools?.find(tool=>tool.name==="day");if(!(lightingControls&&lightingTools&&dayTool))return;lightingControls.visible&&SceneDarknessAdjuster.instance.rendered&&SceneDarknessAdjuster.instance.close({force:!0});const adjusterTool={name:"darkness-adjuster",title:"CONTROLS.AdjustSceneDarkness",icon:"fa-solid fa-adjust",visible:game.user.isGM&&game.settings.get("pf2e","automation.rulesBasedVision"),toggle:!0,active:!1,onClick:()=>{const adjuster=SceneDarknessAdjuster.instance;adjuster.rendered?adjuster.close({force:!0}):adjuster.render(!0)}},gmVisionTool=(()=>{const binding=game.keybindings.actions.get("pf2e.gm-vision")?.editable?.[0];if(!(binding&&game.user.isGM))return null;const gmVisionLabel=game.i18n.localize("PF2E.Keybinding.GMVision.Label"),bindingLabel=KeybindingsConfig._humanizeBinding(binding),gmVisionIcon=__name2((active=game.settings.get("pf2e","gmVision"))=>active?"fa-solid fa-lightbulb-cfl-on":"fa-solid fa-lightbulb-cfl","gmVisionIcon");return{name:"gm-vision",title:`${gmVisionLabel} [${bindingLabel}]`,icon:gmVisionIcon(),visible:game.user.isGM,toggle:!0,active:game.settings.get("pf2e","gmVision"),onClick:()=>{const newStatus=!game.settings.get("pf2e","gmVision");game.settings.set("pf2e","gmVision",newStatus);const toggle=ui.controls.control?.tools.find(t=>t.name==="gm-vision");toggle&&(toggle.active=newStatus,toggle.icon=gmVisionIcon(newStatus),ui.controls.render())}}})(),tools=[adjusterTool,gmVisionTool??[]].flat();lightingTools.splice(lightingTools?.indexOf(dayTool),0,...tools)})}},_HotbarPF2e=class _HotbarPF2e2 extends Hotbar{static{__name(this,"_HotbarPF2e")}constructor(){super(...arguments),__privateAdd(this,_hasRollOptionData)}async _onDrop(event){var _a,_b;const li=htmlClosest(event.target,".macro"),slot=Number(li?.dataset.slot)||null;if(!slot)return;const data=TextEditor.getDragEventData(event);if(!["Item","RollOption","Skill","Action"].includes(data.type??""))return super._onDrop(event);if(Hooks.call("hotbarDrop",this,data,slot)!==!1)switch(data.type==="Item"&&data.itemType==="melee"&&typeof data.index=="number"&&(data.type="Action"),data.type){case"Item":{const itemId=data.id??(isObject(data.data)?data.data._id:null),uuid=data.uuid,prefix=typeof data.pack=="string"?`Compendium.${data.pack}`:typeof data.actorId=="string"?`Actor.${data.actorId}.Item`:"Item",item=await fromUuid(uuid??`${prefix}.${itemId}`);if(!(item instanceof ItemPF2e))return;if(item.isOfType("condition","effect"))return createToggleEffectMacro(item,slot);if(uuid?.startsWith("Compendium.")){ui.notifications.error("PF2E.Macro.NoCompendiumItem",{localize:!0});return}else return __privateMethod(_a=_HotbarPF2e2,_createItemMacro,createItemMacro_fn).call(_a,item,slot)}case"RollOption":{const item=fromUuidSync(data.uuid??"");if(!(item instanceof ItemPF2e&&item.isEmbedded))throw ErrorPF2e("Unexpected error during macro creation");return __privateMethod(this,_hasRollOptionData,hasRollOptionData_fn).call(this,data)?__privateMethod(_b=_HotbarPF2e2,_createRollOptionToggleMacro,createRollOptionToggleMacro_fn).call(_b,{...data,item},slot):void 0}case"Skill":{if(!(data.actorId&&setHasElement(SKILL_ABBREVIATIONS,data.skill)))return;const skillName=data.skillName??game.i18n.localize(CONFIG.PF2E.skills[data.skill]);return createSkillMacro(data.skill,skillName,data.actorId,slot)}case"Action":return typeof data.index!="number"&&!data.elementTrait?void 0:createActionMacro({actorUUID:data.actorUUID,actionIndex:data.index,slot,elementTrait:data.elementTrait})}}};_hasRollOptionData=new WeakSet,hasRollOptionData_fn=__name2(function(data){const{label,domain,option}=data;return typeof label=="string"&&label.length>0&&typeof domain=="string"&&domain.length>0&&typeof option=="string"&&option.length>0},"#hasRollOptionData"),_createItemMacro=new WeakSet,createItemMacro_fn=__name2(async function(item,slot){const command=`game.pf2e.rollItemMacro("${item.id}");`,macro=game.macros.find(m=>m.name===item.name&&m.command===command)??await MacroPF2e.create({command,name:item.name,type:"script",img:item.img,flags:{pf2e:{itemMacro:!0}}},{renderSheet:!1});game.user.assignHotbarMacro(macro??null,slot)},"#createItemMacro"),_createRollOptionToggleMacro=new WeakSet,createRollOptionToggleMacro_fn=__name2(async function(data,slot){const name2=game.i18n.format("PF2E.ToggleWithName",{property:data.label}),escapedName=new Handlebars.SafeString(data.label),{item,domain,option}=data,command=`const item = fromUuidSync("${item.uuid}");
+${game.i18n.localize(trait.description)}`:gmNote}return traitData}async _preCreate(data,options,user){return this._source.system.equipped={carryType:"worn"},this.system.usage.type==="worn"&&!!this.system.usage.where&&this.actor?.isOfType("character")&&(this._source.system.equipped.inSlot=!1),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);for(const property of["quantity","hardness"])if(changed.system[property]!==void 0){const max=property==="quantity"?999999:999;changed.system[property]=Math.clamped(Math.trunc(Number(changed.system[property])),0,max)||0}if(handleHPChange(this,changed),isObject(changed.system.price)){const price=changed.system.price;if(isObject(price.value)){const coins=price.value;for(const denomination of DENOMINATIONS)coins[denomination]===0&&(coins[`-=${denomination}`]=null)}"per"in price&&(!price.per||Number(price.per)<=1)&&(price["-=per"]=null)}const equipped=changed.system.equipped??{};equipped.carryType==="dropped"&&this.system.equipped.invested&&(equipped.invested=!1),String(equipped.carryType??this.system.equipped.carryType).startsWith("held")||(equipped.handsHeld=0);const newUsage=getUsageDetails(String(changed.system.usage?.value??this.system.usage.value)),hasSlot=newUsage.type==="worn"&&newUsage.where,isSlotted=!!(equipped.inSlot??this.system.equipped.inSlot);return hasSlot?equipped.inSlot=isSlotted:"inSlot"in this._source.system.equipped&&(equipped["-=inSlot"]=null),super._preUpdate(changed,options,user)}}class PhysicalItemSheetPF2e extends ItemSheetPF2e{static{__name(this,"PhysicalItemSheetPF2e")}static{__name2(this,"PhysicalItemSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return options.classes.push("physical"),{...options,hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),{item}=this,bulkAdjustment=getAdjustment(item.system.bulk.value,item._source.system.bulk.value,{better:"lower"}),basePrice=new CoinsPF2e(item._source.system.price.value),priceAdjustment=getAdjustment(item.system.price.value.copperValue,basePrice.copperValue),{actionTraits:actionTraits2}=CONFIG.PF2E,rollData={...item.getRollData(),...this.actor?.getRollData()};sheetData.enrichedContent.unidentifiedDescription=await TextEditor.enrichHTML(sheetData.item.system.identification.unidentified.data.description.value,{rollData,async:!0});const activations=[];for(const action2 of item.activations){const description=await TextEditor.enrichHTML(action2.description.value,{rollData,async:!0});activations.push({action:action2,id:action2.id,base:`system.activations.${action2.id}`,description,traits:createSheetTags(actionTraits2,action2.traits??{value:[]})})}const adjustedLevelHint=(()=>{const hintText=AutomaticBonusProgression.isEnabled(this.actor)?"PF2E.Item.Weapon.FromABP":"PF2E.Item.Weapon.FromMaterialAndRunes",levelLabel=game.i18n.lang==="de"?game.i18n.localize("PF2E.LevelLabel"):game.i18n.localize("PF2E.LevelLabel").toLocaleLowerCase(game.i18n.lang);return item.level!==item._source.system.level.value?game.i18n.format(hintText,{property:levelLabel,value:item.level}):null})(),adjustedPriceHint=(()=>{if(!priceAdjustment)return null;const baseData=item._source,basePrice2=new CoinsPF2e(baseData.system.price.value).scale(baseData.system.quantity).copperValue,derivedPrice=item.assetValue.copperValue,priceLabel=game.i18n.lang==="de"?game.i18n.localize("PF2E.PriceLabel"):game.i18n.localize("PF2E.PriceLabel").toLocaleLowerCase(game.i18n.lang);return basePrice2!==derivedPrice?game.i18n.format(game.i18n.localize("PF2E.Item.Weapon.FromMaterialAndRunes"),{property:priceLabel,value:item.price.value.toString()}):null})(),localizeBulk=localizer("PF2E.Item.Physical.Bulk"),bulks=[0,.1,...Array.fromRange(50,1)].map(value=>value===0?{value,label:localizeBulk("Negligible.Label")}:value===.1?{value,label:localizeBulk("Light.Label")}:{value,label:value.toString()});return{...sheetData,itemType:game.i18n.localize("PF2E.ItemTitle"),sidebarTemplate:"systems/pf2e/templates/items/physical-sidebar.hbs",bulkAdjustment,adjustedLevelHint,basePrice,priceAdjustment,adjustedPriceHint,actionTypes:CONFIG.PF2E.actionTypes,bulks,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,sizes:omit(CONFIG.PF2E.actorSizes,["sm"]),usages:CONFIG.PF2E.usages,isPhysical:!0,activations,bulkDisabled:!!sheetData.data?.stackGroup?.trim()}}render(force,options){return!this.item.isIdentified&&!game.user.isGM?(ui.notifications.warn(this.item.description),this):super.render(force,options)}getMaterialSheetData(item,valuationData){const preciousMaterials2=CONFIG.PF2E.preciousMaterials,isSpecificMagicItem=item.isSpecific,materials=Object.entries(valuationData).reduce((result,[materialKey,materialData])=>{const validGrades=[...PRECIOUS_MATERIAL_GRADES].filter(grade=>!!materialData[grade]&&(!isSpecificMagicItem||item.system.material.type===materialKey));return validGrades.length&&(result[materialKey]={label:game.i18n.localize(preciousMaterials2[materialKey]),grades:Object.fromEntries(validGrades.map(grade=>[grade,{value:JSON.stringify({type:materialKey,grade}),label:game.i18n.localize(CONFIG.PF2E.preciousMaterialGrades[grade])}]))}),result},{});return{value:JSON.stringify(pick(this.item.material,["type","grade"])),materials}}activateListeners($html){super.activateListeners($html),$html.find("[data-action=activation-add]").on("click",event2=>{event2.preventDefault();const id=foundry.utils.randomID(16),action2={id,actionCost:{value:1,type:"action"},components:{command:!1,envision:!1,interact:!1,cast:!1},description:{value:""},traits:{value:[],custom:""}};this.item.update({[`system.activations.${id}`]:action2})}),$html.find("[data-action=activation-delete]").on("click",event2=>{event2.preventDefault();const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");Object.values(this.item.system.activations??[]).length===1&&id&&id in(this.item.system.activations??{})?this.item.update({"system.-=activations":null}):this.item.update({[`system.activations.-=${id}`]:null})}),$html.find("[data-action=activation-frequency-add]").on("click",event2=>{const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");if(id&&id in(this.item.system.activations??{})){const per=CONFIG.PF2E.frequencies.day;this.item.update({[`system.activations.${id}.frequency`]:{value:1,max:1,per}})}}),$html.find("[data-action=activation-frequency-delete]").on("click",event2=>{const id=$(event2.target).closest("[data-activation-id]").attr("data-activation-id");id&&id in(this.item.system.activations??{})&&this.item.update({[`system.activations.${id}.-=frequency`]:null})})}async _updateObject(event2,formData){formData["system.quantity"]===null&&(formData["system.quantity"]=0);const[materialType,materialGrade]=[formData["system.material.type"],formData["system.material.grade"]],typeIsValid=materialType===void 0||typeof materialType=="string"&&materialType in CONFIG.PF2E.preciousMaterials,gradeIsValid=materialGrade===void 0||typeof materialGrade=="string"&&materialGrade in CONFIG.PF2E.preciousMaterialGrades;(!typeIsValid||!gradeIsValid)&&(formData["system.material.type"]=null,formData["system.material.grade"]=null),formData["system.baseItem"]===""&&(formData["system.baseItem"]=null),"system.price.value"in formData&&(formData["system.price.value"]=CoinsPF2e.fromString(String(formData["system.price.value"])));const expanded=foundry.utils.expandObject(formData);for(const action2 of Object.values(expanded.system?.activations??[])){const actionCost=action2.actionCost;if(actionCost){const isAction=actionCost.type==="action";actionCost.value||(actionCost.value=isAction?actionCost.value||1:null)}}return super._updateObject(event2,foundry.utils.flattenObject(expanded))}}class ArmorPF2e extends PhysicalItemPF2e{static{__name(this,"ArmorPF2e")}static{__name2(this,"ArmorPF2e")}isStackableWith(item){return this.isEquipped||item.isEquipped?!1:super.isStackableWith(item)}get isBarding(){return["light-barding","heavy-barding"].includes(this.category)}get baseType(){return this.system.baseItem??null}get group(){return this.system.group||null}get category(){return this.system.category}get dexCap(){return this.system.dexCap}get strength(){return this.system.strength}get checkPenalty(){return this.system.checkPenalty||0}get speedPenalty(){return this.system.speedPenalty||0}get acBonus(){return this.system.acBonus}get isSpecific(){return!!this.system.specific}getRollOptions(prefix="armor"){const rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`category:${this.category}`]:!0,[`group:${this.group??"none"}`]:!0,[`base:${this.baseType}`]:!!this.baseType,"rune:potency":this.system.runes.potency>0,"rune:resilient":this.system.runes.resilient>0}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`),...this.system.runes.property.map(r=>`${prefix}:rune:property:${sluggify(r)}`)),rollOptions}prepareBaseData(){const systemUsage=this.system;systemUsage.usage={value:"wornarmor"},super.prepareBaseData(),AutomaticBonusProgression.cleanupRunes(this);const maxPropertySlots=getPropertyRuneSlots(this);this.system.runes.property.length=Math.min(this.system.runes.property.length,maxPropertySlots);const abpEnabled=AutomaticBonusProgression.isEnabled(this.actor),baseTraits=this.system.traits.value,investedTrait=this.system.runes.potency||this.system.runes.resilient||abpEnabled&&this.system.runes.property.length>0?"invested":null,hasTraditionTraits=baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t)),magicTrait=investedTrait&&!hasTraditionTraits?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,investedTrait,magicTrait]).sort())}prepareDerivedData(){super.prepareDerivedData();const potencyRune=this.isInvested&&!AutomaticBonusProgression.isEnabled(this.actor)?this.system.runes.potency:0,baseArmor=Number(this.system.acBonus)||0;this.system.acBonus=baseArmor+potencyRune}prepareActorData(){const{actor}=this;if(!actor)throw ErrorPF2e("This method may only be called from embedded items");if(this.isEquipped)for(const rollOption of this.getRollOptions("armor"))actor.rollOptions.all[rollOption]=!0}async getChatData(htmlOptions={}){const properties=[CONFIG.PF2E.armorCategories[this.category],`${signedInteger(this.acBonus)} ${game.i18n.localize("PF2E.ArmorArmorLabel")}`,`${this.system.dexCap||0} ${game.i18n.localize("PF2E.ArmorDexLabel")}`,`${this.system.checkPenalty||0} ${game.i18n.localize("PF2E.ArmorCheckLabel")}`,this.speedPenalty?`${this.system.speedPenalty} ${game.i18n.localize("PF2E.ArmorSpeedLabel")}`:null];return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.armorTraits),properties})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const base=this.baseType?CONFIG.PF2E.baseArmorTypes[this.baseType]:null,group=this.group?CONFIG.PF2E.armorGroups[this.group]:null,fallback="TYPES.Item.armor",itemType=game.i18n.localize(base??group??fallback);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(changed.system.acBonus!==void 0){const integerValue=Math.floor(Number(changed.system.acBonus))||0;changed.system.acBonus=Math.max(0,integerValue)}if(changed.system.group!==void 0&&(changed.system.group||=null),changed.system.dexCap!==void 0){const integerValue=Math.floor(Number(changed.system.dexCap))||0;changed.system.dexCap=Math.max(0,integerValue)}if(changed.system.checkPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.checkPenalty))||0;changed.system.checkPenalty=Math.min(0,integerValue)}if(changed.system.speedPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.speedPenalty))||0;changed.system.speedPenalty=Math.min(0,integerValue)}return super._preUpdate(changed,options,user)}}class BookPF2e extends PhysicalItemPF2e{static{__name(this,"BookPF2e")}static{__name2(this,"BookPF2e")}}class InventoryBulk{static{__name(this,"InventoryBulk")}static{__name2(this,"InventoryBulk")}actor;#value=null;encumberedAfterAddend=0;maxAddend=0;constructor(actor){this.actor=actor}get#actorStrength(){return this.actor.isOfType("character","npc")?this.actor.abilities.str.mod:1/0}get encumberedAfter(){return Math.floor(this.#actorStrength+5+this.encumberedAfterAddend)}get encumberedAfterBreakdown(){const addend=this.encumberedAfterAddend,stat=game.i18n.localize(CONFIG.PF2E.abilities.str);return`5 + ${this.#actorStrength} (${stat})`+(addend?` + ${addend}`:"")}get max(){return Math.floor(this.#actorStrength+10+this.maxAddend)}get maxBreakdown(){const addend=this.maxAddend,stat=game.i18n.localize(CONFIG.PF2E.abilities.str);return`10 + ${this.#actorStrength} (${stat})`+(addend?` + ${addend}`:"")}get value(){return this.#value?this.#value:(this.#value=InventoryBulk.computeTotalBulk(this.actor.inventory.filter(i=>!i.isInContainer),this.actor.size),this.#value)}get encumberedPercentage(){const totalTimes10=this.value.toLightUnits(),encumberedAtTimes10=this.encumberedAfter*10+10;return Math.floor(totalTimes10/encumberedAtTimes10*100)}get maxPercentage(){const totalTimes10=this.value.toLightUnits(),limitTimes10=this.max*10+10;return Math.floor(totalTimes10/limitTimes10*100)}get maxPercentageInteger(){return this.maxPercentage>100?100:this.maxPercentage}get isEncumbered(){return this.value.normal>this.encumberedAfter}get isOverMax(){return this.value.normal>this.max}get bulk(){return this.value.normal}static computeTotalBulk(items,actorSize){items=this.#flattenNonStowing(items);const nonStackingItems=items.filter(i=>i.isOfType("backpack")||i.system.bulk.per===1&&i.system.baseItem),nonStackingIds=new Set(nonStackingItems.map(i=>i.id)),stackingItems=items.filter(i=>!nonStackingIds.has(i.id)),baseBulk=nonStackingItems.map(i=>i.bulk).reduce((first,second)=>first.plus(second),new Bulk),stackingBehaviors=stackingItems.map(item=>({per:item.system.bulk.per,item,group:item.system.baseItem,bulk:new Bulk(item.system.bulk.value).convertToSize(item.size,actorSize)})),bulks=[...groupBy(stackingBehaviors,d=>`${d.group}-${d.per}-${d.bulk.toLightUnits()}`).values()].map(dataEntries=>{const{bulk,per}=dataEntries[0],quantity=dataEntries.map(entry=>entry.item.quantity).reduce((sum,value)=>sum+value,0),bulkRelevantQuantity=Math.floor(quantity/per);return bulk.times(bulkRelevantQuantity)});return baseBulk.plus(bulks.reduce((first,second)=>first.plus(second),new Bulk))}static#flattenNonStowing(items){return items.map(item=>item.isOfType("backpack")&&!item.stowsItems?this.#flattenNonStowing(item.contents.contents):item).flat()}}class ActorInventory extends DelegatedCollection{static{__name(this,"ActorInventory")}static{__name2(this,"ActorInventory")}actor;bulk;constructor(actor,entries){super(entries?.map(entry=>[entry.id,entry])),this.actor=actor,this.bulk=new InventoryBulk(this.actor)}get coins(){return this.filter(i=>i.isOfType("treasure")&&i.isCoinage).map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e)}get totalWealth(){return this.filter(item=>game.user.isGM||item.isIdentified).map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e)}get invested(){return this.actor.isOfType("character")?{value:this.filter(item=>!!item.isInvested).length,max:this.actor.system.resources.investiture.max}:null}findStackableItem(item){const testItem=item instanceof PhysicalItemPF2e?item.clone():new ItemProxyPF2e(foundry.utils.deepClone(item));if(!testItem.isOfType("physical"))return null;const stackCandidates=this.filter(i=>!i.isInContainer&&i.isStackableWith(testItem));if(stackCandidates.length===0)return null;if(stackCandidates.length>1){const notEquipped=stackCandidates.filter(item2=>!item2.isEquipped);return notEquipped.length>0?notEquipped[0]:stackCandidates[0]}else return stackCandidates[0]}async addCoins(coins,{combineStacks=!0}={}){const topLevelCoins=this.actor.itemTypes.treasure.filter(item=>combineStacks&&item.isCoinage),coinsByDenomination=groupBy(topLevelCoins,item=>item.denomination);for(const denomination of DENOMINATIONS){const quantity=coins[denomination]??0;if(quantity>0){const item=coinsByDenomination.get(denomination)?.at(0);if(item)await item.update({"system.quantity":item.quantity+quantity});else{const compendiumId=coinCompendiumIds[denomination],pack=game.packs.find(p=>p.collection==="pf2e.equipment-srd");if(!pack)throw ErrorPF2e("Unexpected error retrieving equipment compendium");const item2=(await pack.getDocument(compendiumId))?.clone();item2?.isOfType("treasure")&&(item2.updateSource({"system.quantity":quantity}),await this.actor.createEmbeddedDocuments("Item",[item2.toObject()]))}}}}async removeCoins(coins,{byValue=!0}={}){const coinsToRemove=new CoinsPF2e(coins),actorCoins=this.coins,coinsToAdd=new CoinsPF2e;if(byValue){let valueToRemoveInCopper=coinsToRemove.copperValue;if(valueToRemoveInCopper>actorCoins.copperValue)return!1;if(valueToRemoveInCopper%10>actorCoins.cp)coinsToAdd.cp=10,coinsToRemove.cp=valueToRemoveInCopper%10,valueToRemoveInCopper+=10-coinsToRemove.cp;else{coinsToRemove.cp=valueToRemoveInCopper%10,valueToRemoveInCopper-=coinsToRemove.cp;const newCopper=actorCoins.cp-coinsToRemove.cp,extraCopper=Math.min(valueToRemoveInCopper/10,Math.trunc(newCopper/10))*10;coinsToRemove.cp+=extraCopper,valueToRemoveInCopper-=extraCopper}if(valueToRemoveInCopper/10%10>actorCoins.sp)coinsToAdd.sp=10,coinsToRemove.sp=valueToRemoveInCopper/10%10,valueToRemoveInCopper+=100-coinsToRemove.sp*10;else{coinsToRemove.sp=valueToRemoveInCopper/10%10,valueToRemoveInCopper-=coinsToRemove.sp*10;const newSilver=actorCoins.sp-coinsToRemove.sp,extraSilver=Math.min(valueToRemoveInCopper/100,Math.trunc(newSilver/10))*10;coinsToRemove.sp+=extraSilver,valueToRemoveInCopper-=extraSilver*10}if(valueToRemoveInCopper/100%10>actorCoins.gp)coinsToAdd.gp=10,coinsToRemove.gp=valueToRemoveInCopper/100%10,valueToRemoveInCopper+=1e3-coinsToRemove.gp*100;else{coinsToRemove.gp=valueToRemoveInCopper/100%10,valueToRemoveInCopper-=coinsToRemove.gp*100;const newGold=actorCoins.gp-coinsToRemove.gp,extraGold=Math.min(valueToRemoveInCopper/1e3,Math.trunc(newGold/10))*10;coinsToRemove.gp+=extraGold,valueToRemoveInCopper-=extraGold*100}coinsToRemove.pp=valueToRemoveInCopper/1e3}const coinsToPull=actorCoins.add(coinsToAdd);if(!(coinsToRemove.pp<=coinsToPull.pp&&coinsToRemove.gp<=coinsToPull.gp&&coinsToRemove.sp<=coinsToPull.sp&&coinsToRemove.cp<=coinsToPull.cp))return!1;Object.values(coinsToAdd).some(value=>value!==0)&&await this.addCoins(coinsToAdd);const topLevelCoins=this.actor.itemTypes.treasure.filter(item=>item.isCoinage),coinsByDenomination=groupBy(topLevelCoins,item=>item.denomination);for(const denomination of DENOMINATIONS){let quantityToRemove=coinsToRemove[denomination];const coinItems=coinsByDenomination.get(denomination);if(quantityToRemove&&coinItems){const itemsToUpdate=[],itemsToDelete=[];for(const item of coinItems){if(quantityToRemove===0)break;if(item.quantity>quantityToRemove){itemsToUpdate.push({_id:item.id,"system.quantity":item.quantity-quantityToRemove}),quantityToRemove=0;break}else quantityToRemove-=item.quantity,itemsToDelete.push(item.id)}itemsToUpdate.length>0&&await this.actor.updateEmbeddedDocuments("Item",itemsToUpdate),itemsToDelete.length>0&&await this.actor.deleteEmbeddedDocuments("Item",itemsToDelete),quantityToRemove>0&&console.warn("Attempted to remove more coinage than exists")}}return!0}async sellAllTreasure(){const treasures=this.actor.itemTypes.treasure.filter(item=>!item.isCoinage),treasureIds=treasures.map(item=>item.id),coins=treasures.map(item=>item.assetValue).reduce((first,second)=>first.add(second),new CoinsPF2e);await this.actor.deleteEmbeddedDocuments("Item",treasureIds),await this.actor.inventory.addCoins(coins)}async add(item,options={}){if(options.stack&&item.isOfType("physical")){const stackableItem=this.findStackableItem(item._source);if(stackableItem){await stackableItem.update({"system.quantity":stackableItem.quantity+item.quantity});return}}await this.actor.createEmbeddedDocuments("Item",[item.toObject()])}}class ContainerPF2e extends PhysicalItemPF2e{static{__name(this,"ContainerPF2e")}static{__name2(this,"ContainerPF2e")}contents=new Collection;get stowsItems(){return this.system.stowing}get isCollapsed(){return this.system.collapsed}get capacity(){return{value:InventoryBulk.computeTotalBulk(this.contents.contents,this.actor?.size??"med"),max:new Bulk(this.system.bulk.capacity)}}get percentFull(){const{value,max}=this.capacity,realPercent=Math.floor(value.toLightUnits()/max.toLightUnits()*100);return realPercent>100?Math.floor(value.normal/max.normal*100):realPercent}get bulkIgnored(){const isOverfilled=this.percentFull>100,extradimensionalParadox=this.traits.has("extradimensional")&&hasExtraDimensionalParent(this);return!isOverfilled&&!extradimensionalParadox?new Bulk(this.system.bulk.ignored):new Bulk}get bulk(){return super.bulk.plus(this.capacity.value.minus(this.bulkIgnored))}prepareSiblingData(){super.prepareSiblingData(),this.contents=new Collection(this.actor.inventory.filter(i=>i.container?.id===this.id).map(item=>[item.id,item]))}async ejectContents(){if(!this.actor)return;const updates=this.contents.map(i=>({_id:i.id,"system.containerId":this.container?.id??null}));await this.actor.updateEmbeddedDocuments("Item",updates,{render:!1})}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.equipmentTraits)})}_preUpdate(changed,options,user){if(!changed.system?.bulk)return super._preUpdate(changed,options,user);changed.system.bulk.heldOrStowed!==void 0&&(changed.system.bulk.heldOrStowed=Math.clamped(Number(changed.system.bulk.heldOrStowed),0,999)||0,Number.isInteger(changed.system.bulk.heldOrStowed)||(changed.system.bulk.heldOrStowed=.1));for(const property of["capacity","ignored"])changed.system.bulk[property]!==void 0&&(changed.system.bulk[property]=Math.clamped(Math.trunc(Number(changed.system.bulk[property])),0,999)||0);return super._preUpdate(changed,options,user)}}class EquipmentPF2e extends PhysicalItemPF2e{static{__name(this,"EquipmentPF2e")}static{__name2(this,"EquipmentPF2e")}get otherTags(){return new Set(this.system.traits.otherTags)}prepareBaseData(){super.prepareBaseData(),this.system.apex&&(this.traits.has("apex")?this.isInvested||(this.system.apex.selected=!1):delete this.system.apex)}prepareSiblingData(){if(super.prepareSiblingData(),!this.system.apex)return;const otherApexData=this.actor.itemTypes.equipment.flatMap(e=>e===this?[]:e.system.apex??[]);if(this.system.apex.selected||this.isInvested&&otherApexData.every(d=>!d.selected)){this.system.apex.selected=!0;for(const data of otherApexData)data.selected=!1}}prepareActorData(){const{actor}=this;actor?.isOfType("character")&&this.system.apex?.selected&&(actor.system.build.attributes.apex?this.system.apex.selected=!1:actor.system.build.attributes.apex=this.system.apex.attribute)}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.equipmentTraits)})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const identificationConfig=CONFIG.PF2E.identification,slotType=/book\b/.test(this.slug??"")?"Book":/\bring\b/.test(this.slug??"")?"Ring":this.system.usage.value?.replace(/^worn/,"").capitalize()??"",itemType=objectHasKey(identificationConfig.UnidentifiedType,slotType)?game.i18n.localize(identificationConfig.UnidentifiedType[slotType]):game.i18n.localize(identificationConfig.UnidentifiedType.Object);return typeOnly?itemType:game.i18n.format(identificationConfig.UnidentifiedItem,{item:itemType})}async _preCreate(data,options,user){return delete this._source.system.apex?.selected,super._preCreate(data,options,user)}async _preUpdate(changed,options,user){const changedTraits=changed.system?.traits?.value;return!(this._source.system.traits.value.includes("apex")&&(!Array.isArray(changedTraits)||changedTraits.includes("apex")))&&this._source.system.apex&&(delete changed.system?.apex,changed.system??={},changed.system=foundry.utils.mergeObject(changed.system,{"-=apex":null})),super._preUpdate(changed,options,user)}}class TreasurePF2e extends PhysicalItemPF2e{static{__name(this,"TreasurePF2e")}static{__name2(this,"TreasurePF2e")}get isCoinage(){return this.system.stackGroup==="coins"}get denomination(){if(!this.isCoinage)return null;const options=DENOMINATIONS.filter(denomination=>!!this.price.value[denomination]);return options.length===1?options[0]:null}prepareBaseData(){super.prepareBaseData(),this.isCoinage&&(this.system.size="med")}async getChatData(htmlOptions={}){const systemData=this.system,traits=this.traitChatData({});return this.processChatData(htmlOptions,{...systemData,traits})}}class WeaponPF2e extends PhysicalItemPF2e{static{__name(this,"WeaponPF2e")}static{__name2(this,"WeaponPF2e")}constructor(data,context={}){super(data,context),context.shield&&(this.shield=context.shield)}altUsageType=null;get isEquipped(){const{category,slug,traits}=this.system;return category==="unarmed"&&slug!=="handwraps-of-mighty-blows"?!0:super.isEquipped||this.handsHeld===1&&traits.value.some(t=>/^jousting-d\d{1,2}$/.test(t))}isStackableWith(item){if(this.category==="unarmed"||!item.isOfType("weapon")||item.category==="unarmed")return!1;const equippedButStackable=["bomb","dart"].includes(this.group??"");return(this.isEquipped||item.isEquipped)&&!equippedButStackable?!1:super.isStackableWith(item)}get baseType(){return this.system.baseItem}get group(){return this.system.group}get category(){return this.system.category}get defaultAttribute(){return this.system.attribute??(this.isRanged?"dex":"str")}get hands(){return{worngloves:"0","held-in-one-hand":"1","held-in-one-plus-hands":"1+","held-in-two-hands":"2"}[this.system.usage.value]??"1"}get maxRange(){return this.system.maxRange??(this.system.range?this.system.range*6:null)}get range(){const rangeIncrement=this.system.range,maxRange=this.system.maxRange;return maxRange?{increment:null,max:maxRange}:rangeIncrement?{increment:rangeIncrement,max:rangeIncrement*6}:null}get reload(){return this.system.reload.value||null}get isSpecific(){return!!this.system.specific}get isMelee(){return!this.isRanged}get isRanged(){return!!this.system.range}get isThrown(){return this.isRanged&&(this.baseType==="alchemical-bomb"||this.system.traits.value.includes("thrown"))}get isThrowable(){return this.isThrown||this.system.traits.value.some(t=>t.startsWith("thrown"))||!!this.system.meleeUsage?.traits.some(t=>t.startsWith("thrown"))}get isOversized(){return this.category!=="unarmed"&&!!this.parent?.system.traits?.size.isSmallerThan(this.size,{smallIsMedium:!0})}get baseDamage(){return{...foundry.utils.deepClone(this.system.damage),damageType:this.system.traits.toggles.versatile.selection??this.system.traits.toggles.modular.selection??this.system.damage.damageType}}get dealsDamage(){const{baseDamage}=this;return baseDamage.dice>0||baseDamage.modifier>0||this.system.splashDamage.value>0||!!baseDamage.persistent?.number}get requiresAmmo(){return this.isRanged&&!this.isThrown&&![null,"-"].includes(this.reload)}get ammo(){const ammo=this.actor?.items.get(this.system.selectedAmmoId??"");return ammo?.isOfType("consumable","weapon")?ammo:null}get otherTags(){return new Set(this.system.traits.otherTags)}isAmmoFor(weapon){return this.system.usage.canBeAmmo&&!weapon.system.traits.value.includes("repeating")}getRollOptions(prefix=this.type){const{baseDamage}=this,damage={category:DamageCategorization.fromDamageType(baseDamage.damageType),type:baseDamage.damageType,dice:{number:baseDamage.die?baseDamage.dice:0,faces:Number(baseDamage.die?.replace(/^d/,""))}},{actor}=this,isDeityFavored=!!(this.baseType&&actor?.isOfType("character")&&actor.deity?.favoredWeapons.includes(this.baseType)),thrownMelee=this.isThrown&&this.altUsageType==="thrown",baseTypeRollOptions=(()=>{const equivalentBases=CONFIG.PF2E.equivalentWeapons;return[this.baseType??[],equivalentBases[this.baseType??""]??[]].flat().reduce((types,t)=>({...types,[`base:${t}`]:!0}),{})})(),{persistent}=this.system.damage,propertyRunes=mapToObj(this.system.runes.property,p=>[`rune:property:${sluggify(p)}`,!0]),ammunitionRollOptions=(ammunition=>{const rollOptions2={};if(ammunition){rollOptions2[`ammo:id:${ammunition.id}`]=!0,rollOptions2[`ammo:slug:${ammunition.slug}`]=!0,rollOptions2[`ammo:level:${ammunition.level}`]=!0,rollOptions2[`ammo:material:type:${ammunition.material.type}`]=!!ammunition.material.type,rollOptions2[`ammo:material:grade:${ammunition.material.grade}`]=!!ammunition.material.grade;for(const trait of ammunition.traits)rollOptions2[`ammo:trait:${trait}`]=!0}return rollOptions2})(this.ammo),bulk=(()=>{const unitBulk=this.bulk.times(1/this.quantity);return unitBulk.isNegligible?"negligible":unitBulk.isLight?"light":unitBulk.toString()})(),rangeIncrement=this.range?.increment,rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`category:${this.category}`]:!0,[`group:${this.group??"none"}`]:!0,...baseTypeRollOptions,[`base:${this.baseType}`]:!!this.baseType,[`bulk:${bulk}`]:!0,[`usage:hands:${this.hands}`]:this.hands!=="0",[`range-increment:${rangeIncrement}`]:!!rangeIncrement,[`reload:${this.reload}`]:!!this.reload,[`damage:type:${damage.type}`]:!0,[`damage:category:${damage.category}`]:!!damage.category,[`damage:die:number:${damage.dice.number}`]:!!damage.dice.faces,[`damage:die:faces:${damage.dice.faces}`]:!!damage.dice.faces,[`damage-dice:${damage.dice.number}`]:!!damage.dice.faces,[`damage:persistent:${persistent?.type}`]:!!persistent,"deity-favored":isDeityFavored,oversized:this.isOversized,melee:this.isMelee,ranged:this.isRanged,thrown:this.isThrown,"thrown-melee":thrownMelee,...propertyRunes,...ammunitionRollOptions}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}prepareBaseData(){super.prepareBaseData(),this.system.category||="simple",this.system.group||=null,this.system.baseItem||=null,this.system.bonusDamage.value||=0,this.system.splashDamage.value||=0,this.system.graspingAppendage=["fist","claw"].includes(this.baseType??"")?!0:this.category==="unarmed"?!!this.system.graspingAppendage:!1,setHasElement(ATTRIBUTE_ABBREVIATIONS,this.system.attribute)||(this.system.attribute=null);const reloadValue=this.system.reload.value||=null;this.system.reload.label=reloadValue?game.i18n.format("PF2E.Item.Weapon.Reload.LabelN",{value:CONFIG.PF2E.weaponReload[reloadValue]}):null,this.system.selectedAmmoId||=null,this.system.damage.die||=null,this.system.damage.modifier??=0,!this.system.damage.die&&this.system.damage.dice>0&&(this.system.damage.modifier||=this.system.damage.dice),this.isThrown&&!tupleHasValue(["-","0"],this.system.reload.value)&&(this.system.reload.value="-"),this.system.category==="unarmed"&&!this.system.traits.value.includes("unarmed")&&this.system.traits.value.push("unarmed"),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.npcAttackTraits);const traitSet=this.traits,mandatoryRanged=setHasElement(MANDATORY_RANGED_GROUPS,this.system.group)||traitSet.has("thrown");mandatoryRanged&&(this.system.range??=10),this.system.meleeUsage&&(this.system.meleeUsage.traits??=[],this.system.meleeUsage.traitToggles??={modular:null,versatile:null}),this.system.traits.toggles=new WeaponTraitToggles(this);const traitsArray=this.system.traits.value;this.system.category==="unarmed"&&!traitsArray.includes("unarmed")&&this.system.traits.value.push("unarmed"),!mandatoryRanged&&traitsArray.some(t=>/^thrown-\d+$/.test(t))&&(this.system.range=null),this.system.reload.consume=this.isMelee?null:this.reload!==null,this.system.usage.canBeAmmo=this._source.system.usage.canBeAmmo??!1,this.flags.pf2e.comboMeleeUsage??=!1,AutomaticBonusProgression.cleanupRunes(this);const{runes}=this.system;runes.effects=[],runes.property.length=Math.min(runes.property.length,getPropertyRuneSlots(this));const{actor}=this,inherentDiceNumber=this.system.damage.die?this._source.system.damage.dice:0,strikingDice=AutomaticBonusProgression.isEnabled(actor)?AutomaticBonusProgression.getStrikingDice(actor?.level??0):this.system.runes.striking;this.system.damage.dice=inherentDiceNumber===1&&!this.flags.pf2e.battleForm?inherentDiceNumber+strikingDice:this.system.damage.dice;const baseTraits=this.system.traits.value,magicTrait=(runes.potency>0||runes.striking>0||runes.property.length>0)&&!baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t))?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,magicTrait]).sort()),this.flags.pf2e.attackItemBonus=this.system.runes.potency||this.system.bonus.value||0}prepareDerivedData(){super.prepareDerivedData(),this.system.usage.canBeAmmo&&!this.isThrowable&&(this.system.usage.canBeAmmo=!1)}prepareSiblingData(){super.prepareSiblingData();const ammoRules=this.ammo?.system.rules.map(r=>({label:this.ammo?.name,...foundry.utils.deepClone(r)}))??[];this.system.rules.push(...ammoRules)}async getChatData(htmlOptions={}){const traits=this.traitChatData(CONFIG.PF2E.weaponTraits),chatData=await super.getChatData(),rangeLabel=createActionRangeLabel(this.range),properties=compact([CONFIG.PF2E.weaponCategories[this.category],this.system.reload.label,rangeLabel]);return this.processChatData(htmlOptions,{...chatData,traits,properties})}getMystifiedData(status,{source=!1}={}){const mystifiedData=super.getMystifiedData(status);return source&&(mystifiedData.name=this._source.name),mystifiedData}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const baseWeaponTypes2=CONFIG.PF2E.baseWeaponTypes,baseShieldTypes2=CONFIG.PF2E.baseShieldTypes,base=this.baseType?baseWeaponTypes2[this.baseType]??baseShieldTypes2[this.baseType]??null:null,group=this.group?CONFIG.PF2E.weaponGroups[this.group]:null,itemType=game.i18n.localize(base??group??"TYPES.Item.weapon");return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}getAltUsages({recurse=!0}={}){const meleeUsage=this.toMeleeUsage();return[this.toThrownUsage()??[],meleeUsage??[],recurse?meleeUsage?.toThrownUsage()??[]:[]].flat()}clone(data,context){const clone=super.clone(data,context);return context?.altUsage&&clone instanceof WeaponPF2e&&(clone.altUsageType=context.altUsage),clone}toThrownUsage(){const traits=this._source.system.traits.value,thrownTrait=traits.find(t=>/^thrown-\d{1,3}$/.test(t));if(this.isRanged||!thrownTrait)return null;const range2=Number(/(\d{1,3})$/.exec(thrownTrait)?.at(1)),newTraits=foundry.utils.deepClone(traits);newTraits.splice(newTraits.indexOf(thrownTrait),1,"thrown");const overlay={system:{range:range2,traits:{value:newTraits}}};return this.clone(overlay,{keepId:!0,altUsage:"thrown"})}toMeleeUsage(){const{meleeUsage}=this.system;if(!meleeUsage||this.flags.pf2e.comboMeleeUsage)return null;const traitToggles={module:{selection:meleeUsage.traitToggles.modular},versatile:{selection:meleeUsage.traitToggles.versatile}},overlay={system:{damage:{damageType:meleeUsage.damage.type,dice:1,die:meleeUsage.damage.die},group:meleeUsage.group,range:null,reload:{value:null},traits:{value:meleeUsage.traits.concat("combination"),toggles:traitToggles},selectedAmmoId:null},flags:{pf2e:{comboMeleeUsage:!0}}};return this.clone(overlay,{keepId:!0,altUsage:"melee"})}toNPCAttacks({keepId=!1}={}){const{actor}=this;if(!actor.isOfType("npc"))throw ErrorPF2e("Melee items can only be generated for NPCs");const baseDamage=(()=>{const weaponDamage=this.baseDamage,ability=this.range?.increment&&!this.isThrown?"dex":"str",actorLevel=actor.system.details.level.base,dice=this.flags.pf2e.fixedAttack?weaponDamage.dice:[1,2,3,4].reduce((closest,dice2)=>Math.abs(dice2-Math.round((actorLevel+2)/4)){const fromAbility=actor.abilities[ability].mod,totalModifier=this.flags.pf2e.fixedAttack?weaponDamage.modifier:fromAbility+(actor.level>1?dice:0),sign=totalModifier<0?"-":"+";return totalModifier===0?"":[sign,Math.abs(totalModifier)].join("")})();return{damage:weaponDamage.die?`${dice}${weaponDamage.die}${constant}`:dice.toString(),damageType:weaponDamage.damageType,category:null}})(),fromPropertyRunes=this.system.runes.property.flatMap(r=>RUNE_DATA.weapon.property[r].damage?.dice??[]).map(d=>({damage:`${d.diceNumber}${d.dieSize}`,damageType:d.damageType??baseDamage.damageType,category:d.category??null})),reachTraitToNPCReach={tiny:null,sm:"reach-10",med:"reach-10",lg:"reach-15",huge:"reach-20",grg:"reach-25"},toAttackTraits=__name2(traits=>{const{increment:rangeIncrement,max:maxRange}=this.range??{},newTraits=traits.flatMap(t=>t==="reach"?reachTraitToNPCReach[this.size]??[]:t==="thrown"&&setHasElement(THROWN_RANGES,rangeIncrement)?`thrown-${rangeIncrement}`:t).filter(t=>(["holy","unholy"].includes(t)||!(t in CONFIG.PF2E.creatureTraits))&&!(t.startsWith("thrown")&&!this.isThrown)&&!(["grapple","finesse","shove","trip"].includes(t)&&this.isRanged)&&!(t==="brutal"&&this.isMelee)&&!(t==="combination"&&(this.isMelee||this.isThrown))&&!(t==="critical-fusion"&&this.isThrown)&&!["artifact","cursed"].includes(t));if(traits.some(t=>setHasElement(MAGIC_TRADITIONS,t))&&newTraits.push("magical"),rangeIncrement&&!this.isThrown){const prefix=maxRange===rangeIncrement*6?"range-increment":"range";newTraits.push(`${prefix}-${rangeIncrement}`)}const sizeToReach=SIZE_TO_REACH[actor.size];this.isMelee&&sizeToReach!==5&&!newTraits.some(t=>t.startsWith("reach"))&&newTraits.push(`reach-${sizeToReach}`);const reloadTrait=`reload-${this.reload}`;return objectHasKey(CONFIG.PF2E.npcAttackTraits,reloadTrait)&&newTraits.push(reloadTrait),uniq(newTraits).sort()},"toAttackTraits"),persistentDamage=(()=>{const{persistent}=this.system.damage;return persistent?{damage:persistent.faces?`${persistent.number}d${persistent.faces}`:persistent.number.toString(),damageType:persistent.type,category:"persistent"}:[]})(),splashDamage=this.system.splashDamage.value?{damage:this.system.splashDamage.value.toString(),damageType:this.system.damage.damageType,category:"splash"}:[],source={_id:keepId?this.id:null,name:this._source.name,type:"melee",system:{slug:this.slug??sluggify(this._source.name),weaponType:{value:this.isMelee?"melee":"ranged"},bonus:{value:this.flags.pf2e.fixedAttack||Math.round(1.5*this.actor.level+7)},damageRolls:[baseDamage,splashDamage,fromPropertyRunes,persistentDamage].flat().reduce((rolls,roll)=>foundry.utils.mergeObject(rolls,{[foundry.utils.randomID()]:roll}),{}),traits:{value:toAttackTraits(this.system.traits.value)},rules:foundry.utils.deepClone(this._source.system.rules)},flags:{pf2e:{linkedWeapon:this.id}}},attack=new MeleePF2e(source,{parent:this.actor});return attack.category=this.category,attack.group=this.group,attack.baseType=this.baseType,[attack,...this.getAltUsages({recurse:!1}).flatMap(u=>u.toNPCAttacks())]}async consumeAmmo(){const{ammo}=this;if(ammo?.isOfType("consumable"))return ammo.consume();if(ammo?.isOfType("weapon")){if(!ammo.system.usage.canBeAmmo)throw ErrorPF2e("attempted to consume weapon not usable as ammunition");await ammo.update({"system.quantity":Math.max(ammo.quantity-1,0)})}}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const traits=changed.system.traits??{};return"value"in traits&&Array.isArray(traits.value)&&(traits.value=traits.value.filter(t=>t in CONFIG.PF2E.weaponTraits)),changed.system.group!==void 0&&(changed.system.group||=null),super._preUpdate(changed,options,user)}_onDelete(options,userId){if(super._onDelete(options,userId),game.user.id===userId){const updates=this.actor?.itemTypes.melee.filter(a=>a.flags.pf2e.linkedWeapon===this.id).map(a=>({_id:a.id,"flags.pf2e.-=linkedWeapon":null}))??[];this.actor?.updateEmbeddedDocuments("Item",updates)}}}class ABCItemPF2e extends ItemPF2e{static{__name(this,"ABCItemPF2e")}static{__name2(this,"ABCItemPF2e")}get rarity(){return this.system.traits.rarity}getLinkedItems(){if(!this.actor||!objectHasKey(this.actor.itemTypes,this.type))return[];const existingABCIds=this.actor.itemTypes[this.type].map(i=>i.id);return this.actor.itemTypes.feat.filter(f=>existingABCIds.includes(f.system.location??""))}async createGrantedItems(options={}){const entries=Object.values(this.system.items);if(!entries.filter(entry=>!!entry.uuid).length)return[];const items=(await UUIDUtils.fromUUIDs(entries.map(e=>e.uuid))).map(i=>i.clone()),level=options.level??this.parent?.level;return items.flatMap(item=>{if(item instanceof FeatPF2e){if(item.category==="classfeature"){const level2=entries.find(e=>item.sourceId===e.uuid)?.level??item.level;item.updateSource({"system.level.value":level2})}return level!==void 0&&levelboost.value.length===1).map(boost=>boost.selected).filter(boost=>!!boost)}get lockedFlaws(){return Object.values(this.system.flaws).map(flaw=>flaw.selected).filter(flaw=>!!flaw)}getLinkedItems(){return this.actor?Array.from(new Set([...super.getLinkedItems(),...this.actor.itemTypes.feat.filter(f=>f.category==="ancestryfeature")])):[]}prepareBaseData(){super.prepareBaseData();for(const boost of Object.values(this.system.boosts))boost.value.length===1&&(boost.selected=boost.value[0]);for(const flaw of Object.values(this.system.flaws))flaw.value.length===1&&(flaw.selected=flaw.value[0])}prepareActorData(){const{actor}=this;if(!actor.isOfType("character")){console.error("PF2e System | Only a character can have an ancestry");return}actor.ancestry=this,actor.system.attributes.ancestryhp=this.hitPoints,this.logAutoChange("system.attributes.ancestryhp",this.hitPoints),actor.system.traits.size.value=this.size,this.logAutoChange("system.traits.size.value",this.size);const reach=SIZE_TO_REACH[this.size];actor.system.attributes.reach={base:reach,manipulate:reach},actor.system.attributes.speed.value=this.speed;const{build}=actor.system;if(this.system.alternateAncestryBoosts)build.attributes.boosts.ancestry.push(...this.system.alternateAncestryBoosts);else for(const target of["boosts","flaws"])for(const ability of Object.values(this.system[target]))ability.selected&&build.attributes[target].ancestry.push(ability.selected);if(this.system.voluntary){const{boost,flaws}=this.system.voluntary;boost&&build.attributes.boosts.ancestry.push(boost),build.attributes.flaws.ancestry.push(...flaws)}const innateLanguages=this.system.languages.value;for(const language of innateLanguages)language in CONFIG.PF2E.languages&&!actor.system.traits.languages.value.includes(language)&&actor.system.traits.languages.value.push(language);const{senses:senses2}=actor.system.traits,{vision}=this.system;if(!(vision==="normal"||senses2.some(sense=>sense.type===vision))){senses2.push(new CreatureSensePF2e({type:vision,value:"",source:this.name}));const senseRollOptions=actor.rollOptions.sense??={};senseRollOptions[`self:${sluggify(vision)}:from-ancestry`]=!0}actor.system.traits.value.push(...this.traits);const slug=this.slug??sluggify(this.name);actor.system.details.ancestry={name:this.name,trait:slug,adopted:null,versatile:null,countsAs:[slug]},actor.rollOptions.all[`self:ancestry:${slug}`]=!0;for(const trait of this.traits)actor.rollOptions.all[`self:trait:${trait}`]=!0}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),`${prefix}:rarity:${this.rarity}`]}}class BackgroundPF2e extends ABCItemPF2e{static{__name(this,"BackgroundPF2e")}static{__name2(this,"BackgroundPF2e")}get traits(){return new Set(this.system.traits.value)}prepareSiblingData(){if(Object.keys(this.system.items).length>0)return;const grantedSkillFeat=Object.values(this.flags.pf2e.itemGrants).flatMap(g=>this.actor.items.get(g.id)??[]).find(i=>i.isOfType("feat")&&i.category==="skill");grantedSkillFeat&&(this.system.items.GRANT={uuid:grantedSkillFeat.sourceId??grantedSkillFeat.uuid,img:grantedSkillFeat.img,name:grantedSkillFeat.name,level:1},grantedSkillFeat.system.level.taken=1,grantedSkillFeat.system.location=this.id)}prepareActorData(){if(!this.actor.isOfType("character")){console.error("Only a character can have a background");return}this.actor.background=this;const{build}=this.actor.system,boosts=Object.values(this.system.boosts);for(const boost of boosts)boost.selected&&build.attributes.boosts.background.push(boost.selected);const{trainedSkills}=this.system;if(trainedSkills.value.length===1){const key=trainedSkills.value[0],skill=this.actor.system.skills[key];skill.rank=Math.max(skill.rank,1)}}}class ClassPF2e extends ABCItemPF2e{static{__name(this,"ClassPF2e")}static{__name2(this,"ClassPF2e")}get attacks(){return this.system.attacks}get defenses(){return this.system.defenses}get hpPerLevel(){return this.system.hp}get perception(){return this.system.perception}get savingThrows(){return this.system.savingThrows}get grantedFeatSlots(){const system=this.system;return{ancestry:foundry.utils.deepClone(system.ancestryFeatLevels.value),class:[...system.classFeatLevels.value],skill:[...system.skillFeatLevels.value],general:[...system.generalFeatLevels.value]}}getLinkedItems(){const{actor}=this;return actor?Array.from(new Set([...super.getLinkedItems(),...actor.itemTypes.feat.filter(f=>f.category==="classfeature"&&!(f.flags.pf2e.grantedBy&&actor.items.has(f.flags.pf2e.grantedBy.id)))])):[]}async createGrantedItems(options={}){return(await super.createGrantedItems(options)).sort((a,b)=>a.system.level.value-b.system.level.value)}prepareBaseData(){super.prepareBaseData();const{keyAbility}=this.system;keyAbility.selected??=keyAbility.value.length===1?keyAbility.value[0]:null}prepareActorData(){if(!this.actor?.isOfType("character")){console.error("Only a character can have a class");return}this.actor.class=this;const{attributes,build,details,proficiencies,saves,skills}=this.actor.system,slug=this.slug??sluggify(this.name);build.attributes.keyOptions=[...this.system.keyAbility.value],build.attributes.boosts.class=this.system.keyAbility.selected,attributes.classhp=this.hpPerLevel,attributes.perception.rank=Math.max(attributes.perception.rank,this.perception),this.logAutoChange("system.attributes.perception.rank",this.perception),details.keyability.value=(build.attributes.manual?details.keyability.value:build.attributes.boosts.class)??"str";const classDCs=proficiencies.classDCs;classDCs[slug]={label:this.name,rank:1,ability:details.keyability.value,primary:!0},this.logAutoChange(`system.proficiencies.classDCs.${slug}.rank`,1);const{attacks,defenses}=proficiencies;for(const category of WEAPON_CATEGORIES)attacks[category].rank=Math.max(attacks[category].rank,this.attacks[category]),this.logAutoChange(`system.proficiencies.attacks.${category}.rank`,this.attacks[category]);const nonBarding=Array.from(ARMOR_CATEGORIES).filter(c=>!["light-barding","heavy-barding"].includes(c));for(const category of nonBarding)defenses[category].rank=Math.max(defenses[category].rank,this.defenses[category]),this.logAutoChange(`system.proficiencies.defenses.${category}.rank`,this.defenses[category]);for(const saveType of SAVE_TYPES)saves[saveType].rank=Math.max(saves[saveType].rank,this.savingThrows[saveType]),this.logAutoChange(`system.saves.${saveType}.rank`,this.savingThrows[saveType]);for(const trainedSkill of this.system.trainedSkills.value)setHasElement(SKILL_ABBREVIATIONS,trainedSkill)&&(skills[trainedSkill].rank=Math.max(skills[trainedSkill].rank,1));proficiencies.spellcasting.rank=Math.max(proficiencies.spellcasting.rank,this.system.spellcasting),this.logAutoChange("system.proficiencies.spellcasting.rank",this.system.spellcasting),details.class={name:this.name,trait:slug},this.actor.rollOptions.all[`class:${slug}`]=!0}}class AbilityItemPF2e extends ItemPF2e{static{__name(this,"AbilityItemPF2e")}static{__name2(this,"AbilityItemPF2e")}range=null;get traits(){return new Set(this.system.traits.value)}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}prepareBaseData(){super.prepareBaseData(),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max),this.system.selfEffect??=null,this.system.actionType.value==="passive"&&(this.system.selfEffect=null),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.actionTraits)}onPrepareSynthetics(){processSanctification(this)}getRollOptions(prefix=this.type){const options=super.getRollOptions(prefix);return(this.frequency||this.system.deathNote)&&options.push(`${prefix}:frequency:limited`),options}async getChatData(htmlOptions={}){return this.processChatData(htmlOptions,{...this.system,traits:this.traitChatData(CONFIG.PF2E.featTraits)})}async _preCreate(data,options,user){return this.parent||this._source.system.frequency&&this.updateSource({"system.frequency.-=value":null}),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){return typeof changed.system?.category=="string"&&(changed.system.category||=null),normalizeActionChangeData(this,changed),super._preUpdate(changed,options,user)}}const KINGDOM_CATEGORY_DATA={"army-tactic":{behavior:"feat",levelLabel:"PF2E.Kingmaker.Feature.Tactic"},"army-war-action":{behavior:"activity"},"kingdom-feat":{behavior:"feat"},"kingdom-feature":{behavior:"feature"},"kingdom-activity":{behavior:"activity"}},KINGMAKER_CATEGORY_TYPES=Object.keys(KINGDOM_CATEGORY_DATA),KINGMAKER_CATEGORIES=mapToObj(KINGMAKER_CATEGORY_TYPES,type=>[type,`PF2E.Kingmaker.Feature.Categories.${type}`]);class CampaignFeaturePF2e extends ItemPF2e{static{__name(this,"CampaignFeaturePF2e")}static{__name2(this,"CampaignFeaturePF2e")}granter=null;get category(){return this.system.category}get level(){return this.behavior!=="activity"?this.system.level?.value??0:null}get traits(){return new Set(this.system.traits.value)}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}get isAction(){return this.behavior==="activity"}get isFeature(){return this.behavior==="feature"}get isFeat(){return this.behavior==="feat"}prepareBaseData(){super.prepareBaseData();const categoryData=KINGDOM_CATEGORY_DATA[this.category]??Object.values(KINGDOM_CATEGORY_DATA)[0];this.behavior=categoryData.behavior,this.group=null,this.levelLabel=categoryData.levelLabel??(this.isFeat?"PF2E.Item.Feat.LevelLabel":"PF2E.LevelLabel"),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max)}prepareActorData(){const prefix=this.isFeature?"feature":this.isFeat?"feat":null;if(prefix){const slug=this.slug??sluggify(this.name);this.actor.rollOptions.all[`${prefix}:${slug}`]=!0}}prepareSiblingData(){const itemGrants=this.flags.pf2e.itemGrants;this.grants=Object.values(itemGrants).flatMap(grant=>{const item=this.actor?.items.get(grant.id);return item?.isOfType("campaignFeature")?(item.granter=this,[item]):[]})}getRollOptions(prefix=null){return prefix??=this.isFeature?"feature":this.isFeat?"feat":"action",compact([...super.getRollOptions(prefix).filter(o=>!o.endsWith("level:0")),`${prefix}:category:${this.category}`,this.isAction?`action:${this.slug}`:null])}async _preCreate(data,options,user){return this.parent||(this.updateSource({"system.location":null}),this._source.system.frequency&&this.updateSource({"system.frequency.-=value":null})),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(typeof changed.system?.location=="string"&&(changed.system.location||=null),normalizeActionChangeData(this,changed),changed.system&&changed.system.category){const system=changed.system,category=tupleHasValue(KINGMAKER_CATEGORY_TYPES,changed.system.category)?changed.system.category:KINGMAKER_CATEGORY_TYPES[0];if(KINGDOM_CATEGORY_DATA[category].behavior==="activity")"level"in this.system&&(system["-=level"]=null);else{const level=system.level?.value??this.system.level?.value??0;system.level={value:level}}}await super._preUpdate(changed,options,user)}}class TrickMagicItemPopup{static{__name(this,"TrickMagicItemPopup")}static{__name2(this,"TrickMagicItemPopup")}item;checkDC;#localize=localizer("PF2E.TrickMagicItemPopup");constructor(item){if(!item.isOfType("consumable"))throw ErrorPF2e("Unexpected item used for Trick Magic Item");if(!item.actor?.isOfType("character"))throw ErrorPF2e(this.#localize("InvalidActor"));this.item=item,this.actor=item.actor,this.checkDC=calculateTrickMagicItemCheckDC(item),this.#initialize()}async#initialize(){const buttons=TRICK_MAGIC_SKILLS.filter(skill=>skill in this.checkDC).map(value=>({value,label:game.i18n.localize(`PF2E.Skill${value.capitalize()}`),modifier:this.actor.skills[value].check.mod})).reduce((accumulated,skill)=>{const button={icon:fontAwesomeIcon("dice-d20").outerHTML,label:`${skill.label} (${skill.modifier<0?"":"+"}${skill.modifier})`,callback:()=>this.#handleTrickItem(skill.value)};return{...accumulated,[skill.value]:button}},{});new Dialog({title:this.#localize("Title"),content:`${this.#localize("Label")}
`,buttons},{classes:["dialog","trick-magic-item"],width:"auto"}).render(!0)}#handleTrickItem(skill){this.actor.skills[skill].check.roll({extraRollOptions:["action:trick-magic-item"],dc:{value:this.checkDC[skill]??0},item:this.item});const trick=new TrickMagicItemEntry(this.actor,skill);this.item.castEmbeddedSpell(trick)}}class ConsumablePF2e extends PhysicalItemPF2e{static{__name(this,"ConsumablePF2e")}static{__name2(this,"ConsumablePF2e")}get otherTags(){return new Set(this.system.traits.otherTags)}get category(){return this.system.category}get isAmmo(){return this.category==="ammo"}get uses(){return pick(this.system.uses,["value","max"])}get embeddedSpell(){if(!this.actor)throw ErrorPF2e(`No owning actor found for "${this.name}" (${this.id})`);return this.system.spell?new SpellPF2e(foundry.utils.deepClone(this.system.spell),{parent:this.actor,fromConsumable:!0}):null}prepareBaseData(){if(super.prepareBaseData(),this.system.uses.max||=1,!!this.isAmmo){for(const rule of this.system.rules)if(rule.key==="RollOption"&&"toggleable"in rule&&rule.toggleable){console.warn("Toggleable RollOption rule elements may not be added to ammunition"),this.system.rules=[];break}else if(["GrantItem","ChoiceSet"].includes(String(rule.key))){console.warn(`${rule.key} rule elements may not be added to ammunition`),this.system.rules=[];break}}}prepareRuleElements(){const rules=super.prepareRuleElements();for(const rule of rules)rule.ignored=!0;return rules}async getChatData(htmlOptions={},rollOptions={}){const traits=this.traitChatData(CONFIG.PF2E.consumableTraits),[category,isUsable]=this.isIdentified?[game.i18n.localize(CONFIG.PF2E.consumableCategories[this.category]),!0]:[this.generateUnidentifiedName({typeOnly:!0}),!["other","scroll","talisman","toolkit","wand"].includes(this.category)],usesLabel=game.i18n.localize("PF2E.Item.Consumable.Uses.Label"),fromFormula=!!rollOptions.fromFormula;return this.processChatData(htmlOptions,{...await super.getChatData(),traits,properties:this.isIdentified&&this.uses.max>1?[`${this.uses.value}/${this.uses.max} ${usesLabel}`]:[],category,isUsable:fromFormula?!1:isUsable})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const liquidOrSubstance=__name2(()=>this.traits.has("inhaled")||this.traits.has("contact")?"PF2E.identification.UnidentifiedType.Substance":"PF2E.identification.UnidentifiedType.Liquid","liquidOrSubstance"),itemType=game.i18n.localize(["drug","elixir","mutagen","oil","poison","potion"].includes(this.category)?liquidOrSubstance():["scroll","snare","ammo"].includes(this.category)?CONFIG.PF2E.consumableCategories[this.category]:"PF2E.identification.UnidentifiedType.Object");return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}getRollOptions(prefix=this.type){return[...super.getRollOptions(prefix),...Object.entries({[`category:${this.category}`]:!0}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`)]}isAmmoFor(weapon){if(!this.isAmmo)return!1;if(!weapon.isOfType("weapon"))return console.warn("Cannot load a consumable into a non-weapon"),!1;const{max}=this.uses;return weapon.system.traits.value.includes("repeating")?max>1:max<=1}async consume(){const{actor}=this;if(!actor)return;const{value,max}=this.uses;if(["scroll","wand"].includes(this.category)&&this.system.spell)if(actor.spellcasting.canCastConsumable(this))this.castEmbeddedSpell();else if(actor.itemTypes.feat.some(feat=>feat.slug==="trick-magic-item"))new TrickMagicItemPopup(this);else{const formatParams={actor:actor.name,spell:this.name},message=game.i18n.format("PF2E.LackCastConsumableCapability",formatParams);ui.notifications.warn(message);return}else if(this.category!=="ammo"){const key=max>1&&value===1?"UseExhausted":max>1?"UseMulti":"UseSingle",content=game.i18n.format(`PF2E.ConsumableMessage.${key}`,{name:this.name,current:value-1}),flags={pf2e:{origin:{sourceId:this.flags.core?.sourceId,uuid:this.uuid,type:this.type}}},speaker=ChatMessage.getSpeaker({actor});if(this.system.damage){const{formula,type,kind}=this.system.damage;new DamageRoll(`(${formula})[${type},${kind}]`).toMessage({speaker,flavor:content,flags})}else ChatMessage.create({speaker,content,flags})}if(this.system.uses.autoDestroy&&value<=1){const{quantity}=this,isPreservedAmmo=this.category==="ammo"&&this.system.rules.length>0;quantity<=1&&!isPreservedAmmo?await this.delete():await this.update({"system.quantity":Math.max(quantity-1,0),"system.uses.value":max})}else await this.update({"system.uses.value":Math.max(value-1,0)})}async castEmbeddedSpell(trickMagicItemData){const{actor}=this,spell=this.embeddedSpell;if(!actor||!spell)return;const entry=(()=>trickMagicItemData||actor.spellcasting.filter(e=>e instanceof SpellcastingEntryPF2e&&e.canCast(spell,{origin:this})).reduce((previous,current)=>{const previousDC=previous.statistic.dc.value;return current.statistic.dc.value>previousDC?current:previous}))();if(entry){const systemData=spell.system;entry instanceof SpellcastingEntryPF2e&&(systemData.location.value=entry.id),entry.cast(spell,{consume:!1})}}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(typeof changed.system.damage?.type=="string"){const category=changed.system.category??this.system.category;setHasElement(DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES,category)?(setHasElement(DAMAGE_ONLY_CONSUMABLE_CATEGORIES,category)||!["vitality","void","untyped"].includes(changed.system.damage.type))&&(changed.system.damage.kind="damage"):changed.system.damage=null}if(changed.system.uses){if("value"in changed.system.uses){const minimum=this.system.uses.autoDestroy?1:0;changed.system.uses.value=Math.clamped(Math.floor(Number(changed.system.uses.value))||minimum,minimum,9999)}"max"in changed.system.uses&&(changed.system.uses.max=Math.clamped(Math.floor(Number(changed.system.uses.max))||1,1,9999)),typeof changed.system.uses.value=="number"&&typeof changed.system.uses.max=="number"&&(changed.system.uses.value=Math.min(changed.system.uses.value,changed.system.uses.max))}return changed.system.price?.per!==void 0&&(changed.system.price.per=Math.clamped(Math.floor(Number(changed.system.price.per))||1,1,999)),super._preUpdate(changed,options,user)}}class DeityPF2e extends ItemPF2e{static{__name(this,"DeityPF2e")}static{__name2(this,"DeityPF2e")}get category(){return this.system.category}get favoredWeapons(){return[...this.system.weapons]}prepareBaseData(){super.prepareBaseData(),this.system.sanctification?.modal||(this.system.sanctification=null),this.category==="philosophy"&&(this.system.attribute=[],this.system.domains={primary:[],alternate:[]},this.system.font=[],this.system.sanctification=null,this.system.skill=null,this.system.spells={},this.system.weapons=[])}prepareActorData(){if(!this.actor.isOfType("character")){this.delete({render:!1});return}this.actor.deity=this;const{deities}=this.actor.system.details,systemData=this.system;deities.primary={skill:foundry.utils.deepClone(systemData.skill),weapons:foundry.utils.deepClone(systemData.weapons)};for(const domain of this.system.domains.primary){const label=CONFIG.PF2E.deityDomains[domain]?.label;deities.domains[domain]=label??domain;const apocryphaKey=`${domain}-apocryphal`;if(objectHasKey(CONFIG.PF2E.deityDomains,apocryphaKey)){const apocrypha=CONFIG.PF2E.deityDomains[apocryphaKey];deities.domains[apocryphaKey]=apocrypha.label}}const slug=this.slug??sluggify(this.name),prefix="deity:primary",actorRollOptions=this.actor.rollOptions;actorRollOptions.all.deity=!0,actorRollOptions.all[`${prefix}:${slug}`]=!0;const sanctifications=this.getSanctificationRollOptions().map(o=>`${prefix}:${o}`);for(const option of sanctifications)actorRollOptions.all[option]=!0;for(const baseType of this.favoredWeapons)actorRollOptions.all[`${prefix}:favored-weapon:${baseType}`]=!0;actorRollOptions.all[`self:deity:slug:${slug}`]=!0}setFavoredWeaponRank(){if(!this.actor.isOfType("character"))return;const favoredWeaponRank=this.actor.flags.pf2e.favoredWeaponRank;if(favoredWeaponRank>0){const attacks=this.actor.system.proficiencies.attacks,baseWeaponTypes2=CONFIG.PF2E.baseWeaponTypes,baseShieldTypes2=CONFIG.PF2E.baseShieldTypes;for(const baseType of this.favoredWeapons)attacks[`weapon-base-${baseType}`]={label:baseWeaponTypes2[baseType]??baseShieldTypes2[baseType]??baseType,rank:Math.max(Number(attacks[`weapon-base-${baseType}`]?.rank)||0,favoredWeaponRank)}}}getRollOptions(prefix=this.type){const baseOptions=super.getRollOptions(prefix),sanctifications=this.getSanctificationRollOptions().map(o=>`${prefix}:${o}`);return[...baseOptions,`${prefix}:category:${this.category}`,...sanctifications].sort()}getSanctificationRollOptions(){const{sanctification}=this.system,modal=sanctification?.modal;return sanctification?.modal&&sanctification.what.length>0?sanctification.what.map(s=>`sanctification:${modal}:${s}`):["sanctification:none"]}}function featCanHaveKeyOptions(feat){if(feat.category!=="classfeature"||feat.level!==1||feat.traits.size>1)return!1;const{grantedBy}=feat;return!grantedBy||grantedBy.isOfType("feat")&&grantedBy.category==="classfeature"}__name(featCanHaveKeyOptions,"featCanHaveKeyOptions"),__name2(featCanHaveKeyOptions,"featCanHaveKeyOptions");class FeatPF2e extends ItemPF2e{static{__name(this,"FeatPF2e")}static{__name2(this,"FeatPF2e")}get category(){return this.system.category}get level(){return this.system.level.value}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get actionCost(){const actionType=this.system.actionType.value||"passive";return actionType==="passive"?null:{type:actionType,value:this.system.actions.value}}get frequency(){return this.system.frequency??null}get isFeature(){return setHasElement(FEATURE_CATEGORIES,this.category)}get isFeat(){return setHasElement(FEAT_CATEGORIES,this.category)}get onlyLevel1(){return this.system.onlyLevel1}get maxTakable(){return this.system.maxTakable}prepareBaseData(){super.prepareBaseData(),this.group=null,this.system.level.taken??=null,this.system.location||=null;const traits=this.system.traits.value;this.category==="general"&&!traits.includes("general")&&traits.push("general"),this.category==="skill"&&(traits.includes("skill")||traits.push("skill"),!traits.includes("general")&&!traits.includes("archetype")&&traits.push("general")),traits.includes("dedication")&&(this.system.category="class",traits.includes("archetype")||traits.push("archetype")),this.system.traits.value.includes("lineage")&&(this.system.onlyLevel1=!0),this.system.maxTakable??=1/0,this.system.onlyLevel1&&(this.system.maxTakable=1),this.actor&&this.system.frequency&&(this.system.frequency.value??=this.system.frequency.max),this.system.subfeatures=foundry.utils.mergeObject({keyOptions:[]},this.system.subfeatures??{}),this.system.selfEffect??=null,this.system.actionType.value==="passive"&&(this.system.selfEffect=null)}prepareActorData(){const{actor}=this,prefix=this.isFeature?"feature":"feat",slug=this.slug??sluggify(this.name);actor.rollOptions.all[`${prefix}:${slug}`]=!0;const{subfeatures}=this.system;featCanHaveKeyOptions(this)||(subfeatures.keyOptions=[]),actor.isOfType("character")&&subfeatures.keyOptions.length>0&&(actor.system.build.attributes.keyOptions=uniq([...actor.system.build.attributes.keyOptions,...subfeatures.keyOptions]))}prepareSiblingData(){this.grants=Object.values(this.flags.pf2e.itemGrants).flatMap(grant=>{const item=this.actor?.items.get(grant.id);return item?.isOfType("feat")&&!item.system.location||item?.isOfType("heritage")?[item]:[]});for(const grant of this.grants.filter(g=>g.isOfType("feat")))grant.system.level.taken=this.system.level.taken}onPrepareSynthetics(){processSanctification(this)}async getChatData(htmlOptions={}){const levelLabel=game.i18n.format("PF2E.LevelN",{level:this.level}),actionTypeLabel=getActionTypeLabel(this.actionCost?.type,this.actionCost?.value),properties=actionTypeLabel?[levelLabel,actionTypeLabel]:[levelLabel],traits=this.traitChatData(CONFIG.PF2E.featTraits);return this.processChatData(htmlOptions,{...this.system,properties,traits})}getRollOptions(prefix="feat"){return prefix=prefix==="feat"&&this.isFeature?"feature":prefix,compact([...super.getRollOptions(prefix).filter(o=>!o.endsWith("level:0")),`${prefix}:category:${this.category}`,this.isFeat?`${prefix}:rarity:${this.rarity}`:null,this.frequency?`${prefix}:frequency:limited`:null])}async _preCreate(data,options,user){return this.parent||(this._source.system.location=null,delete this._source.system.level.taken,this._source.system.frequency&&delete this._source.system.frequency.value),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);"location"in changed.system&&(changed.system.location||=null),typeof changed.system.level?.value=="number"&&changed.system.level.value!==1&&(changed.system.onlyLevel1=!1),normalizeActionChangeData(this,changed);const traits=changed.system.traits?.value;return setHasElement(FEATURE_CATEGORIES,changed.system.category??this.category)?(changed.system.onlyLevel1=!1,changed.system.maxTakable=1,this.category!=="ancestry"&&Array.isArray(traits)&&traits.findSplice(t=>t==="lineage")):(Array.isArray(traits)&&traits.includes("lineage")||changed.system?.onlyLevel1)&&foundry.utils.mergeObject(changed,{system:{maxTakable:1}}),super._preUpdate(changed,options,user)}_onCreate(data,options,userId){if(super._onCreate(data,options,userId),!(this.isOwner&&this.actor?.isOfType("character")&&this.isFeat))return;const actorItemNames={actor:this.actor.name,item:this.name};if(this.onlyLevel1&&this.actor.level>1){const formatParams={...actorItemNames,actorLevel:this.actor.level},warning=game.i18n.format("PF2E.Item.Feat.Warning.TakenAfterLevel1",formatParams);ui.notifications.warn(warning)}if(this.flags.pf2e.grantedBy)return;const slug=this.slug??sluggify(this.name),timesTaken=this.actor.itemTypes.feat.filter(f=>f.slug===slug).length,{maxTakable}=this;if(maxTakable===1&×Taken>1)ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.TakenMoreThanOnce",actorItemNames));else if(timesTaken>maxTakable){const formatParams={...actorItemNames,maxTakable,timesTaken};ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.TakenMoreThanMax",formatParams))}}}class HeritagePF2e extends ItemPF2e{static{__name(this,"HeritagePF2e")}static{__name2(this,"HeritagePF2e")}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get isVersatile(){return!this.system.ancestry}prepareActorData(){if(!this.actor.isOfType("character"))throw ErrorPF2e("heritage embedded on non-character");const slug=this.slug??sluggify(this.name);(this.actor.itemTypes.heritage.length===1||!this.grantedBy)&&(this.actor.heritage=this,this.actor.system.details.heritage={name:this.name,trait:slug in CONFIG.PF2E.ancestryTraits?slug:null}),this.actor.system.traits.value.push(...this.traits),this.isVersatile&&this.actor.system.details.ancestry?.countsAs.push(slug),this.actor.rollOptions.all[`heritage:${slug}`]=!0,this.actor.rollOptions.all[`self:heritage:${slug}`]=!0}getRollOptions(prefix=this.type){const ancestryOrVersatile=this.system.ancestry?`ancestry:${this.system.ancestry.slug}`:"versatile";return[...super.getRollOptions(prefix),`${prefix}:${ancestryOrVersatile}`]}}class KitPF2e extends ItemPF2e{static{__name(this,"KitPF2e")}static{__name2(this,"KitPF2e")}get entries(){return Object.values(this.system.items)}get price(){return{value:new CoinsPF2e(this.system.price.value),per:this.system.price.per??1}}async createGrantedItems(options={}){const size=new ActorSizePF2e({value:options.size??"med",smallIsMedium:!0}).value,entries=options.entries??this.entries,itemUUIDs=entries.map(e=>e.uuid),items=await UUIDUtils.fromUUIDs(itemUUIDs);if(entries.length!==items.length)throw ErrorPF2e(`Some items from ${this.name} were not found`);return items.every(i=>i instanceof ItemPF2e&&!i.parent)?items.reduce(async(promise,item,index)=>{const prepared=await promise,clone=item.clone({_id:foundry.utils.randomID(),system:{size}},{keepId:!0}),entry=entries[index];if(clone.isOfType("physical")&&clone.updateSource({"system.quantity":entry.quantity,"system.containerId":options.containerId}),clone.isOfType("backpack")&&entry.items){const contents=await this.createGrantedItems({entries:Object.values(entry.items),containerId:clone.id,size});prepared.push(clone,...contents)}else if(clone instanceof KitPF2e){const inflatedKit=await clone.createGrantedItems({containerId:options.containerId,size});prepared.push(...inflatedKit)}else clone instanceof PhysicalItemPF2e&&prepared.push(clone);return prepared},[]):[]}async _preUpdate(changed,options,user){if(!changed.system)return await super._preUpdate(changed,options,user);if(isObject(changed.system.price)){const price=changed.system.price;for(const denomination of DENOMINATIONS)price[denomination]===0&&(price["-=denomination"]=null)}return super._preUpdate(changed,options,user)}}class LorePF2e extends ItemPF2e{static{__name(this,"LorePF2e")}static{__name2(this,"LorePF2e")}}class LoreSheetPF2e extends ItemSheetPF2e{static{__name(this,"LoreSheetPF2e")}static{__name2(this,"LoreSheetPF2e")}}class DicePF2e{static{__name(this,"DicePF2e")}static{__name2(this,"DicePF2e")}_rolled;terms;static async d20Roll({event:event2,item=null,parts,data,template,title,speaker,flavor,onClose,dialogOptions,rollMode=game.settings.get("core","rollMode"),rollType=""}){const userSettingQuickD20Roll=!game.user.settings.showCheckDialogs,_roll=__name2(async(rollParts,adv,$form)=>{let flav=flavor instanceof Function?flavor(rollParts,data):title;adv===1?(rollParts[0]=["2d20kh"],flav=game.i18n.format("PF2E.Roll.FortuneTitle",{title})):adv===-1&&(rollParts[0]=["2d20kl"],flav=game.i18n.format("PF2E.Roll.MisfortuneTitle",{title})),$form&&(data.itemBonus=$form.find("[name=itemBonus]").val()),(!data.itemBonus||data.itemBonus===0)&&rollParts.indexOf("@itemBonus")!==-1&&rollParts.splice(rollParts.indexOf("@itemBonus"),1),$form&&(data.statusBonus=$form.find("[name=statusBonus]").val()),(!data.statusBonus||data.statusBonus===0)&&rollParts.indexOf("@statusBonus")!==-1&&rollParts.splice(rollParts.indexOf("@statusBonus"),1),$form&&(data.circumstanceBonus=$form.find("[name=circumstanceBonus]").val()),(!data.circumstanceBonus||data.circumstanceBonus===0)&&rollParts.indexOf("@circumstanceBonus")!==-1&&rollParts.splice(rollParts.indexOf("@circumstanceBonus"),1);const roll=await new Roll(rollParts.join("+"),data).roll({async:!0}),origin=item?{uuid:item.uuid,type:item.type}:null;return roll.toMessage({speaker,flavor:flav,flags:{pf2e:{context:{type:rollType},origin}}},{rollMode:$form?$form.find("[name=rollMode]").val():rollMode}),roll},"_roll");if(parts.unshift("1d20"),userSettingQuickD20Roll&&!event2.altKey&&!(event2.ctrlKey||event2.metaKey)&&!event2.shiftKey||!userSettingQuickD20Roll&&event2.shiftKey)return _roll(parts,0);if(event2.ctrlKey||event2.metaKey)return rollMode="blindroll",_roll(parts,0);if(event2.shiftKey||!userSettingQuickD20Roll){parts.indexOf("@circumstanceBonus")===-1&&(parts=parts.concat(["@circumstanceBonus"])),parts.indexOf("@itemBonus")===-1&&(parts=parts.concat(["@itemBonus"])),parts.indexOf("@statusBonus")===-1&&(parts=parts.concat(["@statusBonus"])),template=template||"systems/pf2e/templates/chat/roll-dialog.hbs";const dialogData={data,rollMode,formula:parts.join(" + "),rollModes:CONFIG.Dice.rollModes},content=await renderTemplate(template,dialogData);let roll;return new Promise(resolve=>{new Dialog({title,content,buttons:{advantage:{label:game.i18n.localize("PF2E.Roll.Fortune"),callback:async html=>{roll=await _roll(parts,1,html)}},normal:{label:game.i18n.localize("PF2E.Roll.Normal"),callback:async html=>{roll=await _roll(parts,0,html)}},disadvantage:{label:game.i18n.localize("PF2E.Roll.Misfortune"),callback:async html=>{roll=await _roll(parts,-1,html)}}},default:game.i18n.localize("PF2E.Roll.Normal"),close:html=>{onClose&&onClose(html,parts,data),resolve(roll)}},dialogOptions).render(!0)})}else return _roll(parts,0)}alter(add2,multiply){const rgx=new RegExp(DiceTerm.REGEXP,"g");if(this._rolled)throw ErrorPF2e("You may not alter a Roll which has already been rolled");return this.terms=this.terms?.map(t=>t.replace(rgx,(_match,nd,d,mods)=>(nd=nd*(multiply||1)+(add2||0),mods=mods||"",`${nd}d${d}${mods}`))),this}}function simplifyFormula(formula){if(formula==="0")return formula;const fixedFormula=formula.replace(/^\s*-\s+/,"-").replace(/\s*\+\s*-\s*/g," - "),roll=new Roll(fixedFormula);if(!roll.terms.every(t=>[" - "," + "].includes(t.expression)||t instanceof Die||t instanceof NumericTerm))return fixedFormula;const terms=parseTermsFromSimpleFormula(roll);return createSimpleFormula(terms)}__name(simplifyFormula,"simplifyFormula"),__name2(simplifyFormula,"simplifyFormula");class MeleePF2e extends ItemPF2e{static{__name(this,"MeleePF2e")}static{__name2(this,"MeleePF2e")}get traits(){return new Set(this.system.traits.value)}get isMelee(){return this.system.weaponType.value==="melee"}get isRanged(){return this.system.weaponType.value==="ranged"}get isThrown(){return this.isRanged&&this.system.traits.value.some(t=>t.startsWith("thrown"))}get defaultAttribute(){const{traits}=this;return this.isMelee?traits.has("finesse")?"dex":"str":traits.has("brutal")?"str":"dex"}get attackModifier(){return Number(this.system.bonus.value)||0}get reach(){if(this.isRanged)return null;const reachTrait=this.system.traits.value.find(t=>/^reach-\d+$/.test(t));return reachTrait?Number(reachTrait.replace("reach-","")):SIZE_TO_REACH[this.actor?.size??"med"]}get range(){if(this.isMelee)return null;const specifiedMaxRange=(()=>{const rangeTrait=this.system.traits.value.find(t=>/^range-\d+$/.test(t)),range2=Number(rangeTrait?.replace(/\D/g,"")||"NaN");return Number.isInteger(range2)?range2:null})(),rangeIncrement=(()=>{if(specifiedMaxRange)return null;const incrementTrait=this.system.traits.value.find(t=>/^(?:range-increment|thrown)-\d+$/.test(t));return Number(incrementTrait?.replace(/\D/g,""))||10})();return specifiedMaxRange?{increment:null,max:specifiedMaxRange}:rangeIncrement?{increment:rangeIncrement,max:rangeIncrement*6}:null}get baseDamage(){const partials=Object.values(this.system.damageRolls),instance=partials.find(p=>!p.category)??partials.at(0);return instance?WeaponDamagePF2e.npcDamageToWeaponDamage(instance):{dice:0,die:null,modifier:0,damageType:"untyped",persistent:null,category:null}}get dealsDamage(){const{baseDamage}=this;return baseDamage.dice>0||baseDamage.modifier>0||!!baseDamage.persistent?.number||Object.values(this.system.damageRolls).some(d=>d.category==="splash")}get attackEffects(){return this.system.attackEffects.value}get isMagical(){const{traits}=this;return["magical","arcane","primal","divine","occult"].some(t=>traits.has(t))}get linkedWeapon(){const item=this.actor?.items.get(this.flags.pf2e.linkedWeapon??"");return item?.isOfType("weapon")?item:null}_initialize(options){this.category=this.group=this.baseType=null,super._initialize(options)}prepareBaseData(){super.prepareBaseData(),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.npcAttackTraits),this.system.material={type:null,grade:null,effects:[]},this.system.runes={property:[]};for(const attackDamage of Object.values(this.system.damageRolls))attackDamage.category||=null,attackDamage.damageType==="bleed"&&(attackDamage.category="persistent")}prepareSiblingData(){const{linkedWeapon}=this,isUnarmed=this.traits.has("unarmed");this.category=isUnarmed?"unarmed":linkedWeapon?.category??null,this.group=isUnarmed?"brawling":this.linkedWeapon?.group??null,this.baseType=tupleHasValue(["claw","fist","jaws"],this.slug)?this.slug:this.linkedWeapon?.baseType??null}prepareActorData(){if(!this.actor?.isOfType("npc"))return;const damageInstances=Object.values(this.system.damageRolls);for(const instance of Object.values(this.system.damageRolls)){try{instance.damage=new Roll(instance.damage)._formula}catch{const message=`Unable to parse damage formula on NPC attack ${this.name}`;console.warn(`PF2e System | ${message}`),instance.damage="1d4"}const{isElite,isWeak}=this.actor;if((isElite||isWeak)&&damageInstances.indexOf(instance)===0){const adjustment=isElite?2:-2;instance.damage=simplifyFormula(`${instance.damage} + ${adjustment}`)}else instance.damage=new Roll(instance.damage)._formula}}getRollOptions(prefix=this.type){const baseOptions=super.getRollOptions(prefix),{damageType}=this.baseDamage,damageCategory=DamageCategorization.fromDamageType(damageType),rangeIncrement=this.range?.increment,propertyRunes=mapToObj(this.system.runes.property,p=>[`rune:property:${sluggify(p)}`,!0]),otherOptions=Object.entries({equipped:!0,melee:this.isMelee,ranged:this.isRanged,thrown:this.isThrown,[`category:${this.category}`]:!!this.category,[`group:${this.group}`]:!!this.group,[`base:${this.baseType}`]:!!this.baseType,[`range-increment:${rangeIncrement}`]:!!rangeIncrement,[`damage:type:${damageType}`]:!0,[`damage:category:${damageCategory}`]:!!damageCategory,...propertyRunes}).filter(([,isTrue])=>isTrue).map(([key])=>`${prefix}:${key}`);return[baseOptions,otherOptions].flat().sort()}async toMessage(_event,{create=!0}={}){if(!create)return;const strike=this.actor?.system.actions?.find(s=>s.item===this);return strike?game.pf2e.rollActionMacro({itemId:this.id,slug:strike.slug}):void 0}}function setActorShieldData(shield){const{actor}=shield;if(!(shield.isEquipped&&actor.heldShield===shield)||!actor.isOfType("character","npc"))return;const{attributes}=actor.system;if(![shield.id,null].includes(attributes.shield.itemId))return;const{hitPoints}=shield;attributes.shield={itemId:shield.id,name:shield.name,ac:shield.acBonus,hp:hitPoints,hardness:shield.hardness,brokenThreshold:hitPoints.brokenThreshold,raised:shield.isRaised,broken:shield.isBroken,destroyed:shield.isDestroyed,icon:shield.img},actor.rollOptions.all["self:shield:equipped"]=!0,shield.isDestroyed?actor.rollOptions.all["self:shield:destroyed"]=!0:shield.isBroken&&(actor.rollOptions.all["self:shield:broken"]=!0)}__name(setActorShieldData,"setActorShieldData"),__name2(setActorShieldData,"setActorShieldData");class ShieldPF2e extends PhysicalItemPF2e{static{__name(this,"ShieldPF2e")}static{__name2(this,"ShieldPF2e")}isStackableWith(item){return this.isEquipped||item.isEquipped?!1:super.isStackableWith(item)}get baseType(){return this.system.baseItem??null}get isBuckler(){return["buckler","casters-targe","dart-shield","gauntlet-buckler","heavy-rondache","klar"].includes(this.system.baseItem??"")}get isTowerShield(){return["fortress-shield","tower-shield"].includes(this.system.baseItem??"")}get speedPenalty(){return this.system.speedPenalty||0}get acBonus(){return this.system.acBonus}get isSpecific(){return!!this.system.specific}get isRaised(){return!!this.actor?.isOfType("character","npc")&&this.id===this.actor.attributes.shield.itemId&&this.actor.attributes.shield.raised}getRollOptions(prefix="armor"){const reinforcingRune=this.system.runes.reinforcing,reinforcingSlug=[null,"minor","lesser","moderate","greater","major","supreme"][reinforcingRune],reinforcingOptions={[`rune:reinforcing:${reinforcingRune}`]:!!reinforcingRune,[`rune:reinforcing:${reinforcingSlug}`]:!!reinforcingRune},rollOptions=super.getRollOptions(prefix);return rollOptions.push(...Object.entries({[`base:${this.baseType}`]:!!this.baseType,...reinforcingOptions}).filter(e=>!!e[1]).map(e=>`${prefix}:${e[0]}`)),rollOptions}prepareBaseData(){const systemUsage=this.system;systemUsage.usage={value:"held-in-one-hand"},super.prepareBaseData(),"category"in this.system&&(this.type="shield",this.system.runes={reinforcing:0}),this.system.traits.integrated&&(this.system.traits.integrated.runes=foundry.utils.mergeObject({potency:0,striking:0,property:[]},this.system.traits.integrated.runes));const materialData=getMaterialValuationData(this),reinforcingRune=this.system.runes.reinforcing,adjustFromMaterialAndRune=__name2((property,base)=>{const fromMaterial=this.isSpecific?Math.max(base,materialData?.[property]??base):materialData?.[property]??base,additionalFromRune=reinforcingRune?RUNE_DATA.shield.reinforcing[reinforcingRune]?.[property]:null,sumFromRune=fromMaterial+(additionalFromRune?.increase??0);return additionalFromRune&&sumFromRune>additionalFromRune.max?Math.max(fromMaterial,additionalFromRune.max):sumFromRune},"adjustFromMaterialAndRune");this.system.hardness=adjustFromMaterialAndRune("hardness",this.system.hardness),this.system.hp.max=adjustFromMaterialAndRune("maxHP",this.system.hp.max),this.system.hp.brokenThreshold=Math.floor(this.system.hp.max/2);const baseTraits=this.system.traits.value,hasTraditionTraits=baseTraits.some(t=>setHasElement(MAGIC_TRADITIONS,t)),magicTrait=this.system.runes.reinforcing>0&&!hasTraditionTraits?"magical":null;this.system.traits.value=uniq(compact([...baseTraits,magicTrait]).sort()).filter(t=>t in CONFIG.PF2E.shieldTraits);const integratedTrait=this.system.traits.value.find(t=>t.startsWith("integrated"));if(integratedTrait){const isVersatileWeapon=integratedTrait.includes("versatile"),traitParts=integratedTrait.split("-"),damageTypeMap={b:"bludgeoning",p:"piercing",s:"slashing"},mainDamageType=damageTypeMap[traitParts.at(2)??""]??"slashing",versatileDamageType=isVersatileWeapon?damageTypeMap[traitParts.at(-1)??""]:null;this.system.traits.integrated&&versatileDamageType?(this.system.traits.integrated.versatile=foundry.utils.mergeObject({options:[mainDamageType,versatileDamageType],selection:mainDamageType},this.system.traits.integrated.versatile??{}),this.system.traits.integrated.versatile.options):this.system.traits.integrated&&(this.system.traits.integrated.versatile=null),this.system.traits.integrated=foundry.utils.mergeObject({damageType:mainDamageType,runes:{potency:0,striking:0,property:[]},versatile:null},this.system.traits.integrated??{})}else this.system.traits.integrated=null}prepareDerivedData(){super.prepareDerivedData(),this.system.acBonus=this.isBroken||this.isDestroyed?0:this.acBonus}prepareActorData(){const{actor}=this;if(!actor)throw ErrorPF2e("This method may only be called from embedded items");setActorShieldData(this)}onPrepareSynthetics(){super.onPrepareSynthetics(),setActorShieldData(this)}async getChatData(htmlOptions={}){const properties=[`${signedInteger(this.acBonus)} ${game.i18n.localize("PF2E.ArmorArmorLabel")}`,this.speedPenalty?`${this.system.speedPenalty} ${game.i18n.localize("PF2E.ArmorSpeedLabel")}`:null];return this.processChatData(htmlOptions,{...await super.getChatData(),traits:this.traitChatData(CONFIG.PF2E.shieldTraits),properties})}generateUnidentifiedName({typeOnly=!1}={typeOnly:!1}){const base=this.baseType?CONFIG.PF2E.baseShieldTypes[this.baseType]:null,fallback="TYPES.Item.shield",itemType=game.i18n.localize(base??fallback);return typeOnly?itemType:game.i18n.format("PF2E.identification.UnidentifiedItem",{item:itemType})}generateWeapon(){if(this.isStowed)return null;const shieldThrowTrait=this.system.traits.value.find(t=>t.startsWith("shield-throw-")),baseData=foundry.utils.deepClone({...pick(this,["_id","name","img"]),type:"weapon",system:{category:"martial",group:"shield",baseItem:this.baseType,equipped:{...this._source.system.equipped,invested:null},hp:pick(this.system.hp,["value","max"]),material:omit(this.material,["effects"]),traits:{rarity:this.rarity,value:shieldThrowTrait?[`thrown-${shieldThrowTrait.slice(-2)}`]:[],otherTags:[]},damage:{dice:1,die:"d4",damageType:"bludgeoning",modifier:0,persistent:null}}});if(this.system.traits.integrated){const damageType=this.system.traits.integrated.damageType,versatileTrait=this.system.traits.value.find(t=>t.includes("versatile")),versatileWeaponTrait=versatileTrait?.slice(versatileTrait.indexOf("versatile"))??null;objectHasKey(CONFIG.PF2E.weaponTraits,versatileWeaponTrait)&&(baseData.system.traits.value.push(versatileWeaponTrait),baseData.system.traits.toggles={versatile:{selection:this.system.traits.integrated.versatile?.selection??damageType}});const integratedWeaponRunes=this.system.traits.integrated?.runes,additionalData={system:{damage:{dice:1,die:"d6",damageType,modifier:0,persistent:null},runes:integratedWeaponRunes}};(integratedWeaponRunes?.potency||integratedWeaponRunes?.striking)&&(additionalData.name=this._source.name);const combinedData=foundry.utils.mergeObject(baseData,additionalData);return new ItemProxyPF2e(combinedData,{parent:this.parent,shield:this})}return new ItemProxyPF2e(baseData,{parent:this.parent,shield:this})}_preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);if(changed.system.acBonus!==void 0){const integerValue=Math.floor(Number(changed.system.acBonus))||0;changed.system.acBonus=Math.max(0,integerValue)}if(changed.system.speedPenalty!==void 0){const integerValue=Math.floor(Number(changed.system.speedPenalty))||0;changed.system.speedPenalty=Math.min(0,integerValue)}return this._source.system.traits.value.some(t=>t.startsWith("integrated-"))&&!!changed.system.traits?.value&&Array.isArray(changed.system.traits.value)&&!changed.system.traits.value.some(t=>t.startsWith("integrated-"))&&changed.system?.traits&&(changed.system.traits.integrated=null),super._preUpdate(changed,options,user)}}function createSpellRankLabel(spell,castRank){const typeLabel=spell.isCantrip?game.i18n.localize("PF2E.TraitCantrip"):spell.isFocusSpell?game.i18n.localize("PF2E.TraitFocus"):spell.isRitual?game.i18n.localize("PF2E.Item.Spell.Ritual.Label"):game.i18n.localize("TYPES.Item.spell");return castRank?game.i18n.format("PF2E.ItemLevel",{type:typeLabel,level:castRank}):typeLabel}__name(createSpellRankLabel,"createSpellRankLabel"),__name2(createSpellRankLabel,"createSpellRankLabel");async function createDescriptionPrepend(spell,{includeTraditions}){const traditions=includeTraditions?spell.system.traits.traditions.map(t=>game.i18n.localize(CONFIG.PF2E.magicTraditions[t]).toLocaleLowerCase(game.i18n.lang)).sort((a,b)=>a.localeCompare(b,game.i18n.lang)).join(", "):null,templatePath="systems/pf2e/templates/items/partials/spell-description-prepend.hbs",rendered=(await renderTemplate(templatePath,{spell,traditions})).trim();return rendered?`${rendered}
+
`:""}__name(createDescriptionPrepend,"createDescriptionPrepend"),__name2(createDescriptionPrepend,"createDescriptionPrepend");class SpellOverlayCollection extends Collection{static{__name(this,"SpellOverlayCollection")}static{__name2(this,"SpellOverlayCollection")}constructor(spell,entries){super(Object.entries(entries??{})),this.spell=spell}get overrideVariants(){return[...this.entries()].reduce((result,[overlayId,data])=>{if(data.overlayType==="override"){const spell=this.spell.loadVariant({overlayIds:[overlayId]});if(spell)return[...result,spell]}return result},[])}getType(overlayId){return this.get(overlayId,{strict:!0}).overlayType}async create(overlayType,options={renderSheet:!1}){const id=foundry.utils.randomID();switch(overlayType){case"override":if(await this.spell.update({[`system.overlays.${id}`]:{_id:id,sort:this.overrideVariants.length+1,overlayType:"override",system:{}}}),options.renderSheet){const variantSpell=this.spell.loadVariant({overlayIds:[id]});variantSpell&&variantSpell.sheet.render(!0)}break}}async updateOverride(variantSpell,data,options){const variantId=variantSpell.variantId;if(!variantId)return null;variantSpell.updateSource(data,options);const variantSource=variantSpell.toObject(),originSource=this.spell.toObject(),difference2=foundry.utils.diffObject(originSource,variantSource);return Object.keys(difference2).length===0||(delete difference2.system?.description,difference2.overlayType="override",await this.spell.update({[`system.overlays.-=${variantId}`]:null},{render:!1}),await this.spell.update({[`system.overlays.${variantId}`]:difference2}),variantSpell.sheet.rendered&&variantSpell.sheet.render(!0)),variantSpell}async deleteOverlay(overlayId){this.verifyOverlayId(overlayId),await this.spell.update({[`system.overlays.-=${overlayId}`]:null}),this.delete(overlayId)}verifyOverlayId(overlayId){if(!this.has(overlayId))throw ErrorPF2e(`Spell ${this.spell.name} (${this.spell.uuid}) does not have an overlay with id: ${overlayId}`)}}class SpellPF2e extends ItemPF2e{static{__name(this,"SpellPF2e")}static{__name2(this,"SpellPF2e")}isFromConsumable;trickMagicEntry=null;constructor(data,context={}){super(data,context),this.isFromConsumable=!!context.fromConsumable}get variantId(){return this.original?this.appliedOverlays?.get("override")??null:null}get baseRank(){return this.system.level.value}get baseLevel(){return this.baseRank}get rank(){if(!this.actor)return this.baseRank;const isAutoHeightened=this.isCantrip||this.isFocusSpell,fixedHeightenedRank=this.system.location.autoHeightenLevel||this.spellcasting?.system?.autoHeightenLevel.value||null;return(isAutoHeightened?fixedHeightenedRank||Math.ceil(this.actor.level/2)||null:this.system.location.heightenedLevel||null)||this.baseRank}get level(){return this.rank}get traits(){return new Set(this.system.traits.value)}get rarity(){return this.system.traits.rarity}get traditions(){return new Set(this.system.traits.traditions)}get actionGlyph(){return this.isRitual?null:getActionGlyph(this.system.time.value)||null}get spellcasting(){const spellcastingId=this.system.location.value;return this.trickMagicEntry?this.trickMagicEntry:this.actor?.spellcasting.get(spellcastingId??"")??null}get isAttack(){return this.traits.has("attack")}get isCantrip(){return this.traits.has("cantrip")&&!this.isRitual}get isFocusSpell(){return this.traits.has("focus")}get isRitual(){return!!this.system.ritual}get attribute(){return this.spellcasting?.attribute??"cha"}get ability(){return foundry.utils.logCompatibilityWarning("`SpellPF2e#ability` is deprecated. Use `SpellPF2e#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}get unlimited(){return this.isCantrip}get isVariant(){return!!this.original}get hasVariants(){return this.overlays.size>0}get area(){if(!this.system.area)return null;const size=Number(this.system.area.value),unit=game.i18n.localize("PF2E.Foot"),shape=game.i18n.localize(CONFIG.PF2E.areaTypes[this.system.area.type]),label=game.i18n.format("PF2E.Item.Spell.Area",{size,unit,shape});return{...this.system.area,label}}get range(){return null}get damageKinds(){return new Set(Object.values(this.system.damage).flatMap(d=>Array.from(d.kinds)))}get uuid(){return this.isVariant?this.original?.uuid??super.uuid:super.uuid}computeCastRank(slotRank){return(this.isCantrip||this.isFocusSpell)&&this.actor?this.rank:Math.max(this.baseRank,slotRank??this.rank)}getRollData(rollOptions={}){const spellLevel=Number(rollOptions?.castLevel)||null,castLevel=Math.max(this.baseRank,spellLevel||this.rank);if(spellLevel&&castLevel!==this.rank)return this.clone({"system.location.heightenedLevel":castLevel}).getRollData();const rollData=super.getRollData();return this.actor?.isOfType("character","npc")&&(rollData.mod=this.actor.abilities[this.attribute].mod),rollData.castLevel=castLevel,rollData.heighten=Math.max(0,castLevel-this.baseRank),rollData}async getDamage(params={skipDialog:!0}){const{spellcasting}=this;if(!Object.keys(this.system.damage).length||!this.actor||!spellcasting?.statistic)return null;const castLevel=this.rank,rollData=this.getRollData({castLevel}),base=[];for(const[id,damage]of Object.entries(this.system.damage??{})){if(!DamageRoll.validate(damage.formula))return console.error(`Failed to parse damage formula "${damage.formula}"`),null;const terms=parseTermsFromSimpleFormula(damage.formula,{rollData}),heightening=this.system.heightening;if(heightening?.type==="interval"&&heightening.interval){const scalingFormula=heightening.damage[id],partCount=Math.floor((castLevel-this.baseRank)/heightening.interval);if(scalingFormula&&partCount>0){const scalingTerms=parseTermsFromSimpleFormula(scalingFormula,{rollData});for(let i=0;i0&&!base.length&&this.actor.isOfType("npc")&&this.actor.attributes.adjustment){const value=this.unlimited?2:4;terms.push({dice:null,modifier:this.actor.isElite?value:-value})}const damageType=damage.type,category=damage.category||null,materials=damage.materials;base.push({terms:combinePartialTerms(terms),damageType,category,materials})}if(!base.length)return null;const{attribute,isAttack}=this,checkStatistic=spellcasting.statistic,spellTraits2=uniq(compact([...this.traits,spellcasting.tradition])),damageKinds=Array.from(this.damageKinds),domains=compact([damageKinds,damageKinds.map(k=>`spell-${k}`),damageKinds.map(k=>`${this.id}-${k}`),isAttack?["attack-damage","attack-spell-damage"]:null,checkStatistic.base?damageKinds.map(k=>`${checkStatistic.base?.slug}-${k}`):null].flat()),contextData=await this.actor.getDamageRollContext({target:isAttack?params.target:null,item:this,statistic:checkStatistic.check,domains,options:new Set(["action:cast-a-spell","self:action:slug:cast-a-spell",...spellTraits2]),checkContext:null,outcome:null,traits:spellTraits2,viewOnly:!isAttack||!params.target}),context={type:"damage-roll",sourceType:isAttack?"attack":"save",outcome:isAttack?"success":null,domains,options:contextData.options,self:contextData.self,target:contextData.target??null,rollMode:params.rollMode,traits:contextData.traits},modifiers=[],damageDice=[],{actor}=contextData.self;if(actor.system.abilities){const attributes=actor.system.abilities,attributeModifiers=Object.entries(this.system.damage).filter(([,d])=>d.applyMod).map(([k,d])=>new ModifierPF2e({label:CONFIG.PF2E.abilities[attribute],slug:`ability-${k}`,type:"untyped",modifier:attributes[attribute].mod,damageType:d.type,damageCategory:d.category||null,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,`ability-${k}`)})),extractOptions={resolvables:{spell:this,target:contextData.target?.actor??null},test:contextData.options},extracted=processDamageCategoryStacking(base,{modifiers:[attributeModifiers,extractModifiers(actor.synthetics,domains,extractOptions)].flat(),dice:extractDamageDice(actor.synthetics.damageDice,domains,extractOptions),test:contextData.options});modifiers.push(...extracted.modifiers),damageDice.push(...extracted.dice)}const formulaData={base,modifiers,dice:damageDice,ignoredResistances:[],kinds:this.damageKinds};if(!params.skipDialog&&!await new DamageModifierDialog({formulaData,context}).resolve())return null;const{formula,breakdown}=createDamageFormula(formulaData),roll=new DamageRoll(formula);return{template:{name:this.name,damage:{roll,breakdown},materials:Array.from(roll.materials),modifiers},context}}loadVariant(options={}){if(this.original)return this.original.loadVariant(options);const{castLevel,overlayIds}=options,appliedOverlays=new Map,heightenEntries=this.getHeightenLayers(castLevel),overlays=overlayIds?.map(id=>({id,data:this.overlays.get(id,{strict:!0})}))??[],overrides=(()=>{if(!heightenEntries.length&&!overlays.length)return castLevel!==this.rank?foundry.utils.mergeObject(this.toObject(),{system:{location:{heightenedLevel:castLevel}}}):null;let source=this.toObject();if(overlays.map(overlay=>overlay.data.overlayType).filter(type=>type==="override").length>1)throw ErrorPF2e(`Error loading variant of Spell ${this.name} (${this.uuid}). Cannot apply multiple override overlays.`);for(const{id,data}of overlays){switch(data.overlayType){case"override":{delete source.system.overlays,source.system.rules=[],source=foundry.utils.mergeObject(source,data,{overwrite:!0});break}}appliedOverlays.set(data.overlayType,id)}for(const overlay of heightenEntries)foundry.utils.mergeObject(source.system,overlay.system);const currentRank=source.system.location.heightenedLevel??source.system.level.value;return castLevel&&castLevel!==currentRank&&(source.system.location.heightenedLevel=castLevel),source._id=this.id,source})();if(!overrides)return null;const variant=new SpellPF2e(overrides,{parent:this.actor,fromConsumable:this.isFromConsumable});return variant.original=this,variant.appliedOverlays=appliedOverlays,variant.trickMagicEntry=this.trickMagicEntry,variant.system.traits.value=Array.from(variant.traits),processSanctification(variant),variant}getHeightenLayers(rank){const heightening=this.system.heightening;return heightening?.type!=="fixed"?[]:Object.entries(heightening.levels).map(([rank2,system])=>({level:Number(rank2),system})).filter(system=>!rank||rank>=system.level).sort((first,second)=>first.level-second.level)}placeTemplate(message){const templateConversion={burst:"circle",cone:"cone",cube:"rect",emanation:"circle",line:"ray",rect:"rect",square:"rect"},{area}=this.system;if(!area)throw ErrorPF2e("Attempted to create template with non-area spell");const templateType=templateConversion[area.type],templateData={t:templateType,distance:Number(area.value)/5*(canvas.dimensions?.distance??0),fillColor:game.user.color,flags:{pf2e:{messageId:message?.id,origin:{name:this.name,slug:this.slug,traits:foundry.utils.deepClone(this.system.traits.value),...this.getOriginData()},areaType:this.system.area?.type??null}}};switch(templateType){case"ray":templateData.width=CONFIG.MeasuredTemplate.defaults.width*(canvas.dimensions?.distance??1);break;case"cone":templateData.angle=CONFIG.MeasuredTemplate.defaults.angle;break;case"rect":{const distance=templateData.distance??0;templateData.distance=Math.hypot(distance,distance),templateData.width=distance,templateData.direction=45;break}}return canvas.templates.createPreview(templateData)}prepareBaseData(){super.prepareBaseData(),this.system.location.value||=null,this.system.level.value=Math.clamped(this.system.level.value,1,10)||1,this.system.area?.value?(this.system.area.value=Number(this.system.area.value)||5,this.system.area.type||="burst"):this.system.area=null,this.isRitual&&(this.system.damage={},this.system.defense=null,this.system.traits.value=this.system.traits.value.filter(t=>!["attack","cantrip","focus"].includes(t)),this.system.traits.traditions=[],this.system.location.value="rituals"),this.system.traits.value=this.system.traits.value.filter(t=>t in CONFIG.PF2E.spellTraits),this.system.traits.value.includes("attack")&&(this.system.defense=foundry.utils.mergeObject(this.system.defense??{},{passive:{statistic:"ac"},save:this.system.defense?.save??null}));const castTime=this.system.time.value=this.system.time.value.trim();!["","2 to 2 rounds"].includes(castTime)&&!this.isRitual&&!getActionGlyph(castTime)&&(this.system.traits.value.push("exploration"),this.system.traits.value.sort());for(const damage of Object.values(this.system.damage)){if(!isObject$1(damage)||typeof damage.formula!="string"){this.system.damage={},delete this.system.heightening,delete this.system.overlays;break}damage.formula=damage.formula?.trim()||"0",damage.kinds=new Set(damage.kinds??["damage"]),(damage.kinds.size===0||this.system.defense?.save?.statistic)&&damage.kinds.add("damage")}if(this.system.heightening?.type==="fixed")for(const heighten of Object.values(this.system.heightening.levels))for(const partial of compact(Object.values(heighten.damage??{})))partial.formula=partial.formula?.trim()||"0";else if(this.system.heightening?.type==="interval")for(const key of Object.keys(this.system.heightening.damage??{}))this.system.heightening.damage[key]=this.system.heightening.damage[key]?.trim()||"0";this.overlays=new SpellOverlayCollection(this,this.system.overlays)}prepareSiblingData(){this.spellcasting?.isInnate&&foundry.utils.mergeObject(this.system.location,{uses:{value:1,max:1}},{overwrite:!1})}prepareActorData(){if(!this.actor?.isOfType("character"))return;const{traits}=this;traits.has("focus")&&!traits.has("cantrip")&&(this.actor.system.resources.focus.max+=1)}onPrepareSynthetics(){processSanctification(this)}getRollOptions(prefix=this.type){const{spellcasting}=this,spellOptions=new Set(["magical",`${prefix}:rank:${this.rank}`,...this.traits]);spellcasting?.tradition&&spellOptions.add(`${prefix}:trait:${spellcasting.tradition}`),!!(spellcasting?.isPrepared||spellcasting?.isSpontaneous)&&!this.isCantrip&&!this.isFromConsumable&&spellOptions.add(`${prefix}:spell-slot`),this.system.duration.value||spellOptions.add(`${prefix}:duration:0`),this.unlimited||spellOptions.add(`${prefix}:frequency:limited`);for(const damage of Object.values(this.system.damage)){damage.type&&(spellOptions.add(`${prefix}:damage:${damage.type}`),spellOptions.add(`${prefix}:damage:type:${damage.type}`));const category=DamageCategorization.fromDamageType(damage.type);category&&spellOptions.add(`${prefix}:damage:category:${category}`),damage.category==="persistent"&&spellOptions.add(`${prefix}:damage:persistent:${damage.type}`)}const isAreaEffect=!!this.system.area?.value;isAreaEffect&&spellOptions.add("area-effect"),this.damageKinds.has("damage")&&(spellOptions.add("damaging-effect"),isAreaEffect&&spellOptions.add("area-damage"));for(const option of spellcasting?.getRollOptions?.("spellcasting")??[])spellOptions.add(option);const rollOptions=super.getRollOptions(prefix);return rollOptions.push(...spellOptions),rollOptions}async toMessage(event2,{create=!0,data,rollMode}={}){const domData=htmlClosest(event2?.currentTarget,".item")?.dataset,castData=foundry.utils.mergeObject(data??{},domData??{}),castLevel=Number(castData.castLevel??"");if(castLevel&&castLevel!==this.rank)return this.loadVariant({castLevel})?.toMessage(event2,{create,data,rollMode});const message=await super.toMessage(event2,{create:!1,data:castData,rollMode});if(!message)return;const messageSource=message.toObject(),flags=messageSource.flags.pf2e,spellcasting=this.spellcasting;if(spellcasting?.statistic){const tradition=spellcasting.tradition??this.traditions.first()??"arcane";if(flags.casting={id:spellcasting.id,tradition},this.isFromConsumable&&(flags.casting.embeddedSpell=this.toObject()),this.system.defense){const dc=spellcasting.statistic.withRollOptions({item:this}).dc;flags.context={type:"spell-cast",domains:dc.domains,options:[...dc.options],rollMode}}}return create?ChatMessagePF2e.create(messageSource,{renderSheet:!1}):(message.updateSource(messageSource),message)}async getChatData(htmlOptions={},rollOptions={}){if(!this.actor)throw ErrorPF2e(`Cannot retrieve chat data for unowned spell ${this.name}`);const slotRank=Number(rollOptions.slotLevel)||this.rank,castLevel=Number(rollOptions.castLevel)||this.computeCastRank(slotRank);if(!this.isVariant){const variant=this.loadVariant({castLevel});if(variant)return variant.getChatData(htmlOptions,rollOptions)}const variants=this.overlays.overrideVariants.map(variant=>({...pick(variant,["name","actionGlyph","sort"]),overlayIds:[...variant.appliedOverlays.values()]})).sort((a,b)=>a.sort-b.sort),rollData=htmlOptions.rollData??this.getRollData({castLevel});rollData.item??=this;const systemData=this.system,description=await(async()=>{const options={...htmlOptions,rollData},prepend=await createDescriptionPrepend(this,{includeTraditions:!1}),description2=await TextEditor.enrichHTML(this.description,{...options,async:!0});return`${prepend}
+${description2}`})(),spellcasting=this.spellcasting;if(!spellcasting)return console.warn(`PF2e System | Orphaned spell ${this.name} (${this.id}) on actor ${this.actor.name} (${this.actor.id})`),{...systemData};const statistic=spellcasting?.statistic;if(!statistic&&!this.isRitual)return console.warn(`PF2e System | Spell ${this.name} is missing a statistic to cast with (${this.id}) on actor ${this.actor.name} (${this.actor.id})`),{...systemData};const statisticChatData=statistic?.getChatData({item:this}),spellDC=statisticChatData?.dc.value,damage=await this.getDamage(),hasDamage=!!damage,saveType=systemData.defense?.save&&tupleHasValue(SAVE_TYPES,systemData.defense.save.statistic)?systemData.defense.save.statistic:null,isSave=!!saveType,saveKey=systemData.defense?.save?.basic?"PF2E.SaveDCLabelBasic":"PF2E.SaveDCLabel",saveLabel=(()=>{if(!(spellDC&&saveType))return null;const localized=game.i18n.format(saveKey,{dc:spellDC,type:game.i18n.localize(CONFIG.PF2E.saves[saveType])}),tempElement=createHTMLElement("div",{innerHTML:localized}),visibility=game.settings.get("pf2e","metagame_showDC")?"all":"owner";return TextEditorPF2e.convertXMLNode(tempElement,"dc",{visibility,whose:null}),tempElement.innerHTML})(),{damageKinds}=this,damageLabel=damageKinds.has("damage")?damageKinds.has("healing")?"PF2E.Damage.Kind.Both.Roll.Verb":"PF2E.Damage.Kind.Damage.Roll.Verb":"PF2E.Damage.Kind.Healing.Roll.Verb",{baseRank}=this,heightened=castLevel-baseRank,rankLabel=createSpellRankLabel(this,castLevel),area=this.area,properties=compact([heightened?game.i18n.format("PF2E.SpellLevelBase",{level:ordinalString(baseRank)}):null,heightened?game.i18n.format("PF2E.SpellLevelHeightened",{heightened}):null]),spellTraits2=this.traitChatData(CONFIG.PF2E.spellTraits,uniq(compact([...this.traits,spellcasting.tradition])));return{...systemData,description:{value:description},isAttack:this.isAttack,isSave,check:this.isAttack&&statisticChatData?statisticChatData.check:void 0,save:{...statisticChatData?.dc??{},type:saveType,label:saveLabel},hasDamage,castLevel,rankLabel,damageLabel,formula:damage?.template.damage.roll.formula,properties,traits:spellTraits2,area,variants,isAura:this.traits.has("aura")}}async rollAttack(event2,attackNumber=1,context={}){const{spellcasting}=this,statistic=spellcasting?.statistic;if(statistic)context.extraRollOptions=uniq(compact(["action:cast-a-spell","self:action:slug:cast-a-spell",context.extraRollOptions].flat())),await statistic.check.roll({...eventToRollParams(event2,{type:"check"}),...context,action:"cast-a-spell",item:this,traits:uniq(compact([...this.traits,spellcasting.tradition])),attackNumber});else throw ErrorPF2e("Spell points to location that is not a spellcasting type")}async rollDamage(event2,mapIncreases){const element=htmlClosest(event2.currentTarget,"*[data-cast-level]"),castLevel=Number(element?.dataset.castLevel)||this.rank;if(!this.isVariant){const variant=this.loadVariant({castLevel});if(variant)return variant.rollDamage(event2)}const targetToken=Array.from(game.user.targets).find(t=>t.actor?.isOfType("creature","hazard","vehicle"))?.document??null,spellDamage=await this.getDamage({target:targetToken,...eventToRollParams(event2,{type:"damage"})});if(!spellDamage)return null;const{template,context}=spellDamage;return typeof mapIncreases=="number"&&(context.mapIncreases=mapIncreases,context.options.add(`map:increases:${mapIncreases}`)),DamagePF2e.roll(template,context)}async rollCounteract(event2){if(event2=event2 instanceof Event?event2:event2?.originalEvent,!this.actor?.isOfType("character","npc"))return null;if(!this.spellcasting?.statistic?.attribute)return console.warn(ErrorPF2e(`Spell ${this.name} (${this.uuid}) is missing a statistic with which to counteract.`).message),null;const localize=localizer("PF2E.Item.Spell.Counteract"),statistic=new Statistic(this.actor,{slug:"counteract",label:localize("Label"),attribute:this.spellcasting.attribute,rank:this.spellcasting.statistic.rank??0}),domain="counteract-check",notes=[new RollNotePF2e({selector:domain,text:localize("Hint")}),...DEGREE_OF_SUCCESS_STRINGS.map(degreeString=>{const counteractRank={criticalFailure:0,failure:this.rank,success:this.rank+1,criticalSuccess:this.rank+3}[degreeString];return new RollNotePF2e({selector:domain,title:`PF2E.Check.Result.Degree.Check.${degreeString}`,text:localize(degreeString,{rank:counteractRank}),outcome:[degreeString]})})],traits=uniq(compact([...this.traits,this.spellcasting.tradition])),{check}=statistic.extend({domains:[domain],rollOptions:traits});return check.roll({...eventToRollParams(event2,{type:"check"}),label:game.i18n.localize("PF2E.Check.Specific.Counteract"),extraRollNotes:notes,traits})}getOriginData(){const flag=super.getOriginData();return flag.castLevel=this.rank,this.isVariant&&this.appliedOverlays&&(flag.variant={overlays:[...this.appliedOverlays.values()]}),flag}async update(data,options={}){return this.original&&this.appliedOverlays.has("override")&&this.sheet.rendered?this.original.overlays.updateOverride(this,data,options):super.update(data,options)}async _preCreate(data,options,user){return this._source.system.location.value||=null,this._source.system.ritual&&(this._source.system.damage={},this._source.system.defense=null,this._source.system.location.value=null,this._source.system.traits.value=this._source.system.traits.value.filter(t=>!["attack","cantrip","focus"].includes(t)),this._source.system.traits.traditions=[]),super._preCreate(data,options,user)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const diff=options.diff??=!0,newLocation=changed.system.location?.value,locationChanged=typeof newLocation=="string"&&newLocation!==this._source.system.location.value;if(diff&&(!this.actor||locationChanged)){const system=changed.system,locationUpdates=system.location=this.actor?system.location??{}:{value:""},keys2=Object.keys(this._source.system.location).filter(k=>k!=="value"&&!(k in locationUpdates));for(const key of keys2)locationUpdates[`-=${key}`]=null}if(changed.system.level){const{level}=changed.system;level.value=Math.clamped(Math.trunc(Number(level.value)||1),1,10)}const systemChanges=compact([changed.system,...Object.values(changed.system.overlays??{}).map(o=>o?.system)]);for(const system of systemChanges){(system.defense?.save??{}).statistic===""&&(system.defense=null);for(const partial of compact(Object.values(system.damage??{})))typeof partial.category=="string"&&(partial.category||=null),(partial.category||partial?.type&&!["vitality","void","untyped"].includes(partial.type))&&(partial.kinds=["damage"]);if(system.heightening&&"levels"in system.heightening)for(const rank of compact(Object.values(system.heightening.levels??{})))for(const partial of Object.values(rank.damage??{}))typeof partial?.category=="string"&&(partial.category||=null);const uses=system?.location?.uses;if(uses){const currentUses=uses.value??this.system.location.uses?.value??1,currentMax=uses.max??this.system.location.uses?.max??1;uses.value=Math.clamped(Number(currentUses),0,Number(currentMax))}}return super._preUpdate(changed,options,user)}}class RitualSpellcasting{static{__name(this,"RitualSpellcasting")}static{__name2(this,"RitualSpellcasting")}actor;spells;constructor(actor,rituals){this.actor=actor,this.spells=new SpellCollection(this);for(const ritual of rituals)this.spells.set(ritual.id,ritual)}get id(){return"rituals"}get name(){return game.i18n.localize("PF2E.Actor.Creature.Spellcasting.Rituals")}get sort(){return Math.max(0,...this.actor.itemTypes.spellcastingEntry.map(e=>e.sort))+10}get category(){return"ritual"}get tradition(){return null}get isFlexible(){return!1}get isFocusPool(){return!1}get isInnate(){return!1}get isPrepared(){return!1}get isRitual(){return!0}get isSpontaneous(){return!1}canCast(spell){return spell.isRitual}async cast(spell,options={}){if(!spell.isRitual)throw ErrorPF2e("Attempted to cast non-ritual from `RitualSpellcasting`");await spell.toMessage(void 0,{rollMode:options.rollMode})}async getSheetData(){return{id:this.id,name:this.name,statistic:null,tradition:null,category:this.category,isRitual:!0,hasCollection:!0,sort:this.sort,usesSpellProficiency:!1,...await this.spells.getSpellData()}}}class SpellCollection extends Collection{static{__name(this,"SpellCollection")}static{__name2(this,"SpellCollection")}entry;actor;constructor(entry){if(!entry.actor)throw ErrorPF2e("a spell collection must have an associated actor");super(),this.entry=entry,this.actor=entry.actor}get id(){return this.entry.id}get highestRank(){const highestSpell=Math.max(...this.map(s=>s.rank)),actorSpellRank=Math.ceil((this.actor?.level??0)/2);return Math.min(10,Math.max(highestSpell,actorSpellRank))}#assertEntryIsDocument(entry){if(!(entry instanceof ItemPF2e))throw ErrorPF2e("`this#entry` is not a `SpellcastingEntryPF2e`")}async addSpell(spell,options={}){const{actor}=this;if(!actor.isOfType("creature"))throw ErrorPF2e("Spellcasting entries can only exist on creatures");const canHeighten=!(spell.isCantrip||spell.isFocusSpell||spell.isRitual)&&(this.entry.isSpontaneous||this.entry.isInnate),heightenedRank=canHeighten?options.slotLevel??spell.rank:spell.baseRank;if(spell.system.location.value===this.id&&spell.rank===heightenedRank)return null;if(spell.isFocusSpell&&!this.entry.isFocusPool){const focusTypeLabel=game.i18n.format("PF2E.SpellFocusLabel");return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.WrongSpellType",{spellType:focusTypeLabel})),null}if(spell.baseRank>heightenedRank&&this.id===spell.system.location?.value){const targetRankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(heightenedRank)}),baseLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(spell.baseRank)});ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetRankLabel,baseLevel:baseLabel}))}const heightenedUpdate=canHeighten&&heightenedRank>=spell.baseRank?{"system.location.heightenedLevel":heightenedRank}:{};if(spell.actor===actor)return spell.update({"system.location.value":this.id,...heightenedUpdate});{const source=spell.clone({"system.location.value":this.id,...heightenedUpdate}).toObject(),created=(await actor.createEmbeddedDocuments("Item",[source])).shift();return created instanceof SpellPF2e?created:null}}async prepareSpell(spell,slotRank,spellSlot){if(this.#assertEntryIsDocument(this.entry),spell.baseRank>slotRank&&!(slotRank===0&&spell.isCantrip)){const targetRankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(slotRank)}),baseLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(spell.baseRank)});return ui.notifications.warn(game.i18n.format("PF2E.Item.Spell.Warning.InvalidLevel",{name:spell.name,targetLevel:targetRankLabel,baseLevel:baseLabel})),this.entry}CONFIG.debug.hooks&&console.debug(`PF2e System | Updating location for spell ${spell.name} to match spellcasting entry ${this.id}`);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}`,updates={[key]:{id:spell.id}},slot=this.entry.system.slots[`slot${slotRank}`].prepared[spellSlot];return slot&&(slot.prepared!==void 0&&(updates[`${key}.-=prepared`]=null),slot.name!==void 0&&(updates[`${key}.-=name`]=null)),this.entry.update(updates)}unprepareSpell(slotRank,spellSlot){this.#assertEntryIsDocument(this.entry),CONFIG.debug.hooks===!0&&console.debug(`PF2e System | Updating spellcasting entry ${this.id} to remove spellslot ${spellSlot} for spell rank ${slotRank}`);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}`;return this.entry.update({[key]:{name:game.i18n.localize("PF2E.SpellSlotEmpty"),id:null,prepared:!1,expended:!1}})}setSlotExpendedState(slotRank,spellSlot,isExpended){this.#assertEntryIsDocument(this.entry);const key=`system.slots.slot${slotRank}.prepared.${spellSlot}.expended`;return this.entry.update({[key]:isExpended})}async getSpellData(){const{actor}=this;if(!actor.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries can only exist on characters and npcs");if(this.entry instanceof RitualSpellcasting)return this.#getRitualData();this.#assertEntryIsDocument(this.entry);const results=[],spells=this.contents.sort((s1,s2)=>(s1.sort||0)-(s2.sort||0)),signatureSpells=spells.filter(s=>s.system.location.signature),isFlexible=this.entry.isFlexible;if(this.entry.isPrepared&&this.entry instanceof SpellcastingEntryPF2e)for(let rank=0;rank<=this.highestRank;rank++){const data=this.entry.system.slots[`slot${rank}`],active=[];if((this.entry.system.showSlotlessLevels.value||data.max>0)&&(rank===0||!isFlexible)){const maxPrepared=Math.max(data.max,0);active.push(...Array(maxPrepared).fill(null));for(const[key,value]of Object.entries(data.prepared)){const spell=value.id?this.get(value.id):null;spell&&(active[Number(key)]={castLevel:spell.computeCastRank(rank),spell,expended:!!value.expended})}}results.push({label:rank===0?"PF2E.Actor.Creature.Spellcasting.Cantrips":game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,uses:{value:rank>0&&isFlexible?data.value||0:void 0,max:data.max},isCantrip:rank===0,active})}else if(this.entry.isFocusPool){const cantrips=spells.filter(spell=>spell.isCantrip),leveled=spells.filter(spell=>!spell.isCantrip);if(cantrips.length){const active=cantrips.map(spell=>({spell}));results.push({label:"PF2E.Actor.Creature.Spellcasting.Cantrips",level:0,isCantrip:!0,active})}if(leveled.length){const active=leveled.map(spell=>({spell}));results.push({label:actor.type==="character"?"PF2E.Focus.Spells":"PF2E.Focus.Pool",level:Math.max(1,Math.ceil(actor.level/2)),isCantrip:!1,uses:actor.system.resources.focus??{value:0,max:0},active})}}else{const alwaysShowHeader=!this.entry.isRitual,spellsByLevel=groupBy(spells,spell=>spell.isCantrip?0:spell.rank);for(let rank=0;rank<=this.highestRank;rank++){const data=this.entry.system.slots[`slot${rank}`],spells2=spellsByLevel.get(rank)??[];if(alwaysShowHeader||spells2.length){const uses=this.entry.isSpontaneous&&rank!==0?{value:data.value,max:data.max}:void 0,active=spells2.map(spell=>({spell,expended:this.entry.isInnate&&!spell.system.location.uses?.value,uses:this.entry.isInnate&&!spell.unlimited?spell.system.location.uses:void 0})),hideForSpontaneous=this.entry.isSpontaneous&&uses?.max===0&&active.length===0,hideForInnate=this.entry.isInnate&&active.length===0;if(!this.entry.system.showSlotlessLevels.value&&(hideForSpontaneous||hideForInnate))continue;results.push({label:rank===0?"PF2E.Actor.Creature.Spellcasting.Cantrips":game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,isCantrip:rank===0,uses,active})}}}if(this.entry.isSpontaneous||isFlexible){for(const spell of signatureSpells)for(const result of results){if(spell.baseRank>result.level||!this.entry.system.showSlotlessLevels.value&&result.uses?.max===0)continue;const existing=result.active.find(a=>a?.spell.id===spell.id);if(existing)existing.signature=!0;else if(result.uses?.max){const castLevel=result.level;result.active.push({spell,castLevel,signature:!0,virtual:!0})}}for(const result of results)if(result.level>0&&result.uses?.value===0&&result.uses.max>0)for(const slot of result.active)slot&&(slot.expended=!0)}const flexibleAvailable=(()=>{if(!isFlexible)return null;const totalSlots=results.filter(result=>!result.isCantrip).map(rank=>rank.uses?.max||0).reduce((first,second)=>first+second,0);return{value:signatureSpells.length,max:totalSlots}})();return{levels:results,flexibleAvailable,spellPrepList:this.getSpellPrepList(spells)}}async#getRitualData(){const groupedByRank=groupBy(Array.from(this.values()),s=>s.rank);return{levels:Array.from(groupedByRank.entries()).sort(([a],[b])=>a-b).map(([rank,spells])=>({label:game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),level:rank,isCantrip:!1,active:spells.map(spell=>({spell}))})),spellPrepList:null}}getSpellPrepList(spells){if(!this.entry.isPrepared)return{};const spellPrepList={},spellsByRank=groupBy(spells,spell=>spell.isCantrip?0:spell.baseRank);for(let rank=0;rank<=this.highestRank;rank++)spellPrepList[rank]=spellsByRank.get(rank)?.map(spell=>({spell,signature:this.entry.isFlexible&&spell.system.location.signature}))??[];return Object.values(spellPrepList).some(s=>!!s.length)?spellPrepList:null}}class SpellcastingEntryPF2e extends ItemPF2e{static{__name(this,"SpellcastingEntryPF2e")}static{__name2(this,"SpellcastingEntryPF2e")}get attribute(){return this.system.ability.value||"cha"}get ability(){return foundry.utils.logCompatibilityWarning("`SpellcastingEntryPF2e#ability` is deprecated. Use `SpellcastingEntryPF2e#attribute` instead.",{since:"5.3.0",until:"6.0.0"}),this.attribute}get tradition(){const defaultTradition=this.system.prepared.value==="items"?null:"arcane",tradition=this.system.tradition.value;return setHasElement(MAGIC_TRADITIONS,tradition)?tradition:defaultTradition}get category(){return this.system.prepared.value}get rank(){return this.system.proficiency.value??0}get isPrepared(){return this.system.prepared.value==="prepared"}get isFlexible(){return this.isPrepared&&!!this.system.prepared.flexible}get isSpontaneous(){return this.system.prepared.value==="spontaneous"}get isInnate(){return this.system.prepared.value==="innate"}get isFocusPool(){return this.system.prepared.value==="focus"}get isRitual(){return!1}get highestLevel(){return this.spells?.highestRank??0}get showSlotlessLevels(){return this.system.showSlotlessLevels.value}prepareBaseData(){super.prepareBaseData(),this.system.proficiency.value=Math.max(1,this.system.proficiency.value),this.system.prepared.flexible??=!1,this.system.prepared.validItems||=null,this.actor&&(this.statistic=new Statistic(this.actor,{slug:this.slug??sluggify(this.name),label:"PF2E.Actor.Creature.Spellcasting.InvalidProficiency",check:{type:"check"}}))}prepareSiblingData(){if(!this.actor||this.system.prepared.value==="items")this.spells=null;else{this.spells=new SpellCollection(this);const spells=this.actor.itemTypes.spell.filter(i=>i.system.location.value===this.id);for(const spell of spells)this.spells.set(spell.id,spell);this.actor.spellcasting.collections.set(this.spells.id,this.spells)}}prepareActorData(){const actor=this.parent;if(!this.system.proficiency.slug&&!this.isInnate&&actor.isOfType("character")){const spellProficiency=actor.system.proficiencies.spellcasting;spellProficiency.rank=Math.clamped(Math.max(spellProficiency.rank,this.system.proficiency.value),1,4)}}prepareStatistic(){const actor=this.actor;if(!actor)return;const{attribute,tradition}=this,slug=this.slug??sluggify(`${this.name}-spellcasting`),baseDomains=["all",`${attribute}-based`,"spell-attack-dc"],checkDomains=[`${tradition}-spell-attack`,"spell-attack","spell-attack-roll","attack","attack-roll"],dcDomains=[`${tradition}-spell-dc`,"spell-dc"];if(actor.isOfType("character")){const baseStat=actor.getStatistic(this.system.proficiency.slug||"base-spellcasting");if(!baseStat)return;this.system.ability.value=baseStat.attribute??this.system.ability.value,this.system.proficiency.value=Math.max(this.rank,baseStat.rank??0),this.statistic=baseStat.extend({slug,label:baseStat.slug==="base-spellcasting"&&tradition?CONFIG.PF2E.magicTraditions[tradition]:baseStat.label,attribute:this.attribute,rank:this.rank,rollOptions:this.getRollOptions("spellcasting"),domains:baseDomains,check:{type:"attack-roll",domains:checkDomains},dc:{domains:dcDomains}})}else if(actor.isOfType("npc")){const adjustment=actor.isElite?2:actor.isWeak?-2:0,baseMod=Number(this.system?.spelldc?.value??0)+adjustment,baseDC=Number(this.system?.spelldc?.dc??0)+adjustment;this.statistic=new Statistic(actor,{slug,attribute:this.attribute,label:CONFIG.PF2E.magicTraditions[tradition??"arcane"],domains:baseDomains,rollOptions:this.getRollOptions("spellcasting"),check:{type:"attack-roll",domains:checkDomains,modifiers:[new ModifierPF2e("PF2E.ModifierTitle",baseMod,"untyped")]},dc:{domains:dcDomains,modifiers:[new ModifierPF2e("PF2E.ModifierTitle",baseDC-10,"untyped")]}})}else throw ErrorPF2e(`Actor type ${actor.type} does not support spellcasting entries`);const stat=actor.isOfType("npc")?{value:this.statistic.dc.value}:{value:this.statistic.dc.value,rank:this.statistic.rank??0},attributes=actor.system.attributes;stat.value>attributes.classOrSpellDC.value&&(attributes.classOrSpellDC=stat),(!attributes.spellDC||stat.value>attributes.spellDC.value)&&(attributes.spellDC=stat)}getLinkedItems(){return this.actor?.itemTypes.spell.filter(i=>i.system.location.value===this.id)??[]}canCast(spell,{origin}={}){if(this.system.prepared.value==="items")return origin?this.system.prepared.validItems==="scroll"?origin.traits.has("scroll"):!0:!1;const isSpellcastingFeature=this.isPrepared||this.isSpontaneous;if(origin&&!isSpellcastingFeature||!this.spells)return!1;const matchesTradition=this.tradition&&spell.traditions.has(this.tradition),isInSpellList=this.spells.some(s=>s.slug===spell.slug);return matchesTradition||isInSpellList}async cast(spell,options={}){const consume=options.consume??!0,message=options.message??!0,slotRank=options.level??spell.rank,valid=!consume||spell.isCantrip||await this.consume(spell,slotRank,options.slot);if(message&&valid){const castRank=spell.computeCastRank(slotRank);await spell.toMessage(void 0,{rollMode:options.rollMode,data:{castLevel:castRank}})}}async consume(spell,rank,slot){const actor=this.actor;if(!actor?.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries require an actor");if(this.isRitual)return!0;if(spell.isVariant&&(spell=spell.original),this.isFocusPool&&actor.isOfType("character","npc")){const currentPoints=actor.system.resources.focus?.value??0;return currentPoints>0?(await actor.update({"system.resources.focus.value":currentPoints-1}),!0):(ui.notifications.warn(game.i18n.localize("PF2E.Focus.NotEnoughFocusPointsError")),!1)}const rankLabel=game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),slotKey=goesToEleven(rank)?`slot${rank}`:"slot0";if(this.system.slots===null||!this.spells)return!1;if(this.isPrepared&&!this.isFlexible){const preparedData=this.system.slots[slotKey].prepared;if(slot??=Number(Object.entries(preparedData).filter(([_,slot2])=>slot2.id===spell.id&&!slot2.expended).at(0)?.[0]),!Number.isInteger(slot))throw ErrorPF2e("Slot not given for prepared spell, and no alternative slot was found");return preparedData[slot].expended??!1?(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotExpendedError",{name:spell.name})),!1):(await this.spells.setSlotExpendedState(rank,slot,!0),!0)}if(this.isInnate){const remainingUses=spell.system.location.uses?.value||0;return remainingUses<=0?(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotExpendedError",{name:spell.name})),!1):(await spell.update({"system.location.uses.value":remainingUses-1}),!0)}const slots=this.system.slots[slotKey];return slots.value>0?(await this.update({[`system.slots.${slotKey}.value`]:slots.value-1}),!0):(ui.notifications.warn(game.i18n.format("PF2E.SpellSlotNotEnoughError",{name:spell.name,level:rankLabel})),!1)}async addSpell(spell,options){return this.spells?.addSpell(spell,options)??null}async prepareSpell(spell,slotRank,spellSlot){return this.spells?.prepareSpell(spell,slotRank,spellSlot)??null}async unprepareSpell(spellLevel,slotRank){return this.spells?.unprepareSpell(spellLevel,slotRank)??null}async setSlotExpendedState(slotRank,spellSlot,isExpended){return this.spells?.setSlotExpendedState(slotRank,spellSlot,isExpended)??null}async getSheetData(){if(!this.actor?.isOfType("character","npc"))throw ErrorPF2e("Spellcasting entries can only exist on characters and npcs");const spellCollectionData=await this.spells?.getSpellData()??{levels:[],spellPrepList:null};return{id:this.id,name:this.name,sort:this.sort,attribute:this.attribute,statistic:this.statistic.getChatData(),tradition:this.tradition,category:this.system.prepared.value,isPrepared:this.isPrepared,isSpontaneous:this.isSpontaneous,isFlexible:this.isFlexible,isInnate:this.isInnate,isFocusPool:this.isFocusPool,isRitual:this.isRitual,hasCollection:!!this.spells,usesSpellProficiency:!this.system.proficiency.slug,showSlotlessLevels:this.showSlotlessLevels,...spellCollectionData}}getRollOptions(prefix="spellcasting"){return[`${prefix}:${this.attribute}`,`${prefix}:${this.tradition}`,`${prefix}:${this.system.prepared.value}`]}async _preUpdate(changed,options,user){if(changed.system?.slots)for(const key of[0,1,2,3,4,5,6,7,8,9,10]){const slotKey=`slot${key}`,slotData=changed.system.slots[slotKey];if(slotData&&("max"in slotData&&(slotData.max=Math.max(Number(slotData.max)||0,0)),"value"in slotData)){const max="max"in slotData?Number(slotData?.max)||0:this.system.slots[slotKey].max;slotData.value=Math.clamped(Number(slotData.value),0,max)}}return super._preUpdate(changed,options,user)}getSpellData(){return this.getSheetData()}}const createDisintegrateEffect=__name2(()=>({_id:null,type:"effect",name:game.i18n.localize("PF2E.Item.Effect.Disintegrated.Name"),img:"systems/pf2e/icons/effects/fine-powder.svg",system:{slug:"effect-fine-powder",description:{value:game.i18n.localize("PF2E.Item.Effect.Disintegrated.Description")},rules:[{key:"TokenImage",value:"systems/pf2e/icons/effects/fine-powder.svg"}],tokenIcon:{show:!1}}}),"createDisintegrateEffect");function applyIWR(actor,roll,rollOptions){if(actor.isDead)return{finalDamage:0,applications:[],persistent:[]};if(!game.pf2e.settings.iwr)return{finalDamage:roll.total,applications:[],persistent:roll.instances.filter(i=>i.persistent&&!i.options.evaluatePersistent)};const{immunities,weaknesses,resistances}=actor.attributes,instances=roll.instances,persistent=[],ignoredResistances=(roll.options.ignoredResistances??[]).map(ir=>new Resistance({type:ir.type,value:ir.max??1/0})),nonDamageWeaknesses=weaknesses.filter(w=>NON_DAMAGE_WEAKNESSES.has(w.type)&&instances.some(i=>w.test([...i.formalDescription,...rollOptions]))),damageWeaknesses=weaknesses.filter(w=>!nonDamageWeaknesses.includes(w)),applications=instances.flatMap(instance=>{const formalDescription=new Set([...instance.formalDescription,...rollOptions]),wasIncreased=instance.total<=0&&typeof roll.options.increasedFrom=="number",isFirst=instances.indexOf(instance)===0,instanceTotal=wasIncreased&&isFirst?1:Math.max(instance.total,0);if(!actor.isAffectedBy(instance.type))return[{category:"unaffected",type:instance.type,adjustment:-1*instanceTotal}];const immunity=immunities.find(i=>i.test(formalDescription));if(immunity)return[{category:"immunity",type:immunity.label,adjustment:-1*instanceTotal}];const critImmunity=immunities.find(i=>i.type==="critical-hits"),critImmuneTotal=roll.options.degreeOfSuccess===DEGREE_OF_SUCCESS.CRITICAL_SUCCESS?instance.critImmuneTotal:instanceTotal,instanceApplications=[],critImmunityApplies=critImmunity&&critImmuneTotali.type==="precision"),precisionDamage=Math.min(instance.componentTotal("precision"),critImmuneTotal);if(precisionDamage>0&&precisionImmunity?.test([...formalDescription,"damage:component:precision"])){const adjustedPrecisionDamage=critImmunityApplies?Math.floor(precisionDamage/2):precisionDamage,adjustment2=-1*Math.min(critImmuneTotal,adjustedPrecisionDamage);instanceApplications.push({category:"immunity",type:precisionImmunity.applicationLabel,adjustment:adjustment2})}const afterImmunities=Math.max(instanceTotal+instanceApplications.reduce((sum,a)=>sum+a.adjustment,0),0);if(instance.persistent&&!instance.options.evaluatePersistent&&persistent.push(instance),afterImmunities===0)return instanceApplications;const mainWeaknesses=damageWeaknesses.filter(w=>w.test(formalDescription)),splashWeakness=instance.componentTotal("splash")?weaknesses.find(w=>w.type==="splash-damage")??null:null,precisionWeakness=precisionDamage>0?weaknesses.find(r=>r.type==="precision"):null,highestWeakness=compact([...mainWeaknesses,precisionWeakness,splashWeakness]).reduce((highest,w)=>w&&!highest||w&&highest&&w.value>highest.value?w:highest,null);highestWeakness&&instanceApplications.push({category:"weakness",type:highestWeakness.applicationLabel,adjustment:highestWeakness.value});const afterWeaknesses=afterImmunities+(highestWeakness?.value??0),applicableResistances=resistances.filter(r=>r.test(formalDescription)).map(r=>({label:r.applicationLabel,value:r.getDoubledValue(formalDescription),ignored:ignoredResistances.some(ir=>ir.test(formalDescription))})),criticalResistance=resistances.find(r=>r.type==="critical-hits");criticalResistance&&critImmuneTotalir.test(formalDescription))});const precisionResistance=(()=>{const resistance=precisionDamage>0?resistances.find(r=>r.type==="precision"):null;return resistance?{label:resistance.applicationLabel,value:Math.min(resistance.value,precisionDamage),ignored:!1}:null})();precisionResistance&&applicableResistances.push(precisionResistance);const highestResistance=applicableResistances.filter(r=>!r.ignored).reduce((highest,r)=>r&&!highest||r&&highest&&r.value>highest.value?r:highest,null),highestIgnored=applicableResistances.filter(r=>r.ignored).reduce((highest,r)=>r&&!highest||r&&highest&&r.value>highest.value?r:highest,null);return highestResistance?.value?instanceApplications.push({category:"resistance",type:highestResistance.label,adjustment:-1*Math.min(afterWeaknesses,highestResistance.value),ignored:!1}):highestIgnored&&instanceApplications.push({category:"resistance",type:ignoredResistances.find(ir=>ir.test(formalDescription))?.typeLabel??"???",adjustment:0,ignored:!0}),instanceApplications}).concat(...nonDamageWeaknesses.map(w=>({category:"weakness",type:w.typeLabel,adjustment:w.value}))).sort((a,b)=>{if(a.category===b.category)return 0;switch(a.category){case"unaffected":return-1;case"immunity":return b.type==="unaffected"?1:-1;case"weakness":return["unaffected","immunity"].includes(b.category)?1:-1;default:return 1}}),adjustment=applications.reduce((sum,a)=>sum+a.adjustment,0);return{finalDamage:Math.max(roll.total+adjustment,0),applications,persistent}}__name(applyIWR,"applyIWR"),__name2(applyIWR,"applyIWR");class ActorConditions extends DelegatedCollection{static{__name(this,"ActorConditions")}static{__name2(this,"ActorConditions")}#slugMap=new Collection;get active(){return this.filter(c=>c.active)}get stored(){return this.filter(c=>!c.inMemoryOnly)}get clumsy(){return this.bySlug("clumsy",{active:!0}).shift()??null}get doomed(){return this.bySlug("doomed",{active:!0}).shift()??null}get drained(){return this.bySlug("drained",{active:!0}).shift()??null}get dying(){return this.bySlug("dying",{active:!0}).shift()??null}get enfeebled(){return this.bySlug("enfeebled",{active:!0}).shift()??null}get frightened(){return this.bySlug("frightened",{active:!0}).shift()??null}get sickened(){return this.bySlug("sickened",{active:!0}).shift()??null}get slowed(){return this.bySlug("slowed",{active:!0}).shift()??null}get stunned(){return this.bySlug("stunned",{active:!0}).shift()??null}get stupefied(){return this.bySlug("stupefied",{active:!0}).shift()??null}get wounded(){return this.bySlug("wounded",{active:!0}).shift()??null}get(key,{strict=!1,active=null,temporary=null}={}){const condition=super.get(key,{strict});if(!(active===!0&&!condition?.active)&&!(active===!1&&condition?.active)&&!(temporary===!0&&condition?.actor.items.has(key))&&!(temporary===!1&&!condition?.actor.items.has(key)))return condition}set(id,condition){super.set(id,condition);const listBySlug=this.#slugMap.get(condition.slug)??[];return listBySlug.push(condition),this.#slugMap.set(condition.slug,listBySlug),this}every(condition){return this.contents.every(condition)}flatMap(transformer){return this.contents.flatMap(transformer)}delete(){return!1}bySlug(slug,{active=null,temporary=null}={}){return(this.#slugMap.get(slug)??[]).filter(condition=>{const activeFilterSatisfied=active===!0?condition.active:active===!1?!condition.active:!0,temporaryFilterSatisfied=temporary===!0?!condition.actor.items.has(condition.id):temporary===!1?condition.actor.items.has(condition.id):!0;return activeFilterSatisfied&&temporaryFilterSatisfied})}}var VisionLevels=(VisionLevels2=>(VisionLevels2[VisionLevels2.BLINDED=0]="BLINDED",VisionLevels2[VisionLevels2.NORMAL=1]="NORMAL",VisionLevels2[VisionLevels2.LOWLIGHT=2]="LOWLIGHT",VisionLevels2[VisionLevels2.DARKVISION=3]="DARKVISION",VisionLevels2))(VisionLevels||{});class ItemTransfer{static{__name(this,"ItemTransfer")}static{__name2(this,"ItemTransfer")}constructor(source,target,quantity,containerId){this.source=source,this.target=target,this.quantity=quantity,this.containerId=containerId}#templatePaths={flavor:"./systems/pf2e/templates/chat/action/flavor.hbs",content:"./systems/pf2e/templates/chat/action/content.hbs"};async request(){const gamemaster=game.users.find(u=>u.isGM&&u.active);if(!gamemaster){const source=this.#getSource(),target=this.#getTarget(),loot=[source,target].find(a=>a?.isLootableBy(game.user)&&!a.isOwner);if(!loot)throw ErrorPF2e("Unexpected missing actor");ui.notifications.error(game.i18n.format("PF2E.loot.GMSupervisionError",{loot:ItemTransfer.#tokenName(loot)}));return}console.debug(`PF2e System | Requesting item transfer from GM ${gamemaster.name}`),game.socket.emit("system.pf2e",{request:"itemTransfer",data:this})}async enact(requester){if(!game.user.isGM)throw ErrorPF2e("Unauthorized item transfer");console.debug("PF2e System | Enacting item transfer");const sourceActor=this.#getSource(),sourceItem=sourceActor?.inventory.find(i=>i.id===this.source.itemId),targetActor=this.#getTarget();if(!(sourceActor?.isLootableBy(game.user)&&sourceItem&&targetActor?.isLootableBy(game.user)))throw ErrorPF2e("Failed sanity check during item transfer");const targetItem=await sourceActor.transferItemToActor(targetActor,sourceItem,this.quantity,this.containerId),sourceIsLoot=sourceActor.isOfType("loot")&&sourceActor.system.lootSheetType==="Loot";!sourceItem&&sourceIsLoot||this.#sendMessage(requester,sourceActor,targetActor,targetItem)}#getActor(tokenId,actorId){return typeof tokenId=="string"?canvas.tokens.placeables.find(t=>t.id===tokenId)?.actor??null:game.actors.get(actorId)??null}#getSource(){return this.#getActor(this.source.tokenId,this.source.actorId)}#getTarget(){return this.#getActor(this.target.tokenId,this.target.actorId)}static#tokenName(document2){return"items"in document2?document2.isOfType("party")?game.i18n.localize("PF2E.loot.PartyStash"):document2.token?document2.token.name:document2.prototypeToken?.name??document2.name:document2.character?canvas.tokens.placeables.find(t=>t.actor?.id===document2.id)?.name??document2.character?.name:document2.name}async#sendMessage(requester,sourceActor,targetActor,item){const localize=localizer("PF2E.loot");if(!item)if(sourceActor.isOfType("loot")&&sourceActor.system.lootSheetType==="Merchant"){const message=localize("InsufficientFundsMessage"),content2=await renderTemplate(this.#templatePaths.content,{imgPath:targetActor.img,message:game.i18n.format(message,{buyer:targetActor.name})}),flavor2=await this.#messageFlavor(sourceActor,targetActor,localize("BuySubtitle"));await ChatMessage.create({user:requester.id,speaker:{alias:ItemTransfer.#tokenName(targetActor)},type:CONST.CHAT_MESSAGE_TYPES.EMOTE,flavor:flavor2,content:content2});return}else throw ErrorPF2e("Unexpected item-transfer failure");const[speaker,subtitle,formatArgs]=(()=>{const isMerchant=__name2(actor=>actor.isOfType("loot")&&actor.isMerchant,"isMerchant"),isWhat=__name2(actor=>({isCharacter:actor.testUserPermission(requester,"OWNER")&&actor.isOfType("character"),isMerchant:isMerchant(actor),isNPC:actor.isOfType("npc")&&actor.isLootableBy(requester)&&!actor.testUserPermission(requester,"OWNER"),isLoot:(actor.isOfType("party")||actor.isOfType("loot"))&&actor.isLootableBy(requester)&&!actor.testUserPermission(requester,"OWNER")&&!isMerchant(actor)}),"isWhat"),source=isWhat(sourceActor),target=isWhat(targetActor);if(source.isCharacter&&target.isLoot)return[ItemTransfer.#tokenName(sourceActor),localize("DepositSubtitle"),[localize("DepositMessage"),{depositor:ItemTransfer.#tokenName(sourceActor),container:ItemTransfer.#tokenName(targetActor)}]];if(source.isCharacter&&target.isMerchant)return[ItemTransfer.#tokenName(sourceActor),localize("GiveSubtitle"),[localize("GiveMessage"),{giver:ItemTransfer.#tokenName(sourceActor),recipient:ItemTransfer.#tokenName(targetActor)}]];if(source.isCharacter&&target.isNPC)return[ItemTransfer.#tokenName(sourceActor),localize("PlantSubtitle"),[localize("PlantMessage"),{planter:ItemTransfer.#tokenName(sourceActor),corpse:ItemTransfer.#tokenName(targetActor)}]];if(source.isLoot&&target.isCharacter)return[ItemTransfer.#tokenName(targetActor),localize("TakeSubtitle"),[localize("TakeMessage"),{taker:ItemTransfer.#tokenName(targetActor),container:ItemTransfer.#tokenName(sourceActor)}]];if(source.isNPC&&target.isCharacter)return[ItemTransfer.#tokenName(targetActor),localize("LootSubtitle"),[localize("LootMessage"),{looter:ItemTransfer.#tokenName(targetActor),corpse:ItemTransfer.#tokenName(sourceActor)}]];if([source,target].every(actor=>actor.isLoot||actor.isNPC))return[requester.character?.name??requester.name,localize("TransferSubtitle"),[localize("TransferMessage"),{transferrer:requester.character?.name??requester.name,fromContainer:ItemTransfer.#tokenName(sourceActor),toContainer:ItemTransfer.#tokenName(targetActor)}]];if(source.isLoot&&target.isMerchant)return[requester.character?.name??requester.name,localize("GiveSubtitle"),[localize("GiveMessage"),{seller:requester.character?.name??requester.name,buyer:ItemTransfer.#tokenName(targetActor)}]];if(source.isMerchant&&target.isCharacter)return[ItemTransfer.#tokenName(sourceActor),localize("SellSubtitle"),[localize("SellMessage"),{seller:ItemTransfer.#tokenName(sourceActor),buyer:ItemTransfer.#tokenName(targetActor)}]];if(source.isMerchant&&target.isLoot)return[requester.character?.name??requester.name,localize("SellSubtitle"),[localize("SellMessage"),{seller:ItemTransfer.#tokenName(sourceActor),buyer:requester.character?.name??requester.name}]];throw ErrorPF2e("Unexpected item-transfer failure")})(),formatProperties=formatArgs[1];if(!formatProperties)throw ErrorPF2e("Unexpected item-transfer failure");formatProperties.quantity=this.quantity,formatProperties.item=item.name;const content=await renderTemplate(this.#templatePaths.content,{imgPath:item.img,message:game.i18n.format(...formatArgs).replace(/\b1 × /,"")}),flavor=await this.#messageFlavor(sourceActor,targetActor,subtitle);await ChatMessage.create({user:requester.id,speaker:{alias:speaker},type:CONST.CHAT_MESSAGE_TYPES.EMOTE,flavor,content})}async#messageFlavor(sourceActor,targetActor,subtitle){const glyph=getActionGlyph(sourceActor.isOfType("loot")&&targetActor.isOfType("loot")?2:1),action2={title:"PF2E.Actions.Interact.Title",subtitle,glyph},traits=[{name:"manipulate",label:CONFIG.PF2E.featTraits.manipulate,description:CONFIG.PF2E.traitsDescriptions.manipulate}];return await renderTemplate(this.#templatePaths.flavor,{action:action2,traits})}}class ActorSpellcasting extends DelegatedCollection{static{__name(this,"ActorSpellcasting")}static{__name2(this,"ActorSpellcasting")}constructor(actor,entries){super(entries.map(entry=>[entry.id,entry])),this.actor=actor;for(const entry of entries)entry.spells&&this.collections.set(entry.spells.id,entry.spells)}collections=new Collection;get regular(){return this.filter(e=>e instanceof SpellcastingEntryPF2e)}get ritual(){const ritualCasting=this.collections.get("rituals")?.entry;return ritualCasting instanceof RitualSpellcasting?ritualCasting:null}get spellcastingFeatures(){return this.regular.filter(e=>e.isPrepared||e.isSpontaneous)}canCastConsumable(item){const spell=item.embeddedSpell;return!!spell&&this.some(e=>e.canCast(spell,{origin:item}))}refocus(options={}){if(!options.all)throw ErrorPF2e("Actors do not currently support regular refocusing");if(this.actor.isOfType("character","npc")){const focus=this.actor.system.resources.focus,rechargeFocus=focus?.max&&focus.value{if(!(entry instanceof SpellcastingEntryPF2e))return[];if(entry.isFocusPool||!entry.spells)return[];if(entry.isInnate)return entry.spells.map(spell=>{const value=spell.system.location.uses?.max??1;return{_id:spell.id,"system.location.uses.value":value}});const slots=entry.system.slots;let updated=!1;for(const slot of Object.values(slots))if(entry.isPrepared&&!entry.isFlexible)for(const preparedSpell of Object.values(slot.prepared))preparedSpell.expended&&(preparedSpell.expended=!1,updated=!0);else slot.valueu.active),primaryPlayer=this.isToken?null:activeUsers.find(u=>u.character?.id===this.id);return primaryPlayer||(game.users.filter(u=>this.canUserModify(u,"update")).sort((a,b)=>a.id>b.id?1:-1).shift()??null)}get abilities(){return null}get attributes(){return this.system.attributes}get hitPoints(){const{hp}=this.system.attributes;return hp?{value:hp.value,max:hp.max,temp:hp.temp,unrecoverable:hp.unrecoverable,negativeHealing:hp.negativeHealing}:null}get traits(){return new Set(this.system.traits?.value??[])}get level(){return this.system.details.level.value}get size(){return this.system.traits?.size.value??"med"}get dimensions(){const size=this.system.traits?.size??new ActorSizePF2e({value:"med"});return{length:size.length,width:size.width,height:Math.min(size.length,size.width)}}get canSee(){return!0}get canAct(){return!0}get canAttack(){return!1}get isDead(){const deathIcon=game.settings.get("pf2e","deathIcon");if(this.token)return this.token.overlayEffect===deathIcon;const tokens=this.getActiveTokens(!0,!0);return tokens.length>0&&tokens.every(t=>t.overlayEffect===deathIcon)}get modeOfBeing(){const{traits}=this,isPC=isReallyPC(this);return traits.has("undead")&&!traits.has("eidolon")?"undead":traits.has("construct")&&!isPC&&!traits.has("eidolon")?"construct":"living"}get visionLevel(){return VisionLevels.NORMAL}get emitsSound(){return!1}get rollOptions(){return this.flags.pf2e.rollOptions}get heldShield(){return null}get hardness(){return 0}get canHostRuleElements(){return!0}get alliance(){return this.system.details.alliance}get combatant(){return game.combat?.combatants.find(c=>c.actor?.uuid===this.uuid)??null}get temporaryEffects(){const fromConditions=this.conditions.active.map(c=>new TokenEffect(c)),fromEffects=this.itemTypes.effect.filter(e=>e.system.tokenIcon?.show&&(e.isIdentified||game.user.isGM)).map(e=>new TokenEffect(e));return[super.temporaryEffects,fromConditions,fromEffects,this.synthetics.tokenEffectIcons].flat()}isOfType(...types){return types.some(t=>t==="creature"?tupleHasValue(CREATURE_ACTOR_TYPES,this.type):this.type===t)}isAllyOf(actor){return this.alliance!==null&&this!==actor&&this.alliance===actor.alliance}isEnemyOf(actor){return this.alliance!==null&&actor.alliance!==null&&this.alliance!==actor.alliance}isImmuneTo(effect){if(!game.pf2e.settings.iwr)return!1;const item=typeof effect=="string"?null:"parent"in effect?effect:new ItemProxyPF2e(effect),statements=new Set(item?item.getRollOptions("item"):["item:type:condition",`item:slug:${effect}`]);return this.attributes.immunities.some(i=>i.test(statements))}isAffectedBy(damage){const damageType=objectHasKey(CONFIG.PF2E.damageTypes,damage)?damage:damage.isOfType("condition")?damage.system.persistent?.damageType??null:null;if(!setHasElement(UNAFFECTED_TYPES,damageType))return!0;const{traits}=this;return{good:traits.has("evil"),evil:traits.has("good"),lawful:traits.has("chaotic"),chaotic:traits.has("lawful"),vitality:!!this.attributes.hp?.negativeHealing,void:!(this.modeOfBeing==="construct"||this.attributes.hp?.negativeHealing),bleed:this.modeOfBeing==="living",spirit:!this.itemTypes.effect.some(e=>e.traits.has("possession"))}[damageType]}checkItemValidity(source){return itemIsOfType(source,...this.allowedItemTypes)?!0:(ui.notifications.error(game.i18n.format("PF2E.Item.CannotAddType",{type:game.i18n.localize(CONFIG.Item.typeLabels[source.type]??source.type.titleCase())})),!1)}getStatistic(slug){return["armor","ac"].includes(slug)?this.armorClass?.parent??null:tupleHasValue(SAVE_TYPES,slug)?this.saves?.[slug]??null:this.skills&&objectHasKey(this.skills,slug)?this.skills[slug]??null:this.synthetics.statistics.get(slug)??null}getSelfRollOptions(prefix="self"){const{rollOptions}=this;return Object.keys(rollOptions.all).flatMap(o=>o.startsWith("self:")&&rollOptions.all[o]?o.replace(/^self/,prefix):[])}getReach(_options){return 0}getContextualClone(rollOptions,ephemeralEffects=[]){const rollOptionsAll=rollOptions.reduce((options,option)=>({...options,[option]:!0}),{}),applicableEffects=ephemeralEffects.filter(e=>!this.isImmuneTo(e));return this.clone({items:[foundry.utils.deepClone(this._source.items),applicableEffects].flat(),flags:{pf2e:{rollOptions:{all:rollOptionsAll}}}},{keepId:!0})}async applyAreaEffects(aura,origin){if(game.user!==this.primaryUpdater||this.isOfType("party")||!this.allowedItemTypes.includes("effect")||origin.token.hidden)return;const toCreate=[],rollOptions=aura.effects.some(e=>e.predicate.length>0)?new Set([...origin.actor.getRollOptions(),...this.getSelfRollOptions("target")]):new Set([]);for(const data of aura.effects.filter(e=>e.predicate.test(rollOptions)))if(!this.itemTypes.effect.some(e=>e.sourceId===data.uuid)&&auraAffectsActor(data,origin.actor,this)){const effect=await fromUuid(data.uuid);if(!(effect instanceof ItemPF2e&&effect.isOfType("affliction","effect"))){console.warn(`Effect from ${data.uuid} not found`);continue}const flags={core:{sourceId:effect.uuid},pf2e:{aura:{slug:aura.slug,origin:origin.actor.uuid,removeOnExit:data.removeOnExit}}},source=foundry.utils.mergeObject(effect.toObject(),{flags});source.system.level.value=aura.level??source.system.level.value,source.system.duration.unit="unlimited",source.system.duration.expiry=null,source.system.traits.value.length===0&&source.system.traits.value.push(...aura.traits),source.system.context={target:null,origin:{actor:origin.actor.uuid,token:origin.token.uuid,item:null,spellcasting:null},roll:null};for(const alteration of data.alterations)alteration.applyTo(source);toCreate.push(source)}toCreate.length>0&&await this.createEmbeddedDocuments("Item",toCreate)}static async createDialog(data={},context={}){const omittedTypes=[];game.settings.get("pf2e","campaignType")!=="kingmaker"&&omittedTypes.push("army");const original=game.system.documentTypes.Actor;try{if(game.system.documentTypes.Actor=difference(original,omittedTypes),context.types){const validTypes=context.types??[];validTypes.includes("creature")&&validTypes.push(...CREATURE_ACTOR_TYPES),game.system.documentTypes.Actor=game.system.documentTypes.Actor.filter(type=>tupleHasValue(validTypes,type))}return super.createDialog(data,context)}finally{game.system.documentTypes.Actor=original}}static async createDocuments(data=[],context={}){const sources=data.map(d=>d instanceof ActorPF2e?d.toObject():d);for(const source of[...sources]){const linkable=SIZE_LINKABLE_ACTOR_TYPES.has(source.type),linkToActorSize=linkable&&(source.prototypeToken?.flags?.pf2e?.linkToActorSize??!0),autoscale=linkable&&(source.prototypeToken?.flags?.pf2e?.autoscale??(linkToActorSize&&game.settings.get("pf2e","tokens.autoscale"))),merged=foundry.utils.mergeObject(source,{ownership:source.ownership??{default:CONST.DOCUMENT_OWNERSHIP_LEVELS.NONE},prototypeToken:{flags:{pf2e:{linkToActorSize,autoscale}}}}),dimensionMap={familiar:.5,vehicle:2};switch(merged.prototypeToken.height??=dimensionMap[source.type]??1,merged.prototypeToken.width??=merged.prototypeToken.height,merged.type){case"character":case"familiar":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!0};break;case"loot":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!1};break;case"party":merged.ownership.default=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER,merged.prototypeToken.actorLink=!0,merged.prototypeToken.sight={enabled:!0,range:1};break}const migrated=await migrateActorSource(source);sources.splice(sources.indexOf(source),1,migrated)}return super.createDocuments(sources,context)}static async updateDocuments(updates=[],context={}){for(const changed of updates)await processPreUpdateActorHooks(changed,{pack:context.pack??null});return super.updateDocuments(updates,context)}_initialize(options){this.constructed??=!1,this._itemTypes=null,this.rules=[],this.initiative=null,this.armorClass=null,this.conditions=new ActorConditions,this.auras=new Map;const preparationWarnings=new Set;this.synthetics={criticalSpecalizations:{standard:[],alternate:[]},damageDice:{damage:[]},degreeOfSuccessAdjustments:{},dexterityModifierCaps:[],modifierAdjustments:{all:[],damage:[]},modifiers:{all:[],damage:[]},movementTypes:{},multipleAttackPenalties:{},ephemeralEffects:{},rollNotes:{},rollSubstitutions:{},rollTwice:{},senses:[],statistics:new Map,strikeAdjustments:[],strikes:new Map,striking:{},tokenMarks:new Map,toggles:[],tokenEffectIcons:[],tokenOverrides:{},weaponPotency:{},preparationWarnings:{add:warning=>preparationWarnings.add(warning),flush:foundry.utils.debounce(()=>{for(const warning of preparationWarnings)console.warn(warning);preparationWarnings.clear()},10)}},super._initialize(options),game._documentsReady&&this.synthetics.preparationWarnings.flush()}_initializeSource(source,options){const initialized=super._initializeSource(source,options);if(options?.pack&&initialized._id){const uuid=`Compendium.${options.pack}.${initialized._id}`,art=game.pf2e.system.moduleArt.map.get(uuid)??{};return foundry.utils.mergeObject(initialized,art)}return initialized}prepareData(){this.signature??=UUIDv5(this.uuid,"e9fa1461-0edc-4791-826e-08633f1c6ef7"),super.prepareData();const spellcasting=this.itemTypes.spellcastingEntry,traditionBased=spellcasting.filter(s=>setHasElement(MAGIC_TRADITIONS,s.system.proficiency.slug)),nonTraditionBased=spellcasting.filter(s=>!traditionBased.includes(s));for(const entry of traditionBased)entry.prepareStatistic();for(const rule of this.rules)rule.afterPrepareData?.();for(const entry of nonTraditionBased)entry.prepareStatistic();if(this.attributes.flanking.offGuardable&&this.isImmuneTo("off-guard")&&(this.attributes.flanking.offGuardable=!1),this.preparePrototypeToken(),this.constructed&&canvas.ready){const thisTokenIsControlled=canvas.tokens.controlled.some(t=>t.document===this.parent||t.document.actorLink&&t.actor===this);(game.user.character===this||thisTokenIsControlled)&&game.pf2e.effectPanel.refresh()}}prepareBaseData(){super.prepareBaseData(),this.system.autoChanges={},this.system.attributes.flanking={canFlank:!1,canGangUp:[],flankable:!1,offGuardable:!1};const{attributes,details}=this.system;attributes.hp&&=foundry.utils.mergeObject(attributes.hp,{negativeHealing:!1,unrecoverable:0}),attributes.immunities=attributes.immunities?.map(i=>new Immunity(i))??[],attributes.weaknesses=attributes.weaknesses?.map(w=>new Weakness(w))??[],attributes.resistances=attributes.resistances?.map(r=>new Resistance(r))??[],details.level.value=Math.floor(details.level.value)||0;const traits=this.system.traits;traits?.size&&(traits.size=new ActorSizePF2e(traits.size)),this.flags.pf2e=foundry.utils.mergeObject(this.flags.pf2e??{},{rollOptions:{all:{[`self:type:${this.type}`]:!0,[`self:signature:${this.signature}`]:!0,...createEncounterRollOptions(this)}},trackedItems:{}})}prepareEmbeddedDocuments(){for(const item of this.items)item.reset();const physicalItems=this.items.filter(i=>i.isOfType("physical"));this.inventory=new ActorInventory(this,physicalItems),this.spellcasting=(()=>{const rituals=this.itemTypes.spell.filter(s=>s.isRitual).sort((a,b)=>a.sort-b.sort),spellcastingEntries=[this.itemTypes.spellcastingEntry,rituals.length>0?new RitualSpellcasting(this,rituals):[]].flat();return new ActorSpellcasting(this,spellcastingEntries)})();for(const effect of this.itemTypes.effect)game.pf2e.effectTracker.register(effect);this.prepareDataFromItems()}prepareDataFromItems(){for(const condition of this.itemTypes.condition)this.conditions.set(condition.id,condition);for(const item of this.items)item.prepareSiblingData?.(),item.prepareActorData?.();this.rules=this.prepareRuleElements()}prepareRuleElements(){return sortBy(this.items.contents,i=>i instanceof AbstractEffectPF2e).flatMap(item=>item.prepareRuleElements()).filter(rule=>!rule.ignored).sort((elementA,elementB)=>elementA.priority-elementB.priority)}prepareSynthetics(){for(const rule of this.rules.filter(r=>!r.ignored))try{rule.beforePrepareData?.()}catch(error){const ruleName=game.i18n.localize(`PF2E.RuleElement.${rule.key}`);console.error(`PF2e | Failed to execute onBeforePrepareData on rule element ${ruleName}.`,error)}for(const item of this.items)item.onPrepareSynthetics?.()}prepareDerivedData(){const{rollOptions}=this;for(const trait of this.traits)rollOptions.all[`self:trait:${trait}`]=!0;this.spellcasting.base=new Statistic(this,{slug:"base-spellcasting",label:"PF2E.Actor.Creature.Spellcasting.Label",rank:this.isOfType("character")?this.system.proficiencies.spellcasting.rank:0,domains:["all","spell-attack-dc"],check:{type:"attack-roll"}})}preparePrototypeToken(){this.prototypeToken.flags=foundry.utils.mergeObject({pf2e:{linkToActorSize:SIZE_LINKABLE_ACTOR_TYPES.has(this.type)}},this.prototypeToken.flags),TokenDocumentPF2e.assignDefaultImage(this.prototypeToken),TokenDocumentPF2e.prepareSize(this.prototypeToken)}async getRollContext(params){const[selfToken,targetToken]=canvas.ready&&!params.viewOnly?[canvas.tokens.controlled.find(t=>t.actor===this)??this.getActiveTokens().shift()??null,params.target?.token??params.target?.actor?.getActiveTokens().shift()??null]:[null,null],isAttackAction=["attack","attack-roll","attack-damage"].some(d=>params.domains.includes(d)),isMelee=!!(params.melee||params.item?.isOfType("weapon","melee")&¶ms.item.isMelee),reach=isMelee&¶ms.item?.isOfType("action","weapon","melee")?this.getReach({action:"attack",weapon:params.item}):this.getReach({action:"attack"}),isFlankingAttack=!!(isAttackAction&&isMelee&&typeof reach=="number"&&targetToken?.actor&&selfToken?.isFlanking(targetToken,{reach})),originEphemeralEffects=await extractEphemeralEffects({affects:"origin",origin:this,target:params.target?.actor??targetToken?.actor??null,item:params.item??null,domains:params.domains,options:[...params.options,...params.item?.getRollOptions("item")??[]]}),targetMarkOption=(()=>{const tokenMark=targetToken?this.synthetics.tokenMarks.get(targetToken.document.uuid):null;return tokenMark?`target:mark:${tokenMark}`:null})(),initialActionOptions=params.traits?.map(t=>`self:action:trait:${t}`)??[],selfActor=params.viewOnly||!targetToken?.actor?this:this.getContextualClone(compact([...Array.from(params.options),...targetToken.actor.getSelfRollOptions("target"),targetMarkOption,...initialActionOptions,isFlankingAttack?"self:flanking":null]),originEphemeralEffects),isStrike=params.statistic instanceof StatisticModifier,strikeActions=isStrike?selfActor.system.actions?.flatMap(a=>[a,a.altUsages??[]].flat())??[]:[],statistic=params.viewOnly?params.statistic:isStrike?strikeActions.find(action2=>params.item?.id!==action2.item.id||params?.item.name!==action2.item.name?!1:params.item.isOfType("melee")&&action2.item.isOfType("melee")?!0:params.item.isOfType("weapon")&&action2.item.isOfType("weapon")&¶ms.item.isMelee===action2.item.isMelee)??params.statistic:params.statistic,selfItem=(()=>{if(selfActor===this)return params.item??null;if(statistic&&"item"in statistic&&statistic.item instanceof ItemPF2e&&statistic.item.isOfType("action","melee","spell","weapon"))return statistic.item;const itemClone=selfActor.items.get(params.item?.id??"");return itemClone?.isOfType("melee","weapon")?itemClone:params.item??null})(),itemOptions=selfItem?.getRollOptions("item")??[],actionTraits2=(()=>{const traits=compact([params.traits].flat());if(selfItem?.isOfType("weapon","melee")){const strikeAdjustments=[selfActor.synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(selfItem.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(selfItem,traits)}return uniq(traits).sort()})(),distance=selfToken&&targetToken?selfToken.distanceTo(targetToken):null,[originDistance,targetDistance]=typeof distance=="number"?[`origin:distance:${distance}`,`target:distance:${distance}`]:[null,null],originMarkOption=(()=>{const tokenMark=selfToken?targetToken?.actor?.synthetics.tokenMarks.get(selfToken.document.uuid):null;return tokenMark?`origin:mark:${tokenMark}`:null})(),originRollOptions=selfToken&&targetToken?compact(uniq([...selfActor.getSelfRollOptions("origin"),...actionTraits2.map(t=>`origin:action:trait${t}`),...originDistance?[originDistance]:[],originMarkOption])):[],getTargetRollOptions=__name2(actor=>{const targetOptions=actor?.getSelfRollOptions("target")??[];return targetToken&&(targetOptions.push("target"),targetMarkOption&&targetOptions.push(targetMarkOption)),targetOptions.sort()},"getTargetRollOptions"),targetRollOptions=getTargetRollOptions(targetToken?.actor),targetEphemeralEffects=await extractEphemeralEffects({affects:"target",origin:selfActor,target:targetToken?.actor??null,item:selfItem,domains:params.domains,options:[...params.options,...itemOptions,...targetRollOptions]});if(isFlankingAttack&&isOffGuardFromFlanking(targetToken.actor,selfActor,originRollOptions)){const name2=game.i18n.localize("PF2E.Item.Condition.Flanked"),condition=game.pf2e.ConditionManager.getCondition("off-guard",{name:name2});targetEphemeralEffects.push(condition.toObject())}const targetActor=params.viewOnly?null:(params.target?.actor??targetToken?.actor)?.getContextualClone(compact([...params.options,...itemOptions,...originRollOptions]),targetEphemeralEffects)??null,rollOptions=new Set(compact([...params.options,...selfActor.getRollOptions(params.domains),...targetActor?getTargetRollOptions(targetActor):targetRollOptions,...actionTraits2.map(t=>`self:action:trait:${t}`),...itemOptions,isAttackAction?"attack":null]).sort());targetDistance&&rollOptions.add(targetDistance);const rangeIncrement=selfItem?getRangeIncrement(selfItem,distance):null;rangeIncrement&&rollOptions.add(`target:range-increment:${rangeIncrement}`);const self={actor:selfActor,token:selfToken?.document??null,statistic,item:selfItem,modifiers:[]},target=targetActor&&targetToken&&distance!==null?{actor:targetActor,token:targetToken.document,distance,rangeIncrement}:null;return{options:rollOptions,self,target,traits:actionTraits2}}async getCheckContext(params){const context=await this.getRollContext(params),targetActor=context.target?.actor,rangeIncrement=context.target?.rangeIncrement??null,rangePenalty=calculateRangePenalty(this,rangeIncrement,params.domains,context.options);rangePenalty&&context.self.modifiers.push(rangePenalty);const dcData=(()=>{const{domains,defense}=params,scope=domains.includes("attack")?"attack":"check",statistic=targetActor?.getStatistic(defense)?.dc;return statistic?{scope,statistic,slug:defense,value:statistic.value}:null})();return{...context,dc:dcData}}async getDamageRollContext(params){params.checkContext??=findMatchingCheckContext(this,params),params.outcome&¶ms.options.add(`check:outcome:${sluggify(params.outcome)}`);const substitution=params.checkContext?.substitutions.find(s=>s.selected);return substitution&¶ms.options.add(`check:substitution:${substitution.slug}`),this.getRollContext(params)}async toggleRollOption(domain,option,itemId=null,value,suboption=null){return value=typeof itemId=="boolean"?itemId:value??!this.rollOptions[domain]?.[option],typeof itemId=="string"?this.items.get(itemId,{strict:!0}).rules.find(r=>r instanceof RollOptionRuleElement&&r.domain===domain&&r.option===option)?.toggle(value,suboption)??null:this.rules.find(r=>r instanceof RollOptionRuleElement&&r.domain===domain&&r.option===option)?.toggle(value,suboption)??null}async modifyTokenAttribute(attribute,value,isDelta=!1,isBar){const token=this.getActiveTokens(!0,!0).shift(),{hitPoints}=this;if(!!(attribute==="attributes.hp"&&hitPoints&&(isDelta||value===0&&token?.combatant))&&token){const damage=isDelta?-1*value:hitPoints.value-value;return this.applyDamage({damage,token})}return super.modifyTokenAttribute(attribute,value,isDelta,isBar)}async applyDamage({damage,token,item,rollOptions=new Set,skipIWR=!1,shieldBlockRequest=!1,breakdown=[],notes=[]}){const{hitPoints}=this;if(!hitPoints)return this;const result=typeof damage=="number"?{finalDamage:Math.trunc(damage),applications:[],persistent:[]}:skipIWR?{finalDamage:damage.total,applications:[],persistent:[]}:applyIWR(this,damage,rollOptions),{finalDamage}=result,localize=localizer("PF2E.Actor.ApplyDamage"),actorShield=this.isOfType("character","npc")?this.attributes.shield:null,shieldBlock=actorShield&&shieldBlockRequest?(()=>actorShield.broken?(ui.notifications.warn(game.i18n.format("PF2E.Actions.RaiseAShield.ShieldIsBroken",{actor:token.name,shield:actorShield.name})),!1):actorShield.destroyed?(ui.notifications.warn(game.i18n.format("PF2E.Actions.RaiseAShield.ShieldIsDestroyed",{actor:token.name,shield:actorShield.name})),!1):actorShield.raised?!0:(ui.notifications.warn(localize("ShieldNotRaised",{actor:token.name})),!1))():!1,shieldHardness=shieldBlock?actorShield?.hardness??0:0,damageAbsorbedByShield=finalDamage>0?Math.min(shieldHardness,finalDamage):0,{heldShield}=this,blockingShield=heldShield?.id===actorShield?.itemId?heldShield:null,currentShieldHP=blockingShield?blockingShield._source.system.hp.value:actorShield?.hp.value??0,shieldDamage=shieldBlock?Math.min(currentShieldHP,Math.abs(finalDamage)-damageAbsorbedByShield):0,baseActorHardness=this.hardness,effectiveActorHardness=(()=>{const damageHasAdamantine=typeof damage=="number"?!1:damage.materials.has("adamantine"),materialGrade=item?.isOfType("weapon")&&item.system.material.type==="adamantine"?item.system.material.grade??"standard":"standard",itemHardness={low:0,standard:10,high:13}[materialGrade];return damageHasAdamantine&&itemHardness>=baseActorHardness?Math.floor(baseActorHardness/2):baseActorHardness})(),damageAbsorbedByActor=finalDamage>0?Math.min(finalDamage-damageAbsorbedByShield,effectiveActorHardness):0;if(damageAbsorbedByActor>0){const typeLabel=effectiveActorHardness===baseActorHardness?"PF2E.Damage.Hardness.Full":"PF2E.Damage.Hardness.Half";result.applications.push({category:"reduction",type:game.i18n.localize(typeLabel),adjustment:-1*damageAbsorbedByActor})}const damageResult=this.calculateHealthDelta({hp:hitPoints,sp:this.isOfType("character")?this.attributes.hp.sp:null,delta:finalDamage-damageAbsorbedByShield-damageAbsorbedByActor}),preUpdateSource=this.toObject();blockingShield&&shieldDamage>0&&await blockingShield.update({"system.hp.value":Math.max(blockingShield._source.system.hp.value-shieldDamage,0)},{render:damageResult.totalApplied===0});const staminaMax=this.isOfType("character")?this.attributes.hp.sp?.max??0:0,instantDeath=(()=>damageResult.totalApplied<=0||damageResult.updates["system.attributes.hp.value"]!==0?null:rollOptions.has("item:trait:death")&&!this.attributes.immunities.some(i=>i.type==="death-effects")?"death-effect":rollOptions.has("item:type:spell")&&rollOptions.has("item:slug:disintegrate")?"fine-powder":this.isOfType("npc")&&this.modeOfBeing==="undead"?"destroyed":damageResult.totalApplied>=(hitPoints.max+staminaMax)*2?"massive-damage":null)(),finePowder=instantDeath==="fine-powder";if(damageResult.totalApplied!==0){const updated=await this.update(damageResult.updates,{damageTaken:damageResult.totalApplied,finePowder}),setting=game.settings.get("pf2e","automation.actorsDeadAtZero"),deadAtZero=this.isOfType("npc")&&["npcsOnly","both"].includes(setting)||this.isOfType("character")&&setting==="both"&&!!instantDeath;updated?.isDead&&deadAtZero&&(damageResult.totalApplied>=0&&!token.combatant?.isDefeated||damageResult.totalApplied<0&&token.combatant?.isDefeated)&&token.combatant?.toggleDefeated({overlayIcon:!finePowder}).then(()=>{finePowder&&this.createEmbeddedDocuments("Item",[createDisintegrateEffect()])})}const hpStatement=(()=>hitPoints.max===0||finalDamage-damageAbsorbedByActor===0?localize("TakesNoDamage"):finalDamage>0?damageAbsorbedByShield>0?damageResult.totalApplied>0?localize("DamagedForNShield"):localize("ShieldAbsorbsAll"):localize("DamagedForN"):damageResult.totalApplied<0?localize("HealedForN"):localize("AtFullHealth"))(),updatedShield=this.isOfType("character","npc")?this.attributes.shield:null,shieldStatement=updatedShield&&shieldDamage>0?updatedShield.broken?localize("ShieldDamagedForNBroken"):updatedShield.destroyed?localize("ShieldDamagedForNDestroyed"):localize("ShieldDamagedForN"):null,statements=(()=>{const deathMessage=instantDeath&&localize(`InstantDeath.${sluggify(instantDeath,{camel:"bactrian"})}`),concatenated=compact([hpStatement,shieldStatement,deathMessage]).map(s=>game.i18n.format(s,{actor:token.name.replace(/[<>]/g,""),hpDamage:Math.abs(damageResult.totalApplied),absorbedDamage:damageAbsorbedByShield,shieldDamage})).join(" "),tempElem=document.createElement("div");return tempElem.innerHTML=concatenated,TextEditorPF2e.convertXMLNode(tempElem,"actor",{whose:null,classes:["target-name"]}),tempElem.innerHTML})(),deparenthesize=__name2(formula=>formula.replace(/^\(([^)]+)\)$/,"$1"),"deparenthesize"),persistentDamage=result.persistent.map(instance=>{const condition=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject();return condition.system.persistent={formula:deparenthesize(instance.head.expression),damageType:instance.type,dc:15},condition}),persistentCreated=persistentDamage.length>0?await this.createEmbeddedDocuments("Item",persistentDamage):[],canUndoDamage=!!(damageResult.totalApplied||shieldDamage||persistentCreated.length),content=await renderTemplate("systems/pf2e/templates/chat/damage/damage-taken.hbs",{breakdown,notes,statements,persistent:compact(persistentCreated.map(p=>p.system.persistent?.damage.formula)),iwr:{applications:result.applications,visibility:this.hasPlayerOwner?"all":"gm"},canUndoDamage}),flavor=await(async()=>{if(breakdown.length||notes.length)return renderTemplate("systems/pf2e/templates/chat/damage/damage-taken-flavor.hbs",{breakdown,notes})})(),appliedDamage=canUndoDamage?{uuid:this.uuid,isHealing:damageResult.totalApplied<0,shield:shieldDamage!==0?{id:actorShield?.itemId??"",damage:shieldDamage}:null,persistent:persistentCreated.map(c=>c.id),updates:Object.entries(damageResult.updates).map(([path,newValue])=>{const preUpdateValue=foundry.utils.getProperty(preUpdateSource,path);if(typeof preUpdateValue=="number"){const difference2=preUpdateValue-newValue;return difference2===0?[]:{path,value:difference2}}return[]}).flat()}:null;return await ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({token}),flags:{pf2e:{appliedDamage}},flavor,content,type:CONST.CHAT_MESSAGE_TYPES.OTHER,whisper:game.settings.get("pf2e","metagame_secretDamage")&&!token.actor?.hasPlayerOwner?ChatMessagePF2e.getWhisperRecipients("GM").map(u=>u.id):[]}),this}async undoDamage(appliedDamage){const{updates,shield,persistent}=appliedDamage,actorUpdates={};for(const update of updates){const currentValue=foundry.utils.getProperty(this,update.path);typeof currentValue=="number"&&(actorUpdates[update.path]=currentValue+update.value)}if(shield){const item=this.inventory.get(shield.id);item&&(actorUpdates.items=[{_id:shield.id,"system.hp.value":item.hitPoints.value+shield.damage}])}const updateCount=Object.keys(actorUpdates).length;if(persistent.length&&await this.deleteEmbeddedDocuments("Item",persistent,{render:updateCount===0}),updateCount){const{hitPoints}=this,damageTaken=hitPoints&&typeof actorUpdates["system.attributes.hp.value"]=="number"?hitPoints.value-actorUpdates["system.attributes.hp.value"]:0;this.update(actorUpdates,{damageTaken,damageUndo:!0})}}isLootableBy(user){return this.canUserModify(user,"update")}async transferItemToActor(targetActor,item,quantity,containerId,newStack=!1){if(!(item instanceof PhysicalItemPF2e))throw ErrorPF2e("Only physical items (with quantities) can be transfered between actors");const container=targetActor.inventory.get(containerId??"");if(!(!container||container instanceof ContainerPF2e))throw ErrorPF2e("containerId refers to a non-container");if(__name2((source,target)=>{const bothAreOwned=source.isOwner&&target.isOwner,sourceIsOwnedOrLoot=source.isLootableBy(game.user),targetIsOwnedOrLoot=target.isLootableBy(game.user);return!bothAreOwned&&sourceIsOwnedOrLoot&&targetIsOwnedOrLoot},"gmMustTransfer")(this,targetActor)){const source={tokenId:this.token?.id,actorId:this.id,itemId:item.id},target={tokenId:targetActor.token?.id,actorId:targetActor.id};return await new ItemTransfer(source,target,quantity,container?.id).request(),null}if(!this.canUserModify(game.user,"update"))return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.CantMoveItemSource")),null;if(!targetActor.canUserModify(game.user,"update"))return ui.notifications.error(game.i18n.localize("PF2E.ErrorMessage.CantMoveItemDestination")),null;quantity=Math.min(quantity,item.quantity);const newQuantity=item.quantity-quantity;newQuantity<1?await item.delete():await item.update({"system.quantity":newQuantity});const newItemData=item.toObject();return newItemData.system.quantity=quantity,newItemData.system.equipped.carryType="worn",hasInvestedProperty(newItemData)&&(newItemData.system.equipped.invested=item.traits.has("invested")?!1:null),targetActor.addToInventory(newItemData,container,newStack)}async addToInventory(itemSource,container,newStack){const stackItem=this.inventory.findStackableItem(itemSource);if(!newStack&&stackItem&&stackItem.type!=="backpack"){const stackQuantity=stackItem.quantity+itemSource.system.quantity;return await stackItem.update({"system.quantity":stackQuantity}),stackItem}const result=await ItemPF2e.create(itemSource,{parent:this});if(!result)return null;const movedItem=this.inventory.get(result.id);return movedItem?(await this.stowOrUnstow(movedItem,container),movedItem):null}async stowOrUnstow(item,container){if(!container)await item.update({"system.containerId":null,"system.equipped.carryType":"worn","system.equipped.handsHeld":0,"system.equipped.inSlot":!1});else if(!isCycle(item,container)){const carryType=container.stowsItems?"stowed":"worn";await item.update({"system.containerId":container.id,"system.equipped.carryType":carryType,"system.equipped.handsHeld":0,"system.equipped.inSlot":!1})}}calculateHealthDelta(args){const updates={},{hp,sp,delta}=args;if(hp.max===0)return{updates,totalApplied:0};const appliedToTemp=(()=>{if(!hp.temp||delta<=0)return 0;const applied=Math.min(hp.temp,delta);return updates["system.attributes.hp.temp"]=Math.max(hp.temp-applied,0),applied})(),appliedToSP=(()=>{if(!(!!sp&&game.pf2e.settings.variants.stamina)||delta<=0)return 0;const remaining=delta-appliedToTemp,applied=Math.min(sp.value,remaining);return updates["system.attributes.hp.sp.value"]=Math.max(sp.value-applied,0),applied})(),appliedToHP=(()=>{const remaining=delta-appliedToTemp-appliedToSP;return updates["system.attributes.hp.value"]=Math.clamped(hp.value-remaining,0,hp.max),remaining})(),totalApplied=appliedToTemp+appliedToSP+appliedToHP;return{updates,totalApplied}}getRollOptions(domains=[]){const withAll=Array.from(new Set(["all",...domains])),{rollOptions}=this,toReturn=new Set;for(const domain of withAll)for(const[option,value]of Object.entries(rollOptions[domain]??{}))value&&toReturn.add(option);return Array.from(toReturn)}getRollData(){const rollData={actor:this};for(const prop of["abilities","attributes","details","skills","saves"])Object.defineProperty(rollData,prop,{get:()=>(foundry.utils.logCompatibilityWarning(`@${prop} is deprecated`,{since:"5.0.1",until:"6"}),objectHasKey(this.system,prop)?foundry.utils.deepClone(this.system[prop]):null)});return rollData}getCondition(slugOrKey,{all=!1}={}){const conditions=this.conditions.filter(c=>c.key===slugOrKey||c.slug===slugOrKey);return all?conditions.sort((conditionA,conditionB)=>{const[valueA,valueB]=[conditionA.value??0,conditionB.value??0];return valueA>valueB?-1:valueAc.active)??null}hasCondition(...slugs){return slugs.some(s=>this.conditions.bySlug(s,{active:!0}).length>0)}async decreaseCondition(conditionSlug,{forceRemove}={forceRemove:!1}){const condition=typeof conditionSlug=="string"?this.getCondition(conditionSlug):conditionSlug;if(!condition)return;if(condition.slug==="persistent-damage"){const matching=this.conditions.stored.filter(c=>c.key===condition.key).map(c=>c.id);await this.deleteEmbeddedDocuments("Item",matching);return}const currentValue=condition._source.system.value.value,newValue=typeof currentValue=="number"?Math.max(currentValue-1,0):null;newValue!==null&&!forceRemove?await game.pf2e.ConditionManager.updateConditionValue(condition.id,this,newValue):await this.deleteEmbeddedDocuments("Item",[condition.id])}async increaseCondition(conditionSlug,{max=Number.MAX_SAFE_INTEGER,value}={}){if(conditionSlug==="persistent-damage")return await new PersistentDamageDialog(this).render(!0),null;const existing=(()=>{if(typeof conditionSlug!="string")return conditionSlug;const conditions=this.itemTypes.condition;return value?conditions.find(c=>c.slug===conditionSlug&&!c.isLocked):conditions.find(c=>c.slug===conditionSlug&&c.active)})();if(existing){const newValue=(()=>{const currentValue=existing._source.system.value.value;if(currentValue===null)return null;const addend=value??1;return Math.clamped(currentValue+addend,1,max)})();return newValue?(await game.pf2e.ConditionManager.updateConditionValue(existing.id,this,newValue),existing):null}else if(typeof conditionSlug=="string"){const conditionSource=game.pf2e.ConditionManager.getCondition(conditionSlug).toObject(),conditionValue=typeof conditionSource.system.value.value=="number"&&max?Math.clamped(conditionSource.system.value.value,value??1,max):null;return conditionSource.system.value.value=conditionValue,(await this.createEmbeddedDocuments("Item",[conditionSource])).shift()??null}return null}async toggleCondition(conditionSlug){if(!setHasElement(CONDITION_SLUGS,conditionSlug))throw ErrorPF2e(`Unrecognized condition: ${conditionSlug}`);this.hasCondition(conditionSlug)?await this.decreaseCondition(conditionSlug,{forceRemove:!0}):await this.increaseCondition(conditionSlug)}async importFromJSON(json2){const processed=await preImportJSON(this,json2);return processed?super.importFromJSON(processed):this}_applyDefaultTokenSettings(data,options){const diff=super._applyDefaultTokenSettings(data,options);return this._source.prototypeToken.texture.src===CONST.DEFAULT_TOKEN&&(this._source.prototypeToken.texture.src=ActorPF2e.getDefaultArtwork(data).texture.src),diff}async _preUpdate(changed,options,user){const changedHP=changed.system?.attributes?.hp,currentHP=this.hitPoints;if(!options.damageTaken&&this.hasPlayerOwner&&typeof changedHP?.value=="number"&¤tHP){const damageTaken=-1*(changedHP.value-currentHP.value),levelChanged=!!changed.system?.details&&"level"in changed.system.details;damageTaken&&!levelChanged&&(options.damageTaken=damageTaken)}return super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const hideFromUser=!this.hasPlayerOwner&&!game.user.isGM&&game.settings.get("pf2e","metagame_secretDamage");if(options.damageTaken&&!hideFromUser){const tokens=this.getActiveTokens();for(const token of tokens)token.showFloatyText(-1*options.damageTaken)}if(canvas.ready&&changed.system?.details&&"alliance"in changed.system.details)for(const token of this.getActiveTokens(!0,!0))token.reset();const currentHP=this.hitPoints?.value??0,hpChange=Number(changed.system?.attributes?.hp?.value)||0;if(currentHP>0&&hpChange>0&&this.isDead){const{combatant}=this;if(combatant)combatant.toggleDefeated({to:!1});else for(const tokenDoc of this.getActiveTokens(!1,!0))tokenDoc.update({overlayEffect:""})}}_onDelete(options,userId){for(const effect of this.itemTypes.effect)game.pf2e.effectTracker.unregister(effect);super._onDelete(options,userId)}_onEmbeddedDocumentChange(){super._onEmbeddedDocumentChange(),this.synthetics.preparationWarnings.flush()}}const ActorProxyPF2e=new Proxy(ActorPF2e,{construct(_target,args){return new CONFIG.PF2E.Actor.documentClasses[args[0].type](...args)}});class CreaturePF2e extends ActorPF2e{static{__name(this,"CreaturePF2e")}static{__name2(this,"CreaturePF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"affliction"]}get creatureTypes(){return this.system.traits.value.filter(t=>t in CONFIG.PF2E.creatureTypes).sort()}get rarity(){return this.system.traits.rarity}get hardness(){return Math.floor(Math.abs(this.system.attributes.hardness.value))||0}getReach({action:action2="interact",weapon=null}={}){const baseReach=this.attributes.reach.base,weaponReach=weapon?.isOfType("melee")?weapon.reach:null;if(action2==="interact"||this.type==="familiar")return baseReach;if(typeof weaponReach=="number")return weaponReach;{const traitsFromItems=(weapon?[{item:weapon,ready:!0}]:this.system.actions??[]).filter(a=>a.ready).map(a=>new Set(a.item.system.traits?.value??[]));if(traitsFromItems.length===0)return baseReach;const reaches=traitsFromItems.map(traits=>{if(setHasElement(traits,"reach"))return baseReach+5;const reachNPattern=/^reach-\d{1,3}$/;return Number([...traits].find(t=>reachNPattern.test(t))?.replace("reach-",""))||baseReach});return Math.max(...reaches)}}get visionLevel(){const{senses:senses2}=this.system.traits;if(!(Array.isArray(senses2)&&senses2.every(s=>isObject(s)&&"type"in s&&typeof s.type=="string")))return VisionLevels.NORMAL;const senseTypes=new Set(senses2.map(sense=>sense.type));return this.getCondition("blinded")?VisionLevels.BLINDED:senseTypes.has("darkvision")||senseTypes.has("greaterDarkvision")?VisionLevels.DARKVISION:senseTypes.has("lowLightVision")?VisionLevels.LOWLIGHT:VisionLevels.NORMAL}get hasDarkvision(){return this.visionLevel===VisionLevels.DARKVISION&&!this.hasCondition("blinded")}get hasLowLightVision(){return this.visionLevel>=VisionLevels.LOWLIGHT&&!this.hasCondition("blinded")}get canSee(){return canvas.scene?this.visionLevel===VisionLevels.BLINDED?!1:canvas.scene.lightLevel>LightLevels.DARKNESS||this.hasDarkvision:!0}get canAct(){const traits=this.system.traits.value;return(!this.isDead||traits.some(t=>t==="eidolon"))&&!this.hasCondition("paralyzed","stunned","unconscious")}get canAttack(){return this.type!=="familiar"&&this.canAct}get isDead(){const{hitPoints}=this;return hitPoints.max>0&&hitPoints.value===0&&!this.hasCondition("dying","unconscious")?!0:!!(this.token??this.getActiveTokens(!1,!0).shift())?.hasStatusEffect("dead")}get emitsSound(){return this.system.attributes.emitsSound}get isSpellcaster(){const{itemTypes}=this;return itemTypes.spellcastingEntry.length>0&&itemTypes.spell.length>0}get wornArmor(){return this.itemTypes.armor.find(a=>a.isEquipped)??null}get heldShield(){const heldShields=this.itemTypes.shield.filter(s=>s.isEquipped);return heldShields.length===0?null:heldShields.slice(0,-1).reduce((bestShield,shield)=>{if(bestShield===shield)return bestShield;const withBetterAC=bestShield.acBonus>shield.acBonus?bestShield:shield.acBonus>bestShield.acBonus?shield:null,withMoreHP=bestShield.hitPoints.value>shield.hitPoints.value?bestShield:shield.hitPoints.value>bestShield.hitPoints.value?shield:null,withBetterHardness=bestShield.hardness>shield.hardness?bestShield:shield.hardness>bestShield.hardness?shield:null;return withBetterAC??withMoreHP??withBetterHardness??bestShield},heldShields.slice(-1)[0])}getStatistic(slug){switch(slug){case"perception":return this.perception;case"spell":case"spell-attack":return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).sort((a,b)=>b.mod-a.mod).shift()??null;case"spell-dc":return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).sort((a,b)=>b.dc.value-a.dc.value).shift()??null}return this.spellcasting.contents.flatMap(sc=>sc.statistic??[]).find(s=>s.slug===slug)??super.getStatistic(slug)}_initialize(options){this.parties??=new Set,super._initialize(options)}prepareData(){super.prepareData();for(const party of this.parties)party.reset({actor:!0})}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e.rollOptions.all["self:creature"]=!0;const attributes=this.system.attributes;attributes.hardness??={value:0},attributes.flanking.canFlank=!0,attributes.flanking.flankable=!0,attributes.flanking.offGuardable=!0,attributes.reach={base:0,manipulate:0},attributes.speed=foundry.utils.mergeObject({total:0,value:0},attributes.speed??{}),attributes.initiative&&(attributes.initiative.tiebreakPriority=this.hasPlayerOwner?2:1);const customModifiers=this.system.customModifiers??={};for(const selector of Object.keys(customModifiers))customModifiers[selector]=customModifiers[selector].map(rawModifier=>new ModifierPF2e(rawModifier));this.isOfType("character","npc")&&(this.system.attributes.shield={itemId:null,name:game.i18n.localize("PF2E.ArmorTypeShield"),ac:0,hp:{value:0,max:0},brokenThreshold:0,hardness:0,raised:!1,broken:!1,destroyed:!1,icon:"systems/pf2e/icons/actions/raise-a-shield.webp"}),attributes.doomed={value:0,max:3},attributes.dying={value:0,max:4,recoveryDC:10},attributes.wounded={value:0,max:3},setImmunitiesFromTraits(this)}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.();for(const changeEntries of Object.values(this.system.autoChanges))changeEntries?.sort((a,b)=>Number(a.level)>Number(b.level)?1:-1);this.rollOptions.all[`self:mode:${this.modeOfBeing}`]=!0}prepareDerivedData(){super.prepareDerivedData();const{attributes}=this,reachFromSize=SIZE_TO_REACH[this.size];attributes.reach.base=Math.max(attributes.reach.base,reachFromSize),attributes.reach.manipulate=Math.max(attributes.reach.manipulate,attributes.reach.base,reachFromSize);const{rollOptions}=this;this.isSpellcaster&&(rollOptions.all["self:caster"]=!0),this.hitPoints.negativeHealing&&(rollOptions.all["self:negative-healing"]=!0),rollOptions.all["self:armored"]=!!this.wornArmor&&this.wornArmor.category!=="unarmored",attributes.shield?.raised&&!attributes.shield.broken&&!attributes.shield.destroyed&&(this.rollOptions.all["self:shield:raised"]=!0),this.system.attributes.emitsSound=!this.isDead,this.prepareSynthetics();const sizeIndex=SIZES.indexOf(this.size),sizeSlug=SIZE_SLUGS[sizeIndex];rollOptions.all[`self:size:${sizeIndex}`]=!0,rollOptions.all[`self:size:${sizeSlug}`]=!0,attributes.wounded.max=Math.max(0,attributes.dying.max-1),attributes.doomed.max=attributes.dying.max;for(const conditionSlug of["doomed","wounded","dying"]){const condition=this.conditions.bySlug(conditionSlug,{active:!0}).at(0),status=attributes[conditionSlug];conditionSlug==="dying"&&(status.max-=attributes.doomed.value),status.value=Math.min(condition?.value??0,status.max)}if(this.system.resources?.focus){const{focus}=this.system.resources;focus.max=Math.clamped(Math.floor(focus.max),0,focus.cap)||0,focus.value=Math.clamped(Math.floor(focus.value),0,focus.max)||0}imposeEncumberedCondition(this)}prepareSynthetics(){super.prepareSynthetics();for(const[selector,modifiers]of Object.entries(this.system.customModifiers))(this.synthetics.modifiers[selector]??=[]).push(...modifiers.map(m=>()=>m))}async adjustCarryType(item,{carryType,handsHeld=0,inSlot=!1}){const{usage}=item.system;if(carryType==="stowed"){const container=item.actor.itemTypes.backpack.find(c=>c!==item.container&&!isCycle(item,c));container&&await item.actor.stowOrUnstow(item,container)}else{const equipped={carryType,handsHeld:carryType==="held"?handsHeld:0,inSlot:usage.type==="worn"&&usage.where?inSlot:void 0},updates=[];if(isEquipped(usage,equipped)&&item.isOfType("armor")){const wornArmors=this.itemTypes.armor.filter(a=>a!==item&&a.isEquipped);for(const armor of wornArmors)updates.push({_id:armor.id,system:{equipped:{inSlot:!1}}})}else if(equipped.carryType!=="held"&&item.isOfType("weapon")&&item.shield?.isRaised){const effectIds=item.actor.itemTypes.effect.filter(e=>e.slug==="effect-raise-a-shield"||e.slug==="effect-cover"&&e.system.traits.otherTags.includes("tower-shield")&&item.shield?.isTowerShield).map(e=>e.id);await this.deleteEmbeddedDocuments("Item",effectIds)}updates.push({_id:item.id,system:{containerId:null,equipped}}),await this.updateEmbeddedDocuments("Item",updates)}}async addCustomModifier(stat,label,value,type){if(stat=stat==="armor"?"ac":stat,!this.isOfType("character","npc"))return;if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");if(label.length===0)throw ErrorPF2e("A custom modifier's label must be a non-empty string");const modifiers=(this.toObject().system.customModifiers??{})[stat]??[];if(!modifiers.some(m=>m.label===label)){const modifierType=setHasElement(MODIFIER_TYPES,type)?type:"untyped",modifier=new ModifierPF2e({label,modifier:value,type:modifierType,custom:!0}).toObject();await this.update({[`system.customModifiers.${stat}`]:[...modifiers,modifier]})}}async removeCustomModifier(stat,slug){if(stat=stat==="armor"?"ac":stat,stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");const modifiers=(this.toObject().system.customModifiers??{})[stat]??[];if(modifiers.length!==0)if(typeof slug=="string"){const withRemoved=modifiers.filter(m=>m.slug!==slug);await this.update({[`system.customModifiers.${stat}`]:withRemoved})}else throw ErrorPF2e("Custom modifiers can only be removed by slug (string) or index (number)")}async rollRecovery(event2){const{dying}=this.attributes;if(!dying?.value)return null;const localize=localizer("PF2E.Recovery"),recoveryDC=dying.recoveryDC,dc={label:localize("rollingDescription",{dying:dying.value,dc:"{dc}"}),value:recoveryDC+dying.value,visible:!0},notes=[new RollNotePF2e({selector:"all",text:localize("critSuccess"),outcome:["criticalSuccess"]}),new RollNotePF2e({selector:"all",text:localize("success"),outcome:["success"]}),new RollNotePF2e({selector:"all",text:localize("failure"),outcome:["failure"]}),new RollNotePF2e({selector:"all",text:localize("critFailure"),outcome:["criticalFailure"]})];return new Statistic(this,{slug:"dying-recovery",label:"PF2E.Check.Specific.Recovery",check:{type:"flat-check"}}).roll({...eventToRollParams(event2,{type:"check"}),dc,extraRollNotes:notes})}prepareSenses(data,synthetics){const preparedSenses=data.map(datum=>new CreatureSensePF2e(datum));for(const{sense,predicate,force}of synthetics.senses){if(predicate&&!predicate.test(this.getRollOptions(["all","sense"])))continue;const existing=preparedSenses.find(oldSense=>oldSense.type===sense.type);existing?force?preparedSenses.findSplice(oldSense=>oldSense===existing,sense):(sense.isMoreAcuteThan(existing)&&(existing.acuity=sense.acuity),sense.hasLongerRangeThan(existing)&&(existing.value=sense.value)):preparedSenses.push(sense)}return preparedSenses}prepareSpeed(movementType){const systemData=this.system;if(movementType==="land"){const domains=["speed","all-speeds",`${movementType}-speed`],rollOptions=this.getRollOptions(domains),landSpeed=systemData.attributes.speed;landSpeed.value=Number(landSpeed.value)||0;const fromSynthetics=(this.synthetics.movementTypes[movementType]??[]).flatMap(d=>d()??[]);landSpeed.value=Math.max(landSpeed.value,...fromSynthetics.map(s=>s.value));const modifiers=extractModifiers(this.synthetics,domains),stat=foundry.utils.mergeObject(new StatisticModifier(`${movementType}-speed`,modifiers,rollOptions),landSpeed,{overwrite:!1}),typeLabel=game.i18n.localize("PF2E.SpeedTypesLand"),otherData={type:"land",label:game.i18n.format("PF2E.SpeedLabel",{type:typeLabel})};this.rollOptions.all["speed:land"]=!0;const merged=foundry.utils.mergeObject(stat,otherData);return Object.defineProperties(merged,{total:{get(){return stat.value+stat.totalModifier}},breakdown:{get(){return[`${game.i18n.format("PF2E.SpeedBaseLabel",{type:typeLabel})} ${stat.value}`,...stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.signedValue}`)].join(", ")}}}),merged}else{const fastest=(()=>{const{otherSpeeds}=systemData.attributes.speed,existing=otherSpeeds.filter(s=>s.type===movementType),fromSynthetics=(this.synthetics.movementTypes[movementType]??[]).map(d=>d()??[]).flat();return[...existing,...fromSynthetics]})().reduce((best,speed2)=>best?speed2?.value>best.value?speed2:best:speed2,null);if(!fastest)return null;const domains=fastest.derivedFromLand?[`${movementType}-speed`]:["speed","all-speeds",`${movementType}-speed`],rollOptions=this.getRollOptions(domains),label=game.i18n.localize(CONFIG.PF2E.speedTypes[movementType]),speed={type:movementType,label,value:fastest.value};fastest.source&&(speed.source=fastest.source),this.rollOptions.all[`speed:${movementType}`]=!0;const modifiers=extractModifiers(this.synthetics,domains),stat=new StatisticModifier(`${movementType}-speed`,modifiers,rollOptions),merged=foundry.utils.mergeObject(stat,speed,{overwrite:!1});return Object.defineProperties(merged,{total:{get(){return speed.value+stat.totalModifier}},breakdown:{get(){return[`${game.i18n.format("PF2E.SpeedBaseLabel",{type:speed.label})} ${speed.value}`].concat(stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`)).join(", ")}}}),merged}}deleteEmbeddedDocuments(embeddedName,ids,context){if(embeddedName==="Item"){const linked=ids.map(id=>this.items.get(id)).flatMap(item=>item?.getLinkedItems?.()??[]);ids.push(...linked.map(item=>item.id))}return super.deleteEmbeddedDocuments(embeddedName,[...new Set(ids)],context)}async _preUpdate(changed,options,user){if(!changed.system)return super._preUpdate(changed,options,user);const currentHP=this.hitPoints,changedHP=changed.system.attributes?.hp;typeof changedHP?.value=="number"&&(changedHP.value=options.allowHPOverage?Math.max(0,changedHP.value):Math.clamped(changedHP.value,0,Math.max(currentHP.max-currentHP.unrecoverable,0)));const focusUpdate=changed.system.resources?.focus;if(focusUpdate&&this.system.resources){typeof focusUpdate.max=="number"&&(focusUpdate.max=Math.clamped(focusUpdate.max,0,3));const updatedPoints=Number(focusUpdate.value??this.system.resources.focus?.value)||0,enforcedMax=(Number(focusUpdate.max)||this.system.resources.focus?.max)??0;focusUpdate.value=Math.clamped(updatedPoints,0,enforcedMax)}const traitChanges=changed.system.traits;if(isObject$1(traitChanges)&&Array.isArray(traitChanges.value)){const sourceAlignmentTraits=this._source.system.traits?.value.filter(t=>["good","evil","lawful","chaotic"].includes(t)&&!(t in CONFIG.PF2E.creatureTraits));traitChanges.value=uniq(compact([traitChanges.value,sourceAlignmentTraits].flat()).sort())}return super._preUpdate(changed,options,user)}_onDelete(options,userId){super._onDelete(options,userId);for(const party of this.parties){const updater=party.primaryUpdater;game.user===updater?party.removeMembers(this.uuid):updater||(party.reset(),ui.actors.render())}}}class CharacterFeats extends Collection{static{__name(this,"CharacterFeats")}static{__name2(this,"CharacterFeats")}constructor(actor){super(),this.actor=actor;const classFeatSlots=actor.class?.grantedFeatSlots;this.bonus=new FeatGroup(actor,{id:"bonus",label:"PF2E.FeatBonusHeader"}),this.createGroup({id:"ancestryfeature",label:"PF2E.FeaturesAncestryHeader",supported:["ancestryfeature"]}),this.createGroup({id:"classfeature",label:"PF2E.FeaturesClassHeader",supported:["classfeature"]});const ancestryTraitsFilter=actor.system.details.ancestry?.countsAs.flatMap(t=>t in CONFIG.PF2E.featTraits?`traits-${t}`:[])??[];this.createGroup({id:"ancestry",label:"PF2E.FeatAncestryHeader",featFilter:ancestryTraitsFilter,supported:["ancestry"],slots:classFeatSlots?.ancestry??[]});const classTrait=(()=>{const slug=actor.class?actor.class.slug??sluggify(actor.class.name):null;return slug&&slug in CONFIG.PF2E.featTraits?slug:null})(),classFeatFilter=classTrait?this.actor.level<2?[`traits-${classTrait}`]:this.actor.itemTypes.feat.some(f=>f.traits.has("dedication"))?[`traits-${classTrait}`,"traits-archetype"]:[`traits-${classTrait}`,"traits-dedication"]:[];this.createGroup({id:"class",label:"PF2E.FeatClassHeader",featFilter:classFeatFilter,supported:["class"],slots:classFeatSlots?.class??[]});const evenLevels=new Array(actor.level).fill(0).map((_,idx)=>idx+1).filter(idx=>idx%2===0);game.pf2e.settings.variants.fa&&this.createGroup({id:"archetype",label:"PF2E.FeatArchetypeHeader",supported:["class"],slots:evenLevels,featFilter:this.actor.itemTypes.feat.some(f=>f.traits.has("dedication"))?["traits-archetype"]:["traits-dedication"]});const backgroundSkillFeats=actor.background&&Object.keys(actor.background.system.items??{}).length>0?{id:actor.background.id,level:1,label:game.i18n.localize("PF2E.FeatBackgroundShort")}:null;this.createGroup({id:"skill",label:"PF2E.FeatSkillHeader",supported:["skill"],slots:compact([backgroundSkillFeats,classFeatSlots?.skill].flat())}),this.createGroup({id:"general",label:"PF2E.FeatGeneralHeader",supported:["general","skill"],slots:classFeatSlots?.general??[]}),game.pf2e.settings.campaign.enabled&&this.createGroup({id:"campaign",label:"PF2E.FeatCampaignHeader"})}bonus;createGroup(options){return this.set(options.id,new FeatGroup(this.actor,options))}async insertFeat(feat,slotData){const alreadyHasFeat=this.actor.items.has(feat.id);if(isBoonOrCurse(feat))return alreadyHasFeat?[]:this.actor.createEmbeddedDocuments("Item",[feat.toObject()]);const groupId=slotData?.groupId??"",{group,slotId}=this.get(groupId)?.isFeatValid(feat)?{group:this.get(groupId),slotId:slotData?.slotId??null}:this.#findBestLocation(feat,{requested:groupId}),isFeatValidInSlot=!!group?.isFeatValid(feat);if(groupId!=="bonus"&&!group){const badGroup=this.get(groupId);if(badGroup)return ui.notifications.warn(game.i18n.format("PF2E.Item.Feat.Warning.InvalidCategory",{item:feat.name,category:game.i18n.format(badGroup.label)})),[]}return alreadyHasFeat&&feat.system.location&&!isFeatValidInSlot?this.actor.updateEmbeddedDocuments("Item",[{_id:feat.id,"system.location":null}]):group?.insertFeat(feat,slotId)??this.bonus.insertFeat(feat)}#findBestLocation(feat,{requested}){if(feat.isFeature)return{group:this.get(feat.category)??null,slotId:null};if(requested==="bonus")return{group:null,slotId:null};const validGroups=this.filter(c=>c.isFeatValid(feat)&&!c.isFull),group=validGroups.at(0);if(validGroups.length===1&&group){const slotId=group.slotted?Object.values(group.slots).find(slot=>!slot?.feat)?.id??null:null;return{group,slotId}}return{group:null,slotId:null}}assignToSlots(){const groupsBySlot=this.contents.filter(g=>g.slotted).reduce((previous,current)=>{for(const slot of Object.keys(current.slots))previous[slot]=current;return previous},{}),feats=this.actor.itemTypes.feat.sort((f1,f2)=>f1.sort-f2.sort);for(const feat of feats.filter(f=>!isBoonOrCurse(f))){if(feat.flags.pf2e.grantedBy&&!feat.system.location){const granter=this.actor.items.get(feat.flags.pf2e.grantedBy.id);if(granter?.isOfType("feat")&&granter.grants.includes(feat))continue}const location=feat.system.location??"";(groupsBySlot[location]??this.get(location)??this.get(feat.category))?.assignFeat(feat)||this.bonus.assignFeat(feat)}this.get("classfeature").feats.sort((a,b)=>(a.feat?.level||0)-(b.feat?.level||0))}}class FeatGroup{static{__name(this,"FeatGroup")}static{__name2(this,"FeatGroup")}actor;id;label;feats=[];slotted=!1;featFilter;supported=[];slots={};constructor(actor,options){this.actor=actor;const maxLevel=options.level??actor.level;if(this.id=options.id,this.label=options.label,this.supported=options.supported??[],this.featFilter=Array.from(new Set([this.supported.map(s=>`category-${s}`),options.featFilter??[]].flat())),options.slots){this.slotted=!0;for(const slotOption of options.slots){const slotData=typeof slotOption=="number"?{id:`${this.id}-${slotOption}`,level:slotOption,label:slotOption.toString()}:typeof slotOption=="string"?{id:`${this.id}-${sluggify(slotOption)}`,level:null,label:slotOption}:slotOption;if(typeof slotData.level=="number"&&slotData.level>maxLevel)continue;const slot={...slotData,level:slotData.level??null,children:[]};this.feats.push(slot),this.slots[slot.id]=slot}}}get isFull(){return this.slotted&&Object.values(this.slots).every(s=>!!s?.feat)}assignFeat(feat){const slotId=feat.isOfType("feat")&&feat.system.location===this.id?feat.system.level.taken?.toString()??"":feat.system.location??"",slot=this.slots[slotId];if(!slot&&this.slotted)return!1;if(slot?.feat)return console.debug(`PF2e System | Multiple feats with same index: ${feat.name}, ${slot.feat.name}`),!1;const childSlots=this.#getChildSlots(feat);if(slot)slot.feat=feat,slot.children=childSlots;else{const label=feat.category==="classfeature"?feat.system.level?.value.toString()??null:null;this.feats.push({feat,label,children:childSlots})}return feat.group=this,!0}#getChildSlots(feat){return feat?.isOfType("feat")?feat.grants.map(grant=>({id:grant.id,label:null,level:grant.system.level?.taken??null,feat:grant,children:this.#getChildSlots(grant)})):[]}isFeatValid(feat){return this.supported.length===0||tupleHasValue(this.supported,feat.category)}async insertFeat(feat,slotId=null){const slot=this.slots[slotId??""],location=this.slotted||this.id==="bonus"?slot?.id??null:this.id,existing=this.actor.items.filter(i=>isFeatLike(i)&&i.system.location===location),isFeatValidInSlot=this.isFeatValid(feat),alreadyHasFeat=this.actor.items.has(feat.id),changed=[];if(!alreadyHasFeat&&(isFeatValidInSlot||!location)){const source=foundry.utils.mergeObject(feat.toObject(),{system:{location}});changed.push(...await this.actor.createEmbeddedDocuments("Item",[source]));const label=game.i18n.localize(this.label);ui.notifications.info(game.i18n.format("PF2E.Item.Feat.Info.Added",{item:feat.name,category:label}))}const locationUpdates=this.slotted?existing.map(f=>({_id:f.id,"system.location":null,..."taken"in(feat._source.system.level??{})?{"system.level.-=taken":null}:{}})):[];return alreadyHasFeat&&isFeatValidInSlot&&locationUpdates.push({_id:feat.id,"system.location":location,...slot?.level&&feat.isOfType("feat")?{"system.level.taken":slot.level}:{}}),locationUpdates.length>0&&changed.push(...await this.actor.updateEmbeddedDocuments("Item",locationUpdates)),changed}}function isBoonOrCurse(feat){return["pfsboon","deityboon","curse"].includes(feat.category)}__name(isBoonOrCurse,"isBoonOrCurse"),__name2(isBoonOrCurse,"isBoonOrCurse");function isFeatLike(item){return"category"in item&&"location"in item.system&&"isFeat"in item&&"isFeature"in item}__name(isFeatLike,"isFeatLike"),__name2(isFeatLike,"isFeatLike");const CHARACTER_SHEET_TABS=["character","actions","inventory","spellcasting","crafting","proficiencies","feats","effects","biography","pfs"];class CharacterPF2e extends CreaturePF2e{static{__name(this,"CharacterPF2e")}static{__name2(this,"CharacterPF2e")}get allowedItemTypes(){const buildItems=["ancestry","heritage","background","class","deity","feat"];return[...super.allowedItemTypes,...buildItems,"physical","spellcastingEntry","spell","action","lore","kit"]}get keyAttribute(){return this.system.details.keyability.value||"str"}get keyAbility(){return foundry.utils.logCompatibilityWarning("`CharacterPF2e#keyAbility` is deprecated. Use `CharacterPF2e#keyAttribute` instead.",{since:"5.2.0",until:"6.0.0"}),this.keyAttribute}get abilities(){return foundry.utils.deepClone(this.system.abilities)}get handsFree(){const heldItems=this.inventory.filter(i=>i.isHeld);return Math.clamped(2-sumBy(heldItems,i=>i.traits.has("free-hand")?0:i.handsHeld),0,2)}get handsReallyFree(){const heldItems=this.inventory.filter(i=>i.isHeld);return Math.clamped(2-sumBy(heldItems,i=>i.handsHeld),0,2)}get hitPoints(){return{...super.hitPoints,recoveryMultiplier:this.system.attributes.hp.recoveryMultiplier,recoveryAddend:this.system.attributes.hp.recoveryAddend}}get heroPoints(){return foundry.utils.deepClone(this.system.resources.heroPoints)}getStatistic(slug){switch(slug){case"class":case"class-dc":case"classDC":return this.classDC;case"class-spell":{const highestClass=Object.values(this.classDCs).sort((a,b)=>b.mod-a.mod).shift(),highestSpell=this.spellcasting.contents.flatMap(s=>s.statistic??[]).sort((a,b)=>b.mod-a.mod).shift();return compact([highestClass,highestSpell]).sort((a,b)=>b.mod-a.mod).shift()??null}case"base-spellcasting":return this.spellcasting.base}return this.classDCs[slug]??super.getStatistic(slug)}async getCraftingFormulas(){const{formulas}=this.system.crafting;formulas.sort((a,b)=>(a.sort??0)-(b.sort??0));const formulaMap=new Map(formulas.map(data=>[data.uuid,data]));return(await UUIDUtils.fromUUIDs(formulas.map(f=>f.uuid))).filter(i=>i instanceof ItemPF2e&&i.isOfType("physical")).map(item=>{const{dc,batchSize,deletable}=formulaMap.get(item.uuid)??{deletable:!1};return new CraftingFormula(item,{dc,batchSize,deletable})})}async getCraftingEntries(formulas){const craftingFormulas=formulas??await this.getCraftingFormulas();return Object.values(this.system.crafting.entries).filter(entry=>CraftingEntry.isValid(entry)).map(entry=>new CraftingEntry(this,craftingFormulas,entry))}async getCraftingEntry(selector){const craftingFormulas=await this.getCraftingFormulas(),craftingEntryData=this.system.crafting.entries[selector];return CraftingEntry.isValid(craftingEntryData)?new CraftingEntry(this,craftingFormulas,craftingEntryData):null}async performDailyCrafting(){const entries=(await this.getCraftingEntries()).filter(e=>e.isDailyPrep),reagentCost=entries.filter(e=>e.isAlchemical).reduce((sum,entry)=>sum+entry.reagentCost,0),reagentValue=(this.system.resources.crafting.infusedReagents.value||0)-reagentCost;if(reagentValue<0){ui.notifications.warn(game.i18n.localize("PF2E.CraftingTab.Alerts.MissingReagents"));return}else await this.update({"system.resources.crafting.infusedReagents.value":reagentValue});for(const item of this.inventory)item.system.temporary&&await item.delete();for(const entry of entries)for(const formula of entry.preparedCraftingFormulas){const itemSource=formula.item.toObject();itemSource.system.quantity=formula.quantity,itemSource.system.temporary=!0,itemSource.system.size=this.ancestry?.size==="tiny"?"tiny":"med",entry.isAlchemical&&(itemSource.type==="consumable"||itemSource.type==="weapon"||itemSource.type==="equipment")&&itemSource.system.traits.value.push("infused"),await this.addToInventory(itemSource)}}_initialize(options){this.familiar??=null,super._initialize(options)}prepareData(){super.prepareData(),game.ready&&this.familiar&&game.actors.has(this.familiar.id)&&this.familiar.reset({fromMaster:!0})}prepareBaseData(){super.prepareBaseData(),this.parties.size||(this.system.exploration=[]);const{flags}=this;flags.pf2e.favoredWeaponRank=0,flags.pf2e.freeCrafting??=!1,flags.pf2e.quickAlchemy??=!1,flags.pf2e.sheetTabs=foundry.utils.mergeObject(CHARACTER_SHEET_TABS.reduce((tabs,tab)=>({...tabs,[tab]:!0}),{}),flags.pf2e.sheetTabs??{}),flags.pf2e.showBasicUnarmed??=!0;const isGradual=game.pf2e.settings.variants.gab,allowedBoosts=[1,5,10,15,20].reduce((result,level)=>{const allowed=(()=>this.level===0&&level===1?4:isGradual?4-Math.clamped(level-this.level,0,4):this.level>=level?4:0)();return result[level]=allowed,result},{}),manualAttributes=Object.keys(this.system.abilities??{}).length>0;this.system.abilities=mapToObj(Array.from(ATTRIBUTE_ABBREVIATIONS),a=>[a,foundry.utils.mergeObject({mod:0},this.system.abilities?.[a]??{})]);const systemData=this.system,existingBoosts=systemData.build?.attributes?.boosts,isABP=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this);systemData.build={attributes:{manual:manualAttributes,keyOptions:[],boosts:{ancestry:[],background:[],class:null,1:existingBoosts?.[1]?.slice(0,allowedBoosts[1])??[],5:existingBoosts?.[5]?.slice(0,allowedBoosts[5])??[],10:existingBoosts?.[10]?.slice(0,allowedBoosts[10])??[],15:existingBoosts?.[15]?.slice(0,allowedBoosts[15])??[],20:existingBoosts?.[20]?.slice(0,allowedBoosts[20])??[]},allowedBoosts,flaws:{ancestry:[]},apex:isABP?systemData.build?.attributes?.apex??null:null}},systemData.saves=foundry.utils.mergeObject(mapToObj(SAVE_TYPES,t=>[t,{rank:0,ability:SAVING_THROW_DEFAULT_ATTRIBUTES[t]}]),systemData.saves??{});const{details}=this.system;for(const property of["ancestry","heritage","background","class","deity"])this[property]=null,property==="deity"?details.deities={primary:null,secondary:null,domains:{}}:property!=="background"&&(details[property]=null);details.alliance=ALLIANCES.has(details.alliance)?details.alliance:this.hasPlayerOwner?"party":"opposition";const attributes=this.system.attributes;attributes.ac={},attributes.polymorphed=!1,attributes.battleForm=!1,attributes.classDC=null,attributes.spellDC=null,attributes.classOrSpellDC={rank:0,value:0};const perception=attributes.perception??={ability:"wis",rank:0};perception.ability="wis",perception.rank??=0;const hitPoints=this.system.attributes.hp;hitPoints.recoveryMultiplier=1,hitPoints.recoveryAddend=0,attributes.ancestryhp=0,attributes.classhp=0;const{skills}=this.system;for(const key of SKILL_ABBREVIATIONS){const skill=skills[key];skill.ability=SKILL_EXPANDED[SKILL_DICTIONARY[key]].attribute,skill.armor=["dex","str"].includes(skill.ability)}attributes.familiarAbilities={value:0},systemData.proficiencies={...systemData.proficiencies,classDCs:{}},systemData.proficiencies.spellcasting??={rank:0};const{resources}=this.system;resources.heroPoints.max=3,resources.investiture={value:0,max:10},resources.focus={value:resources.focus?.value||0,max:0,cap:3},resources.crafting=foundry.utils.mergeObject({infusedReagents:{value:0,max:0}},resources.crafting??{}),resources.crafting.infusedReagents.max=0,this.system.traits.size=new ActorSizePF2e({value:"med"});const attacks=systemData.proficiencies.attacks??={};for(const category of keys.strict(CONFIG.PF2E.weaponCategories))attacks[category]={rank:attacks[category]?.rank??0,custom:!!attacks[category]?.custom,immutable:!!attacks[category]?.custom};const defenses=systemData.proficiencies.defenses??={};for(const category of ARMOR_CATEGORIES)defenses[category]={rank:defenses[category]?.rank??0,immutable:["light-barding","heavy-barding"].includes(category)};systemData.crafting=foundry.utils.mergeObject({formulas:[],entries:{}},systemData.crafting??{});for(const formula of this.system.crafting.formulas)formula.deletable=!0;this.rollOptions.all[`self:level:${this.level}`]=!0}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const attribute of Object.values(this.system.abilities))attribute.mod=Math.trunc(attribute.mod)||0;if(this.setNumericRollOptions(),this.deity?.setFavoredWeaponRank(),this.spellcasting.some(e=>e.isInnate)){const spellcasting=this.system.proficiencies.spellcasting;spellcasting.rank=Math.max(spellcasting.rank,this.level>=12?2:1)}}prepareDataFromItems(){super.prepareDataFromItems(),this.setAttributeModifiers()}prepareDerivedData(){super.prepareDerivedData(),imposeOversizedWeaponCondition(this);const systemData=this.system,{synthetics}=this;if(game.pf2e.variantRules.AutomaticBonusProgression.concatModifiers(this),systemData.details.xp.pct=Math.min(Math.round(systemData.details.xp.value*100/systemData.details.xp.max),99.5),systemData.pfs.levelBump){const params={slug:"level-bump",label:"PF2E.PFS.LevelBump",modifier:1};this.synthetics.modifiers.all.push(()=>new ModifierPF2e(params)),this.synthetics.modifiers.damage.push(()=>new ModifierPF2e(params))}{const ancestryHP=systemData.attributes.ancestryhp,classHP=systemData.attributes.classhp,hitPoints=systemData.attributes.hp,modifiers=[new ModifierPF2e("PF2E.AncestryHP",ancestryHP,"untyped")];if(game.pf2e.settings.variants.stamina){const halfClassHp=Math.floor(classHP/2);systemData.attributes.hp.sp={value:systemData.attributes.hp.sp?.value??0,max:(halfClassHp+systemData.abilities.con.mod)*this.level},systemData.resources.resolve={value:systemData.resources.resolve?.value??0,max:systemData.abilities[systemData.details.keyability.value].mod},modifiers.push(new ModifierPF2e("PF2E.ClassHP",halfClassHp*this.level,"untyped"))}else{modifiers.push(new ModifierPF2e("PF2E.ClassHP",classHP*this.level,"untyped")),delete systemData.resources.resolve;const conHP=systemData.abilities.con.mod*Math.max(this.level,1);modifiers.push(new ModifierPF2e({slug:"hp-con",label:"PF2E.AbilityCon",ability:"con",type:"ability",modifier:conHP,adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,["con-based"],"hp-con")}))}const hpRollOptions=this.getRollOptions(["hp"]);modifiers.push(...extractModifiers(synthetics,["hp"],{test:hpRollOptions}));const perLevelRollOptions=this.getRollOptions(["hp-per-level"]);modifiers.push(...extractModifiers(synthetics,["hp-per-level"],{test:perLevelRollOptions}).map(clone=>(clone.modifier*=this.level,clone)));const stat=foundry.utils.mergeObject(new StatisticModifier("hp",modifiers),hitPoints,{overwrite:!1});if(systemData.pfs.levelBump){const hitPointsBump=Math.max(10,stat.totalModifier*.1);stat.push(new ModifierPF2e("PF2E.PFS.LevelBump",hitPointsBump,"untyped"))}stat.max=stat.totalModifier,stat.value=Math.min(stat.value,stat.max),stat.breakdown=stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", "),systemData.attributes.hp=stat,setHitPointsRollOptions(this)}this.prepareFeats(),this.prepareSaves(),this.prepareMartialProficiencies(),this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",attribute:"wis",rank:systemData.attributes.perception.rank,domains:["perception","all"],check:{type:"perception-check"}}),systemData.attributes.perception=foundry.utils.mergeObject(systemData.attributes.perception,this.perception.getTraceData({value:"mod"})),this.skills=this.prepareSkills(),this.system.traits.senses=this.prepareSenses(this.system.traits.senses,synthetics),this.classDC=null,this.classDCs={};for(const[slug,classDC]of Object.entries(systemData.proficiencies.classDCs)){const statistic=this.prepareClassDC(slug,classDC);systemData.proficiencies.classDCs[slug]=foundry.utils.mergeObject(classDC,statistic.getTraceData({value:"dc"})),this.classDCs[slug]=statistic,classDC.primary&&(this.classDC=statistic)}systemData.attributes.classDC=Object.values(systemData.proficiencies.classDCs).find(c=>c.primary)??null,systemData.attributes.classDC&&(systemData.attributes.classOrSpellDC=pick(systemData.attributes.classDC,["rank","value"]));const armorStatistic=this.createArmorStatistic();this.armorClass=armorStatistic.dc,systemData.attributes.ac=armorStatistic.getTraceData();const{heldShield}=this;if(heldShield?.speedPenalty){const speedPenalty=new ModifierPF2e(heldShield.name,heldShield.speedPenalty,"untyped");speedPenalty.predicate.push({not:"self:shield:ignore-speed-penalty"}),this.synthetics.modifiers.speed??=[],this.synthetics.modifiers.speed.push(()=>speedPenalty)}const speeds=systemData.attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]),systemData.actions=this.prepareStrikes(),this.flags.pf2e.highestWeaponDamageDice=Math.max(...systemData.actions.filter(s=>s.ready).map(s=>s.item.system.damage.dice),0);const initiativeSkill=systemData.attributes.initiative?.statistic||"perception";this.initiative=new ActorInitiative(this,{statistic:initiativeSkill}),this.system.attributes.initiative=this.initiative.getTraceData();const{crafting}=this.system.resources;crafting.infusedReagents.max=Math.floor(crafting.infusedReagents.max)||0,crafting.infusedReagents.value=Math.clamped(crafting.infusedReagents.value,0,crafting.infusedReagents.max),systemData.attributes.familiarAbilities.value>0&&(this.rollOptions.all["self:has-familiar"]=!0)}setAttributeModifiers(){const{build}=this.system;if(!build.attributes.manual){for(const section of["ancestry","background","class",1,5,10,15,20]){const boosts=build.attributes.boosts[section];if(typeof boosts=="string"){const ability=this.system.abilities[boosts];ability.mod+=ability.mod>=4?.5:1}else if(Array.isArray(boosts))for(const abbrev of boosts){const ability=this.system.abilities[abbrev];ability.mod+=ability.mod>=4?.5:1}const flaws=section==="ancestry"?build.attributes.flaws[section]:[];for(const abbrev of flaws){const ability=this.system.abilities[abbrev];ability.mod-=1}}const isABP=game.pf2e.variantRules.AutomaticBonusProgression.isEnabled(this);if(build.attributes.apex&&(!isABP||this.level>=17)){const attribute=this.system.abilities[build.attributes.apex];attribute.mod=Math.max(attribute.mod+1,4)}}for(const ability of Object.values(this.system.abilities))ability.mod=Math.clamped(ability.mod,-5,10),ability.base=Math.trunc(ability.mod)}setNumericRollOptions(){const rollOptionsAll=this.rollOptions.all,perceptionRank=this.system.attributes.perception.rank;rollOptionsAll[`perception:rank:${perceptionRank}`]=!0;for(const key of ATTRIBUTE_ABBREVIATIONS){const mod=this.abilities[key].mod;rollOptionsAll[`attribute:${key}:mod:${mod}`]=!0}for(const key of SKILL_ABBREVIATIONS){const rank=this.system.skills[key].rank;rollOptionsAll[`skill:${key}:rank:${rank}`]=!0}for(const key of keys.strict(CONFIG.PF2E.weaponCategories)){const rank=this.system.proficiencies.attacks[key].rank;rollOptionsAll[`attack:${key}:rank:${rank}`]=!0}for(const key of ARMOR_CATEGORIES){const rank=this.system.proficiencies.defenses[key].rank;rollOptionsAll[`defense:${key}:rank:${rank}`]=!0}for(const key of SAVE_TYPES){const rank=this.system.saves[key].rank;rollOptionsAll[`save:${key}:rank:${rank}`]=!0}const{handsFree,handsReallyFree}=this;this.attributes.handsFree=handsFree,rollOptionsAll[`hands-free:${handsFree}`]=!0,rollOptionsAll[`hands-free:but-really:${handsReallyFree}`]=!0}createArmorStatistic(){const{synthetics,wornArmor}=this;this.system.proficiencies.defenses["light-barding"].rank||=this.traits.has("animal")&&!isReallyPC(this)?Math.max(this.system.proficiencies.defenses["light-barding"].rank,1):0;const modifiers=[],dexCapSources=[{value:1/0,source:""},...synthetics.dexterityModifierCaps];wornArmor&&dexCapSources.push({value:Number(wornArmor.dexCap??0),source:wornArmor.name});const dexCap=dexCapSources.reduce((lowest,candidate)=>lowest.value>candidate.value?candidate:lowest),dexModifier=createAttributeModifier({actor:this,attribute:"dex",domains:["all","ac","dex-based"],max:dexCap.value}),attributeModifier=modifiers.filter(m=>m.type==="ability"&&!!m.ability).reduce((best,modifier)=>modifier.modifier>best.modifier?modifier:best,dexModifier),proficiency=Object.entries(this.system.proficiencies.defenses).filter(([key,proficiency2])=>wornArmor?wornArmor.category===key?!0:proficiency2.definition?.test(wornArmor.getRollOptions("item"))??!1:key==="unarmored").map(([_k,v])=>v).reduce((best,p)=>p.rank>best.rank?p:best,{rank:0});return new ArmorStatistic(this,{rank:proficiency.rank,attribute:attributeModifier.ability,modifiers:[attributeModifier]})}prepareSaves(){const systemData=this.system,{wornArmor}=this,saves={};for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),modifiers=[],selectors=[saveType,`${save.ability}-based`,"saving-throw","all"];if(wornArmor?.system.runes.resilient&&wornArmor.isInvested){const value=wornArmor.system.runes.resilient;modifiers.push(new ModifierPF2e({slug:"resilient",label:wornArmor.name,type:"item",modifier:value}))}if(saveType==="reflex"&&wornArmor?.traits.has("bulwark")){const slug="bulwark",bulwarkModifier=new ModifierPF2e({slug,type:"untyped",label:CONFIG.PF2E.armorTraits.bulwark,modifier:3,predicate:["damaging-effect"],adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,selectors,slug)});modifiers.push(bulwarkModifier),(this.synthetics.modifierAdjustments[saveType]??=[]).push({slug:"dex",test:options=>new PredicatePF2e("damaging-effect").test(options),suppress:!0})}const stat=new Statistic(this,{slug:saveType,label:saveName,attribute:save.ability,rank:save.rank,modifiers,domains:selectors,check:{type:"saving-throw"}});saves[saveType]=stat,this.system.saves[saveType]=foundry.utils.mergeObject(this.system.saves[saveType],stat.getTraceData())}this.saves=saves}prepareSkills(){const systemData=this.system,{synthetics,wornArmor}=this,skills=Array.from(SKILL_ABBREVIATIONS).reduce((builtSkills,shortForm)=>{const skill=systemData.skills[shortForm],longForm=SKILL_DICTIONARY[shortForm],label=CONFIG.PF2E.skillList[longForm]??longForm,domains=[longForm,`${skill.ability}-based`,"skill-check",`${skill.ability}-skill-check`,"all"],modifiers=[],strengthRequirement=wornArmor?.strength;if(typeof strengthRequirement=="number"&&this.system.abilities.str.mod>=strengthRequirement)for(const selector of["skill-check","initiative"]){const rollOptions=this.rollOptions[selector]??={};rollOptions["armor:strength-requirement-met"]=!0}if(skill.armor&&typeof wornArmor?.strength=="number"&&wornArmor.checkPenalty<0){const slug="armor-check-penalty",armorCheckPenalty=new ModifierPF2e({slug,label:"PF2E.ArmorCheckPenalty",modifier:wornArmor.checkPenalty,type:"untyped",adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,slug)});armorCheckPenalty.predicate.push({nor:["attack","armor:ignore-check-penalty"]}),["acrobatics","athletics"].includes(longForm)?armorCheckPenalty.predicate.push({nor:["armor:strength-requirement-met","armor:trait:flexible"]}):longForm==="stealth"&&wornArmor.traits.has("noisy")?armorCheckPenalty.predicate.push({nand:["armor:strength-requirement-met","armor:ignore-noisy-penalty"]}):armorCheckPenalty.predicate.push({not:"armor:strength-requirement-met"}),modifiers.push(armorCheckPenalty)}longForm==="athletics"&&modifiers.push(createForceOpenPenalty(this,domains));const statistic=new Statistic(this,{slug:longForm,label,rank:skill.rank,attribute:skill.ability,domains,modifiers,lore:!1,check:{type:"skill-check"}});return builtSkills[longForm]=statistic,this.system.skills[shortForm]=foundry.utils.mergeObject(this.system.skills[shortForm],statistic.getTraceData()),builtSkills},{});for(const loreItem of this.itemTypes.lore){const longForm=sluggify(loreItem.name),rank=loreItem.system.proficient.value,statistic=new Statistic(this,{slug:longForm,label:loreItem.name,rank,attribute:"int",domains:[longForm,"skill-check","lore-skill-check","int-skill-check","all"],lore:!0,check:{type:"skill-check"}});skills[longForm]=statistic,this.system.skills[longForm]={armor:!1,ability:"int",rank,lore:!0,itemID:loreItem.id,...statistic.getTraceData()}}return skills}prepareSpeed(movementType){const statistic=super.prepareSpeed(movementType);if(!statistic)return null;const{wornArmor}=this,basePenalty=wornArmor?.speedPenalty??0,strength=this.system.abilities.str.mod,requirement=wornArmor?.strength??null,penaltyValue=Math.min(typeof requirement=="number"&&strength>=requirement?Math.min(basePenalty+5,0):basePenalty,0),derivedFromLand=!!("derivedFromLand"in statistic&&statistic.derivedFromLand),modifierName=wornArmor?.name??"PF2E.ArmorSpeedLabel",slug="armor-speed-penalty",armorPenalty=penaltyValue&&!derivedFromLand?new ModifierPF2e({slug,label:modifierName,modifier:penaltyValue,type:"untyped",predicate:new PredicatePF2e({not:"armor:ignore-speed-penalty"}),adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,["all-speeds","speed",`${movementType}-speed`],slug)}):null;armorPenalty&&(statistic.push(armorPenalty),statistic.calculateTotal(new Set(this.getRollOptions(["all-speeds","speed",`${movementType}-speed`]))));const hinderingPenalty=createHinderingPenalty(this);return hinderingPenalty&&statistic.push(hinderingPenalty),statistic}prepareFeats(){this.pfsBoons=[],this.deityBoonsCurses=[],this.feats=new CharacterFeats(this);for(const section of game.pf2e.settings.campaign.sections)this.feats.createGroup(section);this.feats.assignToSlots();const feats=this.itemTypes.feat.filter(f=>["pfsboon","deityboon","curse"].includes(f.category)).sort((f1,f2)=>f1.sort-f2.sort);for(const feat of feats)feat.category==="pfsboon"?this.pfsBoons.push(feat):this.deityBoonsCurses.push(feat)}prepareClassDC(slug,classDC){classDC.ability??="str",classDC.rank??=0,classDC.primary??=!1;const classNames=CONFIG.PF2E.classTraits;return classDC.label=classDC.label??classNames[slug]??slug.titleCase(),new Statistic(this,{slug,label:classDC.label,attribute:classDC.ability,rank:classDC.rank,domains:["class",slug,"all"],check:{type:"check"}})}prepareStrikes({includeBasicUnarmed=!0}={}){const{itemTypes,synthetics}=this,handwrapsSlug="handwraps-of-mighty-blows",handwraps=itemTypes.weapon.find(w=>w.slug===handwrapsSlug&&w.category==="unarmed"&&w.isEquipped&&w.isInvested),unarmedRunes=foundry.utils.deepClone(handwraps?._source.system.runes)??{potency:0,striking:0,property:[]},basicUnarmed=includeBasicUnarmed?(()=>{const source={_id:"xxPF2ExUNARMEDxx",name:game.i18n.localize("PF2E.WeaponTypeUnarmed"),type:"weapon",img:"icons/skills/melee/unarmed-punch-fist.webp",system:{slug:"basic-unarmed",category:"unarmed",baseItem:null,bonus:{value:0},damage:{dice:1,die:"d4",damageType:"bludgeoning"},equipped:{carryType:"worn",inSlot:!0,handsHeld:0},group:"brawling",traits:{value:["agile","finesse","nonlethal","unarmed"]},usage:{value:"worngloves"},runes:unarmedRunes}};return new WeaponPF2e(source,{parent:this})})():null;if(handwraps){for(const[slug,weapon]of synthetics.strikes.entries())if(weapon.category==="unarmed"){const clone=weapon.clone({system:{runes:unarmedRunes}},{keepId:!0});synthetics.strikes.set(slug,clone),clone.name=clone._source.name}}const ammos=[...itemTypes.consumable.filter(i=>i.category==="ammo"&&!i.isStowed),...itemTypes.weapon.filter(w=>w.system.usage.canBeAmmo)],offensiveCategories=keys.strict(CONFIG.PF2E.weaponCategories),weapons=compact([itemTypes.weapon.filter(w=>w.slug!==handwrapsSlug),Array.from(synthetics.strikes.values()),basicUnarmed??[],this.itemTypes.shield.filter(s=>!s.isStowed&&!s.isBroken&&!s.isDestroyed).map(s=>s.generateWeapon())].flat()),{handsReallyFree}=this;return weapons.map(w=>this.prepareStrike(w,{categories:offensiveCategories,handsReallyFree,ammos})).sort((a,b)=>a.label.toLocaleLowerCase(game.i18n.lang).replace(/[-0-9\s]/g,"").localeCompare(b.label.toLocaleLowerCase(game.i18n.lang).replace(/[-0-9\s]/gi,""),game.i18n.lang)).sort((a,b)=>a.slug==="basic-unarmed"?1:b.slug==="basic-unarmed"?-1:0).sort((a,b)=>a.item.isHeld===b.item.isHeld?0:a.item.isHeld?-1:1).sort((a,b)=>a.ready===b.ready?0:a.ready?-1:1)}prepareStrike(weapon,{categories,handsReallyFree,ammos=[]}){const{synthetics}=this,modifiers=[],systemData=this.system,strikeAdjustments=[synthetics.strikeAdjustments,getPropertyRuneStrikeAdjustments(weapon.system.runes.property)].flat();for(const adjustment of strikeAdjustments)adjustment.adjustWeapon?.(weapon);const weaponRollOptions=weapon.getRollOptions("item"),weaponTraits2=weapon.traits,{proficiencies}=systemData,categoryRank=proficiencies.attacks[weapon.category]?.rank??0,groupRank=proficiencies.attacks[`weapon-group-${weapon.group}`]?.rank??0,baseWeapon=CONFIG.PF2E.equivalentWeapons[weapon.baseType??""]??weapon.baseType,baseWeaponRank=proficiencies.attacks[`weapon-base-${baseWeapon}`]?.rank??0,equivalentCategories=Object.values(proficiencies.attacks).flatMap(p=>p&&"sameAs"in p&&(p.definition?.test(weaponRollOptions)??!0)?`item:category:${p.sameAs}`:[]),weaponProficiencyOptions=new Set(weaponRollOptions.concat(equivalentCategories)),syntheticRanks=compact(Object.values(proficiencies.attacks)).filter(p=>p.immutable&&(p.definition?.test(weaponProficiencyOptions)??!0)).map(p=>p.rank),proficiencyRank=Math.max(categoryRank,groupRank,baseWeaponRank,...syntheticRanks),meleeOrRanged=weapon.isMelee?"melee":"ranged",baseOptions=new Set(["action:strike","self:action:slug:strike",`item:proficiency:rank:${proficiencyRank}`,PROFICIENCY_RANK_OPTION[proficiencyRank],...weaponTraits2,meleeOrRanged]),attackDomains=getStrikeAttackDomains(weapon,proficiencyRank,baseOptions),{defaultAttribute}=weapon;modifiers.push(createAttributeModifier({actor:this,attribute:defaultAttribute,domains:attackDomains})),weapon.isMelee&&weaponTraits2.has("finesse")&&modifiers.push(createAttributeModifier({actor:this,attribute:"dex",domains:attackDomains})),weapon.isRanged&&weaponTraits2.has("brutal")&&modifiers.push(createAttributeModifier({actor:this,attribute:"str",domains:attackDomains})),modifiers.push(createProficiencyModifier({actor:this,rank:proficiencyRank,domains:attackDomains}));const initialRollOptions=new Set([...baseOptions,...this.getRollOptions(attackDomains),...weaponRollOptions]),ABP=game.pf2e.variantRules.AutomaticBonusProgression;if(weapon.group==="bomb"&&!ABP.isEnabled(this)){const attackBonus=Number(weapon.system.bonus?.value)||0;attackBonus!==0&&modifiers.push(new ModifierPF2e("PF2E.ItemBonusLabel",attackBonus,"item"))}const weaponPotency=(()=>{const potency=attackDomains.flatMap(key=>foundry.utils.deepClone(synthetics.weaponPotency[key]??[])).filter(wp=>wp.predicate.test(initialRollOptions));return weapon.system.runes.potency>0&&potency.push({label:"PF2E.Item.Weapon.Rune.Potency",bonus:weapon.system.runes.potency,type:"item",predicate:new PredicatePF2e}),potency.length>0?potency.reduce((highest,current)=>highest.bonus>current.bonus?highest:current):null})();weaponPotency&&(modifiers.push(new ModifierPF2e(weaponPotency.label,weaponPotency.bonus,weaponPotency.type)),!weapon.isMagical&&(weaponPotency.type==="item"||!ABP.isEnabled(weapon.actor))&&weapon.system.traits.value.push("magical"),weapon.flags.pf2e.attackItemBonus=weaponPotency.bonus);const shoddyPenalty=createShoddyPenalty(this,weapon,attackDomains);shoddyPenalty&&modifiers.push(shoddyPenalty),modifiers.push(...PCAttackTraitHelpers.createAttackModifiers({item:weapon,domains:attackDomains}),...extractModifiers(synthetics,attackDomains,{injectables:{weapon},resolvables:{weapon}}));const auxiliaryActions=[],isRealItem=this.items.has(weapon.id);if(weapon.system.traits.toggles.modular.options.length>0&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"modular"})),isRealItem&&weapon.category!=="unarmed"){const traitsArray=weapon.system.traits.value,{usage}=weapon.system,weaponAsShield=weapon.shield,canWield2H=usage.hands===2||usage.hands===1&&this.handsFree>0&&!!weaponAsShield||traitsArray.some(t=>t.startsWith("fatal-aim"))||traitsArray.some(t=>t.startsWith("two-hand"));switch(weapon.carryType){case"held":{if(weaponAsShield){const hasShieldRaised=!!this.rollOptions.all["self:effect:raise-a-shield"],hasGreaterCover=!!this.rollOptions.all["self:cover-level:greater"];if(!hasShieldRaised)auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"raise-a-shield"}));else if(weaponAsShield.isTowerShield&&weaponAsShield.isRaised){const action22=hasGreaterCover?"end-cover":"take-cover",annotation="tower-shield";auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:action22,annotation}))}}weapon.handsHeld===2?auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"release",annotation:"grip",hands:1})):weapon.handsHeld===1&&canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"grip",hands:2})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"sheathe",hands:0})),auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"release",annotation:"drop",hands:0}));break}case"worn":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"draw",hands:1})),canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"draw",hands:2}));break}case"stowed":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"retrieve",hands:1}));break}case"dropped":{auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"pick-up",hands:1})),canWield2H&&auxiliaryActions.push(new WeaponAuxiliaryAction({weapon,action:"interact",annotation:"pick-up",hands:2}));break}}}const weaponSlug=weapon.slug??sluggify(weapon.name),flavor=this.getStrikeDescription(weapon),rollOptions=[...this.getRollOptions(attackDomains),...weaponRollOptions,...weaponTraits2,meleeOrRanged],strikeStat=new StatisticModifier(weaponSlug,modifiers,rollOptions),altUsages=weapon.getAltUsages().map(w=>this.prepareStrike(w,{categories,handsReallyFree})),versatileLabel=__name2(damageType=>{switch(damageType){case"bludgeoning":return CONFIG.PF2E.weaponTraits["versatile-b"];case"piercing":return CONFIG.PF2E.weaponTraits["versatile-p"];case"slashing":return CONFIG.PF2E.weaponTraits["versatile-s"];default:return CONFIG.PF2E.weaponTraits[`versatile-${damageType}`]??CONFIG.PF2E.damageTypes[damageType]}},"versatileLabel"),handsAvailable=!weapon.system.graspingAppendage||handsReallyFree>0,actionTraits2=["attack",weapon.baseType==="alchemical-bomb"?"manipulate":[]].flat();for(const adjustment of strikeAdjustments)adjustment.adjustTraits?.(weapon,actionTraits2);const ready2=weapon.isEquipped&&handsAvailable||weapon.isThrown&&weapon.reload==="0"&&weapon.isWorn&&handsReallyFree>0,action2=foundry.utils.mergeObject(strikeStat,{label:weapon.name,quantity:weapon.quantity,ready:ready2,domains:attackDomains,visible:weapon.slug!=="basic-unarmed"||this.flags.pf2e.showBasicUnarmed,glyph:"A",item:weapon,type:"strike",...flavor,options:Array.from(baseOptions),traits:actionTraits2.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),handsAvailable,weaponTraits:Array.from(weaponTraits2).map(t=>traitSlugToObject(t,CONFIG.PF2E.npcAttackTraits)).sort((a,b)=>a.label.localeCompare(b.label)),variants:[],selectedAmmoId:weapon.system.selectedAmmoId,altUsages,auxiliaryActions,versatileOptions:weapon.system.traits.toggles.versatile.options.map(o=>({value:o,selected:weapon.system.traits.toggles.versatile.selection===o,label:versatileLabel(o),glyph:DAMAGE_TYPE_ICONS[o]}))});if(action2.versatileOptions.length>0&&action2.versatileOptions.unshift({value:weapon.system.damage.damageType,selected:weapon.system.traits.toggles.versatile.selection===null,label:CONFIG.PF2E.damageTypes[weapon.system.damage.damageType],glyph:DAMAGE_TYPE_ICONS[weapon.system.damage.damageType]}),weapon.requiresAmmo){const compatible=ammos.filter(a=>a.isAmmoFor(weapon)),incompatible=ammos.filter(a=>!a.isAmmoFor(weapon)),{ammo}=weapon,selected=ammo?{id:ammo.id,compatible:ammo.isAmmoFor(weapon)}:null;action2.ammunition={compatible,incompatible,selected}}action2.breakdown=action2.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${m.modifier<0?"":"+"}${m.modifier}`).join(", ");const maps=calculateMAPs(weapon,{domains:attackDomains,options:initialRollOptions}),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,attackDomains,maps.slug)}),"createMapModifier"),createMapLabel=__name2(prop=>{const modifier=createMapModifier(prop);adjustModifiers([modifier],new Set(rollOptions));const penalty=modifier.ignored?0:modifier.value;return game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(action2.totalModifier+penalty),penalty})},"createMapLabel"),labels=[()=>signedInteger(action2.totalModifier),()=>createMapLabel("map1"),()=>createMapLabel("map2")],checkModifiers=[(statistic,otherModifiers)=>new CheckModifier("strike",statistic,otherModifiers),(statistic,otherModifiers)=>new CheckModifier("strike-map1",statistic,[...otherModifiers,createMapModifier("map1")]),(statistic,otherModifiers)=>new CheckModifier("strike-map2",statistic,[...otherModifiers,createMapModifier("map2")])];action2.variants=[0,1,2].map(mapIncreases=>({get label(){return labels[mapIncreases]()},roll:async(params={})=>{if(params.options??=[],params.consumeAmmo??=weapon.requiresAmmo,weapon.requiresAmmo&¶ms.consumeAmmo&&!weapon.ammo)return ui.notifications.warn(game.i18n.format("PF2E.Strike.Ranged.NoAmmo",{weapon:weapon.name,actor:this.name})),null;const context=await this.getCheckContext({item:weapon,domains:attackDomains,statistic:action2,target:{token:params.target??game.user.targets.first()??null},defense:"armor",options:new Set([...baseOptions,...params.options]),viewOnly:params.getFormula,traits:actionTraits2});if(action2.traits=context.traits.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits)),context.self.item.isRanged&&typeof context.target?.distance=="number"){const maxRange=context.self.item.range?.max??10;if(context.target.distance>maxRange)return ui.notifications.warn("PF2E.Action.Strike.OutOfRange",{localize:!0}),null}for(const rule of this.rules.filter(r=>!r.ignored))rule.beforeRoll?.(attackDomains,context.options);const dc=params.dc??context.dc,notes=extractNotes(context.self.actor.synthetics.rollNotes,attackDomains),rollTwice=params.rollTwice||extractRollTwice(context.self.actor.synthetics.rollTwice,attackDomains,context.options),substitutions=extractRollSubstitutions(context.self.actor.synthetics.rollSubstitutions,attackDomains,context.options),dosAdjustments=[getPropertyRuneDegreeAdjustments(context.self.item),extractDegreeOfSuccessAdjustments(context.self.actor.synthetics,attackDomains)].flat(),title=game.i18n.format(weapon.isMelee?"PF2E.Action.Strike.MeleeLabel":"PF2E.Action.Strike.RangedLabel",{weapon:weapon.name}),checkContext={type:"attack-roll",identifier:`${weapon.id}.${weaponSlug}.${meleeOrRanged}`,action:"strike",title,actor:context.self.actor,token:context.self.token,target:context.target,item:context.self.item,altUsage:params.altUsage??null,damaging:context.self.item.dealsDamage,domains:attackDomains,options:context.options,notes,dc,traits:context.traits,rollTwice,substitutions,dosAdjustments,mapIncreases};if(params.consumeAmmo&&!this.consumeAmmo(context.self.item,params))return null;const check=checkModifiers[mapIncreases](context.self.statistic??action2,context.self.modifiers),roll=await CheckPF2e.roll(check,checkContext,params.event,params.callback);if(roll)for(const rule of context.self.actor.rules.filter(r=>!r.ignored))await rule.afterRoll?.({roll,check,context:checkContext,domains:attackDomains,rollOptions:context.options});return roll}})),action2.attack=action2.roll=action2.variants[0].roll;for(const method of["damage","critical"])action2[method]=async(params={})=>{const domains=getStrikeDamageDomains(weapon,proficiencyRank);params.options=new Set(params.options??[]);const targetToken=params.target??game.user.targets.first()??null,context=await this.getDamageRollContext({item:weapon,viewOnly:params.getFormula??!1,statistic:action2,target:{token:targetToken},domains,outcome:method==="damage"?"success":"criticalSuccess",options:new Set([...baseOptions,...params.options]),traits:actionTraits2,checkContext:params.checkContext});if(!context.self.item.dealsDamage)return params.getFormula?"":(ui.notifications.warn("PF2E.ErrorMessage.WeaponNoDamage",{localize:!0}),null);const outcome=method==="damage"?"success":"criticalSuccess",{self,target,options}=context,damageContext={type:"damage-roll",sourceType:"attack",self,target,outcome,options,domains,traits:context.traits,...eventToRollParams(params.event,{type:"damage"})};typeof params.mapIncreases=="number"&&(damageContext.mapIncreases=params.mapIncreases,damageContext.options.add(`map:increases:${params.mapIncreases}`)),params.getFormula&&(damageContext.skipDialog=!0);const damage=await WeaponDamagePF2e.calculate({weapon:context.self.item,actor:context.self.actor,weaponPotency,context:damageContext});if(!damage)return null;if(params.getFormula){const formula=damage.damage.formula[outcome];return formula?new DamageRoll(formula).formula:""}else return DamagePF2e.roll(damage,damageContext,params.callback)};return action2}getStrikeDescription(weapon){const flavor={description:"PF2E.Strike.Default.Description",criticalSuccess:"PF2E.Strike.Default.CriticalSuccess",success:"PF2E.Strike.Default.Success"},traits=weapon.traits;return traits.has("unarmed")?(flavor.description="PF2E.Strike.Unarmed.Description",flavor.success="PF2E.Strike.Unarmed.Success"):[...traits].some(trait=>trait.startsWith("thrown-")||trait==="combination")?(flavor.description="PF2E.Strike.Combined.Description",flavor.success="PF2E.Strike.Combined.Success"):weapon.isMelee?(flavor.description="PF2E.Strike.Melee.Description",flavor.success="PF2E.Strike.Melee.Success"):(flavor.description="PF2E.Strike.Ranged.Description",flavor.success="PF2E.Strike.Ranged.Success"),flavor}async getRollContext(params){const context=await super.getRollContext(params);return params.statistic instanceof StatisticModifier&&context.self.item?.isOfType("weapon")&&PCAttackTraitHelpers.adjustWeapon(context.self.item),context}consumeAmmo(weapon,params){const ammo=weapon.ammo;if(ammo){if(ammo.quantity<1)return ui.notifications.warn(game.i18n.localize("PF2E.ErrorMessage.NotEnoughAmmo")),!1;{const existingCallback=params.callback;return params.callback=async roll=>{existingCallback?.(roll),await weapon.consumeAmmo()},!0}}else return!0}prepareMartialProficiencies(){for(const key of["attacks","defenses"]){const proficiencies=this.system.proficiencies[key],linkedProficiencies=Object.values(proficiencies).filter(p=>!!p?.sameAs&&p.sameAs in proficiencies);for(const proficiency of linkedProficiencies){const category=proficiencies[proficiency.sameAs??""];proficiency.rank=(()=>{const maxRankIndex=PROFICIENCY_RANKS.indexOf(proficiency.maxRank??"legendary");return Math.min(category?.rank??0,maxRankIndex)})()}const allProficiencies=Object.entries(proficiencies);for(const[_key,proficiency]of allProficiencies){if(!proficiency)continue;const duplicates=allProficiencies.flatMap(([k,p])=>p&&proficiency!==p&&proficiency.rank>=p.rank&&"definition"in proficiency&&"definition"in p&&proficiency.sameAs===p.sameAs&&equals(p.definition??[],[...proficiency.definition??[]])?k:[]);for(const duplicate of duplicates)delete proficiencies[duplicate];const proficiencyBonus=createProficiencyModifier({actor:this,rank:proficiency.rank,domains:[]});proficiency.value=proficiencyBonus.value,proficiency.breakdown=`${proficiencyBonus.label} ${signedInteger(proficiencyBonus.value)}`}}}async toggleInvested(itemId){const item=this.inventory.get(itemId);if(!item?.traits.has("invested"))throw ErrorPF2e("Unexpected error toggling item investment");const invested=item.isInvested;if(!invested&&!item.isEquipped){const newCarryType=item.system.usage.type==="carried"?"worn":item.system.usage.type;await this.adjustCarryType(item,{carryType:newCarryType,handsHeld:item.system.usage.hands,inSlot:!0})}return!!await item.update({"system.equipped.invested":!invested})}async addAttackProficiency(key){const currentProficiencies=this.system.proficiencies.attacks;if(key in currentProficiencies)return;const newProficiency={rank:1,custom:!0};await this.update({[`system.proficiencies.attacks.${key}`]:newProficiency})}async _preUpdate(changed,options,user){const systemData=this.system;if(typeof changed.system?.resources?.crafting?.infusedReagents?.value=="number"&&(changed.system.resources.crafting.infusedReagents.value=Math.max(0,Math.floor(changed.system.resources.crafting.infusedReagents.value))||0),changed.system?.details?.level||changed.system?.build?.attributes){const level=changed.system?.details?.level;typeof level?.value=="number"&&(level.value=Math.clamped(Number(level.value)||0,0,30)||0);const hpMaxDifference=this.clone(changed).hitPoints.max-this.hitPoints.max;if(hpMaxDifference!==0){options.allowHPOverage=!0;const currentHP=this.hitPoints.value,newHP=Math.max(currentHP+hpMaxDifference,currentHP===0?0:1);changed.system=foundry.utils.mergeObject(changed.system??{},{attributes:{hp:{value:newHP}}})}}game.pf2e.settings.variants.stamina&&(changed.system?.attributes?.hp?.sp&&(changed.system.attributes.hp.sp.value=Math.floor(Math.clamped(changed.system.attributes.hp.sp?.value??0,0,systemData.attributes.hp.sp?.max??0))||0),changed.system?.resources?.resolve&&(changed.system.resources.resolve.value=Math.floor(Math.clamped(changed.system.resources.resolve.value??0,0,systemData.resources.resolve?.max??0))||0));const xp=changed.system?.details?.xp??{};typeof xp.value=="number"&&(xp.value=Math.max(xp.value,0)),typeof xp.max=="number"&&(xp.max=Math.max(xp.max,1));const newLevel=changed.system?.details?.level?.value??this.level,actorClass=this.class;if(actorClass&&newLevel!==this.level){const current=this.itemTypes.feat.filter(feat=>feat.category==="classfeature");if(newLevel>this.level){const classFeaturesToCreate=(await actorClass.createGrantedItems({level:newLevel})).filter(feature=>feature.system.level.value>this.level&&!current.some(currentFeature=>currentFeature.sourceId===feature.flags.core?.sourceId)).map(i=>i.toObject());await this.createEmbeddedDocuments("Item",classFeaturesToCreate,{keepId:!0,render:!1})}else if(newLevelf.level>newLevel&&!f.grantedBy).map(f=>f.id);await this.deleteEmbeddedDocuments("Item",classFeaturestoDelete,{render:!1})}}for(const property of["playerNumber","characterNumber"])if(typeof changed.system?.pfs?.[property]=="number"){const[min,max]=property==="playerNumber"?[1,9999999]:[2001,9999];changed.system.pfs[property]=Math.clamped(changed.system.pfs[property]||0,min,max)}else changed.system?.pfs&&changed.system.pfs[property]!==null&&(changed.system.pfs[property]=this.system.pfs[property]??null);return super._preUpdate(changed,options,user)}}class FamiliarPF2e extends CreaturePF2e{static{__name(this,"FamiliarPF2e")}static{__name2(this,"FamiliarPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"action"]}get master(){if(!game.ready||!this.system.master.id)return null;const master=game.actors.get(this.system.master.id??"");return master?.isOfType("character")?(master.familiar??=this,master):null}get masterAttributeModifier(){return this.system.master.ability||="cha",this.master?.system.abilities[this.system.master.ability].mod??0}get masterAbilityModifier(){return this.masterAttributeModifier}get combatant(){return this.master?.combatant??null}reset({fromMaster=!1}={}){super.reset(),fromMaster&&this.sheet.render()}prepareBaseData(){const systemData=this.system;systemData.details.level={value:0},systemData.traits={value:["minion"],senses:[{type:"lowLightVision",label:CONFIG.PF2E.senses.lowLightVision,value:""}],size:new ActorSizePF2e({value:"tiny"})},super.prepareBaseData();const isItemBonus=new PredicatePF2e(["bonus:type:item"]);this.synthetics.modifierAdjustments.all.push({slug:null,test:options=>isItemBonus.test(options),suppress:!0}),systemData.attributes.flanking.canFlank=!1,systemData.attributes.perception={},systemData.attributes.speed={value:25,label:game.i18n.localize("PF2E.SpeedTypesLand"),otherSpeeds:[]},systemData.skills={},systemData.saves={fortitude:{},reflex:{},will:{}},systemData.traits=foundry.utils.mergeObject(systemData.traits,{dv:[],di:[],dr:[]});const{master}=this;systemData.details.level.value=master?.level??0,this.rollOptions.all[`self:level:${this.level}`]=!0,systemData.details.alliance=master?.alliance??"party",master&&(this.flags.pf2e.rollOptions.all=foundry.utils.mergeObject(this.flags.pf2e.rollOptions.all,createEncounterRollOptions(master)))}prepareRuleElements(){return this.master?super.prepareRuleElements():[]}prepareDerivedData(){super.prepareDerivedData();const{master}=this,systemData=this.system,{attributes,traits}=systemData;traits.value=[...this.traits].sort();const{level,masterAttributeModifier}=this,masterLevel=game.pf2e.settings.variants.pwol.enabled?0:level,{synthetics}=this,speeds=attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]);const hitPoints=new HitPointsStatistic(this,{baseMax:level*5});this.system.attributes.hp=hitPoints.getTraceData(),setHitPointsRollOptions(this);const masterModifier=master?new ModifierPF2e({label:"PF2E.Actor.Familiar.Master.ArmorClass",slug:"base",modifier:master.armorClass.modifiers.filter(m=>m.enabled&&!["status","circumstance"].includes(m.type)).reduce((total,modifier)=>total+modifier.value,0)}):null,statistic=new ArmorStatistic(this,{modifiers:compact([masterModifier])});this.armorClass=statistic.dc,systemData.attributes.ac=statistic.getTraceData(),this.saves=SAVE_TYPES.reduce((partialSaves,saveType)=>{const source=master?.saves[saveType]?.modifiers.filter(m=>!["status","circumstance"].includes(m.type))??[],totalMod=applyStackingRules(source),attribute=CONFIG.PF2E.savingThrowDefaultAttributes[saveType],selectors=[saveType,`${attribute}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:game.i18n.localize(CONFIG.PF2E.saves[saveType]),domains:selectors,modifiers:[new ModifierPF2e(`PF2E.MasterSavingThrow.${saveType}`,totalMod,"untyped")],check:{type:"saving-throw"}});return{...partialSaves,[saveType]:stat}},{}),this.system.saves=SAVE_TYPES.reduce((partial,saveType)=>({...partial,[saveType]:this.saves[saveType].getTraceData()}),{}),traits.senses=this.prepareSenses(this.system.traits.senses,synthetics),this.attackStatistic=new Statistic(this,{slug:"attack-roll",label:"PF2E.Familiar.AttackRoll",modifiers:[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped")],check:{type:"attack-roll"}}),this.system.attack=this.attackStatistic.getTraceData();{const domains=["perception","wis-based","all"],modifiers=[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped"),new ModifierPF2e(`PF2E.MasterAbility.${systemData.master.ability}`,masterAttributeModifier,"untyped")];this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",domains,modifiers,check:{type:"perception-check"}}),systemData.attributes.perception=foundry.utils.mergeObject(systemData.attributes.perception,this.perception.getTraceData({value:"mod"}))}this.skills=Array.from(SKILL_ABBREVIATIONS).reduce((builtSkills,shortForm)=>{const longForm=SKILL_DICTIONARY[shortForm],modifiers=[new ModifierPF2e("PF2E.MasterLevel",masterLevel,"untyped")];if(["acr","ste"].includes(shortForm)){const label2=`PF2E.MasterAbility.${systemData.master.ability}`;modifiers.push(new ModifierPF2e(label2,masterAttributeModifier,"untyped"))}const attribute=SKILL_EXPANDED[longForm].attribute,domains=[longForm,`${attribute}-based`,"skill-check","all"],label=CONFIG.PF2E.skills[shortForm]??longForm,statistic2=new Statistic(this,{slug:longForm,label,attribute,domains,modifiers,lore:!1,check:{type:"skill-check"}});return builtSkills[longForm]=statistic2,this.system.skills[shortForm]=statistic2.getTraceData(),builtSkills},{})}_onDelete(options,userId){this.master&&(this.master.familiar=null),super._onDelete(options,userId)}}const identifySkills=new Map([["aberration",["occultism"]],["animal",["nature"]],["astral",["occultism"]],["beast",["arcana","nature"]],["celestial",["religion"]],["construct",["arcana","crafting"]],["dragon",["arcana"]],["elemental",["arcana","nature"]],["ethereal",["occultism"]],["fey",["nature"]],["fiend",["religion"]],["fungus",["nature"]],["humanoid",["society"]],["monitor",["religion"]],["ooze",["occultism"]],["plant",["nature"]],["spirit",["occultism"]],["undead",["religion"]]]);function toKnowledgeDC(dc,rarity,loreAdjustment="normal"){const rarityAdjustment=rarityToDCAdjustment(rarity),start=combineDCAdjustments(rarityAdjustment,loreAdjustment),progression=createDifficultyScale(dc,start);return{dc:adjustDC(dc,start),progression,start}}__name(toKnowledgeDC,"toKnowledgeDC"),__name2(toKnowledgeDC,"toKnowledgeDC");function creatureIdentificationDCs(creature,{pwol=!1}={}){const{level,rarity}=creature,dc=calculateDC(level,{pwol}),traits=creature.system.traits.value;return{skills:Array.from(new Set(traits.flatMap(t=>identifySkills.get(t)??[]))),standard:toKnowledgeDC(dc,rarity,"normal"),lore:[toKnowledgeDC(dc,rarity,"easy"),toKnowledgeDC(dc,rarity,"very-easy")]}}__name(creatureIdentificationDCs,"creatureIdentificationDCs"),__name2(creatureIdentificationDCs,"creatureIdentificationDCs");class NPCPF2e extends CreaturePF2e{static{__name(this,"NPCPF2e")}static{__name2(this,"NPCPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"physical","spellcastingEntry","spell","action","melee","lore"]}get baseLevel(){return this._source.system.details.level.value}get abilities(){return foundry.utils.deepClone(this.system.abilities)}get description(){return this.system.details.publicNotes}get isElite(){return this.attributes.adjustment==="elite"}get isWeak(){return this.attributes.adjustment==="weak"}get identificationDCs(){const pwol=game.pf2e.settings.variants.pwol.enabled;return creatureIdentificationDCs(this,{pwol})}get isLootable(){const npcsAreLootable=game.settings.get("pf2e","automation.lootableNPCs");return this.isDead&&(npcsAreLootable||this.flags.pf2e.lootable)}get visible(){return super.visible&&this.prototypeToken.actorLink||this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}canUserModify(user,action2){return super.canUserModify(user,action2)||action2==="update"&&this.isLootable}prepareBaseData(){super.prepareBaseData(),this.flags.pf2e.lootable??=!1;const systemData=this.system;systemData.actions=[];for(const key of SAVE_TYPES)systemData.saves[key].ability=CONFIG.PF2E.savingThrowDefaultAttributes[key];const{attributes,details}=systemData;attributes.perception.ability="wis",attributes.reach={base:SIZE_TO_REACH[this.size],manipulate:SIZE_TO_REACH[this.size]},details.alliance===void 0&&(details.alliance=this.hasPlayerOwner?"party":"opposition"),attributes.hp.negativeHealing=systemData.traits.value.includes("undead"),attributes.flanking.flankable=!systemData.traits.value.includes("troop");const{level}=details;level.base=Math.clamped(level.value,-1,100),level.value=this.isElite?level.base+1:this.isWeak?level.base-1:level.base,this.rollOptions.all[`self:level:${level.value}`]=!0,attributes.spellDC=null,attributes.classDC=(()=>{const pwol=game.pf2e.settings.variants.pwol.enabled,levelBasedDC=calculateDC(level.base,{pwol,rarity:this.rarity});return{value:this.isElite?levelBasedDC+2:this.isWeak?levelBasedDC-2:levelBasedDC}})(),attributes.classOrSpellDC={value:attributes.classDC.value},this.system.spellcasting=foundry.utils.mergeObject({rituals:{dc:0}},this.system.spellcasting),this.system.resources.focus=foundry.utils.mergeObject({value:0,max:0,cap:3},this.system.resources.focus)}prepareDerivedData(){super.prepareDerivedData();const{system}=this,{synthetics}=this,{modifierAdjustments}=synthetics,baseLevel=this.system.details.level.base;this.synthetics.modifiers.hp??=[],this.isElite?(modifierAdjustments.all.push({slug:"base",getNewValue:base=>base+2,test:()=>!0}),this.synthetics.modifiers.hp.push(()=>new ModifierPF2e("PF2E.NPC.Adjustment.EliteLabel",this.getHpAdjustment(baseLevel,"elite"),"untyped"))):this.isWeak&&(modifierAdjustments.all.push({slug:"base",getNewValue:base=>base-2,test:()=>!0}),this.synthetics.modifiers.hp.push(()=>new ModifierPF2e("PF2E.NPC.Adjustment.WeakLabel",this.getHpAdjustment(baseLevel,"weak")*-1,"untyped"))),system.details.level.base=baseLevel;for(const ability of Object.values(this.system.abilities))ability.mod=Math.trunc(Number(ability.mod))||0;{const base=system.attributes.hp.max,modifiers=[extractModifiers(this.synthetics,["hp"],{test:this.getRollOptions(["hp"])}),extractModifiers(this.synthetics,["hp-per-level"],{test:this.getRollOptions(["hp-per-level"])}).map(modifier=>(modifier.modifier*=this.level,modifier))].flat(),hpData=foundry.utils.deepClone(system.attributes.hp),stat=foundry.utils.mergeObject(new StatisticModifier("hp",modifiers),hpData,{overwrite:!1});stat.base=base,stat.max=stat.max+stat.totalModifier,stat.value=Math.min(stat.value,stat.max),stat.breakdown=[game.i18n.format("PF2E.MaxHitPointsBaseLabel",{base}),...stat.modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`)].join(", "),system.attributes.hp=stat,setHitPointsRollOptions(this)}const speeds=system.attributes.speed=this.prepareSpeed("land");speeds.otherSpeeds=["burrow","climb","fly","swim"].flatMap(m=>this.prepareSpeed(m)??[]);const armorStatistic=new ArmorStatistic(this,{modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.attributes.ac.value-10,adjustments:extractModifierAdjustments(modifierAdjustments,["all","ac","dex-based"],"base")})],details:system.attributes.ac.details});this.armorClass=armorStatistic.dc,this.system.attributes.ac=armorStatistic.getTraceData(),this.prepareSaves();{const domains=["perception","wis-based","all"];this.perception=new Statistic(this,{slug:"perception",label:"PF2E.PerceptionLabel",attribute:"wis",domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.attributes.perception.value,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"perception-check"}}),system.attributes.perception=foundry.utils.mergeObject(system.attributes.perception,this.perception.getTraceData({value:"mod"}))}this.skills=this.prepareSkills();const generatedMelee=Array.from(synthetics.strikes.values()).flatMap(w=>w.toNPCAttacks({keepId:!0}));for(const item of[...this.itemTypes.melee,...generatedMelee])system.actions.push(strikeFromMeleeItem(item));const initiativeSkill=system.attributes.initiative?.statistic||"perception";this.initiative=new ActorInitiative(this,{statistic:initiativeSkill}),this.system.attributes.initiative=this.initiative.getTraceData()}prepareSaves(){const systemData=this.system,{modifierAdjustments}=this.synthetics,saves={};for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType],saveName=game.i18n.localize(CONFIG.PF2E.saves[saveType]),base=save.value,ability=save.ability,domains=[saveType,`${ability}-based`,"saving-throw","all"],stat=new Statistic(this,{slug:saveType,label:saveName,domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"saving-throw"}});saves[saveType]=stat,foundry.utils.mergeObject(this.system.saves[saveType],stat.getTraceData()),systemData.saves[saveType].base=base}this.saves=saves}prepareSkills(){const{system}=this,{modifierAdjustments}=this.synthetics;system.skills={};function createTrace(stat,item){const{attribute,shortForm}=objectHasKey(SKILL_EXPANDED,stat.slug)?SKILL_EXPANDED[stat.slug]:{attribute:"int",shortForm:stat.slug};system.skills[shortForm]={...stat.getTraceData(),base:item?.system.mod.value,isLore:!!stat.lore,itemID:item?.id,ability:attribute,visible:stat.proficient,variants:Object.values(item?.system.variants??{})}}__name(createTrace,"createTrace"),__name2(createTrace,"createTrace");const skills={};for(const skill of SKILL_LONG_FORMS){const{attribute,shortForm}=SKILL_EXPANDED[skill],domains=[skill,`${attribute}-based`,"skill-check",`${attribute}-skill-check`,"all"],name2=game.i18n.localize(`PF2E.Skill${SKILL_DICTIONARY[shortForm].capitalize()}`),statistic=new Statistic(this,{slug:skill,label:name2,attribute,domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:system.abilities[attribute].mod,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],lore:!1,proficient:!1,check:{type:"skill-check"}});skills[skill]=statistic,createTrace(statistic)}for(const item of this.itemTypes.lore){const skill=sluggify(item.name),attribute=objectHasKey(SKILL_EXPANDED,skill)?SKILL_EXPANDED[skill].attribute:"int",label=objectHasKey(CONFIG.PF2E.skillList,skill)?CONFIG.PF2E.skillList[skill]:item.name,base=item.system.mod.value,domains=[skill,`${attribute}-based`,"skill-check","lore-skill-check",`${attribute}-skill-check`,"all"],statistic=new Statistic(this,{slug:skill,label,attribute,lore:!objectHasKey(SKILL_EXPANDED,skill),domains,modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base,adjustments:extractModifierAdjustments(modifierAdjustments,domains,"base")})],check:{type:"skill-check"}});skills[skill]=statistic,createTrace(statistic,item)}return skills}async getAttackEffects(attack){const notes=[];attack.description&¬es.push(new RollNotePF2e({selector:"all",visibility:"gm",text:attack.description}));const formatItemName=__name2(item=>{if(item.isOfType("consumable")){const button=createHTMLElement("button",{dataset:{action:"consume",item:item.id}});return button.style.width="auto",button.style.lineHeight="14px",button.innerHTML=game.i18n.localize("PF2E.ConsumableUseLabel"),`${item.name} - ${game.i18n.localize("TYPES.Item.consumable")} (${item.quantity}) ${button.outerHTML}`}return item.name},"formatItemName"),formatNoteText=__name2(item=>{const rollData=item.getRollData();return TextEditor.enrichHTML(item.description,{rollData,async:!0})},"formatNoteText");for(const attackEffect of attack.attackEffects){const item=this.items.find(i=>i.type!=="melee"&&(i.slug??sluggify(i.name))===sluggify(attackEffect));if(item){const note=new RollNotePF2e({selector:"all",visibility:"gm",title:formatItemName(item),text:await formatNoteText(item)});notes.push(note)}else{const packItem=(await game.packs.get("pf2e.bestiary-ability-glossary-srd",{strict:!0}).getDocuments({system:{slug:attackEffect}}))[0];if(packItem instanceof ItemPF2e){const note=new RollNotePF2e({selector:"all",visibility:"gm",title:formatItemName(packItem),text:await formatNoteText(packItem)});notes.push(note)}}}return notes}getHpAdjustment(level,adjustment){if(adjustment==="elite"){if(level>=20)return 30;if(level<=19&&level>=5)return 20;if(level<=4&&level>=2)return 15;if(level<=1)return 10}else if(adjustment==="weak"){if(level>=21)return 30;if(level<=20&&level>=6)return 20;if(level<=5&&level>=3)return 15;if(level===1||level===2)return 10}return 0}async applyAdjustment(adjustment){const{isElite,isWeak}=this;if(isElite&&adjustment==="elite"||isWeak&&adjustment==="weak"||!isElite&&!isWeak&&!adjustment)return;const currentHPAdjustment=(()=>isElite?this.getHpAdjustment(this.baseLevel,"elite"):isWeak?this.getHpAdjustment(this.baseLevel,"weak"):0)(),newHPAdjustment=this.getHpAdjustment(this.baseLevel,adjustment),currentHP=this.system.attributes.hp.value,maxHP=this.system.attributes.hp.max,newHP=(()=>{if(isElite){if(adjustment==="weak")return currentHP-currentHPAdjustment-newHPAdjustment;if(!adjustment)return currentHP-currentHPAdjustment}else if(isWeak){if(adjustment==="elite")return this.system.attributes.hp.max=maxHP+currentHPAdjustment+newHPAdjustment,currentHP+currentHPAdjustment+newHPAdjustment;if(!adjustment)return this.system.attributes.hp.max=maxHP+currentHPAdjustment,currentHP+currentHPAdjustment}else{if(adjustment==="elite")return this.system.attributes.hp.max=currentHP+newHPAdjustment,currentHP+newHPAdjustment;if(adjustment==="weak")return currentHP-newHPAdjustment}return currentHP})();await this.update({"system.attributes.hp.value":Math.max(0,newHP),"system.attributes.adjustment":adjustment})}variantClone(params){const source=this._source,changes={name:params.name??this.name,system:{details:{publicNotes:params.description??source.system.details.publicNotes}},img:params.img?.actor??source.img,prototypeToken:{texture:{src:params.img?.token??source.prototypeToken.texture.src}}};return this.clone(changes,{save:params.save,keepId:params.keepId})}}function resolveKingdomBoosts(entry,choices){const notFreeBoosts=entry.boosts.filter(b=>b!=="free");return uniq([notFreeBoosts,choices].flat()).filter(b=>b!==entry.flaw).slice(0,entry.boosts.length)}__name(resolveKingdomBoosts,"resolveKingdomBoosts"),__name2(resolveKingdomBoosts,"resolveKingdomBoosts");function calculateKingdomCollectionData(kingdom){const commodityTypes=["luxuries","lumber","ore","stone"];return{formula:`${kingdom.resources.dice.number}d${kingdom.resources.dice.faces}`,commodities:mapToObj(commodityTypes,type=>{const value=kingdom.resources.workSites[type];return[type,value.value+value.resource*2]})}}__name(calculateKingdomCollectionData,"calculateKingdomCollectionData"),__name2(calculateKingdomCollectionData,"calculateKingdomCollectionData");async function importDocuments(actor,items,skipDialog){const createData=items.filter(d=>!actor.items.some(i=>i.sourceId===d.uuid)).map(d=>d.toObject()),incomingDataByUUID=mapToObj(items,d=>[d.uuid,d.toObject(!0)]),updateData=compact(actor.itemTypes.campaignFeature.map(d=>{const incoming=d.sourceId&&incomingDataByUUID[d.sourceId];if(!incoming)return null;const data=pick(incoming,["name","img","system"]),diff=foundry.utils.diffObject(d.toObject(!0),data);return isEmpty(diff)?null:{_id:d.id,...diff}}));!updateData.length&&!createData.length||!skipDialog&&!await Dialog.confirm({title:game.i18n.localize("PF2E.Kingmaker.Kingdom.ImportDialog.Title"),content:game.i18n.format("PF2E.Kingmaker.Kingdom.ImportDialog.Content",{added:createData.length,updated:updateData.length})})||(await actor.updateEmbeddedDocuments("Item",updateData),await actor.createEmbeddedDocuments("Item",createData))}__name(importDocuments,"importDocuments"),__name2(importDocuments,"importDocuments");const KINGDOM_ABILITIES=["culture","economy","loyalty","stability"],KINGDOM_LEADERSHIP=["ruler","counselor","general","emissary","magister","treasurer","viceroy","warden"],KINGDOM_COMMODITIES=["food","luxuries","lumber","ore","stone"],KINGDOM_SKILLS=["agriculture","arts","boating","defense","engineering","exploration","folklore","industry","intrigue","magic","politics","scholarship","statecraft","trade","warfare","wilderness"],KINGDOM_LEADERSHIP_ABILITIES={ruler:"loyalty",counselor:"culture",general:"stability",emissary:"loyalty",magister:"culture",treasurer:"economy",viceroy:"economy",warden:"stability"},KINGDOM_SKILL_ABILITIES={agriculture:"stability",arts:"culture",boating:"economy",defense:"stability",engineering:"stability",exploration:"economy",folklore:"culture",industry:"economy",intrigue:"loyalty",magic:"culture",politics:"loyalty",scholarship:"culture",statecraft:"loyalty",trade:"economy",warfare:"loyalty",wilderness:"stability"},KINGDOM_ABILITY_LABELS=mapToObj(KINGDOM_ABILITIES,a=>[a,`PF2E.Kingmaker.Abilities.${a}`]),KINGDOM_COMMODITY_LABELS=mapToObj(KINGDOM_COMMODITIES,c=>[c,`PF2E.Kingmaker.Kingdom.Commodity.${c}`]),KINGDOM_RUIN_LABELS={culture:"PF2E.Kingmaker.Kingdom.Ruin.corruption",economy:"PF2E.Kingmaker.Kingdom.Ruin.crime",stability:"PF2E.Kingmaker.Kingdom.Ruin.decay",loyalty:"PF2E.Kingmaker.Kingdom.Ruin.strife"},KINGDOM_SKILL_LABELS=mapToObj(KINGDOM_SKILLS,a=>[a,`PF2E.Kingmaker.Skills.${a}`]),CONTROL_DC_BY_LEVEL=[14,15,16,18,20,22,23,24,26,27,28,30,31,32,34,35,36,38,39,40],KINGDOM_SIZE_DATA={1:{faces:4,type:"territory",controlMod:0,storage:4},10:{faces:6,type:"province",controlMod:1,storage:8},25:{faces:8,type:"state",controlMod:2,storage:12},50:{faces:10,type:"country",controlMod:3,storage:16},100:{faces:12,type:"dominion",controlMod:4,storage:20}},KINGDOM_SETTLEMENT_TYPES=["village","town","city","metropolis"],KINGDOM_SETTLEMENT_TYPE_LABELS=mapToObj(KINGDOM_SETTLEMENT_TYPES,size=>[size,`PF2E.Kingmaker.Settlement.Type.${size}`]),KINGDOM_SETTLEMENT_TYPE_DATA={village:{blocks:1,population:[0,400],level:[1,1],consumption:1,maxItemBonus:1,influence:0},town:{blocks:4,population:[401,2e3],level:[2,4],consumption:2,maxItemBonus:1,influence:1},city:{blocks:9,population:[2001,25e3],level:[5,9],consumption:4,maxItemBonus:2,influence:2},metropolis:{blocks:1/0,population:[25001,1/0],level:[10,1/0],consumption:6,maxItemBonus:3,influence:3}},vacancyLabel=__name2(role=>game.i18n.format("PF2E.Kingmaker.Kingdom.VacantRole",{role:game.i18n.localize(`PF2E.Kingmaker.Kingdom.LeadershipRole.${role}`)}),"vacancyLabel"),VACANCY_PENALTIES={ruler:()=>({modifiers:{"kingdom-check":[{slug:"vacancy-ruler",label:vacancyLabel("ruler"),modifier:-1}],"control-dc":[{slug:"vacancy-ruler",label:vacancyLabel("ruler"),modifier:2}]}}),counselor:()=>({modifiers:{"culture-based":[{slug:"vacancy",label:vacancyLabel("counselor"),modifier:-1}]}}),general:()=>({modifiers:{warfare:[{slug:"vacancy",label:vacancyLabel("general"),modifier:0}]},adjustments:{warfare:[{slug:"vacancy",test:()=>!0,relabel:vacancyLabel("general"),getNewValue:()=>-4}]}}),emissary:()=>({modifiers:{"loyalty-based":[{slug:"vacancy",label:vacancyLabel("emissary"),modifier:-1}]}}),magister:()=>({modifiers:{warfare:[{slug:"vacancy",label:vacancyLabel("magister"),modifier:0}]},adjustments:{warfare:[{slug:"vacancy",test:()=>!0,relabel:vacancyLabel("magister"),getNewValue:()=>-4}]}}),treasurer:()=>({modifiers:{"economy-based":[{slug:"vacancy",label:vacancyLabel("treasurer"),modifier:-1}]}}),viceroy:()=>({modifiers:{"stability-based":[{slug:"vacancy",label:vacancyLabel("viceroy"),modifier:-1}]}}),warden:()=>({modifiers:{"kingdom-check":[{slug:"vacancy",label:vacancyLabel("warden"),modifier:0}]},adjustments:{"kingdom-check":[{slug:"vacancy",test:options=>[...options].includes("region"),relabel:vacancyLabel("warden"),getNewValue:()=>-4}]}})};function getKingdomCHGData(){const localize=localizer("PF2E.Kingmaker");return{charter:{conquest:{name:localize("Charter.conquest.Name"),description:localize("Charter.conquest.Description"),img:"/icons/weapons/swords/sword-guard-steel-green.webp",boosts:["loyalty","free"],flaw:"culture"},expansion:{name:localize("Charter.expansion.Name"),description:localize("Charter.expansion.Description"),img:"/icons/skills/trades/woodcutting-logging-axe-stump.webp",boosts:["culture","free"],flaw:"stability"},exploration:{name:localize("Charter.exploration.Name"),description:localize("Charter.exploration.Description"),img:"/icons/tools/navigation/map-chart-tan.webp",boosts:["stability","free"],flaw:"economy"},grant:{name:localize("Charter.grant.Name"),description:localize("Charter.grant.Description"),img:"/icons/skills/trades/academics-merchant-scribe.webp",boosts:["economy","free"],flaw:"loyalty"},open:{name:localize("Charter.open.Name"),description:localize("Charter.open.Description"),img:"/icons/sundries/documents/document-sealed-brown-red.webp",boosts:["free"],flaw:null}},heartland:{forestOrSwamp:{name:localize("Heartland.forestOrSwamp.Name"),description:localize("Heartland.forestOrSwamp.Description"),img:"/icons/environment/wilderness/tree-oak.webp",boosts:["culture"]},hillOrPlain:{name:localize("Heartland.hillOrPlain.Name"),description:localize("Heartland.hillOrPlain.Description"),img:"/icons/environment/creatures/horses.webp",boosts:["loyalty"]},lakeOrRiver:{name:localize("Heartland.lakeOrRiver.Name"),description:localize("Heartland.lakeOrRiver.Description"),img:"/icons/environment/settlement/bridge-stone.webp",boosts:["economy"]},mountainOrRuins:{name:localize("Heartland.mountainOrRuins.Name"),description:localize("Heartland.mountainOrRuins.Description"),img:"/icons/environment/wilderness/cave-entrance-mountain.webp",boosts:["stability"]}},government:{despotism:{name:localize("Government.despotism.Name"),description:localize("Government.despotism.Description"),img:"/icons/environment/settlement/pyramid.webp",boosts:["stability","economy","free"],skills:["intrigue","warfare"],feat:"Compendium.pf2e.kingmaker-features.Item.WGpkcIChjIk1i0q0"},feudalism:{name:localize("Government.feudalism.Name"),description:localize("Government.feudalism.Description"),img:"/icons/environment/settlement/watchtower-cliff.webp",boosts:["stability","culture","free"],skills:["defense","trade"],feat:"Compendium.pf2e.kingmaker-features.Item.JYY8vQxPe9AIGTvv"},oligarchy:{name:localize("Government.oligarchy.Name"),description:localize("Government.oligarchy.Description"),img:"/icons/environment/settlement/house-manor.webp",boosts:["loyalty","economy","free"],skills:["arts","industry"],feat:"Compendium.pf2e.kingmaker-features.Item.9dkyZ7r1z7loOxI7"},republic:{name:localize("Government.republic.Name"),description:localize("Government.republic.Description"),img:"/icons/environment/settlement/gazebo.webp",boosts:["stability","economy","free"],skills:["engineering","politics"],feat:"Compendium.pf2e.kingmaker-features.Item.BChcBEZpcqMnLISC"},thaumocracy:{name:localize("Government.thaumocracy.Name"),description:localize("Government.thaumocracy.Description"),img:"/icons/environment/settlement/wizard-castle.webp",boosts:["economy","culture","free"],skills:["folklore","magic"],feat:"Compendium.pf2e.kingmaker-features.Item.nDDEbrWj2JouxlRw"},yeomanry:{name:localize("Government.yeomanry.Name"),description:localize("Government.yeomanry.Description"),img:"/icons/environment/settlement/house-farmland-small.webp",boosts:["loyalty","culture","free"],skills:["agriculture","wilderness"],feat:"Compendium.pf2e.kingmaker-features.Item.WFng3pxgEAdpdy1p"}}}}__name(getKingdomCHGData,"getKingdomCHGData"),__name2(getKingdomCHGData,"getKingdomCHGData");const KINGDOM_TRAITS=["commerce","leadership","region","civic","army"];class KingdomSheetPF2e extends ActorSheetPF2e{static{__name(this,"KingdomSheetPF2e")}static{__name2(this,"KingdomSheetPF2e")}selectedFilter=null;focusElement=null;#editingSettlements={};constructor(actor,options){super(actor,options)}get kingdom(){const campaign=this.actor.campaign;if(!(campaign instanceof Kingdom))throw this.close(),ErrorPF2e("Only actors with kingdom data is supported");return campaign}get title(){return this.kingdom.name}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"kingdom"],width:720,height:620,template:"systems/pf2e/templates/actors/party/kingdom/sheet.hbs",scrollY:[...options.scrollY,".tab.active",".tab.active .content",".sidebar"],tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fa-solid fa-eye",onclick:()=>{const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:this.actor.uuid,options:{campaign:!0,tab:this._tabs[0].active}})}}),buttons}async getData(options){const data=await super.getData(options),kingdom=this.kingdom,settlementEntries=pipe(Object.entries(this.kingdom.settlements),filter(entry=>!!entry[1]),sortBy(entry=>entry[1].sort));return{...data,actor:this.actor,kingdom:this.kingdom,nationTypeLabel:game.i18n.localize(`PF2E.Kingmaker.Kingdom.NationType.${kingdom.nationType}`),abilities:KINGDOM_ABILITIES.map(slug=>({...this.kingdom.abilities[slug],slug,label:game.i18n.localize(KINGDOM_ABILITY_LABELS[slug]),ruinLabel:game.i18n.localize(KINGDOM_RUIN_LABELS[slug])})),commodities:KINGDOM_COMMODITIES.map(type=>({...kingdom.resources.commodities[type],type,label:game.i18n.localize(KINGDOM_COMMODITY_LABELS[type]),workSites:{label:game.i18n.localize(`PF2E.Kingmaker.WorkSites.${type}.Name`),description:game.i18n.localize(`PF2E.Kingmaker.WorkSites.${type}.Description`),hasResource:["lumber","ore","stone"].includes(type),value:kingdom.resources.workSites[type].value,resource:kingdom.resources.workSites[type].resource}})),resourceDice:{...kingdom.resources.dice,icon:fontAwesomeIcon(`dice-d${kingdom.resources.dice.faces}`).outerHTML,bonusAdjustment:getAdjustment(kingdom.resources.dice.bonus,kingdom._source.resources.dice.bonus),penaltyAdjustment:getAdjustment(kingdom.resources.dice.penalty,kingdom._source.resources.dice.penalty)},leadership:KINGDOM_LEADERSHIP.map(slug=>{const data2=this.kingdom.leadership[slug],document2=fromUuidSync(data2.uuid??""),actor=document2 instanceof ActorPF2e?document2:null;return{...data2,slug,label:game.i18n.localize(`PF2E.Kingmaker.Kingdom.LeadershipRole.${slug}`),actor,img:actor?.prototypeToken.texture.src??actor?.img??ActorPF2e.DEFAULT_ICON,abilityLabel:game.i18n.localize(KINGDOM_ABILITY_LABELS[KINGDOM_LEADERSHIP_ABILITIES[slug]]),penaltyLabel:game.i18n.localize(`PF2E.Kingmaker.Kingdom.VacancyPenalty.${slug}`)}}),actions:sortBy(kingdom.activities,a=>a.name).map(item=>({item,traits:createSheetTags(CONFIG.PF2E.kingmakerTraits,item.system.traits.value.filter(t=>t!=="downtime"))})),skills:sortBy(Object.values(this.kingdom.skills),s=>s.label),feats:[kingdom.features,kingdom.feats,kingdom.bonusFeats],actionFilterChoices:KINGDOM_TRAITS.map(trait=>({label:game.i18n.localize(CONFIG.PF2E.kingmakerTraits[trait]),value:trait,selected:!1})),settlements:await Promise.all(settlementEntries.map(async([id,data2])=>this.#prepareSettlement(id,data2))),eventText:await TextEditor.enrichHTML(kingdom.event.text,{async:!0,rollData:this.actor.getRollData()}),settlementTypes:KINGDOM_SETTLEMENT_TYPE_LABELS,abilityLabels:KINGDOM_ABILITY_LABELS,skillLabels:KINGDOM_SKILL_LABELS}}async#prepareSettlement(id,settlement){const data=KINGDOM_SETTLEMENT_TYPE_DATA[settlement.type],levelRange=data.level[1]===1/0?`${data.level[0]}+`:data.level[0]===data.level[1]?String(data.level[0]):data.level.join("-"),populationRange=data.population[1]===1/0?`${data.population[0]}+`:data.population.join("-");return{...settlement,id,description:await TextEditor.enrichHTML(settlement.description,{async:!0,rollData:this.actor.getRollData()}),editing:this.#editingSettlements[id]??!1,blocks:data.blocks===1/0?"10+":data.blocks,populationRange,levelRange,typeLabel:KINGDOM_SETTLEMENT_TYPE_LABELS[settlement.type],storage:KINGDOM_COMMODITIES.map(type=>({type,value:settlement.storage[type],label:game.i18n.localize(KINGDOM_COMMODITY_LABELS[type])}))}}activateListeners($html){super.activateListeners($html);const html=$html[0];this.focusElement&&(htmlQuery(html,this.focusElement)?.focus(),this.focusElement=null);for(const openSheetLink of htmlQueryAll(html,"[data-action=open-sheet]")){const actorUUID=htmlClosest(openSheetLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");openSheetLink.addEventListener("click",()=>actor?.sheet.render(!0))}for(const button of htmlQueryAll(html,"[data-action=builder]")){const tab=button.dataset.tab??null;button.addEventListener("click",()=>{new KingdomBuilder(this.kingdom).render(!0,{tab})})}const{fame}=this.kingdom.resources,famePips=htmlQuery(html,"[data-action=adjust-fame]");famePips?.addEventListener("click",async()=>{const newValue=Math.min(fame.value+1,fame.max);await this.kingdom.update({"resources.fame.value":newValue})}),famePips?.addEventListener("contextmenu",async event2=>{event2.preventDefault();const newValue=Math.max(fame.value-1,0);await this.kingdom.update({"resources.fame.value":newValue})});for(const leader of htmlQueryAll(html,".leader[data-role]")){const{role,uuid}=leader.dataset;if(htmlQuery(leader,"[data-action=remove-leader]")?.addEventListener("click",()=>{this.kingdom.update({[`leadership.${role}`]:null})}),uuid)for(const clickable of htmlQueryAll(leader,"[data-action=open-sheet]"))clickable.addEventListener("click",()=>fromUuid(uuid).then(a=>a?.sheet.render(!0)));const vacantEl=htmlQuery(leader,".vacant[title]");if(vacantEl){const lines=vacantEl.title.split(/;\s*/).map(l=>createHTMLElement("li",{children:[l]})),content=createHTMLElement("ul",{children:lines});$(vacantEl).tooltipster({content,contentAsHTML:!0,side:"right",theme:"crb-hover"})}}for(const rollableStat of htmlQueryAll(html,".rollable")){const statSlug=htmlClosest(rollableStat,"[data-statistic]")?.dataset.statistic;statSlug&&rollableStat.addEventListener("click",event2=>{this.actor.getStatistic(statSlug)?.roll(eventToRollParams(event2,{type:"check"}))})}htmlQuery(html,"[data-action=collect]")?.addEventListener("click",async()=>{ChatMessagePF2e.create({speaker:{...ChatMessagePF2e.getSpeaker(this.actor),alias:this.kingdom.name},content:await renderTemplate("systems/pf2e/templates/actors/party/kingdom/collection.hbs",{...calculateKingdomCollectionData(this.kingdom)})})}),this.filterActions(this.selectedFilter,{instant:!0}),htmlQuery(html,".filters")?.addEventListener("click",event2=>{const filterButton=htmlClosest(event2.target,".choice");filterButton&&this.filterActions(filterButton.dataset.slug??null)}),$html.find("[data-tooltip-content]").tooltipster({trigger:"click",arrow:!1,contentAsHTML:!0,debug:!1,interactive:!0,side:["right","bottom"],theme:"crb-hover",minWidth:120});for(const customModifierEl of htmlQueryAll(html,".modifiers-tooltip")){const stat=customModifierEl.dataset.stat;if(!stat)continue;for(const removeButton of htmlQueryAll(customModifierEl,"[data-action=remove-modifier]")){const slug=removeButton.dataset.slug??"";removeButton.addEventListener("click",()=>{this.kingdom.removeCustomModifier(stat,slug)})}const modifierValueEl=htmlQuery(customModifierEl,".add-modifier input[type=number]");htmlQuery(customModifierEl,"[data-action=increment]")?.addEventListener("click",()=>{modifierValueEl?.stepUp()}),htmlQuery(customModifierEl,"[data-action=decrement]")?.addEventListener("click",()=>{modifierValueEl?.stepDown()}),htmlQuery(customModifierEl,"[data-action=create-custom-modifier]")?.addEventListener("click",()=>{const modifier=modifierValueEl?.valueAsNumber||1,type=htmlQuery(customModifierEl,".add-modifier-type")?.value??"",label=htmlQuery(customModifierEl,".add-modifier-name")?.value?.trim()??game.i18n.localize(`PF2E.ModifierType.${type}`);if(!setHasElement(MODIFIER_TYPES,type)){ui.notifications.error("Type is required.");return}this.kingdom.addCustomModifier(stat,{label,modifier,type})})}htmlQuery(html,"[data-action=add-settlement]")?.addEventListener("click",()=>{const id=foundry.utils.randomID();this.#editingSettlements[id]=!0,this.focusElement=`[name="settlements.${id}.name"]`,this.kingdom.update({[`settlements.${id}`]:{}})});for(const settlementElement of htmlQueryAll(html,".settlement"))this.#activateSettlementEvents(settlementElement);for(const link of htmlQueryAll(html,"[data-action=browse-feats]")){const maxLevel=Number(link.dataset.level)||this.kingdom.level;link.addEventListener("click",async()=>{const compendiumTab=game.pf2e.compendiumBrowser.tabs.campaignFeature,filter2=await compendiumTab.getFilterData(),levels=filter2.sliders.level;levels.values.max=Math.min(maxLevel,levels.values.upperLimit),levels.isExpanded=levels.values.max!==levels.values.upperLimit,filter2.checkboxes.category.options["kingdom-feat"].selected=!0,filter2.checkboxes.category.selected.push("kingdom-feat"),filter2.checkboxes.category.isExpanded=!0,compendiumTab.open(filter2)})}htmlQuery(html,"[data-action=random-event]")?.addEventListener("click",()=>{new Statistic(this.actor,{slug:"random-event",label:"Random Kingdom Event",check:{type:"flat-check"}}).roll({dc:this.kingdom.event.dc})}),htmlQuery(html,"[data-action=reset-event-dc]")?.addEventListener("click",()=>{this.kingdom.update({event:{dc:16}})});const settlementList=htmlQuery(html,".settlement-list");settlementList&&Sortable.create(settlementList,{...SORTABLE_BASE_OPTIONS,handle:".drag-handle",onEnd:event2=>{const settlements=this.kingdom.settlements,settlementsWithIds=Object.entries(settlements).map(([id,value])=>({id,...value})),settlement=settlementsWithIds.find(s=>s.id===event2.item.dataset.settlementId),newIndex=event2.newDraggableIndex;if(!settlement||newIndex===void 0){this.render();return}const siblings=sortBy(settlementsWithIds.filter(s=>s!==settlement),s=>s.sort);siblings.splice(newIndex,0,settlement);const updates=mapToObj.indexed(siblings,(s,index)=>[`settlements.${s.id}.sort`,index]);this.kingdom.update(updates)}})}#activateSettlementEvents(settlementElement){const id=settlementElement.dataset.settlementId??null;if(id===null)return;const rerenderSettlement=__name2(async()=>{const settlement=this.kingdom.settlements[id];if(!settlement)return;const newHTML=await renderTemplate("systems/pf2e/templates/actors/party/kingdom/partials/settlement.hbs",{...await this.getData(),settlement:await this.#prepareSettlement(id,settlement)}),newElement=createHTMLElement("div",{innerHTML:newHTML}).firstElementChild;newElement instanceof HTMLElement&&(newElement.classList.toggle("expanded",settlementElement.classList.contains("expanded")),settlementElement.replaceWith(newElement),super.activateListeners($(newElement)),this.#activateSettlementEvents(newElement),this.#editingSettlements[id]&&!newElement.classList.contains("expanded")&&this.itemRenderer.toggleSummary(newElement,{visible:!0}))},"rerenderSettlement");htmlQuery(settlementElement,"[data-action=edit-settlement]")?.addEventListener("click",()=>{this.#editingSettlements[id]=!0,rerenderSettlement()}),htmlQuery(settlementElement,"[data-action=finish-settlement]")?.addEventListener("click",async()=>{this.#editingSettlements[id]=!1,await this.saveEditor(`settlements.${id}.description`),rerenderSettlement()}),htmlQuery(settlementElement,"[data-action=delete-settlement]")?.addEventListener("click",async event2=>{const settlement=this.kingdom.settlements[id];if(!settlement)return;(event2?.ctrlKey||await Dialog.confirm({title:game.i18n.localize("PF2E.DeleteItemTitle"),content:`${game.i18n.format("PF2E.DeleteQuestion",{name:`"${settlement.name}"`})}
`}))&&this.kingdom.update({[`settlements.-=${id}`]:null})})}filterActions(trait,options={}){const html=this.element.get(0),duration=.4;this.selectedFilter=trait;const animateElement=__name2((element,visible)=>{options.instant?element.hidden=!visible:visible&&element.hidden?gsap.fromTo(element,{height:0,opacity:0,hidden:!1},{height:"auto",opacity:1,duration}):!visible&&!element.hidden&&gsap.to(element,{height:0,duration,opacity:0,paddingTop:0,paddingBottom:0,margin:0,clearProps:"all",onComplete:()=>{element.hidden=!0,this.itemRenderer.toggleSummary(element,{visible:!1,instant:!0})}})},"animateElement");for(const action2 of this.kingdom.activities){const element=htmlQuery(html,`[data-item-id="${action2.id}"]`),visible=!trait||tupleHasValue(action2.system.traits.value,trait);element&&animateElement(element,visible)}for(const summary of htmlQueryAll(html,".phase-summary"))animateElement(summary,summary.dataset.phase===trait);for(const choice of htmlQueryAll(html,".filters .choice")){const active=choice.dataset.slug?choice.dataset.slug===trait:trait===null;choice.classList.toggle("active",active)}const actionsList=htmlQuery(html,".actions-list");actionsList&&(actionsList.scrollTop=0)}async _onDropItem(event2,data){const item=await ItemPF2e.fromDropData(data);if(!item)throw ErrorPF2e("Unable to create item from drop data!");if(this.actor.uuid===item.parent?.uuid)return super._onDropItem(event2,data);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const slotData=this.#getFeatSlotData(event2)??{groupId:"bonus",slotId:null};return(slotData.groupId==="bonus"?this.kingdom.bonusFeats:this.kingdom.feats).insertFeat(item,slotData.slotId)}return super._onDropItem(event2,data)}async _onSortItem(event2,itemSource){const item=this.actor.items.get(itemSource._id);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const featSlot=this.#getFeatSlotData(event2);if(!featSlot)return[];const group=featSlot.groupId==="bonus"?this.kingdom.bonusFeats:this.kingdom.feats,resorting=item.group===group&&!group?.slotted;if(group?.slotted&&!featSlot.slotId)return[];if(!resorting)return group.insertFeat(item,featSlot.slotId)}return super._onSortItem(event2,itemSource)}async _onDropActor(event2,data){await super._onDropActor(event2,data);const actor=fromUuidSync(data.uuid),closestLeader=htmlClosest(event2.target,".leader[data-role]");if(actor instanceof CreaturePF2e&&closestLeader){const role=String(closestLeader.dataset.role),uuid=actor.uuid;this.kingdom.update({leadership:{[role]:{uuid}}})}}#getFeatSlotData(event2){const groupId=event2.target?.closest("[data-group-id]")?.dataset.groupId,slotId=event2.target?.closest("[data-slot-id]")?.dataset.slotId;return typeof groupId=="string"?{slotId,groupId}:null}_disableFields(form){for(const gmOnlyField of htmlQueryAll(form,"input, textarea, [data-access=owner]"))gmOnlyField instanceof HTMLTextAreaElement?gmOnlyField.readOnly=!0:(gmOnlyField instanceof HTMLInputElement||gmOnlyField instanceof HTMLButtonElement)&&(gmOnlyField.disabled=!0)}async _updateObject(_event,formData){if(!this.actor.id)return;const data=foundry.utils.expandObject(formData);for(const abilitySlug of KINGDOM_ABILITIES){const ability=data.abilities?.[abilitySlug];ability?.penalty&&(ability.penalty=-Math.abs(ability.penalty))}return this.kingdom.update(data)}}const KINGDOM_BUILD_CATEGORIES=["charter","heartland","government"],KINGDOM_BOOST_LEVELS=[1,5,10,15,20];class KingdomBuilder extends FormApplication{static{__name(this,"KingdomBuilder")}static{__name2(this,"KingdomBuilder")}selected={charter:null,heartland:null,government:null};static get defaultOptions(){return{...super.defaultOptions,classes:["sheet","kingdom-builder"],title:game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.Title"),template:"systems/pf2e/templates/actors/party/kingdom/builder.hbs",width:560,height:"auto",submitOnChange:!0,closeOnSubmit:!1,tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}static showToPlayers(options){const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:options.uuid,options:{campaign:"builder",tab:options.tab}})}constructor(kingdom){super(kingdom),kingdom.actor.apps[this.appId]=this}get id(){return`kingdom-builder-${this.actor.id}`}get kingdom(){return this.object}get actor(){return this.object.actor}get isEditable(){return this.actor.isOwner}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&(buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fa-solid fa-eye",onclick:()=>{KingdomBuilder.showToPlayers({uuid:this.actor.uuid,tab:this._tabs[0].active})}}),this.kingdom.active==="building"&&buttons.unshift({label:"PF2E.Kingmaker.KingdomBuilder.CancelCreation",class:"cancel",icon:"fa-solid fa-times",onclick:async()=>{await this.kingdom.update({active:!1})}})),buttons}async getData(){const database=getKingdomCHGData(),getActiveForCategory=__name2(category=>{const active=this.kingdom.build[category];return active?active?.id??Object.entries(database[category]).find(([_,entry])=>entry?.name===active.name)?.[0]??null:null},"getActiveForCategory");for(const category of KINGDOM_BUILD_CATEGORIES)this.selected[category]??=getActiveForCategory(category);const categories=await pipe(KINGDOM_BUILD_CATEGORIES,map(async category=>{const selected=this.selected[category],entries=database[category],buildEntry=entries[selected??""]??Object.values(entries)[0],featItem=await(async()=>{try{return buildEntry?.feat?await fromUuid(buildEntry.feat):null}catch(ex){return console.error(ex),null}})(),result={selected,active:getActiveForCategory(category),buildEntry,featLink:featItem?await TextEditor.enrichHTML(featItem.link,{async:!0}):null,stale:!equals(buildEntry,this.kingdom.build[category])};return[category,result]}),items=>Promise.all(items).then(result=>fromPairs(result))),{build}=this.kingdom,finished=!!(build.charter&&build.heartland&&build.government);return{options:{editable:this.isEditable},kingdom:this.kingdom,database,categories,abilityLabels:KINGDOM_ABILITY_LABELS,skillLabels:KINGDOM_SKILL_LABELS,build:this.#prepareAbilityBuilder(),finished}}#prepareAbilityBuilder(){function createButtons(){return Array.from(KINGDOM_ABILITIES).reduce((accumulated,ability)=>(accumulated[ability]={ability},accumulated),{})}__name(createButtons,"createButtons"),__name2(createButtons,"createButtons");const choices=this.kingdom.build.boosts,mainBoosts=mapToObj(KINGDOM_BUILD_CATEGORIES,prop=>{const buildItem=this.kingdom[prop];if(!buildItem)return[prop,null];const buttons=createButtons(),selectedChoices=objectHasKey(choices,prop)?choices[prop]:[],boosts=resolveKingdomBoosts(buildItem,selectedChoices),remaining=Math.max(0,buildItem.boosts.length-boosts.length);for(const ability of KINGDOM_ABILITIES){const selected=boosts.includes(ability);ability===buildItem.flaw?buttons[ability].flaw={selected:!0,locked:!0}:(selected||buildItem.boosts.includes("free"))&&(buttons[ability].boost={selected,locked:buildItem.boosts.includes(ability),disabled:!selected&&!remaining})}return[prop,{buttons,remaining}]}),levelBoosts=mapToObj(KINGDOM_BOOST_LEVELS,level=>{const eligible=this.kingdom.level>=level,buttons=createButtons(),boosts=this.kingdom.build.boosts[level],remaining=eligible?Math.max(0,2-boosts.length):0;for(const ability of KINGDOM_ABILITIES){const selected=boosts.includes(ability)&&eligible;buttons[ability].boost={selected,disabled:!selected&&!remaining}}return[level,{buttons,remaining,eligible}]});return{...mainBoosts,levelBoosts}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const categoryEl of htmlQueryAll(html,"[data-category]")){const category=categoryEl.dataset.category??null;if(!tupleHasValue(KINGDOM_BUILD_CATEGORIES,category))continue;for(const choiceElement of htmlQueryAll(categoryEl,".choice"))choiceElement.addEventListener("click",evt=>{const slug=htmlClosest(evt.target,"[data-slug]")?.dataset.slug;category&&objectHasKey(this.selected,category)&&(this.selected[category]=slug??null,this.render())});const saveCategory=__name2(async()=>{const database=getKingdomCHGData(),id=this.selected[category]??"",selected=database[category][id];selected&&(this.selected[category]=null,await this.kingdom.update({[`build.${category}`]:{id,...selected},[`build.boosts.${category}`]:[]}))},"saveCategory");htmlQuery(categoryEl,"[data-action=set]")?.addEventListener("click",()=>{saveCategory()}),htmlQuery(categoryEl,"[data-action=save-and-continue]")?.addEventListener("click",async event2=>{event2.preventDefault(),event2.stopPropagation(),await saveCategory();const activeTab=this._tabs[0].active,idx=KINGDOM_BUILD_CATEGORIES.indexOf(activeTab),newTab=KINGDOM_BUILD_CATEGORIES[idx+1]??"ability";this._tabs[0].activate(newTab,{triggerCallback:!0})})}for(const button of htmlQueryAll(html,".ability-builder [data-section] .boost")){const sectionId=htmlClosest(button,"[data-section]")?.dataset.section,ability=htmlClosest(button,"[data-ability]")?.dataset.ability;!tupleHasValue(KINGDOM_ABILITIES,ability)||!tupleHasValue(KINGDOM_BUILD_CATEGORIES,sectionId)||button.addEventListener("click",()=>{const object=this.kingdom[sectionId],current=this.kingdom.build.boosts[sectionId],maxBoosts=object?.boosts.length;if(!object)return;const boosts=(current.includes(ability)?current.filter(a=>a!==ability):[...current,ability]).filter(a=>!object.boosts.includes(a)&&object.flaw!==a).slice(0,maxBoosts);this.kingdom.update({[`build.boosts.${sectionId}`]:boosts})})}for(const button of htmlQueryAll(html,".ability-builder [data-level] .boost")){const level=Number(htmlClosest(button,"[data-level]")?.dataset.level),ability=htmlClosest(button,"[data-ability]")?.dataset.ability;!tupleHasValue(KINGDOM_ABILITIES,ability)||!tupleHasValue(KINGDOM_BOOST_LEVELS,level)||button.addEventListener("click",()=>{const current=this.kingdom.build.boosts[level],boosts=(current.includes(ability)?current.filter(a=>a!==ability):[...current,ability]).slice(0,2);this.kingdom.update({[`build.boosts.${level}`]:boosts})})}htmlQuery(html,"[data-action=complete]")?.addEventListener("click",async()=>{this.close(),await this.kingdom.update({active:!0}),await this.kingdom.importActivities(),new KingdomSheetPF2e(this.actor).render(!0)})}async _updateObject(_event,formData){if(this.actor.id)return this.object.update(formData)}async _render(force,options){if(this.kingdom.active===!1){this.close({force:!0});return}await super._render(force,options),options?.tab&&this._tabs.at(0)?.activate(options.tab,{triggerCallback:!0})}}const{fields}=foundry.data;function buildKingdomCHGSchema(){return{id:new fields.StringField({required:!1,initial:void 0,blank:!1}),name:new fields.StringField({required:!0,nullable:!1,blank:!1}),img:new fields.StringField({required:!0,nullable:!1}),description:new fields.StringField({required:!0,nullable:!1}),boosts:new fields.ArrayField(new fields.StringField({choices:[...KINGDOM_ABILITIES,"free"],nullable:!1}))}}__name(buildKingdomCHGSchema,"buildKingdomCHGSchema"),__name2(buildKingdomCHGSchema,"buildKingdomCHGSchema");const KINGDOM_BUILD_SCHEMA={manual:new fields.BooleanField({required:!0,nullable:!1,initial:!1}),charter:new fields.SchemaField({...buildKingdomCHGSchema(),flaw:new fields.StringField({choices:KINGDOM_ABILITIES,required:!0,nullable:!0})},{nullable:!0,initial:null}),heartland:new fields.SchemaField(buildKingdomCHGSchema(),{nullable:!0,initial:null}),government:new fields.SchemaField({...buildKingdomCHGSchema(),skills:new fields.ArrayField(new fields.StringField({required:!0,nullable:!1,choices:KINGDOM_SKILLS})),feat:new fields.StringField({required:!0,nullable:!0})},{nullable:!0,initial:null}),skills:new fields.SchemaField(mapToObj(KINGDOM_SKILLS,skill=>{const schema=new fields.SchemaField({rank:new fields.NumberField({initial:0,min:0,max:4,required:!0,nullable:!1})});return[skill,schema]})),boosts:new fields.SchemaField(mapToObj(["charter","heartland","government","1","5","10","15","20"],category=>{const schema=new fields.ArrayField(new fields.StringField({choices:KINGDOM_ABILITIES,nullable:!1}));return[category,schema]}))},KINGDOM_RESOURCES_SCHEMA={dice:new fields.SchemaField({number:new fields.NumberField,faces:new fields.NumberField,bonus:new fields.NumberField({required:!0,nullable:!1,initial:0}),penalty:new fields.NumberField({required:!0,nullable:!1,initial:0})}),fame:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:3})}),commodities:new fields.SchemaField(mapToObj(KINGDOM_COMMODITIES,type=>{const schema=new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:0})});return[type,schema]})),points:new fields.NumberField({min:0,required:!1,nullable:!1,initial:0}),workSites:new fields.SchemaField(mapToObj(["food","luxuries","lumber","ore","stone"],type=>{const schema=new fields.SchemaField({value:new fields.NumberField({required:!1,nullable:!1,min:0,initial:0}),resource:new fields.NumberField({required:!1,nullable:!1,min:0,initial:0})});return[type,schema]}))},KINGDOM_SETTLEMENT_SCHEMA={name:new fields.StringField({required:!0,blank:!0,nullable:!1,initial:""}),type:new fields.StringField({required:!1,nullable:!1,choices:KINGDOM_SETTLEMENT_TYPES,initial:"village"}),level:new fields.NumberField({min:1,initial:1,max:30,nullable:!1}),overcrowded:new fields.BooleanField,description:new fields.StringField({required:!1,nullable:!1,blank:!0,initial:""}),sort:new fields.IntegerSortField,consumption:new fields.SchemaField({base:new fields.NumberField({required:!1,nullable:!1,initial:0}),reduction:new fields.NumberField({required:!1,nullable:!1,initial:0}),total:new fields.NumberField({required:!1,nullable:!1,initial:0})}),storage:new fields.SchemaField(mapToObj(["food","luxuries","lumber","ore","stone"],type=>{const schema=new fields.NumberField({required:!1,nullable:!1,min:0,initial:0});return[type,schema]}))},KINGDOM_SCHEMA={type:new fields.StringField({choices:["kingmaker"],required:!0,nullable:!1,initial:"kingmaker"}),active:new DataUnionField([new StrictStringField({required:!1,nullable:!1,choices:["building"],initial:void 0}),new StrictBooleanField({initial:!1,required:!1,nullable:!1})],{required:!1,nullable:!1,initial:!1}),name:new fields.StringField({required:!0,nullable:!1,initial:""}),img:new fields.FilePathField({categories:["IMAGE"],required:!0,nullable:!1,initial:"systems/pf2e/icons/default-icons/kingdom.svg"}),capital:new fields.StringField({initial:"",required:!0}),size:new fields.NumberField({initial:1,min:1,required:!0,nullable:!1}),level:new fields.NumberField({required:!0,nullable:!1,min:1,max:20,initial:1}),xp:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:1e3})}),aspiration:new fields.StringField({choices:["fame","infamy"],required:!0,nullable:!1,initial:"fame"}),abilities:new fields.SchemaField(mapToObj(KINGDOM_ABILITIES,ability=>{const schema=new fields.SchemaField({value:new fields.NumberField({initial:10,required:!1,nullable:!1}),mod:new fields.NumberField({initial:0,required:!1,nullable:!1}),ruin:new fields.SchemaField({value:new fields.NumberField({required:!0,nullable:!1,initial:0}),max:new fields.NumberField({required:!0,nullable:!1,initial:10})}),penalty:new fields.NumberField({initial:0,required:!1,nullable:!1})});return[ability,schema]})),build:new fields.SchemaField(KINGDOM_BUILD_SCHEMA),customModifiers:new fields.ObjectField({initial:{}}),leadership:new fields.SchemaField(mapToObj(KINGDOM_LEADERSHIP,role=>{const schema=new fields.SchemaField({uuid:new fields.StringField({required:!1,nullable:!0,initial:null}),vacant:new fields.BooleanField({initial:!0}),invested:new fields.BooleanField({required:!1,initial:!1})});return[role,schema]})),resources:new fields.SchemaField(KINGDOM_RESOURCES_SCHEMA),settlements:new RecordField(new fields.StringField({required:!0,nullable:!1,blank:!1}),new fields.SchemaField(KINGDOM_SETTLEMENT_SCHEMA,{required:!0}),{required:!1,nullable:!1,initial:{}}),consumption:new fields.SchemaField({base:new fields.NumberField({required:!1,nullable:!1,initial:0}),settlement:new fields.NumberField({min:0,initial:0}),army:new fields.NumberField({min:0,initial:0}),value:new fields.NumberField({min:0,initial:0})}),unrest:new fields.SchemaField({value:new fields.NumberField({integer:!0,min:0,max:99,required:!1,nullable:!1,initial:0}),anarchyThreshold:new fields.NumberField({integer:!0,required:!1,nullable:!1,initial:20})}),event:new fields.SchemaField({dc:new fields.NumberField({required:!1,nullable:!1,min:0,max:20,initial:16}),text:new fields.StringField({required:!1,nullable:!1,blank:!0,initial:""})}),module:new fields.ObjectField({required:!1,initial:{}})},{DataModel:DataModel$1}=foundry.abstract;class Kingdom extends DataModel$1{static{__name(this,"Kingdom")}static{__name2(this,"Kingdom")}static defineSchema(){return KINGDOM_SCHEMA}get actor(){return this.parent}get extraItemTypes(){return["campaignFeature","effect"]}get activities(){return this.actor.itemTypes.campaignFeature.filter(k=>k.category==="kingdom-activity")}get charter(){return this.build.charter}get heartland(){return this.build.heartland}get government(){return this.build.government}createSidebarButtons(){if(!this.active&&!game.user.isGM)return[];const hoverIcon=this.active==="building"?"wrench":this.active?null:"plus",icon=createHTMLElement("a",{classes:["create-button"],children:compact([fontAwesomeIcon("crown"),hoverIcon?fontAwesomeIcon(hoverIcon):null]),dataset:{tooltip:game.i18n.localize(`PF2E.Kingmaker.SIDEBAR.${this.active===!0?"OpenSheet":"CreateKingdom"}`)}});return icon.addEventListener("click",async event2=>{if(event2.stopPropagation(),!this.active)await Dialog.confirm({title:game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.Title"),content:`${game.i18n.localize("PF2E.Kingmaker.KingdomBuilder.ActivationMessage")}
`})&&(await this.update({active:"building"}),KingdomBuilder.showToPlayers({uuid:this.actor.uuid}),new KingdomBuilder(this).render(!0));else{const type=this.active===!0?null:"builder";this.renderSheet({type})}}),[icon]}async collect(){const{formula,commodities}=calculateKingdomCollectionData(this),roll=await new Roll(formula).evaluate({async:!0});await roll.toMessage({flavor:game.i18n.localize("PF2E.Kingmaker.Kingdom.Resources.Points"),speaker:{...ChatMessagePF2e.getSpeaker(this.actor),alias:this.name}},{rollMode:"publicroll"}),this.update({resources:{points:roll.total,commodities:mapValues$1(commodities,(incoming,type)=>{const current=this.resources.commodities[type];return{value:Math.min(current.value+incoming,current.max)}})}})}async addCustomModifier(stat,data){if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");if(data.label.length===0)throw ErrorPF2e("A custom modifier's label must be a non-empty string");const modifiers=(this.toObject().customModifiers??{})[stat]??[];if(!modifiers.some(m=>m.label===data.label)){data.type=setHasElement(MODIFIER_TYPES,data.type)?data.type:"untyped";const modifier=new ModifierPF2e({...data,custom:!0}).toObject();await this.update({[`customModifiers.${stat}`]:[...modifiers,modifier]})}}async removeCustomModifier(stat,slug){if(stat.length===0)throw ErrorPF2e("A custom modifier's statistic must be a non-empty string");const modifiers=(this.toObject().customModifiers??{})[stat]??[];if(modifiers.length!==0)if(typeof slug=="string"){const withRemoved=modifiers.filter(m=>m.slug!==slug);await this.update({[`customModifiers.${stat}`]:withRemoved})}else throw ErrorPF2e("Custom modifiers can only be removed by slug (string) or index (number)")}async update(data){const expanded=foundry.utils.expandObject(data),updateData=foundry.utils.mergeObject(expanded,expanded.system?.campaign??{});delete updateData.system,await this.actor.update({"system.campaign":updateData}),updateData.level&&await this.updateFeatures(updateData.level)}prepareBaseData(){const{synthetics}=this.actor,{build}=this;if(!build.manual){for(const ability of KINGDOM_ABILITIES)this.abilities[ability].value=10;for(const category of["charter","heartland","government"]){const data=build[category],chosen=build.boosts[category];if(!data)continue;"flaw"in data&&data.flaw&&(this.abilities[data.flaw].value-=2);const activeBoosts=resolveKingdomBoosts(data,chosen);for(const ability of activeBoosts)this.abilities[ability].value+=this.abilities[ability].value>=18?1:2}const activeLevels=[1,5,10,15,20].filter(l=>this.level>=l);for(const level of activeLevels){const chosen=build.boosts[level].slice(0,2);for(const ability of chosen)this.abilities[ability].value+=this.abilities[ability].value>=18?1:2}}for(const ability of KINGDOM_ABILITIES)this.abilities[ability].mod=(this.abilities[ability].value-10)/2;if(build.government&&build.government.skills.length>0)for(const skill of build.government.skills)build.skills[skill].rank=Math.max(1,build.skills[skill].rank);const customModifiers=this.customModifiers??={};for(const selector of Object.keys(customModifiers)){const modifiers=customModifiers[selector]=customModifiers[selector].map(rawModifier=>new ModifierPF2e(rawModifier));(synthetics.modifiers[selector]??=[]).push(...modifiers.map(m=>()=>m))}const sizeData=Object.entries(KINGDOM_SIZE_DATA).findLast(([size])=>this.size>=Number(size))?.[1]??KINGDOM_SIZE_DATA[1];this.nationType=sizeData.type,this.resources.dice.faces=sizeData.faces,sizeData.controlMod&&(synthetics.modifiers["control-dc"]??=[]).push(()=>new ModifierPF2e({slug:"size",label:"Size Modifier",modifier:sizeData.controlMod}));for(const ability of KINGDOM_ABILITIES){const penalty=this.abilities[ability].penalty;penalty&&(synthetics.modifiers[`${ability}-based`]??=[]).push(()=>new ModifierPF2e({slug:"ruin",type:"item",label:KINGDOM_RUIN_LABELS[ability],modifier:penalty}))}for(const role of KINGDOM_LEADERSHIP){const data=this.leadership[role],actor=fromUuidSync(data.uuid??"");if(actor instanceof ActorPF2e?actor.hasPlayerOwner||(data.vacant=!1):data.vacant=!0,data.vacant){const penalties=VACANCY_PENALTIES[role]();for(const[selector,entries]of Object.entries(penalties.adjustments??{}))(synthetics.modifierAdjustments[selector]??=[]).push(...entries);for(const[selector,entries]of Object.entries(penalties.modifiers??{}))(synthetics.modifiers[selector]??=[]).push(...entries.map(e=>()=>new ModifierPF2e(e)))}if(data.invested){const ability=KINGDOM_LEADERSHIP_ABILITIES[role];(synthetics.modifiers[`${ability}-skill-check`]??=[]).push(()=>new ModifierPF2e({slug:"invested",label:"PF2E.Kingmaker.Kingdom.Invested",type:"status",modifier:1}))}}if(this.unrest.value>0){const modifier=-([1,5,10,15].findLastIndex(t=>this.unrest.value>=t)+1);(synthetics.modifiers["kingdom-check"]??=[]).push(()=>new ModifierPF2e({slug:"unrest",label:"PF2E.Kingmaker.Kingdom.Unrest",type:"status",modifier}))}const settlements=compact(Object.values(this.settlements));for(const settlement of settlements){if(!settlement)continue;const typeData=KINGDOM_SETTLEMENT_TYPE_DATA[settlement.type];settlement.consumption.base=typeData.consumption,settlement.consumption.total=Math.max(0,typeData.consumption-settlement.consumption.reduction)}for(const[type,value]of Object.entries(this.resources.commodities)){const settlementStorage=sumBy(settlements,s=>s.storage[type]);value.max=sizeData.storage+settlementStorage}}prepareDerivedData(){const{synthetics}=this.actor,{consumption,resources}=this;resources.dice.number=Math.max(0,this.level+4+resources.dice.bonus-resources.dice.penalty);const settlements=compact(Object.values(this.settlements));consumption.settlement=sumBy(settlements,s=>s.consumption.total);const computedConsumption=consumption.base+consumption.settlement+consumption.army-this.resources.workSites.food.value;consumption.value=Math.max(0,computedConsumption);const controlMod=CONTROL_DC_BY_LEVEL[Math.clamped(this.level-1,0,19)]-10;this.control=new Statistic(this.actor,{slug:"control",label:"PF2E.Kingmaker.Kingdom.ControlDC",domains:["control-dc"],modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:controlMod})]}),this.skills=mapToObj(KINGDOM_SKILLS,skill=>{const ability=KINGDOM_SKILL_ABILITIES[skill],abilityMod=this.abilities[ability].mod,rank=this.build.skills[skill].rank,domains=["kingdom-check",`${ability}-based`,`${ability}-skill-check`,skill],statistic=new Statistic(this.actor,{slug:skill,rank,label:KINGDOM_SKILL_LABELS[skill],domains,modifiers:[new ModifierPF2e({slug:ability,label:KINGDOM_ABILITY_LABELS[ability],modifier:abilityMod,type:"ability",adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,domains,ability)}),createProficiencyModifier({actor:this.actor,rank,domains,level:this.level})],check:{type:"skill-check"}});return[skill,statistic]});const evenLevels=new Array(this.level).fill(0).map((_,idx)=>idx+1).filter(idx=>idx%2===0);this.features=new FeatGroup(this.actor,{id:"features",label:"Kingdom Features",level:this.level}),this.feats=new FeatGroup(this.actor,{id:"kingdom",label:"Kingdom Feats",slots:[{id:"government",label:"G"},...evenLevels],featFilter:["traits-kingdom"],level:this.level}),this.bonusFeats=new FeatGroup(this.actor,{id:"bonus",label:"PF2E.FeatBonusHeader",featFilter:["traits-kingdom"],level:this.level});const allFeatures=this.actor.itemTypes.campaignFeature,features=sortBy(allFeatures.filter(f=>f.isFeature),f=>f.level??1,f=>f.name),feats=sortBy(allFeatures.filter(f=>f.isFeat),f=>f.sort);for(const feature of features)this.features.assignFeat(feature);for(const feat of feats)this.feats.assignFeat(feat)||this.bonusFeats.assignFeat(feat)}getRollOptions(){const prefix="kingdom";return compact([this.unrest.value?`${prefix}:unrest:${this.unrest.value}`:null])}getRollData(){return{kingdom:this}}async importActivities({skipDialog=!1}={}){const pack=game.packs.get("pf2e.kingmaker-features");if(!pack)throw ErrorPF2e("Could not load kingdom features compendium");await this.updateFeatures(this.level);const documents=(await pack.getDocuments({type:"campaignFeature"})).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature")).filter(d=>d.system.category==="kingdom-activity");await importDocuments(this.actor,documents,skipDialog)}async updateFeatures(level){const featuresToDelete=this.actor.itemTypes.campaignFeature.filter(f=>f.isFeature).filter(f=>(f.level??0)>level).map(f=>f.id),featuresToAdd=await(async()=>{const pack=game.packs.get("pf2e.kingmaker-features");return pack?(await pack.getDocuments({type:"campaignFeature"})).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature")).filter(d=>d.system.category==="kingdom-feature").filter(d=>level>=(d.level??0)).filter(d=>!this.actor.items.some(i=>i.sourceId===d.uuid)).map(i=>i.toObject()):(console.error("PF2E System | Could not load kingdom features compendium"),[])})();await this.actor.deleteEmbeddedDocuments("Item",featuresToDelete),await this.actor.createEmbeddedDocuments("Item",featuresToAdd)}getStatistic(slug){return this.skills&&objectHasKey(this.skills,slug)?this.skills[slug]??null:null}renderSheet(options={}){options.type==="builder"?new KingdomBuilder(this).render(!0):new KingdomSheetPF2e(this.actor).render(!0,{tab:options.tab})}_preUpdate(changed){const actor=this.actor,feat=changed.build?.government?.feat;feat&&(console.log("Replacing feat"),fromUuid(feat).then(async f=>{if(!(f instanceof CampaignFeaturePF2e))return;const currentGovernmentFeat=actor.itemTypes.campaignFeature.find(f2=>f2.system.location==="government"),newFeat=f.clone({"system.location":"government"});await currentGovernmentFeat?.delete(),await actor.createEmbeddedDocuments("Item",[newFeat.toObject()])}))}}const BASIC_WAR_ACTIONS_FOLDER="Vqp8b64uH35zkncy",ALIGNMENTS=new Set(["LG","NG","CG","LN","N","CN","LE","NE","CE"]),ARMY_TYPES=["infantry","cavalry","siege","skirmisher"],ARMY_STATS={scouting:[0,7,8,9,11,12,14,15,16,18,19,21,22,23,25,26,28,29,30,32,33],standardDC:[0,15,16,18,19,20,22,23,24,26,27,28,30,31,32,34,35,36,38,39,40],ac:[0,16,18,19,21,22,24,25,27,28,30,31,33,34,36,37,39,40,42,43,45],strongSave:[0,10,11,12,14,15,17,18,19,21,22,24,25,26,28,29,30,32,33,35,36],weakSave:[0,4,5,6,8,9,11,12,13,15,16,18,19,20,22,23,25,26,27,29,30],attack:[0,9,11,12,14,15,17,18,20,21,23,24,26,27,29,30,32,33,35,36,38],maxTactics:[0,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6]};function getArmyGearData(){return{...mapToObj(["melee","ranged"],type=>[`additional-${type}`,{img:type==="melee"?"icons/weapons/axes/axe-battle-black.webp":"icons/weapons/crossbows/crossbow-simple-brown.webp",name:game.i18n.format("PF2E.Kingmaker.Army.Gear.AdditionalWeapon.Name",{type:game.i18n.format(`PF2E.Kingmaker.Army.Strikes.${type}`)}),description:"PF2E.Kingmaker.Army.Gear.AdditionalWeapon.Description",traits:["army"],level:1,price:10}]),...mapToObj(["melee","ranged"],type=>[type,{img:type==="melee"?"icons/weapons/axes/axe-battle-black.webp":"icons/weapons/crossbows/crossbow-simple-brown.webp",name:game.i18n.format("PF2E.Kingmaker.Army.Gear.MagicWeapons.Name",{type:game.i18n.format(`PF2E.Kingmaker.Army.Strikes.${type}`)}),description:"PF2E.Kingmaker.Army.Gear.MagicWeapons.Description",traits:["army","magical"],ranks:[{price:20,level:2},{price:40,level:10},{price:60,level:16}].map((d,idx)=>({...d,name:`PF2E.Kingmaker.Army.Gear.MagicWeapons.rank${idx+1}.Name`,description:`PF2E.Kingmaker.Army.Gear.MagicWeapons.rank${idx+1}.Description`}))}]),potions:{img:"icons/consumables/potions/bottle-round-corked-orante-red.webp",name:"PF2E.Kingmaker.Army.Gear.Potions.Name",description:"PF2E.Kingmaker.Army.Gear.Potions.Description",traits:["army","consumable","healing","magical","potion"],level:1,price:15},armor:{img:"icons/equipment/shield/heater-wooden-brown-axe.webp",name:game.i18n.localize("PF2E.Kingmaker.Army.Gear.Armor.Name"),description:game.i18n.localize("PF2E.Kingmaker.Army.Gear.Armor.Description"),traits:["army","magical"],ranks:[{price:25,level:5},{price:50,level:11},{price:75,level:18}].map((d,idx)=>({...d,name:`PF2E.Kingmaker.Army.Gear.Armor.rank${idx+1}.Name`,description:`PF2E.Kingmaker.Army.Gear.Armor.rank${idx+1}.Description`}))}}}__name(getArmyGearData,"getArmyGearData"),__name2(getArmyGearData,"getArmyGearData");class ArmyPF2e extends ActorPF2e{static{__name(this,"ArmyPF2e")}static{__name2(this,"ArmyPF2e")}get allowedItemTypes(){return["campaignFeature","effect"]}get underRoutThreshold(){return this.hitPoints.value<=this.system.attributes.hp.routThreshold}get kingdom(){if(this.alliance==="party"){const campaign=game.actors.party?.campaign;return campaign instanceof Kingdom?campaign:null}return null}get maxTactics(){return ARMY_STATS.maxTactics[this.level]}prepareBaseData(){super.prepareBaseData(),this.system.ac.value??=this._source.system.ac.value??=ARMY_STATS.ac[this.level],this.system.scouting??=this._source.system.scouting??=ARMY_STATS.scouting[this.level],this.system.details.level.value=Math.clamped(this.system.details.level.value,1,20),this.system.resources.potions.max=3,this.system.saves.strongSave=this.system.saves.maneuver>=this.system.saves.morale?"maneuver":"morale",this.system.traits.senses=[],this.system.details.alliance=this.hasPlayerOwner?"party":"opposition",this.rollOptions.all[`self:trait:${this.system.traits.type}`]=!0,this.rollOptions.all["self:under-rout-threshold"]=this.underRoutThreshold}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){super.prepareDerivedData(),this.prepareSynthetics(),this.system.consumption=Math.max(0,this.system.consumption),this.itemTypes.campaignFeature.some(f=>f.slug==="darkvision")?this.system.traits.senses.push(new CreatureSensePF2e({type:"darkvision"})):this.itemTypes.campaignFeature.some(f=>f.slug==="low-light-vision")&&this.system.traits.senses.push(new CreatureSensePF2e({type:"lowLightVision"})),this.tactics=new FeatGroup(this,{id:"tactics",label:"PF2E.Kingmaker.Army.Tactics",slots:range(0,this.maxTactics).map(idx=>({id:String(idx),label:""}))}),this.bonusTactics=new FeatGroup(this,{id:"bonus",label:"PF2E.Kingmaker.Army.TacticsFree"});const expectedAC=ARMY_STATS.ac[this.level],acAdjustment=this.system.ac.value-expectedAC;this.armorClass=new ArmorStatistic(this,{modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:expectedAC-10}),acAdjustment&&new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:acAdjustment}),this.system.ac.potency&&new ModifierPF2e({slug:"potency",label:"Potency",modifier:this.system.ac.potency})])}).dc,this.system.ac.value=this.armorClass.value;const baseScouting=ARMY_STATS.scouting[this.level],scoutAdjustment=this.system.scouting-baseScouting;this.scouting=new Statistic(this,{slug:"scouting",label:"PF2E.Kingmaker.Army.Scouting",domains:["scouting"],modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:baseScouting}),scoutAdjustment?new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:scoutAdjustment}):null])}),this.system.scouting=this.scouting.mod;for(const saveType of["maneuver","morale"]){const baseValue=(this.system.saves.strongSave===saveType?ARMY_STATS.strongSave:ARMY_STATS.weakSave)[this.level],adjustment=this.system.saves[saveType]-baseValue;this[saveType]=new Statistic(this,{slug:saveType,label:`PF2E.Kingmaker.Army.Save.${saveType}`,domains:["saving-throw",saveType],modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:baseValue}),adjustment?new ModifierPF2e({slug:"adjustment",label:"PF2E.Kingmaker.Army.Adjustment",modifier:adjustment}):null])})}this.initiative=new ActorInitiative(this,{statistic:"scouting"}),this.strikes=flatMapToObj(["melee","ranged"],t=>this.system.weapons[t]?[[t,this.prepareArmyStrike(t)]]:[]);for(const tactic of this.itemTypes.campaignFeature.filter(i=>i.category==="army-tactic"))this.tactics.assignFeat(tactic)||this.bonusTactics.assignFeat(tactic)}async usePotion(){const newPotions=Math.max(0,this.system.resources.potions.value-1),newHP=Math.min(this.attributes.hp.value+1,this.attributes.hp.max);await this.update({"system.attributes.hp.value":newHP,"system.resources.potions.value":newPotions}),await ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({actor:this,token:this.token}),flavor:createHTMLElement("div",{children:[createHTMLElement("strong",{children:[game.i18n.localize("PF2E.Kingmaker.Army.Potions.UsedPotionHeader")]}),document.createElement("hr")]}).outerHTML,content:createHTMLElement("p",{children:[game.i18n.localize("PF2E.Kingmaker.Army.Potions.UsedPotionContent")]}).outerHTML,type:CONST.CHAT_MESSAGE_TYPES.EMOTE})}prepareArmyStrike(type){const synthetics=this.synthetics,data=this.system.weapons[type];if(data===null)return null;const attackDomains=["attack","attack-roll",`${type}-attack-roll`],maps=(()=>{const baseMap={slug:"multiple-attack-penalty",label:"PF2E.MultipleAttackPenalty",map1:-5,map2:-10},optionSet=new Set(this.getRollOptions(attackDomains)),maps2=this.synthetics.multipleAttackPenalties??{},fromSynthetics=attackDomains.flatMap(d=>maps2[d]??[]).filter(p=>p.predicate?.test(optionSet)??!0).map(p=>({slug:baseMap.slug,label:p.label,map1:p.penalty,map2:p.penalty*2}));return[baseMap,...fromSynthetics].reduce((lowest,p)=>p.map1>lowest.map1?p:lowest)})(),createMapModifier=__name2(prop=>new ModifierPF2e({slug:maps.slug,label:maps.label,modifier:maps[prop],adjustments:extractModifierAdjustments(synthetics.modifierAdjustments,attackDomains,maps.slug)}),"createMapModifier"),statistic=new Statistic(this,{slug:`${type}-strike`,label:data.name,domains:attackDomains,rollOptions:[`item:${type}`],check:{type:"attack-roll"},modifiers:compact([new ModifierPF2e({slug:"base",label:"PF2E.Kingmaker.Army.Base",modifier:ARMY_STATS.attack[this.level]}),data.potency&&new ModifierPF2e({slug:"potency",label:"Potency",modifier:data.potency}),new ModifierPF2e({slug:"concealed",label:"PF2E.Kingmaker.Army.Condition.concealed.name",type:"circumstance",modifier:-2,predicate:["target:effect:concealed"],hideIfDisabled:!0})])}),dealDamage=__name2(async(params={},outcome="success")=>{const targetToken=params.target??game.user.targets.first()??null,domains=["damage","strike-damage",`${type}-damage`],context=await this.getDamageRollContext({viewOnly:params.getFormula??!1,statistic:statistic.check,target:{token:targetToken},domains,outcome,checkContext:params.checkContext,options:new Set}),damageContext={type:"damage-roll",sourceType:"attack",self:context.self,target:context.target,outcome,options:context.options,domains,...eventToRollParams(params.event,{type:"damage"})},{formula,breakdown}=createDamageFormula({base:[{modifier:outcome==="success"?1:2,damageType:"untyped",category:null}],modifiers:extractModifiers(context.self.actor.synthetics,domains,{test:context.options}),dice:extractDamageDice(context.self.actor.synthetics.damageDice,domains,{test:context.options,resolvables:{target:context.target?.actor??null}}),ignoredResistances:[]}),template={name:"Army damage",materials:[],modifiers:[],damage:{roll:new DamageRoll(formula),breakdown}};return DamagePF2e.roll(template,damageContext)},"dealDamage");return{slug:`${type}-strike`,label:data.name,type:"strike",glyph:"A",variants:[0,1,2].map(idx=>{const mapModifier=idx===0?null:createMapModifier(`map${idx}`),penalty=mapModifier?.modifier??0;return{label:idx===0?signedInteger(statistic.mod):game.i18n.format("PF2E.MAPAbbreviationValueLabel",{value:signedInteger(statistic.mod+penalty),penalty}),mod:statistic.mod,roll:async params=>{const targetToken=params.target??game.user.targets.find(t=>!!t.actor?.isOfType("army")),roll=await statistic.roll({identifier:type,action:"army-strike",melee:type==="melee",modifiers:mapModifier?[mapModifier]:[],target:targetToken?.actor,dc:{slug:"ac"},damaging:!0,extraRollOptions:["origin:action:slug:army-strike"],...eventToRollParams(params.event,{type:"check"})});if(roll&&type==="ranged"){const newAmmo=Math.max(0,this.system.resources.ammunition.value-1);this.update({"system.resources.ammunition.value":newAmmo})}return roll}}}),damage:params=>dealDamage(params,"success"),critical:params=>dealDamage(params,"criticalSuccess")}}updateLevel(newLevel){newLevel=Math.clamped(newLevel,1,20);const currentLevel=this.system.details.level.value,strongSave=this.system.saves.strongSave,strongSaveDifference=ARMY_STATS.strongSave[newLevel]-ARMY_STATS.strongSave[currentLevel],weakSaveDifference=ARMY_STATS.weakSave[newLevel]-ARMY_STATS.weakSave[currentLevel];return this.update({system:{ac:{value:this.system.ac.value+(ARMY_STATS.ac[newLevel]-ARMY_STATS.ac[currentLevel])},details:{level:{value:newLevel}},saves:{maneuver:this.system.saves.maneuver+(strongSave==="maneuver"?strongSaveDifference:weakSaveDifference),morale:this.system.saves.morale+(strongSave==="morale"?strongSaveDifference:weakSaveDifference)},scouting:this.system.scouting+(ARMY_STATS.scouting[newLevel]-ARMY_STATS.scouting[currentLevel])}})}checkItemValidity(source){if(source.type==="campaignFeature"&&source.system?.category==="army-tactic"){const validArmyTypes=ARMY_TYPES.filter(t=>source.system?.traits?.value?.includes(t));if(validArmyTypes.length>0&&!validArmyTypes.includes(this.system.traits.type))return ui.notifications.error(game.i18n.format("PF2E.Kingmaker.Army.Error.InvalidTacticType",{name:source.name,type:game.i18n.localize(CONFIG.PF2E.kingmakerTraits[this.system.traits.type])})),!1}return super.checkItemValidity(source)}getStatistic(slug){return tupleHasValue(["scouting","morale","maneuver"],slug)?this[slug]:this.kingdom?.getStatistic(slug)??super.getStatistic(slug)}_preUpdate(changed,options,user){if(typeof changed?.system?.attributes?.hp?.value=="number"){const max=Number(changed.system.attributes.hp.max??this.system.attributes.hp.max);changed.system.attributes.hp.value=Math.clamped(changed.system.attributes.hp.value,0,max)}return super._preUpdate(changed,options,user)}}class HazardPF2e extends ActorPF2e{static{__name(this,"HazardPF2e")}static{__name2(this,"HazardPF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"action","melee"]}get rarity(){return this.system.traits.rarity}get isComplex(){return this.system.details.isComplex}get hardness(){return Math.abs(this.system.attributes.hardness)}get hasDefenses(){return!!(this.hitPoints?.max||this.attributes.ac.value)}get canAttack(){return this.itemTypes.melee.length>0}get emitsSound(){const{emitsSound}=this.system.attributes;return!this.isDead&&typeof emitsSound=="boolean"?emitsSound:!!game.combats.active?.started&&game.combats.active.combatants.some(c=>c.actor===this)}isAffectedBy(effect){const damageType=objectHasKey(CONFIG.PF2E.damageTypes,effect)?effect:isObject(effect)?effect.system.persistent?.damageType??null:null;if(!this.system.attributes.hasHealth&&damageType)return!1;const{weaknesses,resistances}=this.system.attributes;return damageType&&["vitality","void"].includes(damageType)?weaknesses.some(w=>w.type===damageType)||resistances.some(r=>r.type===damageType):super.isAffectedBy(effect)}prepareBaseData(){super.prepareBaseData();const{attributes,details}=this.system;if(attributes.hp.negativeHealing=!1,attributes.hp.brokenThreshold=Math.floor(attributes.hp.max/2),attributes.hasHealth=attributes.hp.max>0,attributes.immunities.some(i=>i.type==="object-immunities")||attributes.immunities.unshift(new Immunity({type:"object-immunities",source:"TYPES.Actor.hazard"})),this.isComplex){attributes.stealth.value??=0;const partialAttributes=this.system.attributes;partialAttributes.initiative={statistic:"stealth",tiebreakPriority:this.hasPlayerOwner?2:1}}details.alliance=null}prepareDerivedData(){super.prepareDerivedData();const{system}=this;if(this.prepareSynthetics(),setHitPointsRollOptions(this),this.skills={stealth:new Statistic(this,{slug:"stealth",label:CONFIG.PF2E.skillList.stealth,domains:["stealth","dex-based","skill-check","dex-skill-check","all"],modifiers:[new ModifierPF2e({label:"PF2E.ModifierTitle",slug:"base",type:"untyped",modifier:system.attributes.stealth.value??0})],check:{type:"skill-check"}})},system.attributes.initiative&&(this.initiative=new ActorInitiative(this,{statistic:"stealth"}),system.attributes.initiative=this.initiative.getTraceData()),this.hasDefenses){const baseModifier=new ModifierPF2e({slug:"base",label:"PF2E.BaseModifier",modifier:system.attributes.ac.value-10}),statistic=new ArmorStatistic(this,{rank:1,modifiers:[baseModifier]});this.armorClass=statistic.dc,system.attributes.ac=statistic.getTraceData()}this.saves=this.prepareSaves(),this.system.actions=this.itemTypes.melee.map(m=>strikeFromMeleeItem(m))}prepareData(){super.prepareData();const weaknessesAndResistances=new Set([this.system.attributes.weaknesses.map(w=>w.type),this.system.attributes.resistances.map(r=>r.type)].flat()),objectImmunities=this.system.attributes.immunities.find(i=>i.type==="object-immunities");for(const wrType of["bleed","mental","poison","spirit"])weaknessesAndResistances.has(wrType)&&objectImmunities?.exceptions.push(wrType)}prepareSaves(){const{system}=this;return SAVE_TYPES.reduce((saves,saveType)=>{const save=system.saves[saveType],label=game.i18n.localize(CONFIG.PF2E.saves[saveType]),base=save.value;if(!base)return saves;const statistic=new Statistic(this,{slug:saveType,label,attribute:CONFIG.PF2E.savingThrowDefaultAttributes[saveType],domains:[saveType,"saving-throw"],modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:base})],check:{type:"saving-throw"}});return this.system.saves[saveType]=foundry.utils.mergeObject(save,statistic.getTraceData()),saves[saveType]=statistic,saves},{})}}class LootPF2e extends ActorPF2e{static{__name(this,"LootPF2e")}static{__name2(this,"LootPF2e")}armorClass=null;get allowedItemTypes(){return["physical"]}get isLoot(){return this.system.lootSheetType==="Loot"}get isMerchant(){return this.system.lootSheetType==="Merchant"}get hiddenWhenEmpty(){return this.isLoot&&this.system.hiddenWhenEmpty}get canHostRuleElements(){return!1}get canAct(){return!1}isAffectedBy(){return!1}get visible(){return this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.OBSERVER}canUserModify(user,action2){return action2==="update"?this.permission>=CONST.DOCUMENT_OWNERSHIP_LEVELS.LIMITED:super.canUserModify(user,action2)}async transferItemToActor(targetActor,item,quantity,containerId,newStack=!1){if(!(this.isOwner&&targetActor.isOwner))return super.transferItemToActor(targetActor,item,quantity,containerId,newStack);if(this.isMerchant&&item.isOfType("physical")){const itemValue=CoinsPF2e.fromPrice(item.price,quantity);if(await targetActor.inventory.removeCoins(itemValue))return await item.actor.inventory.addCoins(itemValue),super.transferItemToActor(targetActor,item,quantity,containerId,newStack);if(this.isLoot)throw ErrorPF2e("Loot transfer failed");return null}return super.transferItemToActor(targetActor,item,quantity,containerId,newStack)}async toggleTokenHiding(){if(!this.hiddenWhenEmpty||!this.isOwner)return;const hiddenStatus=this.items.size===0,promises=game.scenes.map(s=>[s,s.tokens.filter(t=>t.actor===this)]).map(([scene,tokenDocs])=>scene.updateEmbeddedDocuments("Token",tokenDocs.map(tokenDoc=>({_id:tokenDoc.id,hidden:hiddenStatus}))));await Promise.allSettled(promises)}prepareDerivedData(){this.rules=[],super.prepareDerivedData()}_onCreate(data,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onCreate(data,options,userId)}_onUpdate(changed,options,userId){game.user.id===userId&&changed.system?.hiddenWhenEmpty!==void 0&&this.toggleTokenHiding(),super._onUpdate(changed,options,userId)}_onCreateDescendantDocuments(parent,collection,documents,result,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onCreateDescendantDocuments(parent,collection,documents,result,options,userId)}_onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId){game.user.id===userId&&this.toggleTokenHiding(),super._onDeleteDescendantDocuments(parent,collection,documents,ids,options,userId)}}const{DataModel}=foundry.abstract;class InvalidCampaign extends DataModel{static{__name(this,"InvalidCampaign")}static{__name2(this,"InvalidCampaign")}type="invalid";actor;options;constructor(actor,options){super(),this.actor=actor,this.options=options}static defineSchema(){return{}}createSidebarButtons(){const icon=createHTMLElement("a",{children:[fontAwesomeIcon("warning",{fixedWidth:!0})]});return icon.title=game.i18n.localize("PF2E.Actor.Party.InvalidCampaign.Hint"),game.user.isGM?icon.addEventListener("click",()=>{new Dialog({title:game.i18n.format("PF2E.Actor.Party.InvalidCampaign.Title",{party:this.actor.name}),content:game.i18n.format(`PF2E.Actor.Party.InvalidCampaign.Message.${this.options.reason}`,{current:this.actor.system.campaign?.type??"",...this.options}),buttons:{yes:{icon:fontAwesomeIcon("trash").outerHTML,label:game.i18n.localize("Yes"),callback:async()=>{await this.actor.update({"system.-=campaign":null}),ui.sidebar.render()}},cancel:{icon:fontAwesomeIcon("times").outerHTML,label:game.i18n.localize("Cancel")}}}).render(!0)}):icon.style.pointerEvents="none",[icon]}}class PartyPF2e extends ActorPF2e{static{__name(this,"PartyPF2e")}static{__name2(this,"PartyPF2e")}armorClass=null;get active(){return game.actors.party===this}get baseAllowedItemTypes(){return["physical"]}get allowedItemTypes(){return[...this.baseAllowedItemTypes,...this.campaign?.extraItemTypes??[]]}get canAct(){return!1}canUserModify(user,action2){return super.canUserModify(user,action2)||action2==="update"&&this.members.some(m=>m.canUserModify(user,action2))}isAffectedBy(){return!1}validate(options){if(!super.validate(options))return!1;const changes=options?.changes??{};return!(changes.system?.campaign&&!this.campaign?.validate({...options,changes:changes.system.campaign}))}updateSource(data,options){if(!this.campaign)return super.updateSource(data,options);const expanded=foundry.utils.expandObject(data??{}),campaignDiff=expanded?.system?.campaign?this.campaign.updateSource(expanded.system.campaign,options):{},diff=super.updateSource(data,options);return isEmpty(campaignDiff)?diff:foundry.utils.mergeObject(diff,campaignDiff)}prepareRuleElements(){return this.items.contents.filter(item=>!item.isOfType("physical")).flatMap(item=>item.prepareRuleElements()).filter(rule=>!rule.ignored).sort((elementA,elementB)=>elementA.priority-elementB.priority)}_initialize(options){super._initialize(options),Object.defineProperty(this.system,"campaign",{writable:!0,enumerable:!1})}prepareBaseData(){this.system.details.level={value:0},super.prepareBaseData(),this.members=this.system.details.members.map(m=>fromUuidSync(m.uuid)).filter(a=>a instanceof ActorPF2e&&a.isOfType("creature")).sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang));for(const member of this.members)member?.parties.add(this);this.system.details.alliance=this.members.some(m=>m.alliance==="party")?"party":this.members.some(m=>m.alliance==="opposition")?"opposition":null;const campaignType=game.settings.get("pf2e","campaignType");if(campaignType!=="none"){const typeMatches=this.system.campaign?.type===campaignType;if(this.system.campaign&&!typeMatches)this.campaign=new InvalidCampaign(this,{campaignType,reason:"mismatch"});else try{this.campaign?.type!==campaignType?this.campaign=new Kingdom(foundry.utils.deepClone(this._source.system.campaign),{parent:this}):(Kingdom.cleanData(this.campaign._source),this.campaign.reset()),this.campaign.prepareBaseData?.(),this.system.campaign=this.campaign}catch(err){console.error(err),this.campaign=new InvalidCampaign(this,{campaignType,reason:"error"})}}else this.campaign=null;const partyLevel=Math.round(meanBy(this.members.filter(m=>m.isOfType("character")),m=>m.level));this.system.details.level.value=partyLevel}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){super.prepareDerivedData();const travelSpeed=Math.min(...this.members.map(m=>m.attributes.speed.total));this.attributes.speed={total:travelSpeed},this.prepareSynthetics(),this.campaign?.prepareDerivedData?.()}async addMembers(...membersToAdd){const existing=this.system.details.members.filter(d=>this.members.some(m=>m.uuid===d.uuid)),existingUUIDs=new Set(existing.map(data=>data.uuid)),newMembers=membersToAdd.filter(a=>a.uuid.startsWith("Actor.")&&!existingUUIDs.has(a.uuid));for(const member of newMembers){const allianceUpdate=member.isOfType("character","npc")?{"system.details.alliance":member._source.system.details.alliance??"party"}:{};await member.update({folder:null,...allianceUpdate})}const members=[...existing,...newMembers.map(m=>({uuid:m.uuid}))];await this.update({system:{details:{members}}}),await resetActors(newMembers)}async removeMembers(...remove2){const uuids=remove2.map(d=>typeof d=="string"?d:d.uuid),members=this.system.details.members.filter(d=>this.members.some(m=>m.uuid===d.uuid)).filter(m=>!tupleHasValue(uuids,m.uuid));await this.update({system:{details:{members}}})}async addToCombat(options={}){const promises=this.members.map(a=>CombatantPF2e.fromActor(a,!0,{combat:options.combat}));return(await Promise.all(promises)).filter(c=>!!c)}getRollOptions(domains){return super.getRollOptions(domains).concat(this.campaign?.getRollOptions?.()??[])}getRollData(){return foundry.utils.mergeObject(super.getRollData(),this.campaign?.getRollData?.()??{})}reset({actor=!1}={}){actor?this._resetAndRerenderDebounced():super.reset()}getStatistic(slug){const statistic=super.getStatistic(slug);return statistic||(this.campaign?.getStatistic?.(slug)??null)}_resetAndRerenderDebounced=foundry.utils.debounce(()=>{super.reset(),this.sheet.render(!1,{actor:!0})},50);async _preUpdate(changed,options,user){const members=this.members,newMemberUUIDs=changed?.system?.details?.members?.map(m=>m?.uuid);if(newMemberUUIDs){const deletedMembers=members.filter(m=>m?.uuid&&!newMemberUUIDs.includes(m.uuid));options.removedMembers=deletedMembers.map(m=>m.uuid)}return changed.system?.campaign&&this.campaign&&this.campaign.type!=="invalid"&&(changed.system.campaign.type=this.campaign.type,this.campaign._preUpdate?.(changed.system.campaign)),super._preUpdate(changed,options,user)}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId);const removedCreatures=(options.removedMembers??[]).map(uuid=>fromUuidSync(uuid)).filter(a=>a instanceof ActorPF2e&&a.isOfType("creature"));for(const actor of removedCreatures)actor.parties.delete(this);if(resetActors(removedCreatures),changed.system?.details?.members&&game.combat)for(const encounter of game.combats)encounter.reset(),ui.combat.render();game.ready&&changed.system?.campaign&&game.actors.get(this.id)===this&&ui.actors.render()}_onDelete(options,userId){super._onDelete(options,userId);for(const member of this.members)member.parties.delete(this);resetActors(this.members),ui.actors.saveActivePartyFolderState()}}class VehiclePF2e extends ActorPF2e{static{__name(this,"VehiclePF2e")}static{__name2(this,"VehiclePF2e")}get allowedItemTypes(){return[...super.allowedItemTypes,"physical","action"]}get dimensions(){return{length:this.system.details.space.long,width:this.system.details.space.wide,height:this.system.details.space.high}}get hardness(){return this.system.attributes.hardness}getTokenDimensions(dimensions=this.dimensions){return{width:Math.max(Math.round(dimensions.width/5),1),height:Math.max(Math.round(dimensions.length/5),1)}}prepareBaseData(){super.prepareBaseData(),this.system.details.alliance=null;const{size}=this.system.traits,{dimensions}=this;if(size.length=dimensions.length,size.width=dimensions.width,this.prototypeToken.flags?.pf2e?.linkToActorSize){const{width,height}=this.getTokenDimensions();this.prototypeToken.width=width,this.prototypeToken.height=height}}prepareEmbeddedDocuments(){super.prepareEmbeddedDocuments();for(const rule of this.rules)rule.onApplyActiveEffects?.()}prepareDerivedData(){if(super.prepareDerivedData(),this.prepareSynthetics(),this.hasCondition("broken"))for(const selector of["ac","saving-throw"]){const modifiers=this.synthetics.modifiers[selector]??=[],brokenModifier=new ModifierPF2e({slug:"broken",label:"PF2E.ConditionTypeBroken",modifier:-2,adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,[selector],"broken")});modifiers.push(()=>brokenModifier)}const{attributes}=this,hitPoints=new HitPointsStatistic(this,{baseMax:attributes.hp.max});attributes.hp=foundry.utils.mergeObject(hitPoints.getTraceData(),{brokenThreshold:Math.floor(hitPoints.max/2)}),setHitPointsRollOptions(this);const armorStatistic=new ArmorStatistic(this,{modifiers:[new ModifierPF2e({slug:"base",label:"PF2E.ModifierTitle",modifier:this.system.attributes.ac.value-10,adjustments:extractModifierAdjustments(this.synthetics.modifierAdjustments,["all","ac"],"base")})]});this.armorClass=armorStatistic.dc,this.system.attributes.ac=armorStatistic.getTraceData(),this.prepareSaves()}prepareSaves(){const{synthetics}=this,slug="fortitude",domains=[slug,"saving-throw","all"],modifiers=[new ModifierPF2e({label:"PF2E.ModifierTitle",slug,type:"untyped",modifier:this.system.saves.fortitude.value}),...extractModifiers(synthetics,domains)],fortitude=new Statistic(this,{slug:"fortitude",label:CONFIG.PF2E.saves.fortitude,modifiers,domains,check:{type:"saving-throw"}});this.saves={fortitude},this.system.saves.fortitude=foundry.utils.mergeObject(this.system.saves.fortitude,fortitude.getTraceData())}async _preUpdate(changed,options,user){const result=await super._preUpdate(changed,options,user);if(result===!1)return result;if(this.prototypeToken.flags?.pf2e?.linkToActorSize){const{space}=this.system.details,spaceUpdates={width:changed.system?.details?.space?.wide??space.wide,length:changed.system?.details?.space?.long??space.long},tokenDimensions=this.getTokenDimensions(spaceUpdates);if(changed.prototypeToken=foundry.utils.mergeObject(changed.prototypeToken??{},tokenDimensions),canvas.scene){const updates=this.getActiveTokens().filter(token=>token.document.linkToActorSize).map(token=>({_id:token.id,...tokenDimensions}));await TokenDocumentPF2e.updateDocuments(updates,{parent:canvas.scene})}}}}function extractModifiers(synthetics,selectors,options={}){const{modifierAdjustments,modifiers:syntheticModifiers}=synthetics,modifiers=Array.from(new Set(selectors)).flatMap(s=>syntheticModifiers[s]??[]).flatMap(d=>d(options)??[]);for(const modifier of modifiers)modifier.adjustments=extractModifierAdjustments(modifierAdjustments,selectors,modifier.slug);return modifiers}__name(extractModifiers,"extractModifiers"),__name2(extractModifiers,"extractModifiers");function extractModifierAdjustments(adjustmentsRecord,selectors,slug){return Array.from(new Set(selectors.flatMap(s=>adjustmentsRecord[s]??[]))).filter(a=>[slug,null].includes(a.slug))}__name(extractModifierAdjustments,"extractModifierAdjustments"),__name2(extractModifierAdjustments,"extractModifierAdjustments");function extractNotes(rollNotes,selectors){return selectors.flatMap(s=>(rollNotes[s]??[]).map(n=>n.clone()))}__name(extractNotes,"extractNotes"),__name2(extractNotes,"extractNotes");function extractDamageDice(deferredDice,selectors,options){return selectors.flatMap(s=>deferredDice[s]??[]).flatMap(d=>d(options)??[])}__name(extractDamageDice,"extractDamageDice"),__name2(extractDamageDice,"extractDamageDice");function processDamageCategoryStacking(base,options){const{dice}=options,groupedModifiers=groupBy$1(options.modifiers,m=>m.category==="persistent"?"persistent":"main"),modifiers=[...new StatisticModifier("damage",groupedModifiers.main??[],options.test).modifiers,...new StatisticModifier("persistent",groupedModifiers.persistent??[],options.test).modifiers],allPersistent=base.length>0&&base.every(b=>b.category==="persistent");return{modifiers:allPersistent?modifiers.filter(m=>m.category==="persistent"):modifiers,dice:allPersistent?dice.filter(m=>m.category==="persistent"):dice}}__name(processDamageCategoryStacking,"processDamageCategoryStacking"),__name2(processDamageCategoryStacking,"processDamageCategoryStacking");async function extractEphemeralEffects({affects,origin,target,item,domains,options}){if(!(origin&&target))return[];const[effectsFrom,effectsTo]=affects==="target"?[origin,target]:[target,origin],fullOptions=[...options,effectsFrom.getRollOptions(domains),effectsTo.getSelfRollOptions(affects)].flat(),resolvables=item?item.isOfType("spell")?{spell:item}:{weapon:item}:{};return(await Promise.all(domains.flatMap(s=>effectsFrom.synthetics.ephemeralEffects[s]?.[affects]??[]).map(d=>d({test:fullOptions,resolvables})))).flatMap(e=>e??[])}__name(extractEphemeralEffects,"extractEphemeralEffects"),__name2(extractEphemeralEffects,"extractEphemeralEffects");function extractRollTwice(rollTwices,selectors,options){const twices=selectors.flatMap(s=>rollTwices[s]??[]).filter(rt=>rt.predicate?.test(options)??!0);return twices.length===0||twices.some(rt=>rt.keep==="higher")&&twices.some(rt=>rt.keep==="lower")?!1:twices.at(0)?.keep==="higher"?"keep-higher":"keep-lower"}__name(extractRollTwice,"extractRollTwice"),__name2(extractRollTwice,"extractRollTwice");function extractRollSubstitutions(substitutions,domains,rollOptions){return domains.flatMap(d=>foundry.utils.deepClone(substitutions[d]??[])).filter(s=>s.predicate?.test(rollOptions)??!0)}__name(extractRollSubstitutions,"extractRollSubstitutions"),__name2(extractRollSubstitutions,"extractRollSubstitutions");function extractDegreeOfSuccessAdjustments(synthetics,selectors){return Object.values(pick(synthetics.degreeOfSuccessAdjustments,selectors)).flat()}__name(extractDegreeOfSuccessAdjustments,"extractDegreeOfSuccessAdjustments"),__name2(extractDegreeOfSuccessAdjustments,"extractDegreeOfSuccessAdjustments");function isBracketedValue(value){return isObject$1(value)&&Array.isArray(value.brackets)}__name(isBracketedValue,"isBracketedValue"),__name2(isBracketedValue,"isBracketedValue");async function processPreUpdateActorHooks(changed,{pack}){const actorId=String(changed._id),actor=pack?await game.packs.get(pack)?.getDocument(actorId):game.actors.get(actorId);if(!(actor instanceof ActorPF2e))return;const rules=actor.rules.filter(r=>!!r.preUpdateActor);if(rules.length===0)return;actor.flags.pf2e.rollOptions=actor.clone(changed,{keepId:!0}).flags.pf2e.rollOptions;const createDeletes=(await Promise.all(rules.map(r=>actor.items.has(r.item.id)?r.preUpdateActor():new Promise(()=>({create:[],delete:[]}))))).reduce((combined,cd)=>(combined.create.push(...cd.create),combined.delete.push(...cd.delete),combined),{create:[],delete:[]});createDeletes.delete=uniq(createDeletes.delete).filter(id=>actor.items.has(id)),createDeletes.create.length>0&&await actor.createEmbeddedDocuments("Item",createDeletes.create,{keepId:!0,render:!1}),createDeletes.delete.length>0&&await actor.deleteEmbeddedDocuments("Item",createDeletes.delete,{render:!1})}__name(processPreUpdateActorHooks,"processPreUpdateActorHooks"),__name2(processPreUpdateActorHooks,"processPreUpdateActorHooks");const PROFICIENCY_RANK_OPTION=["proficiency:untrained","proficiency:trained","proficiency:expert","proficiency:master","proficiency:legendary"];function ensureProficiencyOption(options,rank){rank>=0&&options.add(`skill:rank:${rank}`).add(PROFICIENCY_RANK_OPTION[rank])}__name(ensureProficiencyOption,"ensureProficiencyOption"),__name2(ensureProficiencyOption,"ensureProficiencyOption");const MODIFIER_TYPES=new Set(["ability","circumstance","item","potency","proficiency","status","untyped"]);class ModifierPF2e{static{__name(this,"ModifierPF2e")}static{__name2(this,"ModifierPF2e")}slug;label;modifier;#originalValue;type;ability;adjustments;force;enabled;ignored;rule;source;custom;damageType;damageCategory;predicate;critical;traits;hideIfDisabled;kind;constructor(...args){const params=__name2(args2=>typeof args2[0]=="string","isLegacyParams")(args)?{label:args[0],modifier:args[1],type:args[2]??"untyped",enabled:args[3],ignored:args[4],source:args[5]}:args[0];if(this.label=game.i18n.localize(params.label??params.name),this.slug=sluggify(params.slug??this.label),this.#originalValue=this.modifier=params.modifier,this.type=setHasElement(MODIFIER_TYPES,params.type)?params.type:"untyped",this.ability=params.ability??null,this.force=params.force??!1,this.adjustments=foundry.utils.deepClone(params.adjustments??[]),this.enabled=params.enabled??!0,this.ignored=params.ignored??!1,this.custom=params.custom??!1,this.source=params.source??null,this.predicate=new PredicatePF2e(params.predicate??[]),this.traits=foundry.utils.deepClone(params.traits??[]),this.hideIfDisabled=params.hideIfDisabled??!1,this.modifier=params.modifier,this.rule=params.rule??null,Object.defineProperty(this,"rule",{enumerable:!1}),this.damageType=objectHasKey(CONFIG.PF2E.damageTypes,params.damageType)?params.damageType:null,this.damageCategory=this.damageType==="bleed"?"persistent":params.damageCategory??null,this.critical=this.damageCategory==="splash"?!!params.critical:params.critical??null,this.kind=(()=>this.modifier>=0&&!["ability","untyped"].includes(this.type)?"bonus":this.modifier<0&&this.type!=="ability"?"penalty":"modifier")(),this.force&&this.type==="untyped")throw ErrorPF2e("A forced modifier must have a type")}get category(){return this.damageCategory}get value(){return this.kind==="penalty"&&this.modifier===0?-this.modifier:this.modifier}get signedValue(){return this.modifier===0&&this.kind==="penalty"?signedInteger(-this.modifier):signedInteger(this.modifier)}clone(options={}){const clone=this.modifier===this.#originalValue?new ModifierPF2e(this):new ModifierPF2e({...this,modifier:this.#originalValue});return options.test&&clone.test(options.test),clone}getRollOptions(){const options=["slug","type","value"].map(p=>`${this.kind}:${p}:${this[p]}`);return this.type==="ability"&&this.ability&&options.push(`modifier:ability:${this.ability}`),new Set(options)}test(options){if(this.predicate.length===0)return;const rollOptions=this.rule?[...options,...this.rule.item.getRollOptions("parent")]:options;this.ignored=!this.predicate.test(rollOptions)}toObject(){return foundry.utils.deepClone({...this,predicate:[...this.predicate],rule:this.rule?.toObject(),item:void 0})}toString(){return this.label}}function createAttributeModifier({actor,attribute,domains,max}){const withAttributeBased=domains.includes(`${attribute}-based`)?domains:[...domains,`${attribute}-based`],modifierValue=actor.abilities[attribute].mod,cappedValue=Math.min(modifierValue,max??modifierValue);return new ModifierPF2e({slug:attribute,label:CONFIG.PF2E.abilities[attribute],modifier:cappedValue,type:"ability",ability:attribute,adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,withAttributeBased,attribute)})}__name(createAttributeModifier,"createAttributeModifier"),__name2(createAttributeModifier,"createAttributeModifier");function createProficiencyModifier({actor,rank,domains,level,addLevel}){rank=Math.clamped(rank,0,4),addLevel??=rank>0;const pwolVariant=game.pf2e.settings.variants.pwol.enabled,baseBonuses=pwolVariant?game.pf2e.settings.variants.pwol.modifiers:[0,2,4,6,8],addedLevel=addLevel&&!pwolVariant?level??actor.level:0,bonus=baseBonuses[rank]+addedLevel;return new ModifierPF2e({slug:"proficiency",label:`PF2E.ProficiencyLevel${rank}`,modifier:bonus,type:"proficiency",adjustments:extractModifierAdjustments(actor.synthetics.modifierAdjustments,domains,"proficiency")})}__name(createProficiencyModifier,"createProficiencyModifier"),__name2(createProficiencyModifier,"createProficiencyModifier");const HIGHER_BONUS=__name2((a,b)=>a.modifier>=b.modifier,"HIGHER_BONUS"),LOWER_PENALTY=__name2((a,b)=>a.modifier<=b.modifier,"LOWER_PENALTY");function applyStacking(best,modifier,isBetter){const existing=best[modifier.type];return existing===void 0?(modifier.enabled=!0,best[modifier.type]=modifier,modifier.modifier):isBetter(modifier,existing)?(existing.enabled=!1,modifier.enabled=!0,best[modifier.type]=modifier,modifier.modifier-existing.modifier):(modifier.enabled=!1,0)}__name(applyStacking,"applyStacking"),__name2(applyStacking,"applyStacking");function applyStackingRules(modifiers){let total=0;const highestBonus={},lowestPenalty={},abilityModifiers=modifiers.filter(m=>m.type==="ability"&&!m.ignored),bestAbility=abilityModifiers.reduce((best,modifier)=>best===null||modifier.force?modifier:best.force?best:modifier.modifier>best.modifier?modifier:best,null);for(const modifier of abilityModifiers)modifier.ignored=modifier!==bestAbility;for(const modifier of modifiers){if(modifier.ignored){modifier.enabled=!1;continue}if(modifier.type==="untyped"){modifier.enabled=!0,total+=modifier.modifier;continue}modifier.modifier<0?total+=applyStacking(lowestPenalty,modifier,LOWER_PENALTY):total+=applyStacking(highestBonus,modifier,HIGHER_BONUS)}return total}__name(applyStackingRules,"applyStackingRules"),__name2(applyStackingRules,"applyStackingRules");class StatisticModifier{static{__name(this,"StatisticModifier")}static{__name2(this,"StatisticModifier")}slug;_modifiers;breakdown="";notes;constructor(slug,modifiers=[],rollOptions=new Set){rollOptions=rollOptions instanceof Set?rollOptions:new Set(rollOptions),this.slug=slug;const seen=modifiers.reduce((result,modifier)=>((!result[modifier.slug]?.enabled||Math.abs(modifier.modifier)>Math.abs(result[modifier.slug].modifier))&&(result[modifier.slug]=modifier),result),{});this._modifiers=Object.values(seen),this.calculateTotal(rollOptions)}get modifiers(){return[...this._modifiers]}push(modifier){const existingIdx=this._modifiers.findIndex(o=>o.slug===modifier.slug),existing=this._modifiers[existingIdx];return existing?Math.abs(modifier.modifier)>Math.abs(existing.modifier)&&(this._modifiers[existingIdx]=modifier,this.calculateTotal()):(this._modifiers.push(modifier),this.calculateTotal()),this._modifiers.length}unshift(modifier){return this._modifiers.find(o=>o.slug===modifier.slug)===void 0&&(this._modifiers.unshift(modifier),this.calculateTotal()),this._modifiers.length}delete(modifierSlug){const toDelete2=typeof modifierSlug=="object"?modifierSlug:this._modifiers.find(modifier=>modifier.slug===modifierSlug),wasDeleted=toDelete2&&this._modifiers.includes(toDelete2)?!!this._modifiers.findSplice(modifier=>modifier===toDelete2):!1;return wasDeleted&&this.calculateTotal(),wasDeleted}calculateTotal(rollOptions=new Set){if(rollOptions.size>0){for(const modifier of this._modifiers)modifier.test(rollOptions);adjustModifiers(this._modifiers,rollOptions)}applyStackingRules(this._modifiers),this.totalModifier=this._modifiers.filter(m=>m.enabled).reduce((total,m)=>total+m.modifier,0)}}function adjustModifiers(modifiers,rollOptions){for(const modifier of[...modifiers].sort((a,b)=>Math.abs(b.value)-Math.abs(a.value))){const adjustments=modifier.adjustments.filter(a=>a.test([...rollOptions,...modifier.getRollOptions()]));if(adjustments.some(a=>a.suppress)){modifier.ignored=!0;continue}const resolvedAdjustment=adjustments.reduce((resolved,adjustment)=>{const newValue=adjustment.getNewValue?.(resolved.value)??resolved.value;return newValue!==resolved.value&&(resolved.value=newValue,resolved.relabel=adjustment.relabel??null),resolved},{value:modifier.modifier,relabel:null});modifier.modifier=resolvedAdjustment.value,resolvedAdjustment.relabel&&(modifier.label=game.i18n.localize(resolvedAdjustment.relabel)),modifier.damageType=adjustments.reduce((damageType,adjustment)=>adjustment.getDamageType?.(damageType)??damageType,modifier.damageType)}}__name(adjustModifiers,"adjustModifiers"),__name2(adjustModifiers,"adjustModifiers");class CheckModifier extends StatisticModifier{static{__name(this,"CheckModifier")}static{__name2(this,"CheckModifier")}constructor(slug,statistic,modifiers=[],rollOptions=new Set){const baseModifiers=statistic.modifiers.map(m=>"clone"in m?m.clone():new ModifierPF2e(m));super(slug,baseModifiers.concat(modifiers),rollOptions)}}class DamageDicePF2e{static{__name(this,"DamageDicePF2e")}static{__name2(this,"DamageDicePF2e")}selector;slug;label;diceNumber;dieSize;critical;category;damageType;override;ignored;enabled;custom;predicate;constructor(params){if(params.selector)this.selector=params.selector;else throw ErrorPF2e("`selector` is mandatory");if(this.label=game.i18n.localize(params.label??""),this.slug=sluggify(params.slug??this.label),!this.slug)throw ErrorPF2e("A DiceModifier must have a slug");this.diceNumber=params.diceNumber??0,this.dieSize=params.dieSize??null,this.damageType=params.damageType??null,this.category=params.category??null,this.override=params.override??null,this.custom=params.custom??!1,this.category=tupleHasValue(["persistent","precision","splash"],params.category)?params.category:this.damageType==="bleed"?"persistent":null,this.critical=this.category==="splash"?!!params.critical:params.critical??null,this.predicate=params.predicate instanceof PredicatePF2e?params.predicate:new PredicatePF2e(params.predicate??[]),this.enabled=params.enabled??this.predicate.test([]),this.ignored=params.ignored??!this.enabled}test(options){this.enabled=this.predicate.test(options),this.ignored=!this.enabled}clone(){return new DamageDicePF2e(this)}toObject(){return foundry.utils.deepClone({...this,predicate:[...this.predicate]})}}function isCheckContextFlag(flag){return!!flag&&!tupleHasValue(["damage-roll","spell-cast"],flag.type)}__name(isCheckContextFlag,"isCheckContextFlag"),__name2(isCheckContextFlag,"isCheckContextFlag");async function createSelfEffectMessage(item,rollMode="roll"){if(!item.system.selfEffect)throw ErrorPF2e(["Only actions with self-applied effects can be passed to `ActorPF2e#useAction`.","Support will be expanded at a later time."].join(" "));const{actor,actionCost}=item,token=actor.getActiveTokens(!0,!0).shift()??null,speaker=ChatMessagePF2e.getSpeaker({actor,token}),flavor=await renderTemplate("systems/pf2e/templates/chat/action/flavor.hbs",{action:{title:item.name,glyph:getActionGlyph(actionCost)},item,traits:item.system.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.actionTraits))}),previewLength=100,descriptionPreview=(()=>{if(item.actor.pack)return null;const tempDiv=document.createElement("div"),documentTypes=[...CONST.DOCUMENT_LINK_TYPES,"Compendium","UUID"],linkPattern=new RegExp(`@(${documentTypes.join("|")})\\[([^#\\]]+)(?:#([^\\]]+))?](?:{([^}]+)})?`,"g");return tempDiv.innerHTML=item.description.replace(linkPattern,(_match,...args)=>args[3]),tempDiv.innerText.slice(0,previewLength)})(),description={full:descriptionPreview&&descriptionPreview.lengtho.startsWith("self:")).map(o=>o.replace(/^self/,"origin")),messageItem=message.item;for(const token of tokens){if(!token.actor)continue;messageRollOptions.some(o=>o.startsWith("target"))||messageRollOptions.push(...token.actor.getSelfRollOptions("target"));const domain=multiplier>0?"damage-received":"healing-received",ephemeralEffects=multiplier>0?await extractEphemeralEffects({affects:"target",origin:message.actor,target:token.actor,item:message.item,domains:[domain],options:messageRollOptions}):[],contextClone=token.actor.getContextualClone(originRollOptions,ephemeralEffects),applicationRollOptions=new Set([...messageRollOptions.filter(o=>!/^(?:self|target):/.test(o)),...originRollOptions,...contextClone.getSelfRollOptions()]),outcome=message.flags.pf2e.context?.outcome,breakdown=[],rolls=[];if(typeof damage=="number"&&damage<0){const critical=outcome==="criticalSuccess",resolvables=(()=>messageItem?.isOfType("spell")?{spell:messageItem}:messageItem?.isOfType("weapon")?{weapon:messageItem}:{})(),damageDice=extractDamageDice(contextClone.synthetics.damageDice,[domain],{resolvables,test:applicationRollOptions}).filter(d=>(d.critical===null||d.critical===critical)&&d.predicate.test(applicationRollOptions));for(const dice of damageDice){const formula=`${dice.diceNumber}${dice.dieSize}[${dice.label}]`,roll2=await new Roll(formula).evaluate({async:!0});roll2._formula=`${dice.diceNumber}${dice.dieSize}`,await roll2.toMessage({flags:{pf2e:{suppressDamageButtons:!0}},flavor:dice.label,speaker:ChatMessage.getSpeaker({token})}),breakdown.push(`${dice.label} ${dice.diceNumber}${dice.dieSize}`),rolls.push(roll2)}rolls.length&&(damage-=rolls.map(roll2=>roll2.total).reduce((previous,current)=>previous+current));const modifiers=extractModifiers(contextClone.synthetics,[domain],{resolvables}).filter(m=>(m.critical===null||m.critical===critical)&&m.predicate.test(applicationRollOptions));damage-=applyStackingRules(modifiers??[]),breakdown.push(...modifiers.filter(m=>m.enabled).map(m=>`${m.label} ${signedInteger(m.modifier)}`))}const hasDamage=typeof damage=="number"?damage!==0:damage.total!==0,notes=(()=>hasDamage?extractNotes(contextClone.synthetics.rollNotes,[domain]).filter(n=>(!outcome||n.outcome.length===0||n.outcome.includes(outcome))&&n.predicate.test(applicationRollOptions)).map(note=>note.text):[])();await contextClone.applyDamage({damage,token,item:message.item,skipIWR:multiplier<=0,rollOptions:applicationRollOptions,shieldBlockRequest,breakdown,notes})}toggleOffShieldBlock(message.id)}__name(applyDamageFromMessage,"applyDamageFromMessage"),__name2(applyDamageFromMessage,"applyDamageFromMessage");async function shiftAdjustDamage(message,multiplier,rollIndex){const content=await renderTemplate("systems/pf2e/templates/chat/damage/adjustment-dialog.hbs"),AdjustmentDialog=class extends Dialog{static{__name(this,"AdjustmentDialog")}static{__name2(this,"AdjustmentDialog")}activateListeners($html){super.activateListeners($html),$html[0].querySelector("input")?.focus()}},isHealing=multiplier<0;new AdjustmentDialog({title:game.i18n.localize(isHealing?"PF2E.UI.shiftModifyHealingTitle":"PF2E.UI.shiftModifyDamageTitle"),content,buttons:{ok:{label:game.i18n.localize("PF2E.OK"),callback:async $dialog=>{const adjustment=(Number($dialog[0].querySelector("input")?.value)||0)*Math.sign(multiplier);applyDamageFromMessage({message,multiplier,addend:adjustment,promptModifier:!1,rollIndex})}},cancel:{label:"Cancel"}},default:"ok",close:()=>{toggleOffShieldBlock(message.id)}}).render(!0)}__name(shiftAdjustDamage,"shiftAdjustDamage"),__name2(shiftAdjustDamage,"shiftAdjustDamage");function toggleOffShieldBlock(messageId){for(const app of["#chat-log","#chat-popout"]){const selector=`${app} > li.chat-message[data-message-id="${messageId}"] button[data-action=shield-block]`;htmlQuery(document.body,selector)?.classList.remove("shield-activated")}CONFIG.PF2E.chatDamageButtonShieldToggle=!1}__name(toggleOffShieldBlock,"toggleOffShieldBlock"),__name2(toggleOffShieldBlock,"toggleOffShieldBlock");function toggleClearTemplatesButton(message){if(!message||!canvas.ready)return;const selector=`li[data-message-id="${message.id}"] button[data-action=spell-template-clear]`;for(const chatLogDOM of htmlQueryAll(document.body,"#chat-log, #chat-popout")){const clearTemplatesButton=htmlQuery(chatLogDOM,selector);if(!clearTemplatesButton)continue;const hasMeasuredTemplates=!!canvas.scene?.templates.some(t=>t.message===message&&t.isOwner);clearTemplatesButton.classList.toggle("hidden",!hasMeasuredTemplates)}}__name(toggleClearTemplatesButton,"toggleClearTemplatesButton"),__name2(toggleClearTemplatesButton,"toggleClearTemplatesButton");const CanvasReady={listen:()=>{Hooks.once("canvasReady",async()=>{await game.pf2e.ConditionManager.initialize();const tokenActors=canvas.scene?.tokens.contents.flatMap(t=>t.actor??[])??[];for(const actor of tokenActors)for(const effect of actor.itemTypes.effect.filter(e=>e.fromAura))game.pf2e.effectTracker.register(effect)}),Hooks.on("canvasReady",()=>{if(game.pf2e.effectPanel.render(!0),!!canvas.scene){game.ready&&canvas.scene.reset(),CONFIG.MeasuredTemplate.defaults.angle=canvas.scene.hasHexGrid?60:90;for(const token of canvas.tokens.placeables.filter(t=>t.visible))token.renderFlags.set({redrawEffects:!0});for(const message of game.messages.contents.slice(-1*CONFIG.ChatMessage.batchSize/2))toggleClearTemplatesButton(message)}})}},CloseCombatTrackerConfig={listen:()=>{Hooks.on("closeCombatTrackerConfig",async(_app,$html)=>{const newIcon=String($html.find('input[name="deathIcon"]').val()).trim();newIcon&&newIcon!==game.settings.get("pf2e","deathIcon")&&await game.settings.set("pf2e","deathIcon",newIcon);const currentDeadAtZero=game.settings.get("pf2e","automation.actorsDeadAtZero"),newDeadAtZero=String($html.find('select[name="actorsDeadAtZero"]').val());currentDeadAtZero!==newDeadAtZero&&await game.settings.set("pf2e","automation.actorsDeadAtZero",newDeadAtZero)})}},CloseWorldClockSettings={listen:()=>{Hooks.on("closeWorldClockSettings",()=>{game.user.isGM&&game.socket.emit("system.pf2e",{request:"refreshSceneControls",data:{layer:"TokenLayer"}})})}},isDice3D=__name2(obj=>obj instanceof Object&&["addSystem","addDicePreset","addTexture","addColorset"].every(m=>m in obj),"isDice3D"),DiceSoNiceReady={listen:()=>{Hooks.once("diceSoNiceReady",dice3d=>{if(isDice3D(dice3d)){dice3d.addSystem({id:"basic",name:"Dicefinder Basic",colorset:"basic"});for(const faces of[4,6,8,10,12])dice3d.addDicePreset({type:`d${faces}`,labels:[...Array(faces)].map((_value,idx)=>String(idx+1)),system:"basic",colorset:"basic"});dice3d.addDicePreset({type:"d20",labels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","systems/pf2e/dice/basic/nat20.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"d100",labels:[...Array(10)].map((_value,idx)=>String((idx+1)*10)),system:"basic",colorset:"basic"}),dice3d.addDicePreset({type:"df",labels:["-","","+"],system:"basic",colorset:"basic"}),dice3d.addTexture("PFred",{name:"Pathfinder Red",composite:"source-over",source:"systems/pf2e/dice/texture/texture.webp"}).then(()=>{dice3d.addColorset({name:"basic",description:"Dicefinder Basic",category:"Pathfinder 2e",texture:"PFred",material:"metal",foreground:"#f9b96e",outline:"none",edge:"#f9b96e",visibility:"hidden"})}),dice3d.addSystem({id:"campaign",name:"Dicefinder Campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d4",labels:["systems/pf2e/dice/campaign/d4/d4-1.webp","systems/pf2e/dice/campaign/d4/d4-2.webp","systems/pf2e/dice/campaign/d4/d4-3.webp","systems/pf2e/dice/campaign/d4/d4-4.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d6",labels:["systems/pf2e/dice/campaign/d6/d6-1.webp","systems/pf2e/dice/campaign/d6/d6-2.webp","systems/pf2e/dice/campaign/d6/d6-3.webp","systems/pf2e/dice/campaign/d6/d6-4.webp","systems/pf2e/dice/campaign/d6/d6-5.webp","systems/pf2e/dice/campaign/d6/d6-6.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"df",labels:["systems/pf2e/dice/campaign/df/dfm.webp","systems/pf2e/dice/campaign/df/df.webp","systems/pf2e/dice/campaign/df/dfp.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d8",labels:["systems/pf2e/dice/campaign/d8/d8-1.webp","systems/pf2e/dice/campaign/d8/d8-2.webp","systems/pf2e/dice/campaign/d8/d8-3.webp","systems/pf2e/dice/campaign/d8/d8-4.webp","systems/pf2e/dice/campaign/d8/d8-5.webp","systems/pf2e/dice/campaign/d8/d8-6.webp","systems/pf2e/dice/campaign/d8/d8-7.webp","systems/pf2e/dice/campaign/d8/d8-P.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d10",labels:["systems/pf2e/dice/campaign/d10/d10-1.webp","systems/pf2e/dice/campaign/d10/d10-2.webp","systems/pf2e/dice/campaign/d10/d10-3.webp","systems/pf2e/dice/campaign/d10/d10-4.webp","systems/pf2e/dice/campaign/d10/d10-5.webp","systems/pf2e/dice/campaign/d10/d10-6.webp","systems/pf2e/dice/campaign/d10/d10-7.webp","systems/pf2e/dice/campaign/d10/d10-8.webp","systems/pf2e/dice/campaign/d10/d10-9.webp","systems/pf2e/dice/campaign/d10/d10-10.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d12",labels:["systems/pf2e/dice/campaign/d12/d12-1.webp","systems/pf2e/dice/campaign/d12/d12-2.webp","systems/pf2e/dice/campaign/d12/d12-3.webp","systems/pf2e/dice/campaign/d12/d12-4.webp","systems/pf2e/dice/campaign/d12/d12-5.webp","systems/pf2e/dice/campaign/d12/d12-6.webp","systems/pf2e/dice/campaign/d12/d12-7.webp","systems/pf2e/dice/campaign/d12/d12-8.webp","systems/pf2e/dice/campaign/d12/d12-9.webp","systems/pf2e/dice/campaign/d12/d12-10.webp","systems/pf2e/dice/campaign/d12/d12-11.webp","systems/pf2e/dice/campaign/d12/d12-12.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d100",labels:["systems/pf2e/dice/campaign/d100/d100-10.webp","systems/pf2e/dice/campaign/d100/d100-20.webp","systems/pf2e/dice/campaign/d100/d100-30.webp","systems/pf2e/dice/campaign/d100/d100-40.webp","systems/pf2e/dice/campaign/d100/d100-50.webp","systems/pf2e/dice/campaign/d100/d100-60.webp","systems/pf2e/dice/campaign/d100/d100-70.webp","systems/pf2e/dice/campaign/d100/d100-80.webp","systems/pf2e/dice/campaign/d100/d100-90.webp","systems/pf2e/dice/campaign/d100/d100-100.webp"],system:"campaign",colorset:"campaign"}),dice3d.addDicePreset({type:"d20",labels:["systems/pf2e/dice/campaign/d20/d20-1.webp","systems/pf2e/dice/campaign/d20/d20-2.webp","systems/pf2e/dice/campaign/d20/d20-3.webp","systems/pf2e/dice/campaign/d20/d20-4.webp","systems/pf2e/dice/campaign/d20/d20-5.webp","systems/pf2e/dice/campaign/d20/d20-6.webp","systems/pf2e/dice/campaign/d20/d20-7.webp","systems/pf2e/dice/campaign/d20/d20-8.webp","systems/pf2e/dice/campaign/d20/d20-9.webp","systems/pf2e/dice/campaign/d20/d20-10.webp","systems/pf2e/dice/campaign/d20/d20-11.webp","systems/pf2e/dice/campaign/d20/d20-12.webp","systems/pf2e/dice/campaign/d20/d20-13.webp","systems/pf2e/dice/campaign/d20/d20-14.webp","systems/pf2e/dice/campaign/d20/d20-15.webp","systems/pf2e/dice/campaign/d20/d20-16.webp","systems/pf2e/dice/campaign/d20/d20-17.webp","systems/pf2e/dice/campaign/d20/d20-18.webp","systems/pf2e/dice/campaign/d20/d20-19.webp","systems/pf2e/dice/campaign/d20/d20-20.webp"],system:"campaign",colorset:"campaign"}),dice3d.addTexture("stoneD4",{name:"Pathfinder Stone (D4)",composite:"source-over",source:"systems/pf2e/dice/texture/d4.webp"}).then(()=>{dice3d.addColorset({name:"campaign",description:"Dicefinder Campaign",category:"Pathfinder 2e",texture:"stoneD4",material:"stone",foreground:"#5c2f00",outline:"none",edge:"#f9b96e",visibility:"hidden"})}),dice3d.addSystem({id:"darkmode",name:"Dicefinder Dark Mode",colorset:"darkmode"});for(const faces of[4,6,8,10,12])dice3d.addDicePreset({type:`d${faces}`,labels:[...Array(faces)].map((_value,idx)=>String(idx+1)),system:"darkmode",colorset:"darkmode"});dice3d.addDicePreset({type:"d100",labels:[...Array(10)].map((_value,idx)=>String((idx+1)*10)),system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"df",labels:["-","","+"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"d20",labels:["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","systems/pf2e/dice/basic/nat20.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"dc",labels:["systems/pf2e/dice/basic/tail.webp","systems/pf2e/dice/basic/heads.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addDicePreset({type:"d2",labels:["systems/pf2e/dice/basic/tail_bump.webp","systems/pf2e/dice/basic/heads_bump.webp"],system:"darkmode",colorset:"darkmode"}),dice3d.addTexture("darkModeBlack",{name:"Dark Mode Black",composite:"source-over",source:"systems/pf2e/dice/texture/transparent.webp"}).then(()=>{dice3d.addColorset({name:"darkmode",description:"Dicefinder Dark Mode",category:"Pathfinder 2e",texture:"darkModeBlack",material:"metal",foreground:"#f9b96e",outline:"none",edge:"#f9b96e",visibility:"hidden"})})}})}},DropCanvasData={listen:()=>{Hooks.on("dropCanvasData",(_canvas,data)=>{const actor=[...canvas.tokens.placeables].sort((a,b)=>b.document.sort-a.document.sort).find(token=>{const maximumX=token.x+(token.hitArea?.right??0),maximumY=token.y+(token.hitArea?.bottom??0);return data.x>=token.x&&data.y>=token.y&&data.x<=maximumX&&data.y<=maximumY})?.actor;if(actor&&data.type==="Item")return actor.sheet.emulateItemDrop(data),!1;if(actor&&data.type==="PersistentDamage"&&"formula"in data){const instances=new DamageRoll(String(data.formula)).instances.filter(i=>i.persistent),baseConditionSource=game.pf2e.ConditionManager.getCondition("persistent-damage").toObject(),conditions=instances.map(i=>foundry.utils.mergeObject(baseConditionSource,{system:{persistent:{formula:i.head.expression,damageType:i.type,dc:15}}}));return actor.createEmbeddedDocuments("Item",conditions),!1}return!0})}},dayInSeconds=Duration.fromObject({hours:24}).as("seconds");function darknessLevelAtTime(time){const secondsElapsed=time.diff(time.startOf("day")).as("seconds"),radians=2*Math.PI*(secondsElapsed/dayInSeconds),lightnessLevel=-1*Math.cos(radians),rad18degrees=Math.toRadians(18);return 1-(lightnessLevel>0?1:lightnessLevel<-rad18degrees?0:Math.sin((lightnessLevel+rad18degrees)/rad18degrees*Math.PI/2))}__name(darknessLevelAtTime,"darknessLevelAtTime"),__name2(darknessLevelAtTime,"darknessLevelAtTime");function intervalToTransition(interval,compactInterval){const currentDarkness=canvas.darknessLevel,targetDarkness=interval.end?darknessLevelAtTime(interval.end):NaN,darknessDiff=Math.abs((currentDarkness??targetDarkness)-targetDarkness),proportionOfDay=compactInterval.length("seconds")/dayInSeconds,darkTimeMean=(darknessDiff*.5+proportionOfDay)/2;return{target:targetDarkness,duration:darkTimeMean*6e3,interval}}__name(intervalToTransition,"intervalToTransition"),__name2(intervalToTransition,"intervalToTransition");async function runAnimation(transition){if(!canvas.lighting||canvas.darknessLevel===transition.target)return;const duration=Math.min(Math.trunc(100*transition.duration)/100,6e3);await canvas.effects.animateDarkness(transition.target,{duration}),game.user.isGM&&await canvas.scene.update({darkness:transition.target})}__name(runAnimation,"runAnimation"),__name2(runAnimation,"runAnimation");async function animateDarkness(timeDiff){if(!this.syncDarkness)return;const newTime=this.worldTime,oldTime=newTime.minus({seconds:timeDiff}),fullInterval=Interval.fromDateTimes(oldTime,newTime);if(!fullInterval.isValid){await runAnimation({target:darknessLevelAtTime(newTime),duration:100,interval:fullInterval});return}const compactInterval=(()=>{if(fullInterval.length("hours")>24){const adjustedOldTime=newTime.minus({hours:24});return Interval.fromDateTimes(adjustedOldTime,newTime)}return fullInterval})(),transitionTimes=[4.75,18].map(hour=>compactInterval.start.set({hour,minute:0,second:0})).concat([4.75,18].map(hour=>compactInterval.end.set({hour,minute:0,second:0}))).filter(dateTime=>compactInterval.contains(dateTime)).concat([compactInterval.start,compactInterval.end]).sort((dtA,dtB)=>dtAdtB?1:0),transitions=transitionTimes.reduce((pairs,dateTime)=>{const index=transitionTimes.indexOf(dateTime);if(index===0)return[];const before=transitionTimes[index-1];return[...pairs,[before,dateTime]]},[]).map(pair=>Interval.fromDateTimes(pair[0],pair[1])).filter(interval=>interval.length()>0).map(interval=>intervalToTransition(interval,compactInterval));for(const transition of transitions)await runAnimation(transition)}__name(animateDarkness,"animateDarkness"),__name2(animateDarkness,"animateDarkness");var TimeChangeMode=(TimeChangeMode2=>(TimeChangeMode2[TimeChangeMode2.ADVANCE=0]="ADVANCE",TimeChangeMode2[TimeChangeMode2.RETRACT=1]="RETRACT",TimeChangeMode2))(TimeChangeMode||{});class TimeOfDay{static{__name(this,"TimeOfDay")}static{__name2(this,"TimeOfDay")}constructor(hour,minute,second){this.hour=hour,this.minute=minute,this.second=second}static DAWN=new TimeOfDay(4,58,54);static NOON=new TimeOfDay(12,0,0);static DUSK=new TimeOfDay(18,34,6);static MIDNIGHT=new TimeOfDay(0,0,0);diffSeconds(worldTime,mode){const targetTime=worldTime.set(this),targetDayDifference=TimeOfDay.diffDays(worldTime,targetTime,mode);return worldTime.plus({day:targetDayDifference}).set(this).diff(worldTime,"seconds").seconds}static diffDays(currentTime,targetTime,mode){return currentTime>=targetTime&&mode===0?1:currentTime<=targetTime&&mode===1?-1:0}}class WorldClock extends Application{static{__name(this,"WorldClock")}static{__name2(this,"WorldClock")}ctrlKeyDown=!1;animateDarkness=animateDarkness;constructor(){super();const settingValue=game.settings.get("pf2e","worldClock.worldCreatedOn"),defaultValue=game.settings.settings.get("pf2e.worldClock.worldCreatedOn")?.default;typeof settingValue=="string"&&settingValue===defaultValue?game.settings.set("pf2e","worldClock.worldCreatedOn",settingValue):DateTime.fromISO(settingValue).isValid||game.settings.set("pf2e","worldClock.worldCreatedOn",defaultValue)}get dateTheme(){return game.settings.get("pf2e","worldClock.dateTheme")}get timeConvention(){const setting=game.settings.get("pf2e","worldClock.timeConvention");if(setting!==24&&setting!==12)throw Error("PF2e System | Unrecognized time convention");return setting}get syncDarkness(){const sceneSetting=canvas.scene?.flags.pf2e.syncDarkness??"default";return{enabled:!0,disabled:!1,default:game.settings.get("pf2e","worldClock.syncDarkness")}[sceneSetting]}get worldCreatedOn(){const value=game.settings.get("pf2e","worldClock.worldCreatedOn");return DateTime.fromISO(value).toUTC()}get worldTime(){return this.worldCreatedOn.plus({seconds:game.time.worldTime})}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{id:"world-clock",width:400,template:"systems/pf2e/templates/system/world-clock.hbs",title:"PF2E.WorldClock.Title"})}get era(){switch(this.dateTheme){case"AR":return game.i18n.localize(CONFIG.PF2E.worldClock.AR.Era);case"AD":return this.worldTime.toFormat("G");default:return""}}get year(){const yearOffset=(()=>{switch(this.dateTheme){case"AR":return CONFIG.PF2E.worldClock.AR.yearOffset;case"AD":return CONFIG.PF2E.worldClock.AD.yearOffset;default:return 0}})();return this.worldTime.year+yearOffset}get month(){switch(this.dateTheme){case"AR":{const months=CONFIG.PF2E.worldClock.AR.Months,month=this.worldTime.setLocale("en-US").monthLong;return game.i18n.localize(months[month])}default:return this.worldTime.monthLong}}get weekday(){switch(this.dateTheme){case"AR":{const weekdays=CONFIG.PF2E.worldClock.AR.Weekdays,weekday=this.worldTime.setLocale("en-US").weekdayLong;return game.i18n.localize(weekdays[weekday])}default:return this.worldTime.weekdayLong}}getData(options){const date=this.dateTheme==="CE"?this.worldTime.toLocaleString(DateTime.DATE_HUGE):game.i18n.format(CONFIG.PF2E.worldClock.Date,{era:this.era,year:this.year,month:this.month,day:ordinalString(this.worldTime.day),weekday:this.weekday}),time=this.timeConvention===24?this.worldTime.toFormat("HH:mm:ss"):this.worldTime.toLocaleString(DateTime.TIME_WITH_SECONDS),sign=this.ctrlKeyDown?"-":"+";return{date,time,options,user:game.user,sign}}_getHeaderButtons(){return(game.user.isGM?[{label:"PF2E.SETTINGS.Settings",class:"configure-settings",icon:"fa-solid fa-cog",onclick:()=>{const menu=game.settings.menus.get("pf2e.worldClock");if(!menu)throw ErrorPF2e("PF2e System | World Clock Settings application not found");new menu.type().render(!0)}}]:[]).concat(...super._getHeaderButtons())}static calculateIncrement(wordTime,interval,intervalMode){const mode=intervalMode==="+"?TimeChangeMode.ADVANCE:TimeChangeMode.RETRACT;switch(interval){case"dawn":return TimeOfDay.DAWN.diffSeconds(wordTime,mode);case"noon":return TimeOfDay.NOON.diffSeconds(wordTime,mode);case"dusk":return TimeOfDay.DUSK.diffSeconds(wordTime,mode);case"midnight":return TimeOfDay.MIDNIGHT.diffSeconds(wordTime,mode);default:{const sign=mode===TimeChangeMode.ADVANCE?1:-1;return Number(interval)*sign}}}activateListeners($html){super.activateListeners($html),$html.find("button[data-advance-time]").on("click",event2=>{const $button=$(event2.currentTarget),advanceTime=$button.data("advanceTime")??"0",advanceMode=$button.data("advanceMode")??"+",increment=WorldClock.calculateIncrement(this.worldTime,advanceTime,advanceMode);increment!==0&&game.time.advance(increment)}),$html.find("button[name=advance], button[name=retract]").on("click",event2=>{const value=$html.find('input[type=number][name="diff-value"]').val(),unit=$html.find('select[name="diff-unit"]').val(),increment=($(event2.currentTarget).attr("name")==="advance"?1:-1)*Number(value)*Number(unit);game.time.advance(increment)});for(const eventName of["keydown.pf2e.world-clock","keyup.pf2e.world-clock"])$(document).off(eventName),$(document).on(eventName,event2=>{const{originalEvent}=event2;if(!(originalEvent instanceof KeyboardEvent))return;const ctrlKeys=KeyboardManager.CONTROL_KEY_STRING==="\u2318"?["Control","Meta"]:["Control"];if(originalEvent.repeat||!ctrlKeys.includes(originalEvent.key)||!(event2.ctrlKey||this.ctrlKeyDown))return;const retractTime=this.ctrlKeyDown=event2.type==="keydown",{Advance,Retract,TimeOfDay:TimeOfDay2}=CONFIG.PF2E.worldClock.Button,advanceButtons=Array.from($html.get(0)?.querySelectorAll("button[data-advance-time]")??[]);for(const button of advanceButtons){const{advanceMode,advanceTime}=button.dataset,nextMode=advanceMode==="+"?"-":"+";button.dataset.advanceMode=nextMode;const sign=button.querySelector(".sign");if(sign&&(sign.innerHTML=nextMode),tupleHasValue(["dawn","noon","dusk","midnight"],advanceTime)){const timeOfDayKeys=nextMode==="+"?TimeOfDay2.Advance:TimeOfDay2.Retract;button.title=timeOfDayKeys[advanceTime.titleCase()]}}$html.find("button[name=advance], button[name=retract]").attr("name",retractTime?"retract":"advance").text(game.i18n.localize(retractTime?Retract:Advance))})}async close(options){$(document).off("keydown.pf2e.world-clock").off("keyup.pf2e.world-clock"),await super.close(options)}static createSyncedMessage(){const managedBy=document.createElement("span");managedBy.classList.add("managed"),managedBy.innerHTML=" ".concat(game.i18n.localize("PF2E.SETTINGS.WorldClock.SyncDarknessScene.ManagedBy"));const anchor=document.createElement("a"),wtLink=managedBy.querySelector("wt");return anchor.innerText=wtLink?.innerHTML??"",anchor.setAttribute("href",""),anchor.addEventListener("click",event2=>{event2.preventDefault(),event2.stopPropagation();const menu=game.settings.menus.get("pf2e.worldClock");if(!menu)throw ErrorPF2e("World Clock Settings application not found");new menu.type().render(!0)}),wtLink?.replaceWith(anchor),managedBy}}class SceneDarknessAdjuster extends Application{static{__name(this,"SceneDarknessAdjuster")}static{__name2(this,"SceneDarknessAdjuster")}static instance=new this;#slider;#noRefreshHook=!1;static get defaultOptions(){return{...super.defaultOptions,id:"darkness-adjuster",title:"CONTROLS.AdjustSceneDarkness",template:"systems/pf2e/templates/system/scene-darkness-adjuster.hbs",width:400,height:45,minimizable:!1}}async getData(options={}){return{...await super.getData(options),darknessSyncedToTime:!!game.scenes.viewed?.darknessSyncedToTime}}async render(force=!1,options={}){if(!game.scenes.viewed)return this;const bounds=ui.controls.element[0]?.querySelector("li[data-tool=darkness-adjuster]")?.getBoundingClientRect();return bounds?(options.left=bounds.right+6,options.top=bounds.top-3,this.rendered?super.render(force,options):(await super.render(force,options),await $("#darkness-adjuster").hide(0).fadeIn().promise(),this)):this}async close(options){return this.rendered?(await $("#darkness-adjuster").fadeOut().promise(),super.close(options)):super.close(options)}activateListeners($html){if(!game.scenes.viewed)return;const slider=$html[0].querySelector(".slider");if(this.#slider=noUiSlider.create(slider,{range:{min:0,max:1},start:[.25,game.scenes.viewed.darkness,.75],connect:[!0,!1,!1,!0],behaviour:"snap-unconstrained-snap",pips:{mode:PipsMode.Range,density:5},step:.05}),game.scenes.viewed?.darknessSyncedToTime){const synchronized=document.createElement("div");synchronized.className="message";const message=WorldClock.createSyncedMessage();synchronized.append(message),slider.append(synchronized)}slider.querySelectorAll(".noUi-origin").forEach((thumb,index)=>{index!==1&&$(thumb).attr({disabled:"disabled"}),game.scenes.viewed?.darknessSyncedToTime&&thumb.setAttribute("disabled","true")}),this.#slider.on("slide",(values,thumbNumber)=>{thumbNumber===1&&canvas.scene&&(this.#noRefreshHook=!0,canvas.colorManager.initialize({darknessLevel:Number(values[1])}),canvas.app.ticker.add(()=>{this.#noRefreshHook=!1}))}),this.#slider.on("change",async(values,thumbNumber)=>{if(canvas.scene&&thumbNumber===1){const newValue=Number(values[1]);await canvas.scene.update({darkness:newValue},{animateDarkness:Math.round(5e3*Math.abs(canvas.scene.darkness-newValue))})}}),slider.querySelectorAll(".noUi-handle").forEach((handle,index)=>{const decoration={0:["threshold_bright-light",fontAwesomeIcon("sun")],1:["darkness-level",null],2:["threshold_darkness",fontAwesomeIcon("moon",{fixedWidth:!0})]},$handle=$(handle),[cssClass,icon]=decoration[index];icon&&$handle.append(icon),$handle.addClass(cssClass)}),slider.querySelectorAll(".noUi-connect").forEach((connect,index)=>{const classes={0:"range_bright-light",1:"range_darkness"};connect.classList.add(classes[index])})}onLightingRefresh(darkness){if(!this.rendered||this.#noRefreshHook)return;const sliderValues=this.#slider?.get();if(this.#slider&&Array.isArray(sliderValues)){const currentValue=sliderValues[1],stepValue=Math.round(darkness*20)/20;stepValue!==currentValue&&(sliderValues[1]=stepValue,this.#slider.set(sliderValues))}}}const GetSceneControlButtons={listen:()=>{Hooks.on("getSceneControlButtons",controls=>{controls.find(c=>c.name==="token")?.tools?.push({name:"worldclock",title:"CONTROLS.WorldClock",icon:"fa-solid fa-clock",button:!0,visible:game.settings.get("pf2e","worldClock.showClockButton")&&(game.user.isGM||game.settings.get("pf2e","worldClock.playersCanView")),onClick:()=>{game.pf2e.worldClock.rendered?game.pf2e.worldClock.close({force:!0}):game.pf2e.worldClock.render(!0)}});const lightingControls=controls.find(c=>c.name==="lighting"),lightingTools=lightingControls?.tools,dayTool=lightingTools?.find(tool=>tool.name==="day");if(!(lightingControls&&lightingTools&&dayTool))return;lightingControls.visible&&SceneDarknessAdjuster.instance.rendered&&SceneDarknessAdjuster.instance.close({force:!0});const adjusterTool={name:"darkness-adjuster",title:"CONTROLS.AdjustSceneDarkness",icon:"fa-solid fa-adjust",visible:game.user.isGM&&game.pf2e.settings.rbv,toggle:!0,active:!1,onClick:()=>{const adjuster=SceneDarknessAdjuster.instance;adjuster.rendered?adjuster.close({force:!0}):adjuster.render(!0)}},gmVisionTool=(()=>{const binding=game.keybindings.actions.get("pf2e.gm-vision")?.editable?.[0];if(!(binding&&game.user.isGM))return null;const gmVisionLabel=game.i18n.localize("PF2E.Keybinding.GMVision.Label"),bindingLabel=KeybindingsConfig._humanizeBinding(binding),gmVisionIcon=__name2((active=game.settings.get("pf2e","gmVision"))=>active?"fa-solid fa-lightbulb-cfl-on":"fa-solid fa-lightbulb-cfl","gmVisionIcon");return{name:"gm-vision",title:`${gmVisionLabel} [${bindingLabel}]`,icon:gmVisionIcon(),visible:game.user.isGM,toggle:!0,active:game.settings.get("pf2e","gmVision"),onClick:()=>{const newStatus=!game.settings.get("pf2e","gmVision");game.settings.set("pf2e","gmVision",newStatus);const toggle=ui.controls.control?.tools.find(t=>t.name==="gm-vision");toggle&&(toggle.active=newStatus,toggle.icon=gmVisionIcon(newStatus),ui.controls.render())}}})(),tools=[adjusterTool,gmVisionTool??[]].flat();lightingTools.splice(lightingTools?.indexOf(dayTool),0,...tools)})}},I18nInit={listen:()=>{Hooks.once("i18nInit",()=>{new HomebrewElements().onInit()})}};class HotbarPF2e extends Hotbar{static{__name(this,"HotbarPF2e")}static{__name2(this,"HotbarPF2e")}async _onDrop(event2){const li=htmlClosest(event2.target,".macro"),slot=Number(li?.dataset.slot)||null;if(!slot)return;const data=TextEditor.getDragEventData(event2);if(!["Item","RollOption","Skill","Action"].includes(data.type??""))return super._onDrop(event2);if(Hooks.call("hotbarDrop",this,data,slot)!==!1)switch(data.type==="Item"&&data.itemType==="melee"&&typeof data.index=="number"&&(data.type="Action"),data.type){case"Item":{const itemId=data.id??(isObject(data.data)?data.data._id:null),uuid=data.uuid,prefix=typeof data.pack=="string"?`Compendium.${data.pack}`:typeof data.actorId=="string"?`Actor.${data.actorId}.Item`:"Item",item=await fromUuid(uuid??`${prefix}.${itemId}`);if(!(item instanceof ItemPF2e))return;if(item.isOfType("condition","effect"))return createToggleEffectMacro(item,slot);if(uuid?.startsWith("Compendium.")){ui.notifications.error("PF2E.Macro.NoCompendiumItem",{localize:!0});return}else return HotbarPF2e.#createItemMacro(item,slot)}case"RollOption":{const item=fromUuidSync(data.uuid??"");if(!(item instanceof ItemPF2e&&item.isEmbedded))throw ErrorPF2e("Unexpected error during macro creation");return this.#hasRollOptionData(data)?HotbarPF2e.#createRollOptionToggleMacro({...data,item},slot):void 0}case"Skill":{if(!(data.actorId&&setHasElement(SKILL_ABBREVIATIONS,data.skill)))return;const skillName=data.skillName??game.i18n.localize(CONFIG.PF2E.skills[data.skill]);return createSkillMacro(data.skill,skillName,data.actorId,slot)}case"Action":return typeof data.index!="number"&&!data.elementTrait?void 0:createActionMacro({actorUUID:data.actorUUID,actionIndex:data.index,slot,elementTrait:data.elementTrait})}}#hasRollOptionData(data){const{label,domain,option}=data;return typeof label=="string"&&label.length>0&&typeof domain=="string"&&domain.length>0&&typeof option=="string"&&option.length>0}static async#createItemMacro(item,slot){const command=`game.pf2e.rollItemMacro("${item.id}");`,macro=game.macros.find(m=>m.name===item.name&&m.command===command)??await MacroPF2e.create({command,name:item.name,type:"script",img:item.img,flags:{pf2e:{itemMacro:!0}}},{renderSheet:!1});game.user.assignHotbarMacro(macro??null,slot)}static async#createRollOptionToggleMacro(data,slot){const name2=game.i18n.format("PF2E.ToggleWithName",{property:data.label}),escapedName=new Handlebars.SafeString(data.label),{item,domain,option}=data,command=`const item = fromUuidSync("${item.uuid}");
if (!(item instanceof Item && item.isEmbedded && item.isOwner)) {
ui.notifications.error("PF2E.MacroActionNoActorError", { localize: true });
}
@@ -312,11 +1652,68 @@ const state = game.i18n.localize(result ? "PF2E.Macro.OptionToggle.On" : "PF2E.M
const message = game.i18n.format("PF2E.Macro.OptionToggle.Notification", { toggle: "${escapedName}", state });
if (typeof result === "boolean") {
ui.notifications.info(message);
-}`,toggleMacro=game.macros.find(m=>m.name===name2&&m.command===command)??await MacroPF2e.create({type:"script",name:name2,img:item.img,command},{renderSheet:!1})??null;await game.user.assignHotbarMacro(toggleMacro,slot)},"#createRollOptionToggleMacro"),__privateAdd(_HotbarPF2e,_createItemMacro),__privateAdd(_HotbarPF2e,_createRollOptionToggleMacro),__name2(_HotbarPF2e,"HotbarPF2e");let HotbarPF2e=_HotbarPF2e;const _ActorDirectoryPF2e=class extends ActorDirectory{static{__name(this,"_ActorDirectoryPF2e")}constructor(){super(...arguments),__privateAdd(this,_onDragHighlightFolderLike),__privateAdd(this,_appendBrowseButton),__privateAdd(this,_extraFolders,{}),__privateAdd(this,_renderedOnce,!1),__privateAdd(this,_draggingParty,!1)}static get defaultOptions(){const options=super.defaultOptions;return options.renderUpdateKeys.push("system.details.level.value","system.attributes.adjustment","system.details.members","system.campaign.type"),options}async getData(){const activeParty=game.actors.party;__privateGet(this,_renderedOnce)||(activeParty&&game.settings.get("pf2e","activePartyFolderState")&&(__privateGet(this,_extraFolders)[activeParty.id]=!0),__privateSet(this,_renderedOnce,!0));const parties=sortBy$1(this.documents.filter(a=>a instanceof PartyPF2e&&a!==activeParty),p=>p.sort);return{...await super.getData(),activeParty,parties,placePartiesInSubfolder:parties.length>1,extraFolders:__privateGet(this,_extraFolders)}}saveActivePartyFolderState(){game.settings.set("pf2e","activePartyFolderState",__privateGet(this,_extraFolders)[game.actors.party?.id??""]??!0)}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const element of htmlQueryAll(html,"li.directory-item.actor"))game.actors.get(element.dataset.documentId??"")?.testUserPermission(game.user,"OBSERVER")||element.querySelector("span.actor-level")?.remove();for(const folderLike of htmlQueryAll(html,".folder-like")){const header=htmlQuery(folderLike,":scope > header");if(!header)continue;for(const eventType of["dragenter","dragleave","dragend"])folderLike.addEventListener(eventType,event=>{__privateMethod(this,_onDragHighlightFolderLike,onDragHighlightFolderLike_fn).call(this,folderLike,event)});header.addEventListener("click",event=>{const folderEl=htmlClosest(event.target,".folder-like"),entryId=htmlClosest(event.target,"[data-entry-id]")?.dataset.entryId??"";folderEl&&entryId&&(event.stopPropagation(),__privateGet(this,_extraFolders)[entryId]=folderEl.classList.contains("collapsed"),folderEl.classList.toggle("collapsed",!__privateGet(this,_extraFolders)[entryId]),this.popOut&&this.setPosition(),this.saveActivePartyFolderState())});const openSheetLink=htmlQuery(header,"a[data-action=open-sheet]");openSheetLink?.addEventListener("click",event=>{event.stopPropagation();const documentId=htmlClosest(openSheetLink,"[data-document-id]")?.dataset.documentId;game.actors.get(documentId??"")?.sheet.render(!0)});const createMemberLink=htmlQuery(header,"a[data-action=create-member]");createMemberLink?.addEventListener("click",async event=>{event.preventDefault(),event.stopPropagation();const documentId=htmlClosest(createMemberLink,"[data-document-id]")?.dataset.documentId,party=game.actors.get(documentId??"");if(!(party instanceof PartyPF2e))return;const button=event.currentTarget,actor=await ActorPF2e.createDialog({},{width:320,left:window.innerWidth-630,top:button?.offsetTop??0,types:["creature"]});actor?.isOfType("creature")&&(__privateGet(this,_extraFolders)[party.id]=!0,await party.addMembers(actor))});const createPartyLink=htmlQuery(header,"a[data-action=create-party]");createPartyLink?.addEventListener("click",async event=>{event.stopPropagation(),(await PartyPF2e.create({type:"party",name:"New Party"}))?.sheet.render(!0);const entryId=htmlClosest(createPartyLink,".folder-like")?.dataset.entryId;entryId&&(__privateGet(this,_extraFolders)[entryId]=!0,this.render())});const activatePartyLink=htmlQuery(header,"a[data-action=activate-party]");activatePartyLink?.addEventListener("click",event=>{event.stopPropagation();const documentId=htmlClosest(activatePartyLink,"[data-document-id]")?.dataset.documentId??"";game.actors.has(documentId)&&(game.settings.set("pf2e","activeParty",documentId),this.saveActivePartyFolderState())})}__privateMethod(this,_appendBrowseButton,appendBrowseButton_fn).call(this,html)}_onSearchFilter(event,query,rgx,html){super._onSearchFilter(event,query,rgx,html);const folderLikes=htmlQueryAll(html,".folder-like");for(const folderLike of folderLikes)if(query!==""&&htmlQueryAll(folderLike,".actor").some(li=>li.style.display!=="none")){folderLike.removeAttribute("style"),folderLike.classList.remove("collapsed");const folderLikeHeader=htmlQuery(folderLike,":scope > header");folderLikeHeader&&folderLikeHeader.removeAttribute("style")}else{const entryId=folderLike.dataset.entryId??"";folderLike.classList.toggle("collapsed",!__privateGet(this,_extraFolders)[entryId])}}_onDragStart(event){if(event.target.dataset.entryId==="otherParties"){event.preventDefault();return}super._onDragStart(event);const fromParty=htmlClosest(event.target,".party")?.dataset.documentId;if(fromParty){const data=JSON.parse(event.dataTransfer.getData("text/plain"));data.fromParty=fromParty,__privateSet(this,_draggingParty,fromUuidSync(data.uuid)instanceof PartyPF2e),event.dataTransfer.setData("text/plain",JSON.stringify(data))}else __privateSet(this,_draggingParty,!1)}_onDragHighlight(event){if(event.type==="dragenter"&&__privateGet(this,_draggingParty))return event.stopPropagation();super._onDragHighlight(event)}async _handleDroppedEntry(target,data){await super._handleDroppedEntry(target,data);const toPartyId=htmlClosest(target,".party")?.dataset.documentId;if(toPartyId!==data.fromParty&&data.uuid){const toParty=game.actors.get(toPartyId??""),fromParty=game.actors.get(data.fromParty??""),actor=fromUuidSync(data.uuid);fromParty instanceof PartyPF2e&&await fromParty.removeMembers(data.uuid),toParty instanceof PartyPF2e&&actor instanceof CreaturePF2e&&await toParty.addMembers(actor)}}async _renderInner(data){const $element=await super._renderInner(data);if(game.actors.some(a=>a.isOfType("party"))){const partyHTML=await renderTemplate("systems/pf2e/templates/sidebar/party-document-partial.hbs",data);$element.find(".directory-list").prepend(partyHTML);for(const header of htmlQueryAll($element.get(0),".party")){const party=game.actors.get(header.dataset.documentId??""),sidebarButtons=party?.isOfType("party")?party.campaign?.createSidebarButtons?.()??[]:[];header.querySelector("header h3")?.after(...sidebarButtons)}}return $element}async _render(force,context={}){return context=deepClone(context),context.action==="update"&&context.documentType==="Actor"&&context.data&&(context.data=context.data.map(d=>({...d,...flattenObject(d)}))),super._render(force,context)}_contextMenu($html){super._contextMenu($html),ContextMenu.create(this,$html,".party .party-header",this._getPartyContextOptions())}_getEntryContextOptions(){const options=super._getEntryContextOptions();return options.push({name:"PF2E.Actor.Party.Sidebar.RemoveMember",icon:'',condition:$li=>$li.closest(".party").length>0&&!$li.closest(".party-header").length,callback:$li=>{const actorId=$li.data("document-id"),partyId=$li.closest(".party").data("document-id"),actor=game.actors.get(actorId??""),party=game.actors.get(partyId??"");actor instanceof ActorPF2e&&party instanceof PartyPF2e&&party.removeMembers(actor.uuid)}}),options}_getPartyContextOptions(){const allOptions=super._getEntryContextOptions(),relevantNames=["SIDEBAR.CharArt","SIDEBAR.TokenArt","OWNERSHIP.Configure","SIDEBAR.Delete"],relevantOptions=allOptions.filter(o=>relevantNames.includes(o.name));return relevantOptions.length!==relevantNames.length&&console.error("PF2E System | Failed to extract all sidebar options from the base options"),relevantOptions}};_extraFolders=new WeakMap,_renderedOnce=new WeakMap,_draggingParty=new WeakMap,_onDragHighlightFolderLike=new WeakSet,onDragHighlightFolderLike_fn=__name2(function(folderLike,event){event.stopPropagation(),!__privateGet(this,_draggingParty)&&(event.type==="dragleave"&&document.elementFromPoint(event.clientX,event.clientY)?.closest(".folder-like")===folderLike||folderLike?.classList.toggle("droptarget",event.type==="dragenter"))},"#onDragHighlightFolderLike"),_appendBrowseButton=new WeakSet,appendBrowseButton_fn=__name2(function(html){if(!game.user.isGM)return;const browseButton=document.createElement("button");browseButton.type="button",browseButton.append(fontAwesomeIcon("search",{fixedWidth:!0})," ",game.i18n.localize("PF2E.CompendiumBrowser.BestiaryBrowser")),browseButton.addEventListener("click",()=>{game.pf2e.compendiumBrowser.openTab("bestiary")}),htmlQuery(html,"footer.directory-footer")?.append(browseButton)},"#appendBrowseButton"),__name2(_ActorDirectoryPF2e,"ActorDirectoryPF2e"),__publicField(_ActorDirectoryPF2e,"entryPartial","systems/pf2e/templates/sidebar/actor-document-partial.hbs");let ActorDirectoryPF2e=_ActorDirectoryPF2e;const _ItemDirectoryPF2e=class extends ItemDirectory{static{__name(this,"_ItemDirectoryPF2e")}constructor(){super(...arguments),__privateAdd(this,_appendBrowseButton2)}static get defaultOptions(){const options=super.defaultOptions;return options.renderUpdateKeys.push("system.level.value"),options}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const element of htmlQueryAll(html,"li.directory-item.item"))game.items.get(element.dataset.documentId??"")?.testUserPermission(game.user,"OBSERVER")||element.querySelector("span.item-level")?.remove();__privateMethod(this,_appendBrowseButton2,appendBrowseButton_fn2).call(this,html)}async _render(force,context={}){return context=deepClone(context),context.action==="update"&&context.documentType==="Item"&&context.data&&(context.data=context.data.map(d=>({...d,...flattenObject(d)}))),super._render(force,context)}};_appendBrowseButton2=new WeakSet,appendBrowseButton_fn2=__name2(function(html){const browseButton=document.createElement("button");browseButton.type="button",browseButton.append(fontAwesomeIcon("search",{fixedWidth:!0})," ",game.i18n.localize("PF2E.CompendiumBrowser.Title")),browseButton.addEventListener("click",()=>{game.pf2e.compendiumBrowser.render(!0,{focus:!0})}),htmlQuery(html,"footer.directory-footer")?.append(browseButton)},"#appendBrowseButton"),__name2(_ItemDirectoryPF2e,"ItemDirectoryPF2e"),__publicField(_ItemDirectoryPF2e,"entryPartial","systems/pf2e/templates/sidebar/item-document-partial.hbs");let ItemDirectoryPF2e=_ItemDirectoryPF2e;async function handleKingdomChatMessageEvents(options){const{event,message}=options,party=message.actor??game.actors.party;if(!(!party?.isOfType("party")||!(party?.campaign instanceof Kingdom))&&htmlClosest(event.target,"[data-action=kingdom-collect]")){if(!party.isOwner)return;await party.campaign.collect();const content=createHTMLElement("div",{innerHTML:message.content});htmlQuery(content,"[data-action=kingdom-collect]")?.replaceWith(createHTMLElement("div",{classes:["confirmation"],children:[fontAwesomeIcon("fa-check"),"Resources Collected"]})),message.update({content:content.innerHTML})}}__name(handleKingdomChatMessageEvents,"handleKingdomChatMessageEvents"),__name2(handleKingdomChatMessageEvents,"handleKingdomChatMessageEvents");const _ChatLogPF2e=class _ChatLogPF2e2 extends ChatLog{static{__name(this,"_ChatLogPF2e")}constructor(){super(...arguments),__privateAdd(this,_onClickDamageButton),__privateAdd(this,_onClickRevertDamage),__privateAdd(this,_onClickShieldBlock),__privateAdd(this,_onClickSender)}activateListeners($html){super.activateListeners($html);const html=$html[0],log=htmlQuery(html,"#chat-log");log&&(log.dataset.tooltipDirection="UP"),this.activateClickListener(html),html.addEventListener("dblclick",async event=>{var _a;const{message}=__privateMethod(_a=_ChatLogPF2e2,_messageFromEvent,messageFromEvent_fn).call(_a,event);if((message?htmlClosest(event.target,".message-sender"):null)&&message)return __privateMethod(this,_onClickSender,onClickSender_fn).call(this,message,event)})}activateClickListener(html){html.addEventListener("click",async event=>{var _a;const{message,element:messageEl}=__privateMethod(_a=_ChatLogPF2e2,_messageFromEvent,messageFromEvent_fn).call(_a,event);if((message?htmlClosest(event.target,".message-sender"):null)&&message)return __privateMethod(this,_onClickSender,onClickSender_fn).call(this,message,event);if(message?.isDamageRoll){const button=htmlClosest(event.target,"button");if(!button)return;if(button.dataset.action==="shield-block")return __privateMethod(this,_onClickShieldBlock,onClickShieldBlock_fn).call(this,button,messageEl);const actions=["apply-healing","half-damage","apply-damage","double-damage","triple-damage"];for(const action2 of actions)if(button.dataset.action===action2){const index=htmlClosest(button,".damage-application")?.dataset.rollIndex;return __privateMethod(this,_onClickDamageButton,onClickDamageButton_fn).call(this,message,action2,event.shiftKey,index)}}const revertDamageButton=htmlClosest(event.target,"button[data-action=revert-damage]");if(revertDamageButton){const appliedDamageFlag=message?.flags.pf2e.appliedDamage;appliedDamageFlag&&await __privateMethod(this,_onClickRevertDamage,onClickRevertDamage_fn).call(this,appliedDamageFlag)&&(htmlQuery(messageEl,"span.statements")?.classList.add("reverted"),revertDamageButton.remove(),await message.update({"flags.pf2e.appliedDamage.isReverted":!0,content:htmlQuery(messageEl,".message-content")?.innerHTML??message.content}))}message&&messageEl&&handleKingdomChatMessageEvents({event,message,messageEl})})}async _processDiceCommand(command,matches,chatData,createOptions){const rollData=(ChatMessage.getSpeakerActor(chatData.speaker??{})||game.user.character)?.getRollData()??{},rolls=[];for(const match of matches.filter(m=>!!m)){const[formula,flavor]=match.slice(2,4);flavor&&!chatData.flavor&&(chatData.flavor=flavor);const roll=(()=>{try{const damageRoll=new DamageRoll(formula,rollData);return looksLikeDamageRoll(damageRoll)?damageRoll:new Roll(formula,rollData)}catch{return new Roll(formula,rollData)}})();rolls.push(await roll.evaluate({async:!0}))}chatData.type=CONST.CHAT_MESSAGE_TYPES.ROLL,chatData.rolls=rolls.map(r=>r.toJSON()),chatData.sound=CONFIG.sounds.dice,chatData.content=rolls.reduce((t,r)=>t+r.total,0).toString(),createOptions.rollMode=objectHasKey(CONFIG.Dice.rollModes,command)?command:"roll"}_getEntryContextOptions(){const canApplyDamage=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});return canvas.tokens.controlled.length>0&&message.rolls.some(r=>r instanceof DamageRoll)},"canApplyDamage"),canApplyTripleDamage=__name2($li=>canApplyDamage($li)&&game.settings.get("pf2e","critFumbleButtons"),"canApplyTripleDamage"),canApplyInitiative=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),validActor=message.token?.actor?.type==="npc"&&(message.token.combatant?.initiative??null)===null,validRollType=message.isRoll&&message.isCheckRoll;return validActor&&validRollType},"canApplyInitiative"),canReroll=__name2($li=>game.messages.get($li[0].dataset.messageId,{strict:!0}).isRerollable,"canReroll"),canHeroPointReroll=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),{actor}=message;return message.isRerollable&&!!actor?.isOfType("character")&&actor.heroPoints.value>0},"canHeroPointReroll"),canShowRollDetails=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});return game.user.isGM&&!!message.flags.pf2e.context},"canShowRollDetails"),options=super._getEntryContextOptions();return options.push({name:"PF2E.ChatRollDetails.Select",icon:fontAwesomeIcon("search").outerHTML,condition:canShowRollDetails,callback:$li=>{game.messages.get($li[0].dataset.messageId,{strict:!0}).showDetails()}},{name:"PF2E.DamageButton.FullContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message})}},{name:"PF2E.DamageButton.HalfContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:.5})}},{name:"PF2E.DamageButton.DoubleContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:2})}},{name:"PF2E.DamageButton.TripleContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyTripleDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:3})}},{name:"PF2E.DamageButton.HealingContext",icon:fontAwesomeIcon("heart").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:-1})}},{name:"PF2E.ClickToSetInitiativeContext",icon:fontAwesomeIcon("swords").outerHTML,condition:canApplyInitiative,callback:async $li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),{actor,token}=message;if(!token){ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:message.actor?.name??message.user?.name??""}));return}if(!actor)return;const combatant=await CombatantPF2e.fromActor(actor);if(!combatant)return;const value=message.rolls.at(0)?.total??0;await combatant.encounter.setInitiative(combatant.id,value),ui.notifications.info(game.i18n.format("PF2E.Encounter.InitiativeSet",{actor:actor.name,initiative:value}))}},{name:"PF2E.RerollMenu.HeroPoint",icon:fontAwesomeIcon("hospital-symbol").outerHTML,condition:canHeroPointReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{heroPoint:!0})}},{name:"PF2E.RerollMenu.KeepNew",icon:fontAwesomeIcon("dice").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message)}},{name:"PF2E.RerollMenu.KeepLower",icon:fontAwesomeIcon("dice-one").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{keep:"lower"})}},{name:"PF2E.RerollMenu.KeepHigher",icon:fontAwesomeIcon("dice-six").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{keep:"higher"})}}),options}};_messageFromEvent=new WeakSet,messageFromEvent_fn=__name2(function(event){const element=htmlClosest(event.target,"li[data-message-id]"),messageId=element?.dataset.messageId??"",message=game.messages.get(messageId);return element&&message?{element,message}:{element:null,message:null}},"#messageFromEvent"),_onClickDamageButton=new WeakSet,onClickDamageButton_fn=__name2(function(message,action2,shiftKey,index){const multiplier=(()=>{switch(action2){case"apply-healing":return-1;case"half-damage":return .5;case"apply-damage":return 1;case"double-damage":return 2;case"triple-damage":return 3}})();applyDamageFromMessage({message,multiplier,addend:0,promptModifier:shiftKey,rollIndex:Number(index)||0})},"#onClickDamageButton"),_onClickRevertDamage=new WeakSet,onClickRevertDamage_fn=__name2(async function(flag){const actorOrToken=fromUuidSync(flag.uuid),actor=actorOrToken instanceof ActorPF2e?actorOrToken:actorOrToken instanceof TokenDocumentPF2e?actorOrToken.actor:null;return actor?(await actor.undoDamage(flag),ui.notifications.info(game.i18n.format(`PF2E.RevertDamage.${flag.isHealing?"Healing":"Damage"}Message`,{actor:actor.name})),!0):!1},"#onClickRevertDamage"),_onClickShieldBlock=new WeakSet,onClickShieldBlock_fn=__name2(function(shieldButton,messageEl){const getTokens=__name2(()=>{const tokens=canvas.tokens.controlled.filter(token=>token.actor);return tokens.length||ui.notifications.error("PF2E.UI.errorTargetToken",{localize:!0}),tokens},"getTokens"),getNonBrokenShields=__name2(tokens=>tokens[0].actor.itemTypes.armor.filter(armor=>armor.isEquipped&&armor.isShield).filter(shield=>!shield.isBroken),"getNonBrokenShields");shieldButton.classList.contains("tooltipstered")||$(shieldButton).tooltipster({animation:"fade",trigger:"click",arrow:!1,content:$(messageEl).find("div.hover-content"),contentAsHTML:!0,contentCloning:!0,debug:!1,interactive:!0,side:["top"],theme:"crb-hover",functionBefore:()=>{const tokens=getTokens();if(!tokens.length)return!1;const nonBrokenShields=getNonBrokenShields(tokens),hasMultipleShields=tokens.length===1&&nonBrokenShields.length>1,shieldActivated=shieldButton.classList.contains("shield-activated");return hasMultipleShields&&!shieldActivated?!0:hasMultipleShields&&shieldButton.dataset.shieldId?(shieldButton.attributes.removeNamedItem("data-shield-id"),shieldButton.classList.remove("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!1,!0):(shieldButton.classList.toggle("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!CONFIG.PF2E.chatDamageButtonShieldToggle,!1)},functionFormat:(instance,_helper,$content)=>{const tokens=getTokens(),nonBrokenShields=getNonBrokenShields(tokens),multipleShields=tokens.length===1&&nonBrokenShields.length>1,shieldActivated=shieldButton.classList.contains("shield-activated");if(multipleShields&&!shieldActivated){const content=$content[0],listEl=htmlQuery(content,"ul.shield-options");if(!listEl)return $content;const shieldList=[];for(const shield of nonBrokenShields){const input=document.createElement("input");input.classList.add("data"),input.type="radio",input.name="shield-id",input.value=shield.id,input.addEventListener("click",()=>{shieldButton.dataset.shieldId=input.value,shieldButton.classList.add("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!0,instance.close()});const shieldName=document.createElement("span");shieldName.classList.add("label"),shieldName.innerHTML=shield.name;const hardness=document.createElement("span");hardness.classList.add("tag");const hardnessLabel=game.i18n.localize("PF2E.HardnessLabel");hardness.innerHTML=`${hardnessLabel}: ${shield.hardness}`;const itemLi=document.createElement("li");itemLi.classList.add("item"),itemLi.append(input,shieldName,hardness),shieldList.push(itemLi)}listEl.replaceChildren(...shieldList)}return $content}}).tooltipster("open")},"#onClickShieldBlock"),_onClickSender=new WeakSet,onClickSender_fn=__name2(function(message,event){if(!canvas)return;const token=message.token?.object;if(token?.isVisible&&token.isOwner&&(token.controlled?token.release():token.control({releaseOthers:!event.shiftKey}),event.type==="dblclick")){const scale=Math.max(1,canvas.stage.scale.x);canvas.animatePan({...token.center,scale,duration:1e3})}},"#onClickSender"),__privateAdd(_ChatLogPF2e,_messageFromEvent),__name2(_ChatLogPF2e,"ChatLogPF2e");let ChatLogPF2e=_ChatLogPF2e;const _CompendiumMigrationStatus=class extends Application{static{__name(this,"_CompendiumMigrationStatus")}compendium;static get defaultOptions(){const options=super.defaultOptions;return options.template="systems/pf2e/templates/system/compendium-migration-status.hbs",options.classes=["compendium-migration-status"],options.height="auto",options.title=game.i18n.localize("PF2E.CompendiumMigrationStatus.Title"),options}constructor(compendium){super(),this.compendium=compendium}get id(){return`compendium-info-${this.compendium.metadata.id}`}async getData(options){const index=await this.compendium.getIndex({fields:[randomID(),"system._migration","system.schema","data.schema"]}),schemaVersion=Math.min(...index.map(d=>{const system=d.system??d.data;return Number(system?._migration?.version??system?.schema?.version)})),foundryVersion=pipe(Object.entries(MigrationRunner.FOUNDRY_SCHEMA_VERSIONS),sortBy$1(([_,schema])=>schema),findLast(([_,schema])=>schemaVersion>=schema))?.[0]??game.i18n.localize("PF2E.CompendiumMigrationStatus.FoundryOld");return{...await super.getData(options),compendium:this.compendium,schemaVersion:Number.isNaN(schemaVersion)?game.i18n.localize("PF2E.CompendiumMigrationStatus.Invalid"):schemaVersion,foundryVersion,module:game.modules.get(this.compendium.metadata.packageName??""),updated:schemaVersion>=MigrationRunner.LATEST_SCHEMA_VERSION,size:index.contents.length}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"[data-action=migrate]")?.addEventListener("click",async()=>{await new MigrationRunner(MigrationList.constructFromVersion(null)).runCompendiumMigration(this.compendium),this.render(!0)})}};__name2(_CompendiumMigrationStatus,"CompendiumMigrationStatus");let CompendiumMigrationStatus=_CompendiumMigrationStatus;const _CompendiumDirectoryPF2e=class extends CompendiumDirectory{static{__name(this,"_CompendiumDirectoryPF2e")}constructor(){super(...arguments),__privateAdd(this,_dragPreview)}static get defaultOptions(){const options=super.defaultOptions;return options.dragDrop.push({dragSelector:"ol.document-matches > li.match"}),{...options,filters:[{inputSelector:"input[type=search]",contentSelector:"ol.directory-list"}],template:"systems/pf2e/templates/sidebar/compendium-directory.hbs"}}async getData(options){return{...await super.getData(options),searchContents:game.user.settings.searchPackContents}}activateListeners($html){super.activateListeners($html),$html[0].querySelector("footer > button")?.addEventListener("click",()=>{game.pf2e.compendiumBrowser.render(!0)})}_getEntryContextOptions(){const options=super._getEntryContextOptions();return options.push({name:"COMPENDIUM.MigrationStatus",icon:fontAwesomeIcon("info").outerHTML,condition:$li=>{const compendium=game.packs.get($li.data("pack"),{strict:!0}),actorOrItem=compendium.documentClass===CONFIG.Actor.documentClass||compendium.documentClass===CONFIG.Item.documentClass,isSystemCompendium=compendium.metadata.packageType==="system";return game.user.isGM&&actorOrItem&&!isSystemCompendium},callback:async $li=>{const compendium=game.packs.get($li.data("pack"),{strict:!0});new CompendiumMigrationStatus(compendium).render(!0)}}),options}_contextMenu($html){super._contextMenu($html),ContextMenu.create(this,$html,"ol.document-matches > li",[{name:"COMPENDIUM.ImportEntry",icon:fontAwesomeIcon("download").outerHTML,condition:$li=>{const{uuid}=$li.get(0)?.dataset??{};if(!uuid)throw ErrorPF2e("Unexpected missing uuid");return game.packs.get(fromUuidSync(uuid)?.pack??"",{strict:!0}).documentClass.canUserCreate(game.user)},callback:$li=>{const{uuid}=$li.get(0)?.dataset??{};if(!uuid)throw ErrorPF2e("Unexpected missing uuid");const packCollection=game.packs.get(fromUuidSync(uuid)?.pack??"",{strict:!0}),worldCollection=game.collections.get(packCollection.documentName,{strict:!0}),indexData=fromUuidSync(uuid)??{_id:""};if(!("_id"in indexData&&typeof indexData._id=="string"))throw ErrorPF2e("Unexpected missing document _id");return worldCollection.importFromCompendium(packCollection,indexData._id,{},{renderSheet:!0})}}])}_onSearchFilter(event,query,rgx,listElem){super._onSearchFilter(event,query,rgx,listElem);const html=this.element[0],docMatches=query.length>0?this.constructor.searchEngine.search(query):[],{activeFilters}=this,filteredMatches=this.activeFilters.length>0?docMatches.filter(m=>activeFilters.includes(m.documentType)):docMatches,matchTemplate=htmlQuery(html,".compendium-search-match");if(!matchTemplate)throw ErrorPF2e("Match template not found");const listElements=filteredMatches.map(match=>{const li=matchTemplate.content.firstElementChild.cloneNode(!0);li.dataset.uuid=match.uuid,li.dataset.score=match.score.toString();const thumbnail=li.querySelector("img");typeof match.img=="string"?thumbnail.src=game.pf2e.system.moduleArt.map.get(match.uuid)?.img??match.img:match.documentType==="JournalEntry"&&(thumbnail.src="icons/svg/book.svg"),li.addEventListener("click",async event2=>{event2.stopPropagation();const doc=await fromUuid(match.uuid);await doc?.sheet?.render(!0,{editable:doc.sheet.isEditable})});const anchor=li.querySelector("a");anchor.innerText=match.name;const details=li.querySelector("span"),systemType=["Actor","Item"].includes(match.documentType)?game.i18n.localize(`TYPES.${match.documentType}.${match.type}`):null;return details.innerText=systemType?`${systemType} (${match.packLabel})`:`(${match.packLabel})`,li}),matchesList=htmlQuery(html,"ol.document-matches");if(matchesList){matchesList.replaceChildren(...listElements);for(const dragDrop of this._dragDrop)dragDrop.bind(matchesList)}}_canDragStart(){return!0}_onDragStart(event){const dragElement=event.currentTarget,{uuid}=dragElement.dataset;if(!uuid)return super._onDragStart(event);const indexEntry=fromUuidSync(uuid);if(!indexEntry)throw ErrorPF2e("Unexpected error retrieving index data");document.querySelector("#pack-search-drag-preview")?.remove();const dragPreview=__privateGet(this,_dragPreview,dragPreview_get).cloneNode(!0),[img,title]=Array.from(dragPreview.childNodes);title.innerText=indexEntry.name??"",img.src="img"in indexEntry&&indexEntry.img?indexEntry.img:"icons/svg/book.svg",document.body.appendChild(dragPreview);const documentType=(()=>indexEntry instanceof foundry.abstract.Document?indexEntry.documentName:game.packs.get(indexEntry.pack??"")?.documentName??null)();documentType&&(event.dataTransfer.setDragImage(dragPreview,75,25),event.dataTransfer.setData("text/plain",JSON.stringify({type:documentType,uuid})))}compileSearchIndex(){console.debug("PF2e System | compiling search index");const packs=game.packs.filter(p=>p.index.size>0&&p.testUserPermission(game.user,"OBSERVER"));this.constructor.searchEngine.removeAll();for(const pack of packs){const contents=pack.index.map(i=>({...i,documentType:pack.metadata.type,packLabel:pack.metadata.label}));this.constructor.searchEngine.addAll(contents)}console.debug("PF2e System | Finished compiling search index")}};_dragPreview=new WeakSet,dragPreview_get=__name2(function(){const preview=document.createElement("div");preview.id="pack-search-drag-preview";const thumbnail=document.createElement("img"),title=document.createElement("h4");return preview.append(thumbnail,title),preview},"#dragPreview"),__name2(_CompendiumDirectoryPF2e,"CompendiumDirectoryPF2e"),__publicField(_CompendiumDirectoryPF2e,"STOP_WORDS",new Set(["of","th","the"])),__publicField(_CompendiumDirectoryPF2e,"searchEngine",new MiniSearch({fields:["name"],idField:"uuid",processTerm:t=>t.length>1&&!_CompendiumDirectoryPF2e.STOP_WORDS.has(t)?t.toLocaleLowerCase(game.i18n.lang):null,searchOptions:{combineWith:"AND",prefix:!0},storeFields:["uuid","img","name","type","documentType","packLabel"]}));let CompendiumDirectoryPF2e=_CompendiumDirectoryPF2e;const _EncounterTrackerPF2e=class extends CombatTracker{static{__name(this,"_EncounterTrackerPF2e")}constructor(){super(...arguments),__privateAdd(this,_onToggleTarget),__privateAdd(this,_onDropCombatant)}async _renderInner(data,options){const $html=await super._renderInner(data,options);if(!game.user.isGM)return $html;const metrics=this.viewed?.metrics;if(!metrics)return $html;const localize=localizer("PF2E.Encounter.Metrics"),threat=(()=>{const label=game.i18n.localize(`PF2E.Encounter.Budget.Threats.${metrics.threat}`),tooltip=localize("Budget",metrics.budget),tempContainer=createHTMLElement("div",{innerHTML:localize("Threat",{threat:label})});return TextEditorPF2e.convertXMLNode(tempContainer,"threat",{classes:["value",metrics.threat]}),{label:tempContainer.innerHTML,tooltip}})(),award=(()=>{const label=localize("Award.Label",{xp:metrics.award.xp}),numRecipients=metrics.award.recipients.length,tooltip=localize(numRecipients===1?"Award.Tooltip.Singular":numRecipients===4?"Award.Tooltip.Four":"Award.Tooltip.Plural",{xpPerFour:metrics.budget.spent,recipients:numRecipients});return{label,tooltip}})(),threatAward=parseHTML(await renderTemplate("systems/pf2e/templates/sidebar/encounter-tracker/threat-award.hbs",{threat,award})),html=$html[0];return htmlQuery(html,"nav.encounters")?.after(threatAward),$(html)}activateListeners($html){const html=$html[0],tracker=htmlQuery(html,"#combat-tracker");if(!tracker)throw ErrorPF2e("No tracker found");const encounter=this.viewed;if(!encounter)return super.activateListeners($html);const tokenSetsNameVisibility=game.settings.get("pf2e","metagame_tokenSetsNameVisibility"),allyColor=__name2(c=>c.actor?.hasPlayerOwner?CONFIG.Canvas.dispositionColors.PARTY:CONFIG.Canvas.dispositionColors.FRIENDLY,"allyColor"),combatantRows=htmlQueryAll(tracker,"li.combatant");for(const row of combatantRows){const combatantId=row.dataset.combatantId??"",combatant=encounter.combatants.get(combatantId,{strict:!0});if(row.dataset.initiative=String(combatant.initiative),combatant?.actor&&this.viewed?.combatant===combatant){const alliance=combatant.actor.alliance,dispositionColor=new foundry.utils.Color(alliance==="party"?allyColor(combatant):alliance==="opposition"?CONFIG.Canvas.dispositionColors.HOSTILE:CONFIG.Canvas.dispositionColors.NEUTRAL);row.style.background=dispositionColor.toRGBA(.1),row.style.borderColor=dispositionColor.toString()}const nameHeader=htmlQuery(row,".token-name h4");nameHeader.innerHTML=[createHTMLElement("span",{classes:["name"],children:[nameHeader.innerText]}).outerHTML,createHTMLElement("span",{classes:["users-targeting"]}).outerHTML].join("");for(const control of htmlQueryAll(row,"a.combatant-control")){const controlIcon=htmlQuery(control,"i");if(controlIcon&&(controlIcon.classList.remove("fas"),controlIcon.classList.add("fa-solid","fa-fw"),control.dataset.control==="pingCombatant"&&(controlIcon.classList.remove("fa-bullseye-arrow"),controlIcon.classList.add("fa-signal-stream"),game.scenes.viewed?.tokens.has(combatant.token?.id??"")))){const targetControl=createHTMLElement("a",{classes:["combatant-control"],dataset:{control:"toggleTarget",tooltip:"COMBAT.ToggleTargeting"},children:[fontAwesomeIcon("location-crosshairs",{style:"duotone",fixedWidth:!0})]});control.before(targetControl)}}if(this.refreshTargetDisplay(combatant),tokenSetsNameVisibility&&(!game.user.isGM&&!combatant.playersCanSeeName&&(htmlQuery(nameHeader,"span.name").innerText="",row.querySelector("img.token-image")?.removeAttribute("title")),game.user.isGM&&combatant.actor&&combatant.actor.alliance!=="party")){const toggleNameVisibility=document.createElement("a"),isActive=combatant.playersCanSeeName;toggleNameVisibility.classList.add(...["combatant-control",isActive?"active":[]].flat()),toggleNameVisibility.dataset.control="toggleNameVisibility",toggleNameVisibility.dataset.tooltip=game.i18n.localize(isActive?"PF2E.Encounter.HideName":"PF2E.Encounter.RevealName");const icon=fontAwesomeIcon("signature",{fixedWidth:!0});toggleNameVisibility.append(icon),row.querySelector('.combatant-controls a[data-control="toggleHidden"]')?.after(toggleNameVisibility),isActive||row.classList.add("hidden-name")}}if(game.user.isGM&&!game.modules.get("combat-enhancements")?.active){Sortable.create(tracker,{animation:200,dataIdAttr:"data-combatant-id",direction:"vertical",dragClass:"drag-preview",dragoverBubble:!0,easing:"cubic-bezier(1, 0, 0, 1)",ghostClass:"drag-gap",onEnd:event=>this.adjustFinalOrder(event),onUpdate:event=>__privateMethod(this,_onDropCombatant,onDropCombatant_fn).call(this,event)});for(const row of combatantRows)row.classList.add("gm-draggable")}super.activateListeners($html)}refreshTargetDisplay(combatantOrToken){if(!this.viewed||!canvas.ready)return;const{combatant,tokenDoc}=combatantAndTokenDoc(combatantOrToken);if(!(combatant?.encounter!==this.viewed||tokenDoc?.combatant!==combatant))for(const tracker of htmlQueryAll(document,"#combat, #combat-popout")){const combatantRow=htmlQuery(tracker,`li.combatant[data-combatant-id="${combatant?.id??null}"]`);if(!combatantRow)return;const usersTargetting=game.users.filter(u=>Array.from(u.targets).some(t=>t.document===tokenDoc)),userIndicators=usersTargetting.map(user=>{const icon=fontAwesomeIcon("location-crosshairs",{style:"duotone",fixedWidth:!0});return icon.style.color=user.color,icon}),targetingSection=htmlQuery(combatantRow,".users-targeting");targetingSection&&(targetingSection.innerHTML=userIndicators.map(i=>i.outerHTML).join(""),targetingSection.dataset.tooltip=game.i18n.format("COMBAT.TargetedBy",{list:localizeList(usersTargetting.map(u=>u.name),{conjunction:"and"})}));const targetControlIcon=htmlQuery(combatantRow,"a.combatant-control[data-control=toggleTarget]");usersTargetting.includes(game.user)?targetControlIcon?.classList.add("active"):targetControlIcon?.classList.remove("active")}}async _onCombatControl(event){const control=event.currentTarget.dataset.control;if((control==="rollNPC"||control==="rollAll")&&this.viewed){event.stopPropagation();const args=eventToRollParams(event,{type:"check"});await this.viewed[control]({...args,messageOptions:{rollMode:args.rollMode}})}else await super._onCombatControl(event)}async _onCombatantControl(event){if(event.stopPropagation(),!this.viewed)return;const control=event.currentTarget.dataset.control,li=event.currentTarget.closest(".combatant"),combatant=this.viewed.combatants.get(li?.dataset.combatantId??"",{strict:!0});switch(control){case"rollInitiative":{await this.viewed.rollInitiative([combatant.id],eventToRollParams(event,{type:"check"}));break}case"toggleTarget":return __privateMethod(this,_onToggleTarget,onToggleTarget_fn).call(this,combatant.token,event.originalEvent);case"toggleNameVisibility":return combatant.toggleNameVisibility();default:return super._onCombatantControl(event)}}_onToggleDefeatedStatus(combatant){return combatant.toggleDefeated()}setInitiativeFromDrop(newOrder,dropped){const aboveDropped=newOrder.find(c=>newOrder.indexOf(c)===newOrder.indexOf(dropped)-1),belowDropped=newOrder.find(c=>newOrder.indexOf(c)===newOrder.indexOf(dropped)+1),hasAboveAndBelow=!!aboveDropped&&!!belowDropped,hasAboveAndNoBelow=!!aboveDropped&&!belowDropped,hasBelowAndNoAbove=!aboveDropped&&!!belowDropped,aboveIsHigherThanBelow=hasAboveAndBelow&&belowDropped.initiativec.initiative===dropped.initiative);if(withSameInitiative.length>1)for(let priority=0;priority({id:c.id,value:c.initiative,overridePriority:c.overridePriority(c.initiative)})))}adjustFinalOrder(event){const row=event.item,tracker=this.element[0].querySelector("#combat-tracker");if(!tracker)throw ErrorPF2e("Unexpected failure to retriever tracker DOM element");const rows=Array.from(tracker.querySelectorAll("li.combatant")),[oldIndex,newIndex]=[event.oldIndex??0,event.newIndex??0],firstRowWithNoRoll=rows.find(row2=>Number.isNaN(Number(row2.dataset.initiative)));Number.isNaN(Number(row.dataset.initiative))?newIndex>oldIndex?tracker.insertBefore(row,rows[oldIndex]):tracker.insertBefore(row,rows[oldIndex+1]):firstRowWithNoRoll&&rows.indexOf(firstRowWithNoRoll)row.getAttribute("data-combatant-id")??"").map(id=>combat.combatants.get(id,{strict:!0})).filter(c=>typeof c.initiative=="number")}};_onToggleTarget=new WeakSet,onToggleTarget_fn=__name2(async function(tokenDoc,event){if(!tokenDoc)return;const isTargeted=Array.from(game.user.targets).some(t=>t.document===tokenDoc);if(!tokenDoc.object?.visible){ui.notifications.warn("COMBAT.PingInvisibleToken",{localize:!0});return}tokenDoc.object.setTarget(!isTargeted,{releaseOthers:!event?.shiftKey})},"#onToggleTarget"),_onDropCombatant=new WeakSet,onDropCombatant_fn=__name2(async function(event){this.validateDrop(event);const encounter=this.viewed;if(!encounter)return;const droppedId=event.item.getAttribute("data-combatant-id")??"",dropped=encounter.combatants.get(droppedId,{strict:!0});if(typeof dropped.initiative!="number"){ui.notifications.error(game.i18n.format("PF2E.Encounter.HasNoInitiativeScore",{actor:dropped.name}));return}const newOrder=this.getCombatantsFromDOM(),oldOrder=encounter.turns.filter(c=>c.initiative!==null);newOrder.every(c=>newOrder.indexOf(c)===oldOrder.indexOf(c))||(this.setInitiativeFromDrop(newOrder,dropped),await this.saveNewOrder(newOrder))},"#onDropCombatant"),__name2(_EncounterTrackerPF2e,"EncounterTrackerPF2e");let EncounterTrackerPF2e=_EncounterTrackerPF2e;const darkvision=new VisionMode({id:"darkvision",label:"VISION.ModeDarkvision",canvas:{shader:ColorAdjustmentsSamplerShader,uniforms:{enable:!0,contrast:0,saturation:-1,brightness:0}},lighting:{levels:{},background:{visibility:VisionMode.LIGHTING_VISIBILITY.REQUIRED}},vision:{darkness:{adaptive:!0},defaults:{attenuation:0,contrast:0,saturation:-1,brightness:.75,range:1/0}}}),_VisionDetectionMode=class extends DetectionModeBasicSight{static{__name(this,"_VisionDetectionMode")}constructor(){super({id:"basicSight",label:"DETECTION.BasicSight",type:DetectionMode.DETECTION_TYPES.SIGHT})}_canDetect(visionSource,target){return target instanceof PlaceableObject&&target.document.hidden||target instanceof TokenPF2e&&target.actor?.hasCondition("hidden","undetected","unnoticed")?!1:super._canDetect(visionSource,target)}_testRange(visionSource,mode,target,test){return mode.range>=canvas.dimensions.maxR||super._testRange(visionSource,mode,target,test)}};__name2(_VisionDetectionMode,"VisionDetectionMode");let VisionDetectionMode=_VisionDetectionMode;const _HearingDetectionMode=class extends DetectionMode{static{__name(this,"_HearingDetectionMode")}constructor(){super({id:"hearing",label:"PF2E.Actor.Creature.Sense.Type.Hearing",type:DetectionMode.DETECTION_TYPES.SOUND})}static getDetectionFilter(){const filter2=this._detectionFilter??=OutlineOverlayFilter.create({wave:!0,knockout:!1});return filter2.thickness=1,filter2}_canDetect(visionSource,target){return!(target instanceof TokenPF2e)||target.document.hidden||!target.actor?.emitsSound?!1:game.settings.get("pf2e","automation.rulesBasedVision")?target.actor?.hasCondition("undetected","unnoticed")?!1:!visionSource.object.actor?.hasCondition("deafened"):!0}_testLOS(visionSource,_mode,_target2,test){test.loh??=new Map;const hearingSource=visionSource.object.hearing,hasLOH=test.loh.get(hearingSource)??hearingSource.shape.contains(test.point.x,test.point.y);return test.loh.set(hearingSource,hasLOH),hasLOH}_testRange(visionSource,mode,target,test){return mode.range>=canvas.dimensions.maxR||super._testRange(visionSource,mode,target,test)}};__name2(_HearingDetectionMode,"HearingDetectionMode");let HearingDetectionMode=_HearingDetectionMode;const _DetectionModeTremorPF2e=class extends DetectionModeTremor{static{__name(this,"_DetectionModeTremorPF2e")}constructor(){super({id:"feelTremor",label:"DETECTION.FeelTremor",walls:!1,type:DetectionMode.DETECTION_TYPES.MOVE})}static getDetectionFilter(){const filter2=super.getDetectionFilter();return filter2.thickness=1,filter2}_canDetect(visionSource,target){return super._canDetect(visionSource,target)&&target instanceof TokenPF2e&&!target.document.hidden&&!target.actor?.isOfType("loot")&&!target.actor?.hasCondition("undetected","unnoticed")}};__name2(_DetectionModeTremorPF2e,"DetectionModeTremorPF2e");let DetectionModeTremorPF2e=_DetectionModeTremorPF2e;function setPerceptionModes(){CONFIG.Canvas.visionModes.darkvision=darkvision,CONFIG.Canvas.detectionModes.basicSight=new VisionDetectionMode,CONFIG.Canvas.detectionModes.hearing=new HearingDetectionMode,CONFIG.Canvas.detectionModes.feelTremor=new DetectionModeTremorPF2e}__name(setPerceptionModes,"setPerceptionModes"),__name2(setPerceptionModes,"setPerceptionModes");const _JournalSheetPF2e=class extends JournalSheet{static{__name(this,"_JournalSheetPF2e")}static get theme(){return null}static get defaultOptions(){const options=super.defaultOptions,{theme}=this;return theme&&options.classes.push(theme),options}};__name2(_JournalSheetPF2e,"JournalSheetPF2e");let JournalSheetPF2e=_JournalSheetPF2e;const _JournalTextTinyMCESheetPF2e=class extends JournalTextTinyMCESheet{static{__name(this,"_JournalTextTinyMCESheetPF2e")}async activateEditor(name2,options={},initialContent=""){const editor=await super.activateEditor(name2,options,initialContent),theme=this.object.parent?.sheet.constructor?.theme;return editor.contentDocument.documentElement.classList.add("journal-entry-page","text"),editor.contentDocument.body.classList.add("journal-page-content"),theme&&editor.contentDocument.documentElement.classList.add(theme),editor}};__name2(_JournalTextTinyMCESheetPF2e,"JournalTextTinyMCESheetPF2e");let JournalTextTinyMCESheetPF2e=_JournalTextTinyMCESheetPF2e;const actorTypes={character:"TYPES.Actor.character",familiar:"TYPES.Actor.familiar",hazard:"TYPES.Actor.hazard",loot:"TYPES.Actor.loot",npc:"TYPES.Actor.npc",party:"TYPES.Actor.party",vehicle:"TYPES.Actor.vehicle"},abilities={str:"PF2E.AbilityStr",dex:"PF2E.AbilityDex",con:"PF2E.AbilityCon",int:"PF2E.AbilityInt",wis:"PF2E.AbilityWis",cha:"PF2E.AbilityCha"},senses={darkvision:"PF2E.Actor.Creature.Sense.Type.Darkvision",echolocation:"PF2E.Actor.Creature.Sense.Type.Echolocation",greaterDarkvision:"PF2E.Actor.Creature.Sense.Type.GreaterDarkvision",heatsight:"PF2E.Actor.Creature.Sense.Type.Heatsight",lifesense:"PF2E.Actor.Creature.Sense.Type.Lifesense",lowLightVision:"PF2E.Actor.Creature.Sense.Type.LowLightVision",motionsense:"PF2E.Actor.Creature.Sense.Type.Motionsense",scent:"PF2E.Actor.Creature.Sense.Type.Scent",seeInvisibility:"PF2E.Actor.Creature.Sense.Type.SeeInvisibility",spiritsense:"PF2E.Actor.Creature.Sense.Type.Spiritsense",thoughtsense:"PF2E.Actor.Creature.Sense.Type.Thoughtsense",tremorsense:"PF2E.Actor.Creature.Sense.Type.Tremorsense",wavesense:"PF2E.Actor.Creature.Sense.Type.Wavesense"},senseAcuity={imprecise:"PF2E.Actor.Creature.Sense.Acuity.Imprecise",precise:"PF2E.Actor.Creature.Sense.Acuity.Precise",vague:"PF2E.Actor.Creature.Sense.Acuity.Vague"},tokenHUDConditions={blinded:"PF2E.ConditionTypeBlinded",broken:"PF2E.ConditionTypeBroken",clumsy:"PF2E.ConditionTypeClumsy",concealed:"PF2E.ConditionTypeConcealed",confused:"PF2E.ConditionTypeConfused",controlled:"PF2E.ConditionTypeControlled",dazzled:"PF2E.ConditionTypeDazzled",deafened:"PF2E.ConditionTypeDeafened",doomed:"PF2E.ConditionTypeDoomed",drained:"PF2E.ConditionTypeDrained",dying:"PF2E.ConditionTypeDying",encumbered:"PF2E.ConditionTypeEncumbered",enfeebled:"PF2E.ConditionTypeEnfeebled",fascinated:"PF2E.ConditionTypeFascinated",fatigued:"PF2E.ConditionTypeFatigued",fleeing:"PF2E.ConditionTypeFleeing",frightened:"PF2E.ConditionTypeFrightened",grabbed:"PF2E.ConditionTypeGrabbed",hidden:"PF2E.ConditionTypeHidden",immobilized:"PF2E.ConditionTypeImmobilized",invisible:"PF2E.ConditionTypeInvisible","off-guard":"PF2E.ConditionTypeOffGuard",paralyzed:"PF2E.ConditionTypeParalyzed","persistent-damage":"PF2E.ConditionTypePersistent",petrified:"PF2E.ConditionTypePetrified",prone:"PF2E.ConditionTypeProne",quickened:"PF2E.ConditionTypeQuickened",restrained:"PF2E.ConditionTypeRestrained",sickened:"PF2E.ConditionTypeSickened",slowed:"PF2E.ConditionTypeSlowed",stunned:"PF2E.ConditionTypeStunned",stupefied:"PF2E.ConditionTypeStupefied",unconscious:"PF2E.ConditionTypeUnconscious",undetected:"PF2E.ConditionTypeUndetected",wounded:"PF2E.ConditionTypeWounded"},conditionTypes={...tokenHUDConditions,friendly:"PF2E.ConditionTypeFriendly",helpful:"PF2E.ConditionTypeHelpful",hostile:"PF2E.ConditionTypeHostile",indifferent:"PF2E.ConditionTypeIndifferent",malevolence:"PF2E.ConditionTypeMalevolence",observed:"PF2E.ConditionTypeObserved",unfriendly:"PF2E.ConditionTypeUnfriendly",unnoticed:"PF2E.ConditionTypeUnnoticed"},weaponCategories={simple:"PF2E.WeaponTypeSimple",martial:"PF2E.WeaponTypeMartial",advanced:"PF2E.WeaponTypeAdvanced",unarmed:"PF2E.WeaponTypeUnarmed"},baseArmorTypes=mapValues$1({"armored-cloak":"Armored Cloak","armored-coat":"Armored Coat","bastion-plate":"Bastion Plate",breastplate:"Breastplate","buckle-armor":"Buckle Armor","ceramic-plate":"Ceramic Plate","chain-mail":"Chain Mail","chain-shirt":"Chain Shirt","coral-armor":"Coral Armor","explorers-clothing":"Explorer's Clothing","fortress-plate":"Fortress Plate","full-plate":"Full Plate",gi:"Gi","half-plate":"Half Plate","hellknight-breastplate":"Hellknight Breastplate","hellknight-half-plate":"Hellknight Half Plate","hellknight-plate":"Hellknight Plate","hide-armor":"Hide Armor","lamellar-breastplate":"Lamellar Breastplate","lattice-armor":"Lattice Armor","leaf-weave":"Leaf Weave","leather-armor":"Leather Armor","leather-lamellar":"Leather Lamellar","mantis-shell":"Mantis Shell",niyahaat:"Niyah\xE1at","o-yoroi":"O-Yoroi","padded-armor":"Padded Armor","power-suit":"Power Suit","quilted-armor":"Quilted Armor",sankeit:"Sankeit","scale-mail":"Scale Mail","scroll-robes":"Scroll Robes","splint-mail":"Splint Mail","studded-leather-armor":"Studded Leather Armor","subterfuge-suit":"Subterfuge Suit","wooden-breastplate":"Wooden Breastplate"},(_v,slug)=>`PF2E.Item.Armor.Base.${slug}`),baseWeaponTypes=mapValues$1({adze:"Adze","air-repeater":"Air Repeater",aklys:"Aklys","alchemical-bomb":"Alchemical Bomb","alchemical-crossbow":"Alchemical Crossbow","aldori-dueling-sword":"Aldori Dueling Sword",arbalest:"Arbalest",arquebus:"Arquebus","asp-coil":"Asp Coil",atlatl:"Atlatl","axe-musket":"Axe Musket","barricade-buster":"Barricade Buster","bastard-sword":"Bastard Sword","battle-axe":"Battle Axe","battle-lute":"Battle Lute","battle-saddle":"Battle Saddle","bec-de-corbin":"Bec de Corbin","big-boom-gun":"Big Boom Gun","black-powder-knuckle-dusters":"Black Powder Knuckle Dusters","bladed-diabolo":"Bladed Diabolo","bladed-gauntlet":"Bladed Gauntlet","bladed-hoop":"Bladed Hoop","bladed-scarf":"Bladed Scarf",blowgun:"Blowgun","blowgun-darts":"Blowgun Darts",blunderbuss:"Blunderbuss","bo-staff":"Bo Staff","boarding-axe":"Boarding Axe","boarding-pike":"Boarding Pike",bola:"Bola",boomerang:"Boomerang","bow-staff":"Bow Staff","breaching-pike":"Breaching Pike",broadspear:"Broadspear","butchering-axe":"Butchering Axe","butterfly-sword":"Butterfly Sword",buugeng:"Buugeng","cane-pistol":"Cane Pistol","chain-sword":"Chain Sword",chakram:"Chakram",chakri:"Chakri","clan-dagger":"Clan Dagger","clan-pistol":"Clan Pistol",claw:"Claw","claw-blade":"Claw Blade",club:"Club","coat-pistol":"Coat Pistol","combat-grapnel":"Combat Grapnel","combat-lure":"Combat Lure","composite-longbow":"Composite Longbow","composite-shortbow":"Composite Shortbow","corset-knife":"Corset Knife","crescent-cross":"Crescent Cross",crossbow:"Crossbow",dagger:"Dagger","dagger-pistol":"Dagger Pistol",daikyu:"Daikyu","dancers-spear":"Dancer's Spear",dandpatta:"Dandpatta",dart:"Dart",dogslicer:"Dogslicer",donchak:"Donchak","double-barreled-musket":"Double-Barreled Musket","double-barreled-pistol":"Double-Barreled Pistol","dragon-mouth-pistol":"Dragon Mouth Pistol","dueling-pistol":"Dueling Pistol","dueling-spear":"Dueling Spear","dwarven-dorn-dergar":"Dwarven Dorn-Dergar","dwarven-scattergun":"Dwarven Scattergun","dwarven-war-axe":"Dwarven War Axe",earthbreaker:"Earthbreaker","elven-branched-spear":"Elven Branched Spear","elven-curve-blade":"Elven Curve Blade","explosive-dogslicer":"Explosive Dogslicer","exquisite-sword-cane":"Exquisite Sword Cane","exquisite-sword-cane-sheath":"Exquisite Sword Cane Sheath",falcata:"Falcata",falchion:"Falchion",fangwire:"Fangwire",fauchard:"Fauchard","feng-huo-lun":"Feng Huo Lun","fighting-fan":"Fighting Fan","fighting-stick":"Fighting Stick","filchers-fork":"Filcher's Fork","fire-lance":"Fire Lance","fire-poi":"Fire Poi",fist:"Fist",flail:"Flail",flingflenser:"Flingflenser","flintlock-musket":"Flintlock Musket","flintlock-pistol":"Flintlock Pistol","flying-talon":"Flying Talon",flyssa:"Flyssa","forked-bipod":"Forked Bipod","frying-pan":"Frying Pan",gada:"Gada",gaff:"Gaff",gakgung:"Gakgung",gauntlet:"Gauntlet","gauntlet-bow":"Gauntlet Bow","gill-hook":"Gill Hook",glaive:"Glaive","gnome-amalgam-musket":"Gnome Amalgam Musket","gnome-flickmace":"Gnome Flickmace","gnome-hooked-hammer":"Gnome Hooked Hammer",greataxe:"Greataxe",greatclub:"Greatclub",greatpick:"Greatpick",greatsword:"Greatsword","griffon-cane":"Griffon Cane",guisarme:"Guisarme","gun-sword":"Gun Sword",halberd:"Halberd","halfling-sling-staff":"Halfling Sling Staff","hammer-gun":"Hammer Gun","hand-adze":"Hand Adze","hand-cannon":"Hand Cannon","hand-crossbow":"Hand Crossbow","harmona-gun":"Harmona Gun",harpoon:"Harpoon",hatchet:"Hatchet","heavy-crossbow":"Heavy Crossbow","hongali-hornbow":"Hongali Hornbow","hook-sword":"Hook Sword",horsechopper:"Horsechopper","injection-spear":"Injection Spear",javelin:"Javelin",jaws:"Jaws",jezail:"Jezail","jiu-huan-dao":"Jiu Huan Dao","juggling-club":"Juggling Club",kalis:"Kalis",kama:"Kama",karambit:"Karambit",katana:"Katana",katar:"Katar",khakkhara:"Khakkhara",khopesh:"Khopesh","knuckle-duster":"Knuckle Duster",kris:"Kris",kukri:"Kukri",kusarigama:"Kusarigama",lance:"Lance",lancer:"Lancer",leiomano:"Leiomano","light-hammer":"Light Hammer","light-mace":"Light Mace","light-pick":"Light Pick","lion-scythe":"Lion Scythe","long-air-repeater":"Long Air Repeater","long-hammer":"Long Hammer",longbow:"Longbow",longspear:"Longspear",longsword:"Longsword",mace:"Mace","mace-multipistol":"Mace Multipistol",machete:"Machete","main-gauche":"Main-Gauche",mambele:"Mambele",maul:"Maul","meteor-hammer":"Meteor Hammer",mikazuki:"Mikazuki","mithral-tree":"Mithral Tree","monkeys-fist":"Monkey's Fist",morningstar:"Morningstar",naginata:"Naginata",nightstick:"Nightstick","nine-ring-sword":"Nine-Ring Sword",nodachi:"Nodachi",nunchaku:"Nunchaku","ogre-hook":"Ogre Hook","orc-knuckle-dagger":"Orc Knuckle Dagger","orc-necksplitter":"Orc Necksplitter",panabas:"Panabas",pepperbox:"Pepperbox","phalanx-piercer":"Phalanx Piercer",pick:"Pick","piercing-wind":"Piercing Wind","piranha-kiss":"Piranha Kiss",poi:"Poi",polytool:"Polytool","probing-cane":"Probing Cane",ranseur:"Ranseur",rapier:"Rapier","rapier-pistol":"Rapier Pistol","reinforced-wheels":"Reinforced Wheels","repeating-crossbow":"Repeating Crossbow","repeating-hand-crossbow":"Repeating Hand Crossbow","repeating-heavy-crossbow":"Repeating Heavy Crossbow","rhoka-sword":"Rhoka Sword","rope-dart":"Rope Dart","rotary-bow":"Rotary Bow",rungu:"Rungu",sai:"Sai",sansetsukon:"Sansetsukon",sap:"Sap","sawtooth-saber":"Sawtooth Saber",scimitar:"Scimitar",scizore:"Scizore","scorpion-whip":"Scorpion Whip",scourge:"Scourge",scythe:"Scythe","shauth-lash":"Shauth Lash",shears:"Shears","shield-bash":"Shield Bash","shield-boss":"Shield Boss","shield-bow":"Shield Bow","shield-pistol":"Shield Pistol","shield-spikes":"Shield Spikes","shobhad-longrifle":"Shobhad Longrifle",shortbow:"Shortbow",shortsword:"Shortsword",shuriken:"Shuriken",sickle:"Sickle","sickle-saber":"Sickle-saber","slide-pistol":"Slide Pistol",sling:"Sling","sling-bullets":"Sling Bullets",spear:"Spear","spiked-chain":"Spiked Chain","spiked-gauntlet":"Spiked Gauntlet","spiral-rapier":"Spiral Rapier","spoon-gun":"Spoon Gun",spraysling:"Spraysling",staff:"Staff",starknife:"Starknife","stiletto-pen":"Stiletto Pen",sukgung:"Sukgung","sun-sling":"Sun Sling",switchscythe:"Switchscythe","sword-cane":"Sword Cane",talwar:"Talwar","tamchal-chakram":"Tamchal Chakram","taw-launcher":"Taw Launcher","tekko-kagi":"Tekko-kagi","temple-sword":"Temple Sword","tengu-gale-blade":"Tengu Gale Blade","thorn-whip":"Thorn whip","three-peaked-tree":"Three Peaked Tree","three-section-naginata":"Three-Section Naginata","throwing-knife":"Throwing Knife","thunder-sling":"Thunder Sling",thundermace:"Thundermace",tonfa:"Tonfa","tri-bladed-katar":"Tri-bladed Katar","tricky-pick":"Tricky Pick",trident:"Trident",triggerbrand:"Triggerbrand",urumi:"Urumi",visap:"Visap",wakizashi:"Wakizashi","war-flail":"War Flail","war-lance":"War Lance","war-razor":"War Razor",warhammer:"Warhammer","wheel-blades":"Wheel Blades","wheel-spikes":"Wheel Spikes",whip:"Whip","whip-claw":"Whip Claw","whip-staff":"Whip Staff","wish-blade":"Wish Blade","wish-knife":"Wish Knife","wooden-taws":"Wooden Taws",wrecker:"Wrecker","wrist-launcher":"Wrist Launcher",zulfikar:"Zulfikar"},(_v,slug)=>`PF2E.Weapon.Base.${slug}`),equivalentWeapons={"composite-longbow":"longbow","composite-shortbow":"shortbow","big-boom-gun":"hand-cannon","spoon-gun":"hand-cannon"},preciousMaterialGrades={low:"PF2E.PreciousMaterialLowGrade",standard:"PF2E.PreciousMaterialStandardGrade",high:"PF2E.PreciousMaterialHighGrade"},meleeWeaponGroups={axe:"PF2E.WeaponGroupAxe",brawling:"PF2E.WeaponGroupBrawling",club:"PF2E.WeaponGroupClub",dart:"PF2E.WeaponGroupDart",flail:"PF2E.WeaponGroupFlail",hammer:"PF2E.WeaponGroupHammer",knife:"PF2E.WeaponGroupKnife",pick:"PF2E.WeaponGroupPick",polearm:"PF2E.WeaponGroupPolearm",shield:"PF2E.WeaponGroupShield",spear:"PF2E.WeaponGroupSpear",sword:"PF2E.WeaponGroupSword"},weaponGroups={...meleeWeaponGroups,bomb:"PF2E.WeaponGroupBomb",bow:"PF2E.WeaponGroupBow",firearm:"PF2E.WeaponGroupFirearm",sling:"PF2E.WeaponGroupSling"},sizeTypes={tiny:"PF2E.ActorSizeTiny",sm:"PF2E.ActorSizeSmall",med:"PF2E.ActorSizeMedium",lg:"PF2E.ActorSizeLarge",huge:"PF2E.ActorSizeHuge",grg:"PF2E.ActorSizeGargantuan"},featCategories={ancestry:"PF2E.FeatTypeAncestry",ancestryfeature:"PF2E.FeatTypeAncestryfeature",class:"PF2E.FeatTypeClass",classfeature:"PF2E.FeatTypeClassfeature",skill:"PF2E.FeatTypeSkill",general:"PF2E.FeatTypeGeneral",bonus:"PF2E.FeatTypeBonus",pfsboon:"PF2E.FeatTypePfsboon",deityboon:"PF2E.FeatTypeDeityboon",curse:"PF2E.FeatTypeCurse"},creatureTypes=pick$1(creatureTraits,["aberration","animal","astral","beast","celestial","construct","dragon","dream","elemental","ethereal","fey","fiend","fungus","giant","humanoid","monitor","ooze","petitioner","plant","shadow","spirit","time","vitality","void","undead"]),alignments={LG:"PF2E.AlignmentLG",NG:"PF2E.AlignmentNG",CG:"PF2E.AlignmentCG",LN:"PF2E.AlignmentLN",N:"PF2E.AlignmentN",CN:"PF2E.AlignmentCN",LE:"PF2E.AlignmentLE",NE:"PF2E.AlignmentNE",CE:"PF2E.AlignmentCE"},deityDomains=mapToObj(Object.keys({Abomination:{Description:"You seek to instill abhorrence and horror in those around you.",Label:"Abomination"},Air:{Description:"You can control winds and the weather.",Label:"Air"},AirApocryphal:{Description:"You can control winds and the weather. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Air (apocryphal)"},Ambition:{Description:"You strive to keep up with and outpace the competition.",Label:"Ambition"},AmbitionApocryphal:{Description:"You strive to keep up with and outpace the competition. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Ambition (apocryphal)"},Change:{Description:"You can restructure the physical and metaphysical.",Label:"Change"},Cities:{Description:"You have powers over urban environments and denizens.",Label:"Cities"},Cold:{Description:"You control ice, snow, and freezing temperatures.",Label:"Cold"},Confidence:{Description:"You overcome your fear and project pride.",Label:"Confidence"},ConfidenceApocryphal:{Description:"You overcome your fear and project pride. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Confidence (apocryphal)"},Creation:{Description:"You have divine abilities related to crafting and art.",Label:"Creation"},Darkness:{Description:"You operate in the darkness and take away the light.",Label:"Darkness"},DarknessApocryphal:{Description:"You operate in the darkness and take away the light. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Darkness (apocryphal)"},Death:{Description:"You have the power to end lives and destroy undead.",Label:"Death"},DeathApocryphal:{Description:"You have the power to end lives and destroy undead. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Death (apocryphal)"},Decay:{Description:"You have the power to spoil and deteriorate matter.",Label:"Decay"},Delirium:{Description:"You can bring about hallucinations and restlessness.",Label:"Delirium"},Destruction:{Description:"You are a conduit for divine devastation.",Label:"Destruction"},Dreams:{Description:"You have the power to enter and manipulate dreams.",Label:"Dreams"},Dust:{Description:"You have the power to dry and crumble what opposes you.",Label:"Dust"},Duty:{Description:"You defend oaths and carry out your divine missions with great dedication.",Label:"Duty"},Earth:{Description:"You control soil and stone.",Label:"Earth"},Family:{Description:"You aid and protect your family and community more effectively.",Label:"Family"},Fate:{Description:"You see and understand hidden inevitabilities.",Label:"Fate"},FateApocryphal:{Description:"You see and understand hidden inevitabilities. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Fate (apocryphal)"},Fire:{Description:"You control flame.",Label:"Fire"},FireApocryphal:{Description:"You control flame. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Fire (apocryphal)"},Freedom:{Description:"You liberate yourself and others from shackles and constraints.",Label:"Freedom"},Glyph:{Description:"You wield power over written words and symbols.",Label:"Glyph"},Healing:{Description:"Your healing magic is particularly potent.",Label:"Healing"},Indulgence:{Description:"You feast mightily and can shake off the effects of overindulging.",Label:"Indulgence"},IndulgenceApocryphal:{Description:"You feast mightily and can shake off the effects of overindulging. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Indulgence (apocryphal)"},Introspection:{Description:"You guide others in examining their lives, emotions, and motivations to ultimately become a truer version of themselves\u2014a difficult and often painful process.",Label:"Introspection"},Knowledge:{Description:"You receive divine insights.",Label:"Knowledge"},KnowledgeApocryphal:{Description:"You receive divine insights. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Knowledge (apocryphal)"},Lightning:{Description:"You control electricity, thunder, and storms.",Label:"Lightning"},Luck:{Description:"You're unnaturally lucky and keep out of harm's way.",Label:"Luck"},Magic:{Description:"You perform the unexpected and inexplicable.",Label:"Magic"},Metal:{Description:"You manipulate flexible, mutable metal.",Label:"Metal"},Might:{Description:"Your physical power is bolstered by divine strength.",Label:"Might"},MightApocryphal:{Description:"Your physical power is bolstered by divine strength. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Might (apocryphal)"},Moon:{Description:"You command powers associated with the moon.",Label:"Moon"},Naga:{Description:"Like the serpentine nagas, you're in tune with cosmic forces that Ravithra once controlled.",Label:"Naga"},Nature:{Description:"You hold power over animals and plants.",Label:"Nature"},Nightmares:{Description:"You fill minds with horror and dread.",Label:"Nightmares"},Pain:{Description:"You punish those who displease you with the sharp sting of pain.",Label:"Pain"},Passion:{Description:"You evoke passion, whether as love or lust.",Label:"Passion"},Perfection:{Description:"You strive to perfect your mind, body, and spirit.",Label:"Perfection"},Plague:{Description:"You wield disease and pestilence like a weapon.",Label:"Plague"},Protection:{Description:"You ward yourself and others.",Label:"Protection"},Repose:{Description:"You ease mental burdens.",Label:"Repose"},Secrecy:{Description:"You protect secrets and keep them hidden.",Label:"Secrecy"},SecrecyApocryphal:{Description:"You protect secrets and keep them hidden. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Secrecy (apocryphal)"},Sorrow:{Description:"You have a painful connection to melancholy and sadness.",Label:"Sorrow"},Soul:{Description:"You wield power over the spiritual.",Label:"Soul"},Star:{Description:"You command the power of the stars.",Label:"Star"},Sun:{Description:"You harness the power of the sun and other light sources, and punish undead.",Label:"Sun"},Swarm:{Description:"You exert control over masses of creatures.",Label:"Swarm"},Time:{Description:"You reign over the flow of time.",Label:"Time"},Toil:{Description:"You work constantly and refuse to let anything stand in your way.",Label:"Toil"},Travel:{Description:"You have power over movement and journeys.",Label:"Travel"},TravelApocryphal:{Description:"You have power over movement and journeys. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Travel (apocryphal)"},Trickery:{Description:"You deceive others and cause mischief.",Label:"Trickery"},Truth:{Description:"You pierce lies and discover the truth.",Label:"Truth"},Tyranny:{Description:"You wield power to rule and enslave others.",Label:"Tyranny"},Undeath:{Description:"Your magic carries close ties to the undead.",Label:"Undeath"},Vigil:{Description:"You watch over those long passed and guard their secrets.",Label:"Vigil"},Void:{Description:"You draw power from emptiness.",Label:"Void"},Water:{Description:"You control water and bodies of water.",Label:"Water"},WaterApocryphal:{Description:"You control water and bodies of water. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Water (apocryphal)"},Wealth:{Description:"You hold power over wealth, trade, and treasure.",Label:"Wealth"},Wood:{Description:"You command the indomitable power of wood.",Label:"Wood"},Wyrmkin:{Description:"You draw on the power of dragons, linnorms, and other powerful reptilian creatures.",Label:"Wyrmkin"},Zeal:{Description:"Your inner fire increases your combat prowess.",Label:"Zeal"}}),key=>{const label=`PF2E.Item.Deity.Domain.${key}.Label`,description=`PF2E.Item.Deity.Domain.${key}.Description`;return[sluggify(key),{label,description}]}),weaponReload={"-":"\u2014",0:"0",1:"1",2:"2",3:"3",10:"PF2E.Item.Weapon.Reload.OneMinute"};function notifyDeprecatedPath(configPath,locPath){foundry.utils.logCompatibilityWarning(`CONFIG.PF2E.${configPath} is deprecated. Use localization path ${locPath} directly instead.`,{since:"5.2.0",until:"6.0.0"})}__name(notifyDeprecatedPath,"notifyDeprecatedPath"),__name2(notifyDeprecatedPath,"notifyDeprecatedPath");const PF2ECONFIG={defaultPartyId:"xxxPF2ExPARTYxxx",chatDamageButtonShieldToggle:!1,statusEffects:{lastIconTheme:"default",iconDir:"systems/pf2e/icons/conditions/",conditions:tokenHUDConditions},levels:{1:"PF2E.Level1",2:"PF2E.Level2",3:"PF2E.Level3",4:"PF2E.Level4",5:"PF2E.Level5",6:"PF2E.Level6",7:"PF2E.Level7",8:"PF2E.Level8",9:"PF2E.Level9",10:"PF2E.Level10",11:"PF2E.Level11",12:"PF2E.Level12",13:"PF2E.Level13",14:"PF2E.Level14",15:"PF2E.Level15",16:"PF2E.Level16",17:"PF2E.Level17",18:"PF2E.Level18",19:"PF2E.Level19",20:"PF2E.Level20"},abilities,attributes:{get perception(){const locPath="PF2E.PerceptionLabel";return notifyDeprecatedPath("attributes.perception",locPath),locPath},get stealth(){const locPath="PF2E.StealthLabel";return notifyDeprecatedPath("attributes.stealth",locPath),locPath},get initiative(){const locPath="PF2E.InitiativeLabel";return notifyDeprecatedPath("attributes.initiative",locPath),locPath}},dcAdjustments:{"incredibly-easy":"PF2E.DCAdjustmentIncrediblyEasy","very-easy":"PF2E.DCAdjustmentVeryEasy",easy:"PF2E.DCAdjustmentEasy",normal:"PF2E.DCAdjustmentNormal",hard:"PF2E.DCAdjustmentHard","very-hard":"PF2E.DCAdjustmentVeryHard","incredibly-hard":"PF2E.DCAdjustmentIncrediblyHard"},checkDCs:configFromLocalization({Label:{AdjustedTarget:"Target: {target} ({dcType} {preadjusted} {adjusted})",NoChangeTarget:"Target: {target} ({dcType} {adjusted})",NoTarget:"{dcType} {dc}",WithTarget:"Target: {target} ({dcType} {dc})"},Specific:{armor:"AC",athletics:"Athletics DC",deception:"Deception DC",fortitude:"Fortitude DC",perception:"Perception DC",reflex:"Reflex DC",stealth:"Stealth DC",will:"Will DC"},Unspecific:"DC"},"PF2E.Check.DC"),skills:{acr:"PF2E.SkillAcr",arc:"PF2E.SkillArc",ath:"PF2E.SkillAth",cra:"PF2E.SkillCra",dec:"PF2E.SkillDec",dip:"PF2E.SkillDip",itm:"PF2E.SkillItm",med:"PF2E.SkillMed",nat:"PF2E.SkillNat",occ:"PF2E.SkillOcc",prf:"PF2E.SkillPrf",rel:"PF2E.SkillRel",soc:"PF2E.SkillSoc",ste:"PF2E.SkillSte",sur:"PF2E.SkillSur",thi:"PF2E.SkillThi"},saves:{fortitude:"PF2E.SavesFortitude",reflex:"PF2E.SavesReflex",will:"PF2E.SavesWill"},savingThrowDefaultAttributes:{fortitude:"con",reflex:"dex",will:"wis"},currencies:{pp:"PF2E.CurrencyPP",gp:"PF2E.CurrencyGP",sp:"PF2E.CurrencySP",cp:"PF2E.CurrencyCP"},preciousMaterialGrades,preciousMaterials,accessoryPropertyRunes:{called:"PF2E.AccessoryPropertyRuneCalled",dragonsBreath:"PF2E.AccessoryPropertyRuneDragonsBreath",paired:"PF2E.AccessoryPropertyRunePaired",greaterPaired:"PF2E.AccessoryPropertyRuneGreaterPaired",majorPaired:"PF2E.AccessoryPropertyRuneMajorPaired",presentable:"PF2E.AccessoryPropertyRunePresentable",snagging:"PF2E.AccessoryPropertyRuneSnagging",softLanding:"PF2E.AccessoryPropertyRuneSoftLanding",spellBastion:"PF2E.AccessoryPropertyRuneSpellBastion",windCatcher:"PF2E.AccessoryPropertyRuneWindCatcher",greaterWindCatcher:"PF2E.AccessoryPropertyRuneGreaterWindCatcher"},damageTraits,damageTypes,damageRollFlavors,damageCategories,elementTraits,materialDamageEffects,resistanceTypes,stackGroups:{arrows:"PF2E.StackGroupArrows",blowgunDarts:"PF2E.StackGroupBlowgunDarts",bolts:"PF2E.StackGroupBolts",coins:"PF2E.StackGroupCoins",gems:"PF2E.StackGroupGems",rounds5:"PF2E.StackGroupRounds5",rounds10:"PF2E.StackGroupRounds10",rations:"PF2E.StackGroupRations",sacks:"PF2E.StackGroupSacks",slingBullets:"PF2E.StackGroupSlingBullets",sprayPellets:"PF2E.StackGroupSprayPellets",woodenTaws:"PF2E.StackGroupWoodenTaws"},weaknessTypes,weaponCategories,weaponGroups,meleeWeaponGroups,baseArmorTypes,baseWeaponTypes,equivalentWeapons,weaponDescriptions:{club:"PF2E.WeaponDescriptionClub",knife:"PF2E.WeaponDescriptionKnife",brawling:"PF2E.WeaponDescriptionBrawling",spear:"PF2E.WeaponDescriptionSpear",sword:"PF2E.WeaponDescriptionSword",axe:"PF2E.WeaponDescriptionAxe",flail:"PF2E.WeaponDescriptionFlail",polearm:"PF2E.WeaponDescriptionPolearm",pick:"PF2E.WeaponDescriptionPick",hammer:"PF2E.WeaponDescriptionHammer",shield:"PF2E.WeaponDescriptionShield",dart:"PF2E.WeaponDescriptionDart",bow:"PF2E.WeaponDescriptionBow",sling:"PF2E.WeaponDescriptionSling",bomb:"PF2E.WeaponDescriptionBomb"},usages:{"affixed-to-a-creature":"PF2E.TraitAffixedToCreature","affixed-to-a-magical-staff":"PF2E.TraitAffixedToMagicalStaff","affixed-to-a-ranged-weapon":"PF2E.TraitAffixedToARangedWeapon","affixed-to-a-shield":"PF2E.TraitAffixedToAShield","affixed-to-a-thrown-weapon":"PF2E.TraitAffixedToThrownWeapon","affixed-to-a-two-handed-firearm-or-crossbow":"PF2E.TraitAffixedToATwoHandedFirearmOrCrossbow","affixed-to-an-innovation":"PF2E.TraitAffixedToInnovation","affixed-to-an-object-or-structure":"PF2E.TraitAffixedToObjectOrStructure","affixed-to-armor":"PF2E.TraitAffixedToArmor","affixed-to-medium-heavy-armor":"PF2E.TraitAffixedToMediumHeavyArmor","affixed-to-medium-heavy-metal-armor":"PF2E.TraitAffixedToMediumHeavyMetalArmor","affixed-to-armor-or-a-weapon":"PF2E.TraitAffixedToArmorOrAWeapon","affixed-to-armor-or-travelers-clothing":"PF2E.TraitAffixedToArmorOrTravelersClothing","affixed-to-crossbow-or-firearm":"PF2E.TraitAffixedToCrossbowOrFirearm","affixed-to-firearm":"PF2E.TraitAffixedToFirearm","affixed-to-firearm-with-a-reload-of-1":"PF2E.TraitAffixedToFirearmWithAReloadOf1","affixed-to-firearm-with-the-kickback-trait":"PF2E.TraitAffixedToFirearmWithTheKickbackTrait","affixed-to-ground-in-10-foot-radius":"PF2E.TraitAffixedToGroundIn10FtRadius","affixed-to-ground-in-20-foot-radius":"PF2E.TraitAffixedToGroundIn20FtRadius","affixed-to-harness":"PF2E.TraitAffixedToHarness","affixed-to-headgear":"PF2E.TraitAffixedToHeadgear","affixed-to-instrument":"PF2E.TraitAffixedToInstrument","affixed-to-load-bearing-wall-or-pillar":"PF2E.TraitAffixedToLoadBearingWallOrPillar","affixed-to-melee-weapon":"PF2E.TraitAffixedToMeleeWeapon","affixed-to-object-structure-or-creature":"PF2E.TraitAffixedToStructureObjectOrCreature","affixed-to-the-ground":"PF2E.TraitAffixedToGround","affixed-to-unarmored-defense-item":"PF2E.TraitAffixedToUnarmoredItem","affixed-to-weapon":"PF2E.TraitAffixedToWeapon","applied-to-a-basket-bag-or-other-container":"PF2E.TraitAppliedToBasketBagOrContainer","applied-to-a-weapon":"PF2E.TraitAppliedToAWeapon","applied-to-a-wind-powered-vehicle":"PF2E.TraitAppliedToAWindPoweredVehicle","applied-to-a-non-injection-melee-weapon-piercing-damage":"PF2E.TraitAppliedToANoninjectionMeleePiercingWeapon","applied-to-any-item-of-light-or-negligible-bulk":"PF2E.TraitAppliedToAnyItemOfLightOrNegligibleBulk","applied-to-any-visible-article-of-clothing":"PF2E.TraitAppliedToAnyVisibleArticleOfClothing","applied-to-armor":"PF2E.TraitAppliedToArmor","applied-to-armor-or-unarmored-defense-clothing":"PF2E.TraitAppliedToArmorOrUnarmored","applied-to-belt-cape-cloak-or-scarf":"PF2E.TraitAppliedToBeltCapeCloakOrScarf","applied-to-boots-cape-cloak-or-umbrella":"PF2E.TraitAppliedToBootsCapeCloakOrUmbrella","applied-to-buckler-shield":"PF2E.TraitAppliedToBucklerShield","applied-to-dueling-cape-or-shield":"PF2E.TraitAppliedToDuelingCapeOrShield","applied-to-footwear":"PF2E.TraitAppliedToFootwear","applied-to-medium-heavy-armor":"PF2E.TraitAppliedToMediumHeavyArmor","applied-to-shield":"PF2E.TraitAppliedToShield","attached-to-a-thrown-weapon":"PF2E.TraitAttachedToAThrownWeapon","attached-to-crossbow-or-firearm":"PF2E.TraitAttachedToCrossbowOrFirearm","attached-to-crossbow-or-firearm-firing-mechanism":"PF2E.TraitAttachedToCrossbowOrFirearmFiringMechanism","attached-to-crossbow-or-firearm-scope":"PF2E.TraitAttachedToCrossbowOrFirearmScope","attached-to-firearm":"PF2E.TraitAttachedToFirearm","attached-to-firearm-scope":"PF2E.TraitAttachedToFirearmScope","attached-to-ships-bow":"PF2E.TraitAttachedToShipsBow",bonded:"PF2E.TraitBonded",carried:"PF2E.TraitCarried","each-rune-applied-to-a-separate-item-that-has-pockets":"PF2E.TraitEachRuneAppliedToASeparateItemThatHasPockets","etched-onto-a-weapon":"PF2E.TraitEtchedOntoAWeapon","etched-onto-armor":"PF2E.TraitEtchedOntoArmor","etched-onto-heavy-armor":"PF2E.TraitEtchedOntoHeavyArmor","etched-onto-light-armor":"PF2E.TraitEtchedOntoLightArmor","etched-onto-metal-armor":"PF2E.TraitEtchedOntoMetalArmor","etched-onto-clan-dagger":"PF2E.TraitEtchedOntoAClanDagger","etched-onto-lm-nonmetal-armor":"PF2E.TraitEtchedOntoLightMedNMArmor","etched-onto-med-heavy-armor":"PF2E.TraitEtchedOntoMedHeavyArmor","etched-onto-medium-heavy-metal-armor":"PF2E.TraitEtchedOntoMediumHeavyMetalArmor","etched-onto-bludgeoning-weapon":"PF2E.TraitEtchedOntoABludgeoningWeapon","etched-onto-melee-weapon":"PF2E.TraitEtchedOntoAMeleeWeapon","etched-onto-slashing-melee-weapon":"PF2E.TraitEtchedOntoASlashingMeleeWeapon","etched-onto-piercing-or-slashing-melee-weapon":"PF2E.TraitEtchedOntoAPiercingOrSlashingMeleeWeapon","etched-onto-piercing-or-slashing-weapon":"PF2E.TraitEtchedOntoAPiercingOrSlashingWeapon","etched-onto-weapon-wo-anarchic-rune":"PF2E.TraitEtchedOntoAWeaponWOAxiomaticRune","etched-onto-weapon-wo-axiomatic-rune":"PF2E.TraitEtchedOntoAWeaponWOAnarchicRune","etched-onto-weapon-wo-unholy-rune":"PF2E.TraitEtchedOntoAWeaponWOHolyRune","etched-onto-weapon-wo-holy-rune":"PF2E.TraitEtchedOntoAWeaponWOUnholyRune","etched-onto-melee-weapon-monk":"PF2E.TraitEtchedOntoAMeleeWeaponMonk","etched-onto-thrown-weapon":"PF2E.TraitEtchedOntoAThrownWeapon","held-in-one-hand":"PF2E.TraitHeldOneHand","held-in-one-hand-or-free-standing":"PF2E.TraitHeldOneHandFreeStanding","held-in-two-hands":"PF2E.TraitHeldTwoHands",other:"Other","sewn-into-clothing":"PF2E.TraitSewnIntoClothing","tattooed-on-the-body":"PF2E.TraitTattooedOnTheBody",touched:"PF2E.TraitTouched",worn:"PF2E.TraitWorn",wornamulet:"PF2E.TraitWornAmulet",wornanklets:"PF2E.TraitWornAnklets",wornarmbands:"PF2E.TraitWornArmbands",wornbackpack:"PF2E.TraitWornBackpack",wornbarding:"PF2E.TraitWornBarding",wornbelt:"PF2E.TraitWornBelt",wornbeltpouch:"PF2E.TraitWornBeltPouch",wornboots:"PF2E.TraitWornBoots",wornbracelet:"PF2E.TraitWornBracelet",wornbracers:"PF2E.TraitWornBracers",worncap:"PF2E.TraitWornCap",worncape:"PF2E.TraitWornCape",worncirclet:"PF2E.TraitWornCirclet",worncloak:"PF2E.TraitWornCloak",wornclothing:"PF2E.TraitWornClothing",worncollar:"PF2E.TraitWornCollar",worncrown:"PF2E.TraitWornCrown",wornepaulet:"PF2E.TraitWornEpaulet",worneyeglasses:"PF2E.TraitWornEyeglasses",worneyepiece:"PF2E.TraitWornEyepiece",wornfootwear:"PF2E.TraitWornFootwear",worngarment:"PF2E.TraitWornGarment",worngloves:"PF2E.TraitWornGloves",wornheadwear:"PF2E.TraitWornHeadwear",wornhorseshoes:"PF2E.TraitWornHorseshoes",wornmask:"PF2E.TraitWornMask",wornnecklace:"PF2E.TraitWornNecklace",wornonbelt:"PF2E.TraitWornOnBelt",wornoronehand:"PF2E.TraitWornOrOneHand",wornring:"PF2E.TraitWornRing",wornsaddle:"PF2E.TraitWornSaddle",wornsandles:"PF2E.TraitWornSandles",wornshoes:"PF2E.TraitWornShoes",wornwrist:"PF2E.TraitWornOnWrists","worn-and-attached-to-two-weapons":"PF2E.TraitWornAndAttachedToTwoWeapons","worn-under-armor":"PF2E.TraitWornUnderArmor"},rarityTraits:{common:"PF2E.TraitCommon",uncommon:"PF2E.TraitUncommon",rare:"PF2E.TraitRare",unique:"PF2E.TraitUnique"},magicTraditions,magicSchools,classTraits,ancestryTraits,ancestryItemTraits,deityDomains,weaponTraits,otherWeaponTags,armorTraits,otherArmorTags,equipmentTraits,consumableTraits,otherConsumableTags,actionTraits,spellTraits,featTraits,creatureTraits,kingmakerTraits,npcAttackTraits,hazardTraits,vehicleTraits,traitsDescriptions:traitDescriptions,creatureTypes,weaponHands:{1:"PF2E.WeaponHands1","1+":"PF2E.WeaponHands1Plus",2:"PF2E.WeaponHands2"},itemBonuses:{"-2":"PF2E.ItemBonusMinus2",0:"PF2E.ItemBonus0",1:"PF2E.ItemBonus1",2:"PF2E.ItemBonus2",3:"PF2E.ItemBonus3"},damageDice:{0:"0",1:"1",2:"2",3:"3",4:"4"},damageDie:{d4:"PF2E.DamageDieD4",d6:"PF2E.DamageDieD6",d8:"PF2E.DamageDieD8",d10:"PF2E.DamageDieD10",d12:"PF2E.DamageDieD12"},weaponMAP:{1:"-1/-2",2:"-2/-4",3:"-3/-6",4:"-4/-8",5:"-5/-10"},weaponReload,armorCategories:{unarmored:"PF2E.ArmorTypeUnarmored",light:"PF2E.ArmorTypeLight",medium:"PF2E.ArmorTypeMedium",heavy:"PF2E.ArmorTypeHeavy",shield:"PF2E.ArmorTypeShield","light-barding":"PF2E.Item.Armor.Category.light-barding","heavy-barding":"PF2E.Item.Armor.Category.heavy-barding"},armorGroups:{composite:"PF2E.ArmorGroupComposite",chain:"PF2E.ArmorGroupChain",cloth:"PF2E.ArmorGroupCloth",leather:"PF2E.ArmorGroupLeather",plate:"PF2E.ArmorGroupPlate",skeletal:"PF2E.ArmorGroupSkeletal",wood:"PF2E.ArmorGroupWood"},consumableTypes:{ammo:"PF2E.ConsumableTypeAmmo",catalyst:"PF2E.TraitCatalyst",drug:"PF2E.ConsumableTypeDrug",elixir:"PF2E.ConsumableTypeElixir",fulu:"PF2E.TraitFulu",gadget:"PF2E.TraitGadget",oil:"PF2E.ConsumableTypeOil",other:"PF2E.ConsumableTypeOther",mutagen:"PF2E.ConsumableTypeMutagen",poison:"PF2E.ConsumableTypePoison",potion:"PF2E.ConsumableTypePotion",scroll:"PF2E.ConsumableTypeScroll",snare:"PF2E.ConsumableTypeSnare",talisman:"PF2E.ConsumableTypeTalisman",tool:"PF2E.ConsumableTypeTool",wand:"PF2E.ConsumableTypeWand"},identification:configFromLocalization({Identified:"Identified",Identify:"Identify Item",IdentifyAlchemyDCs:"Identify Alchemy DCs",IdentifyGenericDCs:"Identify Generic DCs",IdentifyMagicDCs:"Identify Magic DCs",IsIdentified:"Identified?",MisidentifiedItem:"Misidentified {item}",Misidentify:"Misidentify Item",MystificationStatus:"Mystification status",Mystify:"Mystify Item",PostSkillsToChat:"Post skill checks to chat",PostSkillsToChatText:"Identify item: Skill checks",TraitGMNote:"Note: this trait is hidden from players.",Unidentified:"Unidentified",UnidentifiedDescription:"The nature of this {item} is unclear.",UnidentifiedHint:"Change the basic display details of this item when unidentified.",UnidentifiedItem:"Unusual {item}",UnidentifiedType:{Amulet:"Amulet",Anklets:"Anklets",Armbands:"Armbands",Backpack:"Backpack",Belt:"Belt",Book:"Book",Bracers:"Bracers",Circlet:"Circlet",Cloak:"Cloak",Collar:"Collar",Epaulets:"Epaulets",Eyepiece:"Eyepiece",Garment:"Garment",Gloves:"Gloves",Headwear:"Headwear",Horseshoes:"Horseshoes",Liquid:"Liquid",Mask:"Mask",Necklace:"Necklace",Object:"Object",Ring:"Ring",Saddle:"Saddle",Shoes:"Shoes",Substance:"Substance",Tool:"Tool"}},"PF2E.identification"),preparationType:{prepared:"PF2E.PreparationTypePrepared",spontaneous:"PF2E.PreparationTypeSpontaneous",innate:"PF2E.PreparationTypeInnate",focus:"PF2E.SpellCategoryFocus",ritual:"PF2E.SpellCategoryRitual",items:"PF2E.PreparationTypeItems"},areaTypes:{burst:"PF2E.AreaTypeBurst",cone:"PF2E.AreaTypeCone",cube:"PF2E.AreaTypeCube",emanation:"PF2E.AreaTypeEmanation",line:"PF2E.AreaTypeLine",square:"PF2E.AreaTypeSquare"},areaSizes:{5:"PF2E.AreaSize5",10:"PF2E.AreaSize10",15:"PF2E.AreaSize15",20:"PF2E.AreaSize20",25:"PF2E.AreaSize25",30:"PF2E.AreaSize30",40:"PF2E.AreaSize40",45:"PF2E.AreaSize45",50:"PF2E.AreaSize50",60:"PF2E.AreaSize60",65:"PF2E.AreaSize65",75:"PF2E.AreaSize75",80:"PF2E.AreaSize80",90:"PF2E.AreaSize90",100:"PF2E.AreaSize100",120:"PF2E.AreaSize120",360:"PF2E.AreaSize360",500:"PF2E.AreaSize500",1e3:"PF2E.AreaSize1000",1320:"PF2E.AreaSizeQuarterMile",5280:"PF2E.AreaSize1Mile"},alignments,alignmentTraits,attitude:{hostile:"PF2E.Attitudes.Hostile",unfriendly:"PF2E.Attitudes.Unfriendly",indifferent:"PF2E.Attitudes.Indifferent",friendly:"PF2E.Attitudes.Friendly",helpful:"PF2E.Attitudes.Helpful"},skillList:{acrobatics:"PF2E.SkillAcrobatics",arcana:"PF2E.SkillArcana",athletics:"PF2E.SkillAthletics",crafting:"PF2E.SkillCrafting",deception:"PF2E.SkillDeception",diplomacy:"PF2E.SkillDiplomacy",intimidation:"PF2E.SkillIntimidation",medicine:"PF2E.SkillMedicine",nature:"PF2E.SkillNature",occultism:"PF2E.SkillOccultism",performance:"PF2E.SkillPerformance",religion:"PF2E.SkillReligion",society:"PF2E.SkillSociety",stealth:"PF2E.SkillStealth",survival:"PF2E.SkillSurvival",thievery:"PF2E.SkillThievery",lore:"PF2E.SkillLore"},spellComponents:{V:"PF2E.SpellComponentV",S:"PF2E.SpellComponentS",M:"PF2E.SpellComponentM",F:"PF2E.SpellComponentF"},spellCategories:{spell:"PF2E.SpellCategorySpell",focus:"PF2E.SpellCategoryFocus",ritual:"PF2E.SpellCategoryRitual"},spellTypes:{attack:"PF2E.SpellTypeAttack",save:"PF2E.SpellTypeSave",heal:"PF2E.SpellTypeHeal",utility:"PF2E.SpellTypeUtility"},featCategories,actionTypes:{action:"PF2E.ActionTypeAction",reaction:"PF2E.ActionTypeReaction",free:"PF2E.ActionTypeFree",passive:"PF2E.ActionTypePassive"},actionsNumber:{1:"PF2E.ActionNumber1",2:"PF2E.ActionNumber2",3:"PF2E.ActionNumber3"},actionCategories:{interaction:"PF2E.Item.Action.Category.Interaction",defensive:"PF2E.Item.Action.Category.Defensive",offensive:"PF2E.Item.Action.Category.Offensive",familiar:"PF2E.Item.Action.Category.Familiar"},frequencies:{turn:"PF2E.Duration.turn",round:"PF2E.Duration.round",PT1M:"PF2E.Duration.PT1M",PT10M:"PF2E.Duration.PT10M",PT1H:"PF2E.Duration.PT1H",PT24H:"PF2E.Duration.PT24H",day:"PF2E.Duration.day",P1W:"PF2E.Duration.P1W",P1M:"PF2E.Duration.P1M",P1Y:"PF2E.Duration.P1Y"},timeUnits:{rounds:"PF2E.Time.Unit.Rounds",minutes:"PF2E.Time.Unit.Minutes",hours:"PF2E.Time.Unit.Hours",days:"PF2E.Time.Unit.Days",unlimited:"PF2E.Time.Unit.Unlimited",encounter:"PF2E.Time.Unit.UntilEncounterEnds"},proficiencyLevels:["PF2E.ProficiencyLevel0","PF2E.ProficiencyLevel1","PF2E.ProficiencyLevel2","PF2E.ProficiencyLevel3","PF2E.ProficiencyLevel4"],actorSizes:sizeTypes,actorTypes,speedTypes:{swim:"PF2E.SpeedTypesSwim",climb:"PF2E.SpeedTypesClimb",fly:"PF2E.SpeedTypesFly",burrow:"PF2E.SpeedTypesBurrow"},prerequisitePlaceholders:{prerequisite1:"PF2E.Prerequisite1",prerequisite2:"PF2E.Prerequisite2",prerequisite3:"PF2E.Prerequisite3",prerequisite4:"PF2E.Prerequisite4",prerequisite5:"PF2E.Prerequisite5"},senses,senseAcuity,bulkTypes:{L:"PF2E.BulkTypeLight",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",14:"14",15:"15",16:"16",17:"17",18:"18",19:"19",20:"20",21:"21",22:"22",23:"23",24:"24",25:"25",26:"26",27:"27",28:"28",29:"29",30:"30",31:"31",32:"32",33:"33",34:"34",35:"35",36:"36",37:"37",38:"38",39:"39",40:"40",41:"41",42:"42",43:"43",44:"44",45:"45",46:"46",47:"47",48:"48",49:"49",50:"50"},conditionTypes,pfsFactions:{EA:"PF2E.PFS.Factions.EA",GA:"PF2E.PFS.Factions.GA",HH:"PF2E.PFS.Factions.HH",VS:"PF2E.PFS.Factions.VS",RO:"PF2E.PFS.Factions.RO",VW:"PF2E.PFS.Factions.VW"},pfsSchools:{none:"PF2E.PFS.School.None",scrolls:"PF2E.PFS.School.Scrolls",spells:"PF2E.PFS.School.Spells",swords:"PF2E.PFS.School.Swords"},immunityTypes,languages:{common:"PF2E.LanguageCommon",draconic:"PF2E.LanguageDraconic",dwarven:"PF2E.LanguageDwarven",elven:"PF2E.LanguageElven",gnomish:"PF2E.LanguageGnomish",goblin:"PF2E.LanguageGoblin",halfling:"PF2E.LanguageHalfling",jotun:"PF2E.LanguageJotun",orcish:"PF2E.LanguageOrcish",undercommon:"PF2E.LanguageUndercommon",ysoki:"PF2E.LanguageYsoki",abyssal:"PF2E.LanguageAbyssal",adlet:"PF2E.LanguageAdlet",aklo:"PF2E.LanguageAklo",akitonian:"PF2E.LanguageAkitonian",alghollthu:"PF2E.LanguageAlghollthu",amurrun:"PF2E.LanguageAmurrun",anadi:"PF2E.LanguageAnadi","ancient-osiriani":"PF2E.LanguageAncientOsiriani",anugobu:"PF2E.LanguageAnugobu",arcadian:"PF2E.LanguageArcadian",arboreal:"PF2E.LanguageArboreal",boggard:"PF2E.LanguageBoggard",calda:"PF2E.LanguageCalda",caligni:"PF2E.LanguageCaligni",celestial:"PF2E.LanguageCelestial",cyclops:"PF2E.LanguageCyclops",daemonic:"PF2E.LanguageDaemonic",destrachan:"PF2E.LanguageDestrachan",drooni:"PF2E.LanguageDrooni",dziriak:"PF2E.LanguageDziriak",ekujae:"PF2E.LanguageEkujae","elder-thing":"PF2E.LanguageElderThing",empyrean:"PF2E.LanguageEmpyrean",erutaki:"PF2E.LanguageErutaki",fey:"PF2E.LanguageFey",formian:"PF2E.LanguageFormian",garundi:"PF2E.LanguageGarundi",girtablilu:"PF2E.LanguageGirtablilu",gnoll:"PF2E.LanguageGnoll",goloma:"PF2E.LanguageGoloma",grippli:"PF2E.LanguageGrippli",hallit:"PF2E.LanguageHallit",hwan:"PF2E.LanguageHwan",iblydan:"PF2E.LanguageIblydan",ikeshti:"PF2E.LanguageIkeshti",immolis:"PF2E.LanguageImmolis",infernal:"PF2E.LanguageInfernal",iruxi:"PF2E.LanguageIruxi",jistkan:"PF2E.LanguageJistkan",jyoti:"PF2E.LanguageJyoti",kaava:"PF2E.LanguageKaava",kashrishi:"PF2E.LanguageKashrishi",kibwani:"PF2E.LanguageKibwani",kitsune:"PF2E.LanguageKitsune",kelish:"PF2E.LanguageKelish",lirgeni:"PF2E.LanguageLirgeni",mahwek:"PF2E.LanguageMahwek",minaten:"PF2E.LanguageMinaten",minkaian:"PF2E.LanguageMinkaian",muan:"PF2E.LanguageMuan",mwangi:"PF2E.LanguageMwangi",mzunu:"PF2E.LanguageMzunu",nagaji:"PF2E.LanguageNagaji",necril:"PF2E.LanguageNecril",ocotan:"PF2E.LanguageOcotan",okaiyan:"PF2E.LanguageOkaiyan",orvian:"PF2E.LanguageOrvian",osiriani:"PF2E.LanguageOsiriani",petran:"PF2E.LanguagePetran",protean:"PF2E.LanguageProtean",pyric:"PF2E.LanguagePyric",rasu:"PF2E.LanguageRasu",ratajin:"PF2E.LanguageRatajin",razatlani:"PF2E.LanguageRazatlani",requian:"PF2E.LanguageRequian",russian:"PF2E.LanguageRussian",sakvroth:"PF2E.LanguageSakvroth",senzar:"PF2E.LanguageSenzar",shadowtongue:"PF2E.LanguageShadowtongue",shobhad:"PF2E.LanguageShobhad",shisk:"PF2E.LanguageShisk",shoanti:"PF2E.LanguageShoanti",shoony:"PF2E.LanguageShoony",shory:"PF2E.LanguageShory",skald:"PF2E.LanguageSkald",sphinx:"PF2E.LanguageSphinx",strix:"PF2E.LanguageStrix",sussuran:"PF2E.LanguageSussuran",taldane:"PF2E.LanguageTaldane",talican:"PF2E.LanguageTalican",tekritanin:"PF2E.LanguageTekritanin",tengu:"PF2E.LanguageTengu",thalassic:"PF2E.LanguageThalassic",thassilonian:"PF2E.LanguageThassilonian",tien:"PF2E.LanguageTien",utopian:"PF2E.LanguageUtopian",vanara:"PF2E.LanguageVanara",varisian:"PF2E.LanguageVarisian",varki:"PF2E.LanguageVarki",vishkanyan:"PF2E.LanguageVishkanyan",vudrani:"PF2E.LanguageVudrani",wyrwood:"PF2E.LanguageWyrwood",xanmba:"PF2E.LanguageXanmba",androffan:"PF2E.LanguageAndroffan",azlanti:"PF2E.LanguageAzlanti",grioth:"PF2E.LanguageGrioth",kovintal:"PF2E.LanguageKovintal",migo:"PF2E.LanguageMiGo",munavri:"PF2E.LanguageMunavri",samsaran:"PF2E.LanguageSamsaran",sasquatch:"PF2E.LanguageSasquatch",shae:"PF2E.LanguageShae",yithian:"PF2E.LanguageYithian",druidic:"PF2E.LanguageDruidic"},attackEffects:{grab:"PF2E.AttackEffectGrab","improved-grab":"PF2E.AttackEffectImprovedGrab",constrict:"PF2E.AttackEffectConstrict","greater-constrict":"PF2E.AttackEffectGreaterConstrict",knockdown:"PF2E.AttackEffectKnockdown","improved-knockdown":"PF2E.AttackEffectImprovedKnockdown",push:"PF2E.AttackEffectPush","improved-push":"PF2E.AttackEffectImprovedPush",trip:"PF2E.AttackEffectTrip"},worldClock:mergeObject(configFromLocalization({AD:{Era:"AD"},AR:{Era:"AR",Months:{April:"Gozran",August:"Arodus",December:"Kuthona",February:"Calistril",January:"Abadius",July:"Erastus",June:"Sarenith",March:"Pharast",May:"Desnus",November:"Neth",October:"Lamashan",September:"Rova"},Weekdays:{Friday:"Fireday",Monday:"Moonday",Saturday:"Starday",Sunday:"Sunday",Thursday:"Oathday",Tuesday:"Toilday",Wednesday:"Wealday"}},Button:{AddOneDay:"1 Day",AddOneHour:"1 Hour",AddOneMinute:"1 Minute",AddOneRound:"1 Round",AddOneWeek:"1 Week",AddTenMinutes:"10 Minutes",Advance:"Advance",Retract:"Retract",TimeOfDay:{Advance:{Dawn:"Advance to Dawn",Dusk:"Advance to Dusk",Midnight:"Advance to Midnight",Noon:"Advance to Noon"},Retract:{Dawn:"Retract to Dawn",Dusk:"Retract to Dusk",Midnight:"Retract to Midnight",Noon:"Retract to Noon"}}},CE:{Era:"CE"},Date:"{weekday}, {day} of {month}, {year} {era}",IC:{Era:"IC"},Placeholder:"Number",Title:"World Clock"},"PF2E.WorldClock"),{AR:{yearOffset:2700},IC:{yearOffset:5200},AD:{yearOffset:-95},CE:{yearOffset:0}}),hexplorationActivities:{10:.5,25:1,40:2,55:3,Infinity:4},SETTINGS:{automation:{rulesBasedVision:{name:"PF2E.SETTINGS.Automation.RulesBasedVision.Name",hint:"PF2E.SETTINGS.Automation.RulesBasedVision.Hint"},iwr:{name:"PF2E.SETTINGS.Automation.IWR.Name",hint:"PF2E.SETTINGS.Automation.IWR.Hint"},effectExpiration:{name:"PF2E.SETTINGS.Automation.EffectExpiration.Name",hint:"PF2E.SETTINGS.Automation.EffectExpiration.Hint"},removeExpiredEffects:{name:"PF2E.SETTINGS.Automation.RemoveExpiredEffects.Name",hint:"PF2E.SETTINGS.Automation.RemoveExpiredEffects.Hint"},flankingDetection:{name:"PF2E.SETTINGS.Automation.FlankingDetection.Name",hint:"PF2E.SETTINGS.Automation.FlankingDetection.Hint"},actorsDeadAtZero:{name:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Name",hint:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Hint",neither:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Neither",npcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.NPCsOnly",both:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Both"},lootableNPCs:{name:"PF2E.SETTINGS.Automation.LootableNPCs.Name",hint:"PF2E.SETTINGS.Automation.LootableNPCs.Hint"}},homebrew:{creatureTraits:{name:"PF2E.SETTINGS.Homebrew.CreatureTraits.Name",hint:"PF2E.SETTINGS.Homebrew.CreatureTraits.Hint"},featTraits:{name:"PF2E.SETTINGS.Homebrew.FeatTraits.Name",hint:"PF2E.SETTINGS.Homebrew.FeatTraits.Hint"},languages:{name:"PF2E.SETTINGS.Homebrew.Languages.Name",hint:"PF2E.SETTINGS.Homebrew.Languages.Hint"},magicSchools:{name:"PF2E.SETTINGS.Homebrew.MagicSchools.Name",hint:"PF2E.SETTINGS.Homebrew.MagicSchools.Hint"},spellTraits:{name:"PF2E.SETTINGS.Homebrew.SpellTraits.Name",hint:"PF2E.SETTINGS.Homebrew.SpellTraits.Hint"},weaponCategories:{name:"PF2E.SETTINGS.Homebrew.WeaponCategories.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponCategories.Hint"},weaponGroups:{name:"PF2E.SETTINGS.Homebrew.WeaponGroups.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponGroups.Hint"},baseWeapons:{name:"PF2E.SETTINGS.Homebrew.BaseWeapons.Name",hint:"PF2E.SETTINGS.Homebrew.BaseWeapons.Hint"},weaponTraits:{name:"PF2E.SETTINGS.Homebrew.WeaponTraits.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponTraits.Hint"},equipmentTraits:{name:"PF2E.SETTINGS.Homebrew.EquipmentTraits.Name",hint:"PF2E.SETTINGS.Homebrew.EquipmentTraits.Hint"}},worldClock:{name:"PF2E.SETTINGS.WorldClock.Name",label:"PF2E.SETTINGS.WorldClock.Label",hint:"PF2E.SETTINGS.WorldClock.Hint",dateTheme:{name:"PF2E.SETTINGS.WorldClock.DateTheme.Name",hint:"PF2E.SETTINGS.WorldClock.DateTheme.Hint",AR:"PF2E.SETTINGS.WorldClock.DateTheme.AR",AD:"PF2E.SETTINGS.WorldClock.DateTheme.AD",CE:"PF2E.SETTINGS.WorldClock.DateTheme.CE"},timeConvention:{name:"PF2E.SETTINGS.WorldClock.TimeConvention.Name",hint:"PF2E.SETTINGS.WorldClock.TimeConvention.Hint",twentyFour:"PF2E.SETTINGS.WorldClock.TimeConvention.TwentyFour",twelve:"PF2E.SETTINGS.WorldClock.TimeConvention.Twelve"},showClockButton:{name:"PF2E.SETTINGS.WorldClock.ShowClockButton.Name",hint:"PF2E.SETTINGS.WorldClock.ShowClockButton.Hint"},playersCanView:{name:"PF2E.SETTINGS.WorldClock.PlayersCanView.Name",hint:"PF2E.SETTINGS.WorldClock.PlayersCanView.Hint"},syncDarkness:{name:"PF2E.SETTINGS.WorldClock.SyncDarkness.Name",hint:"PF2E.SETTINGS.WorldClock.SyncDarkness.Hint"},syncDarknessScene:{name:"PF2E.SETTINGS.WorldClock.SyncDarknessScene.Name",hint:"PF2E.SETTINGS.WorldClock.SyncDarknessScene.Hint",enabled:"PF2E.SETTINGS.EnabledDisabled.Enabled",default:"PF2E.SETTINGS.EnabledDisabled.Default",disabled:"PF2E.SETTINGS.EnabledDisabled.Disabled"},worldCreatedOn:{name:"PF2E.SETTINGS.WorldClock.WorldCreatedOn.Name",hint:"PF2E.SETTINGS.WorldClock.WorldCreatedOn.Hint"}},CampaignFeats:{name:"PF2E.SETTINGS.CampaignFeats.Name",hint:"PF2E.SETTINGS.CampaignFeats.Hint"}},Actor:{documentClasses:{character:CharacterPF2e,npc:NPCPF2e,hazard:HazardPF2e,loot:LootPF2e,familiar:FamiliarPF2e,party:PartyPF2e,vehicle:VehiclePF2e}},Item:{documentClasses:{action:AbilityItemPF2e,affliction:AfflictionPF2e,ancestry:AncestryPF2e,armor:ArmorPF2e,background:BackgroundPF2e,backpack:ContainerPF2e,book:BookPF2e,campaignFeature:CampaignFeaturePF2e,class:ClassPF2e,condition:ConditionPF2e,consumable:ConsumablePF2e,deity:DeityPF2e,effect:EffectPF2e,equipment:EquipmentPF2e,feat:FeatPF2e,heritage:HeritagePF2e,kit:KitPF2e,lore:LorePF2e,melee:MeleePF2e,spell:SpellPF2e,spellcastingEntry:SpellcastingEntryPF2e,treasure:TreasurePF2e,weapon:WeaponPF2e},traits:{action:actionTraits,affliction:actionTraits,armor:armorTraits,ancestry:creatureTraits,background:backgroundTraits,backpack:equipmentTraits,book:equipmentTraits,campaignFeature:kingmakerTraits,consumable:consumableTraits,equipment:equipmentTraits,feat:featTraits,heritage:featTraits,kit:classTraits,melee:npcAttackTraits,spell:spellTraits,weapon:weaponTraits}},JournalEntry:{sheetClass:JournalSheetPF2e},Canvas:{darkness:{default:CONFIG.Canvas.darknessColor,gmVision:9473209}}};function registerHandlebarsHelpers(){Handlebars.registerHelper("pad",(value,length,character)=>`${value}`.padStart(length,character)),Handlebars.registerHelper("add",(a,b)=>Number(a)+Number(b)),Handlebars.registerHelper("nor",(...args)=>!args.slice(0,-1).some(a=>!!a)),Handlebars.registerHelper("any",(...args)=>args.slice(0,-1).some(a=>!!a)),Handlebars.registerHelper("disabled",condition=>condition?"disabled":""),Handlebars.registerHelper("coalesce",(...args)=>args.find(a=>a!=null)??null),Handlebars.registerHelper("lower",str=>String(str).toLowerCase()),Handlebars.registerHelper("capitalize",str=>String(str).capitalize()),Handlebars.registerHelper("multiply",(a,b)=>Number(a)*Number(b)),Handlebars.registerHelper("percentage",(value,max)=>Number(value)*100/Number(max)),Handlebars.registerHelper("ordinal",value=>{const numericValue=Number(value);return isNaN(numericValue)?null:ordinalString(numericValue)}),Handlebars.registerHelper("sluggify",text=>sluggify(String(text))),Handlebars.registerHelper("json",data=>JSON.stringify(data)),Handlebars.registerHelper("actionGlyph",(value,options)=>{const glyph=getActionGlyph(value??"");return glyph?`${glyph}`:options?.hash.fallback?Handlebars.escapeExpression(value):null}),Handlebars.registerHelper("times",(count,options)=>[...Array(Number(count)).keys()].map(i=>options.fn(i,{data:options.data,blockParams:[i]})).join("")),Handlebars.registerHelper("concat",(...params)=>params.slice(0,-1).join("")),Handlebars.registerHelper("developMode",function(options){return""}),Handlebars.registerHelper("isNumber",value=>typeof value=="number"),Handlebars.registerHelper("isNullish",value=>value==null),Handlebars.registerHelper("coinLabel",value=>value?"value"in value?new CoinsPF2e(value.value):new CoinsPF2e(value):null),Handlebars.registerHelper("includes",(arr,element)=>Array.isArray(arr)?arr.includes(element):arr instanceof Set?arr.has(element):arr&&typeof arr=="object"?(typeof element=="number"||typeof element=="string")&&element in arr:!1),Handlebars.registerHelper("raw",function(options){return options.fn(this)})}__name(registerHandlebarsHelpers,"registerHandlebarsHelpers"),__name2(registerHandlebarsHelpers,"registerHandlebarsHelpers");function registerFonts(){CONFIG.fontDefinitions.Eczar={editor:!0,fonts:[{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-800.woff2"],style:"normal",weight:"800"}]},CONFIG.fontDefinitions.Gelasio={editor:!1,fonts:[{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-500italic.woff2"],style:"italic",weight:"500"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-600italic.woff2"],style:"italic",weight:"600"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-700italic.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions["La Belle Aurore"]={editor:!0,fonts:[{urls:["systems/pf2e/fonts/la-belle-aurore-v16-latin-regular.woff2"],style:"normal",weight:"400"}]},CONFIG.fontDefinitions.Pathfinder2eActions={editor:!1,fonts:[{urls:["systems/pf2e/fonts/pathfinder-2e-actions.woff2"]}]},CONFIG.fontDefinitions.Roboto={editor:!0,fonts:[{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-500italic.woff2"],style:"italic",weight:"500"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-700italic.woff2"],style:"italic",weight:"700"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-900.woff2"],style:"normal",weight:"900"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-900italic.woff2"],style:"italic",weight:"900"}]},CONFIG.fontDefinitions["Roboto Condensed"]={editor:!1,fonts:[{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-700italic.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions["Roboto Mono"]={editor:!1,fonts:[{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-700.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions.Signika={editor:!0,fonts:[{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-700.woff2"],style:"normal",weight:"700"}]},CONFIG.fontDefinitions.Vollkorn={editor:!0,fonts:[{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-900.woff2"],style:"normal",weight:"700"}]},delete CONFIG.fontDefinitions.Courier,delete CONFIG.fontDefinitions.Times,CONFIG._fontFamilies=[]}__name(registerFonts,"registerFonts"),__name2(registerFonts,"registerFonts");function registerKeybindings(){game.keybindings.register("pf2e","cycle-token-stack",{name:"PF2E.Keybinding.CycleTokenStack.Label",hint:"PF2E.Keybinding.CycleTokenStack.Hint",editable:[{key:"KeyZ",modifiers:[]}],onUp:()=>canvas.tokens.cycleStack()}),game.keybindings.register("pf2e","toggle-party-sheet",{name:"PF2E.Keybinding.TogglePartySheet.Label",hint:"PF2E.Keybinding.TogglePartySheet.Hint",editable:[{key:"KeyP",modifiers:[]}],onDown:()=>{const party=(()=>{if(game.user.isGM){const token=canvas.ready&&canvas.tokens.controlled.length===1?canvas.tokens.controlled[0]:null;return token?.actor?.isOfType("party")?token.actor:game.actors.party}else if(game.user.character?.isOfType("character")){const pcParties=Array.from(game.user.character.parties);return pcParties.find(p=>p.active)??pcParties.at(0)??null}return null})();if(!party)return!1;const{sheet}=party;return sheet.rendered?sheet._minimized?sheet.maximize():sheet.close():sheet.render(!0),!0}}),!game.modules.get("gm-vision")?.active&&!game.modules.get("perfect-vision")?.active&&game.keybindings.register("pf2e","gm-vision",{name:"PF2E.Keybinding.GMVision.Label",hint:"PF2E.Keybinding.GMVision.Hint",editable:[{key:"KeyG",modifiers:["Control"]}],restricted:!0,onDown:context=>(context.event.preventDefault(),!0),onUp:()=>(ui.controls.control?.name==="lighting"?ui.controls.control.tools.find(t=>t.name==="gm-vision")?.onClick?.():game.settings.set("pf2e","gmVision",!game.settings.get("pf2e","gmVision")),!0)})}__name(registerKeybindings,"registerKeybindings"),__name2(registerKeybindings,"registerKeybindings");function registerTemplates(){const templatePaths=["systems/pf2e/templates/chat/check/roll.hbs","systems/pf2e/templates/chat/check/target-dc-result.hbs","systems/pf2e/templates/chat/damage/damage-taken.hbs","systems/pf2e/templates/dice/damage-roll.hbs","systems/pf2e/templates/dice/damage-tooltip.hbs","systems/pf2e/templates/actors/character/partials/elemental-blast.hbs","systems/pf2e/templates/actors/character/partials/feat-slot.hbs","systems/pf2e/templates/actors/character/partials/header.hbs","systems/pf2e/templates/actors/character/partials/sidebar.hbs","systems/pf2e/templates/actors/character/partials/strike.hbs","systems/pf2e/templates/actors/character/tabs/general.hbs","systems/pf2e/templates/actors/character/tabs/actions.hbs","systems/pf2e/templates/actors/character/tabs/biography.hbs","systems/pf2e/templates/actors/character/tabs/effects.hbs","systems/pf2e/templates/actors/character/tabs/feats.hbs","systems/pf2e/templates/actors/character/tabs/inventory.hbs","systems/pf2e/templates/actors/character/tabs/pfs.hbs","systems/pf2e/templates/actors/character/tabs/proficiencies.hbs","systems/pf2e/templates/actors/character/tabs/spellcasting.hbs","systems/pf2e/templates/actors/character/tabs/crafting.hbs","systems/pf2e/templates/actors/hazard/partials/header.hbs","systems/pf2e/templates/actors/hazard/partials/sidebar.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/main.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/activities.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/world.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/features.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/ongoing.hbs","systems/pf2e/templates/actors/party/kingdom/partials/build-entry-boosts.hbs","systems/pf2e/templates/actors/party/kingdom/partials/settlement.hbs","systems/pf2e/templates/actors/partials/action.hbs","systems/pf2e/templates/actors/partials/carry-type.hbs","systems/pf2e/templates/actors/partials/coinage.hbs","systems/pf2e/templates/actors/partials/dying-pips.hbs","systems/pf2e/templates/actors/partials/effects.hbs","systems/pf2e/templates/actors/partials/encumbrance.hbs","systems/pf2e/templates/actors/partials/inventory.hbs","systems/pf2e/templates/actors/partials/item-line.hbs","systems/pf2e/templates/actors/partials/modifiers-tooltip.hbs","systems/pf2e/templates/actors/partials/toggles.hbs","systems/pf2e/templates/actors/partials/total-bulk.hbs","systems/pf2e/templates/actors/crafting-entry-alchemical.hbs","systems/pf2e/templates/actors/crafting-entry-list.hbs","systems/pf2e/templates/actors/spell-collection.hbs","systems/pf2e/templates/actors/character/partials/proficiencylevels-dropdown.hbs","systems/pf2e/templates/actors/character/icons/d20.hbs","systems/pf2e/templates/actors/character/icons/pfs.hbs","systems/pf2e/templates/actors/character/icons/plus.hbs","systems/pf2e/templates/actors/partials/images/header_stroke.hbs","systems/pf2e/templates/actors/partials/images/header_stroke_large.hbs","systems/pf2e/templates/actors/npc/tabs/main.hbs","systems/pf2e/templates/actors/npc/tabs/inventory.hbs","systems/pf2e/templates/actors/npc/tabs/effects.hbs","systems/pf2e/templates/actors/npc/tabs/spells.hbs","systems/pf2e/templates/actors/npc/tabs/notes.hbs","systems/pf2e/templates/actors/npc/partials/header.hbs","systems/pf2e/templates/actors/npc/partials/sidebar.hbs","systems/pf2e/templates/actors/npc/partials/action.hbs","systems/pf2e/templates/actors/npc/partials/attack.hbs","systems/pf2e/templates/items/action-details.hbs","systems/pf2e/templates/items/action-sidebar.hbs","systems/pf2e/templates/items/activation-panel.hbs","systems/pf2e/templates/items/affliction-details.hbs","systems/pf2e/templates/items/affliction-sidebar.hbs","systems/pf2e/templates/items/ancestry-details.hbs","systems/pf2e/templates/items/ancestry-sidebar.hbs","systems/pf2e/templates/items/armor-details.hbs","systems/pf2e/templates/items/armor-sidebar.hbs","systems/pf2e/templates/items/background-details.hbs","systems/pf2e/templates/items/backpack-details.hbs","systems/pf2e/templates/items/backpack-sidebar.hbs","systems/pf2e/templates/items/book-details.hbs","systems/pf2e/templates/items/book-sidebar.hbs","systems/pf2e/templates/items/campaign-feature-details.hbs","systems/pf2e/templates/items/campaign-feature-sidebar.hbs","systems/pf2e/templates/items/class-details.hbs","systems/pf2e/templates/items/condition-details.hbs","systems/pf2e/templates/items/condition-sidebar.hbs","systems/pf2e/templates/items/consumable-details.hbs","systems/pf2e/templates/items/consumable-sidebar.hbs","systems/pf2e/templates/items/deity-details.hbs","systems/pf2e/templates/items/effect-details.hbs","systems/pf2e/templates/items/effect-sidebar.hbs","systems/pf2e/templates/items/equipment-details.hbs","systems/pf2e/templates/items/equipment-sidebar.hbs","systems/pf2e/templates/items/feat-details.hbs","systems/pf2e/templates/items/feat-sidebar.hbs","systems/pf2e/templates/items/heritage-details.hbs","systems/pf2e/templates/items/heritage-sidebar.hbs","systems/pf2e/templates/items/kit-details.hbs","systems/pf2e/templates/items/kit-sidebar.hbs","systems/pf2e/templates/items/lore-details.hbs","systems/pf2e/templates/items/lore-sidebar.hbs","systems/pf2e/templates/items/melee-details.hbs","systems/pf2e/templates/items/mystify-panel.hbs","systems/pf2e/templates/items/rules-panel.hbs","systems/pf2e/templates/items/spell-details.hbs","systems/pf2e/templates/items/spell-overlay.hbs","systems/pf2e/templates/items/spell-sidebar.hbs","systems/pf2e/templates/items/treasure-details.hbs","systems/pf2e/templates/items/treasure-sidebar.hbs","systems/pf2e/templates/items/weapon-details.hbs","systems/pf2e/templates/items/weapon-sidebar.hbs","systems/pf2e/templates/items/partials/ability-activation.hbs","systems/pf2e/templates/items/partials/duration.hbs","systems/pf2e/templates/items/partials/other-tags.hbs","systems/pf2e/templates/items/partials/self-applied-effect.hbs","systems/pf2e/templates/actors/loot/inventory.hbs","systems/pf2e/templates/actors/loot/sidebar.hbs","systems/pf2e/templates/actors/vehicle/vehicle-header.hbs","systems/pf2e/templates/actors/vehicle/sidebar.hbs","systems/pf2e/templates/actors/vehicle/tabs/details.hbs","systems/pf2e/templates/actors/vehicle/tabs/actions.hbs","systems/pf2e/templates/actors/vehicle/tabs/inventory.hbs","systems/pf2e/templates/actors/vehicle/tabs/description.hbs","systems/pf2e/templates/actors/vehicle/tabs/effects.hbs","systems/pf2e/templates/compendium-browser/settings/settings.hbs","systems/pf2e/templates/compendium-browser/settings/pack-settings.hbs","systems/pf2e/templates/compendium-browser/settings/source-settings.hbs","systems/pf2e/templates/compendium-browser/filters.hbs","systems/pf2e/templates/chat/action/header.hbs","systems/pf2e/templates/system/actions/repair/chat-button-partial.hbs","systems/pf2e/templates/system/actions/repair/repair-result-partial.hbs","systems/pf2e/templates/system/actions/repair/item-heading-partial.hbs","systems/pf2e/templates/scene/token/partials/appearance.hbs","systems/pf2e/templates/scene/token/partials/identity.hbs","systems/pf2e/templates/scene/token/partials/lighting.hbs","systems/pf2e/templates/partials/publication-data.hbs"];loadTemplates(templatePaths)}__name(registerTemplates,"registerTemplates"),__name2(registerTemplates,"registerTemplates");const _PackLoader=class{static{__name(this,"_PackLoader")}constructor(){__privateAdd(this,_setModuleArt),__privateAdd(this,_getSources),__privateAdd(this,_createFilteredIndex),__privateAdd(this,_loadSources),__privateAdd(this,_getSourceFromDocument),__publicField(this,"loadedSources",[]),__publicField(this,"sourcesSettings"),this.sourcesSettings=game.settings.get("pf2e","compendiumBrowserSources")}async*loadPacks(documentType,packs,indexFields){const localize=localizer("PF2E.ProgressBar"),sources=__privateMethod(this,_getSources,getSources_fn).call(this),progress=new Progress({max:packs.length});for(const packId of packs){const pack=game.packs.get(packId);if(!pack){progress.advance();continue}if(progress.advance({label:localize("LoadingPack",{pack:pack.metadata.label})}),pack.documentName===documentType){const index=await pack.getIndex({fields:indexFields});if((index.contents.at(0)??{}).system){const filteredIndex=__privateMethod(this,_createFilteredIndex,createFilteredIndex_fn).call(this,index,sources);__privateMethod(this,_setModuleArt,setModuleArt_fn).call(this,packId,filteredIndex),yield{pack,index:filteredIndex}}else ui.notifications.warn(game.i18n.format("PF2E.BrowserWarnPackNotLoaded",{pack:pack.collection}))}}progress.close({label:localize("LoadingComplete")})}async updateSources(packs){await __privateMethod(this,_loadSources,loadSources_fn).call(this,packs);for(const source of this.loadedSources){const slug=sluggify(source);this.sourcesSettings.sources[slug]===void 0&&(this.sourcesSettings.sources[slug]={load:this.sourcesSettings.showUnknownSources,name:source})}this.sourcesSettings.sources=Object.fromEntries(Object.entries(this.sourcesSettings.sources).sort((a,b)=>a[0].localeCompare(b[0],game.i18n.lang)))}reset(){this.loadedSources=[]}async hardReset(packs){this.reset(),this.sourcesSettings={ignoreAsGM:!0,showEmptySources:!0,showUnknownSources:!0,sources:{}},await this.updateSources(packs)}};_setModuleArt=new WeakSet,setModuleArt_fn=__name2(function(packName,index){if(packName.startsWith("pf2e."))for(const record of index){const uuid=`Compendium.${packName}.${record._id}`,actorArt=game.pf2e.system.moduleArt.map.get(uuid)?.img;record.img=actorArt??record.img}},"#setModuleArt"),_getSources=new WeakSet,getSources_fn=__name2(function(){const sources=new Set;for(const source of Object.values(this.sourcesSettings.sources))source?.load&&sources.add(source.name);return sources},"#getSources"),_createFilteredIndex=new WeakSet,createFilteredIndex_fn=__name2(function(index,sources){if(sources.size===0||game.user.isGM&&this.sourcesSettings.ignoreAsGM)return index;const filteredIndex=new Collection,knownSources=Object.values(this.sourcesSettings.sources).map(value=>value?.name);for(const document2 of index){const source=__privateMethod(this,_getSourceFromDocument,getSourceFromDocument_fn).call(this,document2);(!source&&this.sourcesSettings.showEmptySources||sources.has(source)||this.sourcesSettings.showUnknownSources&&source&&!knownSources.includes(source))&&filteredIndex.set(document2._id,document2)}return filteredIndex},"#createFilteredIndex"),_loadSources=new WeakSet,loadSources_fn=__name2(async function(packs){const localize=localizer("PF2E.ProgressBar"),progress=new Progress({max:packs.length}),loadedSources=new Set,indexFields=["system.publication.title","system.source.value"],knownDocumentTypes=["Actor","Item"];for(const packId of packs){const pack=game.packs.get(packId);if(!pack||!knownDocumentTypes.includes(pack.documentName)){progress.advance();continue}progress.advance({label:localize("LoadingPack",{pack:pack?.metadata.label??""})});const index=await pack.getIndex({fields:indexFields});for(const element of index){const source=__privateMethod(this,_getSourceFromDocument,getSourceFromDocument_fn).call(this,element);source&&source!==""&&loadedSources.add(source)}}progress.close({label:localize("LoadingComplete")});const loadedSourcesArray=Array.from(loadedSources).sort();this.loadedSources=loadedSourcesArray},"#loadSources"),_getSourceFromDocument=new WeakSet,getSourceFromDocument_fn=__name2(function(document2){return document2.system?.publication?.title?document2.system.publication.title:document2.system?.source?.value?document2.system.source.value:""},"#getSourceFromDocument"),__name2(_PackLoader,"PackLoader");let PackLoader=_PackLoader;const _CompendiumBrowserTab=class{static{__name(this,"_CompendiumBrowserTab")}constructor(browser){__privateAdd(this,_getRollTableResults),__publicField(this,"browser"),__publicField(this,"indexData",[]),__publicField(this,"currentIndex",[]),__publicField(this,"isInitialized",!1),__publicField(this,"totalItemCount",0),__publicField(this,"scrollLimit",100),__privateAdd(this,_domParser,new DOMParser),__publicField(this,"searchFields",[]),__publicField(this,"storeFields",[]),this.browser=browser}async init(){await this.loadData(),this.searchEngine=new MiniSearch({fields:this.searchFields,idField:"uuid",processTerm:t=>t.length>1&&!CompendiumDirectoryPF2e.STOP_WORDS.has(t)?t.toLocaleLowerCase(game.i18n.lang):null,storeFields:this.storeFields,searchOptions:{combineWith:"AND",prefix:!0}}),this.searchEngine.addAll(this.indexData),this.defaultFilterData=deepClone(this.filterData),this.isInitialized=!0}async open(filter2){if(filter2){if(!this.isInitialized)throw ErrorPF2e(`Tried to pass an initial filter to uninitialized tab "${this.tabName}"`);this.filterData=filter2}return this.browser.loadTab(this.tabName)}getIndexData(start){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);return this.currentIndex=(()=>{const searchText=this.filterData.search.text;if(searchText){const searchResult=this.searchEngine.search(searchText);return this.sortResult(searchResult.filter(this.filterIndexData.bind(this)))}return this.sortResult(this.indexData.filter(this.filterIndexData.bind(this)))})(),this.totalItemCount=this.currentIndex.length,this.currentIndex.slice(start,this.scrollLimit)}async getFilterData(){return this.isInitialized||await this.init(),deepClone(this.defaultFilterData)}resetFilters(){this.filterData=deepClone(this.defaultFilterData)}isOfType(...types){return types.some(t=>this.tabName===t)}filterTraits(traits,selected,condition){const selectedTraits=selected.filter(s=>!s.not).map(s=>s.value),notTraits=selected.filter(t=>t.not).map(s=>s.value);return!((selectedTraits.length||notTraits.length)&&(notTraits.some(t=>traits.includes(t))||!(condition==="and"?selectedTraits.every(t=>traits.includes(t)):selectedTraits.some(t=>traits.includes(t)))))}async renderResults(start){if(!this.templatePath)throw ErrorPF2e(`Tab "${this.tabName}" has no valid template path.`);const indexData=this.getIndexData(start),liElements=[];for(const entry of indexData){const htmlString=await renderTemplate(this.templatePath,{entry,filterData:this.filterData}),html=__privateGet(this,_domParser).parseFromString(htmlString,"text/html");liElements.push(html.body.firstElementChild)}return liElements}sortResult(result){const{order}=this.filterData,lang=game.i18n.lang,sorted=result.sort((entryA,entryB)=>{switch(order.by){case"name":return entryA.name.localeCompare(entryB.name,lang);case"level":return entryA.level-entryB.level||entryA.name.localeCompare(entryB.name,lang);case"price":return entryA.priceInCopper-entryB.priceInCopper||entryA.name.localeCompare(entryB.name,lang);default:return 0}});return order.direction==="asc"?sorted:sorted.reverse()}parseRangeFilterInput(_name,lower,upper){return{min:Number(lower)||0,max:Number(upper)||0,inputMin:lower,inputMax:upper}}arrayIncludes(array,other){return other.some(value=>array.includes(value))}generateCheckboxOptions(configData,sort=!0){const localized=Object.entries(configData).reduce((result,[key,label])=>({...result,[key]:game.i18n.localize(label)}),{});return Object.entries(sort?this.sortedConfig(localized):localized).reduce((result,[key,label])=>({...result,[key]:{label,selected:!1}}),{})}generateMultiselectOptions(optionsRecord,sort=!0){const options=Object.entries(optionsRecord).map(([value,label])=>({value,label:game.i18n.localize(label)}));return sort&&options.sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)),options}generateSourceCheckboxOptions(sources){return[...sources].sort().reduce((result,source)=>({...result,[sluggify(source)]:{label:source,selected:!1}}),{})}sortedConfig(obj){return Object.fromEntries([...Object.entries(obj)].sort((entryA,entryB)=>entryA[1].localeCompare(entryB[1],game.i18n.lang)))}hasAllIndexFields(data,indexFields){for(const field of indexFields)if(getProperty(data,field)===void 0&&!/\.(?:source|publication)/.test(field))return!1;return!0}async createRollTable(){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);const content=await renderTemplate("systems/pf2e/templates/compendium-browser/roll-table-dialog.hbs",{count:this.currentIndex.length});Dialog.confirm({content,title:game.i18n.localize("PF2E.CompendiumBrowser.RollTable.CreateLabel"),yes:async $html=>{const html=$html[0],name2=htmlQuery(html,"input[name=name]")?.value||game.i18n.localize("PF2E.CompendiumBrowser.Title"),weight=Number(htmlQuery(html,"input[name=weight]")?.value)||1,results=__privateMethod(this,_getRollTableResults,getRollTableResults_fn).call(this,{weight});(await RollTable.create({name:name2,results,formula:`1d${results.length}`}))?.sheet.render(!0)}})}async addToRollTable(){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);const content=await renderTemplate("systems/pf2e/templates/compendium-browser/roll-table-dialog.hbs",{count:this.currentIndex.length,rollTables:game.tables.contents});Dialog.confirm({title:game.i18n.localize("PF2E.CompendiumBrowser.RollTable.SelectTableTitle"),content,yes:async $html=>{const html=$html[0],option=htmlQuery(html,"select[name=roll-table]")?.selectedOptions[0];if(!option)return;const weight=Number(htmlQuery(html,"input[name=weight]")?.value)||1,table=game.tables.get(option.value,{strict:!0});await table.createEmbeddedDocuments("TableResult",__privateMethod(this,_getRollTableResults,getRollTableResults_fn).call(this,{initial:table.results.size,weight})),table?.sheet.render(!0)}})}};_domParser=new WeakMap,_getRollTableResults=new WeakSet,getRollTableResults_fn=__name2(function({initial=0,weight=1}){return this.currentIndex.flatMap((e,i)=>{const data=fromUuidSync(e.uuid);if(!data?.pack||!data._id||!("name"in data))return[];const rangeMinMax=initial+i+1;return{text:data.name,type:CONST.TABLE_RESULT_TYPES.COMPENDIUM,collection:data.pack,resultId:data._id,img:e.img,weight,range:[rangeMinMax,rangeMinMax],drawn:!1}})},"#getRollTableResults"),__name2(_CompendiumBrowserTab,"CompendiumBrowserTab");let CompendiumBrowserTab=_CompendiumBrowserTab;const _CompendiumBrowserActionTab=class extends CompendiumBrowserTab{static{__name(this,"_CompendiumBrowserActionTab")}tabName="action";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/action.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","traits","source","category","actionType"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading actions");const actions=[],indexFields=["img","system.actionType.value","system.category","system.traits.value","system.actionType.value","system.publication","system.source"],publications=new Set;for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("action"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loading`);for(const actionData of index)if(actionData.type==="action"){if(!this.hasAllIndexFields(actionData,indexFields)){console.warn(`Action '${actionData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}actionData.system.actionType.value==="passive"&&(actionData.img=getActionIcon("passive"));const{system}=actionData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),actions.push({type:actionData.type,name:actionData.name,img:actionData.img,uuid:`Compendium.${pack.collection}.${actionData._id}`,traits:actionData.system.traits.value,actionType:actionData.system.actionType.value,category:actionData.system.category,source:sourceSlug})}}this.indexData=actions,this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.actionTraits),this.filterData.checkboxes.types.options=this.generateCheckboxOptions(CONFIG.PF2E.actionTypes),this.filterData.checkboxes.category.options=this.generateCheckboxOptions(pick$1(CONFIG.PF2E.actionCategories,["familiar"])),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading actions")}filterIndexData(entry){const{checkboxes,multiselects}=this.filterData;return!(checkboxes.types.selected.length&&!checkboxes.types.selected.includes(entry.actionType)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source))}prepareFilterData(){return{checkboxes:{types:{isExpanded:!0,label:"PF2E.ActionActionTypeLabel",options:{},selected:[]},category:{isExpanded:!0,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"name",direction:"asc",options:{name:"PF2E.BrowserSortyByNameLabel"}},search:{text:""}}}};__name2(_CompendiumBrowserActionTab,"CompendiumBrowserActionTab");let CompendiumBrowserActionTab=_CompendiumBrowserActionTab;const _CompendiumBrowserBestiaryTab=class extends CompendiumBrowserTab{static{__name(this,"_CompendiumBrowserBestiaryTab")}tabName="bestiary";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/bestiary.hbs";index=["img","system.details.alignment.value","system.details.level.value","system.details.publication.title","system.details.source.value","system.traits"];searchFields=["name"];storeFields=["type","name","img","uuid","level","alignment","actorSize","traits","rarity","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){const bestiaryActors=[],publications=new Set,indexFields=[...this.index];for await(const{pack,index}of this.browser.packLoader.loadPacks("Actor",this.browser.loadedPacks("bestiary"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const actorData of index.filter(d=>d.type==="npc")){if(!this.hasAllIndexFields(actorData,this.index)){console.warn(`Actor '${actorData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const{details}=actorData.system,pubSource=String(details.publication?.title??details.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),bestiaryActors.push({type:actorData.type,name:actorData.name,img:actorData.img,uuid:`Compendium.${pack.collection}.${actorData._id}`,level:actorData.system.details.level.value,alignment:actorData.system.details.alignment.value,actorSize:actorData.system.traits.size.value,traits:actorData.system.traits.value,rarity:actorData.system.traits.rarity,source:sourceSlug})}console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loaded`)}this.indexData=bestiaryActors,this.filterData.checkboxes.sizes.options=this.generateCheckboxOptions(CONFIG.PF2E.actorSizes),this.filterData.checkboxes.alignments.options=this.generateCheckboxOptions(CONFIG.PF2E.alignments,!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.creatureTraits),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading Bestiary actors")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.sizes.selected.length&&!checkboxes.sizes.selected.includes(entry.actorSize)||checkboxes.alignments.selected.length&&!checkboxes.alignments.selected.includes(entry.alignment)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{sizes:{isExpanded:!0,label:"PF2E.BrowserFilterSizes",options:{},selected:[]},alignments:{isExpanded:!1,label:"PF2E.BrowserFilterAlignments",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"PF2E.BrowserSortyByNameLabel",level:"PF2E.BrowserSortyByLevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:-1,upperLimit:25,min:-1,max:25,step:1}}},search:{text:""}}}};__name2(_CompendiumBrowserBestiaryTab,"CompendiumBrowserBestiaryTab");let CompendiumBrowserBestiaryTab=_CompendiumBrowserBestiaryTab;const _CompendiumBrowserCampaignFeaturesTab=class extends CompendiumBrowserTab{static{__name(this,"_CompendiumBrowserCampaignFeaturesTab")}tabName="campaignFeature";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/feat.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","traits","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading feats");const feats=[],publications=new Set,indexFields=["img","system.actionType.value","system.actions.value","system.category","system.level.value","system.prerequisites.value","system.traits","system.publication","system.source"];for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("campaignFeature"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const featData of index.filter(i=>i.type==="campaignFeature")){featData.filters={};const{system}=featData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),feats.push({type:featData.type,name:featData.name,img:featData.img,uuid:`Compendium.${pack.collection}.${featData._id}`,level:featData.system.level?.value,category:featData.system.category,traits:featData.system.traits.value,rarity:featData.system.traits.rarity,source:sourceSlug})}}this.indexData=feats,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(KINGMAKER_CATEGORIES),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.kingmakerTraits),console.debug("PF2e System | Compendium Browser | Finished loading feats")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData,entryLevel=entry.level??0;return!(!(entryLevel>=sliders.level.values.min&&entryLevel<=sliders.level.values.max)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!1,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"PF2E.BrowserSortyByNameLabel",level:"PF2E.BrowserSortyByLevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:20,min:0,max:20,step:1}}},search:{text:""}}}};__name2(_CompendiumBrowserCampaignFeaturesTab,"CompendiumBrowserCampaignFeaturesTab");let CompendiumBrowserCampaignFeaturesTab=_CompendiumBrowserCampaignFeaturesTab;const _CompendiumBrowserEquipmentTab=class extends CompendiumBrowserTab{static{__name(this,"_CompendiumBrowserEquipmentTab")}constructor(browser){super(browser),__publicField(this,"tabName","equipment"),__publicField(this,"filterData"),__publicField(this,"templatePath","systems/pf2e/templates/compendium-browser/partials/equipment.hbs"),__publicField(this,"searchFields",["name"]),__publicField(this,"storeFields",["type","name","img","uuid","level","category","group","price","priceInCopper","traits","rarity","source"]),__privateAdd(this,_localizeCoins,localizer("PF2E.CurrencyAbbreviations")),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading inventory items");const inventoryItems=[],itemTypes=["weapon","armor","equipment","consumable","treasure","backpack","kit"],kitFields=["img","system.price","system.traits"],baseFields=[...kitFields,"system.stackGroup","system.level.value","system.publication","system.source"],armorFields=[...baseFields,"system.category","system.group","system.potencyRune.value"],weaponFields=[...armorFields,"system.strikingRune.value","system.potencyRune.value"],consumableFields=[...baseFields,"system.consumableType.value"],indexFields=[...new Set([...armorFields,...weaponFields,...consumableFields]),"system.denomination.value","system.value.value"],publications=new Set;for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("equipment"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const itemData of index)if(!(itemData.type==="treasure"&&itemData.system.stackGroup==="coins")&&itemTypes.includes(itemData.type)){if((()=>{switch(itemData.type){case"armor":return!this.hasAllIndexFields(itemData,armorFields);case"weapon":return!this.hasAllIndexFields(itemData,weaponFields);case"kit":return!this.hasAllIndexFields(itemData,kitFields);case"consumable":return!this.hasAllIndexFields(itemData,consumableFields);default:return!this.hasAllIndexFields(itemData,baseFields)}})()){console.warn(`Item '${itemData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const priceValue=itemData.system.price.value,priceCoins=typeof priceValue=="string"?CoinsPF2e.fromString(priceValue):new CoinsPF2e(priceValue),coinValue=priceCoins.copperValue,{system}=itemData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource);const traits=itemData.system.traits.value??[];(itemData.type==="armor"&&itemData.system.potencyRune.value||itemData.type==="weapon"&&(itemData.system.strikingRune.value||itemData.system.potencyRune.value))&&traits.push("magical"),inventoryItems.push({type:itemData.type,name:itemData.name,img:itemData.img,uuid:`Compendium.${pack.collection}.${itemData._id}`,level:itemData.system.level?.value??0,category:itemData.system.category??"",group:itemData.system.group??"",price:priceCoins,priceInCopper:coinValue,traits:itemData.system.traits.value,rarity:itemData.system.traits.rarity,source:sourceSlug})}}this.indexData=inventoryItems,this.filterData.checkboxes.armorTypes.options=this.generateCheckboxOptions(CONFIG.PF2E.armorCategories),mergeObject(this.filterData.checkboxes.armorTypes.options,this.generateCheckboxOptions(CONFIG.PF2E.armorGroups)),this.filterData.checkboxes.weaponTypes.options=this.generateCheckboxOptions(CONFIG.PF2E.weaponCategories),mergeObject(this.filterData.checkboxes.weaponTypes.options,this.generateCheckboxOptions(CONFIG.PF2E.weaponGroups)),this.filterData.multiselects.traits.options=this.generateMultiselectOptions({...CONFIG.PF2E.armorTraits,...CONFIG.PF2E.consumableTraits,...CONFIG.PF2E.equipmentTraits,...CONFIG.PF2E.weaponTraits}),this.filterData.checkboxes.itemtypes.options=this.generateCheckboxOptions({weapon:"TYPES.Item.weapon",armor:"TYPES.Item.armor",equipment:"TYPES.Item.equipment",consumable:"TYPES.Item.consumable",treasure:"TYPES.Item.treasure",backpack:"TYPES.Item.backpack",kit:"TYPES.Item.kit"}),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading inventory items")}filterIndexData(entry){const{checkboxes,multiselects,ranges,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||!(entry.priceInCopper>=ranges.price.values.min&&entry.priceInCopper<=ranges.price.values.max)||checkboxes.itemtypes.selected.length>0&&!checkboxes.itemtypes.selected.includes(entry.type)||checkboxes.armorTypes.selected.length>0&&!this.arrayIncludes(checkboxes.armorTypes.selected,[entry.category,entry.group])||checkboxes.weaponTypes.selected.length>0&&!this.arrayIncludes(checkboxes.weaponTypes.selected,[entry.category,entry.group])||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length>0&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length>0&&!checkboxes.rarity.selected.includes(entry.rarity))}parseRangeFilterInput(name2,lower,upper){if(name2==="price"){const coins={cp:__privateGet(this,_localizeCoins).call(this,"cp"),sp:__privateGet(this,_localizeCoins).call(this,"sp"),gp:__privateGet(this,_localizeCoins).call(this,"gp"),pp:__privateGet(this,_localizeCoins).call(this,"pp")};for(const[english,translated]of Object.entries(coins))lower=lower.replaceAll(translated,english),upper=upper.replaceAll(translated,english);return{min:CoinsPF2e.fromString(lower).copperValue,max:CoinsPF2e.fromString(upper).copperValue,inputMin:lower,inputMax:upper}}return super.parseRangeFilterInput(name2,lower,upper)}prepareFilterData(){return{checkboxes:{itemtypes:{isExpanded:!0,label:"PF2E.BrowserFilterInventoryTypes",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},armorTypes:{isExpanded:!1,label:"PF2E.BrowserFilterArmorFilters",options:{},selected:[]},weaponTypes:{isExpanded:!1,label:"PF2E.BrowserFilterWeaponFilters",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"PF2E.BrowserSortyByNameLabel",level:"PF2E.BrowserSortyByLevelLabel",price:"PF2E.BrowserSortyByPriceLabel"}},ranges:{price:{changed:!1,isExpanded:!1,label:"PF2E.PriceLabel",values:{min:0,max:2e7,inputMin:`0${__privateGet(this,_localizeCoins).call(this,"cp")}`,inputMax:`200,000${__privateGet(this,_localizeCoins).call(this,"gp")}`}}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:30,min:0,max:30,step:1}}},search:{text:""}}}};_localizeCoins=new WeakMap,__name2(_CompendiumBrowserEquipmentTab,"CompendiumBrowserEquipmentTab");let CompendiumBrowserEquipmentTab=_CompendiumBrowserEquipmentTab;const _CompendiumBrowserFeatTab=class extends CompendiumBrowserTab{static{__name(this,"_CompendiumBrowserFeatTab")}constructor(browser){super(browser),__publicField(this,"tabName","feat"),__publicField(this,"filterData"),__publicField(this,"templatePath","systems/pf2e/templates/compendium-browser/partials/feat.hbs"),__publicField(this,"searchFields",["name"]),__publicField(this,"storeFields",["type","name","img","uuid","level","category","skills","traits","rarity","source"]),__privateAdd(this,_creatureTraits,CONFIG.PF2E.creatureTraits),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading feats");const feats=[],publications=new Set,indexFields=["img","system.actionType.value","system.actions.value","system.category","system.featType.value","system.level.value","system.prerequisites.value","system.traits","system.publication","system.source"],translatedSkills=Object.entries(CONFIG.PF2E.skillList).reduce((result,[key,value])=>({...result,[key]:game.i18n.localize(value).toLocaleLowerCase(game.i18n.lang)}),{}),skillList=Object.entries(translatedSkills);for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("feat"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const featData of index)if(featData.type==="feat"){featData.filters={};const categoryPaths=["system.category","system.featType.value"],nonCategoryPaths=indexFields.filter(f=>!categoryPaths.includes(f)),categoryPathFound=categoryPaths.some(p=>foundry.utils.hasProperty(featData,p));if(!this.hasAllIndexFields(featData,nonCategoryPaths)||!categoryPathFound){console.warn(`Feat "${featData.name}" does not have all required data fields.`,`Consider unselecting pack "${pack.metadata.label}" in the compendium browser settings.`);continue}const featType=featData.system.featType;isObject(featType)&&"value"in featType&&typeof featType.value=="string"&&(featData.system.category=featType.value,delete featData.system.featType);const prerequisitesArr=featData.system.prerequisites.value.map(prerequisite=>prerequisite?.value?prerequisite.value.toLowerCase():""),skills=new Set;for(const prereq of prerequisitesArr)for(const[key,value]of skillList)(prereq.includes(key)||prereq.includes(value))&&skills.add(key);const pubSource=featData.system.publication?.title??featData.system.source?.value??"",sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),feats.push({type:featData.type,name:featData.name,img:featData.img,uuid:`Compendium.${pack.collection}.Item.${featData._id}`,level:featData.system.level.value,category:featData.system.category,skills:[...skills],traits:featData.system.traits.value,rarity:featData.system.traits.rarity,source:sourceSlug})}}this.indexData=feats,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(CONFIG.PF2E.featCategories),this.filterData.checkboxes.skills.options=this.generateCheckboxOptions(CONFIG.PF2E.skillList),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.featTraits),console.debug("PF2e System | Compendium Browser | Finished loading feats")}filterTraits(traits,selected,condition){if(this.filterData.checkboxes.category.selected.includes("ancestry")&&!traits.some(t=>t in __privateGet(this,_creatureTraits))){const withoutAncestryTraits=selected.filter(t=>!(t.value in __privateGet(this,_creatureTraits)));return super.filterTraits(traits,withoutAncestryTraits,condition)}return super.filterTraits(traits,selected,condition)}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||checkboxes.skills.selected.length&&!this.arrayIncludes(checkboxes.skills.selected,entry.skills)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!1,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},skills:{isExpanded:!1,label:"PF2E.BrowserFilterSkills",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"PF2E.BrowserSortyByNameLabel",level:"PF2E.BrowserSortyByLevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:20,min:0,max:20,step:1}}},search:{text:""}}}};_creatureTraits=new WeakMap,__name2(_CompendiumBrowserFeatTab,"CompendiumBrowserFeatTab");let CompendiumBrowserFeatTab=_CompendiumBrowserFeatTab;const _CompendiumBrowserHazardTab=class extends CompendiumBrowserTab{static{__name(this,"_CompendiumBrowserHazardTab")}tabName="hazard";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/hazard.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","complexity","traits","rarity","source"];index=["img","system.details.level.value","system.details.isComplex","system.traits"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading Hazard actors");const hazardActors=[],publications=new Set,indexFields=[...this.index,"system.details.alignment.value","system.details.publication","system.details.source"];for await(const{pack,index}of this.browser.packLoader.loadPacks("Actor",this.browser.loadedPacks("hazard"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const actorData of index.filter(d=>d.type==="hazard")){if(!this.hasAllIndexFields(actorData,this.index)){console.warn(`Hazard '${actorData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const{details}=actorData.system,pubSource=String(details.publication?.title??details.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),hazardActors.push({type:actorData.type,name:actorData.name,img:actorData.img,uuid:`Compendium.${pack.collection}.${actorData._id}`,level:actorData.system.details.level.value,complexity:actorData.system.details.isComplex?"complex":"simple",traits:actorData.system.traits.value,rarity:actorData.system.traits.rarity,source:sourceSlug})}console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loaded`)}this.indexData=hazardActors,this.filterData.checkboxes.complexity.options=this.generateCheckboxOptions({simple:"PF2E.Actor.Hazard.Simple",complex:"PF2E.TraitComplex"},!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.hazardTraits),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading Hazard actors")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.complexity.selected.length&&!checkboxes.complexity.selected.includes(entry.complexity)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{complexity:{isExpanded:!0,label:"PF2E.BrowserFilterComplexity",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"PF2E.BrowserSortyByNameLabel",level:"PF2E.BrowserSortyByLevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:-1,upperLimit:25,min:-1,max:25,step:1}}},search:{text:""}}}};__name2(_CompendiumBrowserHazardTab,"CompendiumBrowserHazardTab");let CompendiumBrowserHazardTab=_CompendiumBrowserHazardTab;const _CompendiumBrowserSpellTab=class extends CompendiumBrowserTab{static{__name(this,"_CompendiumBrowserSpellTab")}tabName="spell";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/spell.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","time","category","traditions","traits","rarity","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading spells");const spells=[],times=new Set,publications=new Set,indexFields=["img","system.level.value","system.category.value","system.traditions.value","system.time","system.traits","system.publication","system.source"],data=this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("spell"),indexFields);for await(const{pack,index}of data){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const spellData of index)if(spellData.filters={},spellData.type==="spell"){if(!this.hasAllIndexFields(spellData,indexFields)){console.warn(`Item '${spellData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}spellData.system.traits.value.includes("cantrip")&&(spellData.system.category.value="cantrip");let time=spellData.system.time.value;time&&(time.includes("reaction")&&(time="reaction"),times.add(time),spellData.system.time.value=sluggify(time)),spellData.system.time.value==="reaction"?spellData.system.time.img=getActionIcon("reaction"):spellData.system.time.value==="free"?spellData.system.time.img=getActionIcon("free"):spellData.system.time.img=getActionIcon(spellData.system.time.value),spellData.system.time.img==="systems/pf2e/icons/actions/Empty.webp"&&(spellData.system.time.img="systems/pf2e/icons/actions/LongerAction.webp");const{system}=spellData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),spells.push({type:spellData.type,name:spellData.name,img:spellData.img,uuid:`Compendium.${pack.collection}.${spellData._id}`,level:spellData.system.level.value,time:spellData.system.time,category:spellData.system.category.value,traditions:spellData.system.traditions.value,traits:spellData.system.traits.value,rarity:spellData.system.traits.rarity,source:sourceSlug})}}this.indexData=spells,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(CONFIG.PF2E.spellCategories),this.filterData.checkboxes.category.options.cantrip={label:"PF2E.TraitCantrip",selected:!1},this.filterData.checkboxes.traditions.options=this.generateCheckboxOptions(CONFIG.PF2E.magicTraditions);for(let rank=1;rank<=10;rank++)this.filterData.checkboxes.level.options[rank]={label:game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),selected:!1};this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.spellTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.selects.timefilter.options=[...times].sort().reduce((result,time)=>({...result,[sluggify(time)]:time}),{}),console.debug("PF2e System | Compendium Browser | Finished loading spells")}filterIndexData(entry){const{checkboxes,multiselects,selects}=this.filterData;return!(checkboxes.level.selected.length&&!checkboxes.level.selected.map(level=>Number(level)).includes(entry.level)||selects.timefilter.selected&&selects.timefilter.selected!==entry.time.value||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||checkboxes.traditions.selected.length&&!this.arrayIncludes(checkboxes.traditions.selected,entry.traditions)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!0,label:"PF2E.BrowserFilterSpellCategories",options:{},selected:[]},traditions:{isExpanded:!0,label:"PF2E.BrowserFilterTraditions",options:{},selected:[]},level:{isExpanded:!0,label:"PF2E.BrowserFilterLevels",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},selects:{timefilter:{label:"PF2E.BrowserFilterCastingTime",options:{},selected:""}},order:{by:"level",direction:"asc",options:{name:"PF2E.BrowserSortyByNameLabel",level:"PF2E.BrowserSortyByLevelLabel"}},search:{text:""}}}};__name2(_CompendiumBrowserSpellTab,"CompendiumBrowserSpellTab");let CompendiumBrowserSpellTab=_CompendiumBrowserSpellTab;const _CompendiumBrowser=class extends Application{static{__name(this,"_CompendiumBrowser")}constructor(options={}){super(options),__privateAdd(this,_resetInitializedTabs),__privateAdd(this,_renderResultList),__privateAdd(this,_activateResultListeners),__privateAdd(this,_takePhysicalItem),__privateAdd(this,_buyPhysicalItem),__privateAdd(this,_getPhysicalItem),__privateAdd(this,_resetFilters),__privateAdd(this,_clearScrollLimit),__publicField(this,"settings"),__publicField(this,"dataTabsList",["action","bestiary","campaignFeature","equipment","feat","hazard","spell"]),__publicField(this,"navigationTab"),__publicField(this,"tabs"),__publicField(this,"packLoader",new PackLoader),this.settings=game.settings.get("pf2e","compendiumBrowserPacks"),this.navigationTab=this.hookTab(),this.tabs={action:new CompendiumBrowserActionTab(this),bestiary:new CompendiumBrowserBestiaryTab(this),campaignFeature:new CompendiumBrowserCampaignFeaturesTab(this),equipment:new CompendiumBrowserEquipmentTab(this),feat:new CompendiumBrowserFeatTab(this),hazard:new CompendiumBrowserHazardTab(this),spell:new CompendiumBrowserSpellTab(this)},this.initCompendiumList()}get title(){return game.i18n.localize("PF2E.CompendiumBrowser.Title")}static get defaultOptions(){return{...super.defaultOptions,id:"compendium-browser",classes:[],template:"systems/pf2e/templates/compendium-browser/compendium-browser.hbs",width:800,height:700,resizable:!0,dragDrop:[{dragSelector:"ul.item-list > li.item"}],tabs:[{navSelector:"nav",contentSelector:"section.content",initial:"landing-page"},{navSelector:"nav[data-group=settings]",contentSelector:".settings-container",initial:"packs"}],scrollY:[".control-area",".item-list",".settings-container"]}}async close(options){for(const tab of Object.values(this.tabs))tab.filterData.search.text="";await super.close(options)}hookTab(){const navigationTab=this._tabs[0],tabCallback=navigationTab.callback;return navigationTab.callback=async(event,tabs,active)=>{tabCallback?.(event,tabs,active),await this.loadTab(active)},navigationTab}initCompendiumList(){const settings={action:{},bestiary:{},campaignFeature:{},hazard:{},equipment:{},feat:{},spell:{}},loadDefault={bestiary:!0,hazard:!0,"pf2e.actionspf2e":!0,"pf2e.familiar-abilities":!0,"pf2e.equipment-srd":!0,"pf2e.ancestryfeatures":!0,"pf2e.classfeatures":!0,"pf2e.feats-srd":!0,"pf2e.spells-srd":!0,"pf2e.kingmaker-features":!0},browsableTypes=new Set(["action","campaignFeature","feat","kit","hazard","npc","spell",...PHYSICAL_ITEM_TYPES]),typeToTab=new Map([["action","action"],["campaignFeature","campaignFeature"],["feat","feat"],["kit","equipment"],["hazard","hazard"],["npc","bestiary"],["spell","spell"],...Array.from(PHYSICAL_ITEM_TYPES).map(t=>[t,"equipment"])]);for(const pack of game.packs){const tabNames=uniq(uniq(pack.index.map(entry=>entry.type)).filter(t=>setHasElement(browsableTypes,t)).flatMap(t=>typeToTab.get(t)??[]));for(const tabName of tabNames){const load=this.settings[tabName]?.[pack.collection]?.load??loadDefault[tabName]??!!loadDefault[pack.collection];settings[tabName][pack.collection]={load,name:pack.metadata.label,package:pack.metadata.packageName}}}for(const tab of this.dataTabsList)settings[tab]=Object.fromEntries(Object.entries(settings[tab]).sort(([_collectionA,dataA],[_collectionB,dataB])=>(dataA?.name??"")>(dataB?.name??"")?1:-1));this.settings=settings}async openTab(tabName,filter2){return this.activeTab=tabName,tabName!=="settings"&&filter2?this.tabs[tabName].open(filter2):this.loadTab(tabName)}async openActionTab(options){const actionTab=this.tabs.action,filter2=await actionTab.getFilterData(),{types}=filter2.checkboxes,{traits}=filter2.multiselects;types.selected=[];for(const type in types.options)options.types?.includes(type)&&(types.options[type].selected=!0,types.selected.push(type));const traitFilters=options.traits??[];if(traits.selected=traitFilters.length?traits.options.filter(trait=>traitFilters.includes(trait.value)):[],options.categories?.length){const optionsToSwitch=pick$1(filter2.checkboxes.category.options,options.categories);Object.values(optionsToSwitch).forEach(o=>o.selected=!0),filter2.checkboxes.category.selected=Object.keys(optionsToSwitch)}actionTab.open(filter2)}async openSpellTab(entry,maxLevel=10){const spellTab=this.tabs.spell,filter2=await spellTab.getFilterData(),{category,level,traditions}=filter2.checkboxes;if((entry.isRitual||entry.isFocusPool)&&(category.options[entry.category].selected=!0,category.selected.push(entry.category)),maxLevel){const levels=Array.from(Array(maxLevel).keys()).map(l=>String(l+1));for(const l of levels)level.options[l].selected=!0,level.selected.push(l);(entry.isPrepared||entry.isSpontaneous||entry.isInnate)&&(category.options.spell.selected=!0,category.selected.push("spell"))}entry.tradition&&!entry.isFocusPool&&!entry.isRitual&&(traditions.options[entry.tradition].selected=!0,traditions.selected.push(entry.tradition)),spellTab.open(filter2)}async loadTab(tabName){if(this.activeTab=tabName,tabName==="settings"){await this.packLoader.updateSources(this.loadedPacksAll()),await this.render(!0);return}if(!this.dataTabsList.includes(tabName))throw ErrorPF2e(`Unknown tab "${tabName}"`);const currentTab=this.tabs[tabName];currentTab.isInitialized||await currentTab.init(),await this.render(!0,{focus:!0})}loadedPacks(tab){return tab==="settings"?[]:Object.entries(this.settings[tab]??[]).flatMap(([collection,info])=>info?.load?[collection]:[])}loadedPacksAll(){return uniq(this.dataTabsList.flatMap(t=>this.loadedPacks(t))).sort()}activateListeners($html){super.activateListeners($html);const html=$html[0],activeTabName=this.activeTab;if(this.navigationTab.active!==activeTabName&&this.navigationTab.activate(activeTabName),activeTabName==="settings"){const settings=htmlQuery(html,".compendium-browser-settings"),form=settings?.querySelector("form");if(!form)return;htmlQuery(settings,"button[data-action=save-settings]")?.addEventListener("click",async()=>{const formData=new FormData(form);for(const[t,packs]of Object.entries(this.settings))for(const[key,pack]of Object.entries(packs))pack.load=formData.has(`${t}-${key}`);await game.settings.set("pf2e","compendiumBrowserPacks",this.settings);for(const[key,source]of Object.entries(this.packLoader.sourcesSettings.sources)){if(!source||isBlank(source.name)){delete this.packLoader.sourcesSettings.sources[key];continue}source.load=formData.has(`source-${key}`)}this.packLoader.sourcesSettings.showEmptySources=formData.has("show-empty-sources"),this.packLoader.sourcesSettings.showUnknownSources=formData.has("show-unknown-sources"),this.packLoader.sourcesSettings.ignoreAsGM=formData.has("ignore-as-gm"),await game.settings.set("pf2e","compendiumBrowserSources",this.packLoader.sourcesSettings),await __privateMethod(this,_resetInitializedTabs,resetInitializedTabs_fn).call(this),this.render(!0),ui.notifications.info("PF2E.BrowserSettingsSaved",{localize:!0})});const sourceSearch=htmlQuery(form,"input[data-element=setting-sources-search]"),sourceToggle=htmlQuery(form,"input[data-action=setting-sources-toggle-visible]"),sourceSettings=htmlQueryAll(form,"label[data-element=setting-source]");sourceSearch?.addEventListener("input",()=>{const value=sourceSearch.value?.trim().toLocaleLowerCase(game.i18n.lang);for(const element of sourceSettings){const name2=element.dataset.name?.toLocaleLowerCase(game.i18n.lang),shouldBeHidden=!isBlank(value)&&!isBlank(name2)&&!name2.includes(value);element.classList.toggle("hidden",shouldBeHidden)}sourceToggle&&(sourceToggle.checked=!1)}),sourceToggle?.addEventListener("click",()=>{for(const element of sourceSettings){const checkbox=htmlQuery(element,"input[type=checkbox]");!element.classList.contains("hidden")&&checkbox&&(checkbox.checked=sourceToggle.checked)}}),htmlQuery(form,"button[data-action=settings-sources-delete]")?.addEventListener("click",async()=>{const localize=localizer("PF2E.SETTINGS.CompendiumBrowserSources");await Dialog.confirm({title:localize("DeleteAllTitle"),content:`
+}`,toggleMacro=game.macros.find(m=>m.name===name2&&m.command===command)??await MacroPF2e.create({type:"script",name:name2,img:item.img,command},{renderSheet:!1})??null;await game.user.assignHotbarMacro(toggleMacro,slot)}}class ActorDirectoryPF2e extends ActorDirectory{static{__name(this,"ActorDirectoryPF2e")}static{__name2(this,"ActorDirectoryPF2e")}static entryPartial="systems/pf2e/templates/sidebar/actor-document-partial.hbs";#extraFolders={};#renderedOnce=!1;#draggingParty=!1;static get defaultOptions(){const options=super.defaultOptions;return options.renderUpdateKeys.push("system.details.level.value","system.attributes.adjustment","system.details.members","system.campaign.type"),options}async getData(){const activeParty=game.actors.party;this.#renderedOnce||(activeParty&&game.settings.get("pf2e","activePartyFolderState")&&(this.#extraFolders[activeParty.id]=!0),this.#renderedOnce=!0);const parties=sortBy(this.documents.filter(a=>a.isOfType("party")&&a!==activeParty),p=>p.sort);return{...await super.getData(),activeParty,parties,placePartiesInSubfolder:parties.length>1,extraFolders:this.#extraFolders}}saveActivePartyFolderState(){game.settings.set("pf2e","activePartyFolderState",this.#extraFolders[game.actors.party?.id??""]??!0)}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const element of htmlQueryAll(html,"li.directory-item.actor"))game.actors.get(element.dataset.documentId??"")?.testUserPermission(game.user,"OBSERVER")||element.querySelector("span.actor-level")?.remove();for(const folderLike of htmlQueryAll(html,".folder-like")){const header=htmlQuery(folderLike,":scope > header");if(!header)continue;for(const eventType of["dragenter","dragleave","dragend"])folderLike.addEventListener(eventType,event2=>{this.#onDragHighlightFolderLike(folderLike,event2)});header.addEventListener("click",event2=>{const folderEl=htmlClosest(event2.target,".folder-like"),entryId=htmlClosest(event2.target,"[data-entry-id]")?.dataset.entryId??"";folderEl&&entryId&&(event2.stopPropagation(),this.#extraFolders[entryId]=folderEl.classList.contains("collapsed"),folderEl.classList.toggle("collapsed",!this.#extraFolders[entryId]),this.popOut&&this.setPosition(),this.saveActivePartyFolderState())});const openSheetLink=htmlQuery(header,"a[data-action=open-sheet]");openSheetLink?.addEventListener("click",event2=>{event2.stopPropagation();const documentId=htmlClosest(openSheetLink,"[data-document-id]")?.dataset.documentId;game.actors.get(documentId??"")?.sheet.render(!0)});const createMemberLink=htmlQuery(header,"a[data-action=create-member]");createMemberLink?.addEventListener("click",async event2=>{event2.preventDefault(),event2.stopPropagation();const documentId=htmlClosest(createMemberLink,"[data-document-id]")?.dataset.documentId,party=game.actors.get(documentId??"");if(!party?.isOfType("party"))return;const button=event2.currentTarget,actor=await ActorPF2e.createDialog({},{width:320,left:window.innerWidth-630,top:button?.offsetTop??0,types:["creature"]});actor?.isOfType("creature")&&(this.#extraFolders[party.id]=!0,await party.addMembers(actor))});const createPartyLink=htmlQuery(header,"a[data-action=create-party]");createPartyLink?.addEventListener("click",async event2=>{event2.stopPropagation(),(await ActorPF2e.create({type:"party",name:"New Party"}))?.sheet.render(!0);const entryId=htmlClosest(createPartyLink,".folder-like")?.dataset.entryId;entryId&&(this.#extraFolders[entryId]=!0,this.render())});const activatePartyLink=htmlQuery(header,"a[data-action=activate-party]");activatePartyLink?.addEventListener("click",event2=>{event2.stopPropagation();const documentId=htmlClosest(activatePartyLink,"[data-document-id]")?.dataset.documentId??"";game.actors.has(documentId)&&(game.settings.set("pf2e","activeParty",documentId),this.saveActivePartyFolderState())})}this.#appendBrowseButton(html)}_onSearchFilter(event2,query,rgx,html){super._onSearchFilter(event2,query,rgx,html);const folderLikes=htmlQueryAll(html,".folder-like");for(const folderLike of folderLikes)if(query!==""&&htmlQueryAll(folderLike,".actor").some(li=>li.style.display!=="none")){folderLike.removeAttribute("style"),folderLike.classList.remove("collapsed");const folderLikeHeader=htmlQuery(folderLike,":scope > header");folderLikeHeader&&folderLikeHeader.removeAttribute("style")}else{const entryId=folderLike.dataset.entryId??"";folderLike.classList.toggle("collapsed",!this.#extraFolders[entryId])}}_onDragStart(event2){if(event2.target.dataset.entryId==="otherParties"){event2.preventDefault();return}super._onDragStart(event2);const fromParty=htmlClosest(event2.target,".party")?.dataset.documentId;if(fromParty){const data=JSON.parse(event2.dataTransfer.getData("text/plain"));data.fromParty=fromParty,this.#draggingParty=fromUuidSync(data.uuid)instanceof PartyPF2e,event2.dataTransfer.setData("text/plain",JSON.stringify(data))}else this.#draggingParty=!1}_onDragHighlight(event2){if(event2.type==="dragenter"&&this.#draggingParty)return event2.stopPropagation();super._onDragHighlight(event2)}#onDragHighlightFolderLike(folderLike,event2){event2.stopPropagation(),!this.#draggingParty&&(event2.type==="dragleave"&&document.elementFromPoint(event2.clientX,event2.clientY)?.closest(".folder-like")===folderLike||folderLike?.classList.toggle("droptarget",event2.type==="dragenter"))}async _handleDroppedEntry(target,data){await super._handleDroppedEntry(target,data);const toPartyId=htmlClosest(target,".party")?.dataset.documentId;if(toPartyId!==data.fromParty&&data.uuid){const toParty=game.actors.get(toPartyId??""),fromParty=game.actors.get(data.fromParty??""),actor=fromUuidSync(data.uuid);fromParty instanceof PartyPF2e&&await fromParty.removeMembers(data.uuid),toParty instanceof PartyPF2e&&actor instanceof CreaturePF2e&&await toParty.addMembers(actor)}}async _renderInner(data){const $element=await super._renderInner(data);if(game.actors.some(a=>a.isOfType("party"))){const partyHTML=await renderTemplate("systems/pf2e/templates/sidebar/party-document-partial.hbs",data);$element.find(".directory-list").prepend(partyHTML);for(const header of htmlQueryAll($element.get(0),".party")){const party=game.actors.get(header.dataset.documentId??""),sidebarButtons=party?.isOfType("party")?party.campaign?.createSidebarButtons?.()??[]:[];header.querySelector("header h3")?.after(...sidebarButtons)}}return $element}async _render(force,context={}){return context=foundry.utils.deepClone(context),context.action==="update"&&context.documentType==="Actor"&&context.data&&(context.data=context.data.map(d=>({...d,...foundry.utils.flattenObject(d)}))),super._render(force,context)}_contextMenu($html){super._contextMenu($html),ContextMenu.create(this,$html,".party .party-header",this._getPartyContextOptions())}_getEntryContextOptions(){const options=super._getEntryContextOptions();return options.push({name:"PF2E.Actor.Party.Sidebar.RemoveMember",icon:fontAwesomeIcon("bus").outerHTML,condition:$li=>$li.closest(".party").length>0&&!$li.closest(".party-header").length,callback:$li=>{const actorId=$li.data("document-id"),partyId=$li.closest(".party").data("document-id"),actor=game.actors.get(actorId??""),party=game.actors.get(partyId??"");actor&&party instanceof PartyPF2e&&party.removeMembers(actor.uuid)}}),options}_getPartyContextOptions(){const allOptions=super._getEntryContextOptions(),relevantNames=["SIDEBAR.CharArt","SIDEBAR.TokenArt","OWNERSHIP.Configure","SIDEBAR.Delete"],relevantOptions=allOptions.filter(o=>relevantNames.includes(o.name));return relevantOptions.length!==relevantNames.length&&console.error("PF2E System | Failed to extract all sidebar options from the base options"),relevantOptions}#appendBrowseButton(html){if(!game.user.isGM)return;const browseButton=document.createElement("button");browseButton.type="button",browseButton.append(fontAwesomeIcon("search",{fixedWidth:!0})," ",game.i18n.localize("PF2E.CompendiumBrowser.BestiaryBrowser")),browseButton.addEventListener("click",()=>{game.pf2e.compendiumBrowser.openTab("bestiary")}),htmlQuery(html,"footer.directory-footer")?.append(browseButton)}}class ItemDirectoryPF2e extends ItemDirectory{static{__name(this,"ItemDirectoryPF2e")}static{__name2(this,"ItemDirectoryPF2e")}static entryPartial="systems/pf2e/templates/sidebar/item-document-partial.hbs";static get defaultOptions(){const options=super.defaultOptions;return options.renderUpdateKeys.push("system.level.value"),options}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const element of htmlQueryAll(html,"li.directory-item.item"))game.items.get(element.dataset.documentId??"")?.testUserPermission(game.user,"OBSERVER")||element.querySelector("span.item-level")?.remove();this.#appendBrowseButton(html)}async _render(force,context={}){return context=foundry.utils.deepClone(context),context.action==="update"&&context.documentType==="Item"&&context.data&&(context.data=context.data.map(d=>({...d,...foundry.utils.flattenObject(d)}))),super._render(force,context)}#appendBrowseButton(html){const browseButton=document.createElement("button");browseButton.type="button",browseButton.append(fontAwesomeIcon("search",{fixedWidth:!0})," ",game.i18n.localize("PF2E.CompendiumBrowser.Title")),browseButton.addEventListener("click",()=>{game.pf2e.compendiumBrowser.render(!0,{focus:!0})}),htmlQuery(html,"footer.directory-footer")?.append(browseButton)}}async function handleKingdomChatMessageEvents(options){const{event:event2,message}=options,party=message.actor??game.actors.party;if(!(!party?.isOfType("party")||!(party?.campaign instanceof Kingdom))&&htmlClosest(event2.target,"[data-action=kingdom-collect]")){if(!party.isOwner)return;await party.campaign.collect();const content=createHTMLElement("div",{innerHTML:message.content});htmlQuery(content,"[data-action=kingdom-collect]")?.replaceWith(createHTMLElement("div",{classes:["confirmation"],children:[fontAwesomeIcon("fa-check"),"Resources Collected"]})),message.update({content:content.innerHTML})}}__name(handleKingdomChatMessageEvents,"handleKingdomChatMessageEvents"),__name2(handleKingdomChatMessageEvents,"handleKingdomChatMessageEvents");class ChatLogPF2e extends ChatLog{static{__name(this,"ChatLogPF2e")}static{__name2(this,"ChatLogPF2e")}activateListeners($html){super.activateListeners($html);const html=$html[0],log=htmlQuery(html,"#chat-log");log&&(log.dataset.tooltipDirection="UP"),this.activateClickListener(html),html.addEventListener("dblclick",async event2=>{const{message}=ChatLogPF2e.#messageFromEvent(event2);if((message?htmlClosest(event2.target,".message-sender"):null)&&message)return this.#onClickSender(message,event2)})}activateClickListener(html){html.addEventListener("click",async event2=>{const{message,element:messageEl}=ChatLogPF2e.#messageFromEvent(event2);if(!message)return;if((message?htmlClosest(event2.target,".message-sender"):null)&&message)return this.#onClickSender(message,event2);const button=htmlClosest(event2.target,"button[data-action]");if(button){if(message.isDamageRoll){const button2=htmlClosest(event2.target,"button");if(!button2)return;if(button2.dataset.action==="shield-block")return this.#onClickShieldBlock(button2,messageEl);const actions=["apply-damage","apply-healing","double-damage","half-damage","triple-damage"];for(const action2 of actions)if(button2.dataset.action===action2){const index=htmlClosest(button2,".damage-application")?.dataset.rollIndex;return this.#onClickDamageButton(message,action2,event2.shiftKey,index)}}else if(button.dataset.action==="revert-damage"){const appliedDamageFlag=message?.flags.pf2e.appliedDamage;appliedDamageFlag&&await this.#onClickRevertDamage(appliedDamageFlag)&&(htmlQuery(messageEl,"span.statements")?.classList.add("reverted"),button.remove(),await message.update({"flags.pf2e.appliedDamage.isReverted":!0,content:htmlQuery(messageEl,".message-content")?.innerHTML??message.content}))}message&&messageEl&&handleKingdomChatMessageEvents({event:event2,message,messageEl})}})}_onDiceRollClick(event2){const message=ChatLogPF2e.#messageFromEvent(event2.originalEvent).message;if(message&&htmlClosest(event2.target,"button[data-action=set-as-initiative]"))event2.stopPropagation(),this.#onClickSetAsInitiative(message);else return super._onDiceRollClick(event2)}async _processDiceCommand(command,matches,chatData,createOptions){const rollData=(ChatMessage.getSpeakerActor(chatData.speaker??{})||game.user.character)?.getRollData()??{},rolls=[];for(const match of matches.filter(m=>!!m)){const[formula,flavor]=match.slice(2,4);flavor&&!chatData.flavor&&(chatData.flavor=flavor);const roll=(()=>{try{const damageRoll=new DamageRoll(formula,rollData);return looksLikeDamageRoll(damageRoll)?damageRoll:new Roll(formula,rollData)}catch{return new Roll(formula,rollData)}})();rolls.push(await roll.evaluate({async:!0}))}chatData.type=CONST.CHAT_MESSAGE_TYPES.ROLL,chatData.rolls=rolls.map(r=>r.toJSON()),chatData.sound=CONFIG.sounds.dice,chatData.content=rolls.reduce((t,r)=>t+r.total,0).toString(),createOptions.rollMode=objectHasKey(CONFIG.Dice.rollModes,command)?command:"roll"}static#messageFromEvent(event2){const element=htmlClosest(event2?.target,"li[data-message-id]"),messageId=element?.dataset.messageId??"",message=game.messages.get(messageId);return element&&message?{element,message}:{element:null,message:null}}#onClickDamageButton(message,action2,shiftKey,index){const multiplier=(()=>{switch(action2){case"apply-healing":return-1;case"half-damage":return .5;case"apply-damage":return 1;case"double-damage":return 2;case"triple-damage":return 3}})();applyDamageFromMessage({message,multiplier,addend:0,promptModifier:shiftKey,rollIndex:Number(index)||0})}async#onClickRevertDamage(flag){const actorOrToken=fromUuidSync(flag.uuid),actor=actorOrToken instanceof ActorPF2e?actorOrToken:actorOrToken instanceof TokenDocumentPF2e?actorOrToken.actor:null;return actor?(await actor.undoDamage(flag),ui.notifications.info(game.i18n.format(`PF2E.RevertDamage.${flag.isHealing?"Healing":"Damage"}Message`,{actor:actor.name})),!0):!1}#onClickShieldBlock(shieldButton,messageEl){const getTokens=__name2(()=>{const tokens=game.user.getActiveTokens();return tokens.length||ui.notifications.error("PF2E.ErrorMessage.NoTokenSelected",{localize:!0}),tokens},"getTokens"),getNonBrokenShields=__name2(tokens=>tokens.find(t=>!!t.actor)?.actor?.itemTypes.shield.filter(s=>s.isEquipped&&!s.isBroken&&!s.isDestroyed)??[],"getNonBrokenShields");shieldButton.classList.contains("tooltipstered")||$(shieldButton).tooltipster({animation:"fade",trigger:"click",arrow:!1,content:$(messageEl).find("div.hover-content"),contentAsHTML:!0,contentCloning:!0,debug:!1,interactive:!0,side:["top"],theme:"crb-hover",functionBefore:()=>{const tokens=getTokens();if(!tokens.length)return!1;const nonBrokenShields=getNonBrokenShields(tokens),hasMultipleShields=tokens.length===1&&nonBrokenShields.length>1,shieldActivated=shieldButton.classList.contains("shield-activated");return hasMultipleShields&&!shieldActivated?!0:hasMultipleShields&&shieldButton.dataset.shieldId?(shieldButton.attributes.removeNamedItem("data-shield-id"),shieldButton.classList.remove("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!1,!0):(shieldButton.classList.toggle("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!CONFIG.PF2E.chatDamageButtonShieldToggle,!1)},functionFormat:(instance,_helper,$content)=>{const tokens=getTokens(),nonBrokenShields=getNonBrokenShields(tokens),multipleShields=tokens.length===1&&nonBrokenShields.length>1,shieldActivated=shieldButton.classList.contains("shield-activated");if(multipleShields&&!shieldActivated){const content=$content[0],listEl=htmlQuery(content,"ul.shield-options");if(!listEl)return $content;const shieldList=[];for(const shield of nonBrokenShields){const input=document.createElement("input");input.classList.add("data"),input.type="radio",input.name="shield-id",input.value=shield.id,input.addEventListener("click",()=>{shieldButton.dataset.shieldId=input.value,shieldButton.classList.add("shield-activated"),CONFIG.PF2E.chatDamageButtonShieldToggle=!0,instance.close()});const shieldName=document.createElement("span");shieldName.classList.add("label"),shieldName.innerHTML=shield.name;const hardness=document.createElement("span");hardness.classList.add("tag");const hardnessLabel=game.i18n.localize("PF2E.HardnessLabel");hardness.innerHTML=`${hardnessLabel}: ${shield.hardness}`;const itemLi=document.createElement("li");itemLi.classList.add("item"),itemLi.append(input,shieldName,hardness),shieldList.push(itemLi)}listEl.replaceChildren(...shieldList)}return $content}}).tooltipster("open")}#onClickSender(message,event2){if(!canvas)return;const token=message.token?.object;if(token?.isVisible&&token.isOwner&&(token.controlled?token.release():token.control({releaseOthers:!event2.shiftKey}),event2.type==="dblclick")){const scale=Math.max(1,canvas.stage.scale.x);canvas.animatePan({...token.center,scale,duration:1e3})}}async#onClickSetAsInitiative(message){const{actor,token}=message;if(!token){ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:message.actor?.name??message.user?.name??""}));return}if(!actor)return;const combatant=await CombatantPF2e.fromActor(actor);if(!combatant)return;const value=message.rolls.at(0)?.total??0;await combatant.encounter.setInitiative(combatant.id,value),ui.notifications.info(game.i18n.format("PF2E.Encounter.InitiativeSet",{actor:token.name,initiative:value}))}_getEntryContextOptions(){const canApplyDamage=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});return canvas.tokens.controlled.length>0&&message.rolls.some(r=>r instanceof DamageRoll)},"canApplyDamage"),canApplyTripleDamage=__name2($li=>canApplyDamage($li)&&game.settings.get("pf2e","critFumbleButtons"),"canApplyTripleDamage"),canApplyInitiative=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),validActor=message.token?.actor?.type==="npc"&&(message.token.combatant?.initiative??null)===null,validRollType=message.isRoll&&message.isCheckRoll;return validActor&&validRollType},"canApplyInitiative"),canReroll=__name2($li=>game.messages.get($li[0].dataset.messageId,{strict:!0}).isRerollable,"canReroll"),canHeroPointReroll=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),{actor}=message;return message.isRerollable&&!!actor?.isOfType("character")&&actor.heroPoints.value>0},"canHeroPointReroll"),canShowRollDetails=__name2($li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});return game.user.isGM&&!!message.flags.pf2e.context},"canShowRollDetails"),options=super._getEntryContextOptions();return options.push({name:"PF2E.ChatRollDetails.Select",icon:fontAwesomeIcon("search").outerHTML,condition:canShowRollDetails,callback:$li=>{game.messages.get($li[0].dataset.messageId,{strict:!0}).showDetails()}},{name:"PF2E.DamageButton.FullContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message})}},{name:"PF2E.DamageButton.HalfContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:.5})}},{name:"PF2E.DamageButton.DoubleContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:2})}},{name:"PF2E.DamageButton.TripleContext",icon:fontAwesomeIcon("heart-broken").outerHTML,condition:canApplyTripleDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:3})}},{name:"PF2E.DamageButton.HealingContext",icon:fontAwesomeIcon("heart").outerHTML,condition:canApplyDamage,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});applyDamageFromMessage({message,multiplier:-1})}},{name:"PF2E.ClickToSetInitiativeContext",icon:fontAwesomeIcon("swords").outerHTML,condition:canApplyInitiative,callback:async $li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0}),{actor,token}=message;if(!token){ui.notifications.error(game.i18n.format("PF2E.Encounter.NoTokenInScene",{actor:message.actor?.name??message.user?.name??""}));return}if(!actor)return;const combatant=await CombatantPF2e.fromActor(actor);if(!combatant)return;const value=message.rolls.at(0)?.total??0;await combatant.encounter.setInitiative(combatant.id,value),ui.notifications.info(game.i18n.format("PF2E.Encounter.InitiativeSet",{actor:actor.name,initiative:value}))}},{name:"PF2E.RerollMenu.HeroPoint",icon:fontAwesomeIcon("hospital-symbol").outerHTML,condition:canHeroPointReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{heroPoint:!0})}},{name:"PF2E.RerollMenu.KeepNew",icon:fontAwesomeIcon("dice").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message)}},{name:"PF2E.RerollMenu.KeepLower",icon:fontAwesomeIcon("dice-one").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{keep:"lower"})}},{name:"PF2E.RerollMenu.KeepHigher",icon:fontAwesomeIcon("dice-six").outerHTML,condition:canReroll,callback:$li=>{const message=game.messages.get($li[0].dataset.messageId,{strict:!0});CheckPF2e.rerollFromMessage(message,{keep:"higher"})}}),options}}class CompendiumMigrationStatus extends Application{static{__name(this,"CompendiumMigrationStatus")}static{__name2(this,"CompendiumMigrationStatus")}compendium;static get defaultOptions(){const options=super.defaultOptions;return options.template="systems/pf2e/templates/system/compendium-migration-status.hbs",options.classes=["compendium-migration-status"],options.height="auto",options.title=game.i18n.localize("PF2E.CompendiumMigrationStatus.Title"),options}constructor(compendium){super(),this.compendium=compendium}get id(){return`compendium-info-${this.compendium.metadata.id}`}async getData(options){const index=await this.compendium.getIndex({fields:[foundry.utils.randomID(),"system._migration","system.schema","data.schema"]}),schemaVersion=Math.min(...index.map(d=>{const system=d.system??d.data;return Number(system?._migration?.version??system?.schema?.version)})),foundryVersion=pipe(Object.entries(MigrationRunner.FOUNDRY_SCHEMA_VERSIONS),sortBy(([_,schema])=>schema),findLast(([_,schema])=>schemaVersion>=schema))?.[0]??game.i18n.localize("PF2E.CompendiumMigrationStatus.FoundryOld");return{...await super.getData(options),compendium:this.compendium,schemaVersion:Number.isNaN(schemaVersion)?game.i18n.localize("PF2E.CompendiumMigrationStatus.Invalid"):schemaVersion,foundryVersion,module:game.modules.get(this.compendium.metadata.packageName??""),updated:schemaVersion>=MigrationRunner.LATEST_SCHEMA_VERSION,size:index.contents.length}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"[data-action=migrate]")?.addEventListener("click",async()=>{await new MigrationRunner(MigrationList.constructFromVersion(null)).runCompendiumMigration(this.compendium),this.render(!0)})}}class CompendiumDirectoryPF2e extends CompendiumDirectory{static{__name(this,"CompendiumDirectoryPF2e")}static{__name2(this,"CompendiumDirectoryPF2e")}static STOP_WORDS=new Set(["of","th","the"]);static searchEngine=new MiniSearch({fields:["name"],idField:"uuid",processTerm:t=>t.length>1&&!this.STOP_WORDS.has(t)?t.toLocaleLowerCase(game.i18n.lang):null,searchOptions:{combineWith:"AND",prefix:!0},storeFields:["uuid","img","name","type","documentType","packLabel"]});static get defaultOptions(){const options=super.defaultOptions;return options.dragDrop.push({dragSelector:"ol.document-matches > li.match"}),{...options,filters:[{inputSelector:"input[type=search]",contentSelector:"ol.directory-list"}],template:"systems/pf2e/templates/sidebar/compendium-directory.hbs"}}get#dragPreview(){const preview=document.createElement("div");preview.id="pack-search-drag-preview";const thumbnail=document.createElement("img"),title=document.createElement("h4");return preview.append(thumbnail,title),preview}async getData(options){return{...await super.getData(options),searchContents:game.user.settings.searchPackContents}}activateListeners($html){super.activateListeners($html),$html[0].querySelector("footer > button")?.addEventListener("click",()=>{game.pf2e.compendiumBrowser.render(!0)})}_getEntryContextOptions(){const options=super._getEntryContextOptions();return options.push({name:"COMPENDIUM.MigrationStatus",icon:fontAwesomeIcon("info").outerHTML,condition:$li=>{const compendium=game.packs.get($li.data("pack"),{strict:!0}),actorOrItem=compendium.documentClass===CONFIG.Actor.documentClass||compendium.documentClass===CONFIG.Item.documentClass,isSystemCompendium=compendium.metadata.packageType==="system";return game.user.isGM&&actorOrItem&&!isSystemCompendium},callback:async $li=>{const compendium=game.packs.get($li.data("pack"),{strict:!0});new CompendiumMigrationStatus(compendium).render(!0)}}),options}_contextMenu($html){super._contextMenu($html),ContextMenu.create(this,$html,"ol.document-matches > li",[{name:"COMPENDIUM.ImportEntry",icon:fontAwesomeIcon("download").outerHTML,condition:$li=>{const{uuid}=$li.get(0)?.dataset??{};if(!uuid)throw ErrorPF2e("Unexpected missing uuid");return game.packs.get(fromUuidSync(uuid)?.pack??"",{strict:!0}).documentClass.canUserCreate(game.user)},callback:$li=>{const{uuid}=$li.get(0)?.dataset??{};if(!uuid)throw ErrorPF2e("Unexpected missing uuid");const packCollection=game.packs.get(fromUuidSync(uuid)?.pack??"",{strict:!0}),worldCollection=game.collections.get(packCollection.documentName,{strict:!0}),indexData=fromUuidSync(uuid)??{_id:""};if(!("_id"in indexData&&typeof indexData._id=="string"))throw ErrorPF2e("Unexpected missing document _id");return worldCollection.importFromCompendium(packCollection,indexData._id,{},{renderSheet:!0})}}])}_onSearchFilter(event2,query,rgx,listElem){super._onSearchFilter(event2,query,rgx,listElem);const html=this.element[0],docMatches=query.length>0?this.constructor.searchEngine.search(query):[],{activeFilters}=this,filteredMatches=this.activeFilters.length>0?docMatches.filter(m=>activeFilters.includes(m.documentType)):docMatches,matchTemplate=htmlQuery(html,".compendium-search-match");if(!matchTemplate)throw ErrorPF2e("Match template not found");const listElements=filteredMatches.map(match=>{const li=matchTemplate.content.firstElementChild?.cloneNode(!0);li.dataset.uuid=match.uuid,li.dataset.score=match.score.toString();const thumbnail=li.querySelector("img");thumbnail&&(typeof match.img=="string"?thumbnail.src=game.pf2e.system.moduleArt.map.get(match.uuid)?.img??match.img:match.documentType==="JournalEntry"&&(thumbnail.src="icons/svg/book.svg")),li.addEventListener("click",async event22=>{event22.stopPropagation();const doc=await fromUuid(match.uuid);await doc?.sheet?.render(!0,{editable:doc.sheet.isEditable})});const anchor=li.querySelector("a"),details=li.querySelector("span"),systemType=["Actor","Item"].includes(match.documentType)?game.i18n.localize(`TYPES.${match.documentType}.${match.type}`):null;return anchor&&details&&(anchor.innerText=match.name,details.innerText=systemType?`${systemType} (${match.packLabel})`:`(${match.packLabel})`),li}),matchesList=htmlQuery(html,"ol.document-matches");if(matchesList){matchesList.replaceChildren(...listElements);for(const dragDrop of this._dragDrop)dragDrop.bind(matchesList)}}_canDragStart(){return!0}_onDragStart(event2){const dragElement=event2.currentTarget,{uuid}=dragElement.dataset;if(!uuid)return super._onDragStart(event2);const indexEntry=fromUuidSync(uuid);if(!indexEntry)throw ErrorPF2e("Unexpected error retrieving index data");document.querySelector("#pack-search-drag-preview")?.remove();const dragPreview=this.#dragPreview.cloneNode(!0),[img,title]=Array.from(dragPreview.childNodes);title.innerText=indexEntry.name??"",img.src="img"in indexEntry&&indexEntry.img?indexEntry.img:"icons/svg/book.svg",document.body.appendChild(dragPreview);const documentType=(()=>indexEntry instanceof foundry.abstract.Document?indexEntry.documentName:game.packs.get(indexEntry.pack??"")?.documentName??null)();documentType&&(event2.dataTransfer.setDragImage(dragPreview,75,25),event2.dataTransfer.setData("text/plain",JSON.stringify({type:documentType,uuid})))}compileSearchIndex(){console.debug("PF2e System | compiling search index");const packs=game.packs.filter(p=>p.index.size>0&&p.testUserPermission(game.user,"OBSERVER"));this.constructor.searchEngine.removeAll();for(const pack of packs){const contents=pack.index.map(i=>({...i,documentType:pack.metadata.type,packLabel:pack.metadata.label}));this.constructor.searchEngine.addAll(contents)}console.debug("PF2e System | Finished compiling search index")}}class EncounterTrackerPF2e extends CombatTracker{static{__name(this,"EncounterTrackerPF2e")}static{__name2(this,"EncounterTrackerPF2e")}async _renderInner(data,options){const $html=await super._renderInner(data,options);if(!game.user.isGM)return $html;const metrics=this.viewed?.metrics;if(!metrics)return $html;const localize=localizer("PF2E.Encounter.Metrics"),threat=(()=>{const label=game.i18n.localize(`PF2E.Encounter.Budget.Threats.${metrics.threat}`),tooltip=localize("Budget",metrics.budget),tempContainer=createHTMLElement("div",{innerHTML:localize("Threat",{threat:label})});return TextEditorPF2e.convertXMLNode(tempContainer,"threat",{classes:["value",metrics.threat]}),{label:tempContainer.innerHTML,tooltip}})(),award=(()=>{const label=localize("Award.Label",{xp:metrics.award.xp}),numRecipients=metrics.award.recipients.length,tooltip=localize(numRecipients===1?"Award.Tooltip.Singular":numRecipients===4?"Award.Tooltip.Four":"Award.Tooltip.Plural",{xpPerFour:metrics.budget.spent,recipients:numRecipients});return{label,tooltip}})(),threatAward=parseHTML(await renderTemplate("systems/pf2e/templates/sidebar/encounter-tracker/threat-award.hbs",{threat,award})),html=$html[0];return htmlQuery(html,"nav.encounters")?.after(threatAward),$(html)}activateListeners($html){const html=$html[0],tracker=htmlQuery(html,"#combat-tracker");if(!tracker)throw ErrorPF2e("No tracker found");const encounter=this.viewed;if(!encounter)return super.activateListeners($html);const tokenSetsNameVisibility=game.pf2e.settings.tokens.nameVisibility,allyColor=__name2(c=>c.actor?.hasPlayerOwner?CONFIG.Canvas.dispositionColors.PARTY:CONFIG.Canvas.dispositionColors.FRIENDLY,"allyColor"),combatantRows=htmlQueryAll(tracker,"li.combatant");for(const row of combatantRows){const combatantId=row.dataset.combatantId??"",combatant=encounter.combatants.get(combatantId,{strict:!0});if(row.dataset.initiative=String(combatant.initiative),combatant?.actor&&this.viewed?.combatant===combatant){const alliance=combatant.actor.alliance,dispositionColor=new foundry.utils.Color(alliance==="party"?allyColor(combatant):alliance==="opposition"?CONFIG.Canvas.dispositionColors.HOSTILE:CONFIG.Canvas.dispositionColors.NEUTRAL);row.style.background=dispositionColor.toRGBA(.1),row.style.borderColor=dispositionColor.toString()}const nameHeader=htmlQuery(row,".token-name h4");if(nameHeader){nameHeader.innerHTML=[createHTMLElement("span",{classes:["name"],children:[nameHeader.innerText]}).outerHTML,createHTMLElement("span",{classes:["users-targeting"]}).outerHTML].join("");for(const control of htmlQueryAll(row,"a.combatant-control")){const controlIcon=htmlQuery(control,"i");if(controlIcon&&(controlIcon.classList.remove("fas"),controlIcon.classList.add("fa-solid","fa-fw"),control.dataset.control==="pingCombatant"&&(controlIcon.classList.remove("fa-bullseye-arrow"),controlIcon.classList.add("fa-signal-stream"),game.scenes.viewed?.tokens.has(combatant.token?.id??"")))){const targetControl=createHTMLElement("a",{classes:["combatant-control"],dataset:{control:"toggleTarget",tooltip:"COMBAT.ToggleTargeting"},children:[fontAwesomeIcon("location-crosshairs",{style:"duotone",fixedWidth:!0})]});control.before(targetControl)}}if(this.refreshTargetDisplay(combatant),tokenSetsNameVisibility){const nameElement=htmlQuery(nameHeader,"span.name");if(nameElement&&!game.user.isGM&&!combatant.playersCanSeeName&&(nameElement.innerText="",row.querySelector("img.token-image")?.removeAttribute("title")),game.user.isGM&&combatant.actor&&combatant.actor.alliance!=="party"){const toggleNameVisibility=document.createElement("a"),isActive=combatant.playersCanSeeName;toggleNameVisibility.classList.add(...["combatant-control",isActive?"active":[]].flat()),toggleNameVisibility.dataset.control="toggleNameVisibility",toggleNameVisibility.dataset.tooltip=game.i18n.localize(isActive?"PF2E.Encounter.HideName":"PF2E.Encounter.RevealName");const icon=fontAwesomeIcon("signature",{fixedWidth:!0});toggleNameVisibility.append(icon),row.querySelector('.combatant-controls a[data-control="toggleHidden"]')?.after(toggleNameVisibility),isActive||row.classList.add("hidden-name")}}}}if(game.user.isGM&&!game.modules.get("combat-enhancements")?.active){Sortable.create(tracker,{animation:200,dataIdAttr:"data-combatant-id",direction:"vertical",dragClass:"drag-preview",dragoverBubble:!0,easing:"cubic-bezier(1, 0, 0, 1)",ghostClass:"drag-gap",onEnd:event2=>this.adjustFinalOrder(event2),onUpdate:event2=>this.#onDropCombatant(event2)});for(const row of combatantRows)row.classList.add("gm-draggable")}super.activateListeners($html)}refreshTargetDisplay(combatantOrToken){if(!this.viewed||!canvas.ready)return;const{combatant,tokenDoc}=combatantAndTokenDoc(combatantOrToken);if(!(combatant?.encounter!==this.viewed||tokenDoc?.combatant!==combatant))for(const tracker of htmlQueryAll(document,"#combat, #combat-popout")){const combatantRow=htmlQuery(tracker,`li.combatant[data-combatant-id="${combatant?.id??null}"]`);if(!combatantRow)return;const usersTargetting=game.users.filter(u=>Array.from(u.targets).some(t=>t.document===tokenDoc)),userIndicators=usersTargetting.map(user=>{const icon=fontAwesomeIcon("location-crosshairs",{style:"duotone",fixedWidth:!0});return icon.style.color=user.color,icon}),targetingSection=htmlQuery(combatantRow,".users-targeting");targetingSection&&(targetingSection.innerHTML=userIndicators.map(i=>i.outerHTML).join(""),targetingSection.dataset.tooltip=game.i18n.format("COMBAT.TargetedBy",{list:localizeList(usersTargetting.map(u=>u.name),{conjunction:"and"})}));const targetControlIcon=htmlQuery(combatantRow,"a.combatant-control[data-control=toggleTarget]");usersTargetting.includes(game.user)?targetControlIcon?.classList.add("active"):targetControlIcon?.classList.remove("active")}}async _onCombatControl(event2){const control=event2.currentTarget.dataset.control;if((control==="rollNPC"||control==="rollAll")&&this.viewed){event2.stopPropagation();const args=eventToRollParams(event2,{type:"check"});await this.viewed[control]({...args,messageOptions:{rollMode:args.rollMode}})}else await super._onCombatControl(event2)}async _onCombatantControl(event2){if(event2.stopPropagation(),!this.viewed)return;const control=event2.currentTarget.dataset.control,li=event2.currentTarget.closest(".combatant"),combatant=this.viewed.combatants.get(li?.dataset.combatantId??"",{strict:!0});switch(control){case"rollInitiative":{await this.viewed.rollInitiative([combatant.id],eventToRollParams(event2,{type:"check"}));break}case"toggleTarget":return this.#onToggleTarget(combatant.token,event2.originalEvent);case"toggleNameVisibility":return combatant.toggleNameVisibility();default:return super._onCombatantControl(event2)}}_onToggleDefeatedStatus(combatant){return combatant.toggleDefeated()}async#onToggleTarget(tokenDoc,event2){if(!tokenDoc)return;const isTargeted=Array.from(game.user.targets).some(t=>t.document===tokenDoc);if(!tokenDoc.object?.visible){ui.notifications.warn("COMBAT.PingInvisibleToken",{localize:!0});return}tokenDoc.object.setTarget(!isTargeted,{releaseOthers:!event2?.shiftKey})}async#onDropCombatant(event2){this.validateDrop(event2);const encounter=this.viewed;if(!encounter)return;const droppedId=event2.item.getAttribute("data-combatant-id")??"",dropped=encounter.combatants.get(droppedId,{strict:!0});if(typeof dropped.initiative!="number"){ui.notifications.error(game.i18n.format("PF2E.Encounter.HasNoInitiativeScore",{actor:dropped.name}));return}const newOrder=this.getCombatantsFromDOM(),oldOrder=encounter.turns.filter(c=>c.initiative!==null);newOrder.every(c=>newOrder.indexOf(c)===oldOrder.indexOf(c))||(this.setInitiativeFromDrop(newOrder,dropped),await this.saveNewOrder(newOrder))}setInitiativeFromDrop(newOrder,dropped){const aboveDropped=newOrder.find(c=>newOrder.indexOf(c)===newOrder.indexOf(dropped)-1),belowDropped=newOrder.find(c=>newOrder.indexOf(c)===newOrder.indexOf(dropped)+1),hasAboveAndBelow=!!aboveDropped&&!!belowDropped,hasAboveAndNoBelow=!!aboveDropped&&!belowDropped,hasBelowAndNoAbove=!aboveDropped&&!!belowDropped,aboveIsHigherThanBelow=hasAboveAndBelow&&belowDropped.initiativec.initiative===dropped.initiative);if(withSameInitiative.length>1)for(let priority=0;priority({id:c.id,value:c.initiative,overridePriority:c.overridePriority(c.initiative)})))}adjustFinalOrder(event2){const row=event2.item,tracker=this.element[0].querySelector("#combat-tracker");if(!tracker)throw ErrorPF2e("Unexpected failure to retriever tracker DOM element");const rows=Array.from(tracker.querySelectorAll("li.combatant")),[oldIndex,newIndex]=[event2.oldIndex??0,event2.newIndex??0],firstRowWithNoRoll=rows.find(row2=>Number.isNaN(Number(row2.dataset.initiative)));Number.isNaN(Number(row.dataset.initiative))?newIndex>oldIndex?tracker.insertBefore(row,rows[oldIndex]):tracker.insertBefore(row,rows[oldIndex+1]):firstRowWithNoRoll&&rows.indexOf(firstRowWithNoRoll)row.getAttribute("data-combatant-id")??"").map(id=>combat.combatants.get(id,{strict:!0})).filter(c=>typeof c.initiative=="number")}}const darkvision=new VisionMode({id:"darkvision",label:"VISION.ModeDarkvision",canvas:{shader:ColorAdjustmentsSamplerShader,uniforms:{enable:!0,contrast:0,saturation:-1,brightness:0}},lighting:{levels:{},background:{visibility:VisionMode.LIGHTING_VISIBILITY.REQUIRED}},vision:{darkness:{adaptive:!0},defaults:{attenuation:0,contrast:0,saturation:-1,brightness:.75,range:1/0}}});class VisionDetectionMode extends DetectionModeBasicSight{static{__name(this,"VisionDetectionMode")}static{__name2(this,"VisionDetectionMode")}constructor(){super({id:"basicSight",label:"DETECTION.BasicSight",type:DetectionMode.DETECTION_TYPES.SIGHT})}_canDetect(visionSource,target){return target instanceof PlaceableObject&&target.document.hidden||target instanceof TokenPF2e&&target.actor?.hasCondition("hidden","undetected","unnoticed")?!1:super._canDetect(visionSource,target)}_testRange(visionSource,mode,target,test){return mode.range>=canvas.dimensions.maxR||super._testRange(visionSource,mode,target,test)}}class HearingDetectionMode extends DetectionMode{static{__name(this,"HearingDetectionMode")}static{__name2(this,"HearingDetectionMode")}constructor(){super({id:"hearing",label:"PF2E.Actor.Creature.Sense.Type.Hearing",type:DetectionMode.DETECTION_TYPES.SOUND})}static getDetectionFilter(){const filter2=this._detectionFilter??=OutlineOverlayFilter.create({wave:!0,knockout:!1});return filter2.thickness=1,filter2}_canDetect(visionSource,target){return!(target instanceof TokenPF2e)||target.document.hidden||!target.actor?.emitsSound?!1:game.pf2e.settings.rbv?target.actor?.hasCondition("undetected","unnoticed")?!1:!visionSource.object.actor?.hasCondition("deafened"):!0}_testLOS(visionSource,_mode,_target,test){test.loh??=new Map;const hearingSource=visionSource.object.hearing,hasLOH=test.loh.get(hearingSource)??hearingSource.shape.contains(test.point.x,test.point.y);return test.loh.set(hearingSource,hasLOH),hasLOH}_testRange(visionSource,mode,target,test){return mode.range>=canvas.dimensions.maxR||super._testRange(visionSource,mode,target,test)}}class DetectionModeTremorPF2e extends DetectionModeTremor{static{__name(this,"DetectionModeTremorPF2e")}static{__name2(this,"DetectionModeTremorPF2e")}constructor(){super({id:"feelTremor",label:"DETECTION.FeelTremor",walls:!1,type:DetectionMode.DETECTION_TYPES.MOVE})}static getDetectionFilter(){const filter2=super.getDetectionFilter();return filter2.thickness=1,filter2}_canDetect(visionSource,target){return super._canDetect(visionSource,target)&&target instanceof TokenPF2e&&!target.document.hidden&&!target.actor?.isOfType("loot")&&!target.actor?.hasCondition("undetected","unnoticed")}}function setPerceptionModes(){CONFIG.Canvas.visionModes.darkvision=darkvision,CONFIG.Canvas.detectionModes.basicSight=new VisionDetectionMode,CONFIG.Canvas.detectionModes.hearing=new HearingDetectionMode,CONFIG.Canvas.detectionModes.feelTremor=new DetectionModeTremorPF2e}__name(setPerceptionModes,"setPerceptionModes"),__name2(setPerceptionModes,"setPerceptionModes");class JournalSheetPF2e extends JournalSheet{static{__name(this,"JournalSheetPF2e")}static{__name2(this,"JournalSheetPF2e")}static get theme(){return null}static get defaultOptions(){const options=super.defaultOptions,{theme}=this;return theme&&options.classes.push(theme),options}}class JournalTextTinyMCESheetPF2e extends JournalTextTinyMCESheet{static{__name(this,"JournalTextTinyMCESheetPF2e")}static{__name2(this,"JournalTextTinyMCESheetPF2e")}async activateEditor(name2,options={},initialContent=""){const editor=await super.activateEditor(name2,options,initialContent),theme=this.object.parent?.sheet.constructor?.theme;return editor.contentDocument.documentElement.classList.add("journal-entry-page","text"),editor.contentDocument.body.classList.add("journal-page-content"),theme&&editor.contentDocument.documentElement.classList.add(theme),editor}}var define_EN_JSON_default={COMBAT:{Begin:"Begin Encounter",CombatantNotInScene:"The participant {name} is not present in your currently viewed scene.",CombatantRemove:"Remove Participant",CombatantStatus:"Participant Status",CombatantUpdate:"Update Participant",End:"End Encounter",EndConfirmation:"End this encounter and empty the turn tracker?",EndTitle:"End Encounter?",NoneActive:"There is no active Encounter in your currently viewed Scene.",NoneRemaining:"There are no participants remaining in this Encounter that are not defeated.",PingCombatant:"Ping Token",PingInvisibleToken:"You can't see this participant's token.",ResourceHint:"Choose an attribute to track for each participant.",Settings:"Encounter Tracker Settings",SidebarTitle:"Encounter Tracker",SkipDefeatedHint:"Automatically bypass participants marked as defeated?",TargetedBy:"Targeted by {list}",ToggleTargeting:"Toggle Targeting",UnknownCombatant:"Unknown Participant"},COMPENDIUM:{MigrationStatus:"Migration Status"},CONTROLS:{AdjustSceneDarkness:"Adjust Scene Darkness",EffectPanel:"Effects Panel",WorldClock:"World Clock"},DOCUMENT:{Combat:"Encounter",Combats:"Encounters"},PF2E:{AbilityBoost:"Attribute Boost",AbilityBoostLevels:"Attribute Boost Levels",AbilityCha:"Charisma",AbilityCheck:{cha:"Charisma Check",con:"Constitution Check",dex:"Dexterity Check",int:"Intelligence Check",str:"Strength Check",wis:"Wisdom Check"},AbilityCon:"Constitution",AbilityDex:"Dexterity",AbilityFlaw:"Flaw",AbilityFree:"Free",AbilityId:{cha:"Cha",con:"Con",dex:"Dex",int:"Int",str:"Str",wis:"Wis"},AbilityInt:"Intelligence",AbilityModifierLabel:"Attribute Modifier",AbilityStr:"Strength",AbilityTitle:"Attribute",AbilityWis:"Wisdom",AccessoryPropertyRuneCalled:"Called",AccessoryPropertyRuneDragonsBreath:"Dragon's Breath",AccessoryPropertyRuneGreaterPaired:"Greater Paired",AccessoryPropertyRuneGreaterWindCatcher:"Greater Wind-Catcher",AccessoryPropertyRuneMajorPaired:"Major Paired",AccessoryPropertyRunePaired:"Paired",AccessoryPropertyRunePresentable:"Presentable",AccessoryPropertyRuneSnagging:"Snagging",AccessoryPropertyRuneSoftLanding:"Soft-Landing",AccessoryPropertyRuneSpellBastion:"Spell-Bastion",AccessoryPropertyRuneWindCatcher:"Wind-Catcher",Action:{RestForTheNight:{Label:"Rest for the Night",Message:{Awakens:"{actor} awakens well-rested.",ConditionReduced:"{condition} reduced by 1.",ConditionRemoved:"No longer {condition}.",FocusPoints:"Focus points restored.",Frequencies:"Action frequencies refreshed.",HitPoints:"{hitPoints} hit points restored.",HitPointsSingle:"{hitPoints} hit point restored.",InfusedReagents:"Infused reagents restored.",Resolve:"Resolve restored.",SpellSlots:"All spell slots restored.",StaminaPoints:"Stamina points restored.",TemporaryItems:"Temporary items removed.",WandsCharges:"Wands recharged."},Prompt:"Rest for the night?"},Strike:{MeleeLabel:"Melee Strike: {weapon}",OutOfRange:"The target is out of range.",RangedLabel:"Ranged Strike: {weapon}"}},ActionActionTypeLabel:"Action Type",ActionActionsLabel:"Actions",ActionBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:
source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes.
Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",ActionDeathNoteLabel:"Death Note",ActionNumber1:"One",ActionNumber2:"Two",ActionNumber3:"Three",ActionSkillRequirementLabel:"Requirement",ActionTypeAction:"Action",ActionTypeFree:"Free Action",ActionTypePassive:"Passive",ActionTypeReaction:"Reaction",ActionTypeSingle:"Single Action",ActionWeaponLabel:"Associated Weapon",ActionsActionsHeader:"Actions",ActionsFreeActionsHeader:"Free Actions",ActionsReactionsHeader:"Reactions",Actor:{ApplyDamage:{AtFullHealth:"{actor} is already at full health.",DamagedForN:"{actor} takes {hpDamage} damage.",DamagedForNShield:"{actor}'s shield absorbs {absorbedDamage} damage, with an additional {hpDamage} making it through.",HealedForN:"{actor} is healed for {hpDamage} damage.",InstantDeath:{DeathEffect:"The death effect immediately kills them.",Destroyed:"They are destroyed.",FinePowder:"They are reduced to a fine powder; their gear remains.",MassiveDamage:"The massive damage immediately kills them."},ShieldAbsorbsAll:"{actor} is unscathed, their shield completely absorbing {absorbedDamage} damage.",ShieldDamagedForN:"Their shield is also damaged for {shieldDamage}.",ShieldDamagedForNBroken:"Their shield also takes {shieldDamage} damage, breaking it.",ShieldDamagedForNDestroyed:"Their shield also takes {shieldDamage} damage, destroying it.",ShieldNotRaised:"{actor} has not raised their shield.",TakesNoDamage:"{actor} takes no damage.",TheTarget:"The target"},Attacks:"Attacks",Character:{Attribute:{Apex:"Apex Attribute",Boosts:"Attribute Boosts",Key:"Key Attribute"},AttributeBuilder:{InputMethod:{Description:"Switching method resets your attribute modifier distribution.",Manual:"Manual Entry",Title:"Input Method"},AncestryMissingHelp:"Choose an ancestry to select boosts.",AlternateBoostsLabel:"Alternate Boosts",BackgroundBoostDescription:"Two boosts: one must be {a} or {b}.",BackgroundMissingHelp:"Choose a background to select boosts.",Boost:"Boost",Boosts:"Boosts",ClassMissingHelp:"Choose a class to select boosts.",Complete:"Complete",Flaw:"Flaw",Flaws:"Flaws",Increase:"Increase",KeyIcon:"Key",LegacyFlaws:"Legacy Flaws",Partial:"Partial",NotSelected:"Not Selected",Title:"Assign your boosts",VoluntaryFlaw:{Description:"You can take one or more additional penalties purely for roleplaying a highly flawed character.",LegacyDescription:"This is the Voluntary Flaws feature that existed until the CRB's 4th printing. It is kept in place for older characters and as a continued option for Pathfinder Society play.",Title:"Voluntary Flaws"}},Active:"Active",ActiveHeader:"Active Activities",Biography:{Anathema:{Add:"Add Anathema",Delete:"Delete Anathema"},ToggleVisibility:"Toggle visibility to other players",Edicts:{Add:"Add Edict",Delete:"Delete Edict"}},Blurb:"Level {level} {ancestry} {class}",ClassDC:{Label:"Class DC",LabelSpecific:"Class DC ({class})",Plural:"Class DCs"},Clear:"Clear",Configure:{ShowBasicUnarmed:{Hint:"A PC always has available an unspecific unarmed attack using any part of their body. The attack may be hidden from view if the player never intends to use it.",Label:"Show Basic Unarmed Attack"},Title:"Configure Character"},Crafting:{Cost:"Cost"},HandsOccupied:"Hands Occupied",Proficiency:{Attack:{Advanced:"Advanced Weapons",Martial:"Martial Weapons",Simple:"Simple Weapons",Title:"Attacks",Unarmed:"Unarmed Attacks"},Defense:{Heavy:"Heavy Armor",HeavyBarding:"Heavy Barding",Light:"Light Armor",LightBarding:"Light Barding",Medium:"Medium Armor",Title:"Defenses",Unarmored:"Unarmored Defense"},HigherUpgrade:"{ability} has upgraded this proficiency's rank to {rank}."},Rest:{Label:"Rest for the Night"}},Creature:{Alliance:{Default:"Ownership Default ({alliance})",Neutral:"Neutral",Opposition:"Opposition",Party:"Party"},AttributeModifiers:"Attribute Modifiers",Configure:{Alliance:{Hint:"A creature can be in opposition to the party, allied with it, or neutral. This impacts some mechanics during an encounter, such as flanking.",Label:"Alliance"}},CriticalSpecialization:"Critical Specialization",Language:{adlet:"Adlet",akitonian:"Akitonian",aklo:"Aklo",alghollthu:"Alghollthu",amurrun:"Amurrun",anadi:"Anadi","ancient-osiriani":"Ancient Osiriani",androffan:"Androffan",anugobu:"Anugobu",arboreal:"Arboreal",arcadian:"Arcadian",azlanti:"Azlanti",boggard:"Boggard",calda:"Calda",caligni:"Caligni",chthonian:"Chthonian",common:"Common",cyclops:"Cyclops",daemonic:"Daemonic",destrachan:"Destrachan",diabolic:"Diabolic",draconic:"Draconic",drooni:"Drooni",dwarven:"Dwarven",dziriak:"D'ziriak",ekujae:"Ekujae shape-script","elder-thing":"Elder Thing",elven:"Elven",empyrean:"Empyrean",erutaki:"Erutaki",fey:"Fey",formian:"Formian",garundi:"Garundi",girtablilu:"Girtablilu",gnomish:"Gnomish",goblin:"Goblin",goloma:"Goloma",grioth:"Grioth",grippli:"Grippli",halfling:"Halfling",hallit:"Hallit",hwan:"Hwan",iblydan:"Iblydan",ikeshti:"Ikeshti",immolis:"Immolis",iruxi:"Iruxi",jistkan:"Jistkan",jotun:"Jotun",jyoti:"Jyoti",kaava:"Kaava",kashrishi:"Kashrishi",kelish:"Kelish",kholo:"Kholo",kibwani:"Kibwani",kitsune:"Kitsune",kovintal:"Kovintal",lirgeni:"Lirgeni",mahwek:"Mahwek",migo:"Mi-Go",minaten:"Minatan",minkaian:"Minkaian",muan:"Muan",munavri:"Munavri",mwangi:"Mwangi",mzunu:"Mzunu",nagaji:"Nagaji",necril:"Necril",ocotan:"Ocotan",okaiyan:"Okaiyan",orcish:"Orcish",orvian:"Orvian",osiriani:"Osiriani",petran:"Petran",protean:"Protean",pyric:"Pyric",rasu:"Rasu",ratajin:"Ratajin",razatlani:"Razatlani",requian:"Requian",russian:"Russian",sakvroth:"Sakvroth",samsaran:"Samsaran",sasquatch:"Sasquatch",senzar:"Senzar",shadowtongue:"Shadowtongue",shae:"Shae",shisk:"Shisk",shoanti:"Shoanti",shobhad:"Shobhad",shoony:"Shoony",shory:"Shory",skald:"Skald",sphinx:"Sphinx",strix:"Strix",sussuran:"Sussuran",taldane:"Taldane",talican:"Talican",tekritanin:"Tekritanin",tengu:"Tengu",thalassic:"Thalassic",thassilonian:"Thassilonian",tien:"Tien",utopian:"Utopian",vanara:"Vanara",varisian:"Varisian",varki:"Varki",vishkanyan:"Vishkanyan",vudrani:"Vudrani",wildsong:"Wildsong",wyrwood:"Wyrwood",xanmba:"Xanmba",yithian:"Yithian",ysoki:"Ysoki"},Sense:{Acuity:{Imprecise:"Imprecise",Label:"Acuity",Precise:"Precise",Vague:"Vague"},Label:"Senses",NoRangeLimit:"No Limit",RangeLabel:"Range",Type:{Darkvision:"Darkvision",Echolocation:"Echolocation",GreaterDarkvision:"Greater Darkvision",Hearing:"Hearing",Heatsight:"Heatsight",Lifesense:"Lifesense",LowLightVision:"Low-Light Vision",Motionsense:"Motionsense",Scent:"Scent",SeeInvisibility:"See Invisibility",Spiritsense:"Spiritsense",Thoughtsense:"Thoughtsense",Tremorsense:"Tremorsense",Wavesense:"Wavesense"},WithAcuity:"{sense} ({acuity})",WithAcuityAndRange:"{sense} ({acuity} {range} Ft)"},Shield:{ACBonus:"Shield AC Bonus (When Raised)",BrokenThreshold:"Shield Broken Threshold",Hardness:{Hint:"Shield Hardness",Label:"H"},HitPoints:{Value:"Shield HP",Max:"Shield Max HP"}},SpellPreparation:{Hint:"To prepare a spell, drag one from this list to a slot on the actor sheet.",HintFlexible:"To prepare a spell, enable it here. To prepare a cantrip, drag one from this list to a slot on the actor sheet.",Search:"Search Spells",Title:"{actor}: Spell Preparation"},Spellcasting:{Cantrips:"Cantrips",DC:"Spell DC",InvalidProficiency:"Invalid",Label:"Spell Attack Modifiers & DCs",MagicItemTypesLabel:"Magic Item Types",Rituals:"Rituals",TraditionSpellcasting:"{tradition} Spellcasting",ValidItemTypes:{All:"All Magic Items",Scroll:"Scrolls Only"}}},Dead:"Dead",Familiar:{Blurb:"Familiar of {master}",Master:{ArmorClass:"Master Armor Class",Perception:"Master Perception"}},Hardness:{ShortLabel:"HRD"},Hazard:{EmitsSound:{Encounter:"During Encounters",False:"Never",Hint:"Whether this hazard emits sound and can be sensed via hearing",Title:"Emits Sound?",True:"Always"},Level:"Hazard {level}",Plural:"Hazards",Simple:"Simple",TitleEdit:"{name} (Edit Mode)"},HitPoints:{Unrecoverable:"{value} hit points are currently unrecoverable."},Inventory:{DistributeCoins:"Distribute Coins",Encumbrance:"Encumbrance",ItemQuantity:{Decrease:{Click:"[Click] Decrease by 1",ShiftClick:"[Shift-Click] Decrease by 5",ControlClick:"[Control-Click] Decrease by 10"},Increase:{Click:"[Click] Increase by 1",ShiftClick:"[Shift-Click] Increase by 5",ControlClick:"[Control-Click] Increase by 10"}},Section:{WeaponsAndShields:"Weapons & Shields"},TotalBulk:"Total Bulk: {bulk}"},IWREditor:{DoubleVs:"Double Vs.",Exceptions:"Exceptions",Title:"{actor}: {category}",Type:"Type"},NPC:{Configure:{Lootable:{DefaultLootable:"Global Default (Lootable)",DefaultNotLootable:"Global Default (Not Lootable)",Hint:"Set whether this NPC becomes lootable by players upon its demise. The global default can be configured in Automation Settings.",Label:"Lootable?",Lootable:"Lootable",NotLootable:"Not Lootable"},Title:"Configure NPC"},GenerateAttack:{Confirm:{Content:"An attack has already been generated for this weapon. Would you like to replace it?",Title:"Regenerate attack"},Label:"Generate Attack",Notification:"Generated NPC attack: {attack}"},Identification:{Skills:{Label:"{skills}: DC {dc} ({adjustment})",Tooltip:`"The skill used to identify a creature usually depends on that creature's trait, as shown on Table 10\u20137, but you have leeway on which skills apply." \u2013 CRB pg. 506`},Lore:{Label:"Applicable Lore: DC {dc1} ({adjustment1}) or DC {dc2} ({adjustment2})",Tooltip:'"Using the applicable Lore usually has an easy or very easy DC (before adjusting for rarity)." \u2013 CRB pg. 506'}},SimpleSheet:"Simple NPC Sheet",SkillsEditor:{LorePlaceholder:"Carpentry Lore",Title:"Skills Editor ({actor})"}},Party:{BlankSlate:"This party doesn't have any members. Drag a creature from the actor sidebar to get started.",CheckPrompt:{AdjustDifficulty:"Adjust Difficulty",ChooseLores:"Choose Lores",ChooseSaves:"Choose Saves",ChooseSkills:"Choose Skills/Perception",LevelDC:"Level-Based DC",Post:"Generate Prompt",PromptTitle:"Prompt Title",SecretCheck:"Secret Check",SetDC:"Set DC",SimpleDC:"Simple DC",SkillsPerception:"Skills/Perception",Title:"Generate Check Prompt",TitleShort:"Check Prompt"},Coin:"Coin",ClearActivities:{Label:"Clear",Complete:"Party exploration activities have been cleared"},ClownCar:{Deposit:"Deposit PC Tokens",Retrieve:"Retrieve PC Tokens"},DefaultName:"The Party",InvalidCampaign:{Hint:"The campaign data is invalid",Title:"Invalid Campaign ({party})",Message:{mismatch:"This party has campaign data of type {current}, but the configured type is {campaignType}. Do you want to delete existing campaign data?",error:"This party's campaign data ({current}) is corrupt and failed data preparation. Do you want to delete existing campaign data?"}},Languages:"Party Languages",MembersLabel:"Members: ",NoMembers:"No Members",NoSpecialSenses:"No Special Senses",RemoveMember:{Title:"Remove Member",Content:"Remove member from party?"},Rest:"Rest",Sidebar:{ActivateParty:"Activate Party",CreateMember:"Create New Member",CreateParty:"Create New Party",RemoveMember:"Remove Member",OpenSheet:"Open Sheet",OtherParties:"Other Parties"},Skills:"Party Skills",SlotAvailable:"Slot Available",Tabs:{Overview:"Overview",Exploration:"Exploration",Orphaned:"Orphaned Items",Stash:"Stash"},Total:"Party Total",TravelHeader:"Party Travel and Hexploration",Visibility:{Restricted:"Restricted",Unrestricted:"Unrestricted"},Wealth:"Wealth"},Plural:"Actors"},ActorSizeGargantuan:"Gargantuan",ActorSizeHuge:"Huge",ActorSizeLarge:"Large",ActorSizeMedium:"Medium",ActorSizeSmall:"Small",ActorSizeTiny:"Tiny",AddCoinsCombineStacksLabel:"Combine Stacks",AddCoinsTitle:"Add Coins",AddCombatProficiency:{Message:"Select a weapon group or base weapon",Title:"Add Combat Proficiency"},AddModifierTitle:"Add Modifier",AddShortLabel:"Add",AddSpellTitle:"Add Spell",AddSpellcastingEntryTitle:"Add Spellcasting Entry",AdditionalLanguagePlusInt:"(plus Intelligence)",AdditionalSkills:"Additional Skills",Age:"Age",AllSavesLabel:"All Saves",AncestryFeatLevels:"Ancestry Feat Levels",AncestryFeatures:"Ancestry Features",AncestryHP:"Ancestry HP",AreaLabel:"Area",AreaSize10:"10 Foot",AreaSize100:"100 Foot",AreaSize1000:"1000 Foot",AreaSize120:"120 Foot",AreaSize15:"15 Foot",AreaSize1Mile:"1 Mile",AreaSize20:"20 Foot",AreaSize25:"25 Foot",AreaSize30:"30 Foot",AreaSize360:"360 Foot",AreaSize40:"40 Foot",AreaSize45:"45 Foot",AreaSize5:"5 Foot",AreaSize50:"50 Foot",AreaSize500:"500 Foot",AreaSize60:"60 Foot",AreaSize65:"65 Foot",AreaSize75:"75 Foot",AreaSize80:"80 Foot",AreaSize90:"90 Foot",AreaSizeQuarterMile:"Quarter Mile",AreaTypeBurst:"Burst",AreaTypeCone:"Cone",AreaTypeCube:"Cube",AreaTypeEmanation:"Emanation",AreaTypeLine:"Line",AreaTypeSquare:"Square",ArmorArmorLabel:"AC Bonus",ArmorCheckLabel:"Check Penalty",ArmorCheckPenalty:"Armor Check Penalty",ArmorClassBase:"Base Armor Class 10",ArmorClassLabel:"Armor Class",ArmorClassShortLabel:"AC",ArmorDexLabel:"Dex Modifier Cap",ArmorGreaterResilientRune:"Greater Resilient",ArmorGroupChain:"Chain",ArmorGroupCloth:"Cloth",ArmorGroupComposite:"Composite",ArmorGroupLabel:"Group",ArmorGroupLeather:"Leather",ArmorGroupPlate:"Plate",ArmorGroupSkeletal:"Skeletal",ArmorGroupWood:"Wood",ArmorMajorResilientRune:"Major Resilient",ArmorPotencyRune1:"Armor Potency (+1)",ArmorPotencyRune2:"Armor Potency (+2)",ArmorPotencyRune3:"Armor Potency (+3)",ArmorPotencyRune4:"Armor Potency (+4)",ArmorPropertyRuneAcidResistant:"Acid-Resistant",ArmorPropertyRuneAdvancing:"Advancing",ArmorPropertyRuneAimAiding:"Aim-Aiding",ArmorPropertyRuneAntimagic:"Antimagic",ArmorPropertyRuneAssisting:"Assisting",ArmorPropertyRuneBitter:"Bitter",ArmorPropertyRuneColdResistant:"Cold-Resistant",ArmorPropertyRuneDeathless:"Deathless",ArmorPropertyRuneElectricityResistant:"Electricity-Resistant",ArmorPropertyRuneEnergyAdaptive:"Energy Adaptive",ArmorPropertyRuneEthereal:"Ethereal",ArmorPropertyRuneFireResistant:"Fire-Resistant",ArmorPropertyRuneFortification:"Fortification",ArmorPropertyRuneGlamered:"Glamered",ArmorPropertyRuneGliding:"Gliding",ArmorPropertyRuneGreaterAcidResistant:"Greater Acid-Resistant",ArmorPropertyRuneGreaterAdvancing:"Greater Advancing",ArmorPropertyRuneGreaterColdResistant:"Greater Cold-Resistant",ArmorPropertyRuneGreaterDread:"Greater Dread",ArmorPropertyRuneGreaterElectricityResistant:"Greater Electricity-Resistant",ArmorPropertyRuneGreaterFireResistant:"Greater Fire-Resistant",ArmorPropertyRuneGreaterFortification:"Greater Fortification",ArmorPropertyRuneGreaterInvisibility:"Greater Invisibility",ArmorPropertyRuneGreaterQuenching:"Greater Quenching",ArmorPropertyRuneGreaterReady:"Greater Ready",ArmorPropertyRuneGreaterShadow:"Greater Shadow",ArmorPropertyRuneGreaterSlick:"Greater Slick",ArmorPropertyRuneGreaterStanching:"Greater Stanching",ArmorPropertyRuneGreaterSwallowSpike:"Greater Swallow-Spike",ArmorPropertyRuneGreaterWinged:"Greater Winged",ArmorPropertyRuneImmovable:"Immovable",ArmorPropertyRuneImplacable:"Implacable",ArmorPropertyRuneInvisibility:"Invisibility",ArmorPropertyRuneLesserDread:"Lesser Dread",ArmorPropertyRuneMagnetizing:"Magnetizing",ArmorPropertyRuneMajorQuenching:"Major Quenching",ArmorPropertyRuneMajorShadow:"Major Shadow",ArmorPropertyRuneMajorSlick:"Major Slick",ArmorPropertyRuneMajorStanching:"Major Stanching",ArmorPropertyRuneMajorSwallowSpike:"Major Swallow-Spike",ArmorPropertyRuneMalleable:"Malleable",ArmorPropertyRuneMisleading:"Misleading",ArmorPropertyRuneModerateDread:"Moderate Dread",ArmorPropertyRunePortable:"Portable",ArmorPropertyRuneQuenching:"Quenching",ArmorPropertyRuneRaiment:"Raiment",ArmorPropertyRuneReady:"Ready",ArmorPropertyRuneRockBraced:"Rock-Braced",ArmorPropertyRuneShadow:"Shadow",ArmorPropertyRuneSinisterKnight:"Sinister Knight",ArmorPropertyRuneSlick:"Slick",ArmorPropertyRuneSoaring:"Soaring",ArmorPropertyRuneStanching:"Stanching",ArmorPropertyRuneSwallowSpike:"Swallow-Spike",ArmorPropertyRuneTrueQuenching:"True Quenching",ArmorPropertyRuneTrueStanching:"True Stanching",ArmorPropertyRuneWinged:"Winged",ArmorResilientRune:"Resilient",ArmorSpeedLabel:"Speed Penalty",ArmorStrengthLabel:"Strength Requirement",ArmorTypeHeavy:"Heavy Armor",ArmorTypeLight:"Light Armor",ArmorTypeMedium:"Medium Armor",ArmorTypeUnarmored:"Unarmored",AttackEffectConstrict:"Constrict",AttackEffectGrab:"Grab",AttackEffectGreaterConstrict:"Improved Constrict",AttackEffectImprovedGrab:"Improved Grab",AttackEffectImprovedKnockdown:"Improved Knockdown",AttackEffectImprovedPush:"Improved Push",AttackEffectKnockdown:"Knockdown",AttackEffectPush:"Push",AttackEffectTrip:"Trip",AttackLabel:"Attack",AttitudeLabel:"Attitude",Attitudes:{Friendly:"Friendly",Helpful:"Helpful",Hostile:"Hostile",Indifferent:"Indifferent",Unfriendly:"Unfriendly"},AutomaticBonusProgression:{attackPotency:"Attack Potency",defensePotency:"Defense Potency",devastatingAttacks:"Devastating Attacks",perceptionPotency:"Perception Potency",savePotency:"Save Potency"},Background:"Background",BackgroundSkillFeats:"Skill Feats",BaseModifier:"Base Modifier",BaseWeapons:"Base Weapons",BestiaryBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:
source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes.
Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",Biography:"Biography",BiographyAllies:"Allies",BiographyAppearance:"Appearance",BiographyAnathema:"Anathema",BiographyAttitude:"Attitude",BiographyBackStory:"Backstory",BiographyBeliefs:"Beliefs",BiographyBirthPlace:"Birth Place",BiographyCampaignNotes:"Notes",BiographyCampaignNotesHeader:"Campaign",BiographyCatchphrases:"Catchphrases",BiographyDislikes:"Dislikes",BiographyEdicts:"Edicts",BiographyEnemies:"Enemies",BiographyLikes:"Likes",BiographyOrganizations:"Organizations",BiographyPersonalityHeader:"Personality",Bonus:"Bonus",BonusLabel:{ability:"Attribute Bonus",circumstance:"Circumstance Bonus",item:"Item Bonus",proficiency:"Proficiency Bonus",status:"Status Bonus",untyped:"Untyped Bonus"},BonusSPLabel:"Bonus SP",BonusSPperLevel:"Bonus SP per Level",BrowseLabel:"Browse",BrowserClearFilter:"Clear Filter",BrowserClearFilters:"Clear All Filters",BrowserFilterAlignments:"Alignments",BrowserFilterAncestries:"Ancestries",BrowserFilterArmorFilters:"Armor Filters",BrowserFilterCastingTime:"Casting time",BrowserFilterCategory:"Categories",BrowserFilterClass:"Classes",BrowserFilterComplexity:"Hazard Complexities",BrowserFilterConjunction:{AndLabel:"All of above",OrLabel:"Any of above"},BrowserFilterInventoryTypes:"Inventory Types",BrowserFilterLevels:"Levels",BrowserFilterProficiencyRequirements:"Proficiency Requirements",BrowserFilterRarities:"Rarities",BrowserFilterSizes:"Sizes",BrowserFilterSkills:"Skills",BrowserFilterSource:"Source",BrowserFilterSpellCategories:"Categories",BrowserFilterTraditions:"Traditions",BrowserFilterTraits:"Traits",BrowserFilterWeaponFilters:"Weapon Filters",BrowserSearchPlaceholder:"Search Text",BrowserSearchTitle:"Right click for guide",BrowserSettingsSaved:"Settings have been saved",BrowserSortyByLabel:"Sort by",BrowserWarnPackNotLoaded:'Compendium "{pack}" could not be loaded.',BulkMaxLabel:"Max Bulk",CapacityBarLabel:"Capacity",CarryType:{dropped:"Dropped",held1:"Held 1H",held2:"Held 2H",stowed:"Stowed",worn:"Worn","worn-in-slot":"Worn (In Slot)"},CastLabel:"Cast",CastingItemCreateDialog:{"10thLevelWand":"10th level wands don't exist",cantripDeck5:"Cantrip Deck (5-pack)",itemTypeLabel:"Item type: ",label:"Create a spellcasting item from the dropped spell",scroll:"Scroll",spellLevelLabel:"Heightened Rank: ",submit:"Create item",title:"Create a spellcasting item",wand:"Wand"},Category:"Category",CharacterDetails:"Character Details",CharacterLevelLabel:"Level",CharacterNamePlaceholder:"Character Name",CharacterTraits:"Character Traits",CharacterTraitsHeader:"Traits & Other Details",ChatRollDetails:{FlatCheckNoModifiers:"Flat checks never include any modifiers, bonuses, or penalties.",ModifiersAndDice:"Modifiers and Dice",RollOptions:"Roll Options",Select:"Inspect Roll",Title:"Roll Inspector"},Check:{DC:{Label:{AdjustedTarget:"Target: {target} ({dcType} {preadjusted} {adjusted})",NoChangeTarget:"Target: {target} ({dcType} {adjusted})",NoTarget:"{dcType} {dc}",WithTarget:"Target: {target} ({dcType} {dc})"},Specific:{armor:"AC",athletics:"Athletics DC",deception:"Deception DC",fortitude:"Fortitude DC",perception:"Perception DC",reflex:"Reflex DC",stealth:"Stealth DC",will:"Will DC"},Unspecific:"DC"},Label:"Check",Result:{AdjustedLabel:"Result: {unadjusted} {adjusted} by {offset}",Degree:{Attack:{criticalFailure:"Critical Miss",criticalSuccess:"Critical Hit",failure:"Miss",success:"Hit"},Check:{criticalFailure:"Critical Failure",criticalSuccess:"Critical Success",failure:"Failure",success:"Success"}},Label:"Result: {unadjusted} by {offset}"},SetAsInitiative:"Set as {actor}'s initiative",Specific:{Counteract:"Counteract Check",Perception:{Label:"Perception Check",Secret:"Perception Check (Secret)"},Recovery:"Recovery Check"}},CircumstanceBonusShortLabel:"Circumstance",CircumstanceBonusTitle:"Circumstance Bonus",ClassFeatLevels:"Class Feat Levels",ClassFeatures:"Class Features",ClassHP:"Class HP",ClipboardNotification:'Copied "{clipText}" to the clipboard.',CompendiumBrowser:{AddedItem:"Added {item} to the selected actor(s).",AddedItemToCharacter:"Added {item} to {character}.",BestiaryBrowser:"Bestiary Browser",BoughtItemWithAllCharacters:"Purchased {item} with all selected actor(s).",BoughtItemWithCharacter:"Purchased {item} with {character}.",BuyLabel:"Buy Item",FailedToBuyItemWithCharacter:"Could not purchase {item} with {character}.",FailedToBuyItemWithSomeCharacters:"Could not purchase {item} with some of the selected actor(s).",Hint:"Use the tabs above to select a compendium",RollTable:{AddDialogText:"Add {count} result(s) to Roll Table?",AddLabel:"Add to Roll Table",CreateDialogText:"Create Roll Table with {count} result(s)?",CreateLabel:"Create Roll Table",SelectTableTitle:"Select Roll Table",WeightLabel:"Weight"},Settings:{PacksLabel:"Packs",SourcesLabel:"Sources"},TabAction:"Actions",TabBestiary:"Bestiaries",TabCampaign:"Campaign",TabFeat:"Feats/Features",TakeLabel:"Take Item",Title:"Compendium Browser"},CompendiumMigrationStatus:{Document:"Document",Foundry:"Foundry",FoundryOld:"0.7 or older",Invalid:"Invalid",LockedTooltip:"Unable to migrate - compendium is locked",MigrateCompendium:"Migrate Compendium",Schema:"Schema",Size:"Size",Title:"Migration Status",UpToDate:"Up to Date"},Condition:{ActiveLabel:"Active",DurationNumberLabel:"Rounds",DurationTextLabel:"Duration",HasValueLabel:"Has Value",ImmutableLabel:"Immutable",ImmutableTitle:"Value cannot be reduced.",PerpetualLabel:"Perpetual Condition",RemovableLabel:"Removable",ValueLabel:"Value"},ConditionTypeBlinded:"Blinded",ConditionTypeBroken:"Broken",ConditionTypeClumsy:"Clumsy",ConditionTypeConcealed:"Concealed",ConditionTypeConfused:"Confused",ConditionTypeControlled:"Controlled",ConditionTypeDazzled:"Dazzled",ConditionTypeDeafened:"Deafened",ConditionTypeDoomed:"Doomed",ConditionTypeDrained:"Drained",ConditionTypeDying:"Dying",ConditionTypeEncumbered:"Encumbered",ConditionTypeEnfeebled:"Enfeebled",ConditionTypeFascinated:"Fascinated",ConditionTypeFatigued:"Fatigued",ConditionTypeFlatFooted:"Off-Guard",ConditionTypeFleeing:"Fleeing",ConditionTypeFriendly:"Friendly",ConditionTypeFrightened:"Frightened",ConditionTypeGrabbed:"Grabbed",ConditionTypeHelpful:"Helpful",ConditionTypeHidden:"Hidden",ConditionTypeHostile:"Hostile",ConditionTypeImmobilized:"Immobilized",ConditionTypeIndifferent:"Indifferent",ConditionTypeInvisible:"Invisible",ConditionTypeMalevolence:"Malevolence",ConditionTypeObserved:"Observed",ConditionTypeOffGuard:"Off-Guard",ConditionTypeParalyzed:"Paralyzed",ConditionTypePersistent:"Persistent Damage",ConditionTypePersistentShort:"Persistent",ConditionTypePetrified:"Petrified",ConditionTypeProne:"Prone",ConditionTypeQuickened:"Quickened",ConditionTypeRestrained:"Restrained",ConditionTypeSickened:"Sickened",ConditionTypeSlowed:"Slowed",ConditionTypeStunned:"Stunned",ConditionTypeStupefied:"Stupefied",ConditionTypeUnconscious:"Unconscious",ConditionTypeUndetected:"Undetected",ConditionTypeUnfriendly:"Unfriendly",ConditionTypeUnnoticed:"Unnoticed",ConditionTypeWounded:"Wounded",ConditionsLabel:"Conditions",ConsumableMessage:{UseExhausted:"Exhausted {name}",UseMulti:"Uses {name}, {current} remain",UseSingle:"Uses {name}"},CoreSkillsHeader:"Core Skills",Counteractable:"Counteractable",CraftDCTitle:"DC",CraftItemTitle:"Craft",CraftingTab:{Alchemical:{AdvancedAlchemy:"Advanced Alchemy",AdvancedAlchemyLevel:"Advanced Alchemy Level",InfusedReagents:"Infused Reagents",ReagentCost:"Reagent Cost",ToggleSignatureItem:"Toggle Signature Item",TotalCost:"Total Cost"},Alerts:{CharacterLevel:"Item level exceeds character level.",FormulaExpended:"Prepared formula has already been crafted.",ItemMissingTraits:"Item is not compatible with crafting entry item requirements.",MaxItemLevel:"Item level exceeds maximum item level for entry.",MaxSlots:"Crafting entry's allowed slots are full.",MissingReagents:"Insufficient infused reagents to complete crafting."},CraftQuantityTitle:"Quantity",ExpendFormula:"Expend Formula",NoEligibleEntry:"No eligible crafting entry was found.",QuickAddTitle:"Add this formula to one or more crafting entries",RemoveFormulaDialogQuestion:"Are you sure you want to remove the formula for {name}?",RemoveFormulaDialogTitle:"Remove Formula",ToggleFreeCrafting:"Toggle Free Crafting",ToggleQuickAlchemy:"Quick Alchemy",UndeletableTooltip:"This crafting formula is part of another item and cannot be individually deleted.",UnprepareFormulaDialogQuestion:"Are you sure you want to unprepare the formula for {name}?",UnprepareFormulaDialogTitle:"Unprepare Formula"},CreateActionTitle:"Create Action",CreateAttackTitle:"Create Attack",CreateFeatTitle:"Create Feat",CreateFormulaTitle:"Create Formula",CreateItemTitle:"Create Item",CreateLabelUniversal:"Create",CreateSkillTitle:"Create Skill",CreateSpellTitle:"Create Spell",CritFailure:"Critical Failure",CritSuccess:"Critical Success",CriticalDamageLabel:"Critical",CriticalFumbleCardButtonTitle:"Draw a Critical Fumble Card",CriticalHitCardButtonTitle:"Draw a Critical Hit Card",CurrencyAbbreviations:{cp:"cp",gp:"gp",pp:"pp",sp:"sp"},CurrencyCP:"Copper",CurrencyGP:"Gold",CurrencyPP:"Platinum",CurrencySP:"Silver",CurrentHitPointsShortLabel:"Current HP",CurrentStaminaPointsShortLabel:"Current SP",DCAdjustmentEasy:"easy",DCAdjustmentHard:"hard",DCAdjustmentIncrediblyEasy:"incredibly easy",DCAdjustmentIncrediblyHard:"incredibly hard",DCAdjustmentNormal:"baseline",DCAdjustmentVeryEasy:"very easy",DCAdjustmentVeryHard:"very hard",DCBase:"Base DC 10",DCWithValue:"DC {dc} {text}",DCWithValueAndVisibility:'DC {dc} {text}',Damage:{Base:"Base",IWR:{ActorIsImmune:"{actor} is immune to {effect}.",ActorIsUnaffected:"{actor} is unaffected by {effect}.",ApplicationBreakdown:{ignored:"Resistance to {type} ignored!",immunity:"Immune to {type}: {adjustment}",resistance:"Resistant to {type}: {adjustment}",unaffected:"Unaffected by {type}: {adjustment}",weakness:"Weak to {type}: {adjustment}",reduction:"Reduced by {type}: {adjustment}"},CompositeLabel:{Exceptions0DoubleVs0:"{type} {value}",Exceptions0DoubleVs1:"{type} {value} (double resistance vs. {doubleVs1})",Exceptions0DoubleVs2:"{type} {value} (double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions0DoubleVs3:"{type} {value} (double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions0DoubleVs4:"{type} {value} (double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions1DoubleVs0:"{type} {value} (except {exception1})",Exceptions1DoubleVs1:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1})",Exceptions1DoubleVs2:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions1DoubleVs3:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions1DoubleVs4:"{type} {value} (except {exception1}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions2DoubleVs0:"{type} {value} (except {exception1} or {exception2})",Exceptions2DoubleVs1:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1})",Exceptions2DoubleVs2:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions2DoubleVs3:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions2DoubleVs4:"{type} {value} (except {exception1} or {exception2}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions3DoubleVs0:"{type} {value} (except {exception1}, {exception2}, or {exception3})",Exceptions3DoubleVs1:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1})",Exceptions3DoubleVs2:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions3DoubleVs3:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions3DoubleVs4:"{type} {value} (except {exception1}, {exception2}, or {exception3}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})",Exceptions4DoubleVs0:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4})",Exceptions4DoubleVs1:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1})",Exceptions4DoubleVs2:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1} or {doubleVs2})",Exceptions4DoubleVs3:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1}, {doubleVs2}, or {doubleVs3})",Exceptions4DoubleVs4:"{type} {value} (except {exception1}, {exception2}, {exception3}, or {exception4}; double resistance vs. {doubleVs1}, {doubleVs2}, {doubleVs3}, or {doubleVs4})"},Type:{abysium:"abysium",adamantine:"adamantine","all-damage":"all damage","area-damage":"area damage","arrow-vulnerability":"arrow vulnerability",auditory:"auditory","axe-vulnerability":"axe vulnerability",blinded:"blinded",broken:"broken",clumsy:"clumsy","cold-iron":"cold iron",confused:"confused",controlled:"controlled","critical-hits":"critical hits",curse:"curse","damage-from-spells":"damage from spells",dawnsilver:"dawnsilver",dazzled:"dazzled",deafened:"deafened","death-effects":"death effects",disease:"disease",djezet:"djezet",doomed:"doomed",drained:"drained",duskwood:"duskwood",emotion:"emotion",energy:"energy",enfeebled:"enfeebled",fascinated:"fascinated",fatigued:"fatigued","fear-effects":"fear effects",fleeing:"fleeing",frightened:"frightened","ghost-touch":"ghost touch",glass:"glass",grabbed:"grabbed",healing:"healing",hidden:"hidden",holy:"holy",illusion:"illusion",immobilized:"immobilized",inhaled:"inhaled",inubrix:"inubrix",light:"light",magic:"magic",magical:"magical",metal:"metal","misfortune-effects":"misfortune effects","non-magical":"non-magical",nonlethal:"nonlethal","nonlethal-attacks":"nonlethal attacks",noqual:"noqual","object-immunities":"object immunities","off-guard":"off-guard",olfactory:"olfactory",orichalcum:"orichalcum",paralyzed:"paralyzed","persistent-damage":"persistent damage",petrified:"petrified",physical:"physical",plant:"plant",polymorph:"polymorph",possession:"possession",prone:"prone","protean-anatomy":"protean anatomy",radiation:"radiation",restrained:"restrained",salt:"salt","salt-water":"salt water",scrying:"scrying",siccatite:"siccatite",sickened:"sickened",silver:"silver",sleep:"sleep",slowed:"slowed","spell-deflection":"spell deflection",spells:"spells","splash-damage":"splash damage",stunned:"stunned",stupefied:"stupefied","swarm-attacks":"swarm attacks","swarm-mind":"swarm mind",trip:"trip","unarmed-attacks":"unarmed attacks",unconscious:"unconscious",unholy:"unholy","vampire-weaknesses":"vampire weaknesses",visual:"visual",vorpal:"vorpal","vorpal-adamantine":"vorpal adamantine","vorpal-fear":"vorpal fear","vulnerable-to-sunlight":"vulnerable to sunlight",water:"water",weapons:"weapons","weapons-shedding-bright-light":"weapons shedding bright light",wood:"wood",wounded:"wounded"}},Hardness:{Full:"hardness",Half:"half hardness"},IncreasedFrom:"Increased from {original} to minimum of 1",Kind:{Both:{Label:"Both",Roll:{Noun:"Damage/Healing Roll",Verb:"Roll Damage/Healing"}},Damage:{Roll:{Noun:"Damage Roll",Verb:"Roll Damage"}},Healing:{Apply:{Label:"Apply Healing"},Roll:{Noun:"Healing Roll",Verb:"Roll Healing"}}},NoDamageFormulaLabel:"No damage",PersistentTooltip:"Persistent {damageType}",Precision:"Precision",RollFlavor:{acid:"acid",air:"air",bleed:"bleed",bludgeoning:"bludgeoning",cold:"cold",earth:"earth",electricity:"electricity",fire:"fire",force:"force",mental:"mental",metal:"metal",persistent:"persistent {damageType}",piercing:"piercing",poison:"poison",precision:"precision",slashing:"slashing",sonic:"sonic",spirit:"spirit",splash:"splash",vitality:"vitality",void:"void",untyped:"untyped"},Scatter:"Scatter Damage"},DamageButton:{Adjust:"[Shift-Click] Adjust value before applying.",Double:"[Click] Apply double damage to selected tokens.",DoubleContext:"Double Damage",DoubleShort:"Double",Full:"[Click] Apply full damage to selected tokens.",FullContext:"Apply Damage",FullShort:"Damage",Half:"[Click] Apply half damage to selected tokens.",HalfContext:"Half Damage",HalfShort:"Half",Healing:"[Click] Apply full healing to selected tokens.",HealingContext:"Apply Healing",HealingShort:"Heal",ShieldBlock:"[Click] Toggle the shield block status of the selected tokens before applying damage.",ShieldBlockContext:"Shield Block",ShieldBlockShort:"Block",Triple:"[Click] Apply triple damage to selected tokens.",TripleContext:"Apply Triple Damage",TripleShort:"Triple"},DamageCategoriesLabel:"Damage Categories",DamageDieD10:"d10",DamageDieD12:"d12",DamageDieD4:"d4",DamageDieD6:"d6",DamageDieD8:"d8",DamageLabel:"Damage",DamageRoll:"Damage Roll",DecrementEffectTitle:"Decrease Effect Level",DefensesLabel:"Defenses",Deity:"Deity",DeleteQuestion:"Are you sure you want to delete {name}?",DeleteConditionTitle:"Delete Condition",DeleteItemTitle:"Delete Item",DeleteShortLabel:"Delete",DeleteSpellcastEntryQuestion:"Are you sure you want to delete this spellcasting entry?",DeleteSpellcastEntryTitle:"Delete Spellcasting",DeleteSpellcastEntryWarning:"WARNING: All spells in this spellcasting entry will also be deleted.",DenominationLabel:"Denomination",DetailsHeading:"Details",DragDropFeats:"Drag & Drop feats to add",Duration:{P1M:"month",P1W:"week",P1Y:"year",PT10M:"10 minutes",PT1H:"hour",PT1M:"minute",PT24H:"24 hours",day:"day",round:"round",turn:"turn"},Edit:"Edit",EditHazardLabel:"Edit Hazard",EditItemTitle:"Edit Item",EditLabel:"Edit?",EffectPanel:{AppliedBy:"Applied by: {condition-list}",DecrementToolTip:"[Right Click] Decrease value",Expired:"Expired",IncrementToolTip:"[Left Click] Increase value",RemainingDuration:{MultipleDays:"{days} days remaining",MultipleHours:"{hours} hours remaining",MultipleMinutes:"{minutes} minutes remaining",MultipleRounds:"{rounds} rounds remaining",MultipleSeconds:"{seconds} seconds remaining",MultipleWeeks:"{weeks} weeks remaining",MultipleYears:"{years} years remaining",SingleRound:"1 round remaining",SingleSecond:"1 second remaining",SingleWeek:"1 week remaining",SingleYear:"1 year remaining",ZeroRoundsExpireTurnEnd:"0 rounds remaining, expires end of initiative {initiative}",ZeroRoundsExpireTurnStart:"0 rounds remaining, expires start of initiative {initiative}"},RemoveToolTip:"[Right Click] Remove effect",RollDamageToolTip:"[Left Click] Roll damage",Sustained:"Sustained?",Unidentified:"Unidentified",UnlimitedDuration:"Unlimited duration",UntilEncounterEnds:"Until encounter ends"},EffectsLabel:"Effects",EmptySlot:"Empty Slot",Encounter:{AlreadyRolled:"{actor} has already rolled initiative.",Broadcast:{FastHealing:{DeactivatedBy:"Deactivated by {types}","fast-healing":{Name:"Fast Healing",ReceivedMessage:"Received fast healing"},regeneration:{Name:"Regeneration",ReceivedMessage:"Received regeneration"}},TempHP:{PluralNew:"{actor} now has {newQuantity} temporary hit points{wasAt} from {item}.",SingleNew:"{actor} now has {newQuantity} temporary hit point{wasAt} from {item}.",WasAt:" (was at {oldQuantity})"}},Budget:{EncounterBudget:"Encounter Budget",PartyLevel:"Party Level",PartySize:"Party Size",Reward:"Reward",Threat:"Threat",Threats:{extreme:"Extreme",low:"Low",moderate:"Moderate",severe:"Severe",trivial:"Trivial"},XPBudget:"XP Budget",XPNeeded:"XP Needed"},CreatureXPAndRole:{CreatureLevel:"Creature Level",CreatureLevels:{0:"Any standard creature or low-threat boss",1:"Low- or moderate-threat boss",2:"Moderate- or severe-threat boss",3:"Severe- or extreme-threat boss",4:"Extreme-threat solo boss","-1":"Any standard creature","-2":"Any lackey or standard creature","-3":"Low- or moderate-threat lackey","-4":"Low-threat lackey"},CreatureXPAndRole:"Creature XP and Role",SuggestedRole:"Suggested Role"},ExcludingFromInitiative:"Excluding {type} {actor} from initiative.",HasNoInitiativeScore:"{actor} has no initiative score.",HideName:"Hide Name",InitiativeSet:"Initiative of {actor} was set to {initiative}.",Metrics:{Award:{Label:"Award: {xp} XP",Tooltip:{Four:"4 Party Members",Plural:"{xpPerFour} \xD7 4 / {recipients} Party Members",Singular:"1 Party Member"}},Budget:"Budget: {spent}/{max} XP (Party Level {partyLevel})",Threat:"Threat: {threat}"},NoActiveEncounter:"There is no active encounter.",NoTokenInScene:"{actor} has no token in the scene.",RevealName:"Reveal Name",XP:"XP"},ErrorMessage:{CantCreateEffectMacro:"An effect for a toggle macro must come from a compendium or world item.",CantImportTooHighVersion:"Unable to import {sourceName}: its schema version ({sourceSchemaVersion}) is higher than this world's ({worldSchemaVersion}).",CantMoveItemDestination:"You are not allowed to move items to this character.",CantMoveItemSource:"You are not allowed to move items from this character.",ItemNotFoundByUUID:'Item with UUID of "{uuid}" not found.',MinimumProfLevelSetByFeatures:"The selected proficiency is below proficiency set by features.",NoCreatureTokenSelected:"Select at least one token associated with a creature.",NoPCTokenSelected:"Select at least one token associated with a PC.",NoTokenSelected:"Select at least one token.",NoUpdatePermission:"You lack permission to update this actor.",NotEnoughAmmo:"You don't have enough ammo to make this strike.",NotEnoughCoins:"Insufficient Coins",RuleElementSyntax:"Syntax error in rule element definition: {message}",SubV9Module:"{module} is unmaintained and may introduce stability issues to your game.",WeaponNoDamage:"This weapon deals no damage.",WeaponQuantityZero:"You have no more of these weapons equipped."},Ethnicity:"Ethnicity",ExpendSpellTitle:"Expend Spell",Failure:"Failure",Familiar:{AbilitiesLabel:"Abilities",ArmorClass:"Armor Class",AttackRoll:"Attack Roll",Creature:"Creature",CreatureType:"Creature Type",Defenses:"Defense",Familiar:"Familiar",Master:"Master",MasterActor:"Master Actor",MasterLevel:"Master Level",MasterSpellcastingAbility:"Master Attribute",Offenses:"Offenses",Perception:"Perception",SelectMaster:"Select a master...",Skills:"Skills",TotalNumberFamiliarAbilities:"Total # of Familiar Abilities"},FeatActionTypeLabel:"Action Type",FeatActionsLabel:"Number of Actions",FeatAncestryHeader:"Ancestry Feats",FeatArchetypeHeader:"Archetype Feats",FeatBackgroundShort:"BG",FeatBonusHeader:"Bonus Feats",FeatBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:
source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes.
Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",FeatCampaignHeader:"Campaign Feats",FeatClassHeader:"Class Feats",FeatDeityBoonCursesHeader:"Divine Intercessions",FeatGeneralHeader:"General Feats",FeatLevelLabel:"Level",FeatPFSBoonHeader:"Society Boons",FeatPrereqLabel:"Prerequisites",FeatSkillHeader:"Skill Feats",FeatTypeAncestry:"Ancestry Feat",FeatTypeAncestryfeature:"Ancestry Feature",FeatTypeBonus:"Bonus Feat",FeatTypeClass:"Class Feat",FeatTypeClassfeature:"Class Feature",FeatTypeCurse:"Deity Curse",FeatTypeDeityboon:"Deity Boon",FeatTypeGeneral:"General Feat",FeatTypePfsboon:"Society Boon",FeatTypeSkill:"Skill Feat",FeaturesAncestryHeader:"Ancestry Features",FeaturesClassHeader:"Class Features",Feet:"feet",FlatCheck:"Flat Check",Focus:{NotEnoughFocusPointsError:"You do not have enough focus points to cast this spell.",Outdated:"Old value of the focus pool as a reminder. Click to delete.",Pool:"Focus Pool",Previous:"Previous",Spells:"Focus Spells",label:"Focus Points",pointLabel:"Points"},Foot:"Foot",FormulaKnownTitle:"Known Formulas",FormulaListEmpty:"Empty (drag formula/item here)",Formula:"Formula",FormulaSheet:{DescriptionUnknown:"This formula is completely filled with drawings of small stick men, stains from some unknown liquid, nonsensical rhymes written in children's letters, and other seemingly random markings. It must have been made by goblins, and makes no sense to you.
Note This formula is referencing a missing or invalid item.",NameEmpty:"Empty Formula",NamePrefix:"Formula of {name}",NameUnknown:"Unknown Formula"},Frequency:{AtWill:"At-Will",Label:"Frequency",per:"per"},GenderPronoun:"Gender/Pronouns",GeneralFeatLevels:"General Feat Levels",GreaterWeaponSpecialization:"Greater Weapon Specialization",HardnessLabel:"Hardness",HazardDescriptionLabel:"Description",HazardDisableLabel:"Disable",HazardResetLabel:"Reset",HazardRoutineLabel:"Routine",HealingTypeTemporaryHealing:"Healing (Temporary)",Height:"Height",Heritage:"Heritage",HeroPointRatio:{Many:"{value}/{max} Hero Points",One:"1/{max} Hero Point"},HeroPointsLabel:"Hero Points",HitPointsDetailsLabel:"HP Details",HitPointsDetailsTitle:"Additional information related to Hit Points such as Fast Healing or Regeneration",HitPointsHeader:"Hit Points",HitPointsShortLabel:"HP",ImageLabel:"Image",ImmunitiesLabel:"Immunities",IncrementEffectTitle:"Increase Effect Level",InitiativeIsNow:"{name}'s Initiative is now {value}!",InitiativeHeader:"Initiative bonus",InitiativeLabel:"Initiative",InitiativeWithSkill:"Initiative: {skillName}",InlineCheck:{BasicWithSave:"Basic {save}",DCWithName:"{name} DC",Invalid:"Invalid @Check expression: {message}",Errors:{AdjustmentLengthMismatch:"mismatch between number of type and adjustment parameters",DCAndDefense:"cannot have both dc and defense arguments",NonIntegerAdjustment:"adjustments must be integers",TypeMissing:"type argument is mandatory",InvalidDomains:"{type} domains must be sluggified and end with -damage"}},InlineDamage:{Base:"Base: {formula}"},InlineTemplateErrors:{DistanceMissing:"Error in @Template: distance parameter is mandatory",DistanceNoNumber:"Error in @Template: dimension {distance} is not a number",TypeMissing:"Error in @Template: type parameter is mandatory",TypeUnsupported:"Error in @Template: type {type} is not supported",WidthNoNumber:"Error in @Template: width {width} is not a number"},InventroyBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:
source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes.
Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",InvestedLabel:"Invested",Item:{ABC:{InvalidDrop:"{badType} cannot be dropped here (must be {goodType})"},Action:{Category:{None:"None",Defensive:"Defensive",Interaction:"Interaction",Offensive:"Offensive",Familiar:"Familiar Ability"},Plural:"Abilities",SelfAppliedEffect:{Applied:"{effect} was applied.",Delete:"Delete Reference",Drop:"Drop Effect",Label:"Self-Applied Effect",Hint:"A single effect item to be applied to the actor that uses this action"},Type:{Activity:"Activity",Free:"Free Action",Single:"Single Action",Reaction:"Reaction"}},Activation:{Add:"Add Activation",Cast:"Cast a Spell",Command:"command",CommandSheetLabel:"Command",Envision:"envision",EnvisionSheetLabel:"Envision",Interact:"Interact",Label:"Activation"},Affliction:{AddStage:"Add Stage",Error:{RestrictedStageItem:"Only effect items can be directly added to afflictions"},Linked:{Title:"If set, prevents the condition from being removed while the affliction lasts"},OnsetLabel:"Onset",OnsetActive:"Onset Active",SaveLabel:"Save DC",Stage:"Stage {stage}",StageLabel:"Stage"},Ancestry:{Vision:{Label:"Vision",Normal:"Normal Vision"}},Armor:{Base:{"armored-cloak":"Armored Cloak","armored-coat":"Armored Coat","bastion-plate":"Bastion Plate",breastplate:"Breastplate","buckle-armor":"Buckle Armor","ceramic-plate":"Ceramic Plate","chain-mail":"Chain Mail","chain-shirt":"Chain Shirt","coral-armor":"Coral Armor","explorers-clothing":"Explorer's Clothing","fortress-plate":"Fortress Plate","full-plate":"Full Plate",gi:"Gi","half-plate":"Half Plate","hellknight-breastplate":"Hellknight Breastplate","hellknight-half-plate":"Hellknight Half Plate","hellknight-plate":"Hellknight Plate","hide-armor":"Hide Armor","lamellar-breastplate":"Lamellar Breastplate","lattice-armor":"Lattice Armor","leaf-weave":"Leaf Weave","leather-armor":"Leather Armor","leather-lamellar":"Leather Lamellar","mantis-shell":"Mantis Shell",niyahaat:"Niyah\xE1at","o-yoroi":"O-Yoroi","padded-armor":"Padded Armor","power-suit":"Power Suit","quilted-armor":"Quilted Armor",sankeit:"Sankeit","scale-mail":"Scale Mail","scroll-robes":"Scroll Robes","splint-mail":"Splint Mail","studded-leather-armor":"Studded Leather Armor","subterfuge-suit":"Subterfuge Suit","wooden-breastplate":"Wooden Breastplate"},Category:{"heavy-barding":"Heavy Barding","light-barding":"Light Barding"},Rune:{Resilient:{Label:"Resilient Rune"}},Specific:{Hint:"Marking this armor as specific magic armor indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Armor"},UnequippedHint:"This armor is bulkier due to not being equipped."},CampaignFeature:{CampaignLabel:"Campaign"},CannotAddType:"{type} items cannot be added to this actor.",Condition:{Flanked:"Off-Guard (Flanked)",PersistentDamage:{AssistedRecovery:"Roll Assisted Recovery",Chat:{Recover:"Roll Recovery Check",RecoverLabel:"Recovery: {name}"},Dialog:{Add:"Add Persistent Damage",Invalid:"Formula is invalid.",Remove:"Remove Persistent Damage",Title:"Persistent Damage ({actor})"},Error:{DoesNotExist:"No persistent {damageType} damage exists on the actor"},Name:"Persistent Damage ({formula} {damageType})",NameWithDC:"Persistent Damage ({formula} DC{dc})",RollDamage:"Roll Damage"}},Consumable:{Damage:{Add:"Add Damage/Healing",Label:"Damage/Healing",Remove:"Remove Damage/Healing"},Category:{ammo:"Ammunition",catalyst:"Catalyst",drug:"Drug",elixir:"Elixir",fulu:"Fulu",gadget:"Gadget",mutagen:"Mutagen",oil:"Oil",other:"Other",poison:"Poison",potion:"Potion",scroll:"Scroll",snare:"Snare",talisman:"Talisman",toolkit:"Toolkit",wand:"Wand"},Plural:"Consumables",Uses:{AutoDestroy:"Destroy on Use",Label:"Uses",None:"No Uses Remain",Use:"Use"}},Container:{Bulk:{Capacity:"Bulk Capacity",Ignored:"Bulk Ignored"},Plural:"Containers",Stowing:"Is Stowing Container?"},CreationDialog:{Categories:{Character:"Character Building",Other:"Other",Physical:"Physical Items"}},Deity:{Alignment:"Alignment",Category:{Hint:"Pantheons of deities and philosophies not associated with any deity can be followed instead of a particular deity. Clerics and Champions must follow a deity or pantheon.",Pantheon:"Pantheon",Philosophy:"Philosophy"},ClericSpells:{DropError:"A deity's cleric spells may not include cantrips, focus spells, or rituals.",Hint:"To add a spell, drag and drop one onto this sheet.",Label:"Cleric Spells"},DivineAttribute:{Hint:"If choosing the Raised by Belief background, its attribute boost options come from a deity.",Label:"Divine Attribute"},DivineFont:{Harm:"Harm",Heal:"Heal",Label:"Divine Font"},DivineSkill:"Divine Skill",Domain:{Abomination:{Description:"You seek to instill abhorrence and horror in those around you.",Label:"Abomination"},Air:{Description:"You can control winds and the weather.",Label:"Air"},AirApocryphal:{Description:"You can control winds and the weather. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Air (apocryphal)"},Ambition:{Description:"You strive to keep up with and outpace the competition.",Label:"Ambition"},AmbitionApocryphal:{Description:"You strive to keep up with and outpace the competition. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Ambition (apocryphal)"},Change:{Description:"You can restructure the physical and metaphysical.",Label:"Change"},Cities:{Description:"You have powers over urban environments and denizens.",Label:"Cities"},Cold:{Description:"You control ice, snow, and freezing temperatures.",Label:"Cold"},Confidence:{Description:"You overcome your fear and project pride.",Label:"Confidence"},ConfidenceApocryphal:{Description:"You overcome your fear and project pride. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Confidence (apocryphal)"},Creation:{Description:"You have divine abilities related to crafting and art.",Label:"Creation"},Darkness:{Description:"You operate in the darkness and take away the light.",Label:"Darkness"},DarknessApocryphal:{Description:"You operate in the darkness and take away the light. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Darkness (apocryphal)"},Death:{Description:"You have the power to end lives and destroy undead.",Label:"Death"},DeathApocryphal:{Description:"You have the power to end lives and destroy undead. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Death (apocryphal)"},Decay:{Description:"You have the power to spoil and deteriorate matter.",Label:"Decay"},Delirium:{Description:"You can bring about hallucinations and restlessness.",Label:"Delirium"},Destruction:{Description:"You are a conduit for divine devastation.",Label:"Destruction"},Dreams:{Description:"You have the power to enter and manipulate dreams.",Label:"Dreams"},Dust:{Description:"You have the power to dry and crumble what opposes you.",Label:"Dust"},Duty:{Description:"You defend oaths and carry out your divine missions with great dedication.",Label:"Duty"},Earth:{Description:"You control soil and stone.",Label:"Earth"},Family:{Description:"You aid and protect your family and community more effectively.",Label:"Family"},Fate:{Description:"You see and understand hidden inevitabilities.",Label:"Fate"},FateApocryphal:{Description:"You see and understand hidden inevitabilities. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Fate (apocryphal)"},Fire:{Description:"You control flame.",Label:"Fire"},FireApocryphal:{Description:"You control flame. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Fire (apocryphal)"},Freedom:{Description:"You liberate yourself and others from shackles and constraints.",Label:"Freedom"},Glyph:{Description:"You wield power over written words and symbols.",Label:"Glyph"},Healing:{Description:"Your healing magic is particularly potent.",Label:"Healing"},Indulgence:{Description:"You feast mightily and can shake off the effects of overindulging.",Label:"Indulgence"},IndulgenceApocryphal:{Description:"You feast mightily and can shake off the effects of overindulging. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Indulgence (apocryphal)"},Introspection:{Description:"You guide others in examining their lives, emotions, and motivations to ultimately become a truer version of themselves\u2014a difficult and often painful process.",Label:"Introspection"},Knowledge:{Description:"You receive divine insights.",Label:"Knowledge"},KnowledgeApocryphal:{Description:"You receive divine insights. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Knowledge (apocryphal)"},Lightning:{Description:"You control electricity, thunder, and storms.",Label:"Lightning"},Luck:{Description:"You're unnaturally lucky and keep out of harm's way.",Label:"Luck"},Magic:{Description:"You perform the unexpected and inexplicable.",Label:"Magic"},Metal:{Description:"You manipulate flexible, mutable metal.",Label:"Metal"},Might:{Description:"Your physical power is bolstered by divine strength.",Label:"Might"},MightApocryphal:{Description:"Your physical power is bolstered by divine strength. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Might (apocryphal)"},Moon:{Description:"You command powers associated with the moon.",Label:"Moon"},Naga:{Description:"Like the serpentine nagas, you're in tune with cosmic forces that Ravithra once controlled.",Label:"Naga"},Nature:{Description:"You hold power over animals and plants.",Label:"Nature"},Nightmares:{Description:"You fill minds with horror and dread.",Label:"Nightmares"},Pain:{Description:"You punish those who displease you with the sharp sting of pain.",Label:"Pain"},Passion:{Description:"You evoke passion, whether as love or lust.",Label:"Passion"},Perfection:{Description:"You strive to perfect your mind, body, and spirit.",Label:"Perfection"},Plague:{Description:"You wield disease and pestilence like a weapon.",Label:"Plague"},Protection:{Description:"You ward yourself and others.",Label:"Protection"},Repose:{Description:"You ease mental burdens.",Label:"Repose"},Secrecy:{Description:"You protect secrets and keep them hidden.",Label:"Secrecy"},SecrecyApocryphal:{Description:"You protect secrets and keep them hidden. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Secrecy (apocryphal)"},Sorrow:{Description:"You have a painful connection to melancholy and sadness.",Label:"Sorrow"},Soul:{Description:"You wield power over the spiritual.",Label:"Soul"},Star:{Description:"You command the power of the stars.",Label:"Star"},Sun:{Description:"You harness the power of the sun and other light sources, and punish undead.",Label:"Sun"},Swarm:{Description:"You exert control over masses of creatures.",Label:"Swarm"},Time:{Description:"You reign over the flow of time.",Label:"Time"},Toil:{Description:"You work constantly and refuse to let anything stand in your way.",Label:"Toil"},Travel:{Description:"You have power over movement and journeys.",Label:"Travel"},TravelApocryphal:{Description:"You have power over movement and journeys. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Travel (apocryphal)"},Trickery:{Description:"You deceive others and cause mischief.",Label:"Trickery"},Truth:{Description:"You pierce lies and discover the truth.",Label:"Truth"},Tyranny:{Description:"You wield power to rule and enslave others.",Label:"Tyranny"},Undeath:{Description:"Your magic carries close ties to the undead.",Label:"Undeath"},Vigil:{Description:"You watch over those long passed and guard their secrets.",Label:"Vigil"},Void:{Description:"You draw power from emptiness.",Label:"Void"},Water:{Description:"You control water and bodies of water.",Label:"Water"},WaterApocryphal:{Description:"You control water and bodies of water. Not all clerical traditions are taught among the orthodoxy. Some are whispered in secret, passed down from a priest to trusted acolytes or scribed in tomes left behind by splinter factions.",Label:"Water (apocryphal)"},Wealth:{Description:"You hold power over wealth, trade, and treasure.",Label:"Wealth"},Wood:{Description:"You command the indomitable power of wood.",Label:"Wood"},Wyrmkin:{Description:"You draw on the power of dragons, linnorms, and other powerful reptilian creatures.",Label:"Wyrmkin"},Zeal:{Description:"Your inner fire increases your combat prowess.",Label:"Zeal"}},Domains:{Alternate:{Hint:"A cleric can take the Expanded Domain Initiate feat to gain access to one of their deity's alternate domains.",Label:"Alternate Domains"},Primary:"Primary Domains"},FavoredWeapons:{Hint:"Almost all deities have a single favored weapon, but a few have both a favored weapon and unarmed attack.",Label:"Favored Weapon(s)"},Sanctification:{Can:{Holy:"can choose holy",HolyUnholy:"can choose holy or unholy",Unholy:"can choose unholy"},Label:"Divine Sanctification",Must:{Holy:"must choose holy",Unholy:"must choose unholy"},None:"none"},Spellcasting:"Spellcasting"},Effect:{Expiry:{EndOfRound:"End of Round",EndOfTurn:"End of Turn",ExpiresOn:"Expires On",StartOfTurn:"Start of Turn"},Badge:{Add:"Add Badge",Labels:{Add:"Add Label",Label:"Labels",Hint:"The values of a badge can be given descriptive labels. They should be short enough to fit in the effects panel. Labels also serve as a natural maximum value for a badge.",Placeholder:"New Label"},Range:"Range",ReevaluateFormula:{Label:"Reevaluate?",Never:"Never",TurnEnd:"On Turn End",TurnStart:"On Turn Start"},Type:{counter:"Counter",formula:"Formula",value:"Fixed Value"}},Disintegrated:{Description:"Maybe it's a treatable condition.",Name:"Disintegrated"},Plural:"Effects",ShowTokenIcon:"Show token icon?",Sustained:"Sustained",Unidentified:"Unidentified?"},Feat:{Info:{Added:"{item} was added to {category}."},KeyAbilityOptions:{Label:"Key Attribute Options",Hint:"Key attribute options in addition to this provided by a class"},LevelLabel:"Feat",LevelN:"Feat {level}",OnlyLevel1:"Must be taken at level 1",Plural:"Feats",TakeMultiple:{Five:"Up to 5\xD7",Four:"Up to 4\xD7",Label:"Can be taken multiple times",NoLimit:"No limit",Three:"Up to 3\xD7",Two:"Up to 2\xD7"},Warning:{InvalidCategory:'Cannot add feat "{item}" to {category}: feat type is invalid.',TakenAfterLevel1:"{item} must be taken at level 1, but {actor} is at level {actorLevel}.",TakenMoreThanMax:"{item} may only be taken {maxTakable} times, but {actor} has selected it {timesTaken} times.",TakenMoreThanOnce:"{item} may only be taken once, but {actor} has selected it an additional time."}},GMNotes:{Add:"Add GM Notes",Title:"GM Notes"},Heritage:{AncestryNotFound:"The referenced ancestry item was not found.",DragAncestryHere:"Drag an ancestry item here to set this heritage's prerequisite ancestry.",NoneVersatile:"None (Versatile)",RemoveAncestry:"Remove prerequisite ancestry"},IconLabel:"Icon",MaterialEffects:{Hint:"Precious-material damage effects that can trigger or bypass some creatures' immunities, weaknesses, and resistances (applied to inline damage rolls)",Label:"Material Damage Effects"},NameLabel:"Name",OtherTags:{Label:"Other Tags",Hint:"Additional tags beyond traits to help classify an item"},Physical:{Base:"Base",Broken:"Broken",BrokenThreshold:{Label:"Broken Threshold",ShortLabel:"BT"},Bulk:{HeldOrStowed:"Bulk (held/stowed)",Label:"Bulk",Light:{Label:"Light",ShortLabel:"L"},Negligible:{Label:"Negligible",ShortLabel:"\u2014"},NLight:"{light}L",WithLight:"{bulk}, {light}L"},Destroyed:"Destroyed",FromSpell:{CantripDeck5:"Cantrip Deck of {name} (5-pack)",Scroll:"Scroll of {name} (Rank {level})",Wand:"Wand of {name} (Rank {level})"},GeneratedName:{FourProperties:"{property1} {property2} {property3} {property4} {base}",FourPropertiesMaterial:"{property1} {property2} {property3} {property4} {material} {base}",Fundamental2:"{fundamental2} {base}",Fundamental2Material:"{fundamental2} {material} {base}",Hint:'This is the name of the base weapon. For most weapons, the base is used to generate a fuller name, taking into account the material composition and/or runes. Giving this weapon a custom name or marking it as "specific" will prevent the generated name from appearing.',Material:"{material} {base}",OneProperty:"{property1} {base}",OnePropertyMaterial:"{property1} {material} {base}",Potency:"+{potency} {base}",PotencyFourProperties:"+{potency} {property1} {property2} {property3} {property4} {base}",PotencyFourPropertiesMaterial:"+{potency} {property1} {property2} {property3} {property4} {material} {base}",PotencyFundamental2:"+{potency} {fundamental2} {base}",PotencyFundamental2FourProperties:"+{potency} {fundamental2} {property1} {property2} {property3} {property4} {base}",PotencyFundamental2FourPropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {property3} {property4} {material} {base}",PotencyFundamental2Material:"+{potency} {fundamental2} {material} {base}",PotencyFundamental2OneProperty:"+{potency} {fundamental2} {property1} {base}",PotencyFundamental2OnePropertyMaterial:"+{potency} {fundamental2} {property1} {material} {base}",PotencyFundamental2ThreeProperties:"+{potency} {fundamental2} {property1} {property2} {property3} {base}",PotencyFundamental2ThreePropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {property3} {material} {base}",PotencyFundamental2TwoProperties:"+{potency} {fundamental2} {property1} {property2} {base}",PotencyFundamental2TwoPropertiesMaterial:"+{potency} {fundamental2} {property1} {property2} {material} {base}",PotencyMaterial:"+{potency} {material} {base}",PotencyOneProperty:"+{potency} {property1} {base}",PotencyOnePropertyMaterial:"+{potency} {property1} {material} {base}",PotencyThreeProperties:"+{potency} {property1} {property2} {property3} {base}",PotencyThreePropertiesMaterial:"+{potency} {property1} {property2} {property3} {material} {base}",PotencyTwoProperties:"+{potency} {property1} {property2} {base}",PotencyTwoPropertiesMaterial:"+{potency} {property1} {property2} {material} {base}",Reinforcing:"{reinforcing} {base}",ReinforcingMaterial:"{reinforcing} {material} {base}",ThreeProperties:"{property1} {property2} {property3} {base}",ThreePropertiesMaterial:"{property1} {property2} {property3} {material} {base}",TwoProperties:"{property1} {property2} {base}",TwoPropertiesMaterial:"{property1} {property2} {material} {base}"},LevelLabel:"Item {level}",OtherTag:{Herbal:"Herbal",Improvised:"Improvised",Shoddy:"Shoddy"},OtherTags:{Hint:"These are tags indicating classifications in Second Edition rules that lack explicit status/definition but are still yet heavily relied upon. Some may be automatically added when other properties are present.",Label:"Other Tags"},MaterialRunes:{Label:"Precious Material and Runes"},PriceLabel:"Price: {price}",Usage:{WornParenthetical:"Worn ({where})",WornSlot:{amulet:"Amulet",anklets:"Anklets",armbands:"Armbands",armor:"Armor",backpack:"Backpack",barding:"Barding",belt:"Belt",beltpouch:"Belt Pouch",bracelet:"Bracelet",bracers:"Bracers",circlet:"Circlet",cloak:"Cloak",clothing:"Clothing",collar:"Collar",crown:"Crown",epaulet:"Epaulet",eyepiece:"Eyepiece",footwear:"Footwear",garment:"Garment",gloves:"Gloves",headwear:"Headwear",horseshoes:"Horseshoes",mask:"Mask",necklace:"Necklace",onbelt:"On Belt",ring:"Ring",saddle:"Saddle",shoes:"Shoes",wrist:"On Wrists"}}},Plural:"Items",RefreshFromCompendium:{Label:"Refresh",SourceNotFound:'The compendium source for "{item}" (source ID: {sourceId}) was not found.',Tooltip:{Disabled:"Item cannot be refreshed: contains data stored at time of adding to actor",Enabled:"Refresh this item's data with the latest from its originating compendium."}},RemovalPrevented:"Removal of {item} is prevented by {preventer}.",Rules:{Apply:"Apply",Close:"Close",Edit:"Edit JSON",Hint:{Slug:"A stable, human-readable identifier: if set, it will remain in place even if the item is renamed.",SourceId:"The UUID of the original compendium item",UUID:"A universally unique identifier for this item"},New:"New Rule Element",RegenerateSlug:"(Re)generate Slug",Remove:"Remove Rule Element",Tab:"Rules"},Shield:{Base:{buckler:"Buckler","casters-targe":"Caster's Targe","dart-shield":"Dart Shield","fortress-shield":"Fortress Shield","gauntlet-buckler":"Gauntlet Buckler","harnessed-shield":"Harnessed Shield","heavy-rondache":"Heavy Rondache","hide-shield":"Hide Shield",klar:"Klar","meteor-shield":"Meteor Shield","razor-disc":"Razor Disc","salvo-shield":"Salvo Shield","steel-shield":"Steel Shield","swordstealer-shield":"Swordstealer Shield","tower-shield":"Tower Shield","wooden-shield":"Wooden Shield"},Rune:{Reinforcing:{Greater:"Greater Reinforcing",Label:"Reinforcing Rune",Lesser:"Lesser Reinforcing",Major:"Major Reinforcing",Minor:"Minor Reinforcing",Moderate:"Moderate Reinforcing",Supreme:"Supreme Reinforcing"}},Specific:{Hint:"Marking this shield as a specific magic shield indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Shield"}},SidebarSummary:"{type} Summary",Spell:{Area:"{size}-{unit} {shape}",Cast:"Cast",Cost:"Cost",Counteract:{Hint:"If you're counteracting an affliction, the DC is in the affliction's stat block. If it's a spell, use the caster's DC. The GM can also calculate a DC based on the target effect's level.",Label:"Counteract",criticalFailure:"You fail to counteract the target.",criticalSuccess:"Counteract the target if its counteract rank is {rank} or less.",failure:"Counteract the target if its counteract rank is less than {rank}.",success:"Counteract the target if its counteract rank is {rank} or less."},Defense:{BasicSave:"Basic",Label:"Defense"},LevelN:"Spell {level}",MeasuredTemplate:{Clear:"Clear Placed Templates",Place:"Place {area}"},Plural:"Spells",Rank:{Label:"Rank",Ordinal:"{rank} Rank",Plural:"Ranks"},Ritual:{Label:"Ritual",PrimaryCheck:"Primary Check",SecondaryChecks:"Secondary Checks",SecondaryCasters:"Secondary Casters"},Variants:{DeleteDialogText:"Are you sure you want to delete '{variantName}'?",DeleteDialogTitle:"Delete Spell Variant",LabelPlural:"Spell Variants",SelectOtherVariantLabel:"Select Other Variant",SelectVariantLabel:"Select Variant",SheetTitle:"{originalName} (Variant)"},Warning:{InvalidLevel:"Attempted to add spell {name} at {targetLevel}, but spell is {baseLevel}.",WrongSpellType:"Cannot add {spellType} spell to this casting entry."}},Weapon:{CanBeAmmo:{Label:"Usable as Ammo",Hint:"Indicate that this weapon can be loaded into another weapon as ammunition."},CriticalSpecialization:{axe:"Choose one creature adjacent to the initial target and within reach. If its AC is lower than your attack roll result for the critical hit, you deal damage to that creature equal to the result of the weapon damage die you rolled (including extra dice for its potency rune, if any). This amount isn't doubled, and no bonuses or other additional dice apply to this damage.",bomb:"Increase the radius of the bomb's splash damage (if any) to 10 feet.",bow:"If the target of the critical hit is adjacent to a surface, it gets stuck to that surface by the missile. The target is @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{Immobilized} and must spend an Interact action to attempt a @Check[type:athletics|dc:10|name:Pull the Missile Free|showDC:all] check to pull the missile free; it can't move from its space until it succeeds. The creature doesn't become stuck if it is incorporeal, is liquid (like a water elemental or some oozes), or could otherwise escape without effort",brawling:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Brawling Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn.",club:"You knock the target away from you up to 10 feet (you choose the distance). This is forced movement.",firearm:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Firearm Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix]{Stunned 1}.",flail:"The target is knocked @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} unless they success at a @Check[type:reflex|dc:resolve(@actor.attributes.classDC.value)|name:Flail Critical Specialization] save against your class DC.",hammer:"The target is knocked @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone} unless they succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Hammer Critical Specialization] save against your class DC.",polearm:"The target is moved 5 feet in a direction of your choice. This is forced movement.",shield:"You knock the target back from you 5 feet. This is forced movement.",sling:"The target must succeed at a @Check[type:fortitude|dc:resolve(@actor.attributes.classDC.value)|name:Sling Critical Specialization] save or be @UUID[Compendium.pf2e.conditionitems.Item.dfCMdR4wnpbYNTix]{Stunned 1}.",spear:"The weapon pierces the target, weakening its attacks. The target is @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} until the start of your next turn.",sword:"The target is made off-balance by your attack, becoming @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} until the start of your next turn."},Damage:{DiceNumber:"Dice Number"},FromABP:"Automatic bonus progression has adjusted this weapon's {property} to {value}.",FromMaterialAndRunes:"Precious materials and runes on this item have adjusted its {property} to {value}.",HandsLabel:"Hands",MandatoryMelee:"This weapon has a trait that can only be used with melee weapons.",MaterialAndRunes:{MaterialOption:"{type} ({grade})",Title:"Material Composition and Runes"},MeleeUsage:{Hint:"A combination weapon has a firearm form or usage and a melee weapon form or usage. Switching between the melee weapon usage and the firearm usage requires an Interact action. However, if your last action was a successful melee Strike against a foe using a combination weapon, you can make a firearm Strike with the combination weapon against that foe without fully switching to the firearm usage, firing the firearm just as you hit with the melee attack. In this case, the combination weapon returns to its melee usage after the firearm Strike.",Label:"Melee Usage"},NoRangeMelee:"None (Melee)",RangeIncrementN:{Hint:"Ranged and thrown weapons have a range increment. Attacks with these weapons work normally up to that distance. Attack rolls beyond a weapon's range increment take a -2 penalty for each additional multiple of that increment between you and the target. Attacks beyond the sixth range increment are impossible.",Label:"Range Increment {range} ft."},Reload:{LabelN:"Reload {value}",OneMinute:"1 min"},Rune:{Potency:"Weapon Potency",Striking:{Greater:"Greater Striking",Major:"Major Striking",Striking:"Striking"}},SpecificMagicWeapon:{Hint:"Marking this weapon as a specific magic weapon indicates that it does more than what its material composition and runes allow. The name, level, rarity, and price will no longer be overridden from precious material or runes at the time of marking. Those material and runes will, however, serve as a baseline for level, rarity, and price adjustments from later upgrades.",Label:"Specific Magic Weapon"},ThrownUsage:{Label:"Thrown Usage"}},WorldItemWarning:"This is a World Item and will not work if saved in a compendium"},ItemBonus0:"0",ItemBonus1:"+1 Weapon Potency",ItemBonus2:"+2 Weapon Potency",ItemBonus3:"+3 Weapon Potency",ItemBonusLabel:"Item Bonus",ItemBonusMinus2:"Shoddy (-2)",ItemBonusShortLabel:"Item",ItemDescription:"Description",ItemDescriptionHeader:"Description",ItemDetails:"Details",ItemLevel:"{type} {level}",ItemMystification:"Mystification",ItemMystified:"Mystified",ItemNamePlaceholder:"Name",ItemNewSkillVariant:"New Skill Variant",ItemNotSupportedOnActor:"Item not supported on actor",ItemRemoveRuleElement:"Remove Rule Element",ItemTitle:"Item",ItemsLabel:"Items",Keybinding:{CycleTokenStack:{Hint:"Cycle the Z indices of a mouse-hovered stack of tokens, pushing the top to the bottom.",Label:"Cycle Token Stack"},GMVision:{Hint:"Brighten dark scenes for easier viewing.",Label:"GM Vision"},TogglePartySheet:{Hint:"Open or close the sheet of the active or (if a player) assigned party.",Label:"Toggle Party Sheet"}},KitItems:"Items",KitWorldItem:"This item is not found in a Compendium and will not work in other worlds",LackCastConsumableCapability:"{actor} lacks the proficiency to use {spell} and does not have the Trick Magic Item feat.",Languages:"Languages",LanguagesAdditional:"Additional Languages",Level1:"Level 1",Level10:"Level 10",Level11:"Level 11",Level12:"Level 12",Level13:"Level 13",Level14:"Level 14",Level15:"Level 15",Level16:"Level 16",Level17:"Level 17",Level18:"Level 18",Level19:"Level 19",Level2:"Level 2",Level20:"Level 20",Level3:"Level 3",Level4:"Level 4",Level5:"Level 5",Level6:"Level 6",Level7:"Level 7",Level8:"Level 8",Level9:"Level 9",LevelLabel:"Level",LevelN:"Level {level}",LevelRange:"Levels {minLevel} - {level}",LicenseViewer:{Label:"Legal Notice",LandingPageText:"Use the tabs above to read the legal information"},ListPartsAnd:{end:"{first}, and {second}",middle:"{first}, {second}",start:"{first}, {second}",two:"{first} and {second}"},ListPartsOr:{end:"{first}, or {second}",middle:"{first}, {second}",start:"{first}, {second}",two:"{first} or {second}"},Lore:"Lore",LoreProficiencyDisclaimer:"Informational only. Will not change the skill modifier.",LoreSkillsHeader:"Lore Skills",MAPAbbreviationLabel:"MAP {penalty}",MAPAbbreviationValueLabel:"{value} (MAP {penalty})",Macro:{OptionToggle:{Notification:"{toggle} has been toggled {state}.",Off:"OFF",On:"ON"},Plural:"Macros",NoCompendiumItem:"A macro cannot be created from a compendium item that isn't an effect or condition."},MacroActionNoActionError:"This action no longer exists!",MacroActionNoActorError:"This actor no longer exists!",MagicTraditionLabel:"Magic Tradition",MagicTraditionUseSpellLabel:"Use Spell Tradition",MasterAbility:{cha:"Master Charisma",con:"Master Constitution",dex:"Master Dexterity",int:"Master Intelligence",str:"Master Strength",wis:"Master Wisdom"},MasterArmorClass:"Master Armor Class {base}",MasterLevel:"Master Level",MasterSavingThrow:{fortitude:"Master Fortitude",reflex:"Master Reflex",will:"Master Will"},MaxHitPointsBaseLabel:"Base Max HP {base}",MaxHitPointsShortLabel:"Max HP",MaxStaminaPointsShortLabel:"Max SP",Migrations:{Finished:"PF2E System Migration to version {version} completed!",OnlyGMCanUse:"Only a gamemaster can use this tool.",OutsideSchemaRange:"The specified range is outside the system's schema version range (between {minimum} and {maximum}).",Running:"Running system migration ...",Starting:"Applying PF2E System Migration to version {version}. Please be patient and do not close your game or shut down your server.",Summary:{Documents:"Documents",HelpResources:'An unexpected error was encountered while migrating some actors or items. If you would like further assistance, feel free to report an issue at the system repository or visit us on Discord for community support.',Migrated:"Migrated",Remigrate:"Remigrate",Title:"Migration Summary",Total:"Total",Troubleshoot:{Hint:"Here you can run a remigration, which will attempt to automatically fix issues with actors and items.",Title:"System Troubleshooting"}},Troubleshooting:"Troubleshooting",WorldNotReady:"Game world not ready: try again in a few seconds."},ModifierNamePlaceholder:"Name",ModifierTitle:"Modifier",ModifierType:{ability:"Attribute",circumstance:"Circumstance",item:"Item",potency:"Potency",proficiency:"Proficiency",status:"Status",untyped:"Untyped"},ModifierTypeTitle:"[Type]",ModifiersTitle:"Modifiers",MultipleAttackPenalty:"Multiple Attack Penalty",MysticStrikes:"Mystical Strikes",NPC:{Abilities:{Glossary:{AllAroundVision:"This monster can see in all directions simultaneously, and therefore can't be flanked.
",AquaticAmbush:`Requirements The monster is hiding in water and a creature that hasn't detected it is within the listed number of feet.
+
+Effect The monster moves up to its swim Speed + 10 feet toward the triggering creature, traveling on water and on land. Once the creature is in reach, the monster makes a Strike against it. The creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against this Strike.
`,AtWillSpells:"The monster can cast its at-will spells any number of times without using up spell slots.
",AttackOfOpportunity:`Trigger A creature within the monster's reach uses a manipulate action or a move action, makes a ranged attack, or leaves a square during a move action it's using.
+
+Effect The monster attempts a melee Strike against the triggering creature. If the attack is a critical hit and the trigger was a manipulate action, the monster disrupts that action. This Strike doesn't count toward the monster's multiple attack penalty, and its multiple attack penalty doesn't apply to this Strike.
`,Aura:`A monster's aura automatically affects everything within a specified emanation around that monster. The monster doesn't need to spend actions on the aura; rather, the aura's effects are applied at specific times, such as when a creature ends its turn in the aura or when creatures enter the aura.
+If an aura does nothing but deal damage, its entry lists only the radius, damage, and saving throw. Such auras deal this damage to a creature when the creature enters the aura and when a creature starts its turn in the aura. A creature can take damage from the aura only once per round.
+The GM might determine that a monster's aura doesn't affect its own allies. For example, a creature might be immune to a monster's frightful presence if they have been around each other for a long time.
`,Buck:`
+Most monsters that serve as mounts can attempt to buck off unwanted or annoying riders, but most mounts will not use this reaction against a trusted creature unless the mounts are spooked or mistreated.
+Trigger A creature @UUID[Compendium.pf2e.actionspf2e.Item.PM5jvValFkbFH3TV]{Mounts} or uses the @UUID[Compendium.pf2e.actionspf2e.Item.q9nbyIF0PEBqMtYe]{Command an Animal} action while riding the monster.
+
+Effect The triggering creature must succeed at a Reflex saving throw against the listed DC or fall off the creature and land @UUID[Compendium.pf2e.conditionitems.Item.j91X7x0XSomq8d60]{Prone}. If the save is a critical failure, the triggering creature also takes [[/roll 1d6[bludgeoning]]]{1d6 bludgeoning damage} in addition to the normal damage for the fall.
`,CatchRock:`Requirements The monster must have a free hand but can @UUID[Compendium.pf2e.actionspf2e.Item.wQYmDStjdjn0I26t]{Release} anything it's holding as part of this reaction.
+Trigger The monster is targeted with a thrown rock Strike or a rock would fall on the monster.
+
+Effect The monster gains a +4 circumstance bonus to its AC against the triggering attack or to any defense against the falling rock. If the attack misses or the monster successfully defends against the falling rock, the monster catches the rock, takes no damage, and is now holding the rock.
`,ChangeShape:"The monster changes its shape indefinitely. It can use this action again to return to its natural shape or adopt a new shape. Unless otherwise noted, a monster cannot use Change Shape to appear as a specific individual. Using Change Shape counts as creating a disguise for the @UUID[Compendium.pf2e.actionspf2e.Item.AJstokjdG6iDjVjE]{Impersonate} use of Deception. The monster's transformation automatically defeats Perception DCs to determine whether the creature is a member of the ancestry or creature type into which it transformed, and it gains a +4 status bonus to its Deception DC to prevent others from seeing through its disguise. Change Shape abilities specify what shapes the monster can adopt. The monster doesn't gain any special abilities of the new shape, only its physical form. For example, in each shape, it replaces its normal Speeds and Strikes, and might potentially change its senses or size. Any changes are listed in its stat block.
",ConstantSpells:"A constant spell affects the monster without the monster needing to cast it, and its duration is unlimited. If a constant spell gets counteracted, the monster can reactivate it by spending the normal spellcasting actions the spell requires.
",Constrict:"The monster deals the listed amount of damage to any number of creatures @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained} by it. Each of those creatures can attempt a basic Fortitude save with the listed DC.
",Coven:`This monster can form a coven with two or more other creatures who also have the coven ability. This involves performing an 8-hour ceremony with all prospective coven members. After the coven is formed, each of its members gains elite adjustments, adjusting their levels accordingly. Coven members can sense other members' locations and conditions by spending a single action, which has the concentrate trait, and can sense what another coven member is sensing as a two-action activity, which has the concentrate trait as well.
+Covens also grant spells and rituals to their members, but these can be cast only in cooperation between three coven members who are all within 30 feet of one another. A coven member can contribute to a coven spell with a single-action spellcasting activity that has a single verbal component. If two coven members have contributed these actions within the last round, a third member can cast a coven spell on her turn by spending the normal spellcasting actions. A coven can cast its coven spells an unlimited number of times but can cast only one coven spell each round. All covens grant the 8th-rank @UUID[Compendium.pf2e.spells-srd.Item.dN8QBNuTiaBHCKUe]{Baleful Polymorph} spell and all the following spells, which the coven can cast at any rank up to 5th: @UUID[Compendium.pf2e.spells-srd.Item.41TZEjhO6D1nWw2X]{Augury}, @UUID[Compendium.pf2e.spells-srd.Item.vLA0q0WOK2YPuJs6]{Charm}, @UUID[Compendium.pf2e.spells-srd.Item.HXhWYJviWalN5tQ2]{Clairaudience}, @UUID[Compendium.pf2e.spells-srd.Item.zvKWclOZ7A53DObE]{Clairvoyance}, @UUID[Compendium.pf2e.spells-srd.Item.yM3KTTSAIHhyuP14]{Dream Message}, @UUID[Compendium.pf2e.spells-srd.Item.i35dpZFI7jZcRoBo]{Illusory Disguise}, @UUID[Compendium.pf2e.spells-srd.Item.Ucf8eynbZMfUucjE]{Illusory Scene}, @UUID[Compendium.pf2e.spells-srd.Item.Ek5XI0aEdZhBgm21]{Prying Eye}, and @UUID[Compendium.pf2e.spells-srd.Item.FM3SmEW8N1FCRjqt]{Talking Corpse}. Individual creatures with the coven ability also grant additional spells to any coven they join. A coven can also cast the @UUID[Compendium.pf2e.spells-srd.Item.XkDCzMIyc0YOjw05]{Control Weather} ritual, with a DC of 23 instead of the standard DC.
+If a coven member leaving the coven or the death of a coven member brings the coven below three members, the remaining members keep their elite adjustments for 24 hours, but without enough members to contribute the necessary actions, they can't cast coven spells.
`,Darkvision:"A monster with darkvision can see perfectly well in areas of darkness and dim light, though such vision is in black and white only. Some forms of magical darkness, such as a 4th-rank @UUID[Compendium.pf2e.spells-srd.Item.4GE2ZdODgIQtg51c]{Darkness} spell, block normal darkvision. A monster with @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.4Ho2xMPEC05aSxzr]{Greater Darkvision}, however, can see through even these forms of magical darkness.
",Disease:"When a creature is exposed to a monster's disease, it attempts a Fortitude save or succumbs to the disease. The level of a disease is the level of the monster inflicting the disease. The disease follows the rules for afflictions.
",Engulf:`The monster Strides up to double its Speed and can move through the spaces of any creatures in its path. Any creature of the monster's size or smaller whose space the monster moves through can attempt a Reflex save with the listed DC to avoid being engulfed. A creature unable to act automatically critically fails this save. If a creature succeeds at its save, it can choose to be either pushed aside (out of the monster's path) or pushed in front of the monster to the end of the monster's movement. The monster can attempt to Engulf the same creature only once in a single use of Engulf. The monster can contain as many creatures as can fit in its space.
+A creature that fails its save is pulled into the monster's body. It is @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}, is @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1}, and has to hold its breath or start suffocating. The creature takes the listed amount of damage when first engulfed and at the end of each of its turns while it's engulfed. An engulfed creature can get free by @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escaping} against the listed escape DC. An engulfed creature can attack the monster engulfing it, but only with unarmed attacks or with weapons of light Bulk or less. The engulfing creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against the attack. If the monster takes piercing or slashing damage equaling or exceeding the listed Rupture value from a single attack or spell, the engulfed creature cuts itself free. A creature that gets free by either method can immediately breathe and exits the swallowing monster's space.
+If the monster dies, all creatures it has engulfed are automatically released as the monster's form loses cohesion.
`,FastHealing:"A monster with this ability regains the given number of Hit Points each round at the beginning of its turn.
",Ferocity:`Trigger The monster is reduced to 0 HP.
+
+Effect The monster avoids being knocked out and remains at 1 HP, but its @UUID[Compendium.pf2e.conditionitems.Item.Yl48xTdMh3aeQYL2]{Wounded} value increases by 1. When it is Wounded 3, it can no longer use this ability
`,FormUp:"The troop chooses one of the squares it currently occupies and redistributes its squares to any configuration in which all squares are contiguous and within 15 feet of the chosen square. The troop can't share its space with other creatures.
",FrightfulPresence:`A creature that first enters the area must attempt a Will save.
+Regardless of the result of the saving throw, the creature is temporarily immune to this monster's Frightful Presence for 1 minute.
+
+Critical Success The creature is unaffected by the presence.
+Success The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 1}.
+Failure The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 2}.
+Critical Failure The creature is @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 4}.
`,Grab:"Requirements The monster's last action was a successful Strike that lists Grab in its damage entry, or the monster has a creature @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained}
Effect If used after a Strike, the monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.PMbdMWc2QroouFGD]{Grapple} the creature using the body part it attacked with. This attempt neither applies nor counts toward the creature's multiple attack penalty.
The monster can instead use Grab and choose one creature it's grabbing or restraining with an appendage that has Grab to automatically extend that condition to the end of the monster's next turn.
",GreaterConstrict:"The monster deals the listed amount of damage to any number of creatures @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed} or @UUID[Compendium.pf2e.conditionitems.Item.VcDeM8A5oI6VqhbM]{Restrained} by it. Each of those creatures can attempt a basic Fortitude save with the listed DC. A creature that fails this save falls @UUID[Compendium.pf2e.conditionitems.Item.fBnFDH2MTzgFijKf]{Unconscious}, and a creature that succeeds is then temporarily immune to falling unconscious from Greater Constrict for 1 minute.
",GreaterDarkvision:"A creature with greater darkvision can see perfectly well in areas of darkness and dim light, though such vision is in black and white only. Some forms of magical darkness, such as a 4th-rank @UUID[Compendium.pf2e.spells-srd.Item.4GE2ZdODgIQtg51c]{Darkness} spell, block normal @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.qCCLZhnp2HhP3Ex6]{Darkvision}. A creature with greater darkvision, however, can see through even these forms of magical darkness.
",ImprovedGrab:"The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.Tkd8sH4pwFIPzqTr]{Grab} as a free action triggered by a hit with its initial attack. A monster with Improved Grab still needs to spend an action to extend the duration for creatures it already has @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}.
",ImprovedKnockdown:"The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.BCLvAx4Pz4MLa2pu]{Knockdown} as a free action triggered by a hit with its initial attack.
",ImprovedPush:"The monster can use @UUID[Compendium.pf2e.bestiary-ability-glossary-srd.Item.t6cx9FOODmeZQNYl]{Push} as a free action triggered by a hit with its initial attack.
",Knockdown:"Requirements The monster's last action was a successful Strike that lists Knockdown in its damage entry
Effect The monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.ge56Lu1xXVFYUnLP]{Trip} the creature. This attempt neither applies nor counts toward the monster's multiple attack penalty.
",Lifesense:"Lifesense allows a monster to sense the vital essence of living and undead creatures within the listed range. The sense can distinguish between the vitality energy animating living creatures and the void energy animating undead creatures, much as sight distinguishes colors.
",LightBlindness:"When first exposed to bright light, the monster is @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} until the end of its next turn. After this exposure, light doesn't blind the monster again until after it spends 1 hour in darkness. However, as long as the monster is in an area of bright light, it's @UUID[Compendium.pf2e.conditionitems.Item.TkIyaNPgTZFBCCuh]{Dazzled}.
",LowLightVision:"The monster can see in dim light as though it were bright light, so it ignores the @UUID[Compendium.pf2e.conditionitems.Item.DmAIPqOBomZ7H95W]{Concealed} condition due to dim light.
",NegativeHealing:"A creature with void healing draws health from void energy rather than vitality energy. It is damaged by vitality damage and is not healed by vitality healing effects. It does not take void damage, and it is healed by void effects that heal undead.
",Poison:"When a creature is exposed to a monster's poison, it attempts a Fortitude save to avoid becoming poisoned. The level of a poison is the level of the monster inflicting the poison. The poison follows the rules for afflictions.
",PowerAttack:`Frequency once per round
+
+Effect The monster makes a melee Strike. This counts as two attacks when calculating the monster's multiple attack penalty. If this Strike hits, the monster deals an extra die of weapon damage.
`,Push:"Requirements The monster's last action was a successful Strike that lists Push in its damage entry
Effect The monster attempts to @UUID[Compendium.pf2e.actionspf2e.Item.7blmbDrQFNfdT731]{Shove} the creature. This attempt neither applies nor counts toward the monster's multiple attack penalty. If Push lists a distance, change the distance the creature is pushed on a success to that distance.
",Regeneration:"This monster regains the listed number of Hit Points each round at the beginning of its turn. Its @UUID[Compendium.pf2e.conditionitems.Item.yZRUzMqrMmfLu0V1]{Dying} condition never increases beyond Dying 3 as long as its regeneration is active. However, if it takes damage of a type listed in the regeneration entry, its regeneration deactivates until the end of its next turn. Deactivate the regeneration before applying any damage of a listed type, since that damage might kill the monster by bringing it to Dying 4.
",Rend:`A Rend entry lists a Strike the monster has.
+Requirements The monster hit the same enemy with two consecutive Strikes of the listed type in the same round.
+
+Effect The monster automatically deals that Strike's damage again to the enemy.
`,RetributiveStrike:`Trigger An enemy damages the monster's ally, and both are within 15 feet of the monster.
+
+Effect The ally gains resistance to all damage against the triggering damage equal to 2 + the monster's level. If the foe is within reach, the monster makes a melee Strike against it.
`,Scent:`Scent involves sensing creatures or objects by smell, and is usually a vague sense. The range is listed in the ability, and it functions only if the creature or object being detected emits an aroma (for instance, incorporeal creatures usually do not exude an aroma).
+If a creature emits a heavy aroma or is upwind, the GM can double or even triple the range of scent abilities used to detect that creature, and the GM can reduce the range if a creature is downwind.
`,ShieldBlock:`Trigger The monster has its shield raised and takes damage from a physical attack.
+
+Effect The monster snaps its shield into place to deflect a blow. The shield prevents the monster from taking an amount of damage up to the shield's Hardness. The monster and the shield each take any remaining damage, possibly breaking or destroying the shield.
`,SneakAttack:"When the monster Strikes a creature that has the @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} condition with an agile or finesse melee weapon, an agile or finesse unarmed attack, or a ranged weapon attack, it also deals the listed precision damage. For a ranged attack with a thrown weapon, that weapon must also be an agile or finesse weapon.
",SwallowWhole:`The monster attempts to swallow a creature of the listed size or smaller that it has grabbed in its jaws or mouth. If a swallowed creature is of the maximum size listed, the monster can't use Swallow Whole again. If the creature is smaller than the maximum, the monster can usually swallow more creatures; the GM determines the maximum. The monster attempts an @Check[type:athletics|defense:reflex] check opposed by the grabbed creature's Reflex DC. If it succeeds, it swallows the creature. The monster's mouth or jaws no longer grab a creature it has swallowed, so the monster is free to use them to Strike or Grab once again. The monster can't attack creatures it has swallowed.
+A swallowed creature is @UUID[Compendium.pf2e.conditionitems.Item.kWc1fhmv9LBiTuei]{Grabbed}, is @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1}, and has to hold its breath or start suffocating. The swallowed creature takes the listed amount of damage when first swallowed and at the end of each of its turns while it's swallowed. If the victim @UUID[Compendium.pf2e.actionspf2e.Item.SkZAQRkLLkmBQNB9]{Escapes} this ability's grabbed condition, it exits through the monster's mouth. This frees any other creature grabbed in the monster's mouth or jaws. A swallowed creature can attack the monster that has swallowed it, but only with unarmed attacks or with weapons of light Bulk or less. The swallowing creature is @UUID[Compendium.pf2e.conditionitems.Item.AJh5ex99aV6VTggg]{Off-Guard} against the attack. If the monster takes piercing or slashing damage equaling or exceeding the listed Rupture value from a single attack or spell, the swallowed creature cuts itself free. A creature that gets free by either Escaping or cutting itself free can immediately breathe and exits the swallowing monster's space.
+If the monster dies, a swallowed creature can be freed by creatures adjacent to the corpse if they spend a combined total of 3 actions cutting the monster open with a weapon or unarmed attack that deals piercing or slashing damage.
`,SwarmMind:"This monster doesn't have a single mind (typically because it's a swarm of smaller creatures), and is immune to mental effects that target only a specific number of creatures. It is still subject to mental effects that affect all creatures in an area.
",Telepathy:"A monster with telepathy can communicate mentally with any creatures within the listed radius, as long as they share a language. This doesn't give any special access to their thoughts, and communicates no more information than normal speech would.
",Thoughtsense:"Thoughtsense allows a monster to sense all non-mindless creatures at the listed range.
",ThrowRock:"The monster picks up a rock within reach or retrieves a stowed rock and throws it, making a ranged Strike.
",Trample:"The monster Strides up to double its Speed and can move through the spaces of creatures of the listed size, Trampling each creature whose space it enters. The monster can attempt to Trample the same creature only once in a single use of Trample. The monster deals the damage of the listed Strike, but trampled creatures can attempt a basic Reflex save at the listed DC (no damage on a critical success, half damage on a success, double damage on a critical failure).
",Tremorsense:"Tremorsense allows a monster to feel the vibrations through a solid surface caused by movement. It is an imprecise sense with a limited range (listed in the ability). Tremorsense functions only if the monster is on the same surface as the subject, and only if the subject is moving along (or burrowing through) the surface.
",TroopDefenses:`Troops are composed of many individuals, and over the course of enough attacks and downed comrades, troops shrink in size. Most troops start with 16 squares (4 by 4), and their Hit Points have two listed thresholds, typically the first is at 2/3 their maximum Hit Points and the second is at 1/3 their maximum Hit Points. Once the troop drops below the first threshold, it loses 4 squares, leaving 12 squares remaining, and the first threshold becomes the troop's new maximum Hit Points. Once the troop falls below the second threshold, it loses another 4 squares, leaving 8 squares remaining, and the second threshold becomes the troop's new maximum Hit Points. In order to restore its size and maximum Hit Points, a troop needs to spend downtime to use long-term treatment on casualties or recruit new members to replace the fallen. At 0 Hit Points, the troop is reduced down to 4 squares, which is too few to sustain the troop, so it disperses entirely, with the few remaining members surrendering, fleeing, or easily dispatched, depending on their nature.
+A damaging single-target effect, such as a Strike, can't force a troop to pass through more than one threshold at once. For instance, if a troop had 60 Hit Points, with thresholds at 40 and 20, a Strike for 50 damage would leave the troop at 21 Hit Points, just above the second threshold. A damaging area effect or multi-target effect can cross multiple thresholds at once and could potentially destroy the entire troop in one shot.
+Non-damaging effects with an area or that target all creatures in a certain proximity affect a troop normally if they affect the entire area occupied by the troop. If an effect has a smaller area or numbers of targets, it typically has no effect on the troop. However, if the effect can target at least four creatures or cover at least four squares in the troop, and if it would prevent its targets from acting, cause them to flee, or otherwise make them unable to function as part of the troop for a round or more, the troop loses loses a number of Hit Points equal to the amount required to bring it to the next threshold, removing 4 squares. If an effect would both deal damage and automatically cross a threshold due to incapacitating some of the creatures in the troop, apply the damage first. If the damage wasn't enough to cross a threshold on its own, then reduce the Hit Points to cross the threshold for the incapacitating effect.
`,Wavesense:"This sense allows a monster to feel vibrations caused by movement through a liquid. It's an imprecise sense with a limited range (listed in the ability). Wavesense functions only if monster and the subject are in the same body of liquid, and only if the subject is moving through the liquid.
"}},ActionsList:{ActionName:"Name",Cost:"Cost",Traits:"Traits",Type:"Type"},AddAction:"Add Action",AddArmor:"Armor",AddConsumable:"Consumable",AddEquipment:"Equipment",AddItem:"Add Item",AddPassive:"Add Passive",AddSkill:"Add Skill",AddTrait:"Add Trait",AddTreasure:"Treasure",AddWeapon:"Weapon",Adjustment:{EliteLabel:"Elite",EliteNameFormat:"Elite {name}",NormalLabel:"Normal",WeakLabel:"Weak",WeakNameFormat:"Weak {name}"},ArmorExtraInfoLabelPlaceholder:"AC details...",AttackType:{Melee:"NPC Melee Attack",Ranged:"NPC Ranged Attack",Weapon:"Compendium Weapon"},Attacks:"Attacks",Creature:"Creature",Dead:"Dead",Edit:"Edit",EditImmunities:"Edit Immunities",EditLanguages:"Edit Languages",EditResistances:"Edit Resistances",EditSenses:"Edit Senses",EditSkills:"Edit Skills",EditSpeed:"Edit Speed",EditTraits:"Edit Traits",EditWeaknesses:"Edit Weaknesses",EffectsTab:"Effects",HPExtraInfoLabelPlaceholder:"HP details...",Inventory:{Header:{NameLabel:"Name",QuantityLabel:"Quantity",ValueLabel:"Value"}},InventoryTab:"Inventory",MainTab:"Main",NotesTab:"Notes",PassivesLabel:"Passives",PrivateNotes:"Private Notes",PublicNotes:"Description",Remove:"Remove",SavesExtraInfoLabelPlaceholder:"Bonus to all saves...",SendToChat:"Send to chat",SensesLabel:"Senses",SkillRollFlavor:"{skillName} Skill Check ({rank})",SpeedExtraInfoLabelPlaceholder:"Speed details...",SpeedLabel:"Speed",Spells:{AttackLabel:"Attack",DCLabel:"DC",PreparedLabel:"Prepared",PreparedShortLabel:"Prep."},SpellsTab:"Spells"},NPCAttackMelee:"Melee",NPCAttackRanged:"Ranged",NPCNotesLabel:"Notes/Conditions",NPCNotesTitle:"Write any notes for this NPC here.",NPCWeaponAddDamage:"Add Damage Partial",NPCWeaponAttackEffect:"Additional Attack Effects",NPCWeaponAttackLabel:"Attack Modifier",NPCWeaponDamageLabel:"Damage Formula",Nationality:"Nationality",NewLabel:"New",NewLoreSkill:"New skill",NewPlaceholders:{Action:"New Action",Ancestry:"New Ancestry",Armor:"New Armor",Background:"New Background",Backpack:"New Container",Condition:"New Condition",Consumable:"New Consumable",Equipment:"New Equipment",Feat:"New Feat",Kit:"New Kit",Lore:"New Lore",Melee:"New Attack",Skill:"New Skill",Spell:"New Spell",SpellcastingEntry:"New Spellcasting Entry",Treasure:"New Treasure",Weapon:"New Weapon"},NoAmmoLabel:"No Ammo",NoneOption:"None",OK:"OK",OpenActionBrowserTitle:"Open Action Browser",OpenInventoryBrowser:"Open Inventory Browser",OpenItemTitle:"Toggle Container Contents",OpenSpellBrowserTitle:"Open Spell Browser",OrdinalNumber:"{value}{suffix}",OrdinalSuffixes:{few:"rd",many:"th",one:"st",other:"th",two:"nd",zero:"th"},OrphanedSpellsHeader:"Orphaned Spells (move to spellcasting entry above)",OverridesTitle:"Overrides",Pathfinder:"Pathfinder",PFS:{CharacterNumber:"Character #",CurrentFaction:"Current Faction",Factions:{EA:"Envoy's Alliance",GA:"Grand Archive",HH:"Horizon Hunters",RO:"Radiant Oath",VS:"Vigilant Seal",VW:"Verdant Wheel"},LevelBump:"Level Bump",OrganizedPlayNumber:"Organized Play #",Reputation:"Reputation",School:{None:"Field-Commissioned Agent",Scrolls:"Scrolls",Spells:"Spells",Swords:"Swords"}},PenaltyLabel:{ability:"Attribute Penalty",circumstance:"Circumstance Penalty",item:"Item Penalty",proficiency:"Proficiency Penalty",status:"Status Penalty",untyped:"Untyped Penalty"},PerceptionCheck:"Perception Check",PerceptionHeader:"Perception",PerceptionLabel:"Perception",PotencyRuneLabel:"Potency Rune",PreciousMaterialAbysium:"Abysium",PreciousMaterialAbysiumDescription:"A blue-green metal with an eerie green luminescence, abysium radiates power that's inimical to life. Careless exposure to the material can lead to long-term damage to the immune system; as such, mining abysium is hazardous, as large quantities of the metal in an area cause all nearby creatures to become sick. A creature carrying an abysium object is sickened 1 for a standard-grade object of light Bulk, sickened 2 for a standard-grade object of 1 Bulk or more or a high-grade object of light Bulk, or sickened 3 for a high-grade object of 1 Bulk or more. This and all other sickening effects of abysium are poison effects. Crafters can use 1 abysium chunk to create up to 6 doses of poisonous abysium powder. Unscrupulous smiths have harnessed abysium's toxic properties to create noxious weapons and deadly substances. All objects crafted from abysium shed dim light in a 10-foot radius.",PreciousMaterialAdamantine:"Adamantine",PreciousMaterialAdamantineDescription:"Mined from rocks that fell from the heavens, adamantine is one of the hardest metals known. It has a shiny, black appearance, and it is prized for its amazing resiliency and ability to hold an incredibly sharp edge.",PreciousMaterialColdIron:"Cold Iron",PreciousMaterialColdIronDescription:"Weapons made from cold iron are deadly to demons and fey alike. Cold iron looks like normal iron but is mined from particularly pure sources and shaped with little or no heat. This process is extremely difficult, especially for high-grade cold iron items.",PreciousMaterialDawnsilver:"Dawnsilver",PreciousMaterialDawnsilverDescription:"Dawnsilver is renowned for its lightness, durability, and effectiveness against a range of creatures including devils and lycanthropes. It has the same sheen as silver but a slightly lighter hue. Dawnsilver weapons and armor are treated as if they were silver for the purpose of damaging creatures with weakness to silver. A metal item made of dawnsilver is lighter than one made of iron or steel: the item's Bulk is reduced by 1 (reduced to light Bulk if its normal Bulk is 1, with no effect on an item that normally has light Bulk). The Price of an item made of this material is based on the item's normal Bulk, not its reduced Bulk for being made of dawnsilver, but reduce the Bulk before making any further Bulk adjustments for the size of the item.",PreciousMaterialDjezet:"Djezet",PreciousMaterialDjezetDescription:'This rust red metal is liquid at room temperature, making it challenging for all but the most skilled metallurgists to craft with and earning it the name "quickiron" in some places. Djezet is also extremely reactive to magic, even in its solid, workable alloyed form. It glows when targeted by magic, and objects crafted with djezet alloys glow with scarlet striations, which lead some smiths to nickname it "tiger iron." When targeted by spells, objects crafted from djezet alloys exhibit these glowing red markings that last for 1 round or the duration of the spell, whichever is longer. A djezet mass contains enough djezet to refine into up to two djezet doses.',PreciousMaterialDragonhide:"Dragonhide",PreciousMaterialDragonhideDescription:"The hide and scales of a dragon can be used to Craft any item normally made of ordinary leather or hide. Dragonhide varies in color from blue to glittering gold, depending on the dragon it came from. Due to the scales' resiliency, it can also be used to Craft armor usually made out of metal plates (such as a breastplate, half plate, and full plate), allowing such armor to be made without metal. Dragonhide objects are immune to one damage type, depending on the type of dragon.",PreciousMaterialDuskwood:"Duskwood",PreciousMaterialDuskwoodDescription:"Duskwood is a very lightweight wood found primarily in old- growth forests in south-central Avistan; it is dark as ebony but has a slight purple tint. A duskwood item's Bulk is reduced by 1 (or to light Bulk if its normal Bulk is 1, with no effect on an item that normally has light Bulk). The Price of an item made of duskwood is based on the item's normal Bulk, not its reduced Bulk for being made of duskwood, but reduce the Bulk before making any further Bulk adjustments for the size of the item.",PreciousMaterialGradeLabel:"Precious Material Grade",PreciousMaterialGrisantianPelt:"Grisantian Pelt",PreciousMaterialGrisantianPeltDescription:"This supernaturally tough animal skin is gold and shines in sunlight. It can be used to make any item usually made of cloth, leather, or hide. This material is immune to fire, and its Hardness is doubled against piercing or slashing damage. Up to 4 Bulk of grisantian pelt can be harvested from a single creature (this is usually more than enough for 4 suits of standard grade armor or 2 suit of high-grade armor).",PreciousMaterialHighGrade:"High-Grade",PreciousMaterialInubrix:"Inubrix",PreciousMaterialInubrixDescription:"This pale, malleable metal's unusual molecular structure allows it to partially pass through iron and steel without touching them. While this property is useful for making weapons that bypass metal armor, inubrix is barely sturdier than lead. Even in an alloyed state, this skymetal is so fragile that it's difficult to use in crafting reliable shields and less than ideal for crafting armor.",PreciousMaterialLabel:"Precious Material",PreciousMaterialLowGrade:"Low-Grade",PreciousMaterialKeepStone:"Keep Stone",PreciousMaterialKeepStoneDescription:"The crowning achievement of Highhelm's millennia of metallurgical advancements and engineering is the beautiful alloy called keep stone. Despite its name, no stone is used in the production of keep stone. Through the use of a highly guarded process that smelts together adamantine and lead, Highhelm's greatest crafters were able to develop a material with an appearance that more closely resembles marble than metal. Keep stone is only slightly weaker than adamantine alone, but with the incredible ability to disrupt magic. Any spell or magical effect targeting raw keep stone must succeed at a DC 5 flat check or the effect is lost.",PreciousMaterialNoqual:"Noqual",PreciousMaterialNoqualDescription:"Light and strong, noqual also demonstrates a powerful resistance to magic. A side effect of this resistance is that making magical weapons out of noqual requires complex and expensive alchemical treatments. Kevoth-Kul, the Black Sovereign of Numeria, has developed an alloy of noqual and cold iron known as sovereign steel to help mitigate this property. The metal's crystalline appearance might suggest that it's fragile, but the pale-green material can be worked similarly to iron. Objects made of noqual have a +4 circumstance bonus on saves against magic that the item attempts and grant their bonus to saves the owner makes specifically to protect the item from magic (such as against the rusting grasp spell).",PreciousMaterialOrichalcum:"Orichalcum",PreciousMaterialOrichalcumDescription:"The most rare and valuable skymetal, orichalcum is coveted for its incredible time-related magical properties. This dull, coppery metal isn't as physically sturdy as adamantine, but orichalcum's time-bending properties protect it, granting it greater Hardness and Hit Points. If an orichalcum item takes damage but isn't destroyed, it repairs itself completely 24 hours later.",PreciousMaterialPeachwood:"Peachwood",PreciousMaterialPeachwoodDescription:"Peachwood weapons have a particularly auburn tinge to them when under direct sunlight. Peachwood is treated as duskwood for any undead creatures' resistances or weaknesses related to duskwood (allowing a peachwood weapon to bypass a jiang-shi's resistance, for example). In addition, peachwood weapons bypass a small portion of the resistances of any undead creature. Strikes with a peachwood weapon treat an undead's resistances against physical damage as 2 lower for standard-grade peachwood, and 4 lower for high-grade.",PreciousMaterialSiccatite:"Siccatite",PreciousMaterialSiccatiteDescription:"In its raw state, this silvery ore is either scalding hot or freezing cold. Metallurgists disagree over whether siccatite is two related substances or one substance that determines its temperature output via some unknown process. Whatever the reason, the extreme temperature of the material means it must be handled carefully. Hot siccatite can easily ignite flammables such as paper and dry brush, and cold siccatite left in moist areas quickly surrounds itself with a thick layer of ice. A creature that comes into physical contact with a significant amount of siccatite takes 1 energy Damage for each round of continued contact (either fire or cold damage, for hot and cold siccatite respectively).",PreciousMaterialSilver:"Silver",PreciousMaterialSilverDescription:"Silver weapons are a bane to creatures ranging from devils to werewolves. Silver items are less durable than steel items, and low-grade silver items are usually merely silver-plated.",PreciousMaterialSisterstone:"Sisterstone",PreciousMaterialSisterstoneDescription:"Sisterstone is a term used for two closely related ores infused by the spiritual runoff in the Field of Maidens, dusk sisterstone and scarlet sisterstone. They have the same physical properties except for color-dusk sisterstone is a pale orange while scarlet sisterstone is orange-red. When near an object made of the other type of sisterstone, they both begin exuding spiritual energy that repels undead.",PreciousMaterialSisterstoneDusk:"Sisterstone (Dusk)",PreciousMaterialSisterstoneScarlet:"Sisterstone (Scarlet)",PreciousMaterialSovereignSteel:"Sovereign Steel",PreciousMaterialSovereignSteelDescription:"Created by Black Sovereign Kevoth-Kul, this unique alloy of cold iron and the skymetal noqual can provide protection from magical assault. The process of cold-forging the two materials together is quite complicated and precise. Characters in search of sovereign steel weapons and armor will almost assuredly have to travel to Starfall to procure gear made from this rare alloy. While some believe it possible to craft shields of sovereign steel as well, in one of his fits, Kevoth-Kul yelled that he had no use for them and banned anyone from making such a thing. So far, his smiths have been too afraid to confirm whether or not it was a joke. All sovereign steel items (including weapon and armor below) have a +4 circumstance bonus on saves against magic that the item makes, and grant their bonus to saves the owner makes specifically to protect the item from magic (such as against the rusting grasp spell).",PreciousMaterialStandardGrade:"Standard-Grade",PreciousMaterialWarpglass:"Warpglass",PreciousMaterialWarpglassDescription:"This bizarre substance is fashioned from the raw, chaotic quintessence of the Maelstrom. It can be fashioned into weapons and items, but is too unstable to make into useful armor or shields. Raw warpglass is an opalescent glassy material with surprising strength. When worked, it changes its appearance-though not its properties-to appear as random striations of other metals and types of stone.",PreparationTypeInnate:"Innate",PreparationTypeItems:"Items Only",PreparationTypePrepared:"Prepared",PreparationTypeSpontaneous:"Spontaneous",Prerequisite1:"Prerequisite 1",Prerequisite2:"Prerequisite 2",Prerequisite3:"Prerequisite 3",Prerequisite4:"Prerequisite 4",Prerequisite5:"Prerequisite 5",PriceLabel:"Price",ProficiencyLabel:"Proficiency",ProficiencyLevel0:"Untrained",ProficiencyLevel1:"Trained",ProficiencyLevel2:"Expert",ProficiencyLevel3:"Master",ProficiencyLevel4:"Legendary",ProficiencyRankLabel:"Prof",ProgressBar:{LoadingComplete:"Loading complete",LoadingPack:"Loading {pack}"},PropertyRuneLabel1:"Property Rune (1st)",PropertyRuneLabel2:"Property Rune (2nd)",PropertyRuneLabel3:"Property Rune (3rd)",PropertyRuneLabel4:"Property Rune (4th)",Publication:{Authors:"Author(s)",Label:"Publication",License:{Label:"License",OGL:"OGL",ORC:"ORC"},Remaster:"Remaster?",Title:"Title"},QuantityLabel:"Quantity",QuantityShortLabel:"Qty.",RangePenalty:"Range Penalty",Rarity:"Rarity",Reach:"Reach (feet)",RecallKnowledge:{Breakdown:"Attempts",BreakdownTitle:"Identify Creature Attempts",FifthAttempt:"5th DC",FirstAttempt:"1st DC",FourthAttempt:"4th DC",Help:"You can attempt repeated Recall Knowledge actions to recall more information about a creature. These checks increase in difficulty as shown in the chart below. However, if you fail, or if no DC is listed, you can not attempt further Recall Knowledge checks against this creature.",Label:"Recall Knowledge",LoreEasy:"Applicable Lore (Easy)",LoreVeryEasy:"Applicable Lore (Very Easy)",SecondAttempt:"2nd DC",SixthAttempt:"6th DC",Skill:"Skill",ThirdAttempt:"3rd DC"},Recovery:{critFailure:"Increase your dying value by 2.",critSuccess:"Reduce your dying value by 2.",failure:"Increase your dying value by 1.",rollingDescription:"DC {dc} (Dying {dying})",success:"Reduce your dying value by 1."},RemoveCoinsByValueLabel:"Remove value, not specific type",RemoveCoinsTitle:"Remove Coins",RemoveCombatProficiency:{Message:"Remove {proficiency} proficiency?",Title:"Remove Combat Proficiency"},RemoveModifierTitle:"Remove Modifier",RemoveSpellcastingEntryTitle:"Remove Spellcasting Entry",RepairItemTitle:"Attempt to Repair Item",Repost:"Post prompt to chat",RerollMenu:{ErrorCantDelete:"You are unable to delete the original roll.",ErrorNoActor:"No actor is associated to the roll",HeroPoint:"Reroll using a Hero Point",KeepHigher:"Reroll and keep the higher result",KeepNew:"Reroll and keep the new result",KeepLower:"Reroll and keep the lower result",MessageHeroPoint:"Rerolled using a Hero Point",MessageKeep:{higher:"Rerolled and kept the higher result",new:"Rerolled and kept the new result",lower:"Rerolled and kept the lower result"},WarnNoHeroPoint:"{name} has no Hero Points"},ResistancesLabel:"Resistances",ResolvePointsShortLabel:"Resolve",RestoreSpellTitle:"Restore Spell",RevertDamage:{ButtonTooltip:"Undo",DamageMessage:"Damage applied to {actor} was reverted.",HealingMessage:"Healing applied to {actor} was reverted."},Roll:{Add:"Add",CriticalHit:"Critical Hit",Dialog:{Check:{Substitution:"Substitution",Utilize:"Utilize?"},Damage:{BaseDamage:"Base Damage",Dice:"{dice} Dice",DiceHeader:"Dice",DieSizeUpgrade:"Upgrade Die Size",ExtraDice:"Extra {dice}",Label:"Label",None:"None",Override:"Override {value}",Splash:"{damageType} Splash",TitleCritical:"Critical Damage Roll",Title:"Damage Roll"},ShowDefault:"Always Show Dialog",ShowDefaultHint:"If enabled, this dialog is always shown unless you hold Shift. If disabled, you can open this dialog by holding Shift."},Fortune:"Fortune",FortuneTitle:"{title} Fortune",KeepHigher:"Keep Higher",KeepLower:"Keep Lower",Misfortune:"Misfortune",MisfortuneTitle:"{title} Misfortune",Modifier:"Modifier",None:"None",Normal:"Normal",Roll:"Roll",Type:"Type",UntypedPenalty:"Untyped (penalty)"},RollBonusPlaceholder:"e.g. +3 or +1d4",RollModeLabel:"Roll Mode",RollTable:{Plural:"Rollable Tables"},SETTINGS:{Automation:{ActorsDeadAtZero:{Both:"Yes",Hint:"Upon reaching zero hit points, actors are marked as dead. For PCs, this only applies to damage that would immediately kill them.",NPCsOnly:"NPCS only",Name:"Actors Dead at 0 HP",Neither:"No"},Encumbrance:{Hint:"Automatically apply the Encumbered condition to creatures carrying more than their respective limits.",Name:"Encumbrance"},EffectExpiration:{Hint:"Effects automatically disable attached rule elements when the duration expires.",Name:"Effects Auto-Expire"},FlankingDetection:{Hint:"Flanking arrangements and abilities that predicate on it are managed by the system.",Name:"Flanking Detection"},Hint:"Decide how much and what kinds of automation should apply to your game world.",IWR:{Hint:"When applying damage to an actor, adjust its value according to the actor's immunities, weaknesses, and resistances.",Name:"Immunities, Weaknesses, & Resistances"},Label:"Manage Automation",LootableNPCs:{Hint:"Upon their demise, NPCs become lootable by players.",Name:"Lootable NPCs"},Name:"Automation",RemoveExpiredEffects:{Hint:"Expired effects are automatically removed from actors (requires a GM to be logged in).",Name:"Remove Expired Effects"},RulesBasedVision:{Hint:"Apply vision mechanics that are a best-effort attempt to capture Pathfinder Second Edition rules. Enabling this setting will remove the ability to configure Unrestricted Global Vision as well as Token Sight radii.",ManagedBy:"Managed by rules-based vision.",Name:"Rules-Based Vision",ViewWorldSetting:"View World Setting"}},CampaignFeats:{Hint:"Adds a section to all player sheets for campaign specific feats.",Name:"Campaign Feats"},CampaignType:{Hint:"Extended campaign rule type for parties",Name:"Campaign Type",Choices:{none:"None",kingmaker:"Kingmaker"}},CompendiumBrowserPacks:{Hint:"Settings to exclude packs from loading",Name:"Compendium Browser Packs"},CompendiumBrowserSources:{DeleteAllInfo:"All compendium documents will become browseable, including those with empty sources.",DeleteAllQuestion:"Are you sure you want to reset all settings for included sources?",DeleteAllTitle:"Reset Settings",Hint:"Settings to display only entries with specified sources in the compendium browser.",IgnoreAsGM:"Let GMs ignore filtering and see all entries.",Name:"Included Sources",ShowEmptySources:"Do not filter entries with empty sources.",ShowUnknownSources:"Do not filter entries with unknown sources.",SourcesListHeader:"Specified Sources"},CritRule:{Choices:{Doubledamage:"Double the damage",Doubledice:"Double the number of dice"},Hint:"Use a different rule for doubling damage on a critical hit",Name:"Critical Damage Rule"},DeathIcon:{Hint:"Set the overlay icon used to mark dead actors.",Name:"Death Icon"},EnabledDisabled:{Enabled:"Enabled",Default:"World Default ({worldDefault})",Disabled:"Disabled"},EnabledRulesUI:{Hint:"When enabled, players are able to see and utilize the rule elements panel on item sheets.",Name:"Player Rule Elements Access"},Homebrew:{BaseWeapons:{Hint:"The bottom level of Pathfinder 2e weapon taxonomy (e.g, Heavy Crossbow, Longsword)",Name:"Base Weapons"},ConfirmDelete:{Message:"Delete Homebrew element {element}?",Title:"Delete Homebrew Element?"},CreatureTraits:{Hint:"Traits that can be applied to any creature and some item types (e.g., Dragon, Gnome)",Name:"Creature Traits"},DamageTypes:{Add:"Add Damage Type",Hint:"Additional damage types for the system to recognize",Icon:"Icon (Font Awesome)",Name:"Custom Damage Types",Label:"Label"},EquipmentTraits:{Hint:"Traits applicable to equipment other than weapons",Name:"Equipment Traits"},FeatTraits:{Hint:"Traits that can be applied to feats (e.g., Lineage, Monk) and actions",Name:"Feat Traits"},Hint:"Add custom traits, languages, and other elements of a homebrew world.",Instructions:"These settings allow GMs to add traits, languages, and other elements to a homebrew world. To add such elements, simply type the desired terms in the appropriate fields, separated by commas or tab keystrokes. They will then appear in the appropriate places on actor and item sheets. To update a term, click it to make the desired changes.",Label:"Manage Homebrew Elements",Languages:{Hint:"Languages for characters to know or learn (e.g., Draconic, Gnomish)",Name:"Languages"},Name:"Homebrew Elements",ReservedTerm:'"{term}" is a reserved term.',SpellTraits:{Hint:"Traits that can be applied to any spell (e.g., Cursebound, Healing)",Name:"Spell Traits"},Tabs:{Damage:"Damage Types",Traits:"Traits and Categories"},WeaponCategories:{Hint:"The top level of Pathfinder 2e weapon taxonomy (e.g., Simple, Martial)",Name:"Weapon Categories"},WeaponGroups:{Hint:"The mid level of Pathfinder 2e weapon taxonomy (e.g, Crossbow, Sword)",Name:"Weapon Groups"},WeaponTraits:{Hint:"Traits applicable to weapons and NPC attacks",Name:"Weapon Traits"}},IdentifyMagicNotMatchingTraditionModifier:{Choices:{0:"0",2:"+2",5:"+5",10:"+10"},Hint:"Modifier to add to Identify Magic Skill DCs if the skill does not match the item's magic tradition",Name:"Identify Magic Skill Modifier"},Metagame:{Hint:"Limit what kinds of metagame information your players have access to.",Label:"Limit Metagame Information",Name:"Metagame Information",PartyVision:{Hint:"If enabled, all players will mutually share token vision, regardless of permissions or token selection.",Name:"Shared Party Vision"},SecretCondition:{Hint:"If enabled, only the GM will see the condition update and reminder messages that are generated for tokens not owned by a player.",Name:"Hide Condition Update Message"},SecretDamage:{Hint:"If enabled, only the GM will see the damage/healing taken messages that are generated by the damage chat cards for tokens not owned by a player.",Name:"Hide Damage-Taken Message"},ShowDC:{Hint:"If enabled, players will see DCs of checks made against NPCs and other non-player-owned sources.",Name:"Show DCs on Attacks and Saves"},ShowResults:{Hint:"If enabled, players will see the degree of success of checks made against NPCs and other non-player-owned sources.",Name:"Show Results on Attacks and Saves"},ShowPartyStats:{Hint:"If enabled, players will see stats for their fellow party members in the party actor sheet",Name:"Show Party-Member Stats"},TokenSetsNameVisibility:{Hint:"If enabled, then for any NPC token whose nameplate isn't visible to players, its name will also be hidden from them in the encounter tracker and chat messages.",Name:"Tokens Determine NPC Name Visibility"}},NathMode:{Hint:"Use better default token icons",Name:"Nath Mode"},ResetChanges:"Reset Changes",Settings:"Settings",Sidebar:{Changelog:"Changelog",Discord:"Discord",Remaster:"Remaster Changes",Wiki:"Wiki"},TOTMToggles:{Hint:"Include additional toggles on actor sheets to facilitate Theater of the Mind play. Such toggles will allow for enabling certain abilities without targeting in Foundry.",Name:"Theater of the Mind Toggles"},Tokens:{Autoscale:{Hint:"If enabled, tokens will be scaled to 1.0 or (if belonging to a small creature) 0.8",Name:"Scale Tokens According to Size"}},User:{EffectPanel:{Hint:"Show the Effects Panel when a token is selected.",Name:"Show Effects Panel"},MonochromeDarkvision:{Hint:"If rules-based vision is enabled, depict areas of darkness in monochrome for tokens with darkvision. Note that some creatures, such as fetchlings, possess full-color darkvision and will not be affected.",Name:"Monochrome Darkvision"}},Variant:{GradualBoosts:{Hint:"Spread out attribute boosts across multiple levels. Players gain a boost every level except 6, 11, and 16.",Name:"Gradual Attribute Boosts"},AutomaticBonus:{Choices:{ABPFundamentalPotency:"ABP: Allow Property Runes",ABPRulesAsWritten:"ABP: Disallow Property Runes",noABP:"Do not use ABP"},Hint:"Enable the Automatic Bonus Progression variant rule. Skill potency must currently be managed manually.",Name:"Automatic Bonus Progression"},FreeArchetype:{Hint:"Grant additional feat slots for the free archetype variant from Gamemastery Guide pg 194",Name:"Free Archetype"},Hint:"Enable and configure variant rules like Proficiency Without Level or the Stamina system.",Label:"Toggle Variant Rules",Name:"Variant Rules",Proficiency:{Hint:"Play with the proficiency without level variant from Gamemastery Guide pg 198.",ModifiersHint:"Set the modifier value for each proficiency rank.",Name:"Proficiency without Level"},Stamina:{Hint:"Play with the stamina variant from Gamemastery Guide pg 200.",Name:"Stamina"},Title:"Variant Rules"},WorldClock:{DateTheme:{AD:"Earth (Gregorian Calendar)",AR:"Golarion (Absalom Reckoning)",CE:"Unthemed (Gregorian Calendar)",Hint:"Set the theme of the World Clock application.",IC:"Golarion (Imperial Calendar)",Name:"Date Theme"},Hint:"Configure the appearance of the World Clock application.",Label:"Configure World Clock",Name:"World Clock",PlayersCanView:{Hint:"Set whether players can view the World Clock.",Name:"Player Access"},ResetWorldTime:{Button:"Reset",Confirm:{Question:"Are you sure you want to reset this world's elapsed time?",Warning1:"Time-dependent game effects may be impacted.",Warning2:"This action cannot be undone."},Hint:"Reset this world's time elapsed time to zero.",Name:"Reset World Date/Time"},ShowClockButton:{Hint:"Set whether to show the clock button at all (requires refresh).",Name:"Show Clock Button"},SyncDarkness:{Hint:"Set whether any scene's Darkness Level will reflect the time of day.",Name:"Synchronize Darkness (World Default)"},SyncDarknessScene:{Hint:"Set whether this scene's Darkness Level will reflect the time of day.",ManagedBy:"Synchronized with world time.",Name:"Synchronize Darkness (Current Scene)"},TimeConvention:{Hint:"Display either a 24-hour or 12-hour clock.",Name:"Time Convention",Twelve:"12-Hour",TwentyFour:"24-Hour"}},WorldSchemaVersion:{Hint:"Records the schema version for documents in the PF2e system (don't modify this unless you know what you are doing).",Name:"World Schema Version"},critFumbleCardButtons:{hint:"Show critical hit and fumble card draw buttons on attack rolls.",name:"Critical Hit & Fumble Card Buttons"},critFumbleCards:{hint:"Automatically draw a critical hit or fumble card on appropriate rolls.",name:"Critical Hit & Fumble Cards"},statusEffectShowCombatMessage:{hint:"Each turn of an encounter, send a chat message containing the conditions of the turn's participant.",name:"Show Conditions during Encounters"},statusEffectType:{blackWhite:"Black & white",default:"Full color",hint:"Determines which icon set is used for condition token effects.",legacy:"Legacy",name:"Condition Icon Set"}},SaveDCLabel:"Save DC {dc} {type}",SaveDCLabelBasic:"Save DC {dc} basic {type}",SavesFortitude:"Fortitude",SavesFortitudeShort:"Fort",SavesHeader:"Saves",SavesReflex:"Reflex",SavesReflexShort:"Ref",SavesWill:"Will",SavesWillShort:"Will",SavingThrow:"Saving Throw",SavingThrowWithName:"{saveName} Saving Throw",Scene:{HearingRange:{Caveat:"*For performance reasons, the radius is a real measurement rather than a grid-based one.",Hint:'Limit the range* creatures can hear in this scene as a representation of "an environment that distorts the sense, such as a noisy room" (CRB pg. 464). Requires rules-based vision to be enabled.',Name:"Hearing Range (ft.)",Unlimited:"Unlimited"}},ScoreTitle:"Score",SelectLabel:"Select",SellAllTreasureQuestion:"Convert all treasure items into coins",SellAllTreasureTitle:"Sell All Treasure",SellItemConfirmHeader:"Sell Confirmation",SellItemQuestion:"Are you sure you want to sell {item}?",Senses:"Senses",SettingsQuickChecksLabel:"Preview D20 Rolls",SettingsQuickChecksNotes:"If disabled, dialogs to preview D20 rolls will appear only when a roll button is shift-clicked.",SettingsQuickDamageLabel:"Preview Damage Rolls",SettingsQuickDamageNotes:"If disabled, dialogs to preview Damage rolls will appear only when a roll button is shift-clicked.",SheetLabel:"{type} Sheet",ShieldLabel:"Shield",SidebarAppearanceLabel:"Appearance",Size:"Size",SizeLabel:"Size",SkillAcr:"Acrobatics",SkillAcrobatics:"Acrobatics",SkillArc:"Arcana",SkillArcana:"Arcana",SkillAth:"Athletics",SkillAthletics:"Athletics",SkillCheckWithName:"Skill Check: {skillName}",SkillCra:"Crafting",SkillCrafting:"Crafting",SkillDec:"Deception",SkillDeception:"Deception",SkillDip:"Diplomacy",SkillDiplomacy:"Diplomacy",SkillFeatLevels:"Skill Feat Levels",SkillIncreaseLevels:"Skill Increase Levels",SkillIntimidation:"Intimidation",SkillItm:"Intimidation",SkillLabel:"Skill",SkillLore:"Lore",SkillMed:"Medicine",SkillMedicine:"Medicine",SkillNat:"Nature",SkillNature:"Nature",SkillOcc:"Occultism",SkillOccultism:"Occultism",SkillPerformance:"Performance",SkillPotencyHeader:"Skill Potencies",SkillPrf:"Performance",SkillRel:"Religion",SkillReligion:"Religion",SkillSoc:"Society",SkillSociety:"Society",SkillSte:"Stealth",SkillStealth:"Stealth",SkillSur:"Survival",SkillSurvival:"Survival",SkillThi:"Thievery",SkillThievery:"Thievery",SkillsLabel:"Skills",Slug:"Slug",SpecialLabel:"Special",SpecialSensesLabel:"Special Senses",Speed:"Speed",SpeedBaseLabel:"Base {type} Speed",SpeedFeet:"Speed (feet)",SpeedLabel:"{type} Speed",SpeedTypes:"Speed Types",SpeedTypesBurrow:"Burrow",SpeedTypesClimb:"Climb",SpeedTypesFly:"Fly",SpeedTypesLand:"Land",SpeedTypesSwim:"Swim",SpellAbilityModLabel:"+ Mod",SpellArea:"Area: {area}",SpellAttackLabel:"Spell Attack",SpellAttackWithTradition:"{tradition} Spell Attack",SpellBrowserSearchHint:"You can search for name or custom attributes. Possible searchable attributes are:
source, spellType, level, materials, target, range, time, duration, damage, damageType, save, concentration, ritual, ability and classes.
Example: 'fire, damage:d6' to show all spells that have fire in their name and a d6 in the damage",SpellCastingFormat:"{traditionSpells} {preparationType} Spells",SpellCollectionAdd:"Add to Spell Collection",SpellCollectionRemove:"Remove from Spell Collection",SpellDurationLabel:"Duration",SpellFlexibleAvailable:"Flexible: {value} / {max}",SpellFlexibleLabel:"Flexible",SpellFocusLabel:"Focus",SpellLevelBase:"Base: {level}",SpellLevelHeightened:"Heightened: +{heightened}",SpellLevelLabel:"Spell Rank",SpellPreparedLabel:"Prepared",SpellRangeLabel:"Range",SpellRequirementsLabel:"Requirements",SpellScalingInterval:{Add:"Add Heightening (Interval)",Header:"Scaling (Interval)",Label:"Interval",Selection:"Heightened (+{interval})"},SpellScalingLabel:"Scaling",SpellScalingOverlay:{Add:"Add Heightening (Fixed)",Selection:"Heightened ({level})"},SpellSlotEmpty:"Empty Slot (drag spell here)",SpellSlotExpendedError:"Cannot cast {name}: spell is already expended",SpellSlotNotEnoughError:"Cannot cast {name} at the {level}: not enough spell slots",SpellTargetLabel:"Targets",SpellTraditionsLabel:"Traditions",SpellUnlimitedLabel:"Unlimited",SpellUsesLabel:"Uses",SpellcastingSettings:{AutoHeightenDefault:"Default (Use Actor Level)",AutoHeightenLabel:"Auto Heighten Rank",Title:"Spellcasting Settings"},SpellcastingTypeLabel:"Spellcasting Type",SpellsActionHeader:"Action",StackGroupArrows:"Arrows",StackGroupBlowgunDarts:"Blowgun Darts",StackGroupBolts:"Bolts",StackGroupCoins:"Coins",StackGroupGems:"Gems",StackGroupLabel:"Stack Group",StackGroupRounds10:"Rounds (10)",StackGroupRounds5:"Rounds (5)",StackGroupSlingBullets:"Sling Bullets",StackGroupSprayPellets:"Spray Pellets",StackGroupWoodenTaws:"Wooden Taws",StaminaPointsHeader:"Stamina Points",StaminaPointsShortLabel:"Stamina",StatusBonusShortLabel:"Status",StatusBonusTitle:"Status Bonus",StatusEffects:"{name}'s conditions",StealthLabel:"Stealth",Strike:{Combined:{Description:"You attack with a weapon you're wielding, targeting one creature within your reach (for a melee attack) or within range (for a ranged attack). Roll the attack roll for the weapon or unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Default:{CriticalSuccess:"As success, but you deal double damage.",Description:"You attack with a weapon you're wielding or with an unarmed attack, targeting one creature within your reach (for a melee attack) or within range (for a ranged attack). Roll the attack roll for the weapon or unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon or unarmed attack, including any modifiers, bonuses, and penalties you have to damage."},Fist:{Label:"Fist"},Melee:{Description:"You attack with a weapon you're wielding, targeting one creature within your reach. Roll the attack roll for the weapon you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Ranged:{Description:"You attack with a weapon you're wielding, targeting one creature within range. Roll the attack roll for the weapon you are using, and compare the result to the target creature's AC to determine the effect.",NoAmmo:"No ammunition is assigned to {weapon}. Check the Actions tab of {actor}'s sheet.",Success:"You deal damage according to the weapon, including any modifiers, bonuses, and penalties you have to damage."},Unarmed:{Description:"You attack with an unarmed attack, targeting one creature within your reach. Roll the attack roll for the unarmed attack you are using, and compare the result to the target creature's AC to determine the effect.",Success:"You deal damage according to the unarmed attack, including any modifiers, bonuses, and penalties you have to damage."}},StrikesLabel:"Strikes",StrikingRuneLabel:"Striking Rune",Success:"Success",TabActionsDowntimeLabel:"Downtime",TabActionsEncounterLabel:"Encounter",TabActionsExplorationLabel:"Exploration",TabActionsLabel:"Actions",TabCharacterLabel:"Character",TabCraftingLabel:"Crafting",TabDescriptionLabel:"Description",TabDetailsLabel:"Details",TabInventoryLabel:"Inventory",TabManageTabsLabel:"Manage Tabs",TabPathfinderSociety:"Pathfinder Society",TabSkillsLabel:"Proficiencies",TabSpellbookLabel:"Spellcasting",TempHitPointsShortLabel:"Temp HP",TemplateLabel:"{size}-{unit} {shape}",TemporaryItemToolTip:"This item is temporary and will expire after a duration or during daily preparations. It has no value and cannot be sold.",Time:{Duration:"Duration",Unit:{Days:"Days",Hours:"Hours",Minutes:"Minutes",Rounds:"Rounds",Seconds:"Seconds",Unlimited:"Unlimited",UntilEncounterEnds:"Until encounter ends",Weeks:"Weeks"}},ToggleEffectUnidentified:"Toggle Whether Effect Is Unidentified",ToggleSignatureSpellTitle:"Toggle Signature Spell",ToggleSlotlessSpellLevelsTitle:"Toggle visibility of spell ranks without slots",ToggleSpellVisibilityTitle:"Spell Preparation",ToggleUnreadyStrikes:"Toggle unequipped weapons",ToggleWithName:"Toggle: {property}",TogglesLabel:"Toggles",Token:{Appearance:"Appearance",Flanking:"Flanking",SecretDisposition:{Label:"Secret Disposition",Hint:'Activate the "secret" disposition, which displays a purple border for owners and no border or cursor change for all others.'},Size:{Dimensions:"Dimensions",Label:"Size",LinkToActorSize:{Link:"Link to Actor Size",Unlink:"Unlink from Actor Size"}}},TotalCoinage:"Total Coinage",TotalTreasure:"Total Treasure",TotalWealth:"Total Wealth",TrainedSkillsLabel:"Trained Skills",TraitAberration:"Aberration",TraitAcid:"Acid",TraitAdditive0:"Additive 0",TraitAdditive1:"Additive 1",TraitAdditive2:"Additive 2",TraitAdditive3:"Additive 3",TraitAdjusted:"Adjusted",TraitAdjustment:"Adjustment",TraitAeon:"Aeon",TraitAesir:"Aesir",TraitAffixedToAMetalWeapon:"Affixed to a Metal Weapon",TraitAffixedToARangedWeapon:"Affixed to a Ranged Weapon",TraitAffixedToAShield:"Affixed to a Shield",TraitAffixedToAShieldOrWeapon:"Affixed to a Shield or Weapon",TraitAffixedToATwoHandedFirearmOrCrossbow:"Affixed to a Two-Handed Firearm or Crossbow",TraitAffixedToArmor:"Affixed to Armor",TraitAffixedToArmorOrAWeapon:"Affixed to Armor or a Weapon",TraitAffixedToArmorOrTravelersClothing:"Affixed to Armor or Travelers Clothing",TraitAffixedToCreature:"Affixed to a Creature",TraitAffixedToCrossbowOrFirearm:"Affixed to Crossbow or Firearm",TraitAffixedToFirearm:"Affixed to Firearm",TraitAffixedToFirearmWithAReloadOf1:"Affixed to a Firearm With a Reload of 1",TraitAffixedToFirearmWithTheKickbackTrait:"Affixed to a Firearm With the Kickback Trait",TraitAffixedToGround:"Affixed to the Ground",TraitAffixedToGroundIn10FtRadius:"Affixed to the Ground in Four Spaces Along a Circle with a 10-foot Radius",TraitAffixedToGroundIn20FtRadius:"Affixed to the Ground in Four Spaces Along a Circle with a 20-foot Radius",TraitAffixedToHarness:"Affixed to Harness",TraitAffixedToHeadgear:"Affixed to Headgear",TraitAffixedToInnovation:"Affixed to an Innovation",TraitAffixedToInstrument:"Affixed to Instrument",TraitAffixedToLoadBearingWallOrPillar:"Affixed to a Load-Bearing Wall or Pillar",TraitAffixedToMagicalStaff:"Affixed to a Magical Staff",TraitAffixedToMediumHeavyArmor:"Affixed to Medium or Heavy Armor",TraitAffixedToMediumHeavyMetalArmor:"Affixed to Medium or Heavy Metal Armor",TraitAffixedToMeleeWeapon:"Affixed to a Melee Weapon",TraitAffixedToMetalWeapon:"Affixed to a Metal Weapon",TraitAffixedToObjectOrStructure:"Affixed to an Object or Structure",TraitAffixedToStructureObjectOrCreature:"Affixed to Structure, Object, or Creature",TraitAffixedToThrownWeapon:"Affixed to a Thrown Weapon",TraitAffixedToUnarmoredItem:"Affixed to Unarmored Defense Item",TraitAffixedToWeapon:"Affixed to a Weapon",TraitAftermath:"Aftermath",TraitAgathion:"Agathion",TraitAgile:"Agile",TraitAir:"Air",TraitAiuvarin:"Aiuvarin",TraitAlchemical:"Alchemical",TraitAlchemist:"Alchemist",TraitAmp:"Amp",TraitAmphibious:"Amphibious",TraitAnadi:"Anadi",TraitAndroid:"Android",TraitAngel:"Angel",TraitAnimal:"Animal",TraitAnugobu:"Anugobu",TraitApex:"Apex",TraitAphorite:"Aphorite",TraitAppliedToANoninjectionMeleePiercingWeapon:"Applied to a non-injection melee weapon that deals piercing damage",TraitAppliedToAWindPoweredVehicle:"Applied to a wind-powered vehicle",TraitAppliedToAWeapon:"Applied to a weapon",TraitAppliedToAnyItemOfLightOrNegligibleBulk:"Applied to any item of light or negligible Bulk",TraitAppliedToAnyVisibleArticleOfClothing:"Applied to any visible article of clothing",TraitAppliedToArmor:"Applied to armor",TraitAppliedToArmorOrUnarmored:"Applied to armor or unarmored defense clothing",TraitAppliedToBasketBagOrContainer:"Applied to a Basket, Bag, or Other Container",TraitAppliedToBeltCapeCloakOrScarf:"Applied to belt, cape, cloak, or scarf",TraitAppliedToBootsCapeCloakOrUmbrella:"Applied to boots, cape, cloak, or umbrella",TraitAppliedToBucklerShield:"Applied to a buckler or a shield",TraitAppliedToDuelingCapeOrShield:"Applied to dueling cape or shield",TraitAppliedToFootwear:"Applied to Footwear",TraitAppliedToMediumHeavyArmor:"Applied to Medium or Heavy Armor",TraitAppliedToShield:"Applied to shield",TraitAquadynamic:"Aquadynamic",TraitAquatic:"Aquatic",TraitArcane:"Arcane",TraitArchetype:"Archetype",TraitArchon:"Archon",TraitArdande:"Ardande",TraitAreaDamage:"Area Damage",TraitArtifact:"Artifact",TraitAstral:"Astral",TraitAsura:"Asura",TraitAttached:"Attached",TraitAttachedToAThrownWeapon:"Attached to a Thrown Weapon",TraitAttachedToCrossbowOrFirearm:"Attached to Crossbow or Firearm",TraitAttachedToCrossbowOrFirearmFiringMechanism:"Attached to Crossbow or Firearm (Firing Mechanism)",TraitAttachedToCrossbowOrFirearmScope:"Attached to Crossbow or Firearm (Scope)",TraitAttachedToFirearm:"Attached To Firearm",TraitAttachedToFirearmFiringMechanism:"Attached To Firearm (Firing Mechanism)",TraitAttachedToFirearmScope:"Attached To Firearm (Scope)",TraitAttachedToShield:"Attached to Shield",TraitAttachedToShipsBow:"Attached to a Ship's Bow",TraitAttack:"Attack",TraitAuditory:"Auditory",TraitAura:"Aura",TraitAutomaton:"Automaton",TraitAzarketi:"Azarketi",TraitAzata:"Azata",TraitBackstabber:"Backstabber",TraitBackswing:"Backswing",TraitBarbarian:"Barbarian",TraitBard:"Bard",TraitBarding:"Barding",TraitBeast:"Beast",TraitBeastkin:"Beastkin",TraitBleed:"Bleed",TraitBludgeoning:"Bludgeoning",TraitBoggard:"Boggard",TraitBomb:"Bomb",TraitBonded:"Bonded",TraitBottledBreath:"Bottled Breath",TraitBrace:"Brace",TraitBrutal:"Brutal",TraitBulwark:"Bulwark",TraitCaligni:"Caligni",TraitCantrip:"Cantrip",TraitCapacity:"Capacity",TraitCapacity2:"Capacity 2",TraitCapacity3:"Capacity 3",TraitCapacity4:"Capacity 4",TraitCapacity5:"Capacity 5",TraitCarried:"Carried",TraitCatalyst:"Catalyst",TraitCatfolk:"Catfolk",TraitCelestial:"Celestial",TraitChampion:"Champion",TraitChangeling:"Changeling",TraitCharauKa:"Charau-ka",TraitCircus:"Circus",TraitCleric:"Cleric",TraitClimbing:"Climbing",TraitClockwork:"Clockwork",TraitCobbled:"Cobbled",TraitCoda:"Coda",TraitCold:"Cold",TraitColdiron:"Cold Iron",TraitCombination:"Combination",TraitComfort:"Comfort",TraitCommon:"Common",TraitCompanion:"Companion",TraitComplex:"Complex",TraitComposite:"Composite",TraitComposition:"Composition",TraitConcealable:"Concealable",TraitConcentrate:"Concentrate",TraitConcussive:"Concussive",TraitConfusion:"Confusion",TraitConrasu:"Conrasu",TraitConsecration:"Consecration",TraitConstruct:"Construct",TraitConsumable:"Consumable",TraitContact:"Contact",TraitContingency:"Contingency",TraitContract:"Contract",TraitCouatl:"Couatl",TraitCriticalFusion:"Critical Fusion",TraitCurse:"Curse",TraitCursebound:"Cursebound",TraitCursed:"Cursed",TraitDaemon:"Daemon",TraitDarkness:"Darkness",TraitDarvakka:"Darvakka",TraitDeadly:"Deadly",TraitDeadly2D10:"Deadly 2d10",TraitDeadly2D12:"Deadly 2d12",TraitDeadly2D8:"Deadly 2d8",TraitDeadly3D10:"Deadly 3d10",TraitDeadly3D12:"Deadly 3d12",TraitDeadly3D8:"Deadly 3d8",TraitDeadly4D10:"Deadly 4d10",TraitDeadly4D12:"Deadly 4d12",TraitDeadly4D8:"Deadly 4d8",TraitDeadlyD10:"Deadly d10",TraitDeadlyD12:"Deadly d12",TraitDeadlyD4:"Deadly d4",TraitDeadlyD6:"Deadly d6",TraitDeadlyD8:"Deadly d8",TraitDeath:"Death",TraitDedication:"Dedication",TraitDeflectingBludgeoning:"Deflecting Bludgeoning",TraitDeflectingPhysicalRanged:"Deflecting Physical Ranged",TraitDeflectingPiercing:"Deflecting Piercing",TraitDeflectingSlashing:"Deflecting Slashing",TraitDemon:"Demon",TraitDero:"Dero",TraitDescriptionAcid:"Effects with this trait deal acid damage. Creatures with this trait have a magical connection to acid.",TraitDescriptionAdditive:"Feats with the additive trait allow you to spend actions to add special substances to bombs or elixirs. You can add only one additive to a single alchemical item, and attempting to add another spoils the item. You can typically use actions with the additive trait only when you're creating an infused alchemical item, and some can be used only with the Quick Alchemy action. The additive trait is always followed by a level, such as additive 2. An additive adds its level to the level of the alchemical item you're modifying; the result is the new level of the mixture. The mixture's item level must be no higher than your advanced alchemy level",TraitDescriptionAdjusted:"The equipment comes with an adjustment described in its entry. This adjustment is built into the equipment permanently, meaning the equipment can't have another adjustment added, nor can it be swapped out for a different adjustment. If the adjustment alters the item's base statistics, such as adding the noisy trait, that's reflected in the equipment's table entry.",TraitDescriptionAdjustment:"Items with this trait are intended to alter existing pieces of equipment, typically armors, shields, and weapons. The given item will note which type of equipment it modifies. A piece of equipment can only be affected by a single adjustment at a time. Unless otherwise noted, adding or removing an adjustment requires using a 10-minute activity and a repair kit.",TraitDescriptionAeon:"These monitors are the self-styled defenders of reality. Traditional aeons have dualistic natures and forms, and they hold a dichotomy of interests, though axiomites and inevitables do not. Aeons other than axiomites and inevitables communicate via a strange telepathic hodgepodge of sensory sending called envisioning.",TraitDescriptionAesir:"Aesir are often-bellicose monitors of the chaotic planes, honing their skill in battle and preparing for a final confrontation at the end of the multiverse.",TraitDescriptionAftermath:"This trait describes feats that represent special abilities gained after exposure to the weird and deadly.",TraitDescriptionAgathion:"This family of animal-featured celestials is native to the plane of Nirvana. Most agathions are neutral good, have darkvision, and have a weakness to evil damage.",TraitDescriptionAgile:"The multiple attack penalty you take with this weapon on the second attack on your turn is -4 instead of -5, and -8 instead of -10 on the third and subsequent attacks in the turn.",TraitDescriptionAir:"Effects with the air trait either manipulate or conjure air. Those that manipulate air have no effect in a vacuum or an area without air. Creatures with this trait consist primarily of air or have a magical connection to that element.",TraitDescriptionAiuvarin:"A creature with this trait has the aiuvarin versatile heritage. Aiuvarins are of mixed ancestry, including elves or other aiuvarins. An ability with this trait can be used or selected only by aiuvarins.",TraitDescriptionAlchemical:"Alchemical items are powered by reactions of alchemical reagents. Alchemical items aren't magical and don't radiate a magical aura.",TraitDescriptionAlchemist:"This indicates abilities from the alchemist class.",TraitDescriptionAmp:"An amp is a special thoughtform that modifies the properties of your psi cantrips. Psi cantrips each have their own amp, and feats with the amp trait provide different amps you can apply to psi cantrips in place of their normal amps.",TraitDescriptionAmphibious:"An amphibious creature can breathe in water and in air, even outside of its preferred environment, usually indefinitely but at least for hours. These creatures often have a swim Speed. Their bludgeoning and slashing unarmed Strikes don't take the usual -2 penalty for being underwater.",TraitDescriptionAnadi:"A reclusive people from Garund who resemble spiders and can assume human forms.",TraitDescriptionAndroid:"A synthetic humanoid ancestry created by artificial means. Most common in Numeria.",TraitDescriptionApex:"When you Invest an Item that has the apex trait, it improves one of your attribute modifiers, either increasing it by 1 or to a total of +4, whichever grants the higher modifier. This gives you all the benefits of the new attribute modifier until the investiture ends. An apex item grants this benefit only the first time it's invested within a 24-hour period, and you can benefit from only one apex item at a time. If you attempt to invest an apex item when you already have one invested, you don't gain the attribute modifier increase, though you do gain any other effects of Investing the Item.",TraitDescriptionAphorite:"A type of planar scion descended from a being from Axis, the Plane of Law.",TraitDescriptionAquadynamic:"This armor is designed for use underwater, with streamlined design and buoyant materials used in strategic places. You don't apply the armor's check penalty to Acrobatics or Athletics checks in water or similar liquids.",TraitDescriptionArcane:"This magic comes from the arcane tradition, which is built on logic and rationality. Anything with this trait is magical.",TraitDescriptionArdande:"Ardandes are planar scions descended from kizidhars and other beings of elemental wood.",TraitDescriptionArchetype:"This feat belongs to an archetype.",TraitDescriptionArtifact:"Items with this trait are artifacts. These magic items can't be crafted by normal means, and they can't be damaged by normal means. Artifacts are always rare or unique.",TraitDescriptionAttached:"An attached weapon must be combined with another piece of gear to be used. The trait lists what type of item the weapon must be attached to. You must be wielding or wearing the item the weapon is attached to in order to attack with it. For example, shield spikes are attached to a shield, allowing you to attack with the spikes instead of a shield bash, but only if you're wielding the shield. An attached weapon is usually bolted onto or built into the item it's attached to, and typically an item can have only one weapon attached to it. An attached weapon can be affixed to an item with 10 minutes of work and a successful @Check[type:crafting|dc:10] check; this includes the time needed to remove the weapon from a previous item, if necessary. If an item is destroyed, its attached weapon can usually be salvaged.",TraitDescriptionAttack:"An ability with this trait involves an attack. For each attack you make beyond the first on your turn, you take a multiple attack penalty.",TraitDescriptionAuditory:"Auditory actions and effects rely on sound. An action with the auditory trait can be successfully performed only if the creature using the action can speak or otherwise produce the required sounds. A spell or effect with the auditory trait has its effect only if the target can hear it. This applies only to sound-based parts of the effect, as determined by the GM. This is different from a sonic effect, which still affects targets who can't hear it (such as deaf targets) as long as the effect itself makes sound.",TraitDescriptionAura:"An aura is an emanation that continually ebbs out from you, affecting creatures within a certain radius. Aura can also refer to the magical signature of an item or a creature with a strong alignment.",TraitDescriptionAutomaton:"A creature with this trait is a member of the automaton ancestry.",TraitDescriptionAzarketi:"Amphibious humanoids who live among the seas of the Inner Sea region, said to have descended from the people of Azlant. Sometimes known as gillmen or Low Azlanti.",TraitDescriptionBackstabber:"When you hit an off-guard creature, this weapon deals 1 precision damage in addition to its normal damage. The precision damage increases to 2 if the weapon is a +3 weapon.",TraitDescriptionBackswing:"You can use the momentum from a missed attack with this weapon to lead into your next attack. After missing with this weapon on your turn, you gain a +1 circumstance bonus to your next attack with this weapon before the end of your turn.",TraitDescriptionBarbarian:"This indicates abilities from the barbarian class.",TraitDescriptionBard:"This indicates abilities from the bard class.",TraitDescriptionBarding:"You can purchase special armor for animals, called barding. All animals have a trained proficiency rank in light barding, and combat-trained animals are trained in heavy barding. Barding uses the same rules as armor except for the following. The Price and Bulk of barding depend on the animal's size. Unlike for a suit of armor, barding's Strength entry is listed as a modifier, not a score. Barding can't be etched with magic runes, though special magical barding might be available.",TraitDescriptionBeastkin:"Humanoids that can partially or fully transform into animal forms.",TraitDescriptionBomb:"An alchemical bomb combines volatile alchemical components that explode when the bomb hits a creature or object. Most alchemical bombs deal damage, though some produce other effects.",TraitDescriptionBottledBreath:"Bottles of breath are enchanted bottles of cloud and mist, first developed by the denizens of the Plane of Air. You can Activate an item with the bottled breath trait as you inhale it or cause another creature to inhale it.",TraitDescriptionBrace:"A brace weapon is effective at damaging moving opponents. When you Ready to Strike an opponent that moves within your reach, until the start of your next turn Strikes with the brace weapon deal an additional 2 precision damage for each weapon damage die it has.",TraitDescriptionBrutal:"A ranged attack with this trait uses its Strength modifier instead of Dexterity on the attack roll.",TraitDescriptionBulwark:"The armor covers you so completely that it provides benefits against some damaging effects. On Reflex saves to avoid a damaging effect, such as a fireball, you add a +3 modifier instead of your Dexterity modifier.",TraitDescriptionCantrip:"A spell you can cast at will that is automatically heightened to half your level rounded up.",TraitDescriptionCapacity:"Weapons that have the capacity trait typically have multiple barrels or chambers capable of containing a round of ammunition. Capacity is always accompanied by a number indicating the number of barrels or chambers. After a capacity weapon is fired, you can select the next loaded barrel or chamber as an Interact action that doesn't require a free hand. Each barrel or chamber can be reloaded after it's fired as a separate Interact action.",TraitDescriptionCatalyst:"Items with the catalyst trait are consumable material spell components that alter or magnify specific spells. Activating a catalyst is part of Casting the Spell. The catalyst might increase the number of actions required to Cast the Spell, as indicated in the catalyst's Activate entry. Additionally, the spell gains material components if it didn't have them already or adds the catalyst to its existing components. Because the catalyst becomes part of the material components, you can draw the catalyst as part of Casting the Spell.",TraitDescriptionCatfolk:"A creature with this trait is a member of the catfolk ancestry.",TraitDescriptionCenser:"Censers are decorative containers, often metal or ceramic, in which incense is burned. An item with the censer trait must be filled with incense to Activate it, which ignites the incense and causes the censer to exude a cloud of smoke.",TraitDescriptionChampion:"This indicates abilities from the champion class.",TraitDescriptionChangeling:"A creature with this trait is a member of the changeling ancestry.",TraitDescriptionClass:"Archetypes with the class trait fundamentally diverge from your class's specialties but still fit within the theme of your class. You can select a class archetype only if your class meets the criteria listed in the archetype's prerequisites. Class archetypes always alter or replace some of a class's static class features in addition to any new feats they offer. It might be possible to take a class archetype at 1st level if it alters or replaces some of the class's initial class features. The 1st-level ability is presented much like a class feature and includes the class archetype's prerequisites and rules on how it changes your class. If you select this ability, you must take that archetype's dedication feat at 2nd level, and you proceed normally afterward. You can never have more than one class archetype.",TraitDescriptionCleric:"This indicates abilities from the cleric class.",TraitDescriptionClimbing:"The hand wielding the weapon is available to Climb.",TraitDescriptionClockwork:"Clockworks are intricate, complex constructs that can be programmed to perform specific functions.",TraitDescriptionCobbled:"This firearm is cobbled together and likely to misfire. No matter how well you upkeep it, on a failed attack roll, the attack misses and you must roll a @Check[type:flat|dc:5]. If you fail this check, the weapon misfires.",TraitDescriptionCoda:"Instruments with the coda trait work mostly like staves and have the staff trait. There are two differences: Coda instruments are in the form of musical instruments, and they can be prepared only by bards. Because they're not physically staves, you can't attack with a coda instrument, nor can you etch it with weapon runes.
The process of preparing a coda instrument involves playing significant portions of songs related to the spells within the instrument\u2014either old standards or ones of your own creation. This leaves magical reverberations within the instrument that allow you to complete the songs by playing their coda later in the day.
",TraitDescriptionCold:"Effects with this trait deal cold damage. Creatures with this trait have a connection to magical cold.",TraitDescriptionCombination:"This is a trait for weapons that combine the functionality of melee weapons and firearms in unique or unusual ways. A combination weapon has both a firearm form or usage and a melee weapon form or usage.",TraitDescriptionComfort:"The armor is so comfortable that you can rest normally while wearing it.",TraitDescriptionCommon:"Anything that doesn't list another rarity trait (uncommon, rare, or unique) automatically has the common trait. This rarity indicates that an ability, item, or spell is available to all players who meet the prerequisites for it. A creature of this rarity is generally known and can be summoned with the appropriate summon spell.",TraitDescriptionCompanion:"An item with this trait can be worn by an animal companion or similar creature. A companion can have up to two items invested.",TraitDescriptionComplex:"A hazard with this trait takes turns in an encounter.",TraitDescriptionComposite:"A composite impulse combines multiple elements. You can gain an impulse with the composite trait only if your kinetic elements include all the elements listed in the impulse's traits.",TraitDescriptionComposition:"To cast a composition cantrip or focus spell, you usually use a type of Performance. If the spell includes a verbal component, you must use an auditory performance, and if it includes a somatic component, you must use a visual one. The spell gains all the traits of the performance you used. You can cast only one composition spell each turn, and you can have only one active at a time. If you cast a new composition spell, any ongoing effects from your previous composition spell end immediately.",TraitDescriptionConcealable:"This weapon is designed to be inconspicuous or easily concealed. You gain a +2 circumstance bonus to Stealth checks and DCs to hide or conceal a weapon with this trait.",TraitDescriptionConcentrate:"An action with this trait requires a degree of mental concentration and discipline.",TraitDescriptionConcussive:"These weapons smash as much as puncture. When determining a creature's resistance or immunity to damage from this weapon, use the weaker of the target's resistance or immunity to piercing or to bludgeoning. For instance, if the creature were immune to piercing and had no resistance or immunity to bludgeoning damage, it would take full damage from a concussive weapon. Resistance or immunity to all physical damage, or all damage, applies as normal.",TraitDescriptionConrasu:"A people that are made of cosmic force given consciousness and housed within unique exoskeletons.",TraitDescriptionConsecration:"A consecration spell enhances an area for an extended period of time. A given area can have only a single consecration effect at a time. The new effect attempts to counteract any existing one in areas of overlap.",TraitDescriptionConstruct:"A construct is an artificial creature empowered by a force other than necromancy. Constructs are often mindless; they are immune to bleed damage, death effects, disease, healing, necromancy, nonlethal attacks, poison, and the doomed, drained, fatigued, paralyzed, sickened, and unconscious conditions; and they may have Hardness based on the materials used to construct their bodies. Constructs are not living creatures, nor are they undead. When reduced to 0 Hit Points, a construct creature is destroyed.",TraitDescriptionConsumable:"An item with this trait can be used only once. Unless stated otherwise, it's destroyed after activation. Consumable items include alchemical items and magical consumables such as scrolls and talismans. When a character creates consumable items, they can make them in batches of four.",TraitDescriptionContact:"This poison is delivered by contact with the skin.",TraitDescriptionContingency:"Spells with this trait grant you an action during the spell's effects, typically a reaction with a special trigger. They typically have a long duration, such as 24 hours. You can have only one spell with the contingency trait, or one contingency spell, active at a time. If you cast another spell with the contingency trait or contingency, the newer casting supersedes the older.",TraitDescriptionContract:"A contract is a type of item that magically establishes an agreement between multiple parties and typically grants magical benefits.",TraitDescriptionCriticalFusion:"Critical fusion is a new trait for combination weapons that grants you two additional options for the critical specialization effect when using the combination weapon's melee version to make a melee attack while the firearm is loaded. If you choose to use one of them, they replace the melee usage's normal critical specialization effect. First, you can discharge the firearm to create a loud bang and concussion, using the critical specialization effect for firearms instead of the melee weapon group's critical specialization effect. Second, you can choose to discharge the firearm to increase the critical hit's momentum or shoot the foe as you attack them in melee, dealing 2 additional damage per weapon damage die. Both of these options discharge the firearm, which typically means you have to reload it before firing it again.",TraitDescriptionCurse:"A curse is an effect that places some long-term affliction on a creature. Curses are always magical and are typically the result of a spell or trap. Effects with this trait can be removed only by effects that specifically target curses.",TraitDescriptionCursebound:"Spells with this trait increase the severity of your oracular curse when cast. Usually, only revelation spells have this trait. You can't cast a cursebound spell if you don't have an oracular curse.",TraitDescriptionCursed:"An item with this trait is cursed to cause trouble for its owner. A curse isn't detected when the item is identified, though a critical success reveals both the presence and exact nature of the curse. Cursed items can't be discarded once they've been triggered or invested the first time. The item can be removed only if the curse is removed.",TraitDescriptionDarkness:"Darkness effects extinguish non-magical light in the area, and can counteract less powerful magical light. You must usually target light magic with your darkness magic directly to counteract the light, but some darkness spells automatically attempt to counteract light.",TraitDescriptionDarvakka:"Entropic undead creatures twisted by the Netherworld and the Void.",TraitDescriptionDeadly:"On a critical hit, the weapon adds a weapon damage die of the listed size. Roll this after doubling the weapon's damage. This increases to two dice if the weapon has a greater striking rune and three dice if the weapon has a major striking rune. For instance, a rapier with a greater striking rune deals 2d8 extra piercing damage on a critical hit. An ability that changes the size of the weapon's normal damage dice doesn't change the size of its deadly die.",TraitDescriptionDeath:"An effect with the death trait kills you immediately if it reduces you to 0 HP. Some death effects can bring you closer to death or slay you outright without reducing you to 0 HP.",TraitDescriptionDedication:"You must select a feat with this trait to apply an archetype to your character.",TraitDescriptionDeflecting:"This shield is designed to block or divert certain types of attacks or weapons. Increase the shield's Hardness against the listed type of attack by 2.",TraitDescriptionDetection:"Effects with this trait attempt to determine the presence or location of a person, object, or aura.",TraitDescriptionDeviant:"This trait describes strange supernatural or paranormal abilities.",TraitDescriptionDhampir:"A creature with this trait is a member of the dhampir ancestry. These humanoids are the mortal offspring of vampires and members of other ancestries.",TraitDescriptionDisarm:"You can use this weapon to Disarm with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls (if any) as an item bonus to the Athletics check. If you critically fail a check to Disarm using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure. On a critical success, you still need a free hand if you want to take the item.",TraitDescriptionDisease:"An effect with this trait applies one or more diseases. A disease is typically an affliction.",TraitDescriptionDivine:"This magic comes from the divine tradition, drawing power from deities or similar sources. Anything with this trait is magical.",TraitDescriptionDoubleBarrel:"This weapon has two barrels that are each loaded separately. You can fire both barrels of a double barrel weapon in a single Strike to increase the weapon damage die by one step. If the weapon has the fatal trait, this increases the fatal die by one step.",TraitDescriptionDowntime:"An activity with this trait takes a day or more, and can be used only during downtime.",TraitDescriptionDromaar:"A creature with this trait has the dromaar versatile heritage. Dromaars are of mixed ancestry, including orcs or other dromaars. An ability with this trait can be used or selected only by dromaars.",TraitDescriptionDrug:"An item with this trait is a drug, a poison that conveys short-term benefits in addition to harmful side effects and long-term consequences. Each time a creature uses a given drug it must also attempt a saving throw against addiction to that drug.",TraitDescriptionDruid:"This indicates abilities from the druid class.",TraitDescriptionDuskwalker:"A creature with this trait has the duskwalker versatile heritage. Duskwalkers are planar scions infused with the supernatural energy of psychopomps. An ability with this trait can be used or selected only by duskwalkers.",TraitDescriptionDwarf:"A creature with this trait is a member of the dwarf ancestry. Dwarves are stout folk who often live underground and typically have darkvision. An ability with this trait can be used or selected only by dwarves. An item with this trait is created and used by dwarves.",TraitDescriptionEarth:"Effects with the earth trait either manipulate or conjure earth. Those that manipulate earth have no effect in an area without earth. Creatures with this trait consist primarily of earth or have a magical connection to that element.",TraitDescriptionEidolon:"A creature with this trait is a summoner's eidolon. An item with this trait can be worn by an eidolon. An eidolon can have up to two items invested.",TraitDescriptionElectricity:"Effects with this trait deal electricity damage. A creature with this trait has a magical connection to electricity.",TraitDescriptionElf:"A creature with this trait is a member of the elf ancestry. Elves are mysterious people with rich traditions of magic and scholarship who typically have low-light vision. An ability with this trait can be used or selected only by elves. A weapon with this trait is created and used by elves.",TraitDescriptionElixir:"Elixirs are alchemical liquids that are used by drinking them.",TraitDescriptionEmotion:"This effect alters a creature's emotions. Effects with this trait always have the mental trait as well. Creatures with special training or that have mechanical or artificial intelligence are immune to emotion effects.",TraitDescriptionEntrench:"You can position yourself in the armor or reposition its articulated pieces to better protect against some attacks. If you're trained in this armor, while wearing it you can spend a single action to gain a +1 circumstance bonus to AC against a certain type of attack until the start of your next turn. The entrench trait lists the type of attack this bonus applies against, typically entrench melee or entrench ranged.",TraitDescriptionEnvironment:"A hazard with this trait is something dangerous that's part of the natural world, such as quicksand or harmful mold.",TraitDescriptionEsoterica:"The esoterica trait is present in many thaumaturge feats and class features that incorporate the various talismans, supernatural trinkets, and other objects you carry with you. Abilities that have the esoterica trait require you to be in possession of your esoterica to use them. Normally, you're assumed to always have your esoterica with you, but in some rare circumstances, you might either not have them on hand or have your gear stripped from you.",TraitDescriptionEvolution:"Feats with this trait affect your eidolon instead of you, typically by granting it additional physical capabilities.",TraitDescriptionExpandable:"An item with the expandable trait increases to a specific size when activated. Unless otherwise noted, this space must be adjacent to you and on the ground, and the item needs to have enough open space to expand into or else the activation has no effect. When the effect ends, the expanded item disintegrates if it's a consumable or shrinks back to its normal size if it's not a consumable.",TraitDescriptionExploration:"An activity with this trait takes more than a turn to use, and can usually be used only during exploration mode.",TraitDescriptionExtradimensional:"This effect or item creates an extradimensional space. An extradimensional effect placed inside another extradimensional space ceases to function until it is removed.",TraitDescriptionFatal:"The fatal trait includes a die size. On a critical hit, the weapon's damage die increases to that die size instead of the normal die size, and the weapon adds one additional damage die of the listed size.",TraitDescriptionFatalAim:"It's possible to hold the stock of this weapon under one arm so you can fire it with a single hand as long as the other hand isn't holding a weapon, shield, or anything else you would need to move and position, to ensure the weapon doesn't slip out from under your arm. However, if you use both hands, the weapon can make fatal attacks. When you wield the weapon in two hands, it gains the fatal trait with the listed damage die. Holding the weapon underarm stably enough to fire is significantly more complicated than just releasing one hand from the weapon, so to switch between the two grips, you must do so with an Interact action rather than Releasing or as part of reloading.",TraitDescriptionFear:"Fear effects evoke the emotion of fear. Effects with this trait always have the mental and emotion traits as well.",TraitDescriptionFetchling:"A creature with this trait is a member of the fetchling ancestry. Fetchlings were once human, but generations of life in the Netherworld have transformed them.",TraitDescriptionFey:"Creatures of the First World are called the fey.",TraitDescriptionFighter:"This indicates abilities from the fighter class.",TraitDescriptionFigurehead:"While many ships are adorned with decorative carvings, daring crews sometimes procure magical figureheads for their vessels.",TraitDescriptionFinesse:"You can use your Dexterity modifier instead of your Strength modifier on attack rolls using this melee weapon. You still use your Strength modifier when calculating damage.",TraitDescriptionFinisher:"Finishers are spectacular finishing moves. You can use a finisher only if you have panache, and you lose your panache immediately after performing a finisher. Once you use a finisher, you can't use actions that have the attack trait for the rest of your turn. Some finisher actions also grant an effect on a failure. If your finisher succeeds, you can choose to apply the failure effect instead.",TraitDescriptionFinite:"Planes with this trait consist of a limited amount of space.",TraitDescriptionFire:"Effects with the fire trait deal fire damage or either conjure or manipulate fire. Those that manipulate fire have no effect in an area without fire. Creatures with this trait consist primarily of fire or have a magical connection to that element.",TraitDescriptionFleshwarp:"A humanoid transformed so completely by outside forces that they are now a unique ancestry.",TraitDescriptionFlexible:"The armor is flexible enough that it doesn't hinder most actions. You don't apply its check penalty to Acrobatics or Athletics checks.",TraitDescriptionFlourish:"Flourish actions are actions that require too much exertion to perform a large number in a row. You can use only 1 action with the flourish trait per turn.",TraitDescriptionFocus:"Focus spells are a special type of spell attained directly from a branch of study, from a deity, or from another specific source. You can learn focus spells only through special class features or feats, rather than choosing them from a spell list. Furthermore, you cast focus spells using a special pool of Focus Points\u2014you can't prepare a focus spell in a spell slot or use your spell slots to cast focus spells; similarly, you can't spend your Focus Points to cast spells that aren't focus spells.",TraitDescriptionFocused:"An item with this trait can give you an additional Focus Point. This focus point is separate from your focus pool and doesn't count toward the cap on your focus pool. You can gain this benefit only if you have a focus pool, and there might be restrictions on how the point can be used. You can't gain more than 1 Focus Point per day from focused items.",TraitDescriptionFoldaway:"This shield can collapse into a smaller form attached to a gauntlet for stability and easy travel. You can use an Interact action to deploy or stow the shield. While it's deployed, you can Raise the Shield as long as you have that hand free or are holding an object of light Bulk that's not a weapon in that hand. The shield impedes the use of your hand while it's deployed. Though you can still hold items in that hand, you can't wield weapons in that hand, operate anything that takes two hands, or attack with the gauntlet.
A foldaway shield must be attached to a gauntlet for stability. It can be affixed to an item with 10 minutes of work and a successful DC 10 Crafting check; this includes the time needed to remove the shield from a previous gauntlet, if necessary. If the gauntlet is destroyed, the foldaway shield can usually be salvaged. The collapsible nature of the shield makes it impossible to affix an attached weapon to it.
",TraitDescriptionForce:"Effects with this trait deal force damage or create objects made of pure magical force.",TraitDescriptionForceful:"This weapon becomes more dangerous as you build momentum. When you attack with it more than once on your turn, the second attack gains a circumstance bonus to damage equal to the number of weapon damage dice, and each subsequent attack gains a circumstance bonus to damage equal to double the number of weapon damage dice.",TraitDescriptionFortune:"A fortune effect beneficially alters how you roll your dice. You can never have more than one fortune effect alter a single roll. If multiple fortune effects would apply, you have to pick which to use. If a fortune effect and a misfortune effect would apply to the same roll, the two cancel each other out, and you roll normally.",TraitDescriptionFreeHand:"This weapon doesn't take up your hand, usually because it is built into your armor. A free-hand weapon can't be Disarmed. You can use the hand covered by your free-hand weapon to wield other items, perform manipulate actions, and so on. You can't attack with a free-hand weapon if you're wielding anything in that hand or otherwise using that hand. When you're not wielding anything and not otherwise using the hand, you can use abilities that require you to have a hand free as well as those that require you to be wielding a weapon in that hand. Each of your hands can have only one free-hand weapon on it.",TraitDescriptionFulu:"Fulus are small paper charms that can be affixed to a suit of armor, a shield, a weapon, a creature, or even a structure. Some fulus are composed of multiple such charms, taking effect only once all have been affixed. Normal fulus have effects immediately once affixed, while fulu talismans have an effect only once activated. Once a fulu has been activated, it lasts for the given duration and then burns out. Unless otherwise noted, fulus expire one year after being created, reverting to mundane paper. All fulus have the fulu and consumable traits. Fulus also have a tradition trait\u2014either arcane, divine, occult or primal\u2014determined by the magical tradition of its creator. For example, a fulu created by a priest would have the divine trait, whereas a witch who dabbles in fate might create a fulu with the occult trait. Some fulus also have the talisman trait, if they work similarly to talismans (such as being affixed to a suit of armor, a shield, or a weapon. Each fulu's stat block indicates the type of item or creature it can be affixed to. Affixing or removing a fulu requires using the Affix a Fulu activity, or the Affix a Talisman action instead if the fulu is also a talisman.",TraitDescriptionGadget:"Gadgets are consumable technological inventions with innovative uses.",TraitDescriptionGanzi:"A planar scion descended from a chaotic being of the Maelstrom, such as a protean.",TraitDescriptionGeneral:"A type of feat that any character can select, regardless of ancestry and class, as long as they meet the prerequisites. You can select a feat with this trait when your class grants a general feat.",TraitDescriptionGenie:"The diverse families of genies hold positions of prominence on the Elemental Planes. They have powerful magical abilities.",TraitDescriptionGeniekin:"An umbrella term for planar scions descended from beings from the Elemental Planes.",TraitDescriptionGhoran:"An intelligent plant ancestry that maintain long lives by rejuvenating themselves from seeds.",TraitDescriptionGhul:"Greedy and gluttonous undead originally formed from genie.",TraitDescriptionGnoll:"Gnolls are humanoids that resemble hyenas.",TraitDescriptionGnome:"A creature with this trait is a member of the gnome ancestry. Gnomes are small people skilled at magic who seek out new experiences and usually have low-light vision. An ability with this trait can be used or selected only by gnomes. A weapon with this trait is created and used by gnomes.",TraitDescriptionGoblin:"A creature with this trait can come from multiple tribes of creatures, including goblins, hobgoblins, and bugbears. Goblins tend to have darkvision. An ability with this trait can be used or chosen only by goblins. A weapon with this trait is created and used by goblins.",TraitDescriptionGoloma:"Insular humanoids that bear countless eyes.",TraitDescriptionGrapple:"You can use this weapon to Grapple with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Grapple using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionGrimoire:"Spellbooks are useful tools for any magic user to write down incantations and runes of power, but where most spellbooks are nothing more than ink on parchment, grimoires have absorbed the magic of the spells within\u2014magic that knowledgeable spellcasters can use to augment their spells.",TraitDescriptionGrippli:"Gripplis are a family of frog-like humanoids",TraitDescriptionGunslinger:"This indicates abilities from the gunslinger class.",TraitDescriptionHalfling:"A creature with this trait is a member of the halfling ancestry. These small people are friendly wanderers considered to be lucky. An ability with this trait can be used or selected only by halflings. A weapon with this trait is created and used by halflings.",TraitDescriptionHampering:"A weapon with the hampering trait includes a disruptive limb or flange. You can use an Interact action to thrash the weapon in a square within the weapon's reach. That square becomes difficult terrain until you attack with the weapon, move, would otherwise stop thrashing it, or at the beginning of your next turn.",TraitDescriptionHarnessed:"This shield features a special brace or opening designed to hold jousting weapons.",TraitDescriptionHaunt:"A hazard with this trait is a spiritual echo, often of someone with a tragic death. Putting a haunt to rest often involves resolving the haunt's unfinished business. A haunt that hasn't been properly put to rest always returns after a time.",TraitDescriptionHealing:"A healing effect restores a creature's body, typically by restoring Hit Points, but sometimes by removing diseases or other debilitating effects.",TraitDescriptionHefty:"A hefty shield is so heavy that raising it takes more effort. Raising a Shield with the hefty trait is a 2-action activity unless your Strength score equals or exceeds the number with the trait.",TraitDescriptionHex:"A hex is a type of focus spell a witch can cast.",TraitDescriptionHindering:"This armor is so heavy and bulky it slows you down no matter what. You take a -5 penalty to all your Speeds (to a minimum of a 5-foot Speed). This is separate from and in addition to the armor's Speed penalty, and affects you even if your Strength or an ability lets you reduce or ignore the armor's Speed penalty.",TraitDescriptionHobgolin:"Hobgoblins are a sturdy, clever people with a propensity for militaristic order.",TraitDescriptionHoly:"Effects with the holy trait are tied to powerful magical forces of benevolence and virtue. They often have stronger effects on unholy creatures. Creatures with this trait are strongly devoted to holy causes and often have weakness to unholy. If a creature with weakness to holy uses a holy item or effect, it takes damage from its weaknes",TraitDescriptionHuman:"A creature with this trait is a member of the human ancestry. Humans are a diverse array of people known for their adaptability. An ability with this trait can be used or selected only by humans.",TraitDescriptionHumanoid:"Humanoid creatures reason and act much like humans. They typically stand upright and have two arms and two legs.",TraitDescriptionIfrit:"A type of geniekin descended from a being from the Plane of Fire.",TraitDescriptionIllusion:"Effects and magic items with this trait involve false sensory stimuli.",TraitDescriptionImpulse:"The primary magical actions kineticists use are called impulses. You can use an impulse only if your kinetic aura is active and channeling that element, and only if you have a hand free to shape the elemental flow. The impulse trait means the action has the concentrate trait unless another ability changes this. If an impulse allows you to choose an element, you can choose any element you're channeling, and the impulse gains that element's trait.",TraitDescriptionIncapacitation:"An ability with this trait can take a character completely out of the fight or even kill them, and it's harder to use on a more powerful character. If a spell has the incapacitation trait, any creature of more than twice the spell's rank treats the result of their check to prevent being incapacitated by the spell as one degree of success better, or the result of any check the spellcaster made to incapacitate them as one degree of success worse. If any other effect has the incapacitation trait, a creature of higher level than the item, creature, or hazard generating the effect gains the same benefits.",TraitDescriptionIncarnate:"A spell with the incarnate trait is similar in theme to spells that summon creatures, but it doesn't conjure a minion with the summoned trait. Instead, when summoned, the incarnate creature takes its Arrive action when you finish Casting the Spell. At the end of your next turn, the incarnate creature can either Step, Stride, or take the action for another movement type it has (such as Climb or Burrow), and then takes its Depart action. The spell then ends. The names of specific Arrive and Depart actions are listed in italics after the word \u201CArrive\u201D or \u201CDepart\u201D respectively, along with any traits. A creature summoned by an incarnate spell acts in your interests, directs its effects away from you and your allies as much as possible, and might listen to your requests, but ultimately makes its own decisions. If the spell indicates that the incarnate makes a decision, the GM determines what the incarnate would do. It might even become more inclined to do precisely as you wish over multiple summonings. The incarnate is not fully a creature. It can't take any other actions, nor can it be targeted or harmed by Strikes, spells, or other effects unless they would be able to target or end a spell effect (such as dispel magic). It has a size for the purposes of determining its placement for effects, but it doesn't block movement. If applicable, its effects use your spell DCs and spell attack roll modifier.",TraitDescriptionIncorporeal:"An incorporeal creature or object has no physical form. It can pass through solid objects, including walls. When inside an object, an incorporeal creature can't perceive, attack, or interact with anything outside the object, and if it starts its turn in an object, it is slowed 1. Corporeal creatures can pass through an incorporeal creature, but they can't end their movement in its space. An incorporeal creature can't attempt Strength-based checks against physical creatures or objects-only against incorporeal ones-unless those objects have the ghost touch property rune. Likewise, a corporeal creature can't attempt Strength-based checks against incorporeal creatures or objects. Incorporeal creatures usually have immunity to effects or conditions that require a physical body, like disease, poison, and precision damage. They usually have resistance against all damage (except force damage and damage from Strikes with the ghost touch property rune), with double the resistance against non-magical damage.",TraitDescriptionInfused:"You created an alchemical item with the infused trait using your infused reagents, and it has a limited time before it becomes inert. Any nonpermanent effects from your infused alchemical items, with the exception of afflictions such as slow-acting poisons, end when you make your daily preparations again.",TraitDescriptionInfusion:"Actions with the infusion trait tweak your kineticist impulses. You must use an infusion action directly before the impulse action you want to alter. If you use any action (including free actions and reactions) other than an impulse action directly after, you waste the benefits of the infusion action. Any additional effects added by an infusion action are part of the impulse's effect, not of the infusion action itself.",TraitDescriptionIngested:"This poison is delivered when drunk or eaten.",TraitDescriptionInhaled:"This poison is delivered when breathed in.",TraitDescriptionInjection:"This weapon can be filled with an injury poison. Immediately after a successful attack with the weapon, you can inject the target with the loaded poison with a single Interact action. Refilling the weapon with a new substance requires three Interact actions, and uses both hands.",TraitDescriptionInjury:"This poison is delivered by damaging the recipient.",TraitDescriptionInscribed:"The armor or shield has been treated so it can be inscribed with magical symbols using the same method as Crafting a scroll. Inscribed attire can hold one scroll inscribed on it. You need a free hand to Activate the scroll, but you don't need to Interact to draw it. You can also Activate the magic to erase the scroll the armor currently contains. You can't inscribe a new scroll onto the armor if a scroll is currently inscribed on it or if the armor is broken.",TraitDescriptionIntegrated:"This shield has been created to include a weapon in its construction, which works like an attached weapon but can't be removed from the shield.",TraitDescriptionIntelligent:"An item with this trait is intelligent and has its own will and personality, as well as several statistics that most items don't have. Intelligent items can't be crafted by normal means, and they are always rare or unique.",TraitDescriptionInventor:"This indicates abilities from the inventor class.",TraitDescriptionInvested:"A character can wear only 10 magical items that have the invested trait. None of the magical effects of the item apply if the character hasn't invested it, nor can it be activated, though the character still gains any normal benefits from wearing the physical item (like a hat keeping rain off their head).",TraitDescriptionInvestigator:"This indicates abilities from the investigator class.",TraitDescriptionJousting:"The weapon is suited for mounted combat with a harness or similar means. When mounted, if you moved at least 10 feet on the action before your attack, add a circumstance bonus to damage for that attack equal to the number of damage dice for the weapon. In addition, while mounted, you can wield the weapon in one hand, changing the damage die to the listed value.",TraitDescriptionKashrishi:"A stout ancestry bearing distinctive crystal horns and inherent psychic abilities.",TraitDescriptionKickback:"A kickback weapon is extra powerful and difficult to use due to its high recoil. A kickback weapon deals 1 additional damage with all attacks. Firing a kickback weapon gives a -2 circumstance penalty to the attack roll, but characters with 14 or more Strength ignore the penalty. Attaching a kickback weapon to a deployed bipod, tripod, or other stabilizer can lower or negate this penalty.",TraitDescriptionKineticist:"This indicates abilities from the kineticist class.",TraitDescriptionKitsune:"Shapeshifting humanoids whose true forms resemble foxes.",TraitDescriptionKobold:"A creature with this trait is a member of the kobold ancestry.",TraitDescriptionLaminar:"The armor is made up of layered sections, so when it breaks, it isn't as much of a problem. The status penalty to AC if this armor is broken is \u20131 for broken medium armor, \u20132 for broken heavy armor, or no penalty for broken light armor.",TraitDescriptionLaunching:`A mechanism within this shield can shoot projectiles, causing the shield to also function as a ranged weapon. The trait lists the type of weapon, such as "launching dart." Striking with the launcher requires the same number of hands as normal, except that the hand holding the shield counts toward this total, so a one-handed ranged weapon would require only one hand. Reloading takes the normal number of Interact actions, to a minimum of 1 action, and you can't use the hand holding your shield to reload.`,TraitDescriptionLeshy:"A creature with this trait is a member of the leshy ancestry.",TraitDescriptionLight:"Light effects overcome non-magical darkness in the area, and can counteract magical darkness. You must usually target darkness magic with your light magic directly to counteract the darkness, but some light spells automatically attempt to counteract darkness.",TraitDescriptionLinguistic:"An effect with this trait depends on language comprehension. A linguistic effect that targets a creature works only if the target understands the language you are using.",TraitDescriptionLitany:"Litanies are special devotion spells, typically used by champions and requiring a single action, that usually give temporary immunity to further litanies.",TraitDescriptionLizardfolk:"These reptilian humanoids, also known as iruxi, are extremely adaptable and patient.",TraitDescriptionLozenge:"You Activate an alchemical lozenge by putting it in your mouth. It stays there, slowly dissolving and releasing its ingredients over time. You can bite a lozenge for a secondary effect. The action this takes is noted in the item. As soon as this secondary effect is over, the lozenge is used up and its benefits for you end. You can drink elixirs, potions, and beverages with a lozenge in your mouth, but you can't benefit from more than one lozenge at a time. If you have two lozenges in your mouth at the same time, both become inert. You can also spit out a lozenge as a single action to end its effect and make it inert. A lozenge dissolves due to its alchemical ingredients, so it typically still works even if you don't have saliva.",TraitDescriptionMagical:"Something with the magical trait is imbued with magical energies not tied to a specific tradition of magic. Some items or effects are closely tied to a particular tradition of magic. In these cases, the item has the arcane, divine, occult, or primal trait instead of the magical trait. Any of these traits indicate that the item is magical.",TraitDescriptionMagus:"This indicates abilities from the magus class.",TraitDescriptionManipulate:"You must physically manipulate an item or make gestures to use an action with this trait. Creatures without a suitable appendage can't perform actions with this trait. Manipulate actions often trigger reactions.",TraitDescriptionMechanical:"A hazard with this trait is a constructed physical object.",TraitDescriptionMental:"A mental effect can alter the target's mind. It has no effect on an object or a mindless creature.",TraitDescriptionMetal:"Effects with the metal trait either manipulate or conjure metal. Those that manipulate metal have no effect in an area without metal. Creatures with this trait consist primarily of metal or have a magical connection to that element.",TraitDescriptionMindless:"A mindless creature has either programmed or rudimentary mental attributes. Most, if not all, of their mental attribute modifiers are -5. They are immune to all mental effects.",TraitDescriptionMindshift:"An action with this trait can always be altered to use the raw power of your mind. When you take this action, you can choose to replace any damage it deals with mental damage, give it the mental trait, and replace any save it requires with a Will save. The action loses any traits matching damage types it no longer deals.",TraitDescriptionMinion:"Minions are creatures that directly serve another creature. A creature with this trait can use only 2 actions per turn, doesn't have reactions, and can't act when it's not your turn. Your minion acts on your turn in combat, once per turn, when you spend an action to issue it commands. For an animal companion, you Command an Animal; for a minion that's a spell or magic item effect, like a summoned minion, you Sustain a Spell or Sustain an Activation; if not otherwise specified, you issue a verbal command as a single action with the auditory and concentrate traits. If given no commands, minions use no actions except to defend themselves or to escape obvious harm. If left unattended for long enough, typically 1 minute, mindless minions usually don't act, animals follow their instincts, and sapient minions act how they please. A minion can't control other creatures.",TraitDescriptionMisfortune:"A misfortune effect detrimentally alters how you roll your dice. You can never have more than one misfortune effect alter a single roll. If multiple misfortune effects would apply, the GM decides which is worse and applies it. If a fortune effect and a misfortune effect would apply to the same roll, the two cancel each other out, and you roll normally.",TraitDescriptionMissive:"A missive is a piece of magical stationery that must be crafted and composed before it can be activated. All missives have the missive and consumable traits. Missives are often constructed of paper, parchment, or vellum, but any other thin, portable material that can hold writing or embossing upon it can be crafted into missives. After being crafted, the missive is a blank sheet until a message is composed upon it, completing its magic.",TraitDescriptionModification:"A feat with this trait alters the construction of your innovation. If you have the reconfigure class feature, you can retrain such a feat more easily.",TraitDescriptionModular:`The weapon has multiple configurations that you can switch between using an Interact action. Typically, switching between configurations of a modular weapon allows it to deal different types of damage (listed in the trait, such as "modular B, P, or S"), though it's possible for a modular weapon's description to list more complicated configurations.`,TraitDescriptionMonk:"Abilities with this trait are from the monk class. A weapon with this trait is primarily used by monks.",TraitDescriptionMonkWeapon:"Many monks learn to use these weapons.",TraitDescriptionMorph:"Effects that slightly alter a creature's form have the morph trait. Any Strikes specifically granted by a morph effect are magical. You can be affected by multiple morph spells at once, but if you morph the same body part more than once, the second morph effect attempts to counteract the first (in the same manner as two polymorph effects, described in that trait). Your morph effects might also end if you are polymorphed and the polymorph effect invalidates or overrides your morph effect. The GM determines which morph effects can be used together and which can't.",TraitDescriptionMounted:"Mounted siege weapons take up a certain size and space, and typically have statistics to allow them to be attacked. They're used for large-scale warfare.",TraitDescriptionMove:"An action with this trait involves moving from one space to another.",TraitDescriptionMulticlass:"Archetypes with the multiclass trait represent diversifying your training into another class's specialties. You can't select a multiclass archetype's dedication feat if you are a member of the class of the same name.",TraitDescriptionMutagen:"An elixir with the mutagen trait temporarily transmogrifies the subject's body and alters its mind. A mutagen always conveys one or more beneficial effects paired with one or more detrimental effects. Mutagens are polymorph effects, meaning you can benefit from only one at a time.",TraitDescriptionNagaji:"A traditionalist ancestry with reptilian features and serpentine heads.",TraitDescriptionNephilim:"A creature with this trait has the nephilim versatile heritage. Nephilim are planar scions descended from immortal beings from other planes. An ability with this trait can be used or selected only by nephilim.",TraitDescriptionNindoru:"Nindorus are chaotic evil fiends that rise from corruptions to the cycle of reincarnating souls and live on the Universe. Although they often have elements in their appearance that make them seem undead, they're actually living beings. Most nindorus have darkvision, are immune to death effects, have weakness to silver, and possess the power to manifest objects or creatures from their thoughts.",TraitDescriptionNoisy:"This armor is loud and likely to alert others to your presence when you're using the Avoid Notice exploration activity. The armor's check penalty applies to Stealth checks even if you meet the required Strength score.",TraitDescriptionNone:"This trait has no description.",TraitDescriptionNonlethal:"Attacks with this weapon are nonlethal, and are used to knock creatures unconscious instead of kill them. You can use a nonlethal weapon to make a lethal attack with a -2 circumstance penalty.",TraitDescriptionOath:"Oaths add an additional tenet to your code. You can usually have only one feat with this trait.",TraitDescriptionOccult:"This magic comes from the occult tradition, calling upon bizarre and ephemeral mysteries. Anything with this trait is magical.",TraitDescriptionOil:"Oils are magical gels, ointments, pastes, or salves that are typically applied to an object and are used up in the process.",TraitDescriptionOlfactory:"An olfactory effect can affect only creatures that can smell it. This applies only to olfactory parts of the effect, as determined by the GM.",TraitDescriptionOpen:"These maneuvers work only as the first salvo on your turn. You can use an open only if you haven't used an action with the attack or open trait yet this turn.",TraitDescriptionOracle:"This indicates abilities from the oracle class.",TraitDescriptionOrc:"A creature with this trait is a member of the orc ancestry. A weapon with this trait is a weapon which orcs craft and use.",TraitDescriptionOread:"A type of geniekin descended from a being from the Plane of Earth.",TraitDescriptionOverflow:"Powerful impulses temporarily overdraw the energy of your kinetic gate. When you use an impulse that has the overflow trait, your kinetic aura deactivates until you revitalize it (typically with Channel Elements). Extinguishing your element this severely is taxing, and consequently, you can use only one overflow impulse per round, even if you reactivate your kinetic gate.",TraitDescriptionParry:"This weapon can be used defensively to block attacks. While wielding this weapon, if your proficiency with it is trained or better, you can spend a single action to position your weapon defensively, gaining a +1 circumstance bonus to AC until the start of your next turn.",TraitDescriptionPeachwood:"Peachwood weapons have a particularly auburn tinge to them when under direct sunlight. Peachwood is treated as duskwood for any undead creatures' resistances or weaknesses related to duskwood (allowing a peachwood weapon to bypass a jiang-shi's resistance, for example). In addition, peachwood weapons bypass a small portion of the resistances of any undead creature. Strikes with a peachwood weapon treat an undead's resistances against physical damage as 2 lower for standard-grade peachwood, and 4 lower for high-grade.",TraitDescriptionPlant:"Vegetable creatures have the plant trait. They are distinct from normal plants. Magical effects with this trait manipulate or conjure plants or plant matter in some way. Those that manipulate plants have no effect in an area with no plants.",TraitDescriptionPoison:"An effect with this trait delivers a poison or deals poison damage. An item with this trait is poisonous and might cause an affliction.",TraitDescriptionPolymorph:"These effects transform the target into a new form. A target can't be under the effect of more than one polymorph effect at a time. If it comes under the effect of a second polymorph effect, the second polymorph effect attempts to counteract the first. If it succeeds, it takes effect, and if it fails, the spell has no effect on that target. Any Strikes specifically granted by a polymorph effect are magical. Unless otherwise stated, polymorph spells don't allow the target to take on the appearance of a specific individual creature, but rather just a generic creature of a general type or ancestry. If you take on a battle form with a polymorph spell, the special statistics can be adjusted only by circumstance bonuses, status bonuses, and penalties. Unless otherwise noted, the battle form prevents you from casting spells, speaking, and using most manipulate actions that require hands. (If there's doubt about whether you can use an action, the GM decides.) Your gear is absorbed into you; the constant abilities of your gear still function, but you can't activate any items.",TraitDescriptionPonderous:"The armor has moving parts or other complications that lengthen the wearer's initial reaction time. While wearing the armor, you take a \u20131 penalty to initiative checks. If you don't meet the armor's required Strength score, this penalty increases to be equal to the armor's check penalty if it's worse.",TraitDescriptionPoppet:"A creature with this trait is a member of the poppet ancestry.",TraitDescriptionPortable:"Portable siege weapons, such as battering rams, can be more easily carried and have a role in both warfare and smaller conflicts or exploration.",TraitDescriptionPossession:"Effects with this trait allow a creature to project its mind and spirit into a target. A creature immune to mental effects can't use a possession effect. While possessing a target, a possessor's true body is unconscious (and can't wake up normally), unless the possession effect allows the creature to physically enter the target. Whenever the target takes damage, the possessor takes half that amount of damage as mental damage. A possessor loses the benefits of any of its active spells or abilities that affect its physical body, though it gains the benefits of the target's active spells and abilities that affect their body. A possessor can use any of the target's abilities that are purely physical, and it can't use any of its own abilities except spells and purely mental abilities. The GM decides whether an ability is purely physical or purely mental. A possessor uses the target's attack modifier, AC, Fortitude save, Reflex save, Perception, and physical skills, and its own Will save, mental skills, spell attack roll, and spell DC; benefits of invested items apply where relevant (the possessor's invested items apply when using its own values, and the target's invested items apply when using the target's values). A possessor gains no benefit from casting spells that normally affect only the caster, since it isn't in its own body. The possessor must use its own actions to make the possessed creature act. If a possessor reaches 0 Hit Points through any combination of damage to its true body and mental damage from the possession, it is knocked out as normal and the possession immediately ends. If the target reaches 0 Hit Points first, the possessor can either fall unconscious with the body and continue the possession or end the effect as a free action and return to its body. If the target dies, the possession ends immediately and the possessor is stunned for 1 minute.",TraitDescriptionPotion:"A potion is a magical liquid activated when you drink it.",TraitDescriptionPrecious:"Valuable materials with special properties have the precious trait. They can be substituted for base materials when you Craft items.",TraitDescriptionPrediction:"Effects with this trait determine what is likely to happen in the near future. Most predictions are divinations.",TraitDescriptionPress:"Actions with this trait allow you to follow up earlier attacks. An action with the press trait can be used only if you are currently affected by a multiple attack penalty. You can't use a press action when it's not your turn, even if you use the Ready activity. Some actions with the press trait also grant an effect on a failure. The effects that are added on a failure don't apply on a critical failure. If your press action succeeds, you can choose to apply the failure effect instead. (For example, you may wish to do this when an attack deals no damage due to resistance.)",TraitDescriptionPrimal:"This magic comes from the primal tradition, connecting to the natural world and instinct. Anything with this trait is magical.",TraitDescriptionProcessed:"An alchemical consumable with the processed trait can be created with Quick Alchemy but is too complex to create in a single action.",TraitDescriptionPropulsive:"You add half your Strength modifier (if positive) to damage rolls with a propulsive ranged weapon. If you have a negative Strength modifier, you add your full Strength modifier instead.",TraitDescriptionPsyche:"Your psyche must be unleashed to use abilities that have the psyche trait, and they end automatically when your unleashed psyche subsides.",TraitDescriptionPsychic:"This indicates abilities from the psychic class.",TraitDescriptionRadiation:"A dangerous, typically poisonous emission typically originating from radioactive minerals.",TraitDescriptionRage:"You must be raging to use abilities with the rage trait, and they end automatically when you stop raging.",TraitDescriptionRange:"These attacks will either list a finite range or a range increment, which follows the normal rules for range increments.",TraitDescriptionRangedTrip:"This weapon can be used to Trip with the Athletics skill at a distance up to the weapon's first range increment. The skill check takes a -2 circumstance penalty. You can add the weapon's item bonus to attack rolls as a bonus to the check. As with using a melee weapon to trip, a ranged trip doesn't deal any damage when used to Trip.",TraitDescriptionRanger:"This indicates abilities from the ranger class.",TraitDescriptionRare:"This rarity indicates that a rules element is very difficult to find in the game world. A rare feat, spell, item or the like is available to players only if the GM decides to include it in the game, typically through discovery during play. Creatures with this trait are rare. They typically can't be summoned. The DC of Recall Knowledge checks related to these creatures is increased by 5.",TraitDescriptionRatfolk:"A creature with this trait is a member of the ratfolk ancestry.",TraitDescriptionRazing:"Razing weapons are particularly good at damaging objects, structures, and vehicles. Whenever you deal damage to an object (including shields and animated objects), structure, or vehicle with a razing weapon, the object takes an amount of additional damage equal to double the number of weapon damage dice.",TraitDescriptionReach:"Natural attacks with this trait can be used to attack creatures up to the listed distance away instead of only adjacent creatures. Weapons with this trait are long and can be used to attack creatures up to 10 feet away instead of only adjacent creatures. For creatures that already have reach with the limb or limbs that wield the weapon, the weapon increases their reach by 5 feet.",TraitDescriptionReckless:"Actions with the reckless trait run the risk of the pilot losing control of a vehicle. When performing a reckless action, the pilot must first attempt an appropriate piloting check to keep control of the vehicle.",TraitDescriptionRecovery:"Recovery weapons are thrown weapons designed to return to the thrower when they miss the target. When you make an unsuccessful thrown Strike with this weapon, it flies back to your hand after the Strike is complete, allowing you to try again. If your hands are full when the weapon returns, it falls to the ground in your space.",TraitDescriptionReflection:"A creature with this trait has the reflection versatile heritage. Reflections are beings who are copies of living people, whether through cloning, planar duplication, or another mechanism. An ability with this trait can be used or selected only by reflections.",TraitDescriptionRelic:"An item with the relic trait grows in power with its wielder.",TraitDescriptionReload:"While all weapons need some amount of time to get into position, many ranged weapons also need to be loaded and reloaded. This entry indicates how many Interact actions it takes to reload such weapons. This can be 0 if drawing ammunition and firing the weapon are part of the same action. If an item takes 2 or more actions to reload, the GM determines whether they must be performed together as an activity, or you can spend some of those actions during one turn and the rest during your next turn.",TraitDescriptionRepeating:"A repeating weapon is typically a type of crossbow that has a shorter reload time. These weapons can't be loaded with individual bolts like other crossbows; instead, they require a magazine of specialized ammunition to be loaded into a special slot. Once that magazine is in place, the ammunition is automatically loaded each time the weapon is cocked to fire, reducing its reload to the value in its reload entry (typically 0). When the ammunition runs out, a new magazine must be loaded, which requires a free hand and 3 Interact actions (to remove the old magazine, retrieve the new magazine, and slot the new magazine in place). These actions don't need to be consecutive.",TraitDescriptionResonant:"This weapon can channel energy damage. You gain the Conduct Energy free action while wielding a resonant weapon.",TraitDescriptionRevelation:"Effects with this trait see things as they truly are.",TraitDescriptionRogue:"This indicates abilities from the rogue class.",TraitDescriptionSaggorak:"Ancient dwarven blacksmiths in Saggorak designed a series of spectacularly powerful runes. Only someone with legendary proficiency in Crafting, or a well-versed dwarven crafter from the city of Kovlar, can apply, transfer, or remove a rune with the Saggorak trait. Because of their considerable power, all Saggorak runes take up two property rune slots, and consequently they can be applied only to armor and weapons with at least a +2 potency rune.",TraitDescriptionSanctified:"If you are holy or unholy, your sanctified actions and spells gain the same trait.",TraitDescriptionScatter:"This weapon fires a cluster of pellets in a wide spray. Scatter always has an area listed with it, indicating the radius of the spray. On a hit, the primary target of attacks with a scatter weapon take the listed damage, and the target and all other creatures within the listed radius around it take 1 point of splash damage per weapon damage die.",TraitDescriptionScroll:"A scroll contains a single spell you can cast without a spell slot.",TraitDescriptionScrying:"A scrying effect lets you see, hear, or otherwise get sensory information from a distance using a sensor or apparatus, rather than your own eyes and ears.",TraitDescriptionSecret:"The GM rolls the check for this ability in secret.",TraitDescriptionShadow:"This magic involves shadows or the energy of the Netherworld.",TraitDescriptionShieldThrow:"A shield with this trait is designed to be thrown as a ranged attack.",TraitDescriptionShisk:"Secretive humanoids covered in bony plumage that reside underground.",TraitDescriptionShoony:"A creature with this trait is a member of the shoony ancestry.",TraitDescriptionShove:"You can use this weapon to Shove with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Shove using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionSkeleton:"This undead is made by animating a dead creature's skeleton with void energy. An ability with this trait can be used or selected only by skeletons.",TraitDescriptionSkill:"A general feat with the skill trait improves your skills and their actions or gives you new actions for a skill. A feat with this trait can be selected when a class grants a skill feat or general feat. Archetype feats with the skill trait can be selected in place of a skill feat if you have that archetype's dedication feat.",TraitDescriptionSleep:"This effect can cause a creature to fall asleep or get drowsy.",TraitDescriptionSnare:"Traps typically made by rangers, snares follow special rules that allow them to be constructed quickly and used on the battlefield.",TraitDescriptionSocial:"Actions and abilities with the social trait can be used only while a vigilante is in their social identity.",TraitDescriptionSonic:"An effect with the sonic trait functions only if it makes sound, meaning it has no effect in an area of silence or in a vacuum. This is different from an auditory spell, which is effective only if the target can hear it. A sonic effect might deal sonic damage.",TraitDescriptionSorcerer:"This indicates abilities from the sorcerer class.",TraitDescriptionSpellgun:"The spellgun trait appears on items that can generate a magical effect that flies out like a bullet. You can make either a spell attack roll with a spellgun or a ranged attack roll using your proficiency with simple firearms. Spellguns have a range increment, which applies regardless of which type of attack roll you make. Though you can use your modifier for simple firearms, a spellgun isn't actually a firearm. You don't get the damage of a firearm Strike, nor other benefits like critical specialization. Similarly, you can't load or reload a spellgun, affix talismans to one, make a spellgun Strike as part of an action that lets you make a firearm Strike, and so on.",TraitDescriptionSpellheart:"Spellhearts are permanent items that work similarly to talismans. You affix a spellheart using the Affix a Spellheart activity, which is otherwise identical to Affix a Talisman. The limit of one talisman per item remains\u2014an item can have one spellheart or one talisman, not both. When casting a cantrip from a spellheart, you can use your own spell attack roll or spell DC if it's higher. Crafting a spellheart requires the spells the spellheart can cast. For example, a major five-feather wreath requires air walk, gale blast, and wall of wind.",TraitDescriptionSpellshape:"Spellshape actions tweak the properties of your spells. You must use a spellshape action directly before casting the spell you want to alter. If you use any action (including free actions and reactions) other than casting a spell directly after, you waste the benefits of the spellshape action. The benefit is also lost if your turn ends before you cast the spell. Any additional effects added by a spellshape action are part of the spell's effect, not of the spellshape action itself.",TraitDescriptionSplash:"When you use a thrown weapon with the splash trait, you don't add your Strength modifier to the damage roll. If an attack with a splash weapon fails, succeeds, or critically succeeds, all creatures within 5 feet of the target (including the target) take the listed splash damage. On a failure (but not a critical failure), the target of the attack still takes the splash damage. Add splash damage together with the initial damage against the target before applying the target's weaknesses or resistances. You don't multiply splash damage on a critical hit.",TraitDescriptionSplash10:"When you use a thrown weapon with the splash trait, you don't add your Strength modifier to the damage roll. If an attack with a splash weapon fails, succeeds, or critically succeeds, all creatures within 10 feet of the target (including the target) take the listed splash damage. On a failure (but not a critical failure), the target of the attack still takes the splash damage. Add splash damage together with the initial damage against the target before applying the target's weaknesses or resistances. You don't multiply splash damage on a critical hit.",TraitDescriptionSpirit:"Effects with this trait can affect creatures with spiritual essence and might deal spirit damage. A creature with this trait is defined by its spiritual essence. Spirit creatures often lack a material form.",TraitDescriptionSprite:"A family of diminutive winged fey with a strong connection to primal magic.",TraitDescriptionStaff:"This magic item holds spells of a particular theme and allows a spellcaster to cast additional spells by preparing the staff.",TraitDescriptionStance:"A stance is a general combat strategy that you enter by using an action with the stance trait, and that you remain in for some time. A stance lasts until you get knocked out, until its requirements (if any) are violated, until the encounter ends, or until you enter a new stance, whichever comes first. After you use an action with the stance trait, you can't use another one for 1 round. You can enter or be in a stance only in encounter mode.",TraitDescriptionSteam:"Items with this trait are powered by engines that boil water to produce steam and move their components.",TraitDescriptionStrix:"Winged humanoids, most of whom live in and around Cheliax.",TraitDescriptionStructure:"An item with the structure trait creates a magical building or other structure when activated. The item must be activated on a plot of land free of other structures. The structure adapts to the natural terrain, adopting the structural requirements for being built there. The structure adjusts around small features such as ponds or spires of rock, but it can't be created on water or other nonsolid surfaces. If activated on snow, sand dunes, or other soft surfaces with a solid surface underneath, the structure's foundation (if any) reaches the solid ground. If an item with this trait is activated on a solid but unstable surface, such as a swamp or an area plagued by tremors, roll a @Check[type:flat|dc:3] each day; on a failure, the structure begins to sink or collapse. The structure doesn't harm creatures within the area when it appears, and it can't be created within a crowd or in a densely populated area. Any creature inadvertently caught inside the structure when the item is activated ends up unharmed inside the complete structure and always has a clear path of escape. A creature inside the structure when the activation ends isn't harmed, and it lands harmlessly on the ground if it was on an upper level of the structure.",TraitDescriptionSubjectiveGravity:"On planes with this trait, all bodies of mass can be centers of gravity with the same amount of force, but only if a non-mindless creature wills it.",TraitDescriptionSubtle:"A spell with the subtle trait can be cast without incantations and doesn't have obvious manifestations.",TraitDescriptionSuli:"Sulis are planar scions descended from jann.",TraitDescriptionSummon:"Spells with the summon trait can conjure creatures, typically ones with a particular trait. Such creatures can be found in Monster Core and similar books. Unless noted otherwise, the creature must be common, it gains the summoned trait, and it must appear in an unoccupied space in range large enough to contain it. The highest level of creature the spell can summon depends on the rank of the spell, as listed below. The spell can still summon a creature of a lower level if you so choose. These rules apply only to spells that have the summon trait; other spells that call or conjure items or beings but that don't have the trait, like summon instrument, work as explained in the spell.",TraitDescriptionSummoned:"A creature called by a spell or effect gains the summoned trait. A summoned creature can't summon other creatures, create things of value, or cast spells that require a cost. It has the minion trait. If it tries to Cast a Spell of equal or higher rank than the spell that summoned it, it overpowers the summoning magic, causing its own spell to fail and the summon spell to end. Otherwise, the summoned creature uses the standard abilities for a creature of its kind. It generally attacks your enemies to the best of its ability. If you can communicate with it, you can attempt to command it, but the GM determines the degree to which it follows your commands. Immediately when you finish Casting the Spell, the summoned creature uses its 2 actions for that turn. A spawn or other creature generated from a summoned creature returns to its unaltered state (usually a corpse in the case of spawn) once the summoned creature is gone. If it's unclear what this state would be, the GM decides. Summoned creatures can be banished by various spells and effects. They are automatically banished if reduced to 0 Hit Points or if the spell that called them ends.",TraitDescriptionSummoner:"This indicates abilities from the Summoner class.",TraitDescriptionSwashbuckler:"This indicates abilities from the Swashbuckler class.",TraitDescriptionSweep:"This weapon makes wide sweeping or spinning attacks, making it easier to attack multiple enemies. When you attack with this weapon, you gain a +1 circumstance bonus to your attack roll if you already attempted to attack a different target this turn using this weapon.",TraitDescriptionSylph:"A type of geniekin descended from a being from the Plane of Air.",TraitDescriptionTalisman:"A talisman is a small object affixed to armor, a shield, or a weapon (called the affixed item). You must be wielding or wearing an item to activate a talisman attached to it. Once activated, a talisman burns out permanently.",TraitDescriptionTalos:"Taloses are planar scions descended from zuhras.",TraitDescriptionTandem:"Actions with this trait involve you and your eidolon acting in concert. You can't use a tandem action if either you or your eidolon can't act, if you haven't Manifested your Eidolon, or if you've Manifested your Eidolon in a way where it isn't a separate entity (such as with the Meld into Eidolon feat). Tandem actions often let both you and your eidolon take separate actions, but these must be actions taken separately by you and your eidolon; you can't use a tandem action to take another tandem action.",TraitDescriptionTattoo:"A tattoo is a type of item that is drawn or cut into a creature's skin and usually takes the form of images or symbols.",TraitDescriptionTea:"Magic tea is a type of potion. It activates when you drink it, which uses it up. Magic tea has the potion and tea traits. When you craft a dose of magic tea, the raw materials you supply are in the form of unusual and costly tea leaves. The process of crafting magic tea includes infusing the leaves with magical reagents, purifying the water, and steeping the tea in the water, resulting in what's essentially a particularly delicious-tasting potion. You can activate magic tea with an Interact action as you drink it or feed it to another creature, as if it were a potion. You can also activate magic tea with a 10-minute activity that requires sterling tea ware (these artisan's tools can be shared by up to four people who take this activity simultaneously) to prepare the tea and then consume it or present it to someone during a short tea ceremony, after which the magic tea's effects begin; activating magic tea in this way enhances its effect, as detailed in each entry's Tea Ceremony.
Once you drink a dose of magic tea, you're temporarily immune to that particular type of magic tea for 24 hours.
",TraitDescriptionTech:"Items with this trait are associated with the technology of Numeria.",TraitDescriptionTelepathy:"A creature with telepathy can communicate mentally with creatures. This doesn't give any special access to their thoughts, and communicates no more information than normal speech would.",TraitDescriptionTeleportation:"Teleportation effects allow you to instantaneously move from one point in space to another. Teleportation does not usually trigger reactions based on movement.",TraitDescriptionTengu:"A creature with this trait is a member of the tengu ancestry. Tengus are humanoids who resemble birds. An ability with this trait can be used or selected only by tengus. An item with this trait is created and used by tengus.",TraitDescriptionTethered:"This weapon is attached to a length of rope or chain that allows you to retrieve it after it has left your hand. If you have a free hand while wielding this weapon, you can use an Interact action to pull the weapon back into your grasp after you have thrown it as a ranged attack or after it has been disarmed (unless it is being held by another creature).",TraitDescriptionThaumaturge:"This indicates abilities from the thaumaturge class.",TraitDescriptionThrown:"You can throw this weapon as a ranged attack. A thrown weapon adds your Strength modifier to damage just like a melee weapon does. When this trait appears on a melee weapon, it also includes the range increment.",TraitDescriptionTraining:"A training weapon is designed to be used when training an animal to participate in combat by identifying the target for the animal to attack. Striking a creature with a training weapon gives your animal companion or your bonded animal a +1 circumstance bonus to its next attack roll against that target.",TraitDescriptionTrap:"A hazard or item with this trait is constructed to hinder interlopers.",TraitDescriptionTrip:"You can use this weapon to Trip with the Athletics skill even if you don't have a free hand. This uses the weapon's reach (if different from your own) and adds the weapon's item bonus to attack rolls as an item bonus to the Athletics check. If you critically fail a check to Trip using the weapon, you can drop the weapon to take the effects of a failure instead of a critical failure.",TraitDescriptionTrueName:"Certain spells, feats, and items have the true name trait. This trait means they require you to know a creature's true name to use them.",TraitDescriptionTwin:"These weapons are used as a pair, complementing each other. When you attack with a twin weapon, you add a circumstance bonus to the damage roll equal to the weapon's number of damage dice if you have previously attacked with a different weapon of the same type this turn. The weapons must be of the same type to benefit from this trait, but they don't need to have the same runes.",TraitDescriptionTwoHand:"This weapon can be wielded with two hands. Doing so changes its weapon damage die to the indicated value. This change applies to all the weapon's damage dice, such as those from striking runes.",TraitDescriptionUnarmed:"An unarmed attack uses your body rather than a manufactured weapon. An unarmed attack isn't a weapon, though it's categorized with weapons for weapon groups, and it might have weapon traits. Since it's part of your body, an unarmed attack can't be Disarmed. It also doesn't take up a hand, though a fist or other grasping appendage follows the same rules as a free-hand weapon.",TraitDescriptionUncommon:"Something of uncommon rarity requires special training or comes from a particular culture or part of the world. Some character choices give access to uncommon options, and the GM can choose to allow access for anyone. Less is known about uncommon creatures than common creatures. They typically can't be summoned. The DC of Recall Knowledge checks related to these creature is increased by 2.",TraitDescriptionUndead:"Once living, these creatures were infused after death with void energy and soul-corrupting unholy magic. When reduced to 0 Hit Points, an undead creature is destroyed. Undead creatures are damaged by vitality energy and are healed by void energy, and don't benefit from healing vitality effects.",TraitDescriptionUndine:"A type of geniekin descended from a being from the Plane of Water.",TraitDescriptionUnholy:"Effects with the unholy trait are tied to powerful magical forces of cruelty and sin. They often have stronger effects on holy creatures. Creatures with this trait are strongly devoted to unholy causes, and often have weakness to holy. If a creature with weakness to unholy uses an unholy item or effect, it takes damage from its weakness.",TraitDescriptionUnique:"A rules element with this trait is one-of-a-kind. The DC of Recall Knowledge checks related to creatures with this trait is increased by 10.",TraitDescriptionUnstable:"Unstable actions rely on experimental functions of your innovation that even you can't fully predict. After an unstable action is used on an innovation, using another one is dangerous.",TraitDescriptionVanara:"An inquisitive ancestry with primate-like features and prehensile tails.",TraitDescriptionVehicular:"A vehicular weapon is attached to a vehicle or worn by a mount and can typically only be wielded by the driver of the vehicle or the mount's primary rider. The driver or rider can control a vehicular weapon with the same hands they use to steer the vehicle or guide the mount. A vehicular weapon can be Disarmed by knocking the controls (typically reins for a mount or a steering device for a vehicle) out of the wielder's hands.",TraitDescriptionVersatile:"A versatile weapon can be used to deal a different type of damage than that listed in the Damage entry. This trait indicates the alternate damage type. For instance, a piercing weapon that is versatile S can be used to deal piercing or slashing damage. You choose the damage type each time you make an attack.",TraitDescriptionVirulent:"Afflictions with the virulent trait are harder to remove. You must succeed at two consecutive saves to reduce a virulent affliction's stage by 1. A critical success reduces a virulent affliction's stage by only 1 instead of by 2.",TraitDescriptionVishkanya:"An ancestry with snake-like features and powerful venom.",TraitDescriptionVisual:"A visual effect can affect only creatures that can see it. This applies only to visible parts of the effect, as determined by the GM.",TraitDescriptionVitality:"Effects with this trait heal living creatures with energy from the Forge of Creation, deal vitality energy damage to undead, or manipulate vitality energy.",TraitDescriptionVoid:"Effects with this trait heal undead creatures with void energy, deal void damage to living creatures, or manipulate void energy.",TraitDescriptionVolley:"This ranged weapon is less effective at close distances. Your attacks against targets that are at a distance within the range listed take a -2 penalty.",TraitDescriptionWand:"A wand contains a single spell which you can cast once per day.",TraitDescriptionWater:"Effects with the water trait either manipulate or conjure water. Those that manipulate water have no effect in an area without water. Creatures with this trait consist primarily of water or have a magical connection to the element.",TraitDescriptionWildHunt:"Creatures with the wild hunt trait are never below 14th level. They possess greater darkvision, greensight, planar acclimation, wild gaze, instinctive cooperation, weakness to cold iron, the ability to speak with plants and animals, and their own specific wild hunt link.",TraitDescriptionWitch:"This indicates abilities from the witch class.",TraitDescriptionWizard:"This indicates abilities from the wizard class.",TraitDescriptionWood:"Effects with the wood trait conjure or manipulate wood. Those that manipulate wood have no effect in an area without wood. Creatures with this trait consist primarily of wood or have a connection to magical wood.",TraitCenser:"Censer",TraitDetection:"Detection",TraitDeviant:"Deviant",TraitDevil:"Devil",TraitDhampir:"Dhampir",TraitDinosaur:"Dinosaur",TraitDisarm:"Disarm",TraitDisease:"Disease",TraitDiv:"Div",TraitDivine:"Divine",TraitDoubleBarrel:"Double Barrel",TraitDowntime:"Downtime",TraitDragon:"Dragon",TraitDream:"Dream",TraitDromaar:"Dromaar",TraitDrow:"Drow",TraitDrug:"Drug",TraitDruid:"Druid",TraitDuergar:"Duergar",TraitDuskwalker:"Duskwalker",TraitDwarf:"Dwarf",TraitEachRuneAppliedToASeparateItemThatHasPockets:"Each rune applied to a separate item that has pockets",TraitEarth:"Earth",TraitEidolon:"Eidolon",TraitElectricity:"Electricity",TraitElemental:"Elemental",TraitElf:"Elf",TraitElixir:"Elixir",TraitEmotion:"Emotion",TraitEnergy:"Energy",TraitEntrenchMelee:"Entrench Melee",TraitEntrenchRanged:"Entrench Ranged",TraitEnvironmental:"Environmental",TraitEsoterica:"Esoterica",TraitEtchedOntoABludgeoningWeapon:"Etched on Bludgeoning Weapon",TraitEtchedOntoAClanDagger:"Etched on Clan Dagger",TraitEtchedOntoAMeleeWeapon:"Etched on Melee Weapon",TraitEtchedOntoAMeleeWeaponMonk:"Etched onto a melee weapon with the monk trait",TraitEtchedOntoAPiercingOrSlashingMeleeWeapon:"Etched on Piercing/Slashing Melee Weapon",TraitEtchedOntoAPiercingOrSlashingWeapon:"Etched on Piercing/Slashing Weapon",TraitEtchedOntoAShield:"Etched onto a Shield",TraitEtchedOntoASlashingMeleeWeapon:"Etched on Slashing Melee Weapon",TraitEtchedOntoAThrownWeapon:"Etched on Thrown Weapon",TraitEtchedOntoAWeapon:"Etched onto a Weapon",TraitEtchedOntoAWeaponWOAnarchicRune:"Etched on Weapon w/o Anarchic Rune",TraitEtchedOntoAWeaponWOAxiomaticRune:"Etched on Weapon w/o Axiomatic Rune",TraitEtchedOntoAWeaponWOHolyRune:"Etched on Weapon that isn't Holy",TraitEtchedOntoAWeaponWOUnholyRune:"Etched on Weapon that isn't Unholy",TraitEtchedOntoArmor:"Etched onto Armor",TraitEtchedOntoHeavyArmor:"Etched onto Heavy Armor",TraitEtchedOntoLightArmor:"Etched onto Light Armor",TraitEtchedOntoLightMedNMArmor:"Etched on L/M Nonmetal Armor",TraitEtchedOntoMedHeavyArmor:"Etched onto Medium or Heavy Armor",TraitEtchedOntoMediumHeavyMetalArmor:"Etched onto Medium or Heavy Metal Armor",TraitEtchedOntoMetalArmor:"Etched onto Metal Armor",TraitEthereal:"Ethereal",TraitEvolution:"Evolution",TraitExpandable:"Expandable",TraitExploration:"Exploration",TraitExtradimensional:"Extradimensional",TraitFatal:"Fatal",TraitFatalAim:"Fatal Aim",TraitFatalAimD10:"Fatal Aim d10",TraitFatalAimD12:"Fatal Aim d12",TraitFatalD10:"Fatal d10",TraitFatalD12:"Fatal d12",TraitFatalD8:"Fatal d8",TraitFear:"Fear",TraitFetchling:"Fetchling",TraitFey:"Fey",TraitFiend:"Fiend",TraitFighter:"Fighter",TraitFigurehead:"Figurehead",TraitFinesse:"Finesse",TraitFinisher:"Finisher",TraitFinite:"Finite",TraitFire:"Fire",TraitFleshwarp:"Fleshwarp",TraitFlexible:"Flexible",TraitFlourish:"Flourish",TraitFocus:"Focus",TraitFocused:"Focused",TraitFoldaway:"Foldaway",TraitForce:"Force",TraitForceful:"Forceful",TraitFormian:"Formian",TraitFortune:"Fortune",TraitFreeHand:"Free-Hand",TraitFulu:"Fulu",TraitFungus:"Fungus",TraitGadget:"Gadget",TraitGanzi:"Ganzi",TraitGeneral:"General",TraitGenie:"Genie",TraitGeniekin:"Geniekin",TraitGhoran:"Ghoran",TraitGhost:"Ghost",TraitGhoul:"Ghoul",TraitGhul:"Ghul",TraitGiant:"Giant",TraitGnoll:"Gnoll",TraitGnome:"Gnome",TraitGoblin:"Goblin",TraitGolem:"Golem",TraitGoloma:"Goloma",TraitGrapple:"Grapple",TraitGremlin:"Gremlin",TraitGrimoire:"Grimoire",TraitGrioth:"Grioth",TraitGrippli:"Grippli",TraitGunslinger:"Gunslinger",TraitHag:"Hag",TraitHalcyon:"Halcyon",TraitHalfling:"Halfling",TraitHampering:"Hampering",TraitHantu:"Hantu",TraitHarnessed:"Harnessed",TraitHarrowCourt:"Harrow Court",TraitHaunt:"Haunt",TraitHealing:"Healing",TraitHefty2:"Hefty 2",TraitHeldOneHand:"Held in 1 hand",TraitHeldOneHandFreeStanding:"Held in 1 hand or free-standing",TraitHeldOneTwoHands:"Held in 1 or 2 hands",TraitHeldTwoHands:"Held in 2 hands",TraitHerald:"Herald",TraitHeritage:"Heritage",TraitHex:"Hex",TraitHindering:"Hindering",TraitHobgoblin:"Hobgoblin",TraitHoly:"Holy",TraitHryngar:"Hryngar",TraitHuman:"Human",TraitHumanoid:"Humanoid",TraitIfrit:"Ifrit",TraitIkeshti:"Ikeshti",TraitIllusion:"Illusion",TraitImpulse:"Impulse",TraitIncapacitation:"Incapacitation",TraitIncarnate:"Incarnate",TraitIncorporeal:"Incorporeal",TraitInevitable:"Inevitable",TraitInfused:"Infused",TraitInfusion:"Infusion",TraitIngested:"Ingested",TraitInhaled:"Inhaled",TraitInjection:"Injection",TraitInjury:"Injury",TraitInscribed:"Inscribed",TraitIntegrated1d6B:"Integrated 1d6 B",TraitIntegrated1d6P:"Integrated 1d6 P",TraitIntegrated1d6S:"Integrated 1d6 S",TraitIntegrated1d6SVersatileP:"Integrated 1d6 S (Versatile P)",TraitIntelligent:"Intelligent",TraitInteract:"Interact",TraitInventor:"Inventor",TraitInvested:"Invested",TraitInvestigator:"Investigator",TraitJousting:"Jousting",TraitJoustingD6:"Jousting d6",TraitKaiju:"Kaiju",TraitKami:"Kami",TraitKashrishi:"Kashrishi",TraitKickback:"Kickback",TraitKineticist:"Kineticist",TraitKingdom:"Kingdom",TraitKitsune:"Kitsune",TraitKobold:"Kobold",TraitKovintus:"Kovintus",TraitLaminar:"Laminar",TraitLaunching:"Launching",TraitLeshy:"Leshy",TraitLight:"Light",TraitLilu:"Lilu",TraitLineage:"Lineage",TraitLinguistic:"Linguistic",TraitLitany:"Litany",TraitLizardfolk:"Lizardfolk",TraitLocathah:"Locathah",TraitLozenge:"Lozenge",TraitMagic:"Magic",TraitMagical:"Magical",TraitMagus:"Magus",TraitManipulate:"Manipulate",TraitMechanical:"Mechanical",TraitMental:"Mental",TraitMerfolk:"Merfolk",TraitMetal:"Metal",TraitMindless:"Mindless",TraitMindshift:"Mindshift",TraitMinion:"Minion",TraitMisfortune:"Misfortune",TraitMisfortuneEffects:"Misfortune Effects",TraitMissive:"Missive",TraitModification:"Modification",TraitModular:"Modular B, P, or S",TraitMonitor:"Monitor",TraitMonk:"Monk",TraitMorlock:"Morlock",TraitMorph:"Morph",TraitMortic:"Mortic",TraitMounted:"Mounted",TraitMove:"Move",TraitMulticlass:"Multiclass",TraitMummy:"Mummy",TraitMunavri:"Munavri",TraitMutagen:"Mutagen",TraitMutant:"Mutant",TraitNaari:"Naari",TraitNagaji:"Nagaji",TraitNephilim:"Nephilim",TraitNindoru:"Nindoru",TraitNoisy:"Noisy",TraitNonlethal:"Nonlethal",TraitNymph:"Nymph",TraitOath:"Oath",TraitOccult:"Occult",TraitOil:"Oil",TraitOlfactory:"Olfactory",TraitOni:"Oni",TraitOoze:"Ooze",TraitOpen:"Open",TraitOracle:"Oracle",TraitOrc:"Orc",TraitOread:"Oread",TraitOverflow:"Overflow",TraitPaaridar:"Paaridar",TraitParry:"Parry",TraitPervasiveMagic:"Pervasive Magic",TraitPetitioner:"Petitioner",TraitPhantom:"Phantom",TraitPhysical:"Physical",TraitPiercing:"Piercing",TraitPlant:"Plant",TraitPoison:"Poison",TraitPolymorph:"Polymorph",TraitPonderous:"Ponderous",TraitPoppet:"Poppet",TraitPortable:"Portable",TraitPossession:"Possession",TraitPotion:"Potion",TraitPrecious:"Precious",TraitPrediction:"Prediction",TraitPress:"Press",TraitPrimal:"Primal",TraitProcessed:"Processed",TraitPropulsive:"Propulsive",TraitProtean:"Protean",TraitPsyche:"Psyche",TraitPsychic:"Psychic",TraitPsychopomp:"Psychopomp",TraitQlippoth:"Qlippoth",TraitRadiation:"Radiation",TraitRage:"Rage",TraitRakshasa:"Rakshasa",TraitRange:"Range",TraitRange10:"Range 10 feet",TraitRange100:"Range 100 feet",TraitRange110:"Range 110 feet",TraitRange120:"Range 120 feet",TraitRange130:"Range 130 feet",TraitRange140:"Range 140 feet",TraitRange15:"Range 15 feet",TraitRange150:"Range 150 feet",TraitRange160:"Range 160 feet",TraitRange170:"Range 170 feet",TraitRange180:"Range 180 feet",TraitRange190:"Range 190 feet",TraitRange20:"Range 20 feet",TraitRange200:"Range 200 feet",TraitRange210:"Range 210 feet",TraitRange220:"Range 220 feet",TraitRange230:"Range 230 feet",TraitRange240:"Range 240 feet",TraitRange25:"Range 25 feet",TraitRange250:"Range 250 feet",TraitRange260:"Range 260 feet",TraitRange270:"Range 270 feet",TraitRange280:"Range 280 feet",TraitRange290:"Range 290 feet",TraitRange30:"Range 30 feet",TraitRange300:"Range 300 feet",TraitRange310:"Range 310 feet",TraitRange320:"Range 320 feet",TraitRange40:"Range 40 feet",TraitRange5:"Range 5 feet",TraitRange50:"Range 50 feet",TraitRange500:"Range 500 feet",TraitRange60:"Range 60 feet",TraitRange70:"Range 70 feet",TraitRange80:"Range 80 feet",TraitRange90:"Range 90 feet",TraitRangeIncrement10:"Range Increment 10 feet",TraitRangeIncrement100:"Range Increment 100 feet",TraitRangeIncrement110:"Range Increment 110 feet",TraitRangeIncrement120:"Range Increment 120 feet",TraitRangeIncrement130:"Range Increment 130 feet",TraitRangeIncrement140:"Range Increment 140 feet",TraitRangeIncrement15:"Range Increment 15 feet",TraitRangeIncrement150:"Range Increment 150 feet",TraitRangeIncrement160:"Range Increment 160 feet",TraitRangeIncrement170:"Range Increment 170 feet",TraitRangeIncrement180:"Range Increment 180 feet",TraitRangeIncrement190:"Range Increment 190 feet",TraitRangeIncrement20:"Range Increment 20 feet",TraitRangeIncrement200:"Range Increment 200 feet",TraitRangeIncrement210:"Range Increment 210 feet",TraitRangeIncrement220:"Range Increment 220 feet",TraitRangeIncrement230:"Range Increment 230 feet",TraitRangeIncrement240:"Range Increment 240 feet",TraitRangeIncrement25:"Range Increment 25 feet",TraitRangeIncrement250:"Range Increment 250 feet",TraitRangeIncrement260:"Range Increment 260 feet",TraitRangeIncrement270:"Range Increment 270 feet",TraitRangeIncrement280:"Range Increment 280 feet",TraitRangeIncrement290:"Range Increment 290 feet",TraitRangeIncrement30:"Range Increment 30 feet",TraitRangeIncrement300:"Range Increment 300 feet",TraitRangeIncrement310:"Range Increment 310 feet",TraitRangeIncrement320:"Range Increment 320 feet",TraitRangeIncrement40:"Range Increment 40 feet",TraitRangeIncrement5:"Range Increment 5 feet",TraitRangeIncrement50:"Range Increment 50 feet",TraitRangeIncrement60:"Range Increment 60 feet",TraitRangeIncrement70:"Range Increment 70 feet",TraitRangeIncrement75:"Range Increment 75 feet",TraitRangeIncrement80:"Range Increment 80 feet",TraitRangeIncrement90:"Range Increment 90 feet",TraitRangedTrip:"Ranged Trip",TraitRanger:"Ranger",TraitRare:"Rare",TraitRatajin:"Ratajin",TraitRatfolk:"Ratfolk",TraitRazing:"Razing",TraitReach:"Reach",TraitReach0:"Reach 0 feet",TraitReach10:"Reach 10 feet",TraitReach100:"Reach 100 feet",TraitReach120:"Reach 120 feet",TraitReach1000:"Reach 1,000 feet",TraitReach15:"Reach 15 feet",TraitReach20:"Reach 20 feet",TraitReach200:"Reach 200 feet",TraitReach25:"Reach 25 feet",TraitReach30:"Reach 30 feet",TraitReach40:"Reach 40 feet",TraitReach50:"Reach 50 feet",TraitReach60:"Reach 60 feet",TraitReckless:"Reckless",TraitRecovery:"Recovery",TraitReflection:"Reflection",TraitRelic:"Relic",TraitReload:"Reload",TraitReload0:"Reload 0",TraitReload1:"Reload 1",TraitReload1Min:"Reload 1 min",TraitReload2:"Reload 2",TraitRepeating:"Repeating",TraitResonant:"Resonant",TraitRevelation:"Revelation",TraitRogue:"Rogue",TraitSaggorak:"Saggorak",TraitSahkil:"Sahkil",TraitSamsaran:"Samsaran",TraitSanctified:"Sanctified",TraitScatter:"Scatter",TraitScatter10:"Scatter 10",TraitScatter15:"Scatter 15",TraitScatter20:"Scatter 20",TraitScatter5:"Scatter 5",TraitScroll:"Scroll",TraitScrying:"Scrying",TraitSeaDevil:"Sea Devil",TraitSecret:"Secret",TraitSerpentfolk:"Serpentfolk",TraitSeugathi:"Seugathi",TraitSewnIntoClothing:"Sewn Into Clothing",TraitShabti:"Shabti",TraitShadow:"Shadow",TraitShieldThrow20:"Shield Throw 20 ft",TraitShieldThrow30:"Shield Throw 30 ft",TraitShisk:"Shisk",TraitShobhad:"Shobhad",TraitShoony:"Shoony",TraitShove:"Shove",TraitSiktempora:"Siktempora",TraitSkeleton:"Skeleton",TraitSkelm:"Skelm",TraitSkill:"Skill",TraitSkulk:"Skulk",TraitSlashing:"Slashing",TraitSleep:"Sleep",TraitSnare:"Snare",TraitSocial:"Social",TraitSonic:"Sonic",TraitSorcerer:"Sorcerer",TraitSoulbound:"Soulbound",TraitSpellDeflection:"Spell Deflection",TraitSpellgun:"Spellgun",TraitSpellheart:"Spellheart",TraitSpellshape:"Spellshape",TraitSpellshot:"Spellshot",TraitSpirit:"Spirit",TraitSplash:"Splash",TraitSplash10:"Splash 10 ft",TraitSporeborn:"Sporeborn",TraitSpriggan:"Spriggan",TraitSprite:"Sprite",TraitStaff:"Staff",TraitStamina:"Stamina",TraitStance:"Stance",TraitSteam:"Steam",TraitStheno:"Stheno",TraitStrix:"Strix",TraitStructure:"Structure",TraitSubjectiveGravity:"Subjective Gravity",TraitSubtle:"Subtle",TraitSuli:"Suli",TraitSummon:"Summon",TraitSummoned:"Summoned",TraitSummoner:"Summoner",TraitSwarm:"Swarm",TraitSwashbuckler:"Swashbuckler",TraitSweep:"Sweep",TraitSylph:"Sylph",TraitTalisman:"Talisman",TraitTalos:"Talos",TraitTandem:"Tandem",TraitTane:"Tane",TraitTanggal:"Tanggal",TraitTattoo:"Tattoo",TraitTattooedOnTheBody:"Tattooed on the Body",TraitTea:"Tea",TraitTech:"Tech",TraitTechnological:"Technological",TraitTelepathy:"Telepathy",TraitTeleportation:"Teleportation",TraitTengu:"Tengu",TraitTethered:"Tethered",TraitThaumaturge:"Thaumaturge",TraitThrown:"Thrown",TraitThrown10:"Thrown 10 ft.",TraitThrown100:"Thrown 100 ft.",TraitThrown15:"Thrown 15 ft.",TraitThrown20:"Thrown 20 ft.",TraitThrown200:"Thrown 200 ft.",TraitThrown30:"Thrown 30 ft.",TraitThrown40:"Thrown 40 ft.",TraitThrown60:"Thrown 60 ft.",TraitThrown80:"Thrown 80 ft.",TraitTime:"Time",TraitTitan:"Titan",TraitTouched:"Touched",TraitTraining:"Training",TraitTrap:"Trap",TraitTrip:"Trip",TraitTroll:"Troll",TraitTroop:"Troop",TraitTrueName:"True Name",TraitTwin:"Twin",TraitTwoHand:"Two-Hand",TraitTwoHandD10:"Two-Hand d10",TraitTwoHandD12:"Two-Hand d12",TraitTwoHandD6:"Two-Hand d6",TraitTwoHandD8:"Two-Hand d8",TraitUnarmed:"Unarmed",TraitUncommon:"Uncommon",TraitUndead:"Undead",TraitUndine:"Undine",TraitUnholy:"Unholy",TraitUnique:"Unique",TraitUnstable:"Unstable",TraitUntyped:"Untyped",TraitUrdefhan:"Urdefhan",TraitVampire:"Vampire",TraitVanara:"Vanara",TraitVehicular:"Vehicular",TraitVelstrac:"Velstrac",TraitVersatile:"Versatile",TraitVersatileAcid:"Versatile Acid",TraitVersatileB:"Versatile B",TraitVersatileCold:"Versatile Cold",TraitVersatileElectricity:"Versatile Electricity",TraitVersatileFire:"Versatile Fire",TraitVersatileForce:"Versatile Force",TraitVersatileP:"Versatile P",TraitVersatilePoison:"Versatile Poison",TraitVersatileS:"Versatile S",TraitVersatileSonic:"Versatile Sonic",TraitVersatileSpirit:"Versatile Spirit",TraitVersatileVitality:"Versatile Vitality",TraitVersatileVoid:"Versatile Void",TraitVersatileX:"Versatile {x}",TraitVigilante:"Vigilante",TraitVirulent:"Virulent",TraitVishkanya:"Vishkanya",TraitVisual:"Visual",TraitVitality:"Vitality",TraitVoid:"Void",TraitVolley:"Volley",TraitVolley20:"Volley 20 ft.",TraitVolley30:"Volley 30 ft.",TraitVolley50:"Volley 50 ft.",TraitVorpalFear:"Vorpal Fear",TraitWand:"Wand",TraitWater:"Water",TraitWayang:"Wayang",TraitWeapons:"Weapons",TraitWerecreature:"Werecreature",TraitWight:"Wight",TraitWildHunt:"Wild Hunt",TraitWitch:"Witch",TraitWizard:"Wizard",TraitWood:"Wood",TraitWorn:"Worn",TraitWornAmulet:"Worn Amulet",TraitWornAndAttachedToTwoWeapons:"Worn and Attached to Two Weapons",TraitWornAnklets:"Worn Anklets",TraitWornArmbands:"Worn Armbands",TraitWornBackpack:"Worn Backpack",TraitWornBarding:"Worn Barding",TraitWornBelt:"Worn Belt",TraitWornBeltPouch:"Worn Belt Pouch",TraitWornBoots:"Worn Boots",TraitWornBracelet:"Worn Bracelet",TraitWornBracers:"Worn Bracers",TraitWornCap:"Worn Cap",TraitWornCape:"Worn Cape",TraitWornCirclet:"Worn Circlet",TraitWornCloak:"Worn Cloak",TraitWornClothing:"Worn Clothing",TraitWornCollar:"Worn Collar",TraitWornCrown:"Worn Crown",TraitWornEpaulet:"Worn Epaulets",TraitWornEyeglasses:"Worn Eyeglasses",TraitWornEyepiece:"Worn Eyepiece",TraitWornFootwear:"Worn Footwear",TraitWornGarment:"Worn Garment",TraitWornGloves:"Worn Gloves",TraitWornHeadwear:"Worn Headwear",TraitWornHorseshoes:"Worn Horseshoes",TraitWornMask:"Worn Mask",TraitWornNecklace:"Worn Necklace",TraitWornOnBelt:"Worn on Belt",TraitWornOnWrists:"Worn on Wrists",TraitWornOrOneHand:"Worn or Held in One Hand",TraitWornRing:"Worn Ring",TraitWornSaddle:"Worn Saddle",TraitWornSandles:"Worn Sandles",TraitWornShoes:"Worn Shoes",TraitWornUnderArmor:"Worn Under Light Armor or Clothes",TraitWraith:"Wraith",TraitWyrwood:"Wyrwood",TraitXulgath:"Xulgath",TraitZombie:"Zombie",Traits:"Traits",TraitsLabel:"Traits",Trap:"Trap",TravelSpeed:{Days:"Days",DetectBeforeRunningIntoIt:"Notice Everything in Advance",DetectEverything:"Notice Everything",DetectionMode:"Detection Mode",DifficultTerrain:"Difficult Terrain Speed",Distance:"Distance",ExplorationActivities:{AvoidNotice:"Avoid Notice",CoverTracks:"Cover Tracks",Defend:"Defend",DetectMagic:"Detect Magic",HalfSpeed:"Other (Half Speed)",Investigate:"Investigate",None:"None (Full Speed)",RepeatASpell:"Repeat a Spell",Scout:"Scout",Search:"Search",Track:"Track"},ExplorationActivity:"Exploration Activity",ExplorationSpeed:"Exploration Speed",Feet:"Feet",FeetAcronym:"ft",GreaterDifficultTerrain:"Greater Difficult Terrain Speed",HexplorationActivities:"Hexploration Activities",Hours:"Hours",HoursPerDay:"Hours Spent Traveling Per Day",HustleMinutes:"Minutes Spent Hustling Per Day",Journey:"Journey",Label:"Travel Speed",Miles:"Miles",Name:"Name",None:"Full Speed",NormalTerrain:"Normal Terrain Speed",PartySpeed:"Party Speed",Speed:"Speed",TerrainSlowdown:"Terrain Speed",Title:"Travel Duration Calculator (Alpha)",TravelDuration:"Travel Duration",Weeks:"Weeks"},TrickMagicItemPopup:{InvalidActor:"Only a character or NPC can use Trick Magic Item.",Label:"Select a skill to use with Trick Magic Item.",Title:"Trick Magic Item"},UI:{applyDamage:{by:"by",damaged:"damaged for ",healed:"healed for ",shieldActive:"and their {shield} gets ",shieldInActive:"gets"},noDamageInfoForOutcome:"No damage information for outcome {outcome}.",shiftModifyDamageLabel:"Amount",shiftModifyDamageTitle:"Adjust Damage",shiftModifyHealingTitle:"Adjust Healing"},UUID:{Label:"UUID",SourceId:"Source ID"},UnitPriceLabel:"Unit price",UnitedPaizoWorkers:{PFSNote:'Note for Pathfinder Society players: In support of UPW, merchandise purchased from the union store will count in the Online PFS region for the Promotional Vestments boon.',ReleaseIntro:"Redmond, WA (October 14th, 2021) \u2014 Today, the workers at Paizo, Inc - publisher of the Pathfinder and Starfinder roleplaying games - are announcing their formation of the United Paizo Workers union (UPW), with the Communication Workers of America's CODE-CWA project. This union is the first of its kind in the tabletop roleplaying games industry.",Title:"Announcement: United Paizo Workers"},UnprepareItemTitle:"Unprepare Item",UpdateLabelUniversal:"Update",Usage:"Usage",UserSettings:{DarkvisionFilter:{Hint:"Add a (usually monochrome) filter when viewing a scene through the sight of a creature with darkvision",Label:"Darkvision Filter"}},ValueLabel:"Value",WeaknessesLabel:"Weaknesses",Weapon:{Base:{adze:"Adze","air-repeater":"Air Repeater",aklys:"Aklys","alchemical-bomb":"Alchemical Bomb","alchemical-crossbow":"Alchemical Crossbow","aldori-dueling-sword":"Aldori Dueling Sword",arbalest:"Arbalest",arquebus:"Arquebus","asp-coil":"Asp Coil",atlatl:"Atlatl","axe-musket":"Axe Musket","barricade-buster":"Barricade Buster","bastard-sword":"Bastard Sword","battle-axe":"Battle Axe","battle-lute":"Battle Lute","battle-saddle":"Battle Saddle","bec-de-corbin":"Bec de Corbin","big-boom-gun":"Big Boom Gun","black-powder-knuckle-dusters":"Black Powder Knuckle Dusters","bladed-diabolo":"Bladed Diabolo","bladed-gauntlet":"Bladed Gauntlet","bladed-hoop":"Bladed Hoop","bladed-scarf":"Bladed Scarf",blowgun:"Blowgun","blowgun-darts":"Blowgun Darts",blunderbuss:"Blunderbuss","bo-staff":"Bo Staff","boarding-axe":"Boarding Axe","boarding-pike":"Boarding Pike",bola:"Bola",boomerang:"Boomerang","bow-staff":"Bow Staff","breaching-pike":"Breaching Pike",broadspear:"Broadspear","butchering-axe":"Butchering Axe","butterfly-sword":"Butterfly Sword",buugeng:"Buugeng","cane-pistol":"Cane Pistol","chain-sword":"Chain Sword",chakram:"Chakram",chakri:"Chakri","clan-dagger":"Clan Dagger","clan-pistol":"Clan Pistol",claw:"Claw","claw-blade":"Claw Blade",club:"Club","coat-pistol":"Coat Pistol","combat-grapnel":"Combat Grapnel","combat-lure":"Combat Lure","composite-longbow":"Composite Longbow","composite-shortbow":"Composite Shortbow","corset-knife":"Corset Knife","crescent-cross":"Crescent Cross",crossbow:"Crossbow",dagger:"Dagger","dagger-pistol":"Dagger Pistol",daikyu:"Daikyu","dancers-spear":"Dancer's Spear",dandpatta:"Dandpatta",dart:"Dart",dogslicer:"Dogslicer",donchak:"Donchak","double-barreled-musket":"Double-Barreled Musket","double-barreled-pistol":"Double-Barreled Pistol","dragon-mouth-pistol":"Dragon Mouth Pistol","dueling-pistol":"Dueling Pistol","dueling-spear":"Dueling Spear","dwarven-dorn-dergar":"Dwarven Dorn-Dergar","dwarven-scattergun":"Dwarven Scattergun","dwarven-war-axe":"Dwarven War Axe",earthbreaker:"Earthbreaker","elven-branched-spear":"Elven Branched Spear","elven-curve-blade":"Elven Curve Blade","explosive-dogslicer":"Explosive Dogslicer","exquisite-sword-cane":"Exquisite Sword Cane","exquisite-sword-cane-sheath":"Exquisite Sword Cane Sheath",falcata:"Falcata",falchion:"Falchion",fangwire:"Fangwire",fauchard:"Fauchard","feng-huo-lun":"Feng Huo Lun","fighting-fan":"Fighting Fan","fighting-stick":"Fighting Stick","filchers-fork":"Filcher's Fork","fire-lance":"Fire Lance","fire-poi":"Fire Poi",fist:"Fist",flail:"Flail",flingflenser:"Flingflenser","flintlock-musket":"Flintlock Musket","flintlock-pistol":"Flintlock Pistol","flying-talon":"Flying Talon",flyssa:"Flyssa","forked-bipod":"Forked Bipod","frying-pan":"Frying Pan",gada:"Gada",gaff:"Gaff",gakgung:"Gakgung",gauntlet:"Gauntlet","gauntlet-bow":"Gauntlet Bow","gill-hook":"Gill Hook",glaive:"Glaive","gnome-amalgam-musket":"Gnome Amalgam Musket","gnome-flickmace":"Gnome Flickmace","gnome-hooked-hammer":"Gnome Hooked Hammer",greataxe:"Greataxe",greatclub:"Greatclub",greatpick:"Greatpick",greatsword:"Greatsword","griffon-cane":"Griffon Cane",guisarme:"Guisarme","gun-sword":"Gun Sword",halberd:"Halberd","halfling-sling-staff":"Halfling Sling Staff","hammer-gun":"Hammer Gun","hand-adze":"Hand Adze","hand-cannon":"Hand Cannon","hand-crossbow":"Hand Crossbow","harmona-gun":"Harmona Gun",harpoon:"Harpoon",hatchet:"Hatchet","heavy-crossbow":"Heavy Crossbow","hongali-hornbow":"Hongali Hornbow","hook-sword":"Hook Sword",horsechopper:"Horsechopper","injection-spear":"Injection Spear",javelin:"Javelin",jaws:"Jaws",jezail:"Jezail","jiu-huan-dao":"Jiu Huan Dao","juggling-club":"Juggling Club",kalis:"Kalis",kama:"Kama",karambit:"Karambit",katana:"Katana",katar:"Katar",khakkhara:"Khakkhara",khopesh:"Khopesh","knuckle-duster":"Knuckle Duster",kris:"Kris",kukri:"Kukri",kusarigama:"Kusarigama",lance:"Lance",lancer:"Lancer",leiomano:"Leiomano","light-hammer":"Light Hammer","light-mace":"Light Mace","light-pick":"Light Pick","lion-scythe":"Lion Scythe","long-air-repeater":"Long Air Repeater","long-hammer":"Long Hammer",longbow:"Longbow",longspear:"Longspear",longsword:"Longsword",mace:"Mace","mace-multipistol":"Mace Multipistol",machete:"Machete","main-gauche":"Main-Gauche",mambele:"Mambele",maul:"Maul","meteor-hammer":"Meteor Hammer",mikazuki:"Mikazuki","mithral-tree":"Mithral Tree","monkeys-fist":"Monkey's Fist",morningstar:"Morningstar",naginata:"Naginata",nightstick:"Nightstick","nine-ring-sword":"Nine-Ring Sword",nodachi:"Nodachi",nunchaku:"Nunchaku","ogre-hook":"Ogre Hook","orc-knuckle-dagger":"Orc Knuckle Dagger","orc-necksplitter":"Orc Necksplitter",panabas:"Panabas",pepperbox:"Pepperbox","phalanx-piercer":"Phalanx Piercer",pick:"Pick","piercing-wind":"Piercing Wind","piranha-kiss":"Piranha Kiss",poi:"Poi",polytool:"Polytool","probing-cane":"Probing Cane",ranseur:"Ranseur",rapier:"Rapier","rapier-pistol":"Rapier Pistol","reinforced-wheels":"Reinforced Wheels","repeating-crossbow":"Repeating Crossbow","repeating-hand-crossbow":"Repeating Hand Crossbow","repeating-heavy-crossbow":"Repeating Heavy Crossbow","rhoka-sword":"Rhoka Sword","rope-dart":"Rope Dart","rotary-bow":"Rotary Bow",rungu:"Rungu",sai:"Sai",sansetsukon:"Sansetsukon",sap:"Sap","sawtooth-saber":"Sawtooth Saber",scimitar:"Scimitar",scizore:"Scizore","scorpion-whip":"Scorpion Whip",scourge:"Scourge",scythe:"Scythe","shauth-lash":"Shauth Lash",shears:"Shears","shield-bash":"Shield Bash","shield-boss":"Shield Boss","shield-bow":"Shield Bow","shield-pistol":"Shield Pistol","shield-spikes":"Shield Spikes","shobhad-longrifle":"Shobhad Longrifle",shortbow:"Shortbow",shortsword:"Shortsword",shuriken:"Shuriken",sickle:"Sickle","sickle-saber":"Sickle-saber","slide-pistol":"Slide Pistol",sling:"Sling","sling-bullets":"Sling Bullets",spear:"Spear","spiked-chain":"Spiked Chain","spiked-gauntlet":"Spiked Gauntlet","spiral-rapier":"Spiral Rapier","spoon-gun":"Spoon Gun",spraysling:"Spraysling",staff:"Staff",starknife:"Starknife","stiletto-pen":"Stiletto Pen",sukgung:"Sukgung","sun-sling":"Sun Sling",switchscythe:"Switchscythe","sword-cane":"Sword Cane",talwar:"Talwar","tamchal-chakram":"Tamchal Chakram","taw-launcher":"Taw Launcher","tekko-kagi":"Tekko-kagi","temple-sword":"Temple Sword","tengu-gale-blade":"Tengu Gale Blade","thorn-whip":"Thorn whip","three-peaked-tree":"Three Peaked Tree","three-section-naginata":"Three-Section Naginata","throwing-knife":"Throwing Knife","thunder-sling":"Thunder Sling",thundermace:"Thundermace",tonfa:"Tonfa","tri-bladed-katar":"Tri-bladed Katar","tricky-pick":"Tricky Pick",trident:"Trident",triggerbrand:"Triggerbrand",urumi:"Urumi",visap:"Visap",wakizashi:"Wakizashi","war-flail":"War Flail","war-lance":"War Lance","war-razor":"War Razor",warhammer:"Warhammer","wheel-blades":"Wheel Blades","wheel-spikes":"Wheel Spikes",whip:"Whip","whip-claw":"Whip Claw","whip-staff":"Whip Staff","wish-blade":"Wish Blade","wish-knife":"Wish Knife","wooden-taws":"Wooden Taws",wrecker:"Wrecker","wrist-launcher":"Wrist Launcher",zulfikar:"Zulfikar"}},WeaponAbilityLabel:"Weapon Ability",WeaponBaseDamageTitle:"This section configures the base damage for the weapon. Additional die from Striking runes should not be added here and instead configured in the Weapon Runes section above.",WeaponBaseLabel:"Base",WeaponBonusAttackLabel:"Bonus Attack",WeaponBonusDamageLabel:"Bonus Damage",WeaponCustomDamageLabel:"Additional Custom Damage",WeaponCustomDamageTitle:"This section adds any custom damage that is not covered by the Rune system. The Strike Effect and Critical Effect attributes are not currently used in the system and are informational only.",WeaponDamageLabel:"Base Damage",WeaponGroupAxe:"Axe",WeaponGroupBomb:"Bomb",WeaponGroupBow:"Bow",WeaponGroupBrawling:"Brawling",WeaponGroupClub:"Club",WeaponGroupCrossbow:"Crossbow",WeaponGroupDart:"Dart",WeaponGroupFirearm:"Firearm",WeaponGroupFlail:"Flail",WeaponGroupHammer:"Hammer",WeaponGroupKnife:"Knife",WeaponGroupLabel:"Group",WeaponGroupPick:"Pick",WeaponGroupPolearm:"Polearm",WeaponGroupShield:"Shield",WeaponGroupSling:"Sling",WeaponGroupSpear:"Spear",WeaponGroupSword:"Sword",WeaponGroups:"Weapon Groups",WeaponHands1:"One",WeaponHands1Plus:"One Plus",WeaponHands2:"Two",WeaponMAPDefaultOption:"Default (uses Agile trait if present)",WeaponMAPLabel:"Multiple Attack Penalty",WeaponPotencyRune1:"Weapon Potency (+1)",WeaponPotencyRune2:"Weapon Potency (+2)",WeaponPotencyRune3:"Weapon Potency (+3)",WeaponPotencyRune4:"Weapon Potency (+4)",WeaponPropertyCriticalDamageLabel:"Critical Damage",WeaponPropertyCriticalEffectLabel:"Critical Effect",WeaponPropertyRune:{ancestralEchoing:{Name:"Ancestral Echoing"},anchoring:{Name:"Anchoring",Note:{criticalSuccess:"If you critically hit a target with an anchoring weapon, the weapon casts @UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor} on the target (@Check[type:will|dc:27|name:Anchoring Rune], counteract modifier [[/r 1d20+17 # Anchoring Rune Counteract Check]]{+17})."}},ashen:{Name:"Ashen",Note:{success:"This ash clouds the senses, causing the creature to become confused for 1 round unless it succeeds at a @Check[type:will|dc:25] save."}},astral:{Name:"Astral",Note:{criticalSuccess:"On a critical hit against a creature possessing another creature, the possessing creature must succeed at a @Check[type:will|dc:26] save or be expelled and unable to possess a creature for [[/br 1d4 #rounds]]{1d4 rounds}.",Note:"The weapon can harm creatures without physical form. An astral weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to astral weapons. Incorporeal creatures can touch, hold, and wield astral weapons (unlike most physical objects)."}},authorized:{Name:"Authorized"},bane:{Name:"Bane"},bloodbane:{Name:"Bloodbane"},bloodthirsty:{Name:"Bloodthirsty",Note:{criticalSuccess:"When you critically hit a target that's taking @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage}, your target becomes @UUID[Compendium.pf2e.conditionitems.Item.4D2KBtexWXa6oUMR]{Drained 1}."}},brilliant:{Name:"Brilliant",Note:{criticalSuccess:"On a critical hit, the target must succeed at a @Check[type:fortitude|dc:29|name:Brilliant Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} for 1 round."}},called:{Name:"Called"},coating:{Name:"Coating"},conducting:{Name:"Conducting"},corrosive:{Name:"Corrosive",Note:{criticalSuccess:"On a critical hit, the target's armor (if any) takes [[/r 3d6[acid] #Corrosive Rune]]{3d6 acid} damage (before applying Hardness); if the target has a shield raised, the shield takes this damage instead."}},crushing:{Name:"Crushing",Note:{criticalSuccess:"When you critically hit a target with this weapon, your target becomes @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} and @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn. @UUID[Compendium.pf2e.equipment-effects.Item.zNHvhwHsC8ckhKVp]{Effect: Crushing}"}},cunning:{Name:"Cunning"},dancing:{Name:"Dancing"},decaying:{Name:"Decaying"},deathdrinking:{Name:"Deathdrinking"},demolishing:{Name:"Demolishing"},disrupting:{Name:"Vitalizing",Note:{criticalSuccess:"On a critical hit, the undead is also @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn."}},earthbinding:{Name:"Earthbinding"},energizing:{Name:"Energizing"},extending:{Name:"Extending"},fanged:{Name:"Fanged"},fearsome:{Name:"Fearsome",Note:{criticalSuccess:"When you critically hit with this weapon, the target becomes @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 1}."}},flaming:{Name:"Flaming",Note:{criticalSuccess:"On a critical hit, you deal an additional [[/r 1d10[persistent,fire]]]."}},flurrying:{Name:"Flurrying"},frost:{Name:"Frost",Note:{criticalSuccess:"On a critical hit, the target is also @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn unless it succeeds at a @Check[type:fortitude|dc:24|name:Frost Rune] save."}},ghostTouch:{Name:"Ghost Touch",Note:"The weapon can harm creatures without physical form. A ghost touch weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to ghost touch weapons. Incorporeal creatures can touch, hold, and wield ghost touch weapons (unlike most physical objects)."},giantKilling:{Name:"Giant-Killing",Note:{criticalSuccess:"On a critical hit with this weapon, the giant is also @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn."}},greaterAnchoring:{Name:"Greater Anchoring",Note:{criticalSuccess:"When you critically hit a target with a weapon with the anchoring rune, the weapon casts 8th-rank @UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor} on the target (@Check[type:will|dc:38|name:Greater Anchoring Rune], counteract modifier [[/r 1d20+28 #Greater Anchoring Rune Counteract Check]]{+28}), except that if the target critically succeeds at its Will save, instead of having no effect, the dimensional anchor lasts for 1 round.",success:"When you hit a target with the weapon but don't critically hit, the target is affected by 4th-rank @UUID[Compendium.pf2e.spells-srd.Item.ksLCg62cLOojw3gN]{Dimensional Anchor} for 1 round without a save (counteract modifier [[/r 1d20+28 #Greater Anchoring Rune Counteract Check]]{+28})."}},greaterAshen:{Name:"Greater Ashen",Note:{success:"This ash clouds the senses, causing the creature to become confused for 1 round unless it succeeds at a @Check[type:will|dc:35] save. On a critical failure, the effect lasts for 1 minute."}},greaterAstral:{Name:"Greater Astral",Note:{criticalSuccess:"On a critical hit against a creature possessing another creature, the possessing creature must succeed at a @Check[type:will|dc:36] save or be expelled and unable to possess a creature for [[/br 1d4 #rounds]]{1d4 rounds}.",Note:"The weapon can harm creatures without physical form. A greater astral weapon is particularly effective against incorporeal creatures, which almost always have a specific vulnerability to greater astral weapons. Incorporeal creatures can touch, hold, and wield greater astral weapons (unlike most physical objects). The spirit damage granted by a greater astral weapon ignores any spirit resistance the target has."}},greaterBloodbane:{Name:"Greater Bloodbane"},greaterBrilliant:{Name:"Greater Brilliant",Note:{criticalSuccess:"Damage dealt by this weapon ignores the target's fire, good, or vitality resistance. On a critical hit, the target must succeed at a @Check[type:fortitude|dc:41|name:Greater Brilliant Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.XgEqL1kFApUbl5Z2]{Blinded} for 1 round.",success:"Damage dealt by this weapon ignores the target's fire, good, or vitality resistance."}},greaterCorrosive:{Name:"Greater Corrosive",Note:{criticalSuccess:"The acid damage dealt by this weapon ignores the target's acid resistance. On a critical hit, the target's armor (if any) takes [[/r 6d6[acid]]]{6d6 acid} damage (before applying Hardness); if the target has a shield raised, the shield takes this damage instead.",success:"The acid damage dealt by this weapon ignores the target's acid resistance."}},greaterCrushing:{Name:"Greater Crushing",Note:{criticalSuccess:"Your critical hits leave the target @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 2} and @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} until the end of your next turn. @UUID[Compendium.pf2e.equipment-effects.Item.czdEHtLsrUcZxSDx]{Effect: Crushing (Greater)}"}},greaterDecaying:{Name:"Greater Decaying"},greaterDisrupting:{Name:"Greater Vitalizing",Note:{criticalSuccess:"On a critical hit, the undead creature is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} and @UUID[Compendium.pf2e.conditionitems.Item.e1XGnhKNSQIm5IXg]{Stupefied 1} as long as it has the persistent damage from this rune."}},greaterExtending:{Name:"Greater Extending"},greaterFanged:{Name:"Greater Fanged"},greaterFearsome:{Name:"Greater Fearsome",Note:{criticalSuccess:"When you critically hit with this weapon, the target becomes @UUID[Compendium.pf2e.conditionitems.Item.TBSHQspnbcqxsmjL]{Frightened 2}."}},greaterFlaming:{Name:"Greater Flaming",Note:{criticalSuccess:"Fire damage dealt by this weapon (including the persistent fire damage) ignores the target's fire resistance.",success:"Fire damage dealt by this weapon ignores the target's fire resistance."}},greaterFrost:{Name:"Greater Frost",Note:{criticalSuccess:"Cold damage dealt by this weapon ignores the target's cold resistance. On a critical hit, the target is also @UUID[Compendium.pf2e.conditionitems.Item.xYTAsEpcJE1Ccni3]{Slowed 1} until the end of your next turn unless it succeeds at a @Check[type:fortitude|dc:34|name:Greater Frost Rune] save.",success:"Cold damage dealt by this weapon ignores the target's cold resistance."}},greaterGiantKilling:{Name:"Greater Giant-Killing",Note:{success:"Mental damage dealt by this weapon ignores the target's mental resistance.",criticalSuccess:"On a critical hit with this weapon, the giant must attempt a @Check[type:fortitude|dc:34] with the following effects.
Critical Success The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 1} until the end of your next turn.
Success The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} until the end of your next turn and takes @Damage[1d10[mental]].
Failure The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 2} for the next minute and takes @Damage[2d10[mental]].
Critical Failure The giant is @UUID[Compendium.pf2e.conditionitems.Item.MIRkyAjyBeXivMa7]{Enfeebled 4} for the next minute and takes @Damage[4d10[mental]]."}},greaterHauling:{Name:"Greater Hauling"},greaterImpactful:{Name:"Greater Impactful",Note:{criticalSuccess:"On a critical hit, you can choose to force the target to succeed at a @Check[type:fortitude|dc:37|name:Greater Impactful Rune] save or be pushed 10 feet away from you."}},greaterRooting:{Name:"Greater Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (Escape DC 28) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},greaterShock:{Name:"Greater Shock",Note:{criticalSuccess:"Electricity damage dealt by this weapon ignores the targets electricity resistance (and the other creatures' on a critical hit). On a critical hit, electricity arcs out to deal an equal amount of electricity damage to up to two other creatures of your choice within 10 feet of the target.",success:"Electricity damage dealt by this weapon ignores the target's electricity resistance."}},greaterThundering:{Name:"Greater Thundering",Note:{criticalSuccess:"Sonic damage dealt by this weapon ignores the target's sonic resistance. On a critical hit, the target has to succeed at a @Check[type:fortitude|dc:34|name:Greater Thundering Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR]{Deafened} permanently.",success:"Sonic damage dealt by this weapon ignores the target's sonic resistance."}},grievous:{Name:"Grievous",Note:{Axe:"You can damage a third creature, with the same restrictions.",Bow:"The Athletics check to pull the missile free is DC 20.",Brawling:"The target takes a -4 circumstance penalty to its save.",Club:"You can knock the target up to 15 feet away.",Dart:"The base persistent bleed damage increases to [[/r 2d6[bleed]]].",Flail:"You move the target 5 feet. You can't move it away from you, but you can move it in another direction of your choice.",Hammer:"You can also knock the target 5 feet away from you.",Knife:"The target takes a -5-foot status penalty to its Speed while it has the @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage}.",Pick:"The extra damage from the critical specialization effect increases to 4 per weapon damage die.",Polearm:"You can move the target up to 10 feet.",Shield:"You can knock the target up to 10 feet away.",Sling:"The target also takes a -10-foot status penalty to its Speed for 1 round if it fails the save.",Spear:"The clumsy condition lasts for 2 rounds.",Sword:"The target is off-guard until the end of your next turn."}},hauling:{Name:"Hauling"},holy:{Name:"Holy",Note:{criticalSuccess:`(R command; once per day)
Trigger You critically succeed at an attack roll against an evil creature with the weapon
Effect You regain HP equal to double the evil creature's level. This is a good, vitality, healing effect.`}},hopeful:{Name:"Hopeful",Note:{criticalSuccess:"On a critical hit with this weapon, you inspire your comrades, pushing them to fight harder and stand for your shared convictions. Allies within 30 feet that share at least one alignment component with you gain a +1 status bonus to attack rolls until the end of your next turn."}},hooked:{Name:"Hooked",Note:{criticalSuccess:"If a hooked weapon normally has the trip trait, you can attempt to Trip a foe as a reaction when you critically hit it with the hooked weapon."}},impactful:{Name:"Impactful",Note:{criticalSuccess:"On a critical hit, you can choose to force the target to succeed at a @Check[type:fortitude|dc:27|name:Impactful Rune] save or be pushed 5 feet away from you."}},impossible:{Name:"Impossible"},keen:{Name:"Keen"},kinWarding:{Name:"Kin-Warding"},majorRooting:{Name:"Major Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (Escape DC 34) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},merciful:{Name:"Merciful"},majorFanged:{Name:"Major Fanged"},pacifying:{Name:"Pacifying"},returning:{Name:"Returning",Note:"When you make a thrown Strike with this weapon, it flies back to your hand after the Strike is complete. If your hands are full when the weapon returns, it falls to the ground in your space."},rooting:{Name:"Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (Escape DC 23) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},serrating:{Name:"Serrating"},shifting:{Name:"Shifting"},shock:{Name:"Shock",Note:{criticalSuccess:"On a critical hit, electricity arcs out to deal an equal amount of electricity damage to up to two other creatures of your choice within 10 feet of the target."}},speed:{Name:"Speed"},spellStoring:{Name:"Spell-Storing"},swarming:{Name:"Swarming"},thundering:{Name:"Thundering",Note:{criticalSuccess:"On a critical hit, the target has to succeed at a @Check[type:fortitude|dc:24|name:Thundering Rune] save or be @UUID[Compendium.pf2e.conditionitems.Item.9PR9y0bi4JPKnHPR]{Deafened} for 1 minute (or 1 hour on a critical failure)."}},trueRooting:{Name:"True Rooting",Note:{criticalSuccess:`When you critically hit a target with this weapon, roots grow from the target. It's @UUID[Compendium.pf2e.conditionitems.Item.eIcWbB5o3pP6OIMe]{immobilized} for 1 round (Escape DC 41) and @UUID[Compendium.pf2e.conditionitems.Item.i3OJZU2nk64Df3xm]{Clumsy 1} for as long as the immobilization lasts.`}},underwater:{Name:"Underwater"},unholy:{Name:"Unholy",Note:{criticalSuccess:'(R command; once per day)
Trigger You critically succeed at an attack roll against a good creature with the weapon
Effect The target takes @UUID[Compendium.pf2e.conditionitems.Item.lDVqvLKA6eF3Df60]{Persistent Bleed Damage} equal to 1d8 per weapon damage die of the etched weapon.'}},vorpal:{Name:"Vorpal",Note:{criticalSuccess:`(R envision (death, incapacitation))
Trigger You roll a natural 20 on a Strike with the weapon, critically succeed, and deal slashing damage. The target must have a head
Effect The target must succeed at a @Check[type:fortitude|dc:37|traits:death,incapacitation|name:Vorpal Rune] save or be decapitated. This kills any creature except ones that don't require a head to live. For creatures with multiple heads, this usually kills the creature only if you sever its last head.`}},wounding:{Name:"Wounding"}},WeaponPropertyStrikeDamageLabel:"Strike Damage",WeaponPropertyStrikeEffectLabel:"Strike Effect",WeaponRange10:"10 ft.",WeaponRange100:"100 ft.",WeaponRange120:"120 ft.",WeaponRange140:"140 ft.",WeaponRange150:"150 ft.",WeaponRange180:"180 ft.",WeaponRange20:"20 ft.",WeaponRange200:"200 ft",WeaponRange240:"240 ft.",WeaponRange30:"30 ft.",WeaponRange300:"300 ft.",WeaponRange40:"40 ft.",WeaponRange50:"50 ft.",WeaponRange60:"60 ft.",WeaponRange70:"70 ft.",WeaponRange80:"80 ft.",WeaponRange90:"90 ft.",WeaponRangeMelee:"Melee",WeaponRangeN:"{range} ft.",WeaponRangeReach:"Reach",WeaponReloadLabel:"Reload Time",WeaponSpecialization:"Weapon Specialization",WeaponSplashDamageLabel:"Splash Damage",WeaponStrikeLabel:"Strike",WeaponTypeAdvanced:"Advanced Weapon",WeaponTypeMartial:"Martial Weapon",WeaponTypeSimple:"Simple Weapon",WeaponTypeSpecial:"Other Weapons",WeaponTypeUnarmed:"Unarmed Attack",Weight:"Weight",WorldClock:{AD:{Era:"AD"},AR:{Era:"AR",Months:{April:"Gozran",August:"Arodus",December:"Kuthona",February:"Calistril",January:"Abadius",July:"Erastus",June:"Sarenith",March:"Pharast",May:"Desnus",November:"Neth",October:"Lamashan",September:"Rova"},Weekdays:{Friday:"Fireday",Monday:"Moonday",Saturday:"Starday",Sunday:"Sunday",Thursday:"Oathday",Tuesday:"Toilday",Wednesday:"Wealday"}},Button:{AddOneDay:"1 Day",AddOneHour:"1 Hour",AddOneMinute:"1 Minute",AddOneRound:"1 Round",AddOneWeek:"1 Week",AddTenMinutes:"10 Minutes",Advance:"Advance",Retract:"Retract",TimeOfDay:{Advance:{Dawn:"Advance to Dawn",Dusk:"Advance to Dusk",Midnight:"Advance to Midnight",Noon:"Advance to Noon"},Retract:{Dawn:"Retract to Dawn",Dusk:"Retract to Dusk",Midnight:"Retract to Midnight",Noon:"Retract to Noon"}}},CE:{Era:"CE"},Date:"{weekday}, {day} of {month}, {year} {era}",IC:{Era:"IC"},Placeholder:"Number",Title:"World Clock"},condition:{blinded:{name:"Blinded",rules:"You can't see. All normal terrain is difficult terrain to you. You can't detect anything using vision. You automatically critically fail Perception checks that require you to be able to see, and if vision is your only precise sense, you take a -4 status penalty to Perception checks. You are immune to visual effects. Blinded overrides dazzled.
",summary:"You're unable to see."},broken:{name:"Broken",rules:`Broken is a condition that affects objects. An object is broken when damage has reduced its Hit Points to equal or less than its Broken Threshold. A broken object can't be used for its normal function, nor does it grant bonuses-with the exception of armor. Broken armor still grants its item bonus to AC, but it also imparts a status penalty to AC depending on its category: -1 for broken light armor, -2 for broken medium armor, or -3 for broken heavy armor.
+A broken item still imposes penalties and limitations normally incurred by carrying, holding, or wearing it. For example, broken armor would still impose its Dexterity modifier cap, check penalty, and so forth.
+If an effect makes an item broken automatically and the item has more HP than its Broken Threshold, that effect also reduces the item's current HP to the Broken Threshold.
`,summary:"This item can't be used for its normal function until repaired."},clumsy:{name:"Clumsy",rules:"Your movements become clumsy and inexact. Clumsy always includes a value. You take a status penalty equal to the condition value to Dexterity-based checks and DCs, including AC, Reflex saves, ranged attack rolls, and skill checks using Acrobatics, Stealth, and Thievery.
",summary:"You can't move as easily or gracefully as usual."},concealed:{name:"Concealed",rules:`While you are concealed from a creature, such as in a thick fog, you are difficult for that creature to see. You can still be observed, but you're tougher to target. A creature that you're concealed from must succeed at a @Check[type:flat|dc:5] when targeting you with an attack, spell, or other effect.
+Area effects aren't subject to this flat check. If the check fails, the attack, spell, or effect doesn't affect you.
`,summary:"Fog or similar obscuration makes you difficult to see and target."},confused:{name:"Confused",rules:`You don't have your wits about you, and you attack wildly. You are off-guard, you don't treat anyone as your ally (though they might still treat you as theirs), and you can't Delay, Ready, or use reactions.
You use all your actions to Strike or cast offensive cantrips, though the GM can have you use other actions to facilitate attack, such as draw a weapon, move so that a target is in reach, and so forth. Your targets are determined randomly by the GM. If you have no other viable targets, you target yourself, automatically hitting but not scoring a critical hit. If it's impossible for you to attack or cast spells, you babble incoherently, wasting your actions.
+Each time you take damage from an attack or spell, you can attempt a @Check[type:flat|dc:11] to recover from your confusion and end the condition.
`,summary:"You attack indiscriminately."},controlled:{name:"Controlled",rules:"Someone else is making your decisions for you, usually because you're being commanded or magically dominated. The controller dictates how you act and can make you use any of your actions, including attacks, reactions, or even Delay. The controller usually does not have to spend their own actions when controlling you.
",summary:"Another creature determines your actions."},dazzled:{name:"Dazzled",rules:"Your eyes are overstimulated. If vision is your only precise sense, all creatures and objects are concealed from you.
",summary:"Everything is concealed to you."},deafened:{name:"Deafened",rules:"You can't hear. You automatically critically fail Perception checks that require you to be able to hear. You take a -2 status penalty to Perception checks for initiative and checks that involve sound but also rely on other senses. If you perform an action with the auditory trait, you must succeed at a @Check[type:flat|dc:5] or the action is lost; attempt the check after spending the action but before any effects are applied. You are immune to auditory effects.
",summary:"You're unable to hear."},doomed:{name:"Doomed",rules:`Your life is ebbing away, bringing you ever closer to death. Some powerful spells and evil creatures can inflict the doomed condition on you. Doomed always includes a value. The maximum dying value at which you die is reduced by your doomed value. For example, if you were doomed 1, you would die upon reaching dying 3 instead of dying 4. If your maximum dying value is ever reduced to 0, you instantly die. When you die, you're no longer doomed.
+Your doomed value decreases by 1 each time you get a full night's rest.
`,summary:"With your soul in peril, you are now closer to death."},drained:{name:"Drained",rules:`When a creature successfully drains you of blood or life force, you become less healthy. Drained always includes a value. You take a status penalty equal to your drained value on Constitution-based checks, such as Fortitude saves. You also lose a number of Hit Points equal to your level (minimum 1) times the drained value, and your maximum Hit Points are reduced by the same amount. For example, if you're hit by an effect that inflicts drained 3 and you're a 3rd-level character, you lose 9 Hit Points and reduce your maximum Hit Points by 9. Losing these Hit Points doesn't count as taking damage.
+Each time you get a full night's rest, your drained value decreases by 1. This increases your maximum Hit Points, but you don't immediately recover the lost Hit Points.
`,summary:"Blood loss or something similar has leached your vitality."},dying:{name:"Dying",rules:`You are bleeding out or otherwise at death's door. While you have this condition, you are unconscious. Dying always includes a value, and if it ever reaches dying 4, you die. If you're dying, you must attempt a recovery check at the start of your turn each round to determine whether you get better or worse. Your dying condition increases by 1 if you take damage while dying, or by 2 if you take damage from an enemy's critical hit or a critical failure on your save.
+If you lose the dying condition by succeeding at a recovery check and are still at 0 Hit Points, you remain unconscious, but you can wake up as described in that condition. You lose the dying condition automatically and wake up if you ever have 1 Hit Point or more. Any time you lose the dying condition, you gain the wounded 1 condition, or increase your wounded condition value by 1 if you already have that condition.
`,summary:"You're slipping closer to death."},encumbered:{name:"Encumbered",rules:"You are carrying more weight than you can manage. While you're encumbered, you're clumsy 1 and take a 10-foot penalty to all your Speeds. As with all penalties to your Speed, this can't reduce your Speed below 5 feet.
",summary:"You're carrying more weight than you can manage."},enfeebled:{name:"Enfeebled",rules:"You're physically weakened. Enfeebled always includes a value. When you are enfeebled, you take a status penalty equal to the condition value to Strength-based rolls and DCs, including Strength-based melee attack rolls, Strength-based damage rolls, and Athletics checks.
",summary:"Your strength has been sapped away."},fascinated:{name:"Fascinated",rules:"You are compelled to focus your attention on something, distracting you from whatever else is going on around you. You take a -2 status penalty to Perception and skill checks, and you can't use actions with the concentrate trait unless they or their intended consequences are related to the subject of your fascination (as determined by the GM). For instance, you might be able to Seek and Recall Knowledge about the subject, but you likely couldn't cast a spell targeting a different creature. This condition ends if a creature uses hostile actions against you or any of your allies.
",summary:"You are compelled to focus your attention on something."},fatigued:{name:"Fatigued",rules:`You're tired and can't summon much energy. You take a -1 status penalty to AC and saving throws. While exploring, you can't choose an exploration activity.
+You recover from fatigue after a full night's rest.
`,summary:"Your defenses are lower and you can't focus while exploring."},"off-guard":{name:"Off-Guard",rules:`You're distracted or otherwise unable to focus your full attention on defense. You take a -2 circumstance penalty to AC. Some effects give you the off-guard condition only to certain creatures or against certain attacks. Others\u2014especially conditions\u2014can make you universally off-guard against everything. If a rule doesn't specify that the condition applies only to certain circumstances, it applies to all of them; for example, many effects simply say "The target is off-guard."
`,summary:"You're unable to defend yourself to your full capability."},fleeing:{name:"Fleeing",rules:"You're forced to run away due to fear or some other compulsion. On your turn, you must spend each of your actions trying to escape the source of the fleeing condition as expediently as possible (such as by using move actions to flee, or opening doors barring your escape). The source is usually the effect or caster that gave you the condition, though some effects might define something else as the source. You can't Delay or Ready while fleeing.
",summary:"You must run away."},friendly:{name:"Friendly",rules:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is friendly to a character likes that character. The character can attempt to make a Request of a friendly creature, and the friendly creature is likely to agree to a simple and safe request that doesn't cost it much to fulfill. If the character or one of their allies uses hostile actions against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
",summary:"An NPC with this condition has a good attitude toward you."},frightened:{name:"Frightened",rules:"You're gripped by fear and struggle to control your nerves. The frightened condition always includes a value. You take a status penalty equal to this value to all your checks and DCs. Unless specified otherwise, at the end of each of your turns, the value of your frightened condition decreases by 1.
",summary:"Fear makes you less capable of attacking and defending."},grabbed:{name:"Grabbed",rules:"You're held in place by another creature, giving you the off-guard and immobilized conditions. If you attempt a manipulate action while grabbed, you must succeed at a @Check[type:flat|dc:5] or it is lost; roll the check after spending the action, but before any effects are applied.
",summary:"A creature, object, or magic holds you in place."},group:{attitudes:"Attitudes",death:"Death and Dying",detection:"Degrees of Detection",senses:"Senses"},helpful:{name:"Helpful",rules:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is helpful to a character wishes to actively aid that character. It will accept reasonable Requests from that character, as long as such requests aren't at the expense of the helpful creature's goals or quality of life. If the character or one of their allies uses a hostile action against the creature, the creature gains a worse attitude condition depending on the severity of the hostile action, as determined by the GM.
",summary:"An NPC with this condition wants to assist you."},hidden:{name:"Hidden",rules:`While you're hidden from a creature, that creature knows the space you're in but can't tell precisely where you are. You typically become hidden by using Stealth to Hide. When Seeking a creature using only imprecise senses, it remains hidden, rather than observed. A creature you're hidden from is off-guard to you, and it must succeed at a @Check[type:flat|dc:11] when targeting you with an attack, spell, or other effect or it fails affect you. Area effects aren't subject to this flat check.
+A creature might be able to use the Seek action to try to observe you.
`,summary:"A creature you're hidden from knows your location but can't see you."},hostile:{name:"Hostile",rules:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is hostile to a character actively seeks to harm that character. It doesn't necessarily attack, but it won't accept Requests from the character.
",summary:"An NPC with this condition wants to harm you."},immobilized:{name:"Immobilized",rules:"You can't use any action with the move trait. If you're immobilized by something holding you in place and an external force would move you out of your space, the force must succeed at a check against either the DC of the effect holding you in place or the relevant defense (usually Fortitude DC) of the monster holding you in place.
",summary:"You can't move."},indifferent:{name:"Indifferent",rules:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is indifferent to a character doesn't really care one way or the other about that character. Assume a creature's attitude to a given character is indifferent unless specified otherwise.
",summary:"An NPC with this condition doesn't have a strong opinion about you."},invisible:{name:"Invisible",rules:"While invisible, you can't be seen. You're undetected to everyone. Creatures can Seek to attempt to detect you; if a creature succeeds at its Perception check against your Stealth DC, you become hidden to that creature until you Sneak to become undetected again. If you become invisible while someone can already see you, you start out hidden to the observer (instead of undetected) until you successfully Sneak. You can't become observed while invisible except via special abilities or magic.
",summary:"Creatures can't see you."},observed:{name:"Observed",rules:"Anything in plain view is observed by you. If a creature takes measures to avoid detection, such as by using Stealth to Hide, it can become hidden or undetected instead of observed. If you have another precise sense instead of or in addition to sight, you might be able to observe a creature or object using that sense instead. You can observe a creature only with precise senses. When Seeking a creature using only imprecise senses, it remains hidden, rather than observed.
",summary:"You're in plain view."},paralyzed:{name:"Paralyzed",rules:"Your body is frozen in place. You have the off-guard condition and can't act except to Recall Knowledge and use actions that require only the use of your mind (as determined by the GM). Your senses still function, but only in the areas you can perceive without moving your body, so you can't Seek while paralyzed.
",summary:"Your body is frozen in place."},"persistent-damage":{name:"Persistent Damage",rules:'Persistent damage comes from effects like acid, being on fire, or many other situations. It appears as "X persistent [type] damage," where "X" is the amount of damage dealt and "[type]" is the damage type. Instead of taking persistent damage immediately, you take it at the end of each of your turns as long as you have the condition, rolling any damage dice anew each time. After you take persistent damage, roll a @Check[type:flat|dc:15] to see if you recover from the persistent damage. If you succeed, the condition ends.
',summary:"You keep taking damage every round."},petrified:{name:"Petrified",rules:"You have been turned to stone. You can't act, nor can you sense anything. You become an object with a Bulk double your normal Bulk (typically 12 for a petrified Medium creature or 6 for a petrified Small creature), AC 9, Hardness 8, and the same current Hit Points you had when alive. You don't have a Broken Threshold. When you're turned back into flesh, you have the same number of Hit Points you had as a statue. If the statue is destroyed, you immediately die. While petrified, your mind and body are in stasis, so you don't age or notice the passing of time.
",summary:"You've been turned to stone."},prone:{name:"Prone",rules:`You're lying on the ground. You are off-guard and take a -2 circumstance penalty to attack rolls. The only move actions you can use while you're prone are Crawl and Stand. Standing up ends the prone condition. You can Take Cover while prone to hunker down and gain cover against ranged attacks, even if you don't have an object to get behind, gaining a +4 circumstance bonus to AC against ranged attacks (but you remain off-guard).
+If you would be knocked prone while you're Climbing or Flying, you fall. You can't be knocked prone when Swimming.
`,summary:"You're lying on the ground and are easier to attack."},quickened:{name:"Quickened",rules:"You gain 1 additional action at the start of your turn each round. Many effects that make you quickened specify the types of actions you can use with this additional action. If you become quickened from multiple sources, you can use the extra action you've been granted for any single action allowed by any of the effects that made you quickened. Because quickened has its effect at the start of your turn, you don't immediately gain actions if you become quickened during your turn.
",summary:"You get an extra action each turn."},restrained:{name:"Restrained",rules:"You're tied up and can barely move, or a creature has you pinned. You have the off-guard and immobilized conditions, and you can't use any actions with the attack or manipulate traits except to attempt to Escape or Force Open your bonds. Restrained overrides grabbed.
",summary:"You're tied up and can't move, or a grappling creature has you pinned."},sickened:{name:"Sickened",rules:`You feel ill. Sickened always includes a value. You take a status penalty equal to this value on all your checks and DCs. You can't willingly ingest anything-including elixirs and potions-while sickened.
+You can spend a single action retching in an attempt to recover, which lets you immediately attempt a Fortitude save against the DC of the effect that made you sickened. On a success, you reduce your sickened value by 1 (or by 2 on a critical success).
`,summary:"You're sick to your stomach."},slowed:{name:"Slowed",rules:"You have fewer actions. Slowed always includes a value. When you regain your actions at the start of your turn, reduce the number of actions you regain by your slowed value. Because slowed has its effect at the start of your turn, you don't immediately lose actions if you become slowed during your turn.
",summary:"You lose actions each turn."},stunned:{name:"Stunned",rules:`You've become senseless. You can't act while stunned. Stunned usually includes a value, which indicates how many total actions you lose, possibly over multiple turns, from being stunned. Each time you regain actions (such as at the start of your turn), reduce the number you regain by your stunned value, then reduce your stunned value by the number of actions you lost. For example, if you were stunned 4, you would lose all 3 of your actions on your turn, reducing you to stunned 1; on your next turn, you would lose 1 more action, and then be able to use your remaining 2 actions normally. Stunned might also have a duration instead of a value, such as "stunned for 1 minute." In this case, you lose all your actions for the listed duration.
+Stunned overrides slowed. If the duration of your stunned condition ends while you are slowed, you count the actions lost to the stunned condition toward those lost to being slowed. So, if you were stunned 1 and slowed 2 at the beginning of your turn, you would lose 1 action from stunned, and then lose only 1 additional action by being slowed, so you would still have 1 action remaining to use that turn.
`,summary:"You can't use actions."},stupefied:{name:"Stupefied",rules:"Your thoughts and instincts are clouded. Stupefied always includes a value. You take a status penalty equal to this value on Intelligence-, Wisdom-, and Charisma-based checks and DCs, including Will saving throws, spell attack rolls, spell DCs, and skill checks that use these attribute modifiers. Any time you attempt to Cast a Spell while stupefied, the spell is disrupted unless you succeed at a flat check with a DC equal to 5 + your stupefied value.
",summary:"You can't access your full mental faculties, and you have trouble casting spells."},unconscious:{name:"Unconscious",rules:`You're sleeping, or you've been knocked out. You can't act. You take a -4 status penalty to AC, Perception, and Reflex saves, and you have the blinded and off-guard conditions. When you gain this condition, you fall prone and drop items you are wielding or holding unless the effect states otherwise or the GM determines you're in a position in which you wouldn't.
+If you're unconscious because you're dying, you can't wake up while you have 0 Hit Points. If you are restored to 1 Hit Point or more via healing, you lose the dying and unconscious conditions and can act normally on your next turn.
+If you are unconscious and at 0 Hit Points, but not dying, you naturally return to 1 Hit Point and awaken after sufficient time passes. The GM determines how long you remain unconscious, from a minimum of 10 minutes to several hours. If you receive healing during this time, you lose the unconscious condition and can act normally on your next turn.
+If you're unconscious and have more than 1 Hit Point (typically because you are asleep or unconscious due to an effect), you wake up in one of the following ways. Each causes you to lose the unconscious condition.
- You take damage, provided the damage doesn't reduce you to 0 Hit Points. If the damage reduces you to 0 Hit Points, you remain unconscious and gain the dying condition as normal.
- You receive healing, other than the natural healing you get from resting.
- Someone shakes you awake with an Interact action.
- There's loud noise going on around you-though this isn't automatic. At the start of your turn, you automatically attempt a Perception check against the noise's DC (or the lowest DC if there is more than one noise), waking up if you succeed. If creatures are attempting to stay quiet around you, this Perception check uses their Stealth DCs. Some magical effects make you sleep so deeply that they don't allow you to attempt this Perception check.
- If you are simply asleep, the GM decides you wake up either because you have had a restful night's sleep or something disrupted that rest.
`,summary:"You're asleep or knocked out."},undetected:{name:"Undetected",rules:`When you are undetected by a creature, that creature cannot see you at all, has no idea what space you occupy, and can't target you, though you still can be affected by abilities that target an area. When you're undetected by a creature, that creature is off-guard to you.
+A creature you're undetected by can guess which square you're in to try targeting you. It must pick a square and attempt an attack. This works like targeting a hidden creature (requiring a @Check[type:flat|dc:11]), but the flat check and attack roll are rolled in secret by the GM, who doesn't reveal whether the attack missed due to failing the flat check, failing the attack roll, or choosing the wrong square.
+A creature can use the Seek action to try to find you.
`,summary:"A creature you're undetected by doesn't know where you are."},unfriendly:{name:"Unfriendly",rules:"This condition reflects a creature's disposition toward a particular character, and only supernatural effects (like a spell) can impose these conditions on player characters. A creature that is unfriendly to a character dislikes and specifically distrusts that character. The unfriendly creature won't accept Requests from the character.
",summary:"An NPC with this condition doesn't like you."},unnoticed:{name:"Unnoticed",rules:"If you are unnoticed by a creature, that creature has no idea you are present at all. When you're unnoticed, you're also undetected by the creature. This condition matters for abilities that can be used only against targets totally unaware of your presence.
",summary:"A creature is entirely unaware you're present."},wounded:{name:"Wounded",rules:`You have been seriously injured. If you lose the dying condition and do not already have the wounded condition, you become wounded 1. If you already have the wounded condition when you lose the dying condition, your wounded condition value increases by 1. If you gain the dying condition while wounded, increase your dying condition value by your wounded value.
+The wounded condition ends if someone successfully restores Hit Points to you with Treat Wounds, or if you are restored to full Hit Points and rest for 10 minutes.
`,summary:"You've been brought back from the brink of death but haven't fully recovered."}},identification:{DisplayDetails:"Display Details",Identified:"Identified",Identify:"Identify Item",IdentifyAlchemyDCs:"Identify Alchemy DCs",IdentifyGenericDCs:"Identify Generic DCs",IdentifyMagicDCs:"Identify Magic DCs",IsIdentified:"Identified?",MisidentifiedItem:"Misidentified {item}",Misidentify:"Misidentify Item",MystificationStatus:"Mystification status",Mystify:"Mystify Item",PostSkillsToChat:"Post skill checks to chat",PostSkillsToChatText:"Identify item: Skill checks",TraitGMNote:"Note: this trait is hidden from players.",Unidentified:"Unidentified",UnidentifiedDescription:"The nature of this {item} is unclear.",UnidentifiedHint:"Change the basic details seen by players when this item is unidentified.",UnidentifiedItem:"Unusual {item}",UnidentifiedType:{Amulet:"Amulet",Anklets:"Anklets",Armbands:"Armbands",Backpack:"Backpack",Belt:"Belt",Book:"Book",Bracers:"Bracers",Circlet:"Circlet",Cloak:"Cloak",Collar:"Collar",Epaulets:"Epaulets",Eyepiece:"Eyepiece",Garment:"Garment",Gloves:"Gloves",Headwear:"Headwear",Horseshoes:"Horseshoes",Liquid:"Liquid",Mask:"Mask",Necklace:"Necklace",Object:"Object",Ring:"Ring",Saddle:"Saddle",Shoes:"Shoes",Substance:"Substance",Tool:"Tool"}},loot:{BuySubtitle:"Buy item",DepositMessage:"{depositor} deposits {quantity} \xD7 {item} in {container}.",DepositSubtitle:"Deposit item",EditLootLabel:"Configure Loot?",GMSupervisionError:"A GM must be online in order to interact with {loot}.",GiveMessage:"{giver} gives {quantity} \xD7 {item} to {recipient}.",GiveSubtitle:"Give item",HiddenWhenEmpty:{Hint:"Hide this actor's token(s) when its inventory is empty.",Label:"Hidden When Empty"},InsufficientCurrencyError:"Insufficient currency for purchase by {buyer}",InsufficientFundsMessage:"{buyer} reaches for their coins but comes up short!",LootDescription:"Allows for distribution of coins across players",LootLabel:"Loot",LootMessage:"{looter} loots {quantity} \xD7 {item} off {corpse}.",LootNPCsLabel:"Loot Selected Tokens",LootNPCsPopupHeader:"Choose tokens to loot from",LootNamePlaceholder:"Loot",LootSubtitle:"Loot item",MerchantDescription:"Allows players to purchase items directly from the sheet",MerchantLabel:"Merchant",MoveLoot:"Move Items",MoveLootMessage:"How many items do you wish to move?",MoveLootPopupTitle:"Item Quantity",PartyStash:"the party stash",PermissionError:"A GM must be online in order to loot or stow an item.",PlantMessage:"{planter} plants {quantity} \xD7 {item} on {corpse}.",PlantSubtitle:"Plant Item",PurchaseLoot:"Purchase Items",PurchaseLootMessage:"How many items do you wish to purchase?",Quantity:"Quantity",SellMessage:"{seller} sells {quantity} \xD7 {item} to {buyer}.",SellSubtitle:"Sell item",SheetType:"Sheet Type",SplitCoinsLabel:"Distribute Coins",SplitCoinsPopupHeader:"Choose actors to receive a share",Stack:"Create new stack?",TakeMessage:"{taker} takes {quantity} \xD7 {item} from {container}.",TakeSubtitle:"Take item",TransferMessage:"{transferrer} moves {quantity} \xD7 {item} from {fromContainer} to {toContainer}.",TransferSubtitle:"Transfer item"},ui:{armorEquipped:"Toggle wearing your equipment",equipmentInvested:"Toggle Investment",sell:"Sell",weaponEquipped:"Toggle holding your weapon"},vehicle:{BrokenThresholdShortLabel:"BT",CrewLabel:"Crew",CurrentHPTitle:"Current Hitpoints",DescriptionHeading:"Description",HardnessLabel:"Hardness",HardnessShortLabel:"Hard.",LevelN:"Vehicle {level}",MaxHPTitle:"Maximum Hitpoints",NamePlaceholder:"Vehicle",PassengersLabel:"Passengers",PilotingCheckLabel:"Piloting Check",PropertyDescriptionCollisionDC:"The vehicle's DC for saving throws to mitigate damage.",PropertyDescriptionCollisionDamage:"The vehicle's collision damage. Unless otherwise stated, collisions deal bludgeoning damage.",PropertyDescriptionCrew:"The crew members required to operate the vehicle.",PropertyDescriptionPassengers:"The number of passengers the vehicle is typically configured to carry, if any.",PropertyDescriptionPilotingCheck:"This entry lists the skills that can be used for piloting checks while operating the vehicle. Some skills may increase the DC; these list the DC adjustment in parentheses following the skill name.",PropertyDescriptionPrice:"Vehicle's Price. This does not include creatures for pulling a vehicle, materials needed to power the vehicle, or the cost of rowers.",PropertyDescriptionSpace:"Vehicle's dimensions, not including any creatures pulling the vehicle.",PropertyDescriptionSpeed:"The vehicle's Speeds, each followed by the propulsion type for that Speed in parentheses. A pulled vehicle indicates the number and size of the pulling creatures.",SpaceHighLabel:"Height",SpaceLongLabel:"Length",SpaceWideLabel:"Width",VehicleLevelLabel:"Vehicle",VehicleString:"Vehicle",collisionDCLabel:"Collision DC",collisionDamageLabel:"Collision Damage"}},SIDEBAR:{TabCombat:"Encounter Tracker"},TYPES:{Actor:{army:"Army",character:"Player Character",eidolon:"Eidolon",familiar:"Familiar",hazard:"Hazard",loot:"Loot",npc:"NPC",party:"Party",vehicle:"Vehicle"},Item:{action:"Ability",affliction:"Affliction",ancestry:"Ancestry",armor:"Armor",background:"Background",backpack:"Container",book:"Book",campaignFeature:"Campaign Feature",class:"Class",condition:"Condition",consumable:"Consumable",deity:"Deity",effect:"Effect",equipment:"Equipment",feat:"Feat/Feature",heritage:"Heritage",kit:"Kit",lore:"Lore Skill",melee:"NPC Attack",shield:"Shield",spell:"Spell",spellcastingEntry:"Spellcasting Entry",treasure:"Treasure",weapon:"Weapon"}}};const actorTypes={army:"TYPES.Actor.army",character:"TYPES.Actor.character",familiar:"TYPES.Actor.familiar",hazard:"TYPES.Actor.hazard",loot:"TYPES.Actor.loot",npc:"TYPES.Actor.npc",party:"TYPES.Actor.party",vehicle:"TYPES.Actor.vehicle"},abilities={str:"PF2E.AbilityStr",dex:"PF2E.AbilityDex",con:"PF2E.AbilityCon",int:"PF2E.AbilityInt",wis:"PF2E.AbilityWis",cha:"PF2E.AbilityCha"},senses={darkvision:"PF2E.Actor.Creature.Sense.Type.Darkvision",echolocation:"PF2E.Actor.Creature.Sense.Type.Echolocation",greaterDarkvision:"PF2E.Actor.Creature.Sense.Type.GreaterDarkvision",heatsight:"PF2E.Actor.Creature.Sense.Type.Heatsight",lifesense:"PF2E.Actor.Creature.Sense.Type.Lifesense",lowLightVision:"PF2E.Actor.Creature.Sense.Type.LowLightVision",motionsense:"PF2E.Actor.Creature.Sense.Type.Motionsense",scent:"PF2E.Actor.Creature.Sense.Type.Scent",seeInvisibility:"PF2E.Actor.Creature.Sense.Type.SeeInvisibility",spiritsense:"PF2E.Actor.Creature.Sense.Type.Spiritsense",thoughtsense:"PF2E.Actor.Creature.Sense.Type.Thoughtsense",tremorsense:"PF2E.Actor.Creature.Sense.Type.Tremorsense",wavesense:"PF2E.Actor.Creature.Sense.Type.Wavesense"},senseAcuity={imprecise:"PF2E.Actor.Creature.Sense.Acuity.Imprecise",precise:"PF2E.Actor.Creature.Sense.Acuity.Precise",vague:"PF2E.Actor.Creature.Sense.Acuity.Vague"},tokenHUDConditions={blinded:"PF2E.ConditionTypeBlinded",broken:"PF2E.ConditionTypeBroken",clumsy:"PF2E.ConditionTypeClumsy",concealed:"PF2E.ConditionTypeConcealed",confused:"PF2E.ConditionTypeConfused",controlled:"PF2E.ConditionTypeControlled",dazzled:"PF2E.ConditionTypeDazzled",deafened:"PF2E.ConditionTypeDeafened",doomed:"PF2E.ConditionTypeDoomed",drained:"PF2E.ConditionTypeDrained",dying:"PF2E.ConditionTypeDying",encumbered:"PF2E.ConditionTypeEncumbered",enfeebled:"PF2E.ConditionTypeEnfeebled",fascinated:"PF2E.ConditionTypeFascinated",fatigued:"PF2E.ConditionTypeFatigued",fleeing:"PF2E.ConditionTypeFleeing",frightened:"PF2E.ConditionTypeFrightened",grabbed:"PF2E.ConditionTypeGrabbed",hidden:"PF2E.ConditionTypeHidden",immobilized:"PF2E.ConditionTypeImmobilized",invisible:"PF2E.ConditionTypeInvisible","off-guard":"PF2E.ConditionTypeOffGuard",paralyzed:"PF2E.ConditionTypeParalyzed","persistent-damage":"PF2E.ConditionTypePersistent",petrified:"PF2E.ConditionTypePetrified",prone:"PF2E.ConditionTypeProne",quickened:"PF2E.ConditionTypeQuickened",restrained:"PF2E.ConditionTypeRestrained",sickened:"PF2E.ConditionTypeSickened",slowed:"PF2E.ConditionTypeSlowed",stunned:"PF2E.ConditionTypeStunned",stupefied:"PF2E.ConditionTypeStupefied",unconscious:"PF2E.ConditionTypeUnconscious",undetected:"PF2E.ConditionTypeUndetected",wounded:"PF2E.ConditionTypeWounded"},conditionTypes={...tokenHUDConditions,friendly:"PF2E.ConditionTypeFriendly",helpful:"PF2E.ConditionTypeHelpful",hostile:"PF2E.ConditionTypeHostile",indifferent:"PF2E.ConditionTypeIndifferent",malevolence:"PF2E.ConditionTypeMalevolence",observed:"PF2E.ConditionTypeObserved",unfriendly:"PF2E.ConditionTypeUnfriendly",unnoticed:"PF2E.ConditionTypeUnnoticed"},weaponCategories={simple:"PF2E.WeaponTypeSimple",martial:"PF2E.WeaponTypeMartial",advanced:"PF2E.WeaponTypeAdvanced",unarmed:"PF2E.WeaponTypeUnarmed"},baseArmorTypes=mapValues$1(define_EN_JSON_default.PF2E.Item.Armor.Base,(_v,slug)=>`PF2E.Item.Armor.Base.${slug}`),baseShieldTypes=mapValues$1(define_EN_JSON_default.PF2E.Item.Shield.Base,(_v,slug)=>`PF2E.Item.Shield.Base.${slug}`),baseWeaponTypes=mapValues$1(define_EN_JSON_default.PF2E.Weapon.Base,(_v,slug)=>`PF2E.Weapon.Base.${slug}`),equivalentWeapons={"composite-longbow":"longbow","composite-shortbow":"shortbow","big-boom-gun":"hand-cannon","spoon-gun":"hand-cannon"},preciousMaterialGrades={low:"PF2E.PreciousMaterialLowGrade",standard:"PF2E.PreciousMaterialStandardGrade",high:"PF2E.PreciousMaterialHighGrade"},meleeWeaponGroups={axe:"PF2E.WeaponGroupAxe",brawling:"PF2E.WeaponGroupBrawling",club:"PF2E.WeaponGroupClub",dart:"PF2E.WeaponGroupDart",flail:"PF2E.WeaponGroupFlail",hammer:"PF2E.WeaponGroupHammer",knife:"PF2E.WeaponGroupKnife",pick:"PF2E.WeaponGroupPick",polearm:"PF2E.WeaponGroupPolearm",shield:"PF2E.WeaponGroupShield",spear:"PF2E.WeaponGroupSpear",sword:"PF2E.WeaponGroupSword"},weaponGroups={...meleeWeaponGroups,bomb:"PF2E.WeaponGroupBomb",bow:"PF2E.WeaponGroupBow",crossbow:"PF2E.WeaponGroupCrossbow",firearm:"PF2E.WeaponGroupFirearm",sling:"PF2E.WeaponGroupSling"},sizeTypes={tiny:"PF2E.ActorSizeTiny",sm:"PF2E.ActorSizeSmall",med:"PF2E.ActorSizeMedium",lg:"PF2E.ActorSizeLarge",huge:"PF2E.ActorSizeHuge",grg:"PF2E.ActorSizeGargantuan"},featCategories={ancestry:"PF2E.FeatTypeAncestry",ancestryfeature:"PF2E.FeatTypeAncestryfeature",class:"PF2E.FeatTypeClass",classfeature:"PF2E.FeatTypeClassfeature",skill:"PF2E.FeatTypeSkill",general:"PF2E.FeatTypeGeneral",bonus:"PF2E.FeatTypeBonus",pfsboon:"PF2E.FeatTypePfsboon",deityboon:"PF2E.FeatTypeDeityboon",curse:"PF2E.FeatTypeCurse"},creatureTypes=pick(creatureTraits,["aberration","animal","astral","beast","celestial","construct","dragon","dream","elemental","ethereal","fey","fiend","fungus","giant","humanoid","monitor","ooze","petitioner","plant","shadow","spirit","time","vitality","void","undead"]),consumableCategories=mapToObj(Array.from(CONSUMABLE_CATEGORIES),c=>[c,`PF2E.Item.Consumable.Category.${c}`]),deityDomains=mapToObj(Object.keys(define_EN_JSON_default.PF2E.Item.Deity.Domain),key=>{const label=`PF2E.Item.Deity.Domain.${key}.Label`,description=`PF2E.Item.Deity.Domain.${key}.Description`;return[sluggify(key),{label,description}]}),weaponReload={"-":"\u2014",0:"0",1:"1",2:"2",3:"3",10:"PF2E.Item.Weapon.Reload.OneMinute"};function notifyDeprecatedPath(configPath,locPath){foundry.utils.logCompatibilityWarning(`CONFIG.PF2E.${configPath} is deprecated. Use localization path ${locPath} directly instead.`,{since:"5.2.0",until:"6.0.0"})}__name(notifyDeprecatedPath,"notifyDeprecatedPath"),__name2(notifyDeprecatedPath,"notifyDeprecatedPath");const PF2ECONFIG={defaultPartyId:"xxxPF2ExPARTYxxx",chatDamageButtonShieldToggle:!1,statusEffects:{lastIconTheme:"default",iconDir:"systems/pf2e/icons/conditions/",conditions:tokenHUDConditions},levels:{1:"PF2E.Level1",2:"PF2E.Level2",3:"PF2E.Level3",4:"PF2E.Level4",5:"PF2E.Level5",6:"PF2E.Level6",7:"PF2E.Level7",8:"PF2E.Level8",9:"PF2E.Level9",10:"PF2E.Level10",11:"PF2E.Level11",12:"PF2E.Level12",13:"PF2E.Level13",14:"PF2E.Level14",15:"PF2E.Level15",16:"PF2E.Level16",17:"PF2E.Level17",18:"PF2E.Level18",19:"PF2E.Level19",20:"PF2E.Level20"},abilities,attributes:{get perception(){const locPath="PF2E.PerceptionLabel";return notifyDeprecatedPath("attributes.perception",locPath),locPath},get stealth(){const locPath="PF2E.StealthLabel";return notifyDeprecatedPath("attributes.stealth",locPath),locPath},get initiative(){const locPath="PF2E.InitiativeLabel";return notifyDeprecatedPath("attributes.initiative",locPath),locPath}},dcAdjustments:{"incredibly-easy":"PF2E.DCAdjustmentIncrediblyEasy","very-easy":"PF2E.DCAdjustmentVeryEasy",easy:"PF2E.DCAdjustmentEasy",normal:"PF2E.DCAdjustmentNormal",hard:"PF2E.DCAdjustmentHard","very-hard":"PF2E.DCAdjustmentVeryHard","incredibly-hard":"PF2E.DCAdjustmentIncrediblyHard"},checkDCs:configFromLocalization(define_EN_JSON_default.PF2E.Check.DC,"PF2E.Check.DC"),skills:{acr:"PF2E.SkillAcr",arc:"PF2E.SkillArc",ath:"PF2E.SkillAth",cra:"PF2E.SkillCra",dec:"PF2E.SkillDec",dip:"PF2E.SkillDip",itm:"PF2E.SkillItm",med:"PF2E.SkillMed",nat:"PF2E.SkillNat",occ:"PF2E.SkillOcc",prf:"PF2E.SkillPrf",rel:"PF2E.SkillRel",soc:"PF2E.SkillSoc",ste:"PF2E.SkillSte",sur:"PF2E.SkillSur",thi:"PF2E.SkillThi"},saves:{fortitude:"PF2E.SavesFortitude",reflex:"PF2E.SavesReflex",will:"PF2E.SavesWill"},savingThrowDefaultAttributes:{fortitude:"con",reflex:"dex",will:"wis"},currencies:{pp:"PF2E.CurrencyPP",gp:"PF2E.CurrencyGP",sp:"PF2E.CurrencySP",cp:"PF2E.CurrencyCP"},preciousMaterialGrades,preciousMaterials,accessoryPropertyRunes:{called:"PF2E.AccessoryPropertyRuneCalled",dragonsBreath:"PF2E.AccessoryPropertyRuneDragonsBreath",paired:"PF2E.AccessoryPropertyRunePaired",greaterPaired:"PF2E.AccessoryPropertyRuneGreaterPaired",majorPaired:"PF2E.AccessoryPropertyRuneMajorPaired",presentable:"PF2E.AccessoryPropertyRunePresentable",snagging:"PF2E.AccessoryPropertyRuneSnagging",softLanding:"PF2E.AccessoryPropertyRuneSoftLanding",spellBastion:"PF2E.AccessoryPropertyRuneSpellBastion",windCatcher:"PF2E.AccessoryPropertyRuneWindCatcher",greaterWindCatcher:"PF2E.AccessoryPropertyRuneGreaterWindCatcher"},damageTraits,damageTypes,damageRollFlavors,damageCategories,elementTraits,materialDamageEffects,resistanceTypes,stackGroups:{arrows:"PF2E.StackGroupArrows",blowgunDarts:"PF2E.StackGroupBlowgunDarts",bolts:"PF2E.StackGroupBolts",coins:"PF2E.StackGroupCoins",gems:"PF2E.StackGroupGems",rounds5:"PF2E.StackGroupRounds5",rounds10:"PF2E.StackGroupRounds10",slingBullets:"PF2E.StackGroupSlingBullets",sprayPellets:"PF2E.StackGroupSprayPellets",woodenTaws:"PF2E.StackGroupWoodenTaws"},weaknessTypes,weaponCategories,weaponGroups,meleeWeaponGroups,baseArmorTypes,baseShieldTypes,baseWeaponTypes,equivalentWeapons,weaponDescriptions:{club:"PF2E.WeaponDescriptionClub",knife:"PF2E.WeaponDescriptionKnife",brawling:"PF2E.WeaponDescriptionBrawling",spear:"PF2E.WeaponDescriptionSpear",sword:"PF2E.WeaponDescriptionSword",axe:"PF2E.WeaponDescriptionAxe",flail:"PF2E.WeaponDescriptionFlail",polearm:"PF2E.WeaponDescriptionPolearm",pick:"PF2E.WeaponDescriptionPick",hammer:"PF2E.WeaponDescriptionHammer",shield:"PF2E.WeaponDescriptionShield",dart:"PF2E.WeaponDescriptionDart",bow:"PF2E.WeaponDescriptionBow",sling:"PF2E.WeaponDescriptionSling",bomb:"PF2E.WeaponDescriptionBomb"},usages:{"affixed-to-a-creature":"PF2E.TraitAffixedToCreature","affixed-to-a-magical-staff":"PF2E.TraitAffixedToMagicalStaff","affixed-to-a-metal-weapon":"PF2E.TraitAffixedToAMetalWeapon","affixed-to-a-ranged-weapon":"PF2E.TraitAffixedToARangedWeapon","affixed-to-a-shield":"PF2E.TraitAffixedToAShield","affixed-to-a-shield-or-weapon":"PF2E.TraitAffixedToAShieldOrWeapon","affixed-to-a-thrown-weapon":"PF2E.TraitAffixedToThrownWeapon","affixed-to-a-two-handed-firearm-or-crossbow":"PF2E.TraitAffixedToATwoHandedFirearmOrCrossbow","affixed-to-an-innovation":"PF2E.TraitAffixedToInnovation","affixed-to-an-object-or-structure":"PF2E.TraitAffixedToObjectOrStructure","affixed-to-armor":"PF2E.TraitAffixedToArmor","affixed-to-medium-heavy-armor":"PF2E.TraitAffixedToMediumHeavyArmor","affixed-to-medium-heavy-metal-armor":"PF2E.TraitAffixedToMediumHeavyMetalArmor","affixed-to-armor-or-a-weapon":"PF2E.TraitAffixedToArmorOrAWeapon","affixed-to-armor-or-travelers-clothing":"PF2E.TraitAffixedToArmorOrTravelersClothing","affixed-to-crossbow-or-firearm":"PF2E.TraitAffixedToCrossbowOrFirearm","affixed-to-firearm":"PF2E.TraitAffixedToFirearm","affixed-to-firearm-with-a-reload-of-1":"PF2E.TraitAffixedToFirearmWithAReloadOf1","affixed-to-firearm-with-the-kickback-trait":"PF2E.TraitAffixedToFirearmWithTheKickbackTrait","affixed-to-ground-in-10-foot-radius":"PF2E.TraitAffixedToGroundIn10FtRadius","affixed-to-ground-in-20-foot-radius":"PF2E.TraitAffixedToGroundIn20FtRadius","affixed-to-harness":"PF2E.TraitAffixedToHarness","affixed-to-headgear":"PF2E.TraitAffixedToHeadgear","affixed-to-instrument":"PF2E.TraitAffixedToInstrument","affixed-to-load-bearing-wall-or-pillar":"PF2E.TraitAffixedToLoadBearingWallOrPillar","affixed-to-melee-weapon":"PF2E.TraitAffixedToMeleeWeapon","affixed-to-metal-weapon":"PF2E.TraitAffixedToMetalWeapon","affixed-to-object-structure-or-creature":"PF2E.TraitAffixedToStructureObjectOrCreature","affixed-to-the-ground":"PF2E.TraitAffixedToGround","affixed-to-unarmored-defense-item":"PF2E.TraitAffixedToUnarmoredItem","affixed-to-weapon":"PF2E.TraitAffixedToWeapon","applied-to-a-basket-bag-or-other-container":"PF2E.TraitAppliedToBasketBagOrContainer","applied-to-a-weapon":"PF2E.TraitAppliedToAWeapon","applied-to-a-wind-powered-vehicle":"PF2E.TraitAppliedToAWindPoweredVehicle","applied-to-a-non-injection-melee-weapon-piercing-damage":"PF2E.TraitAppliedToANoninjectionMeleePiercingWeapon","applied-to-any-item-of-light-or-negligible-bulk":"PF2E.TraitAppliedToAnyItemOfLightOrNegligibleBulk","applied-to-any-visible-article-of-clothing":"PF2E.TraitAppliedToAnyVisibleArticleOfClothing","applied-to-armor":"PF2E.TraitAppliedToArmor","applied-to-armor-or-unarmored-defense-clothing":"PF2E.TraitAppliedToArmorOrUnarmored","applied-to-belt-cape-cloak-or-scarf":"PF2E.TraitAppliedToBeltCapeCloakOrScarf","applied-to-boots-cape-cloak-or-umbrella":"PF2E.TraitAppliedToBootsCapeCloakOrUmbrella","applied-to-buckler-shield":"PF2E.TraitAppliedToBucklerShield","applied-to-dueling-cape-or-shield":"PF2E.TraitAppliedToDuelingCapeOrShield","applied-to-footwear":"PF2E.TraitAppliedToFootwear","applied-to-medium-heavy-armor":"PF2E.TraitAppliedToMediumHeavyArmor","applied-to-shield":"PF2E.TraitAppliedToShield","attached-to-a-thrown-weapon":"PF2E.TraitAttachedToAThrownWeapon","attached-to-crossbow-or-firearm":"PF2E.TraitAttachedToCrossbowOrFirearm","attached-to-crossbow-or-firearm-firing-mechanism":"PF2E.TraitAttachedToCrossbowOrFirearmFiringMechanism","attached-to-crossbow-or-firearm-scope":"PF2E.TraitAttachedToCrossbowOrFirearmScope","attached-to-firearm":"PF2E.TraitAttachedToFirearm","attached-to-firearm-scope":"PF2E.TraitAttachedToFirearmScope","attached-to-ships-bow":"PF2E.TraitAttachedToShipsBow",bonded:"PF2E.TraitBonded",carried:"PF2E.TraitCarried","each-rune-applied-to-a-separate-item-that-has-pockets":"PF2E.TraitEachRuneAppliedToASeparateItemThatHasPockets","etched-onto-a-weapon":"PF2E.TraitEtchedOntoAWeapon","etched-onto-a-shield":"PF2E.TraitEtchedOntoAShield","etched-onto-armor":"PF2E.TraitEtchedOntoArmor","etched-onto-heavy-armor":"PF2E.TraitEtchedOntoHeavyArmor","etched-onto-light-armor":"PF2E.TraitEtchedOntoLightArmor","etched-onto-metal-armor":"PF2E.TraitEtchedOntoMetalArmor","etched-onto-clan-dagger":"PF2E.TraitEtchedOntoAClanDagger","etched-onto-lm-nonmetal-armor":"PF2E.TraitEtchedOntoLightMedNMArmor","etched-onto-med-heavy-armor":"PF2E.TraitEtchedOntoMedHeavyArmor","etched-onto-medium-heavy-metal-armor":"PF2E.TraitEtchedOntoMediumHeavyMetalArmor","etched-onto-bludgeoning-weapon":"PF2E.TraitEtchedOntoABludgeoningWeapon","etched-onto-melee-weapon":"PF2E.TraitEtchedOntoAMeleeWeapon","etched-onto-slashing-melee-weapon":"PF2E.TraitEtchedOntoASlashingMeleeWeapon","etched-onto-piercing-or-slashing-melee-weapon":"PF2E.TraitEtchedOntoAPiercingOrSlashingMeleeWeapon","etched-onto-piercing-or-slashing-weapon":"PF2E.TraitEtchedOntoAPiercingOrSlashingWeapon","etched-onto-weapon-wo-anarchic-rune":"PF2E.TraitEtchedOntoAWeaponWOAxiomaticRune","etched-onto-weapon-wo-axiomatic-rune":"PF2E.TraitEtchedOntoAWeaponWOAnarchicRune","etched-onto-weapon-wo-unholy-rune":"PF2E.TraitEtchedOntoAWeaponWOHolyRune","etched-onto-weapon-wo-holy-rune":"PF2E.TraitEtchedOntoAWeaponWOUnholyRune","etched-onto-melee-weapon-monk":"PF2E.TraitEtchedOntoAMeleeWeaponMonk","etched-onto-thrown-weapon":"PF2E.TraitEtchedOntoAThrownWeapon","held-in-one-hand":"PF2E.TraitHeldOneHand","held-in-one-hand-or-free-standing":"PF2E.TraitHeldOneHandFreeStanding","held-in-one-or-two-hands":"PF2E.TraitHeldOneTwoHands","held-in-two-hands":"PF2E.TraitHeldTwoHands",other:"Other","sewn-into-clothing":"PF2E.TraitSewnIntoClothing","tattooed-on-the-body":"PF2E.TraitTattooedOnTheBody",touched:"PF2E.TraitTouched",worn:"PF2E.TraitWorn",wornamulet:"PF2E.TraitWornAmulet",wornanklets:"PF2E.TraitWornAnklets",wornarmbands:"PF2E.TraitWornArmbands",wornbackpack:"PF2E.TraitWornBackpack",wornbarding:"PF2E.TraitWornBarding",wornbelt:"PF2E.TraitWornBelt",wornbeltpouch:"PF2E.TraitWornBeltPouch",wornboots:"PF2E.TraitWornBoots",wornbracelet:"PF2E.TraitWornBracelet",wornbracers:"PF2E.TraitWornBracers",worncap:"PF2E.TraitWornCap",worncape:"PF2E.TraitWornCape",worncirclet:"PF2E.TraitWornCirclet",worncloak:"PF2E.TraitWornCloak",wornclothing:"PF2E.TraitWornClothing",worncollar:"PF2E.TraitWornCollar",worncrown:"PF2E.TraitWornCrown",wornepaulet:"PF2E.TraitWornEpaulet",worneyeglasses:"PF2E.TraitWornEyeglasses",worneyepiece:"PF2E.TraitWornEyepiece",wornfootwear:"PF2E.TraitWornFootwear",worngarment:"PF2E.TraitWornGarment",worngloves:"PF2E.TraitWornGloves",wornheadwear:"PF2E.TraitWornHeadwear",wornhorseshoes:"PF2E.TraitWornHorseshoes",wornmask:"PF2E.TraitWornMask",wornnecklace:"PF2E.TraitWornNecklace",wornonbelt:"PF2E.TraitWornOnBelt",wornoronehand:"PF2E.TraitWornOrOneHand",wornring:"PF2E.TraitWornRing",wornsaddle:"PF2E.TraitWornSaddle",wornsandles:"PF2E.TraitWornSandles",wornshoes:"PF2E.TraitWornShoes",wornwrist:"PF2E.TraitWornOnWrists","worn-and-attached-to-two-weapons":"PF2E.TraitWornAndAttachedToTwoWeapons","worn-under-armor":"PF2E.TraitWornUnderArmor"},rarityTraits:{common:"PF2E.TraitCommon",uncommon:"PF2E.TraitUncommon",rare:"PF2E.TraitRare",unique:"PF2E.TraitUnique"},magicTraditions,classTraits,ancestryTraits,deityDomains,weaponTraits,otherWeaponTags,armorTraits,otherArmorTags,equipmentTraits,consumableTraits,otherConsumableTags,actionTraits,shieldTraits,spellTraits,featTraits,creatureTraits,kingmakerTraits,npcAttackTraits,hazardTraits,vehicleTraits,traitsDescriptions:traitDescriptions,creatureTypes,weaponHands:{1:"PF2E.WeaponHands1","1+":"PF2E.WeaponHands1Plus",2:"PF2E.WeaponHands2"},itemBonuses:{"-2":"PF2E.ItemBonusMinus2",0:"PF2E.ItemBonus0",1:"PF2E.ItemBonus1",2:"PF2E.ItemBonus2",3:"PF2E.ItemBonus3"},damageDice:{0:"0",1:"1",2:"2",3:"3",4:"4"},damageDie:{d4:"PF2E.DamageDieD4",d6:"PF2E.DamageDieD6",d8:"PF2E.DamageDieD8",d10:"PF2E.DamageDieD10",d12:"PF2E.DamageDieD12"},weaponMAP:{1:"-1/-2",2:"-2/-4",3:"-3/-6",4:"-4/-8",5:"-5/-10"},weaponReload,armorCategories:{unarmored:"PF2E.ArmorTypeUnarmored",light:"PF2E.ArmorTypeLight",medium:"PF2E.ArmorTypeMedium",heavy:"PF2E.ArmorTypeHeavy","light-barding":"PF2E.Item.Armor.Category.light-barding","heavy-barding":"PF2E.Item.Armor.Category.heavy-barding"},armorGroups:{composite:"PF2E.ArmorGroupComposite",chain:"PF2E.ArmorGroupChain",cloth:"PF2E.ArmorGroupCloth",leather:"PF2E.ArmorGroupLeather",plate:"PF2E.ArmorGroupPlate",skeletal:"PF2E.ArmorGroupSkeletal",wood:"PF2E.ArmorGroupWood"},consumableCategories,identification:configFromLocalization(define_EN_JSON_default.PF2E.identification,"PF2E.identification"),preparationType:{prepared:"PF2E.PreparationTypePrepared",spontaneous:"PF2E.PreparationTypeSpontaneous",innate:"PF2E.PreparationTypeInnate",focus:"PF2E.TraitFocus",items:"PF2E.PreparationTypeItems",ritual:"PF2E.Item.Spell.Ritual.Label"},areaTypes:{burst:"PF2E.AreaTypeBurst",cone:"PF2E.AreaTypeCone",cube:"PF2E.AreaTypeCube",emanation:"PF2E.AreaTypeEmanation",line:"PF2E.AreaTypeLine",square:"PF2E.AreaTypeSquare"},areaSizes:{5:"PF2E.AreaSize5",10:"PF2E.AreaSize10",15:"PF2E.AreaSize15",20:"PF2E.AreaSize20",25:"PF2E.AreaSize25",30:"PF2E.AreaSize30",40:"PF2E.AreaSize40",45:"PF2E.AreaSize45",50:"PF2E.AreaSize50",60:"PF2E.AreaSize60",65:"PF2E.AreaSize65",75:"PF2E.AreaSize75",80:"PF2E.AreaSize80",90:"PF2E.AreaSize90",100:"PF2E.AreaSize100",120:"PF2E.AreaSize120",360:"PF2E.AreaSize360",500:"PF2E.AreaSize500",1e3:"PF2E.AreaSize1000",1320:"PF2E.AreaSizeQuarterMile",5280:"PF2E.AreaSize1Mile"},attitude:{hostile:"PF2E.Attitudes.Hostile",unfriendly:"PF2E.Attitudes.Unfriendly",indifferent:"PF2E.Attitudes.Indifferent",friendly:"PF2E.Attitudes.Friendly",helpful:"PF2E.Attitudes.Helpful"},skillList:{acrobatics:"PF2E.SkillAcrobatics",arcana:"PF2E.SkillArcana",athletics:"PF2E.SkillAthletics",crafting:"PF2E.SkillCrafting",deception:"PF2E.SkillDeception",diplomacy:"PF2E.SkillDiplomacy",intimidation:"PF2E.SkillIntimidation",medicine:"PF2E.SkillMedicine",nature:"PF2E.SkillNature",occultism:"PF2E.SkillOccultism",performance:"PF2E.SkillPerformance",religion:"PF2E.SkillReligion",society:"PF2E.SkillSociety",stealth:"PF2E.SkillStealth",survival:"PF2E.SkillSurvival",thievery:"PF2E.SkillThievery",lore:"PF2E.SkillLore"},spellComponents:{V:"PF2E.SpellComponentV",S:"PF2E.SpellComponentS",M:"PF2E.SpellComponentM",F:"PF2E.SpellComponentF"},featCategories,actionTypes:{action:"PF2E.ActionTypeAction",reaction:"PF2E.ActionTypeReaction",free:"PF2E.ActionTypeFree",passive:"PF2E.ActionTypePassive"},actionsNumber:{1:"PF2E.ActionNumber1",2:"PF2E.ActionNumber2",3:"PF2E.ActionNumber3"},actionCategories:{interaction:"PF2E.Item.Action.Category.Interaction",defensive:"PF2E.Item.Action.Category.Defensive",offensive:"PF2E.Item.Action.Category.Offensive",familiar:"PF2E.Item.Action.Category.Familiar"},frequencies:{turn:"PF2E.Duration.turn",round:"PF2E.Duration.round",PT1M:"PF2E.Duration.PT1M",PT10M:"PF2E.Duration.PT10M",PT1H:"PF2E.Duration.PT1H",PT24H:"PF2E.Duration.PT24H",day:"PF2E.Duration.day",P1W:"PF2E.Duration.P1W",P1M:"PF2E.Duration.P1M",P1Y:"PF2E.Duration.P1Y"},timeUnits:{rounds:"PF2E.Time.Unit.Rounds",minutes:"PF2E.Time.Unit.Minutes",hours:"PF2E.Time.Unit.Hours",days:"PF2E.Time.Unit.Days",unlimited:"PF2E.Time.Unit.Unlimited",encounter:"PF2E.Time.Unit.UntilEncounterEnds"},proficiencyLevels:["PF2E.ProficiencyLevel0","PF2E.ProficiencyLevel1","PF2E.ProficiencyLevel2","PF2E.ProficiencyLevel3","PF2E.ProficiencyLevel4"],actorSizes:sizeTypes,actorTypes,speedTypes:{swim:"PF2E.SpeedTypesSwim",climb:"PF2E.SpeedTypesClimb",fly:"PF2E.SpeedTypesFly",burrow:"PF2E.SpeedTypesBurrow"},prerequisitePlaceholders:{prerequisite1:"PF2E.Prerequisite1",prerequisite2:"PF2E.Prerequisite2",prerequisite3:"PF2E.Prerequisite3",prerequisite4:"PF2E.Prerequisite4",prerequisite5:"PF2E.Prerequisite5"},senses,senseAcuity,conditionTypes,pfsFactions:{EA:"PF2E.PFS.Factions.EA",GA:"PF2E.PFS.Factions.GA",HH:"PF2E.PFS.Factions.HH",VS:"PF2E.PFS.Factions.VS",RO:"PF2E.PFS.Factions.RO",VW:"PF2E.PFS.Factions.VW"},pfsSchools:{none:"PF2E.PFS.School.None",scrolls:"PF2E.PFS.School.Scrolls",spells:"PF2E.PFS.School.Spells",swords:"PF2E.PFS.School.Swords"},immunityTypes,languages:mapToObj(LANGUAGES,l=>[l,`PF2E.Actor.Creature.Language.${l}`]),attackEffects:{grab:"PF2E.AttackEffectGrab","improved-grab":"PF2E.AttackEffectImprovedGrab",constrict:"PF2E.AttackEffectConstrict","greater-constrict":"PF2E.AttackEffectGreaterConstrict",knockdown:"PF2E.AttackEffectKnockdown","improved-knockdown":"PF2E.AttackEffectImprovedKnockdown",push:"PF2E.AttackEffectPush","improved-push":"PF2E.AttackEffectImprovedPush",trip:"PF2E.AttackEffectTrip"},worldClock:foundry.utils.mergeObject(configFromLocalization(define_EN_JSON_default.PF2E.WorldClock,"PF2E.WorldClock"),{AR:{yearOffset:2700},IC:{yearOffset:5200},AD:{yearOffset:-95},CE:{yearOffset:0}}),hexplorationActivities:{10:.5,25:1,40:2,55:3,Infinity:4},SETTINGS:{automation:{rulesBasedVision:{name:"PF2E.SETTINGS.Automation.RulesBasedVision.Name",hint:"PF2E.SETTINGS.Automation.RulesBasedVision.Hint"},iwr:{name:"PF2E.SETTINGS.Automation.IWR.Name",hint:"PF2E.SETTINGS.Automation.IWR.Hint"},effectExpiration:{name:"PF2E.SETTINGS.Automation.EffectExpiration.Name",hint:"PF2E.SETTINGS.Automation.EffectExpiration.Hint"},removeExpiredEffects:{name:"PF2E.SETTINGS.Automation.RemoveExpiredEffects.Name",hint:"PF2E.SETTINGS.Automation.RemoveExpiredEffects.Hint"},flankingDetection:{name:"PF2E.SETTINGS.Automation.FlankingDetection.Name",hint:"PF2E.SETTINGS.Automation.FlankingDetection.Hint"},actorsDeadAtZero:{name:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Name",hint:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Hint",neither:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Neither",npcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.NPCsOnly",both:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Both"},lootableNPCs:{name:"PF2E.SETTINGS.Automation.LootableNPCs.Name",hint:"PF2E.SETTINGS.Automation.LootableNPCs.Hint"}},homebrew:{creatureTraits:{name:"PF2E.SETTINGS.Homebrew.CreatureTraits.Name",hint:"PF2E.SETTINGS.Homebrew.CreatureTraits.Hint"},featTraits:{name:"PF2E.SETTINGS.Homebrew.FeatTraits.Name",hint:"PF2E.SETTINGS.Homebrew.FeatTraits.Hint"},languages:{name:"PF2E.SETTINGS.Homebrew.Languages.Name",hint:"PF2E.SETTINGS.Homebrew.Languages.Hint"},spellTraits:{name:"PF2E.SETTINGS.Homebrew.SpellTraits.Name",hint:"PF2E.SETTINGS.Homebrew.SpellTraits.Hint"},weaponCategories:{name:"PF2E.SETTINGS.Homebrew.WeaponCategories.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponCategories.Hint"},weaponGroups:{name:"PF2E.SETTINGS.Homebrew.WeaponGroups.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponGroups.Hint"},baseWeapons:{name:"PF2E.SETTINGS.Homebrew.BaseWeapons.Name",hint:"PF2E.SETTINGS.Homebrew.BaseWeapons.Hint"},weaponTraits:{name:"PF2E.SETTINGS.Homebrew.WeaponTraits.Name",hint:"PF2E.SETTINGS.Homebrew.WeaponTraits.Hint"},equipmentTraits:{name:"PF2E.SETTINGS.Homebrew.EquipmentTraits.Name",hint:"PF2E.SETTINGS.Homebrew.EquipmentTraits.Hint"}},worldClock:{name:"PF2E.SETTINGS.WorldClock.Name",label:"PF2E.SETTINGS.WorldClock.Label",hint:"PF2E.SETTINGS.WorldClock.Hint",dateTheme:{name:"PF2E.SETTINGS.WorldClock.DateTheme.Name",hint:"PF2E.SETTINGS.WorldClock.DateTheme.Hint",AR:"PF2E.SETTINGS.WorldClock.DateTheme.AR",AD:"PF2E.SETTINGS.WorldClock.DateTheme.AD",CE:"PF2E.SETTINGS.WorldClock.DateTheme.CE"},timeConvention:{name:"PF2E.SETTINGS.WorldClock.TimeConvention.Name",hint:"PF2E.SETTINGS.WorldClock.TimeConvention.Hint",twentyFour:"PF2E.SETTINGS.WorldClock.TimeConvention.TwentyFour",twelve:"PF2E.SETTINGS.WorldClock.TimeConvention.Twelve"},showClockButton:{name:"PF2E.SETTINGS.WorldClock.ShowClockButton.Name",hint:"PF2E.SETTINGS.WorldClock.ShowClockButton.Hint"},playersCanView:{name:"PF2E.SETTINGS.WorldClock.PlayersCanView.Name",hint:"PF2E.SETTINGS.WorldClock.PlayersCanView.Hint"},syncDarkness:{name:"PF2E.SETTINGS.WorldClock.SyncDarkness.Name",hint:"PF2E.SETTINGS.WorldClock.SyncDarkness.Hint"},syncDarknessScene:{name:"PF2E.SETTINGS.WorldClock.SyncDarknessScene.Name",hint:"PF2E.SETTINGS.WorldClock.SyncDarknessScene.Hint",enabled:"PF2E.SETTINGS.EnabledDisabled.Enabled",default:"PF2E.SETTINGS.EnabledDisabled.Default",disabled:"PF2E.SETTINGS.EnabledDisabled.Disabled"},worldCreatedOn:{name:"PF2E.SETTINGS.WorldClock.WorldCreatedOn.Name",hint:"PF2E.SETTINGS.WorldClock.WorldCreatedOn.Hint"}},CampaignFeats:{name:"PF2E.SETTINGS.CampaignFeats.Name",hint:"PF2E.SETTINGS.CampaignFeats.Hint"}},Actor:{documentClasses:{army:ArmyPF2e,character:CharacterPF2e,npc:NPCPF2e,hazard:HazardPF2e,loot:LootPF2e,familiar:FamiliarPF2e,party:PartyPF2e,vehicle:VehiclePF2e}},Item:{documentClasses:{action:AbilityItemPF2e,affliction:AfflictionPF2e,ancestry:AncestryPF2e,armor:ArmorPF2e,background:BackgroundPF2e,backpack:ContainerPF2e,book:BookPF2e,campaignFeature:CampaignFeaturePF2e,class:ClassPF2e,condition:ConditionPF2e,consumable:ConsumablePF2e,deity:DeityPF2e,effect:EffectPF2e,equipment:EquipmentPF2e,feat:FeatPF2e,heritage:HeritagePF2e,kit:KitPF2e,lore:LorePF2e,melee:MeleePF2e,shield:ShieldPF2e,spell:SpellPF2e,spellcastingEntry:SpellcastingEntryPF2e,treasure:TreasurePF2e,weapon:WeaponPF2e},traits:{action:actionTraits,affliction:actionTraits,armor:armorTraits,ancestry:creatureTraits,background:backgroundTraits,backpack:equipmentTraits,book:equipmentTraits,campaignFeature:kingmakerTraits,consumable:consumableTraits,equipment:equipmentTraits,feat:featTraits,heritage:featTraits,kit:classTraits,melee:npcAttackTraits,shield:shieldTraits,spell:spellTraits,weapon:weaponTraits}},JournalEntry:{sheetClass:JournalSheetPF2e},Canvas:{darkness:{default:CONFIG.Canvas.darknessColor,gmVision:9473209}}};function registerHandlebarsHelpers(){Handlebars.registerHelper("pad",(value,length,character)=>`${value}`.padStart(length,character)),Handlebars.registerHelper("add",(a,b)=>Number(a)+Number(b)),Handlebars.registerHelper("nor",(...args)=>!args.slice(0,-1).some(a=>!!a)),Handlebars.registerHelper("any",(...args)=>args.slice(0,-1).some(a=>!!a)),Handlebars.registerHelper("disabled",condition=>condition?"disabled":""),Handlebars.registerHelper("coalesce",(...args)=>args.find(a=>a!=null)??null),Handlebars.registerHelper("lower",str=>String(str).toLowerCase()),Handlebars.registerHelper("capitalize",str=>String(str).capitalize()),Handlebars.registerHelper("multiply",(a,b)=>Number(a)*Number(b)),Handlebars.registerHelper("percentage",(value,max)=>Number(value)*100/Number(max)),Handlebars.registerHelper("ordinal",value=>{const numericValue=Number(value);return isNaN(numericValue)?null:ordinalString(numericValue)}),Handlebars.registerHelper("sluggify",text=>sluggify(String(text))),Handlebars.registerHelper("json",data=>JSON.stringify(data)),Handlebars.registerHelper("actionGlyph",(value,options)=>{const glyph=getActionGlyph(value??"");return glyph?`${glyph}`:options?.hash.fallback?Handlebars.escapeExpression(value):null}),Handlebars.registerHelper("times",(count,options)=>[...Array(Number(count)||0).keys()].map(i=>options.fn(i,{data:options.data,blockParams:[i]})).join("")),Handlebars.registerHelper("concat",(...params)=>params.slice(0,-1).join("")),Handlebars.registerHelper("developMode",function(options){return""}),Handlebars.registerHelper("isNumber",value=>typeof value=="number"),Handlebars.registerHelper("isNullish",value=>value==null),Handlebars.registerHelper("signedInteger",(value,options)=>{const number=Number(value)||0,emptyStringZero=!!options.hash.emptyStringZero,zeroIsNegative=!!options.hash.zeroIsNegative;return signedInteger(number,{emptyStringZero,zeroIsNegative})}),Handlebars.registerHelper("coinLabel",value=>value?"value"in value?new CoinsPF2e(value.value):new CoinsPF2e(value):null),Handlebars.registerHelper("includes",(arr,element)=>Array.isArray(arr)?arr.includes(element):arr instanceof Set?arr.has(element):arr&&typeof arr=="object"?(typeof element=="number"||typeof element=="string")&&element in arr:!1),Handlebars.registerHelper("raw",function(options){return options.fn(this)})}__name(registerHandlebarsHelpers,"registerHandlebarsHelpers"),__name2(registerHandlebarsHelpers,"registerHandlebarsHelpers");function registerFonts(){CONFIG.fontDefinitions.Eczar={editor:!0,fonts:[{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/eczar-v16-latin-ext_latin-800.woff2"],style:"normal",weight:"800"}]},CONFIG.fontDefinitions.Gelasio={editor:!1,fonts:[{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-500italic.woff2"],style:"italic",weight:"500"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-600italic.woff2"],style:"italic",weight:"600"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/gelasio-v9-latin-ext_latin-700italic.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions["La Belle Aurore"]={editor:!0,fonts:[{urls:["systems/pf2e/fonts/la-belle-aurore-v16-latin-regular.woff2"],style:"normal",weight:"400"}]},CONFIG.fontDefinitions.Pathfinder2eActions={editor:!1,fonts:[{urls:["systems/pf2e/fonts/pathfinder-2e-actions.woff2"]}]},CONFIG.fontDefinitions.Roboto={editor:!0,fonts:[{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-500italic.woff2"],style:"italic",weight:"500"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-700italic.woff2"],style:"italic",weight:"700"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-900.woff2"],style:"normal",weight:"900"},{urls:["systems/pf2e/fonts/roboto-v30-latin-ext_latin_cyrillic-900italic.woff2"],style:"italic",weight:"900"}]},CONFIG.fontDefinitions["Roboto Condensed"]={editor:!1,fonts:[{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-italic.woff2"],style:"italic",weight:"400"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"700"},{urls:["systems/pf2e/fonts/roboto-condensed-v24-latin-ext_latin_cyrillic-700italic.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions["Roboto Mono"]={editor:!1,fonts:[{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/roboto-mono-v21-latin-ext_latin_cyrillic-700.woff2"],style:"italic",weight:"700"}]},CONFIG.fontDefinitions.Signika={editor:!0,fonts:[{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-600.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/signika-v19-latin-ext_latin-700.woff2"],style:"normal",weight:"700"}]},CONFIG.fontDefinitions.Vollkorn={editor:!0,fonts:[{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-regular.woff2"],style:"normal",weight:"400"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-500.woff2"],style:"normal",weight:"500"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-700.woff2"],style:"normal",weight:"600"},{urls:["systems/pf2e/fonts/vollkorn-v20-latin-ext_latin_cyrillic-900.woff2"],style:"normal",weight:"700"}]},delete CONFIG.fontDefinitions.Courier,delete CONFIG.fontDefinitions.Times,CONFIG._fontFamilies=[]}__name(registerFonts,"registerFonts"),__name2(registerFonts,"registerFonts");function registerKeybindings(){game.keybindings.register("pf2e","cycle-token-stack",{name:"PF2E.Keybinding.CycleTokenStack.Label",hint:"PF2E.Keybinding.CycleTokenStack.Hint",editable:[{key:"KeyZ",modifiers:[]}],onUp:()=>canvas.tokens.cycleStack()}),game.keybindings.register("pf2e","toggle-party-sheet",{name:"PF2E.Keybinding.TogglePartySheet.Label",hint:"PF2E.Keybinding.TogglePartySheet.Hint",editable:[{key:"KeyP",modifiers:[]}],onDown:()=>{const party=(()=>{if(game.user.isGM){const token=canvas.ready&&canvas.tokens.controlled.length===1?canvas.tokens.controlled[0]:null;return token?.actor?.isOfType("party")?token.actor:game.actors.party}else if(game.user.character?.isOfType("character")){const pcParties=Array.from(game.user.character.parties);return pcParties.find(p=>p.active)??pcParties.at(0)??null}return null})();if(!party)return!1;const{sheet}=party;return sheet.rendered?sheet._minimized?sheet.maximize():sheet.close():sheet.render(!0),!0}}),!game.modules.get("gm-vision")?.active&&!game.modules.get("perfect-vision")?.active&&game.keybindings.register("pf2e","gm-vision",{name:"PF2E.Keybinding.GMVision.Label",hint:"PF2E.Keybinding.GMVision.Hint",editable:[{key:"KeyG",modifiers:["Control"]}],restricted:!0,onDown:context=>(context.event.preventDefault(),!0),onUp:()=>(ui.controls.control?.name==="lighting"?ui.controls.control.tools.find(t=>t.name==="gm-vision")?.onClick?.():game.settings.set("pf2e","gmVision",!game.settings.get("pf2e","gmVision")),!0)})}__name(registerKeybindings,"registerKeybindings"),__name2(registerKeybindings,"registerKeybindings");function registerTemplates(){const templatePaths=["systems/pf2e/templates/chat/check/roll.hbs","systems/pf2e/templates/chat/check/target-dc-result.hbs","systems/pf2e/templates/chat/damage/damage-taken.hbs","systems/pf2e/templates/dice/damage-roll.hbs","systems/pf2e/templates/dice/damage-tooltip.hbs","systems/pf2e/templates/actors/character/partials/elemental-blast.hbs","systems/pf2e/templates/actors/character/partials/feat-slot.hbs","systems/pf2e/templates/actors/character/partials/header.hbs","systems/pf2e/templates/actors/character/partials/sidebar.hbs","systems/pf2e/templates/actors/character/partials/strike.hbs","systems/pf2e/templates/actors/character/tabs/general.hbs","systems/pf2e/templates/actors/character/tabs/actions.hbs","systems/pf2e/templates/actors/character/tabs/biography.hbs","systems/pf2e/templates/actors/character/tabs/effects.hbs","systems/pf2e/templates/actors/character/tabs/feats.hbs","systems/pf2e/templates/actors/character/tabs/inventory.hbs","systems/pf2e/templates/actors/character/tabs/pfs.hbs","systems/pf2e/templates/actors/character/tabs/proficiencies.hbs","systems/pf2e/templates/actors/character/tabs/spellcasting.hbs","systems/pf2e/templates/actors/character/tabs/crafting.hbs","systems/pf2e/templates/actors/hazard/partials/header.hbs","systems/pf2e/templates/actors/hazard/partials/sidebar.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/main.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/activities.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/world.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/features.hbs","systems/pf2e/templates/actors/party/kingdom/tabs/ongoing.hbs","systems/pf2e/templates/actors/party/kingdom/partials/build-entry-boosts.hbs","systems/pf2e/templates/actors/party/kingdom/partials/settlement.hbs","systems/pf2e/templates/actors/partials/action.hbs","systems/pf2e/templates/actors/partials/carry-type.hbs","systems/pf2e/templates/actors/partials/coinage.hbs","systems/pf2e/templates/actors/partials/dying-pips.hbs","systems/pf2e/templates/actors/partials/effects.hbs","systems/pf2e/templates/actors/partials/encumbrance.hbs","systems/pf2e/templates/actors/partials/inventory.hbs","systems/pf2e/templates/actors/partials/item-line.hbs","systems/pf2e/templates/actors/partials/modifiers-tooltip.hbs","systems/pf2e/templates/actors/partials/spell-collection.hbs","systems/pf2e/templates/actors/partials/toggles.hbs","systems/pf2e/templates/actors/partials/total-bulk.hbs","systems/pf2e/templates/actors/crafting-entry-alchemical.hbs","systems/pf2e/templates/actors/crafting-entry-list.hbs","systems/pf2e/templates/actors/character/partials/proficiencylevels-dropdown.hbs","systems/pf2e/templates/actors/character/icons/d20.hbs","systems/pf2e/templates/actors/character/icons/pfs.hbs","systems/pf2e/templates/actors/character/icons/plus.hbs","systems/pf2e/templates/actors/npc/tabs/main.hbs","systems/pf2e/templates/actors/npc/tabs/inventory.hbs","systems/pf2e/templates/actors/npc/tabs/effects.hbs","systems/pf2e/templates/actors/npc/tabs/spells.hbs","systems/pf2e/templates/actors/npc/tabs/notes.hbs","systems/pf2e/templates/actors/npc/partials/header.hbs","systems/pf2e/templates/actors/npc/partials/sidebar.hbs","systems/pf2e/templates/actors/npc/partials/action.hbs","systems/pf2e/templates/actors/npc/partials/attack.hbs","systems/pf2e/templates/items/action-details.hbs","systems/pf2e/templates/items/action-sidebar.hbs","systems/pf2e/templates/items/activation-panel.hbs","systems/pf2e/templates/items/affliction-details.hbs","systems/pf2e/templates/items/affliction-sidebar.hbs","systems/pf2e/templates/items/ancestry-details.hbs","systems/pf2e/templates/items/ancestry-sidebar.hbs","systems/pf2e/templates/items/armor-details.hbs","systems/pf2e/templates/items/background-details.hbs","systems/pf2e/templates/items/backpack-details.hbs","systems/pf2e/templates/items/book-details.hbs","systems/pf2e/templates/items/campaign-feature-details.hbs","systems/pf2e/templates/items/campaign-feature-sidebar.hbs","systems/pf2e/templates/items/class-details.hbs","systems/pf2e/templates/items/condition-details.hbs","systems/pf2e/templates/items/condition-sidebar.hbs","systems/pf2e/templates/items/consumable-details.hbs","systems/pf2e/templates/items/deity-details.hbs","systems/pf2e/templates/items/effect-details.hbs","systems/pf2e/templates/items/effect-sidebar.hbs","systems/pf2e/templates/items/equipment-details.hbs","systems/pf2e/templates/items/feat-details.hbs","systems/pf2e/templates/items/feat-sidebar.hbs","systems/pf2e/templates/items/heritage-details.hbs","systems/pf2e/templates/items/heritage-sidebar.hbs","systems/pf2e/templates/items/kit-details.hbs","systems/pf2e/templates/items/lore-details.hbs","systems/pf2e/templates/items/melee-details.hbs","systems/pf2e/templates/items/mystify-panel.hbs","systems/pf2e/templates/items/physical-sidebar.hbs","systems/pf2e/templates/items/rules-panel.hbs","systems/pf2e/templates/items/shield-details.hbs","systems/pf2e/templates/items/spell-details.hbs","systems/pf2e/templates/items/spell-overlay.hbs","systems/pf2e/templates/items/treasure-details.hbs","systems/pf2e/templates/items/weapon-details.hbs","systems/pf2e/templates/items/partials/ability-activation.hbs","systems/pf2e/templates/items/partials/duration.hbs","systems/pf2e/templates/items/partials/other-tags.hbs","systems/pf2e/templates/items/partials/self-applied-effect.hbs","systems/pf2e/templates/actors/loot/inventory.hbs","systems/pf2e/templates/actors/loot/sidebar.hbs","systems/pf2e/templates/actors/vehicle/vehicle-header.hbs","systems/pf2e/templates/actors/vehicle/sidebar.hbs","systems/pf2e/templates/actors/vehicle/tabs/details.hbs","systems/pf2e/templates/actors/vehicle/tabs/actions.hbs","systems/pf2e/templates/actors/vehicle/tabs/inventory.hbs","systems/pf2e/templates/actors/vehicle/tabs/description.hbs","systems/pf2e/templates/actors/vehicle/tabs/effects.hbs","systems/pf2e/templates/compendium-browser/settings/settings.hbs","systems/pf2e/templates/compendium-browser/settings/pack-settings.hbs","systems/pf2e/templates/compendium-browser/settings/source-settings.hbs","systems/pf2e/templates/compendium-browser/filters.hbs","systems/pf2e/templates/chat/action/header.hbs","systems/pf2e/templates/system/actions/repair/chat-button-partial.hbs","systems/pf2e/templates/system/actions/repair/repair-result-partial.hbs","systems/pf2e/templates/system/actions/repair/item-heading-partial.hbs","systems/pf2e/templates/scene/token/partials/appearance.hbs","systems/pf2e/templates/scene/token/partials/identity.hbs","systems/pf2e/templates/scene/token/partials/lighting.hbs","systems/pf2e/templates/partials/publication-data.hbs"];loadTemplates(templatePaths)}__name(registerTemplates,"registerTemplates"),__name2(registerTemplates,"registerTemplates");class PackLoader{static{__name(this,"PackLoader")}static{__name2(this,"PackLoader")}loadedSources=[];sourcesSettings;constructor(){this.sourcesSettings=game.settings.get("pf2e","compendiumBrowserSources")}async*loadPacks(documentType,packs,indexFields){const localize=localizer("PF2E.ProgressBar"),sources=this.#getSources(),progress=new Progress({max:packs.length});for(const packId of packs){const pack=game.packs.get(packId);if(!pack){progress.advance();continue}if(progress.advance({label:localize("LoadingPack",{pack:pack.metadata.label})}),pack.documentName===documentType){const index=await pack.getIndex({fields:indexFields});if((index.contents.at(0)??{}).system){const filteredIndex=this.#createFilteredIndex(index,sources);this.#setModuleArt(packId,filteredIndex),yield{pack,index:filteredIndex}}else ui.notifications.warn(game.i18n.format("PF2E.BrowserWarnPackNotLoaded",{pack:pack.collection}))}}progress.close({label:localize("LoadingComplete")})}#setModuleArt(packName,index){if(packName.startsWith("pf2e."))for(const record of index){const uuid=`Compendium.${packName}.${record._id}`,actorArt=game.pf2e.system.moduleArt.map.get(uuid)?.img;record.img=actorArt??record.img}}#getSources(){const sources=new Set;for(const source of Object.values(this.sourcesSettings.sources))source?.load&&sources.add(source.name);return sources}#createFilteredIndex(index,sources){if(sources.size===0||game.user.isGM&&this.sourcesSettings.ignoreAsGM)return index;const filteredIndex=new Collection,knownSources=Object.values(this.sourcesSettings.sources).map(value=>value?.name);for(const data of index){const source=this.#getSourceFromDocument(data);(!source&&this.sourcesSettings.showEmptySources||sources.has(source)||this.sourcesSettings.showUnknownSources&&source&&!knownSources.includes(source))&&filteredIndex.set(data._id,foundry.utils.deepClone(data))}return filteredIndex}async updateSources(packs){await this.#loadSources(packs);for(const source of this.loadedSources){const slug=sluggify(source);this.sourcesSettings.sources[slug]===void 0&&(this.sourcesSettings.sources[slug]={load:this.sourcesSettings.showUnknownSources,name:source})}this.sourcesSettings.sources=Object.fromEntries(Object.entries(this.sourcesSettings.sources).sort((a,b)=>a[0].localeCompare(b[0],game.i18n.lang)))}async#loadSources(packs){const localize=localizer("PF2E.ProgressBar"),progress=new Progress({max:packs.length}),loadedSources=new Set,indexFields=["system.publication.title","system.source.value"],knownDocumentTypes=["Actor","Item"];for(const packId of packs){const pack=game.packs.get(packId);if(!pack||!knownDocumentTypes.includes(pack.documentName)){progress.advance();continue}progress.advance({label:localize("LoadingPack",{pack:pack?.metadata.label??""})});const index=await pack.getIndex({fields:indexFields});for(const element of index){const source=this.#getSourceFromDocument(element);source&&source!==""&&loadedSources.add(source)}}progress.close({label:localize("LoadingComplete")});const loadedSourcesArray=Array.from(loadedSources).sort();this.loadedSources=loadedSourcesArray}#getSourceFromDocument(document2){const{system}=document2;return isObject$1(system)?system.publication?.title??system.details?.publication?.title??system.source?.value??system.details?.source?.value??"":""}reset(){this.loadedSources=[]}async hardReset(packs){this.reset(),this.sourcesSettings={ignoreAsGM:!0,showEmptySources:!0,showUnknownSources:!0,sources:{}},await this.updateSources(packs)}}class CompendiumBrowserTab{static{__name(this,"CompendiumBrowserTab")}static{__name2(this,"CompendiumBrowserTab")}browser;indexData=[];currentIndex=[];isInitialized=!1;totalItemCount=0;scrollLimit=100;#domParser=new DOMParser;searchFields=[];storeFields=[];constructor(browser){this.browser=browser}async init(){await this.loadData(),this.searchEngine=new MiniSearch({fields:this.searchFields,idField:"uuid",processTerm:t=>t.length>1&&!CompendiumDirectoryPF2e.STOP_WORDS.has(t)?t.toLocaleLowerCase(game.i18n.lang):null,storeFields:this.storeFields,searchOptions:{combineWith:"AND",prefix:!0}}),this.searchEngine.addAll(this.indexData),this.defaultFilterData=foundry.utils.deepClone(this.filterData),this.isInitialized=!0}async open(filter2){if(filter2){if(!this.isInitialized)throw ErrorPF2e(`Tried to pass an initial filter to uninitialized tab "${this.tabName}"`);this.filterData=filter2}return this.browser.loadTab(this.tabName)}getIndexData(start){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);return this.currentIndex=(()=>{const searchText=this.filterData.search.text;if(searchText){const searchResult=this.searchEngine.search(searchText);return this.sortResult(searchResult.filter(this.filterIndexData.bind(this)))}return this.sortResult(this.indexData.filter(this.filterIndexData.bind(this)))})(),this.totalItemCount=this.currentIndex.length,this.currentIndex.slice(start,this.scrollLimit)}async getFilterData(){return this.isInitialized||await this.init(),foundry.utils.deepClone(this.defaultFilterData)}resetFilters(){this.filterData=foundry.utils.deepClone(this.defaultFilterData)}isOfType(...types){return types.some(t=>this.tabName===t)}filterTraits(traits,selected,condition){const selectedTraits=selected.filter(s=>!s.not).map(s=>s.value),notTraits=selected.filter(t=>t.not).map(s=>s.value);return!((selectedTraits.length||notTraits.length)&&(notTraits.some(t=>traits.includes(t))||!(condition==="and"?selectedTraits.every(t=>traits.includes(t)):selectedTraits.some(t=>traits.includes(t)))))}async renderResults(start){if(!this.templatePath)throw ErrorPF2e(`Tab "${this.tabName}" has no valid template path.`);const indexData=this.getIndexData(start),liElements=[];for(const entry of indexData){const htmlString=await renderTemplate(this.templatePath,{entry,filterData:this.filterData}),html=this.#domParser.parseFromString(htmlString,"text/html");liElements.push(html.body.firstElementChild)}return liElements}sortResult(result){const{order}=this.filterData,lang=game.i18n.lang,sorted=result.sort((entryA,entryB)=>{switch(order.by){case"name":return entryA.name.localeCompare(entryB.name,lang);case"level":return entryA.level-entryB.level||entryA.name.localeCompare(entryB.name,lang);case"price":return entryA.priceInCopper-entryB.priceInCopper||entryA.name.localeCompare(entryB.name,lang);case"rank":return entryA.rank-entryB.rank||entryA.name.localeCompare(entryB.name,lang);default:return 0}});return order.direction==="asc"?sorted:sorted.reverse()}parseRangeFilterInput(_name,lower,upper){return{min:Number(lower)||0,max:Number(upper)||0,inputMin:lower,inputMax:upper}}arrayIncludes(array,other){return other.some(value=>array.includes(value))}generateCheckboxOptions(configData,sort=!0){const localized=Object.entries(configData).reduce((result,[key,label])=>({...result,[key]:game.i18n.localize(label)}),{});return Object.entries(sort?this.sortedConfig(localized):localized).reduce((result,[key,label])=>({...result,[key]:{label,selected:!1}}),{})}generateMultiselectOptions(optionsRecord,sort=!0){const options=Object.entries(optionsRecord).map(([value,label])=>({value,label:game.i18n.localize(label)}));return sort&&options.sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang)),options}generateSourceCheckboxOptions(sources){return[...sources].sort().reduce((result,source)=>({...result,[sluggify(source)]:{label:source,selected:!1}}),{})}sortedConfig(obj){return Object.fromEntries([...Object.entries(obj)].sort((entryA,entryB)=>entryA[1].localeCompare(entryB[1],game.i18n.lang)))}hasAllIndexFields(data,indexFields){for(const field of indexFields)if(foundry.utils.getProperty(data,field)===void 0&&!/\.(?:source|publication)/.test(field))return!1;return!0}#getRollTableResults({initial=0,weight=1}){return this.currentIndex.flatMap((e,i)=>{const data=fromUuidSync(e.uuid);if(!data?.pack||!data._id||!("name"in data))return[];const rangeMinMax=initial+i+1;return{text:data.name,type:CONST.TABLE_RESULT_TYPES.COMPENDIUM,collection:data.pack,resultId:data._id,img:e.img,weight,range:[rangeMinMax,rangeMinMax],drawn:!1}})}async createRollTable(){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);const content=await renderTemplate("systems/pf2e/templates/compendium-browser/roll-table-dialog.hbs",{count:this.currentIndex.length});Dialog.confirm({content,title:game.i18n.localize("PF2E.CompendiumBrowser.RollTable.CreateLabel"),yes:async $html=>{const html=$html[0],name2=htmlQuery(html,"input[name=name]")?.value||game.i18n.localize("PF2E.CompendiumBrowser.Title"),weight=Number(htmlQuery(html,"input[name=weight]")?.value)||1,results=this.#getRollTableResults({weight});(await RollTable.create({name:name2,results,formula:`1d${results.length}`}))?.sheet.render(!0)}})}async addToRollTable(){if(!this.isInitialized)throw ErrorPF2e(`Compendium Browser Tab "${this.tabName}" is not initialized!`);const content=await renderTemplate("systems/pf2e/templates/compendium-browser/roll-table-dialog.hbs",{count:this.currentIndex.length,rollTables:game.tables.contents});Dialog.confirm({title:game.i18n.localize("PF2E.CompendiumBrowser.RollTable.SelectTableTitle"),content,yes:async $html=>{const html=$html[0],option=htmlQuery(html,"select[name=roll-table]")?.selectedOptions[0];if(!option)return;const weight=Number(htmlQuery(html,"input[name=weight]")?.value)||1,table=game.tables.get(option.value,{strict:!0});await table.createEmbeddedDocuments("TableResult",this.#getRollTableResults({initial:table.results.size,weight})),table?.sheet.render(!0)}})}}class CompendiumBrowserActionTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserActionTab")}static{__name2(this,"CompendiumBrowserActionTab")}tabName="action";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/action.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","traits","source","category","actionType"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading actions");const actions=[],indexFields=["img","system.actionType.value","system.category","system.traits.value","system.actionType.value","system.publication","system.source"],publications=new Set;for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("action"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loading`);for(const actionData of index)if(actionData.type==="action"){if(!this.hasAllIndexFields(actionData,indexFields)){console.warn(`Action '${actionData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}actionData.system.actionType.value==="passive"&&(actionData.img=getActionIcon("passive"));const{system}=actionData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),actions.push({type:actionData.type,name:actionData.name,img:actionData.img,uuid:`Compendium.${pack.collection}.${actionData._id}`,traits:actionData.system.traits.value.map(t=>t.replace(/^hb_/,"")),actionType:actionData.system.actionType.value,category:actionData.system.category,source:sourceSlug})}}this.indexData=actions,this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.actionTraits),this.filterData.checkboxes.types.options=this.generateCheckboxOptions(CONFIG.PF2E.actionTypes),this.filterData.checkboxes.category.options=this.generateCheckboxOptions(pick(CONFIG.PF2E.actionCategories,["familiar"])),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading actions")}filterIndexData(entry){const{checkboxes,multiselects}=this.filterData;return!(checkboxes.types.selected.length&&!checkboxes.types.selected.includes(entry.actionType)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source))}prepareFilterData(){return{checkboxes:{types:{isExpanded:!0,label:"PF2E.ActionActionTypeLabel",options:{},selected:[]},category:{isExpanded:!0,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"name",direction:"asc",options:{name:"Name"}},search:{text:""}}}}class CompendiumBrowserBestiaryTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserBestiaryTab")}static{__name2(this,"CompendiumBrowserBestiaryTab")}tabName="bestiary";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/bestiary.hbs";index=["img","system.details.level.value","system.details.publication.title","system.details.source.value","system.traits"];searchFields=["name"];storeFields=["type","name","img","uuid","level","actorSize","traits","rarity","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){const bestiaryActors=[],publications=new Set,indexFields=[...this.index];for await(const{pack,index}of this.browser.packLoader.loadPacks("Actor",this.browser.loadedPacks("bestiary"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const actorData of index.filter(d=>d.type==="npc")){if(!this.hasAllIndexFields(actorData,this.index)){console.warn(`Actor '${actorData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const{details}=actorData.system,pubSource=String(details.publication?.title??details.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),bestiaryActors.push({type:actorData.type,name:actorData.name,img:actorData.img,uuid:`Compendium.${pack.collection}.${actorData._id}`,level:actorData.system.details.level.value,actorSize:actorData.system.traits.size.value,traits:actorData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:actorData.system.traits.rarity,source:sourceSlug})}console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loaded`)}this.indexData=bestiaryActors,this.filterData.checkboxes.sizes.options=this.generateCheckboxOptions(CONFIG.PF2E.actorSizes),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.creatureTraits),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading Bestiary actors")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.sizes.selected.length&&!checkboxes.sizes.selected.includes(entry.actorSize)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{sizes:{isExpanded:!0,label:"PF2E.BrowserFilterSizes",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:-1,upperLimit:25,min:-1,max:25,step:1}}},search:{text:""}}}}class CompendiumBrowserCampaignFeaturesTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserCampaignFeaturesTab")}static{__name2(this,"CompendiumBrowserCampaignFeaturesTab")}tabName="campaignFeature";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/feat.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","traits","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading feats");const feats=[],publications=new Set,indexFields=["img","system.actionType.value","system.actions.value","system.category","system.level.value","system.prerequisites.value","system.traits","system.publication","system.source"];for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("campaignFeature"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const featData of index.filter(i=>i.type==="campaignFeature")){featData.filters={};const{system}=featData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),feats.push({type:featData.type,name:featData.name,img:featData.img,uuid:`Compendium.${pack.collection}.${featData._id}`,level:featData.system.level?.value,category:featData.system.category,traits:featData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:featData.system.traits.rarity,source:sourceSlug})}}this.indexData=feats,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(KINGMAKER_CATEGORIES),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.kingmakerTraits),console.debug("PF2e System | Compendium Browser | Finished loading feats")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData,entryLevel=entry.level??0;return!(!(entryLevel>=sliders.level.values.min&&entryLevel<=sliders.level.values.max)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!1,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:20,min:0,max:20,step:1}}},search:{text:""}}}}class CompendiumBrowserEquipmentTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserEquipmentTab")}static{__name2(this,"CompendiumBrowserEquipmentTab")}tabName="equipment";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/equipment.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","group","price","priceInCopper","traits","rarity","source"];#localizeCoins=localizer("PF2E.CurrencyAbbreviations");constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading inventory items");const inventoryItems=[],itemTypes=["weapon","shield","armor","equipment","consumable","treasure","backpack","kit"],baseFields=["img","system.price","system.traits","system.publication","system.source"],physicalItemFields=[...baseFields,"system.level.value"],runedItemFields=[...physicalItemFields,"system.runes"],armorAndWeaponFields=[...runedItemFields,"system.category","system.group"],indexFields=uniq([...armorAndWeaponFields]).sort(),publications=new Set;for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("equipment"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const itemData of index)if(!(itemData.type==="treasure"&&itemData.system.stackGroup==="coins")&&itemTypes.includes(itemData.type)){if((()=>{switch(itemData.type){case"armor":case"weapon":return!this.hasAllIndexFields(itemData,armorAndWeaponFields);case"kit":return!this.hasAllIndexFields(itemData,baseFields);case"shield":return!this.hasAllIndexFields(itemData,runedItemFields);default:return!this.hasAllIndexFields(itemData,physicalItemFields)}})()){console.warn(`Item '${itemData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const priceValue=itemData.system.price.value,priceCoins=typeof priceValue=="string"?CoinsPF2e.fromString(priceValue):new CoinsPF2e(priceValue),coinValue=priceCoins.copperValue,{system}=itemData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource);const traits=itemData.system.traits.value??[],runes=itemData.system.runes,traditionTraits=MAGIC_TRADITIONS;!traits.some(t=>traditionTraits.has(t))&&["armor","shield","weapon"].includes(itemData.type)&&(runes.potency||runes.reinforcing||runes.resilient||runes.striking)&&traits.push("magical"),inventoryItems.push({type:itemData.type,name:itemData.name,img:itemData.img,uuid:`Compendium.${pack.collection}.${itemData._id}`,level:itemData.system.level?.value??0,category:itemData.system.category??"",group:itemData.system.group??"",price:priceCoins,priceInCopper:coinValue,traits:uniq(itemData.system.traits.value),rarity:itemData.system.traits.rarity,source:sourceSlug})}}this.indexData=inventoryItems,this.filterData.checkboxes.armorTypes.options=this.generateCheckboxOptions(CONFIG.PF2E.armorCategories),foundry.utils.mergeObject(this.filterData.checkboxes.armorTypes.options,this.generateCheckboxOptions(CONFIG.PF2E.armorGroups)),this.filterData.checkboxes.weaponTypes.options=this.generateCheckboxOptions(CONFIG.PF2E.weaponCategories),foundry.utils.mergeObject(this.filterData.checkboxes.weaponTypes.options,this.generateCheckboxOptions(CONFIG.PF2E.weaponGroups)),this.filterData.multiselects.traits.options=this.generateMultiselectOptions({...CONFIG.PF2E.armorTraits,...CONFIG.PF2E.consumableTraits,...CONFIG.PF2E.equipmentTraits,...CONFIG.PF2E.shieldTraits,...CONFIG.PF2E.weaponTraits}),this.filterData.checkboxes.itemTypes.options=this.generateCheckboxOptions({weapon:"TYPES.Item.weapon",shield:"TYPES.Item.shield",armor:"TYPES.Item.armor",equipment:"TYPES.Item.equipment",consumable:"TYPES.Item.consumable",treasure:"TYPES.Item.treasure",backpack:"TYPES.Item.backpack",kit:"TYPES.Item.kit"}),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading inventory items")}filterIndexData(entry){const{checkboxes,multiselects,ranges,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||!(entry.priceInCopper>=ranges.price.values.min&&entry.priceInCopper<=ranges.price.values.max)||checkboxes.itemTypes.selected.length>0&&!checkboxes.itemTypes.selected.includes(entry.type)||checkboxes.armorTypes.selected.length>0&&!this.arrayIncludes(checkboxes.armorTypes.selected,[entry.category,entry.group])||checkboxes.weaponTypes.selected.length>0&&!this.arrayIncludes(checkboxes.weaponTypes.selected,[entry.category,entry.group])||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length>0&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length>0&&!checkboxes.rarity.selected.includes(entry.rarity))}parseRangeFilterInput(name2,lower,upper){if(name2==="price"){const coins={cp:this.#localizeCoins("cp"),sp:this.#localizeCoins("sp"),gp:this.#localizeCoins("gp"),pp:this.#localizeCoins("pp")};for(const[english,translated]of Object.entries(coins))lower=lower.replaceAll(translated,english),upper=upper.replaceAll(translated,english);return{min:CoinsPF2e.fromString(lower).copperValue,max:CoinsPF2e.fromString(upper).copperValue,inputMin:lower,inputMax:upper}}return super.parseRangeFilterInput(name2,lower,upper)}prepareFilterData(){return{checkboxes:{itemTypes:{isExpanded:!0,label:"PF2E.BrowserFilterInventoryTypes",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},armorTypes:{isExpanded:!1,label:"PF2E.BrowserFilterArmorFilters",options:{},selected:[]},weaponTypes:{isExpanded:!1,label:"PF2E.BrowserFilterWeaponFilters",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel",price:"PF2E.PriceLabel"}},ranges:{price:{changed:!1,isExpanded:!1,label:"PF2E.PriceLabel",values:{min:0,max:2e7,inputMin:`0${this.#localizeCoins("cp")}`,inputMax:`200,000${this.#localizeCoins("gp")}`}}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:30,min:0,max:30,step:1}}},search:{text:""}}}}class CompendiumBrowserFeatTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserFeatTab")}static{__name2(this,"CompendiumBrowserFeatTab")}tabName="feat";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/feat.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","category","skills","traits","rarity","source"];#creatureTraits=CONFIG.PF2E.creatureTraits;constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading feats");const feats=[],publications=new Set,indexFields=["img","system.actionType.value","system.actions.value","system.category","system.level.value","system.prerequisites.value","system.traits","system.publication","system.source"],translatedSkills=Object.entries(CONFIG.PF2E.skillList).reduce((result,[key,value])=>({...result,[key]:game.i18n.localize(value).toLocaleLowerCase(game.i18n.lang)}),{}),skillList=Object.entries(translatedSkills);for await(const{pack,index}of this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("feat"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const featData of index)if(featData.type==="feat"){featData.filters={};const categoryPaths=["system.category","system.featType.value"],nonCategoryPaths=indexFields.filter(f=>!categoryPaths.includes(f)),categoryPathFound=categoryPaths.some(p=>foundry.utils.hasProperty(featData,p));if(!this.hasAllIndexFields(featData,nonCategoryPaths)||!categoryPathFound){console.warn(`Feat "${featData.name}" does not have all required data fields.`,`Consider unselecting pack "${pack.metadata.label}" in the compendium browser settings.`);continue}const featType=featData.system.featType;isObject(featType)&&"value"in featType&&typeof featType.value=="string"&&(featData.system.category=featType.value,delete featData.system.featType);const prerequisitesArr=featData.system.prerequisites.value.map(prerequisite=>prerequisite?.value?prerequisite.value.toLowerCase():""),skills=new Set;for(const prereq of prerequisitesArr)for(const[key,value]of skillList)(prereq.includes(key)||prereq.includes(value))&&skills.add(key);const pubSource=featData.system.publication?.title??featData.system.source?.value??"",sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),feats.push({type:featData.type,name:featData.name,img:featData.img,uuid:`Compendium.${pack.collection}.Item.${featData._id}`,level:featData.system.level.value,category:featData.system.category,skills:[...skills],traits:featData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:featData.system.traits.rarity,source:sourceSlug})}}this.indexData=feats,this.filterData.checkboxes.category.options=this.generateCheckboxOptions(CONFIG.PF2E.featCategories),this.filterData.checkboxes.skills.options=this.generateCheckboxOptions(CONFIG.PF2E.skillList),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.featTraits),console.debug("PF2e System | Compendium Browser | Finished loading feats")}filterTraits(traits,selected,condition){if(this.filterData.checkboxes.category.selected.includes("ancestry")&&!traits.some(t=>t in this.#creatureTraits)){const withoutAncestryTraits=selected.filter(t=>!(t.value in this.#creatureTraits));return super.filterTraits(traits,withoutAncestryTraits,condition)}return super.filterTraits(traits,selected,condition)}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.category.selected.length&&!checkboxes.category.selected.includes(entry.category)||checkboxes.skills.selected.length&&!this.arrayIncludes(checkboxes.skills.selected,entry.skills)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!1,label:"PF2E.BrowserFilterCategory",options:{},selected:[]},skills:{isExpanded:!1,label:"PF2E.BrowserFilterSkills",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:0,upperLimit:20,min:0,max:20,step:1}}},search:{text:""}}}}class CompendiumBrowserHazardTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserHazardTab")}static{__name2(this,"CompendiumBrowserHazardTab")}tabName="hazard";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/hazard.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","level","complexity","traits","rarity","source"];index=["img","system.details.level.value","system.details.isComplex","system.traits"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading Hazard actors");const hazardActors=[],publications=new Set,indexFields=[...this.index,"system.details.alignment.value","system.details.publication","system.details.source"];for await(const{pack,index}of this.browser.packLoader.loadPacks("Actor",this.browser.loadedPacks("hazard"),indexFields)){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const actorData of index.filter(d=>d.type==="hazard")){if(!this.hasAllIndexFields(actorData,this.index)){console.warn(`Hazard '${actorData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const{details}=actorData.system,pubSource=String(details.publication?.title??details.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),hazardActors.push({type:actorData.type,name:actorData.name,img:actorData.img,uuid:`Compendium.${pack.collection}.${actorData._id}`,level:actorData.system.details.level.value,complexity:actorData.system.details.isComplex?"complex":"simple",traits:actorData.system.traits.value,rarity:actorData.system.traits.rarity,source:sourceSlug})}console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - Loaded`)}this.indexData=hazardActors,this.filterData.checkboxes.complexity.options=this.generateCheckboxOptions({simple:"PF2E.Actor.Hazard.Simple",complex:"PF2E.TraitComplex"},!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(CONFIG.PF2E.hazardTraits),this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),console.debug("PF2e System | Compendium Browser | Finished loading Hazard actors")}filterIndexData(entry){const{checkboxes,multiselects,sliders}=this.filterData;return!(!(entry.level>=sliders.level.values.min&&entry.level<=sliders.level.values.max)||checkboxes.complexity.selected.length&&!checkboxes.complexity.selected.includes(entry.complexity)||!this.filterTraits(entry.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.source.selected.length&&!checkboxes.source.selected.includes(entry.source)||checkboxes.rarity.selected.length&&!checkboxes.rarity.selected.includes(entry.rarity))}prepareFilterData(){return{checkboxes:{complexity:{isExpanded:!0,label:"PF2E.BrowserFilterComplexity",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},order:{by:"level",direction:"asc",options:{name:"Name",level:"PF2E.LevelLabel"}},sliders:{level:{isExpanded:!1,label:"PF2E.BrowserFilterLevels",values:{lowerLimit:-1,upperLimit:25,min:-1,max:25,step:1}}},search:{text:""}}}}class CompendiumBrowserSpellTab extends CompendiumBrowserTab{static{__name(this,"CompendiumBrowserSpellTab")}static{__name2(this,"CompendiumBrowserSpellTab")}tabName="spell";filterData;templatePath="systems/pf2e/templates/compendium-browser/partials/spell.hbs";searchFields=["name"];storeFields=["type","name","img","uuid","rank","time","traditions","traits","categories","rarity","source"];constructor(browser){super(browser),this.filterData=this.prepareFilterData()}async loadData(){console.debug("PF2e System | Compendium Browser | Started loading spells");const spells=[],times=new Set,publications=new Set,indexFields=["img","system.level.value","system.time","system.traits","system.publication","system.ritual","system.source"],data=this.browser.packLoader.loadPacks("Item",this.browser.loadedPacks("spell"),indexFields);for await(const{pack,index}of data){console.debug(`PF2e System | Compendium Browser | ${pack.metadata.label} - ${index.size} entries found`);for(const spellData of index)if(spellData.filters={},spellData.type==="spell"){if("system"in spellData&&isObject$1(spellData.system)&&(spellData.system.ritual??=null),!this.hasAllIndexFields(spellData,indexFields)){console.warn(`Item '${spellData.name}' does not have all required data fields. Consider unselecting pack '${pack.metadata.label}' in the compendium browser settings.`);continue}const isCantrip=spellData.system.traits.value.includes("cantrip"),isFocusSpell=spellData.system.traits.value.includes("focus"),isRitual=!!spellData.system.ritual,categories=compact([!isCantrip&&!isFocusSpell&&!isRitual?"spell":null,isCantrip?"cantrip":null,isFocusSpell?"focus":null,isRitual?"ritual":null]),time=spellData.system.time.value;if(time&&typeof time=="string"){const normalizedTime=time.toLocaleLowerCase("en").includes("reaction")?"reaction":sluggify(time);times.add(normalizedTime),spellData.system.time.value=normalizedTime}const actionGlyph=getActionGlyph(spellData.system.time.value),{system}=spellData,pubSource=String(system.publication?.title??system.source?.value??"").trim(),sourceSlug=sluggify(pubSource);pubSource&&publications.add(pubSource),spells.push({type:spellData.type,name:spellData.name,img:spellData.img,uuid:`Compendium.${pack.collection}.${spellData._id}`,rank:spellData.system.level.value,categories,time:spellData.system.time,actionGlyph,traditions:spellData.system.traits.traditions,traits:spellData.system.traits.value.map(t=>t.replace(/^hb_/,"")),rarity:spellData.system.traits.rarity,source:sourceSlug})}}this.indexData=spells,this.filterData.checkboxes.traditions.options=this.generateCheckboxOptions(CONFIG.PF2E.magicTraditions);for(let rank=1;rank<=10;rank++)this.filterData.checkboxes.rank.options[rank]={label:game.i18n.format("PF2E.Item.Spell.Rank.Ordinal",{rank:ordinalString(rank)}),selected:!1};this.filterData.checkboxes.rarity.options=this.generateCheckboxOptions(CONFIG.PF2E.rarityTraits,!1),this.filterData.multiselects.traits.options=this.generateMultiselectOptions(omit(CONFIG.PF2E.spellTraits,Array.from(MAGIC_TRADITIONS))),this.filterData.checkboxes.source.options=this.generateSourceCheckboxOptions(publications),this.filterData.checkboxes.category.options=this.generateCheckboxOptions({spell:"TYPES.Item.spell",cantrip:"PF2E.TraitCantrip",focus:"PF2E.TraitFocus",ritual:"PF2E.Item.Spell.Ritual.Label"},!1),this.filterData.selects.timefilter.options=[...times].sort().reduce((result,time)=>({...result,[sluggify(time)]:time}),{}),console.debug("PF2e System | Compendium Browser | Finished loading spells")}filterIndexData(indexData){const{checkboxes,multiselects,selects}=this.filterData;return!(checkboxes.rank.selected.length>0&&!checkboxes.rank.selected.map(r=>Number(r)).includes(indexData.rank)||checkboxes.category.selected.length>0&&!equals(checkboxes.category.selected.sort(),indexData.categories.sort())||selects.timefilter.selected&&selects.timefilter.selected!==indexData.time.value||checkboxes.traditions.selected.length>0&&intersection(checkboxes.traditions.selected,indexData.traditions).length===0||!this.filterTraits(indexData.traits,multiselects.traits.selected,multiselects.traits.conjunction)||checkboxes.rarity.selected.length>0&&!checkboxes.rarity.selected.includes(indexData.rarity)||checkboxes.source.selected.length>0&&!checkboxes.source.selected.includes(indexData.source))}prepareFilterData(){return{checkboxes:{category:{isExpanded:!0,label:"PF2E.BrowserFilterSpellCategories",options:{},selected:[]},traditions:{isExpanded:!0,label:"PF2E.BrowserFilterTraditions",options:{},selected:[]},rank:{isExpanded:!0,label:"PF2E.Item.Spell.Rank.Plural",options:{},selected:[]},rarity:{isExpanded:!1,label:"PF2E.BrowserFilterRarities",options:{},selected:[]},source:{isExpanded:!1,label:"PF2E.BrowserFilterSource",options:{},selected:[]}},multiselects:{traits:{conjunction:"and",label:"PF2E.BrowserFilterTraits",options:[],selected:[]}},selects:{timefilter:{label:"PF2E.BrowserFilterCastingTime",options:{},selected:""}},order:{by:"rank",direction:"asc",options:{name:"Name",rank:"PF2E.Item.Spell.Rank.Label"}},search:{text:""}}}}class CompendiumBrowser extends Application{static{__name(this,"CompendiumBrowser")}static{__name2(this,"CompendiumBrowser")}settings;dataTabsList=["action","bestiary","campaignFeature","equipment","feat","hazard","spell"];navigationTab;tabs;packLoader=new PackLoader;constructor(options={}){super(options),this.settings=game.settings.get("pf2e","compendiumBrowserPacks"),this.navigationTab=this.hookTab(),this.tabs={action:new CompendiumBrowserActionTab(this),bestiary:new CompendiumBrowserBestiaryTab(this),campaignFeature:new CompendiumBrowserCampaignFeaturesTab(this),equipment:new CompendiumBrowserEquipmentTab(this),feat:new CompendiumBrowserFeatTab(this),hazard:new CompendiumBrowserHazardTab(this),spell:new CompendiumBrowserSpellTab(this)},this.initCompendiumList()}get title(){return game.i18n.localize("PF2E.CompendiumBrowser.Title")}static get defaultOptions(){return{...super.defaultOptions,id:"compendium-browser",classes:[],template:"systems/pf2e/templates/compendium-browser/compendium-browser.hbs",width:800,height:700,resizable:!0,dragDrop:[{dragSelector:"ul.item-list > li.item"}],tabs:[{navSelector:"nav",contentSelector:"section.content",initial:"landing-page"},{navSelector:"nav[data-group=settings]",contentSelector:".settings-container",initial:"packs"}],scrollY:[".control-area",".item-list",".settings-container"]}}async close(options){for(const tab of Object.values(this.tabs))tab.filterData.search.text="";await super.close(options)}hookTab(){const navigationTab=this._tabs[0],tabCallback=navigationTab.callback;return navigationTab.callback=async(event2,tabs,active)=>{tabCallback?.(event2,tabs,active),await this.loadTab(active)},navigationTab}initCompendiumList(){const settings={action:{},bestiary:{},campaignFeature:{},hazard:{},equipment:{},feat:{},spell:{}},loadDefault={bestiary:!0,hazard:!0,"pf2e.actionspf2e":!0,"pf2e.familiar-abilities":!0,"pf2e.equipment-srd":!0,"pf2e.ancestryfeatures":!0,"pf2e.classfeatures":!0,"pf2e.feats-srd":!0,"pf2e.spells-srd":!0,"pf2e.kingmaker-features":!0},browsableTypes=new Set(["action","campaignFeature","feat","kit","hazard","npc","spell",...PHYSICAL_ITEM_TYPES]),typeToTab=new Map([["action","action"],["campaignFeature","campaignFeature"],["feat","feat"],["kit","equipment"],["hazard","hazard"],["npc","bestiary"],["spell","spell"],...Array.from(PHYSICAL_ITEM_TYPES).map(t=>[t,"equipment"])]);for(const pack of game.packs){const tabNames=uniq(uniq(pack.index.map(entry=>entry.type)).filter(t=>setHasElement(browsableTypes,t)).flatMap(t=>typeToTab.get(t)??[]));for(const tabName of tabNames){const load=this.settings[tabName]?.[pack.collection]?.load??loadDefault[tabName]??!!loadDefault[pack.collection];settings[tabName][pack.collection]={load,name:pack.metadata.label,package:pack.metadata.packageName}}}for(const tab of this.dataTabsList)settings[tab]=Object.fromEntries(Object.entries(settings[tab]).sort(([_collectionA,dataA],[_collectionB,dataB])=>(dataA?.name??"")>(dataB?.name??"")?1:-1));this.settings=settings}async openTab(tabName,filter2){return this.activeTab=tabName,tabName!=="settings"&&filter2?this.tabs[tabName].open(filter2):this.loadTab(tabName)}async openActionTab(options){const actionTab=this.tabs.action,filter2=await actionTab.getFilterData(),{types}=filter2.checkboxes,{traits}=filter2.multiselects;types.selected=[];for(const type in types.options)options.types?.includes(type)&&(types.options[type].selected=!0,types.selected.push(type));const traitFilters=options.traits??[];if(traits.selected=traitFilters.length?traits.options.filter(trait=>traitFilters.includes(trait.value)):[],options.categories?.length){const optionsToSwitch=pick(filter2.checkboxes.category.options,options.categories);Object.values(optionsToSwitch).forEach(o=>o.selected=!0),filter2.checkboxes.category.selected=Object.keys(optionsToSwitch)}actionTab.open(filter2)}async openSpellTab(entry,maxRank=10,category=null){const spellTab=this.tabs.spell,filter2=await spellTab.getFilterData(),{traditions}=filter2.checkboxes;if(category&&filter2.checkboxes.category.options[category]&&(filter2.checkboxes.category.options[category].selected=!0,filter2.checkboxes.category.selected.push(category)),(entry.isRitual||entry.isFocusPool)&&(filter2.checkboxes.category.options[entry.category].selected=!0,filter2.checkboxes.category.selected.push(entry.category)),maxRank){const ranks=Array.from(Array(maxRank).keys()).map(l=>String(l+1));for(const rank of ranks)filter2.checkboxes.rank.options[rank].selected=!0,filter2.checkboxes.rank.selected.push(rank);(entry.isPrepared||entry.isSpontaneous||entry.isInnate)&&!category&&(filter2.checkboxes.category.options.spell.selected=!0,filter2.checkboxes.category.selected.push("spell"))}entry.tradition&&!entry.isFocusPool&&!entry.isRitual&&(traditions.options[entry.tradition].selected=!0,traditions.selected.push(entry.tradition)),spellTab.open(filter2)}async loadTab(tabName){if(this.activeTab=tabName,tabName==="settings"){await this.packLoader.updateSources(this.loadedPacksAll()),await this.render(!0);return}if(!this.dataTabsList.includes(tabName))throw ErrorPF2e(`Unknown tab "${tabName}"`);const currentTab=this.tabs[tabName];currentTab.isInitialized||await currentTab.init(),await this.render(!0,{focus:!0})}loadedPacks(tab){return tab==="settings"?[]:Object.entries(this.settings[tab]??[]).flatMap(([collection,info])=>info?.load?[collection]:[])}loadedPacksAll(){return uniq(this.dataTabsList.flatMap(t=>this.loadedPacks(t))).sort()}activateListeners($html){super.activateListeners($html);const html=$html[0],activeTabName=this.activeTab;if(this.navigationTab.active!==activeTabName&&this.navigationTab.activate(activeTabName),activeTabName==="settings"){const settings=htmlQuery(html,".compendium-browser-settings"),form=settings?.querySelector("form");if(!form)return;htmlQuery(settings,"button[data-action=save-settings]")?.addEventListener("click",async()=>{const formData=new FormData(form);for(const[t,packs]of Object.entries(this.settings))for(const[key,pack]of Object.entries(packs))pack.load=formData.has(`${t}-${key}`);await game.settings.set("pf2e","compendiumBrowserPacks",this.settings);for(const[key,source]of Object.entries(this.packLoader.sourcesSettings.sources)){if(!source?.name){delete this.packLoader.sourcesSettings.sources[key];continue}source.load=formData.has(`source-${key}`)}this.packLoader.sourcesSettings.showEmptySources=formData.has("show-empty-sources"),this.packLoader.sourcesSettings.showUnknownSources=formData.has("show-unknown-sources"),this.packLoader.sourcesSettings.ignoreAsGM=formData.has("ignore-as-gm"),await game.settings.set("pf2e","compendiumBrowserSources",this.packLoader.sourcesSettings),await this.#resetInitializedTabs(),this.render(!0),ui.notifications.info("PF2E.BrowserSettingsSaved",{localize:!0})});const sourceSearch=htmlQuery(form,"input[data-element=setting-sources-search]"),sourceToggle=htmlQuery(form,"input[data-action=setting-sources-toggle-visible]"),sourceSettings=htmlQueryAll(form,"label[data-element=setting-source]");sourceSearch?.addEventListener("input",()=>{const value=sourceSearch.value?.trim().toLocaleLowerCase(game.i18n.lang);for(const element of sourceSettings){const name2=element.dataset.name?.toLocaleLowerCase(game.i18n.lang),shouldBeHidden=!!value&&!!name2&&!name2.includes(value);element.classList.toggle("hidden",shouldBeHidden)}sourceToggle&&(sourceToggle.checked=!1)}),sourceToggle?.addEventListener("click",()=>{for(const element of sourceSettings){const checkbox=htmlQuery(element,"input[type=checkbox]");!element.classList.contains("hidden")&&checkbox&&(checkbox.checked=sourceToggle.checked)}}),htmlQuery(form,"button[data-action=settings-sources-delete]")?.addEventListener("click",async()=>{const localize=localizer("PF2E.SETTINGS.CompendiumBrowserSources");await Dialog.confirm({title:localize("DeleteAllTitle"),content:`
${localize("DeleteAllQuestion")}
${localize("DeleteAllInfo")}
- `})&&(await this.packLoader.hardReset(this.loadedPacksAll()),await game.settings.set("pf2e","compendiumBrowserSources",this.packLoader.sourcesSettings),await __privateMethod(this,_resetInitializedTabs,resetInitializedTabs_fn).call(this),this.render(!0))});return}const currentTab=this.tabs[activeTabName],controlArea=html.querySelector("div.control-area");if(!controlArea)return;const search=controlArea.querySelector("input[name=textFilter]");search&&search.addEventListener("input",()=>{currentTab.filterData.search.text=search.value,__privateMethod(this,_clearScrollLimit,clearScrollLimit_fn).call(this),__privateMethod(this,_renderResultList,renderResultList_fn).call(this,{replace:!0})});const sortContainer=controlArea.querySelector("div.sortcontainer");if(sortContainer){const order=sortContainer.querySelector("select.order");order&&order.addEventListener("change",()=>{const orderBy=order.value??"name";currentTab.filterData.order.by=orderBy,__privateMethod(this,_clearScrollLimit,clearScrollLimit_fn).call(this,!0)});const directionAnchor=sortContainer.querySelector("a.direction");directionAnchor&&directionAnchor.addEventListener("click",()=>{const direction=directionAnchor.dataset.direction??"asc";currentTab.filterData.order.direction=direction==="asc"?"desc":"asc",__privateMethod(this,_clearScrollLimit,clearScrollLimit_fn).call(this,!0)})}if(activeTabName==="spell"){const timeFilter=controlArea.querySelector("select[name=timefilter]");timeFilter&&timeFilter.addEventListener("change",()=>{if(!currentTab.isOfType("spell"))return;const filterData=currentTab.filterData;filterData.selects?.timefilter&&(filterData.selects.timefilter.selected=timeFilter.value,__privateMethod(this,_clearScrollLimit,clearScrollLimit_fn).call(this,!0))})}controlArea.querySelector("button.clear-filters")?.addEventListener("click",()=>{__privateMethod(this,_resetFilters,resetFilters_fn).call(this),__privateMethod(this,_clearScrollLimit,clearScrollLimit_fn).call(this,!0)}),htmlQuery(html,"[data-action=create-roll-table]")?.addEventListener("click",()=>currentTab.createRollTable()),htmlQuery(html,"[data-action=add-to-roll-table]")?.addEventListener("click",async()=>{game.tables.contents.length&¤tTab.addToRollTable()});const filterContainers=controlArea.querySelectorAll("div.filtercontainer");for(const container of Array.from(filterContainers)){const{filterType,filterName}=container.dataset;container.querySelector("button[data-action=clear-filter]")?.addEventListener("click",event=>{switch(event.stopImmediatePropagation(),filterType){case"checkboxes":{const checkboxes=currentTab.filterData.checkboxes;if(objectHasKey(checkboxes,filterName)){for(const option of Object.values(checkboxes[filterName].options))option.selected=!1;checkboxes[filterName].selected=[],this.render(!0)}break}case"ranges":if(currentTab.isOfType("equipment")){const ranges=currentTab.filterData.ranges;objectHasKey(ranges,filterName)&&(ranges[filterName].values=currentTab.defaultFilterData.ranges[filterName].values,ranges[filterName].changed=!1,this.render(!0))}}});const title=container.querySelector("div.title");if(title?.addEventListener("click",()=>{const toggleFilter=__name2(filter2=>{filter2.isExpanded=!filter2.isExpanded;const contentElement=title.nextElementSibling;contentElement instanceof HTMLElement&&(filter2.isExpanded?contentElement.style.display="":contentElement.style.display="none")},"toggleFilter");switch(filterType){case"checkboxes":{objectHasKey(currentTab.filterData.checkboxes,filterName)&&toggleFilter(currentTab.filterData.checkboxes[filterName]);break}case"ranges":{if(!currentTab.isOfType("equipment"))return;objectHasKey(currentTab.filterData.ranges,filterName)&&toggleFilter(currentTab.filterData.ranges[filterName]);break}case"sliders":{if(!currentTab.isOfType("bestiary","equipment","feat","campaignFeature","hazard"))return;objectHasKey(currentTab.filterData.sliders,filterName)&&toggleFilter(currentTab.filterData.sliders[filterName]);break}}}),filterType==="checkboxes"&&container.querySelectorAll("input[type=checkbox]").forEach(checkboxElement=>{checkboxElement.addEventListener("click",()=>{if(objectHasKey(currentTab.filterData.checkboxes,filterName)){const optionName=checkboxElement.name,checkbox=currentTab.filterData.checkboxes[filterName],option=checkbox.options[optionName];option.selected=!option.selected,option.selected?checkbox.selected.push(optionName):checkbox.selected=checkbox.selected.filter(name2=>name2!==optionName),__privateMethod(this,_clearScrollLimit,clearScrollLimit_fn).call(this,!0)}})}),filterType==="ranges"&&container.querySelectorAll("input[name*=Bound]").forEach(range=>{range.addEventListener("keyup",event=>{if(!currentTab.isOfType("equipment")||event.key!=="Enter")return;const ranges=currentTab.filterData.ranges;if(ranges&&objectHasKey(ranges,filterName)){const range2=ranges[filterName],lowerBound=container.querySelector("input[name*=lowerBound]")?.value??"",upperBound=container.querySelector("input[name*=upperBound]")?.value??"",values=currentTab.parseRangeFilterInput(filterName,lowerBound,upperBound);range2.values=values,range2.changed=!0,__privateMethod(this,_clearScrollLimit,clearScrollLimit_fn).call(this,!0)}})}),filterType==="multiselects"){const multiselects=currentTab.filterData.multiselects;if(!multiselects)continue;if(objectHasKey(multiselects,filterName)){const multiselect=container.querySelector(`input[name=${filterName}][data-tagify-select]`);if(!multiselect)continue;const data=multiselects[filterName],tagify2=new Tagify(multiselect,{enforceWhitelist:!0,keepInvalidTags:!1,editTags:!1,tagTextProp:"label",dropdown:{enabled:0,fuzzySearch:!1,mapValueTo:"label",maxItems:data.options.length,searchKeys:["label"]},whitelist:data.options,transformTag(tagData){data.selected.find(s=>s.value===tagData.value)?.not&&(tagData.class="conjunction-not")}});tagify2.on("click",event=>{const target=event.detail.event.target;if(!target)return;if(htmlClosest(target,"[data-action]")?.dataset?.action==="toggle-not"){const value=event.detail.data.value,selected=data.selected.find(s=>s.value===value);selected&&(selected.not=!selected.not,this.render())}}),tagify2.on("change",event=>{const selections=JSON.parse(event.detail.value||"[]");Array.isArray(selections)&&selections.every(s=>isObject(s)&&typeof s.value=="string")&&(data.selected=selections,this.render())});for(const element of htmlQueryAll(container,`input[name=${filterName}-filter-conjunction]`))element.addEventListener("change",()=>{const value=element.value;(value==="and"||value==="or")&&(data.conjunction=value,this.render())});for(const tag of htmlQueryAll(container,"tag")){const icon=fontAwesomeIcon("ban",{style:"solid"});icon.classList.add("fa-2xs");const notButton=createHTMLElement("a",{classes:["conjunction-not-button"],children:[icon],dataset:{action:"toggle-not"}});tag.appendChild(notButton)}}}if(filterType==="sliders"){if(!currentTab.isOfType("bestiary","campaignFeature","equipment","feat","hazard"))continue;const sliders=currentTab.filterData.sliders;if(!sliders)continue;if(objectHasKey(sliders,filterName)){const sliderElement=container.querySelector(`div.slider-${filterName}`);if(!sliderElement)continue;const data=sliders[filterName];noUiSlider.create(sliderElement,{range:{min:data.values.lowerLimit,max:data.values.upperLimit},start:[data.values.min,data.values.max],tooltips:{to(value){return Math.floor(value).toString()}},connect:[!1,!0,!1],behaviour:"snap",step:data.values.step}).on("change",values=>{const[min,max]=values.map(value=>Number(value));data.values.min=min,data.values.max=max;const $minLabel=$html.find(`label.${name}-min-label`),$maxLabel=$html.find(`label.${name}-max-label`);$minLabel.text(min),$maxLabel.text(max),__privateMethod(this,_clearScrollLimit,clearScrollLimit_fn).call(this,!0)}),sliderElement.querySelectorAll(".noUi-handle").forEach(element=>{element.classList.add("handle")}),sliderElement.querySelectorAll(".noUi-connect").forEach(element=>{element.classList.add("range_selected")})}}}const list=html.querySelector(".tab.active ul.item-list");list&&(list.addEventListener("scroll",()=>{if(list.scrollTop+list.clientHeight>=list.scrollHeight-5){const currentValue=currentTab.scrollLimit,maxValue=currentTab.totalItemCount??0;currentValue{window.setTimeout(()=>{this.element.animate({opacity:1},250,()=>{this.element.css({pointerEvents:""})})},500)},{once:!0})}_onDragOver(event){super._onDragOver(event),event.dataTransfer.types.includes("from-browser")&&this.element.css({pointerEvents:"none"})}getData(){const activeTab=this.activeTab,tab=objectHasKey(this.tabs,activeTab)?this.tabs[activeTab]:null,settings={settings:this.settings,sources:this.packLoader.sourcesSettings};return{user:game.user,[activeTab]:activeTab==="settings"?settings:{filterData:tab?.filterData},scrollLimit:tab?.scrollLimit,showCampaign:game.settings.get("pf2e","campaignType")!=="none"}}};_resetInitializedTabs=new WeakSet,resetInitializedTabs_fn=__name2(async function(){for(const tab of Object.values(this.tabs))tab.isInitialized&&(await tab.init(),tab.scrollLimit=100)},"#resetInitializedTabs"),_renderResultList=new WeakSet,renderResultList_fn=__name2(async function({list,start=0,replace=!1}){const currentTab=this.activeTab!=="settings"?this.tabs[this.activeTab]:null,html=this.element[0];if(!currentTab)return;if(!list){const listElement=html.querySelector(".tab.active ul.item-list");if(!listElement)return;list=listElement}const newResults=await currentTab.renderResults(start);__privateMethod(this,_activateResultListeners,activateResultListeners_fn).call(this,newResults);const fragment=document.createDocumentFragment();fragment.append(...newResults),replace?list.replaceChildren(fragment):list.append(fragment);for(const dragDropHandler of this._dragDrop)dragDropHandler.bind(html)},"#renderResultList"),_activateResultListeners=new WeakSet,activateResultListeners_fn=__name2(function(liElements=[]){for(const liElement of liElements){const{entryUuid}=liElement.dataset;if(!entryUuid)continue;const nameAnchor=liElement.querySelector("div.name > a");nameAnchor&&nameAnchor.addEventListener("click",async()=>{const document2=await fromUuid(entryUuid);document2?.sheet&&document2.sheet.render(!0)}),this.activeTab==="equipment"&&(liElement.querySelector("a[data-action=take-item]")?.addEventListener("click",()=>{__privateMethod(this,_takePhysicalItem,takePhysicalItem_fn).call(this,entryUuid)}),liElement.querySelector("a[data-action=buy-item]")?.addEventListener("click",()=>{__privateMethod(this,_buyPhysicalItem,buyPhysicalItem_fn).call(this,entryUuid)}))}},"#activateResultListeners"),_takePhysicalItem=new WeakSet,takePhysicalItem_fn=__name2(async function(uuid){const actors=getSelectedOrOwnActors(["character","npc"]),item=await __privateMethod(this,_getPhysicalItem,getPhysicalItem_fn).call(this,uuid);if(actors.length===0){ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.NoTokenSelected"));return}for(const actor of actors)await actor.inventory.add(item,{stack:!0});actors.length===1&&game.user.character&&actors[0]===game.user.character?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.AddedItemToCharacter",{item:item.name,character:game.user.character.name})):ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.AddedItem",{item:item.name}))},"#takePhysicalItem"),_buyPhysicalItem=new WeakSet,buyPhysicalItem_fn=__name2(async function(uuid){const actors=getSelectedOrOwnActors(["character","npc"]),item=await __privateMethod(this,_getPhysicalItem,getPhysicalItem_fn).call(this,uuid);if(actors.length===0){ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.NoTokenSelected"));return}let purchasesSucceeded=0;for(const actor of actors)await actor.inventory.removeCoins(item.price.value)&&(purchasesSucceeded=purchasesSucceeded+1,await actor.inventory.add(item,{stack:!0}));actors.length===1?purchasesSucceeded===1?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.BoughtItemWithCharacter",{item:item.name,character:actors[0].name})):ui.notifications.warn(game.i18n.format("PF2E.CompendiumBrowser.FailedToBuyItemWithCharacter",{item:item.name,character:actors[0].name})):purchasesSucceeded===actors.length?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.BoughtItemWithAllCharacters",{item:item.name})):ui.notifications.warn(game.i18n.format("PF2E.CompendiumBrowser.FailedToBuyItemWithSomeCharacters",{item:item.name}))},"#buyPhysicalItem"),_getPhysicalItem=new WeakSet,getPhysicalItem_fn=__name2(async function(uuid){const item=await fromUuid(uuid);if(!(item instanceof PhysicalItemPF2e||item instanceof KitPF2e))throw ErrorPF2e("Unexpected failure retrieving compendium item");return item},"#getPhysicalItem"),_resetFilters=new WeakSet,resetFilters_fn=__name2(function(){const activeTab=this.activeTab;activeTab!=="settings"&&this.tabs[activeTab].resetFilters()},"#resetFilters"),_clearScrollLimit=new WeakSet,clearScrollLimit_fn=__name2(function(render=!1){const tab=this.activeTab;if(tab==="settings")return;const list=this.element[0].querySelector(".tab.active ul.item-list");list&&(list.scrollTop=0,this.tabs[tab].scrollLimit=100,render&&this.render())},"#clearScrollLimit"),__name2(_CompendiumBrowser,"CompendiumBrowser");let CompendiumBrowser=_CompendiumBrowser;const _EffectsPanel=class extends Application{static{__name(this,"_EffectsPanel")}constructor(){super(...arguments),__privateAdd(this,_getRemainingDurationLabel),__privateAdd(this,_getEnrichedDescriptions),__publicField(this,"refresh",foundry.utils.debounce(this.render,100))}get token(){return canvas.tokens.controlled.at(0)?.document??null}get actor(){return this.token?.actor??game.user?.character??null}static get defaultOptions(){return{...super.defaultOptions,id:"pf2e-effects-panel",popOut:!1,template:"systems/pf2e/templates/system/effects-panel.hbs"}}async getData(options){const{actor}=this;if(!actor||!game.user.settings.showEffectPanel)return{afflictions:[],conditions:[],effects:[],descriptions:{afflictions:[],conditions:[],effects:[]},actor:null,user:{isGM:!1}};const effects=actor.itemTypes.effect.map(effect=>{const duration=effect.totalDuration,{system}=effect;if(duration===1/0)system.duration.unit==="encounter"?system.remaining=system.expired?game.i18n.localize("PF2E.EffectPanel.Expired"):game.i18n.localize("PF2E.EffectPanel.UntilEncounterEnds"):system.remaining=game.i18n.localize("PF2E.EffectPanel.UnlimitedDuration");else{const duration2=effect.remainingDuration;system.remaining=system.expired?game.i18n.localize("PF2E.EffectPanel.Expired"):__privateMethod(this,_getRemainingDurationLabel,getRemainingDurationLabel_fn).call(this,duration2.remaining,system.start.initiative??0,system.duration.expiry)}return effect})??[],conditions=actor.conditions.active,afflictions=actor.itemTypes.affliction,descriptions={afflictions:await __privateMethod(this,_getEnrichedDescriptions,getEnrichedDescriptions_fn).call(this,afflictions),conditions:await __privateMethod(this,_getEnrichedDescriptions,getEnrichedDescriptions_fn).call(this,conditions),effects:await __privateMethod(this,_getEnrichedDescriptions,getEnrichedDescriptions_fn).call(this,effects)};return{...await super.getData(options),afflictions,conditions,descriptions,effects,actor,user:{isGM:game.user.isGM}}}activateListeners($html){super.activateListeners($html);const html=$html[0];InlineRollLinks.listen(html,this.actor);for(const effectEl of htmlQueryAll(html,".effect-item[data-item-id]")){const{actor}=this,itemId=effectEl.dataset.itemId??"",effect=actor?.conditions.get(itemId)??actor?.items.get(itemId);if(!actor||!effect)continue;const iconElem=effectEl.querySelector(":scope > .icon");iconElem?.addEventListener("click",async()=>{actor&&effect.isOfType("condition")&&effect.slug==="persistent-damage"?await effect.onEndTurn({token:this.token}):effect instanceof AbstractEffectPF2e&&await effect.increase()}),iconElem?.addEventListener("contextmenu",async()=>{effect instanceof AbstractEffectPF2e?await effect.decrease():this.refresh()}),effectEl.querySelector("[data-action=recover-persistent-damage]")?.addEventListener("click",()=>{effect.isOfType("condition")&&effect.rollRecovery()}),effectEl.querySelector("[data-action=edit]")?.addEventListener("click",()=>{effect.isOfType("condition")&&effect.slug==="persistent-damage"?new PersistentDamageDialog(actor,{editing:effect.id}).render(!0):effect.sheet.render(!0)}),effectEl.querySelector("[data-action=send-to-chat]")?.addEventListener("click",()=>{effect.toMessage()});const valueContainer=htmlQuery(iconElem,".value"),textElement=htmlQuery(valueContainer,"strong");if(valueContainer&&textElement){const parentWidth=valueContainer.clientWidth,scale=textElement.clientWidth?Math.clamped(parentWidth/textElement.clientWidth,.75,1):1;scale<1&&(valueContainer.style.transformOrigin="left",valueContainer.style.transform=`scaleX(${scale})`,valueContainer.style.width=`${1/scale*100+1}%`),textElement.style.display="inline"}}}};_getRemainingDurationLabel=new WeakSet,getRemainingDurationLabel_fn=__name2(function(remaining,initiative,expiry){if(remaining>=63072e3)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleYears",{years:Math.floor(remaining/31536e3)});if(remaining>=31536e3)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleYear");if(remaining>=1209600)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleWeeks",{weeks:Math.floor(remaining/604800)});if(remaining>604800)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleWeek");if(remaining>=172800)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleDays",{days:Math.floor(remaining/86400)});if(remaining>7200)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleHours",{hours:Math.floor(remaining/3600)});if(remaining>120)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleMinutes",{minutes:Math.floor(remaining/60)});if(remaining>=12)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleRounds",{rounds:Math.floor(remaining/6)});if(remaining>=6)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleRound");if(remaining>=2)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleSeconds",{seconds:remaining});if(remaining===1)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleSecond");{const key=expiry==="turn-end"?"PF2E.EffectPanel.RemainingDuration.ZeroRoundsExpireTurnEnd":"PF2E.EffectPanel.RemainingDuration.ZeroRoundsExpireTurnStart";return game.i18n.format(key,{initiative})}},"#getRemainingDurationLabel"),_getEnrichedDescriptions=new WeakSet,getEnrichedDescriptions_fn=__name2(async function(effects){return await Promise.all(effects.map(async effect=>{const rollData={actor:"actor"in effect?effect.actor:null,item:effect};return await TextEditor.enrichHTML(effect.description,{async:!0,rollData})}))},"#getEnrichedDescriptions"),__name2(_EffectsPanel,"EffectsPanel");let EffectsPanel=_EffectsPanel;const _LicenseViewer=class extends Application{static{__name(this,"_LicenseViewer")}static get defaultOptions(){return mergeObject(super.defaultOptions,{id:"license-viewer",title:game.i18n.localize("PF2E.LicenseViewer.Label"),template:"systems/pf2e/templates/packs/license-viewer.hbs",width:500,height:600,resizable:!0,tabs:[{navSelector:"nav",contentSelector:"section.content",initial:"landing-page"}]})}};__name2(_LicenseViewer,"LicenseViewer");let LicenseViewer=_LicenseViewer;const debouncedRender=foundry.utils.debounce(()=>{canvas.tokens.hud.render()},20),_StatusEffects=class{static{__name(this,"_StatusEffects")}static initialize(){const iconTheme=game.settings.get("pf2e","statusEffectType");CONFIG.controlIcons.defeated=game.settings.get("pf2e","deathIcon"),CONFIG.PF2E.statusEffects.lastIconTheme=iconTheme,CONFIG.PF2E.statusEffects.iconDir=__privateGet(this,_ICON_THEME_DIRS)[iconTheme],__privateMethod(this,_updateStatusIcons,updateStatusIcons_fn).call(this)}static reset(){CONFIG.controlIcons.defeated=game.settings.get("pf2e","deathIcon"),__privateMethod(this,_updateStatusIcons,updateStatusIcons_fn).call(this),this.refresh()}static get conditions(){return __privateGet(this,_conditionSummaries)??__privateSet(this,_conditionSummaries,mapToObj(Array.from(CONDITION_SLUGS),s=>[s,{name:game.i18n.localize(`PF2E.condition.${s}.name`),rules:game.i18n.localize(`PF2E.condition.${s}.rules`),summary:game.i18n.localize(`PF2E.condition.${s}.summary`)}]))}static async migrateStatusEffectUrls(chosenSetting){console.debug("PF2e System | Changing status effect icon types");const iconDir=__privateGet(this,_ICON_THEME_DIRS)[chosenSetting];if(CONFIG.PF2E.statusEffects.iconDir=iconDir,CONFIG.PF2E.statusEffects.lastIconTheme=chosenSetting,__privateMethod(this,_updateStatusIcons,updateStatusIcons_fn).call(this),await resetActors(),canvas.ready)for(const token of canvas.tokens.placeables)token.drawEffects()}static async onRenderTokenHUD(html,tokenData){const token=canvas.tokens.get(tokenData._id??"");if(!token)return;const iconGrid=html.querySelector(".status-effects");if(!iconGrid)throw ErrorPF2e("Unexpected error retrieving status effects grid");const affectingConditions=token.actor?.conditions.active.filter(c=>c.isInHUD)??[],titleBar=document.createElement("div");titleBar.className="title-bar",iconGrid.append(titleBar);const statusIcons=iconGrid.querySelectorAll(".effect-control");for(const icon of statusIcons){const picture=document.createElement("picture");picture.classList.add("effect-control"),picture.dataset.statusId=icon.dataset.statusId,picture.title=icon.title;const iconSrc=icon.getAttribute("src");picture.setAttribute("src",iconSrc);const newIcon=document.createElement("img");newIcon.src=iconSrc,picture.append(newIcon),icon.replaceWith(picture);const slug=picture.dataset.statusId??"",actorType=token.actor?.type??"";(slug==="hidden"&&["loot","vehicle"].includes(actorType)||slug==="broken"&&!["loot","vehicle"].includes(actorType))&&(picture.style.display="none");const affecting=affectingConditions.filter(c=>c.slug===slug);if((affecting.length>0||iconSrc===token.document.overlayEffect)&&picture.classList.add("active"),affecting.length>0){const isOverridden=affecting.every(c=>c.system.references.overriddenBy.length>0),isLocked=affecting.every(c=>c.isLocked),hasValue=affecting.some(c=>c.value);if(isOverridden){picture.classList.add("overridden");const badge=fontAwesomeIcon("angle-double-down");badge.classList.add("badge"),picture.append(badge)}else if(isLocked){picture.classList.add("locked");const badge=fontAwesomeIcon("lock");badge.classList.add("badge"),picture.append(badge)}else if(hasValue){picture.classList.add("valued");const badge=document.createElement("i");badge.classList.add("badge");const value=Math.max(...affecting.map(c=>c.value??1));badge.innerText=value.toString(),picture.append(badge)}}}__privateMethod(this,_activateListeners,activateListeners_fn).call(this,iconGrid)}static onUpdateEncounter(encounter){if(!(game.user.isGM&&game.settings.get("pf2e","statusEffectShowCombatMessage")))return;if(!encounter.started){__privateSet(this,_lastCombatantToken,null);return}const{combatant}=encounter,token=combatant?.token;combatant&&token&&token.id!==__privateGet(this,_lastCombatantToken)&&typeof combatant.initiative=="number"&&!combatant.defeated&&(__privateSet(this,_lastCombatantToken,token.id),__privateMethod(this,_createChatMessage,createChatMessage_fn).call(this,token,combatant.hidden))}static refresh(){canvas.ready&&canvas.tokens.hud.rendered&&debouncedRender()}};_lastCombatantToken=new WeakMap,_ICON_THEME_DIRS=new WeakMap,_conditionSummaries=new WeakMap,_activateListeners=new WeakSet,activateListeners_fn=__name2(function(html){for(const control of htmlQueryAll(html,".effect-control"))control.addEventListener("click",event=>{__privateMethod(this,_setStatusValue,setStatusValue_fn).call(this,control,event)}),control.addEventListener("contextmenu",event=>{__privateMethod(this,_setStatusValue,setStatusValue_fn).call(this,control,event)}),control.addEventListener("mouseover",()=>{__privateMethod(this,_showStatusLabel,showStatusLabel_fn).call(this,control)}),control.addEventListener("mouseout",()=>{__privateMethod(this,_showStatusLabel,showStatusLabel_fn).call(this,control)})},"#activateListeners"),_updateStatusIcons=new WeakSet,updateStatusIcons_fn=__name2(function(){const directory=game.settings.get("pf2e","statusEffectType")==="default"?"conditions":"conditions-2";CONFIG.statusEffects=Object.entries(CONFIG.PF2E.statusEffects.conditions).map(([id,label])=>({id,label,icon:`systems/pf2e/icons/${directory}/${id}.webp`})),CONFIG.statusEffects.push({id:"dead",label:"PF2E.Actor.Dead",icon:CONFIG.controlIcons.defeated})},"#updateStatusIcons"),_showStatusLabel=new WeakSet,showStatusLabel_fn=__name2(function(control){const titleBar=control.closest(".status-effects")?.querySelector(".title-bar");titleBar&&control.title&&(titleBar.innerText=control.title,titleBar.classList.toggle("active"))},"#showStatusLabel"),_setStatusValue=new WeakSet,setStatusValue_fn=__name2(async function(control,event){event.preventDefault(),event.stopPropagation();const slug=control.dataset.statusId;if(!setHasElement(CONDITION_SLUGS,slug)&&slug!=="dead")return;const tokensAndActors=uniqBy(compact(canvas.tokens.controlled.map(t=>t.actor?[t,t.actor]:null)),([,a])=>a);for(const[token,actor]of tokensAndActors){if(slug==="persistent-damage"){await new PersistentDamageDialog(actor).render(!0);continue}const condition=actor.conditions.bySlug(slug,{active:!0,temporary:!1}).find(c=>c.isInHUD&&!c.system.references.parent);if(event.type==="click")typeof condition?.value=="number"?game.pf2e.ConditionManager.updateConditionValue(condition.id,token,condition.value+1):objectHasKey(CONFIG.PF2E.conditionTypes,slug)?actor.increaseCondition(slug):__privateMethod(this,_toggleStatus,toggleStatus_fn).call(this,token,control,event);else if(event.type==="contextmenu")if(event.ctrlKey&&slug!=="dead"){const conditionIds=actor.conditions.bySlug(slug,{temporary:!1}).map(c=>c.id);actor.deleteEmbeddedDocuments("Item",conditionIds)}else condition?.value?game.pf2e.ConditionManager.updateConditionValue(condition.id,token,condition.value-1):__privateMethod(this,_toggleStatus,toggleStatus_fn).call(this,token,control,event)}},"#setStatusValue"),_toggleStatus=new WeakSet,toggleStatus_fn=__name2(async function(token,control,event){const{actor}=token;if(!actor)return;const slug=control.dataset.statusId??"";if(!setHasElement(CONDITION_SLUGS,slug)&&slug!=="dead")return;const iconSrc=control.querySelector("img")?.getAttribute("src"),affecting=actor?.conditions.bySlug(slug,{active:!0,temporary:!1}).find(c=>!c.system.references.parent),conditionIds=[];if(event.type==="click"&&!affecting)if(objectHasKey(CONFIG.PF2E.conditionTypes,slug)){const newCondition=game.pf2e.ConditionManager.getCondition(slug).toObject();await token.actor?.createEmbeddedDocuments("Item",[newCondition])}else iconSrc&&(event.shiftKey||control.dataset.statusId==="dead")&&await token.toggleEffect(iconSrc,{overlay:!0,active:!0});else event.type==="contextmenu"&&(affecting&&conditionIds.push(affecting.id),conditionIds.length>0?await token.actor?.deleteEmbeddedDocuments("Item",conditionIds):token.document.overlayEffect===iconSrc&&await token.document.update({overlayEffect:""}))},"#toggleStatus"),_createChatMessage=new WeakSet,createChatMessage_fn=__name2(async function(token,whisper=!1){if(!token?.actor)return null;const conditions=await Promise.all(token.actor.conditions.active.map(async c=>({...pick$1(c,["name","img"]),description:await TextEditor.enrichHTML(c.description,{async:!0})})));if(conditions.length===0)return null;const content=await renderTemplate("systems/pf2e/templates/chat/participant-conditions.hbs",{conditions}),messageSource={user:game.user.id,speaker:{...ChatMessagePF2e.getSpeaker({token,actor:token.actor}),alias:game.i18n.format("PF2E.StatusEffects",{name:token.name})},content,type:CONST.CHAT_MESSAGE_TYPES.OTHER};return(!token.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition")||whisper)&&(messageSource.whisper=ChatMessage.getWhisperRecipients("GM").map(u=>u.id)),ChatMessagePF2e.create(messageSource)},"#createChatMessage"),__privateAdd(_StatusEffects,_activateListeners),__privateAdd(_StatusEffects,_updateStatusIcons),__privateAdd(_StatusEffects,_showStatusLabel),__privateAdd(_StatusEffects,_setStatusValue),__privateAdd(_StatusEffects,_toggleStatus),__privateAdd(_StatusEffects,_createChatMessage),__name2(_StatusEffects,"StatusEffects"),__privateAdd(_StatusEffects,_lastCombatantToken,null),__privateAdd(_StatusEffects,_ICON_THEME_DIRS,{default:"systems/pf2e/icons/conditions/",blackWhite:"systems/pf2e/icons/conditions-2/"}),__privateAdd(_StatusEffects,_conditionSummaries,null);let StatusEffects=_StatusEffects;async function remigrate(versionRange){if(!game.ready){ui.notifications.warn("PF2E.Migrations.WorldNotReady",{localize:!0});return}if(game.user.role!==CONST.USER_ROLES.GAMEMASTER){ui.notifications.error("PF2E.Migrations.OnlyGMCanUse",{localize:!0});return}const migrations=MigrationList.constructRange(versionRange.from,versionRange.to);if(migrations.length===0||versionRange.from({description:traitDescriptions2[trait],label:traitLabels[trait]??trait,slug:trait})),content=await renderTemplate("/systems/pf2e/templates/actors/actions/base/chat-message-content.hbs",{description,glyph:this.glyph,name:name2,traits});return ChatMessagePF2e.create({blind:options?.blind,content,whisper:options?.whisper})}};_action2=new WeakMap,_cost=new WeakMap,_description=new WeakMap,_slug=new WeakMap,_traits=new WeakMap,__name2(_BaseActionVariant,"BaseActionVariant");let BaseActionVariant=_BaseActionVariant;const _BaseAction=class{static{__name(this,"_BaseAction")}constructor(data){__publicField(this,"cost"),__publicField(this,"description"),__publicField(this,"img"),__publicField(this,"name"),__publicField(this,"slug"),__publicField(this,"traits"),__privateAdd(this,_variants,void 0),this.cost=data.cost,this.description=data.description,this.img=data.img,this.name=data.name.trim(),this.slug=data.slug?.trim()||sluggify(this.name),this.traits=data.traits??[],__privateSet(this,_variants,Array.isArray(data.variants)?data.variants.map(this.toActionVariant.bind(this)):data.variants?[this.toActionVariant(data.variants)]:[])}get glyph(){if(__privateGet(this,_variants).length===1)return __privateGet(this,_variants)[0].glyph;const numbers=__privateGet(this,_variants).filter(variant=>typeof variant.cost=="number").sort();if(__privateGet(this,_variants).length===numbers.length&&numbers.length>1){const first=numbers.shift()?.cost,last=numbers.pop()?.cost,key=first===last?String(first):first===2||last===2?`${first} or ${last}`:`${first} to ${last}`;return getActionGlyph(key)}return getActionGlyph(this.cost??"")}get variants(){const variants=__privateGet(this,_variants).map(variant=>[variant.slug,variant]);return new Collection(variants)}async getDefaultVariant(options){const variants=this.variants;if(options?.variant&&!variants.size){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.None",{action:this.name,variant:options.variant});return Promise.reject(reason)}if(!options?.variant&&variants.size>1){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.Multiple",{action:this.name});return Promise.reject(reason)}const variant=variants.get(options?.variant??"");if(options?.variant&&!variant){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.Nonexisting",{action:this.name,variant:options.variant});return Promise.reject(reason)}return variant??this.toActionVariant()}async toMessage(options){return((options?.variant?await this.getDefaultVariant(options):void 0)??this.toActionVariant()).toMessage(options)}async use(options){return(await this.getDefaultVariant(options)??this.toActionVariant()).use(options)}};_variants=new WeakMap,__name2(_BaseAction,"BaseAction");let BaseAction=_BaseAction;async function toEffectItem(effect){return typeof effect=="string"?await fromUuid(effect):effect}__name(toEffectItem,"toEffectItem"),__name2(toEffectItem,"toEffectItem");const _SimpleActionVariant=class extends BaseActionVariant{static{__name(this,"_SimpleActionVariant")}constructor(action2,data){super(action2,data),__privateAdd(this,_action3,void 0),__privateAdd(this,_effect2,void 0),__privateSet(this,_action3,action2),__privateSet(this,_effect2,data?.effect??action2.effect)}get effect(){return __privateGet(this,_effect2)??__privateGet(this,_action3).effect}async use(options={}){const actors=[];if(Array.isArray(options.actors)?actors.push(...options.actors):options.actors?actors.push(options.actors):actors.push(...getSelectedOrOwnActors()),actors.length===0)throw new Error(game.i18n.localize("PF2E.ActionsWarning.NoActor"));const traitLabels=CONFIG.PF2E.actionTraits,traitDescriptions2=CONFIG.PF2E.traitsDescriptions,traits=this.traits.concat(options.traits??[]).map(trait=>({description:traitDescriptions2[trait],label:traitLabels[trait]??trait,slug:trait})),effect=options?.effect===!1?void 0:await toEffectItem(options?.effect??this.effect),name2=this.name?`${game.i18n.localize(__privateGet(this,_action3).name)} - ${game.i18n.localize(this.name)}`:game.i18n.localize(__privateGet(this,_action3).name),flavor=await renderTemplate("systems/pf2e/templates/actors/actions/simple/chat-message-flavor.hbs",{effect,glyph:this.glyph,name:name2,traits}),results=[];for(const actor of actors){const message=await ChatMessage.create({flavor,speaker:ChatMessage.getSpeaker({actor})}),item=effect&&actor.isOwner?(await actor.createEmbeddedDocuments("Item",[effect.toObject()]))[0]:void 0;results.push({actor,effect:item,message})}return results}};_action3=new WeakMap,_effect2=new WeakMap,__name2(_SimpleActionVariant,"SimpleActionVariant");let SimpleActionVariant=_SimpleActionVariant;const _SimpleAction=class extends BaseAction{static{__name(this,"_SimpleAction")}effect;constructor(data){super(data),this.effect=data.effect}toActionVariant(data){return new SimpleActionVariant(this,data)}};__name2(_SimpleAction,"SimpleAction");let SimpleAction=_SimpleAction;function toRollNoteSource(data){return data.selector??="",data}__name(toRollNoteSource,"toRollNoteSource"),__name2(toRollNoteSource,"toRollNoteSource");const _SingleCheckActionVariant=class extends BaseActionVariant{static{__name(this,"_SingleCheckActionVariant")}constructor(action2,data){super(action2,data),__privateAdd(this,_action4,void 0),__privateAdd(this,_difficultyClass,void 0),__privateAdd(this,_modifiers,void 0),__privateAdd(this,_notes,void 0),__privateAdd(this,_rollOptions,void 0),__privateAdd(this,_statistic,void 0),__privateSet(this,_action4,action2),data&&(__privateSet(this,_difficultyClass,data.difficultyClass),__privateSet(this,_modifiers,data?.modifiers),__privateSet(this,_notes,data.notes?data.notes.map(toRollNoteSource):void 0),__privateSet(this,_rollOptions,data.rollOptions),__privateSet(this,_statistic,data.statistic))}get difficultyClass(){return __privateGet(this,_difficultyClass)??__privateGet(this,_action4).difficultyClass}get modifiers(){return __privateGet(this,_modifiers)??__privateGet(this,_action4).modifiers}get notes(){return __privateGet(this,_notes)??__privateGet(this,_action4).notes}get rollOptions(){return __privateGet(this,_rollOptions)??__privateGet(this,_action4).rollOptions}get statistic(){return __privateGet(this,_statistic)??__privateGet(this,_action4).statistic}async use(options={}){const modifiers=this.modifiers.map(raw=>new ModifierPF2e(raw)).concat(options.modifiers??[]);if(options.multipleAttackPenalty){const map2=options.multipleAttackPenalty,modifier=map2>0?Math.min(2,map2)*-5:map2;modifiers.push(new ModifierPF2e({label:"PF2E.MultipleAttackPenalty",modifier}))}const notes=this.notes.concat(options.notes??[]).map(toRollNoteSource).map(note=>new RollNotePF2e(note)),rollOptions=this.rollOptions.concat(options.rollOptions??[]),slug=options.statistic?.trim()||this.statistic,title=this.name?`${game.i18n.localize(__privateGet(this,_action4).name)} - ${game.i18n.localize(this.name)}`:game.i18n.localize(__privateGet(this,_action4).name),results=[],difficultyClass=setHasElement(DC_SLUGS,options.difficultyClass)||isObject(options.difficultyClass)&&typeof options.difficultyClass.value=="number"?options.difficultyClass:this.difficultyClass;return await ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,title,actionGlyph:getActionGlyph(this.cost??null),callback:result=>results.push(result),checkContext:opts=>this.checkContext(opts,{modifiers,rollOptions,slug}),difficultyClass,event:options.event,extraNotes:selector=>notes.map(note=>(note.selector||=selector,note)),traits:this.traits.concat(options?.traits??[])}),results}checkContext(opts,data){return ActionMacroHelpers.defaultCheckContext(opts,data)}};_action4=new WeakMap,_difficultyClass=new WeakMap,_modifiers=new WeakMap,_notes=new WeakMap,_rollOptions=new WeakMap,_statistic=new WeakMap,__name2(_SingleCheckActionVariant,"SingleCheckActionVariant");let SingleCheckActionVariant=_SingleCheckActionVariant;const _SingleCheckAction=class extends BaseAction{static{__name(this,"_SingleCheckAction")}difficultyClass;modifiers;notes;rollOptions;statistic;constructor(data){super(data),this.difficultyClass=data.difficultyClass,this.modifiers=data.modifiers??[],this.notes=(data.notes??[]).map(toRollNoteSource),this.rollOptions=data.rollOptions??[],this.statistic=data.statistic}toActionVariant(data){return new SingleCheckActionVariant(this,data)}};__name2(_SingleCheckAction,"SingleCheckAction");let SingleCheckAction=_SingleCheckAction;const PREFIX$f="PF2E.Actions.Balance";function balance(options){const slug=options?.skill??"acrobatics",rollOptions=["action:balance"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$f}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(balance,"balance"),__name2(balance,"balance");const action$q=new SingleCheckAction({cost:1,description:`${PREFIX$f}.Description`,name:`${PREFIX$f}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$f}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$f}.Notes.success`},{outcome:["failure"],text:`${PREFIX$f}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$f}.Notes.criticalFailure`}],rollOptions:["action:balance"],slug:"balance",statistic:"acrobatics",traits:["move"]}),PREFIX$e="PF2E.Actions.ManeuverInFlight";async function maneuverInFlight(options){const slug=options?.skill??"acrobatics",rollOptions=["action:maneuver-in-flight"],modifiers=options?.modifiers;return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$e}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$e}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$e,"failure"),ActionMacroHelpers.note(selector,PREFIX$e,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(maneuverInFlight,"maneuverInFlight"),__name2(maneuverInFlight,"maneuverInFlight");const action$p=new SingleCheckAction({cost:1,description:`${PREFIX$e}.Description`,name:`${PREFIX$e}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$e}.Notes.success`},{outcome:["failure"],text:`${PREFIX$e}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$e}.Notes.criticalFailure`}],rollOptions:["action:maneuver-in-flight"],slug:"maneuver-in-flight",statistic:"acrobatics",traits:["move"]}),PREFIX$d="PF2E.Actions.Squeeze";function squeeze(options){const slug=options?.skill??"acrobatics",rollOptions=["action:squeeze"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$d}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(squeeze,"squeeze"),__name2(squeeze,"squeeze");const action$o=new SingleCheckAction({description:`${PREFIX$d}.Description`,name:`${PREFIX$d}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$d}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$d}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$d}.Notes.criticalFailure`}],rollOptions:["action:squeeze"],slug:"squeeze",statistic:"acrobatics",traits:["exploration","move"]}),PREFIX$c="PF2E.Actions.TumbleThrough";function tumbleThrough(options){const slug=options?.skill??"acrobatics",rollOptions=["action:tumble-through"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$c}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$c}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$c}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(tumbleThrough,"tumbleThrough"),__name2(tumbleThrough,"tumbleThrough");const action$n=new SingleCheckAction({cost:1,description:`${PREFIX$c}.Description`,difficultyClass:"reflex",name:`${PREFIX$c}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$c}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$c}.Notes.failure`}],rollOptions:["action:tumble-through"],slug:"tumble-through",statistic:"acrobatics",traits:["move"]});function arcaneSlam(options){const{actor:target,token}=ActionMacroHelpers.target(),slug=options?.skill??"acrobatics",rollOptions=["action:arcane-slam"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:"PF2E.Actions.ArcaneSlam.Title",checkContext:opts=>{const modifiers=options.modifiers?.length?[...options.modifiers]:[];if(opts.actor instanceof CreaturePF2e&&opts.target instanceof CreaturePF2e){const attackerSize=opts.actor.system.traits.size,targetSize=opts.target.system.traits.size,sizeDifference=attackerSize.difference(targetSize),sizeModifier=new ModifierPF2e("PF2E.Actions.ArcaneSlam.Modifier.SizeDifference",Math.clamped(2*sizeDifference,-4,4),"circumstance");sizeModifier.modifier&&modifiers.push(sizeModifier)}return ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug})},traits:["automaton"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>{const notes=[ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","criticalFailure")];if(!target){const translated=game.i18n.localize("PF2E.Actions.ArcaneSlam.Notes.NoTarget");notes.unshift(new RollNotePF2e({selector,text:`${translated}
`,predicate:new PredicatePF2e,outcome:[]}))}return notes},target:()=>target&&token?{actor:target,token}:null}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(arcaneSlam,"arcaneSlam"),__name2(arcaneSlam,"arcaneSlam");function climb(options){const slug=options?.skill??"athletics",rollOptions=["action:climb"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Climb.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Climb","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Climb","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Climb","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(climb,"climb"),__name2(climb,"climb");function disarm(options){const slug=options?.skill??"athletics",rollOptions=["action:disarm"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Disarm.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"disarm")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.slug!=="basic-unarmed"){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(disarm,"disarm"),__name2(disarm,"disarm");function forceOpen(options){const slug=options?.skill??"athletics",rollOptions=["action:force-open"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.ForceOpen.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(forceOpen,"forceOpen"),__name2(forceOpen,"forceOpen");function grapple(options){const slug=options?.skill??"athletics",rollOptions=["action:grapple"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Grapple.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"grapple")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.traits.has("grapple")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(grapple,"grapple"),__name2(grapple,"grapple");function highJump(options){const slug=options?.skill??"athletics",rollOptions=["action:stride","action:leap","action:high-jump"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:"PF2E.Actions.HighJump.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.HighJump","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.HighJump","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.HighJump","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.HighJump","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(highJump,"highJump"),__name2(highJump,"highJump");const PREFIX$b="PF2E.Actions.LongJump";function longJump(options){const slug=options?.skill??"athletics",rollOptions=["action:stride","action:leap","action:long-jump"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:`${PREFIX$b}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$b}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$b,"failure"),ActionMacroHelpers.note(selector,PREFIX$b,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(longJump,"longJump"),__name2(longJump,"longJump");function shove(options){const slug=options?.skill??"athletics",rollOptions=["action:shove"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Shove.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"shove")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.traits.has("shove")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(shove,"shove"),__name2(shove,"shove");function swim(options){const slug=options?.skill??"athletics",rollOptions=["action:swim"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Swim.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Swim","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Swim","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Swim","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(swim,"swim"),__name2(swim,"swim");function tripCheckContext(opts,data){const item=[...ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"trip")??[],...ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"ranged-trip")??[]].shift(),context=ActionMacroHelpers.defaultCheckContext(opts,{item:data.item,modifiers:data.modifiers,rollOptions:data.rollOptions,slug:data.slug});if(item&&context){const modifiers=context.modifiers?.length?[...context.modifiers]:[];if(item.traits.has("trip")||item.traits.has("ranged-trip")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,data.slug);modifier&&modifiers.push(modifier)}item.traits.has("ranged-trip")&&modifiers.push(new ModifierPF2e({slug:"ranged-trip",adjustments:extractModifierAdjustments(opts.actor.synthetics.modifierAdjustments,context.rollOptions,"ranged-trip"),type:"circumstance",label:CONFIG.PF2E.weaponTraits["ranged-trip"],modifier:-2})),context.modifiers=modifiers}return context}__name(tripCheckContext,"tripCheckContext"),__name2(tripCheckContext,"tripCheckContext");function trip(options){const slug=options?.skill??"athletics",modifiers=options?.modifiers,rollOptions=["action:trip"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Trip.Title",checkContext:opts=>tripCheckContext(opts,{modifiers,rollOptions,slug}),traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(trip,"trip"),__name2(trip,"trip");const _TripActionVariant=class extends SingleCheckActionVariant{static{__name(this,"_TripActionVariant")}checkContext(opts,data){return tripCheckContext(opts,data)}};__name2(_TripActionVariant,"TripActionVariant");let TripActionVariant=_TripActionVariant;const _TripAction=class extends SingleCheckAction{static{__name(this,"_TripAction")}constructor(){super({cost:1,description:"PF2E.Actions.Trip.Description",difficultyClass:"reflex",name:"PF2E.Actions.Trip.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Trip.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Trip.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.Trip.Notes.criticalFailure"}],rollOptions:["action:trip"],slug:"trip",statistic:"athletics",traits:["attack"]})}toActionVariant(data){return new TripActionVariant(this,data)}};__name2(_TripAction,"TripAction");let TripAction=_TripAction;const action$m=new TripAction;function determineSizeBonus(actorSize,targetSize){const sizeDifference=actorSize.difference(targetSize);return Math.clamped(2*sizeDifference,-4,4)}__name(determineSizeBonus,"determineSizeBonus"),__name2(determineSizeBonus,"determineSizeBonus");function whirlingThrow(options){const slug=options?.skill??"athletics",rollOptions=["action:whirling-throw"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.WhirlingThrow.Title",checkContext:opts=>{const modifiers=options.modifiers?.length?[...options.modifiers]:[];if(opts.actor instanceof CreaturePF2e&&opts.target instanceof CreaturePF2e){const actorSize=opts.actor.system.traits.size,targetSize=opts.target.system.traits.size,sizeModifier=new ModifierPF2e("Size Modifier",determineSizeBonus(actorSize,targetSize),"circumstance");sizeModifier.modifier&&modifiers.push(sizeModifier)}return ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug})},traits:["monk"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(whirlingThrow,"whirlingThrow"),__name2(whirlingThrow,"whirlingThrow");const _AidActionVariant=class extends SingleCheckActionVariant{static{__name(this,"_AidActionVariant")}async use(options){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.Aid.Warning.NoStatistic"));const rollOption=`action:aid:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}};__name2(_AidActionVariant,"AidActionVariant");let AidActionVariant=_AidActionVariant;const _AidAction=class extends SingleCheckAction{static{__name(this,"_AidAction")}constructor(){super({cost:"reaction",description:"PF2E.Actions.Aid.Description",difficultyClass:{value:20},name:"PF2E.Actions.Aid.Title",notes:[{outcome:["criticalFailure"],text:"PF2E.Actions.Aid.Notes.criticalFailure",title:"PF2E.Check.Result.Degree.Check.criticalFailure"},{outcome:["criticalSuccess"],text:"PF2E.Actions.Aid.Notes.criticalSuccess",title:"PF2E.Check.Result.Degree.Check.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Aid.Notes.success",title:"PF2E.Check.Result.Degree.Check.success"}],rollOptions:["action:aid"],slug:"aid",statistic:""})}toActionVariant(data){return new AidActionVariant(this,data)}};__name2(_AidAction,"AidAction");let AidAction=_AidAction;const aid=new AidAction,crawl=new SimpleAction({cost:1,description:"PF2E.Actions.Crawl.Description",name:"PF2E.Actions.Crawl.Title",slug:"crawl",traits:["move"]}),delay=new SimpleAction({cost:"free",description:"PF2E.Actions.Delay.Description",name:"PF2E.Actions.Delay.Title",slug:"delay"}),_DropProneActionVariant=class extends SimpleActionVariant{static{__name(this,"_DropProneActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)result.actor.hasCondition("prone")||await result.actor.toggleCondition("prone");return results})}};__name2(_DropProneActionVariant,"DropProneActionVariant");let DropProneActionVariant=_DropProneActionVariant;const _DropProneAction=class extends SimpleAction{static{__name(this,"_DropProneAction")}constructor(){super({cost:1,description:"PF2E.Actions.DropProne.Description",name:"PF2E.Actions.DropProne.Title",slug:"drop-prone",traits:["move"]})}toActionVariant(data){return new DropProneActionVariant(this,data)}};__name2(_DropProneAction,"DropProneAction");let DropProneAction=_DropProneAction;const dropProne=new DropProneAction,toHighestModifier=__name2((highest,current)=>current.totalModifier>(highest?.totalModifier??0)?current:highest,"toHighestModifier");function unarmedStrikeWithHighestModifier(opts,data){const actionRollOptions=["action:escape","action:escape:unarmed"],{rollOptions}=opts.buildContext({actor:opts.actor,rollOptions:actionRollOptions,target:opts.target}),{actor}=opts,statistic=(()=>actor instanceof CharacterPF2e?actor.system.actions.filter(strike=>strike.weaponTraits.map(trait=>trait.name).includes("unarmed")):actor instanceof NPCPF2e?actor.system.actions.filter(strike=>strike.traits.map(trait=>trait.name).includes("unarmed")):[])().map(strike=>{const modifiers=(strike.modifiers??[]).concat(data.modifiers??[]);return new StatisticModifier("unarmed",modifiers,rollOptions)}).reduce(toHighestModifier,null);return statistic?{actor,rollOptions,statistic}:null}__name(unarmedStrikeWithHighestModifier,"unarmedStrikeWithHighestModifier"),__name2(unarmedStrikeWithHighestModifier,"unarmedStrikeWithHighestModifier");function escapeCheckContext(opts,data){const unarmed=data.slug&&data.slug!=="unarmed"?null:unarmedStrikeWithHighestModifier(opts,data),highest=(data.slug?[data.slug]:["acrobatics","athletics"]).filter(slug=>slug!=="unarmed").map(slug=>{const actionRollOptions=["action:escape",`action:escape:${slug}`],{property}=ActionMacroHelpers.resolveStat(slug),{rollOptions}=opts.buildContext({actor:opts.actor,rollOptions:actionRollOptions,target:opts.target}),statistic=getProperty(opts.actor,property);return{actor:opts.actor,rollOptions,statistic:new StatisticModifier(statistic.slug,statistic.modifiers.concat(data.modifiers??[]),rollOptions)}}).reduce((highest2,current)=>!highest2||current.statistic.totalModifier>(highest2?.statistic.totalModifier??0)?current:highest2,unarmed);if(highest){const{checkType,stat:slug,subtitle}=ActionMacroHelpers.resolveStat(highest.statistic.slug);return{modifiers:data.modifiers,rollOptions:highest.rollOptions,slug,statistic:highest.statistic,subtitle,type:checkType}}throw new CheckContextError("No applicable statistic to roll for Escape check.",opts.actor,"null")}__name(escapeCheckContext,"escapeCheckContext"),__name2(escapeCheckContext,"escapeCheckContext");function escape(options){const slug=options?.skill??"",modifiers=options?.modifiers,rollOptions=["action:escape"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,checkContext:opts=>escapeCheckContext(opts,{modifiers,rollOptions,slug}),actionGlyph:options.glyph??"A",title:"PF2E.Actions.Escape.Title",traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"athletics",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(escape,"escape"),__name2(escape,"escape");const _EscapeActionVariant=class extends SingleCheckActionVariant{static{__name(this,"_EscapeActionVariant")}get statistic(){return""}checkContext(opts,data){return escapeCheckContext(opts,data)}};__name2(_EscapeActionVariant,"EscapeActionVariant");let EscapeActionVariant=_EscapeActionVariant;const _EscapeAction=class extends SingleCheckAction{static{__name(this,"_EscapeAction")}constructor(){super({cost:1,description:"PF2E.Actions.Escape.Description",difficultyClass:"athletics",name:"PF2E.Actions.Escape.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Escape.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Escape.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.Escape.Notes.criticalFailure"}],rollOptions:["action:escape"],slug:"escape",statistic:"unarmed",traits:["attack"]})}toActionVariant(data){return new EscapeActionVariant(this,data)}};__name2(_EscapeAction,"EscapeAction");let EscapeAction=_EscapeAction;const action$l=new EscapeAction,interact=new SimpleAction({cost:1,description:"PF2E.Actions.Interact.Description",name:"PF2E.Actions.Interact.Title",slug:"interact",traits:["manipulate"]}),leap=new SimpleAction({cost:1,description:"PF2E.Actions.Leap.Description",name:"PF2E.Actions.Leap.Title",slug:"leap",traits:["move"]}),ready=new SimpleAction({cost:2,description:"PF2E.Actions.Ready.Description",name:"PF2E.Actions.Ready.Title",slug:"ready",traits:["concentrate"]}),release=new SimpleAction({cost:"free",description:"PF2E.Actions.Release.Description",name:"PF2E.Actions.Release.Title",slug:"release",traits:["manipulate"]});function seek(options){const slug=options?.skill??"perception",rollOptions=["action:seek"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Seek.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Seek","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Seek","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(seek,"seek"),__name2(seek,"seek");const action$k=new SingleCheckAction({cost:1,description:"PF2E.Actions.Seek.Description",name:"PF2E.Actions.Seek.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Seek.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Seek.Notes.success"}],rollOptions:["action:seek"],slug:"seek",statistic:"perception",traits:["concentrate","secret"]});function senseMotive(options){const slug=options?.skill??"perception",rollOptions=["action:sense-motive"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.SenseMotive.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"deception",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(senseMotive,"senseMotive"),__name2(senseMotive,"senseMotive");const action$j=new SingleCheckAction({cost:1,description:"PF2E.Actions.SenseMotive.Description",difficultyClass:"deception",name:"PF2E.Actions.SenseMotive.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.SenseMotive.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.SenseMotive.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.SenseMotive.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.SenseMotive.Notes.criticalFailure"}],rollOptions:["action:sense-motive"],slug:"sense-motive",statistic:"perception",traits:["concentrate","secret"]}),_StandActionVariant=class extends SimpleActionVariant{static{__name(this,"_StandActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)result.actor.hasCondition("prone")&&await result.actor.toggleCondition("prone");return results})}};__name2(_StandActionVariant,"StandActionVariant");let StandActionVariant=_StandActionVariant;const _StandAction=class extends SimpleAction{static{__name(this,"_StandAction")}constructor(){super({cost:1,description:"PF2E.Actions.Stand.Description",name:"PF2E.Actions.Stand.Title",slug:"stand",traits:["move"]})}toActionVariant(data){return new StandActionVariant(this,data)}};__name2(_StandAction,"StandAction");let StandAction=_StandAction;const stand=new StandAction,step=new SimpleAction({cost:1,description:"PF2E.Actions.Step.Description",name:"PF2E.Actions.Step.Title",slug:"step",traits:["move"]}),stride=new SimpleAction({cost:1,description:"PF2E.Actions.Stride.Description",name:"PF2E.Actions.Stride.Title",slug:"stride",traits:["move"]}),takeCover=new SimpleAction({cost:1,description:"PF2E.Actions.TakeCover.Description",effect:"Compendium.pf2e.other-effects.I9lfZUiCwMiGogVi",img:"systems/pf2e/icons/conditions-2/status_acup.webp",name:"PF2E.Actions.TakeCover.Title",slug:"take-cover"});function tamper(options){const slug=options?.skill??"crafting",rollOptions=["action:tamper"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Tamper.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["inventor","manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(tamper,"tamper"),__name2(tamper,"tamper");const PREFIX$a="PF2E.Actions.CreateADiversion",CREATE_A_DIVERSION_VARIANTS=["distracting-words","gesture","trick"];function createADiversion(options){const{title,traits,variant}=(()=>{switch(options?.variant){case"distracting-words":return{title:`${PREFIX$a}.DistractingWords.Title`,traits:["auditory","linguistic","mental"],variant:options.variant};case"gesture":return{title:`${PREFIX$a}.Gesture.Title`,traits:["manipulate","mental"],variant:options.variant};case"trick":return{title:`${PREFIX$a}.Trick.Title`,traits:["manipulate","mental"],variant:options.variant};default:{const variant2=options?.variant?`'${options.variant}'`:"null",variants=CREATE_A_DIVERSION_VARIANTS.map(v=>`'${v}'`).join(", ");throw ui.notifications.error(game.i18n.format(`${PREFIX$a}.Warning.UnknownVariant`,{variant:variant2,variants})),new Error(`Unknown variant ${variant2} for Create a Diversion, use one of ${variants}.`)}}})(),slug=options?.skill??"deception",rollOptions=["action:create-a-diversion",`action:create-a-diversion:${variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits,event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$a}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$a}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(createADiversion,"createADiversion"),__name2(createADiversion,"createADiversion");function feint(options){const slug=options?.skill??"deception",rollOptions=["action:feint"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Feint.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(feint,"feint"),__name2(feint,"feint");const PREFIX$9="PF2E.Actions.Impersonate";function impersonate(options){const slug=options?.skill??"deception",rollOptions=["action:impersonate"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$9}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","manipulate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$9}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$9,"failure"),ActionMacroHelpers.note(selector,PREFIX$9,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(impersonate,"impersonate"),__name2(impersonate,"impersonate");const PREFIX$8="PF2E.Actions.Lie";function lie(options){const slug=options?.skill??"deception",rollOptions=["action:lie"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$8}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","linguistic","mental","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$8}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$8}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(lie,"lie"),__name2(lie,"lie");function bonMot(options){const slug=options?.skill??"diplomacy",rollOptions=["action:bon-mot"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.BonMot.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(bonMot,"bonMot"),__name2(bonMot,"bonMot");const PREFIX$7="PF2E.Actions.GatherInformation";function gatherInformation(options){const slug=options?.skill??"diplomacy",rollOptions=["action:gather-information"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$7}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$7}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$7,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(gatherInformation,"gatherInformation"),__name2(gatherInformation,"gatherInformation");function makeAnImpression(options){const slug=options?.skill??"diplomacy",rollOptions=["action:make-an-impression"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.MakeAnImpression.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","exploration","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(makeAnImpression,"makeAnImpression"),__name2(makeAnImpression,"makeAnImpression");function request(options){const slug=options?.skill??"diplomacy",rollOptions=["action:request"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Request.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Request","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(request,"request"),__name2(request,"request");function avoidNotice(options){const slug=options?.skill??"stealth",rollOptions=["action:avoid-notice"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.AvoidNotice.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.AvoidNotice","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.AvoidNotice","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(avoidNotice,"avoidNotice"),__name2(avoidNotice,"avoidNotice");const action$i=new SingleCheckAction({description:"PF2E.Actions.AvoidNotice.Description",name:"PF2E.Actions.AvoidNotice.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.AvoidNotice.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.AvoidNotice.Notes.success"}],rollOptions:["action:avoid-notice"],slug:"avoid-notice",statistic:"stealth",traits:["exploration"]});function senseDirection(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.SenseDirection.Modifier.NoCompass",modifier:-2,predicate:[{not:"compass-in-possession"}],type:"item"})].concat(options?.modifiers??[]),slug=options?.skill??"survival",rollOptions=["action:sense-direction"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.SenseDirection.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.SenseDirection","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseDirection","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(senseDirection,"senseDirection"),__name2(senseDirection,"senseDirection");const action$h=new SingleCheckAction({description:"PF2E.Actions.SenseDirection.Description",modifiers:[{label:"PF2E.Actions.SenseDirection.Modifier.NoCompass",modifier:-2,predicate:[{not:"compass-in-possession"}],type:"item"}],name:"PF2E.Actions.SenseDirection.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.SenseDirection.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.SenseDirection.Notes.success"}],rollOptions:["action:sense-direction"],slug:"sense-direction",statistic:"survival",traits:["exploration","secret"]});function track(options){const slug=options?.skill??"survival",rollOptions=["action:track"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Track.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Track","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Track","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Track","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(track,"track"),__name2(track,"track");const action$g=new SingleCheckAction({description:"PF2E.Actions.Track.Description",name:"PF2E.Actions.Track.Title",notes:[{outcome:["success","criticalSuccess"],text:"PF2E.Actions.Track.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Track.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Track.Notes.criticalFailure"}],rollOptions:["action:track"],slug:"track",statistic:"survival",traits:["concentrate","exploration","move"]});function decipherWriting(options){if(!options?.skill){ui.notifications.warn(game.i18n.localize("PF2E.Actions.DecipherWriting.Warning.NoSkill"));return}const{skill:slug}=options,rollOptions=["action:decipher-writing",`action:decipher-writing:${slug}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.DecipherWriting.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(decipherWriting,"decipherWriting"),__name2(decipherWriting,"decipherWriting");const _DecipherWritingActionVariant=class extends SingleCheckActionVariant{static{__name(this,"_DecipherWritingActionVariant")}async use(options){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.DecipherWriting.Warning.NoSkill"));const rollOption=`action:decipher-writing:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}};__name2(_DecipherWritingActionVariant,"DecipherWritingActionVariant");let DecipherWritingActionVariant=_DecipherWritingActionVariant;const _DecipherWritingAction=class extends SingleCheckAction{static{__name(this,"_DecipherWritingAction")}constructor(){super({description:"PF2E.Actions.DecipherWriting.Description",name:"PF2E.Actions.DecipherWriting.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.DecipherWriting.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.DecipherWriting.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.DecipherWriting.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.DecipherWriting.Notes.criticalFailure"}],rollOptions:["action:decipher-writing"],slug:"decipher-writing",statistic:"",traits:["concentrate","exploration","secret"]})}toActionVariant(data){return new DecipherWritingActionVariant(this,data)}};__name2(_DecipherWritingAction,"DecipherWritingAction");let DecipherWritingAction=_DecipherWritingAction;const action$f=new DecipherWritingAction;function subsist(options){if(!options?.skill){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Subsist.Warning.NoSkill"));return}const modifiers=[new ModifierPF2e({label:"PF2E.Actions.Subsist.AfterExplorationPenalty",modifier:-5,predicate:["action:subsist:after-exploration"]})].concat(options?.modifiers??[]),{skill:slug}=options,rollOptions=["action:subsist",`action:subsist:${slug}`];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Subsist.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(subsist,"subsist"),__name2(subsist,"subsist");const _SubsistActionVariant=class extends SingleCheckActionVariant{static{__name(this,"_SubsistActionVariant")}async use(options={}){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.Subsist.Warning.NoSkill"));const rollOption=`action:subsist:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}};__name2(_SubsistActionVariant,"SubsistActionVariant");let SubsistActionVariant=_SubsistActionVariant;const _SubsistAction=class extends SingleCheckAction{static{__name(this,"_SubsistAction")}constructor(){super({description:"PF2E.Actions.Subsist.Description",modifiers:[{label:"PF2E.Actions.Subsist.AfterExplorationPenalty",modifier:-5,predicate:["action:subsist:after-exploration"]}],name:"PF2E.Actions.Subsist.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Subsist.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Subsist.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Subsist.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Subsist.Notes.criticalFailure"}],rollOptions:["action:subsist"],slug:"subsist",statistic:"",traits:["downtime"]})}toActionVariant(data){return new SubsistActionVariant(this,data)}};__name2(_SubsistAction,"SubsistAction");let SubsistAction=_SubsistAction;const action$e=new SubsistAction;function coerce(options){const slug=options?.skill??"intimidation",rollOptions=["action:coerce"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Coerce.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","exploration","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(coerce,"coerce"),__name2(coerce,"coerce");const action$d=new SingleCheckAction({description:"PF2E.Actions.Coerce.Description",difficultyClass:"will",name:"PF2E.Actions.Coerce.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Coerce.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Coerce.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Coerce.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Coerce.Notes.criticalFailure"}],rollOptions:["action:coerce"],slug:"coerce",statistic:"intimidation",traits:["auditory","concentrate","emotion","exploration","linguistic","mental"]});function demoralize(options){const slug=options?.skill??"intimidation",rollOptions=["action:demoralize"],modifiers=[new ModifierPF2e({label:"PF2E.Actions.Demoralize.Unintelligible",modifier:-4,predicate:["action:demoralize:unintelligible"],type:"circumstance"})].concat(options?.modifiers??[]);ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Demoralize.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","fear","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Demoralize","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Demoralize","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(demoralize,"demoralize"),__name2(demoralize,"demoralize");const action$c=new SingleCheckAction({description:"PF2E.Actions.Demoralize.Description",difficultyClass:"will",modifiers:[{label:"PF2E.Actions.Demoralize.Unintelligible",modifier:-4,predicate:["action:demoralize:unintelligible"],type:"circumstance"}],name:"PF2E.Actions.Demoralize.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Demoralize.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Demoralize.Notes.success"}],rollOptions:["action:demoralize"],slug:"demoralize",statistic:"intimidation",traits:["auditory","concentrate","emotion","fear","mental"]}),PREFIX$6="PF2E.Actions.AdministerFirstAid",ADMINISTER_FIRST_AID_VARIANTS=["stabilize","stop-bleeding"];function stabilizeDifficultyClass(target){if(!target?.isOfType("creature"))return null;const{dying}=target.attributes;if(!dying?.value)throw new Error(game.i18n.localize(`${PREFIX$6}.Warning.TargetNotDying`));const dcModifier=new ModifierPF2e({slug:"dying-recovery",label:"PF2E.ModifierTitle",modifier:5+dying.recoveryDC+dying.value-10});return new Statistic(target,{slug:"administer-first-aid",label:`${PREFIX$6}.Stabilize.Title`,dc:{label:`${PREFIX$6}.Stabilize.DifficultyClass.Label`,modifiers:[dcModifier]}}).dc}__name(stabilizeDifficultyClass,"stabilizeDifficultyClass"),__name2(stabilizeDifficultyClass,"stabilizeDifficultyClass");function administerFirstAid(options){const{notes,title,variant}=(()=>{const mainTitle=game.i18n.localize(`${PREFIX$6}.Title`);switch(options?.variant){case"stabilize":return{notes:{criticalFailure:`${PREFIX$6}.Stabilize.Notes.criticalFailure`,success:`${PREFIX$6}.Stabilize.Notes.success`},title:mainTitle+" - "+game.i18n.localize(`${PREFIX$6}.Stabilize.Title`),variant:options.variant};case"stop-bleeding":return{notes:{criticalFailure:`${PREFIX$6}.StopBleeding.Notes.criticalFailure`,success:`${PREFIX$6}.StopBleeding.Notes.success`},title:mainTitle+" - "+game.i18n.localize(`${PREFIX$6}.StopBleeding.Title`),variant:options.variant};default:{const variant2=options?.variant?`'${options.variant}'`:"null",variants=ADMINISTER_FIRST_AID_VARIANTS.map(v=>`'${v}'`).join(", "),error=`${PREFIX$6}.Warning.UnknownVariant`;throw ui.notifications.error(game.i18n.format(error,{variant:variant2,variants})),new Error(`Unknown variant ${variant2} for Administer First Aid, use one of ${variants}.`)}}})(),slug=options?.skill??"medicine",rollOptions=["action:administer-first-aid",`action:administer-first-aid:${variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??(target=>{if(variant==="stabilize"&&target)try{return stabilizeDifficultyClass(target)}catch(error){if(error instanceof Error)ui.notifications.warn(error.message);else throw error}return null}),extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,notes.success,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,notes.criticalFailure,["criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(administerFirstAid,"administerFirstAid"),__name2(administerFirstAid,"administerFirstAid");const _AdministerFirstAidAction=class extends SingleCheckAction{static{__name(this,"_AdministerFirstAidAction")}constructor(){super({cost:2,description:`${PREFIX$6}.Description`,name:`${PREFIX$6}.Title`,slug:"administer-first-aid",statistic:"medicine",traits:["manipulate"],variants:[{description:`${PREFIX$6}.Stabilize.Description`,name:`${PREFIX$6}.Stabilize.Title`,notes:[{outcome:["criticalSuccess","success"],text:`${PREFIX$6}.Stabilize.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$6}.Stabilize.Notes.criticalFailure`}],slug:"stabilize"},{description:`${PREFIX$6}.StopBleeding.Description`,name:`${PREFIX$6}.StopBleeding.Title`,notes:[{outcome:["criticalSuccess","success"],text:`${PREFIX$6}.StopBleeding.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$6}.StopBleeding.Notes.criticalFailure`}],slug:"stop-bleeding"}]})}};__name2(_AdministerFirstAidAction,"AdministerFirstAidAction");let AdministerFirstAidAction=_AdministerFirstAidAction;const action$b=new AdministerFirstAidAction;function treatDisease(options){const slug=options?.skill??"medicine",rollOptions=["action:treat-disease"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.TreatDisease.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(treatDisease,"treatDisease"),__name2(treatDisease,"treatDisease");const action$a=new SingleCheckAction({description:"PF2E.Actions.TreatDisease.Description",name:"PF2E.Actions.TreatDisease.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.TreatDisease.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.TreatDisease.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.TreatDisease.Notes.criticalFailure"}],rollOptions:["action:treat-disease"],slug:"treat-disease",statistic:"medicine",traits:["downtime","manipulate"]});function treatPoison(options){const slug=options?.skill??"medicine",rollOptions=["action:treat-poison"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.TreatPoison.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(treatPoison,"treatPoison"),__name2(treatPoison,"treatPoison");const action$9=new SingleCheckAction({cost:1,description:"PF2E.Actions.TreatPoison.Description",name:"PF2E.Actions.TreatPoison.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.TreatPoison.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.TreatPoison.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.TreatPoison.Notes.criticalFailure"}],rollOptions:["action:treat-poison"],slug:"treat-poison",statistic:"medicine",traits:["manipulate"]}),PREFIX$5="PF2E.Actions.CommandAnAnimal";function commandAnAnimal(options){const slug=options?.skill??"nature",rollOptions=["action:command-an-animal"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$5}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$5}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$5,"failure"),ActionMacroHelpers.note(selector,PREFIX$5,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(commandAnAnimal,"commandAnAnimal"),__name2(commandAnAnimal,"commandAnAnimal");const action$8=new SingleCheckAction({cost:1,description:`${PREFIX$5}.Description`,difficultyClass:"will",name:`${PREFIX$5}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$5}.Notes.success`},{outcome:["failure"],text:`${PREFIX$5}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$5}.Notes.criticalFailure`}],rollOptions:["action:command-an-animal"],slug:"command-an-animal",statistic:"nature",traits:["auditory","concentrate"]}),PERFORM_VARIANT_TRAITS={acting:["auditory","linguistic","visual"],comedy:["auditory","linguistic","visual"],dance:["move","visual"],keyboards:["auditory","manipulate"],oratory:["auditory","linguistic"],percussion:["auditory","manipulate"],singing:["auditory","linguistic"],strings:["auditory","manipulate"],winds:["auditory","manipulate"]};function perform(options){const traits=PERFORM_VARIANT_TRAITS[options?.variant??""];if(!traits){const msg=game.i18n.format("PF2E.Actions.Perform.Warning.UnknownVariant",{variant:options.variant});ui.notifications.warn(msg);return}const slug=options?.skill??"performance",rollOptions=["action:perform",`action:perform:${options.variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`PF2E.Actions.Perform.${options.variant.charAt(0).toUpperCase()}${options.variant.slice(1)}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate",...traits].sort(),event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(perform,"perform"),__name2(perform,"perform");async function createForgeryCallback(result,callback){const societyDC=(()=>{if(result.actor instanceof CreaturePF2e){const systemFlags=result.message?.flags.pf2e,modifiers=systemFlags.modifiers.filter(modifier=>modifier.enabled).map(modifier=>({...modifier,predicate:[]})).map(modifier=>new ModifierPF2e(modifier));return result.actor.skills.society.extend({slug:result.actor.skills.society.slug,modifiers}).withRollOptions({extraRollOptions:systemFlags.context.options,origin:result.actor}).dc}return null})(),gmNotes=(()=>["criticalSuccess","success"].includes(result.outcome??"")?game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.SuccessGmNote",{societyDC:societyDC?.value??null}):["criticalFailure","failure"].includes(result.outcome??"")?game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.FailureGmNote",{failure:game.i18n.localize("PF2E.Actions.CreateForgery.Notes.failure"),success:game.i18n.localize("PF2E.Actions.CreateForgery.Notes.success"),total:result.roll.total}):"")();await Item.create({img:"systems/pf2e/icons/equipment/adventuring-gear/scroll-case.webp",name:game.i18n.localize("PF2E.Actions.CreateForgery.ForgedDocument.Name"),type:"equipment",system:{description:{gm:gmNotes,value:game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.Description",{societyDC:societyDC?.value??null})}}},{parent:result.actor});const notification=game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocumentCreatedNotification",{name:result.actor.name});ui.notifications.info(notification),callback?.(result)}__name(createForgeryCallback,"createForgeryCallback"),__name2(createForgeryCallback,"createForgeryCallback");function createForgery(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.CreateForgery.UnspecificHandwriting",modifier:4,predicate:["action:create-forgery:unspecific-handwriting"],type:"circumstance"})].concat(options?.modifiers??[]),slug=options?.skill??"society",rollOptions=["action:create-forgery"];return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.CreateForgery.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","secret"],event:options.event,callback:async result=>createForgeryCallback(result,options?.callback),difficultyClass:options.difficultyClass??{value:20},extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(createForgery,"createForgery"),__name2(createForgery,"createForgery");const _CreateForgeryActionVariant=class extends SingleCheckActionVariant{static{__name(this,"_CreateForgeryActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)await createForgeryCallback(result);return results})}};__name2(_CreateForgeryActionVariant,"CreateForgeryActionVariant");let CreateForgeryActionVariant=_CreateForgeryActionVariant;const _CreateForgeryAction=class extends SingleCheckAction{static{__name(this,"_CreateForgeryAction")}constructor(){super({description:"PF2E.Actions.CreateForgery.Description",difficultyClass:{value:20},modifiers:[{label:"PF2E.Actions.CreateForgery.UnspecificHandwriting",modifier:4,predicate:["action:create-forgery:unspecific-handwriting"],type:"circumstance"}],name:"PF2E.Actions.CreateForgery.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.CreateForgery.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.CreateForgery.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.CreateForgery.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.CreateForgery.Notes.criticalFailure"}],rollOptions:["action:create-forgery"],slug:"create-forgery",statistic:"society",traits:["downtime","secret"]})}toActionVariant(data){return new CreateForgeryActionVariant(this,data)}};__name2(_CreateForgeryAction,"CreateForgeryAction");let CreateForgeryAction=_CreateForgeryAction;const action$7=new CreateForgeryAction,PREFIX$4="PF2E.Actions.ConcealAnObject";function concealAnObject(options){const slug=options?.skill??"stealth",rollOptions=["action:conceal-an-object"],modifiers=options?.modifiers;return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$4}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$4}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$4}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(concealAnObject,"concealAnObject"),__name2(concealAnObject,"concealAnObject");const action$6=new SingleCheckAction({cost:1,description:`${PREFIX$4}.Description`,difficultyClass:"perception",name:`${PREFIX$4}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$4}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$4}.Notes.failure`}],rollOptions:["action:conceal-an-object"],slug:"conceal-an-object",statistic:"stealth",traits:["manipulate","secret"]}),PREFIX$3="PF2E.Actions.Hide";function hide(options){const slug=options?.skill??"stealth",rollOptions=["action:hide"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$3}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$3}.Notes.success`,["success","criticalSuccess"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(hide,"hide"),__name2(hide,"hide");const action$5=new SingleCheckAction({cost:1,description:`${PREFIX$3}.Description`,difficultyClass:"perception",name:`${PREFIX$3}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$3}.Notes.success`}],rollOptions:["action:hide"],slug:"hide",statistic:"stealth",traits:["secret"]}),PREFIX$2="PF2E.Actions.Sneak";function sneak(options){const slug=options?.skill??"stealth",rollOptions=["action:sneak"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$2}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$2}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$2,"failure"),ActionMacroHelpers.note(selector,PREFIX$2,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(sneak,"sneak"),__name2(sneak,"sneak");const action$4=new SingleCheckAction({cost:1,description:`${PREFIX$2}.Description`,difficultyClass:"perception",name:`${PREFIX$2}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$2}.Notes.success`},{outcome:["failure"],text:`${PREFIX$2}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$2}.Notes.criticalFailure`}],rollOptions:["action:sneak"],slug:"sneak",statistic:"stealth",traits:["move","secret"]}),PREFIX$1="PF2E.Actions.PalmAnObject";function palmAnObject(options){const slug=options?.skill??"thievery",rollOptions=["action:palm-an-object"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$1}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$1}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$1}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(palmAnObject,"palmAnObject"),__name2(palmAnObject,"palmAnObject");const action$3=new SingleCheckAction({cost:1,description:`${PREFIX$1}.Description`,difficultyClass:"perception",name:`${PREFIX$1}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$1}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$1}.Notes.failure`}],rollOptions:["action:palm-an-object"],slug:"palm-an-object",statistic:"thievery",traits:["manipulate"]});function disableDevice(options){const slug=options?.skill??"thievery",rollOptions=["action:disable-a-device","action:disable-device"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options?.actors,actionGlyph:options?.glyph??"D",title:"PF2E.Actions.DisableDevice.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options?.event,callback:options?.callback,difficultyClass:options?.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(disableDevice,"disableDevice"),__name2(disableDevice,"disableDevice");const action$2=new SingleCheckAction({cost:2,description:"PF2E.Actions.DisableDevice.Description",name:"PF2E.Actions.DisableDevice.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.DisableDevice.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.DisableDevice.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.DisableDevice.Notes.criticalFailure"}],rollOptions:["action:disable-a-device","action:disable-device"],slug:"disable-device",statistic:"thievery",traits:["manipulate"]});function pickALock(options){const slug=options?.skill??"thievery",rollOptions=["action:pick-a-lock"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:"PF2E.Actions.PickALock.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(pickALock,"pickALock"),__name2(pickALock,"pickALock");const action$1=new SingleCheckAction({cost:2,description:"PF2E.Actions.PickALock.Description",name:"PF2E.Actions.PickALock.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.PickALock.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.PickALock.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.PickALock.Notes.criticalFailure"}],rollOptions:["action:pick-a-lock"],slug:"pick-a-lock",statistic:"thievery",traits:["manipulate"]}),PREFIX="PF2E.Actions.Steal";function steal(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.Steal.Pocketed",modifier:-5,predicate:["action:steal:pocketed"]})].concat(options?.modifiers??[]),slug=options?.skill??"thievery",rollOptions=["action:steal"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(steal,"steal"),__name2(steal,"steal");const action=new SingleCheckAction({cost:1,description:`${PREFIX}.Description`,difficultyClass:"perception",modifiers:[{label:"PF2E.Actions.Steal.Pocketed",modifier:-5,predicate:["action:steal:pocketed"]}],name:`${PREFIX}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX}.Notes.failure`}],rollOptions:["action:steal"],slug:"steal",statistic:"thievery",traits:["manipulate"]}),ActionMacros={escape,seek,senseMotive,arcaneSlam,tamper,avoidNotice,senseDirection,track,balance,maneuverInFlight,squeeze,tumbleThrough,climb,disarm,forceOpen,grapple,highJump,longJump,shove,swim,trip,whirlingThrow,craft,repair,createADiversion,feint,impersonate,lie,bonMot,gatherInformation,makeAnImpression,request,decipherWriting,subsist,coerce,demoralize,administerFirstAid,treatDisease,treatPoison,commandAnAnimal,perform,createForgery,concealAnObject,hide,sneak,palmAnObject,disableDevice,pickALock,steal},SystemActions=[action$b,aid,action$i,action$q,action$d,action$8,action$6,crawl,action$7,action$f,delay,action$c,action$2,dropProne,action$l,action$5,interact,leap,action$p,action$3,action$1,ready,release,action$k,action$h,action$j,action$4,action$o,stand,action,step,stride,action$e,takeCover,action$g,action$a,action$9,action$m,action$n],_EffectTracker=class{static{__name(this,"_EffectTracker")}constructor(){__privateAdd(this,_insert),__privateAdd(this,_removeExpired),__publicField(this,"effects",[]),__publicField(this,"auraEffects",new Collection)}register(effect){effect.fromAura&&(canvas.ready||!effect.actor.isToken)&&effect.id&&this.auraEffects.set(effect.uuid,effect);const index=this.effects.findIndex(e=>e.id===effect.id),systemData=effect.system,duration=systemData.duration.unit;switch(duration){case"unlimited":case"encounter":{duration==="unlimited"&&(systemData.expired=!1),index>=0&&indexe!==toRemove),this.auraEffects.delete(toRemove.uuid)}async refresh(options={}){if(options.resetItemData){const actors=new Set(this.effects.flatMap(e=>e.actor??[]));for(const actor of actors)actor.reset();game.pf2e.effectPanel.refresh()}const actorsToUpdate=new Set(this.effects.filter(e=>e.isExpired).map(e=>e.actor));if(game.settings.get("pf2e","automation.removeExpiredEffects"))for(const actor of actorsToUpdate)await __privateMethod(this,_removeExpired,removeExpired_fn).call(this,actor);else game.settings.get("pf2e","automation.effectExpiration")&&resetActors(actorsToUpdate)}async onEncounterEnd(encounter){const autoRemoveExpired=game.settings.get("pf2e","automation.removeExpiredEffects"),autoExpireEffects=!autoRemoveExpired&&game.settings.get("pf2e","automation.effectExpiration");if(!(autoExpireEffects||autoRemoveExpired))return;const actors=encounter.combatants.contents.flatMap(c=>c.actor??[]).filter(a=>game.user===a.primaryUpdater);for(const actor of actors){const expiresNow=actor.itemTypes.effect.filter(e=>e.system.duration.unit==="encounter");if(expiresNow.length!==0){if(autoExpireEffects){const updates=expiresNow.map(e=>({_id:e.id,"system.expired":!0}));await actor.updateEmbeddedDocuments("Item",updates)}else{const deletes=expiresNow.map(e=>e.id);await actor.deleteEmbeddedDocuments("Item",deletes)}for(const effect of expiresNow)this.unregister(effect)}}}};_insert=new WeakSet,insert_fn=__name2(function(effect,duration){if(this.effects.length===0)this.effects.push(effect);else{for(let index=0;indexremaining)){if(remaining>duration.remaining){this.effects.splice(index,0,effect);return}else if(!((effect.system.start.initiative??0)>(other.system.start.initiative??0))){if((other.system.start.initiative??0)>(effect.system.start.initiative??0)){this.effects.splice(index,0,effect);return}else if(other.system.duration.expiry==="turn-start"&&effect.system.duration.expiry==="turn-end"){this.effects.splice(index,0,effect);return}}}}this.effects.push(effect)}},"#insert"),_removeExpired=new WeakSet,removeExpired_fn=__name2(async function(actor){actor.primaryUpdater===game.user&&await actor.deleteEmbeddedDocuments("Item",actor.itemTypes.effect.filter(e=>e.isExpired).map(e=>e.id))},"#removeExpired"),__name2(_EffectTracker,"EffectTracker");let EffectTracker=_EffectTracker;const _ModuleArt=class{static{__name(this,"_ModuleArt")}constructor(){__privateAdd(this,_getArtMap),__privateAdd(this,_isModuleArt),__publicField(this,"map",new Map)}async refresh(){this.map.clear();const activeModules=[...game.modules.entries()].filter(([_key,m])=>m.active);for(const[moduleKey,foundryModule]of activeModules){const moduleArt=await __privateMethod(this,_getArtMap,getArtMap_fn).call(this,foundryModule.flags?.[moduleKey]?.["pf2e-art"]);if(moduleArt)for(const[packName,art]of Object.entries(moduleArt)){const pack=game.packs.get(`pf2e.${packName}`);if(!pack){console.warn(`PF2e System | Failed pack lookup from module art registration (${moduleKey}): ${packName}`);continue}const index=pack.indexed?pack.index:await pack.getIndex();for(const[actorId,paths]of Object.entries(art)){const record=index.get(actorId);if(!record)continue;record.img=paths.actor;const actorArtPartial={img:paths.actor,prototypeToken:{texture:{src:typeof paths.token=="string"?paths.token:paths.token.img}}};typeof paths.token!="string"&&(typeof paths.token.scale=="number"&&(actorArtPartial.prototypeToken.texture.scaleX=paths.token.scale,actorArtPartial.prototypeToken.texture.scaleY=paths.token.scale,actorArtPartial.prototypeToken.flags={pf2e:{autoscale:!1}}),typeof paths.token.randomImg=="boolean"&&(actorArtPartial.prototypeToken.randomImg=paths.token.randomImg)),this.map.set(`Compendium.pf2e.${packName}.${actorId}`,actorArtPartial)}}}const apps=Object.values(ui.windows).filter(w=>w instanceof Compendium);for(const compendium of apps)compendium.render()}};_getArtMap=new WeakSet,getArtMap_fn=__name2(async function(art){if(art){if(__privateMethod(this,_isModuleArt,isModuleArt_fn).call(this,art))return art;if(typeof art=="string")try{const response=await fetch(art);if(!response.ok)return console.warn(`PF2e System | Failed loading art mapping file at ${art}`),null;const map2=await response.json();return __privateMethod(this,_isModuleArt,isModuleArt_fn).call(this,map2)?map2:null}catch(error){error instanceof Error&&console.warn(`PF2e System | ${error.message}`)}}else return null;return null},"#getArtMap"),_isModuleArt=new WeakSet,isModuleArt_fn=__name2(function(record){return isObject(record)&&Object.values(record).every(packToArt=>isObject(packToArt)&&Object.values(packToArt).every(art=>isObject(art)&&"actor"in art&&typeof isImageFilePath(art.actor)&&"token"in art&&(isImageOrVideoPath(art.token)||isObject(art.token)&&"img"in art.token&&isImageOrVideoPath(art.token.img)&&(!("scale"in art.token)||typeof art.token.scale=="number"&&art.token.scale>0)&&(!("randomImg"in art.token)||typeof art.token.randomImg=="boolean"))))},"#isModuleArt"),__name2(_ModuleArt,"ModuleArt");let ModuleArt=_ModuleArt;const SetGamePF2e={onInit:()=>{const actions=new Map(SystemActions.map(action2=>[action2.slug,action2]));for(const[name2,action2]of Object.entries({encouragingWords,raiseAShield,restForTheNight,earnIncome:showEarnIncomePopup,steelYourResolve,takeABreather,treatWounds,...ActionMacros}))actions[name2]=action2;const initSafe={Check:CheckPF2e,CheckModifier,Coins:CoinsPF2e,ConditionManager,Dice:DicePF2e,Modifier:ModifierPF2e,ModifierType:{ABILITY:"ability",PROFICIENCY:"proficiency",CIRCUMSTANCE:"circumstance",ITEM:"item",POTENCY:"potency",STATUS:"status",UNTYPED:"untyped"},RuleElement:RuleElementPF2e,RuleElements,StatisticModifier,StatusEffects,TextEditor:TextEditorPF2e,ElementalBlast,actions,effectPanel:new EffectsPanel,effectTracker:new EffectTracker,gm:{calculateXP,checkPrompt,editPersistent,launchTravelSheet,perceptionForSelected,stealthForSelected,xpFromEncounter},licenseViewer:new LicenseViewer,rollActionMacro,rollItemMacro,system:{generateItemName,moduleArt:new ModuleArt,remigrate,sluggify},variantRules:{AutomaticBonusProgression}};game.pf2e=mergeObject(game.pf2e??{},initSafe),game.pf2e.ConditionManager.initialize()},onSetup:()=>{},onReady:()=>{game.pf2e.compendiumBrowser=new CompendiumBrowser,game.pf2e.worldClock=new WorldClock}},_AutomationSettings=class extends SettingsMenuPF2e{static{__name(this,"_AutomationSettings")}static get settings(){return{rulesBasedVision:{name:CONFIG.PF2E.SETTINGS.automation.rulesBasedVision.name,hint:CONFIG.PF2E.SETTINGS.automation.rulesBasedVision.hint,default:!0,type:Boolean,requiresReload:!0},iwr:{name:CONFIG.PF2E.SETTINGS.automation.iwr.name,hint:CONFIG.PF2E.SETTINGS.automation.iwr.hint,default:!1,type:Boolean},effectExpiration:{name:CONFIG.PF2E.SETTINGS.automation.effectExpiration.name,hint:CONFIG.PF2E.SETTINGS.automation.effectExpiration.hint,default:!0,type:Boolean,onChange:()=>{for(const actor of game.actors){actor.reset(),actor.sheet.render(!1);for(const token of actor.getActiveTokens())token.drawEffects()}}},removeExpiredEffects:{name:CONFIG.PF2E.SETTINGS.automation.removeExpiredEffects.name,hint:CONFIG.PF2E.SETTINGS.automation.removeExpiredEffects.hint,default:!1,type:Boolean},flankingDetection:{name:CONFIG.PF2E.SETTINGS.automation.flankingDetection.name,hint:CONFIG.PF2E.SETTINGS.automation.flankingDetection.hint,default:!0,type:Boolean},encumbrance:{name:"PF2E.SETTINGS.Automation.Encumbrance.Name",hint:"PF2E.SETTINGS.Automation.Encumbrance.Hint",default:!1,type:Boolean},lootableNPCs:{name:CONFIG.PF2E.SETTINGS.automation.lootableNPCs.name,hint:CONFIG.PF2E.SETTINGS.automation.lootableNPCs.hint,default:!0,type:Boolean}}}};__name2(_AutomationSettings,"AutomationSettings"),__publicField(_AutomationSettings,"namespace","automation"),__publicField(_AutomationSettings,"SETTINGS",["rulesBasedVision","iwr","effectExpiration","removeExpiredEffects","flankingDetection","encumbrance","lootableNPCs"]);let AutomationSettings=_AutomationSettings;const MetagameSettingsConfig={showDC:{name:"PF2E.SETTINGS.Metagame.ShowDC.Name",hint:"PF2E.SETTINGS.Metagame.ShowDC.Hint",default:!1,type:Boolean},showResults:{name:"PF2E.SETTINGS.Metagame.ShowResults.Name",hint:"PF2E.SETTINGS.Metagame.ShowResults.Hint",default:!0,type:Boolean},tokenSetsNameVisibility:{name:"PF2E.SETTINGS.Metagame.TokenSetsNameVisibility.Name",hint:"PF2E.SETTINGS.Metagame.TokenSetsNameVisibility.Hint",default:!1,type:Boolean,onChange:async()=>{await ui.combat.render();const renderedMessages=document.querySelectorAll("#chat-log > li");for(const rendered of Array.from(renderedMessages)){const message=game.messages.get(rendered?.dataset.messageId??"");message&&await ui.chat.updateMessage(message)}}},secretDamage:{name:"PF2E.SETTINGS.Metagame.SecretDamage.Name",hint:"PF2E.SETTINGS.Metagame.SecretDamage.Hint",default:!1,type:Boolean},secretCondition:{name:"PF2E.SETTINGS.Metagame.SecretCondition.Name",hint:"PF2E.SETTINGS.Metagame.SecretCondition.Hint",default:!1,type:Boolean},showPartyStats:{name:"PF2E.SETTINGS.Metagame.ShowPartyStats.Name",hint:"PF2E.SETTINGS.Metagame.ShowPartyStats.Hint",default:!0,type:Boolean,onChange:()=>{resetActors(game.actors.filter(a=>a.isOfType("party")))}},partyVision:{name:"PF2E.SETTINGS.Metagame.PartyVision.Name",hint:"PF2E.SETTINGS.Metagame.PartyVision.Hint",default:!1,type:Boolean,onChange:()=>{canvas.ready&&canvas.scene&&canvas.perception.update({initializeVision:!0,refreshLighting:!0},!0)}}},_MetagameSettings=class extends SettingsMenuPF2e{static{__name(this,"_MetagameSettings")}static get settings(){return MetagameSettingsConfig}static get SETTINGS(){return Object.keys(this.settings)}static get prefix(){return`${this.namespace}_`}};__name2(_MetagameSettings,"MetagameSettings"),__publicField(_MetagameSettings,"namespace","metagame");let MetagameSettings=_MetagameSettings;const SETTINGS={gradualBoostsVariant:{name:"PF2E.SETTINGS.Variant.GradualBoosts.Name",hint:"PF2E.SETTINGS.Variant.GradualBoosts.Hint",default:!1,type:Boolean},staminaVariant:{name:"PF2E.SETTINGS.Variant.Stamina.Name",hint:"PF2E.SETTINGS.Variant.Stamina.Hint",default:!1,type:Boolean,onChange:()=>{resetActors(game.actors.filter(a=>a.type==="character"))}},ancestryParagonVariant:{name:"PF2E.SETTINGS.Variant.AncestryParagon.Name",hint:"PF2E.SETTINGS.Variant.AncestryParagon.Hint",default:!1,type:Boolean,onChange:()=>{resetActors(game.actors.filter(a=>a.type==="character"))}},freeArchetypeVariant:{name:"PF2E.SETTINGS.Variant.FreeArchetype.Name",hint:"PF2E.SETTINGS.Variant.FreeArchetype.Hint",default:!1,type:Boolean,onChange:()=>{resetActors(game.actors.filter(a=>a.type==="character"))}},dualClassVariant:{name:"PF2E.SETTINGS.Variant.DualClass.Name",hint:"PF2E.SETTINGS.Variant.DualClass.Hint",default:!1,type:Boolean},automaticBonusVariant:{name:"PF2E.SETTINGS.Variant.AutomaticBonus.Name",hint:"PF2E.SETTINGS.Variant.AutomaticBonus.Hint",default:"noABP",type:String,choices:{noABP:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.noABP",ABPFundamentalPotency:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.ABPFundamentalPotency",ABPRulesAsWritten:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.ABPRulesAsWritten"},onChange:()=>{resetActors(game.actors.filter(a=>a.type==="character"))}},proficiencyVariant:{name:"PF2E.SETTINGS.Variant.Proficiency.Name",hint:"PF2E.SETTINGS.Variant.Proficiency.Hint",default:!1,type:Boolean,onChange:()=>{resetActors(game.actors.filter(a=>a.type==="character"))}},proficiencyUntrainedModifier:{name:"PF2E.SETTINGS.Variant.UntrainedModifier.Name",hint:"PF2E.SETTINGS.Variant.UntrainedModifier.Hint",default:-2,type:Number},proficiencyTrainedModifier:{name:"PF2E.SETTINGS.Variant.TrainedModifier.Name",hint:"PF2E.SETTINGS.Variant.TrainedModifier.Hint",default:2,type:Number},proficiencyExpertModifier:{name:"PF2E.SETTINGS.Variant.ExpertModifier.Name",hint:"PF2E.SETTINGS.Variant.ExpertModifier.Hint",default:4,type:Number},proficiencyMasterModifier:{name:"PF2E.SETTINGS.Variant.MasterModifier.Name",hint:"PF2E.SETTINGS.Variant.MasterModifier.Hint",default:6,type:Number},proficiencyLegendaryModifier:{name:"PF2E.SETTINGS.Variant.LegendaryModifier.Name",hint:"PF2E.SETTINGS.Variant.LegendaryModifier.Hint",default:8,type:Number}},_VariantRulesSettings=class extends FormApplication{static{__name(this,"_VariantRulesSettings")}static get defaultOptions(){return{...super.defaultOptions,title:"PF2E.SETTINGS.Variant.Title",id:"variant-rules-settings",template:"systems/pf2e/templates/system/settings/variant-rules.hbs",width:550,height:"auto",closeOnSubmit:!0}}async getData(){return Object.entries(SETTINGS).reduce((data,[key,setting])=>({...data,[key]:{value:game.settings.get("pf2e",key),setting}}),{})}static registerSettings(){for(const[key,value]of Object.entries(SETTINGS))value.config=!1,value.scope="world",game.settings.register("pf2e",key,value)}activateListeners($html){super.activateListeners($html),htmlQuery($html[0],"button[name=reset]")?.addEventListener("click",async event=>{event.preventDefault();for(const[key,value]of Object.entries(SETTINGS))await game.settings.set("pf2e",key,value?.default);return this.render()})}async _updateObject(_event,data){for(const key of Object.keys(SETTINGS))game.settings.set("pf2e",key,data[key])}};__name2(_VariantRulesSettings,"VariantRulesSettings");let VariantRulesSettings=_VariantRulesSettings;const _WorldClockSettings=class _WorldClockSettings2 extends FormApplication{static{__name(this,"_WorldClockSettings")}static get defaultOptions(){return mergeObject(super.defaultOptions,{title:CONFIG.PF2E.SETTINGS.worldClock.name,id:"world-clock-settings",template:"systems/pf2e/templates/system/settings/world-clock/index.hbs",width:550,height:"auto",closeOnSubmit:!0})}async getData(){const worldDefault=game.settings.get("pf2e","worldClock.syncDarkness")?game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.enabled):game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.disabled),sceneSetting=["syncDarknessScene",{name:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.name,hint:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.hint,default:"default",type:String,choices:{enabled:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.enabled,disabled:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.disabled,default:game.i18n.format(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.default,{worldDefault})}}],settings=[...Object.entries(_WorldClockSettings2.settings).filter(([key])=>key!=="worldCreatedOn"),sceneSetting].map(([key,setting])=>{const value=(()=>{if(key==="syncDarknessScene")return canvas.scene?.flags.pf2e.syncDarkness;const rawValue=game.settings.get("pf2e",`worldClock.${key}`);return key==="worldCreatedOn"&&typeof rawValue=="string"?DateTime.fromISO(rawValue).toFormat("yyyy-MM-dd'T'HH:mm"):rawValue})();return{...setting,key,value,isSelect:"choices"in setting,isCheckbox:setting.type===Boolean,isDateTime:setting.type===String&&!("choices"in setting)}});return mergeObject(await super.getData(),{settings})}static registerSettings(){game.settings.register("pf2e","worldClock.dateTheme",this.settings.dateTheme),game.settings.register("pf2e","worldClock.timeConvention",this.settings.timeConvention),game.settings.register("pf2e","worldClock.playersCanView",this.settings.playersCanView),game.settings.register("pf2e","worldClock.syncDarkness",this.settings.syncDarkness),game.settings.register("pf2e","worldClock.worldCreatedOn",this.settings.worldCreatedOn),game.settings.register("pf2e","worldClock.showClockButton",this.settings.showClockButton)}activateListeners($html){super.activateListeners($html);const localize=localizer("PF2E.SETTINGS.WorldClock"),title=localize("ResetWorldTime.Name");$html.find("button.reset-world-time").on("click",async()=>{const template=await renderTemplate("systems/pf2e/templates/system/settings/world-clock/confirm-reset.hbs");Dialog.confirm({title,content:template,yes:()=>{game.time.advance(-1*game.time.worldTime),this.close()},defaultYes:!1})}),$html.find('input[name="syncDarkness"]').on("change",event=>{const worldDefault=$(event.currentTarget)[0].checked?localize("SyncDarknessScene.Enabled"):localize("SyncDarknessScene.Disabled"),optionSelector='select[name="syncDarknessScene"] > option[value="default"]';$html.find(optionSelector).text(localize("SyncDarknessScene.Default",{worldDefault}))})}async _updateObject(_event,data){const keys2=["dateTheme","timeConvention","playersCanView","syncDarkness","showClockButton"];for(const key of keys2){const settingKey=`worldClock.${key}`,newValue=key==="worldCreatedOn"?DateTime.fromISO(data[key]).toUTC():data[key];await game.settings.set("pf2e",settingKey,newValue)}await canvas.scene?.setFlag("pf2e","syncDarkness",data.syncDarknessScene??"default"),delete data.syncDarknessScene,game.pf2e.worldClock.render(!1)}static get settings(){return{dateTheme:{name:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.name,hint:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.hint,scope:"world",config:!1,default:"AR",type:String,choices:{AR:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.AR,AD:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.AD,CE:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.CE}},timeConvention:{name:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.name,hint:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.hint,scope:"world",config:!1,default:24,type:Number,choices:{24:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.twentyFour,12:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.twelve}},showClockButton:{name:CONFIG.PF2E.SETTINGS.worldClock.showClockButton.name,hint:CONFIG.PF2E.SETTINGS.worldClock.showClockButton.hint,scope:"world",config:!1,default:!0,type:Boolean,onChange:()=>{game.settings.set("pf2e","worldClock.playersCanView",game.settings.get("pf2e","worldClock.showClockButton"))}},playersCanView:{name:CONFIG.PF2E.SETTINGS.worldClock.playersCanView.name,hint:CONFIG.PF2E.SETTINGS.worldClock.playersCanView.hint,scope:"world",config:!1,default:!1,type:Boolean},syncDarkness:{name:CONFIG.PF2E.SETTINGS.worldClock.syncDarkness.name,hint:CONFIG.PF2E.SETTINGS.worldClock.syncDarkness.hint,scope:"world",config:!1,default:!1,type:Boolean},worldCreatedOn:{name:CONFIG.PF2E.SETTINGS.worldClock.worldCreatedOn.name,hint:CONFIG.PF2E.SETTINGS.worldClock.worldCreatedOn.hint,scope:"world",config:!1,default:DateTime.utc().toISO(),type:String}}}};__name2(_WorldClockSettings,"WorldClockSettings");let WorldClockSettings=_WorldClockSettings;function registerSettings(){game.settings.register("pf2e","tokens.autoscale",{name:"PF2E.SETTINGS.Tokens.Autoscale.Name",hint:"PF2E.SETTINGS.Tokens.Autoscale.Hint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.register("pf2e","identifyMagicNotMatchingTraditionModifier",{name:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Name",hint:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Hint",choices:{0:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.0",2:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.2",5:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.5",10:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.10"},type:Number,default:5,scope:"world",config:!0}),game.settings.register("pf2e","critRule",{name:"PF2E.SETTINGS.CritRule.Name",hint:"PF2E.SETTINGS.CritRule.Hint",scope:"world",config:!0,default:"doubledamage",type:String,choices:{doubledamage:"PF2E.SETTINGS.CritRule.Choices.Doubledamage",doubledice:"PF2E.SETTINGS.CritRule.Choices.Doubledice"},onChange:()=>{for(const sheet of Object.values(ui.windows).filter(w=>w instanceof ActorSheetPF2e))sheet.render()}}),game.settings.register("pf2e","compendiumBrowserPacks",{name:"PF2E.SETTINGS.CompendiumBrowserPacks.Name",hint:"PF2E.SETTINGS.CompendiumBrowserPacks.Hint",default:{},type:Object,scope:"world",onChange:()=>{game.pf2e.compendiumBrowser.initCompendiumList()}}),game.settings.register("pf2e","compendiumBrowserSources",{name:"PF2E.SETTINGS.compendiumBrowserSources.Name",hint:"PF2E.SETTINGS.compendiumBrowserSources.Hint",default:{ignoreAsGM:!0,showEmptySources:!0,showUnknownSources:!0,sources:{}},type:Object,scope:"world",onChange:()=>{game.pf2e.compendiumBrowser.packLoader.reset(),game.pf2e.compendiumBrowser.initCompendiumList()}}),game.settings.register("pf2e","enabledRulesUI",{name:"PF2E.SETTINGS.EnabledRulesUI.Name",hint:"PF2E.SETTINGS.EnabledRulesUI.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:()=>{const itemSheets=Object.values(ui.windows).filter(w=>w instanceof ItemSheetPF2e);for(const sheet of itemSheets)sheet.render()}}),game.settings.register("pf2e","critFumbleButtons",{name:game.i18n.localize("PF2E.SETTINGS.critFumbleCardButtons.name"),hint:game.i18n.localize("PF2E.SETTINGS.critFumbleCardButtons.hint"),scope:"world",config:!0,default:!1,type:Boolean,requiresReload:!0}),game.settings.register("pf2e","drawCritFumble",{name:game.i18n.localize("PF2E.SETTINGS.critFumbleCards.name"),hint:game.i18n.localize("PF2E.SETTINGS.critFumbleCards.hint"),scope:"world",config:!0,default:!1,type:Boolean,requiresReload:!0});const iconChoices={blackWhite:"PF2E.SETTINGS.statusEffectType.blackWhite",default:"PF2E.SETTINGS.statusEffectType.default"};game.settings.register("pf2e","statusEffectType",{name:"PF2E.SETTINGS.statusEffectType.name",hint:"PF2E.SETTINGS.statusEffectType.hint",scope:"world",config:!0,default:"default",type:String,choices:iconChoices,onChange:iconType=>{StatusEffects.migrateStatusEffectUrls(iconType)}}),game.settings.register("pf2e","totmToggles",{name:"PF2E.SETTINGS.TOTMToggles.Name",hint:"PF2E.SETTINGS.TOTMToggles.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:()=>{resetActors()}}),game.settings.register("pf2e","deathIcon",{name:"PF2E.SETTINGS.DeathIcon.Name",hint:"PF2E.SETTINGS.DeathIcon.Hint",scope:"world",config:!1,default:"icons/svg/skull.svg",type:String,onChange:choice=>{isImageOrVideoPath(choice)?StatusEffects.reset():choice||game.settings.set("pf2e","deathIcon","icons/svg/skull.svg")}}),game.settings.register("pf2e","dataTools",{name:"PF2E.SETTINGS.DataTools.Name",hint:"PF2E.SETTINGS.DataTools.Hint",scope:"world",config:!1,default:!1,type:Boolean,onChange:()=>{for(const app of Object.values(ui.windows).filter(a=>a instanceof DocumentSheet))app.render()}}),game.settings.register("pf2e","nathMode",{name:"PF2E.SETTINGS.NathMode.Name",hint:"PF2E.SETTINGS.NathMode.Hint",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("pf2e","statusEffectShowCombatMessage",{name:"PF2E.SETTINGS.statusEffectShowCombatMessage.name",hint:"PF2E.SETTINGS.statusEffectShowCombatMessage.hint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.registerMenu("pf2e","automation",{name:"PF2E.SETTINGS.Automation.Name",label:"PF2E.SETTINGS.Automation.Label",hint:"PF2E.SETTINGS.Automation.Hint",icon:"fas fa-robot",type:AutomationSettings,restricted:!0}),game.settings.register("pf2e","automation.actorsDeadAtZero",{name:CONFIG.PF2E.SETTINGS.automation.actorsDeadAtZero.name,scope:"world",config:!1,choices:{neither:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Neither",npcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.NPCsOnly",both:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Both"},default:"both",type:String}),AutomationSettings.registerSettings(),game.settings.registerMenu("pf2e","metagame",{name:"PF2E.SETTINGS.Metagame.Name",label:"PF2E.SETTINGS.Metagame.Label",hint:"PF2E.SETTINGS.Metagame.Hint",icon:"fas fa-brain",type:MetagameSettings,restricted:!0}),MetagameSettings.registerSettings(),game.settings.registerMenu("pf2e","variantRules",{name:"PF2E.SETTINGS.Variant.Name",label:"PF2E.SETTINGS.Variant.Label",hint:"PF2E.SETTINGS.Variant.Hint",icon:"fas fa-book",type:VariantRulesSettings,restricted:!0}),VariantRulesSettings.registerSettings(),game.settings.registerMenu("pf2e","homebrew",{name:"PF2E.SETTINGS.Homebrew.Name",label:"PF2E.SETTINGS.Homebrew.Label",hint:"PF2E.SETTINGS.Homebrew.Hint",icon:"fas fa-beer",type:HomebrewElements,restricted:!0}),HomebrewElements.registerSettings(),game.settings.registerMenu("pf2e","worldClock",{name:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.name),label:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.label),hint:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.hint),icon:"far fa-clock",type:WorldClockSettings,restricted:!0}),WorldClockSettings.registerSettings(),game.settings.register("pf2e","campaignType",{name:"PF2E.SETTINGS.CampaignType.Name",hint:"PF2E.SETTINGS.CampaignType.Hint",scope:"world",config:!1,default:"none",choices:mapToObj(["none","kingmaker"],key=>[key,`PF2E.SETTINGS.CampaignType.Choices.${key}`]),type:String,onChange:async()=>{await resetActors(game.actors.filter(a=>a.isOfType("party"))),ui.sidebar.render()}}),game.settings.register("pf2e","campaignFeats",{name:"PF2E.SETTINGS.CampaignFeats.Name",hint:"PF2E.SETTINGS.CampaignFeats.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:()=>resetActors()}),game.settings.register("pf2e","campaignFeatSections",{name:"Campaign Feat Sections",scope:"world",config:!1,default:[],type:Array,onChange:()=>resetActors()}),game.settings.register("pf2e","RAI.TreatWoundsAltSkills",{name:"Treat Wounds Macro Compat",scope:"world",config:!1,default:!0,type:Boolean}),game.settings.register("pf2e","gmVision",{name:"PF2E.SETTINGS.GMVision",scope:"client",config:!1,default:!1,type:Boolean,onChange:value=>{const color=value?CONFIG.PF2E.Canvas.darkness.gmVision:CONFIG.PF2E.Canvas.darkness.default;CONFIG.Canvas.darknessColor=color,canvas.colorManager.initialize()}}),game.settings.register("pf2e","seenLastStopMessage",{name:"Seen Last Stop Before Remaster Message",scope:"world",config:!1,type:Boolean,default:!1}),registerTrackingSettings(),registerWorldSchemaVersion()}__name(registerSettings,"registerSettings"),__name2(registerSettings,"registerSettings");function registerTrackingSettings(){game.settings.register("pf2e","createdFirstParty",{name:"Created First Party",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("pf2e","activeParty",{name:"Active Party",scope:"world",config:!1,type:String,default:"",onChange:()=>{ui.actors.render(!0)}}),game.settings.register("pf2e","activePartyFolderState",{name:"Active Party Opened or closed",scope:"client",config:!1,type:Boolean,default:!0}),game.settings.register("pf2e","worldSystemVersion",{name:"World System Version",scope:"world",config:!1,default:game.system.version,type:String}),game.settings.register("pf2e","seenRemasterJournalEntry",{name:"Seen Remaster journal entry?",scope:"world",config:!1,default:!1,type:Boolean})}__name(registerTrackingSettings,"registerTrackingSettings"),__name2(registerTrackingSettings,"registerTrackingSettings");function registerWorldSchemaVersion(){game.settings.register("pf2e","worldSchemaVersion",{name:"PF2E.SETTINGS.WorldSchemaVersion.Name",hint:"PF2E.SETTINGS.WorldSchemaVersion.Hint",scope:"world",config:!0,default:MigrationRunner.LATEST_SCHEMA_VERSION,type:Number,requiresReload:!0})}__name(registerWorldSchemaVersion,"registerWorldSchemaVersion"),__name2(registerWorldSchemaVersion,"registerWorldSchemaVersion");const Init={listen:()=>{Hooks.once("init",()=>{if(console.log("PF2e System | Initializing Pathfinder 2nd Edition System"),CONFIG.PF2E=PF2ECONFIG,CONFIG.debug.ruleElement??=!1,CONFIG.AmbientLight.layerClass=LightingLayerPF2e,CONFIG.AmbientLight.objectClass=AmbientLightPF2e,CONFIG.MeasuredTemplate.objectClass=MeasuredTemplatePF2e,CONFIG.MeasuredTemplate.layerClass=TemplateLayerPF2e,CONFIG.MeasuredTemplate.defaults.angle=90,CONFIG.MeasuredTemplate.defaults.width=1,CONFIG.Token.objectClass=TokenPF2e,CONFIG.Token.layerClass=TokenLayerPF2e,CONFIG.Canvas.groups.effects.groupClass=EffectsCanvasGroupPF2e,CONFIG.Canvas.layers.lighting.layerClass=LightingLayerPF2e,CONFIG.Canvas.layers.templates.layerClass=TemplateLayerPF2e,CONFIG.Canvas.layers.tokens.layerClass=TokenLayerPF2e,setPerceptionModes(),CONFIG.time.roundTime=6,CONFIG.Combat.initiative.decimals=0,CONFIG.ui.actors=ActorDirectoryPF2e,CONFIG.ui.items=ItemDirectoryPF2e,CONFIG.ui.combat=EncounterTrackerPF2e,CONFIG.ui.chat=ChatLogPF2e,CONFIG.ui.compendium=CompendiumDirectoryPF2e,CONFIG.ui.hotbar=HotbarPF2e,CONFIG.specialStatusEffects.BLIND="blinded",document.querySelector("#ui-top")!==null){const uiTop=document.querySelector("#ui-top"),template=document.createElement("template");template.setAttribute("id","pf2e-effects-panel"),uiTop?.insertAdjacentElement("afterend",template)}CONFIG.TinyMCE.extended_valid_elements="pf2-action[action|glyph]",CONFIG.TinyMCE.content_css.push("systems/pf2e/styles/pf2e.css"),CONFIG.TinyMCE.style_formats=(CONFIG.TinyMCE.style_formats??[]).concat({title:"PF2E",items:[{title:"Icons 1 2 3 F R",inline:"span",classes:["action-glyph"],wrapper:!0},{title:"Inline Header",block:"h4",classes:"inline-header"},{title:"Info Block",block:"section",classes:"info",wrapper:!0,exact:!0,merge_siblings:!1},{title:"Stat Block",block:"section",classes:"statblock",wrapper:!0,exact:!0,merge_siblings:!1},{title:"Trait",block:"section",classes:"traits",wrapper:!0},{title:"Written Note",block:"p",classes:"message"},{title:"GM Text Block",block:"div",wrapper:!0,attributes:{"data-visibility":"gm"}},{title:"GM Text Inline",inline:"span",attributes:{"data-visibility":"gm"}}]}),CONFIG.TextEditor.enrichers.push({pattern:new RegExp(/@(Check|Localize|Template)\[([^\]]+)\](?:{([^}]+)})?/,"g"),enricher:(match,options)=>game.pf2e.TextEditor.enrichString(match,options)}),CONFIG.TextEditor.enrichers.push({pattern:new RegExp(/@(Damage)\[((?:[^[\]]*|\[[^[\]]*\])*)\](?:{([^}]+)})?/,"g"),enricher:(match,options)=>game.pf2e.TextEditor.enrichString(match,options)}),registerFonts(),registerHandlebarsHelpers(),registerKeybindings(),registerSettings(),registerTemplates(),MystifiedTraits.compile(),SetGamePF2e.onInit();for(const element of htmlQueryAll(document.head,"link[rel=stylesheet]")){const href=element.getAttribute("href");href?.startsWith("modules/")&&href.endsWith("tagify.css")&&element.setAttribute("disabled","")}game.pf2e.StatusEffects.initialize(),new HomebrewElements().onInit()})}},LightingRefresh={listen:()=>{Hooks.on("lightingRefresh",()=>{SceneDarknessAdjuster.instance.onLightingRefresh(canvas.darknessLevel)})}},_ActiveEffectPF2e=class extends ActiveEffect{static{__name(this,"_ActiveEffectPF2e")}constructor(data,context){data.disabled=!0,data.transfer=!1,super(data,context)}static async createDocuments(){return[]}};__name2(_ActiveEffectPF2e,"ActiveEffectPF2e");let ActiveEffectPF2e=_ActiveEffectPF2e;const _ActorsPF2e=class extends Actors{static{__name(this,"_ActorsPF2e")}get party(){const activePartyId=game.settings.get("pf2e","activeParty"),actor=this.get(activePartyId);return actor?.isOfType("party")?actor:this.find(a=>a.isOfType("party"))??null}_getVisibleTreeContents(){return super._getVisibleTreeContents().filter(a=>a.isOfType("creature")&&!a.parties.size||!a.isOfType("party","creature"))}};__name2(_ActorsPF2e,"ActorsPF2e");let ActorsPF2e=_ActorsPF2e;const _ActorDeltaPF2e=class extends ActorDelta{static{__name(this,"_ActorDeltaPF2e")}prepareData(){super.prepareData(),!game.ready&&!this.parent?.isLinked&&this.syntheticActor?.reset()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.system?.traits?.size&&this.parent?.rendered&&this.parent.object?._onUpdate({width:this.parent.width},{...options,parent:this.parent.scene},userId)}_dispatchDescendantDocumentEvents(event,collection,args,parent){super._dispatchDescendantDocumentEvents(event,collection,args,parent);const isPostWriteCallback=["onCreate","onUpdate","onDelete"].includes(event);if(!this.parent||this.parent.isLinked||!this.parent.rendered||!isPostWriteCallback)return;const items=(args[0]??[]).filter(i=>i instanceof ItemPF2e),nameChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenName")),sizeChanged=items.some(i=>i.system.rules.some(r=>r.key==="CreatureSize")),textureChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenImage"))||!!this.syntheticActor?.rules.some(r=>r.key==="TokenImage"),lightChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenLight"));if(nameChanged||sizeChanged||textureChanged||lightChanged){this.parent.reset();const fakeUpdates={};nameChanged&&(fakeUpdates.name=this.parent.name),sizeChanged&&(fakeUpdates.width=this.parent.width),textureChanged&&(fakeUpdates.texture=deepClone(this.parent._source.texture)),lightChanged&&(fakeUpdates.light=deepClone(this.parent._source.light)),this.parent.object?._onUpdate(fakeUpdates,{parent:this.parent.scene},game.user.id)}}};__name2(_ActorDeltaPF2e,"ActorDeltaPF2e");let ActorDeltaPF2e=_ActorDeltaPF2e;function monkeyPatchFoundry(){TextEditor.enrichHTML=TextEditorPF2e.enrichHTML,TextEditor._enrichContentLinks=TextEditorPF2e._enrichContentLinks,TextEditor._createInlineRoll=TextEditorPF2e._createInlineRoll,TextEditor._onClickInlineRoll=TextEditorPF2e._onClickInlineRoll}__name(monkeyPatchFoundry,"monkeyPatchFoundry"),__name2(monkeyPatchFoundry,"monkeyPatchFoundry");const _ClientDatabaseBackendPF2e=class extends ClientDatabaseBackend{static{__name(this,"_ClientDatabaseBackendPF2e")}async _getDocuments(documentClass,context,user){const type=documentClass.documentName;if(!["Actor","Item"].includes(type)||context.pack?.startsWith("pf2e.")||context.options?.index)return super._getDocuments(documentClass,context,user);const request2={action:"get",type,...pick$1(context,["query","options","pack"])},response=await SocketInterface.dispatch("modifyDocument",request2);return Promise.all(response.result.map(async data=>{const document2=documentClass.fromSource(data,{pack:context.pack}),migrations=MigrationList.constructFromVersion(document2.schemaVersion);if(migrations.length>0)try{await MigrationRunner.ensureSchemaVersion(document2,migrations)}catch(error){error instanceof Error&&console.error(error.message)}return document2}))}};__name2(_ClientDatabaseBackendPF2e,"ClientDatabaseBackendPF2e");let ClientDatabaseBackendPF2e=_ClientDatabaseBackendPF2e;const Load={listen(){CONFIG.DatabaseBackend=new ClientDatabaseBackendPF2e,CONFIG.ActiveEffect.documentClass=ActiveEffectPF2e,CONFIG.Actor.collection=ActorsPF2e,CONFIG.Actor.documentClass=ActorProxyPF2e,CONFIG.ActorDelta.documentClass=ActorDeltaPF2e,CONFIG.AmbientLight.documentClass=AmbientLightDocumentPF2e,CONFIG.ChatMessage.documentClass=ChatMessagePF2e,CONFIG.Combat.documentClass=EncounterPF2e,CONFIG.Combatant.documentClass=CombatantPF2e,CONFIG.Item.documentClass=ItemProxyPF2e,CONFIG.Macro.documentClass=MacroPF2e,CONFIG.MeasuredTemplate.documentClass=MeasuredTemplateDocumentPF2e,CONFIG.Scene.documentClass=ScenePF2e,CONFIG.Tile.documentClass=TileDocumentPF2e,CONFIG.Token.documentClass=TokenDocumentPF2e,CONFIG.Token.prototypeSheetClass=TokenConfigPF2e,CONFIG.User.documentClass=UserPF2e,CONFIG.Canvas.darknessColor=2960722,CONFIG.Canvas.exploredColor=2500134,CONFIG.Dice.rolls.push(CheckRoll,StrikeAttackRoll,DamageRoll,DamageInstance);for(const TermCls of[ArithmeticExpression,Grouping,InstancePool,IntermediateDie])CONFIG.Dice.termTypes[TermCls.name]=TermCls;Math.eq=(a,b)=>a===b,Math.gt=(a,b)=>a>b,Math.gte=(a,b)=>a>=b,Math.lt=(a,b)=>aa<=b,Math.ne=(a,b)=>a!==b,Math.ternary=(condition,ifTrue,ifFalse)=>condition?ifTrue:ifFalse,Actor.DEFAULT_ICON="systems/pf2e/icons/default-icons/mystery-man.svg",CONFIG.Actor.typeIcons={familiar:"fa-solid fa-cat",hazard:"fa-solid fa-hill-rockslide",loot:"fa-solid fa-treasure-chest"},CONFIG.Item.typeIcons={action:"fa-solid fa-person-running-fast",affliction:"fa-solid fa-biohazard",armor:"fa-solid fa-shirt-long-sleeve",backpack:"fa-solid fa-sack",book:"fa-solid fa-book",condition:"fa-solid fa-face-zany",consumable:"fa-solid fa-flask-round-potion",deity:"fa-solid fa-hamsa",effect:"fa-solid fa-person-rays",equipment:"fa-solid fa-hat-cowboy",feat:"fa-solid fa-medal",spell:"fa-solid fa-sparkles",treasure:"fa-solid fa-gem",weapon:"fa-solid fa-sword"},window.AutomaticBonusProgression=AutomaticBonusProgression,monkeyPatchFoundry(),document.addEventListener("mouseup",()=>{const element=document.activeElement;element instanceof HTMLButtonElement&&!element.classList.contains("pm-dropdown")&&element.blur()})}};async function createFirstParty(){game.user!==game.users.activeGM||game.settings.get("pf2e","createdFirstParty")||(game.actors.some(a=>a.isOfType("party"))||(await ActorPF2e.create({_id:CONFIG.PF2E.defaultPartyId,type:"party",name:game.i18n.localize("PF2E.Actor.Party.DefaultName")},{keepId:!0}),await game.settings.set("pf2e","activeParty",CONFIG.PF2E.defaultPartyId)),await game.settings.set("pf2e","createdFirstParty",!0))}__name(createFirstParty,"createFirstParty"),__name2(createFirstParty,"createFirstParty");const _MigrationSummary=class _MigrationSummary2 extends Application{static{__name(this,"_MigrationSummary")}constructor(options={}){super(options),__privateAdd(this,_isRemigrating,!1),this.options.troubleshoot??=!1,this.options.title=options.troubleshoot?game.i18n.localize("PF2E.Migrations.Summary.Troubleshoot.Title"):game.i18n.localize("PF2E.Migrations.Summary.Title");const existing=Object.values(ui.windows).find(app=>app instanceof _MigrationSummary2);if(existing)return existing.options=mergeObject(existing.options,options),existing}static get defaultOptions(){return{...super.defaultOptions,id:"migration-summary",width:400,height:"auto",template:"systems/pf2e/templates/system/migration-summary.hbs"}}async getData(){const latestSchemaVersion=MigrationRunner.LATEST_SCHEMA_VERSION,actors={successful:game.actors.filter(actor=>actor.schemaVersion===latestSchemaVersion).length,total:game.actors.size},items={successful:game.items.filter(item=>item.schemaVersion===latestSchemaVersion).length,total:game.items.size},canRemigrate=this.options.troubleshoot||actors.successful{const{LATEST_SCHEMA_VERSION,RECOMMENDED_SAFE_VERSION}=MigrationRunner,lowestVersions={actor:game.actors.size>0?Math.min(...game.actors.map(a=>a.schemaVersion??0)):LATEST_SCHEMA_VERSION,item:game.items.size>0?Math.min(...game.items.map(a=>a.schemaVersion??0)):LATEST_SCHEMA_VERSION},lowestSchemaVersion=Math.max(Math.min(lowestVersions.actor,lowestVersions.item),RECOMMENDED_SAFE_VERSION),result=html.querySelector(".docs-successful");result&&(result.textContent="...");try{__privateSet(this,_isRemigrating,!0),this.options.troubleshoot=!1,remigrateButton.disabled=!0,await game.pf2e.system.remigrate({from:lowestSchemaVersion}),this.options.troubleshoot=!1,this.render(!1)}catch{return}}),html.querySelector("button[data-action=close]")?.addEventListener("click",()=>{this.close()})}};_isRemigrating=new WeakMap,__name2(_MigrationSummary,"MigrationSummary");let MigrationSummary=_MigrationSummary;function activateSocketListener(){game.socket.on("system.pf2e",async(...[message,userId])=>{const sender=game.users.get(userId,{strict:!0});switch(message.request){case"itemTransfer":if(game.user.isGM){console.debug(`PF2e System | Received item-transfer request from ${sender.name}`);const{data}=message;new ItemTransfer(data.source,data.target,data.quantity,data.containerId).enact(sender)}break;case"refreshSceneControls":!game.user.isGM&&message.data.layer===ui.controls.control?.layer&&(console.debug("PF2e System | Refreshing Scene Controls"),ui.controls.initialize({layer:message.data.layer}));break;case"showSheet":{const document2=await fromUuid(message.document);if(!sender.isGM||!document2)return;const{tab,campaign}=message.options??{};if(campaign){if(!(document2 instanceof PartyPF2e))return;const type=campaign===!0?null:campaign;return document2.campaign?.renderSheet?.({tab,type})}document2.sheet.render(!0,{tab});break}default:throw ErrorPF2e(`Received unrecognized socket emission: ${message.request}`)}})}__name(activateSocketListener,"activateSocketListener"),__name2(activateSocketListener,"activateSocketListener");async function storeInitialWorldVersions(){if(!game.user.hasRole(CONST.USER_ROLES.GAMEMASTER))return;if(game.settings.storage.get("world").getItem("pf2e.worldSystemVersion")||await game.settings.set("pf2e","worldSystemVersion",game.system.version),!game.settings.storage.get("world").getItem("pf2e.worldSchemaVersion")){const minimumVersion=MigrationRunner.RECOMMENDED_SAFE_VERSION,currentVersion=game.actors.size===0?game.settings.get("pf2e","worldSchemaVersion"):Math.max(Math.min(...new Set(game.actors.map(actor=>actor.schemaVersion??minimumVersion))),minimumVersion);await game.settings.set("pf2e","worldSchemaVersion",currentVersion)}}__name(storeInitialWorldVersions,"storeInitialWorldVersions"),__name2(storeInitialWorldVersions,"storeInitialWorldVersions");function extendDragData(){document.body.addEventListener("dragstart",event=>{const{dataTransfer,target}=event;if(dataTransfer&&target instanceof HTMLAnchorElement){if(target.classList.contains("content-link")){const data=JSON.parse(dataTransfer.getData("text/plain"));if(data.type!=="Item")return;const match=target.innerText.trim().match(/[0-9]+/);match&&(data.value=Number(match[0]));const containerElement=htmlClosest(target,"[data-cast-level]"),castLevel=Number(containerElement?.dataset.castLevel);castLevel>0&&(data.level=castLevel);const messageId=htmlClosest(target,"li.chat-message")?.dataset.messageId,message=game.messages.get(messageId??""),originItem=message?.item;if(message?.actor){const{actor,token,target:target2}=message,roll=message.rolls.at(-1),spellcasting=originItem?.isOfType("spell")&&originItem.spellcasting?{attribute:{type:originItem.attribute,mod:originItem.spellcasting.statistic?.attributeModifier?.value??0},tradition:originItem.spellcasting.tradition}:null;data.context={origin:{actor:actor.uuid,token:token?.uuid??null,item:originItem?.uuid??null,spellcasting},target:target2?{actor:target2.actor.uuid,token:target2.token.uuid}:null,roll:roll?{total:roll.total,degreeOfSuccess:roll instanceof CheckRoll?roll.degreeOfSuccess??null:null}:null}}dataTransfer.setData("text/plain",JSON.stringify(data))}else if("persistent"in target.dataset&&target.dataset.formula){const data={type:"PersistentDamage",formula:target.dataset.formula};dataTransfer.setData("text/plain",JSON.stringify(data))}}})}__name(extendDragData,"extendDragData"),__name2(extendDragData,"extendDragData");const Ready={listen:()=>{Hooks.once("ready",()=>{console.log("PF2e System | Starting Pathfinder 2nd Edition System"),console.debug("PF2e System | Build mode: production"),SetGamePF2e.onReady(),game.scenes.apps.push(SceneDarknessAdjuster.instance);const currentVersion=game.settings.get("pf2e","worldSchemaVersion");storeInitialWorldVersions().then(async()=>{if(game.user!==game.users.activeGM)return;await createFirstParty();const migrationRunner=new MigrationRunner(MigrationList.constructFromVersion(currentVersion));migrationRunner.needsMigration()&&(currentVersion&¤tVersionm.active&&(m.esmodules.size>0||m.scripts.size>0)&&!!m.compatibility.verified&&(abandonedModules.has(m.id)||!foundry.utils.isNewerVersion(m.compatibility.verified,"9.280")));for(const badModule of subV10Modules){const message=game.i18n.format("PF2E.ErrorMessage.SubV9Module",{module:badModule.title});ui.notifications.warn(message),console.warn(message)}});for(const li of htmlQueryAll(document.body,"#chat-log > li.message"))SetAsInitiative.listen(li);activateSocketListener(),extendDragData(),canvas.ready&&game.user.isGM&&!game.modules.get("gm-vision")?.active&&!game.modules.get("perfect-vision")?.active&&game.settings.get("pf2e","gmVision")&&(CONFIG.Canvas.darknessColor=CONFIG.PF2E.Canvas.darkness.gmVision,canvas.colorManager.initialize()),game.system.documentTypes.Item.sort((typeA,typeB)=>game.i18n.localize(CONFIG.Item.typeLabels[typeA]??"").localeCompare(game.i18n.localize(CONFIG.Item.typeLabels[typeB]??""))),game.pf2e.system.moduleArt.refresh().then(()=>{ui.compendium.compileSearchIndex()});const actorsToReprepare=compact([...game.combats.contents.flatMap(e=>e.combatants.contents).map(c=>c.actor),...game.actors.filter(a=>a.isOfType("party")).flatMap(p=>p.members).filter(a=>!a.isOfType("familiar")),...game.actors.filter(a=>a.type==="familiar")]);if(resetActors(new Set(actorsToReprepare)),game.user.isGM&&!game.settings.get("pf2e","seenRemasterJournalEntry")&&(fromUuid("Compendium.pf2e.journals.JournalEntry.6L2eweJuM8W7OCf2").then(entry=>{entry?.sheet.render(!0)}),game.settings.set("pf2e","seenRemasterJournalEntry",!0)),game.combat){for(const encounter of game.combats)encounter.reset();ui.combat.render()}Hooks.callAll("pf2e.systemReady")})}},RenderChatPopout={listen:()=>{Hooks.on("renderChatPopout",(_app,$html)=>{ui.chat.activateClickListener($html[0])})}},RenderCombatTrackerConfig={listen:()=>{Hooks.on("renderCombatTrackerConfig",async(app,$html)=>{const html=$html[0],appWindow=htmlClosest(html,"#combat-config");appWindow&&(appWindow.style.height="");const template=await(async()=>{const markup=await renderTemplate("systems/pf2e/templates/sidebar/encounter-tracker/config.hbs",{values:{deathIcon:game.settings.get("pf2e","deathIcon"),actorsDeadAtZero:game.settings.get("pf2e","automation.actorsDeadAtZero")}}),tempElem=document.createElement("div");return tempElem.innerHTML=markup,tempElem.firstElementChild instanceof HTMLTemplateElement?tempElem.firstElementChild:null})();htmlQueryAll(html,".form-group").at(-1)?.after(...template?.content.children??[]),app.activateListeners($html)})}},PC_ITEM_TYPES=new Set(["ancestry","background","class","deity","feat","heritage"]),RenderDialog={listen:()=>{Hooks.on("renderDialog",(_dialog,$html)=>{const html=$html[0];if(InlineRollLinks.listen(html),html.classList.contains("dialog-item-create")){const select=html.querySelector("select[name=type]"),localize=localizer("PF2E.Item.CreationDialog.Categories");select&&(select.append(extractOptGroup(select,localize("Physical"),[...PHYSICAL_ITEM_TYPES,"kit"])),select.append(extractOptGroup(select,localize("Character"),Array.from(PC_ITEM_TYPES))),select.append(extractOptGroup(select,localize("Other"))),select.querySelector("option").selected=!0)}})}};function extractOptGroup(select,label,types){const filtered=[...select.querySelectorAll(":scope > option").values()].filter(option=>!types||types.includes(option.value)),optgroup=document.createElement("optgroup");optgroup.label=label;for(const physicalElement of filtered)optgroup.appendChild(physicalElement);return optgroup}__name(extractOptGroup,"extractOptGroup"),__name2(extractOptGroup,"extractOptGroup");const RenderJournalPageSheet={listen:()=>{Hooks.on("renderJournalPageSheet",(sheet,$html)=>{const pageEl=$html.get(0)?.closest(".journal-entry-page"),parentSheetClass=sheet.object.parent?.sheet.constructor;if(!parentSheetClass||!pageEl)return;const theme=parentSheetClass.theme?String(parentSheetClass.theme):null;theme&&pageEl.classList.add(theme)})}},RenderJournalTextPageSheet={listen:()=>{Hooks.on("renderJournalTextPageSheet",(sheet,$html)=>{const content=$html.filter(".journal-page-content").get(0);content&&(InlineRollLinks.listen(content,sheet.document),UserVisibilityPF2e.process(content,sheet))})}},RenderSettings={listen:()=>{Hooks.on("renderSettings",async(_app,$html)=>{const html=$html[0],systemRow=html.querySelector(".settings-sidebar li.system"),systemInfo=systemRow?.cloneNode(!1);if(!(systemInfo instanceof HTMLLIElement))throw ErrorPF2e("Unexpected error attaching system information to settings sidebar");systemInfo.classList.remove("system"),systemInfo.classList.add("system-links");const links=[{url:"https://github.com/foundryvtt/pf2e/blob/release/CHANGELOG.md",label:"PF2E.SETTINGS.Sidebar.Changelog"},{url:"https://github.com/foundryvtt/pf2e/wiki",label:"PF2E.SETTINGS.Sidebar.Wiki"},{url:"https://discord.gg/SajryVzCyf",label:"PF2E.SETTINGS.Sidebar.Discord"}].map(data=>{const anchor=document.createElement("a");return anchor.href=data.url,anchor.innerText=game.i18n.localize(data.label),anchor.target="_blank",anchor});systemInfo.append(...links),systemRow?.after(systemInfo);const header=createHTMLElement("h2",{children:[game.system.title]}),pf2eSettings=createHTMLElement("div");html.querySelector("#settings-documentation")?.after(header,pf2eSettings);const licenseButton=document.createElement("button");licenseButton.type="button",licenseButton.append(fontAwesomeIcon("balance-scale"),game.i18n.localize("PF2E.LicenseViewer.Label")),licenseButton.addEventListener("click",()=>{game.pf2e.licenseViewer.render(!0)});const remasterButton=document.createElement("button");if(remasterButton.type="button",remasterButton.append(fontAwesomeIcon("rocket"),game.i18n.localize("PF2E.SETTINGS.Sidebar.Remaster")),remasterButton.addEventListener("click",()=>{fromUuid("Compendium.pf2e.journals.JournalEntry.6L2eweJuM8W7OCf2").then(entry=>{entry?.sheet.render(!0)})}),pf2eSettings.append(licenseButton,remasterButton),game.user.isGM){const shootButton=document.createElement("button");shootButton.type="button",shootButton.append(fontAwesomeIcon("wrench"),game.i18n.localize("PF2E.Migrations.Troubleshooting")),shootButton.addEventListener("click",()=>{new MigrationSummary({troubleshoot:!0}).render(!0)}),pf2eSettings.append(shootButton)}})}},_PartyClownCar=class{static{__name(this,"_PartyClownCar")}constructor(token){if(__privateAdd(this,_retrieve),__privateAdd(this,_deposit),__privateAdd(this,_getDepositSpaces),__publicField(this,"party"),__publicField(this,"token"),this.token=token,!this.token.scene.isOwner)throw ErrorPF2e("Cannot write to scene");const party=token.actor;if(!party?.isOfType("party"))throw ErrorPF2e("Unexpected actor type");this.party=party}get scene(){return this.token.scene}get memberTokens(){return this.party.members.flatMap(m=>m.getActiveTokens(!0,!0))}toggleState(){return this.memberTokens.length>0?__privateMethod(this,_retrieve,retrieve_fn).call(this):__privateMethod(this,_deposit,deposit_fn).call(this)}};_retrieve=new WeakSet,retrieve_fn=__name2(async function(){const tokens=this.memberTokens,updates=tokens.map(t=>({_id:t.id,...pick$1(this.token,["x","y"])})),animation={spin:!0};await this.scene.updateEmbeddedDocuments("Token",updates,{animation}),await Promise.all(tokens.map(async token=>(await token.object?._animation,token.delete())))},"#retrieve"),_deposit=new WeakSet,deposit_fn=__name2(async function(){const{token}=this;if(!token.object)return;const newTokens=(await Promise.all(this.party.members.map(m=>m.getTokenDocument({x:token.x,y:token.y})))).map(t=>({...t.toObject(),x:token.x,y:token.y})),createdTokens=await this.scene.createEmbeddedDocuments("Token",newTokens),freeSpaces=__privateMethod(this,_getDepositSpaces,getDepositSpaces_fn).call(this),placementData=createdTokens.map((t,index)=>({_id:t._id,...pick$1(freeSpaces.at(index)??token,["x","y"])}));await this.scene.updateEmbeddedDocuments("Token",placementData)},"#deposit"),_getDepositSpaces=new WeakSet,getDepositSpaces_fn=__name2(function(){const placeable=this.token.object;if(!placeable)return[];const{center}=placeable,diameter=placeable.bounds.width*7,radiusPixels=diameter/2,radius=radiusPixels/(canvas.dimensions?.distance??5),areaBounds=new PIXI.Rectangle(center.x-radiusPixels,center.y-radiusPixels,diameter,diameter),squares=getAreaSquares({bounds:areaBounds,radius,token:placeable}).filter(s=>s.active);return sortBy$1(squares.filter(s=>!(s.x===placeable.x&&s.y===placeable.y)&&!(s.center.x===center.x&&s.center.y===center.y)&&!placeable.checkCollision(s.center,{type:"move",mode:"any"})).reverse(),s=>canvas.grid.measureDistance(center,s.center))},"#getDepositSpaces"),__name2(_PartyClownCar,"PartyClownCar");let PartyClownCar=_PartyClownCar;const _RenderTokenHUD=class{static{__name(this,"_RenderTokenHUD")}static listen(){Hooks.on("renderTokenHUD",(_app,$html,data)=>{const html=$html[0];game.pf2e.StatusEffects.onRenderTokenHUD(html,data);const token=canvas.scene?.tokens.get(data._id??"")?.object;this.addClownCarButton(html,token)})}static addClownCarButton(html,token){if(!token?.actor?.isOfType("party"))return;const{actor}=token,actionIcon=(()=>{const imgElement=document.createElement("img");imgElement.src="systems/pf2e/icons/other/enter-exit.svg";const willRetrieve=actor.members.some(m=>m.getActiveTokens(!0,!0).length>0);return imgElement.className=willRetrieve?"retrieve":"deposit",imgElement.title=game.i18n.localize(willRetrieve?"PF2E.Actor.Party.ClownCar.Retrieve":"PF2E.Actor.Party.ClownCar.Deposit"),imgElement})(),controlButton=createHTMLElement("div",{classes:["control-icon"],dataset:{action:"clown-car"},children:[actionIcon]});controlButton.addEventListener("click",async()=>{if(!controlButton.dataset.disabled){controlButton.dataset.disabled="true";try{await new PartyClownCar(token.document).toggleState();const switchToDeposit=actionIcon.className==="retrieve";actionIcon.className=switchToDeposit?"deposit":"retrieve",actionIcon.title=game.i18n.localize(switchToDeposit?"PF2E.Actor.Party.ClownCar.Deposit":"PF2E.Actor.Party.ClownCar.Retrieve")}finally{delete controlButton.dataset.disabled}}}),htmlQuery(html,"[data-action=effects]")?.replaceWith(controlButton)}};__name2(_RenderTokenHUD,"RenderTokenHUD");let RenderTokenHUD=_RenderTokenHUD;const _FamiliarSheetPF2e=class extends CreatureSheetPF2e{static{__name(this,"_FamiliarSheetPF2e")}actorConfigClass=null;static get defaultOptions(){const options=super.defaultOptions;return mergeObject(options,{classes:[...options.classes,"familiar"],width:650,height:680,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"attributes"}]}),options}get template(){return"systems/pf2e/templates/actors/familiar-sheet.hbs"}async getData(options){const sheetData=await super.getData(options),familiar=this.actor,masters=game.actors.filter(a=>a.type==="character"&&a.testUserPermission(game.user,"OWNER")),abilities2=CONFIG.PF2E.abilities,size=CONFIG.PF2E.actorSizes[familiar.system.traits.size.value]??null,familiarAbilities=this.actor.master?.attributes?.familiarAbilities;if(sheetData.data.saves)for(const key of["fortitude","reflex","will"]){const save=sheetData.data.saves[key];save.label=CONFIG.PF2E.saves[key]}const skills=Object.values(sheetData.data.skills).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang));return{...sheetData,master:this.actor.master,masters,abilities:abilities2,size,skills,familiarAbilities:{value:familiarAbilities?.value??0,items:sortBy$1(this.actor.itemTypes.action,a=>a.sort)}}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,".rollable[data-action=perception-check]")?.addEventListener("click",event=>{this.actor.perception.roll(eventToRollParams(event,{type:"check"}))}),htmlQuery(html,".rollable[data-attack-roll]")?.addEventListener("click",event=>{this.actor.attackStatistic.roll(eventToRollParams(event,{type:"check"}))})}};__name2(_FamiliarSheetPF2e,"FamiliarSheetPF2e");let FamiliarSheetPF2e=_FamiliarSheetPF2e;const _HazardSheetPF2e=class extends ActorSheetPF2e{static{__name(this,"_HazardSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_prepareActions),__privateAdd(this,_prepareSaves)}static get defaultOptions(){const options=super.defaultOptions;return mergeObject(options,{classes:[...options.classes,"hazard"],scrollY:[".container > section"],width:700,height:680}),options}get template(){return"systems/pf2e/templates/actors/hazard/sheet.hbs"}get title(){return this.editing?game.i18n.format("PF2E.Actor.Hazard.TitleEdit",{name:super.title}):super.title}get editing(){return this.options.editable&&!!this.actor.getFlag("pf2e","editHazard.value")}async getData(options){const sheetData=await super.getData(options);sheetData.actor.flags.editHazard??={value:!1};const systemData=sheetData.data,actor=this.actor,{hasDefenses}=actor,hasImmunities=systemData.attributes.immunities.length>0,hasResistances=systemData.attributes.resistances.length>0,hasWeaknesses=systemData.attributes.weaknesses.length>0,hasIWR=hasDefenses||hasImmunities||hasResistances||hasWeaknesses,stealthMod=actor.system.attributes.stealth.value,stealthDC=typeof stealthMod=="number"?stealthMod+10:null,hasStealthDescription=!!systemData.attributes.stealth?.details,rollData=this.actor.getRollData(),enrich=__name2(async content=>TextEditor.enrichHTML(content??"",{rollData,async:!0}),"enrich");sheetData.enrichedContent=mergeObject(sheetData.enrichedContent,{stealthDetails:await enrich(systemData.attributes.stealth.details),description:await enrich(systemData.details.description),disable:await enrich(systemData.details.disable),routine:await enrich(systemData.details.routine),reset:await enrich(systemData.details.reset)});const strikesWithDescriptions=systemData.actions,actorRollData=actor.getRollData();for(const attack of strikesWithDescriptions){const itemRollData=attack.item.getRollData();attack.description.length>0&&(attack.description=await TextEditor.enrichHTML(attack.description,{rollData:{...actorRollData,...itemRollData},async:!0})),attack.damageFormula=String(await attack.damage?.({getFormula:!0}))}return{...sheetData,actions:__privateMethod(this,_prepareActions,prepareActions_fn).call(this),editing:this.editing,actorTraits:systemData.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.hazardTraits)),rarity:CONFIG.PF2E.rarityTraits,rarityLabel:CONFIG.PF2E.rarityTraits[this.actor.rarity],brokenThreshold:systemData.attributes.hp.brokenThreshold,stealthDC,saves:__privateMethod(this,_prepareSaves,prepareSaves_fn).call(this),hasDefenses,hasHPDetails:!!systemData.attributes.hp.details.trim(),hasSaves:Object.keys(actor.saves??{}).length>0,hasIWR,hasStealth:stealthDC!==null||hasStealthDescription,hasStealthDescription,hasDescription:!!systemData.details.description?.trim(),hasDisable:!!systemData.details.disable?.trim(),hasRoutineDetails:!!systemData.details.routine?.trim(),hasResetDetails:!!systemData.details.reset?.trim()}}activateListeners($html){super.activateListeners($html);const html=$html[0],traitsEl=html.querySelector('input[name="system.traits.value"]');if(traitsEl){const tags=tagify$1(traitsEl,{whitelist:CONFIG.PF2E.hazardTraits}),traitsPrepend=html.querySelector(".traits-extra");traitsPrepend&&tags.DOM.scope.prepend(traitsPrepend.content)}$html.find(".edit-mode-button").on("click",()=>{this.actor.setFlag("pf2e","editHazard.value",!this.editing)}),$html.find("input[data-property]").on("focus",event=>{const $input=$(event.target),propertyPath=$input.attr("data-property")??"",baseValue=Number(getProperty(this.actor._source,propertyPath));$input.val(baseValue).attr({name:propertyPath})}),$html.find("input[data-property]").on("blur",event=>{const $input=$(event.target);$input.removeAttr("name").removeAttr("style").attr({type:"text"});const propertyPath=$input.attr("data-property")??"",valueAttr=$input.attr("data-value");if(valueAttr)$input.val(valueAttr);else{const preparedValue=Number(getProperty(this.actor,propertyPath));$input.val(preparedValue!==null&&preparedValue>=0?`+${preparedValue}`:preparedValue)}}),$html.find("[data-action=edit-section]").on("click",event=>{const name2=$(event.target).closest(".section-container").find("[data-edit]").attr("data-edit");name2&&this.activateEditor(name2)}),this.options.editable&&$html.find(".isHazardEditable").on("change",event=>{this.actor.setFlag("pf2e","editHazard",{value:event.target.checked})})}async _updateObject(event,formData){const emitsSound=formData["system.attributes.emitsSound"];return emitsSound!=="encounter"&&(formData["system.attributes.emitsSound"]=emitsSound==="true"),super._updateObject(event,formData)}};_prepareActions=new WeakSet,prepareActions_fn=__name2(function(){const actions=this.actor.itemTypes.action.sort((a,b)=>a.sort-b.sort);return{reaction:actions.filter(a=>a.actionCost?.type==="reaction"),action:actions.filter(a=>a.actionCost?.type!=="reaction")}},"#prepareActions"),_prepareSaves=new WeakSet,prepareSaves_fn=__name2(function(){if(!this.actor.saves)return[];const results=[];for(const saveType of SAVE_TYPES){const save=this.actor.saves[saveType];(this.editing||save)&&results.push({label:game.i18n.localize(`PF2E.Saves${saveType.titleCase()}Short`),type:saveType,mod:save?.check.mod})}return results},"#prepareSaves"),__name2(_HazardSheetPF2e,"HazardSheetPF2e");let HazardSheetPF2e=_HazardSheetPF2e;const _LootNPCsPopup=class extends FormApplication{static{__name(this,"_LootNPCsPopup")}static get defaultOptions(){const options=super.defaultOptions;return options.id="loot-NPCs",options.classes=[],options.title="Loot NPCs",options.template="systems/pf2e/templates/actors/loot/loot-npcs-popup.hbs",options.width="auto",options}async _updateObject(_event,formData){const lootActor=this.object,newItems=[],itemUpdates=new Map,itemsToDelete=new Map,selectionData=Array.isArray(formData.selection)?formData.selection:[formData.selection];for(let i=0;itoken2.actor&&token2.id===this.form[i]?.id);if(!token)throw ErrorPF2e(`Token ${this.form[i]?.id} not found`);const currentSource=token.actor;if(selectionData[i]&¤tSource){for(const item of currentSource.inventory){const stackableItem=lootActor.inventory.findStackableItem(item);if(stackableItem){const currentQuantity=itemUpdates.get(stackableItem.id)??stackableItem.quantity;itemUpdates.set(stackableItem.id,currentQuantity+item.quantity);continue}newItems.push(item)}itemsToDelete.set(currentSource,currentSource.inventory.map(item=>item.id))}}if(newItems.length>0){const sources=newItems.reduce((result,item)=>{const stackableItem=result.find(i=>i.isStackableWith(item));return stackableItem?(stackableItem.updateSource({system:{quantity:stackableItem.quantity+item.quantity}}),result):(result.push(item),result)},[]).map(i=>i.toObject());await lootActor.createEmbeddedDocuments("Item",sources,{render:itemUpdates.size===0})}if(itemUpdates.size>0){const updates=[...itemUpdates.entries()].map(([id,quantity])=>({_id:id,system:{quantity}}));await lootActor.updateEmbeddedDocuments("Item",updates)}if(itemsToDelete.size>0)for(const[actor,ids]of itemsToDelete)actor.deleteEmbeddedDocuments("Item",ids)}async getData(){const tokenInfo=canvas.tokens.controlled.filter(token=>token.actor&&token.actor.id!==this.object.id).map(token=>({id:token.id,name:token.name,checked:token.actor.hasPlayerOwner}));return{...await super.getData(),tokenInfo}}};__name2(_LootNPCsPopup,"LootNPCsPopup");let LootNPCsPopup=_LootNPCsPopup;const _DistributeCoinsPopup=class extends FormApplication{static{__name(this,"_DistributeCoinsPopup")}constructor(actor,options={}){super(actor,options)}static get defaultOptions(){const options=super.defaultOptions;return options.id="distribute-coins",options.classes=[],options.title="Distribute Coins",options.template="systems/pf2e/templates/actors/distribute-coins.hbs",options.width="auto",options}async getData(options){const sheetData=await super.getData(options),playerActors=(options?.recipients??game.actors.contents).filter(a=>a.hasPlayerOwner&&a.isOfType("character")&&!a.isToken&&!a.system.traits.value.some(t=>["minion","eidolon"].includes(t)));return sheetData.actorInfo=playerActors.map(a=>({id:a.id,name:a.name,checked:game.users.players.some(u=>u.active&&u.character?.id===a.id)})),sheetData}async _updateObject(_event,formData){const thisActor=this.object,selectedActors=formData.actorIds.flatMap(actorId=>{const maybeActor=game.actors.get(actorId);return maybeActor?.isOfType("character")?maybeActor:[]}),playerCount=selectedActors.length;if(playerCount===0)return;const coinShare=new CoinsPF2e;if(formData.breakCoins){const thisActorCopperValue=thisActor.inventory.coins.copperValue,copperToDistribute=Math.trunc(thisActorCopperValue/playerCount);if(copperToDistribute===0){ui.notifications.warn("Nothing to distribute");return}thisActor.inventory.removeCoins({cp:copperToDistribute*playerCount}),coinShare.cp=copperToDistribute%10,coinShare.sp=Math.trunc(copperToDistribute/10)%10,coinShare.gp=Math.trunc(copperToDistribute/100)%10,coinShare.pp=Math.trunc(copperToDistribute/1e3)}else{const thisActorCurrency=thisActor.inventory.coins;if(coinShare.pp=Math.trunc(thisActorCurrency.pp/playerCount),coinShare.cp=Math.trunc(thisActorCurrency.cp/playerCount),coinShare.gp=Math.trunc(thisActorCurrency.gp/playerCount),coinShare.sp=Math.trunc(thisActorCurrency.sp/playerCount),coinShare.pp===0&&coinShare.gp===0&&coinShare.sp===0&&coinShare.cp===0){ui.notifications.warn("Nothing to distribute");return}const coinsToRemove=coinShare.scale(playerCount);thisActor.inventory.removeCoins(coinsToRemove,{byValue:!1})}let message="Distributed ";coinShare.pp!==0&&(message+=`${coinShare.pp} pp `),coinShare.gp!==0&&(message+=`${coinShare.gp} gp `),coinShare.sp!==0&&(message+=`${coinShare.sp} sp `),coinShare.cp!==0&&(message+=`${coinShare.cp} cp `);const each=playerCount>1?"each ":"";message+=`${each}from ${thisActor.name} to `;for(const actor of selectedActors){await actor.inventory.addCoins(coinShare);const index=selectedActors.indexOf(actor);index===0?message+=`${actor.name}`:indexelement instanceof HTMLInputElement&&element.name==="actorIds"&&element.checked?element.value:[]);return options.updateData=mergeObject(options.updateData??{},{actorIds}),super._onSubmit(event,options)}};__name2(_DistributeCoinsPopup,"DistributeCoinsPopup");let DistributeCoinsPopup=_DistributeCoinsPopup;const _LootSheetPF2e=class extends ActorSheetPF2e{static{__name(this,"_LootSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return{...options,editable:!0,classes:[...options.classes,"loot"],width:650,height:680,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"inventory"}]}}get template(){return"systems/pf2e/templates/actors/loot/sheet.hbs"}get isLootSheet(){return!this.actor.isOwner&&this.actor.isLootableBy(game.user)}async getData(){const sheetData=await super.getData(),isLoot=this.actor.system.lootSheetType==="Loot",rollData=this.actor.getRollData();return sheetData.enrichedContent.description=await TextEditor.enrichHTML(sheetData.data.details.description,{rollData,async:!0}),{...sheetData,isLoot}}activateListeners($html){if(super.activateListeners($html),!this.isEditable)return;const html=$html[0];htmlQuery(html,"[data-sidebar-buttons]")?.addEventListener("click",event=>{const button=htmlClosest(event.target,"button[data-action]");button?.dataset.action==="split-coins"?new DistributeCoinsPopup(this.actor).render(!0):button?.dataset.action==="loot-npcs"&&(canvas.tokens.controlled.some(token=>token.actor?.id!==this.actor.id)?new LootNPCsPopup(this.actor).render(!0):ui.notifications.warn("No tokens selected."))})}async _onDropItem(event,itemData){return this.actor.id===itemData.actorId&&!this.actor.testUserPermission(game.user,"OWNER")?[]:super._onDropItem(event,itemData)}};__name2(_LootSheetPF2e,"LootSheetPF2e");let LootSheetPF2e=_LootSheetPF2e;const _NPCSkillsEditor=class extends DocumentSheet{static{__name(this,"_NPCSkillsEditor")}get actor(){return this.object}static get defaultOptions(){return{...super.defaultOptions,classes:["pf2e","npc-skills-editor"],template:"systems/pf2e/templates/actors/npc/skills-editor.hbs",height:"auto",scrollY:[".scroll-container"],sheetConfig:!1,submitOnChange:!1,submitOnClose:!1,width:"400"}}get title(){return game.i18n.format("PF2E.Actor.NPC.SkillsEditor.Title",{actor:this.actor.name})}async getData(options){const allSkills=Object.values(this.actor.system.skills);return{...await super.getData(options),actor:this.actor,trainedSkills:allSkills.filter(s=>s.visible).sort((a,b)=>a.label.localeCompare(b.label)),untrainedSkills:allSkills.filter(s=>!s.visible).sort((a,b)=>a.label.localeCompare(b.label))}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=add-skill]")?.addEventListener("click",async event=>{const slug=htmlQuery(htmlClosest(event.currentTarget,".skill-selector"),"select")?.value;setHasElement(SKILL_LONG_FORMS,slug)&&await this.actor.createEmbeddedDocuments("Item",[{name:slug.titleCase(),type:"lore"}])}),htmlQuery(html,"button[data-action=add-lore]")?.addEventListener("click",async event=>{const loreName=htmlQuery(htmlClosest(event.currentTarget,".lore-skill-creator"),"input")?.value.trim();if(loreName){const data={name:loreName,type:"lore",system:{mod:{value:0}}};await this.actor.createEmbeddedDocuments("Item",[data])}});for(const input of htmlQueryAll(html,"input[data-modifier]"))input.addEventListener("change",async()=>{const modifier=Math.clamped(Math.trunc(Number(input.value)||0),-999,999);if(Number.isInteger(modifier)){const itemId=htmlClosest(input,"[data-item-id]")?.dataset.itemId;await this.actor.items.get(itemId,{strict:!0}).update({"system.mod.value":modifier})}}),input.addEventListener("focus",()=>{input.select()});for(const anchor of htmlQueryAll(html,"a[data-action=edit-skill]"))anchor.addEventListener("click",()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;this.actor.items.get(itemId,{strict:!0}).sheet.render(!0)});for(const anchor of htmlQueryAll(html,"a[data-action=remove-skill]"))anchor.addEventListener("click",async()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;await this.actor.items.get(itemId,{strict:!0}).delete()})}async _render(force,options){const focusedElement=htmlQuery(this.form,"input:focus, select:focus");if(await super._render(force,options),focusedElement){const selector=["input","select"].map(s=>`${s}#${CSS.escape(focusedElement.id)}`).join(","),newInput=htmlQuery(this.form,selector);window.setTimeout(()=>{newInput?.focus()},0)}}};__name2(_NPCSkillsEditor,"NPCSkillsEditor");let NPCSkillsEditor=_NPCSkillsEditor;const _RecallKnowledgePopup=class extends Application{static{__name(this,"_RecallKnowledgePopup")}constructor(options,data){super(options),__privateAdd(this,_padAttempts),__privateAdd(this,_identificationData,void 0),__privateSet(this,_identificationData,data)}static get defaultOptions(){return{...super.defaultOptions,id:"recall-knowledge-breakdown",classes:[],title:game.i18n.localize("PF2E.RecallKnowledge.BreakdownTitle"),template:"systems/pf2e/templates/actors/recall-knowledge.hbs",width:630}}async getData(){const identificationData=__privateGet(this,_identificationData);return{standard:{label:localizeList(identificationData.skills.map(s=>game.i18n.localize(CONFIG.PF2E.skillList[s]))),attempts:__privateMethod(this,_padAttempts,padAttempts_fn).call(this,identificationData.standard.progression)},loreEasy:__privateMethod(this,_padAttempts,padAttempts_fn).call(this,identificationData.lore[0].progression),loreVeryEasy:__privateMethod(this,_padAttempts,padAttempts_fn).call(this,identificationData.lore[1].progression)}}};_identificationData=new WeakMap,_padAttempts=new WeakSet,padAttempts_fn=__name2(function(attempts){return padArray(attempts.map(attempt=>attempt.toString()),6,"-")},"#padAttempts"),__name2(_RecallKnowledgePopup,"RecallKnowledgePopup");let RecallKnowledgePopup=_RecallKnowledgePopup;const _NPCConfig=class extends CreatureConfig{static{__name(this,"_NPCConfig")}async getData(options={}){const lootableOptions={default:`PF2E.Actor.NPC.Configure.Lootable.${game.settings.get("pf2e","automation.lootableNPCs")?"DefaultLootable":"DefaultNotLootable"}`,lootable:"PF2E.Actor.NPC.Configure.Lootable.Lootable",notLootable:"PF2E.Actor.NPC.Configure.Lootable.NotLootable"},lootableSelection=(()=>{const storedSelection=this.actor._source.flags.pf2e?.lootable;return typeof storedSelection=="boolean"?storedSelection?"lootable":"notLootable":"default"})();return{...await super.getData(options),lootable:createSheetOptions(lootableOptions,{value:[lootableSelection]})}}async _updateObject(event,formData){const key="flags.pf2e.lootable",lootable=formData[key];return lootable==="default"?(delete formData[key],formData["flags.pf2e.-=lootable"]=null):formData[key]=lootable==="lootable",super._updateObject(event,formData)}};__name2(_NPCConfig,"NPCConfig");let NPCConfig=_NPCConfig;const _AbstractNPCSheet=class extends CreatureSheetPF2e{static{__name(this,"_AbstractNPCSheet")}constructor(){super(...arguments),__privateAdd(this,_prepareAbilities2),__privateAdd(this,_prepareAlignment),__privateAdd(this,_prepareSkills2),__privateAdd(this,_prepareSaves2),__privateAdd(this,_onClickRollable),__privateAdd(this,_rollAbility),__publicField(this,"actorConfigClass",NPCConfig)}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"pf2e","npc","simple"],scrollY:[".sidebar",".inventory-list"]}}async prepareItems(sheetData){__privateMethod(this,_prepareAbilities2,prepareAbilities_fn2).call(this,sheetData.data.abilities),__privateMethod(this,_prepareAlignment,prepareAlignment_fn).call(this,sheetData.data),__privateMethod(this,_prepareSkills2,prepareSkills_fn2).call(this,sheetData.data),__privateMethod(this,_prepareSaves2,prepareSaves_fn2).call(this,sheetData.data)}async getData(options){const sheetData=await super.getData(options),alignmentTraits2=ALIGNMENT_TRAITS,actorTraits=sheetData.data.traits;actorTraits.value=actorTraits.value.filter(t=>!alignmentTraits2.has(t));const rollData=this.actor.getRollData();return sheetData.enrichedContent.publicNotes=await TextEditor.enrichHTML(sheetData.data.details.publicNotes,{rollData,async:!0}),sheetData.enrichedContent.privateNotes=await TextEditor.enrichHTML(sheetData.data.details.privateNotes,{rollData,async:!0}),sheetData.traitTagifyData=createTagifyTraits(this.actor.system.traits.value,{sourceTraits:this.actor._source.system.traits.value,record:CONFIG.PF2E.creatureTraits}),sheetData}_canUserView(user){return super._canUserView(user)||this.isLootSheet}activateListeners($html){super.activateListeners($html);const html=$html[0],traitsEl=htmlQuery(html,'input[name="system.traits.value"]');tagify$1(traitsEl,{whitelist:CONFIG.PF2E.creatureTraits});const rollables=["a.rollable",".item-icon.rollable"].join(", ");for(const rollable of htmlQueryAll(html,rollables))rollable.addEventListener("click",event=>{__privateMethod(this,_onClickRollable,onClickRollable_fn).call(this,rollable,event)});this.isEditable&&htmlQuery(html,".skills-edit")?.addEventListener("click",()=>{new NPCSkillsEditor(this.actor).render(!0)})}};_prepareAbilities2=new WeakSet,prepareAbilities_fn2=__name2(function(attributes){for(const key of ATTRIBUTE_ABBREVIATIONS){const data=attributes[key],localizedCode=game.i18n.localize(`PF2E.AbilityId.${key}`),nameKey=CONFIG.PF2E.abilities[key],localizedName=game.i18n.localize(nameKey);data.localizedCode=localizedCode,data.localizedName=localizedName}},"#prepareAbilities"),_prepareAlignment=new WeakSet,prepareAlignment_fn=__name2(function(sheetSystemData){const alignmentCode=sheetSystemData.details.alignment.value,localizedName=game.i18n.localize(`PF2E.Alignment${alignmentCode}`);sheetSystemData.details.alignment.localizedName=localizedName},"#prepareAlignment"),_prepareSkills2=new WeakSet,prepareSkills_fn2=__name2(function(sheetSystemData){const sortedSkillsIds=Object.keys(sheetSystemData.skills),skills=sheetSystemData.skills;for(const shortForm of sortedSkillsIds){const skill=skills[shortForm];skill.adjustedHigher=skill.value>Number(skill.base),skill.adjustedLower=skill.value{const skillA=skills[a],skillB=skills[b];return skillA.labelskillB.label?1:0});const sortedSkills={};for(const skillId of sortedSkillsIds)sortedSkills[skillId]=skills[skillId];sheetSystemData.sortedSkills=sortedSkills},"#prepareSkills"),_prepareSaves2=new WeakSet,prepareSaves_fn2=__name2(function(systemData){for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType];save.labelShort=game.i18n.localize(`PF2E.Saves${saveType.titleCase()}Short`),save.adjustedHigher=save.totalModifier>Number(save.base),save.adjustedLower=save.totalModifiero.trim()).filter(o=>!!o),key=objectHasKey(SKILL_DICTIONARY,skill)?SKILL_DICTIONARY[skill]:skill;await this.actor.skills[key]?.check.roll({...rollParams,extraRollOptions})}else objectHasKey(this.actor.saves,save)&&await this.actor.saves[save].check.roll(rollParams)},"#onClickRollable"),_rollAbility=new WeakSet,rollAbility_fn=__name2(async function(event,abilityId){const bonus=this.actor.system.abilities[abilityId].mod,parts=["@bonus"],title=game.i18n.localize(`PF2E.AbilityCheck.${abilityId}`),data={bonus},speaker=ChatMessage.getSpeaker({token:this.token,actor:this.actor});await DicePF2e.d20Roll({event,parts,data,title,speaker})},"#rollAbility"),__name2(_AbstractNPCSheet,"AbstractNPCSheet");let AbstractNPCSheet=_AbstractNPCSheet;const _NPCSheetPF2e=class extends AbstractNPCSheet{static{__name(this,"_NPCSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_prepareActions2),__privateAdd(this,_onChangeSpellcastingEntry)}static get defaultOptions(){const options=super.defaultOptions;return{...options,width:650,height:680,tabs:[{navSelector:".sheet-tabs",contentSelector:".sheet-body",initial:"main"}],scrollY:[...options.scrollY,".tab.main",".tab.inventory",".tab.spells",".tab.effects",".tab.notes"]}}get template(){return this.isLootSheet?"systems/pf2e/templates/actors/npc/loot-sheet.hbs":this.actor.limited?"systems/pf2e/templates/actors/limited/npc-sheet.hbs":"systems/pf2e/templates/actors/npc/sheet.hbs"}get title(){if(this.isLootSheet||this.actor.limited){const actorName=!game.settings.get("pf2e","metagame_tokenSetsNameVisibility")||!this.token||this.token.playersCanSeeName?this.token?.name??this.actor.name:"";return this.actor.isDead?`${actorName} [${game.i18n.localize("PF2E.NPC.Dead")}]`:actorName}return super.title}get isLootSheet(){return this.actor.isLootable&&!this.actor.isOwner&&this.actor.isLootableBy(game.user)}async getData(options){const sheetData=await super.getData(options);(this.actor.limited||this.isLootSheet)&&(sheetData.actor.name=this.actor.token?.name??sheetData.actor.name);const alignmentTraits2=ALIGNMENT_TRAITS,actorTraits=sheetData.data.traits;actorTraits.value=actorTraits.value.filter(t=>!alignmentTraits2.has(t)),sheetData.identificationDCs=(()=>{const data=this.actor.identificationDCs,skills=data.skills.length>0?localizeList(data.skills.map(s=>game.i18n.localize(CONFIG.PF2E.skillList[s]))):null;return{standard:skills?game.i18n.format("PF2E.Actor.NPC.Identification.Skills.Label",{skills,dc:data.standard.dc,adjustment:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.standard.start])}):null,lore:game.i18n.format("PF2E.Actor.NPC.Identification.Lore.Label",{dc1:data.lore[0].dc,adjustment1:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.lore[0].start]),dc2:data.lore[1].dc,adjustment2:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.lore[1].start])})}})();const{heldShield}=this.actor,actorShieldData=sheetData.data.attributes.shield;sheetData.hasShield=!!heldShield||actorShieldData.hp.max>0;const isElite=this.actor.isElite,isWeak=this.actor.isWeak;sheetData.isElite=isElite,sheetData.isWeak=isWeak,sheetData.notAdjusted=!isElite&&!isWeak,isElite?(sheetData.eliteState="active",sheetData.weakState="inactive"):isWeak?(sheetData.eliteState="inactive",sheetData.weakState="active"):(sheetData.eliteState="inactive",sheetData.weakState="inactive"),this.isLootSheet&&(sheetData.actor.name=this.token?.name??this.actor.name);const{level}=sheetData.data.details;level.adjustedHigher=level.value>Number(level.base),level.adjustedLower=level.valuesourceAttributes.ac.value,ac.adjustedLower=ac.valuesourceAttributes.hp.max,hp.adjustedLower=hp.maxsourceAttributes.perception.value,perception.adjustedLower=perception.totalModifierspeedData.value,adjustedLower:speedData.totalt!=="land").reduce((speeds,type)=>{const speed=speedData.otherSpeeds.find(s=>s.type===type);return{...speeds,[type]:speed?{label:speed.label,value:speed.total,adjustedHigher:typeof speed.total=="number"&&speed.total>speed.value,adjustedLower:typeof speed.total=="number"&&speed.total0,sheetData.configLootableNpc=game.settings.get("pf2e","automation.lootableNPCs"),sheetData.languageDetails=this.actor.system.traits.languages.custom.trim(),sheetData}async prepareItems(sheetData){super.prepareItems(sheetData),await __privateMethod(this,_prepareActions2,prepareActions_fn2).call(this,sheetData),sheetData.spellcastingEntries=await this.prepareSpellcasting()}async prepareSpellcasting(){const entries=await super.prepareSpellcasting();for(const entry of entries){const entryItem=this.actor.items.get(entry.id);entryItem?.isOfType("spellcastingEntry")&&(entry.adjustedHigher=entry.statistic?{dc:entry.statistic.dc.value>entryItem._source.system.spelldc.dc,mod:entry.statistic.check.mod>entryItem._source.system.spelldc.value}:{dc:!1,mod:!1},entry.adjustedLower=entry.statistic?{dc:entry.statistic.dc.value{new RecallKnowledgePopup({},this.actor.identificationDCs).render(!0)}),!this.isEditable)return;for(const anchor of htmlQueryAll(html,"a[data-adjustment]"))anchor.addEventListener("click",()=>{const adjustment=anchor.dataset.adjustment;if(adjustment==="elite"||adjustment==="weak"){const alreadyHasAdjustment=adjustment===this.actor.system.attributes.adjustment;this.actor.applyAdjustment(alreadyHasAdjustment?null:adjustment)}});const selector=[".attack-input",".dc-input",".key-attribute select"].map(s=>`.spellcasting-entry ${s}`).join(", ");for(const element of htmlQueryAll(html,selector))element.addEventListener("change",event=>__privateMethod(this,_onChangeSpellcastingEntry,onChangeSpellcastingEntry_fn).call(this,element,event));for(const anchor of htmlQueryAll(html,"a[data-action=generate-attack]"))anchor.addEventListener("click",async()=>{const{actor}=this,itemId=htmlClosest(anchor,".item")?.dataset.itemId??"",item=actor.items.get(itemId,{strict:!0});if(!item.isOfType("weapon"))return;const existing=actor.itemTypes.melee.filter(m=>m.flags.pf2e.linkedWeapon===itemId).map(m=>m.id);if(existing.length>0)if(await Dialog.confirm({title:game.i18n.localize("PF2E.Actor.NPC.GenerateAttack.Confirm.Title"),content:game.i18n.localize("PF2E.Actor.NPC.GenerateAttack.Confirm.Content"),defaultYes:!1}))await actor.deleteEmbeddedDocuments("Item",existing,{render:!1});else return;const attacks=item.toNPCAttacks().map(a=>a.toObject());await actor.createEmbeddedDocuments("Item",attacks),ui.notifications.info(game.i18n.format("PF2E.Actor.NPC.GenerateAttack.Notification",{attack:attacks.at(0)?.name??""}))})}async _updateObject(event,formData){if(this.actor.isElite||this.actor.isWeak){const{max}=this.actor.system.attributes.hp;formData["system.attributes.hp.max"]===max&&delete formData["system.attributes.hp.max"]}const shield=this.actor.heldShield;return shield&&Number.isInteger(formData["system.attributes.shield.value"])&&await shield.update({"system.hp.value":formData["system.attributes.shield.value"]}),super._updateObject(event,formData)}};_prepareActions2=new WeakSet,prepareActions_fn2=__name2(async function(sheetData){const attacks=sheetData.data.actions,actorRollData=this.actor.getRollData();for(const attack of attacks){if(attack.description.length>0){const itemRollData=attack.item.getRollData();attack.description=await TextEditor.enrichHTML(attack.description,{rollData:{...actorRollData,...itemRollData},async:!0})}attack.damageFormula=String(await attack.damage?.({getFormula:!0}))}const actions={passive:{label:game.i18n.localize("PF2E.ActionTypePassive"),actions:[]},active:{label:game.i18n.localize("PF2E.ActionTypeAction"),actions:[]}},baseOrder=["free","reaction","action"],abilities2=sortBy$1(this.actor.itemTypes.action,a=>a.sort,a=>baseOrder.indexOf(a.actionCost?.type??"action"));for(const item of abilities2){const itemData=item.toObject(!1),chatData=await item.getChatData(),traits=chatData.traits??[],actionGroup=item.actionCost?"active":"passive",hasAura=actionGroup==="passive"&&(item.system.traits.value.includes("aura")||!!item.system.rules.find(r=>r.key==="Aura"));actions[actionGroup].actions.push({...itemData,glyph:getActionGlyph(item.actionCost),imageUrl:getActionIcon(item.actionCost),chatData,traits,hasAura})}sheetData.actions=actions},"#prepareActions"),_onChangeSpellcastingEntry=new WeakSet,onChangeSpellcastingEntry_fn=__name2(async function(element,event){event.preventDefault();const itemId=htmlClosest(element,".spellcasting-entry")?.dataset.containerId??"",key=element.dataset.baseProperty?.replace(/data\.items\.\d+\./,"")??"",value=element.classList.contains("focus-points")||element.classList.contains("focus-pool")?Math.min(Number(element.value)||0,3):element.nodeName==="SELECT"?element.value:Number(element.value)||0;await this.actor.updateEmbeddedDocuments("Item",[{_id:itemId,[key]:value}])},"#onChangeSpellcastingEntry"),__name2(_NPCSheetPF2e,"NPCSheetPF2e");let NPCSheetPF2e=_NPCSheetPF2e;const _SimpleNPCSheet=class extends AbstractNPCSheet{static{__name(this,"_SimpleNPCSheet")}static get defaultOptions(){return{...super.defaultOptions,width:650,height:420,scrollY:[".sheet-body"],template:"systems/pf2e/templates/actors/npc/simple-sheet.hbs"}}};__name2(_SimpleNPCSheet,"SimpleNPCSheet");let SimpleNPCSheet=_SimpleNPCSheet;const _PartySheetPF2e=class extends ActorSheetPF2e{static{__name(this,"_PartySheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_prepareMembers),__privateAdd(this,_prepareOverviewSummary),__privateAdd(this,_getActorsThatUnderstand),__privateAdd(this,_renderRegions),__publicField(this,"currentSummaryView","languages"),__publicField(this,"regionTemplates",{overview:"overview.hbs",inventoryMembers:"inventory-members.hbs",exploration:"exploration.hbs",explorationSidebar:"exploration-sidebar.hbs"})}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"party"],width:720,height:720,template:"systems/pf2e/templates/actors/party/sheet.hbs",scrollY:[...options.scrollY,".tab.active",".tab.active .content",".sidebar"],tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}get isLootSheet(){return this.actor.canUserModify(game.user,"update")}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fas fa-eye",onclick:()=>{const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:this.actor.uuid,options:{tab:this._tabs[0].active}})}}),buttons}async getData(options){const base=await super.getData(options),members=this.actor.members,canDistributeCoins=game.user.isGM&&this.isEditable?{enabled:this.actor.inventory.coins.copperValue>0&&members.some(isReallyPC)}:null;return{...base,playerRestricted:!game.settings.get("pf2e","metagame_showPartyStats"),restricted:!(game.user.isGM||game.settings.get("pf2e","metagame_showPartyStats")),members:__privateMethod(this,_prepareMembers,prepareMembers_fn).call(this),overviewSummary:__privateMethod(this,_prepareOverviewSummary,prepareOverviewSummary_fn).call(this),inventorySummary:{totalCoins:sum(members.map(actor=>actor.inventory.coins.goldValue??0))+this.actor.inventory.coins.goldValue,totalWealth:sum(members.map(actor=>actor.inventory.totalWealth.goldValue??0))+this.actor.inventory.totalWealth.goldValue,totalBulk:members.map(actor=>actor.inventory.bulk.value).reduce((a,b)=>a.plus(b),this.actor.inventory.bulk.value)},canDistributeCoins,explorationSummary:{speed:this.actor.system.attributes.speed.total,activities:Object.entries(CONFIG.PF2E.hexplorationActivities).find(([max])=>Number(max)>=this.actor.system.attributes.speed.total)?.[1]??0},orphaned:this.actor.items.filter(i=>!i.isOfType(...this.actor.allowedItemTypes))}}setSummaryView(view){const summary=htmlQuery(this.element[0],"[data-tab=overview] .summary");if(!summary)return;const viewElements=htmlQueryAll(summary,"[data-view]:not([data-action=change-view])");for(const element of viewElements)element.hidden=view!==element.dataset.view;for(const button of htmlQueryAll(summary,"[data-action=change-view]"))button.classList.toggle("active",button.dataset.view===view);this.currentSummaryView=view}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"a[data-action=open-meta-setting]")?.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.metagame");if(menu){const options={highlightSetting:"showPartyStats"};new menu.type(void 0,options).render(!0)}});for(const rollLink of htmlQueryAll(html,"[data-action=roll]")){const actorUUID=htmlClosest(rollLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");actor instanceof ActorPF2e&&rollLink.addEventListener("click",event=>{const rollMode=rollLink.dataset.secret?game.user.isGM?"gmroll":"blindroll":void 0;actor.getStatistic(rollLink.dataset.statistic??"")?.roll({...eventToRollParams(event,{type:"check"}),rollMode})})}for(const openSheetLink of htmlQueryAll(html,"[data-action=open-sheet]")){const tab=openSheetLink.dataset.tab,actorUUID=htmlClosest(openSheetLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");openSheetLink.addEventListener("click",async()=>actor?.sheet.render(!0,{tab}))}this.setSummaryView(this.currentSummaryView);for(const button of htmlQueryAll(html,"[data-action=change-view]"))button.addEventListener("click",()=>{this.setSummaryView(button.dataset.view??"languages")});for(const memberElem of htmlQueryAll(html,"[data-actor-uuid]")){const actorUUID=memberElem.dataset.actorUuid,actor=this.document.members.find(m=>m.uuid===actorUUID);if(game.user.isGM&&htmlQuery(memberElem,"a[data-action=remove-member]")?.addEventListener("click",async event=>{(event.ctrlKey?!0:await Dialog.confirm({title:game.i18n.localize("PF2E.Actor.Party.RemoveMember.Title"),content:game.i18n.localize("PF2E.Actor.Party.RemoveMember.Content")}))&&actor&&this.document.removeMembers(actor)}),actor?.isOfType("character")&&actor.canUserModify(game.user,"update")){const heroPointsPips=htmlQuery(memberElem,"a[data-action=adjust-hero-points]"),{heroPoints}=actor;heroPointsPips?.addEventListener("click",async()=>{const newValue=Math.min(heroPoints.value+1,heroPoints.max);await actor.update({"system.resources.heroPoints.value":newValue})}),heroPointsPips?.addEventListener("contextmenu",async event=>{event.preventDefault();const newValue=Math.max(heroPoints.value-1,0);await actor.update({"system.resources.heroPoints.value":newValue})})}}for(const languageTag of htmlQueryAll(html,"[data-language]")){const slug=languageTag.dataset.language,members=__privateMethod(this,_getActorsThatUnderstand,getActorsThatUnderstand_fn).call(this,slug).map(m=>m.name).join(", "),titleLabel=game.i18n.localize("PF2E.Actor.Party.MembersLabel"),title=createHTMLElement("strong",{children:[titleLabel]}),content=createHTMLElement("span",{children:[title,members]});$(languageTag).tooltipster({content})}for(const skillTag of htmlQueryAll(html,".summary .skills [data-slug]")){const slug=skillTag.dataset.slug??"",statistics=compact(this.actor.members.map(m=>m.skills[slug])),labels=sortBy$1(statistics,s=>s.mod).map(statistic=>{const rank=statistic.rank??(statistic.proficient?1:0),prof=game.i18n.localize(CONFIG.PF2E.proficiencyLevels[rank]),label=`${statistic.actor.name} (${prof}) ${addSign(statistic.mod)}`,row=createHTMLElement("div",{children:[label]});return row.style.textAlign="right",row}),content=createHTMLElement("div",{children:labels});$(skillTag).tooltipster({content})}for(const activityElem of htmlQueryAll(html,".activity[data-activity-uuid]")){const document2=fromUuidSync(activityElem.dataset.activityUuid??"");if(!(document2 instanceof ItemPF2e))continue;const rollData=document2.getRollData();(async()=>{const content=createHTMLElement("div",{classes:["item-summary"],innerHTML:await TextEditor.enrichHTML(document2.description,{async:!0,rollData})});InlineRollLinks.listen(content,document2),$(activityElem).tooltipster({contentAsHTML:!0,content,interactive:!0,maxWidth:500,side:"right",theme:"crb-hover"})})()}htmlQuery(html,"button[data-action=distribute-coins]")?.addEventListener("click",()=>{new DistributeCoinsPopup(this.actor,{recipients:this.actor.members}).render(!0)}),htmlQuery(html,"[data-action=clear-exploration]")?.addEventListener("click",async()=>{await Promise.all(this.actor.members.map(m=>m.update({"system.exploration":[]}))),ui.notifications.info("PF2E.Actor.Party.ClearActivities.Complete",{localize:!0})}),htmlQuery(html,"[data-action=rest]")?.addEventListener("click",event=>{game.pf2e.actions.restForTheNight({event,actors:this.actor.members})}),htmlQuery(html,"[data-action=prompt]")?.addEventListener("click",()=>{game.pf2e.gm.checkPrompt({actors:this.actor.members})})}async _onDropItemCreate(itemData){const toTest=Array.isArray(itemData)?itemData:[itemData],supported=[...PHYSICAL_ITEM_TYPES,...this.actor.baseAllowedItemTypes],invalid=toTest.filter(i=>!supported.includes(i.type));if(invalid.length){for(const source of invalid){const type=game.i18n.localize(CONFIG.Item.typeLabels[source.type]??source.type.titleCase());ui.notifications.error(game.i18n.format("PF2E.Item.CannotAddType",{type}))}return[]}return super._onDropItemCreate(itemData)}async _onDropItem(event,data){const droppedRegion=event.target?.closest("[data-region]")?.dataset.region,targetActor=event.target?.closest("[data-actor-uuid]")?.dataset.actorUuid;if(droppedRegion==="inventoryMembers"&&targetActor){const item=await ItemPF2e.fromDropData(data);if(!item)return[];const actorUuid=foundry.utils.parseUuid(targetActor).documentId;if(actorUuid&&item.actor&&item.isOfType("physical"))return await this.moveItemBetweenActors(event,item.actor.id,item.actor.token?.id??null,actorUuid,null,item.id),[item]}return super._onDropItem(event,data)}_disableFields(_form){}async render(force,options){if(options?.actors){const data=await this.getData();return this._saveScrollPositions(this.element),await __privateMethod(this,_renderRegions,renderRegions_fn).call(this,this.element[0],data),this._restoreScrollPositions(this.element),this}else return super.render(force,options)}async _renderInner(data,options){const result=await super._renderInner(data,options);return await __privateMethod(this,_renderRegions,renderRegions_fn).call(this,result[0],data),result}async _onDropActor(event,data){await super._onDropActor(event,data);const actor=fromUuidSync(data.uuid);actor instanceof CreaturePF2e&&this.document.addMembers(actor)}};_prepareMembers=new WeakSet,prepareMembers_fn=__name2(function(){function sanitizeSense(label){return label.replace(/\((imprecise|precise)\)/gi,"").replace(/\d+/g,"").replaceAll("feet","").trim()}return __name(sanitizeSense,"sanitizeSense"),__name2(sanitizeSense,"sanitizeSense"),this.actor.members.map(actor=>{const observer=actor.testUserPermission(game.user,"OBSERVER"),restricted=!(game.settings.get("pf2e","metagame_showPartyStats")||observer),genderPronouns=actor.isOfType("character")&&actor.system.details.gender.value.trim()||null,blurb=actor.isOfType("character")&&actor.ancestry&&actor.class?game.i18n.format("PF2E.Actor.Character.Blurb",{level:actor.level,ancestry:actor.ancestry.name,class:actor.class.name}):actor.isOfType("familiar")&&actor.master?game.i18n.format("PF2E.Actor.Familiar.Blurb",{master:actor.master.name}):actor.isOfType("npc")&&actor.system.details.blurb.trim()||null,heroPoints=actor.isOfType("character")&&isReallyPC(actor)?actor.system.resources.heroPoints:null,activities=actor.isOfType("character")?compact(actor.system.exploration.map(id=>actor.items.get(id))):[];return{actor,hasBulk:actor.inventory.bulk.encumberedAfter!==1/0,bestSkills:Object.values(actor.skills??{}).filter(s=>!!s?.proficient&&!s.lore).sort(sortBy(s=>s.mod??0)).reverse().slice(0,4).map(s=>({slug:s.slug,mod:s.mod,label:s.label,rank:s.rank})),genderPronouns,blurb,heroPoints,owner:actor.isOwner,observer,limited:observer||actor.limited,speeds:[{label:"PF2E.Speed",value:actor.attributes.speed.value},...actor.attributes.speed.otherSpeeds.map(s=>({label:s.label,value:s.value}))],senses:(()=>{const rawSenses=actor.system.traits.senses??[];return Array.isArray(rawSenses)?(rawSenses.some(s=>s.type==="darkvision")?rawSenses.filter(r=>r.type!=="lowLightVision"):rawSenses).map(r=>({acuity:r.acuity,labelFull:r.label??"",label:CONFIG.PF2E.senses[r.type]??r.type})):rawSenses.value.split(",").filter(s=>!!s.trim()).map(l=>({labelFull:l.trim(),label:sanitizeSense(l)}))})(),hp:actor.hitPoints,activities:activities.map(action2=>({uuid:action2.uuid,name:action2.name,img:action2.img,traits:createSheetTags(CONFIG.PF2E.actionTraits,action2.system.traits?.value??[])})),restricted}})},"#prepareMembers"),_prepareOverviewSummary=new WeakSet,prepareOverviewSummary_fn=__name2(function(){const members=this.actor.members;if(!members.length)return null;const allLanguages=new Set(members.flatMap(m=>m.system.traits.languages?.value??[])),baseKnowledgeSkills=["arcana","nature","occultism","religion","crafting","society","medicine"],loreSkills=new Set(members.flatMap(m=>Object.values(m.skills)).filter(s=>!!s?.lore).map(s=>s.slug));function getBestSkill(slug){const statistic=maxBy(members,m=>m.skills[slug]?.mod??-1/0)?.skills[slug];return statistic?pick$1(statistic,["slug","mod","label","rank"]):null}return __name(getBestSkill,"getBestSkill"),__name2(getBestSkill,"getBestSkill"),{languages:sortBy$1([...allLanguages].map(slug=>({slug,label:game.i18n.localize(CONFIG.PF2E.languages[slug]),actors:__privateMethod(this,_getActorsThatUnderstand,getActorsThatUnderstand_fn).call(this,slug)})),l=>l.label),skills:sortBy$1(Array.from(SKILL_LONG_FORMS).map(slug=>{const best=getBestSkill(slug),label=game.i18n.localize(CONFIG.PF2E.skillList[slug]);return best??{mod:0,label,slug,rank:0}}),s=>s.label),knowledge:{regular:compact(baseKnowledgeSkills.map(getBestSkill)),lore:sortBy$1(compact([...loreSkills].map(getBestSkill)),s=>s.label)}}},"#prepareOverviewSummary"),_getActorsThatUnderstand=new WeakSet,getActorsThatUnderstand_fn=__name2(function(slug){return this.actor.members.filter(m=>!!m?.system.traits.languages?.value.includes(slug))},"#getActorsThatUnderstand"),_renderRegions=new WeakSet,renderRegions_fn=__name2(async function(element,data){for(const region of htmlQueryAll(element,"[data-region]")){const regionId=region.dataset.region??"",templateName=this.regionTemplates[regionId];if(!templateName)continue;const template=`systems/pf2e/templates/actors/party/regions/${templateName}`,result=await renderTemplate(template,data);region.innerHTML=result,this._state!==Application.RENDER_STATES.RENDERING&&this.activateListeners($(region)),await __privateMethod(this,_renderRegions,renderRegions_fn).call(this,region,data)}},"#renderRegions"),__name2(_PartySheetPF2e,"PartySheetPF2e");let PartySheetPF2e=_PartySheetPF2e;const _VehicleSheetPF2e=class extends ActorSheetPF2e{static{__name(this,"_VehicleSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"vehicle"],width:670,height:480,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"details"}],template:"systems/pf2e/templates/actors/vehicle/sheet.hbs"}}async getData(){const sheetData=await super.getData(),actions={action:{label:game.i18n.localize("PF2E.ActionsActionsHeader"),actions:[]},reaction:{label:game.i18n.localize("PF2E.ActionsReactionsHeader"),actions:[]},free:{label:game.i18n.localize("PF2E.ActionsFreeActionsHeader"),actions:[]}};for(const item of this.actor.itemTypes.action.sort((a,b)=>a.sort-b.sort)){const itemData=item.toObject(!1),{actionCost,frequency}=item,actionType=actionCost?.type??"free",img=(()=>{const actionIcon=getActionIcon(item.actionCost),defaultIcon=ItemPF2e.getDefaultArtwork(item._source).img;return item.isOfType("action")&&![actionIcon,defaultIcon].includes(item.img)?item.img:item.system.selfEffect?.img??actionIcon})();actions[actionType].actions.push({...itemData,id:item.id,img,actionCost,glyph:actionCost?getActionGlyph(actionCost):null,frequency,hasEffect:!!item.system.selfEffect})}return{...sheetData,actions,actorSizes:CONFIG.PF2E.actorSizes,actorSize:CONFIG.PF2E.actorSizes[this.actor.size],actorRarities:CONFIG.PF2E.rarityTraits,actorRarity:CONFIG.PF2E.rarityTraits[this.actor.system.traits.rarity],ac:getAdjustment(this.actor.attributes.ac.value,this.actor._source.system.attributes.ac.value),saves:{fortitude:getAdjustment(this.actor.saves.fortitude.mod,this.actor._source.system.saves.fortitude.value)}}}activateListeners($html){super.activateListeners($html);const html=$html[0],titleElem=htmlQuery(html,".navigation-title");if(!titleElem)throw ErrorPF2e("Unexpected missing DOM element");const initialTitle=htmlQuery(html,".sheet-navigation .active")?.title;initialTitle&&(titleElem.title=initialTitle);for(const element of htmlQueryAll(html,".sheet-navigation .item"))element.addEventListener("mouseover",()=>{titleElem.textContent=element.title}),element.addEventListener("mouseout",()=>{const parent=htmlClosest(element,".sheet-navigation"),title=htmlQuery(parent,".item.active")?.title;title&&(titleElem.textContent=title)})}};__name2(_VehicleSheetPF2e,"VehicleSheetPF2e");let VehicleSheetPF2e=_VehicleSheetPF2e;const _ActionSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_ActionSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}]}}async getData(options){const sheetData=await super.getData(options);return{...sheetData,hasSidebar:!0,categories:CONFIG.PF2E.actionCategories,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,actionTraits:CONFIG.PF2E.actionTraits,frequencies:CONFIG.PF2E.frequencies,skills:CONFIG.PF2E.skillList,proficiencies:CONFIG.PF2E.proficiencyLevels,selfEffect:createSelfEffectSheetData(sheetData.data.selfEffect)}}activateListeners($html){if(super.activateListeners($html),!this.isEditable)return;const html=$html[0];activateActionSheetListeners(this.item,html)}async _onDrop(event){return handleSelfEffectDrop(this,event)}};__name2(_ActionSheetPF2e,"ActionSheetPF2e");let ActionSheetPF2e=_ActionSheetPF2e;const _AfflictionSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_AfflictionSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return options.dragDrop=[{dropSelector:"[data-stage-id]"}],options}async getData(options){const definingTraits=["disease","poison","curse"],traits=new Set(this.item.system.traits.value),definingTrait=definingTraits.find(t=>traits.has(t));return{...await super.getData(options),hasSidebar:!0,itemType:game.i18n.localize(definingTrait?CONFIG.PF2E.actionTraits[definingTrait]:"PF2E.LevelLabel"),conditionTypes:omit(CONFIG.PF2E.conditionTypes,["persistent-damage"]),damageTypes:CONFIG.PF2E.damageTypes,damageCategories:pick(CONFIG.PF2E.damageCategories,DAMAGE_CATEGORIES_UNIQUE),durationUnits:omit(CONFIG.PF2E.timeUnits,["encounter"]),onsetUnits:omit(CONFIG.PF2E.timeUnits,["encounter","unlimited"]),saves:CONFIG.PF2E.saves,stages:await this.prepareStages()}}async prepareStages(){const stages={};for(const[idx,[id,stage]]of Object.entries(Object.entries(this.item.system.stages))){const conditions=Object.entries(stage.conditions).reduce((result,[key,data])=>{const document2=ConditionManager.getCondition(data.slug);return result[key]={...data,document:document2},result},{}),effectDocuments=await UUIDUtils.fromUUIDs(stage.effects.map(e=>e.uuid)),effects=stage.effects.map(effect=>{const document2=effectDocuments.find(d=>d.uuid===effect.uuid);return document2 instanceof ItemPF2e?{...effect,name:document2.name,img:document2.img}:effect});stages[id]={...stage,stage:Number(idx)+1,conditions,effects}}return stages}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"[data-action=onset-add]")?.addEventListener("click",()=>{const onset={value:1,unit:"minutes"};this.item.update({system:{onset}})}),htmlQuery(html,"[data-action=onset-delete]")?.addEventListener("click",()=>{this.item.update({system:{"-=onset":null}})}),htmlQuery(html,"[data-action=stage-add]")?.addEventListener("click",()=>{const stage={damage:{},conditions:{},effects:[],duration:{value:-1,unit:"unlimited"}},id=randomID();this.item.update({system:{stages:{[id]:stage}}})});for(const deleteIcon of htmlQueryAll(html,"[data-action=stage-delete]"))deleteIcon.addEventListener("click",event=>{const deleteId=htmlClosest(event.target,"[data-stage-id]")?.dataset.stageId;deleteId&&this.item.update({[`system.stages.-=${deleteId}`]:null})});for(const addIcon of htmlQueryAll(html,"[data-action=damage-create]")??[])addIcon?.addEventListener("click",event=>{const stageId=htmlClosest(event.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const damage={formula:"",type:"untyped"};this.item.update({[`system.stages.${stageId}.damage.${randomID()}`]:damage})});for(const deleteIcon of htmlQueryAll(html,"[data-action=damage-delete"))deleteIcon.addEventListener("click",event=>{const stageId=htmlClosest(event.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const deleteId=htmlClosest(event.target,"[data-id]")?.dataset.id;this.item.update({[`system.stages.${stageId}.damage.-=${deleteId}`]:null})});for(const addIcon of htmlQueryAll(html,"[data-action=condition-create")??[])addIcon?.addEventListener("click",event=>{const stageId=htmlClosest(event.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const newCondition={slug:"frightened",value:1};this.item.update({[`system.stages.${stageId}.conditions.${randomID()}`]:newCondition})});for(const conditionEl of htmlQueryAll(html,".stage-condition[data-condition-id]")){const stageId=htmlClosest(conditionEl,"[data-stage-id]")?.dataset.stageId,conditionId=conditionEl.dataset.conditionId??"",stage=this.item.system.stages[stageId??""];!stage||!(conditionId in stage.conditions)||(htmlQuery(conditionEl,"[data-action=condition-link]")?.addEventListener("click",()=>{const linked=stage.conditions[conditionId].linked;this.item.update({[`system.stages.${stageId}.conditions.${conditionId}.linked`]:!linked})}),htmlQuery(conditionEl,"[data-action=condition-delete]")?.addEventListener("click",()=>{this.item.update({[`system.stages.${stageId}.conditions.-=${conditionId}`]:null})}))}for(const deleteIcon of htmlQueryAll(html,"[data-action=effect-delete"))deleteIcon.addEventListener("click",event=>{const stageId=htmlClosest(event.target,"[data-stage-id]")?.dataset.stageId,stage=this.item.system.stages[stageId??""];if(!stage)return;const deleteId=htmlClosest(event.target,"[data-uuid]")?.dataset.uuid,effects=stage.effects.filter(e=>e.uuid!==deleteId);this.item.update({[`system.stages.${stageId}.effects`]:effects})});for(const link of htmlQueryAll(html,"a.document-link[data-uuid]"))link.addEventListener("click",async event=>{const uuid=htmlClosest(event.target,"[data-uuid]")?.dataset.uuid;(await fromUuid(uuid??""))?.sheet?.render(!0)})}async _onDrop(event){if(!this.isEditable)return;const stageId=htmlClosest(event.target,"[data-stage-id]")?.dataset.stageId;if(!stageId)return;const stage=this.item.system.stages[stageId];if(!stage)return;const item=await(async()=>{try{const dataString=event.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(item instanceof EffectPF2e){const effects=[...stage.effects,{uuid:item.uuid}];this.item.update({system:{stages:{[stageId]:{effects}}}})}else ui.notifications.error("PF2E.Item.Affliction.Error.RestrictedStageItem",{localize:!0})}async _updateObject(event,formData){const categories=Object.keys(formData).filter(k=>/^system\.stages\.[a-z0-9]+\.damage\.[a-z0-9]+\.category$/i.test(k));for(const key of categories)formData[key]||=null;return super._updateObject(event,formData)}};__name2(_AfflictionSheetPF2e,"AfflictionSheetPF2e");let AfflictionSheetPF2e=_AfflictionSheetPF2e;const _ABCSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_ABCSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_isValidDrop)}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}]}}async getData(options){const sheetData=await super.getData(options),features=Object.entries(this.item.toObject().system.items).map(([key,ref])=>({key,item:{...ref,fromWorld:ref.uuid.startsWith("Item.")}})).sort((a,b)=>a.item.level-b.item.level);return{...sheetData,features}}getLocalizedAbilities(traits){return traits!==void 0&&traits.value?traits.value.length===6?{free:game.i18n.localize("PF2E.AbilityFree")}:Object.fromEntries(traits.value.map(x=>[x,CONFIG.PF2E.abilities[x]])):{}}async _onDrop(event){event.preventDefault();const dataString=event.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??""),item=await ItemPF2e.fromDropData(dropData);if(!item?.isOfType("feat")||!__privateMethod(this,_isValidDrop,isValidDrop_fn).call(this,event,item))return;const entry={uuid:item.uuid,img:item.img,name:item.name,level:item.level},items=this.item.system.items,pathPrefix="system.items";let id;do id=randomID(5);while(items[id]);await this.item.update({[`${pathPrefix}.${id}`]:entry})}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const li of htmlQueryAll(html,"li[data-index]")){const index=li.dataset.index,itemUUID=li.dataset.itemUuid;index&&(itemUUID&&htmlQuery(li,"a.name")?.addEventListener("click",()=>fromUuid(itemUUID).then(i=>i?.sheet.render(!0))),htmlQuery(li,"[data-action=remove]")?.addEventListener("click",()=>{this.item.update({[`system.items.-=${index}`]:null})}))}}};_isValidDrop=new WeakSet,isValidDrop_fn=__name2(function(event,feat){const validCategories=(htmlClosest(event.target,"[data-valid-drops]")?.dataset.validDrops?.split(" ")??[]).filter(f=>setHasElement(FEAT_CATEGORIES,f));if(validCategories.includes(feat.category))return!0;const goodCategories=validCategories.map(c=>game.i18n.localize(CONFIG.PF2E.featCategories[c]));if(goodCategories.length>0){const badCategory=game.i18n.localize(CONFIG.PF2E.featCategories[feat.category]),warning=game.i18n.format("PF2E.Item.ABC.InvalidDrop",{badType:badCategory,goodType:goodCategories[0]});return ui.notifications.warn(warning),!1}return!0},"#isValidDrop"),__name2(_ABCSheetPF2e,"ABCSheetPF2e");let ABCSheetPF2e=_ABCSheetPF2e;const _AncestrySheetPF2e=class extends ABCSheetPF2e{static{__name(this,"_AncestrySheetPF2e")}async getData(options){const data=await super.getData(options),itemData=data.item;return{...data,hasSidebar:!0,selectedBoosts:Object.fromEntries(Object.entries(itemData.system.boosts).map(([k,b])=>[k,this.getLocalizedAbilities(b)])),selectedFlaws:Object.fromEntries(Object.entries(itemData.system.flaws).map(([k,b])=>[k,this.getLocalizedAbilities(b)])),sizes:createSheetOptions(CONFIG.PF2E.actorSizes,{value:[itemData.system.size]}),languages:createSheetOptions(CONFIG.PF2E.languages,itemData.system.languages),additionalLanguages:createSheetOptions(CONFIG.PF2E.languages,itemData.system.additionalLanguages)}}};__name2(_AncestrySheetPF2e,"AncestrySheetPF2e");let AncestrySheetPF2e=_AncestrySheetPF2e;const _ArmorSheetPF2e=class extends PhysicalItemSheetPF2e{static{__name(this,"_ArmorSheetPF2e")}async getData(options){const sheetData=await super.getData(options),maxPropertySlots=getPropertySlots(this.item),propertyRuneSlots={};for(const slot of[1,2,3,4])slot<=maxPropertySlots&&(propertyRuneSlots[`propertyRuneSlots${slot}`]=!0);const fundamentalRunes=pick$1(RUNE_DATA.armor,["potency","resilient"]),propertyRunes=Object.values(RUNE_DATA.armor.property).map(r=>({slug:r.slug,name:game.i18n.localize(r.name)})).sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang));return{...sheetData,rarity:this.item._source.system.traits.rarity,fundamentalRunes,propertyRunes,categories:CONFIG.PF2E.armorCategories,groups:CONFIG.PF2E.armorGroups,baseTypes:CONFIG.PF2E.baseArmorTypes,bulkTypes:CONFIG.PF2E.bulkTypes,preciousMaterials:this.prepareMaterials(ARMOR_MATERIAL_VALUATION_DATA),...propertyRuneSlots,otherTags:createSheetTags(CONFIG.PF2E.otherArmorTags,sheetData.data.traits.otherTags),basePrice:new CoinsPF2e(this.item._source.system.price.value)}}async _updateObject(event,formData){formData["system.potencyRune.value"]||=null,formData["system.resiliencyRune.value"]||=null,formData["system.acBonus"]===null&&(formData["system.acBonus"]=0);for(const slotNumber of[1,2,3,4])formData[`system.propertyRune${slotNumber}.value`]||=null;return super._updateObject(event,formData)}};__name2(_ArmorSheetPF2e,"ArmorSheetPF2e");let ArmorSheetPF2e=_ArmorSheetPF2e;const _BackgroundSheetPF2e=class extends ABCSheetPF2e{static{__name(this,"_BackgroundSheetPF2e")}async getData(options){const data=await super.getData(options),itemData=data.item;return{...data,trainedSkills:createSheetOptions(CONFIG.PF2E.skills,itemData.system.trainedSkills),selectedBoosts:Object.fromEntries(Object.entries(itemData.system.boosts).map(([k,b])=>[k,this.getLocalizedAbilities(b)]))}}};__name2(_BackgroundSheetPF2e,"BackgroundSheetPF2e");let BackgroundSheetPF2e=_BackgroundSheetPF2e;const _BookSheetPF2e=class extends PhysicalItemSheetPF2e{static{__name(this,"_BookSheetPF2e")}};__name2(_BookSheetPF2e,"BookSheetPF2e");let BookSheetPF2e=_BookSheetPF2e;const _CampaignFeatureSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_CampaignFeatureSheetPF2e")}get validTraits(){return CONFIG.PF2E.kingmakerTraits}async getData(options){const sheetData=await super.getData(options),hasLevel=this.item.behavior!=="activity";return{...sheetData,hasSidebar:!0,itemType:hasLevel?game.i18n.localize(this.item.levelLabel):null,categories:KINGMAKER_CATEGORIES,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,prerequisites:JSON.stringify(this.item.system.prerequisites?.value??[]),isFeat:this.item.isFeat}}activateListeners($html){super.activateListeners($html);const html=$html[0];activateActionSheetListeners(this.item,html);const prerequisites=htmlQuery(html,'input[name="system.prerequisites.value"]');prerequisites&&new Tagify(prerequisites,{editTags:1})}_updateObject(event,formData){return Array.isArray(formData["system.prerequisites.value"])&&(formData["system.prerequisites.value"]=formData["system.prerequisites.value"].map(value=>({value}))),super._updateObject(event,formData)}};__name2(_CampaignFeatureSheetPF2e,"CampaignFeatureSheetPF2e");let CampaignFeatureSheetPF2e=_CampaignFeatureSheetPF2e;const _ClassSheetPF2e=class extends ABCSheetPF2e{static{__name(this,"_ClassSheetPF2e")}async getData(options){const sheetData=await super.getData(options),itemData=sheetData.item;return{...sheetData,skills:CONFIG.PF2E.skills,proficiencyChoices:CONFIG.PF2E.proficiencyLevels,selectedKeyAbility:this.getLocalizedAbilities(itemData.system.keyAbility),trainedSkills:createSheetTags(CONFIG.PF2E.skills,itemData.system.trainedSkills),ancestryFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.ancestryFeatLevels),classFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.classFeatLevels),generalFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.generalFeatLevels),skillFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.skillFeatLevels),skillIncreaseLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.skillIncreaseLevels)}}};__name2(_ClassSheetPF2e,"ClassSheetPF2e");let ClassSheetPF2e=_ClassSheetPF2e;const _ConsumableSheetPF2e=class extends PhysicalItemSheetPF2e{static{__name(this,"_ConsumableSheetPF2e")}async getData(options){const item=this.item;return{...await super.getData(options),consumableTypes:CONFIG.PF2E.consumableTypes,otherTags:createSheetTags(CONFIG.PF2E.otherConsumableTags,item.system.traits.otherTags)}}};__name2(_ConsumableSheetPF2e,"ConsumableSheetPF2e");let ConsumableSheetPF2e=_ConsumableSheetPF2e;const _ContainerSheetPF2e=class extends PhysicalItemSheetPF2e{static{__name(this,"_ContainerSheetPF2e")}};__name2(_ContainerSheetPF2e,"ContainerSheetPF2e");let ContainerSheetPF2e=_ContainerSheetPF2e;const _DeitySheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_DeitySheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".sheet-header, .sheet-content"}]}}async getData(options){const sheetData=await super.getData(options),spellEntries=Object.entries(sheetData.data.spells),spells=(await UUIDUtils.fromUUIDs(Object.values(sheetData.data.spells))).filter(i=>i instanceof SpellPF2e).map(spell=>{const level=Number(spellEntries.find(([,uuid])=>uuid===spell.uuid)?.at(0));return{uuid:spell.uuid,level,name:spell.name,img:spell.img}}).sort((spellA,spellB)=>spellA.level-spellB.level);return{...sheetData,alignments:CONFIG.PF2E.alignments,atheistic:this.item.category==="philosophy",skills:CONFIG.PF2E.skills,divineFonts:createSheetOptions({harm:"PF2E.Item.Deity.DivineFont.Harm",heal:"PF2E.Item.Deity.DivineFont.Heal"},sheetData.data.font),spells}}activateListeners($html){super.activateListeners($html);const html=$html[0],getInput=__name2(name2=>html.querySelector(`input[name="${name2}"]`),"getInput");if(tagify$1(getInput("system.ability"),{whitelist:CONFIG.PF2E.abilities,maxTags:2}),tagify$1(getInput("system.alignment.follower"),{whitelist:CONFIG.PF2E.alignments,maxTags:9}),this.item.category==="philosophy")return;tagify$1(getInput("system.weapons"),{whitelist:CONFIG.PF2E.baseWeaponTypes,maxTags:2});const domainWhitelist=omitBy(CONFIG.PF2E.deityDomains,(_v,k)=>k.endsWith("-apocryphal"));tagify$1(getInput("system.domains.primary"),{whitelist:domainWhitelist,maxTags:6}),tagify$1(getInput("system.domains.alternate"),{whitelist:domainWhitelist,maxTags:6});const clericSpells=htmlQuery(html,".cleric-spells");if(!clericSpells)return;for(const link of htmlQueryAll(clericSpells,"a[data-action=view-spell]"))link.addEventListener("click",async()=>{const uuid=htmlClosest(link,"li")?.dataset.uuid??"",spell=await fromUuid(uuid);if(!(spell instanceof SpellPF2e)){this.render(!1),ui.notifications.error(`A spell with the UUID "${uuid}" no longer exists`);return}spell.sheet.render(!0)});for(const link of htmlQueryAll(clericSpells,"a[data-action=remove-spell]"))link.addEventListener("click",async()=>{const uuidToRemove=htmlClosest(link,"li")?.dataset.uuid,[levelToRemove]=Object.entries(this.item.system.spells).find(([_level,uuid])=>uuid===uuidToRemove)??[];if(!levelToRemove){this.render(!1);return}await this.item.update({[`system.spells.-=${levelToRemove}`]:null})});const spellLevelInputs=htmlQueryAll(clericSpells,"input[data-action=update-spell-level]");for(const input of spellLevelInputs)input.addEventListener("change",async()=>{const oldLevel=Number(input.dataset.level),uuid=this.item.system.spells[oldLevel];if(!uuid){this.render(!1);return}const newLevel=Math.clamped(Number(input.value)||1,1,10);oldLevel!==newLevel&&await this.item.update({[`system.spells.-=${oldLevel}`]:null,[`system.spells.${newLevel}`]:uuid})})}async _onDrop(event){if(!this.isEditable)return;const item=await(async()=>{try{const dataString=event.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(!(item instanceof SpellPF2e))throw ErrorPF2e("Invalid item drop on deity sheet");if(item.isCantrip||item.isFocusSpell||item.isRitual){ui.notifications.error("PF2E.Item.Deity.ClericSpells.DropError",{localize:!0});return}await this.item.update({[`system.spells.${item.rank}`]:item.uuid})}async _updateObject(event,formData){Array.isArray(formData["system.font"])&&(formData["system.font"]=formData["system.font"].filter(f=>!!f));for(const property of["system.alignment.own","system.skill"])typeof formData[property]=="string"&&(formData[property]||=null);return super._updateObject(event,formData)}};__name2(_DeitySheetPF2e,"DeitySheetPF2e");let DeitySheetPF2e=_DeitySheetPF2e;const _EffectSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_EffectSheetPF2e")}async getData(options){const badge=this.item.badge;return{...await super.getData(options),hasSidebar:!0,itemType:game.i18n.localize("PF2E.LevelLabel"),badgeType:badge?game.i18n.localize(`PF2E.Item.Effect.Badge.Type.${badge.type}`):"",timeUnits:CONFIG.PF2E.timeUnits}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"select.badge-type")?.addEventListener("change",event=>{event.stopPropagation()}),htmlQuery(html,"[data-action=badge-add]")?.addEventListener("click",()=>{const badge=htmlQuery(html,".badge-type")?.value==="formula"?{type:"formula",value:"1d20",evaluate:!0}:{type:"counter",value:1};this.item.update({system:{badge}})}),htmlQuery(html,"[data-action=badge-delete]")?.addEventListener("click",()=>{this.item.update({"system.-=badge":null})}),htmlQuery(html,"[data-action=badge-add-label")?.addEventListener("click",()=>{if(!this.item.system.badge)throw ErrorPF2e("Unexpected error adding badge label");const labels=this.item.system.badge.labels??[];labels.push(""),this.item.update({system:{badge:{labels}}})});for(const deleteIcon of htmlQueryAll(html,"[data-action=badge-delete-label]")){const index=Number(deleteIcon.dataset.idx);deleteIcon.addEventListener("click",()=>{const labels=this.item.system.badge?.labels;labels&&(labels.splice(index,1),labels.length===0?this.item.update({"system.badge.-=labels":null}):this.item.update({system:{badge:{labels}}}))})}}async _updateObject(event,formData){const expanded=expandObject(formData),badge=expanded.system?.badge;badge&&("labels"in badge&&typeof badge.labels=="object"&&(badge.labels=Object.values(badge.labels)),"reevaluate"in badge&&(badge.reevaluate||=null)),super._updateObject(event,flattenObject(expanded))}};__name2(_EffectSheetPF2e,"EffectSheetPF2e");let EffectSheetPF2e=_EffectSheetPF2e;const _EquipmentSheetPF2e=class extends PhysicalItemSheetPF2e{static{__name(this,"_EquipmentSheetPF2e")}async getData(options){const item=this.item;return{...await super.getData(options),isApex:item._source.system.traits.value.includes("apex"),attributes:CONFIG.PF2E.abilities,otherTags:createSheetTags(CONFIG.PF2E.otherArmorTags,item.system.traits.otherTags)}}};__name2(_EquipmentSheetPF2e,"EquipmentSheetPF2e");let EquipmentSheetPF2e=_EquipmentSheetPF2e;const _FeatSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_FeatSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}]}}get validTraits(){return CONFIG.PF2E.featTraits}async getData(options){const sheetData=await super.getData(options),hasLineageTrait=this.item.traits.has("lineage");return{...sheetData,hasSidebar:!0,itemType:game.i18n.localize(this.item.isFeature?"PF2E.LevelLabel":"PF2E.Item.Feat.LevelLabel"),categories:CONFIG.PF2E.featCategories,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,mandatoryTakeOnce:hasLineageTrait||sheetData.data.onlyLevel1,hasLineageTrait,canHaveKeyOptions:featCanHaveKeyOptions(this.item),selfEffect:createSelfEffectSheetData(sheetData.data.selfEffect)}}activateListeners($html){super.activateListeners($html);const html=$html[0];activateActionSheetListeners(this.item,html);const getInput=__name2(name2=>html.querySelector(`input[name="${name2}"]`),"getInput");tagify$1(getInput("system.prerequisites.value"),{maxTags:6}),tagify$1(getInput("system.subfeatures.keyOptions"),{whitelist:CONFIG.PF2E.abilities,maxTags:3})}async _onDrop(event){return handleSelfEffectDrop(this,event)}_updateObject(event,formData){Array.isArray(formData["system.prerequisites.value"])&&(formData["system.prerequisites.value"]=formData["system.prerequisites.value"].map(value=>({value})));const keyOptionsKey="system.subfeatures.keyOptions",hasEmptyKeyOptions=Array.isArray(formData[keyOptionsKey])&&formData[keyOptionsKey].length===0,hasNoKeyOptions=!(keyOptionsKey in formData);return(hasEmptyKeyOptions||hasNoKeyOptions)&&(delete formData[keyOptionsKey],this.item._source.system.subfeatures&&(formData["system.subfeatures.-=keyOptions"]=null)),super._updateObject(event,formData)}};__name2(_FeatSheetPF2e,"FeatSheetPF2e");let FeatSheetPF2e=_FeatSheetPF2e;const _HeritageSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_HeritageSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".sidebar"}]}}async getData(options){const sheetData=await super.getData(options),ancestry=await(async()=>{const item=this.item.system.ancestry?await fromUuid(this.item.system.ancestry.uuid):null;return item instanceof AncestryPF2e?item:null})();return{...sheetData,hasSidebar:!0,ancestry,ancestryRefBroken:!!sheetData.data.ancestry&&ancestry===null}}activateListeners($html){super.activateListeners($html),$html.find('a[data-action="remove-ancestry"]').on("click",()=>{this.item.update({"system.ancestry":null})})}async _onDrop(event){const item=await(async()=>{try{const dataString=event.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(!(item instanceof AncestryPF2e))throw ErrorPF2e("Invalid item drop on heritage sheet");const ancestryReference={name:item.name,slug:item.slug??sluggify(item.name),uuid:item.uuid};await this.item.update({"system.ancestry":ancestryReference})}};__name2(_HeritageSheetPF2e,"HeritageSheetPF2e");let HeritageSheetPF2e=_HeritageSheetPF2e;const _KitSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_KitSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}]}}async getData(options){const items=Object.fromEntries(Object.entries(this.item.system.items).map(([key,ref])=>[key,{...ref,fromWorld:ref.uuid.startsWith("Item.")}]));return{...await super.getData(options),hasSidebar:!0,priceString:this.item.price.value,items}}async _onDrop(event){event.preventDefault();const dragData=event.dataTransfer?.getData("text/plain"),dragItem=JSON.parse(dragData??""),containerId=event.target.dataset.containerId??event.target.closest("[data-container-id]")?.dataset.containerId;if(dragItem.type!=="Item")return;const item=await fromUuid(dragItem.uuid??"");if(!(item instanceof PhysicalItemPF2e||item instanceof KitPF2e))return;const entry={uuid:item.uuid,img:item.img,quantity:1,name:item.name,isContainer:item.type==="backpack"&&!containerId,items:{}};let{items}=this.item.system,pathPrefix="system.items";containerId!==void 0&&(pathPrefix=`${pathPrefix}.${containerId}.items`,items=items[containerId]?.items??{});let id;do id=randomID(5);while(items[id]);await this.item.update({[`${pathPrefix}.${id}`]:entry})}async removeItem(event){const target=htmlClosest(event.currentTarget??null,"li"),index=target?.dataset.index;if(!index)return this.item;const containerId=target.closest("[data-container-id]")?.dataset.containerId,path=containerId?`${containerId}.items.-=${index}`:`-=${target.dataset.index}`;return this.item.update({[`system.items.${path}`]:null})}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const link of htmlQueryAll(html,"[data-action=remove]"))link.addEventListener("click",event=>{this.removeItem(event)})}async _updateObject(event,formData){return formData["system.price.value"]&&(formData["system.price.value"]=CoinsPF2e.fromString(String(formData["system.price.value"]))),super._updateObject(event,formData)}};__name2(_KitSheetPF2e,"KitSheetPF2e");let KitSheetPF2e=_KitSheetPF2e;const _MeleeSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_MeleeSheetPF2e")}async getData(options){const data=await super.getData(options),itemSource=this.item._source;data.data.attack.value=itemSource.system.attack.value;for(const key of Object.keys(data.data.damageRolls))data.data.damageRolls[key].damage=itemSource.system.damageRolls[key].damage;return{...data,damageTypes:CONFIG.PF2E.damageTypes,damageCategories:damageCategoriesUnique,attackEffects:createSheetOptions(this.getAttackEffectOptions(),this.item.system.attackEffects)}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const button of htmlQueryAll(html,"a[data-action=add-partial]"))button.addEventListener("click",()=>{const newKey=randomID();this.item.update({[`system.damageRolls.${newKey}`]:{damage:"1d4",damageType:"bludgeoning"}})});for(const button of htmlQueryAll(html,"a[data-action=remove-partial]"))button.addEventListener("click",()=>{const partialKey=htmlClosest(button,"[data-key]")?.dataset.key;partialKey&&this.item.update({[`system.damageRolls.-=${partialKey}`]:null})})}async _updateObject(event,formData){const categories=Object.keys(formData).filter(k=>/^system.damageRolls\.[a-z0-9]+\.category$/i.test(k));for(const key of categories)formData[key]||=null;return super._updateObject(event,formData)}};__name2(_MeleeSheetPF2e,"MeleeSheetPF2e");let MeleeSheetPF2e=_MeleeSheetPF2e;const spellOverridable={traits:"PF2E.Traits",time:"PF2E.SpellTimeLabel",components:"PF2E.SpellComponentsLabel",target:"PF2E.SpellTargetLabel",area:"PF2E.AreaLabel",range:"PF2E.SpellRangeLabel",damage:"PF2E.DamageLabel"},_SpellSheetPF2e=class extends ItemSheetPF2e{static{__name(this,"_SpellSheetPF2e")}constructor(){super(...arguments),__privateAdd(this,_getOverlayFromElement),__privateAdd(this,_getDefaultProperty),__privateAdd(this,_formatSpellComponents),__privateAdd(this,_prepareHeighteningLevels)}get id(){const baseId=super.id,appliedOverlays=this.item.appliedOverlays;return this.item.isVariant&&appliedOverlays?`${baseId}-${[...appliedOverlays.keys()].join("-")}`:baseId}async getData(options){const sheetData=await super.getData(options),{isCantrip,isFocusSpell,isRitual}=this.item,itemType=isCantrip&&isFocusSpell?game.i18n.localize("PF2E.SpellCategoryFocusCantrip"):this.item.isCantrip?game.i18n.localize("PF2E.TraitCantrip"):game.i18n.localize(CONFIG.PF2E.spellCategories[this.item.system.category.value]),damageTypes2=Object.fromEntries(Object.entries(CONFIG.PF2E.damageTypes).map(([slug,localizeKey])=>[slug,game.i18n.localize(localizeKey)]).sort((damageA,damageB)=>damageA[1].localeCompare(damageB[1]))),variants=this.item.overlays.overrideVariants.map(variant=>({name:variant.name,id:variant.id,sort:variant.sort,actions:getActionGlyph(variant.system.time.value)})).sort((variantA,variantB)=>variantA.sort-variantB.sort);return{...sheetData,hasSidebar:!0,itemType,isCantrip,isFocusSpell,isRitual,variants,isVariant:this.item.isVariant,spellCategories:CONFIG.PF2E.spellCategories,spellTypes:CONFIG.PF2E.spellTypes,saves:CONFIG.PF2E.saves,magicSchools:CONFIG.PF2E.magicSchools,damageTypes:damageTypes2,damageSubtypes:pick$1(CONFIG.PF2E.damageCategories,[...DAMAGE_CATEGORIES_UNIQUE]),damageCategories:CONFIG.PF2E.damageCategories,spellComponents:__privateMethod(this,_formatSpellComponents,formatSpellComponents_fn).call(this,sheetData.data),areaSizes:CONFIG.PF2E.areaSizes,areaTypes:CONFIG.PF2E.areaTypes,heightenIntervals:[1,2,3,4],heightenOverlays:__privateMethod(this,_prepareHeighteningLevels,prepareHeighteningLevels_fn).call(this),canHeighten:this.getAvailableHeightenLevels().length>0}}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dragSelector:"[data-variant-id]",dropSelector:"[data-can-drop=true]"}]}}get title(){return this.item.isVariant?game.i18n.format("PF2E.Item.Spell.Variants.SheetTitle",{originalName:this.item.original.name}):super.title}activateListeners($html){super.activateListeners($html);const html=$html[0];tagify$1(html.querySelector('input[name="system.traditions.value"]'),{whitelist:CONFIG.PF2E.magicTraditions});for(const tags of htmlQueryAll(html,"input.spell-traits"))tagify$1(tags,{whitelist:CONFIG.PF2E.spellTraits});$html.find(".toggle-trait").on("change",evt=>{const target=evt.target,trait=target.dataset.trait??"";if(!objectHasKey(CONFIG.PF2E.spellTraits,trait)){console.warn("Toggled trait is invalid");return}if(target.checked&&!this.item.traits.has(trait)){const newTraits=this.item.system.traits.value.concat([trait]);this.item.update({"system.traits.value":newTraits})}else if(!target.checked&&this.item.traits.has(trait)){const newTraits=this.item.system.traits.value.filter(t=>t!==trait);this.item.update({"system.traits.value":newTraits})}}),$html.find("[data-action=damage-create]").on("click",event=>{event.preventDefault();const baseKey=__privateMethod(this,_getOverlayFromElement,getOverlayFromElement_fn).call(this,event.target)?.base??"system",emptyDamage={value:"",type:{value:"bludgeoning",categories:[]}};this.item.update({[`${baseKey}.damage.value.${randomID()}`]:emptyDamage})}),$html.find("[data-action=damage-delete]").on("click",event=>{event.preventDefault();const overlayData=__privateMethod(this,_getOverlayFromElement,getOverlayFromElement_fn).call(this,event.target),baseKey=overlayData?.base??"system",id=$(event.target).closest("[data-action=damage-delete]").attr("data-id");if(id){const values={[`${baseKey}.damage.value.-=${id}`]:null};overlayData||(values[`${baseKey}.heightening.damage.-=${id}`]=null),this.item.update(values)}});for(const button of htmlQueryAll(html,"[data-action=heightening-interval-create]"))button.addEventListener("click",event=>{event.preventDefault();const baseKey=__privateMethod(this,_getOverlayFromElement,getOverlayFromElement_fn).call(this,event.target)?.base??"system",data={type:"interval",interval:1,damage:mapToObj(Object.keys(this.item.system.damage.value),key=>[key,"0"])};this.item.update({[`${baseKey}.heightening`]:data})});$html.find("[data-action=heightening-delete]").on("click",()=>{this.item.update({"system.-=heightening":null})}),$html.find("[data-action=heightening-fixed-create]").on("click",()=>{const highestLevel=this.item.getHeightenLayers().at(-1)?.level,available=this.getAvailableHeightenLevels(),level=highestLevel&&highestLevel<10?highestLevel+1:available.at(0);level!==void 0&&this.item.update({"system.heightening":{type:"fixed",levels:{[level]:{}}}})});for(const overlayEditor of htmlQueryAll(html,"[data-overlay-type=heighten]")){const overlay=__privateMethod(this,_getOverlayFromElement,getOverlayFromElement_fn).call(this,overlayEditor);if(!overlay)continue;htmlQuery(overlayEditor,"[data-action=overlay-delete]")?.addEventListener("click",()=>{if(overlay.type==="heighten"){const layers=this.item.getHeightenLayers();if(layers.length===1&&layers[0].level===overlay.level){this.item.update({"system.-=heightening":null});return}}const parts=overlay.base.split(".");parts.push(`-=${parts.pop()}`),this.item.update({[parts.join(".")]:null})});for(const addProperty of htmlQueryAll(overlayEditor,"[data-action=overlay-add-property]")){const property=addProperty.dataset.property;!overlay.system||!property||property in overlay.system||addProperty.addEventListener("click",()=>{try{const value=__privateMethod(this,_getDefaultProperty,getDefaultProperty_fn).call(this,property);this.item.update({[`${overlay.base}.${property}`]:value})}catch(ex){ex instanceof Error&&ui.notifications.error(ex.message)}})}for(const removeProperty of htmlQueryAll(overlayEditor,"[data-action=overlay-remove-property]")){const property=removeProperty.dataset.property;property&&removeProperty.addEventListener("click",()=>{const updates={[`${overlay.base}.-=${property}`]:null};property==="damage"&&(updates[`${overlay.base}.-=heightening`]=null),this.item.update(updates)})}const levelSelect=htmlQuery(overlayEditor,"[data-action=change-heighten-level]");levelSelect?.addEventListener("change",()=>{const newLevel=Number(levelSelect.value),existingData=this.item.getHeightenLayers().find(layer=>layer.level===overlay.level);this.item.update({[`system.heightening.levels.-=${overlay.level}`]:null,[`system.heightening.levels.${newLevel}`]:existingData?.system??{}})})}$html.find("[data-action=variant-create]").on("click",()=>{this.item.overlays.create("override")}),$html.find("[data-action=variant-edit]").on("click",event=>{const id=$(event.target).closest("[data-action=variant-edit]").attr("data-id");id&&this.item.loadVariant({overlayIds:[id]})?.sheet.render(!0)}),$html.find("[data-action=variant-delete]").on("click",event=>{const id=$(event.target).closest("[data-action=variant-delete]").attr("data-id");if(id){const variant=this.item.loadVariant({overlayIds:[id]});if(!variant)throw ErrorPF2e(`Spell ${this.item.name} (${this.item.uuid}) does not have a variant with id: ${id}`);new Dialog({title:game.i18n.localize("PF2E.Item.Spell.Variants.DeleteDialogTitle"),content:`${game.i18n.format("PF2E.Item.Spell.Variants.DeleteDialogText",{variantName:variant.name})}
`,buttons:{delete:{icon:fontAwesomeIcon("fa-trash").outerHTML,label:game.i18n.localize("PF2E.DeleteShortLabel"),callback:()=>{this.item.overlays.deleteOverlay(id)}},cancel:{icon:fontAwesomeIcon("fa-times").outerHTML,label:game.i18n.localize("Cancel")}},default:"cancel"}).render(!0)}})}async _updateObject(event,formData){if(formData["system.area.value"]?formData["system.area.type"]||="burst":(delete formData["system.area.value"],delete formData["system.area.type"],formData["system.area"]=null),this.item.original&&this.item.appliedOverlays.has("override")&&!this.rendered){await this.item.original.overlays.updateOverride(this.item,formData);return}super._updateObject(event,formData)}_onDragStart(event){const id=event.target.closest(".variant")?.dataset.variantId??"";event.dataTransfer.setData("text/plain",JSON.stringify({action:"sort",data:{sourceId:id}}))}async _onDrop(event){event.preventDefault();const transferString=event.dataTransfer.getData("text/plain");if(!transferString)return;const{action:action2,data}=JSON.parse(transferString)??{};switch(action2){case"sort":{const sourceId=data?.sourceId??"",targetId=event.target.closest(".variant")?.dataset.variantId??"";if(sourceId&&targetId&&sourceId!==targetId){const sourceVariant=this.item.loadVariant({overlayIds:[sourceId]}),targetVariant=this.item.loadVariant({overlayIds:[targetId]});if(sourceVariant&&targetVariant){const siblings=this.item.overlays.overrideVariants.filter(variant=>variant.id!==sourceId&&variant.id!==targetId);siblings.push(targetVariant);const sorting=SortingHelpers.performIntegerSort(sourceVariant,{target:targetVariant,siblings,sortKey:"sort",sortBefore:!0});for(const s of sorting)await this.item.overlays.updateOverride(s.target,s.update,{render:!1});this.render(!0)}}break}}}getAvailableHeightenLevels(){const heightenLayers=this.item.getHeightenLayers();return[2,3,4,5,6,7,8,9,10].filter(level=>level>this.item.baseRank&&!heightenLayers.some(layer=>layer.level===level))}};_getOverlayFromElement=new WeakSet,getOverlayFromElement_fn=__name2(function(target){const overlayEl=htmlClosest(target,"[data-overlay-type]");if(!overlayEl)return null;const domData=overlayEl.dataset,type=String(domData.overlayType);if(!tupleHasValue(["heighten","variant"],type))return null;const id="overlayId"in domData?String(domData.overlayId):null,level="level"in domData?Number(domData.level):null,collectionPath=type==="heighten"?"system.heightening.levels":"system.variants",base=type==="heighten"?`${collectionPath}.${level}`:`${collectionPath}.${id}`,system=(()=>{if(type==="heighten"){const heightening=this.item.system.heightening;if(heightening?.type==="fixed")return heightening.levels[level]}return null})();return{id,level,type,base,dataPath:base,system}},"#getOverlayFromElement"),_getDefaultProperty=new WeakSet,getDefaultProperty_fn=__name2(function(property){const scaling=this.item.getHeightenLayers().reverse(),baseValue=(()=>{for(const entry of[...scaling,{system:this.item.system}])if(objectHasKey(entry.system,property))return entry.system[property];return null})();if(baseValue)return baseValue;if(property==="area")return{value:5,type:"burst"};throw ErrorPF2e(`Failed to initialize property ${property} for overlay`)},"#getDefaultProperty"),_formatSpellComponents=new WeakSet,formatSpellComponents_fn=__name2(function(data){if(!data.components)return[];const comps=[];return data.components.focus&&comps.push(game.i18n.localize(CONFIG.PF2E.spellComponents.F)),data.components.material&&comps.push(game.i18n.localize(CONFIG.PF2E.spellComponents.M)),data.components.somatic&&comps.push(game.i18n.localize(CONFIG.PF2E.spellComponents.S)),data.components.verbal&&comps.push(game.i18n.localize(CONFIG.PF2E.spellComponents.V)),data.materials.value&&comps.push(data.materials.value),comps},"#formatSpellComponents"),_prepareHeighteningLevels=new WeakSet,prepareHeighteningLevels_fn=__name2(function(){return this.item.getHeightenLayers().map(layer=>{const base=`system.heightening.levels.${layer.level}`,missing=[];for(const[key,label]of Object.entries(spellOverridable))key in layer.system||missing.push({key,label});return{id:null,type:"heighten",level:layer.level,base,dataPath:base,system:layer.system,missing,heightenLevels:[layer.level,...this.getAvailableHeightenLevels()].sort(),traits:layer.system.traits?.value?createTagifyTraits(layer.system.traits.value,{record:CONFIG.PF2E.spellTraits}):null}})},"#prepareHeighteningLevels"),__name2(_SpellSheetPF2e,"SpellSheetPF2e");let SpellSheetPF2e=_SpellSheetPF2e;const _TreasureSheetPF2e=class extends PhysicalItemSheetPF2e{static{__name(this,"_TreasureSheetPF2e")}async getData(options){return{...await super.getData(options),currencies:CONFIG.PF2E.currencies}}};__name2(_TreasureSheetPF2e,"TreasureSheetPF2e");let TreasureSheetPF2e=_TreasureSheetPF2e;const _WeaponSheetPF2e=class extends PhysicalItemSheetPF2e{static{__name(this,"_WeaponSheetPF2e")}async getData(options){const sheetData=await super.getData(options),weapon=this.item,maxPropertySlots=getPropertySlots(weapon),propertyRuneSlotsData=[[1,sheetData.data.propertyRune1],[2,sheetData.data.propertyRune2],[3,sheetData.data.propertyRune3],[4,sheetData.data.propertyRune4]],lastDisplayedPropertySlot=Math.min(maxPropertySlots,propertyRuneSlotsData.findLastIndex(([,slot])=>!!slot?.value)+2),propertyRuneSlots=propertyRuneSlotsData.filter(([slotNumber,slot])=>slotNumber<=lastDisplayedPropertySlot&&!(sheetData.data.specific?.value&&slot.value===null)).map(([slotNumber,slot])=>({...slot,name:`system.propertyRune${slotNumber}.value`,label:game.i18n.localize(`PF2E.PropertyRuneLabel${slotNumber}`),number:slotNumber})),fundamentalRunes=pick$1(RUNE_DATA.weapon,["potency","striking"]),propertyRunes=Object.values(RUNE_DATA.weapon.property).map(r=>({slug:r.slug,name:game.i18n.localize(r.name)})).sort((a,b)=>a.name.localeCompare(b.name,game.i18n.lang)),abpEnabled=AutomaticBonusProgression.isEnabled(this.actor),hintText=abpEnabled?"PF2E.Item.Weapon.FromABP":"PF2E.Item.Weapon.FromMaterialAndRunes",adjustedDiceHint=weapon.system.damage.dice!==weapon._source.system.damage.dice?game.i18n.format(game.i18n.localize(hintText),{property:game.i18n.localize("PF2E.Item.Weapon.Damage.DiceNumber"),value:weapon.system.damage.dice}):null,damageDieFaces=Object.fromEntries(Object.entries(CONFIG.PF2E.damageDie).map(([num,label])=>[Number(num.replace("d","")),label]).sort(([numA],[numB])=>numA-numB)),traitSet=weapon.traits,isComboWeapon=traitSet.has("combination"),weaponRanges=Array.from(WEAPON_RANGES).reduce((ranges,range)=>({...ranges,[range]:game.i18n.format("PF2E.WeaponRangeN",{range})}),{}),rangedOnlyTraits=["combination","thrown","volley-20","volley-30","volley-50"],mandatoryRanged=setHasElement(MANDATORY_RANGED_GROUPS,weapon.group)||rangedOnlyTraits.some(trait=>traitSet.has(trait)),mandatoryMelee=sheetData.data.traits.value.some(trait=>/^thrown-\d+$/.test(trait)),otherTags=(()=>{const otherWeaponTags2=deepClone(CONFIG.PF2E.otherWeaponTags);return weapon.hands!=="1"&&delete otherWeaponTags2.implement,createSheetTags(otherWeaponTags2,sheetData.data.traits.otherTags)})(),meleeUsage=sheetData.data.meleeUsage??{group:"knife",damage:{type:"piercing",die:"d4"},traits:[]};return{...sheetData,propertyRuneSlots,preciousMaterials:this.prepareMaterials(WEAPON_MATERIAL_VALUATION_DATA),fundamentalRunes,propertyRunes,otherTags,adjustedDiceHint,abpEnabled,categories:sortStringRecord(CONFIG.PF2E.weaponCategories),groups:sortStringRecord(CONFIG.PF2E.weaponGroups),baseTypes:sortStringRecord(CONFIG.PF2E.baseWeaponTypes),itemBonuses:CONFIG.PF2E.itemBonuses,damageDieFaces,damageDie:CONFIG.PF2E.damageDie,damageDice:CONFIG.PF2E.damageDice,conditionTypes:sortStringRecord(CONFIG.PF2E.conditionTypes),damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),weaponRanges,mandatoryMelee,mandatoryRanged,weaponReload:CONFIG.PF2E.weaponReload,weaponMAP:CONFIG.PF2E.weaponMAP,isBomb:weapon.group==="bomb",isComboWeapon,meleeGroups:sortStringRecord(CONFIG.PF2E.meleeWeaponGroups),meleeUsage,meleeUsageTraits:createSheetTags(CONFIG.PF2E.weaponTraits,meleeUsage.traits??[])}}activateListeners($html){super.activateListeners($html);const html=$html[0],pdElements=htmlQueryAll(html,"[data-action=update-persistent]");for(const element of pdElements)element.addEventListener("change",async event=>{if(!(event.target instanceof HTMLInputElement||event.target instanceof HTMLSelectElement))throw ErrorPF2e("Unexpected error updating persistent damage data");const diceNumber=Number(pdElements.find(e=>e.dataset.persistentField==="number")?.value)||0,dieFaces=Number(pdElements.find(e=>e.dataset.persistentField==="faces")?.value),baseDamageType=this.item.system.damage.damageType,damageType=pdElements.find(e=>e.dataset.persistentField==="type")?.value||baseDamageType;if(!(typeof diceNumber=="number"&&typeof dieFaces=="number"&&damageType))throw ErrorPF2e("Unexpected error updating persistent damage data");const maybeDiceNumber=Math.trunc(Math.abs(Number(event.target.value)||0));if(event.target.dataset.persistentField==="number"&&maybeDiceNumber===0)await this.item.update({"system.damage.persistent":null});else if(objectHasKey(CONFIG.PF2E.damageTypes,damageType)){const damage={number:Math.trunc(Math.abs(diceNumber))||1,faces:tupleHasValue([4,6,8,10,12],dieFaces)?dieFaces:null,type:damageType};await this.item.update({"system.damage.persistent":damage})}})}async _updateObject(event,formData){const weapon=this.item;formData["system.bonusDamage.value"]||=0,formData["system.splashDamage.value"]||=0,formData["system.potencyRune.value"]||=null,formData["system.strikingRune.value"]||=null;for(const slotNumber of[1,2,3,4])formData[`system.propertyRune${slotNumber}.value`]||=null;formData["system.range"]||=null,"system.damage.dice"in formData&&(formData["system.damage.dice"]=Math.clamped(Number(formData["system.damage.dice"])||0,0,8));const isSpecific=formData["system.specific.value"];return isSpecific!==weapon.isSpecific&&(isSpecific===!0?(formData["system.specific.price"]=this.item.price.value,formData["system.specific.material"]=weapon.material,formData["system.specific.runes"]={potency:formData["system.potencyRune.value"],striking:formData["system.strikingRune.value"]}):isSpecific===!1&&(formData["system.specific.-=price"]=null,formData["system.specific.-=material"]=null,formData["system.specific.-=runes"]=null)),weapon.system.meleeUsage&&!this.item.traits.has("combination")&&(formData["system.-=meleeUsage"]=null),super._updateObject(event,formData)}};__name2(_WeaponSheetPF2e,"WeaponSheetPF2e");let WeaponSheetPF2e=_WeaponSheetPF2e;const _UserConfigPF2e=class extends UserConfig{static{__name(this,"_UserConfigPF2e")}async getData(options){const data=await super.getData(options);return data.actors=data.actors.filter(a=>a.type!=="party"),data}get template(){return"systems/pf2e/templates/user/sheet.hbs"}};__name2(_UserConfigPF2e,"UserConfigPF2e");let UserConfigPF2e=_UserConfigPF2e;const _SceneConfigPF2e=class extends SceneConfig{static{__name(this,"_SceneConfigPF2e")}constructor(){super(...arguments),__privateAdd(this,_activateRBVListeners)}get scene(){return this.document}async _renderInner(data,options){const html=(await super._renderInner(data,options))[0],[tab,panel]=await(async()=>{const hbsPath="systems/pf2e/templates/scene/sheet-partials.hbs",rbvWorldDefault=game.i18n.localize(game.settings.get("pf2e","automation.rulesBasedVision")?"PF2E.SETTINGS.EnabledDisabled.Enabled":"PF2E.SETTINGS.EnabledDisabled.Disabled"),templates=await renderTemplate(hbsPath,{scene:this.scene,rbvWorldDefault});return htmlQueryAll(createHTMLElement("div",{innerHTML:templates}),"template")})();return htmlQuery(html,"nav.tabs")?.append(...tab.content.children),htmlQuery(html,".tab[data-tab=ambience]")?.after(...panel.content.children),$(html)}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=world-rbv-setting]")?.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.automation");if(menu){const options={highlightSetting:"rulesBasedVision"};new menu.type(void 0,options).render(!0)}}),__privateMethod(this,_activateRBVListeners,activateRBVListeners_fn).call(this,html)}async _updateObject(event,formData){const rbvSetting=formData["flags.pf2e.rulesBasedVision"];formData["flags.pf2e.rulesBasedVision"]=rbvSetting==="true"?!0:rbvSetting==="false"?!1:null;const hearingRange=formData["flags.pf2e.hearingRange"];return formData["flags.pf2e.hearingRange"]=typeof hearingRange=="number"?Math.ceil(Math.clamped(hearingRange||5,5,3e3)/5)*5:null,super._updateObject(event,formData)}};_activateRBVListeners=new WeakSet,activateRBVListeners_fn=__name2(function(html){if(!this.document.rulesBasedVision)return;const globalLight=html.querySelector("input[name^=globalLight]"),hasglobalThreshold=html.querySelector("input[name=hasGlobalThreshold]"),globalLightThreshold=html.querySelector("input[name=globalLightThreshold]");if(!(globalLight&&hasglobalThreshold&&globalLightThreshold))throw ErrorPF2e("");globalLight.disabled=!0,hasglobalThreshold.disabled=!0,globalLightThreshold.disabled=!0,globalLightThreshold.nextElementSibling?.classList.add("disabled");for(const input of[globalLight,globalLightThreshold]){const managedBy=document.createElement("span");managedBy.classList.add("managed"),managedBy.innerHTML=" ".concat(game.i18n.localize("PF2E.SETTINGS.Automation.RulesBasedVision.ManagedBy"));const rbvLink=managedBy.querySelector("rbv"),anchor=document.createElement("a");anchor.innerText=rbvLink?.innerHTML??"",anchor.setAttribute("href",""),anchor.addEventListener("click",event=>{event.preventDefault(),event.stopPropagation();const menu=game.settings.menus.get("pf2e.automation");if(!menu)throw ErrorPF2e("Automation Settings application not found");new menu.type().render(!0)}),rbvLink?.replaceWith(anchor),input.closest(".form-group")?.querySelector("p.notes")?.append(managedBy)}if(this.document.darknessSyncedToTime){const darknessInput=html.querySelector("input[name=darkness]");if(darknessInput){darknessInput.disabled=!0,darknessInput.nextElementSibling?.classList.add("disabled");const managedBy=WorldClock.createSyncedMessage();darknessInput.closest(".form-group")?.querySelector("p.notes")?.append(managedBy)}}},"#activateRBVListeners"),__name2(_SceneConfigPF2e,"SceneConfigPF2e");let SceneConfigPF2e=_SceneConfigPF2e;function registerSheets(){const sheetLabel=game.i18n.localize("PF2E.SheetLabel");Scenes.registerSheet("pf2e",SceneConfigPF2e,{makeDefault:!0}),DocumentSheetConfig.registerSheet(TokenDocumentPF2e,"pf2e",TokenConfigPF2e,{makeDefault:!0}),Actors.unregisterSheet("core",ActorSheet);const localizeType=__name2(type=>{const docType=type in CONFIG.PF2E.Actor.documentClasses?"Actor":"Item";return game.i18n.localize(`TYPES.${docType}.${type}`)},"localizeType");Actors.registerSheet("pf2e",CharacterSheetPF2e,{types:["character"],label:game.i18n.format(sheetLabel,{type:localizeType("character")}),makeDefault:!0}),Actors.registerSheet("pf2e",NPCSheetPF2e,{types:["npc"],label:game.i18n.format(sheetLabel,{type:localizeType("npc")}),makeDefault:!0}),Actors.registerSheet("pf2e",SimpleNPCSheet,{types:["npc"],label:"PF2E.Actor.NPC.SimpleSheet",canBeDefault:!1}),Actors.registerSheet("pf2e",HazardSheetPF2e,{types:["hazard"],label:game.i18n.format(sheetLabel,{type:localizeType("hazard")})}),Actors.registerSheet("pf2e",LootSheetPF2e,{types:["loot"],label:game.i18n.format(sheetLabel,{type:localizeType("loot")}),makeDefault:!0}),Actors.registerSheet("pf2e",FamiliarSheetPF2e,{types:["familiar"],label:game.i18n.format(sheetLabel,{type:localizeType("familiar")}),makeDefault:!0}),Actors.registerSheet("pf2e",VehicleSheetPF2e,{types:["vehicle"],label:game.i18n.format(sheetLabel,{type:localizeType("vehicle")}),makeDefault:!0}),Actors.registerSheet("pf2e",PartySheetPF2e,{types:["party"],label:game.i18n.format(sheetLabel,{type:localizeType("party")}),makeDefault:!0}),Items.unregisterSheet("core",ItemSheet);const itemTypes=["condition","lore","spellcastingEntry"];for(const itemType of itemTypes)Items.registerSheet("pf2e",ItemSheetPF2e,{types:[itemType],label:game.i18n.format(sheetLabel,{type:localizeType(itemType)}),makeDefault:!0});const sheetEntries=[["action",ActionSheetPF2e],["affliction",AfflictionSheetPF2e],["ancestry",AncestrySheetPF2e],["armor",ArmorSheetPF2e],["background",BackgroundSheetPF2e],["backpack",ContainerSheetPF2e],["book",BookSheetPF2e],["campaignFeature",CampaignFeatureSheetPF2e],["class",ClassSheetPF2e],["consumable",ConsumableSheetPF2e],["deity",DeitySheetPF2e],["effect",EffectSheetPF2e],["equipment",EquipmentSheetPF2e],["feat",FeatSheetPF2e],["heritage",HeritageSheetPF2e],["kit",KitSheetPF2e],["melee",MeleeSheetPF2e],["spell",SpellSheetPF2e],["treasure",TreasureSheetPF2e],["weapon",WeaponSheetPF2e]];for(const[type,Sheet]of sheetEntries)Items.registerSheet("pf2e",Sheet,{types:[type],label:game.i18n.format(sheetLabel,{type:localizeType(type)}),makeDefault:!0});for(const itemType of PHYSICAL_ITEM_TYPES)sheetEntries.some(([type,_sheet])=>itemType===type)||Items.registerSheet("pf2e",PhysicalItemSheetPF2e,{types:[itemType],label:game.i18n.format(sheetLabel,{type:localizeType(itemType)}),makeDefault:!0});Journal.unregisterSheet("core",JournalSheet),Journal.registerSheet("pf2e",JournalSheetPF2e,{label:()=>game.i18n.format("SHEETS.DefaultDocumentSheet",{document:game.i18n.localize("DOCUMENT.JournalEntry")}),makeDefault:!0}),DocumentSheetConfig.unregisterSheet(JournalEntryPage,"core",JournalTextTinyMCESheet),DocumentSheetConfig.registerSheet(JournalEntryPage,"pf2e",JournalTextTinyMCESheetPF2e,{types:["text"],label:game.i18n.localize("EDITOR.TinyMCE")}),Users.unregisterSheet("core",UserConfig),Users.registerSheet("pf2e",UserConfigPF2e,{makeDefault:!0,label:()=>game.i18n.format("SHEETS.DefaultDocumentSheet",{document:game.i18n.localize("DOCUMENT.User")})})}__name(registerSheets,"registerSheets"),__name2(registerSheets,"registerSheets");const Setup={listen:()=>{Hooks.once("setup",()=>{registerSheets(),game.settings.settings.get("core.chatBubblesPan").default=!1,game.settings.settings.get("core.notesDisplayToggle").default=!0;const defaultTokenSettingsDefaults=game.settings.settings.get("core.defaultToken").default;defaultTokenSettingsDefaults.displayName=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,defaultTokenSettingsDefaults.displayBars=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER})}},TargetToken={listen:()=>{Hooks.on("targetToken",(user,token)=>{const tokenDocument=token.document;ui.combat.refreshTargetDisplay(tokenDocument);const actors=getSelectedOrOwnActors();if(actors.length===1&&tokenDocument.object){const actorToken=actors[0].getActiveTokens(!1,!1).shift();canvas.tokens.highlightObjects&&user===game.user&&actorToken?.flankingHighlight.draw()}})}},UpdateWorldTime={listen:()=>{Hooks.on("updateWorldTime",async(_total,diff)=>{game.combat?.started||game.pf2e.effectTracker.refresh({resetItemData:!0});const worldClock=game.pf2e.worldClock;setTimeout(()=>worldClock.render(!1),1),await worldClock.animateDarkness(diff)})}},HooksPF2e={listen(){const listeners=[Load,BabeleReady,CanvasInit,CanvasReady,CloseCombatTrackerConfig,CloseWorldClockSettings,DiceSoNiceReady,DropCanvasData,GetSceneControlButtons,Init,LightingRefresh,Ready,RenderChatPopout,RenderCombatTrackerConfig,RenderDialog,RenderJournalPageSheet,RenderJournalTextPageSheet,RenderSettings,RenderTokenHUD,Setup,TargetToken,UpdateWorldTime];for(const Listener of listeners)Listener.listen()}},main="";HooksPF2e.listen();
+ `})&&(await this.packLoader.hardReset(this.loadedPacksAll()),await game.settings.set("pf2e","compendiumBrowserSources",this.packLoader.sourcesSettings),await this.#resetInitializedTabs(),this.render(!0))});return}const currentTab=this.tabs[activeTabName],controlArea=html.querySelector("div.control-area");if(!controlArea)return;const search=controlArea.querySelector("input[name=textFilter]");search&&search.addEventListener("input",()=>{currentTab.filterData.search.text=search.value,this.#clearScrollLimit(),this.#renderResultList({replace:!0})});const sortContainer=controlArea.querySelector("div.sortcontainer");if(sortContainer){const order=sortContainer.querySelector("select.order");order&&order.addEventListener("change",()=>{currentTab.filterData.order.by=order.value??"name",this.#clearScrollLimit(!0)});const directionAnchor=sortContainer.querySelector("a.direction");directionAnchor&&directionAnchor.addEventListener("click",()=>{const direction=directionAnchor.dataset.direction??"asc";currentTab.filterData.order.direction=direction==="asc"?"desc":"asc",this.#clearScrollLimit(!0)})}if(activeTabName==="spell"){const timeFilter=controlArea.querySelector("select[name=timefilter]");timeFilter&&timeFilter.addEventListener("change",()=>{if(!currentTab.isOfType("spell"))return;const filterData=currentTab.filterData;filterData.selects?.timefilter&&(filterData.selects.timefilter.selected=timeFilter.value,this.#clearScrollLimit(!0))})}controlArea.querySelector("button.clear-filters")?.addEventListener("click",()=>{this.#resetFilters(),this.#clearScrollLimit(!0)}),htmlQuery(html,"[data-action=create-roll-table]")?.addEventListener("click",()=>currentTab.createRollTable()),htmlQuery(html,"[data-action=add-to-roll-table]")?.addEventListener("click",async()=>{game.tables.contents.length&¤tTab.addToRollTable()});const filterContainers=controlArea.querySelectorAll("div.filtercontainer");for(const container of Array.from(filterContainers)){const{filterType,filterName}=container.dataset;container.querySelector("button[data-action=clear-filter]")?.addEventListener("click",event2=>{switch(event2.stopImmediatePropagation(),filterType){case"checkboxes":{const checkboxes=currentTab.filterData.checkboxes;if(objectHasKey(checkboxes,filterName)){for(const option of Object.values(checkboxes[filterName].options))option.selected=!1;checkboxes[filterName].selected=[],this.render(!0)}break}case"ranges":if(currentTab.isOfType("equipment")){const ranges=currentTab.filterData.ranges;objectHasKey(ranges,filterName)&&(ranges[filterName].values=currentTab.defaultFilterData.ranges[filterName].values,ranges[filterName].changed=!1,this.render(!0))}}});const title=container.querySelector("div.title");if(title?.addEventListener("click",()=>{const toggleFilter=__name2(filter2=>{filter2.isExpanded=!filter2.isExpanded;const contentElement=title.nextElementSibling;contentElement instanceof HTMLElement&&(filter2.isExpanded?contentElement.style.display="":contentElement.style.display="none")},"toggleFilter");switch(filterType){case"checkboxes":{objectHasKey(currentTab.filterData.checkboxes,filterName)&&toggleFilter(currentTab.filterData.checkboxes[filterName]);break}case"ranges":{if(!currentTab.isOfType("equipment"))return;objectHasKey(currentTab.filterData.ranges,filterName)&&toggleFilter(currentTab.filterData.ranges[filterName]);break}case"sliders":{if(!currentTab.isOfType("bestiary","equipment","feat","campaignFeature","hazard"))return;objectHasKey(currentTab.filterData.sliders,filterName)&&toggleFilter(currentTab.filterData.sliders[filterName]);break}}}),filterType==="checkboxes"&&container.querySelectorAll("input[type=checkbox]").forEach(checkboxElement=>{checkboxElement.addEventListener("click",()=>{if(objectHasKey(currentTab.filterData.checkboxes,filterName)){const optionName=checkboxElement.name,checkbox=currentTab.filterData.checkboxes[filterName],option=checkbox.options[optionName];option.selected=!option.selected,option.selected?checkbox.selected.push(optionName):checkbox.selected=checkbox.selected.filter(name2=>name2!==optionName),this.#clearScrollLimit(!0)}})}),filterType==="ranges"&&container.querySelectorAll("input[name*=Bound]").forEach(range2=>{range2.addEventListener("keyup",event2=>{if(!currentTab.isOfType("equipment")||event2.key!=="Enter")return;const ranges=currentTab.filterData.ranges;if(ranges&&objectHasKey(ranges,filterName)){const range22=ranges[filterName],lowerBound=container.querySelector("input[name*=lowerBound]")?.value??"",upperBound=container.querySelector("input[name*=upperBound]")?.value??"",values=currentTab.parseRangeFilterInput(filterName,lowerBound,upperBound);range22.values=values,range22.changed=!0,this.#clearScrollLimit(!0)}})}),filterType==="multiselects"){const multiselects=currentTab.filterData.multiselects;if(!multiselects)continue;if(objectHasKey(multiselects,filterName)){const multiselect=container.querySelector(`input[name=${filterName}][data-tagify-select]`);if(!multiselect)continue;const data=multiselects[filterName],tagify2=new Tagify(multiselect,{enforceWhitelist:!0,keepInvalidTags:!1,editTags:!1,tagTextProp:"label",dropdown:{enabled:0,fuzzySearch:!1,mapValueTo:"label",maxItems:data.options.length,searchKeys:["label"]},whitelist:data.options,transformTag(tagData){data.selected.find(s=>s.value===tagData.value)?.not&&(tagData.class="conjunction-not")}});tagify2.on("click",event2=>{const target=event2.detail.event.target;if(!target)return;if(htmlClosest(target,"[data-action]")?.dataset?.action==="toggle-not"){const value=event2.detail.data.value,selected=data.selected.find(s=>s.value===value);selected&&(selected.not=!selected.not,this.render())}}),tagify2.on("change",event2=>{const selections=JSON.parse(event2.detail.value||"[]");Array.isArray(selections)&&selections.every(s=>isObject(s)&&typeof s.value=="string")&&(data.selected=selections,this.render())});for(const element of htmlQueryAll(container,`input[name=${filterName}-filter-conjunction]`))element.addEventListener("change",()=>{const value=element.value;(value==="and"||value==="or")&&(data.conjunction=value,this.render())});for(const tag of htmlQueryAll(container,"tag")){const icon=fontAwesomeIcon("ban",{style:"solid"});icon.classList.add("fa-2xs");const notButton=createHTMLElement("a",{classes:["conjunction-not-button"],children:[icon],dataset:{action:"toggle-not"}});tag.appendChild(notButton)}}}if(filterType==="sliders"){if(!currentTab.isOfType("bestiary","campaignFeature","equipment","feat","hazard"))continue;const sliders=currentTab.filterData.sliders;if(!sliders)continue;if(objectHasKey(sliders,filterName)){const sliderElement=container.querySelector(`div.slider-${filterName}`);if(!sliderElement)continue;const data=sliders[filterName];noUiSlider.create(sliderElement,{range:{min:data.values.lowerLimit,max:data.values.upperLimit},start:[data.values.min,data.values.max],tooltips:{to(value){return Math.floor(value).toString()}},connect:[!1,!0,!1],behaviour:"snap",step:data.values.step}).on("change",values=>{const[min,max]=values.map(value=>Number(value));data.values.min=min,data.values.max=max;const $minLabel=$html.find(`label.${name}-min-label`),$maxLabel=$html.find(`label.${name}-max-label`);$minLabel.text(min),$maxLabel.text(max),this.#clearScrollLimit(!0)}),sliderElement.querySelectorAll(".noUi-handle").forEach(element=>{element.classList.add("handle")}),sliderElement.querySelectorAll(".noUi-connect").forEach(element=>{element.classList.add("range_selected")})}}}const list=html.querySelector(".tab.active ul.item-list");list&&(list.addEventListener("scroll",()=>{if(list.scrollTop+list.clientHeight>=list.scrollHeight-5){const currentValue=currentTab.scrollLimit,maxValue=currentTab.totalItemCount??0;currentValue a");nameAnchor&&nameAnchor.addEventListener("click",async()=>{const document2=await fromUuid(entryUuid);document2?.sheet&&document2.sheet.render(!0)}),this.activeTab==="equipment"&&(liElement.querySelector("a[data-action=take-item]")?.addEventListener("click",()=>{this.#takePhysicalItem(entryUuid)}),liElement.querySelector("a[data-action=buy-item]")?.addEventListener("click",()=>{this.#buyPhysicalItem(entryUuid)}))}}async#takePhysicalItem(uuid){const actors=getSelectedOrOwnActors(["character","loot","npc"]),item=await this.#getPhysicalItem(uuid);if(actors.length===0){ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.NoTokenSelected"));return}for(const actor of actors)await actor.inventory.add(item,{stack:!0});actors.length===1&&game.user.character&&actors[0]===game.user.character?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.AddedItemToCharacter",{item:item.name,character:game.user.character.name})):ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.AddedItem",{item:item.name}))}async#buyPhysicalItem(uuid){const actors=getSelectedOrOwnActors(["character","loot","npc"]),item=await this.#getPhysicalItem(uuid);if(actors.length===0){ui.notifications.error(game.i18n.format("PF2E.ErrorMessage.NoTokenSelected"));return}let purchasesSucceeded=0;for(const actor of actors)await actor.inventory.removeCoins(item.price.value)&&(purchasesSucceeded=purchasesSucceeded+1,await actor.inventory.add(item,{stack:!0}));actors.length===1?purchasesSucceeded===1?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.BoughtItemWithCharacter",{item:item.name,character:actors[0].name})):ui.notifications.warn(game.i18n.format("PF2E.CompendiumBrowser.FailedToBuyItemWithCharacter",{item:item.name,character:actors[0].name})):purchasesSucceeded===actors.length?ui.notifications.info(game.i18n.format("PF2E.CompendiumBrowser.BoughtItemWithAllCharacters",{item:item.name})):ui.notifications.warn(game.i18n.format("PF2E.CompendiumBrowser.FailedToBuyItemWithSomeCharacters",{item:item.name}))}async#getPhysicalItem(uuid){const item=await fromUuid(uuid);if(!(item instanceof PhysicalItemPF2e||item instanceof KitPF2e))throw ErrorPF2e("Unexpected failure retrieving compendium item");return item}_canDragStart(){return!0}_canDragDrop(){return!0}_onDragStart(event2){this.element.animate({opacity:.125},250);const item=$(event2.currentTarget)[0];event2.dataTransfer.setData("text/plain",JSON.stringify({type:item.dataset.type,uuid:item.dataset.entryUuid})),event2.dataTransfer.setData("from-browser","true"),item.addEventListener("dragend",()=>{window.setTimeout(()=>{this.element.animate({opacity:1},250,()=>{this.element.css({pointerEvents:""})})},500)},{once:!0})}_onDragOver(event2){super._onDragOver(event2),event2.dataTransfer.types.includes("from-browser")&&this.element.css({pointerEvents:"none"})}getData(){const activeTab=this.activeTab,tab=objectHasKey(this.tabs,activeTab)?this.tabs[activeTab]:null,settings={settings:this.settings,sources:this.packLoader.sourcesSettings};return{user:game.user,[activeTab]:activeTab==="settings"?settings:{filterData:tab?.filterData},scrollLimit:tab?.scrollLimit,showCampaign:game.settings.get("pf2e","campaignType")!=="none"}}#resetFilters(){const activeTab=this.activeTab;activeTab!=="settings"&&this.tabs[activeTab].resetFilters()}#clearScrollLimit(render=!1){const tab=this.activeTab;if(tab==="settings")return;const list=htmlQuery(this.element[0],".tab.active ul.item-list");list&&(list.scrollTop=0,this.tabs[tab].scrollLimit=100,render&&this.render())}}class EffectsPanel extends Application{static{__name(this,"EffectsPanel")}static{__name2(this,"EffectsPanel")}get token(){return canvas.tokens.controlled.at(0)?.document??null}get actor(){return this.token?.actor??game.user?.character??null}refresh=foundry.utils.debounce(this.render,100);static get defaultOptions(){return{...super.defaultOptions,id:"pf2e-effects-panel",popOut:!1,template:"systems/pf2e/templates/system/effects-panel.hbs"}}async getData(options){const{actor}=this;if(!actor||!game.user.settings.showEffectPanel)return{afflictions:[],conditions:[],effects:[],descriptions:{afflictions:[],conditions:[],effects:[]},actor:null,user:{isGM:!1}};const effects=actor.itemTypes.effect.map(effect=>{const duration=effect.totalDuration,{system}=effect;if(duration===1/0)system.duration.unit==="encounter"?system.remaining=system.expired?game.i18n.localize("PF2E.EffectPanel.Expired"):game.i18n.localize("PF2E.EffectPanel.UntilEncounterEnds"):system.remaining=game.i18n.localize("PF2E.EffectPanel.UnlimitedDuration");else{const duration2=effect.remainingDuration;system.remaining=system.expired?game.i18n.localize("PF2E.EffectPanel.Expired"):this.#getRemainingDurationLabel(duration2.remaining,system.start.initiative??0,system.duration.expiry)}return effect})??[],conditions=actor.conditions.active,afflictions=actor.itemTypes.affliction,descriptions={afflictions:await this.#getEnrichedDescriptions(afflictions),conditions:await this.#getEnrichedDescriptions(conditions),effects:await this.#getEnrichedDescriptions(effects)};return{...await super.getData(options),afflictions,conditions,descriptions,effects,actor,user:{isGM:game.user.isGM}}}activateListeners($html){super.activateListeners($html);const html=$html[0];InlineRollLinks.listen(html,this.actor);for(const effectEl of htmlQueryAll(html,".effect-item[data-item-id]")){const{actor}=this,itemId=effectEl.dataset.itemId??"",effect=actor?.conditions.get(itemId)??actor?.items.get(itemId);if(!actor||!effect)continue;const iconElem=effectEl.querySelector(":scope > .icon");iconElem?.addEventListener("click",async()=>{actor&&effect.isOfType("condition")&&effect.slug==="persistent-damage"?await effect.onEndTurn({token:this.token}):effect instanceof AbstractEffectPF2e&&await effect.increase()}),iconElem?.addEventListener("contextmenu",async()=>{effect instanceof AbstractEffectPF2e?await effect.decrease():this.refresh()}),effectEl.querySelector("[data-action=recover-persistent-damage]")?.addEventListener("click",()=>{effect.isOfType("condition")&&effect.rollRecovery()}),effectEl.querySelector("[data-action=edit]")?.addEventListener("click",()=>{effect.isOfType("condition")&&effect.slug==="persistent-damage"?new PersistentDamageDialog(actor,{editing:effect.id}).render(!0):effect.sheet.render(!0)}),effectEl.querySelector("[data-action=send-to-chat]")?.addEventListener("click",()=>{effect.toMessage()});const valueContainer=htmlQuery(iconElem,".value"),textElement=htmlQuery(valueContainer,"strong");if(valueContainer&&textElement){const parentWidth=valueContainer.clientWidth,scale=textElement.clientWidth?Math.clamped(parentWidth/textElement.clientWidth,.75,1):1;scale<1&&(valueContainer.style.transformOrigin="left",valueContainer.style.transform=`scaleX(${scale})`,valueContainer.style.width=`${1/scale*100+1}%`),textElement.style.display="inline"}}}#getRemainingDurationLabel(remaining,initiative,expiry){if(remaining>=63072e3)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleYears",{years:Math.floor(remaining/31536e3)});if(remaining>=31536e3)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleYear");if(remaining>=1209600)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleWeeks",{weeks:Math.floor(remaining/604800)});if(remaining>604800)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleWeek");if(remaining>=172800)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleDays",{days:Math.floor(remaining/86400)});if(remaining>7200)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleHours",{hours:Math.floor(remaining/3600)});if(remaining>120)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleMinutes",{minutes:Math.floor(remaining/60)});if(remaining>=12)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleRounds",{rounds:Math.floor(remaining/6)});if(remaining>=6)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleRound");if(remaining>=2)return game.i18n.format("PF2E.EffectPanel.RemainingDuration.MultipleSeconds",{seconds:remaining});if(remaining===1)return game.i18n.localize("PF2E.EffectPanel.RemainingDuration.SingleSecond");{const key=expiry==="turn-end"?"PF2E.EffectPanel.RemainingDuration.ZeroRoundsExpireTurnEnd":"PF2E.EffectPanel.RemainingDuration.ZeroRoundsExpireTurnStart";return game.i18n.format(key,{initiative})}}async#getEnrichedDescriptions(effects){return await Promise.all(effects.map(async effect=>{const rollData={actor:"actor"in effect?effect.actor:null,item:effect};return await TextEditor.enrichHTML(effect.description,{async:!0,rollData})}))}}class LicenseViewer extends Application{static{__name(this,"LicenseViewer")}static{__name2(this,"LicenseViewer")}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{id:"license-viewer",title:game.i18n.localize("PF2E.LicenseViewer.Label"),template:"systems/pf2e/templates/packs/license-viewer.hbs",width:500,height:600,resizable:!0,tabs:[{navSelector:"nav",contentSelector:"section.content",initial:"landing-page"}]})}}const debouncedRender=foundry.utils.debounce(()=>{canvas.tokens.hud.render()},20);class StatusEffects{static{__name(this,"StatusEffects")}static{__name2(this,"StatusEffects")}static#lastCombatantToken=null;static#ICON_THEME_DIRS={default:"systems/pf2e/icons/conditions/",blackWhite:"systems/pf2e/icons/conditions-2/"};static#conditionSummaries=null;static initialize(){const iconTheme=game.settings.get("pf2e","statusEffectType");CONFIG.controlIcons.defeated=game.settings.get("pf2e","deathIcon"),CONFIG.PF2E.statusEffects.lastIconTheme=iconTheme,CONFIG.PF2E.statusEffects.iconDir=this.#ICON_THEME_DIRS[iconTheme],this.#updateStatusIcons()}static reset(){CONFIG.controlIcons.defeated=game.settings.get("pf2e","deathIcon"),this.#updateStatusIcons(),this.refresh()}static get conditions(){return this.#conditionSummaries??=mapToObj(Array.from(CONDITION_SLUGS),s=>[s,{name:game.i18n.localize(`PF2E.condition.${s}.name`),rules:game.i18n.localize(`PF2E.condition.${s}.rules`),summary:game.i18n.localize(`PF2E.condition.${s}.summary`)}])}static async migrateStatusEffectUrls(chosenSetting){console.debug("PF2e System | Changing status effect icon types");const iconDir=this.#ICON_THEME_DIRS[chosenSetting];if(CONFIG.PF2E.statusEffects.iconDir=iconDir,CONFIG.PF2E.statusEffects.lastIconTheme=chosenSetting,this.#updateStatusIcons(),await resetActors(),canvas.ready)for(const token of canvas.tokens.placeables)token.drawEffects()}static#activateListeners(html){for(const control of htmlQueryAll(html,".effect-control"))control.addEventListener("click",event2=>{this.#setStatusValue(control,event2)}),control.addEventListener("contextmenu",event2=>{this.#setStatusValue(control,event2)}),control.addEventListener("mouseover",()=>{this.#showStatusLabel(control)}),control.addEventListener("mouseout",()=>{this.#showStatusLabel(control)})}static#updateStatusIcons(){const directory=game.settings.get("pf2e","statusEffectType")==="default"?"conditions":"conditions-2";CONFIG.statusEffects=Object.entries(CONFIG.PF2E.statusEffects.conditions).map(([id,label])=>({id,label,icon:`systems/pf2e/icons/${directory}/${id}.webp`})),CONFIG.statusEffects.push({id:"dead",label:"PF2E.Actor.Dead",icon:CONFIG.controlIcons.defeated})}static async onRenderTokenHUD(html,tokenData){const token=canvas.tokens.get(tokenData._id??"");if(!token)return;const iconGrid=html.querySelector(".status-effects");if(!iconGrid)throw ErrorPF2e("Unexpected error retrieving status effects grid");const affectingConditions=token.actor?.conditions.active.filter(c=>c.isInHUD)??[],titleBar=document.createElement("div");titleBar.className="title-bar",iconGrid.append(titleBar);const statusIcons=iconGrid.querySelectorAll(".effect-control");for(const icon of statusIcons){const picture=document.createElement("picture");picture.classList.add("effect-control"),picture.dataset.statusId=icon.dataset.statusId,picture.title=icon.title;const iconSrc=icon.getAttribute("src");picture.setAttribute("src",iconSrc);const newIcon=document.createElement("img");newIcon.src=iconSrc,picture.append(newIcon),icon.replaceWith(picture);const slug=picture.dataset.statusId??"",actorType=token.actor?.type??"";(slug==="hidden"&&["loot","vehicle"].includes(actorType)||slug==="broken"&&!["loot","vehicle"].includes(actorType))&&(picture.style.display="none");const affecting=affectingConditions.filter(c=>c.slug===slug);if((affecting.length>0||iconSrc===token.document.overlayEffect)&&picture.classList.add("active"),affecting.length>0){const isOverridden=affecting.every(c=>c.system.references.overriddenBy.length>0),isLocked=affecting.every(c=>c.isLocked),hasValue=affecting.some(c=>c.value);if(isOverridden){picture.classList.add("overridden");const badge=fontAwesomeIcon("angle-double-down");badge.classList.add("badge"),picture.append(badge)}else if(isLocked){picture.classList.add("locked");const badge=fontAwesomeIcon("lock");badge.classList.add("badge"),picture.append(badge)}else if(hasValue){picture.classList.add("valued");const badge=document.createElement("i");badge.classList.add("badge");const value=Math.max(...affecting.map(c=>c.value??1));badge.innerText=value.toString(),picture.append(badge)}}}this.#activateListeners(iconGrid)}static onUpdateEncounter(encounter){if(!(game.user.isGM&&game.settings.get("pf2e","statusEffectShowCombatMessage")))return;if(!encounter.started){this.#lastCombatantToken=null;return}const{combatant}=encounter,token=combatant?.token;combatant&&token&&token.id!==this.#lastCombatantToken&&typeof combatant.initiative=="number"&&!combatant.defeated&&(this.#lastCombatantToken=token.id,this.#createChatMessage(token,combatant.hidden))}static#showStatusLabel(control){const titleBar=control.closest(".status-effects")?.querySelector(".title-bar");titleBar&&control.title&&(titleBar.innerText=control.title,titleBar.classList.toggle("active"))}static async#setStatusValue(control,event2){event2.preventDefault(),event2.stopPropagation();const slug=control.dataset.statusId;if(!setHasElement(CONDITION_SLUGS,slug)&&slug!=="dead")return;const tokensAndActors=uniqBy(compact(canvas.tokens.controlled.map(t=>t.actor?[t,t.actor]:null)),([,a])=>a);for(const[token,actor]of tokensAndActors){if(slug==="persistent-damage"){await new PersistentDamageDialog(actor).render(!0);continue}const condition=actor.conditions.bySlug(slug,{active:!0,temporary:!1}).find(c=>c.isInHUD&&!c.system.references.parent);if(event2.type==="click")typeof condition?.value=="number"?game.pf2e.ConditionManager.updateConditionValue(condition.id,token,condition.value+1):objectHasKey(CONFIG.PF2E.conditionTypes,slug)?actor.increaseCondition(slug):this.#toggleStatus(token,control,event2);else if(event2.type==="contextmenu")if(event2.ctrlKey&&slug!=="dead"){const conditionIds=actor.conditions.bySlug(slug,{temporary:!1}).map(c=>c.id);actor.deleteEmbeddedDocuments("Item",conditionIds)}else condition?.value?game.pf2e.ConditionManager.updateConditionValue(condition.id,token,condition.value-1):this.#toggleStatus(token,control,event2)}}static async#toggleStatus(token,control,event2){const{actor}=token;if(!actor)return;const slug=control.dataset.statusId??"";if(!setHasElement(CONDITION_SLUGS,slug)&&slug!=="dead")return;const iconSrc=control.querySelector("img")?.getAttribute("src"),affecting=actor?.conditions.bySlug(slug,{active:!0,temporary:!1}).find(c=>!c.system.references.parent),conditionIds=[];if(event2.type==="click"&&!affecting)if(objectHasKey(CONFIG.PF2E.conditionTypes,slug)){const newCondition=game.pf2e.ConditionManager.getCondition(slug).toObject();await token.actor?.createEmbeddedDocuments("Item",[newCondition])}else iconSrc&&(event2.shiftKey||control.dataset.statusId==="dead")&&await token.toggleEffect(iconSrc,{overlay:!0,active:!0});else event2.type==="contextmenu"&&(affecting&&conditionIds.push(affecting.id),conditionIds.length>0?await token.actor?.deleteEmbeddedDocuments("Item",conditionIds):token.document.overlayEffect===iconSrc&&await token.document.update({overlayEffect:""}))}static async#createChatMessage(token,whisper=!1){if(!token?.actor)return null;const conditions=await Promise.all(token.actor.conditions.active.map(async c=>({...pick(c,["name","img"]),description:await TextEditor.enrichHTML(c.description,{async:!0})})));if(conditions.length===0)return null;const content=await renderTemplate("systems/pf2e/templates/chat/participant-conditions.hbs",{conditions}),messageSource={user:game.user.id,speaker:{...ChatMessagePF2e.getSpeaker({token,actor:token.actor}),alias:game.i18n.format("PF2E.StatusEffects",{name:token.name})},content,type:CONST.CHAT_MESSAGE_TYPES.OTHER};return(!token.actor?.hasPlayerOwner&&game.settings.get("pf2e","metagame_secretCondition")||whisper)&&(messageSource.whisper=ChatMessage.getWhisperRecipients("GM").map(u=>u.id)),ChatMessagePF2e.create(messageSource)}static refresh(){canvas.ready&&canvas.tokens.hud.rendered&&debouncedRender()}}async function remigrate(versionRange){if(!game.ready){ui.notifications.warn("PF2E.Migrations.WorldNotReady",{localize:!0});return}if(game.user.role!==CONST.USER_ROLES.GAMEMASTER){ui.notifications.error("PF2E.Migrations.OnlyGMCanUse",{localize:!0});return}const migrations=MigrationList.constructRange(versionRange.from,versionRange.to);if(migrations.length===0||versionRange.from({description:traitDescriptions2[trait],label:traitLabels[trait]??trait,slug:trait})),content=await renderTemplate("/systems/pf2e/templates/actors/actions/base/chat-message-content.hbs",{description,glyph:this.glyph,name:name2,traits});return ChatMessagePF2e.create({blind:options?.blind,content,whisper:options?.whisper})}}class BaseAction{static{__name(this,"BaseAction")}static{__name2(this,"BaseAction")}cost;description;img;name;slug;traits;#variants;constructor(data){this.cost=data.cost,this.description=data.description,this.img=data.img,this.name=data.name.trim(),this.slug=data.slug?.trim()||sluggify(this.name),this.traits=data.traits??[],this.#variants=Array.isArray(data.variants)?data.variants.map(this.toActionVariant.bind(this)):data.variants?[this.toActionVariant(data.variants)]:[]}get glyph(){if(this.#variants.length===1)return this.#variants[0].glyph;const numbers=this.#variants.filter(variant=>typeof variant.cost=="number").sort();if(this.#variants.length===numbers.length&&numbers.length>1){const first=numbers.shift()?.cost,last=numbers.pop()?.cost,key=first===last?String(first):first===2||last===2?`${first} or ${last}`:`${first} to ${last}`;return getActionGlyph(key)}return getActionGlyph(this.cost??"")}get variants(){const variants=this.#variants.map(variant=>[variant.slug,variant]);return new Collection(variants)}async getDefaultVariant(options){const variants=this.variants;if(options?.variant&&!variants.size){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.None",{action:this.name,variant:options.variant});return Promise.reject(reason)}if(!options?.variant&&variants.size>1){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.Multiple",{action:this.name});return Promise.reject(reason)}const variant=variants.get(options?.variant??"");if(options?.variant&&!variant){const reason=game.i18n.format("PF2E.ActionsWarning.Variants.Nonexisting",{action:this.name,variant:options.variant});return Promise.reject(reason)}return variant??this.toActionVariant()}async toMessage(options){return((options?.variant?await this.getDefaultVariant(options):void 0)??this.toActionVariant()).toMessage(options)}async use(options){return(await this.getDefaultVariant(options)??this.toActionVariant()).use(options)}}async function toEffectItem(effect){return typeof effect=="string"?await fromUuid(effect):effect}__name(toEffectItem,"toEffectItem"),__name2(toEffectItem,"toEffectItem");class SimpleActionVariant extends BaseActionVariant{static{__name(this,"SimpleActionVariant")}static{__name2(this,"SimpleActionVariant")}#action;#effect;constructor(action2,data){super(action2,data),this.#action=action2,this.#effect=data?.effect??action2.effect}get effect(){return this.#effect??this.#action.effect}async use(options={}){const actors=[];if(Array.isArray(options.actors)?actors.push(...options.actors):options.actors?actors.push(options.actors):actors.push(...getSelectedOrOwnActors()),actors.length===0)throw new Error(game.i18n.localize("PF2E.ActionsWarning.NoActor"));const traitLabels=CONFIG.PF2E.actionTraits,traitDescriptions2=CONFIG.PF2E.traitsDescriptions,traits=this.traits.concat(options.traits??[]).map(trait=>({description:traitDescriptions2[trait],label:traitLabels[trait]??trait,slug:trait})),effect=options?.effect===!1?void 0:await toEffectItem(options?.effect??this.effect),name2=this.name?`${game.i18n.localize(this.#action.name)} - ${game.i18n.localize(this.name)}`:game.i18n.localize(this.#action.name),flavor=await renderTemplate("systems/pf2e/templates/actors/actions/simple/chat-message-flavor.hbs",{effect,glyph:this.glyph,name:name2,traits}),results=[];for(const actor of actors){const message=await ChatMessage.create({flavor,speaker:ChatMessage.getSpeaker({actor})}),item=effect&&actor.isOwner?(await actor.createEmbeddedDocuments("Item",[effect.toObject()]))[0]:void 0;results.push({actor,effect:item,message})}return results}}class SimpleAction extends BaseAction{static{__name(this,"SimpleAction")}static{__name2(this,"SimpleAction")}effect;constructor(data){super(data),this.effect=data.effect}toActionVariant(data){return new SimpleActionVariant(this,data)}}function toRollNoteSource(data){return data.selector??="",data}__name(toRollNoteSource,"toRollNoteSource"),__name2(toRollNoteSource,"toRollNoteSource");class SingleCheckActionVariant extends BaseActionVariant{static{__name(this,"SingleCheckActionVariant")}static{__name2(this,"SingleCheckActionVariant")}#action;#difficultyClass;#modifiers;#notes;#rollOptions;#statistic;constructor(action2,data){super(action2,data),this.#action=action2,data&&(this.#difficultyClass=data.difficultyClass,this.#modifiers=data?.modifiers,this.#notes=data.notes?data.notes.map(toRollNoteSource):void 0,this.#rollOptions=data.rollOptions,this.#statistic=data.statistic)}get difficultyClass(){return this.#difficultyClass??this.#action.difficultyClass}get modifiers(){return this.#modifiers??this.#action.modifiers}get notes(){return this.#notes??this.#action.notes}get rollOptions(){return this.#rollOptions??this.#action.rollOptions}get statistic(){return this.#statistic??this.#action.statistic}async use(options={}){const modifiers=this.modifiers.map(raw=>new ModifierPF2e(raw)).concat(options.modifiers??[]);if(options.multipleAttackPenalty){const map2=options.multipleAttackPenalty,modifier=map2>0?Math.min(2,map2)*-5:map2;modifiers.push(new ModifierPF2e({label:"PF2E.MultipleAttackPenalty",modifier}))}const notes=this.notes.concat(options.notes??[]).map(toRollNoteSource).map(note=>new RollNotePF2e(note)),rollOptions=this.rollOptions.concat(options.rollOptions??[]),slug=options.statistic?.trim()||this.statistic,title=this.name?`${game.i18n.localize(this.#action.name)} - ${game.i18n.localize(this.name)}`:game.i18n.localize(this.#action.name),results=[],difficultyClass=setHasElement(DC_SLUGS,options.difficultyClass)||isObject(options.difficultyClass)&&typeof options.difficultyClass.value=="number"?options.difficultyClass:this.difficultyClass;return await ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,title,actionGlyph:getActionGlyph(this.cost??null),callback:result=>results.push(result),checkContext:opts=>this.checkContext(opts,{modifiers,rollOptions,slug}),difficultyClass,event:options.event,extraNotes:selector=>notes.map(note=>(note.selector||=selector,note)),traits:this.traits.concat(options?.traits??[])}),results}checkContext(opts,data){return ActionMacroHelpers.defaultCheckContext(opts,data)}}class SingleCheckAction extends BaseAction{static{__name(this,"SingleCheckAction")}static{__name2(this,"SingleCheckAction")}difficultyClass;modifiers;notes;rollOptions;statistic;constructor(data){super(data),this.difficultyClass=data.difficultyClass,this.modifiers=data.modifiers??[],this.notes=(data.notes??[]).map(toRollNoteSource),this.rollOptions=data.rollOptions??[],this.statistic=data.statistic}toActionVariant(data){return new SingleCheckActionVariant(this,data)}}const PREFIX$l="PF2E.Actions.Balance";function balance(options){const slug=options?.skill??"acrobatics",rollOptions=["action:balance"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$l}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Balance","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(balance,"balance"),__name2(balance,"balance");const action$y=new SingleCheckAction({cost:1,description:`${PREFIX$l}.Description`,name:`${PREFIX$l}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$l}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$l}.Notes.success`},{outcome:["failure"],text:`${PREFIX$l}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$l}.Notes.criticalFailure`}],rollOptions:["action:balance"],slug:"balance",statistic:"acrobatics",traits:["move"]}),PREFIX$k="PF2E.Actions.ManeuverInFlight";async function maneuverInFlight(options){const slug=options?.skill??"acrobatics",rollOptions=["action:maneuver-in-flight"],modifiers=options?.modifiers;return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$k}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$k}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$k,"failure"),ActionMacroHelpers.note(selector,PREFIX$k,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(maneuverInFlight,"maneuverInFlight"),__name2(maneuverInFlight,"maneuverInFlight");const action$x=new SingleCheckAction({cost:1,description:`${PREFIX$k}.Description`,name:`${PREFIX$k}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$k}.Notes.success`},{outcome:["failure"],text:`${PREFIX$k}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$k}.Notes.criticalFailure`}],rollOptions:["action:maneuver-in-flight"],slug:"maneuver-in-flight",statistic:"acrobatics",traits:["move"]}),PREFIX$j="PF2E.Actions.Squeeze";function squeeze(options){const slug=options?.skill??"acrobatics",rollOptions=["action:squeeze"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$j}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Squeeze","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(squeeze,"squeeze"),__name2(squeeze,"squeeze");const action$w=new SingleCheckAction({description:`${PREFIX$j}.Description`,name:`${PREFIX$j}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$j}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$j}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$j}.Notes.criticalFailure`}],rollOptions:["action:squeeze"],slug:"squeeze",statistic:"acrobatics",traits:["exploration","move"]}),PREFIX$i="PF2E.Actions.TumbleThrough";function tumbleThrough(options){const slug=options?.skill??"acrobatics",rollOptions=["action:tumble-through"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$i}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$i}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$i}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(tumbleThrough,"tumbleThrough"),__name2(tumbleThrough,"tumbleThrough");const action$v=new SingleCheckAction({cost:1,description:`${PREFIX$i}.Description`,difficultyClass:"reflex",name:`${PREFIX$i}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$i}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$i}.Notes.failure`}],rollOptions:["action:tumble-through"],slug:"tumble-through",statistic:"acrobatics",traits:["move"]});function arcaneSlam(options){const{actor:target,token}=ActionMacroHelpers.target(),slug=options?.skill??"acrobatics",rollOptions=["action:arcane-slam"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:"PF2E.Actions.ArcaneSlam.Title",checkContext:opts=>{const modifiers=options.modifiers?.length?[...options.modifiers]:[];if(opts.actor instanceof CreaturePF2e&&opts.target instanceof CreaturePF2e){const attackerSize=opts.actor.system.traits.size,targetSize=opts.target.system.traits.size,sizeDifference=attackerSize.difference(targetSize),sizeModifier=new ModifierPF2e("PF2E.Actions.ArcaneSlam.Modifier.SizeDifference",Math.clamped(2*sizeDifference,-4,4),"circumstance");sizeModifier.modifier&&modifiers.push(sizeModifier)}return ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug})},traits:["automaton"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>{const notes=[ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.ArcaneSlam","criticalFailure")];if(!target){const translated=game.i18n.localize("PF2E.Actions.ArcaneSlam.Notes.NoTarget");notes.unshift(new RollNotePF2e({selector,text:`${translated}
`,predicate:new PredicatePF2e,outcome:[]}))}return notes},target:()=>target&&token?{actor:target,token}:null}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(arcaneSlam,"arcaneSlam"),__name2(arcaneSlam,"arcaneSlam");const PREFIX$h="PF2E.Actions.Climb";function climb(options){const slug=options?.skill??"athletics",rollOptions=["action:climb"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$h}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,PREFIX$h,"criticalSuccess"),ActionMacroHelpers.note(selector,PREFIX$h,"success"),ActionMacroHelpers.note(selector,PREFIX$h,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(climb,"climb"),__name2(climb,"climb");const action$u=new SingleCheckAction({cost:1,description:`${PREFIX$h}.Description`,name:`${PREFIX$h}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$h}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$h}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$h}.Notes.criticalFailure`}],rollOptions:["action:climb"],slug:"climb",statistic:"athletics",traits:["move"]});function disarm(options){const slug=options?.skill??"athletics",rollOptions=["action:disarm"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Disarm.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"disarm")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.slug!=="basic-unarmed"){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Disarm","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(disarm,"disarm"),__name2(disarm,"disarm");const PREFIX$g="PF2E.Actions.ForceOpen";function forceOpen(options){const slug=options?.skill??"athletics",rollOptions=["action:force-open"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$g}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.ForceOpen","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(forceOpen,"forceOpen"),__name2(forceOpen,"forceOpen");const action$t=new SingleCheckAction({cost:1,description:`${PREFIX$g}.Description`,name:`${PREFIX$g}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$g}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$g}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$g}.Notes.criticalFailure`}],rollOptions:["action:force-open"],slug:"force-open",statistic:"athletics",traits:["attack"]});function grapple(options){const slug=options?.skill??"athletics",rollOptions=["action:grapple"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Grapple.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"grapple")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.traits.has("grapple")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Grapple","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(grapple,"grapple"),__name2(grapple,"grapple");const PREFIX$f="PF2E.Actions.HighJump";function highJump(options){const slug=options?.skill??"athletics",rollOptions=["action:stride","action:leap","action:high-jump"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:`${PREFIX$f}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??{value:30},extraNotes:selector=>[ActionMacroHelpers.note(selector,PREFIX$f,"criticalSuccess"),ActionMacroHelpers.note(selector,PREFIX$f,"success"),ActionMacroHelpers.note(selector,PREFIX$f,"failure"),ActionMacroHelpers.note(selector,PREFIX$f,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(highJump,"highJump"),__name2(highJump,"highJump");const action$s=new SingleCheckAction({cost:2,description:`${PREFIX$f}.Description`,difficultyClass:{value:30},name:`${PREFIX$f}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$f}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$f}.Notes.success`},{outcome:["failure"],text:`${PREFIX$f}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$f}.Notes.criticalFailure`}],rollOptions:["action:stride","action:leap","action:high-jump"],slug:"high-jump",statistic:"athletics",traits:["move"]}),PREFIX$e="PF2E.Actions.LongJump";function longJump(options){const slug=options?.skill??"athletics",rollOptions=["action:stride","action:leap","action:long-jump"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:`${PREFIX$e}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??{value:15},extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$e}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$e,"failure"),ActionMacroHelpers.note(selector,PREFIX$e,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(longJump,"longJump"),__name2(longJump,"longJump");const action$r=new SingleCheckAction({cost:2,description:`${PREFIX$e}.Description`,difficultyClass:{value:15},name:`${PREFIX$e}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$e}.Notes.success`},{outcome:["failure"],text:`${PREFIX$e}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$e}.Notes.criticalFailure`}],rollOptions:["action:stride","action:leap","action:long-jump"],slug:"long-jump",statistic:"athletics",traits:["move"]}),PREFIX$d="PF2E.Actions.Reposition";function reposition(options){const slug=options?.skill??"athletics",modifiers=options?.modifiers,rollOptions=["action:reposition"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$d}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,PREFIX$d,"criticalSuccess"),ActionMacroHelpers.note(selector,PREFIX$d,"success"),ActionMacroHelpers.note(selector,PREFIX$d,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(reposition,"reposition"),__name2(reposition,"reposition");const action$q=new SingleCheckAction({cost:1,description:`${PREFIX$d}.Description`,difficultyClass:"fortitude",name:`${PREFIX$d}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$d}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$d}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$d}.Notes.criticalFailure`}],rollOptions:["action:reposition"],slug:"reposition",statistic:"athletics",traits:["attack"]});function shove(options){const slug=options?.skill??"athletics",rollOptions=["action:shove"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Shove.Title",checkContext:opts=>{const item=(ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"shove")??[]).shift(),modifiers=options.modifiers?.length?[...options.modifiers]:[];if(item&&item.traits.has("shove")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,slug);modifier&&modifiers.push(modifier)}return ActionMacroHelpers.defaultCheckContext(opts,{item,modifiers,rollOptions,slug})},traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Shove","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(shove,"shove"),__name2(shove,"shove");const PREFIX$c="PF2E.Actions.Swim";function swim(options){const slug=options?.skill??"athletics",rollOptions=["action:swim"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$c}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,PREFIX$c,"criticalSuccess"),ActionMacroHelpers.note(selector,PREFIX$c,"success"),ActionMacroHelpers.note(selector,PREFIX$c,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(swim,"swim"),__name2(swim,"swim");const action$p=new SingleCheckAction({cost:1,description:`${PREFIX$c}.Description`,name:`${PREFIX$c}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$c}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$c}.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$c}.Notes.criticalFailure`}],rollOptions:["action:swim"],slug:"swim",statistic:"athletics",traits:["move"]});function tripCheckContext(opts,data){const item=[...ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"trip")??[],...ActionMacroHelpers.getApplicableEquippedWeapons(opts.actor,"ranged-trip")??[]].shift(),context=ActionMacroHelpers.defaultCheckContext(opts,{item:data.item,modifiers:data.modifiers,rollOptions:data.rollOptions,slug:data.slug});if(item&&context){const modifiers=context.modifiers?.length?[...context.modifiers]:[];if(item.traits.has("trip")||item.traits.has("ranged-trip")){const modifier=ActionMacroHelpers.getWeaponPotencyModifier(item,data.slug);modifier&&modifiers.push(modifier)}item.traits.has("ranged-trip")&&modifiers.push(new ModifierPF2e({slug:"ranged-trip",adjustments:extractModifierAdjustments(opts.actor.synthetics.modifierAdjustments,context.rollOptions,"ranged-trip"),type:"circumstance",label:CONFIG.PF2E.weaponTraits["ranged-trip"],modifier:-2})),context.modifiers=modifiers}return context}__name(tripCheckContext,"tripCheckContext"),__name2(tripCheckContext,"tripCheckContext");function trip(options){const slug=options?.skill??"athletics",modifiers=options?.modifiers,rollOptions=["action:trip"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Trip.Title",checkContext:opts=>tripCheckContext(opts,{modifiers,rollOptions,slug}),traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Trip","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(trip,"trip"),__name2(trip,"trip");class TripActionVariant extends SingleCheckActionVariant{static{__name(this,"TripActionVariant")}static{__name2(this,"TripActionVariant")}checkContext(opts,data){return tripCheckContext(opts,data)}}class TripAction extends SingleCheckAction{static{__name(this,"TripAction")}static{__name2(this,"TripAction")}constructor(){super({cost:1,description:"PF2E.Actions.Trip.Description",difficultyClass:"reflex",name:"PF2E.Actions.Trip.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Trip.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Trip.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.Trip.Notes.criticalFailure"}],rollOptions:["action:trip"],slug:"trip",statistic:"athletics",traits:["attack"]})}toActionVariant(data){return new TripActionVariant(this,data)}}const action$o=new TripAction;function determineSizeBonus(actorSize,targetSize){const sizeDifference=actorSize.difference(targetSize);return Math.clamped(2*sizeDifference,-4,4)}__name(determineSizeBonus,"determineSizeBonus"),__name2(determineSizeBonus,"determineSizeBonus");function whirlingThrow(options){const slug=options?.skill??"athletics",rollOptions=["action:whirling-throw"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.WhirlingThrow.Title",checkContext:opts=>{const modifiers=options.modifiers?.length?[...options.modifiers]:[];if(opts.actor instanceof CreaturePF2e&&opts.target instanceof CreaturePF2e){const actorSize=opts.actor.system.traits.size,targetSize=opts.target.system.traits.size,sizeModifier=new ModifierPF2e("Size Modifier",determineSizeBonus(actorSize,targetSize),"circumstance");sizeModifier.modifier&&modifiers.push(sizeModifier)}return ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug})},traits:["monk"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"fortitude",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.WhirlingThrow","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(whirlingThrow,"whirlingThrow"),__name2(whirlingThrow,"whirlingThrow");class AidActionVariant extends SingleCheckActionVariant{static{__name(this,"AidActionVariant")}static{__name2(this,"AidActionVariant")}async use(options){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.Aid.Warning.NoStatistic"));const rollOption=`action:aid:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}}class AidAction extends SingleCheckAction{static{__name(this,"AidAction")}static{__name2(this,"AidAction")}constructor(){super({cost:"reaction",description:"PF2E.Actions.Aid.Description",difficultyClass:{value:15},name:"PF2E.Actions.Aid.Title",notes:[{outcome:["criticalFailure"],text:"PF2E.Actions.Aid.Notes.criticalFailure",title:"PF2E.Check.Result.Degree.Check.criticalFailure"},{outcome:["criticalSuccess"],text:"PF2E.Actions.Aid.Notes.criticalSuccess",title:"PF2E.Check.Result.Degree.Check.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Aid.Notes.success",title:"PF2E.Check.Result.Degree.Check.success"}],rollOptions:["action:aid"],slug:"aid",statistic:""})}toActionVariant(data){return new AidActionVariant(this,data)}}const aid=new AidAction,crawl=new SimpleAction({cost:1,description:"PF2E.Actions.Crawl.Description",name:"PF2E.Actions.Crawl.Title",slug:"crawl",traits:["move"]}),delay=new SimpleAction({cost:"free",description:"PF2E.Actions.Delay.Description",name:"PF2E.Actions.Delay.Title",slug:"delay"});class DropProneActionVariant extends SimpleActionVariant{static{__name(this,"DropProneActionVariant")}static{__name2(this,"DropProneActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)result.actor.hasCondition("prone")||await result.actor.toggleCondition("prone");return results})}}class DropProneAction extends SimpleAction{static{__name(this,"DropProneAction")}static{__name2(this,"DropProneAction")}constructor(){super({cost:1,description:"PF2E.Actions.DropProne.Description",name:"PF2E.Actions.DropProne.Title",slug:"drop-prone",traits:["move"]})}toActionVariant(data){return new DropProneActionVariant(this,data)}}const dropProne=new DropProneAction,toHighestModifier=__name2((highest,current)=>current.totalModifier>(highest?.totalModifier??0)?current:highest,"toHighestModifier");function unarmedStrikeWithHighestModifier(opts,data){const actionRollOptions=["action:escape","action:escape:unarmed"],{rollOptions}=opts.buildContext({actor:opts.actor,rollOptions:actionRollOptions,target:opts.target}),{actor}=opts,statistic=(()=>actor instanceof CharacterPF2e?actor.system.actions.filter(strike=>strike.weaponTraits.map(trait=>trait.name).includes("unarmed")):actor instanceof NPCPF2e?actor.system.actions.filter(strike=>strike.item.category==="unarmed"):[])().map(strike=>{const modifiers=(strike.modifiers??[]).concat(data.modifiers??[]);return new StatisticModifier("unarmed",modifiers,rollOptions)}).reduce(toHighestModifier,null);return statistic?{actor,rollOptions,statistic}:null}__name(unarmedStrikeWithHighestModifier,"unarmedStrikeWithHighestModifier"),__name2(unarmedStrikeWithHighestModifier,"unarmedStrikeWithHighestModifier");function escapeCheckContext(opts,data){const unarmed=data.slug&&data.slug!=="unarmed"?null:unarmedStrikeWithHighestModifier(opts,data),highest=(data.slug?[data.slug]:["acrobatics","athletics"]).filter(slug=>slug!=="unarmed").map(slug=>{const actionRollOptions=["action:escape",`action:escape:${slug}`],{property}=ActionMacroHelpers.resolveStat(slug),{rollOptions}=opts.buildContext({actor:opts.actor,rollOptions:actionRollOptions,target:opts.target}),statistic=foundry.utils.getProperty(opts.actor,property);return{actor:opts.actor,rollOptions,statistic:new StatisticModifier(statistic.slug,statistic.modifiers.concat(data.modifiers??[]),rollOptions)}}).reduce((highest2,current)=>!highest2||current.statistic.totalModifier>(highest2?.statistic.totalModifier??0)?current:highest2,unarmed);if(highest){const{checkType,stat:slug,subtitle}=ActionMacroHelpers.resolveStat(highest.statistic.slug);return{modifiers:data.modifiers,rollOptions:highest.rollOptions,slug,statistic:highest.statistic,subtitle,type:checkType}}throw new CheckContextError("No applicable statistic to roll for Escape check.",opts.actor,"null")}__name(escapeCheckContext,"escapeCheckContext"),__name2(escapeCheckContext,"escapeCheckContext");function escape(options){const slug=options?.skill??"",modifiers=options?.modifiers,rollOptions=["action:escape"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,checkContext:opts=>escapeCheckContext(opts,{modifiers,rollOptions,slug}),actionGlyph:options.glyph??"A",title:"PF2E.Actions.Escape.Title",traits:["attack"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"athletics",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Escape","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(escape,"escape"),__name2(escape,"escape");class EscapeActionVariant extends SingleCheckActionVariant{static{__name(this,"EscapeActionVariant")}static{__name2(this,"EscapeActionVariant")}get statistic(){return""}checkContext(opts,data){return escapeCheckContext(opts,data)}}class EscapeAction extends SingleCheckAction{static{__name(this,"EscapeAction")}static{__name2(this,"EscapeAction")}constructor(){super({cost:1,description:"PF2E.Actions.Escape.Description",difficultyClass:"athletics",name:"PF2E.Actions.Escape.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Escape.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Escape.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.Escape.Notes.criticalFailure"}],rollOptions:["action:escape"],slug:"escape",statistic:"unarmed",traits:["attack"]})}toActionVariant(data){return new EscapeActionVariant(this,data)}}const action$n=new EscapeAction,interact=new SimpleAction({cost:1,description:"PF2E.Actions.Interact.Description",name:"PF2E.Actions.Interact.Title",slug:"interact",traits:["manipulate"]}),leap=new SimpleAction({cost:1,description:"PF2E.Actions.Leap.Description",name:"PF2E.Actions.Leap.Title",slug:"leap",traits:["move"]}),ready=new SimpleAction({cost:2,description:"PF2E.Actions.Ready.Description",name:"PF2E.Actions.Ready.Title",slug:"ready",traits:["concentrate"]}),release=new SimpleAction({cost:"free",description:"PF2E.Actions.Release.Description",name:"PF2E.Actions.Release.Title",slug:"release",traits:["manipulate"]});function seek(options){const slug=options?.skill??"perception",rollOptions=["action:seek"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Seek.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Seek","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Seek","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(seek,"seek"),__name2(seek,"seek");const action$m=new SingleCheckAction({cost:1,description:"PF2E.Actions.Seek.Description",name:"PF2E.Actions.Seek.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Seek.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Seek.Notes.success"}],rollOptions:["action:seek"],slug:"seek",statistic:"perception",traits:["concentrate","secret"]});function senseMotive(options){const slug=options?.skill??"perception",rollOptions=["action:sense-motive"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.SenseMotive.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"deception",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseMotive","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(senseMotive,"senseMotive"),__name2(senseMotive,"senseMotive");const action$l=new SingleCheckAction({cost:1,description:"PF2E.Actions.SenseMotive.Description",difficultyClass:"deception",name:"PF2E.Actions.SenseMotive.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.SenseMotive.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.SenseMotive.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.SenseMotive.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.SenseMotive.Notes.criticalFailure"}],rollOptions:["action:sense-motive"],slug:"sense-motive",statistic:"perception",traits:["concentrate","secret"]});class StandActionVariant extends SimpleActionVariant{static{__name(this,"StandActionVariant")}static{__name2(this,"StandActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)result.actor.hasCondition("prone")&&await result.actor.toggleCondition("prone");return results})}}class StandAction extends SimpleAction{static{__name(this,"StandAction")}static{__name2(this,"StandAction")}constructor(){super({cost:1,description:"PF2E.Actions.Stand.Description",name:"PF2E.Actions.Stand.Title",slug:"stand",traits:["move"]})}toActionVariant(data){return new StandActionVariant(this,data)}}const stand=new StandAction,step=new SimpleAction({cost:1,description:"PF2E.Actions.Step.Description",name:"PF2E.Actions.Step.Title",slug:"step",traits:["move"]}),stride=new SimpleAction({cost:1,description:"PF2E.Actions.Stride.Description",name:"PF2E.Actions.Stride.Title",slug:"stride",traits:["move"]}),takeCover=new SimpleAction({cost:1,description:"PF2E.Actions.TakeCover.Description",effect:"Compendium.pf2e.other-effects.I9lfZUiCwMiGogVi",img:"systems/pf2e/icons/conditions-2/status_acup.webp",name:"PF2E.Actions.TakeCover.Title",slug:"take-cover"});function tamper(options){const slug=options?.skill??"crafting",rollOptions=["action:tamper"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Tamper.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["inventor","manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"reflex",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Tamper","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(tamper,"tamper"),__name2(tamper,"tamper");const PREFIX$b="PF2E.Actions.CreateADiversion",CREATE_A_DIVERSION_VARIANTS=["distracting-words","gesture","trick"];function createADiversion(options){const{title,traits,variant}=(()=>{switch(options?.variant){case"distracting-words":return{title:`${PREFIX$b}.DistractingWords.Title`,traits:["auditory","linguistic","mental"],variant:options.variant};case"gesture":return{title:`${PREFIX$b}.Gesture.Title`,traits:["manipulate","mental"],variant:options.variant};case"trick":return{title:`${PREFIX$b}.Trick.Title`,traits:["manipulate","mental"],variant:options.variant};default:{const variant2=options?.variant?`'${options.variant}'`:"null",variants=CREATE_A_DIVERSION_VARIANTS.map(v=>`'${v}'`).join(", ");throw ui.notifications.error(game.i18n.format(`${PREFIX$b}.Warning.UnknownVariant`,{variant:variant2,variants})),new Error(`Unknown variant ${variant2} for Create a Diversion, use one of ${variants}.`)}}})(),slug=options?.skill??"deception",rollOptions=["action:create-a-diversion",`action:create-a-diversion:${variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits,event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$b}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$b}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(createADiversion,"createADiversion"),__name2(createADiversion,"createADiversion");function feint(options){const slug=options?.skill??"deception",rollOptions=["action:feint"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Feint.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Feint","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(feint,"feint"),__name2(feint,"feint");const PREFIX$a="PF2E.Actions.Impersonate";function impersonate(options){const slug=options?.skill??"deception",rollOptions=["action:impersonate"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$a}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","manipulate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$a}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$a,"failure"),ActionMacroHelpers.note(selector,PREFIX$a,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(impersonate,"impersonate"),__name2(impersonate,"impersonate");const PREFIX$9="PF2E.Actions.Lie";function lie(options){const slug=options?.skill??"deception",rollOptions=["action:lie"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$9}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","linguistic","mental","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$9}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$9}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(lie,"lie"),__name2(lie,"lie");const action$k=new SingleCheckAction({description:`${PREFIX$9}.Description`,difficultyClass:"perception",name:`${PREFIX$9}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$9}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$9}.Notes.failure`}],rollOptions:["action:lie"],slug:"lie",statistic:"deception",traits:["auditory","concentrate","linguistic","mental","secret"]});function bonMot(options){const slug=options?.skill??"diplomacy",rollOptions=["action:bon-mot"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.BonMot.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.BonMot","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(bonMot,"bonMot"),__name2(bonMot,"bonMot");const PREFIX$8="PF2E.Actions.GatherInformation";function gatherInformation(options){const slug=options?.skill??"diplomacy",rollOptions=["action:gather-information"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:`${PREFIX$8}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$8}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$8,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(gatherInformation,"gatherInformation"),__name2(gatherInformation,"gatherInformation");function makeAnImpression(options){const slug=options?.skill??"diplomacy",rollOptions=["action:make-an-impression"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.MakeAnImpression.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","exploration","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.MakeAnImpression","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(makeAnImpression,"makeAnImpression"),__name2(makeAnImpression,"makeAnImpression");const PREFIX$7="PF2E.Actions.Request";function request(options){const slug=options?.skill??"diplomacy",rollOptions=["action:request"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$7}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Request","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Request","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(request,"request"),__name2(request,"request");const action$j=new SingleCheckAction({cost:1,description:`${PREFIX$7}.Description`,name:`${PREFIX$7}.Title`,notes:[{outcome:["criticalSuccess"],text:`${PREFIX$7}.Notes.criticalSuccess`},{outcome:["success"],text:`${PREFIX$7}.Notes.success`},{outcome:["failure"],text:`${PREFIX$7}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$7}.Notes.criticalFailure`}],rollOptions:["action:request"],slug:"request",statistic:"diplomacy",traits:["auditory","concentrate","linguistic","mental"]});function avoidNotice(options){const slug=options?.skill??"stealth",rollOptions=["action:avoid-notice"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.AvoidNotice.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.AvoidNotice","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.AvoidNotice","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(avoidNotice,"avoidNotice"),__name2(avoidNotice,"avoidNotice");const action$i=new SingleCheckAction({description:"PF2E.Actions.AvoidNotice.Description",name:"PF2E.Actions.AvoidNotice.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.AvoidNotice.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.AvoidNotice.Notes.success"}],rollOptions:["action:avoid-notice"],slug:"avoid-notice",statistic:"stealth",traits:["exploration"]});function senseDirection(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.SenseDirection.Modifier.NoCompass",modifier:-2,predicate:[{not:"compass-in-possession"}],type:"item"})].concat(options?.modifiers??[]),slug=options?.skill??"survival",rollOptions=["action:sense-direction"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.SenseDirection.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.SenseDirection","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.SenseDirection","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(senseDirection,"senseDirection"),__name2(senseDirection,"senseDirection");const action$h=new SingleCheckAction({description:"PF2E.Actions.SenseDirection.Description",modifiers:[{label:"PF2E.Actions.SenseDirection.Modifier.NoCompass",modifier:-2,predicate:[{not:"compass-in-possession"}],type:"item"}],name:"PF2E.Actions.SenseDirection.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.SenseDirection.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.SenseDirection.Notes.success"}],rollOptions:["action:sense-direction"],slug:"sense-direction",statistic:"survival",traits:["exploration","secret"]});function track(options){const slug=options?.skill??"survival",rollOptions=["action:track"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Track.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","move"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Track","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Track","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Track","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(track,"track"),__name2(track,"track");const action$g=new SingleCheckAction({description:"PF2E.Actions.Track.Description",name:"PF2E.Actions.Track.Title",notes:[{outcome:["success","criticalSuccess"],text:"PF2E.Actions.Track.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Track.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Track.Notes.criticalFailure"}],rollOptions:["action:track"],slug:"track",statistic:"survival",traits:["concentrate","exploration","move"]});function decipherWriting(options){if(!options?.skill){ui.notifications.warn(game.i18n.localize("PF2E.Actions.DecipherWriting.Warning.NoSkill"));return}const{skill:slug}=options,rollOptions=["action:decipher-writing",`action:decipher-writing:${slug}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.DecipherWriting.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate","exploration","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.DecipherWriting","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(decipherWriting,"decipherWriting"),__name2(decipherWriting,"decipherWriting");class DecipherWritingActionVariant extends SingleCheckActionVariant{static{__name(this,"DecipherWritingActionVariant")}static{__name2(this,"DecipherWritingActionVariant")}async use(options){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.DecipherWriting.Warning.NoSkill"));const rollOption=`action:decipher-writing:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}}class DecipherWritingAction extends SingleCheckAction{static{__name(this,"DecipherWritingAction")}static{__name2(this,"DecipherWritingAction")}constructor(){super({description:"PF2E.Actions.DecipherWriting.Description",name:"PF2E.Actions.DecipherWriting.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.DecipherWriting.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.DecipherWriting.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.DecipherWriting.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.DecipherWriting.Notes.criticalFailure"}],rollOptions:["action:decipher-writing"],slug:"decipher-writing",statistic:"",traits:["concentrate","exploration","secret"]})}toActionVariant(data){return new DecipherWritingActionVariant(this,data)}}const action$f=new DecipherWritingAction;function subsist(options){if(!options?.skill){ui.notifications.warn(game.i18n.localize("PF2E.Actions.Subsist.Warning.NoSkill"));return}const modifiers=[new ModifierPF2e({label:"PF2E.Actions.Subsist.AfterExplorationPenalty",modifier:-5,predicate:["action:subsist:after-exploration"]})].concat(options?.modifiers??[]),{skill:slug}=options,rollOptions=["action:subsist",`action:subsist:${slug}`];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Subsist.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Subsist","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(subsist,"subsist"),__name2(subsist,"subsist");class SubsistActionVariant extends SingleCheckActionVariant{static{__name(this,"SubsistActionVariant")}static{__name2(this,"SubsistActionVariant")}async use(options={}){if(!options?.statistic)throw new Error(game.i18n.localize("PF2E.Actions.Subsist.Warning.NoSkill"));const rollOption=`action:subsist:${options.statistic}`;return options.rollOptions??=[],options.rollOptions.includes(rollOption)||options.rollOptions.push(rollOption),super.use(options)}}class SubsistAction extends SingleCheckAction{static{__name(this,"SubsistAction")}static{__name2(this,"SubsistAction")}constructor(){super({description:"PF2E.Actions.Subsist.Description",modifiers:[{label:"PF2E.Actions.Subsist.AfterExplorationPenalty",modifier:-5,predicate:["action:subsist:after-exploration"]}],name:"PF2E.Actions.Subsist.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Subsist.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Subsist.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Subsist.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Subsist.Notes.criticalFailure"}],rollOptions:["action:subsist"],slug:"subsist",statistic:"",traits:["downtime"]})}toActionVariant(data){return new SubsistActionVariant(this,data)}}const action$e=new SubsistAction;function coerce(options){const slug=options?.skill??"intimidation",rollOptions=["action:coerce"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.Coerce.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","exploration","linguistic","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Coerce","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(coerce,"coerce"),__name2(coerce,"coerce");const action$d=new SingleCheckAction({description:"PF2E.Actions.Coerce.Description",difficultyClass:"will",name:"PF2E.Actions.Coerce.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Coerce.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Coerce.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.Coerce.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.Coerce.Notes.criticalFailure"}],rollOptions:["action:coerce"],slug:"coerce",statistic:"intimidation",traits:["auditory","concentrate","emotion","exploration","linguistic","mental"]});function demoralize(options){const slug=options?.skill??"intimidation",rollOptions=["action:demoralize"],modifiers=[new ModifierPF2e({label:"PF2E.Actions.Demoralize.Unintelligible",modifier:-4,predicate:["action:demoralize:unintelligible"],type:"circumstance"})].concat(options?.modifiers??[]);ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.Demoralize.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate","emotion","fear","mental"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Demoralize","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Demoralize","success")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(demoralize,"demoralize"),__name2(demoralize,"demoralize");const action$c=new SingleCheckAction({description:"PF2E.Actions.Demoralize.Description",difficultyClass:"will",modifiers:[{label:"PF2E.Actions.Demoralize.Unintelligible",modifier:-4,predicate:["action:demoralize:unintelligible"],type:"circumstance"}],name:"PF2E.Actions.Demoralize.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.Demoralize.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.Demoralize.Notes.success"}],rollOptions:["action:demoralize"],slug:"demoralize",statistic:"intimidation",traits:["auditory","concentrate","emotion","fear","mental"]}),PREFIX$6="PF2E.Actions.AdministerFirstAid",ADMINISTER_FIRST_AID_VARIANTS=["stabilize","stop-bleeding"];function stabilizeDifficultyClass(target){if(!target?.isOfType("creature"))return null;const{dying}=target.attributes;if(!dying?.value)throw new Error(game.i18n.localize(`${PREFIX$6}.Warning.TargetNotDying`));const dcModifier=new ModifierPF2e({slug:"dying-recovery",label:"PF2E.ModifierTitle",modifier:5+dying.recoveryDC+dying.value-10});return new Statistic(target,{slug:"administer-first-aid",label:`${PREFIX$6}.Stabilize.Title`,dc:{label:`${PREFIX$6}.Stabilize.DifficultyClass.Label`,modifiers:[dcModifier]}}).dc}__name(stabilizeDifficultyClass,"stabilizeDifficultyClass"),__name2(stabilizeDifficultyClass,"stabilizeDifficultyClass");function administerFirstAid(options){const{notes,title,variant}=(()=>{const mainTitle=game.i18n.localize(`${PREFIX$6}.Title`);switch(options?.variant){case"stabilize":return{notes:{criticalFailure:`${PREFIX$6}.Stabilize.Notes.criticalFailure`,success:`${PREFIX$6}.Stabilize.Notes.success`},title:mainTitle+" - "+game.i18n.localize(`${PREFIX$6}.Stabilize.Title`),variant:options.variant};case"stop-bleeding":return{notes:{criticalFailure:`${PREFIX$6}.StopBleeding.Notes.criticalFailure`,success:`${PREFIX$6}.StopBleeding.Notes.success`},title:mainTitle+" - "+game.i18n.localize(`${PREFIX$6}.StopBleeding.Title`),variant:options.variant};default:{const variant2=options?.variant?`'${options.variant}'`:"null",variants=ADMINISTER_FIRST_AID_VARIANTS.map(v=>`'${v}'`).join(", "),error=`${PREFIX$6}.Warning.UnknownVariant`;throw ui.notifications.error(game.i18n.format(error,{variant:variant2,variants})),new Error(`Unknown variant ${variant2} for Administer First Aid, use one of ${variants}.`)}}})(),slug=options?.skill??"medicine",rollOptions=["action:administer-first-aid",`action:administer-first-aid:${variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??(target=>{if(variant==="stabilize"&&target)try{return stabilizeDifficultyClass(target)}catch(error){if(error instanceof Error)ui.notifications.warn(error.message);else throw error}return null}),extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,notes.success,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,notes.criticalFailure,["criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(administerFirstAid,"administerFirstAid"),__name2(administerFirstAid,"administerFirstAid");class AdministerFirstAidAction extends SingleCheckAction{static{__name(this,"AdministerFirstAidAction")}static{__name2(this,"AdministerFirstAidAction")}constructor(){super({cost:2,description:`${PREFIX$6}.Description`,name:`${PREFIX$6}.Title`,slug:"administer-first-aid",statistic:"medicine",traits:["manipulate"],variants:[{description:`${PREFIX$6}.Stabilize.Description`,name:`${PREFIX$6}.Stabilize.Title`,notes:[{outcome:["criticalSuccess","success"],text:`${PREFIX$6}.Stabilize.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$6}.Stabilize.Notes.criticalFailure`}],slug:"stabilize"},{description:`${PREFIX$6}.StopBleeding.Description`,name:`${PREFIX$6}.StopBleeding.Title`,notes:[{outcome:["criticalSuccess","success"],text:`${PREFIX$6}.StopBleeding.Notes.success`},{outcome:["criticalFailure"],text:`${PREFIX$6}.StopBleeding.Notes.criticalFailure`}],slug:"stop-bleeding"}]})}}const action$b=new AdministerFirstAidAction;function treatDisease(options){const slug=options?.skill??"medicine",rollOptions=["action:treat-disease"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.TreatDisease.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatDisease","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(treatDisease,"treatDisease"),__name2(treatDisease,"treatDisease");const action$a=new SingleCheckAction({description:"PF2E.Actions.TreatDisease.Description",name:"PF2E.Actions.TreatDisease.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.TreatDisease.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.TreatDisease.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.TreatDisease.Notes.criticalFailure"}],rollOptions:["action:treat-disease"],slug:"treat-disease",statistic:"medicine",traits:["downtime","manipulate"]});function treatPoison(options){const slug=options?.skill??"medicine",rollOptions=["action:treat-poison"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:"PF2E.Actions.TreatPoison.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.TreatPoison","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(treatPoison,"treatPoison"),__name2(treatPoison,"treatPoison");const action$9=new SingleCheckAction({cost:1,description:"PF2E.Actions.TreatPoison.Description",name:"PF2E.Actions.TreatPoison.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.TreatPoison.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.TreatPoison.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.TreatPoison.Notes.criticalFailure"}],rollOptions:["action:treat-poison"],slug:"treat-poison",statistic:"medicine",traits:["manipulate"]}),PREFIX$5="PF2E.Actions.CommandAnAnimal";function commandAnAnimal(options){const slug=options?.skill??"nature",rollOptions=["action:command-an-animal"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$5}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["auditory","concentrate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$5}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$5,"failure"),ActionMacroHelpers.note(selector,PREFIX$5,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(commandAnAnimal,"commandAnAnimal"),__name2(commandAnAnimal,"commandAnAnimal");const action$8=new SingleCheckAction({cost:1,description:`${PREFIX$5}.Description`,difficultyClass:"will",name:`${PREFIX$5}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$5}.Notes.success`},{outcome:["failure"],text:`${PREFIX$5}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$5}.Notes.criticalFailure`}],rollOptions:["action:command-an-animal"],slug:"command-an-animal",statistic:"nature",traits:["auditory","concentrate"]}),PERFORM_VARIANT_TRAITS={acting:["auditory","linguistic","visual"],comedy:["auditory","linguistic","visual"],dance:["move","visual"],keyboards:["auditory","manipulate"],oratory:["auditory","linguistic"],percussion:["auditory","manipulate"],singing:["auditory","linguistic"],strings:["auditory","manipulate"],winds:["auditory","manipulate"]};function perform(options){const traits=PERFORM_VARIANT_TRAITS[options?.variant??""];if(!traits){const msg=game.i18n.format("PF2E.Actions.Perform.Warning.UnknownVariant",{variant:options.variant});ui.notifications.warn(msg);return}const slug=options?.skill??"performance",rollOptions=["action:perform",`action:perform:${options.variant}`],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"1",title:`PF2E.Actions.Perform.${options.variant.charAt(0).toUpperCase()}${options.variant.slice(1)}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["concentrate",...traits].sort(),event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"will",extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.Perform","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(perform,"perform"),__name2(perform,"perform");async function createForgeryCallback(result,callback){const societyDC=(()=>{if(result.actor instanceof CreaturePF2e){const systemFlags=result.message?.flags.pf2e,modifiers=systemFlags.modifiers.filter(modifier=>modifier.enabled).map(modifier=>({...modifier,predicate:[]})).map(modifier=>new ModifierPF2e(modifier));return result.actor.skills.society.extend({slug:result.actor.skills.society.slug,modifiers}).withRollOptions({extraRollOptions:systemFlags.context.options,origin:result.actor}).dc}return null})(),gmNotes=(()=>["criticalSuccess","success"].includes(result.outcome??"")?game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.SuccessGmNote",{societyDC:societyDC?.value??null}):["criticalFailure","failure"].includes(result.outcome??"")?game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.FailureGmNote",{failure:game.i18n.localize("PF2E.Actions.CreateForgery.Notes.failure"),success:game.i18n.localize("PF2E.Actions.CreateForgery.Notes.success"),total:result.roll.total}):"")();await Item.create({img:"systems/pf2e/icons/equipment/adventuring-gear/scroll-case.webp",name:game.i18n.localize("PF2E.Actions.CreateForgery.ForgedDocument.Name"),type:"equipment",system:{description:{gm:gmNotes,value:game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocument.Description",{societyDC:societyDC?.value??null})}}},{parent:result.actor});const notification=game.i18n.format("PF2E.Actions.CreateForgery.ForgedDocumentCreatedNotification",{name:result.actor.name});ui.notifications.info(notification),callback?.(result)}__name(createForgeryCallback,"createForgeryCallback"),__name2(createForgeryCallback,"createForgeryCallback");function createForgery(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.CreateForgery.UnspecificHandwriting",modifier:4,predicate:["action:create-forgery:unspecific-handwriting"],type:"circumstance"})].concat(options?.modifiers??[]),slug=options?.skill??"society",rollOptions=["action:create-forgery"];return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph,title:"PF2E.Actions.CreateForgery.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["downtime","secret"],event:options.event,callback:async result=>createForgeryCallback(result,options?.callback),difficultyClass:options.difficultyClass??{value:20},extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","failure"),ActionMacroHelpers.note(selector,"PF2E.Actions.CreateForgery","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(createForgery,"createForgery"),__name2(createForgery,"createForgery");class CreateForgeryActionVariant extends SingleCheckActionVariant{static{__name(this,"CreateForgeryActionVariant")}static{__name2(this,"CreateForgeryActionVariant")}async use(options={}){return super.use(options).then(async results=>{for(const result of results)await createForgeryCallback(result);return results})}}class CreateForgeryAction extends SingleCheckAction{static{__name(this,"CreateForgeryAction")}static{__name2(this,"CreateForgeryAction")}constructor(){super({description:"PF2E.Actions.CreateForgery.Description",difficultyClass:{value:20},modifiers:[{label:"PF2E.Actions.CreateForgery.UnspecificHandwriting",modifier:4,predicate:["action:create-forgery:unspecific-handwriting"],type:"circumstance"}],name:"PF2E.Actions.CreateForgery.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.CreateForgery.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.CreateForgery.Notes.success"},{outcome:["failure"],text:"PF2E.Actions.CreateForgery.Notes.failure"},{outcome:["criticalFailure"],text:"PF2E.Actions.CreateForgery.Notes.criticalFailure"}],rollOptions:["action:create-forgery"],slug:"create-forgery",statistic:"society",traits:["downtime","secret"]})}toActionVariant(data){return new CreateForgeryActionVariant(this,data)}}const action$7=new CreateForgeryAction,PREFIX$4="PF2E.Actions.ConcealAnObject";function concealAnObject(options){const slug=options?.skill??"stealth",rollOptions=["action:conceal-an-object"],modifiers=options?.modifiers;return ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$4}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$4}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$4}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(concealAnObject,"concealAnObject"),__name2(concealAnObject,"concealAnObject");const action$6=new SingleCheckAction({cost:1,description:`${PREFIX$4}.Description`,difficultyClass:"perception",name:`${PREFIX$4}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$4}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$4}.Notes.failure`}],rollOptions:["action:conceal-an-object"],slug:"conceal-an-object",statistic:"stealth",traits:["manipulate","secret"]}),PREFIX$3="PF2E.Actions.Hide";function hide(options){const slug=options?.skill??"stealth",rollOptions=["action:hide"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$3}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$3}.Notes.success`,["success","criticalSuccess"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(hide,"hide"),__name2(hide,"hide");const action$5=new SingleCheckAction({cost:1,description:`${PREFIX$3}.Description`,difficultyClass:"perception",name:`${PREFIX$3}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$3}.Notes.success`}],rollOptions:["action:hide"],slug:"hide",statistic:"stealth",traits:["secret"]}),PREFIX$2="PF2E.Actions.Sneak";function sneak(options){const slug=options?.skill??"stealth",rollOptions=["action:sneak"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$2}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["move","secret"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$2}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.note(selector,PREFIX$2,"failure"),ActionMacroHelpers.note(selector,PREFIX$2,"criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(sneak,"sneak"),__name2(sneak,"sneak");const action$4=new SingleCheckAction({cost:1,description:`${PREFIX$2}.Description`,difficultyClass:"perception",name:`${PREFIX$2}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$2}.Notes.success`},{outcome:["failure"],text:`${PREFIX$2}.Notes.failure`},{outcome:["criticalFailure"],text:`${PREFIX$2}.Notes.criticalFailure`}],rollOptions:["action:sneak"],slug:"sneak",statistic:"stealth",traits:["move","secret"]}),PREFIX$1="PF2E.Actions.PalmAnObject";function palmAnObject(options){const slug=options?.skill??"thievery",rollOptions=["action:palm-an-object"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX$1}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX$1}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX$1}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(palmAnObject,"palmAnObject"),__name2(palmAnObject,"palmAnObject");const action$3=new SingleCheckAction({cost:1,description:`${PREFIX$1}.Description`,difficultyClass:"perception",name:`${PREFIX$1}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX$1}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX$1}.Notes.failure`}],rollOptions:["action:palm-an-object"],slug:"palm-an-object",statistic:"thievery",traits:["manipulate"]});function disableDevice(options){const slug=options?.skill??"thievery",rollOptions=["action:disable-a-device","action:disable-device"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options?.actors,actionGlyph:options?.glyph??"D",title:"PF2E.Actions.DisableDevice.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options?.event,callback:options?.callback,difficultyClass:options?.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.DisableDevice","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(disableDevice,"disableDevice"),__name2(disableDevice,"disableDevice");const action$2=new SingleCheckAction({cost:2,description:"PF2E.Actions.DisableDevice.Description",name:"PF2E.Actions.DisableDevice.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.DisableDevice.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.DisableDevice.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.DisableDevice.Notes.criticalFailure"}],rollOptions:["action:disable-a-device","action:disable-device"],slug:"disable-device",statistic:"thievery",traits:["manipulate"]});function pickALock(options){const slug=options?.skill??"thievery",rollOptions=["action:pick-a-lock"],modifiers=options?.modifiers;ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"D",title:"PF2E.Actions.PickALock.Title",checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass,extraNotes:selector=>[ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","criticalSuccess"),ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","success"),ActionMacroHelpers.note(selector,"PF2E.Actions.PickALock","criticalFailure")]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(pickALock,"pickALock"),__name2(pickALock,"pickALock");const action$1=new SingleCheckAction({cost:2,description:"PF2E.Actions.PickALock.Description",name:"PF2E.Actions.PickALock.Title",notes:[{outcome:["criticalSuccess"],text:"PF2E.Actions.PickALock.Notes.criticalSuccess"},{outcome:["success"],text:"PF2E.Actions.PickALock.Notes.success"},{outcome:["criticalFailure"],text:"PF2E.Actions.PickALock.Notes.criticalFailure"}],rollOptions:["action:pick-a-lock"],slug:"pick-a-lock",statistic:"thievery",traits:["manipulate"]}),PREFIX="PF2E.Actions.Steal";function steal(options){const modifiers=[new ModifierPF2e({label:"PF2E.Actions.Steal.Pocketed",modifier:-5,predicate:["action:steal:pocketed"]})].concat(options?.modifiers??[]),slug=options?.skill??"thievery",rollOptions=["action:steal"];ActionMacroHelpers.simpleRollActionCheck({actors:options.actors,actionGlyph:options.glyph??"A",title:`${PREFIX}.Title`,checkContext:opts=>ActionMacroHelpers.defaultCheckContext(opts,{modifiers,rollOptions,slug}),traits:["manipulate"],event:options.event,callback:options.callback,difficultyClass:options.difficultyClass??"perception",extraNotes:selector=>[ActionMacroHelpers.outcomesNote(selector,`${PREFIX}.Notes.success`,["success","criticalSuccess"]),ActionMacroHelpers.outcomesNote(selector,`${PREFIX}.Notes.failure`,["failure","criticalFailure"])]}).catch(error=>{throw ui.notifications.error(error.message),error})}__name(steal,"steal"),__name2(steal,"steal");const action=new SingleCheckAction({cost:1,description:`${PREFIX}.Description`,difficultyClass:"perception",modifiers:[{label:"PF2E.Actions.Steal.Pocketed",modifier:-5,predicate:["action:steal:pocketed"]}],name:`${PREFIX}.Title`,notes:[{outcome:["success","criticalSuccess"],text:`${PREFIX}.Notes.success`},{outcome:["failure","criticalFailure"],text:`${PREFIX}.Notes.failure`}],rollOptions:["action:steal"],slug:"steal",statistic:"thievery",traits:["manipulate"]}),ActionMacros={escape,seek,senseMotive,arcaneSlam,tamper,avoidNotice,senseDirection,track,balance,maneuverInFlight,squeeze,tumbleThrough,climb,disarm,forceOpen,grapple,highJump,longJump,reposition,shove,swim,trip,whirlingThrow,craft,repair,createADiversion,feint,impersonate,lie,bonMot,gatherInformation,makeAnImpression,request,decipherWriting,subsist,coerce,demoralize,administerFirstAid,treatDisease,treatPoison,commandAnAnimal,perform,createForgery,concealAnObject,hide,sneak,palmAnObject,disableDevice,pickALock,steal},SystemActions=[action$b,aid,action$i,action$y,action$u,action$d,action$8,action$6,crawl,action$7,action$f,delay,action$c,action$2,dropProne,action$n,action$t,action$5,action$s,interact,leap,action$k,action$r,action$x,action$3,action$1,ready,release,action$q,action$j,action$m,action$h,action$l,action$4,action$w,stand,action,step,stride,action$e,action$p,takeCover,action$g,action$a,action$9,action$o,action$v];class EffectTracker{static{__name(this,"EffectTracker")}static{__name2(this,"EffectTracker")}effects=[];auraEffects=new Collection;#insert(effect,duration){if(this.effects.length===0)this.effects.push(effect);else{for(let index=0;indexremaining)){if(remaining>duration.remaining){this.effects.splice(index,0,effect);return}else if(!((effect.system.start.initiative??0)>(other.system.start.initiative??0))){if((other.system.start.initiative??0)>(effect.system.start.initiative??0)){this.effects.splice(index,0,effect);return}else if(other.system.duration.expiry==="turn-start"&&effect.system.duration.expiry==="turn-end"){this.effects.splice(index,0,effect);return}}}}this.effects.push(effect)}}register(effect){effect.fromAura&&(canvas.ready||!effect.actor.isToken)&&effect.id&&this.auraEffects.set(effect.uuid,effect);const index=this.effects.findIndex(e=>e.id===effect.id),systemData=effect.system,duration=systemData.duration.unit;switch(duration){case"unlimited":case"encounter":{duration==="unlimited"&&(systemData.expired=!1),index>=0&&indexe!==toRemove),this.auraEffects.delete(toRemove.uuid)}async refresh(options={}){if(options.resetItemData){const actors=new Set(this.effects.flatMap(e=>e.actor??[]));for(const actor of actors)actor.reset();game.pf2e.effectPanel.refresh()}const actorsToUpdate=new Set(this.effects.filter(e=>e.isExpired).map(e=>e.actor));if(game.settings.get("pf2e","automation.removeExpiredEffects"))for(const actor of actorsToUpdate)await this.#removeExpired(actor);else game.settings.get("pf2e","automation.effectExpiration")&&resetActors(actorsToUpdate)}async#removeExpired(actor){actor.primaryUpdater===game.user&&await actor.deleteEmbeddedDocuments("Item",actor.itemTypes.effect.filter(e=>e.isExpired).map(e=>e.id))}async onEncounterEnd(encounter){const autoRemoveExpired=game.settings.get("pf2e","automation.removeExpiredEffects"),autoExpireEffects=!autoRemoveExpired&&game.settings.get("pf2e","automation.effectExpiration");if(!(autoExpireEffects||autoRemoveExpired))return;const actors=encounter.combatants.contents.flatMap(c=>c.actor??[]).filter(a=>game.user===a.primaryUpdater);for(const actor of actors){const expiresNow=actor.itemTypes.effect.filter(e=>e.system.duration.unit==="encounter");if(expiresNow.length!==0){if(autoExpireEffects){const updates=expiresNow.map(e=>({_id:e.id,"system.expired":!0}));await actor.updateEmbeddedDocuments("Item",updates)}else{const deletes=expiresNow.map(e=>e.id);await actor.deleteEmbeddedDocuments("Item",deletes)}for(const effect of expiresNow)this.unregister(effect)}}}}class ModuleArt{static{__name(this,"ModuleArt")}static{__name2(this,"ModuleArt")}map=new Map;async refresh(){this.map.clear();const activeModules=[...game.modules.entries()].filter(([_key,m])=>m.active);for(const[moduleKey,foundryModule]of activeModules){const moduleArt=await this.#getArtMap(foundryModule.flags?.[moduleKey]?.["pf2e-art"]);if(moduleArt)for(const[packName,art]of Object.entries(moduleArt)){const pack=game.packs.get(`pf2e.${packName}`);if(!pack){console.warn(`PF2e System | Failed pack lookup from module art registration (${moduleKey}): ${packName}`);continue}const index=pack.indexed?pack.index:await pack.getIndex();for(const[actorId,paths]of Object.entries(art)){const record=index.get(actorId);if(!record)continue;record.img=paths.actor;const actorArtPartial={img:paths.actor,prototypeToken:{texture:{src:typeof paths.token=="string"?paths.token:paths.token.img}}};typeof paths.token!="string"&&(typeof paths.token.scale=="number"&&(actorArtPartial.prototypeToken.texture.scaleX=paths.token.scale,actorArtPartial.prototypeToken.texture.scaleY=paths.token.scale,actorArtPartial.prototypeToken.flags={pf2e:{autoscale:!1}}),typeof paths.token.randomImg=="boolean"&&(actorArtPartial.prototypeToken.randomImg=paths.token.randomImg)),this.map.set(`Compendium.pf2e.${packName}.${actorId}`,actorArtPartial)}}}const apps=Object.values(ui.windows).filter(w=>w instanceof Compendium);for(const compendium of apps)compendium.render()}async#getArtMap(art){if(art){if(this.#isModuleArt(art))return art;if(typeof art=="string")try{const response=await fetch(art);if(!response.ok)return console.warn(`PF2e System | Failed loading art mapping file at ${art}`),null;const map2=await response.json();return this.#isModuleArt(map2)?map2:null}catch(error){error instanceof Error&&console.warn(`PF2e System | ${error.message}`)}}else return null;return null}#isModuleArt(record){return isObject(record)&&Object.values(record).every(packToArt=>isObject(packToArt)&&Object.values(packToArt).every(art=>isObject(art)&&"actor"in art&&typeof isImageFilePath(art.actor)&&"token"in art&&(isImageOrVideoPath(art.token)||isObject(art.token)&&"img"in art.token&&isImageOrVideoPath(art.token.img)&&(!("scale"in art.token)||typeof art.token.scale=="number"&&art.token.scale>0)&&(!("randomImg"in art.token)||typeof art.token.randomImg=="boolean"))))}}const SetGamePF2e={onInit:()=>{const actions=new Map(SystemActions.map(action2=>[action2.slug,action2]));for(const[name2,action2]of Object.entries({encouragingWords,raiseAShield,restForTheNight,earnIncome:showEarnIncomePopup,steelYourResolve,takeABreather,treatWounds,...ActionMacros}))actions[name2]=action2;const initSafe={Check:CheckPF2e,CheckModifier,Coins:CoinsPF2e,ConditionManager,Dice:DicePF2e,Modifier:ModifierPF2e,ModifierType:{ABILITY:"ability",PROFICIENCY:"proficiency",CIRCUMSTANCE:"circumstance",ITEM:"item",POTENCY:"potency",STATUS:"status",UNTYPED:"untyped"},RuleElement:RuleElementPF2e,RuleElements,StatisticModifier,StatusEffects,TextEditor:TextEditorPF2e,ElementalBlast,actions,effectPanel:new EffectsPanel,effectTracker:new EffectTracker,gm:{calculateXP,checkPrompt,editPersistent,launchTravelSheet,perceptionForSelected,stealthForSelected,xpFromEncounter},licenseViewer:new LicenseViewer,rollActionMacro,rollItemMacro,system:{generateItemName,moduleArt:new ModuleArt,remigrate,sluggify},variantRules:{AutomaticBonusProgression}};game.pf2e=foundry.utils.mergeObject(game.pf2e??{},initSafe),game.pf2e.ConditionManager.initialize(),game.pf2e.settings={campaign:{enabled:game.settings.get("pf2e","campaignFeats"),sections:game.settings.get("pf2e","campaignFeatSections")},encumbrance:game.settings.get("pf2e","automation.encumbrance"),iwr:game.settings.get("pf2e","automation.iwr"),rbv:game.settings.get("pf2e","automation.rulesBasedVision"),tokens:{autoscale:game.settings.get("pf2e","tokens.autoscale"),nameVisibility:game.settings.get("pf2e","metagame_tokenSetsNameVisibility"),nathMode:game.settings.get("pf2e","nathMode")},totm:game.settings.get("pf2e","totmToggles"),variants:{abp:game.settings.get("pf2e","automaticBonusVariant"),fa:game.settings.get("pf2e","freeArchetypeVariant"),gab:game.settings.get("pf2e","gradualBoostsVariant"),pwol:{enabled:game.settings.get("pf2e","proficiencyVariant"),modifiers:[game.settings.get("pf2e","proficiencyUntrainedModifier"),game.settings.get("pf2e","proficiencyTrainedModifier"),game.settings.get("pf2e","proficiencyExpertModifier"),game.settings.get("pf2e","proficiencyMasterModifier"),game.settings.get("pf2e","proficiencyLegendaryModifier")]},stamina:game.settings.get("pf2e","staminaVariant")}}},onSetup:()=>{},onReady:()=>{game.pf2e.compendiumBrowser=new CompendiumBrowser,game.pf2e.worldClock=new WorldClock}};class AutomationSettings extends SettingsMenuPF2e{static{__name(this,"AutomationSettings")}static{__name2(this,"AutomationSettings")}static namespace="automation";static SETTINGS=["rulesBasedVision","iwr","effectExpiration","removeExpiredEffects","flankingDetection","encumbrance","lootableNPCs"];static get settings(){return{rulesBasedVision:{name:CONFIG.PF2E.SETTINGS.automation.rulesBasedVision.name,hint:CONFIG.PF2E.SETTINGS.automation.rulesBasedVision.hint,default:!0,type:Boolean,requiresReload:!0,onChange:value=>{game.pf2e.settings.rbv=!!value}},iwr:{name:CONFIG.PF2E.SETTINGS.automation.iwr.name,hint:CONFIG.PF2E.SETTINGS.automation.iwr.hint,default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.iwr=!!value}},effectExpiration:{name:CONFIG.PF2E.SETTINGS.automation.effectExpiration.name,hint:CONFIG.PF2E.SETTINGS.automation.effectExpiration.hint,default:!0,type:Boolean,onChange:()=>{for(const actor of game.actors){actor.reset(),actor.sheet.render(!1);for(const token of actor.getActiveTokens())token.drawEffects()}}},removeExpiredEffects:{name:CONFIG.PF2E.SETTINGS.automation.removeExpiredEffects.name,hint:CONFIG.PF2E.SETTINGS.automation.removeExpiredEffects.hint,default:!1,type:Boolean},flankingDetection:{name:CONFIG.PF2E.SETTINGS.automation.flankingDetection.name,hint:CONFIG.PF2E.SETTINGS.automation.flankingDetection.hint,default:!0,type:Boolean},encumbrance:{name:"PF2E.SETTINGS.Automation.Encumbrance.Name",hint:"PF2E.SETTINGS.Automation.Encumbrance.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.encumbrance=!!value}},lootableNPCs:{name:CONFIG.PF2E.SETTINGS.automation.lootableNPCs.name,hint:CONFIG.PF2E.SETTINGS.automation.lootableNPCs.hint,default:!0,type:Boolean}}}}const MetagameSettingsConfig={showDC:{name:"PF2E.SETTINGS.Metagame.ShowDC.Name",hint:"PF2E.SETTINGS.Metagame.ShowDC.Hint",default:!1,type:Boolean},showResults:{name:"PF2E.SETTINGS.Metagame.ShowResults.Name",hint:"PF2E.SETTINGS.Metagame.ShowResults.Hint",default:!0,type:Boolean},tokenSetsNameVisibility:{name:"PF2E.SETTINGS.Metagame.TokenSetsNameVisibility.Name",hint:"PF2E.SETTINGS.Metagame.TokenSetsNameVisibility.Hint",default:!1,type:Boolean,onChange:async value=>{game.pf2e.settings.tokens.nameVisibility=!!value,await ui.combat.render();const renderedMessages=document.querySelectorAll("#chat-log > li");for(const rendered of Array.from(renderedMessages)){const message=game.messages.get(rendered?.dataset.messageId??"");message&&await ui.chat.updateMessage(message)}}},secretDamage:{name:"PF2E.SETTINGS.Metagame.SecretDamage.Name",hint:"PF2E.SETTINGS.Metagame.SecretDamage.Hint",default:!1,type:Boolean},secretCondition:{name:"PF2E.SETTINGS.Metagame.SecretCondition.Name",hint:"PF2E.SETTINGS.Metagame.SecretCondition.Hint",default:!1,type:Boolean},showPartyStats:{name:"PF2E.SETTINGS.Metagame.ShowPartyStats.Name",hint:"PF2E.SETTINGS.Metagame.ShowPartyStats.Hint",default:!0,type:Boolean,onChange:()=>{resetActors(game.actors.filter(a=>a.isOfType("party")))}},partyVision:{name:"PF2E.SETTINGS.Metagame.PartyVision.Name",hint:"PF2E.SETTINGS.Metagame.PartyVision.Hint",default:!1,type:Boolean,onChange:()=>{canvas.ready&&canvas.scene&&canvas.perception.update({initializeVision:!0,refreshLighting:!0},!0)}}};class MetagameSettings extends SettingsMenuPF2e{static{__name(this,"MetagameSettings")}static{__name2(this,"MetagameSettings")}static namespace="metagame";static get settings(){return MetagameSettingsConfig}static get SETTINGS(){return Object.keys(this.settings)}static get prefix(){return`${this.namespace}_`}}const SETTINGS={gradualBoostsVariant:{name:"PF2E.SETTINGS.Variant.GradualBoosts.Name",hint:"PF2E.SETTINGS.Variant.GradualBoosts.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.variants.gab=!!value,resetActors(game.actors.filter(a=>a.type==="character"))}},staminaVariant:{name:"PF2E.SETTINGS.Variant.Stamina.Name",hint:"PF2E.SETTINGS.Variant.Stamina.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.variants.stamina=!!value,resetActors(game.actors.filter(a=>a.type==="character"))}},freeArchetypeVariant:{name:"PF2E.SETTINGS.Variant.FreeArchetype.Name",hint:"PF2E.SETTINGS.Variant.FreeArchetype.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.variants.fa=!!value,resetActors(game.actors.filter(a=>a.type==="character"))}},automaticBonusVariant:{name:"PF2E.SETTINGS.Variant.AutomaticBonus.Name",hint:"PF2E.SETTINGS.Variant.AutomaticBonus.Hint",default:"noABP",type:String,choices:{noABP:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.noABP",ABPFundamentalPotency:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.ABPFundamentalPotency",ABPRulesAsWritten:"PF2E.SETTINGS.Variant.AutomaticBonus.Choices.ABPRulesAsWritten"},onChange:value=>{const choices=["noABP","ABPFundamentalPotency","ABPRulesAsWritten"];game.pf2e.settings.variants.abp=tupleHasValue(choices,value)?value:game.pf2e.settings.variants.abp,resetActors(game.actors.filter(a=>a.type==="character"))}},proficiencyVariant:{name:"PF2E.SETTINGS.Variant.Proficiency.Name",hint:"PF2E.SETTINGS.Variant.Proficiency.Hint",default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.variants.pwol.enabled=!!value,resetActors(game.actors.filter(a=>a.type==="character"))}},proficiencyUntrainedModifier:{name:"PF2E.SETTINGS.Variant.UntrainedModifier.Name",hint:"PF2E.SETTINGS.Variant.UntrainedModifier.Hint",default:-2,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[0]=Number(value)||0}},proficiencyTrainedModifier:{name:"PF2E.SETTINGS.Variant.TrainedModifier.Name",hint:"PF2E.SETTINGS.Variant.TrainedModifier.Hint",default:2,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[1]=Number(value)||0}},proficiencyExpertModifier:{name:"PF2E.SETTINGS.Variant.ExpertModifier.Name",hint:"PF2E.SETTINGS.Variant.ExpertModifier.Hint",default:4,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[2]=Number(value)||0}},proficiencyMasterModifier:{name:"PF2E.SETTINGS.Variant.MasterModifier.Name",hint:"PF2E.SETTINGS.Variant.MasterModifier.Hint",default:6,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[3]=Number(value)||0}},proficiencyLegendaryModifier:{name:"PF2E.SETTINGS.Variant.LegendaryModifier.Name",hint:"PF2E.SETTINGS.Variant.LegendaryModifier.Hint",default:8,type:Number,onChange:value=>{game.pf2e.settings.variants.pwol.modifiers[4]=Number(value)||0}}};class VariantRulesSettings extends FormApplication{static{__name(this,"VariantRulesSettings")}static{__name2(this,"VariantRulesSettings")}static get defaultOptions(){return{...super.defaultOptions,title:"PF2E.SETTINGS.Variant.Title",id:"variant-rules-settings",template:"systems/pf2e/templates/system/settings/variant-rules.hbs",width:550,height:"auto",closeOnSubmit:!0}}async getData(){return Object.entries(SETTINGS).reduce((data,[key,setting])=>({...data,[key]:{value:game.settings.get("pf2e",key),setting}}),{})}static registerSettings(){for(const[key,value]of Object.entries(SETTINGS))value.config=!1,value.scope="world",game.settings.register("pf2e",key,value)}activateListeners($html){super.activateListeners($html),htmlQuery($html[0],"button[name=reset]")?.addEventListener("click",async event2=>{event2.preventDefault();for(const[key,value]of Object.entries(SETTINGS))await game.settings.set("pf2e",key,value?.default);return this.render()})}async _updateObject(_event,data){for(const key of Object.keys(SETTINGS))game.settings.set("pf2e",key,data[key])}}class WorldClockSettings extends FormApplication{static{__name(this,"WorldClockSettings")}static{__name2(this,"WorldClockSettings")}static get defaultOptions(){return foundry.utils.mergeObject(super.defaultOptions,{title:CONFIG.PF2E.SETTINGS.worldClock.name,id:"world-clock-settings",template:"systems/pf2e/templates/system/settings/world-clock/index.hbs",width:550,height:"auto",closeOnSubmit:!0})}async getData(){const worldDefault=game.settings.get("pf2e","worldClock.syncDarkness")?game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.enabled):game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.disabled),sceneSetting=["syncDarknessScene",{name:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.name,hint:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.hint,default:"default",type:String,choices:{enabled:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.enabled,disabled:CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.disabled,default:game.i18n.format(CONFIG.PF2E.SETTINGS.worldClock.syncDarknessScene.default,{worldDefault})}}],settings=[...Object.entries(WorldClockSettings.settings).filter(([key])=>key!=="worldCreatedOn"),sceneSetting].map(([key,setting])=>{const value=(()=>{if(key==="syncDarknessScene")return canvas.scene?.flags.pf2e.syncDarkness;const rawValue=game.settings.get("pf2e",`worldClock.${key}`);return key==="worldCreatedOn"&&typeof rawValue=="string"?DateTime.fromISO(rawValue).toFormat("yyyy-MM-dd'T'HH:mm"):rawValue})();return{...setting,key,value,isSelect:"choices"in setting,isCheckbox:setting.type===Boolean,isDateTime:setting.type===String&&!("choices"in setting)}});return foundry.utils.mergeObject(await super.getData(),{settings})}static registerSettings(){game.settings.register("pf2e","worldClock.dateTheme",this.settings.dateTheme),game.settings.register("pf2e","worldClock.timeConvention",this.settings.timeConvention),game.settings.register("pf2e","worldClock.playersCanView",this.settings.playersCanView),game.settings.register("pf2e","worldClock.syncDarkness",this.settings.syncDarkness),game.settings.register("pf2e","worldClock.worldCreatedOn",this.settings.worldCreatedOn),game.settings.register("pf2e","worldClock.showClockButton",this.settings.showClockButton)}activateListeners($html){super.activateListeners($html);const localize=localizer("PF2E.SETTINGS.WorldClock"),title=localize("ResetWorldTime.Name");$html.find("button.reset-world-time").on("click",async()=>{const template=await renderTemplate("systems/pf2e/templates/system/settings/world-clock/confirm-reset.hbs");Dialog.confirm({title,content:template,yes:()=>{game.time.advance(-1*game.time.worldTime),this.close()},defaultYes:!1})}),$html.find('input[name="syncDarkness"]').on("change",event2=>{const worldDefault=$(event2.currentTarget)[0].checked?localize("SyncDarknessScene.Enabled"):localize("SyncDarknessScene.Disabled"),optionSelector='select[name="syncDarknessScene"] > option[value="default"]';$html.find(optionSelector).text(localize("SyncDarknessScene.Default",{worldDefault}))})}async _updateObject(_event,data){const keys2=["dateTheme","timeConvention","playersCanView","syncDarkness","showClockButton"];for(const key of keys2){const settingKey=`worldClock.${key}`,newValue=key==="worldCreatedOn"?DateTime.fromISO(data[key]).toUTC():data[key];await game.settings.set("pf2e",settingKey,newValue)}await canvas.scene?.setFlag("pf2e","syncDarkness",data.syncDarknessScene??"default"),delete data.syncDarknessScene,game.pf2e.worldClock.render(!1)}static get settings(){return{dateTheme:{name:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.name,hint:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.hint,scope:"world",config:!1,default:"AR",type:String,choices:{AR:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.AR,AD:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.AD,CE:CONFIG.PF2E.SETTINGS.worldClock.dateTheme.CE}},timeConvention:{name:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.name,hint:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.hint,scope:"world",config:!1,default:24,type:Number,choices:{24:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.twentyFour,12:CONFIG.PF2E.SETTINGS.worldClock.timeConvention.twelve}},showClockButton:{name:CONFIG.PF2E.SETTINGS.worldClock.showClockButton.name,hint:CONFIG.PF2E.SETTINGS.worldClock.showClockButton.hint,scope:"world",config:!1,default:!0,type:Boolean,onChange:()=>{game.settings.set("pf2e","worldClock.playersCanView",game.settings.get("pf2e","worldClock.showClockButton"))}},playersCanView:{name:CONFIG.PF2E.SETTINGS.worldClock.playersCanView.name,hint:CONFIG.PF2E.SETTINGS.worldClock.playersCanView.hint,scope:"world",config:!1,default:!1,type:Boolean},syncDarkness:{name:CONFIG.PF2E.SETTINGS.worldClock.syncDarkness.name,hint:CONFIG.PF2E.SETTINGS.worldClock.syncDarkness.hint,scope:"world",config:!1,default:!1,type:Boolean},worldCreatedOn:{name:CONFIG.PF2E.SETTINGS.worldClock.worldCreatedOn.name,hint:CONFIG.PF2E.SETTINGS.worldClock.worldCreatedOn.hint,scope:"world",config:!1,default:DateTime.utc().toISO(),type:String}}}}function registerSettings(){game.settings.register("pf2e","tokens.autoscale",{name:"PF2E.SETTINGS.Tokens.Autoscale.Name",hint:"PF2E.SETTINGS.Tokens.Autoscale.Hint",scope:"world",config:!0,default:!0,type:Boolean,onChange:value=>{game.pf2e.settings.tokens.autoscale=!!value}}),game.settings.register("pf2e","identifyMagicNotMatchingTraditionModifier",{name:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Name",hint:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Hint",choices:{0:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.0",2:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.2",5:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.5",10:"PF2E.SETTINGS.IdentifyMagicNotMatchingTraditionModifier.Choices.10"},type:Number,default:5,scope:"world",config:!0}),game.settings.register("pf2e","critRule",{name:"PF2E.SETTINGS.CritRule.Name",hint:"PF2E.SETTINGS.CritRule.Hint",scope:"world",config:!0,default:"doubledamage",type:String,choices:{doubledamage:"PF2E.SETTINGS.CritRule.Choices.Doubledamage",doubledice:"PF2E.SETTINGS.CritRule.Choices.Doubledice"},onChange:()=>{for(const sheet of Object.values(ui.windows).filter(w=>w instanceof ActorSheetPF2e))sheet.render()}}),game.settings.register("pf2e","compendiumBrowserPacks",{name:"PF2E.SETTINGS.CompendiumBrowserPacks.Name",hint:"PF2E.SETTINGS.CompendiumBrowserPacks.Hint",default:{},type:Object,scope:"world",onChange:()=>{game.pf2e.compendiumBrowser.initCompendiumList()}}),game.settings.register("pf2e","compendiumBrowserSources",{name:"PF2E.SETTINGS.compendiumBrowserSources.Name",hint:"PF2E.SETTINGS.compendiumBrowserSources.Hint",default:{ignoreAsGM:!0,showEmptySources:!0,showUnknownSources:!0,sources:{}},type:Object,scope:"world",onChange:()=>{game.pf2e.compendiumBrowser.packLoader.reset(),game.pf2e.compendiumBrowser.initCompendiumList()}}),game.settings.register("pf2e","enabledRulesUI",{name:"PF2E.SETTINGS.EnabledRulesUI.Name",hint:"PF2E.SETTINGS.EnabledRulesUI.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:()=>{const itemSheets=Object.values(ui.windows).filter(w=>w instanceof ItemSheetPF2e);for(const sheet of itemSheets)sheet.render()}}),game.settings.register("pf2e","critFumbleButtons",{name:game.i18n.localize("PF2E.SETTINGS.critFumbleCardButtons.name"),hint:game.i18n.localize("PF2E.SETTINGS.critFumbleCardButtons.hint"),scope:"world",config:!0,default:!1,type:Boolean,requiresReload:!0}),game.settings.register("pf2e","drawCritFumble",{name:game.i18n.localize("PF2E.SETTINGS.critFumbleCards.name"),hint:game.i18n.localize("PF2E.SETTINGS.critFumbleCards.hint"),scope:"world",config:!0,default:!1,type:Boolean,requiresReload:!0});const iconChoices={blackWhite:"PF2E.SETTINGS.statusEffectType.blackWhite",default:"PF2E.SETTINGS.statusEffectType.default"};game.settings.register("pf2e","statusEffectType",{name:"PF2E.SETTINGS.statusEffectType.name",hint:"PF2E.SETTINGS.statusEffectType.hint",scope:"world",config:!0,default:"default",type:String,choices:iconChoices,onChange:iconType=>{StatusEffects.migrateStatusEffectUrls(iconType)}}),game.settings.register("pf2e","totmToggles",{name:"PF2E.SETTINGS.TOTMToggles.Name",hint:"PF2E.SETTINGS.TOTMToggles.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.totm=!!value,resetActors()}}),game.settings.register("pf2e","deathIcon",{name:"PF2E.SETTINGS.DeathIcon.Name",hint:"PF2E.SETTINGS.DeathIcon.Hint",scope:"world",config:!1,default:"icons/svg/skull.svg",type:String,onChange:choice=>{isImageOrVideoPath(choice)?StatusEffects.reset():choice||game.settings.set("pf2e","deathIcon","icons/svg/skull.svg")}}),game.settings.register("pf2e","nathMode",{name:"PF2E.SETTINGS.NathMode.Name",hint:"PF2E.SETTINGS.NathMode.Hint",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("pf2e","statusEffectShowCombatMessage",{name:"PF2E.SETTINGS.statusEffectShowCombatMessage.name",hint:"PF2E.SETTINGS.statusEffectShowCombatMessage.hint",scope:"world",config:!0,default:!0,type:Boolean}),game.settings.registerMenu("pf2e","automation",{name:"PF2E.SETTINGS.Automation.Name",label:"PF2E.SETTINGS.Automation.Label",hint:"PF2E.SETTINGS.Automation.Hint",icon:"fa-solid fa-robot",type:AutomationSettings,restricted:!0}),game.settings.register("pf2e","automation.actorsDeadAtZero",{name:CONFIG.PF2E.SETTINGS.automation.actorsDeadAtZero.name,scope:"world",config:!1,choices:{neither:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Neither",npcsOnly:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.NPCsOnly",both:"PF2E.SETTINGS.Automation.ActorsDeadAtZero.Both"},default:"both",type:String}),AutomationSettings.registerSettings(),game.settings.registerMenu("pf2e","metagame",{name:"PF2E.SETTINGS.Metagame.Name",label:"PF2E.SETTINGS.Metagame.Label",hint:"PF2E.SETTINGS.Metagame.Hint",icon:"fa-solid fa-brain",type:MetagameSettings,restricted:!0}),MetagameSettings.registerSettings(),game.settings.registerMenu("pf2e","variantRules",{name:"PF2E.SETTINGS.Variant.Name",label:"PF2E.SETTINGS.Variant.Label",hint:"PF2E.SETTINGS.Variant.Hint",icon:"fa-solid fa-book",type:VariantRulesSettings,restricted:!0}),VariantRulesSettings.registerSettings(),game.settings.registerMenu("pf2e","homebrew",{name:"PF2E.SETTINGS.Homebrew.Name",label:"PF2E.SETTINGS.Homebrew.Label",hint:"PF2E.SETTINGS.Homebrew.Hint",icon:"fa-solid fa-beer",type:HomebrewElements,restricted:!0}),HomebrewElements.registerSettings(),game.settings.registerMenu("pf2e","worldClock",{name:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.name),label:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.label),hint:game.i18n.localize(CONFIG.PF2E.SETTINGS.worldClock.hint),icon:"fa-regular fa-clock",type:WorldClockSettings,restricted:!0}),WorldClockSettings.registerSettings(),game.settings.register("pf2e","campaignType",{name:"PF2E.SETTINGS.CampaignType.Name",hint:"PF2E.SETTINGS.CampaignType.Hint",scope:"world",config:!1,default:"none",choices:mapToObj(["none","kingmaker"],key=>[key,`PF2E.SETTINGS.CampaignType.Choices.${key}`]),type:String,onChange:async()=>{await resetActors(game.actors.filter(a=>a.isOfType("party"))),ui.sidebar.render()}}),game.settings.register("pf2e","campaignFeats",{name:"PF2E.SETTINGS.CampaignFeats.Name",hint:"PF2E.SETTINGS.CampaignFeats.Hint",scope:"world",config:!0,default:!1,type:Boolean,onChange:value=>{game.pf2e.settings.campaign.enabled=!!value,resetActors(game.actors.filter(a=>a.isOfType("character")))}}),game.settings.register("pf2e","campaignFeatSections",{name:"Campaign Feat Sections",scope:"world",config:!1,default:[],type:Array,onChange:value=>{game.pf2e.settings.campaign.sections=Array.isArray(value)?value:game.pf2e.settings.campaign.sections,resetActors(game.actors.filter(a=>a.isOfType("character")))}}),game.settings.register("pf2e","RAI.TreatWoundsAltSkills",{name:"Treat Wounds Macro Compat",scope:"world",config:!1,default:!0,type:Boolean}),game.settings.register("pf2e","gmVision",{name:"PF2E.SETTINGS.GMVision",scope:"client",config:!1,default:!1,type:Boolean,onChange:value=>{const color=value?CONFIG.PF2E.Canvas.darkness.gmVision:CONFIG.PF2E.Canvas.darkness.default;CONFIG.Canvas.darknessColor=color,canvas.colorManager.initialize()}}),game.settings.register("pf2e","seenLastStopMessage",{name:"Seen Last Stop Before Remaster Message",scope:"world",config:!1,type:Boolean,default:!1}),registerTrackingSettings(),registerWorldSchemaVersion()}__name(registerSettings,"registerSettings"),__name2(registerSettings,"registerSettings");function registerTrackingSettings(){game.settings.register("pf2e","createdFirstParty",{name:"Created First Party",scope:"world",config:!1,default:!1,type:Boolean}),game.settings.register("pf2e","activeParty",{name:"Active Party",scope:"world",config:!1,type:String,default:"",onChange:()=>{ui.actors.render(!0)}}),game.settings.register("pf2e","activePartyFolderState",{name:"Active Party Opened or closed",scope:"client",config:!1,type:Boolean,default:!0}),game.settings.register("pf2e","worldSystemVersion",{name:"World System Version",scope:"world",config:!1,default:game.system.version,type:String}),game.settings.register("pf2e","seenRemasterJournalEntry",{name:"Seen Remaster journal entry?",scope:"world",config:!1,default:!1,type:Boolean})}__name(registerTrackingSettings,"registerTrackingSettings"),__name2(registerTrackingSettings,"registerTrackingSettings");function registerWorldSchemaVersion(){game.settings.register("pf2e","worldSchemaVersion",{name:"PF2E.SETTINGS.WorldSchemaVersion.Name",hint:"PF2E.SETTINGS.WorldSchemaVersion.Hint",scope:"world",config:!0,default:MigrationRunner.LATEST_SCHEMA_VERSION,type:Number,requiresReload:!0})}__name(registerWorldSchemaVersion,"registerWorldSchemaVersion"),__name2(registerWorldSchemaVersion,"registerWorldSchemaVersion");const Init={listen:()=>{Hooks.once("init",()=>{if(console.log("PF2e System | Initializing Pathfinder 2nd Edition System"),CONFIG.PF2E=PF2ECONFIG,CONFIG.debug.ruleElement??=!1,CONFIG.AmbientLight.layerClass=LightingLayerPF2e,CONFIG.AmbientLight.objectClass=AmbientLightPF2e,CONFIG.MeasuredTemplate.objectClass=MeasuredTemplatePF2e,CONFIG.MeasuredTemplate.layerClass=TemplateLayerPF2e,CONFIG.MeasuredTemplate.defaults.angle=90,CONFIG.MeasuredTemplate.defaults.width=1,CONFIG.Token.objectClass=TokenPF2e,CONFIG.Token.layerClass=TokenLayerPF2e,CONFIG.Canvas.groups.effects.groupClass=EffectsCanvasGroupPF2e,CONFIG.Canvas.layers.lighting.layerClass=LightingLayerPF2e,CONFIG.Canvas.layers.templates.layerClass=TemplateLayerPF2e,CONFIG.Canvas.layers.tokens.layerClass=TokenLayerPF2e,setPerceptionModes(),CONFIG.time.roundTime=6,CONFIG.Combat.initiative.decimals=0,CONFIG.ui.actors=ActorDirectoryPF2e,CONFIG.ui.items=ItemDirectoryPF2e,CONFIG.ui.combat=EncounterTrackerPF2e,CONFIG.ui.chat=ChatLogPF2e,CONFIG.ui.compendium=CompendiumDirectoryPF2e,CONFIG.ui.hotbar=HotbarPF2e,CONFIG.specialStatusEffects.BLIND="blinded",document.querySelector("#ui-top")!==null){const uiTop=document.querySelector("#ui-top"),template=document.createElement("template");template.setAttribute("id","pf2e-effects-panel"),uiTop?.insertAdjacentElement("afterend",template)}CONFIG.TinyMCE.extended_valid_elements="pf2-action[action|glyph]",CONFIG.TinyMCE.content_css.push("systems/pf2e/styles/pf2e.css"),CONFIG.TinyMCE.style_formats=(CONFIG.TinyMCE.style_formats??[]).concat({title:"PF2E",items:[{title:"Icons 1 2 3 F R",inline:"span",classes:["action-glyph"],wrapper:!0},{title:"Inline Header",block:"h4",classes:"inline-header"},{title:"Info Block",block:"section",classes:"info",wrapper:!0,exact:!0,merge_siblings:!1},{title:"Stat Block",block:"section",classes:"statblock",wrapper:!0,exact:!0,merge_siblings:!1},{title:"Trait",block:"section",classes:"traits",wrapper:!0},{title:"Written Note",block:"p",classes:"message"},{title:"GM Text Block",block:"div",wrapper:!0,attributes:{"data-visibility":"gm"}},{title:"GM Text Inline",inline:"span",attributes:{"data-visibility":"gm"}}]}),CONFIG.TextEditor.enrichers.push({pattern:new RegExp(/@(Check|Localize|Template)\[([^\]]+)\](?:{([^}]+)})?/,"g"),enricher:(match,options)=>game.pf2e.TextEditor.enrichString(match,options)}),CONFIG.TextEditor.enrichers.push({pattern:new RegExp(/@(Damage)\[((?:[^[\]]*|\[[^[\]]*\])*)\](?:{([^}]+)})?/,"g"),enricher:(match,options)=>game.pf2e.TextEditor.enrichString(match,options)}),registerFonts(),registerHandlebarsHelpers(),registerKeybindings(),registerSettings(),registerTemplates(),MystifiedTraits.compile(),SetGamePF2e.onInit();for(const element of htmlQueryAll(document.head,"link[rel=stylesheet]")){const href=element.getAttribute("href");href?.startsWith("modules/")&&href.endsWith("tagify.css")&&element.setAttribute("disabled","")}game.pf2e.StatusEffects.initialize()})}},LightingRefresh={listen:()=>{Hooks.on("lightingRefresh",()=>{SceneDarknessAdjuster.instance.onLightingRefresh(canvas.darknessLevel)})}};class ActiveEffectPF2e extends ActiveEffect{static{__name(this,"ActiveEffectPF2e")}static{__name2(this,"ActiveEffectPF2e")}constructor(data,context){data.disabled=!0,data.transfer=!1,super(data,context)}static async createDocuments(){return[]}}class ActorsPF2e extends Actors{static{__name(this,"ActorsPF2e")}static{__name2(this,"ActorsPF2e")}get party(){const activePartyId=game.settings.get("pf2e","activeParty"),actor=this.get(activePartyId);return actor?.isOfType("party")?actor:this.find(a=>a.isOfType("party"))??null}_getVisibleTreeContents(){return super._getVisibleTreeContents().filter(a=>a.isOfType("creature")&&!a.parties.size||!a.isOfType("party","creature"))}}class ActorDeltaPF2e extends ActorDelta{static{__name(this,"ActorDeltaPF2e")}static{__name2(this,"ActorDeltaPF2e")}prepareData(){super.prepareData(),!game.ready&&!this.parent?.isLinked&&this.syntheticActor?.reset()}_onUpdate(changed,options,userId){super._onUpdate(changed,options,userId),changed.system?.traits?.size&&this.parent?.rendered&&this.parent.object?._onUpdate({width:this.parent.width},{...options,parent:this.parent.scene},userId)}_dispatchDescendantDocumentEvents(event2,collection,args,parent){super._dispatchDescendantDocumentEvents(event2,collection,args,parent);const isPostWriteCallback=["onCreate","onUpdate","onDelete"].includes(event2);if(!this.parent||this.parent.isLinked||!this.parent.rendered||!isPostWriteCallback)return;const items=(args[0]??[]).filter(i=>i instanceof ItemPF2e),nameChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenName")),sizeChanged=items.some(i=>i.system.rules.some(r=>r.key==="CreatureSize")),textureChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenImage"))||!!this.syntheticActor?.rules.some(r=>r.key==="TokenImage"),lightChanged=items.some(i=>i.system.rules.some(r=>r.key==="TokenLight"));if(nameChanged||sizeChanged||textureChanged||lightChanged){this.parent.reset();const fakeUpdates={};nameChanged&&(fakeUpdates.name=this.parent.name),sizeChanged&&(fakeUpdates.width=this.parent.width),textureChanged&&(fakeUpdates.texture=foundry.utils.deepClone(this.parent._source.texture)),lightChanged&&(fakeUpdates.light=foundry.utils.deepClone(this.parent._source.light)),this.parent.object?._onUpdate(fakeUpdates,{parent:this.parent.scene},game.user.id)}}}function monkeyPatchFoundry(){TextEditor.enrichHTML=TextEditorPF2e.enrichHTML,TextEditor._enrichContentLinks=TextEditorPF2e._enrichContentLinks,TextEditor._createInlineRoll=TextEditorPF2e._createInlineRoll,TextEditor._onClickInlineRoll=TextEditorPF2e._onClickInlineRoll}__name(monkeyPatchFoundry,"monkeyPatchFoundry"),__name2(monkeyPatchFoundry,"monkeyPatchFoundry");class ClientDatabaseBackendPF2e extends ClientDatabaseBackend{static{__name(this,"ClientDatabaseBackendPF2e")}static{__name2(this,"ClientDatabaseBackendPF2e")}async _getDocuments(documentClass,context,user){const type=documentClass.documentName;if(!["Actor","Item"].includes(type)||context.pack?.startsWith("pf2e.")||context.options?.index)return super._getDocuments(documentClass,context,user);const request2={action:"get",type,...pick(context,["query","options","pack"])},response=await SocketInterface.dispatch("modifyDocument",request2);return Promise.all(response.result.map(async data=>{const document2=documentClass.fromSource(data,{pack:context.pack}),migrations=MigrationList.constructFromVersion(document2.schemaVersion);if(migrations.length>0)try{await MigrationRunner.ensureSchemaVersion(document2,migrations)}catch(error){error instanceof Error&&console.error(error.message)}return document2}))}}const Load={listen(){CONFIG.DatabaseBackend=new ClientDatabaseBackendPF2e,CONFIG.ActiveEffect.documentClass=ActiveEffectPF2e,CONFIG.Actor.collection=ActorsPF2e,CONFIG.Actor.documentClass=ActorProxyPF2e,CONFIG.ActorDelta.documentClass=ActorDeltaPF2e,CONFIG.AmbientLight.documentClass=AmbientLightDocumentPF2e,CONFIG.ChatMessage.documentClass=ChatMessagePF2e,CONFIG.Combat.documentClass=EncounterPF2e,CONFIG.Combatant.documentClass=CombatantPF2e,CONFIG.Item.documentClass=ItemProxyPF2e,CONFIG.Macro.documentClass=MacroPF2e,CONFIG.MeasuredTemplate.documentClass=MeasuredTemplateDocumentPF2e,CONFIG.Scene.documentClass=ScenePF2e,CONFIG.Tile.documentClass=TileDocumentPF2e,CONFIG.Token.documentClass=TokenDocumentPF2e,CONFIG.Token.prototypeSheetClass=TokenConfigPF2e,CONFIG.User.documentClass=UserPF2e,CONFIG.Canvas.darknessColor=2960722,CONFIG.Canvas.exploredColor=2500134,CONFIG.Dice.rolls.push(CheckRoll,StrikeAttackRoll,DamageRoll,DamageInstance);for(const TermCls of[ArithmeticExpression,Grouping,InstancePool,IntermediateDie])CONFIG.Dice.termTypes[TermCls.name]=TermCls;Math.eq=(a,b)=>a===b,Math.gt=(a,b)=>a>b,Math.gte=(a,b)=>a>=b,Math.lt=(a,b)=>aa<=b,Math.ne=(a,b)=>a!==b,Math.ternary=(condition,ifTrue,ifFalse)=>condition?ifTrue:ifFalse,Actor.DEFAULT_ICON="systems/pf2e/icons/default-icons/mystery-man.svg",CONFIG.Actor.typeIcons={familiar:"fa-solid fa-cat",hazard:"fa-solid fa-hill-rockslide",loot:"fa-solid fa-treasure-chest"},CONFIG.Item.typeIcons={action:"fa-solid fa-person-running-fast",affliction:"fa-solid fa-biohazard",armor:"fa-solid fa-shirt-long-sleeve",backpack:"fa-solid fa-sack",book:"fa-solid fa-book",condition:"fa-solid fa-face-zany",consumable:"fa-solid fa-flask-round-potion",deity:"fa-solid fa-hamsa",effect:"fa-solid fa-person-rays",equipment:"fa-solid fa-hat-cowboy",feat:"fa-solid fa-medal",shield:"fa-solid fa-shield-halved",spell:"fa-solid fa-sparkles",treasure:"fa-solid fa-gem",weapon:"fa-solid fa-sword"},window.AutomaticBonusProgression=AutomaticBonusProgression,monkeyPatchFoundry(),document.addEventListener("mouseup",()=>{const element=document.activeElement;element instanceof HTMLButtonElement&&!element.classList.contains("pm-dropdown")&&element.blur()})}};async function createFirstParty(){game.user!==game.users.activeGM||game.settings.get("pf2e","createdFirstParty")||(game.actors.some(a=>a.isOfType("party"))||(await ActorPF2e.create({_id:CONFIG.PF2E.defaultPartyId,type:"party",name:game.i18n.localize("PF2E.Actor.Party.DefaultName")},{keepId:!0}),await game.settings.set("pf2e","activeParty",CONFIG.PF2E.defaultPartyId)),await game.settings.set("pf2e","createdFirstParty",!0))}__name(createFirstParty,"createFirstParty"),__name2(createFirstParty,"createFirstParty");class MigrationSummary extends Application{static{__name(this,"MigrationSummary")}static{__name2(this,"MigrationSummary")}#isRemigrating=!1;constructor(options={}){super(options),this.options.troubleshoot??=!1,this.options.title=options.troubleshoot?game.i18n.localize("PF2E.Migrations.Summary.Troubleshoot.Title"):game.i18n.localize("PF2E.Migrations.Summary.Title");const existing=Object.values(ui.windows).find(app=>app instanceof MigrationSummary);if(existing)return existing.options=foundry.utils.mergeObject(existing.options,options),existing}static get defaultOptions(){return{...super.defaultOptions,id:"migration-summary",width:400,height:"auto",template:"systems/pf2e/templates/system/migration-summary.hbs"}}async getData(){const latestSchemaVersion=MigrationRunner.LATEST_SCHEMA_VERSION,actors={successful:game.actors.filter(actor=>actor.schemaVersion===latestSchemaVersion).length,total:game.actors.size},items={successful:game.items.filter(item=>item.schemaVersion===latestSchemaVersion).length,total:game.items.size},canRemigrate=this.options.troubleshoot||actors.successful{const{LATEST_SCHEMA_VERSION,RECOMMENDED_SAFE_VERSION}=MigrationRunner,lowestVersions={actor:game.actors.size>0?Math.min(...game.actors.map(a=>a.schemaVersion??0)):LATEST_SCHEMA_VERSION,item:game.items.size>0?Math.min(...game.items.map(a=>a.schemaVersion??0)):LATEST_SCHEMA_VERSION},lowestSchemaVersion=Math.max(Math.min(lowestVersions.actor,lowestVersions.item),RECOMMENDED_SAFE_VERSION),result=html.querySelector(".docs-successful");result&&(result.textContent="...");try{this.#isRemigrating=!0,this.options.troubleshoot=!1,remigrateButton.disabled=!0,await game.pf2e.system.remigrate({from:lowestSchemaVersion}),this.options.troubleshoot=!1,this.render(!1)}catch{return}}),html.querySelector("button[data-action=close]")?.addEventListener("click",()=>{this.close()})}}function activateSocketListener(){game.socket.on("system.pf2e",async(...[message,userId])=>{const sender=game.users.get(userId,{strict:!0});switch(message.request){case"itemTransfer":if(game.user.isGM){console.debug(`PF2e System | Received item-transfer request from ${sender.name}`);const{data}=message;new ItemTransfer(data.source,data.target,data.quantity,data.containerId).enact(sender)}break;case"refreshSceneControls":!game.user.isGM&&message.data.layer===ui.controls.control?.layer&&(console.debug("PF2e System | Refreshing Scene Controls"),ui.controls.initialize({layer:message.data.layer}));break;case"showSheet":{const document2=await fromUuid(message.document);if(!sender.isGM||!document2)return;const{tab,campaign}=message.options??{};if(campaign){if(!(document2 instanceof PartyPF2e))return;const type=campaign===!0?null:campaign;return document2.campaign?.renderSheet?.({tab,type})}document2.sheet.render(!0,{tab});break}default:throw ErrorPF2e(`Received unrecognized socket emission: ${message.request}`)}})}__name(activateSocketListener,"activateSocketListener"),__name2(activateSocketListener,"activateSocketListener");async function storeInitialWorldVersions(){if(!game.user.hasRole(CONST.USER_ROLES.GAMEMASTER))return;if(game.settings.storage.get("world").getItem("pf2e.worldSystemVersion")||await game.settings.set("pf2e","worldSystemVersion",game.system.version),!game.settings.storage.get("world").getItem("pf2e.worldSchemaVersion")){const minimumVersion=MigrationRunner.RECOMMENDED_SAFE_VERSION,currentVersion=game.actors.size===0?game.settings.get("pf2e","worldSchemaVersion"):Math.max(Math.min(...new Set(game.actors.map(actor=>actor.schemaVersion??minimumVersion))),minimumVersion);await game.settings.set("pf2e","worldSchemaVersion",currentVersion)}}__name(storeInitialWorldVersions,"storeInitialWorldVersions"),__name2(storeInitialWorldVersions,"storeInitialWorldVersions");function extendDragData(){document.body.addEventListener("dragstart",event2=>{const{dataTransfer,target}=event2;if(dataTransfer&&target instanceof HTMLAnchorElement){if(target.classList.contains("content-link")){const data=JSON.parse(dataTransfer.getData("text/plain"));if(data.type!=="Item")return;const match=target.innerText.trim().match(/[0-9]+/);match&&(data.value=Number(match[0]));const containerElement=htmlClosest(target,"[data-cast-level]"),castLevel=Number(containerElement?.dataset.castLevel);castLevel>0&&(data.level=castLevel);const messageId=htmlClosest(target,"li.chat-message")?.dataset.messageId,message=game.messages.get(messageId??""),originItem=message?.item;if(message?.actor){const{actor,token,target:target2}=message,roll=message.rolls.at(-1),spellcasting=originItem?.isOfType("spell")&&originItem.spellcasting?{attribute:{type:originItem.attribute,mod:originItem.spellcasting.statistic?.attributeModifier?.value??0},tradition:originItem.spellcasting.tradition}:null;data.context={origin:{actor:actor.uuid,token:token?.uuid??null,item:originItem?.uuid??null,spellcasting},target:target2?{actor:target2.actor.uuid,token:target2.token.uuid}:null,roll:roll?{total:roll.total,degreeOfSuccess:roll instanceof CheckRoll?roll.degreeOfSuccess??null:null}:null}}dataTransfer.setData("text/plain",JSON.stringify(data))}else if("persistent"in target.dataset&&target.dataset.formula){const data={type:"PersistentDamage",formula:target.dataset.formula};dataTransfer.setData("text/plain",JSON.stringify(data))}}})}__name(extendDragData,"extendDragData"),__name2(extendDragData,"extendDragData");const Ready={listen:()=>{Hooks.once("ready",()=>{console.log("PF2e System | Starting Pathfinder 2nd Edition System"),console.debug("PF2e System | Build mode: production"),SetGamePF2e.onReady(),game.scenes.apps.push(SceneDarknessAdjuster.instance);const currentVersion=game.settings.get("pf2e","worldSchemaVersion");storeInitialWorldVersions().then(async()=>{if(game.user!==game.users.activeGM)return;await createFirstParty();const migrationRunner=new MigrationRunner(MigrationList.constructFromVersion(currentVersion));migrationRunner.needsMigration()&&(currentVersion&¤tVersionm.active&&(m.esmodules.size>0||m.scripts.size>0)&&!!m.compatibility.verified&&(abandonedModules.has(m.id)||!foundry.utils.isNewerVersion(m.compatibility.verified,"10.312")));for(const badModule of subV10Modules){const message=game.i18n.format("PF2E.ErrorMessage.SubV9Module",{module:badModule.title});ui.notifications.warn(message),console.warn(message)}});for(const li of htmlQueryAll(document.body,"#chat-log > li.message"))SetAsInitiative.listen(li);activateSocketListener(),extendDragData(),canvas.ready&&game.user.isGM&&!game.modules.get("gm-vision")?.active&&!game.modules.get("perfect-vision")?.active&&game.settings.get("pf2e","gmVision")&&(CONFIG.Canvas.darknessColor=CONFIG.PF2E.Canvas.darkness.gmVision,canvas.colorManager.initialize()),game.system.documentTypes.Item.sort((typeA,typeB)=>game.i18n.localize(CONFIG.Item.typeLabels[typeA]??"").localeCompare(game.i18n.localize(CONFIG.Item.typeLabels[typeB]??""))),game.pf2e.system.moduleArt.refresh().then(()=>{ui.compendium.compileSearchIndex()});const actorsToReprepare=compact([...game.combats.contents.flatMap(e=>e.combatants.contents).map(c=>c.actor),...game.actors.filter(a=>a.isOfType("party")).flatMap(p=>p.members).filter(a=>!a.isOfType("familiar")),...game.actors.filter(a=>a.type==="familiar")]);if(resetActors(new Set(actorsToReprepare)),game.user.isGM&&!game.settings.get("pf2e","seenRemasterJournalEntry")&&(fromUuid("Compendium.pf2e.journals.JournalEntry.6L2eweJuM8W7OCf2").then(entry=>{entry?.sheet.render(!0)}),game.settings.set("pf2e","seenRemasterJournalEntry",!0)),game.combat){for(const encounter of game.combats)encounter.reset();ui.combat.render()}Hooks.callAll("pf2e.systemReady")})}},RenderChatPopout={listen:()=>{Hooks.on("renderChatPopout",(_app,$html)=>{ui.chat.activateClickListener($html[0])})}},RenderCombatTrackerConfig={listen:()=>{Hooks.on("renderCombatTrackerConfig",async(app,$html)=>{const html=$html[0],appWindow=htmlClosest(html,"#combat-config");appWindow&&(appWindow.style.height="");const template=await(async()=>{const markup=await renderTemplate("systems/pf2e/templates/sidebar/encounter-tracker/config.hbs",{values:{deathIcon:game.settings.get("pf2e","deathIcon"),actorsDeadAtZero:game.settings.get("pf2e","automation.actorsDeadAtZero")}}),tempElem=document.createElement("div");return tempElem.innerHTML=markup,tempElem.firstElementChild instanceof HTMLTemplateElement?tempElem.firstElementChild:null})();htmlQueryAll(html,".form-group").at(-1)?.after(...template?.content.children??[]),app.activateListeners($html)})}},PC_ITEM_TYPES=new Set(["ancestry","background","class","deity","feat","heritage"]),RenderDialog={listen:()=>{Hooks.on("renderDialog",(_dialog,$html)=>{const html=$html[0];if(InlineRollLinks.listen(html),html.classList.contains("dialog-item-create")){const select=html.querySelector("select[name=type]"),option=select?.querySelector("option");if(select&&option){const localize=localizer("PF2E.Item.CreationDialog.Categories");select.append(extractOptGroup(select,localize("Physical"),[...PHYSICAL_ITEM_TYPES,"kit"])),select.append(extractOptGroup(select,localize("Character"),Array.from(PC_ITEM_TYPES))),select.append(extractOptGroup(select,localize("Other"))),option.selected=!0}}})}};function extractOptGroup(select,label,types){const filtered=[...select.querySelectorAll(":scope > option").values()].filter(option=>!types||types.includes(option.value)),optgroup=document.createElement("optgroup");optgroup.label=label;for(const physicalElement of filtered)optgroup.appendChild(physicalElement);return optgroup}__name(extractOptGroup,"extractOptGroup"),__name2(extractOptGroup,"extractOptGroup");const RenderJournalPageSheet={listen:()=>{Hooks.on("renderJournalPageSheet",(sheet,$html)=>{const pageEl=$html.get(0)?.closest(".journal-entry-page"),parentSheetClass=sheet.object.parent?.sheet.constructor;if(!parentSheetClass||!pageEl)return;const theme=parentSheetClass.theme?String(parentSheetClass.theme):null;theme&&pageEl.classList.add(theme)})}},RenderJournalTextPageSheet={listen:()=>{Hooks.on("renderJournalTextPageSheet",(sheet,$html)=>{const content=$html.filter(".journal-page-content").get(0);content&&(InlineRollLinks.listen(content,sheet.document),UserVisibilityPF2e.process(content,sheet))})}},RenderSettings={listen:()=>{Hooks.on("renderSettings",async(_app,$html)=>{const html=$html[0],systemRow=html.querySelector(".settings-sidebar li.system"),systemInfo=systemRow?.cloneNode(!1);if(!(systemInfo instanceof HTMLLIElement))throw ErrorPF2e("Unexpected error attaching system information to settings sidebar");systemInfo.classList.remove("system"),systemInfo.classList.add("system-links");const links=[{url:"https://github.com/foundryvtt/pf2e/blob/release/CHANGELOG.md",label:"PF2E.SETTINGS.Sidebar.Changelog"},{url:"https://github.com/foundryvtt/pf2e/wiki",label:"PF2E.SETTINGS.Sidebar.Wiki"},{url:"https://discord.gg/SajryVzCyf",label:"PF2E.SETTINGS.Sidebar.Discord"}].map(data=>{const anchor=document.createElement("a");return anchor.href=data.url,anchor.innerText=game.i18n.localize(data.label),anchor.target="_blank",anchor});systemInfo.append(...links),systemRow?.after(systemInfo);const header=createHTMLElement("h2",{children:[game.system.title]}),pf2eSettings=createHTMLElement("div");html.querySelector("#settings-documentation")?.after(header,pf2eSettings);const licenseButton=document.createElement("button");licenseButton.type="button",licenseButton.append(fontAwesomeIcon("balance-scale"),game.i18n.localize("PF2E.LicenseViewer.Label")),licenseButton.addEventListener("click",()=>{game.pf2e.licenseViewer.render(!0)});const remasterButton=document.createElement("button");if(remasterButton.type="button",remasterButton.append(fontAwesomeIcon("rocket"),game.i18n.localize("PF2E.SETTINGS.Sidebar.Remaster")),remasterButton.addEventListener("click",()=>{fromUuid("Compendium.pf2e.journals.JournalEntry.6L2eweJuM8W7OCf2").then(entry=>{entry?.sheet.render(!0)})}),pf2eSettings.append(licenseButton,remasterButton),game.user.isGM){const shootButton=document.createElement("button");shootButton.type="button",shootButton.append(fontAwesomeIcon("wrench"),game.i18n.localize("PF2E.Migrations.Troubleshooting")),shootButton.addEventListener("click",()=>{new MigrationSummary({troubleshoot:!0}).render(!0)}),pf2eSettings.append(shootButton)}})}};class PartyClownCar{static{__name(this,"PartyClownCar")}static{__name2(this,"PartyClownCar")}party;token;constructor(token){if(this.token=token,!this.token.scene.isOwner)throw ErrorPF2e("Cannot write to scene");const party=token.actor;if(!party?.isOfType("party"))throw ErrorPF2e("Unexpected actor type");this.party=party}get scene(){return this.token.scene}get memberTokens(){return this.party.members.flatMap(m=>m.getActiveTokens(!0,!0))}toggleState(){return this.memberTokens.length>0?this.#retrieve():this.#deposit()}async#retrieve(){const tokens=this.memberTokens,updates=tokens.map(t=>({_id:t.id,...pick(this.token,["x","y"])})),animation={spin:!0};await this.scene.updateEmbeddedDocuments("Token",updates,{animation}),await Promise.all(tokens.map(async token=>(await token.object?._animation,token.delete())))}async#deposit(){const{token}=this;if(!token.object)return;const newTokens=(await Promise.all(this.party.members.map(m=>m.getTokenDocument({x:token.x,y:token.y})))).map(t=>({...t.toObject(),x:token.x,y:token.y})),createdTokens=await this.scene.createEmbeddedDocuments("Token",newTokens),freeSpaces=this.#getDepositSpaces(),placementData=createdTokens.map((t,index)=>({_id:t._id,...pick(freeSpaces.at(index)??token,["x","y"])}));await this.scene.updateEmbeddedDocuments("Token",placementData)}#getDepositSpaces(){const placeable=this.token.object;if(!placeable)return[];const{center}=placeable,diameter=placeable.bounds.width*7,radiusPixels=diameter/2,radius=radiusPixels/(canvas.dimensions?.distance??5),areaBounds=new PIXI.Rectangle(center.x-radiusPixels,center.y-radiusPixels,diameter,diameter),squares=getAreaSquares({bounds:areaBounds,radius,token:placeable}).filter(s=>s.active);return sortBy(squares.filter(s=>!(s.x===placeable.x&&s.y===placeable.y)&&!(s.center.x===center.x&&s.center.y===center.y)&&!placeable.checkCollision(s.center,{type:"move",mode:"any"})).reverse(),s=>canvas.grid.measureDistance(center,s.center))}}class RenderTokenHUD{static{__name(this,"RenderTokenHUD")}static{__name2(this,"RenderTokenHUD")}static listen(){Hooks.on("renderTokenHUD",(_app,$html,data)=>{const html=$html[0];game.pf2e.StatusEffects.onRenderTokenHUD(html,data);const token=canvas.scene?.tokens.get(data._id??"")?.object;this.addClownCarButton(html,token),token?.actor?.isOfType("army")&&htmlQuery(html,".control-icon[data-action=effects]")?.remove()})}static addClownCarButton(html,token){if(!token?.actor?.isOfType("party"))return;const{actor}=token,actionIcon=(()=>{const imgElement=document.createElement("img");imgElement.src="systems/pf2e/icons/other/enter-exit.svg";const willRetrieve=actor.members.some(m=>m.getActiveTokens(!0,!0).length>0);return imgElement.className=willRetrieve?"retrieve":"deposit",imgElement.title=game.i18n.localize(willRetrieve?"PF2E.Actor.Party.ClownCar.Retrieve":"PF2E.Actor.Party.ClownCar.Deposit"),imgElement})(),controlButton=createHTMLElement("div",{classes:["control-icon"],dataset:{action:"clown-car"},children:[actionIcon]});controlButton.addEventListener("click",async()=>{if(!controlButton.dataset.disabled){controlButton.dataset.disabled="true";try{await new PartyClownCar(token.document).toggleState();const switchToDeposit=actionIcon.className==="retrieve";actionIcon.className=switchToDeposit?"deposit":"retrieve",actionIcon.title=game.i18n.localize(switchToDeposit?"PF2E.Actor.Party.ClownCar.Deposit":"PF2E.Actor.Party.ClownCar.Retrieve")}finally{delete controlButton.dataset.disabled}}}),htmlQuery(html,"[data-action=effects]")?.replaceWith(controlButton)}}class ArmySheetPF2e extends ActorSheetPF2e{static{__name(this,"ArmySheetPF2e")}static{__name2(this,"ArmySheetPF2e")}basicWarActions=[];itemRenderer=new ArmyItemRenderer(this);static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"army"],width:750,height:625,template:"systems/pf2e/templates/actors/army/sheet.hbs",scrollY:[".sheet-body"]}}async getData(options){const data=await super.getData(options),actor=this.actor,campaignFeatures=actor.itemTypes.campaignFeature;if(!this.basicWarActions.length){const compendiumFeatures=(await game.packs.get("pf2e.kingmaker-features")?.getDocuments({type:"campaignFeature"})??[]).filter(d=>d instanceof ItemPF2e&&d.isOfType("campaignFeature"));this.basicWarActions=compendiumFeatures.filter(d=>d.system.category==="army-war-action"&&d.folder?.id===BASIC_WAR_ACTIONS_FOLDER).map(i=>new ItemProxyPF2e(i.toObject(!0),{parent:this.actor})).filter(i=>i.isOfType("campaignFeature"))}return{...data,ac:{value:actor.armorClass.value,breakdown:actor.armorClass.breakdown,adjustmentClass:getAdjustment(actor.armorClass.value,actor._source.system.ac.value+actor.system.ac.potency)},consumption:getAdjustedValue(actor.system.consumption,actor._source.system.consumption,{better:"lower"}),hitPoints:{value:actor.system.attributes.hp.value,max:getAdjustedValue(actor.system.attributes.hp.max,actor._source.system.attributes.hp.max),routThreshold:getAdjustedValue(actor.system.attributes.hp.routThreshold,actor._source.system.attributes.hp.routThreshold,{better:"lower"})},linked:!!actor.prototypeToken.actorLink&&(!actor.token||actor.token.isLinked),alignments:ALIGNMENTS,armyTypes:pick(kingmakerTraits,ARMY_TYPES),rarityTraits:CONFIG.PF2E.rarityTraits,saves:sortBy(["maneuver","morale"].map(slug=>{const statistic=this.actor[slug];return{slug,label:statistic.label,mod:statistic.mod,breakdown:statistic.check.breakdown,adjustmentClass:getAdjustment(statistic.mod,this.actor._source.system.saves[slug])}}),s=>s.label),basicWarActions:this.basicWarActions,warActions:campaignFeatures.filter(f=>f.category==="army-war-action")}}activateListeners($html){super.activateListeners($html);const html=$html[0],levelInput=htmlQuery(html,".level");levelInput?.addEventListener("change",()=>{const value=levelInput.value;this.actor.updateLevel(Number(value))});for(const rollableStat of htmlQueryAll(html,".rollable")){const statSlug=htmlClosest(rollableStat,"[data-statistic]")?.dataset.statistic;statSlug&&rollableStat.addEventListener("click",event2=>{this.actor.getStatistic(statSlug)?.roll(eventToRollParams(event2,{type:"check"}))})}htmlQuery(html,"[data-action=link-actor]")?.addEventListener("click",()=>{this.actor.token?ui.notifications.error("PF2E.Kingmaker.Army.Alliance.LinkError",{localize:!0}):this.actor.update({prototypeToken:{actorLink:!0}})});for(const resourceElement of htmlQueryAll(html,"[data-action=change-resource]")){const resource=resourceElement.dataset.resource;if(!tupleHasValue(["potions","ammunition"],resource))continue;const max=this.actor.system.resources[resource].max;resourceElement.addEventListener("click",()=>{const newValue=Math.clamped(this.actor.system.resources[resource].value+1,0,max);this.actor.update({[`system.resources.${resource}.value`]:newValue})}),resourceElement.addEventListener("contextmenu",event2=>{event2.preventDefault();const newValue=Math.clamped(this.actor.system.resources[resource].value-1,0,max);this.actor.update({[`system.resources.${resource}.value`]:newValue})})}htmlQuery(html,"[data-action=reset-ammo]")?.addEventListener("click",()=>{const max=this.actor.system.resources.ammunition.max;this.actor.update({"system.resources.ammunition.value":max})}),htmlQuery(html,"[data-action=use-potion]")?.addEventListener("click",()=>{this.actor.usePotion()});for(const gearElement of htmlQueryAll(html,"[data-action=change-magic-armor]"))gearElement.addEventListener("click",()=>{const newValue=Math.clamped(this.actor.system.ac.potency+1,0,3);this.actor.update({"system.ac.potency":newValue})}),gearElement.addEventListener("contextmenu",event2=>{event2.preventDefault();const newValue=Math.clamped(this.actor.system.ac.potency-1,0,3);this.actor.update({"system.ac.potency":newValue})});for(const gearElement of htmlQueryAll(html,"[data-action=change-magic-weapon]")){const gear=gearElement.dataset.weapon;if(!tupleHasValue(["melee","ranged"],gear))continue;const data=this.actor.system.weapons[gear];gearElement.addEventListener("click",()=>{if(data){const newValue=Math.clamped(data.potency+1,0,3);this.actor.update({[`system.weapons.${gear}.potency`]:newValue})}else{const newData={name:"",potency:0};this.actor.update({[`system.weapons.${gear}`]:newData})}}),gearElement.addEventListener("contextmenu",event2=>{if(event2.preventDefault(),!!data)if(data.potency===0)this.actor.update({[`system.weapons.${gear}`]:null});else{const newValue=Math.clamped(data.potency-1,0,3);this.actor.update({[`system.weapons.${gear}.potency`]:newValue})}})}const gearData=getArmyGearData();for(const showGear of htmlQueryAll(html,"[data-action=show-gear]")){const rawGearType=showGear.dataset.gear,gearType=tupleHasValue(["melee","ranged"],rawGearType)&&!this.actor.system.weapons[rawGearType]?`additional-${rawGearType}`:rawGearType;if(!objectHasKey(gearData,gearType))continue;const kingmakerTraits2=CONFIG.PF2E.kingmakerTraits,actionTraits2=CONFIG.PF2E.actionTraits,descriptions=CONFIG.PF2E.traitsDescriptions;showGear.addEventListener("click",async()=>{const gear=gearData[gearType];ChatMessagePF2e.create({speaker:ChatMessagePF2e.getSpeaker({actor:this.actor}),content:await renderTemplate("systems/pf2e/templates/actors/army/gear-card.hbs",{...gear,level:gear.level??(gear.ranks?.length?`${gear.ranks[0].level}+`:null),traits:gear.traits.map(t=>({label:game.i18n.localize(kingmakerTraits2[t]??actionTraits2[t]??t),description:game.i18n.localize(descriptions[t]??"")}))})})})}htmlQuery(html,"[data-action=edit-description]")?.addEventListener("click",()=>{this.activateEditor("system.details.description")});for(const strikeAttack of htmlQueryAll(html,"[data-action=strike-attack]")){const type=htmlClosest(strikeAttack,"[data-strike]")?.dataset.strike,variant=Number(strikeAttack.dataset.variantIndex);objectHasKey(this.actor.strikes,type)&&strikeAttack.addEventListener("click",event2=>{this.actor.strikes[type]?.variants[variant]?.roll({event:event2})})}for(const strikeDamage of htmlQueryAll(html,"[data-action=strike-damage]")){const type=htmlClosest(strikeDamage,"[data-strike]")?.dataset.strike,outcome=strikeDamage.dataset.outcome==="criticalSuccess"?"critical":"damage";objectHasKey(this.actor.strikes,type)&&strikeDamage.addEventListener("click",event2=>{this.actor.strikes[type]?.[outcome]({event:event2})})}}activateClickListener(html){const handlers=super.activateClickListener(html);return handlers["toggle-basic-war-action-summary"]=async event2=>{const element=htmlClosest(event2.target,"[data-slug]");element&&this.itemRenderer.toggleSummary(element)},handlers["use-basic-war-action"]=async event2=>{const slug=htmlClosest(event2.target,"[data-slug]")?.dataset.slug;this.basicWarActions.find(a=>a.slug===slug)?.toMessage(event2)},handlers}async _onDropItem(event2,data){const item=await ItemPF2e.fromDropData(data);if(!item)throw ErrorPF2e("Unable to create item from drop data!");if(this.actor.uuid===item.parent?.uuid)return super._onDropItem(event2,data);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const slotData=this.#getFeatSlotData(event2)??{groupId:"bonus",slotId:null};return(slotData.groupId==="tactics"?this.actor.tactics:this.actor.bonusTactics).insertFeat(item,slotData.slotId)}return super._onDropItem(event2,data)}async _onSortItem(event2,itemSource){const item=this.actor.items.get(itemSource._id);if(item?.isOfType("campaignFeature")&&(item.isFeat||item.isFeature)){const featSlot=this.#getFeatSlotData(event2)??{groupId:"bonus",slotId:null},group=featSlot.groupId==="tactics"?this.actor.tactics:this.actor.bonusTactics,resorting=item.group===group&&!group?.slotted;if(group?.slotted&&!featSlot.slotId)return[];if(!resorting)return group.insertFeat(item,featSlot.slotId)}return super._onSortItem(event2,itemSource)}#getFeatSlotData(event2){const groupId=event2.target?.closest("[data-group-id]")?.dataset.groupId,slotId=event2.target?.closest("[data-slot-id]")?.dataset.slotId;return typeof groupId=="string"?{slotId,groupId}:null}}class ArmyItemRenderer extends ItemSummaryRenderer{static{__name(this,"ArmyItemRenderer")}static{__name2(this,"ArmyItemRenderer")}async getItemFromElement(element){const slug=element.dataset.slug;return this.sheet.basicWarActions.find(a=>a.slug===slug)??super.getItemFromElement(element)}}class FamiliarSheetPF2e extends CreatureSheetPF2e{static{__name(this,"FamiliarSheetPF2e")}static{__name2(this,"FamiliarSheetPF2e")}actorConfigClass=null;static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"familiar"],width:650,height:680,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"attributes"}]}}get template(){return"systems/pf2e/templates/actors/familiar-sheet.hbs"}async getData(options){const sheetData=await super.getData(options),familiar=this.actor,masters=game.actors.filter(a=>a.type==="character"&&a.testUserPermission(game.user,"OWNER")),abilities2=CONFIG.PF2E.abilities,size=CONFIG.PF2E.actorSizes[familiar.system.traits.size.value]??null,familiarAbilities=this.actor.master?.attributes?.familiarAbilities;if(sheetData.data.saves)for(const key of["fortitude","reflex","will"]){const save=sheetData.data.saves[key];save.label=CONFIG.PF2E.saves[key]}const skills=Object.values(sheetData.data.skills).sort((a,b)=>a.label.localeCompare(b.label,game.i18n.lang));return{...sheetData,master:this.actor.master,masters,abilities:abilities2,size,skills,familiarAbilities:{value:familiarAbilities?.value??0,items:sortBy(this.actor.itemTypes.action,a=>a.sort)}}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,".rollable[data-action=perception-check]")?.addEventListener("click",event2=>{this.actor.perception.roll(eventToRollParams(event2,{type:"check"}))}),htmlQuery(html,".rollable[data-attack-roll]")?.addEventListener("click",event2=>{this.actor.attackStatistic.roll(eventToRollParams(event2,{type:"check"}))})}}class HazardSheetPF2e extends ActorSheetPF2e{static{__name(this,"HazardSheetPF2e")}static{__name2(this,"HazardSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return foundry.utils.mergeObject(options,{classes:[...options.classes,"hazard"],scrollY:[".container > section"],width:700,height:680}),options}get template(){return"systems/pf2e/templates/actors/hazard/sheet.hbs"}get title(){return this.editing?game.i18n.format("PF2E.Actor.Hazard.TitleEdit",{name:super.title}):super.title}get editing(){return this.options.editable&&!!this.actor.getFlag("pf2e","editHazard.value")}async getData(options){const sheetData=await super.getData(options);sheetData.actor.flags.editHazard??={value:!1};const systemData=sheetData.data,actor=this.actor,{hasDefenses}=actor,hasImmunities=systemData.attributes.immunities.length>0,hasResistances=systemData.attributes.resistances.length>0,hasWeaknesses=systemData.attributes.weaknesses.length>0,hasIWR=hasDefenses||hasImmunities||hasResistances||hasWeaknesses,stealthMod=actor.system.attributes.stealth.value,stealthDC=typeof stealthMod=="number"?stealthMod+10:null,hasStealthDescription=!!systemData.attributes.stealth?.details,rollData=this.actor.getRollData(),enrich=__name2(async content=>TextEditor.enrichHTML(content??"",{rollData,async:!0}),"enrich");sheetData.enrichedContent=foundry.utils.mergeObject(sheetData.enrichedContent,{stealthDetails:await enrich(systemData.attributes.stealth.details),description:await enrich(systemData.details.description),disable:await enrich(systemData.details.disable),routine:await enrich(systemData.details.routine),reset:await enrich(systemData.details.reset)});const strikesWithDescriptions=systemData.actions,actorRollData=actor.getRollData();for(const attack of strikesWithDescriptions){const itemRollData=attack.item.getRollData();attack.description.length>0&&(attack.description=await TextEditor.enrichHTML(attack.description,{rollData:{...actorRollData,...itemRollData},async:!0})),attack.damageFormula=String(await attack.damage?.({getFormula:!0}))}return{...sheetData,actions:this.#prepareActions(),editing:this.editing,actorTraits:systemData.traits.value.map(t=>traitSlugToObject(t,CONFIG.PF2E.hazardTraits)),rarity:CONFIG.PF2E.rarityTraits,rarityLabel:CONFIG.PF2E.rarityTraits[this.actor.rarity],brokenThreshold:systemData.attributes.hp.brokenThreshold,stealthDC,saves:this.#prepareSaves(),hasDefenses,hasHPDetails:!!systemData.attributes.hp.details.trim(),hasSaves:Object.keys(actor.saves??{}).length>0,hasIWR,hasStealth:stealthDC!==null||hasStealthDescription,hasStealthDescription,hasDescription:!!systemData.details.description?.trim(),hasDisable:!!systemData.details.disable?.trim(),hasRoutineDetails:!!systemData.details.routine?.trim(),hasResetDetails:!!systemData.details.reset?.trim()}}#prepareActions(){const actions=this.actor.itemTypes.action.sort((a,b)=>a.sort-b.sort);return{reaction:actions.filter(a=>a.actionCost?.type==="reaction"),action:actions.filter(a=>a.actionCost?.type!=="reaction")}}#prepareSaves(){if(!this.actor.saves)return[];const results=[];for(const saveType of SAVE_TYPES){const save=this.actor.saves[saveType];(this.editing||save)&&results.push({label:game.i18n.localize(`PF2E.Saves${saveType.titleCase()}Short`),type:saveType,mod:save?.check.mod})}return results}activateListeners($html){super.activateListeners($html);const html=$html[0],traitsEl=html.querySelector('input[name="system.traits.value"]');if(traitsEl){const tags=tagify(traitsEl,{whitelist:CONFIG.PF2E.hazardTraits}),traitsPrepend=html.querySelector(".traits-extra");traitsPrepend&&tags.DOM.scope.prepend(traitsPrepend.content)}$html.find(".edit-mode-button").on("click",()=>{this.actor.setFlag("pf2e","editHazard.value",!this.editing)}),$html.find("input[data-property]").on("focus",event2=>{const $input=$(event2.target),propertyPath=$input.attr("data-property")??"",baseValue=Number(foundry.utils.getProperty(this.actor._source,propertyPath));$input.val(baseValue).attr({name:propertyPath})}),$html.find("input[data-property]").on("blur",event2=>{const $input=$(event2.target);$input.removeAttr("name").removeAttr("style").attr({type:"text"});const propertyPath=$input.attr("data-property")??"",valueAttr=$input.attr("data-value");if(valueAttr)$input.val(valueAttr);else{const preparedValue=Number(foundry.utils.getProperty(this.actor,propertyPath));$input.val(preparedValue!==null&&preparedValue>=0?`+${preparedValue}`:preparedValue)}}),$html.find("[data-action=edit-section]").on("click",event2=>{const name2=$(event2.target).closest(".section-container").find("[data-edit]").attr("data-edit");name2&&this.activateEditor(name2)}),this.options.editable&&$html.find(".isHazardEditable").on("change",event2=>{this.actor.setFlag("pf2e","editHazard",{value:event2.target.checked})})}async _updateObject(event2,formData){const emitsSound=formData["system.attributes.emitsSound"];return emitsSound!=="encounter"&&(formData["system.attributes.emitsSound"]=emitsSound==="true"),super._updateObject(event2,formData)}}class LootNPCsPopup extends FormApplication{static{__name(this,"LootNPCsPopup")}static{__name2(this,"LootNPCsPopup")}static get defaultOptions(){const options=super.defaultOptions;return options.id="loot-NPCs",options.classes=[],options.title="Loot NPCs",options.template="systems/pf2e/templates/actors/loot/loot-npcs-popup.hbs",options.width="auto",options}async getData(){const tokenInfo=(canvas.ready?canvas.tokens.controlled.filter(t=>t.actor&&t.actor.id!==this.object.id):[]).map(t=>({id:t.id,name:t.name,checked:t.actor?.hasPlayerOwner??!1}));return{...await super.getData(),tokenInfo}}async _updateObject(_event,formData){if(!canvas.ready)return;const lootActor=this.object,newItems=[],itemUpdates=new Map,itemsToDelete=new Map,selectionData=Array.isArray(formData.selection)?formData.selection:[formData.selection];for(let i=0;itoken2.actor&&token2.id===this.form[i]?.id);if(!token)throw ErrorPF2e(`Token ${this.form[i]?.id} not found`);const currentSource=token.actor;if(selectionData[i]&¤tSource){for(const item of currentSource.inventory){const stackableItem=lootActor.inventory.findStackableItem(item);if(stackableItem){const currentQuantity=itemUpdates.get(stackableItem.id)??stackableItem.quantity;itemUpdates.set(stackableItem.id,currentQuantity+item.quantity);continue}newItems.push(item)}itemsToDelete.set(currentSource,currentSource.inventory.map(item=>item.id))}}if(newItems.length>0){const sources=newItems.reduce((result,item)=>{const stackableItem=result.find(i=>i.isStackableWith(item));return stackableItem?(stackableItem.updateSource({system:{quantity:stackableItem.quantity+item.quantity}}),result):(result.push(item),result)},[]).map(i=>i.toObject());await lootActor.createEmbeddedDocuments("Item",sources,{render:itemUpdates.size===0})}if(itemUpdates.size>0){const updates=[...itemUpdates.entries()].map(([id,quantity])=>({_id:id,system:{quantity}}));await lootActor.updateEmbeddedDocuments("Item",updates)}if(itemsToDelete.size>0)for(const[actor,ids]of itemsToDelete)actor.deleteEmbeddedDocuments("Item",ids)}}class DistributeCoinsPopup extends FormApplication{static{__name(this,"DistributeCoinsPopup")}static{__name2(this,"DistributeCoinsPopup")}constructor(actor,options={}){super(actor,options)}static get defaultOptions(){const options=super.defaultOptions;return options.id="distribute-coins",options.classes=[],options.title="Distribute Coins",options.template="systems/pf2e/templates/actors/distribute-coins.hbs",options.width="auto",options}async getData(options){const sheetData=await super.getData(options),playerActors=(options?.recipients??game.actors.contents).filter(a=>a.hasPlayerOwner&&a.isOfType("character")&&!a.isToken&&!a.system.traits.value.some(t=>["minion","eidolon"].includes(t)));return sheetData.actorInfo=playerActors.map(a=>({id:a.id,name:a.name,checked:game.users.players.some(u=>u.active&&u.character?.id===a.id)})),sheetData}async _updateObject(_event,formData){const thisActor=this.object,selectedActors=formData.actorIds.flatMap(actorId=>{const maybeActor=game.actors.get(actorId);return maybeActor?.isOfType("character")?maybeActor:[]}),playerCount=selectedActors.length;if(playerCount===0)return;const coinShare=new CoinsPF2e;if(formData.breakCoins){const thisActorCopperValue=thisActor.inventory.coins.copperValue,copperToDistribute=Math.trunc(thisActorCopperValue/playerCount);if(copperToDistribute===0){ui.notifications.warn("Nothing to distribute");return}thisActor.inventory.removeCoins({cp:copperToDistribute*playerCount}),coinShare.cp=copperToDistribute%10,coinShare.sp=Math.trunc(copperToDistribute/10)%10,coinShare.gp=Math.trunc(copperToDistribute/100)%10,coinShare.pp=Math.trunc(copperToDistribute/1e3)}else{const thisActorCurrency=thisActor.inventory.coins;if(coinShare.pp=Math.trunc(thisActorCurrency.pp/playerCount),coinShare.cp=Math.trunc(thisActorCurrency.cp/playerCount),coinShare.gp=Math.trunc(thisActorCurrency.gp/playerCount),coinShare.sp=Math.trunc(thisActorCurrency.sp/playerCount),coinShare.pp===0&&coinShare.gp===0&&coinShare.sp===0&&coinShare.cp===0){ui.notifications.warn("Nothing to distribute");return}const coinsToRemove=coinShare.scale(playerCount);thisActor.inventory.removeCoins(coinsToRemove,{byValue:!1})}let message="Distributed ";coinShare.pp!==0&&(message+=`${coinShare.pp} pp `),coinShare.gp!==0&&(message+=`${coinShare.gp} gp `),coinShare.sp!==0&&(message+=`${coinShare.sp} sp `),coinShare.cp!==0&&(message+=`${coinShare.cp} cp `);const each=playerCount>1?"each ":"";message+=`${each}from ${thisActor.name} to `;for(const actor of selectedActors){await actor.inventory.addCoins(coinShare);const index=selectedActors.indexOf(actor);index===0?message+=`${actor.name}`:indexelement instanceof HTMLInputElement&&element.name==="actorIds"&&element.checked?element.value:[]);return options.updateData=foundry.utils.mergeObject(options.updateData??{},{actorIds}),super._onSubmit(event2,options)}}class LootSheetPF2e extends ActorSheetPF2e{static{__name(this,"LootSheetPF2e")}static{__name2(this,"LootSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return{...options,editable:!0,classes:[...options.classes,"loot"],width:650,height:680,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"inventory"}]}}get template(){return"systems/pf2e/templates/actors/loot/sheet.hbs"}get isLootSheet(){return!this.actor.isOwner&&this.actor.isLootableBy(game.user)}async getData(){const sheetData=await super.getData(),isLoot=this.actor.system.lootSheetType==="Loot",rollData=this.actor.getRollData();return sheetData.enrichedContent.description=await TextEditor.enrichHTML(sheetData.data.details.description,{rollData,async:!0}),{...sheetData,isLoot}}activateListeners($html){if(super.activateListeners($html),!this.isEditable)return;const html=$html[0];htmlQuery(html,"[data-sidebar-buttons]")?.addEventListener("click",event2=>{const button=htmlClosest(event2.target,"button[data-action]");button?.dataset.action==="split-coins"?new DistributeCoinsPopup(this.actor).render(!0):button?.dataset.action==="loot-npcs"&&(canvas.tokens.controlled.some(token=>token.actor?.id!==this.actor.id)?new LootNPCsPopup(this.actor).render(!0):ui.notifications.warn("No tokens selected."))})}async _onDropItem(event2,itemData){return this.actor.id===itemData.actorId&&!this.actor.testUserPermission(game.user,"OWNER")?[]:super._onDropItem(event2,itemData)}}class NPCSkillsEditor extends DocumentSheet{static{__name(this,"NPCSkillsEditor")}static{__name2(this,"NPCSkillsEditor")}get actor(){return this.object}static get defaultOptions(){return{...super.defaultOptions,classes:["pf2e","npc-skills-editor"],template:"systems/pf2e/templates/actors/npc/skills-editor.hbs",height:"auto",scrollY:[".scroll-container"],sheetConfig:!1,submitOnChange:!1,submitOnClose:!1,width:"400"}}get title(){return game.i18n.format("PF2E.Actor.NPC.SkillsEditor.Title",{actor:this.actor.name})}async getData(options){const allSkills=Object.values(this.actor.system.skills);return{...await super.getData(options),actor:this.actor,trainedSkills:allSkills.filter(s=>s.visible).sort((a,b)=>a.label.localeCompare(b.label)),untrainedSkills:allSkills.filter(s=>!s.visible).sort((a,b)=>a.label.localeCompare(b.label))}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=add-skill]")?.addEventListener("click",async event2=>{const slug=htmlQuery(htmlClosest(event2.currentTarget,".skill-selector"),"select")?.value;setHasElement(SKILL_LONG_FORMS,slug)&&await this.actor.createEmbeddedDocuments("Item",[{name:slug.titleCase(),type:"lore"}])}),htmlQuery(html,"button[data-action=add-lore]")?.addEventListener("click",async event2=>{const loreName=htmlQuery(htmlClosest(event2.currentTarget,".lore-skill-creator"),"input")?.value.trim();if(loreName){const data={name:loreName,type:"lore",system:{mod:{value:0}}};await this.actor.createEmbeddedDocuments("Item",[data])}});for(const input of htmlQueryAll(html,"input[data-modifier]"))input.addEventListener("change",async()=>{const modifier=Math.clamped(Math.trunc(Number(input.value)||0),-999,999);if(Number.isInteger(modifier)){const itemId=htmlClosest(input,"[data-item-id]")?.dataset.itemId;await this.actor.items.get(itemId,{strict:!0}).update({"system.mod.value":modifier})}}),input.addEventListener("focus",()=>{input.select()});for(const anchor of htmlQueryAll(html,"a[data-action=edit-skill]"))anchor.addEventListener("click",()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;this.actor.items.get(itemId,{strict:!0}).sheet.render(!0)});for(const anchor of htmlQueryAll(html,"a[data-action=remove-skill]"))anchor.addEventListener("click",async()=>{const itemId=htmlClosest(anchor,"[data-item-id]")?.dataset.itemId;await this.actor.items.get(itemId,{strict:!0}).delete()})}async _render(force,options){const focusedElement=htmlQuery(this.form,"input:focus, select:focus");if(await super._render(force,options),focusedElement){const selector=["input","select"].map(s=>`${s}#${CSS.escape(focusedElement.id)}`).join(","),newInput=htmlQuery(this.form,selector);window.setTimeout(()=>{newInput?.focus()},0)}}}class RecallKnowledgePopup extends Application{static{__name(this,"RecallKnowledgePopup")}static{__name2(this,"RecallKnowledgePopup")}#identificationData;constructor(options,data){super(options),this.#identificationData=data}static get defaultOptions(){return{...super.defaultOptions,id:"recall-knowledge-breakdown",classes:[],title:game.i18n.localize("PF2E.RecallKnowledge.BreakdownTitle"),template:"systems/pf2e/templates/actors/recall-knowledge.hbs",width:630}}async getData(){const identificationData=this.#identificationData;return{standard:{label:localizeList(identificationData.skills.map(s=>game.i18n.localize(CONFIG.PF2E.skillList[s]))),attempts:this.#padAttempts(identificationData.standard.progression)},loreEasy:this.#padAttempts(identificationData.lore[0].progression),loreVeryEasy:this.#padAttempts(identificationData.lore[1].progression)}}#padAttempts(attempts){return padArray(attempts.map(attempt=>attempt.toString()),6,"-")}}class NPCConfig extends CreatureConfig{static{__name(this,"NPCConfig")}static{__name2(this,"NPCConfig")}async getData(options={}){const lootableOptions={default:`PF2E.Actor.NPC.Configure.Lootable.${game.settings.get("pf2e","automation.lootableNPCs")?"DefaultLootable":"DefaultNotLootable"}`,lootable:"PF2E.Actor.NPC.Configure.Lootable.Lootable",notLootable:"PF2E.Actor.NPC.Configure.Lootable.NotLootable"},lootableSelection=(()=>{const storedSelection=this.actor._source.flags.pf2e?.lootable;return typeof storedSelection=="boolean"?storedSelection?"lootable":"notLootable":"default"})();return{...await super.getData(options),lootable:createSheetOptions(lootableOptions,{value:[lootableSelection]})}}async _updateObject(event2,formData){const key="flags.pf2e.lootable",lootable=formData[key];return lootable==="default"?(delete formData[key],formData["flags.pf2e.-=lootable"]=null):formData[key]=lootable==="lootable",super._updateObject(event2,formData)}}class AbstractNPCSheet extends CreatureSheetPF2e{static{__name(this,"AbstractNPCSheet")}static{__name2(this,"AbstractNPCSheet")}actorConfigClass=NPCConfig;static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"pf2e","npc","simple"],scrollY:[".sidebar",".inventory-list"]}}async prepareItems(sheetData){this.#prepareAbilities(sheetData.data.abilities),this.#prepareSkills(sheetData.data),this.#prepareSaves(sheetData.data)}async getData(options){const sheetData=await super.getData(options),rollData=this.actor.getRollData();return sheetData.enrichedContent.publicNotes=await TextEditor.enrichHTML(sheetData.data.details.publicNotes,{rollData,secrets:this.actor.isOwner,async:!0}),sheetData.enrichedContent.privateNotes=await TextEditor.enrichHTML(sheetData.data.details.privateNotes,{rollData,async:!0}),sheetData.traitTagifyData=createTagifyTraits(this.actor.system.traits.value,{sourceTraits:this.actor._source.system.traits.value,record:CONFIG.PF2E.creatureTraits}),sheetData}#prepareAbilities(attributes){for(const key of ATTRIBUTE_ABBREVIATIONS){const data=attributes[key],localizedCode=game.i18n.localize(`PF2E.AbilityId.${key}`),nameKey=CONFIG.PF2E.abilities[key],localizedName=game.i18n.localize(nameKey);data.localizedCode=localizedCode,data.localizedName=localizedName}}#prepareSkills(sheetSystemData){const sortedSkillsIds=Object.keys(sheetSystemData.skills),skills=sheetSystemData.skills;for(const shortForm of sortedSkillsIds){const skill=skills[shortForm];skill.adjustedHigher=skill.value>Number(skill.base),skill.adjustedLower=skill.value{const skillA=skills[a],skillB=skills[b];return skillA.labelskillB.label?1:0});const sortedSkills={};for(const skillId of sortedSkillsIds)sortedSkills[skillId]=skills[skillId];sheetSystemData.sortedSkills=sortedSkills}#prepareSaves(systemData){for(const saveType of SAVE_TYPES){const save=systemData.saves[saveType];save.labelShort=game.i18n.localize(`PF2E.Saves${saveType.titleCase()}Short`),save.adjustedHigher=save.totalModifier>Number(save.base),save.adjustedLower=save.totalModifier{this.#onClickRollable(rollable,event2)});this.isEditable&&htmlQuery(html,".skills-edit")?.addEventListener("click",()=>{new NPCSkillsEditor(this.actor).render(!0)})}async#onClickRollable(link,event2){const{attribute,save,skill}=link?.parentElement?.dataset??{},rollParams=eventToRollParams(event2,{type:"check"});if(attribute)attribute==="perception"?await this.actor.perception.roll(eventToRollParams(event2,{type:"check"})):setHasElement(ATTRIBUTE_ABBREVIATIONS,attribute)&&this.#rollAbility(event2,attribute);else if(skill){const extraRollOptions=link.dataset.options?.split(",").map(o=>o.trim()).filter(o=>!!o),key=objectHasKey(SKILL_DICTIONARY,skill)?SKILL_DICTIONARY[skill]:skill;await this.actor.skills[key]?.check.roll({...rollParams,extraRollOptions})}else objectHasKey(this.actor.saves,save)&&await this.actor.saves[save].check.roll(rollParams)}async#rollAbility(event2,abilityId){const bonus=this.actor.system.abilities[abilityId].mod,parts=["@bonus"],title=game.i18n.localize(`PF2E.AbilityCheck.${abilityId}`),data={bonus},speaker=ChatMessage.getSpeaker({token:this.token,actor:this.actor});await DicePF2e.d20Roll({event:event2,parts,data,title,speaker})}}class NPCSheetPF2e extends AbstractNPCSheet{static{__name(this,"NPCSheetPF2e")}static{__name2(this,"NPCSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return{...options,width:650,height:680,tabs:[{navSelector:".sheet-tabs",contentSelector:".sheet-body",initial:"main"}],scrollY:[...options.scrollY,".tab.main",".tab.inventory",".tab.spells",".tab.effects",".tab.notes"]}}get template(){return this.isLootSheet?"systems/pf2e/templates/actors/npc/loot-sheet.hbs":this.actor.limited?"systems/pf2e/templates/actors/limited/npc-sheet.hbs":"systems/pf2e/templates/actors/npc/sheet.hbs"}get title(){if(this.isLootSheet||this.actor.limited){const actorName=!game.pf2e.settings.tokens.nameVisibility||!this.token||this.token.playersCanSeeName?this.token?.name??this.actor.name:"";return this.actor.isDead?`${actorName} [${game.i18n.localize("PF2E.NPC.Dead")}]`:actorName}return super.title}get isLootSheet(){return this.actor.isLootable&&!this.actor.isOwner&&this.actor.isLootableBy(game.user)}async getData(options){const sheetData=await super.getData(options);(this.actor.limited||this.isLootSheet)&&(sheetData.actor.name=this.actor.token?.name??sheetData.actor.name),sheetData.identificationDCs=(()=>{const data=this.actor.identificationDCs,skills=data.skills.length>0?localizeList(data.skills.map(s=>game.i18n.localize(CONFIG.PF2E.skillList[s]))):null;return{standard:skills?game.i18n.format("PF2E.Actor.NPC.Identification.Skills.Label",{skills,dc:data.standard.dc,adjustment:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.standard.start])}):null,lore:game.i18n.format("PF2E.Actor.NPC.Identification.Lore.Label",{dc1:data.lore[0].dc,adjustment1:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.lore[0].start]),dc2:data.lore[1].dc,adjustment2:game.i18n.localize(CONFIG.PF2E.dcAdjustments[data.lore[1].start])})}})();const{heldShield}=this.actor,actorShieldData=sheetData.data.attributes.shield;sheetData.hasShield=!!heldShield||actorShieldData.hp.max>0;const isElite=this.actor.isElite,isWeak=this.actor.isWeak;sheetData.isElite=isElite,sheetData.isWeak=isWeak,sheetData.notAdjusted=!isElite&&!isWeak,isElite?(sheetData.eliteState="active",sheetData.weakState="inactive"):isWeak?(sheetData.eliteState="inactive",sheetData.weakState="active"):(sheetData.eliteState="inactive",sheetData.weakState="inactive"),this.isLootSheet&&(sheetData.actor.name=this.token?.name??this.actor.name);const{level}=sheetData.data.details;level.adjustedHigher=level.value>Number(level.base),level.adjustedLower=level.valuesourceAttributes.ac.value,ac.adjustedLower=ac.valuesourceAttributes.hp.max,hp.adjustedLower=hp.maxsourceAttributes.perception.value,perception.adjustedLower=perception.totalModifierspeedData.value,adjustedLower:speedData.totalt!=="land").reduce((speeds,type)=>{const speed=speedData.otherSpeeds.find(s=>s.type===type);return{...speeds,[type]:speed?{label:speed.label,value:speed.total,adjustedHigher:typeof speed.total=="number"&&speed.total>speed.value,adjustedLower:typeof speed.total=="number"&&speed.total0,sheetData.configLootableNpc=game.settings.get("pf2e","automation.lootableNPCs"),sheetData.languageDetails=this.actor.system.traits.languages.custom.trim(),sheetData}async prepareItems(sheetData){super.prepareItems(sheetData),await this.#prepareActions(sheetData),sheetData.spellcastingEntries=await this.prepareSpellcasting()}async prepareSpellcasting(){const entries=await super.prepareSpellcasting();for(const entry of entries){const entryItem=this.actor.items.get(entry.id);entryItem?.isOfType("spellcastingEntry")&&(entry.adjustedHigher=entry.statistic?{dc:entry.statistic.dc.value>entryItem._source.system.spelldc.dc,mod:entry.statistic.check.mod>entryItem._source.system.spelldc.value}:{dc:!1,mod:!1},entry.adjustedLower=entry.statistic?{dc:entry.statistic.dc.value0){const itemRollData=attack.item.getRollData();attack.description=await TextEditor.enrichHTML(attack.description,{rollData:{...actorRollData,...itemRollData},async:!0})}attack.damageFormula=String(await attack.damage?.({getFormula:!0}))}const actions={passive:{label:game.i18n.localize("PF2E.ActionTypePassive"),actions:[]},active:{label:game.i18n.localize("PF2E.ActionTypeAction"),actions:[]}},baseOrder=["free","reaction","action"],abilities2=sortBy(this.actor.itemTypes.action,a=>a.sort,a=>baseOrder.indexOf(a.actionCost?.type??"action"));for(const item of abilities2){const itemData=item.toObject(!1),chatData=await item.getChatData(),traits=chatData.traits??[],actionGroup=item.actionCost?"active":"passive",hasAura=actionGroup==="passive"&&(item.system.traits.value.includes("aura")||!!item.system.rules.find(r=>r.key==="Aura"));actions[actionGroup].actions.push({...itemData,glyph:getActionGlyph(item.actionCost),imageUrl:getActionIcon(item.actionCost),chatData,traits,hasAura})}sheetData.actions=actions}activateListeners($html){super.activateListeners($html);const html=$html[0],mainPanel=htmlQuery(html,".tab[data-tab=main]");if(mainPanel&&htmlQuery(mainPanel,".recall-knowledge button.breakdown")?.addEventListener("click",()=>{new RecallKnowledgePopup({},this.actor.identificationDCs).render(!0)}),!this.isEditable)return;for(const anchor of htmlQueryAll(html,"a[data-adjustment]"))anchor.addEventListener("click",()=>{const adjustment=anchor.dataset.adjustment;if(adjustment==="elite"||adjustment==="weak"){const alreadyHasAdjustment=adjustment===this.actor.system.attributes.adjustment;this.actor.applyAdjustment(alreadyHasAdjustment?null:adjustment)}});const selector=[".attack-input",".dc-input",".key-attribute select"].map(s=>`.spellcasting-entry ${s}`).join(", ");for(const element of htmlQueryAll(html,selector))element.addEventListener("change",event2=>this.#onChangeSpellcastingEntry(element,event2))}activateClickListener(html){const handlers=super.activateClickListener(html);return handlers["generate-attack"]=async event2=>{const{actor}=this,itemId=htmlClosest(event2.target,"[data-item-id]")?.dataset.itemId??"",item=actor.items.get(itemId,{strict:!0});if(!item.isOfType("weapon"))return;const existing=actor.itemTypes.melee.filter(m=>m.flags.pf2e.linkedWeapon===itemId).map(m=>m.id);if(existing.length>0)if(await Dialog.confirm({title:game.i18n.localize("PF2E.Actor.NPC.GenerateAttack.Confirm.Title"),content:game.i18n.localize("PF2E.Actor.NPC.GenerateAttack.Confirm.Content"),defaultYes:!1}))await actor.deleteEmbeddedDocuments("Item",existing,{render:!1});else return;const attacks=item.toNPCAttacks().map(a=>a.toObject());await actor.createEmbeddedDocuments("Item",attacks),ui.notifications.info(game.i18n.format("PF2E.Actor.NPC.GenerateAttack.Notification",{attack:attacks.at(0)?.name??""}))},handlers}async#onChangeSpellcastingEntry(element,event2){event2.preventDefault();const itemId=htmlClosest(element,".spellcasting-entry")?.dataset.containerId??"",key=element.dataset.baseProperty?.replace(/data\.items\.\d+\./,"")??"",value=element.classList.contains("focus-points")||element.classList.contains("focus-pool")?Math.min(Number(element.value)||0,3):element.nodeName==="SELECT"?element.value:Number(element.value)||0;await this.actor.updateEmbeddedDocuments("Item",[{_id:itemId,[key]:value}])}async _updateObject(event2,formData){if(this.actor.isElite||this.actor.isWeak){const{max}=this.actor.system.attributes.hp;formData["system.attributes.hp.max"]===max&&delete formData["system.attributes.hp.max"]}const shield=this.actor.heldShield;return shield&&Number.isInteger(formData["system.attributes.shield.value"])&&await shield.update({"system.hp.value":formData["system.attributes.shield.value"]}),super._updateObject(event2,formData)}}class SimpleNPCSheet extends AbstractNPCSheet{static{__name(this,"SimpleNPCSheet")}static{__name2(this,"SimpleNPCSheet")}static get defaultOptions(){return{...super.defaultOptions,width:650,height:420,scrollY:[".sheet-body"],template:"systems/pf2e/templates/actors/npc/simple-sheet.hbs"}}}class PartySheetPF2e extends ActorSheetPF2e{static{__name(this,"PartySheetPF2e")}static{__name2(this,"PartySheetPF2e")}currentSummaryView="languages";static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"party"],width:720,height:720,template:"systems/pf2e/templates/actors/party/sheet.hbs",scrollY:[...options.scrollY,".tab.active",".tab.active .content",".sidebar"],tabs:[{navSelector:"form > nav",contentSelector:".container",initial:"main"}]}}regionTemplates={overview:"overview.hbs",inventoryMembers:"inventory-members.hbs",exploration:"exploration.hbs",explorationSidebar:"exploration-sidebar.hbs"};get isLootSheet(){return this.actor.canUserModify(game.user,"update")}_getHeaderButtons(){const buttons=super._getHeaderButtons();return game.user.isGM&&buttons.unshift({label:"JOURNAL.ActionShow",class:"show-sheet",icon:"fa-solid fa-eye",onclick:()=>{const users=game.users.filter(u=>!u.isSelf);game.socket.emit("system.pf2e",{request:"showSheet",users:users.map(u=>u.uuid),document:this.actor.uuid,options:{tab:this._tabs[0].active}})}}),buttons}async getData(options){const base=await super.getData(options),members=this.actor.members,canDistributeCoins=game.user.isGM&&this.isEditable?{enabled:this.actor.inventory.coins.copperValue>0&&members.some(isReallyPC)}:null;return{...base,playerRestricted:!game.settings.get("pf2e","metagame_showPartyStats"),restricted:!(game.user.isGM||game.settings.get("pf2e","metagame_showPartyStats")),members:this.#prepareMembers(),overviewSummary:this.#prepareOverviewSummary(),inventorySummary:{totalCoins:sumBy(members,actor=>actor.inventory.coins.goldValue??0)+this.actor.inventory.coins.goldValue,totalWealth:sumBy(members,actor=>actor.inventory.totalWealth.goldValue??0)+this.actor.inventory.totalWealth.goldValue,totalBulk:members.map(actor=>actor.inventory.bulk.value).reduce((a,b)=>a.plus(b),this.actor.inventory.bulk.value)},canDistributeCoins,explorationSummary:{speed:this.actor.system.attributes.speed.total,activities:Object.entries(CONFIG.PF2E.hexplorationActivities).find(([max])=>Number(max)>=this.actor.system.attributes.speed.total)?.[1]??0},orphaned:this.actor.items.filter(i=>!i.isOfType(...this.actor.allowedItemTypes))}}#prepareMembers(){function sanitizeSense(label){return label.replace(/\((imprecise|precise)\)/gi,"").replace(/\d+/g,"").replaceAll("feet","").trim()}return __name(sanitizeSense,"sanitizeSense"),__name2(sanitizeSense,"sanitizeSense"),this.actor.members.map(actor=>{const observer=actor.testUserPermission(game.user,"OBSERVER"),restricted=!(game.settings.get("pf2e","metagame_showPartyStats")||observer),genderPronouns=actor.isOfType("character")&&actor.system.details.gender.value.trim()||null,blurb=actor.isOfType("character")&&actor.ancestry&&actor.class?game.i18n.format("PF2E.Actor.Character.Blurb",{level:actor.level,ancestry:actor.ancestry.name,class:actor.class.name}):actor.isOfType("familiar")&&actor.master?game.i18n.format("PF2E.Actor.Familiar.Blurb",{master:actor.master.name}):actor.isOfType("npc")&&actor.system.details.blurb.trim()||null,heroPoints=actor.isOfType("character")&&isReallyPC(actor)?actor.system.resources.heroPoints:null,activities=actor.isOfType("character")?compact(actor.system.exploration.map(id=>actor.items.get(id))):[];return{actor,hasBulk:actor.inventory.bulk.encumberedAfter!==1/0,bestSkills:Object.values(actor.skills??{}).filter(s=>!!s?.proficient&&!s.lore).sort((a,b)=>(b.mod??0)-(a.mod??0)).slice(0,4).map(s=>({slug:s.slug,mod:s.mod,label:s.label,rank:s.rank})),genderPronouns,blurb,heroPoints,owner:actor.isOwner,observer,limited:observer||actor.limited,speeds:[{label:"PF2E.Speed",value:actor.attributes.speed.value},...actor.attributes.speed.otherSpeeds.map(s=>({label:s.label,value:s.value}))],senses:(()=>{const rawSenses=actor.system.traits.senses??[];if(!Array.isArray(rawSenses))return rawSenses.value.split(",").filter(s=>!!s.trim()).map(l=>({labelFull:l.trim(),label:sanitizeSense(l)}));const senseTypes=new Set(rawSenses.map(s=>s.type));return(senseTypes.has("darkvision")||senseTypes.has("greaterDarkvision"))&&senseTypes.delete("lowLightVision"),senseTypes.has("greaterDarkvision")&&senseTypes.delete("darkvision"),rawSenses.filter(r=>senseTypes.has(r.type)).map(r=>({acuity:r.acuity,labelFull:r.label??"",label:CONFIG.PF2E.senses[r.type]??r.type}))})(),hp:actor.hitPoints,activities:activities.map(action2=>({uuid:action2.uuid,name:action2.name,img:action2.img,traits:createSheetTags(CONFIG.PF2E.actionTraits,action2.system.traits?.value??[])})),restricted}})}#prepareOverviewSummary(){const members=this.actor.members;if(!members.length)return null;const allLanguages=new Set(members.flatMap(m=>m.system.traits.languages?.value??[])),baseKnowledgeSkills=["arcana","nature","occultism","religion","crafting","society","medicine"],loreSkills=new Set(members.flatMap(m=>Object.values(m.skills)).filter(s=>!!s?.lore).map(s=>s.slug));function getBestSkill(slug){const statistic=maxBy(members,m=>m.skills[slug]?.mod??-1/0)?.skills[slug];return statistic?pick(statistic,["slug","mod","label","rank"]):null}return __name(getBestSkill,"getBestSkill"),__name2(getBestSkill,"getBestSkill"),{languages:sortBy([...allLanguages].map(slug=>({slug,label:game.i18n.localize(CONFIG.PF2E.languages[slug]),actors:this.#getActorsThatUnderstand(slug)})),l=>l.label),skills:sortBy(Array.from(SKILL_LONG_FORMS).map(slug=>{const best=getBestSkill(slug),label=game.i18n.localize(CONFIG.PF2E.skillList[slug]);return best??{mod:0,label,slug,rank:0}}),s=>s.label),knowledge:{regular:compact(baseKnowledgeSkills.map(getBestSkill)),lore:sortBy(compact([...loreSkills].map(getBestSkill)),s=>s.label)}}}#getActorsThatUnderstand(slug){return this.actor.members.filter(m=>!!m?.system.traits.languages?.value.includes(slug))}setSummaryView(view){const summary=htmlQuery(this.element[0],"[data-tab=overview] .summary");if(!summary)return;const viewElements=htmlQueryAll(summary,"[data-view]:not([data-action=change-view])");for(const element of viewElements)element.hidden=view!==element.dataset.view;for(const button of htmlQueryAll(summary,"[data-action=change-view]"))button.classList.toggle("active",button.dataset.view===view);this.currentSummaryView=view}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"a[data-action=open-meta-setting]")?.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.metagame");if(menu){const options={highlightSetting:"showPartyStats"};new menu.type(void 0,options).render(!0)}});for(const rollLink of htmlQueryAll(html,"[data-action=roll]")){const actorUUID=htmlClosest(rollLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");actor instanceof ActorPF2e&&rollLink.addEventListener("click",event2=>{const rollMode=rollLink.dataset.secret?game.user.isGM?"gmroll":"blindroll":void 0;actor.getStatistic(rollLink.dataset.statistic??"")?.roll({...eventToRollParams(event2,{type:"check"}),rollMode})})}for(const openSheetLink of htmlQueryAll(html,"[data-action=open-sheet]")){const tab=openSheetLink.dataset.tab,actorUUID=htmlClosest(openSheetLink,"[data-actor-uuid]")?.dataset.actorUuid,actor=fromUuidSync(actorUUID??"");openSheetLink.addEventListener("click",async()=>actor?.sheet.render(!0,{tab}))}this.setSummaryView(this.currentSummaryView);for(const button of htmlQueryAll(html,"[data-action=change-view]"))button.addEventListener("click",()=>{this.setSummaryView(button.dataset.view??"languages")});for(const memberElem of htmlQueryAll(html,"[data-actor-uuid]")){const actorUUID=memberElem.dataset.actorUuid,actor=this.document.members.find(m=>m.uuid===actorUUID);if(game.user.isGM&&htmlQuery(memberElem,"a[data-action=remove-member]")?.addEventListener("click",async event2=>{(event2.ctrlKey?!0:await Dialog.confirm({title:game.i18n.localize("PF2E.Actor.Party.RemoveMember.Title"),content:game.i18n.localize("PF2E.Actor.Party.RemoveMember.Content")}))&&actor&&this.document.removeMembers(actor)}),actor?.isOfType("character")&&actor.canUserModify(game.user,"update")){const heroPointsPips=htmlQuery(memberElem,"a[data-action=adjust-hero-points]"),{heroPoints}=actor;heroPointsPips?.addEventListener("click",async()=>{const newValue=Math.min(heroPoints.value+1,heroPoints.max);await actor.update({"system.resources.heroPoints.value":newValue})}),heroPointsPips?.addEventListener("contextmenu",async event2=>{event2.preventDefault();const newValue=Math.max(heroPoints.value-1,0);await actor.update({"system.resources.heroPoints.value":newValue})})}}for(const languageTag of htmlQueryAll(html,"[data-language]")){const slug=languageTag.dataset.language,members=this.#getActorsThatUnderstand(slug).map(m=>m.name).join(", "),titleLabel=game.i18n.localize("PF2E.Actor.Party.MembersLabel"),title=createHTMLElement("strong",{children:[titleLabel]}),content=createHTMLElement("span",{children:[title,members]});$(languageTag).tooltipster({content})}for(const skillTag of htmlQueryAll(html,".summary .skills [data-slug]")){const slug=skillTag.dataset.slug??"",statistics=compact(this.actor.members.map(m=>m.skills[slug])),labels=sortBy(statistics,s=>s.mod).map(statistic=>{const rank=statistic.rank??(statistic.proficient?1:0),prof=game.i18n.localize(CONFIG.PF2E.proficiencyLevels[rank]),label=`${statistic.actor.name} (${prof}) ${signedInteger(statistic.mod)}`,row=createHTMLElement("div",{children:[label]});return row.style.textAlign="right",row}),content=createHTMLElement("div",{children:labels});$(skillTag).tooltipster({content})}for(const activityElem of htmlQueryAll(html,".activity[data-activity-uuid]")){const document2=fromUuidSync(activityElem.dataset.activityUuid??"");if(!(document2 instanceof ItemPF2e))continue;const rollData=document2.getRollData();(async()=>{const content=createHTMLElement("div",{classes:["item-summary"],innerHTML:await TextEditor.enrichHTML(document2.description,{async:!0,rollData})});InlineRollLinks.listen(content,document2),$(activityElem).tooltipster({contentAsHTML:!0,content,interactive:!0,maxWidth:500,side:"right",theme:"crb-hover"})})()}htmlQuery(html,"button[data-action=distribute-coins]")?.addEventListener("click",()=>{new DistributeCoinsPopup(this.actor,{recipients:this.actor.members}).render(!0)}),htmlQuery(html,"[data-action=clear-exploration]")?.addEventListener("click",async()=>{await Promise.all(this.actor.members.map(m=>m.update({"system.exploration":[]}))),ui.notifications.info("PF2E.Actor.Party.ClearActivities.Complete",{localize:!0})}),htmlQuery(html,"[data-action=rest]")?.addEventListener("click",event2=>{game.pf2e.actions.restForTheNight({event:event2,actors:this.actor.members})}),htmlQuery(html,"[data-action=prompt]")?.addEventListener("click",()=>{game.pf2e.gm.checkPrompt({actors:this.actor.members})})}async _onDropItemCreate(itemData){const toTest=Array.isArray(itemData)?itemData:[itemData],supported=[...PHYSICAL_ITEM_TYPES,...this.actor.baseAllowedItemTypes],invalid=toTest.filter(i=>!supported.includes(i.type));if(invalid.length){for(const source of invalid){const type=game.i18n.localize(CONFIG.Item.typeLabels[source.type]??source.type.titleCase());ui.notifications.error(game.i18n.format("PF2E.Item.CannotAddType",{type}))}return[]}return super._onDropItemCreate(itemData)}async _onDropItem(event2,data){const droppedRegion=event2.target?.closest("[data-region]")?.dataset.region,targetActor=event2.target?.closest("[data-actor-uuid]")?.dataset.actorUuid;if(droppedRegion==="inventoryMembers"&&targetActor){const item=await ItemPF2e.fromDropData(data);if(!item)return[];const actorUuid=foundry.utils.parseUuid(targetActor).documentId;if(actorUuid&&item.actor&&item.isOfType("physical"))return await this.moveItemBetweenActors(event2,item.actor.id,item.actor.token?.id??null,actorUuid,null,item.id),[item]}return super._onDropItem(event2,data)}_disableFields(_form){}async#renderRegions(element,data){for(const region of htmlQueryAll(element,"[data-region]")){const regionId=region.dataset.region??"",templateName=this.regionTemplates[regionId];if(!templateName)continue;const template=`systems/pf2e/templates/actors/party/regions/${templateName}`,result=await renderTemplate(template,data);region.innerHTML=result,this._state!==Application.RENDER_STATES.RENDERING&&this.activateListeners($(region)),await this.#renderRegions(region,data)}}async render(force,options){if(options?.actors){const data=await this.getData();return this._saveScrollPositions(this.element),await this.#renderRegions(this.element[0],data),this._restoreScrollPositions(this.element),this}else return super.render(force,options)}async _renderInner(data,options){const result=await super._renderInner(data,options);return await this.#renderRegions(result[0],data),result}async _onDropActor(event2,data){await super._onDropActor(event2,data);const actor=fromUuidSync(data.uuid);actor instanceof CreaturePF2e&&this.document.addMembers(actor)}}class VehicleSheetPF2e extends ActorSheetPF2e{static{__name(this,"VehicleSheetPF2e")}static{__name2(this,"VehicleSheetPF2e")}static get defaultOptions(){const options=super.defaultOptions;return{...options,classes:[...options.classes,"vehicle"],width:670,height:480,tabs:[{navSelector:".sheet-navigation",contentSelector:".sheet-content",initial:"details"}],template:"systems/pf2e/templates/actors/vehicle/sheet.hbs"}}async getData(){const sheetData=await super.getData(),actions={action:{label:game.i18n.localize("PF2E.ActionsActionsHeader"),actions:[]},reaction:{label:game.i18n.localize("PF2E.ActionsReactionsHeader"),actions:[]},free:{label:game.i18n.localize("PF2E.ActionsFreeActionsHeader"),actions:[]}};for(const item of this.actor.itemTypes.action.sort((a,b)=>a.sort-b.sort)){const itemData=item.toObject(!1),{actionCost,frequency}=item,actionType=actionCost?.type??"free",img=(()=>{const actionIcon=getActionIcon(item.actionCost),defaultIcon=ItemPF2e.getDefaultArtwork(item._source).img;return item.isOfType("action")&&![actionIcon,defaultIcon].includes(item.img)?item.img:item.system.selfEffect?.img??actionIcon})();actions[actionType].actions.push({...itemData,id:item.id,img,actionCost,glyph:actionCost?getActionGlyph(actionCost):null,frequency,hasEffect:!!item.system.selfEffect})}return{...sheetData,actions,actorSizes:CONFIG.PF2E.actorSizes,actorSize:CONFIG.PF2E.actorSizes[this.actor.size],actorRarities:CONFIG.PF2E.rarityTraits,actorRarity:CONFIG.PF2E.rarityTraits[this.actor.system.traits.rarity],ac:getAdjustedValue(this.actor.attributes.ac.value,this.actor._source.system.attributes.ac.value),saves:{fortitude:getAdjustedValue(this.actor.saves.fortitude.mod,this.actor._source.system.saves.fortitude.value)}}}activateListeners($html){super.activateListeners($html);const html=$html[0],titleElem=htmlQuery(html,"nav > .panel-title");if(!titleElem)throw ErrorPF2e("Unexpected missing DOM element");const initialTitle=htmlQuery(html,".sheet-navigation .active")?.title;initialTitle&&(titleElem.title=initialTitle);for(const element of htmlQueryAll(html,".sheet-navigation .item"))element.addEventListener("mouseover",()=>{titleElem.textContent=element.title}),element.addEventListener("mouseout",()=>{const parent=htmlClosest(element,".sheet-navigation"),title=htmlQuery(parent,".item.active")?.title;title&&(titleElem.textContent=title)})}}class AbilitySheetPF2e extends ItemSheetPF2e{static{__name(this,"AbilitySheetPF2e")}static{__name2(this,"AbilitySheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}],hasSidebar:!0}}async getData(options={}){const sheetData=await super.getData(options);return{...sheetData,categories:CONFIG.PF2E.actionCategories,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,actionTraits:CONFIG.PF2E.actionTraits,frequencies:CONFIG.PF2E.frequencies,skills:CONFIG.PF2E.skillList,proficiencies:CONFIG.PF2E.proficiencyLevels,selfEffect:createSelfEffectSheetData(sheetData.data.selfEffect)}}activateListeners($html){if(super.activateListeners($html),!this.isEditable)return;const html=$html[0];activateActionSheetListeners(this.item,html)}async _onDrop(event2){return handleSelfEffectDrop(this,event2)}}class AfflictionSheetPF2e extends ItemSheetPF2e{static{__name(this,"AfflictionSheetPF2e")}static{__name2(this,"AfflictionSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:"[data-stage-id]"}],hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),definingTraits=["disease","poison","curse"],traits=new Set(this.item.system.traits.value),definingTrait=definingTraits.find(t=>traits.has(t));return{...sheetData,itemType:game.i18n.localize(definingTrait?CONFIG.PF2E.actionTraits[definingTrait]:"PF2E.LevelLabel"),conditionTypes:omit(CONFIG.PF2E.conditionTypes,["persistent-damage"]),damageTypes:CONFIG.PF2E.damageTypes,damageCategories:pick(CONFIG.PF2E.damageCategories,["precision","persistent","splash"]),durationUnits:omit(CONFIG.PF2E.timeUnits,["encounter"]),onsetUnits:omit(CONFIG.PF2E.timeUnits,["encounter","unlimited"]),saves:CONFIG.PF2E.saves,stages:await this.prepareStages()}}async prepareStages(){const stages={};for(const[idx,[id,stage]]of Object.entries(Object.entries(this.item.system.stages))){const conditions=Object.entries(stage.conditions).reduce((result,[key,data])=>{const document2=ConditionManager.getCondition(data.slug);return result[key]={...data,document:document2},result},{}),effectDocuments=await UUIDUtils.fromUUIDs(stage.effects.map(e=>e.uuid)),effects=stage.effects.map(effect=>{const document2=effectDocuments.find(d=>d.uuid===effect.uuid);return document2 instanceof ItemPF2e?{...effect,name:document2.name,img:document2.img}:effect});stages[id]={...stage,stage:Number(idx)+1,conditions,effects}}return stages}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"[data-action=onset-add]")?.addEventListener("click",()=>{const onset={value:1,unit:"minutes",active:!0};this.item.update({system:{onset}})}),htmlQuery(html,"[data-action=onset-delete]")?.addEventListener("click",()=>{this.item.update({system:{"-=onset":null}})}),htmlQuery(html,"[data-action=stage-add]")?.addEventListener("click",()=>{const stage={damage:{},conditions:{},effects:[],duration:{value:-1,unit:"unlimited"}};this.item.update({system:{stages:{[foundry.utils.randomID()]:stage}}})});for(const deleteIcon of htmlQueryAll(html,"[data-action=stage-delete]"))deleteIcon.addEventListener("click",event2=>{const deleteId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;deleteId&&this.item.update({[`system.stages.-=${deleteId}`]:null})});for(const addIcon of htmlQueryAll(html,"[data-action=damage-create]")??[])addIcon?.addEventListener("click",event2=>{const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const damage={formula:"",type:"untyped"};this.item.update({[`system.stages.${stageId}.damage.${foundry.utils.randomID()}`]:damage})});for(const deleteIcon of htmlQueryAll(html,"[data-action=damage-delete"))deleteIcon.addEventListener("click",event2=>{const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const deleteId=htmlClosest(event2.target,"[data-id]")?.dataset.id;this.item.update({[`system.stages.${stageId}.damage.-=${deleteId}`]:null})});for(const addIcon of htmlQueryAll(html,"[data-action=condition-create")??[])addIcon?.addEventListener("click",event2=>{const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;if(!this.item.system.stages[stageId??""])return;const newCondition={slug:"frightened",value:1};this.item.update({[`system.stages.${stageId}.conditions.${foundry.utils.randomID()}`]:newCondition})});for(const conditionEl of htmlQueryAll(html,".stage-condition[data-condition-id]")){const stageId=htmlClosest(conditionEl,"[data-stage-id]")?.dataset.stageId,conditionId=conditionEl.dataset.conditionId??"",stage=this.item.system.stages[stageId??""];!stage||!(conditionId in stage.conditions)||(htmlQuery(conditionEl,"[data-action=condition-link]")?.addEventListener("click",()=>{const linked=stage.conditions[conditionId].linked;this.item.update({[`system.stages.${stageId}.conditions.${conditionId}.linked`]:!linked})}),htmlQuery(conditionEl,"[data-action=condition-delete]")?.addEventListener("click",()=>{this.item.update({[`system.stages.${stageId}.conditions.-=${conditionId}`]:null})}))}for(const deleteIcon of htmlQueryAll(html,"[data-action=effect-delete"))deleteIcon.addEventListener("click",event2=>{const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId,stage=this.item.system.stages[stageId??""];if(!stage)return;const deleteId=htmlClosest(event2.target,"[data-uuid]")?.dataset.uuid,effects=stage.effects.filter(e=>e.uuid!==deleteId);this.item.update({[`system.stages.${stageId}.effects`]:effects})});for(const link of htmlQueryAll(html,"a.document-link[data-uuid]"))link.addEventListener("click",async event2=>{const uuid=htmlClosest(event2.target,"[data-uuid]")?.dataset.uuid;(await fromUuid(uuid??""))?.sheet?.render(!0)})}async _onDrop(event2){if(!this.isEditable)return;const stageId=htmlClosest(event2.target,"[data-stage-id]")?.dataset.stageId;if(!stageId)return;const stage=this.item.system.stages[stageId];if(!stage)return;const item=await(async()=>{try{const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(item?.isOfType("effect")){const effects=[...stage.effects,{uuid:item.uuid}];this.item.update({system:{stages:{[stageId]:{effects}}}})}else ui.notifications.error("PF2E.Item.Affliction.Error.RestrictedStageItem",{localize:!0})}async _updateObject(event2,formData){const categories=Object.keys(formData).filter(k=>/^system\.stages\.[a-z0-9]+\.damage\.[a-z0-9]+\.category$/i.test(k));for(const key of categories)formData[key]||=null;return super._updateObject(event2,formData)}}class ABCSheetPF2e extends ItemSheetPF2e{static{__name(this,"ABCSheetPF2e")}static{__name2(this,"ABCSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}]}}async getData(options){const sheetData=await super.getData(options),features=Object.entries(this.item.toObject().system.items).map(([key,ref])=>({key,item:{...ref,fromWorld:ref.uuid.startsWith("Item.")}})).sort((a,b)=>a.item.level-b.item.level);return{...sheetData,features}}getLocalizedAbilities(traits){return traits!==void 0&&traits.value?traits.value.length===6?{free:game.i18n.localize("PF2E.AbilityFree")}:Object.fromEntries(traits.value.map(x=>[x,CONFIG.PF2E.abilities[x]])):{}}#isValidDrop(event2,feat){const validCategories=(htmlClosest(event2.target,"[data-valid-drops]")?.dataset.validDrops?.split(" ")??[]).filter(f=>setHasElement(FEAT_CATEGORIES,f));if(validCategories.includes(feat.category))return!0;const goodCategories=validCategories.map(c=>game.i18n.localize(CONFIG.PF2E.featCategories[c]));if(goodCategories.length>0){const badCategory=game.i18n.localize(CONFIG.PF2E.featCategories[feat.category]),warning=game.i18n.format("PF2E.Item.ABC.InvalidDrop",{badType:badCategory,goodType:goodCategories[0]});return ui.notifications.warn(warning),!1}return!0}async _onDrop(event2){event2.preventDefault();const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??""),item=await ItemPF2e.fromDropData(dropData);if(!item?.isOfType("feat")||!this.#isValidDrop(event2,item))return;const entry={uuid:item.uuid,img:item.img,name:item.name,level:item.level},items=this.item.system.items,pathPrefix="system.items";let id;do id=foundry.utils.randomID(5);while(items[id]);await this.item.update({[`${pathPrefix}.${id}`]:entry})}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const li of htmlQueryAll(html,"li[data-index]")){const index=li.dataset.index,itemUUID=li.dataset.itemUuid;index&&(itemUUID&&htmlQuery(li,"a.name")?.addEventListener("click",()=>fromUuid(itemUUID).then(i=>i?.sheet.render(!0))),htmlQuery(li,"[data-action=remove]")?.addEventListener("click",()=>{this.item.update({[`system.items.-=${index}`]:null})}))}}}class AncestrySheetPF2e extends ABCSheetPF2e{static{__name(this,"AncestrySheetPF2e")}static{__name2(this,"AncestrySheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),itemData=sheetData.item;return{...sheetData,selectedBoosts:Object.fromEntries(Object.entries(itemData.system.boosts).map(([k,b])=>[k,this.getLocalizedAbilities(b)])),selectedFlaws:Object.fromEntries(Object.entries(itemData.system.flaws).map(([k,b])=>[k,this.getLocalizedAbilities(b)])),sizes:createSheetOptions(CONFIG.PF2E.actorSizes,{value:[itemData.system.size]}),languages:createSheetOptions(CONFIG.PF2E.languages,itemData.system.languages),additionalLanguages:createSheetOptions(CONFIG.PF2E.languages,itemData.system.additionalLanguages)}}}class ArmorSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"ArmorSheetPF2e")}static{__name2(this,"ArmorSheetPF2e")}async getData(options){const sheetData=await super.getData(options),armor=this.item,adjustedBulkHint=armor.isEquipped||!armor.actor?null:"PF2E.Item.Armor.UnequippedHint",runes=armor.system.runes,propertyRuneSlots=Array.fromRange(armor.isSpecific?runes.property.length:getPropertyRuneSlots(armor)).map(i=>({slug:runes.property[i]??null,label:RUNE_DATA.armor.property[runes.property[i]]?.name??null,disabled:i>0&&!runes.property[i-1]})),specificMagicData=armor._source.system.specific??pick(armor._source.system,["material","runes"]);return{...sheetData,adjustedBulkHint,basePrice:new CoinsPF2e(armor._source.system.price.value),baseTypes:CONFIG.PF2E.baseArmorTypes,categories:CONFIG.PF2E.armorCategories,groups:CONFIG.PF2E.armorGroups,otherTags:createSheetTags(CONFIG.PF2E.otherArmorTags,sheetData.data.traits.otherTags),preciousMaterials:this.getMaterialSheetData(armor,MATERIAL_DATA.armor),propertyRuneSlots,runeTypes:RUNE_DATA.armor,specificMagicData}}async _updateObject(event2,formData){formData["system.acBonus"]===null&&(formData["system.acBonus"]=0);const propertyRuneIndices=[0,1,2,3],propertyRuneUpdates=propertyRuneIndices.flatMap(i=>formData[`system.runes.property.${i}`]??[]);if(propertyRuneUpdates.length>0){formData["system.runes.property"]=compact(propertyRuneUpdates);for(const index of propertyRuneIndices)delete formData[`system.runes.property.${index}`]}return super._updateObject(event2,formData)}}class BackgroundSheetPF2e extends ABCSheetPF2e{static{__name(this,"BackgroundSheetPF2e")}static{__name2(this,"BackgroundSheetPF2e")}async getData(options){const data=await super.getData(options),itemData=data.item;return{...data,trainedSkills:createSheetOptions(CONFIG.PF2E.skills,itemData.system.trainedSkills),selectedBoosts:Object.fromEntries(Object.entries(itemData.system.boosts).map(([k,b])=>[k,this.getLocalizedAbilities(b)]))}}}class BookSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"BookSheetPF2e")}static{__name2(this,"BookSheetPF2e")}}class CampaignFeatureSheetPF2e extends ItemSheetPF2e{static{__name(this,"CampaignFeatureSheetPF2e")}static{__name2(this,"CampaignFeatureSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,hasSidebar:!0}}get validTraits(){return CONFIG.PF2E.kingmakerTraits}async getData(options){const sheetData=await super.getData(options),hasLevel=this.item.behavior!=="activity";return{...sheetData,itemType:hasLevel?game.i18n.localize(this.item.levelLabel):null,categories:KINGMAKER_CATEGORIES,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,prerequisites:JSON.stringify(this.item.system.prerequisites?.value??[]),isFeat:this.item.isFeat}}activateListeners($html){super.activateListeners($html);const html=$html[0];activateActionSheetListeners(this.item,html);const prerequisites=htmlQuery(html,'input[name="system.prerequisites.value"]');prerequisites&&new Tagify(prerequisites,{editTags:1})}_updateObject(event2,formData){return Array.isArray(formData["system.prerequisites.value"])&&(formData["system.prerequisites.value"]=formData["system.prerequisites.value"].map(value=>({value}))),super._updateObject(event2,formData)}}class ClassSheetPF2e extends ABCSheetPF2e{static{__name(this,"ClassSheetPF2e")}static{__name2(this,"ClassSheetPF2e")}async getData(options){const sheetData=await super.getData(options),itemData=sheetData.item;return{...sheetData,skills:CONFIG.PF2E.skills,proficiencyChoices:CONFIG.PF2E.proficiencyLevels,selectedKeyAbility:this.getLocalizedAbilities(itemData.system.keyAbility),trainedSkills:createSheetTags(CONFIG.PF2E.skills,itemData.system.trainedSkills),ancestryFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.ancestryFeatLevels),classFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.classFeatLevels),generalFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.generalFeatLevels),skillFeatLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.skillFeatLevels),skillIncreaseLevels:createSheetTags(CONFIG.PF2E.levels,itemData.system.skillIncreaseLevels)}}}class ConditionSheetPF2e extends ItemSheetPF2e{static{__name(this,"ConditionSheetPF2e")}static{__name2(this,"ConditionSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,hasSidebar:!0}}}class ConsumableSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"ConsumableSheetPF2e")}static{__name2(this,"ConsumableSheetPF2e")}async getData(options){const sheetData=await super.getData(options),item=this.item,canHaveDamageOrHealing=DAMAGE_OR_HEALING_CONSUMABLE_CATEGORIES.has(item.category),canHaveHealing=canHaveDamageOrHealing&&item.system.category!=="snare"&&!!item.system.damage&&["vitality","void","untyped"].includes(item.system.damage.type);return{...sheetData,canHaveDamageOrHealing,canHaveHealing,categories:sortStringRecord(CONFIG.PF2E.consumableCategories),damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),materialEffects:createSheetTags(CONFIG.PF2E.materialDamageEffects,item.system.material.effects),otherTags:createSheetTags(CONFIG.PF2E.otherConsumableTags,item.system.traits.otherTags),stackGroups:this.item.isAmmo?omit(CONFIG.PF2E.stackGroups,["coins","gems"]):null}}activateListeners($html){super.activateListeners($html);const html=$html[0];html.querySelector("button[data-action=add-damage]")?.addEventListener("click",()=>{this.item.update({"system.damage":{formula:"1d4",type:"untyped",kind:"damage"}})}),html.querySelector("a[data-action=remove-damage]")?.addEventListener("click",()=>{this.item.update({"system.damage":null})})}_updateObject(event2,formData){return formData["system.stackGroup"]===""&&(formData["system.stackGroup"]=null),super._updateObject(event2,formData)}}class ContainerSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"ContainerSheetPF2e")}static{__name2(this,"ContainerSheetPF2e")}}const DEITY_SANCTIFICATIONS=[{modal:"can",what:["holy"]},{modal:"can",what:["unholy"]},{modal:"can",what:["holy","unholy"]},{modal:"must",what:["holy"]},{modal:"must",what:["unholy"]}];class DeitySheetPF2e extends ItemSheetPF2e{static{__name(this,"DeitySheetPF2e")}static{__name2(this,"DeitySheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".sheet-header, .sheet-content"}]}}async getData(options){const sheetData=await super.getData(options),spellEntries=Object.entries(sheetData.data.spells),spells=(await UUIDUtils.fromUUIDs(Object.values(sheetData.data.spells))).filter(i=>i instanceof SpellPF2e).map(spell=>{const level=Number(spellEntries.find(([,uuid])=>uuid===spell.uuid)?.at(0));return{uuid:spell.uuid,level,name:spell.name,img:spell.img}}).sort((spellA,spellB)=>spellA.level-spellB.level),sanctifications=[...DEITY_SANCTIFICATIONS.map(value=>{const modal=value.modal.capitalize(),what=value.what.map(c=>c.capitalize()).join("");return{value,label:`PF2E.Item.Deity.Sanctification.${modal}.${what}`}}),{value:null,label:"PF2E.Item.Deity.Sanctification.None"}];return{...sheetData,sanctifications,skills:CONFIG.PF2E.skills,divineFonts:createSheetOptions({harm:"PF2E.Item.Deity.DivineFont.Harm",heal:"PF2E.Item.Deity.DivineFont.Heal"},sheetData.data.font),spells}}activateListeners($html){super.activateListeners($html);const html=$html[0],getInput=__name2(name2=>html.querySelector(`input[name="${name2}"]`),"getInput");if(tagify(getInput("system.attribute"),{whitelist:CONFIG.PF2E.abilities,maxTags:2}),this.item.category==="philosophy")return;tagify(getInput("system.weapons"),{whitelist:CONFIG.PF2E.baseWeaponTypes,maxTags:2});const domainWhitelist=omitBy(CONFIG.PF2E.deityDomains,(_v,k)=>k.endsWith("-apocryphal"));tagify(getInput("system.domains.primary"),{whitelist:domainWhitelist,maxTags:6}),tagify(getInput("system.domains.alternate"),{whitelist:domainWhitelist,maxTags:6});const clericSpells=htmlQuery(html,".cleric-spells");if(!clericSpells)return;for(const link of htmlQueryAll(clericSpells,"a[data-action=view-spell]"))link.addEventListener("click",async()=>{const uuid=htmlClosest(link,"li")?.dataset.uuid??"",spell=await fromUuid(uuid);if(!(spell instanceof SpellPF2e)){this.render(!1),ui.notifications.error(`A spell with the UUID "${uuid}" no longer exists`);return}spell.sheet.render(!0)});for(const link of htmlQueryAll(clericSpells,"a[data-action=remove-spell]"))link.addEventListener("click",async()=>{const uuidToRemove=htmlClosest(link,"li")?.dataset.uuid,[levelToRemove]=Object.entries(this.item.system.spells).find(([_level,uuid])=>uuid===uuidToRemove)??[];if(!levelToRemove){this.render(!1);return}await this.item.update({[`system.spells.-=${levelToRemove}`]:null})});const spellLevelInputs=htmlQueryAll(clericSpells,"input[data-action=update-spell-level]");for(const input of spellLevelInputs)input.addEventListener("change",async()=>{const oldLevel=Number(input.dataset.level),uuid=this.item.system.spells[oldLevel];if(!uuid){this.render(!1);return}const newLevel=Math.clamped(Number(input.value)||1,1,10);oldLevel!==newLevel&&await this.item.update({[`system.spells.-=${oldLevel}`]:null,[`system.spells.${newLevel}`]:uuid})})}async _onDrop(event2){if(!this.isEditable)return;const item=await(async()=>{try{const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(!(item instanceof SpellPF2e))throw ErrorPF2e("Invalid item drop on deity sheet");if(item.isCantrip||item.isFocusSpell||item.isRitual){ui.notifications.error("PF2E.Item.Deity.ClericSpells.DropError",{localize:!0});return}await this.item.update({[`system.spells.${item.rank}`]:item.uuid})}async _updateObject(event2,formData){return Array.isArray(formData["system.font"])&&(formData["system.font"]=formData["system.font"].filter(f=>!!f)),typeof formData["system.skill"]=="string"&&(formData["system.skill"]||=null),super._updateObject(event2,formData)}}class EffectSheetPF2e extends ItemSheetPF2e{static{__name(this,"EffectSheetPF2e")}static{__name2(this,"EffectSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,hasSidebar:!0}}async getData(options){const badge=this.item.badge;return{...await super.getData(options),itemType:game.i18n.localize("PF2E.LevelLabel"),badgeType:badge?game.i18n.localize(`PF2E.Item.Effect.Badge.Type.${badge.type}`):"",timeUnits:CONFIG.PF2E.timeUnits}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"select.badge-type")?.addEventListener("change",event2=>{event2.stopPropagation()}),htmlQuery(html,"[data-action=badge-add]")?.addEventListener("click",()=>{const badge=htmlQuery(html,".badge-type")?.value==="formula"?{type:"formula",value:"1d20",evaluate:!0}:{type:"counter",value:1};this.item.update({system:{badge}})}),htmlQuery(html,"[data-action=badge-delete]")?.addEventListener("click",()=>{this.item.update({"system.-=badge":null})}),htmlQuery(html,"[data-action=badge-add-label")?.addEventListener("click",()=>{if(!this.item.system.badge)throw ErrorPF2e("Unexpected error adding badge label");const labels=this.item.system.badge.labels??[];labels.push(""),this.item.update({system:{badge:{labels}}})});for(const deleteIcon of htmlQueryAll(html,"[data-action=badge-delete-label]")){const index=Number(deleteIcon.dataset.idx);deleteIcon.addEventListener("click",()=>{const labels=this.item.system.badge?.labels;labels&&(labels.splice(index,1),labels.length===0?this.item.update({"system.badge.-=labels":null}):this.item.update({system:{badge:{labels}}}))})}}async _updateObject(event2,formData){const expanded=foundry.utils.expandObject(formData),badge=expanded.system?.badge;badge&&("labels"in badge&&typeof badge.labels=="object"&&(badge.labels=Object.values(badge.labels)),"reevaluate"in badge&&(badge.reevaluate||=null)),super._updateObject(event2,foundry.utils.flattenObject(expanded))}}class EquipmentSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"EquipmentSheetPF2e")}static{__name2(this,"EquipmentSheetPF2e")}async getData(options){const item=this.item;return{...await super.getData(options),isApex:item._source.system.traits.value.includes("apex"),attributes:CONFIG.PF2E.abilities,otherTags:createSheetTags(CONFIG.PF2E.otherArmorTags,item.system.traits.otherTags)}}}class FeatSheetPF2e extends ItemSheetPF2e{static{__name(this,"FeatSheetPF2e")}static{__name2(this,"FeatSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}],hasSidebar:!0}}get validTraits(){return CONFIG.PF2E.featTraits}async getData(options){const sheetData=await super.getData(options),hasLineageTrait=this.item.traits.has("lineage");return{...sheetData,itemType:game.i18n.localize(this.item.isFeature?"PF2E.LevelLabel":"PF2E.Item.Feat.LevelLabel"),categories:CONFIG.PF2E.featCategories,actionTypes:CONFIG.PF2E.actionTypes,actionsNumber:CONFIG.PF2E.actionsNumber,frequencies:CONFIG.PF2E.frequencies,mandatoryTakeOnce:hasLineageTrait||sheetData.data.onlyLevel1,hasLineageTrait,canHaveKeyOptions:featCanHaveKeyOptions(this.item),selfEffect:createSelfEffectSheetData(sheetData.data.selfEffect)}}activateListeners($html){super.activateListeners($html);const html=$html[0];activateActionSheetListeners(this.item,html);const getInput=__name2(name2=>html.querySelector(`input[name="${name2}"]`),"getInput");tagify(getInput("system.prerequisites.value"),{maxTags:6}),tagify(getInput("system.subfeatures.keyOptions"),{whitelist:CONFIG.PF2E.abilities,maxTags:3})}async _onDrop(event2){return handleSelfEffectDrop(this,event2)}_updateObject(event2,formData){Array.isArray(formData["system.prerequisites.value"])&&(formData["system.prerequisites.value"]=formData["system.prerequisites.value"].map(value=>({value})));const keyOptionsKey="system.subfeatures.keyOptions",hasEmptyKeyOptions=Array.isArray(formData[keyOptionsKey])&&formData[keyOptionsKey].length===0,hasNoKeyOptions=!(keyOptionsKey in formData);return(hasEmptyKeyOptions||hasNoKeyOptions)&&(delete formData[keyOptionsKey],this.item._source.system.subfeatures&&(formData["system.subfeatures.-=keyOptions"]=null)),super._updateObject(event2,formData)}}class HeritageSheetPF2e extends ItemSheetPF2e{static{__name(this,"HeritageSheetPF2e")}static{__name2(this,"HeritageSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".sidebar"}],hasSidebar:!0}}async getData(options){const sheetData=await super.getData(options),ancestry=await(async()=>{const item=this.item.system.ancestry?await fromUuid(this.item.system.ancestry.uuid):null;return item instanceof AncestryPF2e?item:null})();return{...sheetData,ancestry,ancestryRefBroken:!!sheetData.data.ancestry&&ancestry===null}}activateListeners($html){super.activateListeners($html),$html.find('a[data-action="remove-ancestry"]').on("click",()=>{this.item.update({"system.ancestry":null})})}async _onDrop(event2){const item=await(async()=>{try{const dataString=event2.dataTransfer?.getData("text/plain"),dropData=JSON.parse(dataString??"");return await ItemPF2e.fromDropData(dropData)??null}catch{return null}})();if(!(item instanceof AncestryPF2e))throw ErrorPF2e("Invalid item drop on heritage sheet");const ancestryReference={name:item.name,slug:item.slug??sluggify(item.name),uuid:item.uuid};await this.item.update({"system.ancestry":ancestryReference})}}class KitSheetPF2e extends ItemSheetPF2e{static{__name(this,"KitSheetPF2e")}static{__name2(this,"KitSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dropSelector:".tab[data-tab=details]"}]}}async getData(options){const items=Object.fromEntries(Object.entries(this.item.system.items).map(([key,ref])=>[key,{...ref,fromWorld:ref.uuid.startsWith("Item.")}]));return{...await super.getData(options),priceString:this.item.price.value,items}}async _onDrop(event2){event2.preventDefault();const dragData=event2.dataTransfer?.getData("text/plain"),dragItem=JSON.parse(dragData??""),containerId=event2.target.dataset.containerId??event2.target.closest("[data-container-id]")?.dataset.containerId;if(dragItem.type!=="Item")return;const item=await fromUuid(dragItem.uuid??"");if(!(item instanceof PhysicalItemPF2e||item instanceof KitPF2e))return;const entry={uuid:item.uuid,img:item.img,quantity:1,name:item.name,isContainer:item.type==="backpack"&&!containerId,items:{}};let{items}=this.item.system,pathPrefix="system.items";containerId!==void 0&&(pathPrefix=`${pathPrefix}.${containerId}.items`,items=items[containerId]?.items??{});let id;do id=foundry.utils.randomID(5);while(items[id]);await this.item.update({[`${pathPrefix}.${id}`]:entry})}async removeItem(event2){const target=htmlClosest(event2.currentTarget??null,"li"),index=target?.dataset.index;if(!index)return this.item;const containerId=target.closest("[data-container-id]")?.dataset.containerId,path=containerId?`${containerId}.items.-=${index}`:`-=${target.dataset.index}`;return await this.item.update({[`system.items.${path}`]:null})??null}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const link of htmlQueryAll(html,"[data-action=remove]"))link.addEventListener("click",event2=>{this.removeItem(event2)})}async _updateObject(event2,formData){return formData["system.price.value"]&&(formData["system.price.value"]=CoinsPF2e.fromString(String(formData["system.price.value"]))),super._updateObject(event2,formData)}}class MeleeSheetPF2e extends ItemSheetPF2e{static{__name(this,"MeleeSheetPF2e")}static{__name2(this,"MeleeSheetPF2e")}async getData(options){const sheetData=await super.getData(options),itemSource=this.item._source;sheetData.data.attack.value=itemSource.system.attack.value;for(const key of Object.keys(sheetData.data.damageRolls))sheetData.data.damageRolls[key].damage=itemSource.system.damageRolls[key].damage;return{...sheetData,damageTypes:CONFIG.PF2E.damageTypes,damageCategories:damageCategoriesUnique,attackEffects:createSheetOptions(this.getAttackEffectOptions(),this.item.system.attackEffects)}}activateListeners($html){super.activateListeners($html);const html=$html[0];for(const button of htmlQueryAll(html,"a[data-action=add-partial]"))button.addEventListener("click",()=>{const newKey=foundry.utils.randomID();this.item.update({[`system.damageRolls.${newKey}`]:{damage:"1d4",damageType:"bludgeoning"}})});for(const button of htmlQueryAll(html,"a[data-action=remove-partial]"))button.addEventListener("click",()=>{const partialKey=htmlClosest(button,"[data-key]")?.dataset.key;partialKey&&this.item.update({[`system.damageRolls.-=${partialKey}`]:null})})}async _updateObject(event2,formData){const categories=Object.keys(formData).filter(k=>/^system.damageRolls\.[a-z0-9]+\.category$/i.test(k));for(const key of categories)formData[key]||=null;return super._updateObject(event2,formData)}}class ShieldSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"ShieldSheetPF2e")}static{__name2(this,"ShieldSheetPF2e")}async getData(options){const sheetData=await super.getData(options),shield=this.item,isSpecificShield=shield.isSpecific,weaponRunes=shield.system.traits.integrated?.runes,hasPotencyRune=!!weaponRunes?.potency,propertyRuneSlots=(()=>hasPotencyRune?isSpecificShield?weaponRunes.property.map((_p,index)=>index):shield.system.material.type==="orichalcum"?[0,1,2,3]:[0,1,2]:[])().map(i=>({slug:weaponRunes?.property[i]??null,disabled:!weaponRunes?.potency||(i===3||weaponRunes.potency<3)&&i>0&&(!weaponRunes.property[i-1]||!isSpecificShield),readOnly:isSpecificShield})),materialData=shield.isBuckler?MATERIAL_DATA.shield.buckler:shield.isTowerShield?MATERIAL_DATA.shield.towerShield:MATERIAL_DATA.shield.shield;return{...sheetData,baseHardness:shield._source.system.hardness,basePrice:new CoinsPF2e(shield._source.system.price.value),baseTypes:sortStringRecord(CONFIG.PF2E.baseShieldTypes),canChangeMaterial:!shield.isSpecific||!!shield.system.material.type,preciousMaterials:this.getMaterialSheetData(shield,materialData),propertyRuneSlots,reinforcing:mapToObj.indexed(REINFORCING_RUNE_LOC_PATHS,(value,index)=>[index,value]),weaponRunes:weaponRunes?RUNE_DATA.weapon:null}}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"input[data-action=toggle-specific")?.addEventListener("change",()=>{const newValue=this.item.system.specific?null:foundry.utils.deepClone({...pick(this.item._source.system,["material","runes"]),integrated:this.item._source.system.traits.integrated?{runes:this.item._source.system.traits.integrated.runes}:null});this.item.update({"system.specific":newValue})})}_updateObject(event2,formData){const propertyRuneIndices=[0,1,2,3],propertyRuneUpdates=propertyRuneIndices.flatMap(i=>formData[`system.traits.integrated.runes.property.${i}`]??[]);if(propertyRuneUpdates.length>0){formData["system.traits.integrated.runes.property"]=compact(propertyRuneUpdates);for(const index of propertyRuneIndices)delete formData[`system.traits.integrated.runes.property.${index}`]}return super._updateObject(event2,formData)}}const spellOverridable={traits:"PF2E.Traits",time:"PF2E.Item.Spell.Cast",target:"PF2E.SpellTargetLabel",area:"PF2E.AreaLabel",range:"PF2E.SpellRangeLabel",damage:"PF2E.DamageLabel"};class SpellSheetPF2e extends ItemSheetPF2e{static{__name(this,"SpellSheetPF2e")}static{__name2(this,"SpellSheetPF2e")}static get defaultOptions(){return{...super.defaultOptions,dragDrop:[{dragSelector:"[data-variant-id]",dropSelector:"[data-can-drop=true]"}]}}get id(){const baseId=super.id,appliedOverlays=this.item.appliedOverlays;return this.item.isVariant&&appliedOverlays?`${baseId}-${[...appliedOverlays.keys()].join("-")}`:baseId}get validTraits(){return omit(CONFIG.PF2E.Item.traits.spell,Array.from(MAGIC_TRADITIONS))}async getData(options){const sheetData=await super.getData(options),spell=this.item,{isCantrip,isFocusSpell,isRitual}=spell,descriptionPrepend=await createDescriptionPrepend(spell,{includeTraditions:!0});sheetData.enrichedContent.description=`${descriptionPrepend}${sheetData.enrichedContent.description}`;const variants=spell.overlays.overrideVariants.map(variant=>({name:variant.name,variantId:variant.variantId,sort:variant.sort,actions:getActionGlyph(variant.system.time.value)})).sort((a,b)=>a.sort-b.sort),passiveDefense=(()=>{switch(spell.system.defense?.passive?.statistic){case"ac":return"PF2E.Check.DC.Specific.armor";case"fortitude-dc":return"PF2E.Check.DC.Specific.fortitude";case"reflex-dc":return"PF2E.Check.DC.Specific.reflex";case"will-dc":return"PF2E.Check.DC.Specific.will";default:return null}})(),damageKinds=mapValues$1(spell.system.damage,(damage,id)=>{const healingDisabled=!["vitality","void","untyped"].includes(damage.type)||!!damage.category,currentKinds=Array.from(spell.system.damage[id].kinds);return[{value:["damage"],label:"PF2E.DamageLabel",selected:equals(currentKinds,["damage"]),disabled:!1},{value:["healing"],label:"PF2E.TraitHealing",selected:equals(currentKinds,["healing"]),disabled:healingDisabled},{value:["damage","healing"],label:"PF2E.Damage.Kind.Both.Label",selected:equals(currentKinds,["damage","healing"]),disabled:healingDisabled}]});return{...sheetData,itemType:createSpellRankLabel(this.item),isCantrip,isFocusSpell,isRitual,passiveDefense,variants,isVariant:this.item.isVariant,damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),damageSubtypes:pick(CONFIG.PF2E.damageCategories,[...DAMAGE_CATEGORIES_UNIQUE]),damageKinds,materials:CONFIG.PF2E.materialDamageEffects,areaSizes:CONFIG.PF2E.areaSizes,areaTypes:CONFIG.PF2E.areaTypes,heightenIntervals:[1,2,3,4],heightenOverlays:this.#prepareHeighteningLevels(),canHeighten:this.isEditable&&this.getAvailableHeightenLevels().length>0}}get title(){return this.item.isVariant?game.i18n.format("PF2E.Item.Spell.Variants.SheetTitle",{originalName:this.item.original?.name??""}):super.title}activateListeners($html){super.activateListeners($html);const html=$html[0];if(this.isEditable&&this.item.isVariant){const levelInput=htmlQuery(html,'input[name="system.level.value"');levelInput&&(levelInput.readOnly=!0)}tagify(html.querySelector('input[name="system.traits.traditions"]'),{whitelist:CONFIG.PF2E.magicTraditions});for(const anchor of htmlQueryAll(html,"a[data-action=add-damage-partial]"))anchor.addEventListener("click",()=>{const baseKey=this.#getOverlayFromElement(anchor)?.base??"system",emptyDamage={formula:"",kinds:["damage"],type:"bludgeoning",category:null,materials:[]};this.item.update({[`${baseKey}.damage.${foundry.utils.randomID()}`]:emptyDamage})});for(const anchor of htmlQueryAll(html,"a[data-action=delete-damage-partial]"))anchor.addEventListener("click",()=>{const overlayData=this.#getOverlayFromElement(anchor),baseKey=overlayData?.base??"system",key=anchor.dataset.id;if(key){const values={[`${baseKey}.damage.-=${key}`]:null};overlayData||(values[`${baseKey}.heightening.damage.-=${key}`]=null),this.item.update(values)}});htmlQuery(html,"button[data-action=add-interval-heightening]")?.addEventListener("click",event2=>{event2.preventDefault();const baseKey=this.#getOverlayFromElement(event2.target)?.base??"system",data={type:"interval",interval:1,damage:mapToObj(Object.keys(this.item.system.damage),key=>[key,"0"])};this.item.update({[`${baseKey}.heightening`]:data})}),htmlQuery(html,"button[data-action=add-fixed-heightening]")?.addEventListener("click",()=>{const highestLevel=this.item.getHeightenLayers().at(-1)?.level,available=this.getAvailableHeightenLevels(),level=highestLevel&&highestLevel<10?highestLevel+1:available.at(0);level!==void 0&&this.item.update({"system.heightening":{type:"fixed",levels:{[level]:{}}}})}),htmlQuery(html,"a[data-action=delete-heightening]")?.addEventListener("click",()=>{this.item.update({"system.-=heightening":null})});for(const overlayEditor of htmlQueryAll(html,"[data-overlay-type=heighten]")){const overlay=this.#getOverlayFromElement(overlayEditor);if(!overlay)continue;htmlQuery(overlayEditor,"a[data-action=delete-overlay]")?.addEventListener("click",()=>{if(overlay.type==="heighten"){const layers=this.item.getHeightenLayers();if(layers.length===1&&layers[0].level===overlay.level){this.item.update({"system.-=heightening":null});return}}const parts=overlay.base.split(".");parts.push(`-=${parts.pop()}`),this.item.update({[parts.join(".")]:null})});for(const addProperty of htmlQueryAll(overlayEditor,"button[data-action=add-overlay-property]")){const property=addProperty.dataset.property;!overlay.system||!property||property in overlay.system||addProperty.addEventListener("click",()=>{try{const value=this.#getDefaultProperty(property);this.item.update({[`${overlay.base}.${property}`]:value})}catch(ex){ex instanceof Error&&ui.notifications.error(ex.message)}})}for(const removeProperty of htmlQueryAll(overlayEditor,"a[data-action=delete-overlay-property]")){const property=removeProperty.dataset.property;property&&removeProperty.addEventListener("click",()=>{const updates={[`${overlay.base}.-=${property}`]:null};property==="damage"&&(updates[`${overlay.base}.-=heightening`]=null),this.item.update(updates)})}const levelSelect=htmlQuery(overlayEditor,"select[data-action=change-heighten-level]");levelSelect?.addEventListener("change",()=>{const newLevel=Number(levelSelect.value),existingData=this.item.getHeightenLayers().find(layer=>layer.level===overlay.level);this.item.update({[`system.heightening.levels.-=${overlay.level}`]:null,[`system.heightening.levels.${newLevel}`]:existingData?.system??{}})})}htmlQuery(html,"a[data-action=variant-create]")?.addEventListener("click",()=>{this.item.overlays.create("override")});for(const anchor of htmlQueryAll(html,"a[data-action=edit-variant]"))anchor.addEventListener("click",()=>{const overlayId=anchor.dataset.id;overlayId&&this.item.loadVariant({overlayIds:[overlayId]})?.sheet.render(!0)});for(const anchor of htmlQueryAll(html,"a[data-action=delete-variant]"))anchor.addEventListener("click",()=>{const id=anchor.dataset.id;if(id){const variant=this.item.loadVariant({overlayIds:[id]});if(!variant)throw ErrorPF2e(`Spell ${this.item.name} (${this.item.uuid}) does not have a variant with id: ${id}`);new Dialog({title:game.i18n.localize("PF2E.Item.Spell.Variants.DeleteDialogTitle"),content:`${game.i18n.format("PF2E.Item.Spell.Variants.DeleteDialogText",{variantName:variant.name})}
`,buttons:{delete:{icon:fontAwesomeIcon("fa-trash").outerHTML,label:game.i18n.localize("PF2E.DeleteShortLabel"),callback:()=>{this.item.overlays.deleteOverlay(id)}},cancel:{icon:fontAwesomeIcon("fa-times").outerHTML,label:game.i18n.localize("Cancel")}},default:"cancel"}).render(!0)}});const ritualCheckbox=htmlQuery(html,"input[data-action=toggle-ritual-data]");ritualCheckbox?.addEventListener("click",async event2=>{event2.preventDefault(),ritualCheckbox.readOnly=!0,await this.item.update({"system.ritual":this.item.system.ritual?null:{primary:{check:""},secondary:{checks:"",casters:0}}})})}async _updateObject(event2,formData){if(formData["system.area.value"]?formData["system.area.type"]||="burst":(delete formData["system.area.value"],delete formData["system.area.type"],formData["system.area"]=null),this.item.original&&this.item.appliedOverlays?.has("override")&&!this.rendered){await this.item.original.overlays.updateOverride(this.item,formData);return}super._updateObject(event2,formData)}_onDragStart(event2){const id=event2.target.closest(".variant")?.dataset.variantId??"";event2.dataTransfer.setData("text/plain",JSON.stringify({action:"sort",data:{sourceId:id}}))}async _onDrop(event2){event2.preventDefault();const transferString=event2.dataTransfer.getData("text/plain");if(!transferString)return;const{action:action2,data}=JSON.parse(transferString)??{};switch(action2){case"sort":{const sourceId=data?.sourceId??"",targetId=event2.target.closest(".variant")?.dataset.variantId??"";if(sourceId&&targetId&&sourceId!==targetId){const sourceVariant=this.item.loadVariant({overlayIds:[sourceId]}),targetVariant=this.item.loadVariant({overlayIds:[targetId]});if(sourceVariant&&targetVariant){const siblings=this.item.overlays.overrideVariants.filter(variant=>variant.id!==sourceId&&variant.id!==targetId);siblings.push(targetVariant);const sorting=SortingHelpers.performIntegerSort(sourceVariant,{target:targetVariant,siblings,sortKey:"sort",sortBefore:!0});for(const s of sorting)await this.item.overlays.updateOverride(s.target,s.update,{render:!1});this.render(!0)}}break}}}getAvailableHeightenLevels(){const heightenLayers=this.item.getHeightenLayers();return[2,3,4,5,6,7,8,9,10].filter(level=>level>this.item.baseRank&&!heightenLayers.some(layer=>layer.level===level))}#getOverlayFromElement(target){const overlayEl=htmlClosest(target,"[data-overlay-type]");if(!overlayEl)return null;const domData=overlayEl.dataset,type=String(domData.overlayType);if(!tupleHasValue(["heighten","variant"],type))return null;const id="overlayId"in domData?String(domData.overlayId):null,level="level"in domData?Number(domData.level):null,collectionPath=type==="heighten"?"system.heightening.levels":"system.variants",base=type==="heighten"?`${collectionPath}.${level}`:`${collectionPath}.${id}`,system=(()=>{if(type==="heighten"){const heightening=this.item.system.heightening;if(heightening?.type==="fixed")return heightening.levels[level]??null}return null})();return{id,level,type,base,dataPath:base,system}}#getDefaultProperty(property){const scaling=this.item.getHeightenLayers().reverse(),baseValue=(()=>{for(const entry of[...scaling,{system:foundry.utils.deepClone(this.item._source.system)}])if(objectHasKey(entry.system,property))return entry.system[property];return null})();if(baseValue)return baseValue;if(property==="area")return{value:5,type:"burst"};throw ErrorPF2e(`Failed to initialize property ${property} for overlay`)}#prepareHeighteningLevels(){return this.item.getHeightenLayers().map(layer=>{const base=`system.heightening.levels.${layer.level}`,missing=[];for(const[key,label]of Object.entries(spellOverridable))key in layer.system||missing.push({key,label});return{id:null,type:"heighten",level:layer.level,base,dataPath:base,system:layer.system,missing,heightenLevels:[layer.level,...this.getAvailableHeightenLevels()].sort(),traits:layer.system.traits?.value?createTagifyTraits(layer.system.traits.value,{record:CONFIG.PF2E.spellTraits}):null}})}}class TreasureSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"TreasureSheetPF2e")}static{__name2(this,"TreasureSheetPF2e")}async getData(options){return{...await super.getData(options),currencies:CONFIG.PF2E.currencies,stackGroups:pick(CONFIG.PF2E.stackGroups,["coins","gems"])}}_updateObject(event2,formData){return formData["system.stackGroup"]===""&&(formData["system.stackGroup"]=null),super._updateObject(event2,formData)}}class WeaponSheetPF2e extends PhysicalItemSheetPF2e{static{__name(this,"WeaponSheetPF2e")}static{__name2(this,"WeaponSheetPF2e")}async getData(options){const sheetData=await super.getData(options),weapon=this.item,runes=weapon.system.runes,propertyRuneSlots=Array.fromRange(weapon.isSpecific?runes.property.length:getPropertyRuneSlots(weapon)).map(i=>({slug:runes.property[i]??null,label:RUNE_DATA.weapon.property[runes.property[i]]?.name??null,disabled:i>0&&!runes.property[i-1]})),abpEnabled=AutomaticBonusProgression.isEnabled(this.actor),hintText=abpEnabled?"PF2E.Item.Weapon.FromABP":"PF2E.Item.Weapon.FromMaterialAndRunes",adjustedDiceHint=weapon.system.damage.dice!==weapon._source.system.damage.dice?game.i18n.format(game.i18n.localize(hintText),{property:game.i18n.localize("PF2E.Item.Weapon.Damage.DiceNumber"),value:weapon.system.damage.dice}):null,damageDieFaces=Object.fromEntries(Object.entries(CONFIG.PF2E.damageDie).map(([num,label])=>[Number(num.replace("d","")),label]).sort(([numA],[numB])=>numA-numB)),traitSet=weapon.traits,isComboWeapon=traitSet.has("combination"),weaponRanges=Array.from(WEAPON_RANGES).reduce((ranges,range2)=>({...ranges,[range2]:game.i18n.format("PF2E.WeaponRangeN",{range:range2})}),{}),rangedOnlyTraits=["combination","thrown","volley-20","volley-30","volley-50"],mandatoryRanged=setHasElement(MANDATORY_RANGED_GROUPS,weapon.group)||rangedOnlyTraits.some(trait=>traitSet.has(trait)),mandatoryMelee=sheetData.data.traits.value.some(trait=>/^thrown-\d+$/.test(trait)),otherTags=(()=>{const otherWeaponTags2=foundry.utils.deepClone(CONFIG.PF2E.otherWeaponTags);return weapon.hands!=="1"&&delete otherWeaponTags2.implement,createSheetTags(otherWeaponTags2,sheetData.data.traits.otherTags)})(),meleeUsage=sheetData.data.meleeUsage??{group:"knife",damage:{type:"piercing",die:"d4"},traits:[]},specificMagicData=weapon._source.system.specific??pick(weapon._source.system,["material","runes"]);return{...sheetData,abpEnabled,adjustedDiceHint,baseTypes:sortStringRecord(CONFIG.PF2E.baseWeaponTypes),categories:sortStringRecord(CONFIG.PF2E.weaponCategories),conditionTypes:sortStringRecord(CONFIG.PF2E.conditionTypes),damageDice:CONFIG.PF2E.damageDice,damageDie:CONFIG.PF2E.damageDie,damageDieFaces,damageTypes:sortStringRecord(CONFIG.PF2E.damageTypes),groups:sortStringRecord(CONFIG.PF2E.weaponGroups),isBomb:weapon.group==="bomb",isComboWeapon,itemBonuses:CONFIG.PF2E.itemBonuses,mandatoryMelee,mandatoryRanged,meleeGroups:sortStringRecord(CONFIG.PF2E.meleeWeaponGroups),meleeUsage,meleeUsageTraits:createSheetTags(CONFIG.PF2E.weaponTraits,meleeUsage.traits??[]),otherTags,preciousMaterials:this.getMaterialSheetData(weapon,MATERIAL_DATA.weapon),propertyRuneSlots,runeTypes:RUNE_DATA.weapon,specificMagicData,weaponMAP:CONFIG.PF2E.weaponMAP,weaponRanges,weaponReload:CONFIG.PF2E.weaponReload}}activateListeners($html){super.activateListeners($html);const html=$html[0],pdElements=htmlQueryAll(html,"[data-action=update-persistent]");for(const element of pdElements)element.addEventListener("change",async event2=>{if(!(event2.target instanceof HTMLInputElement||event2.target instanceof HTMLSelectElement))throw ErrorPF2e("Unexpected error updating persistent damage data");const diceNumber=Number(pdElements.find(e=>e.dataset.persistentField==="number")?.value)||0,dieFaces=Number(pdElements.find(e=>e.dataset.persistentField==="faces")?.value),baseDamageType=this.item.system.damage.damageType,damageType=pdElements.find(e=>e.dataset.persistentField==="type")?.value||baseDamageType;if(!(typeof diceNumber=="number"&&typeof dieFaces=="number"&&damageType))throw ErrorPF2e("Unexpected error updating persistent damage data");const maybeDiceNumber=Math.trunc(Math.abs(Number(event2.target.value)||0));if(event2.target.dataset.persistentField==="number"&&maybeDiceNumber===0)await this.item.update({"system.damage.persistent":null});else if(objectHasKey(CONFIG.PF2E.damageTypes,damageType)){const damage={number:Math.trunc(Math.abs(diceNumber))||1,faces:tupleHasValue([4,6,8,10,12],dieFaces)?dieFaces:null,type:damageType};await this.item.update({"system.damage.persistent":damage})}})}async _updateObject(event2,formData){const weapon=this.item;formData["system.bonusDamage.value"]||=0,formData["system.splashDamage.value"]||=0,formData["system.range"]||=null,"system.damage.dice"in formData&&(formData["system.damage.dice"]=Math.clamped(Number(formData["system.damage.dice"])||0,0,8)),weapon.system.meleeUsage&&!this.item.traits.has("combination")&&(formData["system.-=meleeUsage"]=null);const propertyRuneIndices=[0,1,2,3],propertyRuneUpdates=propertyRuneIndices.flatMap(i=>formData[`system.runes.property.${i}`]??[]);if(propertyRuneUpdates.length>0){formData["system.runes.property"]=compact(propertyRuneUpdates);for(const index of propertyRuneIndices)delete formData[`system.runes.property.${index}`]}return super._updateObject(event2,formData)}}class UserConfigPF2e extends UserConfig{static{__name(this,"UserConfigPF2e")}static{__name2(this,"UserConfigPF2e")}async getData(options){const data=await super.getData(options);return data.actors=data.actors.filter(a=>a.type!=="party"),data}get template(){return"systems/pf2e/templates/user/sheet.hbs"}}class SceneConfigPF2e extends SceneConfig{static{__name(this,"SceneConfigPF2e")}static{__name2(this,"SceneConfigPF2e")}get scene(){return this.document}async _renderInner(data,options){const html=(await super._renderInner(data,options))[0],[tab,panel]=await(async()=>{const hbsPath="systems/pf2e/templates/scene/sheet-partials.hbs",rbvWorldDefault=game.i18n.localize(game.pf2e.settings.rbv?"PF2E.SETTINGS.EnabledDisabled.Enabled":"PF2E.SETTINGS.EnabledDisabled.Disabled"),templates=await renderTemplate(hbsPath,{scene:this.scene,rbvWorldDefault});return htmlQueryAll(createHTMLElement("div",{innerHTML:templates}),"template")})(),tabs=htmlQuery(html,"nav.tabs"),ambientTabContent=htmlQuery(html,".tab[data-tab=ambience]");if(!tabs||!ambientTabContent)throw ErrorPF2e("Unexpected error in scene configuration");return tabs.append(...tab.content.children),ambientTabContent.after(...panel.content.children),$(html)}activateListeners($html){super.activateListeners($html);const html=$html[0];htmlQuery(html,"button[data-action=world-rbv-setting]")?.addEventListener("click",()=>{const menu=game.settings.menus.get("pf2e.automation");if(menu){const options={highlightSetting:"rulesBasedVision"};new menu.type(void 0,options).render(!0)}}),this.#activateRBVListeners(html)}#activateRBVListeners(html){if(!this.document.rulesBasedVision)return;const globalLight=html.querySelector("input[name^=globalLight]"),hasglobalThreshold=html.querySelector("input[name=hasGlobalThreshold]"),globalLightThreshold=html.querySelector("input[name=globalLightThreshold]");if(globalLight&&hasglobalThreshold&&globalLightThreshold){globalLight.disabled=!0,hasglobalThreshold.disabled=!0,globalLightThreshold.disabled=!0,globalLightThreshold.nextElementSibling?.classList.add("disabled");for(const input of[globalLight,globalLightThreshold]){const managedBy=document.createElement("span");managedBy.classList.add("managed"),managedBy.innerHTML=" ".concat(game.i18n.localize("PF2E.SETTINGS.Automation.RulesBasedVision.ManagedBy"));const rbvLink=managedBy.querySelector("rbv"),anchor=document.createElement("a");anchor.innerText=rbvLink?.innerHTML??"",anchor.setAttribute("href",""),anchor.addEventListener("click",event2=>{event2.preventDefault(),event2.stopPropagation();const menu=game.settings.menus.get("pf2e.automation");if(!menu)throw ErrorPF2e("Automation Settings application not found");new menu.type().render(!0)}),rbvLink?.replaceWith(anchor),input.closest(".form-group")?.querySelector("p.notes")?.append(managedBy)}if(this.document.darknessSyncedToTime){const darknessInput=html.querySelector("input[name=darkness]");if(darknessInput){darknessInput.disabled=!0,darknessInput.nextElementSibling?.classList.add("disabled");const managedBy=WorldClock.createSyncedMessage();darknessInput.closest(".form-group")?.querySelector("p.notes")?.append(managedBy)}}}}async _updateObject(event2,formData){const rbvSetting=formData["flags.pf2e.rulesBasedVision"];formData["flags.pf2e.rulesBasedVision"]=rbvSetting==="true"?!0:rbvSetting==="false"?!1:null;const hearingRange=formData["flags.pf2e.hearingRange"];return formData["flags.pf2e.hearingRange"]=typeof hearingRange=="number"?Math.ceil(Math.clamped(hearingRange||5,5,3e3)/5)*5:null,super._updateObject(event2,formData)}}function registerSheets(){const sheetLabel=game.i18n.localize("PF2E.SheetLabel");Scenes.registerSheet("pf2e",SceneConfigPF2e,{makeDefault:!0}),DocumentSheetConfig.registerSheet(TokenDocumentPF2e,"pf2e",TokenConfigPF2e,{makeDefault:!0}),Actors.unregisterSheet("core",ActorSheet);const localizeType=__name2(type=>{const docType=type in CONFIG.PF2E.Actor.documentClasses?"Actor":"Item";return game.i18n.localize(`TYPES.${docType}.${type}`)},"localizeType");Actors.registerSheet("pf2e",CharacterSheetPF2e,{types:["character"],label:game.i18n.format(sheetLabel,{type:localizeType("character")}),makeDefault:!0}),Actors.registerSheet("pf2e",NPCSheetPF2e,{types:["npc"],label:game.i18n.format(sheetLabel,{type:localizeType("npc")}),makeDefault:!0}),Actors.registerSheet("pf2e",SimpleNPCSheet,{types:["npc"],label:"PF2E.Actor.NPC.SimpleSheet",canBeDefault:!1}),Actors.registerSheet("pf2e",HazardSheetPF2e,{types:["hazard"],label:game.i18n.format(sheetLabel,{type:localizeType("hazard")})}),Actors.registerSheet("pf2e",LootSheetPF2e,{types:["loot"],label:game.i18n.format(sheetLabel,{type:localizeType("loot")}),makeDefault:!0}),Actors.registerSheet("pf2e",FamiliarSheetPF2e,{types:["familiar"],label:game.i18n.format(sheetLabel,{type:localizeType("familiar")}),makeDefault:!0}),Actors.registerSheet("pf2e",VehicleSheetPF2e,{types:["vehicle"],label:game.i18n.format(sheetLabel,{type:localizeType("vehicle")}),makeDefault:!0}),Actors.registerSheet("pf2e",PartySheetPF2e,{types:["party"],label:game.i18n.format(sheetLabel,{type:localizeType("party")}),makeDefault:!0}),Actors.registerSheet("pf2e",ArmySheetPF2e,{types:["army"],label:game.i18n.format(sheetLabel,{type:localizeType("army")}),makeDefault:!0}),Items.unregisterSheet("core",ItemSheet);const itemTypes=["lore","spellcastingEntry"];for(const itemType of itemTypes)Items.registerSheet("pf2e",ItemSheetPF2e,{types:[itemType],label:game.i18n.format(sheetLabel,{type:localizeType(itemType)}),makeDefault:!0});const sheetEntries=[["action",AbilitySheetPF2e],["affliction",AfflictionSheetPF2e],["ancestry",AncestrySheetPF2e],["armor",ArmorSheetPF2e],["background",BackgroundSheetPF2e],["backpack",ContainerSheetPF2e],["book",BookSheetPF2e],["campaignFeature",CampaignFeatureSheetPF2e],["class",ClassSheetPF2e],["condition",ConditionSheetPF2e],["consumable",ConsumableSheetPF2e],["deity",DeitySheetPF2e],["effect",EffectSheetPF2e],["equipment",EquipmentSheetPF2e],["feat",FeatSheetPF2e],["heritage",HeritageSheetPF2e],["kit",KitSheetPF2e],["lore",LoreSheetPF2e],["melee",MeleeSheetPF2e],["shield",ShieldSheetPF2e],["spell",SpellSheetPF2e],["treasure",TreasureSheetPF2e],["weapon",WeaponSheetPF2e]];for(const[type,Sheet]of sheetEntries)Items.registerSheet("pf2e",Sheet,{types:[type],label:game.i18n.format(sheetLabel,{type:localizeType(type)}),makeDefault:!0});for(const itemType of PHYSICAL_ITEM_TYPES)sheetEntries.some(([type,_sheet])=>itemType===type)||Items.registerSheet("pf2e",PhysicalItemSheetPF2e,{types:[itemType],label:game.i18n.format(sheetLabel,{type:localizeType(itemType)}),makeDefault:!0});Journal.unregisterSheet("core",JournalSheet),Journal.registerSheet("pf2e",JournalSheetPF2e,{label:()=>game.i18n.format("SHEETS.DefaultDocumentSheet",{document:game.i18n.localize("DOCUMENT.JournalEntry")}),makeDefault:!0}),DocumentSheetConfig.unregisterSheet(JournalEntryPage,"core",JournalTextTinyMCESheet),DocumentSheetConfig.registerSheet(JournalEntryPage,"pf2e",JournalTextTinyMCESheetPF2e,{types:["text"],label:game.i18n.localize("EDITOR.TinyMCE")}),Users.unregisterSheet("core",UserConfig),Users.registerSheet("pf2e",UserConfigPF2e,{makeDefault:!0,label:()=>game.i18n.format("SHEETS.DefaultDocumentSheet",{document:game.i18n.localize("DOCUMENT.User")})})}__name(registerSheets,"registerSheets"),__name2(registerSheets,"registerSheets");const Setup={listen:()=>{Hooks.once("setup",()=>{registerSheets(),game.settings.settings.get("core.chatBubblesPan").default=!1,game.settings.settings.get("core.notesDisplayToggle").default=!0;const defaultTokenSettingsDefaults=game.settings.settings.get("core.defaultToken").default;defaultTokenSettingsDefaults.displayName=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER,defaultTokenSettingsDefaults.displayBars=CONST.TOKEN_DISPLAY_MODES.OWNER_HOVER})}},TargetToken={listen:()=>{Hooks.on("targetToken",(user,token)=>{const tokenDocument=token.document;ui.combat.refreshTargetDisplay(tokenDocument);const actors=getSelectedOrOwnActors();if(actors.length===1&&tokenDocument.object){const actorToken=actors[0].getActiveTokens(!1,!1).shift();canvas.tokens.highlightObjects&&user===game.user&&actorToken?.flankingHighlight.draw()}})}},UpdateWorldTime={listen:()=>{Hooks.on("updateWorldTime",async(_total,diff)=>{game.combat?.started||game.pf2e.effectTracker.refresh({resetItemData:!0});const worldClock=game.pf2e.worldClock;setTimeout(()=>worldClock.render(!1),1),await worldClock.animateDarkness(diff)})}},HooksPF2e={listen(){const listeners=[Load,BabeleReady,CanvasInit,CanvasReady,CloseCombatTrackerConfig,CloseWorldClockSettings,DiceSoNiceReady,DropCanvasData,GetSceneControlButtons,I18nInit,Init,LightingRefresh,Ready,RenderChatPopout,RenderCombatTrackerConfig,RenderDialog,RenderJournalPageSheet,RenderJournalTextPageSheet,RenderSettings,RenderTokenHUD,Setup,TargetToken,UpdateWorldTime];for(const Listener of listeners)Listener.listen()}};HooksPF2e.listen();
diff --git a/Data/systems/pf2e/styles/pf2e.css b/Data/systems/pf2e/styles/pf2e.css
index 6d989011..b4095c62 100644
--- a/Data/systems/pf2e/styles/pf2e.css
+++ b/Data/systems/pf2e/styles/pf2e.css
@@ -578,8 +578,8 @@
:root {
/* Global */
--color-pf-primary: #5e0000;
- --color-pf-primary-light: #910000;
- --color-pf-primary-dark: #2b0000;
+ --color-pf-primary-light: #780000;
+ --color-pf-primary-dark: #450000;
--color-pf-secondary: #171f69;
--color-pf-secondary-light: #202b93;
--color-pf-secondary-dark: #0e133f;
@@ -591,16 +591,15 @@
--bg: #f8f4f1;
--bg-dark: #e7d9cf;
--sub: #605856;
- --color-disabled: #ababab;
+ --color-disabled: var(--color-text-dark-4);
--inline-link-bg: #ddd;
--inline-repost-bg: #eaeaea;
--visibility-gm-bg: #e8e8ef;
--visibility-owner-bg: #ddebe1;
--blind-roll: #f5eaf5;
/* Lighter / Darker */
- --light: #910000;
- --primary-dark: #2b0000;
- --primary-darker: #120000;
+ --primary-dark: #450000;
+ --primary-darker: #2b0000;
--tertiary-dark: #dfc578;
--tertiary-light: #f3e9ca;
/* Text */
@@ -619,7 +618,6 @@
--sidebar-label: var(--tertiary-dark);
--sidebar-title: var(--tertiary);
/** Traits */
- --color-bg-alignment: #576293;
--color-bg-size: #3a7b59;
--color-bg-trait: #5e0000;
--color-border-trait: #d8c384;
@@ -725,7 +723,6 @@
:root .damage.color.cold {
background-color: var(--color-bg-cold);
border-color: var(--color-border-cold);
- box-shadow: var(--color-border-cold);
color: var(--color-text-cold);
}
:root .damage.color.cold i[class^=fa-] {
@@ -750,7 +747,6 @@
:root .damage.color.fire {
background-color: var(--color-bg-fire);
border-color: var(--color-border-fire);
- box-shadow: var(--color-border-fire);
color: var(--color-text-fire);
}
:root .damage.color.fire i[class^=fa-] {
@@ -824,7 +820,7 @@
:root .damage.color.void {
background-color: var(--color-bg-void);
border-color: var(--color-border-void);
- color: var(--color-border-void);
+ color: var(--color-text-void);
}
:root .damage.color.void i[class^=fa-] {
color: var(--color-border-void);
@@ -1042,15 +1038,15 @@ li.list-row.hover-container {
.recall-knowledge-table th:first-child {
text-align: right;
}
-button:hover::not(:disabled) {
+button:not(:disabled):hover {
box-shadow: 0 0 3px #c00;
}
+button:not(:disabled):active {
+ box-shadow: 0 0 5px red;
+}
button:disabled {
color: #666;
}
-button:active {
- box-shadow: 0 0 5px red;
-}
.app.tag-selector {
max-height: 700px;
}
@@ -1058,60 +1054,58 @@ button:active {
/* Item Card Structure */
/* ----------------------------------------- */
.pf2e.chat-card {
- font-style: normal;
+ font-family: var(--sans-serif);
+}
+.pf2e.chat-card h2,
+.pf2e.chat-card h3,
+.pf2e.chat-card h4 {
+ font-weight: 600;
}
.pf2e.chat-card .card-header {
padding: 2px 0;
border-top: 2px groove #fff;
- border-bottom: 2px groove #fff;
align-items: center;
- min-height: 36px;
+ min-height: 2.25rem;
}
.pf2e.chat-card .card-header img {
- flex: 0 0 36px;
- margin-right: 5px;
- height: 36px;
- width: 36px;
+ flex: 0 0 2.25rem;
+ margin-right: 0.25rem;
+ height: 2.25rem;
+ width: 2.25rem;
}
.pf2e.chat-card .card-header h3 {
border-bottom: none;
flex: 1;
margin: 0;
+ font-size: var(--font-size-16);
}
.pf2e.chat-card .card-header h4 {
flex: 0;
- margin: 0 5px 0 0;
+ margin: 0 0.5em 0 0;
white-space: nowrap;
}
+.pf2e.chat-card .card-header h4.level, .pf2e.chat-card .card-header h4.rank {
+ margin-left: auto;
+}
.pf2e.chat-card .tags {
margin: 3px 0 0;
}
.pf2e.chat-card .card-content {
- margin: 4px 0;
+ margin: 0.25rem 0;
}
.pf2e.chat-card .card-content p {
- margin: 4px 0;
+ margin: 0.25rem 0;
min-height: unset;
}
.pf2e.chat-card .card-buttons {
display: flex;
flex-basis: 100%;
flex-direction: column;
- margin: 4px 0;
+ margin: 0.25rem 0;
}
.pf2e.chat-card .card-buttons button {
margin: 2px 0;
}
-.pf2e.chat-card .card-buttons button.with-image {
- display: flex;
- align-items: center;
- justify-content: center;
-}
-.pf2e.chat-card .card-buttons button.with-image img {
- border: none;
- height: 2em;
- margin-right: 0.5em;
-}
.pf2e.chat-card .card-buttons button span {
border: none;
}
@@ -1149,22 +1143,17 @@ button:active {
}
.pf2e.chat-card .card-footer span {
border-right: 2px groove #fff;
- padding: 0 5px 0 0;
+ padding: 0 0.25rem 0 0;
font-size: var(--font-size-12);
}
.pf2e.chat-card .card-footer span:last-child {
border-right: none;
padding-right: 0;
}
-.pf2e.chat-card .card-buttons-multiattack {
- display: grid;
- grid-template-columns: auto 40px 40px;
- grid-column-gap: 4px;
-}
.pf2e.chat-card .card-buttons-two-column {
display: grid;
grid-template-columns: 1fr 1fr;
- grid-column-gap: 4px;
+ grid-column-gap: 0.25rem;
}
/* This is the core CSS of Tooltipster */
/* GENERAL STRUCTURE RULES (do not edit this section) */
@@ -1570,29 +1559,15 @@ corresponds to the arrow we want to display */
/* ----------------------------------------- */
/* Layout */
/* ----------------------------------------- */
+[hidden] {
+ display: none !important;
+}
/** A vertical rule in a flexbox */
hr.vr {
border: 1px inset;
height: 1.25em;
margin: 1px 2px;
}
-/* ----------------------------------------- */
-/* Typography */
-/* ----------------------------------------- */
-.pf2e,
-.app.sheet.actor {
- font-family: var(--sans-serif);
-}
-.pf2e h1,
-.pf2e h2,
-.pf2e h3,
-.pf2e h4,
-.app.sheet.actor h1,
-.app.sheet.actor h2,
-.app.sheet.actor h3,
-.app.sheet.actor h4 {
- font-weight: 600;
-}
.pf2e.sheet form span.pf2-icon,
.pf2e.sheet form span[data-pf2-action],
.pf2e.sheet form span[data-pf2-action] *,
@@ -1625,42 +1600,50 @@ p.compact-text {
/* ----------------------------------------- */
/* Styled table */
/* ----------------------------------------- */
+table.pf2e,
table.pf2-table {
- border: solid 1px #000000;
border-collapse: collapse;
+ color: var(--text-dark);
font-size: var(--font-size-13);
- color: #191813;
user-select: text;
}
+table.pf2e thead,
+table.pf2e tbody,
+table.pf2e th,
+table.pf2e td,
table.pf2-table thead,
table.pf2-table tbody,
-table.pf2-table tr,
table.pf2-table th,
table.pf2-table td {
box-sizing: border-box;
user-select: text;
+ word-break: auto-phrase;
}
+table.pf2e tr:nth-child(odd),
table.pf2-table tr:nth-child(odd) {
- background-color: #eee5c8;
+ background-color: var(--tertiary-light);
}
+table.pf2e tr:nth-child(even),
table.pf2-table tr:nth-child(even) {
- background-color: #f6f1e1;
+ background-color: var(--text-light);
+}
+table.pf2e th,
+table.pf2e td,
+table.pf2-table th,
+table.pf2-table td {
+ border: solid 1px var(--color-border-light-tertiary);
+ text-align: center;
}
+table.pf2e th,
table.pf2-table th {
+ background-color: var(--color-pf-primary-dark);
color: var(--text-light);
font-weight: bold;
- background-color: #522e2c;
+ padding: 0.5rem 0.25rem;
}
-table.pf2-table th,
+table.pf2e td,
table.pf2-table td {
- border: solid 1px #808080;
- padding: 6px 15px;
- text-align: center;
-}
-a.foundry-href {
- color: var(--primary);
- font-weight: 500;
- text-decoration: underline;
+ padding: 0.25rem;
}
a.content-link {
line-height: 1.6em;
@@ -1968,9 +1951,6 @@ a[href]:hover {
--space-2xl: 2em;
--radius: 3px;
}
-#tinymce p {
- min-height: unset;
-}
#tinymce :is(h1, h2, h3, h4, h5, h6):not(:first-child) {
margin-top: 1em;
}
@@ -2171,12 +2151,18 @@ button:disabled {
text-align: center;
}
.actors-sidebar li.folder-like > header h3 {
- display: block;
+ align-items: baseline;
+ display: flex;
flex: 1;
font-size: var(--font-size-16);
+ gap: 0.125rem;
margin: 0;
padding-left: 1px;
}
+.actors-sidebar li.folder-like > header h3 span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
.actors-sidebar li.folder-like > header a.create-button {
flex: 0 0 20px;
margin-left: 3px;
@@ -2464,6 +2450,20 @@ button:disabled {
height: 32px;
width: 32px;
}
+.chat-message > .message-content .dice-total button.set-as-initiative {
+ align-items: center;
+ display: flex;
+ font-size: var(--font-size-10);
+ height: 2.2em;
+ justify-content: center;
+ position: absolute;
+ right: 0;
+ top: 1px;
+ width: 2.2em;
+}
+.chat-message > .message-content .dice-total button.set-as-initiative > i {
+ margin-right: 0;
+}
.chat-message .message-content .damage-roll:not(:first-child) {
margin-top: 1em;
}
@@ -2478,7 +2478,6 @@ button:disabled {
padding: 0 0.25em;
}
.chat-message .message-content .damage-roll .dice-result .dice-total {
- flex-direction: column;
font-weight: normal;
}
.chat-message .message-content .damage-roll .dice-result .dice-total .total {
@@ -2496,13 +2495,14 @@ button:disabled {
display: flex;
flex-wrap: wrap;
font-size: var(--font-size-12);
+ gap: 1px;
justify-content: center;
- line-height: var(--font-size-12);
- margin-bottom: 0.2em;
+ line-height: normal;
+ margin-bottom: 1px;
vertical-align: top;
}
.chat-message .message-content .damage-roll .dice-result .dice-total .instances .instance {
- padding: 0.15em 0.25em;
+ padding: 1px 0.25em 0;
}
.chat-message .message-content .damage-roll .dice-result .dice-tooltip {
display: flex;
@@ -2546,25 +2546,6 @@ button:disabled {
padding: 1px 2px;
line-height: 0;
}
-.chat-message .message-content .damage-roll .dice-result .dice-tooltip .damage-type {
- margin-bottom: 3px;
-}
-.chat-message .message-content .damage-roll .dice-result .dice-tooltip .damage-type h3 {
- text-transform: capitalize;
- padding-left: 3px;
- padding-right: 1px;
-}
-.chat-message .message-content .damage-roll .dice-result .dice-tooltip .damage-type i.fa {
- flex: none;
- margin: 2px;
-}
-.chat-message .message-content .damage-roll .dice-result .dice-tooltip .damage-type .dice {
- margin-left: 2px;
- margin-right: 2px;
-}
-.chat-message .message-content .damage-roll .dice-result .dice-tooltip .dice .part-header .part-flavor {
- text-transform: capitalize;
-}
.chat-message .message-content .damage-application {
display: flex;
justify-content: center;
@@ -2876,9 +2857,6 @@ section.compendium-sidebar ol.directory-list ol.document-matches li.match .detai
--space-2xl: 2em;
--radius: 3px;
}
-.crb-hover .tooltipster-box .tooltipster-content .item-summary p {
- min-height: unset;
-}
.crb-hover .tooltipster-box .tooltipster-content .item-summary :is(h1, h2, h3, h4, h5, h6):not(:first-child) {
margin-top: 1em;
}
@@ -3270,7 +3248,7 @@ section.compendium-sidebar ol.directory-list ol.document-matches li.match .detai
.crb-hover .tooltipster-box .tooltipster-content .hover-content.carry-hover-content {
white-space: nowrap;
}
-.crb-hover .tooltipster-box .tooltipster-content .hover-content.carry-hover-content a.item-control i.fas {
+.crb-hover .tooltipster-box .tooltipster-content .hover-content.carry-hover-content a.item-control i.fa-solid {
min-width: 1.25em;
}
.icon.anger::before {
@@ -3617,6 +3595,9 @@ section.compendium-sidebar ol.directory-list ol.document-matches li.match .detai
/* ----------------------------------------- */
/* Tag Selector */
/* ----------------------------------------- */
+.app.tag-selector a.document-id-link {
+ visibility: hidden;
+}
.app.tag-selector form {
height: 100%;
}
@@ -4158,43 +4139,70 @@ body > .choices__list--dropdown {
background-color: white;
position: fixed;
}
-.actor.sheet .image-container {
+.actor.sheet .window-content {
+ font-family: var(--sans-serif);
+}
+.actor.sheet .window-content input,
+.actor.sheet .window-content label,
+.actor.sheet .window-content select {
+ --form-field-height: 1.5rem;
+}
+.actor.sheet .window-content input[type=checkbox] {
+ height: var(--font-size-20);
+}
+.actor.sheet .window-content select {
+ height: var(--form-field-height);
+}
+.actor.sheet .window-content h3 {
+ border-bottom: none;
+}
+.actor.sheet .window-content button > i {
+ margin-right: 0;
+}
+.actor.sheet .window-content h1,
+.actor.sheet .window-content h2,
+.actor.sheet .window-content h3,
+.actor.sheet .window-content h4 {
+ font-weight: 600;
+}
+.actor.sheet .window-content a.disabled {
+ cursor: default;
+}
+.actor.sheet .window-content a.disabled:hover {
+ text-shadow: none;
+}
+.actor.sheet .window-content i.fa-info-circle {
+ cursor: help;
+}
+.actor.sheet .window-content .image-container {
position: relative;
}
-.actor.sheet .image-container .hover-icon {
+.actor.sheet .window-content .image-container .hover-icon {
display: none;
font-size: var(--font-size-16);
}
-.actor.sheet .image-container:hover .hover-icon {
+.actor.sheet .window-content .image-container:hover .hover-icon {
display: block;
}
-.actor.sheet .image-container [data-action=show-image] {
+.actor.sheet .window-content .image-container [data-action=show-image] {
bottom: 0.25rem;
position: absolute;
right: 0.025rem;
}
-.actor.sheet h3 {
- border-bottom: none;
-}
-.actor.sheet button > i {
- margin-right: 0;
-}
-.actor.sheet .item-summary {
+.actor.sheet .window-content .item-summary {
--space-s: 0.25em;
--space-m: 0.5em;
--space-l: 1em;
--space-xl: 1.5em;
--space-2xl: 2em;
--radius: 3px;
+ line-height: normal;
overflow: hidden;
}
-.actor.sheet .item-summary p {
- min-height: unset;
-}
-.actor.sheet .item-summary :is(h1, h2, h3, h4, h5, h6):not(:first-child) {
+.actor.sheet .window-content .item-summary :is(h1, h2, h3, h4, h5, h6):not(:first-child) {
margin-top: 1em;
}
-.actor.sheet .item-summary .inline-header {
+.actor.sheet .window-content .item-summary .inline-header {
display: flex;
align-items: center;
gap: var(--space-l);
@@ -4206,7 +4214,7 @@ body > .choices__list--dropdown {
font-weight: 400;
border: none;
}
-.actor.sheet .item-summary .inline-header strong {
+.actor.sheet .window-content .item-summary .inline-header strong {
display: inline-flex;
padding: 0 var(--space-m);
background-color: var(--primary);
@@ -4215,10 +4223,10 @@ body > .choices__list--dropdown {
box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2);
font-weight: 400;
}
-.actor.sheet .item-summary .inline-header + p {
+.actor.sheet .window-content .item-summary .inline-header + p {
margin-top: var(--space-s);
}
-.actor.sheet .item-summary .info {
+.actor.sheet .window-content .item-summary .info {
background-color: var(--secondary);
padding: var(--space-m);
color: var(--text-light);
@@ -4229,16 +4237,16 @@ body > .choices__list--dropdown {
font-family: var(--sans-serif);
padding-bottom: var(--space-m);
}
-.actor.sheet .item-summary .info > * + * {
+.actor.sheet .window-content .item-summary .info > * + * {
margin-top: var(--space-m);
}
-.actor.sheet .item-summary .info + * {
+.actor.sheet .window-content .item-summary .info + * {
margin-top: var(--space-xl);
}
-.actor.sheet .item-summary .info + .actor.sheet .item-summary .info {
+.actor.sheet .window-content .item-summary .info + .actor.sheet .window-content .item-summary .info {
margin-top: var(--space-s);
}
-.actor.sheet .item-summary .info h4 {
+.actor.sheet .window-content .item-summary .info h4 {
font-size: 0.9em;
font-weight: 400;
line-height: 1.2;
@@ -4251,27 +4259,27 @@ body > .choices__list--dropdown {
justify-content: space-between;
color: var(--text-light);
}
-.actor.sheet .item-summary .info h4::after {
+.actor.sheet .window-content .item-summary .info h4::after {
font-family: "Font Awesome 6";
content: "\f05a";
font-weight: 900;
margin-right: var(--space-s);
}
-.actor.sheet .item-summary .info p {
+.actor.sheet .window-content .item-summary .info p {
font-size: 0.8em;
margin: 0;
padding: 0 var(--space-l);
}
-.actor.sheet .item-summary .info p:first-of-type {
+.actor.sheet .window-content .item-summary .info p:first-of-type {
padding-top: var(--space-m);
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
-.actor.sheet .item-summary .traits {
+.actor.sheet .window-content .item-summary .traits {
display: flex;
flex-wrap: wrap;
padding: 0;
}
-.actor.sheet .item-summary .traits p {
+.actor.sheet .window-content .item-summary .traits p {
display: inline-flex;
padding: 0.16rem 0.25rem;
margin: 0;
@@ -4281,34 +4289,34 @@ body > .choices__list--dropdown {
font: 500 var(--font-size-10) var(--sans-serif);
text-transform: uppercase;
}
-.actor.sheet .item-summary .statblock {
+.actor.sheet .window-content .item-summary .statblock {
font-family: var(--sans-serif-condensed);
color: var(--text-dark);
line-height: 1.2;
margin-bottom: var(--space-m);
}
-.actor.sheet .item-summary .statblock > * + * {
+.actor.sheet .window-content .item-summary .statblock > * + * {
margin-top: var(--space-s);
margin-bottom: 0;
}
-.actor.sheet .item-summary .statblock p {
+.actor.sheet .window-content .item-summary .statblock p {
--indent: var(--space-l);
margin-left: var(--indent);
position: relative;
}
-.actor.sheet .item-summary .statblock p strong:first-of-type {
+.actor.sheet .window-content .item-summary .statblock p strong:first-of-type {
margin-left: calc(var(--indent) * -1);
}
-.actor.sheet .item-summary .statblock p .trait:first-of-type {
+.actor.sheet .window-content .item-summary .statblock p .trait:first-of-type {
margin-left: calc(var(--indent) * -1 - 2px);
}
-.actor.sheet .item-summary .statblock span.pf2-icon {
+.actor.sheet .window-content .item-summary .statblock span.pf2-icon {
line-height: 1;
}
-.actor.sheet .item-summary .statblock h1,
-.actor.sheet .item-summary .statblock h2,
-.actor.sheet .item-summary .statblock h3,
-.actor.sheet .item-summary .statblock h4 {
+.actor.sheet .window-content .item-summary .statblock h1,
+.actor.sheet .window-content .item-summary .statblock h2,
+.actor.sheet .window-content .item-summary .statblock h3,
+.actor.sheet .window-content .item-summary .statblock h4 {
display: flex;
align-items: baseline;
justify-content: space-between;
@@ -4318,21 +4326,21 @@ body > .choices__list--dropdown {
font-family: var(--sans-serif-condensed);
font-weight: 700;
}
-.actor.sheet .item-summary .statblock hr {
+.actor.sheet .window-content .item-summary .statblock hr {
border: none;
border-bottom: 1px solid var(--color-border-dark);
}
-.actor.sheet .item-summary .message {
+.actor.sheet .window-content .item-summary .message {
font-family: var(--journal-cursive);
font-size: 2em;
line-height: 1.2;
}
-.actor.sheet .item-summary span[data-visibility=all] {
+.actor.sheet .window-content .item-summary span[data-visibility=all] {
display: inline-block;
line-height: 1em;
padding: 2px 1px 1px;
}
-.actor.sheet .item-summary .item-buttons button {
+.actor.sheet .window-content .item-summary .item-buttons button:not(:disabled) {
background-color: var(--primary);
border: none;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5);
@@ -4347,27 +4355,22 @@ body > .choices__list--dropdown {
margin: 8px 0 0 0;
padding: 0 8px;
}
-.actor.sheet .item-summary .item-buttons button:hover {
+.actor.sheet .window-content .item-summary .item-buttons button:not(:disabled):hover {
box-shadow: none;
text-shadow: 0 0 2px white;
}
-.actor.sheet .expandable:not(.expanded) .item-summary {
- display: none;
-}
-.actor.sheet .inventory {
+.actor.sheet .window-content .inventory {
--border-color: var(--alt);
}
-.actor.sheet .inventory ol:not(.currency) {
- margin: 0;
- padding: 0;
- list-style: none;
+.actor.sheet .window-content .inventory .inventory-list,
+.actor.sheet .window-content .inventory ul.items {
display: flex;
flex-direction: column;
+ position: relative;
+ width: 100%;
}
-.actor.sheet .inventory .notify {
- animation: glow 0.75s infinite alternate;
-}
-.actor.sheet .inventory .item-name {
+.actor.sheet .window-content .inventory .inventory-list .item-name,
+.actor.sheet .window-content .inventory ul.items .item-name {
align-items: center;
display: flex;
flex: 2;
@@ -4375,108 +4378,42 @@ body > .choices__list--dropdown {
gap: 0.25rem;
padding-right: 0.25rem;
}
-.actor.sheet .inventory .item-name h3,
-.actor.sheet .inventory .item-name h4 {
- cursor: pointer;
- font-weight: 500;
- line-height: var(--font-size-12);
- margin: auto auto auto 0;
- padding: 2px;
- word-break: break-word;
-}
-.actor.sheet .inventory .item-name h3:hover,
-.actor.sheet .inventory .item-name h4:hover {
- color: var(--primary);
-}
-.actor.sheet .inventory .item-name h3 i.fa-info-circle,
-.actor.sheet .inventory .item-name h4 i.fa-info-circle {
- color: var(--text-dark);
-}
-.actor.sheet .inventory .item-name h3 i.fa-info-circle:hover,
-.actor.sheet .inventory .item-name h4 i.fa-info-circle:hover {
- color: var(--text-dark);
-}
-.actor.sheet .inventory .item-name h4:not(:hover).rarity-uncommon {
- border-color: var(--color-rarity-uncommon);
- color: var(--color-rarity-uncommon);
-}
-.actor.sheet .inventory .item-name h4:not(:hover).rarity-rare {
- border-color: var(--color-rarity-rare);
- color: var(--color-rarity-rare);
-}
-.actor.sheet .inventory .item-name h4:not(:hover).rarity-unique {
- border-color: var(--color-rarity-unique);
- color: var(--color-rarity-unique);
-}
-.actor.sheet .inventory .item-name .size {
- font-size: 0.8em;
- color: var(--alt);
- margin: 0;
-}
-.actor.sheet .inventory .item-name .item-charges {
- color: var(--sub);
-}
-.actor.sheet .inventory .inventory-list,
-.actor.sheet .inventory .inventory-items {
- flex-direction: column;
- list-style-type: none;
- position: relative;
- width: 100%;
-}
-.actor.sheet .inventory .inventory-list > li:nth-of-type(even),
-.actor.sheet .inventory .inventory-items > li:nth-of-type(even) {
- background-color: rgba(120, 100, 82, 0.1);
-}
-.actor.sheet .inventory .inventory-list .list-row:last-child .item-summary,
-.actor.sheet .inventory .inventory-items .list-row:last-child .item-summary {
- border-bottom: none;
-}
-.actor.sheet .inventory .inventory-list .temporary-item,
-.actor.sheet .inventory .inventory-items .temporary-item {
- background-color: rgba(0, 5, 255, 0.1137254902);
-}
-.actor.sheet .inventory .inventory-list {
- overflow: hidden scroll;
- display: flex;
- height: calc(100% - 60px);
- padding-right: 0.15rem;
-}
-.actor.sheet .inventory .quantity,
-.actor.sheet .inventory .bulk,
-.actor.sheet .inventory .item-controls,
-.actor.sheet .inventory .sell-value {
+.actor.sheet .window-content .inventory .inventory-list .quantity,
+.actor.sheet .window-content .inventory .inventory-list .bulk,
+.actor.sheet .window-content .inventory .inventory-list .item-controls,
+.actor.sheet .window-content .inventory .inventory-list .sell-value,
+.actor.sheet .window-content .inventory ul.items .quantity,
+.actor.sheet .window-content .inventory ul.items .bulk,
+.actor.sheet .window-content .inventory ul.items .item-controls,
+.actor.sheet .window-content .inventory ul.items .sell-value {
display: flex;
justify-content: center;
align-items: center;
flex: 0 0 68px;
}
-.actor.sheet .inventory .sell-value {
+.actor.sheet .window-content .inventory .inventory-list .sell-value,
+.actor.sheet .window-content .inventory ul.items .sell-value {
justify-content: end;
padding-right: 3px;
}
-.actor.sheet .inventory .quantity {
- justify-content: space-around;
-}
-.actor.sheet .inventory .quantity .decrease,
-.actor.sheet .inventory .quantity .increase {
- display: flex;
- justify-content: center;
- align-items: center;
- font-family: var(--sans-serif-monospace);
- height: 100%;
- text-align: center;
- width: 18px;
-}
-.actor.sheet .inventory .bulk {
+.actor.sheet .window-content .inventory .inventory-list .bulk,
+.actor.sheet .window-content .inventory ul.items .bulk {
flex: 0 0 36px;
}
-.actor.sheet .inventory .item-controls {
+.actor.sheet .window-content .inventory .inventory-list .item-controls,
+.actor.sheet .window-content .inventory ul.items .item-controls {
flex: 0 0 90px;
font-size: var(--font-size-12);
gap: 1px;
justify-content: end;
}
-.actor.sheet .inventory .inventory-header {
+.actor.sheet .window-content .inventory .inventory-list {
+ overflow: hidden scroll;
+ height: calc(100% - 60px);
+ padding-right: 0.15rem;
+}
+.actor.sheet .window-content .inventory .inventory-list > header,
+.actor.sheet .window-content .inventory .total-bulk {
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.3), inset 0 0 0 2px rgba(255, 255, 255, 0.2);
align-items: center;
background-color: var(--alt);
@@ -4493,80 +4430,175 @@ body > .choices__list--dropdown {
text-transform: uppercase;
width: 100%;
}
-.actor.sheet .inventory .inventory-header:first-child {
+.actor.sheet .window-content .inventory .inventory-list > header:first-child,
+.actor.sheet .window-content .inventory .total-bulk:first-child {
margin-top: 0;
}
-.actor.sheet .inventory .inventory-header h3 {
+.actor.sheet .window-content .inventory .inventory-list > header h3,
+.actor.sheet .window-content .inventory .total-bulk h3 {
font-size: var(--font-size-14);
margin: 2px 0;
text-shadow: 0 0 2px rgba(0, 0, 0, 0.75);
text-transform: capitalize;
}
-.actor.sheet .inventory .inventory-header h3:hover {
+.actor.sheet .window-content .inventory .inventory-list > header h3:hover,
+.actor.sheet .window-content .inventory .total-bulk h3:hover {
color: var(--color-text-light-0);
}
-.actor.sheet .inventory .inventory-header .item-name {
+.actor.sheet .window-content .inventory .inventory-list > header .item-name,
+.actor.sheet .window-content .inventory .total-bulk .item-name {
padding-left: 4px;
}
-.actor.sheet .inventory .inventory-header .item-invested-total {
+.actor.sheet .window-content .inventory .inventory-list > header .item-invested-total,
+.actor.sheet .window-content .inventory .total-bulk .item-invested-total {
flex: none;
margin-right: 1em;
}
-.actor.sheet .inventory .inventory-header .item-controls {
+.actor.sheet .window-content .inventory .inventory-list > header .item-controls,
+.actor.sheet .window-content .inventory .total-bulk .item-controls {
gap: 0.25rem;
}
-.actor.sheet .inventory .inventory-header .overinvested {
+.actor.sheet .window-content .inventory .inventory-list > header .overinvested,
+.actor.sheet .window-content .inventory .total-bulk .overinvested {
color: orange;
text-shadow: 1px 1px 0px black;
}
-.actor.sheet .inventory .inventory-items {
- border: 1px solid var(--border-color);
+.actor.sheet .window-content .inventory ul.items {
+ margin: 0;
+ padding: 0;
border-top: none;
+ border: 1px solid var(--border-color);
+ display: flex;
+ flex-direction: column;
+ list-style: none;
+}
+.actor.sheet .window-content .inventory ul.items > li {
+ width: 100%;
+}
+.actor.sheet .window-content .inventory ul.items > li:nth-of-type(even) {
+ background-color: rgba(120, 100, 82, 0.1);
}
-.actor.sheet .inventory .item {
+.actor.sheet .window-content .inventory ul.items > li:last-child .item-summary {
+ border-bottom: none;
+}
+.actor.sheet .window-content .inventory ul.items > li.temporary-item {
+ background-color: rgba(0, 5, 255, 0.1137254902);
+}
+.actor.sheet .window-content .inventory ul.items > li > .data {
display: flex;
flex-wrap: wrap;
font-size: var(--font-size-12);
justify-content: flex-start;
width: 100%;
}
-.actor.sheet .inventory .item .quantity,
-.actor.sheet .inventory .item .bulk,
-.actor.sheet .inventory .item .item-controls,
-.actor.sheet .inventory .item .sell-value {
+.actor.sheet .window-content .inventory ul.items > li > .data.drop-highlight {
+ background: #b7f8c7;
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h3,
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h4 {
+ font-weight: 500;
+ line-height: var(--font-size-12);
+ margin: auto auto auto 0;
+ padding: 2px;
+ word-break: break-word;
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h3 a:hover,
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h4 a:hover {
+ text-shadow: none;
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h3:hover,
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h4:hover {
+ color: var(--primary);
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h3 i.fa-info-circle,
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h4 i.fa-info-circle {
+ color: var(--text-dark);
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h3 i.fa-info-circle:hover,
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h4 i.fa-info-circle:hover {
+ color: var(--text-dark);
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h4:not(:hover).rarity-uncommon {
+ border-color: var(--color-rarity-uncommon);
+ color: var(--color-rarity-uncommon);
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h4:not(:hover).rarity-rare {
+ border-color: var(--color-rarity-rare);
+ color: var(--color-rarity-rare);
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name h4:not(:hover).rarity-unique {
+ border-color: var(--color-rarity-unique);
+ color: var(--color-rarity-unique);
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name .size {
+ font-size: 0.8em;
+ color: var(--alt);
+ margin: 0;
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .item-name .uses {
+ color: var(--color-text-dark-3);
+ margin-left: auto;
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .quantity,
+.actor.sheet .window-content .inventory ul.items > li > .data .bulk,
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls,
+.actor.sheet .window-content .inventory ul.items > li > .data .sell-value {
border-left: 1px solid var(--alt);
}
-.actor.sheet .inventory .list-row {
- width: 100%;
+.actor.sheet .window-content .inventory ul.items > li > .data .quantity {
+ justify-content: space-around;
+}
+.actor.sheet .window-content .inventory ul.items > li > .data .quantity .decrease,
+.actor.sheet .window-content .inventory ul.items > li > .data .quantity .increase {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ font-family: var(--sans-serif-monospace);
+ height: 100%;
+ text-align: center;
+ width: 18px;
}
-.actor.sheet .inventory .list-row .item-controls {
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls {
color: var(--text-dark);
font-size: var(--font-size-13);
}
-.actor.sheet .inventory .list-row .item-controls .item-control.toggle-invested, .actor.sheet .inventory .list-row .item-controls .item-control.item-carry-type {
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control.toggle-invested, .actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control.item-carry-type {
color: rgba(0, 0, 0, 0.5);
}
-.actor.sheet .inventory .list-row .item-controls .item-control.toggle-invested.active, .actor.sheet .inventory .list-row .item-controls .item-control.item-carry-type.active {
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control.toggle-invested.active, .actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control.item-carry-type.active {
color: var(--secondary);
}
-.actor.sheet .inventory .list-row .item-controls .item-control.item-carry-type {
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control.item-carry-type {
text-align: right;
}
-.actor.sheet .inventory .list-row .item-controls .item-control .fa-stack {
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control .fa-stack {
margin: -3px -2px 0;
}
-.actor.sheet .inventory .list-row .item-controls .item-control .fa-stack .fa-1,
-.actor.sheet .inventory .list-row .item-controls .item-control .fa-stack .fa-2 {
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control .fa-stack .fa-1,
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control .fa-stack .fa-2 {
left: 1px;
position: relative;
}
-.actor.sheet .inventory .list-row.drag-preview {
+.actor.sheet .window-content .inventory ul.items > li > .data .item-controls .item-control .notify {
+ animation: glow 0.75s infinite alternate;
+}
+.actor.sheet .window-content .inventory ul.items > li.drag-preview {
box-shadow: 0 0 6px inset var(--color-shadow-highlight);
}
-.actor.sheet .inventory .list-row.drag-gap {
+.actor.sheet .window-content .inventory ul.items > li.drag-gap {
visibility: hidden;
}
-.actor.sheet .inventory .container-metadata .container-capacity {
+.actor.sheet .window-content .inventory ul.items > li .item-summary {
+ flex: 100%;
+ padding: 4px 8px 8px;
+ border-top: 1px solid var(--alt);
+ border-bottom: 1px solid var(--alt);
+ background: rgba(255, 255, 255, 0.333);
+}
+.actor.sheet .window-content .inventory ul.items > li .container-metadata {
+ flex-basis: 100%;
+}
+.actor.sheet .window-content .inventory ul.items > li .container-metadata .capacity {
font-family: var(--sans-serif);
font-size: var(--font-size-10);
text-transform: uppercase;
@@ -4579,38 +4611,38 @@ body > .choices__list--dropdown {
display: flex;
width: 100%;
}
-.actor.sheet .inventory .container-metadata .container-capacity .container-capacity-bar {
+.actor.sheet .window-content .inventory ul.items > li .container-metadata .capacity .bar {
background-color: var(--secondary);
border-radius: 0 2px 2px 0;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5), inset 0 0 0 2px rgba(255, 255, 255, 0.1);
padding: 8px 0;
}
-.actor.sheet .inventory .container-metadata .container-capacity .container-capacity-label {
+.actor.sheet .window-content .inventory ul.items > li .container-metadata .capacity .label {
position: absolute;
height: 100%;
top: 0;
left: 0;
padding: 2px;
}
-.actor.sheet .inventory .container-metadata .container-capacity.over-limit .container-capacity-bar {
+.actor.sheet .window-content .inventory ul.items > li .container-metadata .capacity.over-limit .container-capacity-bar {
background-color: var(--primary);
}
-.actor.sheet .inventory .container-metadata .container-held-items {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents {
padding-left: 10px;
border-left: none;
border-right: none;
}
-.actor.sheet .inventory .container-metadata .container-held-items li:nth-of-type(even) {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li {
+ position: relative;
+}
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li:nth-of-type(even) {
background-color: rgba(120, 100, 82, 0.1);
}
-.actor.sheet .inventory .container-metadata .container-held-items li:first-of-type .item::before {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li:first-of-type .item::before {
height: 50%;
top: 0;
}
-.actor.sheet .inventory .container-metadata .container-held-items .item {
- position: relative;
-}
-.actor.sheet .inventory .container-metadata .container-held-items .item::before, .actor.sheet .inventory .container-metadata .container-held-items .item::after {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li::before, .actor.sheet .window-content .inventory ul.items > li ul.container-contents > li::after {
position: absolute;
border-left: 1px solid var(--alt);
top: 0;
@@ -4619,20 +4651,20 @@ body > .choices__list--dropdown {
width: 5px;
content: "";
}
-.actor.sheet .inventory .container-metadata .container-held-items .item::before {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li::before {
border-bottom: 1px solid var(--alt);
top: 0;
}
-.actor.sheet .inventory .container-metadata .container-held-items .item::after {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li::after {
top: 50%;
}
-.actor.sheet .inventory .container-metadata .container-held-items .item .item-summary {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li .item-summary {
border-left: 1px solid var(--alt);
}
-.actor.sheet .inventory .container-metadata .container-held-items .container-metadata {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents .container-metadata {
position: relative;
}
-.actor.sheet .inventory .container-metadata .container-held-items .container-metadata::before {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents .container-metadata::before {
position: absolute;
border-left: 1px solid var(--alt);
top: 0;
@@ -4641,24 +4673,17 @@ body > .choices__list--dropdown {
width: 0px;
content: "";
}
-.actor.sheet .inventory .container-metadata .container-held-items li:last-of-type .item::after,
-.actor.sheet .inventory .container-metadata .container-held-items li:last-of-type .container-metadata::before {
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li:last-of-type .item::after,
+.actor.sheet .window-content .inventory ul.items > li ul.container-contents > li:last-of-type .container-metadata::before {
border: none;
}
-.actor.sheet .inventory .item-summary {
- flex: 100%;
- padding: 4px 8px 8px;
- border-top: 1px solid var(--alt);
- border-bottom: 1px solid var(--alt);
- background: rgba(255, 255, 255, 0.333);
-}
-.actor.sheet .inventory .encumbrance {
+.actor.sheet .window-content .inventory .encumbrance {
align-items: center;
display: grid;
grid: "img bar overflow" min-content/24px 1fr;
margin-top: auto;
}
-.actor.sheet .inventory .encumbrance img {
+.actor.sheet .window-content .inventory .encumbrance img {
border: none;
border-radius: 2px;
box-shadow: 0 0 0 1px var(--tertiary), 0 0 0 2px #9f725b, inset 0 0 4px rgba(0, 0, 0, 0.5);
@@ -4667,7 +4692,7 @@ body > .choices__list--dropdown {
position: relative;
z-index: 4;
}
-.actor.sheet .inventory .encumbrance .encumbrance-bar {
+.actor.sheet .window-content .inventory .encumbrance .encumbrance-bar {
position: relative;
z-index: 2;
grid-area: bar;
@@ -4676,7 +4701,7 @@ body > .choices__list--dropdown {
background-color: var(--secondary);
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5), inset 0 0 0 2px rgba(255, 255, 255, 0.2);
}
-.actor.sheet .inventory .encumbrance .encumbrance-label {
+.actor.sheet .window-content .inventory .encumbrance .encumbrance-label {
position: relative;
z-index: 3;
grid-area: bar;
@@ -4692,7 +4717,7 @@ body > .choices__list--dropdown {
width: 100%;
text-shadow: 0 0 2px black;
}
-.actor.sheet .inventory .encumbrance .encumbrance-light-bulk-overflow {
+.actor.sheet .window-content .inventory .encumbrance .encumbrance-light-bulk-overflow {
position: relative;
z-index: 3;
grid-area: overflow;
@@ -4708,7 +4733,7 @@ body > .choices__list--dropdown {
width: 100%;
text-shadow: 0 0 2px white;
}
-.actor.sheet .inventory .encumbrance .bar-bg {
+.actor.sheet .window-content .inventory .encumbrance .bar-bg {
position: relative;
z-index: 1;
grid-area: bar;
@@ -4718,46 +4743,27 @@ body > .choices__list--dropdown {
border-radius: 0 2px 2px 0;
box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.75);
}
-.actor.sheet .inventory .encumbrance.over-limit .encumbrance-bar {
+.actor.sheet .window-content .inventory .encumbrance.over-limit .encumbrance-bar {
background-color: var(--primary) !important;
}
-.actor.sheet .inventory .total-bulk {
- align-items: center;
- display: flex;
+.actor.sheet .window-content .inventory .total-bulk {
font-weight: 500;
gap: 0.25rem;
height: 1.5rem;
+ padding-left: 0;
+ border-radius: 0;
justify-content: start;
margin-bottom: 0.7rem;
}
-.actor.sheet .inventory .total-bulk img {
+.actor.sheet .window-content .inventory .total-bulk img {
border: none;
border-radius: 2px;
box-shadow: 0 0 0 1px var(--tertiary), 0 0 0 2px #9f725b, inset 0 0 4px rgba(0, 0, 0, 0.5);
height: 1.5rem;
width: 1.5rem;
- border-radius: 0;
z-index: 1;
}
-.actor.sheet .inventory .total-bulk .bar {
- justify-content: start;
- margin-top: 0;
- position: relative;
- height: 1.25rem;
- padding-left: 0.5rem;
- left: -0.35rem;
- z-index: 0;
-}
-.actor.sheet a.disabled {
- cursor: default;
-}
-.actor.sheet a.disabled:hover {
- text-shadow: none;
-}
-.actor.sheet i.fa-info-circle {
- cursor: help;
-}
-.actor.sheet .item-image {
+.actor.sheet .window-content .item-image {
cursor: pointer;
display: flex;
flex: 0 0 1.5rem;
@@ -4765,23 +4771,23 @@ body > .choices__list--dropdown {
height: 1.5rem;
position: relative;
}
-.actor.sheet .item-image.framed {
+.actor.sheet .window-content .item-image.framed {
background-color: var(--tertiary);
}
-.actor.sheet .item-image.framed img {
+.actor.sheet .window-content .item-image.framed img {
border-radius: 2px;
}
-.actor.sheet .item-image.framed,
-.actor.sheet .item-image.framed i {
+.actor.sheet .window-content .item-image.framed,
+.actor.sheet .window-content .item-image.framed i {
border: none;
border-radius: 2px;
box-shadow: 0 0 0 1px var(--tertiary), 0 0 0 2px #9f725b, inset 0 0 4px rgba(0, 0, 0, 0.5);
}
-.actor.sheet .item-image img {
+.actor.sheet .window-content .item-image img {
border: none;
border-radius: 0;
}
-.actor.sheet .item-image i {
+.actor.sheet .window-content .item-image i {
box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.5);
color: var(--text-dark);
display: none;
@@ -4789,36 +4795,31 @@ body > .choices__list--dropdown {
position: absolute;
width: 100%;
}
-.actor.sheet .item-image:hover i {
+.actor.sheet .window-content .item-image:hover i {
align-items: center;
background: #f1eee9;
display: flex;
justify-content: center;
}
-.actor.sheet .alignment-select {
- background-color: var(--color-bg-alignment);
- border: 2px solid var(--color-border-trait);
- color: var(--color-text-trait);
-}
-.actor.sheet .size-select {
+.actor.sheet .window-content .size-select {
background-color: var(--color-bg-size);
border: 2px solid var(--color-border-trait);
color: var(--color-text-trait);
}
-.actor.sheet .rarity-select {
+.actor.sheet .window-content .rarity-select {
border: 2px solid var(--color-border-trait);
color: var(--color-text-trait);
}
-.actor.sheet .rarity-select.common {
+.actor.sheet .window-content .rarity-select.common {
background-color: var(--color-rarity-common);
}
-.actor.sheet .rarity-select.uncommon {
+.actor.sheet .window-content .rarity-select.uncommon {
background-color: var(--color-rarity-uncommon);
}
-.actor.sheet .rarity-select.rare {
+.actor.sheet .window-content .rarity-select.rare {
background-color: var(--color-rarity-rare);
}
-.actor.sheet .rarity-select.unique {
+.actor.sheet .window-content .rarity-select.unique {
background-color: var(--color-rarity-unique);
}
.actor.sheet.character .attack-popout.actions {
@@ -5097,7 +5098,6 @@ body > .choices__list--dropdown {
margin: 0;
}
.actor.sheet.character .attack-popout ol.actions-list li.action .item-name h4, .actor.sheet.character .attack-popout ol.actions-list li.strike .item-name h4 {
- cursor: pointer;
margin: 0;
max-width: fit-content;
}
@@ -5119,13 +5119,10 @@ body > .choices__list--dropdown {
flex-direction: row;
gap: 0.5em;
}
-.actor.sheet.character .attack-popout ol.actions-list li.action .item-name .actions-title .action-name > h4, .actor.sheet.character .attack-popout ol.actions-list li.strike .item-name .actions-title .action-name > h4 {
- cursor: pointer;
-}
-.actor.sheet.character .attack-popout ol.actions-list li.action .item-name .actions-title .action-name > h4:hover, .actor.sheet.character .attack-popout ol.actions-list li.strike .item-name .actions-title .action-name > h4:hover {
- color: var(--primary);
+.actor.sheet.character .attack-popout ol.actions-list li.action .item-name .actions-title .action-name > h4 a:hover, .actor.sheet.character .attack-popout ol.actions-list li.strike .item-name .actions-title .action-name > h4 a:hover {
+ color: var(--color-pf-primary);
}
-.actor.sheet.character .attack-popout ol.actions-list li.action .item-name .actions-title .action-name > h4:hover .action-glyph, .actor.sheet.character .attack-popout ol.actions-list li.strike .item-name .actions-title .action-name > h4:hover .action-glyph {
+.actor.sheet.character .attack-popout ol.actions-list li.action .item-name .actions-title .action-name > h4 .action-glyph, .actor.sheet.character .attack-popout ol.actions-list li.strike .item-name .actions-title .action-name > h4 .action-glyph {
color: var(--text-dark);
}
.actor.sheet.character .attack-popout ol.actions-list li.action button.use-action, .actor.sheet.character .attack-popout ol.actions-list li.strike button.use-action {
@@ -5241,6 +5238,9 @@ body > .choices__list--dropdown {
margin-bottom: 0;
text-align: left;
}
+.actor.sheet.character .attack-popout ol.actions-list li.action .name > a:hover {
+ color: var(--color-pf-primary);
+}
.actor.sheet.character .attack-popout ol.actions-list li.action .button-group {
grid-area: buttons;
display: flex;
@@ -5296,17 +5296,14 @@ body > .choices__list--dropdown {
text-transform: uppercase;
letter-spacing: 0.05em;
text-rendering: optimizeLegibility;
- align-items: center;
background: var(--color-proficiency-untrained);
border-radius: 2px;
border: 1px solid rgba(0, 0, 0, 0.5);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1);
color: var(--text-light);
- cursor: pointer;
- display: flex;
font-weight: 500;
- justify-content: center;
padding: 2px 1px 1px 1px;
+ width: 6.5em;
text-align-last: center;
}
.actor.sheet.character .crb-style .pf-rank.readonly {
@@ -5331,6 +5328,10 @@ body > .choices__list--dropdown {
.actor.sheet.character .crb-style .pf-rank option[value="4"] {
background: var(--color-proficiency-legendary);
}
+.actor.sheet.character .crb-style select.pf-rank {
+ cursor: pointer;
+ height: 1rem;
+}
.actor.sheet.character .crb-style span.pf-rank {
min-width: 61px;
pointer-events: none;
@@ -5433,42 +5434,8 @@ body > .choices__list--dropdown {
.actor.sheet.character .crb-style .sheet-body .sheet-content nav + .tab-content {
padding-top: 0.75rem;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content h3.header {
- position: relative;
- margin-top: 0.75em;
- font-size: var(--font-size-16);
- font-family: var(--serif);
- font-weight: 600;
- color: var(--primary);
- line-height: 1;
- border-bottom: 1px solid var(--color-border-divider);
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content h3.header > button, .actor.sheet.character .crb-style .sheet-body .sheet-content h3.header > .controls {
- position: absolute;
- bottom: -1px;
- right: 0;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content h3.header .controls {
- display: flex;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content h3.header button {
- background: transparent;
- border-radius: 2px 2px 0 0;
- border: 1px solid var(--color-border-divider);
- color: var(--primary);
- cursor: pointer;
- font-family: var(--sans-serif);
- font-size: var(--font-size-12);
- font-weight: 500;
- height: 20px;
- line-height: var(--font-size-12);
- margin: 0;
- outline: none;
- text-transform: uppercase;
- width: auto;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content h3.header button.has-unallocated {
- animation: glow 0.75s infinite alternate;
+.actor.sheet.character .crb-style .sheet-body .sheet-content .name a:hover {
+ text-shadow: none;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .item-image i {
display: none;
@@ -5507,41 +5474,29 @@ body > .choices__list--dropdown {
margin: 10px 6px 10px 0;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .pc h3 {
+ align-items: center;
background-color: rgba(28, 28, 28, 0.1);
border: none;
color: var(--text-dark);
display: flex;
- font: 700 var(--font-size-14) var(--body-serif);
- grid-area: mod;
- line-height: 1;
+ font: 700 var(--font-size-14)/1em var(--body-serif);
margin: 0;
- padding: 8px 4px 6px;
- width: calc(100% - 6px);
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .pc h3 a {
- margin-left: auto;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .pc h3 a i {
- position: relative;
- right: -2px;
- top: -2px;
- float: right;
+ padding: 0.5em 0.25em;
+ width: calc(100% - 0.5em);
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .pc h3 span.value {
- display: inline-block;
- max-width: 87%;
+ flex-basis: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details {
display: grid;
- grid: "img alignment deity" 46px "img details details" auto/120px 130px 1fr;
- margin-top: 4px;
+ grid: "img details" 9rem "img deity" auto/120px 1fr;
+ margin-top: 0.25rem;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .image-container {
grid-area: img;
- margin-left: 0.25rem;
z-index: 3;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .image-container .actor-image {
@@ -5553,105 +5508,41 @@ body > .choices__list--dropdown {
object-position: top;
width: 100%;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .alignment {
- grid-area: alignment;
- position: relative;
- display: flex;
- align-items: center;
- justify-content: center;
- background: url("../assets/sheet/banner-bg.webp") repeat-x center;
- z-index: 1;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .alignment .bio-alignment {
- position: absolute;
- left: 0;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .alignment select {
- background: none;
- border: none;
- box-shadow: none;
- color: var(--text-dark);
- cursor: pointer;
- display: block;
- font-family: var(--body-serif);
- font-size: var(--font-size-14);
- font-weight: 700;
- outline: none;
- overflow-x: visible;
- padding-left: 8px;
- width: auto;
- line-height: 1;
- text-transform: capitalize;
- margin-top: 2px;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .alignment select option {
- color: var(--text-light);
- font: initial;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .alignment input[type=text] {
- font: 700 var(--font-size-14) var(--body-serif);
- text-align: center;
- max-width: 138px;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .alignment::after {
- position: absolute;
- content: "";
- height: 46px;
- width: 15px;
- top: 0;
- right: -11px;
- background: url("../assets/sheet/banner-bg2.webp") no-repeat right;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .pc_deity {
- align-items: center;
- display: flex;
- grid-area: deity;
- margin-left: auto;
- min-width: 10em;
- padding-bottom: 0.7em;
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .abcd {
+ grid-area: details;
+ display: grid;
+ grid-template-columns: repeat(2, 13em);
+ grid-row-gap: 0.5rem;
+ justify-content: start;
+ padding-left: 0.75rem;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .pc_deity .input {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .abcd > * {
display: flex;
- flex-flow: column wrap;
- justify-content: end;
+ flex-wrap: wrap;
+ gap: 2px;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .pc_deity .input span {
- text-align: right;
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .abcd > * .details-label {
+ flex-basis: 100%;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .pc_deity .input h3 {
- min-width: 9em;
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .abcd .deity {
+ align-items: center;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .pc_deity .input h3 span {
- max-width: 10em;
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .abcd .deity .input h3 {
+ min-width: 11em;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .pc_deity img.symbol {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .abcd img.deity-emblem {
border: none;
box-shadow: 0 0 0 1px #918c88, 0 0 0 2px #e1d8cf, 0 0 0 3px #a98f39, inset 0 0 8px rgba(0, 0, 0, 0.5), 0 0 8px black;
+ align-self: end;
border-radius: 50%;
- height: 32px;
- margin: 0.5rem 0 0 0.5rem;
- width: 32px;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-sheet {
- grid-area: details;
- display: grid;
- grid-template-columns: 44% 55%;
- grid-template-rows: repeat(2, 42px);
- grid-row-gap: 8px;
- padding-left: 12px;
- margin-top: 8px;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-sheet .pc_heritage, .actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-sheet .pc_background, .actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-sheet .pc_weight {
- margin: 0;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-sheet .detail-small {
- display: flex;
+ height: 2rem;
+ margin-left: 0.25rem;
+ width: 2rem;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-item-control {
cursor: pointer;
- margin-left: auto;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-item-control i.fa-ellipsis-v:hover {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-item-control > i:hover {
text-shadow: 0 0 8px var(--color-shadow-primary);
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-details .detail-item-control #context-menu {
@@ -5697,7 +5588,7 @@ body > .choices__list--dropdown {
justify-content: start;
align-items: start;
flex: 20%;
- margin-bottom: 8px;
+ margin-bottom: 0.5rem;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-traits .pc span {
width: 100%;
@@ -5735,7 +5626,7 @@ body > .choices__list--dropdown {
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-traits .pc select,
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-traits .pc input,
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .character-traits .pc h3 {
- margin-top: 4px;
+ margin-top: 0.25rem;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.character .attributes {
margin: 0;
@@ -6114,6 +6005,9 @@ body > .choices__list--dropdown {
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.spellcasting .spellcasting-entry:first-child .action-header {
justify-content: start;
}
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.spellcasting .spellcasting-entry .rollable:hover {
+ text-shadow: none;
+}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.spellcasting .spellcasting-entry .rollable .d20-svg {
width: var(--font-size-14);
height: var(--font-size-14);
@@ -6135,9 +6029,6 @@ body > .choices__list--dropdown {
display: flex;
align-items: center;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.spellcasting .spellcasting-entry .spell-ability-data .rollable {
- cursor: pointer;
-}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.spellcasting .spellcasting-entry .spell-ability-data button {
width: auto;
line-height: 1.5em;
@@ -6218,10 +6109,6 @@ body > .choices__list--dropdown {
width: 100%;
margin-bottom: 12px;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .proficiencies-pane {
- margin: 0;
- padding: 0;
-}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies h1,
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies h4,
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies h6 {
@@ -6232,173 +6119,107 @@ body > .choices__list--dropdown {
align-items: center;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies h6 {
- padding: 2px 4px;
- border-radius: 2px;
- box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5);
font-family: var(--sans-serif);
font-size: var(--font-size-10);
text-transform: uppercase;
letter-spacing: 0.05em;
text-rendering: optimizeLegibility;
+ padding: 2px 0.25rem;
+ border-radius: 2px;
+ box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5);
color: var(--text-light);
- display: flex;
- justify-content: center;
- align-items: center;
- cursor: pointer;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .core-title {
- width: 100%;
- text-align: left;
- margin: 0;
- padding: 0;
- margin-left: 0;
- padding-top: 10px;
- padding-left: 12px;
- height: 43px;
- border: none;
- color: var(--text-light);
- font-family: var(--serif);
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list {
list-style: none;
margin: 0;
padding: 0;
display: grid;
grid-template-columns: repeat(2, 1fr);
- gap: 12px;
+ gap: 0.75rem;
align-items: center;
- margin-bottom: 2em;
+ margin-bottom: 1rem;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li {
border-image-repeat: repeat;
border-image-slice: 11;
border-image-source: url("../assets/sheet/frame-elegant.svg");
border-image-width: 14px;
border-style: double;
- padding: 2px 15px 2px 4px;
- display: flex;
align-items: center;
+ display: flex;
+ gap: 0.25rem;
+ padding: 0.125rem 0.875rem 0.125rem 0.25rem;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill .rollable,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .rollable,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .rollable {
- cursor: pointer;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill .rollable:hover,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .rollable:hover,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .rollable:hover {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li a.skill-name:hover,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li a.modifier:hover {
color: var(--primary);
- text-shadow: 0 0 2px white;
+ text-shadow: none;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill .rollable:hover .skill-score,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .rollable:hover .skill-score,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .rollable:hover .skill-score {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li a.modifier:hover,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li a.skill-name:hover > .modifier {
text-decoration: underline;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill .skill-score,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .skill-score,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .skill-score {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li .modifier {
color: var(--primary);
- font-family: var(--serif);
- font-size: var(--font-size-24);
- font-weight: 600;
- line-height: 1;
+ font: 600 var(--font-size-22)/1em var(--serif);
text-align: end;
- margin-right: 4px;
width: 2.5rem;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill .skill-name,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .skill-name,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .skill-name {
- display: flex;
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li .skill-name {
align-items: center;
+ display: flex;
flex: 1;
+ gap: 0.25rem;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill .button-group,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .button-group,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .button-group {
- display: flex;
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li .button-group {
align-items: center;
+ display: flex;
+ flex-flow: column wrap;
justify-content: center;
- flex-wrap: wrap;
- flex-direction: column;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill .button-group h6,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .button-group h6,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .button-group h6 {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li .button-group h6 {
margin: 1px 0;
background: var(--sub);
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.2);
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill .button-group h6:hover,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .button-group h6:hover,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .button-group h6:hover {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li .button-group h6:hover {
background: var(--primary);
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill.custom,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill.custom,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill.custom {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li.custom {
position: relative;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill.custom a.delete,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill.custom a.delete,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill.custom a.delete {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li.custom a.delete {
position: absolute;
- top: -8px;
- right: -8px;
- z-index: -1;
+ top: -0.5rem;
+ right: -0.5rem;
opacity: 0.75;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill.custom a.delete:hover,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill.custom a.delete:hover,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill.custom a.delete:hover {
- z-index: 1;
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.proficiencies-list li.custom a.delete:hover {
opacity: 1;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .skills-list .skill.custom:hover a.delete,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill.custom:hover a.delete,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill.custom:hover a.delete {
- z-index: 1;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill {
- grid: "score name btn" min-content/42px 2fr 1fr;
- padding: 2px 15px 2px 6px;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill input,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill input {
- color: var(--text-dark);
- border-bottom: 1px solid var(--sub);
- margin-right: 4px;
- font-weight: 600;
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill input:hover,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill input:hover {
- border: 1px solid var(--sub);
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .button-group,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .button-group {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.lores-list li .button-group,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.combat-list li .button-group {
flex-direction: row;
flex-wrap: nowrap;
margin-left: auto;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list .skill .button-group .item-controls,
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .skill .button-group .item-controls {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.lores-list li .button-group .item-controls,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.combat-list li .button-group .item-controls {
font-size: var(--font-size-12);
- margin-top: 1px;
margin-left: 0.5rem;
+ margin-top: 1px;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lores-list {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.lores-list {
grid-template-columns: 1fr;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.lores-list input {
+ color: var(--text-dark);
+ font-weight: 600;
+}
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.combat-list {
grid-template: repeat(2, 1fr);
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .combat-list .item {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies ul.combat-list .item {
grid-column: 1/3;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lore-header .item-controls {
@@ -6411,7 +6232,7 @@ body > .choices__list--dropdown {
text-rendering: optimizeLegibility;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.proficiencies .lore-header .item-controls .item-control {
- padding: 4px;
+ padding: 0.25rem;
background: var(--secondary);
font-size: var(--font-size-10);
border-radius: 2px;
@@ -6489,7 +6310,7 @@ body > .choices__list--dropdown {
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.feats .feat-item ol.nested-items {
grid-column: span 2;
- border-left: 3px dotted #786452;
+ border-left: 3px dotted var(--alt);
display: flex;
margin: 1px 0 0 45px;
padding: 0;
@@ -6519,17 +6340,13 @@ body > .choices__list--dropdown {
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.feats .feat-item ol.nested-items li ol.nested-items {
margin-left: 25px;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography h3.header {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography > header {
display: flex;
align-items: baseline;
justify-content: space-between;
padding: 0 1px;
}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography h3.header a {
- color: var(--color-text-dark-primary);
- font-size: var(--font-size-12);
-}
-.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography h3.header a i.fa-eye-slash {
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography > header i.fa-eye-slash {
opacity: 75%;
}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.editable .editor-content,
@@ -6567,6 +6384,35 @@ body > .choices__list--dropdown {
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .bio span {
width: 100%;
}
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .edicts,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .anathema {
+ flex-basis: 100%;
+}
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .edicts > *,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .anathema > * {
+ width: 100%;
+}
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .edicts .label-add,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .anathema .label-add {
+ align-items: center;
+ display: flex;
+ justify-content: space-between;
+ width: calc(100% - 0.75em);
+}
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .edicts ol,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .anathema ol {
+ list-style-type: decimal;
+ margin-top: 0;
+}
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .edicts ol li,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .anathema ol li {
+ white-space: nowrap;
+}
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .edicts ol li input,
+.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.personality .anathema ol li input {
+ margin: 0.2em;
+ max-width: calc(100% - 2rem);
+}
.actor.sheet.character .crb-style .sheet-body .sheet-content .tab.biography section.campaign {
display: flex;
flex-direction: column;
@@ -7471,40 +7317,6 @@ body > .choices__list--dropdown {
.actor.sheet.vehicle .crb-style .sheet-body .sheet-content > .tab.active.effects.effects .effects-list .item-name h4 {
font-family: var(--serif);
}
-.actor.sheet.vehicle .crb-style .sheet-body .sheet-content > .tab.active.effects h3.header {
- position: relative;
- margin-top: 0.75em;
- font-size: var(--font-size-16);
- font-family: var(--serif);
- font-weight: 600;
- color: var(--primary);
- line-height: 1;
- border-bottom: 1px solid var(--color-border-divider);
-}
-.actor.sheet.vehicle .crb-style .sheet-body .sheet-content > .tab.active.effects h3.header > button, .actor.sheet.vehicle .crb-style .sheet-body .sheet-content > .tab.active.effects h3.header > .controls {
- position: absolute;
- bottom: -1px;
- right: 0;
-}
-.actor.sheet.vehicle .crb-style .sheet-body .sheet-content > .tab.active.effects h3.header .controls {
- display: flex;
-}
-.actor.sheet.vehicle .crb-style .sheet-body .sheet-content > .tab.active.effects h3.header button {
- background: transparent;
- border-radius: 2px 2px 0 0;
- border: 1px solid var(--color-border-divider);
- color: var(--primary);
- cursor: pointer;
- font-family: var(--sans-serif);
- font-size: var(--font-size-12);
- font-weight: 500;
- height: 20px;
- line-height: var(--font-size-12);
- margin: 0;
- outline: none;
- text-transform: uppercase;
- width: auto;
-}
.actor.sheet.vehicle .crb-style .sheet-body .sheet-content > .tab.active.effects ol.directory-list {
margin: 0;
padding: 0;
@@ -7617,7 +7429,6 @@ body > .choices__list--dropdown {
height: 100%;
/* Navigation */
/** White background navigation with little decorations on the left and right */
- /* Page structure elements */
/* Read-Only Sheet */
}
.actor.sheet .crb-style .d20-svg {
@@ -7837,7 +7648,7 @@ body > .choices__list--dropdown {
border: 1px solid var(--sidebar-title);
display: flex;
flex-direction: column;
- padding: 10px 4px 0;
+ padding: 0.625rem 0.25rem 0;
position: relative;
width: min-content;
z-index: 0;
@@ -7848,7 +7659,7 @@ body > .choices__list--dropdown {
.actor.sheet .crb-style aside .sidebar .hitpoints .hp-big .container.current-hp .data-value input[type=number] {
font-size: var(--font-size-32);
letter-spacing: -1px;
- height: 32px;
+ height: 2rem;
}
.actor.sheet .crb-style aside .sidebar .hitpoints .hp-big .container.max-hp, .actor.sheet .crb-style aside .sidebar .hitpoints .hp-big .container.temp-hp {
margin-top: 0.75rem;
@@ -7866,10 +7677,10 @@ body > .choices__list--dropdown {
}
.actor.sheet .crb-style aside .sidebar .hitpoints .hp-small {
display: flex;
+ gap: 0.125rem;
justify-content: space-evenly;
- margin: 8px 2px 0 2px;
+ margin: 0.5rem 0.125rem 0 0.125rem;
text-align: center;
- gap: 2px;
}
.actor.sheet .crb-style aside .sidebar .hitpoints .hp-small h4,
.actor.sheet .crb-style aside .sidebar .hitpoints .hp-small label {
@@ -7879,8 +7690,8 @@ body > .choices__list--dropdown {
letter-spacing: 0.05em;
text-rendering: optimizeLegibility;
}
-.actor.sheet .crb-style aside .sidebar .hitpoints .hp-small .far,
-.actor.sheet .crb-style aside .sidebar .hitpoints .hp-small .fas {
+.actor.sheet .crb-style aside .sidebar .hitpoints .hp-small i.fa-regular,
+.actor.sheet .crb-style aside .sidebar .hitpoints .hp-small i.fa-solid {
color: var(--text-light);
}
.actor.sheet .crb-style aside .sidebar .armor-class {
@@ -8251,16 +8062,15 @@ body > .choices__list--dropdown {
align-items: center;
background: none;
cursor: default;
- display: grid;
- grid: "name range components cast-spell controls" auto "content content content content content" auto/9fr 4fr 4fr 2fr 2.5fr;
- justify-content: center;
- padding: 0 0.3em 1px 0.35em;
+ display: flex;
+ flex-wrap: wrap;
+ padding: 0 0.35em;
}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li[data-expended-state=true] h4 {
color: var(--color-disabled);
text-decoration: line-through;
}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li[data-expended-state=true] .cast-spell {
+.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li[data-expended-state=true] .cast-spell button {
background: var(--color-disabled);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.5);
cursor: not-allowed;
@@ -8276,8 +8086,6 @@ body > .choices__list--dropdown {
margin-top: 2px;
}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li.spell-level-header {
- margin: 0;
- padding: 0;
background: rgba(96, 88, 86, 0.25);
border: 1px solid var(--color-border-light-2);
border-radius: 2px;
@@ -8285,27 +8093,24 @@ body > .choices__list--dropdown {
font: 500 var(--font-size-12) var(--sans-serif);
letter-spacing: 0.25px;
line-height: 1;
- padding: 0 0.5em;
text-transform: uppercase;
}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li.spell-level-header h3 {
text-transform: capitalize;
font-size: var(--font-size-13);
margin-left: 0;
- padding: 4px 0;
+ padding: 0.25rem 0;
}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li.spell-level-header .item-name {
line-height: 1;
gap: 0.25em;
+ padding-left: 0.2em;
}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li.spell-level-header .item-name h3 {
margin: 0;
padding: 0;
font-weight: 700;
}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li.spell-level-header .item-controls {
- grid-column: span 2;
-}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .uses {
align-items: center;
display: flex;
@@ -8340,11 +8145,14 @@ body > .choices__list--dropdown {
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-name {
align-items: center;
display: flex;
+ flex: 1;
flex-wrap: nowrap;
- justify-content: start;
- justify-self: start;
min-height: 1.75rem;
}
+.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-name.empty {
+ color: var(--color-text-dark-secondary);
+ pointer-events: none;
+}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-name h3 {
white-space: nowrap;
}
@@ -8382,42 +8190,25 @@ body > .choices__list--dropdown {
letter-spacing: -0.075em;
line-height: 1;
margin-left: 8px;
- cursor: pointer;
}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-name h4:hover {
+.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-name h4 > a:hover {
color: var(--secondary);
+ text-shadow: none;
}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-name .action-glyph {
margin-left: 4px;
font-size: small;
}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-name.empty {
- grid-column: 1/span 4;
-}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .spell-range {
- grid-area: range;
+ flex: 0 0 6rem;
padding-left: 0.2em;
}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .spell-components {
- grid-area: components;
- justify-self: right;
- padding: 0 0.5em;
-}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .spell-components .tag {
- font: var(--font-size-12) var(--sans-serif-condensed);
-}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .spell-cast {
- grid-area: cast-spell;
+.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .cast-spell {
+ flex: 0 0 3.5rem;
display: flex;
justify-content: center;
}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-controls {
- grid-area: controls;
- display: flex;
- justify-self: end;
- padding-right: 0.25em;
-}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li button.cast-spell {
+.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .cast-spell button {
align-items: center;
background: var(--secondary);
border-radius: 2px;
@@ -8425,21 +8216,24 @@ body > .choices__list--dropdown {
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5);
color: var(--text-light);
cursor: pointer;
- display: flex;
font: 700 0.55rem var(--sans-serif);
- justify-self: center;
letter-spacing: 0.25px;
max-width: fit-content;
padding: 0.5em 1em;
text-transform: uppercase;
}
+.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-controls {
+ flex: 0 0 3.25rem;
+ display: flex;
+ justify-content: end;
+ padding-right: 0.25em;
+}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list > li .item-summary {
- grid-area: content;
- width: 100%;
- padding: 8px;
+ background-color: var(--bg);
border-bottom: 1px solid var(--sub);
border-top: 1px solid #aca5a3;
- background-color: var(--bg);
+ flex: 100%;
+ padding: 0.5rem;
}
.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list[data-category=spontaneous] .virtual {
position: relative;
@@ -8465,31 +8259,6 @@ body > .choices__list--dropdown {
background: var(--secondary);
position: relative;
}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list .spell .item-name {
- width: 100%;
-}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list input.toggle-signature-spell[type=checkbox] {
- width: 12px;
- height: 12px;
- margin: 0 2px 0 0;
- flex: 0 0 auto;
-}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list .spellbook-empty {
- display: flex;
- align-items: center;
- min-height: 28px;
- justify-content: flex-end;
-}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list .spellbook-empty h4 {
- margin: 0;
- white-space: nowrap;
- margin-right: auto;
-}
-.actor.sheet .crb-style .sheet-body .sheet-content ol.spell-list .spellbook-empty a {
- flex: 0 1 0;
- white-space: nowrap;
- margin-left: 8px;
-}
.actor.sheet .crb-style .sheet-body .sheet-content ol.directory-list > h3,
.actor.sheet .crb-style .sheet-body .sheet-content ol.directory-list > li > h3 {
font-size: 1rem;
@@ -8633,7 +8402,6 @@ body > .choices__list--dropdown {
margin: 0;
}
.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action .item-name h4, .actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.strike .item-name h4 {
- cursor: pointer;
margin: 0;
max-width: fit-content;
}
@@ -8655,13 +8423,10 @@ body > .choices__list--dropdown {
flex-direction: row;
gap: 0.5em;
}
-.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action .item-name .actions-title .action-name > h4, .actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.strike .item-name .actions-title .action-name > h4 {
- cursor: pointer;
-}
-.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action .item-name .actions-title .action-name > h4:hover, .actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.strike .item-name .actions-title .action-name > h4:hover {
- color: var(--primary);
+.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action .item-name .actions-title .action-name > h4 a:hover, .actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.strike .item-name .actions-title .action-name > h4 a:hover {
+ color: var(--color-pf-primary);
}
-.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action .item-name .actions-title .action-name > h4:hover .action-glyph, .actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.strike .item-name .actions-title .action-name > h4:hover .action-glyph {
+.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action .item-name .actions-title .action-name > h4 .action-glyph, .actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.strike .item-name .actions-title .action-name > h4 .action-glyph {
color: var(--text-dark);
}
.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action button.use-action, .actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.strike button.use-action {
@@ -8777,6 +8542,9 @@ body > .choices__list--dropdown {
margin-bottom: 0;
text-align: left;
}
+.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action .name > a:hover {
+ color: var(--color-pf-primary);
+}
.actor.sheet .crb-style .sheet-body .sheet-content .tab.actions ol.actions-list li.action .button-group {
grid-area: buttons;
display: flex;
@@ -8804,19 +8572,18 @@ body > .choices__list--dropdown {
margin: 1em 1em 0;
}
.actor.sheet .crb-style nav.sheet-navigation {
- display: inline-flex;
- justify-content: center;
- align-items: center;
- height: 20px;
- background: var(--secondary);
background: url("../assets/sheet/border-pattern.webp") repeat-x top, url("../assets/sheet/border-pattern.webp") repeat-x bottom, var(--secondary);
- transition: all 0.1s ease-out;
- box-shadow: 0 -1px 1px rgba(0, 0, 0, 0.25);
- border-top: 1px solid rgba(255, 255, 255, 0.1);
+ align-items: center;
border-bottom: 1px solid rgba(255, 255, 255, 0.5);
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
+ box-shadow: 0 -1px 1px rgba(0, 0, 0, 0.25);
+ display: inline-flex;
+ height: 1.25rem;
+ justify-content: center;
position: relative;
+ transition: all 0.1s ease-out;
}
-.actor.sheet .crb-style nav.sheet-navigation .navigation-title {
+.actor.sheet .crb-style nav.sheet-navigation .panel-title {
color: var(--text-light);
margin-right: auto;
padding-left: 1em;
@@ -8831,8 +8598,8 @@ body > .choices__list--dropdown {
font-size: var(--font-size-12);
}
.actor.sheet .crb-style nav.sheet-navigation .item {
- height: 24px;
- width: 24px;
+ height: 1.5rem;
+ width: 1.5rem;
border-radius: 50%;
z-index: 1;
transition: all 0.1s ease-out;
@@ -8856,7 +8623,7 @@ body > .choices__list--dropdown {
fill: var(--text-light);
background-image: url("../assets/sheet/nav-item.webp");
}
-.actor.sheet .crb-style nav.sheet-navigation .item .fas {
+.actor.sheet .crb-style nav.sheet-navigation .item i.fa-solid {
padding-bottom: 0;
}
.actor.sheet .crb-style nav.sheet-navigation .item:hover .pfs-icon {
@@ -8868,15 +8635,15 @@ body > .choices__list--dropdown {
.actor.sheet .crb-style nav.sub-nav {
margin: 0;
padding: 0;
+ align-items: center;
+ background-color: var(--bg);
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18);
display: flex;
flex-wrap: nowrap;
+ flex: 0 0 2.5rem;
justify-content: center;
- align-items: center;
list-style: none;
- background-color: var(--bg);
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18);
width: 100%;
- flex: 0 0 2.5rem;
}
.actor.sheet .crb-style nav.sub-nav::before, .actor.sheet .crb-style nav.sub-nav::after {
content: "";
@@ -8921,17 +8688,42 @@ body > .choices__list--dropdown {
text-shadow: 0 0 3px rgba(255, 255, 255, 0.5);
}
.actor.sheet .crb-style .tab nav.sub-nav {
- padding-right: 20px;
+ padding-right: 1.25rem;
}
-.actor.sheet .crb-style .stroke-header {
+.actor.sheet .crb-style section.major > header {
+ border-bottom: 1px solid var(--color-border-divider);
+ color: var(--primary);
+ font: 600 var(--font-size-16)/1 var(--serif);
position: relative;
+ margin: 0.75rem 0 0.5rem 0;
+}
+.actor.sheet .crb-style section.major > header a {
+ color: var(--color-text-dark-primary);
+ font-size: var(--font-size-12);
}
-.actor.sheet .crb-style .stroke-header svg {
+.actor.sheet .crb-style section.major > header > button, .actor.sheet .crb-style section.major > header > .controls {
position: absolute;
- fill: var(--primary);
+ bottom: -1px;
+ right: 0;
}
-.actor.sheet .crb-style .stroke-header h3 {
- position: relative;
+.actor.sheet .crb-style section.major > header .controls {
+ display: flex;
+}
+.actor.sheet .crb-style section.major > header button {
+ background: transparent;
+ border-radius: 2px 2px 0 0;
+ border: 1px solid var(--color-border-divider);
+ color: var(--primary);
+ cursor: pointer;
+ font: 500 var(--font-size-12)/1 var(--sans-serif);
+ height: 20px;
+ margin: 0;
+ outline: none;
+ text-transform: uppercase;
+ width: auto;
+}
+.actor.sheet .crb-style section.major > header button.has-unallocated {
+ animation: glow 0.75s infinite alternate;
}
.actor.sheet .crb-style.limited .sidebar {
align-items: center;
@@ -9010,6 +8802,17 @@ body > .choices__list--dropdown {
height: 9px;
width: auto;
}
+.spellcasting-entry.preparation input,
+.spellcasting-entry.preparation label,
+.spellcasting-entry.preparation select {
+ --form-field-height: 1.5rem;
+}
+.spellcasting-entry.preparation input[type=checkbox] {
+ height: var(--font-size-20);
+}
+.spellcasting-entry.preparation select {
+ height: var(--form-field-height);
+}
.spellcasting-entry.preparation h3 {
border-bottom: none;
}
@@ -9032,16 +8835,15 @@ body > .choices__list--dropdown {
align-items: center;
background: none;
cursor: default;
- display: grid;
- grid: "name range components cast-spell controls" auto "content content content content content" auto/9fr 4fr 4fr 2fr 2.5fr;
- justify-content: center;
- padding: 0 0.3em 1px 0.35em;
+ display: flex;
+ flex-wrap: wrap;
+ padding: 0 0.35em;
}
.spellcasting-entry.preparation ol.spell-list > li[data-expended-state=true] h4 {
color: var(--color-disabled);
text-decoration: line-through;
}
-.spellcasting-entry.preparation ol.spell-list > li[data-expended-state=true] .cast-spell {
+.spellcasting-entry.preparation ol.spell-list > li[data-expended-state=true] .cast-spell button {
background: var(--color-disabled);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.5);
cursor: not-allowed;
@@ -9057,8 +8859,6 @@ body > .choices__list--dropdown {
margin-top: 2px;
}
.spellcasting-entry.preparation ol.spell-list > li.spell-level-header {
- margin: 0;
- padding: 0;
background: rgba(96, 88, 86, 0.25);
border: 1px solid var(--color-border-light-2);
border-radius: 2px;
@@ -9066,27 +8866,24 @@ body > .choices__list--dropdown {
font: 500 var(--font-size-12) var(--sans-serif);
letter-spacing: 0.25px;
line-height: 1;
- padding: 0 0.5em;
text-transform: uppercase;
}
.spellcasting-entry.preparation ol.spell-list > li.spell-level-header h3 {
text-transform: capitalize;
font-size: var(--font-size-13);
margin-left: 0;
- padding: 4px 0;
+ padding: 0.25rem 0;
}
.spellcasting-entry.preparation ol.spell-list > li.spell-level-header .item-name {
line-height: 1;
gap: 0.25em;
+ padding-left: 0.2em;
}
.spellcasting-entry.preparation ol.spell-list > li.spell-level-header .item-name h3 {
margin: 0;
padding: 0;
font-weight: 700;
}
-.spellcasting-entry.preparation ol.spell-list > li.spell-level-header .item-controls {
- grid-column: span 2;
-}
.spellcasting-entry.preparation ol.spell-list > li .uses {
align-items: center;
display: flex;
@@ -9121,11 +8918,14 @@ body > .choices__list--dropdown {
.spellcasting-entry.preparation ol.spell-list > li .item-name {
align-items: center;
display: flex;
+ flex: 1;
flex-wrap: nowrap;
- justify-content: start;
- justify-self: start;
min-height: 1.75rem;
}
+.spellcasting-entry.preparation ol.spell-list > li .item-name.empty {
+ color: var(--color-text-dark-secondary);
+ pointer-events: none;
+}
.spellcasting-entry.preparation ol.spell-list > li .item-name h3 {
white-space: nowrap;
}
@@ -9163,42 +8963,25 @@ body > .choices__list--dropdown {
letter-spacing: -0.075em;
line-height: 1;
margin-left: 8px;
- cursor: pointer;
}
-.spellcasting-entry.preparation ol.spell-list > li .item-name h4:hover {
+.spellcasting-entry.preparation ol.spell-list > li .item-name h4 > a:hover {
color: var(--secondary);
+ text-shadow: none;
}
.spellcasting-entry.preparation ol.spell-list > li .item-name .action-glyph {
margin-left: 4px;
font-size: small;
}
-.spellcasting-entry.preparation ol.spell-list > li .item-name.empty {
- grid-column: 1/span 4;
-}
.spellcasting-entry.preparation ol.spell-list > li .spell-range {
- grid-area: range;
+ flex: 0 0 6rem;
padding-left: 0.2em;
}
-.spellcasting-entry.preparation ol.spell-list > li .spell-components {
- grid-area: components;
- justify-self: right;
- padding: 0 0.5em;
-}
-.spellcasting-entry.preparation ol.spell-list > li .spell-components .tag {
- font: var(--font-size-12) var(--sans-serif-condensed);
-}
-.spellcasting-entry.preparation ol.spell-list > li .spell-cast {
- grid-area: cast-spell;
+.spellcasting-entry.preparation ol.spell-list > li .cast-spell {
+ flex: 0 0 3.5rem;
display: flex;
justify-content: center;
}
-.spellcasting-entry.preparation ol.spell-list > li .item-controls {
- grid-area: controls;
- display: flex;
- justify-self: end;
- padding-right: 0.25em;
-}
-.spellcasting-entry.preparation ol.spell-list > li button.cast-spell {
+.spellcasting-entry.preparation ol.spell-list > li .cast-spell button {
align-items: center;
background: var(--secondary);
border-radius: 2px;
@@ -9206,21 +8989,24 @@ body > .choices__list--dropdown {
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5);
color: var(--text-light);
cursor: pointer;
- display: flex;
font: 700 0.55rem var(--sans-serif);
- justify-self: center;
letter-spacing: 0.25px;
max-width: fit-content;
padding: 0.5em 1em;
text-transform: uppercase;
}
+.spellcasting-entry.preparation ol.spell-list > li .item-controls {
+ flex: 0 0 3.25rem;
+ display: flex;
+ justify-content: end;
+ padding-right: 0.25em;
+}
.spellcasting-entry.preparation ol.spell-list > li .item-summary {
- grid-area: content;
- width: 100%;
- padding: 8px;
+ background-color: var(--bg);
border-bottom: 1px solid var(--sub);
border-top: 1px solid #aca5a3;
- background-color: var(--bg);
+ flex: 100%;
+ padding: 0.5rem;
}
.spellcasting-entry.preparation ol.spell-list[data-category=spontaneous] .virtual {
position: relative;
@@ -9246,31 +9032,6 @@ body > .choices__list--dropdown {
background: var(--secondary);
position: relative;
}
-.spellcasting-entry.preparation ol.spell-list .spell .item-name {
- width: 100%;
-}
-.spellcasting-entry.preparation ol.spell-list input.toggle-signature-spell[type=checkbox] {
- width: 12px;
- height: 12px;
- margin: 0 2px 0 0;
- flex: 0 0 auto;
-}
-.spellcasting-entry.preparation ol.spell-list .spellbook-empty {
- display: flex;
- align-items: center;
- min-height: 28px;
- justify-content: flex-end;
-}
-.spellcasting-entry.preparation ol.spell-list .spellbook-empty h4 {
- margin: 0;
- white-space: nowrap;
- margin-right: auto;
-}
-.spellcasting-entry.preparation ol.spell-list .spellbook-empty a {
- flex: 0 1 0;
- white-space: nowrap;
- margin-left: 8px;
-}
.spellcasting-entry.preparation form {
display: flex;
flex-direction: column;
@@ -9309,9 +9070,6 @@ body > .choices__list--dropdown {
.spellcasting-entry.preparation .sheet-content .item-image {
cursor: pointer;
}
-.spellcasting-entry.preparation .sheet-content [hidden] {
- display: none;
-}
.currency {
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.3), inset 0 0 0 2px rgba(255, 255, 255, 0.2);
align-items: center;
@@ -9607,6 +9365,12 @@ body > .choices__list--dropdown {
.sheet.familiar .attacks-list li.attack .button-group .critical-button {
background-color: var(--primary);
}
+.sheet.familiar .actions-list li.action > .item-summary,
+.sheet.familiar .actions-list li.attack > .item-summary,
+.sheet.familiar .attacks-list li.action > .item-summary,
+.sheet.familiar .attacks-list li.attack > .item-summary {
+ flex-basis: 100%;
+}
.sheet.familiar .actions-list li.attack,
.sheet.familiar .attacks-list li.attack {
border-bottom: 1px solid var(--color-border-light-tertiary);
@@ -9640,10 +9404,6 @@ body > .choices__list--dropdown {
line-height: 1.125rem;
margin-right: 4px;
}
-.sheet.familiar .actions-list li.attack > .description,
-.sheet.familiar .attacks-list li.attack > .description {
- flex-basis: 100%;
-}
.sheet.familiar .actions-list li.action,
.sheet.familiar .attacks-list li.action {
display: flex;
@@ -9705,10 +9465,6 @@ body > .choices__list--dropdown {
.sheet.familiar .attacks-list li.action .tracking span {
white-space: nowrap;
}
-.sheet.familiar .actions-list li.action .item-summary,
-.sheet.familiar .attacks-list li.action .item-summary {
- flex-basis: 100%;
-}
.sheet.familiar form {
background: url("../assets/sheet/background.webp");
background-repeat: repeat-x, no-repeat;
@@ -10340,6 +10096,12 @@ body > .choices__list--dropdown {
.sheet.hazard .attacks-list li.attack .button-group .critical-button {
background-color: var(--primary);
}
+.sheet.hazard .actions-list li.action > .item-summary,
+.sheet.hazard .actions-list li.attack > .item-summary,
+.sheet.hazard .attacks-list li.action > .item-summary,
+.sheet.hazard .attacks-list li.attack > .item-summary {
+ flex-basis: 100%;
+}
.sheet.hazard .actions-list li.attack,
.sheet.hazard .attacks-list li.attack {
border-bottom: 1px solid var(--color-border-light-tertiary);
@@ -10373,10 +10135,6 @@ body > .choices__list--dropdown {
line-height: 1.125rem;
margin-right: 4px;
}
-.sheet.hazard .actions-list li.attack > .description,
-.sheet.hazard .attacks-list li.attack > .description {
- flex-basis: 100%;
-}
.sheet.hazard .actions-list li.action,
.sheet.hazard .attacks-list li.action {
display: flex;
@@ -10438,10 +10196,6 @@ body > .choices__list--dropdown {
.sheet.hazard .attacks-list li.action .tracking span {
white-space: nowrap;
}
-.sheet.hazard .actions-list li.action .item-summary,
-.sheet.hazard .attacks-list li.action .item-summary {
- flex-basis: 100%;
-}
.sheet.hazard ul,
.sheet.hazard ol {
margin: 0;
@@ -10484,10 +10238,6 @@ body > .choices__list--dropdown {
border: 1px solid black;
box-shadow: 0 0 10px #00005a;
}
-.sheet.hazard select {
- font-size: var(--font-size-12);
- height: 2em;
-}
.sheet.hazard .container {
display: flex;
background: linear-gradient(rgba(255, 255, 255, 0), rgba(255, 255, 255, 0));
@@ -10607,6 +10357,10 @@ body > .choices__list--dropdown {
width: 220px;
overflow: hidden scroll;
}
+.sheet.hazard .sidebar select {
+ font-size: var(--font-size-12);
+ height: 2em;
+}
.sheet.hazard .sidebar .sidebar-title {
display: flex;
justify-content: space-between;
@@ -10848,16 +10602,15 @@ body > .choices__list--dropdown {
align-items: center;
background: none;
cursor: default;
- display: grid;
- grid: "name range components cast-spell controls" auto "content content content content content" auto/9fr 4fr 4fr 2fr 2.5fr;
- justify-content: center;
- padding: 0 0.3em 1px 0.35em;
+ display: flex;
+ flex-wrap: wrap;
+ padding: 0 0.35em;
}
.actor.npc.sheet form ol.spell-list > li[data-expended-state=true] h4 {
color: var(--color-disabled);
text-decoration: line-through;
}
-.actor.npc.sheet form ol.spell-list > li[data-expended-state=true] .cast-spell {
+.actor.npc.sheet form ol.spell-list > li[data-expended-state=true] .cast-spell button {
background: var(--color-disabled);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.5);
cursor: not-allowed;
@@ -10873,8 +10626,6 @@ body > .choices__list--dropdown {
margin-top: 2px;
}
.actor.npc.sheet form ol.spell-list > li.spell-level-header {
- margin: 0;
- padding: 0;
background: rgba(96, 88, 86, 0.25);
border: 1px solid var(--color-border-light-2);
border-radius: 2px;
@@ -10882,27 +10633,24 @@ body > .choices__list--dropdown {
font: 500 var(--font-size-12) var(--sans-serif);
letter-spacing: 0.25px;
line-height: 1;
- padding: 0 0.5em;
text-transform: uppercase;
}
.actor.npc.sheet form ol.spell-list > li.spell-level-header h3 {
text-transform: capitalize;
font-size: var(--font-size-13);
margin-left: 0;
- padding: 4px 0;
+ padding: 0.25rem 0;
}
.actor.npc.sheet form ol.spell-list > li.spell-level-header .item-name {
line-height: 1;
gap: 0.25em;
+ padding-left: 0.2em;
}
.actor.npc.sheet form ol.spell-list > li.spell-level-header .item-name h3 {
margin: 0;
padding: 0;
font-weight: 700;
}
-.actor.npc.sheet form ol.spell-list > li.spell-level-header .item-controls {
- grid-column: span 2;
-}
.actor.npc.sheet form ol.spell-list > li .uses {
align-items: center;
display: flex;
@@ -10937,11 +10685,14 @@ body > .choices__list--dropdown {
.actor.npc.sheet form ol.spell-list > li .item-name {
align-items: center;
display: flex;
+ flex: 1;
flex-wrap: nowrap;
- justify-content: start;
- justify-self: start;
min-height: 1.75rem;
}
+.actor.npc.sheet form ol.spell-list > li .item-name.empty {
+ color: var(--color-text-dark-secondary);
+ pointer-events: none;
+}
.actor.npc.sheet form ol.spell-list > li .item-name h3 {
white-space: nowrap;
}
@@ -10979,42 +10730,25 @@ body > .choices__list--dropdown {
letter-spacing: -0.075em;
line-height: 1;
margin-left: 8px;
- cursor: pointer;
}
-.actor.npc.sheet form ol.spell-list > li .item-name h4:hover {
+.actor.npc.sheet form ol.spell-list > li .item-name h4 > a:hover {
color: var(--secondary);
+ text-shadow: none;
}
.actor.npc.sheet form ol.spell-list > li .item-name .action-glyph {
margin-left: 4px;
font-size: small;
}
-.actor.npc.sheet form ol.spell-list > li .item-name.empty {
- grid-column: 1/span 4;
-}
.actor.npc.sheet form ol.spell-list > li .spell-range {
- grid-area: range;
+ flex: 0 0 6rem;
padding-left: 0.2em;
}
-.actor.npc.sheet form ol.spell-list > li .spell-components {
- grid-area: components;
- justify-self: right;
- padding: 0 0.5em;
-}
-.actor.npc.sheet form ol.spell-list > li .spell-components .tag {
- font: var(--font-size-12) var(--sans-serif-condensed);
-}
-.actor.npc.sheet form ol.spell-list > li .spell-cast {
- grid-area: cast-spell;
+.actor.npc.sheet form ol.spell-list > li .cast-spell {
+ flex: 0 0 3.5rem;
display: flex;
justify-content: center;
}
-.actor.npc.sheet form ol.spell-list > li .item-controls {
- grid-area: controls;
- display: flex;
- justify-self: end;
- padding-right: 0.25em;
-}
-.actor.npc.sheet form ol.spell-list > li button.cast-spell {
+.actor.npc.sheet form ol.spell-list > li .cast-spell button {
align-items: center;
background: var(--secondary);
border-radius: 2px;
@@ -11022,21 +10756,24 @@ body > .choices__list--dropdown {
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5);
color: var(--text-light);
cursor: pointer;
- display: flex;
font: 700 0.55rem var(--sans-serif);
- justify-self: center;
letter-spacing: 0.25px;
max-width: fit-content;
padding: 0.5em 1em;
text-transform: uppercase;
}
+.actor.npc.sheet form ol.spell-list > li .item-controls {
+ flex: 0 0 3.25rem;
+ display: flex;
+ justify-content: end;
+ padding-right: 0.25em;
+}
.actor.npc.sheet form ol.spell-list > li .item-summary {
- grid-area: content;
- width: 100%;
- padding: 8px;
+ background-color: var(--bg);
border-bottom: 1px solid var(--sub);
border-top: 1px solid #aca5a3;
- background-color: var(--bg);
+ flex: 100%;
+ padding: 0.5rem;
}
.actor.npc.sheet form ol.spell-list[data-category=spontaneous] .virtual {
position: relative;
@@ -11062,42 +10799,15 @@ body > .choices__list--dropdown {
background: var(--secondary);
position: relative;
}
-.actor.npc.sheet form ol.spell-list .spell .item-name {
- width: 100%;
-}
-.actor.npc.sheet form ol.spell-list input.toggle-signature-spell[type=checkbox] {
- width: 12px;
- height: 12px;
- margin: 0 2px 0 0;
- flex: 0 0 auto;
-}
-.actor.npc.sheet form ol.spell-list .spellbook-empty {
- display: flex;
- align-items: center;
- min-height: 28px;
- justify-content: flex-end;
-}
-.actor.npc.sheet form ol.spell-list .spellbook-empty h4 {
- margin: 0;
- white-space: nowrap;
- margin-right: auto;
-}
-.actor.npc.sheet form ol.spell-list .spellbook-empty a {
- flex: 0 1 0;
- white-space: nowrap;
- margin-left: 8px;
-}
.actor.npc.sheet form .npc-sheet-header {
display: flex;
flex: 1 0 auto;
flex-direction: column;
}
.actor.npc.sheet form .npc-sheet-header .name {
- font-family: var(--sans-serif-condensed);
- font-size: 1.75rem;
- font-weight: 700;
- width: 100%;
flex-wrap: nowrap;
+ font: 700 1.75rem var(--sans-serif-condensed);
+ width: 100%;
}
.actor.npc.sheet form .npc-sheet-header .name input {
font-weight: inherit;
@@ -11105,7 +10815,7 @@ body > .choices__list--dropdown {
}
.actor.npc.sheet form .npc-sheet-header .name .name-value {
font-variant: small-caps;
- margin-left: 6px;
+ margin-left: 0.375rem;
margin-right: 1.125rem;
}
.actor.npc.sheet form .npc-sheet-header .name .level-label {
@@ -11118,7 +10828,7 @@ body > .choices__list--dropdown {
flex: 0 0 2.5rem;
text-align: center;
}
-.actor.npc.sheet form .npc-sheet-header .rarity-alignment-size {
+.actor.npc.sheet form .npc-sheet-header .rarity-size {
display: flex;
flex-direction: row;
justify-content: space-between;
@@ -11137,13 +10847,13 @@ body > .choices__list--dropdown {
}
.actor.npc.sheet form .sidebar .image-container img.actor-image {
border: none;
- border-radius: 8px;
+ border-radius: 0.5rem;
}
.actor.npc.sheet form .sidebar .armor-section .armor-value {
flex: 0;
text-align: right;
font-weight: 700;
- padding-right: 4px;
+ padding-right: 0.25rem;
}
.actor.npc.sheet form .sidebar .health-section .hit-points,
.actor.npc.sheet form .sidebar .shield-section .hit-points {
@@ -11154,7 +10864,7 @@ body > .choices__list--dropdown {
}
.actor.npc.sheet form .sidebar .health-section .hit-points input.current,
.actor.npc.sheet form .sidebar .shield-section .hit-points input.current {
- width: 36px;
+ width: 2.25rem;
text-align: right;
padding-right: 3px;
}
@@ -11168,20 +10878,23 @@ body > .choices__list--dropdown {
.actor.npc.sheet form .sidebar .health-section .hit-points .max,
.actor.npc.sheet form .sidebar .shield-section .hit-points .max {
font-weight: 700;
- margin-right: 4px;
+ margin-right: 0.25rem;
text-align: center;
}
.actor.npc.sheet form .sidebar .health-section .hit-points .max.lt10,
.actor.npc.sheet form .sidebar .shield-section .hit-points .max.lt10 {
- width: 8px;
+ width: 0.5rem;
}
.actor.npc.sheet form .sidebar .health-section .hit-points .max.lt100,
.actor.npc.sheet form .sidebar .shield-section .hit-points .max.lt100 {
- width: 24px;
+ width: 1.5rem;
}
.actor.npc.sheet form .sidebar .health-section .hit-points .max.lt1000,
.actor.npc.sheet form .sidebar .shield-section .hit-points .max.lt1000 {
- width: 36px;
+ width: 2.25rem;
+}
+.actor.npc.sheet form .sidebar .shield-section .hit-points .max {
+ font-size: var(--font-size-16);
}
.actor.npc.sheet form .sidebar .shield-section .shield-details {
display: flex;
@@ -11197,7 +10910,7 @@ body > .choices__list--dropdown {
.actor.npc.sheet form .sidebar .shield-section .shield-details .value {
flex: auto;
font-weight: normal;
- margin-left: 6px !important;
+ margin-left: 0.375rem;
}
.actor.npc.sheet form .sidebar .shield-section.broken {
color: rgba(0, 0, 0, 0.4);
@@ -11208,20 +10921,8 @@ body > .choices__list--dropdown {
.actor.npc.sheet form .sidebar .shield-section.broken .shield-label h4 {
text-decoration: line-through;
}
-.actor.npc.sheet form .sidebar .shield-section.broken .shield-value {
- color: rgba(0, 0, 0, 0.4);
-}
-.actor.npc.sheet form .sidebar .shield-section.broken .shield-value .shield-current {
- color: rgba(0, 0, 0, 0.4);
-}
-.actor.npc.sheet form .sidebar .shield-section.broken .shield-value .shield-max {
- color: rgba(0, 0, 0, 0.4);
-}
-.actor.npc.sheet form .sidebar .speed-section {
- text-align: left;
-}
.actor.npc.sheet form .sidebar .speed-section .land-speed-value {
- flex: 0 0 30px;
+ flex: 0 0 1.5rem;
text-align: right;
}
.actor.npc.sheet form .sidebar .speed-section .land-speed .speed-details {
@@ -11229,18 +10930,17 @@ body > .choices__list--dropdown {
}
.actor.npc.sheet form .sidebar .speed-section .other-speeds {
display: flex;
- justify-content: left;
- align-items: left;
- width: 100%;
flex-wrap: wrap;
+ justify-content: start;
+ width: 100%;
}
.actor.npc.sheet form .sidebar .saves {
- margin-top: 12px;
display: flex;
flex-direction: row;
- width: 100%;
flex: 1 0 auto;
font-size: 1.1rem;
+ margin-top: 12px;
+ width: 100%;
}
.actor.npc.sheet form .sidebar .saves .container {
display: flex;
@@ -11258,18 +10958,18 @@ body > .choices__list--dropdown {
display: flex;
flex: auto;
flex-direction: column;
- justify-content: flex-start;
- align-items: flex-start;
+ justify-content: start;
+ align-items: start;
}
.actor.npc.sheet form .side-bar-section .controls {
- padding-right: 4px;
+ padding-right: 0.25rem;
}
.actor.npc.sheet form .side-bar-section.initiative a.roll-init {
display: flex;
flex-wrap: nowrap;
font-weight: 700;
+ margin-bottom: 0.125rem;
margin-left: auto;
- margin-bottom: 2px;
padding-right: 0.5em;
}
.actor.npc.sheet form .side-bar-section.initiative a.roll-init i.fa-dice-d20 {
@@ -11288,38 +10988,37 @@ body > .choices__list--dropdown {
color: darkgrey;
}
.actor.npc.sheet form .side-bar-section-content {
+ align-items: start;
display: flex;
+ flex-flow: row wrap;
+ justify-content: start;
+ padding-top: 0.125rem;
width: 100%;
- flex-direction: row;
- flex-wrap: wrap;
- justify-content: flex-start;
- align-items: flex-start;
- padding-top: 2px;
}
.actor.npc.sheet form .side-bar-section-header {
- display: flex;
- width: 100%;
- font-size: 1rem;
+ align-items: baseline;
border-bottom: 1px solid;
border-color: #7a7971;
- margin-top: 10px;
- margin-bottom: 2px;
- align-items: baseline;
+ display: flex;
+ font-size: 1rem;
+ margin-bottom: 0.125rem;
+ margin-top: var(--font-size-10);
+ width: 100%;
}
.actor.npc.sheet form .side-bar-section-header .side-bar-label {
+ align-items: center;
display: flex;
- flex: auto;
flex-direction: row;
- align-items: center;
+ flex: auto;
}
-.actor.npc.sheet form .side-bar-section-header .side-bar-label .fa {
+.actor.npc.sheet form .side-bar-section-header .side-bar-label .fa-solid {
font-size: 0.8rem;
}
.actor.npc.sheet form .side-bar-section-header .side-bar-label h4,
.actor.npc.sheet form .side-bar-section-header .side-bar-label label {
font-size: 0.8rem;
- margin-bottom: 0px;
- padding-left: 2px;
+ margin-bottom: 0;
+ padding-left: 0.125rem;
}
.actor.npc.sheet form .side-bar-section-header .side-bar-label input.modifier {
font-size: 0.9rem;
@@ -11341,20 +11040,19 @@ body > .choices__list--dropdown {
.actor.npc.sheet form .sheet-body .tab .identification-skills ul li:not(:last-of-type):after {
content: ",";
}
-.actor.npc.sheet form .sheet-body .inventory {
+.actor.npc.sheet form .sheet-body .tab.inventory.active {
+ display: flex;
flex-basis: 100%;
flex-direction: column;
overflow-y: hidden;
padding-bottom: 1.25rem;
}
-.actor.npc.sheet form .sheet-body .inventory.active {
- display: flex;
-}
-.actor.npc.sheet form .sheet-body .inventory .inventory-section {
+.actor.npc.sheet form .sheet-body .tab.inventory.active .inventory-section {
max-height: calc(100% - 1rem);
}
-.actor.npc.sheet form .sheet-body .inventory .inventory-section .inventory-header {
- background-color: var(--primary-background);
+.actor.npc.sheet form .sheet-body .tab.inventory.active .inventory-section .coinage .wealth,
+.actor.npc.sheet form .sheet-body .tab.inventory.active .inventory-section header {
+ background: var(--primary-background);
}
.actor.npc.sheet form .sheet-body .entries-list {
list-style: none;
@@ -11707,6 +11405,12 @@ body > .choices__list--dropdown {
.actor.npc.sheet form .sheet-body .attacks-list li.attack .button-group .critical-button {
background-color: var(--primary);
}
+.actor.npc.sheet form .sheet-body .actions-list li.action > .item-summary,
+.actor.npc.sheet form .sheet-body .actions-list li.attack > .item-summary,
+.actor.npc.sheet form .sheet-body .attacks-list li.action > .item-summary,
+.actor.npc.sheet form .sheet-body .attacks-list li.attack > .item-summary {
+ flex-basis: 100%;
+}
.actor.npc.sheet form .sheet-body .actions-list li.attack,
.actor.npc.sheet form .sheet-body .attacks-list li.attack {
border-bottom: 1px solid var(--color-border-light-tertiary);
@@ -11740,10 +11444,6 @@ body > .choices__list--dropdown {
line-height: 1.125rem;
margin-right: 4px;
}
-.actor.npc.sheet form .sheet-body .actions-list li.attack > .description,
-.actor.npc.sheet form .sheet-body .attacks-list li.attack > .description {
- flex-basis: 100%;
-}
.actor.npc.sheet form .sheet-body .actions-list li.action,
.actor.npc.sheet form .sheet-body .attacks-list li.action {
display: flex;
@@ -11805,10 +11505,6 @@ body > .choices__list--dropdown {
.actor.npc.sheet form .sheet-body .attacks-list li.action .tracking span {
white-space: nowrap;
}
-.actor.npc.sheet form .sheet-body .actions-list li.action .item-summary,
-.actor.npc.sheet form .sheet-body .attacks-list li.action .item-summary {
- flex-basis: 100%;
-}
.actor.npc.sheet form input.adjustable:not(:focus),
.actor.npc.sheet form span.adjustable,
.actor.npc.sheet form div.adjustable {
@@ -11835,7 +11531,7 @@ body > .choices__list--dropdown {
}
.actor.npc.sheet form .trait {
flex: auto 0 0;
- padding: 4px;
+ padding: 0.25rem;
background: var(--primary);
border: 2px solid var(--color-border-trait);
color: var(--color-text-trait);
@@ -11845,23 +11541,22 @@ body > .choices__list--dropdown {
}
.actor.npc.sheet form .effects-list {
display: flex;
+ flex-flow: row wrap;
flex: 1 0 auto;
- flex-direction: row;
- flex-wrap: wrap;
width: 100%;
}
.actor.npc.sheet form .effects-list .separator {
- flex: 0 0 1px;
- height: 32px;
- margin-right: 4px;
border-left: 2px solid var(--color-rarity-common);
+ flex: 0 0 1px;
+ height: 2rem;
+ margin-right: 0.25rem;
}
.actor.npc.sheet form .effects-list > .effect {
display: flex;
- flex: 0 0 32px;
- height: 32px;
- margin-right: 4px;
- margin-bottom: 4px;
+ flex: 0 0 2rem;
+ height: 2rem;
+ margin-right: 0.25rem;
+ margin-bottom: 0.25rem;
border-bottom: none !important;
}
.actor.npc.sheet form .effects-list > .effect .item-image {
@@ -11869,7 +11564,7 @@ body > .choices__list--dropdown {
border: 1px solid var(--color-rarity-common);
border-bottom: 1px solid var(--color-rarity-common);
border-radius: 3px;
- width: 32px;
+ width: 2rem;
}
.actor.npc.sheet form .effects-list > .effect .item-image:hover {
border: 1px solid var(--text-light);
@@ -11918,7 +11613,7 @@ body > .choices__list--dropdown {
.actor.npc.sheet form .labelled-field input[type=number] {
flex: 0;
font-weight: normal;
- margin: 1px 4px;
+ margin: 1px 0.25rem;
margin-left: auto;
min-width: 2.5em;
padding-right: 1px;
@@ -11947,7 +11642,7 @@ body > .choices__list--dropdown {
flex-basis: 5em;
}
.actor.npc.sheet form .top-sections .senses .perception input {
- flex: 0 0 24px;
+ flex: 0 0 1.5rem;
z-index: 1;
}
.actor.npc.sheet form .top-sections .ability-scores {
@@ -11960,7 +11655,7 @@ body > .choices__list--dropdown {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.actor.npc.sheet form .top-sections .ability-scores .list input {
- flex: 0 0 24px;
+ flex: 0 0 1.5rem;
margin-right: 1em;
z-index: 1;
}
@@ -11975,25 +11670,24 @@ body > .choices__list--dropdown {
}
.actor.npc.sheet form .section-container.skills > .section-body .list {
display: flex;
- flex-direction: row;
- flex-wrap: wrap;
+ flex-flow: row wrap;
}
.actor.npc.sheet form .section-container.recall-knowledge .section-header {
align-items: center;
}
.actor.npc.sheet form .section-container.recall-knowledge .section-header .breakdown {
- width: auto;
- cursor: pointer;
- font-size: var(--font-size-9);
- line-height: var(--font-size-15);
- box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.3), inset 0 0 0 2px rgba(255, 255, 255, 0.2);
background: var(--secondary);
+ border-radius: 3px;
+ border: none;
+ box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.3), inset 0 0 0 2px rgba(255, 255, 255, 0.2);
color: var(--text-light);
+ cursor: pointer;
font-family: var(--sans-serif);
+ font-size: var(--font-size-9);
+ line-height: var(--font-size-15);
+ padding: 2px 0.25rem 0;
text-transform: uppercase;
- border-radius: 3px;
- border: none;
- padding: 2px 4px 0;
+ width: auto;
}
.actor.npc.sheet form .section-container.recall-knowledge .section-header .breakdown:hover {
box-shadow: none;
@@ -12004,7 +11698,7 @@ body > .choices__list--dropdown {
}
.actor.npc.sheet form select {
flex: auto 0 0;
- padding: 4px;
+ padding: 0.25rem;
height: auto;
font-weight: 500;
}
@@ -12037,88 +11731,86 @@ body > .choices__list--dropdown {
.actor.npc.sheet form .notes.active {
display: flex;
flex-direction: column;
+ font-size: var(--font-size-14);
gap: 0.5rem;
padding-bottom: 0.5rem;
padding-right: 0.75rem;
}
-.actor.npc.sheet form .notes .notes-section {
+.actor.npc.sheet form .notes.active .notes-section {
display: flex;
flex-direction: column;
}
-.actor.npc.sheet form .notes .notes-section > h4 {
+.actor.npc.sheet form .notes.active .notes-section > h4 {
color: var(--primary);
- font-family: var(--sans-serif);
- font-size: var(--font-size-11);
- font-weight: 700;
- line-height: 1;
+ font: 700 var(--font-size-12)/1em var(--sans-serif);
margin: 0 2px 0 0;
- padding: 4px;
+ padding: 0.25rem;
text-transform: uppercase;
white-space: nowrap;
}
-.actor.npc.sheet form .notes .notes-section > .notes-text {
- padding: 0 4px 4px;
+.actor.npc.sheet form .notes.active .notes-section > .notes-text {
+ padding: 0 0.25rem 0.25rem;
color: var(--text-dark);
flex-grow: 1;
}
-.actor.npc.sheet form .notes .notes-section > .notes-text .editor {
+.actor.npc.sheet form .notes.active .notes-section > .notes-text .editor {
height: 100%;
}
-.actor.npc.sheet form .notes .notes-section > .notes-text .editor .editor-content {
+.actor.npc.sheet form .notes.active .notes-section > .notes-text .editor .editor-content {
min-height: 75px;
}
-.actor.npc.sheet form .notes .notes-section > .notes-text .editor .editor-edit {
+.actor.npc.sheet form .notes.active .notes-section > .notes-text .editor .editor-edit {
background: var(--primary);
color: var(--text-light);
}
-.actor.npc.sheet form .notes .notes-section > .notes-text .editor a.editor-edit {
- padding: 2px 2px 2px 4px;
+.actor.npc.sheet form .notes.active .notes-section > .notes-text .editor a.editor-edit {
+ padding: 2px 2px 2px 0.25rem;
}
-.actor.npc.sheet form .notes .notes-section.publication {
+.actor.npc.sheet form .notes.active .notes-section.publication {
margin-top: auto;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text {
align-items: baseline;
gap: 0.25em;
display: grid;
grid-template: "title title title" 2fr "authors license remaster" 3fr/60% 20% 20%;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text label {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text label {
font-weight: 500;
min-width: unset;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text input[type=text] {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text input[type=text] {
height: 1.6rem;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .title {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .title {
grid-area: title;
margin-right: 0;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .authors {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .authors {
grid-area: authors;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .license {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .license {
grid-area: license;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .license select {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .license select {
margin-top: 1px;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .remaster {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .remaster {
grid-area: remaster;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .license,
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .remaster {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .license,
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .remaster {
text-align: center;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .license label,
-.actor.npc.sheet form .notes .notes-section.publication .notes-text .remaster label {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .license label,
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text .remaster label {
padding: 0;
}
-.actor.npc.sheet form .notes .notes-section.publication .notes-text input[type=text] {
+.actor.npc.sheet form .notes.active .notes-section.publication .notes-text input[type=text] {
background: rgba(0, 0, 0, 0.05);
padding: 1px 3px;
}
-.actor.npc.sheet form .notes .tox {
+.actor.npc.sheet form .notes.active .tox {
min-height: 20em;
}
.actor.npc.sheet form.dead .profile {
@@ -12285,16 +11977,16 @@ body > .choices__list--dropdown {
--border-color: var(--secondary-background);
margin-bottom: 2px;
}
+.sheet.actor.loot form section.content .inventory .inventory-list > header {
+ background: var(--primary-background);
+ color: var(--text-light);
+}
.sheet.actor.loot form section.content .inventory .inventory-list .item-controls {
flex: 0 0 4rem;
}
.sheet.actor.loot form section.content .inventory .inventory-list .item-controls a.item-toggle-equip {
display: none;
}
-.sheet.actor.loot form section.content .inventory .inventory-header {
- background: var(--primary-background);
- color: var(--text-light);
-}
.loot-actor-popup {
flex: unset;
}
@@ -12413,19 +12105,18 @@ body > .choices__list--dropdown {
margin-right: 0.125rem;
}
.sheet.party nav.sheet-navigation {
- display: inline-flex;
- justify-content: center;
- align-items: center;
- height: 20px;
- background: var(--secondary);
background: url("../assets/sheet/border-pattern.webp") repeat-x top, url("../assets/sheet/border-pattern.webp") repeat-x bottom, var(--secondary);
- transition: all 0.1s ease-out;
- box-shadow: 0 -1px 1px rgba(0, 0, 0, 0.25);
- border-top: 1px solid rgba(255, 255, 255, 0.1);
+ align-items: center;
border-bottom: 1px solid rgba(255, 255, 255, 0.5);
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
+ box-shadow: 0 -1px 1px rgba(0, 0, 0, 0.25);
+ display: inline-flex;
+ height: 1.25rem;
+ justify-content: center;
position: relative;
+ transition: all 0.1s ease-out;
}
-.sheet.party nav.sheet-navigation .navigation-title {
+.sheet.party nav.sheet-navigation .panel-title {
color: var(--text-light);
margin-right: auto;
padding-left: 1em;
@@ -12440,8 +12131,8 @@ body > .choices__list--dropdown {
font-size: var(--font-size-12);
}
.sheet.party nav.sheet-navigation .item {
- height: 24px;
- width: 24px;
+ height: 1.5rem;
+ width: 1.5rem;
border-radius: 50%;
z-index: 1;
transition: all 0.1s ease-out;
@@ -12465,7 +12156,7 @@ body > .choices__list--dropdown {
fill: var(--text-light);
background-image: url("../assets/sheet/nav-item.webp");
}
-.sheet.party nav.sheet-navigation .item .fas {
+.sheet.party nav.sheet-navigation .item i.fa-solid {
padding-bottom: 0;
}
.sheet.party nav.sheet-navigation .item:hover .pfs-icon {
@@ -12477,15 +12168,15 @@ body > .choices__list--dropdown {
.sheet.party nav.sub-nav {
margin: 0;
padding: 0;
+ align-items: center;
+ background-color: var(--bg);
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18);
display: flex;
flex-wrap: nowrap;
+ flex: 0 0 2.5rem;
justify-content: center;
- align-items: center;
list-style: none;
- background-color: var(--bg);
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18);
width: 100%;
- flex: 0 0 2.5rem;
}
.sheet.party nav.sub-nav::before, .sheet.party nav.sub-nav::after {
content: "";
@@ -12530,7 +12221,7 @@ body > .choices__list--dropdown {
text-shadow: 0 0 3px rgba(255, 255, 255, 0.5);
}
.sheet.party .tab nav.sub-nav {
- padding-right: 20px;
+ padding-right: 1.25rem;
}
.sheet.party .actor-link {
cursor: pointer;
@@ -12852,9 +12543,6 @@ body > .choices__list--dropdown {
.sheet.party [data-tab=overview] .summary .skills {
margin: 0;
}
-.sheet.party [data-tab=overview] .summary [hidden] {
- display: none;
-}
.sheet.party [data-tab=overview] .skills {
display: flex;
flex-wrap: wrap;
@@ -13401,19 +13089,18 @@ body > .choices__list--dropdown {
background: var(--sidebar-title);
}
.sheet.kingdom nav.sheet-navigation {
- display: inline-flex;
- justify-content: center;
- align-items: center;
- height: 20px;
- background: var(--secondary);
background: url("../assets/sheet/border-pattern.webp") repeat-x top, url("../assets/sheet/border-pattern.webp") repeat-x bottom, var(--secondary);
- transition: all 0.1s ease-out;
- box-shadow: 0 -1px 1px rgba(0, 0, 0, 0.25);
- border-top: 1px solid rgba(255, 255, 255, 0.1);
+ align-items: center;
border-bottom: 1px solid rgba(255, 255, 255, 0.5);
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
+ box-shadow: 0 -1px 1px rgba(0, 0, 0, 0.25);
+ display: inline-flex;
+ height: 1.25rem;
+ justify-content: center;
position: relative;
+ transition: all 0.1s ease-out;
}
-.sheet.kingdom nav.sheet-navigation .navigation-title {
+.sheet.kingdom nav.sheet-navigation .panel-title {
color: var(--text-light);
margin-right: auto;
padding-left: 1em;
@@ -13428,8 +13115,8 @@ body > .choices__list--dropdown {
font-size: var(--font-size-12);
}
.sheet.kingdom nav.sheet-navigation .item {
- height: 24px;
- width: 24px;
+ height: 1.5rem;
+ width: 1.5rem;
border-radius: 50%;
z-index: 1;
transition: all 0.1s ease-out;
@@ -13453,7 +13140,7 @@ body > .choices__list--dropdown {
fill: var(--text-light);
background-image: url("../assets/sheet/nav-item.webp");
}
-.sheet.kingdom nav.sheet-navigation .item .fas {
+.sheet.kingdom nav.sheet-navigation .item i.fa-solid {
padding-bottom: 0;
}
.sheet.kingdom nav.sheet-navigation .item:hover .pfs-icon {
@@ -13465,15 +13152,15 @@ body > .choices__list--dropdown {
.sheet.kingdom nav.sub-nav {
margin: 0;
padding: 0;
+ align-items: center;
+ background-color: var(--bg);
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18);
display: flex;
flex-wrap: nowrap;
+ flex: 0 0 2.5rem;
justify-content: center;
- align-items: center;
list-style: none;
- background-color: var(--bg);
- box-shadow: 0 2px 4px rgba(0, 0, 0, 0.18);
width: 100%;
- flex: 0 0 2.5rem;
}
.sheet.kingdom nav.sub-nav::before, .sheet.kingdom nav.sub-nav::after {
content: "";
@@ -13518,7 +13205,7 @@ body > .choices__list--dropdown {
text-shadow: 0 0 3px rgba(255, 255, 255, 0.5);
}
.sheet.kingdom .tab nav.sub-nav {
- padding-right: 20px;
+ padding-right: 1.25rem;
}
.sheet.kingdom .container {
height: 100%;
@@ -13538,9 +13225,6 @@ body > .choices__list--dropdown {
display: flex;
height: 100%;
}
-.sheet.kingdom [hidden] {
- display: none !important;
-}
.sheet.kingdom .drag-gap {
visibility: hidden;
}
@@ -13602,6 +13286,10 @@ body > .choices__list--dropdown {
padding: 0;
margin: 0;
}
+.sheet.kingdom .directory-list h4 > a:hover {
+ color: var(--color-pf-primary);
+ text-shadow: 0 0 3px var(--tertiary);
+}
.sheet.kingdom .effects .directory-list {
gap: 0.2em;
display: flex;
@@ -13694,35 +13382,29 @@ body > .choices__list--dropdown {
.sheet.kingdom .effects .directory-list .item .item-summary {
margin-top: 8px;
}
-.sheet.kingdom h3.header {
- position: relative;
- margin-top: 0.75em;
- font-size: var(--font-size-16);
- font-family: var(--serif);
- font-weight: 600;
- color: var(--primary);
- line-height: 1;
+.sheet.kingdom section.major > header {
border-bottom: 1px solid var(--color-border-divider);
+ color: var(--primary);
+ font: 600 var(--font-size-16)/1 var(--serif);
+ position: relative;
+ margin: 0.75rem 0 0.5rem 0;
}
-.sheet.kingdom h3.header > button, .sheet.kingdom h3.header > .controls {
+.sheet.kingdom section.major > header > button, .sheet.kingdom section.major > header > .controls {
position: absolute;
bottom: -1px;
right: 0;
}
-.sheet.kingdom h3.header .controls {
+.sheet.kingdom section.major > header .controls {
display: flex;
}
-.sheet.kingdom h3.header button {
+.sheet.kingdom section.major > header button {
background: transparent;
border-radius: 2px 2px 0 0;
border: 1px solid var(--color-border-divider);
color: var(--primary);
cursor: pointer;
- font-family: var(--sans-serif);
- font-size: var(--font-size-12);
- font-weight: 500;
+ font: 500 var(--font-size-12)/1 var(--sans-serif);
height: 20px;
- line-height: var(--font-size-12);
margin: 0;
outline: none;
text-transform: uppercase;
@@ -14096,19 +13778,19 @@ body > .choices__list--dropdown {
.sheet.kingdom .tab.active[data-tab=activities] .actions {
flex: 1;
}
-.sheet.kingdom .tab.active[data-tab=activities] .actions h3.header .filters {
+.sheet.kingdom .tab.active[data-tab=activities] .actions header .filters {
float: right;
margin: -0.125rem 0 0.125rem auto;
}
-.sheet.kingdom .tab.active[data-tab=activities] .actions h3.header .filters .choice {
+.sheet.kingdom .tab.active[data-tab=activities] .actions header .filters .choice {
cursor: pointer;
opacity: 0.6;
transition: opacity 0.2s ease-in-out;
}
-.sheet.kingdom .tab.active[data-tab=activities] .actions h3.header .filters .choice.active {
+.sheet.kingdom .tab.active[data-tab=activities] .actions header .filters .choice.active {
opacity: 1;
}
-.sheet.kingdom .tab.active[data-tab=activities] .actions h3.header .filters .choice:hover {
+.sheet.kingdom .tab.active[data-tab=activities] .actions header .filters .choice:hover {
box-shadow: 0 0 5px var(--primary);
}
.sheet.kingdom .tab.active[data-tab=activities] .actions .phase-summary {
@@ -14341,13 +14023,12 @@ body > .choices__list--dropdown {
margin-right: 4px;
}
.sheet.kingdom .tab.active[data-tab=features] .feat-item .item-name h4 {
- cursor: pointer;
display: flex;
align-items: center;
font-family: var(--serif);
}
-.sheet.kingdom .tab.active[data-tab=features] .feat-item .item-name h4:hover {
- color: var(--primary);
+.sheet.kingdom .tab.active[data-tab=features] .feat-item .item-name h4 a:hover {
+ color: var(--color-pf-primary);
text-shadow: 0 0 3px var(--tertiary);
}
.sheet.kingdom .tab.active[data-tab=features] .feat-item .item-name .item-image {
@@ -14396,7 +14077,7 @@ body > .choices__list--dropdown {
}
.sheet.kingdom .tab.active[data-tab=features] .feat-item ol.nested-items {
grid-column: span 2;
- border-left: 3px dotted #786452;
+ border-left: 3px dotted var(--alt);
display: flex;
margin: 1px 0 0 45px;
padding: 0;
@@ -14469,16 +14150,16 @@ body > .choices__list--dropdown {
.sheet.kingdom .tab.active[data-tab=ongoing] .events .event-details .editor {
flex: 1;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects {
width: 18rem;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside > h3.header {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects > header {
margin-top: 0;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list {
gap: 0.2em;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item {
display: flex;
flex-wrap: wrap;
align-items: center;
@@ -14486,44 +14167,44 @@ body > .choices__list--dropdown {
padding: 2px 4px 2px 12px;
width: 100%;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item p:empty {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item p:empty {
display: none;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .item-name {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .item-name {
display: flex;
align-items: center;
flex: 1;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .item-name h4 {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .item-name h4 {
cursor: pointer;
margin: 0;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .item-name .item-image {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .item-name .item-image {
margin-right: 8px;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .item-controls {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .item-controls {
display: flex;
flex: 0;
font-size: var(--font-size-12);
gap: 1px;
white-space: nowrap;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .item-controls a.info-only:hover {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .item-controls a.info-only:hover {
cursor: default;
text-shadow: none;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .item-controls a + a {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .item-controls a + a {
margin-left: 4px;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .item-summary {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .item-summary {
flex-basis: 100%;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item.unidentified {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item.unidentified {
border-radius: 1px;
outline: 1px dotted rgba(75, 74, 68, 0.5);
background: var(--visibility-gm-bg);
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .button-group {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .button-group {
display: flex;
justify-content: flex-end;
align-items: center;
@@ -14531,7 +14212,7 @@ body > .choices__list--dropdown {
width: 50%;
flex: 0;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .button-group button {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .button-group button {
margin: 0;
border: none;
cursor: pointer;
@@ -14551,11 +14232,11 @@ body > .choices__list--dropdown {
margin-left: 4px;
flex: 0;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item .button-group button:hover {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item .button-group button:hover {
box-shadow: none;
text-shadow: 0 0 2px white;
}
-.sheet.kingdom .tab.active[data-tab=ongoing] aside .effects-list .item {
+.sheet.kingdom .tab.active[data-tab=ongoing] section.effects .effects-list .item {
padding-left: 0;
}
.sheet.kingdom-builder .window-content {
@@ -14881,7 +14562,7 @@ body > .choices__list--dropdown {
box-shadow: none;
cursor: not-allowed;
}
-.sheet.kingdom-builder .ability-builder .row-column button i.fas {
+.sheet.kingdom-builder .ability-builder .row-column button i.fa-solid {
font-size: var(--font-size-10);
left: 0.5em;
position: absolute;
@@ -15002,7 +14683,7 @@ body > .choices__list--dropdown {
font-size: var(--font-size-12);
margin-top: -0.25rem;
}
-.sheet.kingdom-builder .ability-builder .extra .fas {
+.sheet.kingdom-builder .ability-builder .extra i.fa-solid {
margin-left: 0.125rem;
}
.sheet.kingdom-builder .ability-builder .extra input[type=checkbox] {
@@ -15022,185 +14703,603 @@ body > .choices__list--dropdown {
justify-content: center;
padding: 0.25rem 0;
}
-/* Mystification data revealed to GMs */
-.gm-mystified-data {
- opacity: 0.75;
-}
-#compendium-browser > section.window-content > .content-box,
-#license-viewer > section.window-content > .content-box {
- flex: 1;
+.sheet.army form {
+ display: grid;
+ grid-template: "header header" min-content "sidebar content" 1fr/min-content 1fr;
overflow: hidden;
- height: inherit;
+ background: url("../assets/sheet/background.webp");
+ background-repeat: no-repeat;
+ background-size: cover;
+ background-attachment: local;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-],
-#license-viewer > section.window-content > .content-box div[class^=slider-] {
- height: 10px;
- width: 80%;
- border: 1px solid black;
+.sheet.army form input[type=text],
+.sheet.army form input[type=number] {
+ background: rgba(0, 0, 0, 0.03);
+ border: 1px solid transparent;
+ padding: 0 4px;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base {
- background: #dddddd;
+.sheet.army form input[type=text]:hover:not(:disabled), .sheet.army form input[type=text]:focus,
+.sheet.army form input[type=number]:hover:not(:disabled),
+.sheet.army form input[type=number]:focus {
+ border: 1px solid black;
+ box-shadow: 0 0 10px #00005a;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle {
- background: none;
- border: none;
- box-shadow: none;
- color: var(--text-light);
- cursor: grab;
- font-size: var(--font-size-16);
- height: 14px;
- right: -7px;
- text-shadow: 0 0 4px black;
- top: -4px;
- width: 14px;
+.sheet.army form input.adjusted-higher {
+ color: #009988;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle:active,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle:active {
- cursor: grabbing;
+.sheet.army form input.adjusted-lower {
+ color: #cc3311;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle.handle,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle.handle {
- background: #c85019;
- border-radius: 2px;
- border: 1px solid black;
- box-shadow: 1px 1px 4px black;
+.sheet.army form > header {
+ background: url("../assets/sheet/header-bw.webp"), url("../assets/sheet/background.webp");
+ background-repeat: repeat-x, no-repeat;
+ background-size: cover;
+ background-color: #d9d3d2;
+ background-blend-mode: multiply;
+ color: var(--text-light);
+ align-items: center;
+ display: flex;
+ grid-area: header;
+ gap: 0.5rem;
+ min-height: 5.5rem;
+ padding: 0 0.75rem;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle::before, #compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle::after,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle::before,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle::after {
- background: none;
+.sheet.army form > header .frame {
+ position: relative;
+ width: 4rem;
+ height: 4rem;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle .noUi-touch-area,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle .noUi-touch-area {
+.sheet.army form > header .frame img {
+ object-fit: cover;
+ object-position: top;
+ border: none;
+ border-radius: 0;
+ width: 4rem;
+ height: 4rem;
cursor: pointer;
+ border: none;
+ box-shadow: 0 0 0 1px #918c88, 0 0 0 2px #e1d8cf, 0 0 0 3px #a98f39, inset 0 0 8px rgba(0, 0, 0, 0.5), 0 0 8px black;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-tooltip,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-tooltip {
- display: none;
+.sheet.army form > header .details {
+ display: grid;
+ flex: 1;
+ align-items: center;
+ grid-template: "name level" min-content "traits alliance" min-content/1fr min-content;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-active .noUi-tooltip,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-active .noUi-tooltip {
- display: block;
- background-color: rgba(0, 0, 0, 0.9);
+.sheet.army form > header .details input[type=text],
+.sheet.army form > header .details input[type=number] {
color: var(--text-light);
- line-height: 18px;
- padding: 6px 14px;
+ border: none;
+ border-bottom: 1px solid transparent;
+ padding: 0;
+ height: unset;
}
-#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-connect.range_selected,
-#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-connect.range_selected {
- background: rgba(255, 255, 240, 0.8);
+.sheet.army form > header .details input[type=text]:hover, .sheet.army form > header .details input[type=text]:focus,
+.sheet.army form > header .details input[type=number]:hover,
+.sheet.army form > header .details input[type=number]:focus {
+ border: none;
+ border-bottom: 1px solid var(--text-light);
+ box-shadow: none;
}
-#compendium-browser > section.window-content > .content-box > nav,
-#license-viewer > section.window-content > .content-box > nav {
- border-style: solid;
- border-image-outset: 0;
- border-width: 9px;
- border-image: url("../assets/sheet/corner-box.webp") 9 repeat;
- box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);
- flex: 0;
+.sheet.army form > header .details input[type=text]::placeholder,
+.sheet.army form > header .details input[type=number]::placeholder {
+ color: #bbb;
+ opacity: 0.4;
+}
+.sheet.army form > header .details .name {
+ grid-area: name;
+ font-family: var(--sans-serif-condensed);
+ font-size: var(--font-size-30);
+ font-weight: 700;
width: 100%;
- display: inline-flex;
- justify-content: space-evenly;
- align-items: center;
- background: var(--secondary);
- background: url("../assets/sheet/border-pattern.webp") repeat-x top, url("../assets/sheet/border-pattern.webp") repeat-x bottom, var(--secondary);
+ max-width: calc(100% - 5.5rem);
+ font-variant: small-caps;
+ text-indent: 0.5rem;
+ margin-right: 18px;
}
-#compendium-browser > section.window-content > .content-box > nav > a,
-#license-viewer > section.window-content > .content-box > nav > a {
- color: var(--sidebar-label);
- padding: 4px 0;
- font-family: var(--sans-serif);
- font-size: var(--font-size-12);
- position: relative;
+.sheet.army form > header .details .tags {
+ grid-area: traits;
+ padding: 0 0.5rem;
}
-#compendium-browser > section.window-content > .content-box > nav > a.active::after,
-#license-viewer > section.window-content > .content-box > nav > a.active::after {
- bottom: -2px;
- right: 39%;
- position: absolute;
- content: "";
- width: 0;
- height: 0;
- border-left: 4px solid transparent;
- border-right: 4px solid transparent;
- border-top: 4px solid var(--sidebar-label);
+.sheet.army form > header .details .tags .alignment {
+ background-color: #576293;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings {
- height: 100%;
+.sheet.army form > header .details .level-label {
+ grid-area: level;
+ align-self: end;
+ display: block;
+ font-family: var(--serif-condensed);
+ font-size: var(--font-size-28);
+ font-weight: 700;
+ min-width: 9rem;
+ text-align: right;
+ text-transform: uppercase;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form {
+.sheet.army form > header .details .level-label input.level {
+ width: 2ch;
+ text-align: center;
+ margin: 0 0.25rem;
+}
+.sheet.army form > header .details .alliance {
+ grid-area: alliance;
+ align-self: start;
+ margin-right: 0.25rem;
+ opacity: 0.8;
+ text-align: right;
+}
+.sheet.army form > header .details .alliance i {
+ font-size: 0.9em;
+ margin-left: 0.5rem;
+}
+.sheet.army form > header .details .alliance .error {
+ color: #ff5555;
+}
+.sheet.army form .army-sidebar {
display: flex;
- height: 88%;
flex-direction: column;
- margin-bottom: 10px;
+ gap: 1rem;
+ overflow: hidden scroll;
+ padding: 0.75rem 0.25rem 0.5rem 0.5rem;
+ width: 11rem;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section {
- border: 1px solid #bbb;
- border-radius: 5px;
- margin-top: 5px;
- padding: 2px;
- /* Checkbox */
+.sheet.army form .army-sidebar input {
+ flex: 0;
+ min-width: 5ch;
+ text-align: right;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section h3,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section h3 {
- margin: 0;
- cursor: pointer;
+.sheet.army form .army-sidebar input[type=checkbox] {
+ font-size: var(--font-size-10);
+ height: 12px;
+ margin: 2px;
+ padding: 0;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section dt,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section dt {
- width: 10%;
+.sheet.army form .army-sidebar header {
+ border-bottom: 1px solid var(--color-border-divider);
+ color: var(--primary);
+ display: flex;
+ flex-direction: row;
+ justify-content: space-between;
+ align-items: baseline;
+ line-height: 18px;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section dt > input[type=checkbox],
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section dt > input[type=checkbox] {
- transform: none;
- flex: none;
- height: auto;
- margin: 3px 3px;
+.sheet.army form .army-sidebar header input {
+ text-align: right;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section dd,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section dd {
- width: 88%;
+.sheet.army form .army-sidebar header h4 {
+ font-size: var(--font-size-15);
+ font-family: var(--serif);
+ font-weight: 600;
+ margin-bottom: 0px;
+ padding-left: 4px;
+ width: 100%;
+ text-align: left;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form dl,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form dl {
- margin: 5px 0;
+.sheet.army form .army-sidebar > section > label,
+.sheet.army form .army-sidebar > section .row {
+ align-items: baseline;
+ display: flex;
+ gap: 0.25rem;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form dt,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form dt {
- display: inline-block;
- width: 40%;
- padding-left: 5px;
+.sheet.army form .army-sidebar > section > label span:first-child,
+.sheet.army form .army-sidebar > section .row span:first-child {
+ flex: 1;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form dd,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form dd {
- display: inline-block;
- width: 58%;
- margin-left: 0;
+.sheet.army form .army-sidebar > section > label input,
+.sheet.army form .army-sidebar > section .row input {
+ width: 3em;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .settings-container,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form .settings-container {
- overflow-y: auto;
+.sheet.army form .army-sidebar > section .gear {
+ align-items: center;
+ gap: 0.5rem;
+}
+.sheet.army form .army-sidebar > section .gear span.disabled {
+ opacity: 0.4;
+}
+.sheet.army form .army-sidebar .saves {
display: flex;
- flex-wrap: wrap;
+ font-size: var(--font-size-17);
+ gap: 0.25rem;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .settings-container .tab[data-tab].active,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form .settings-container .tab[data-tab].active {
+.sheet.army form .army-sidebar .saves .save {
display: flex;
- flex-direction: row;
- flex-wrap: wrap;
- justify-content: center;
- width: 100%;
+ flex-direction: column;
+ align-items: center;
+ flex: 1 0 0;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .settings-container .single-column,
-#license-viewer > section.window-content > .content-box .compendium-browser-settings form .settings-container .single-column {
- width: 100%;
+.sheet.army form .army-sidebar .saves .save label {
+ font-weight: 600;
}
-#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .settings-container h2,
+.sheet.army form .army-sidebar .saves .save input.modifier {
+ text-align: center;
+ z-index: 1;
+}
+.sheet.army form .army-sidebar .senses.tags {
+ margin-top: 0.125rem;
+ flex-direction: row-reverse;
+}
+.sheet.army form section.army-body {
+ grid-area: content;
+ display: flex;
+ flex-direction: column;
+ padding: 0.75rem 0.5rem;
+ overflow: auto;
+ gap: 0.5rem;
+}
+.sheet.army form section.army-body fieldset {
+ border: 1px solid #5e0000;
+ border-radius: 3px;
+ padding: 0 0.75rem 0.5rem 0.75rem;
+}
+.sheet.army form section.army-body fieldset legend {
+ align-items: baseline;
+ color: var(--primary);
+ display: flex;
+ font-size: var(--font-size-15);
+ font-family: var(--serif);
+ font-weight: 600;
+ gap: 0.25rem;
+ margin-bottom: -0.125rem;
+}
+.sheet.army form section.army-body fieldset legend .item-controls {
+ margin-left: 0.125rem;
+ font-size: 0.8em;
+}
+.sheet.army form section.army-body .toggles input[type=checkbox] {
+ width: 1rem;
+ height: 1rem;
+}
+.sheet.army form section.army-body label {
+ display: flex;
+ align-items: center;
+ position: relative;
+}
+.sheet.army form section.army-body .editor .editor-edit {
+ display: none;
+}
+.sheet.army form section.army-body .weapons {
+ display: flex;
+ flex-direction: column;
+}
+.sheet.army form section.army-body .weapons .ammunition {
+ display: flex;
+ font-size: 0.9em;
+ gap: 0.125rem;
+ margin-left: 0.25rem;
+}
+.sheet.army form section.army-body .weapons .ammunition .pips {
+ margin: 0 0.375rem;
+}
+.sheet.army form section.army-body .weapons .strike {
+ align-items: center;
+ display: flex;
+ flex: 0;
+ gap: 0.25rem;
+ line-height: 1.5rem;
+}
+.sheet.army form section.army-body .weapons .strike input.name {
+ flex: 1;
+ text-indent: 0.25rem;
+ height: 1.5rem;
+}
+.sheet.army form ol.item-list {
+ list-style-type: none;
+ padding: 0;
+}
+.sheet.army form ol.item-list li.item {
+ align-items: center;
+ display: flex;
+ line-height: 1.5rem;
+ flex-wrap: wrap;
+}
+.sheet.army form ol.item-list li.item:nth-child(odd) {
+ background: rgba(180, 175, 175, 0.25);
+}
+.sheet.army form ol.item-list li.item.expanded {
+ flex-wrap: wrap;
+}
+.sheet.army form ol.item-list li.item.expanded .tags {
+ line-height: 1rem;
+ padding: 0.5rem 0 0 0;
+}
+.sheet.army form ol.item-list li.item .item-icon {
+ border-radius: 6px;
+ border: none;
+ height: 1.5rem;
+ width: 1.5rem;
+ position: relative;
+}
+.sheet.army form ol.item-list li.item .item-name {
+ display: flex;
+ text-indent: 0.5rem;
+ flex: 1 1;
+ margin: auto 0;
+ font-weight: bold;
+ width: 100%;
+}
+.sheet.army form ol.item-list li.item .item-frequency {
+ flex: 0.2 0 4rem;
+ gap: 0.25rem;
+ display: flex;
+}
+.sheet.army form ol.item-list li.item .item-frequency input {
+ text-align: right;
+}
+.sheet.army form ol.item-list li.item .item-frequency input,
+.sheet.army form ol.item-list li.item .item-frequency span {
+ flex: 1;
+ margin: auto;
+}
+.sheet.army form ol.item-list li.item .item-controls i {
+ flex: 0 0 4rem;
+}
+.sheet.army form .item-summary {
+ color: var(--text-dark);
+ font-size: var(--font-size-12);
+ padding: 0.25rem 0.5rem;
+ flex: 100%;
+}
+.sheet.army form .pips,
+.sheet.army form .pips span {
+ align-items: center;
+ height: 24px;
+ display: flex;
+ flex-flow: row nowrap;
+ justify-content: center;
+}
+.sheet.army form .pips i,
+.sheet.army form .pips span i {
+ opacity: 0.4;
+}
+.sheet.army form .pips .filled,
+.sheet.army form .pips span .filled {
+ opacity: 1;
+}
+.sheet.army form .pips .split + *,
+.sheet.army form .pips span .split + * {
+ margin-left: 0.25rem;
+}
+.sheet.army form button.attack,
+.sheet.army form button.damage {
+ align-items: center;
+ border: none;
+ border-radius: 2px;
+ box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.5);
+ color: var(--color-text-trait);
+ display: inline-flex;
+ flex: 0;
+ font-family: var(--sans-serif);
+ font-size: var(--font-size-10);
+ font-weight: 500;
+ gap: 2px;
+ height: 1.25rem;
+ letter-spacing: 0.05em;
+ line-height: unset;
+ margin: 0;
+ padding: 0 0.5em;
+ text-rendering: optimizeLegibility;
+ text-transform: uppercase;
+ white-space: nowrap;
+}
+.sheet.army form button.attack.attack,
+.sheet.army form button.damage.attack {
+ background-color: var(--secondary);
+}
+.sheet.army form button.attack.damage,
+.sheet.army form button.damage.damage {
+ background-color: var(--primary);
+}
+.sheet.army form button.attack:disabled,
+.sheet.army form button.damage:disabled {
+ background-color: var(--color-text-dark-3);
+ opacity: 0.8;
+}
+.sheet.army form button.attack:not(:disabled):hover,
+.sheet.army form button.damage:not(:disabled):hover {
+ box-shadow: none;
+ text-shadow: 0 0 2px var(--text-light);
+}
+.sheet.army form section.roll {
+ display: flex;
+ align-items: center;
+ min-width: 4rem;
+ justify-content: space-between;
+}
+.sheet.army form section.roll i {
+ min-width: 1.5rem;
+ font-size: 1rem;
+}
+.sheet.army form span.plus {
+ font-size: 0.75rem;
+}
+.sheet.army form legend.compendium-items:hover {
+ cursor: pointer;
+ text-shadow: 0 0 5px var(--color-shadow-highlight);
+}
+.sheet.army form .placeholder {
+ color: gray;
+}
+.sheet.army form .routed {
+ color: darkred;
+}
+/* Mystification data revealed to GMs */
+.gm-mystified-data {
+ opacity: 0.75;
+}
+#compendium-browser > section.window-content > .content-box,
+#license-viewer > section.window-content > .content-box {
+ flex: 1;
+ overflow: hidden;
+ height: inherit;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-],
+#license-viewer > section.window-content > .content-box div[class^=slider-] {
+ height: 10px;
+ width: 80%;
+ border: 1px solid black;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base {
+ background: #dddddd;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle {
+ background: none;
+ border: none;
+ box-shadow: none;
+ color: var(--text-light);
+ cursor: grab;
+ font-size: var(--font-size-16);
+ height: 14px;
+ right: -7px;
+ text-shadow: 0 0 4px black;
+ top: -4px;
+ width: 14px;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle:active,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle:active {
+ cursor: grabbing;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle.handle,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle.handle {
+ background: #c85019;
+ border-radius: 2px;
+ border: 1px solid black;
+ box-shadow: 1px 1px 4px black;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle::before, #compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle::after,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle::before,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle::after {
+ background: none;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle .noUi-touch-area,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-origin .noUi-handle .noUi-touch-area {
+ cursor: pointer;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-tooltip,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-tooltip {
+ display: none;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-active .noUi-tooltip,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-active .noUi-tooltip {
+ display: block;
+ background-color: rgba(0, 0, 0, 0.9);
+ color: var(--text-light);
+ line-height: 18px;
+ padding: 6px 14px;
+}
+#compendium-browser > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-connect.range_selected,
+#license-viewer > section.window-content > .content-box div[class^=slider-] .noUi-base .noUi-connect.range_selected {
+ background: rgba(255, 255, 240, 0.8);
+}
+#compendium-browser > section.window-content > .content-box > nav,
+#license-viewer > section.window-content > .content-box > nav {
+ border-style: solid;
+ border-image-outset: 0;
+ border-width: 9px;
+ border-image: url("../assets/sheet/corner-box.webp") 9 repeat;
+ box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);
+ flex: 0;
+ width: 100%;
+ display: inline-flex;
+ justify-content: space-evenly;
+ align-items: center;
+ background: var(--secondary);
+ background: url("../assets/sheet/border-pattern.webp") repeat-x top, url("../assets/sheet/border-pattern.webp") repeat-x bottom, var(--secondary);
+}
+#compendium-browser > section.window-content > .content-box > nav > a,
+#license-viewer > section.window-content > .content-box > nav > a {
+ color: var(--sidebar-label);
+ padding: 4px 0;
+ font-family: var(--sans-serif);
+ font-size: var(--font-size-12);
+ position: relative;
+}
+#compendium-browser > section.window-content > .content-box > nav > a.active::after,
+#license-viewer > section.window-content > .content-box > nav > a.active::after {
+ bottom: -2px;
+ right: 39%;
+ position: absolute;
+ content: "";
+ width: 0;
+ height: 0;
+ border-left: 4px solid transparent;
+ border-right: 4px solid transparent;
+ border-top: 4px solid var(--sidebar-label);
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings {
+ height: 100%;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form {
+ display: flex;
+ height: 88%;
+ flex-direction: column;
+ margin-bottom: 10px;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section {
+ border: 1px solid #bbb;
+ border-radius: 5px;
+ margin-top: 5px;
+ padding: 2px;
+ /* Checkbox */
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section h3,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section h3 {
+ margin: 0;
+ cursor: pointer;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section dt,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section dt {
+ width: 10%;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section dt > input[type=checkbox],
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section dt > input[type=checkbox] {
+ transform: none;
+ flex: none;
+ height: auto;
+ margin: 3px 3px;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .setting-section dd,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form .setting-section dd {
+ width: 88%;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form dl,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form dl {
+ margin: 5px 0;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form dt,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form dt {
+ display: inline-block;
+ width: 40%;
+ padding-left: 5px;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form dd,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form dd {
+ display: inline-block;
+ width: 58%;
+ margin-left: 0;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .settings-container,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form .settings-container {
+ overflow-y: auto;
+ display: flex;
+ flex-wrap: wrap;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .settings-container .tab[data-tab].active,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form .settings-container .tab[data-tab].active {
+ display: flex;
+ flex-direction: row;
+ flex-wrap: wrap;
+ justify-content: center;
+ width: 100%;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .settings-container .single-column,
+#license-viewer > section.window-content > .content-box .compendium-browser-settings form .settings-container .single-column {
+ width: 100%;
+}
+#compendium-browser > section.window-content > .content-box .compendium-browser-settings form .settings-container h2,
#license-viewer > section.window-content > .content-box .compendium-browser-settings form .settings-container h2 {
margin-top: 1em;
margin-bottom: 0.5em;
@@ -15407,6 +15506,8 @@ body > .choices__list--dropdown {
}
#compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li > .name,
#license-viewer > section.window-content > .content-box .spell-browser ul.result-list > li > .name {
+ gap: 0.25em;
+ flex-basis: 6ch;
justify-content: start;
}
#compendium-browser > section.window-content > .content-box .spell-browser ul.result-list > li > .level,
@@ -15498,1697 +15599,1738 @@ body > .choices__list--dropdown {
#license-viewer > section.window-content > .content-box > section.content > .tab.settings.active {
height: 98%;
}
+.pf2e.item.sheet input,
+.pf2e.item.sheet label,
+.pf2e.item.sheet select {
+ --form-field-height: 1.5rem;
+}
+.pf2e.item.sheet input[type=checkbox] {
+ height: var(--font-size-20);
+}
+.pf2e.item.sheet select {
+ height: var(--form-field-height);
+}
.pf2e.item.sheet h3 {
border-bottom: none;
}
.pf2e.item.sheet button > i {
margin-right: 0;
}
-.pf2e.item.sheet .sheet-header {
+.pf2e.item.sheet form {
display: flex;
- flex: 0 0 70px;
- align-items: bottom;
+ flex-flow: column nowrap;
+ font-family: var(--sans-serif);
+ height: 100%;
+ overflow: hidden;
width: 100%;
- padding-bottom: 6px;
- border-bottom: 1px solid var(--secondary-background);
}
-.pf2e.item.sheet .sheet-header img {
+.pf2e.item.sheet form h2,
+.pf2e.item.sheet form h3,
+.pf2e.item.sheet form h4 {
+ font-weight: 500;
+}
+.pf2e.item.sheet form > header img {
border: none;
object-fit: contain;
- flex: 0 0 64px;
- margin-right: 6px;
}
-.pf2e.item.sheet .sheet-header .details {
+.pf2e.item.sheet form > header .details {
+ align-items: baseline;
+ column-gap: 0.33rem;
display: flex;
flex-wrap: wrap;
- align-items: baseline;
}
-.pf2e.item.sheet .sheet-header .details input,
-.pf2e.item.sheet .sheet-header .details .level {
- font-family: var(--serif-condensed);
- font-size: var(--font-size-36);
- font-weight: 700;
+.pf2e.item.sheet form > header .details input,
+.pf2e.item.sheet form > header .details .level {
+ font: 700 var(--font-size-36) var(--serif-condensed);
}
-.pf2e.item.sheet .sheet-header input[type=text],
-.pf2e.item.sheet .sheet-header input[type=number] {
+.pf2e.item.sheet form > header input[type=text],
+.pf2e.item.sheet form > header input[type=number] {
+ color: var(--color-text-dark-input);
border: none;
height: var(--font-size-34);
}
-.pf2e.item.sheet .sheet-header input[type=text]:hover, .pf2e.item.sheet .sheet-header input[type=text]:focus,
-.pf2e.item.sheet .sheet-header input[type=number]:hover,
-.pf2e.item.sheet .sheet-header input[type=number]:focus {
+.pf2e.item.sheet form > header input[type=text]:hover, .pf2e.item.sheet form > header input[type=text]:focus,
+.pf2e.item.sheet form > header input[type=number]:hover,
+.pf2e.item.sheet form > header input[type=number]:focus {
box-shadow: none;
}
-.pf2e.item.sheet .sheet-header input[name=name] {
+.pf2e.item.sheet form > header input[name=name] {
flex: 1;
}
-.pf2e.item.sheet .sheet-header .level {
+.pf2e.item.sheet form > header .level {
flex: 0;
white-space: nowrap;
margin-left: auto;
- padding-left: 8px;
-}
-.pf2e.item.sheet .sheet-header .level i {
- font-size: 0.6em;
- vertical-align: middle;
-}
-.pf2e.item.sheet .sheet-header .level input {
- width: 40px;
- text-align: center;
-}
-.pf2e.item.sheet .sheet-header .feat-action-cost {
- font-size: 2.5rem;
- margin-top: -0.6rem;
- margin-bottom: -0.3rem;
- padding-left: 0.4rem;
-}
-.pf2e.item.sheet .sheet-header .paizo-style {
- flex-basis: 100%;
- width: 0;
- border: none;
- margin-top: 2px;
- padding-left: 0;
- padding-right: 0;
-}
-.pf2e.item.sheet .sheet-body {
- height: calc(100% - 35px);
- overflow: hidden;
- display: flex;
- flex-direction: column;
- flex-wrap: nowrap;
-}
-.pf2e.item.sheet.action form .drop-zone {
- align-items: center;
- border: 1px solid var(--color-border-light-tertiary);
- display: flex;
- gap: 0.25rem;
- max-width: fit-content;
- padding: 0 4px 0 0;
-}
-.pf2e.item.sheet.action form .drop-zone.empty {
- font-weight: normal;
- min-width: 12rem;
- padding: 4px;
-}
-.pf2e.item.sheet.action form .drop-zone.empty .name {
- font-style: italic;
- flex: 1;
- text-align: center;
}
-.pf2e.item.sheet.action form .drop-zone picture,
-.pf2e.item.sheet.action form .drop-zone img {
- border: 1px solid var(--color-border-dark);
- border-radius: 2px;
- box-sizing: border-box;
- display: block;
- float: left;
- height: 24px;
- width: 24px;
+.pf2e.item.sheet form > header .level i {
+ font-size: 0.6em;
+ vertical-align: middle;
}
-.pf2e.item.sheet.action form .drop-zone a.content-link {
- align-items: center;
+.pf2e.item.sheet form > header .level input {
+ width: 40px;
+ text-align: center;
+}
+.pf2e.item.sheet form > header .action-glyph {
+ font-size: 2.125rem;
+}
+.pf2e.item.sheet form > header .paizo-style {
border: none;
- border-right: 1px solid var(--color-border-light-2);
- display: flex;
- gap: 0.5em;
- min-width: 9rem;
- padding: 4px;
+ flex-basis: 100%;
+ margin-top: 0.125rem;
+ padding: 0;
}
-.pf2e.item.sheet.action form .drop-zone a.delete {
+.pf2e.item.sheet form > nav {
+ align-items: baseline;
+ border-bottom: 1px solid var(--secondary-background);
+ border-top: 1px solid var(--secondary-background);
display: flex;
+ flex: 0 0 1.75rem;
+ line-height: 1.75rem;
}
-.pf2e.item.sheet.affliction form .affliction-stage .link:not(.linked) {
- opacity: 0.6;
- color: #a00;
+.pf2e.item.sheet form > nav a {
+ flex: 1 1 auto;
}
-.pf2e.item.sheet.affliction form .affliction-stage .formula-row {
- align-items: center;
- display: flex;
- gap: 4px;
+.pf2e.item.sheet form > nav a.active {
+ text-decoration: underline;
}
-.pf2e.item.sheet.deity form .tab.details .checkbox-pair {
- align-items: center;
- display: flex;
+.pf2e.item.sheet form > nav .sidebar-summary {
+ flex: 0 0 13.75rem;
+ margin: 0;
+ text-align: center;
}
-.pf2e.item.sheet.deity form .tab.details .checkbox-pair span {
- font-weight: 400;
+.pf2e.item.sheet form > nav > .tabs {
+ font-weight: 500;
+ margin: 0;
+ flex: 1;
+ align-items: baseline;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .inventory-details .form-group select {
- max-width: fit-content;
+.pf2e.item.sheet form > nav > .tabs > a {
+ font-size: var(--font-size-12);
+ text-align: center;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .inventory-details .form-group .form-group.duration label {
- max-width: fit-content;
- padding-right: 0.1em;
+.pf2e.item.sheet form > nav > .tabs > a:last-of-type {
+ padding-right: 0.25rem;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row {
- align-items: center;
- display: flex;
- gap: 4px;
- width: 100%;
+.pf2e.item.sheet form > nav > .tabs > a.active {
+ font-weight: 600;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row label {
+.pf2e.item.sheet form .mce-panel span {
+ display: inherit;
+}
+.pf2e.item.sheet form.editable .rollable:hover {
+ color: var(--text-dark);
+ text-shadow: 0 0 10px #00005a;
cursor: pointer;
- max-width: unset;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row input[type=radio] {
- margin: 0;
- top: 0;
+.pf2e.item.sheet form .tab {
+ flex: 1;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row .badge-value {
- margin-right: 0.1rem;
- width: 3ch;
- font-weight: bold;
- text-align: end;
+.pf2e.item.sheet form:has(.tab.active.rules) .sidebar-summary {
+ visibility: hidden;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row input[type=text] {
- flex: 1;
- text-align: end;
+.pf2e.item.sheet form:has(.tab.active.rules) section.sidebar {
+ display: none;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-header {
+.pf2e.item.sheet form .tag-legacy {
+ float: left;
+ margin: 0 2px 2px 0;
+ padding: 0 3px;
+ font-size: var(--font-size-10);
+ line-height: 16px;
+ border: 1px solid #999;
+ border-radius: 3px;
+ white-space: normal;
+ font-weight: 500;
+}
+.pf2e.item.sheet form p.hint {
+ font-family: var(--font-primary);
+ font-weight: normal;
+}
+.pf2e.item.sheet form .item-controls {
display: flex;
- align-items: center;
- justify-content: space-between;
- margin: 0.5em 0 0.25em 0;
+ margin: 0 0 0 4px;
+ align-items: baseline;
+ gap: 2px;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .add-badge {
+.pf2e.item.sheet form i.fa-info-circle {
+ cursor: help;
+}
+.pf2e.item.sheet form .sheet-content {
+ width: 100%;
display: flex;
- align-items: center;
+ flex-direction: row;
+ flex-wrap: wrap;
+ justify-content: flex-start;
+ height: calc(100% - 35px);
+ overflow: hidden;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .add-badge select {
+.pf2e.item.sheet form .sheet-content > * {
flex: 1;
- max-width: unset;
}
-.pf2e.item.sheet.effect form .sheet-content .sidebar .add-badge button {
- flex: 0;
- line-height: 1.2em;
+.pf2e.item.sheet form .sheet-content label {
+ display: block;
}
-.pf2e.item.sheet.feat form .drop-zone {
- align-items: center;
- border: 1px solid var(--color-border-light-tertiary);
- display: flex;
- gap: 0.25rem;
- max-width: fit-content;
- padding: 0 4px 0 0;
+.pf2e.item.sheet form .sheet-content input {
+ color: var(--color-text-dark-input);
}
-.pf2e.item.sheet.feat form .drop-zone.empty {
- font-weight: normal;
- min-width: 12rem;
- padding: 4px;
+.pf2e.item.sheet form .sheet-content input[type=checkbox] {
+ margin: 0.25em 0.5em;
}
-.pf2e.item.sheet.feat form .drop-zone.empty .name {
- font-style: italic;
- flex: 1;
- text-align: center;
+.pf2e.item.sheet form .sheet-content input[type=number],
+.pf2e.item.sheet form .sheet-content input[type=text] {
+ margin: 1px 0;
+ width: calc(100% - 2px);
}
-.pf2e.item.sheet.feat form .drop-zone picture,
-.pf2e.item.sheet.feat form .drop-zone img {
- border: 1px solid var(--color-border-dark);
- border-radius: 2px;
- box-sizing: border-box;
- display: block;
- float: left;
- height: 24px;
- width: 24px;
+.pf2e.item.sheet form .sheet-content input[type=checkbox],
+.pf2e.item.sheet form .sheet-content input[type=number],
+.pf2e.item.sheet form .sheet-content input[type=text],
+.pf2e.item.sheet form .sheet-content select {
+ background: rgba(255, 255, 255, 0.5);
+ border: 1px solid var(--color-border-light-2);
}
-.pf2e.item.sheet.feat form .drop-zone a.content-link {
- align-items: center;
+.pf2e.item.sheet form .sheet-content select {
+ font-size: var(--font-size-13);
+}
+.pf2e.item.sheet form .sheet-content button:hover:not(:disabled), .pf2e.item.sheet form .sheet-content button:focus,
+.pf2e.item.sheet form .sheet-content input:not([type=range]):hover:not(:disabled),
+.pf2e.item.sheet form .sheet-content input:not([type=range]):focus,
+.pf2e.item.sheet form .sheet-content select:hover:not(:disabled),
+.pf2e.item.sheet form .sheet-content select:focus {
+ border-color: var(--color-border-dark-1);
+ box-shadow: 0 0 5px var(--secondary);
+}
+.pf2e.item.sheet form .sheet-content input:disabled,
+.pf2e.item.sheet form .sheet-content select:disabled {
+ background: rgba(0, 0, 0, 0.05);
border: none;
- border-right: 1px solid var(--color-border-light-2);
- display: flex;
- gap: 0.5em;
- min-width: 9rem;
- padding: 4px;
+ color: var(--color-disabled);
}
-.pf2e.item.sheet.feat form .drop-zone a.delete {
+.pf2e.item.sheet form .sheet-content > section.sidebar,
+.pf2e.item.sheet form .sheet-content > .sheet-body {
+ height: calc(100% - 10px);
+ overflow-y: auto;
+}
+.pf2e.item.sheet form .sheet-content section.sidebar {
+ flex: 0 0 13.75rem;
display: flex;
+ flex-flow: column nowrap;
}
-.pf2e.item.sheet.feat form .tab.details .form-group > label {
- min-width: fit-content;
- margin-right: 1em;
+.pf2e.item.sheet form .sheet-content section.sidebar > * {
+ flex: 1;
}
-.pf2e.item.sheet.heritage form section.sidebar .required-ancestry {
- flex-wrap: nowrap;
- width: 100%;
- white-space: nowrap;
- max-width: 100%;
+.pf2e.item.sheet form .sheet-content section.sidebar .item-summary {
+ font-family: var(--serif-condensed);
+ font-weight: 700;
+ flex: 0 0 1.5em;
+ line-height: 1.5em;
+ text-align: center;
+ font-size: var(--font-size-18);
+ color: #444;
}
-.pf2e.item.sheet.heritage form section.sidebar .required-ancestry label {
+.pf2e.item.sheet form .sheet-content section.sidebar ol.item-tags {
+ padding-left: 0;
flex: 0;
+ list-style: none;
}
-.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone {
- background-color: rgba(0, 0, 0, 0.05);
- border-radius: 2px;
- border: 1px dotted var(--alt-dark);
- display: flex;
- font-weight: normal;
+.pf2e.item.sheet form .sheet-content section.sidebar ol.item-tags .tag {
+ align-items: center;
justify-content: center;
- margin: 2px 3px 0 auto;
- max-width: 8em;
- padding: 3px;
- position: relative;
-}
-.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone span {
- display: inline-block;
- overflow: hidden;
- text-overflow: ellipsis;
-}
-.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone.ancestry-ref-broken {
- background-color: rgba(255, 0, 0, 0.15);
- border-color: var(--primary);
-}
-.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone a.remove-ancestry {
- display: none;
- position: absolute;
- right: -0.5em;
- top: -0.25em;
+ width: 100%;
}
-.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone a.remove-ancestry:hover {
- display: flex;
+.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details,
+.pf2e.item.sheet form .sheet-content section.sidebar .feat-details {
+ overflow: hidden scroll;
+ padding: 0 0.25rem 0 0;
}
-.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone:hover a.remove-ancestry {
- display: flex;
+.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group,
+.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group {
+ margin: 3px 0;
}
-.pf2e.item.sheet.kit form .kit-list ul.kit-items {
- padding: 0;
+.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group label,
+.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group label {
+ font-weight: 500;
+ max-width: 6em;
+ white-space: nowrap;
}
-.pf2e.item.sheet.kit form .kit-list ul.kit-items li.kit-item {
- display: grid;
- grid-template-columns: 26px 30px auto 10px;
- align-items: center;
+.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group input,
+.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group input {
+ text-align: right;
}
-.pf2e.item.sheet.kit form .kit-list ul.kit-items li.kit-item:nth-of-type(even) {
- background-color: rgba(120, 100, 82, 0.1);
+.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group input.left-of-select,
+.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group input.left-of-select {
+ min-width: 4ch;
+ padding-right: 0.25em;
}
-.pf2e.item.sheet.kit form .kit-list ul.kit-items li.kit-item .kit-item-name {
- line-height: 1em;
- height: 1em;
+.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group select,
+.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group select {
+ max-width: 12em;
}
-.pf2e.item.sheet.kit form .kit-list ul.kit-items li.kit-item .kit-item-name .fa.fa-globe {
- padding: 0 3px;
- float: right;
+.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .price-fields,
+.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .price-fields {
+ display: flex;
+ gap: 4px;
}
-.pf2e.item.sheet.kit form .kit-list ul.kit-items ul {
- padding-left: 0.5em;
- margin-top: 0;
- grid-column: 1/5;
+.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .price-fields input[name="system.price.per"],
+.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .price-fields input[name="system.price.per"] {
+ width: 22px;
}
-.pf2e.item.sheet.kit form .kit-list ul.kit-items ul:empty {
- display: none;
+.pf2e.item.sheet form .sheet-content section.sidebar button {
+ padding-top: 0;
+ padding-bottom: 0;
+ white-space: nowrap;
}
-.pf2e.item.sheet.melee form .sheet-body .tab.details .form-group.attack-modifier label,
-.pf2e.item.sheet.melee form .sheet-body .tab.details li.damage-partial form-group label {
- max-width: fit-content;
+.pf2e.item.sheet form .sheet-body {
+ height: calc(100% - 2.25rem);
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+ flex-wrap: nowrap;
}
-.pf2e.item.sheet.melee form .sheet-body .tab.details .form-group.attack-modifier input,
-.pf2e.item.sheet.melee form .sheet-body .tab.details li.damage-partial form-group input {
- max-width: 6ch;
+.pf2e.item.sheet form .sheet-body .tab.active {
+ overflow: hidden scroll;
+ padding-left: 0.5rem;
}
-.pf2e.item.sheet.melee form .sheet-body .tab.details ol.form-list li.damage-partial {
- align-items: center;
+.pf2e.item.sheet form .sheet-body .tab.active.description {
display: flex;
- gap: 1em;
+ flex-direction: column;
+ gap: 3px;
+ height: 100%;
+ padding: 0 0.25em;
}
-.pf2e.item.sheet.melee form .sheet-body .tab.details ol.form-list li.damage-partial input {
- max-width: 12ch;
+.pf2e.item.sheet form .sheet-body .tab.active.description > * {
+ display: flex;
+ overflow: hidden;
}
-.pf2e.item.sheet.melee form .sheet-body .tab.details ol.form-list li.damage-partial .type {
- gap: 0.25em;
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor {
+ min-height: 2.5em;
+ flex: 1;
}
-.pf2e.item.sheet.melee form .sheet-body .tab.details ol.form-list li.damage-partial .remove-partial {
- margin: 0 0.5em 0 auto;
+.pf2e.item.sheet form .sheet-body .tab.active.description.editing {
+ overflow: hidden;
}
-.pf2e.item.sheet.spell form .damage-formulas {
- margin-top: 8px;
+.pf2e.item.sheet form .sheet-body .tab.active.description.editing > section {
+ flex: 1;
}
-.pf2e.item.sheet.spell form .damage-formulas .form-fields {
- gap: 2px;
- margin-top: 4px;
+.pf2e.item.sheet form .sheet-body .tab.active.description .gm-notes {
+ background-color: var(--visibility-gm-bg);
+ border: 1px dotted rgba(75, 74, 68, 0.5);
+ padding: 0 0.25em;
+ flex: 0 0 auto;
}
-.pf2e.item.sheet.spell form .damage-formulas input[type=checkbox] {
- margin-left: 2px;
+.pf2e.item.sheet form .sheet-body .tab.active.description .gm-notes:not(.has-content) {
+ display: none;
+}
+.pf2e.item.sheet form .sheet-body .tab.active.description .main {
+ flex: 1 0 auto;
}
-.pf2e.item.sheet.spell form .damage-formulas .traits-list {
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor {
display: flex;
- margin-top: 2px;
+ flex-direction: column;
}
-.pf2e.item.sheet.spell form .damage-formulas .tag {
- float: none;
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.add-gm-notes,
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.editor-edit {
+ font-size: 1.33em;
+ background: rgb(205, 205, 205);
}
-.pf2e.item.sheet.spell form button[data-action=damage-add] {
- margin-top: 4px;
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.add-gm-notes i,
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.editor-edit i {
+ width: 1em;
+ text-align: center;
}
-.pf2e.item.sheet.spell form button + fieldset {
- margin-top: 0.5rem;
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.add-gm-notes {
+ border-radius: 4px;
+ border: 1px solid var(--color-border-dark-1);
+ box-shadow: 0 0 1px var(--color-shadow-dark);
+ display: none;
+ padding: 1px 2px;
+ position: absolute;
+ right: 35px;
+ top: 5px;
}
-.pf2e.item.sheet.spell form .overlay .traits {
- align-items: center;
- display: flex;
- gap: 4px;
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor:hover a.add-gm-notes {
+ display: block;
}
-.pf2e.item.sheet.spell form .overlay .traits .tags {
+.pf2e.item.sheet form .sheet-body .tab.active.description .editor .tox {
flex: 1;
}
-.pf2e.item.sheet.spell form .variants .variant {
- display: grid;
- grid-template-columns: 1fr 1fr 0.2fr;
-}
-.pf2e.item.sheet.spell form .variants .variant .item-controls {
- justify-self: end;
+.pf2e.item.sheet form .sheet-body .tab.active label {
+ color: var(--color-text-dark-2);
+ font-weight: 500;
+ padding-right: 0.5em;
+ white-space: nowrap;
}
-.pf2e.item.sheet.weapon form .tab.details label {
- min-width: 9em;
+.pf2e.item.sheet form .sheet-body .tab.active label.disabled, .pf2e.item.sheet form .sheet-body .tab.active label.no-data {
+ color: var(--color-text-dark-4);
}
-.pf2e.item.sheet.weapon form .tab.details .precious-material select {
- width: 19.5em;
+.pf2e.item.sheet form .sheet-body .tab.active.details {
+ padding: 0.5rem 0.5rem 0;
}
-.pf2e.item.sheet form {
- display: flex;
- flex-direction: column;
- flex-wrap: nowrap;
- width: 100%;
- height: 100%;
- overflow: hidden;
+.pf2e.item.sheet form .sheet-body .tab.active.details button {
+ height: 2rem;
+ line-height: normal;
}
-.pf2e.item.sheet form .item-ref-group ul.item-refs {
- border: 1px solid var(--color-border-light-2);
- border-radius: 3px;
- padding: 0;
+.pf2e.item.sheet form .sheet-body .tab.active.details.no-sidebar .form-group label {
+ max-width: 12em;
+ white-space: wrap;
}
-.pf2e.item.sheet form .item-ref-group ul.item-refs.empty {
- background-color: rgba(120, 100, 82, 0.1);
- height: 28px;
+.pf2e.item.sheet form .sheet-body .tab.active.details .tags .tag {
+ font-size: var(--font-size-10);
}
-.pf2e.item.sheet form .item-ref-group ul.item-refs > li {
- align-items: center;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data {
+ align-items: baseline;
+ gap: 0.25em;
display: grid;
- grid-template-columns: 26px auto 2em 1em;
- padding: 1px;
-}
-.pf2e.item.sheet form .item-ref-group ul.item-refs > li:nth-of-type(even) {
- background-color: rgba(120, 100, 82, 0.1);
-}
-.pf2e.item.sheet form .item-ref-group ul.item-refs > li .name {
- display: block;
- margin-left: 0.25em;
- line-height: 1em;
- height: 1em;
+ grid-template: "title title title" 2fr "authors license remaster" 3fr/60% 20% 20%;
}
-.pf2e.item.sheet form .item-ref-group ul.item-refs > li .name .fa.fa-globe {
- padding: 0 3px;
- float: right;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data label {
+ font-weight: 500;
+ min-width: unset;
}
-.pf2e.item.sheet form .item-ref-group ul.item-refs > li .level {
- font-weight: bold;
- height: 1.25em;
- text-align: center;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data input[type=text] {
+ height: 1.6rem;
}
-.pf2e.item.sheet form .item-ref-group ul.item-refs > li a.remove {
- padding: 0 2px;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .title {
+ grid-area: title;
+ margin-right: 0;
}
-.pf2e.item.sheet form .item-ref-group ul.item-refs ul {
- grid-column: 1/5;
- margin-top: 0;
- padding-left: 0.5em;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .authors {
+ grid-area: authors;
}
-.pf2e.item.sheet form .item-ref-group ul.item-refs ul:empty {
- display: none;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .license {
+ grid-area: license;
}
-.pf2e.item.sheet form .item-ref-list {
- align-items: start;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .license select {
+ margin-top: 1px;
}
-.pf2e.item.sheet form .form-group.form-group-trait {
- height: auto;
- margin: 2px 0;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .remaster {
+ grid-area: remaster;
}
-.pf2e.item.sheet form .form-group.form-group-trait label {
- vertical-align: top;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .license,
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .remaster {
+ text-align: center;
}
-.pf2e.item.sheet form .form-group.form-group-trait > ul.abc-traits-list {
- list-style: none;
- margin: 0;
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .license label,
+.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .remaster label {
padding: 0;
- display: flex;
- flex-wrap: wrap;
}
-.pf2e.item.sheet form .form-group.form-group-trait > ul.abc-traits-list span.tag {
- float: none;
+.pf2e.item.sheet form .sheet-body fieldset {
+ border: 1px solid var(--color-border-medium);
+ border-radius: 2px;
+ margin-bottom: 0.5rem;
+ padding: 0 0.5em 0.25em;
}
-.pf2e.item.sheet form .form-group.other-weapons input {
- flex: 2;
+.pf2e.item.sheet form .sheet-body fieldset legend {
+ font-weight: 600;
}
-.pf2e.item.sheet form .form-group.other-weapons select {
- flex: 1;
+.pf2e.item.sheet form .sheet-body fieldset.basics {
+ border-color: transparent;
+ padding: 0;
}
-.pf2e.item.sheet form .form-group.additional-language input {
- flex: 0.5;
+.pf2e.item.sheet form .sheet-body .editor {
+ --space-s: 0.25em;
+ --space-m: 0.5em;
+ --space-l: 1em;
+ --space-xl: 1.5em;
+ --space-2xl: 2em;
+ --radius: 3px;
}
-.pf2e.item.sheet form .form-group.additional-language span {
- flex: 2.5;
- padding-left: 4px;
+.pf2e.item.sheet form .sheet-body .editor :is(h1, h2, h3, h4, h5, h6):not(:first-child) {
+ margin-top: 1em;
}
-.pf2e.item.sheet form .item-activations {
- padding: 8px 8px 0;
- overflow: hidden scroll;
+.pf2e.item.sheet form .sheet-body .editor .inline-header {
+ display: flex;
+ align-items: center;
+ gap: var(--space-l);
+ background-color: var(--alt);
+ font-family: var(--sans-serif);
+ color: var(--text-light);
+ padding: 0;
+ font-size: 0.8em;
+ font-weight: 400;
+ border: none;
+}
+.pf2e.item.sheet form .sheet-body .editor .inline-header strong {
+ display: inline-flex;
+ padding: 0 var(--space-m);
+ background-color: var(--primary);
+ min-width: 15ch;
+ border-right: 1px solid rgba(0, 0, 0, 0.4);
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2);
+ font-weight: 400;
}
-.pf2e.item.sheet form .item-activations .activation + .activation, .pf2e.item.sheet form .item-activations .activation + button {
- margin-top: 0.5em;
+.pf2e.item.sheet form .sheet-body .editor .inline-header + p {
+ margin-top: var(--space-s);
}
-.pf2e.item.sheet form .item-activations .activation .editor {
- min-height: 28px;
+.pf2e.item.sheet form .sheet-body .editor .info {
+ background-color: var(--secondary);
+ padding: var(--space-m);
+ color: var(--text-light);
+ margin-left: auto;
+ margin-right: auto;
+ padding: 0;
+ border-radius: var(--radius);
+ font-family: var(--sans-serif);
+ padding-bottom: var(--space-m);
}
-.pf2e.item.sheet form .item-activations header {
- font-size: 1.05em;
- margin-bottom: 0.25em;
- line-height: 1.25em;
+.pf2e.item.sheet form .sheet-body .editor .info > * + * {
+ margin-top: var(--space-m);
}
-.pf2e.item.sheet form .item-activations .activation-time {
- flex: 1;
- height: 20px;
+.pf2e.item.sheet form .sheet-body .editor .info + * {
+ margin-top: var(--space-xl);
}
-.pf2e.item.sheet form .item-activations .frequency {
- flex: 1;
- gap: 4px;
- padding-right: 6px;
+.pf2e.item.sheet form .sheet-body .editor .info + .pf2e.item.sheet form .sheet-body .editor .info {
+ margin-top: var(--space-s);
}
-.pf2e.item.sheet form .item-activations .frequency input[type=number] {
- border: none;
- background: none;
- text-align: right;
- margin: 0 0 0 24px;
+.pf2e.item.sheet form .sheet-body .editor .info h4 {
+ font-size: 0.9em;
+ font-weight: 400;
+ line-height: 1.2;
+ font-family: var(--sans-serif);
+ border-bottom: 1px solid rgba(0, 0, 0, 0.6);
+ padding: var(--space-m) var(--space-l);
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ color: var(--text-light);
}
-.pf2e.item.sheet form .item-activations .frequency > select:first-child {
- margin-left: 24px;
+.pf2e.item.sheet form .sheet-body .editor .info h4::after {
+ font-family: "Font Awesome 6";
+ content: "\f05a";
+ font-weight: 900;
+ margin-right: var(--space-s);
}
-.pf2e.item.sheet form .item-activations .frequency.empty {
- text-align: right;
+.pf2e.item.sheet form .sheet-body .editor .info p {
+ font-size: 0.8em;
+ margin: 0;
+ padding: 0 var(--space-l);
}
-.pf2e.item.sheet form .item-activations .tags {
- margin-top: 4px;
+.pf2e.item.sheet form .sheet-body .editor .info p:first-of-type {
+ padding-top: var(--space-m);
+ border-top: 1px solid rgba(255, 255, 255, 0.1);
}
-.pf2e.item.sheet form .item-activations .tags label {
- margin-right: 3px;
+.pf2e.item.sheet form .sheet-body .editor .traits {
+ display: flex;
+ flex-wrap: wrap;
+ padding: 0;
}
-.pf2e.item.sheet form .item-activations .tox {
- min-height: 150px;
+.pf2e.item.sheet form .sheet-body .editor .traits p {
+ display: inline-flex;
+ padding: 0.16rem 0.25rem;
+ margin: 0;
+ background-color: var(--primary);
+ border: 2px solid var(--color-border-trait);
+ color: var(--text-light);
+ font: 500 var(--font-size-10) var(--sans-serif);
+ text-transform: uppercase;
}
-.pf2e.item.sheet form .identify-popup {
- min-width: 300px;
+.pf2e.item.sheet form .sheet-body .editor .statblock {
+ font-family: var(--sans-serif-condensed);
+ color: var(--text-dark);
+ line-height: 1.2;
+ margin-bottom: var(--space-m);
}
-.pf2e.item.sheet form .sheet-body .tab.mystification.active .mystification-status select {
- max-width: fit-content;
- margin-right: auto;
+.pf2e.item.sheet form .sheet-body .editor .statblock > * + * {
+ margin-top: var(--space-s);
+ margin-bottom: 0;
}
-.pf2e.item.sheet form .sheet-body .tab.mystification.active .unidentified {
- display: flex;
- align-items: center;
- gap: 0.5rem;
- flex-wrap: wrap;
+.pf2e.item.sheet form .sheet-body .editor .statblock p {
+ --indent: var(--space-l);
+ margin-left: var(--indent);
+ position: relative;
}
-.pf2e.item.sheet form .sheet-body .tab.mystification.active .unidentified > * {
- display: flex;
+.pf2e.item.sheet form .sheet-body .editor .statblock p strong:first-of-type {
+ margin-left: calc(var(--indent) * -1);
}
-.pf2e.item.sheet form .sheet-body .tab.mystification.active .unidentified img {
- height: 42px;
- width: 42px;
+.pf2e.item.sheet form .sheet-body .editor .statblock p .trait:first-of-type {
+ margin-left: calc(var(--indent) * -1 - 2px);
}
-.pf2e.item.sheet form .sheet-body .tab.mystification.active .unidentified input {
- width: 50%;
+.pf2e.item.sheet form .sheet-body .editor .statblock span.pf2-icon {
+ line-height: 1;
}
-.pf2e.item.sheet form .sheet-body .tab.mystification.active .unidentified .editor {
- min-height: 100px;
- width: 100%;
+.pf2e.item.sheet form .sheet-body .editor .statblock h1,
+.pf2e.item.sheet form .sheet-body .editor .statblock h2,
+.pf2e.item.sheet form .sheet-body .editor .statblock h3,
+.pf2e.item.sheet form .sheet-body .editor .statblock h4 {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ border-bottom: 1px solid var(--color-border-dark);
+ text-transform: uppercase;
+ letter-spacing: -0.05em;
+ font-family: var(--sans-serif-condensed);
+ font-weight: 700;
}
-.pf2e.item.sheet form .sheet-body .tab.mystification.active .unidentified .tox.tox-tinymce {
- min-height: 200px;
+.pf2e.item.sheet form .sheet-body .editor .statblock hr {
+ border: none;
+ border-bottom: 1px solid var(--color-border-dark);
}
-.pf2e.item.sheet form .tab.active.rules select {
- font-size: var(--font-size-12);
- height: 1.36rem;
- width: auto;
+.pf2e.item.sheet form .sheet-body .editor .message {
+ font-family: var(--journal-cursive);
+ font-size: 2em;
+ line-height: 1.2;
}
-.pf2e.item.sheet form .tab.active.rules select span {
- padding: 0;
+.pf2e.item.sheet form h3 .item-controls,
+.pf2e.item.sheet form header .item-controls {
+ float: right;
}
-.pf2e.item.sheet form .tab.active.rules fieldset {
+.pf2e.item.sheet form .form-list h3,
+.pf2e.item.sheet form fieldset h3 {
+ font-weight: 600;
+ font-size: 1.05em;
+ margin-bottom: 0.25em;
+}
+.pf2e.item.sheet form .form-list {
border-radius: 5px;
border: 1px solid var(--secondary-background);
+ list-style-type: none;
+ margin: 0.5em 0;
padding: 0.25em;
}
-.pf2e.item.sheet form .tab.active.rules fieldset legend {
- font-weight: 500;
+.pf2e.item.sheet form .form-list:first-child {
+ margin-top: 0;
}
-.pf2e.item.sheet form .tab.active.rules .nerd-details {
- margin-bottom: 10px;
+.pf2e.item.sheet form .form-list.subsection {
+ padding: 0;
}
-.pf2e.item.sheet form .tab.active.rules .nerd-details .form-group {
- margin: 0;
+.pf2e.item.sheet form .form-list.subsection > * {
+ padding: 0.25rem;
}
-.pf2e.item.sheet form .tab.active.rules .nerd-details label {
- align-items: center;
+.pf2e.item.sheet form .form-list.subsection > header {
+ align-items: baseline;
+ background-color: var(--secondary);
+ border-radius: 5px 5px 0 0;
+ color: var(--text-light);
display: flex;
- flex: 0 0 70px;
- line-height: 1.5em;
- margin-right: 4px;
- min-width: 8em;
-}
-.pf2e.item.sheet form .tab.active.rules .nerd-details label i.fa-info-circle {
- margin-left: auto;
- margin-right: 0.5em;
-}
-.pf2e.item.sheet form .tab.active.rules .rules {
- padding-top: 7px;
- padding-right: 7px;
-}
-.pf2e.item.sheet form .tab.active.rules .rules .add-rule-element {
- text-align: right;
+ justify-content: space-between;
+ margin: -1px -1px 0 -1px;
+ padding: 1px;
}
-.pf2e.item.sheet form .tab.active.rules .rules textarea {
- padding: 4px;
- min-height: 60px;
- resize: vertical;
+.pf2e.item.sheet form .form-list.subsection > header h3,
+.pf2e.item.sheet form .form-list.subsection > header .item-controls {
+ padding: 0.25rem;
+ margin-bottom: 0;
}
-.pf2e.item.sheet form .tab.active.rules .create-rule-element {
- display: flex;
- align-items: center;
- white-space: nowrap;
- gap: 6px;
- justify-content: flex-end;
+.pf2e.item.sheet form .two-by-two {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ column-gap: 0.25rem;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing {
- display: flex;
- flex-direction: column;
- height: 100%;
- gap: 5px;
+.pf2e.item.sheet form .two-by-two .item-controls {
+ margin-left: 2px;
+ gap: 0;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor {
- flex: 1;
- background-color: white;
- overflow: hidden;
+.pf2e.item.sheet form .form-group > label:not(.large) {
+ max-width: 11em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor .cm-scroller {
- overflow: hidden scroll;
- overflow: scroll;
+.pf2e.item.sheet form .form-group > label.short {
+ max-width: 9em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor button {
- width: auto;
- line-height: normal;
+.pf2e.item.sheet form .form-group ul.tags {
+ margin: 0 0 0.5em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor input[type=checkbox] {
- width: auto;
- height: auto;
+.pf2e.item.sheet form .form-group .item-controls {
+ flex: 0 1 auto;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor label {
- display: inline;
+.pf2e.item.sheet form .form-group input.adjusted-higher:not(:focus),
+.pf2e.item.sheet form .form-group select.adjusted-higher:not(:focus) {
+ color: #009988;
+ font-weight: 700;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor .cm-search .cm-textfield {
- width: 100px;
+.pf2e.item.sheet form .form-group input.adjusted-lower:not(:focus),
+.pf2e.item.sheet form .form-group select.adjusted-lower:not(:focus) {
+ color: #cc3311;
+ font-weight: 700;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor ::selection {
- color: var(--text-dark);
+.pf2e.item.sheet form .form-group select.readonly {
+ opacity: 0.7;
+ pointer-events: none;
}
-.pf2e.item.sheet form .tab.active.rules .rule-editing .item-controls {
- margin: 0;
+.pf2e.item.sheet form .form-group select.readonly:hover {
+ border: 1px solid var(--color-border-light-2);
+ box-shadow: none;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form {
- --form-field-height: normal;
- border-bottom: 1px solid var(--color-border-light-primary);
- padding-bottom: 0.5rem;
- margin-bottom: 0.5rem;
+.pf2e.item.sheet form .details-container,
+.pf2e.item.sheet form .dice-data {
+ display: grid;
+ grid: "dice die type"/40px 60px auto;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form.drag-preview {
- background: url(../ui/parchment.jpg) repeat;
+.pf2e.item.sheet form .effects-container {
+ display: grid;
+ grid: "effect number"/auto 40px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form.drag-gap {
- visibility: hidden;
+.pf2e.item.sheet form .details-container-two-columns {
+ display: grid;
+ grid: "size type"/50% 50%;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form input::placeholder {
- opacity: 0.9;
+.pf2e.item.sheet form .details-container-three-columns {
+ display: grid;
+ grid-template-columns: 1fr 1fr 1fr;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form label {
- align-items: center;
+.pf2e.item.sheet form .form-fields > label {
display: flex;
- gap: 4px;
- font-weight: 500;
+ align-items: center;
white-space: nowrap;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form label:not(:first-child) {
- padding-left: 2px;
-}
-.pf2e.item.sheet form .tab.active.rules .rule-form label input,
-.pf2e.item.sheet form .tab.active.rules .rule-form label tags {
+.pf2e.item.sheet form .form-fields select {
flex: 1;
+ width: auto;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form label input[type=checkbox] {
- width: 1rem;
- height: 1rem;
- flex-basis: auto;
+.pf2e.item.sheet form .consumable-details {
+ flex: 0 0 24px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form label input[type=checkbox]:first-child:last-child {
- margin-left: auto;
- justify-self: flex-end;
+.pf2e.item.sheet form .consumable-details label {
+ font-weight: bold;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form select.short {
- flex: 0 0 auto;
+.pf2e.item.sheet form .consumable-details input {
+ flex: 0 0 24px;
+ margin-right: 6px;
+ text-align: right;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .content-link {
- display: flex;
- flex: 0 0 auto;
- flex-direction: row;
- align-items: center;
- gap: 3px;
+.pf2e.item.sheet form .consumable-details span {
+ line-height: 24px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .content-link img {
- width: 16px;
- height: 16px;
+.pf2e.item.sheet form .consumable-details .max-charges {
+ flex: 0 0 16px;
+ text-align: center;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header {
- display: flex;
- align-items: center;
- margin-bottom: 0.25rem;
+.pf2e.item.sheet form .consumable-charges label {
+ flex: 0 0 144px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header .drag-handle {
- cursor: grab;
- font-weight: normal;
- margin-right: 0.375rem;
- padding: 0.125rem;
+.pf2e.item.sheet form .consumable-charges input {
+ flex: 0 0 64px;
+ text-align: center;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header h3 {
- flex: 1;
- margin: 0;
+.pf2e.item.sheet form .consumable-charges span.flex0 {
+ line-height: 24px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header h3.unrecognized {
- color: #880000;
+.pf2e.item.sheet form .feat-uses select {
+ flex: 2;
+ margin-right: 5px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header .priority {
- margin-right: 0.75rem;
+.pf2e.item.sheet form .feat-uses input {
+ flex: 1;
+ text-align: center;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header .priority input {
- width: 4ch;
+.pf2e.item.sheet form .feat-uses span.sep {
+ flex: 0 0 16px;
+ line-height: 24px;
+ font-size: var(--font-size-14);
+ text-align: center;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header .item-controls {
- margin-left: auto;
+.pf2e.item.sheet form .spell-components input {
+ margin-left: 0;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .form-fields [data-action] {
- flex: 0 0 auto;
+.pf2e.item.sheet form .spell-components label {
+ padding-right: 6px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .range {
+.pf2e.item.sheet form input.adjusted:not(:focus) {
+ font-weight: 700;
+ color: #009988;
+}
+.pf2e.item.sheet form .frequency {
+ align-items: baseline;
display: flex;
- gap: 3px;
- align-items: center;
+ gap: 0.2rem;
+ text-align: end;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .range input {
- width: 40px;
+.pf2e.item.sheet form .frequency.empty {
+ justify-content: flex-end;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input {
- align-items: center;
- display: flex;
- flex: 2;
- justify-content: center;
+.pf2e.item.sheet form .frequency select {
+ flex: 1 1 auto;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .attachment,
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input input,
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .tags {
- z-index: 0;
+.pf2e.item.sheet form .frequency a {
+ align-self: center;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .attachment:hover, .pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .attachment:focus,
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input input:hover,
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input input:focus,
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .tags:hover,
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .tags:focus {
- z-index: 1;
+.pf2e.item.sheet form .item-ref-group ul.item-refs {
+ border: 1px solid var(--color-border-light-2);
+ border-radius: 3px;
+ padding: 0;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .attachment {
- display: flex;
- justify-content: center;
+.pf2e.item.sheet form .item-ref-group ul.item-refs.empty {
+ background-color: rgba(120, 100, 82, 0.1);
+ height: 28px;
+}
+.pf2e.item.sheet form .item-ref-group ul.item-refs > li {
align-items: center;
- padding: 0 6px;
- margin: 0;
- line-height: unset;
- flex: 0 0 auto;
- width: auto;
- min-width: 68px;
- align-self: stretch;
- border: 1px solid #aaa;
- border-right: none;
- border-radius: 3px 0 0 3px;
+ display: grid;
+ grid-template-columns: 26px auto 2em 1em;
+ padding: 1px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .file-picker {
- line-height: unset;
+.pf2e.item.sheet form .item-ref-group ul.item-refs > li:nth-of-type(even) {
+ background-color: rgba(120, 100, 82, 0.1);
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input input,
-.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input tags {
- border-top-left-radius: 0;
- border-bottom-left-radius: 0;
- margin: 0;
- flex: 1;
+.pf2e.item.sheet form .item-ref-group ul.item-refs > li .name {
+ display: block;
+ margin-left: 0.25em;
+ line-height: 1em;
+ height: 1em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .brackets {
- margin-left: 9.5em;
+.pf2e.item.sheet form .item-ref-group ul.item-refs > li .name i.fa-globe {
+ padding: 0 3px;
+ float: right;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .brackets .bracket {
- align-items: center;
- display: flex;
- gap: 4px;
+.pf2e.item.sheet form .item-ref-group ul.item-refs > li .level {
+ font-weight: 500;
+ height: 1.25em;
+ text-align: center;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .brackets .bracket .value {
- flex: 1;
+.pf2e.item.sheet form .item-ref-group ul.item-refs > li a.remove {
+ padding: 0 2px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form nav.rule-tabs {
- border-bottom: 1px solid var(--secondary-background);
+.pf2e.item.sheet form .item-ref-group ul.item-refs ul {
+ grid-column: 1/5;
+ margin-top: 0;
+ padding-left: 0.5em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form nav.rule-tabs h4 {
- display: flex;
- justify-content: space-evenly;
- width: 100%;
- margin-top: 0.5em;
- font-weight: 200;
+.pf2e.item.sheet form .item-ref-group ul.item-refs ul:empty {
+ display: none;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form nav.rule-tabs a.active {
- font-weight: 600;
- text-decoration: underline;
+.pf2e.item.sheet form fieldset.item-ref-group .item-refs {
+ border: none;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container {
- display: flex;
- justify-content: center;
- align-items: center;
- width: 100%;
- height: 4em;
+.pf2e.item.sheet form .item-ref-list {
+ align-items: start;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container .rules-drop-zone {
- display: flex;
- justify-content: center;
- align-items: center;
- width: 40%;
- height: 3.5em;
- border: 1px solid var(--color-border-light-primary);
- border-radius: 3px;
- color: #222;
- background-color: #ddd;
- cursor: default;
- padding: 1px 6px;
- font-family: var(--font-primary);
- font-size: var(--font-size-14);
- line-height: 28px;
+.pf2e.item.sheet form .form-group.form-group-trait {
+ height: auto;
+ margin: 2px 0;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container .rules-drop-zone i {
- border: 1px solid #bbb;
- border-radius: 2px;
- align-items: center;
+.pf2e.item.sheet form .form-group.form-group-trait label {
+ vertical-align: top;
+}
+.pf2e.item.sheet form .form-group.form-group-trait > ul.abc-traits-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
display: flex;
- height: 1.6em;
- justify-content: center;
- margin-right: 0.5em;
- width: 1.6em;
+ flex-wrap: wrap;
+}
+.pf2e.item.sheet form .form-group.form-group-trait > ul.abc-traits-list span.tag {
+ float: none;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container .rules-drop-zone i:after {
- font-size: var(--font-size-20);
+.pf2e.item.sheet form .form-group.other-weapons input {
+ flex: 2;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container .rules-drop-zone span {
- color: var(--text-dark);
+.pf2e.item.sheet form .form-group.other-weapons select {
+ flex: 1;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .grid-item {
- display: grid;
- grid: 1fr/5em 1fr;
+.pf2e.item.sheet form .form-group.additional-language input {
+ flex: 0.5;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .grid-item.long-label {
- grid: 1fr/9em 1fr;
+.pf2e.item.sheet form .form-group.additional-language span {
+ flex: 2.5;
+ padding-left: 4px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .checkbox {
- display: flex;
- justify-content: flex-end;
+.pf2e.item.sheet form .item-activations {
+ padding: 8px 8px 0;
+ overflow: hidden scroll;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .item-controls {
- justify-content: flex-end;
+.pf2e.item.sheet form .item-activations .activation + .activation, .pf2e.item.sheet form .item-activations .activation + button {
+ margin-top: 0.5em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .item-controls a {
- margin: 2px 5px 0 0;
+.pf2e.item.sheet form .item-activations .activation .editor {
+ min-height: 28px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .stacked {
- display: grid;
- grid-template-columns: 1fr 1fr;
- column-gap: 0.5rem;
+.pf2e.item.sheet form .item-activations header {
+ font-size: 1.05em;
+ margin-bottom: 0.25em;
+ line-height: 1.25em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .column-span-two {
- grid-column: span 2;
+.pf2e.item.sheet form .item-activations .activation-time {
+ flex: 1;
+ height: 20px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .resolvable {
- grid-column: span 2;
- display: flex;
- align-items: center;
+.pf2e.item.sheet form .item-activations .frequency {
+ flex: 1;
+ gap: 4px;
+ padding-right: 6px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .brackets-container {
- grid-column: span 3;
+.pf2e.item.sheet form .item-activations .frequency input[type=number] {
+ border: none;
+ background: none;
+ text-align: right;
+ margin: 0 0 0 24px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] label {
- min-width: 5em;
- font-weight: 500;
+.pf2e.item.sheet form .item-activations .frequency > select:first-child {
+ margin-left: 24px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] label.short {
- max-width: 5em;
+.pf2e.item.sheet form .item-activations .frequency.empty {
+ text-align: right;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] label.with-hint {
- margin-right: 5px;
+.pf2e.item.sheet form .item-activations .tags {
+ margin-top: 4px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] fieldset {
- grid-column: span 2;
- padding-bottom: 0.4rem;
+.pf2e.item.sheet form .item-activations .tags label {
+ margin-right: 3px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .brackets {
- margin-left: 6em;
+.pf2e.item.sheet form .item-activations .tox {
+ min-height: 150px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] hr {
- grid-column: span 2;
- width: 100%;
+.pf2e.item.sheet form .identify-popup {
+ min-width: 300px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] {
- height: 90px;
- overflow-y: auto;
+.pf2e.item.sheet form .sheet-body .tab.mystification.active .mystification-status select {
+ max-width: fit-content;
+ margin-right: auto;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .item-container {
- grid-column: span 2;
- display: grid;
- grid: 1fr/5em 10fr 1fr;
+.pf2e.item.sheet form .sheet-body .tab.mystification.active fieldset > legend {
+ font-weight: 500;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .item-container a.content-link {
- display: flex;
+.pf2e.item.sheet form .sheet-body .tab.mystification.active .form-group.unidentified {
+ align-items: start;
+ flex-direction: column;
+ gap: 0.25rem;
+}
+.pf2e.item.sheet form .sheet-body .tab.mystification.active .form-group.unidentified .img-name {
align-items: center;
gap: 0.5em;
- width: fit-content;
- min-width: 12rem;
- height: 2em;
- padding: 4px;
+ display: flex;
+ flex-wrap: nowrap;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .item-container a.content-link img {
- border: 1px solid var(--color-border-dark);
- border-radius: 2px;
- box-sizing: border-box;
- display: block;
- float: left;
- height: 24px;
- width: 24px;
+.pf2e.item.sheet form .sheet-body .tab.mystification.active .form-group.unidentified .img-name img {
+ flex: 0 0 3em;
+ height: 3em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .item-container a.content-link span {
- text-wrap: wrap;
+.pf2e.item.sheet form .sheet-body .tab.mystification.active .form-group.unidentified .editor {
+ background: rgba(0, 0, 0, 0.05);
+ padding: 0.25rem;
+ min-height: 100px;
+ min-width: 100%;
+ flex-basis: 100%;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .three-items {
- grid-column: span 2;
- display: grid;
- grid: 1fr/5em 8fr 7em 5fr 6em 1fr;
- margin-top: 5px;
+.pf2e.item.sheet form .sheet-body .tab.mystification.active .form-group.unidentified .tox.tox-tinymce {
+ min-height: 200px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .three-items select {
- width: fit-content;
- min-width: 10em;
+.pf2e.item.sheet form .tab.active.rules select {
+ width: auto;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .saves-container {
- display: grid;
- grid: 1fr/5em 8.8fr;
- align-items: center;
- row-gap: 5px;
+.pf2e.item.sheet form .tab.active.rules select span {
+ padding: 0;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .saves-container select {
- width: fit-content;
- min-width: 10em;
+.pf2e.item.sheet form .tab.active.rules fieldset {
+ border-radius: 5px;
+ border: 1px solid var(--secondary-background);
+ padding: 0.25em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .rules-drop-container {
- grid-column: span 2;
+.pf2e.item.sheet form .tab.active.rules fieldset legend {
+ font-weight: 500;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .translation input {
- width: 5em;
+.pf2e.item.sheet form .tab.active.rules .nerd-details {
+ margin-bottom: 10px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] input[type=checkbox] {
- margin-left: unset;
+.pf2e.item.sheet form .tab.active.rules .nerd-details .form-group {
+ margin: 0;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items {
+.pf2e.item.sheet form .tab.active.rules .nerd-details label {
+ align-items: center;
display: flex;
- justify-content: space-between;
- gap: 0.5em;
+ flex: 0 0 4.5rem;
+ white-space: nowrap;
+ line-height: 1.5em;
+ margin-right: 1.25rem;
+ min-width: 8em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items > label {
- min-width: unset;
- width: fit-content;
+.pf2e.item.sheet form .tab.active.rules .nerd-details label i.fa-info-circle {
+ margin-left: auto;
+ margin-right: 0.5em;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker {
- align-items: center;
+.pf2e.item.sheet form .tab.active.rules .rules {
+ padding-top: 0.5em;
+ padding-right: 0.5em;
+}
+.pf2e.item.sheet form .tab.active.rules .rules .add-rule-element {
+ text-align: right;
+}
+.pf2e.item.sheet form .tab.active.rules .rules textarea {
+ padding: 4px;
+ min-height: 60px;
+ resize: vertical;
+}
+.pf2e.item.sheet form .tab.active.rules .create-rule-element {
display: flex;
- width: 16rem;
+ align-items: center;
white-space: nowrap;
+ gap: 6px;
+ justify-content: flex-end;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker input[type=text] {
- flex: 1;
-}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker input[type=color] {
- flex: 2;
- height: 94%;
+.pf2e.item.sheet form .tab.active.rules .rule-editing {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ gap: 5px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker input[type=color]:disabled {
- background: rgba(0, 0, 0, 0.05);
- border: 1px solid transparent;
+.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor {
+ flex: 1;
+ background-color: white;
+ overflow: hidden;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker .user {
- flex: 0;
- gap: 0;
- justify-content: start;
+.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor .cm-scroller {
+ overflow: hidden scroll;
+ overflow: scroll;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker .user input[type=checkbox] {
- flex: 0;
- margin-left: 0;
+.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor button {
+ width: auto;
+ line-height: normal;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker .user span {
- font-size: small;
+.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor input[type=checkbox] {
+ width: auto;
+ height: auto;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items {
- display: grid;
- grid-template-columns: 5em 2.5fr 1fr;
- align-items: center;
+.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor label {
+ display: inline;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items.long-label {
- grid: 1fr/9em 2.5fr 1fr;
+.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor .cm-search .cm-textfield {
+ width: 100px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items input[type=color] {
- min-width: 7em;
+.pf2e.item.sheet form .tab.active.rules .rule-editing > .cm-editor ::selection {
+ color: var(--text-dark);
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items.image-path {
- grid-column: span 2;
- grid: 1fr/9em 8fr 1fr;
+.pf2e.item.sheet form .tab.active.rules .rule-editing .item-controls {
+ margin: 0;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items.image-path button.file-picker {
- margin: unset;
+.pf2e.item.sheet form .tab.active.rules .rule-form {
+ border-bottom: 1px solid var(--color-border-light-primary);
+ padding-bottom: 0.5rem;
+ margin-bottom: 0.5rem;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Note] {
- display: flex;
- flex-direction: column;
- gap: 2px;
+.pf2e.item.sheet form .tab.active.rules .rule-form.drag-preview {
+ background: url(../ui/parchment.jpg) repeat;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] {
- display: grid;
- grid: "label content" 1fr/1fr 1fr;
- column-gap: 5px;
+.pf2e.item.sheet form .tab.active.rules .rule-form.drag-gap {
+ visibility: hidden;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] fieldset.radii {
+.pf2e.item.sheet form .tab.active.rules .rule-form input::placeholder {
+ opacity: 0.9;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form label {
+ align-items: center;
display: flex;
- flex-direction: column;
- grid-column: span 2;
+ gap: 4px;
+ font-weight: 500;
+ white-space: nowrap;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] fieldset.radii .brackets {
- margin-left: 6.5em;
+.pf2e.item.sheet form .tab.active.rules .rule-form label:not(:first-child) {
+ padding-left: 2px;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] label {
- display: flex;
- flex: unset;
- margin-left: 5px;
- margin-right: 5px;
+.pf2e.item.sheet form .tab.active.rules .rule-form label input,
+.pf2e.item.sheet form .tab.active.rules .rule-form label tags {
+ flex: 1;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] label.short {
- min-width: 5em;
+.pf2e.item.sheet form .tab.active.rules .rule-form label input[type=checkbox] {
+ width: 1rem;
+ height: 1rem;
+ flex-basis: auto;
}
-.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] .column-span-two {
- grid-column: span 2;
+.pf2e.item.sheet form .tab.active.rules .rule-form label input[type=checkbox]:first-child:last-child {
+ margin-left: auto;
+ justify-self: flex-end;
}
-.pf2e.item.sheet form label {
- display: block;
+.pf2e.item.sheet form .tab.active.rules .rule-form select.short {
+ flex: 0 0 auto;
}
-.pf2e.item.sheet form input:not(:disabled) {
- color: var(--color-text-dark-input);
+.pf2e.item.sheet form .tab.active.rules .rule-form .content-link {
+ display: flex;
+ flex: 0 0 auto;
+ flex-direction: row;
+ align-items: center;
+ gap: 3px;
}
-.pf2e.item.sheet form .mce-panel span {
- display: inherit;
+.pf2e.item.sheet form .tab.active.rules .rule-form .content-link img {
+ width: 16px;
+ height: 16px;
}
-.pf2e.item.sheet form.editable .rollable:hover {
- color: var(--text-dark);
- text-shadow: 0 0 10px #00005a;
- cursor: pointer;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header {
+ display: flex;
+ align-items: center;
+ margin-bottom: 0.25rem;
}
-.pf2e.item.sheet form .tab {
+.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header .drag-handle {
+ cursor: grab;
+ font-weight: normal;
+ margin-right: 0.375rem;
+ padding: 0.125rem;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header h3 {
flex: 1;
+ margin: 0;
}
-.pf2e.item.sheet form:has(.tab.active.rules) .sidebar-summary {
- visibility: hidden;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header h3.unrecognized {
+ color: #880000;
}
-.pf2e.item.sheet form:has(.tab.active.rules) section.sidebar {
- display: none;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header .priority {
+ margin-right: 0.75rem;
}
-.pf2e.item.sheet form .tag-legacy {
- float: left;
- margin: 0 2px 2px 0;
- padding: 0 3px;
- font-size: var(--font-size-10);
- line-height: 16px;
- border: 1px solid #999;
- border-radius: 3px;
- white-space: normal;
- font-weight: 500;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header .priority input {
+ width: 4ch;
}
-.pf2e.item.sheet form p.hint {
- font-family: var(--font-primary);
- font-weight: normal;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rule-element-header .item-controls {
+ margin-left: auto;
}
-.pf2e.item.sheet form .item-controls {
+.pf2e.item.sheet form .tab.active.rules .rule-form .form-fields [data-action] {
+ flex: 0 0 auto;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form .range {
display: flex;
- margin: 0 0 0 4px;
- align-items: baseline;
- gap: 2px;
+ gap: 3px;
+ align-items: center;
}
-.pf2e.item.sheet form i.fa-info-circle {
- cursor: help;
+.pf2e.item.sheet form .tab.active.rules .rule-form .range input {
+ width: 40px;
}
-.pf2e.item.sheet form > nav {
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input {
+ align-items: center;
display: flex;
- align-items: baseline;
- border-bottom: 1px solid var(--secondary-background);
- flex: 0 0 30px;
- line-height: 30px;
- margin-bottom: 0.5rem;
+ flex: 2;
+ justify-content: center;
}
-.pf2e.item.sheet form > nav a {
- flex: 1 1 auto;
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .attachment,
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input input,
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .tags {
+ z-index: 0;
}
-.pf2e.item.sheet form > nav a.active {
- text-decoration: underline;
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .attachment:hover, .pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .attachment:focus,
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input input:hover,
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input input:focus,
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .tags:hover,
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .tags:focus {
+ z-index: 1;
}
-.pf2e.item.sheet form > nav .sidebar-summary {
- flex: 0 0 220px;
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .attachment {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ padding: 0 6px;
margin: 0;
- text-align: center;
+ line-height: unset;
+ flex: 0 0 auto;
+ width: auto;
+ min-width: 68px;
+ align-self: stretch;
+ border: 1px solid #aaa;
+ border-right: none;
+ border-radius: 3px 0 0 3px;
}
-.pf2e.item.sheet form > nav .sheet-tabs {
- font-weight: 500;
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input .file-picker {
+ line-height: unset;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input input,
+.pf2e.item.sheet form .tab.active.rules .rule-form .attached-input tags {
+ border-top-left-radius: 0;
+ border-bottom-left-radius: 0;
margin: 0;
flex: 1;
- align-items: baseline;
-}
-.pf2e.item.sheet form > nav .sheet-tabs > .list-row {
- font-size: var(--font-size-12);
- text-align: center;
-}
-.pf2e.item.sheet form > nav .sheet-tabs > .list-row:last-of-type {
- padding-right: 4px;
}
-.pf2e.item.sheet form > nav .sheet-tabs > .list-row.active {
- font-weight: 600;
+.pf2e.item.sheet form .tab.active.rules .rule-form .brackets {
+ margin-left: 9.5em;
}
-.pf2e.item.sheet form .sheet-content {
- width: 100%;
+.pf2e.item.sheet form .tab.active.rules .rule-form .brackets .bracket {
+ align-items: center;
display: flex;
- flex-direction: row;
- flex-wrap: wrap;
- justify-content: flex-start;
- height: calc(100% - 35px);
- overflow: hidden;
+ gap: 4px;
}
-.pf2e.item.sheet form .sheet-content > * {
+.pf2e.item.sheet form .tab.active.rules .rule-form .brackets .bracket .value {
flex: 1;
}
-.pf2e.item.sheet form .sheet-content > section.sidebar,
-.pf2e.item.sheet form .sheet-content > .sheet-body {
- height: calc(100% - 10px);
- overflow-y: auto;
+.pf2e.item.sheet form .tab.active.rules .rule-form nav.rule-tabs {
+ border-bottom: 1px solid var(--secondary-background);
}
-.pf2e.item.sheet form .sheet-content section.sidebar {
- flex: 0 0 220px;
+.pf2e.item.sheet form .tab.active.rules .rule-form nav.rule-tabs h4 {
display: flex;
- flex-direction: column;
- flex-wrap: nowrap;
+ justify-content: space-evenly;
+ width: 100%;
+ margin-top: 0.5em;
+ font-weight: 200;
}
-.pf2e.item.sheet form .sheet-content section.sidebar > * {
- flex: 1;
+.pf2e.item.sheet form .tab.active.rules .rule-form nav.rule-tabs a.active {
+ font-weight: 600;
+ text-decoration: underline;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .item-summary {
- font-family: var(--serif-condensed);
- font-weight: 700;
- flex: 0 0 28px;
- line-height: 28px;
- text-align: center;
- font-size: var(--font-size-18);
- color: #444;
+.pf2e.item.sheet form .tab.active.rules .rule-form .validation-failures {
+ background: rgba(214, 150, 0, 0.5);
+ border-radius: 3px;
}
-.pf2e.item.sheet form .sheet-content section.sidebar ol.item-tags {
- padding-left: 0;
- flex: 0;
- list-style: none;
+.pf2e.item.sheet form .tab.active.rules .rule-form .validation-failures ul {
+ list-style: "\f071" outside;
+ padding: 0.25em 0.25em 0.25em 1.5em;
}
-.pf2e.item.sheet form .sheet-content section.sidebar ol.item-tags .tag {
- align-items: center;
+.pf2e.item.sheet form .tab.active.rules .rule-form .validation-failures ul li {
+ font-weight: 900;
+ font-family: var(--font-awesome);
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form .validation-failures ul li > span {
+ margin-left: 0.25em;
+ font-weight: normal;
+ font-family: var(--font-primary);
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container {
+ display: flex;
justify-content: center;
+ align-items: center;
width: 100%;
+ height: 4em;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details {
- overflow: hidden scroll;
- padding: 0 4px 0 0;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container .rules-drop-zone {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ width: 40%;
+ height: 3.5em;
+ border: 1px solid var(--color-border-light-primary);
+ border-radius: 3px;
+ color: #222;
+ background-color: #ddd;
+ cursor: default;
+ padding: 1px 6px;
+ font-family: var(--font-primary);
+ font-size: var(--font-size-14);
+ line-height: 28px;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details label,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details label {
- font-weight: 500;
- max-width: 6em;
- white-space: nowrap;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container .rules-drop-zone i {
+ border: 1px solid #bbb;
+ border-radius: 2px;
+ align-items: center;
+ display: flex;
+ height: 1.6em;
+ justify-content: center;
+ margin-right: 0.5em;
+ width: 1.6em;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group {
- margin: 3px 0;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container .rules-drop-zone i:after {
+ font-size: var(--font-size-20);
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group input,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group input {
- text-align: right;
+.pf2e.item.sheet form .tab.active.rules .rule-form .rules-drop-container .rules-drop-zone span {
+ color: var(--text-dark);
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group input.left-of-select,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group input.left-of-select {
- min-width: 4ch;
- padding-right: 0.25em;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .grid-item {
+ display: grid;
+ grid: 1fr/5em 1fr;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group select,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group select {
- max-width: 12em;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .grid-item.long-label {
+ grid: 1fr/9em 1fr;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group.longtext,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group.longtext {
- height: fit-content;
- align-items: start;
- margin: 0 0 0.5em 0;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .checkbox {
+ display: flex;
+ justify-content: flex-end;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group.longtext label,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group.longtext label {
- max-width: 6em;
- white-space: normal;
- line-height: unset;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .item-controls {
+ justify-content: flex-end;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group.longtext .editor-content,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group.longtext .editor-content {
- min-height: 3em;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .item-controls a {
+ margin: 2px 5px 0 0;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .form-group.longtext .editor-content > p,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .form-group.longtext .editor-content > p {
- font-weight: 400;
- margin: 0;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .stacked {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ column-gap: 0.5rem;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .price-fields,
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .price-fields {
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .column-span-two {
+ grid-column: span 2;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .resolvable {
+ grid-column: span 2;
display: flex;
- gap: 4px;
+ align-items: center;
}
-.pf2e.item.sheet form .sheet-content section.sidebar .inventory-details .price-fields input[name="system.price.per"],
-.pf2e.item.sheet form .sheet-content section.sidebar .feat-details .price-fields input[name="system.price.per"] {
- width: 22px;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .brackets-container {
+ grid-column: span 3;
}
-.pf2e.item.sheet form .sheet-content section.sidebar select {
- font-family: inherit;
- font-size: 0.85em;
- height: 1.8em;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] label {
+ min-width: 5em;
+ font-weight: 500;
}
-.pf2e.item.sheet form .sheet-content section.sidebar button {
- padding-top: 0;
- padding-bottom: 0;
- white-space: nowrap;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] label.short {
+ max-width: 5em;
}
-.pf2e.item.sheet form .sheet-content input[type=text], .pf2e.item.sheet form .sheet-content input[type=number] {
- border: 1px solid transparent;
- height: calc(100% - 2px);
- margin: 1px 0;
- width: calc(100% - 2px);
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] label.with-hint {
+ margin-right: 5px;
}
-.pf2e.item.sheet form .sheet-content select {
- background: rgba(255, 255, 255, 0.5);
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] fieldset {
+ grid-column: span 2;
+ padding-bottom: 0.4rem;
}
-.pf2e.item.sheet form .sheet-content button:hover:not(:disabled), .pf2e.item.sheet form .sheet-content button:focus,
-.pf2e.item.sheet form .sheet-content input:not([type=range]):hover:not(:disabled),
-.pf2e.item.sheet form .sheet-content input:not([type=range]):focus,
-.pf2e.item.sheet form .sheet-content select:hover:not(:disabled),
-.pf2e.item.sheet form .sheet-content select:focus {
- border-color: var(--color-border-dark-1);
- box-shadow: 0 0 5px var(--secondary);
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] .brackets {
+ margin-left: 6em;
}
-.pf2e.item.sheet form .sheet-body input[type=text],
-.pf2e.item.sheet form .sheet-body input[type=number] {
- padding: 3px;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab] hr {
+ grid-column: span 2;
+ width: 100%;
}
-.pf2e.item.sheet form .sheet-body input[type=text]:not(:disabled),
-.pf2e.item.sheet form .sheet-body input[type=number]:not(:disabled) {
- background: rgba(255, 255, 255, 0.5);
- border: 1px solid var(--color-text-light-5);
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] {
+ height: 90px;
+ overflow-y: auto;
}
-.pf2e.item.sheet form .sheet-body .tab.active {
- overflow: hidden scroll;
- padding-left: 0.5rem;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .item-container {
+ grid-column: span 2;
+ display: grid;
+ grid: 1fr/5em 10fr 1fr;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description {
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .item-container a.content-link {
display: flex;
- flex-direction: column;
- gap: 3px;
- height: 100%;
- padding: 0 0.25em;
+ align-items: center;
+ gap: 0.5em;
+ width: fit-content;
+ min-width: 12rem;
+ height: 2em;
+ padding: 4px;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description > * {
- display: flex;
- overflow: hidden;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .item-container a.content-link img {
+ border: 1px solid var(--color-border-dark);
+ border-radius: 2px;
+ box-sizing: border-box;
+ display: block;
+ float: left;
+ height: 24px;
+ width: 24px;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor {
- min-height: 2.5em;
- flex: 1;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .item-container a.content-link span {
+ text-wrap: wrap;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description.editing {
- overflow: hidden;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .three-items {
+ grid-column: span 2;
+ display: grid;
+ grid: 1fr/5em 8fr 7em 5fr 6em 1fr;
+ margin-top: 5px;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description.editing > section {
- flex: 1;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .three-items select {
+ width: fit-content;
+ min-width: 10em;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .gm-notes {
- background-color: var(--visibility-gm-bg);
- border: 1px dotted rgba(75, 74, 68, 0.5);
- padding: 0 0.25em;
- flex: 0 0 auto;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .saves-container {
+ display: grid;
+ grid: 1fr/5em 8.8fr;
+ align-items: center;
+ row-gap: 5px;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .gm-notes:not(.has-content) {
- display: none;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .saves-container select {
+ width: fit-content;
+ min-width: 10em;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .main {
- flex: 1 0 auto;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=effects] .rules-drop-container {
+ grid-column: span 2;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor {
- display: flex;
- flex-direction: column;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .translation input {
+ width: 5em;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.add-gm-notes,
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.editor-edit {
- font-size: 1.33em;
- background: rgb(205, 205, 205);
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] input[type=checkbox] {
+ margin-left: unset;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.add-gm-notes i,
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.editor-edit i {
- width: 1em;
- text-align: center;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items {
+ display: flex;
+ justify-content: space-between;
+ gap: 0.5em;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor a.add-gm-notes {
- border-radius: 4px;
- border: 1px solid var(--color-border-dark-1);
- box-shadow: 0 0 1px var(--color-shadow-dark);
- display: none;
- padding: 1px 2px;
- position: absolute;
- right: 35px;
- top: 5px;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items > label {
+ min-width: unset;
+ width: fit-content;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor:hover a.add-gm-notes {
- display: block;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker {
+ align-items: center;
+ display: flex;
+ width: 16rem;
+ white-space: nowrap;
}
-.pf2e.item.sheet form .sheet-body .tab.active.description .editor .tox {
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker input[type=text] {
flex: 1;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details {
- padding: 0.5rem 0.5rem 0;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker input[type=color] {
+ flex: 2;
+ height: 94%;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details label {
- color: var(--color-text-dark-2);
- font-weight: 500;
- padding-right: 0.5em;
- white-space: nowrap;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker input[type=color]:disabled {
+ background: rgba(0, 0, 0, 0.05);
+ border: 1px solid transparent;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details label.no-data {
- color: var(--color-text-dark-4);
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker .user {
+ flex: 0;
+ gap: 0;
+ justify-content: start;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details select {
- font-size: var(--font-size-12);
- height: 1.5rem;
- padding-right: 1em;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker .user input[type=checkbox] {
+ flex: 0;
+ margin-left: 0;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details .tags .tag {
- font-size: var(--font-size-10);
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .two-items .color-picker .user span {
+ font-size: small;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data {
- align-items: baseline;
- gap: 0.25em;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items {
display: grid;
- grid-template: "title title title" 2fr "authors license remaster" 3fr/60% 20% 20%;
+ grid-template-columns: 5em 2.5fr 1fr;
+ align-items: center;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data label {
- font-weight: 500;
- min-width: unset;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items.long-label {
+ grid: 1fr/9em 2.5fr 1fr;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data input[type=text] {
- height: 1.6rem;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items input[type=color] {
+ min-width: 7em;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items.image-path {
+ grid-column: span 2;
+ grid: 1fr/9em 8fr 1fr;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Aura] div[data-rule-tab=appearance] .three-items.image-path button.file-picker {
+ margin: unset;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=Note] {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] {
+ display: grid;
+ grid: "label content" 1fr/1fr 1fr;
+ column-gap: 5px;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .title {
- grid-area: title;
- margin-right: 0;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] fieldset.radii {
+ display: flex;
+ flex-direction: column;
+ grid-column: span 2;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .authors {
- grid-area: authors;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] fieldset.radii .brackets {
+ margin-left: 6.5em;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .license {
- grid-area: license;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] label {
+ display: flex;
+ flex: unset;
+ margin-left: 5px;
+ margin-right: 5px;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .license select {
- margin-top: 1px;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] label.short {
+ min-width: 5em;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .remaster {
- grid-area: remaster;
+.pf2e.item.sheet form .tab.active.rules .rule-form[data-key=TokenLight] div[data-rule-tab] .column-span-two {
+ grid-column: span 2;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .license,
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .remaster {
- text-align: center;
+.pf2e.item.sheet a.disabled {
+ cursor: default;
}
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .license label,
-.pf2e.item.sheet form .sheet-body .tab.active.details fieldset.publication .data .remaster label {
- padding: 0;
+.pf2e.item.sheet a.disabled:hover {
+ text-shadow: none;
}
-.pf2e.item.sheet form .sheet-body fieldset {
- border: 1px solid var(--color-border-medium);
- border-radius: 2px;
- margin-bottom: 0.5rem;
- padding: 0 0.5em 0.25em;
+.pf2e.item.sheet a.disabled.header-button {
+ color: var(--color-text-light-5);
}
-.pf2e.item.sheet form .sheet-body fieldset legend {
- font-weight: 600;
+.pf2e.item.sheet.action form .drop-zone {
+ align-items: center;
+ border: 1px solid var(--color-border-light-tertiary);
+ display: flex;
+ gap: 0.25rem;
+ max-width: fit-content;
+ padding: 0 4px 0 0;
}
-.pf2e.item.sheet form .sheet-body fieldset.basics {
- border-color: transparent;
- padding: 0;
+.pf2e.item.sheet.action form .drop-zone.empty {
+ font-weight: normal;
+ min-width: 12rem;
+ padding: 4px;
}
-.pf2e.item.sheet form .sheet-body .editor {
- --space-s: 0.25em;
- --space-m: 0.5em;
- --space-l: 1em;
- --space-xl: 1.5em;
- --space-2xl: 2em;
- --radius: 3px;
+.pf2e.item.sheet.action form .drop-zone.empty .name {
+ font-style: italic;
+ flex: 1;
+ text-align: center;
}
-.pf2e.item.sheet form .sheet-body .editor p {
- min-height: unset;
+.pf2e.item.sheet.action form .drop-zone picture,
+.pf2e.item.sheet.action form .drop-zone img {
+ border: 1px solid var(--color-border-dark);
+ border-radius: 2px;
+ box-sizing: border-box;
+ display: block;
+ float: left;
+ height: 24px;
+ width: 24px;
}
-.pf2e.item.sheet form .sheet-body .editor :is(h1, h2, h3, h4, h5, h6):not(:first-child) {
- margin-top: 1em;
+.pf2e.item.sheet.action form .drop-zone a.content-link {
+ align-items: center;
+ border: none;
+ border-right: 1px solid var(--color-border-light-2);
+ display: flex;
+ gap: 0.5em;
+ min-width: 9rem;
+ padding: 4px;
}
-.pf2e.item.sheet form .sheet-body .editor .inline-header {
+.pf2e.item.sheet.action form .drop-zone a.delete {
display: flex;
+}
+.pf2e.item.sheet.affliction form .affliction-stage .link:not(.linked) {
+ opacity: 0.6;
+ color: #a00;
+}
+.pf2e.item.sheet.affliction form .affliction-stage .formula-row {
align-items: center;
- gap: var(--space-l);
- background-color: var(--alt);
- font-family: var(--sans-serif);
- color: var(--text-light);
- padding: 0;
- font-size: 0.8em;
- font-weight: 400;
- border: none;
+ display: flex;
+ gap: 4px;
}
-.pf2e.item.sheet form .sheet-body .editor .inline-header strong {
- display: inline-flex;
- padding: 0 var(--space-m);
- background-color: var(--primary);
- min-width: 15ch;
- border-right: 1px solid rgba(0, 0, 0, 0.4);
- box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.2);
- font-weight: 400;
+.pf2e.item.sheet.consumable form .form-group.price input.per {
+ max-width: 4ch;
}
-.pf2e.item.sheet form .sheet-body .editor .inline-header + p {
- margin-top: var(--space-s);
+.pf2e.item.sheet.consumable form .form-group.damage a,
+.pf2e.item.sheet.consumable form .form-group.damage button,
+.pf2e.item.sheet.consumable form .form-group.damage select {
+ max-width: fit-content;
}
-.pf2e.item.sheet form .sheet-body .editor .info {
- background-color: var(--secondary);
- padding: var(--space-m);
- color: var(--text-light);
- margin-left: auto;
- margin-right: auto;
- padding: 0;
- border-radius: var(--radius);
- font-family: var(--sans-serif);
- padding-bottom: var(--space-m);
+.pf2e.item.sheet.deity form .tab.details .form-group.fonts {
+ display: flex;
+ gap: 0.25rem;
}
-.pf2e.item.sheet form .sheet-body .editor .info > * + * {
- margin-top: var(--space-m);
+.pf2e.item.sheet.deity form .tab.details .form-group.fonts .form-fields {
+ justify-content: start;
}
-.pf2e.item.sheet form .sheet-body .editor .info + * {
- margin-top: var(--space-xl);
+.pf2e.item.sheet.deity form .tab.details .form-group.fonts .form-fields label {
+ font-weight: normal;
}
-.pf2e.item.sheet form .sheet-body .editor .info + .pf2e.item.sheet form .sheet-body .editor .info {
- margin-top: var(--space-s);
+.pf2e.item.sheet.effect form .sheet-content .sidebar .inventory-details .form-group select {
+ max-width: fit-content;
}
-.pf2e.item.sheet form .sheet-body .editor .info h4 {
- font-size: 0.9em;
- font-weight: 400;
- line-height: 1.2;
- font-family: var(--sans-serif);
- border-bottom: 1px solid rgba(0, 0, 0, 0.6);
- padding: var(--space-m) var(--space-l);
- position: relative;
- display: flex;
+.pf2e.item.sheet.effect form .sheet-content .sidebar .inventory-details .form-group .form-group.duration label {
+ max-width: fit-content;
+ padding-right: 0.1em;
+}
+.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row {
align-items: center;
- justify-content: space-between;
- color: var(--text-light);
+ display: flex;
+ gap: 4px;
+ width: 100%;
}
-.pf2e.item.sheet form .sheet-body .editor .info h4::after {
- font-family: "Font Awesome 6";
- content: "\f05a";
- font-weight: 900;
- margin-right: var(--space-s);
+.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row label {
+ cursor: pointer;
+ max-width: unset;
}
-.pf2e.item.sheet form .sheet-body .editor .info p {
- font-size: 0.8em;
+.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row input[type=radio] {
margin: 0;
- padding: 0 var(--space-l);
+ top: 0;
}
-.pf2e.item.sheet form .sheet-body .editor .info p:first-of-type {
- padding-top: var(--space-m);
- border-top: 1px solid rgba(255, 255, 255, 0.1);
+.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row .badge-value {
+ margin-right: 0.1rem;
+ width: 3ch;
+ font-weight: bold;
+ text-align: end;
}
-.pf2e.item.sheet form .sheet-body .editor .traits {
+.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-row input[type=text] {
+ flex: 1;
+ text-align: end;
+}
+.pf2e.item.sheet.effect form .sheet-content .sidebar .badge-label-header {
display: flex;
- flex-wrap: wrap;
- padding: 0;
+ align-items: center;
+ justify-content: space-between;
+ margin: 0.5em 0 0.25em 0;
}
-.pf2e.item.sheet form .sheet-body .editor .traits p {
- display: inline-flex;
- padding: 0.16rem 0.25rem;
- margin: 0;
- background-color: var(--primary);
- border: 2px solid var(--color-border-trait);
- color: var(--text-light);
- font: 500 var(--font-size-10) var(--sans-serif);
- text-transform: uppercase;
+.pf2e.item.sheet.effect form .sheet-content .sidebar .add-badge {
+ display: flex;
+ align-items: center;
}
-.pf2e.item.sheet form .sheet-body .editor .statblock {
- font-family: var(--sans-serif-condensed);
- color: var(--text-dark);
- line-height: 1.2;
- margin-bottom: var(--space-m);
+.pf2e.item.sheet.effect form .sheet-content .sidebar .add-badge select {
+ flex: 1;
+ max-width: unset;
}
-.pf2e.item.sheet form .sheet-body .editor .statblock > * + * {
- margin-top: var(--space-s);
- margin-bottom: 0;
+.pf2e.item.sheet.effect form .sheet-content .sidebar .add-badge button {
+ flex: 0;
+ line-height: 1.2em;
}
-.pf2e.item.sheet form .sheet-body .editor .statblock p {
- --indent: var(--space-l);
- margin-left: var(--indent);
- position: relative;
+.pf2e.item.sheet.feat form .drop-zone {
+ align-items: center;
+ border: 1px solid var(--color-border-light-tertiary);
+ display: flex;
+ gap: 0.25rem;
+ max-width: fit-content;
+ padding: 0 4px 0 0;
}
-.pf2e.item.sheet form .sheet-body .editor .statblock p strong:first-of-type {
- margin-left: calc(var(--indent) * -1);
+.pf2e.item.sheet.feat form .drop-zone.empty {
+ font-weight: normal;
+ min-width: 12rem;
+ padding: 4px;
}
-.pf2e.item.sheet form .sheet-body .editor .statblock p .trait:first-of-type {
- margin-left: calc(var(--indent) * -1 - 2px);
+.pf2e.item.sheet.feat form .drop-zone.empty .name {
+ font-style: italic;
+ flex: 1;
+ text-align: center;
}
-.pf2e.item.sheet form .sheet-body .editor .statblock span.pf2-icon {
- line-height: 1;
+.pf2e.item.sheet.feat form .drop-zone picture,
+.pf2e.item.sheet.feat form .drop-zone img {
+ border: 1px solid var(--color-border-dark);
+ border-radius: 2px;
+ box-sizing: border-box;
+ display: block;
+ float: left;
+ height: 24px;
+ width: 24px;
+}
+.pf2e.item.sheet.feat form .drop-zone a.content-link {
+ align-items: center;
+ border: none;
+ border-right: 1px solid var(--color-border-light-2);
+ display: flex;
+ gap: 0.5em;
+ min-width: 9rem;
+ padding: 4px;
}
-.pf2e.item.sheet form .sheet-body .editor .statblock h1,
-.pf2e.item.sheet form .sheet-body .editor .statblock h2,
-.pf2e.item.sheet form .sheet-body .editor .statblock h3,
-.pf2e.item.sheet form .sheet-body .editor .statblock h4 {
+.pf2e.item.sheet.feat form .drop-zone a.delete {
display: flex;
- align-items: baseline;
- justify-content: space-between;
- border-bottom: 1px solid var(--color-border-dark);
- text-transform: uppercase;
- letter-spacing: -0.05em;
- font-family: var(--sans-serif-condensed);
- font-weight: 700;
}
-.pf2e.item.sheet form .sheet-body .editor .statblock hr {
- border: none;
- border-bottom: 1px solid var(--color-border-dark);
+.pf2e.item.sheet.feat form .tab.details .form-group > label {
+ min-width: fit-content;
+ margin-right: 1em;
}
-.pf2e.item.sheet form .sheet-body .editor .message {
- font-family: var(--journal-cursive);
- font-size: 2em;
- line-height: 1.2;
+.pf2e.item.sheet.heritage form section.sidebar .required-ancestry {
+ flex-wrap: nowrap;
+ width: 100%;
+ white-space: nowrap;
+ max-width: 100%;
}
-.pf2e.item.sheet form h3 .item-controls,
-.pf2e.item.sheet form header .item-controls {
- float: right;
+.pf2e.item.sheet.heritage form section.sidebar .required-ancestry label {
+ flex: 0;
}
-.pf2e.item.sheet form .form-list h3, .pf2e.item.sheet form fieldset h3 {
- font-weight: 600;
- font-size: 1.05em;
- margin-bottom: 0.25em;
+.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone {
+ background-color: rgba(0, 0, 0, 0.05);
+ border-radius: 2px;
+ border: 1px dotted var(--alt-dark);
+ display: flex;
+ font-weight: normal;
+ justify-content: center;
+ margin: 2px 3px 0 auto;
+ max-width: 8em;
+ padding: 3px;
+ position: relative;
}
-.pf2e.item.sheet form .form-list {
- border-radius: 5px;
- border: 1px solid var(--secondary-background);
- list-style-type: none;
- margin: 0.5em 0;
- padding: 0.25em;
+.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone span {
+ display: inline-block;
+ overflow: hidden;
+ text-overflow: ellipsis;
}
-.pf2e.item.sheet form .form-list:first-child {
- margin-top: 0;
+.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone.ancestry-ref-broken {
+ background-color: rgba(255, 0, 0, 0.15);
+ border-color: var(--primary);
}
-.pf2e.item.sheet form .form-list.subsection {
- padding: 0;
+.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone a.remove-ancestry {
+ display: none;
+ position: absolute;
+ right: -0.5em;
+ top: -0.25em;
}
-.pf2e.item.sheet form .form-list.subsection > * {
- padding: 0.25rem;
+.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone a.remove-ancestry:hover {
+ display: flex;
}
-.pf2e.item.sheet form .form-list.subsection > header {
- align-items: baseline;
- background-color: var(--secondary);
- border-radius: 5px 5px 0 0;
- color: var(--text-light);
+.pf2e.item.sheet.heritage form section.sidebar .required-ancestry .drop-zone:hover a.remove-ancestry {
display: flex;
- justify-content: space-between;
- margin: -1px -1px 0 -1px;
- padding: 1px;
}
-.pf2e.item.sheet form .form-list.subsection > header h3,
-.pf2e.item.sheet form .form-list.subsection > header .item-controls {
- padding: 0.25rem;
- margin-bottom: 0;
+.pf2e.item.sheet.kit form .kit-list ul.kit-items {
+ padding: 0;
}
-.pf2e.item.sheet form .two-by-two {
+.pf2e.item.sheet.kit form .kit-list ul.kit-items li.kit-item {
display: grid;
- grid-template-columns: 1fr 1fr;
- column-gap: 0.25rem;
-}
-.pf2e.item.sheet form .two-by-two .item-controls {
- margin-left: 2px;
- gap: 0;
+ grid-template-columns: 26px 30px auto 10px;
+ align-items: center;
}
-.pf2e.item.sheet form .form-group.scalable {
- height: auto;
- min-height: 1.5rem;
+.pf2e.item.sheet.kit form .kit-list ul.kit-items li.kit-item:nth-of-type(even) {
+ background-color: rgba(120, 100, 82, 0.1);
}
-.pf2e.item.sheet form .form-group.scalable ul.traits-list {
- list-style-type: none;
+.pf2e.item.sheet.kit form .kit-list ul.kit-items li.kit-item .kit-item-name {
+ line-height: 1em;
+ height: 1em;
}
-.pf2e.item.sheet form .form-group > label:not(.large) {
- max-width: 11em;
+.pf2e.item.sheet.kit form .kit-list ul.kit-items li.kit-item .kit-item-name .fa.fa-globe {
+ padding: 0 3px;
+ float: right;
}
-.pf2e.item.sheet form .form-group > label.short {
- max-width: 9em;
+.pf2e.item.sheet.kit form .kit-list ul.kit-items ul {
+ padding-left: 0.5em;
+ margin-top: 0;
+ grid-column: 1/5;
}
-.pf2e.item.sheet form .form-group .item-controls {
- flex: 0 1 auto;
+.pf2e.item.sheet.kit form .kit-list ul.kit-items ul:empty {
+ display: none;
}
-.pf2e.item.sheet form .form-group input.adjusted-higher:not(:focus) {
- font-weight: 700;
- color: #009988;
+.pf2e.item.sheet.melee form .sheet-body .tab.details .form-group.attack-modifier label,
+.pf2e.item.sheet.melee form .sheet-body .tab.details li.damage-partial form-group label {
+ max-width: fit-content;
}
-.pf2e.item.sheet form .form-group input.adjusted-lower:not(:focus) {
- font-weight: 700;
- color: #cc3311;
+.pf2e.item.sheet.melee form .sheet-body .tab.details .form-group.attack-modifier input,
+.pf2e.item.sheet.melee form .sheet-body .tab.details li.damage-partial form-group input {
+ max-width: 6ch;
}
-.pf2e.item.sheet form .details-container,
-.pf2e.item.sheet form .dice-data {
- display: grid;
- grid: "dice die type"/40px 60px auto;
+.pf2e.item.sheet.melee form .sheet-body .tab.details ol.form-list li.damage-partial {
+ align-items: center;
+ display: flex;
+ gap: 1em;
}
-.pf2e.item.sheet form .effects-container {
- display: grid;
- grid: "effect number"/auto 40px;
+.pf2e.item.sheet.melee form .sheet-body .tab.details ol.form-list li.damage-partial input {
+ max-width: 12ch;
}
-.pf2e.item.sheet form .details-container-two-columns {
- display: grid;
- grid: "size type"/50% 50%;
+.pf2e.item.sheet.melee form .sheet-body .tab.details ol.form-list li.damage-partial .type {
+ gap: 0.25em;
}
-.pf2e.item.sheet form .details-container-three-columns {
- display: grid;
- grid-template-columns: 1fr 1fr 1fr;
+.pf2e.item.sheet.melee form .sheet-body .tab.details ol.form-list li.damage-partial .remove-partial {
+ margin: 0 0.5em 0 auto;
}
-.pf2e.item.sheet form .form-fields > label {
+.pf2e.item.sheet.spell form .tab.details.active .save-basic {
display: flex;
- align-items: center;
- white-space: nowrap;
+ flex-wrap: nowrap;
+ justify-content: end;
}
-.pf2e.item.sheet form .form-fields select {
- flex: 1;
- width: auto;
+.pf2e.item.sheet.spell form .tab.details.active .damage-formulas {
+ margin-top: 0.5rem;
}
-.pf2e.item.sheet form .toggle-button-list {
- display: flex;
+.pf2e.item.sheet.spell form .tab.details.active .damage-formulas .form-fields {
gap: 2px;
- margin: 4px 0;
+ white-space: nowrap;
}
-.pf2e.item.sheet form .toggle-button-list button {
- margin: 0;
- font-size: var(--font-size-10);
- line-height: 16px;
- display: flex;
- align-items: center;
+.pf2e.item.sheet.spell form .tab.details.active .damage-formulas .form-fields .apply-mod {
white-space: nowrap;
- padding: 3px 4px;
}
-.pf2e.item.sheet form .consumable-details {
- flex: 0 0 24px;
+.pf2e.item.sheet.spell form .tab.details.active .damage-formulas .form-fields select {
+ max-width: 8em;
}
-.pf2e.item.sheet form .consumable-details label {
- font-weight: bold;
+.pf2e.item.sheet.spell form .tab.details.active .damage-formulas .form-fields .materials {
+ align-self: end;
}
-.pf2e.item.sheet form .consumable-details input {
- flex: 0 0 24px;
- margin-right: 6px;
- text-align: right;
+.pf2e.item.sheet.spell form .tab.details.active button + fieldset {
+ margin-top: 0.5rem;
}
-.pf2e.item.sheet form .consumable-details span {
- line-height: 24px;
+.pf2e.item.sheet.spell form .tab.details.active fieldset.heightening {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
}
-.pf2e.item.sheet form .consumable-details .max-charges {
- flex: 0 0 16px;
- text-align: center;
+.pf2e.item.sheet.spell form .tab.details.active fieldset.heightening .add {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
}
-.pf2e.item.sheet form .consumable-charges label {
- flex: 0 0 144px;
+.pf2e.item.sheet.spell form .tab.details.active fieldset.heightening .add button.only-option {
+ grid-column: span 2;
}
-.pf2e.item.sheet form .consumable-charges input {
- flex: 0 0 64px;
- text-align: center;
+.pf2e.item.sheet.spell form .tab.details.active fieldset.heightening .overlay .toggle-button-list {
+ column-gap: 2px;
+ display: grid;
+ grid-template-columns: repeat(6, 1fr);
+ margin: 4px 0;
}
-.pf2e.item.sheet form .consumable-charges span.flex0 {
- line-height: 24px;
+.pf2e.item.sheet.spell form .tab.details.active fieldset.heightening .overlay .toggle-button-list button {
+ font-size: var(--font-size-12);
+ line-height: normal;
+ margin: 0;
+ padding: 0.25em;
+ white-space: nowrap;
}
-.pf2e.item.sheet form .feat-uses select {
- flex: 2;
- margin-right: 5px;
+.pf2e.item.sheet.spell form .tab.details.active .overlay .traits {
+ align-items: center;
+ display: flex;
+ gap: 4px;
}
-.pf2e.item.sheet form .feat-uses input {
+.pf2e.item.sheet.spell form .tab.details.active .overlay .traits .tags {
flex: 1;
- text-align: center;
-}
-.pf2e.item.sheet form .feat-uses span.sep {
- flex: 0 0 16px;
- line-height: 24px;
- font-size: var(--font-size-14);
- text-align: center;
-}
-.pf2e.item.sheet form .spell-components input {
- margin-left: 0;
-}
-.pf2e.item.sheet form .spell-components label {
- padding-right: 6px;
-}
-.pf2e.item.sheet form input.adjusted:not(:focus) {
- font-weight: 700;
- color: #009988;
}
-.pf2e.item.sheet form .frequency {
- align-items: baseline;
- display: flex;
- gap: 0.2rem;
- text-align: end;
+.pf2e.item.sheet.spell form .tab.details.active .variants .variant {
+ display: grid;
+ grid-template-columns: 1fr 1fr 0.2fr;
}
-.pf2e.item.sheet form .frequency.empty {
- justify-content: flex-end;
+.pf2e.item.sheet.spell form .tab.details.active .variants .variant .item-controls {
+ justify-self: end;
}
-.pf2e.item.sheet form .frequency select {
- flex: 1 1 auto;
+.pf2e.item.sheet.weapon form .tab.details label {
+ min-width: 9em;
}
-.pf2e.item.sheet form .frequency a {
- align-self: center;
+.pf2e.item.sheet.weapon form .tab.details .precious-material select {
+ width: 19.5em;
}
.persistent-damage-dialog {
/** Work around Font Awesome styling bug present as of version 6.2 */
@@ -17250,10 +17392,6 @@ body > .choices__list--dropdown {
.persistent-damage-dialog .persistent-entry .input-fields .dc {
width: 2.5rem;
}
-.persistent-damage-dialog .persistent-entry .input-fields .invalid {
- box-shadow: 0 0 5px 0px red;
- border-color: red;
-}
#darkness-adjuster {
background: none;
box-shadow: 0 0 10px black;
@@ -17360,7 +17498,7 @@ body > .choices__list--dropdown {
#darkness-adjuster .synchronized .slider .noUi-origin .noUi-handle.darkness-level .noUi-touch-area, #darkness-adjuster .synchronized .slider .noUi-origin .noUi-handle.darkness-level:active .noUi-touch-area {
cursor: inherit;
}
-#darkness-adjuster .synchronized .slider .noUi-origin .noUi-handle i.fas {
+#darkness-adjuster .synchronized .slider .noUi-origin .noUi-handle i.fa-solid {
cursor: inherit;
}
#darkness-adjuster .synchronized .slider .noUi-pips {
@@ -17441,24 +17579,24 @@ body > .choices__list--dropdown {
#homebrew-settings section.window-content .form-group.buttons {
margin-top: 0.5em;
}
-.damage-types th,
-.damage-types td {
+table.damage-types th,
+table.damage-types td {
white-space: nowrap;
}
-.damage-types th:not(:last-child),
-.damage-types td:not(:last-child) {
+table.damage-types th:not(:last-child),
+table.damage-types td:not(:last-child) {
padding-right: 0.25rem;
}
-.damage-types .icon-preview {
+table.damage-types .icon-preview {
display: flex;
align-items: center;
gap: 0.125rem;
}
-.damage-types .delete-cell {
+table.damage-types .delete-cell {
text-align: end;
width: 1rem;
}
-.damage-types .delete-cell i {
+table.damage-types .delete-cell i {
padding: 0.125rem 0.25rem;
cursor: pointer;
}
@@ -17646,7 +17784,8 @@ body > .choices__list--dropdown {
.compendium-migration-status table * {
user-select: text;
}
-.compendium-migration-status table * th, .compendium-migration-status table * td {
+.compendium-migration-status table * th,
+.compendium-migration-status table * td {
padding: 0.25em 0.5em;
white-space: nowrap;
}
@@ -17844,9 +17983,6 @@ body > .choices__list--dropdown {
--space-2xl: 2em;
--radius: 3px;
}
-.journal-entry-page .journal-page-content p {
- min-height: unset;
-}
.journal-entry-page .journal-page-content :is(h1, h2, h3, h4, h5, h6):not(:first-child) {
margin-top: 1em;
}
@@ -18317,9 +18453,6 @@ body > .choices__list--dropdown {
.tags.paizo-style .tag:last-child {
border-right-width: 3px;
}
-.tags.paizo-style .tag.alignment {
- background-color: var(--color-bg-alignment);
-}
.tags.paizo-style .tag.size {
background-color: var(--color-bg-size);
}
@@ -18408,8 +18541,8 @@ tags.tags.paizo-style tag[readonly=true] {
}
tags.tagify.pf2e-tagify {
--tag-bg: var(--color-text-light-3);
- --tags-border-color: var(--color-text-light-5);
- --tags-hover-border-color: var(--color-text-light-5);
+ --tags-border-color: var(--color-border-light-2);
+ --tags-hover-border-color: var(--color-border-light-2);
align-items: center;
background-color: rgba(255, 255, 255, 0.5);
border-radius: 3px;
diff --git a/Data/systems/pf2e/system.json b/Data/systems/pf2e/system.json
index 950d1d8b..a5edb730 100644
--- a/Data/systems/pf2e/system.json
+++ b/Data/systems/pf2e/system.json
@@ -2,10 +2,10 @@
"id": "pf2e",
"title": "Pathfinder Second Edition",
"description": "A community contributed game system for Pathfinder Second Edition",
+ "version": "5.11.5",
"license": "./LICENSE",
- "version": "5.8.3",
"compatibility": {
- "minimum": "11.308",
+ "minimum": "11.311",
"verified": "11.315",
"maximum": "11"
},
@@ -1241,5 +1241,5 @@
"bugs": "https://github.com/foundryvtt/pf2e/issues",
"changelog": "https://github.com/foundryvtt/pf2e/blob/release/CHANGELOG.md",
"manifest": "https://github.com/foundryvtt/pf2e/releases/latest/download/system.json",
- "download": "https://github.com/foundryvtt/pf2e/releases/download/5.8.3/pf2e.zip"
+ "download": "https://github.com/foundryvtt/pf2e/releases/download/5.11.5/pf2e.zip"
}
diff --git a/Data/systems/pf2e/template.json b/Data/systems/pf2e/template.json
index a8212e1a..dd82268a 100644
--- a/Data/systems/pf2e/template.json
+++ b/Data/systems/pf2e/template.json
@@ -7,7 +7,8 @@
"loot",
"familiar",
"party",
- "vehicle"
+ "vehicle",
+ "army"
],
"templates": {
"common": {
@@ -25,9 +26,6 @@
}
},
"details": {
- "alignment": {
- "value": "N"
- },
"level": {
"value": 1
}
@@ -62,7 +60,7 @@
"templates": [
"common"
],
- "exploration": [],
+ "abilities": null,
"details": {
"biography": {
"appearance": "",
@@ -70,6 +68,8 @@
"birthPlace": "",
"attitude": "",
"beliefs": "",
+ "anathema": [],
+ "edicts": [],
"likes": "",
"dislikes": "",
"catchphrases": "",
@@ -182,7 +182,8 @@
"RO": null,
"VW": null
}
- }
+ },
+ "exploration": []
},
"npc": {
"templates": [
@@ -435,6 +436,55 @@
"version": null,
"previous": null
}
+ },
+ "army": {
+ "templates": [],
+ "ac": {
+ "value": null,
+ "potency": 0
+ },
+ "attributes": {
+ "hp": {
+ "value": 4,
+ "max": 4,
+ "routThreshold": 2
+ }
+ },
+ "details": {
+ "level": {
+ "value": 1
+ },
+ "alignment": "Neutral",
+ "description": "",
+ "blurb": ""
+ },
+ "traits": {
+ "rarity": "common",
+ "type": "infantry",
+ "size": {
+ "value": "med"
+ },
+ "value": []
+ },
+ "consumption": 1,
+ "recruitmentDC": 15,
+ "resources": {
+ "potions": {
+ "value": 0
+ },
+ "ammunition": {
+ "value": 5,
+ "max": 5
+ }
+ },
+ "saves": {
+ "maneuver": 10,
+ "morale": 4
+ },
+ "weapons": {
+ "melee": null,
+ "ranged": null
+ }
}
},
"Item": {
@@ -458,6 +508,7 @@
"kit",
"lore",
"melee",
+ "shield",
"spell",
"spellcastingEntry",
"treasure",
@@ -505,27 +556,20 @@
},
"quantity": 1,
"baseItem": null,
+ "bulk": {
+ "value": 0.1
+ },
"hp": {
"value": 0,
"max": 0
},
"hardness": 0,
- "weight": {
- "value": "L"
- },
- "equippedBulk": {
- "value": ""
- },
"price": {
"value": {}
},
"equipped": {
"carryType": "worn"
},
- "stackGroup": null,
- "negateBulk": {
- "value": "0"
- },
"containerId": null,
"size": "med",
"material": {
@@ -544,9 +588,6 @@
}
},
"misidentified": {}
- },
- "usage": {
- "value": ""
}
},
"itemLevel": {
@@ -590,8 +631,11 @@
"physical",
"investable"
],
- "bulkCapacity": {
- "value": ""
+ "bulk": {
+ "value": 0,
+ "heldOrStowed": 0.1,
+ "capacity": 10,
+ "ignored": 0
},
"collapsed": false,
"stowing": false,
@@ -612,7 +656,8 @@
"templates": [
"common",
"physical"
- ]
+ ],
+ "stackGroup": null
},
"weapon": {
"templates": [
@@ -620,6 +665,9 @@
"physical",
"investable"
],
+ "usage": {
+ "value": "held-in-one-hand"
+ },
"category": "simple",
"group": null,
"bonus": {
@@ -644,30 +692,12 @@
"reload": {
"value": null
},
- "potencyRune": {
- "value": 0
- },
- "strikingRune": {
- "value": ""
- },
- "specific": {
- "value": false
- },
- "propertyRune1": {
- "value": null
- },
- "propertyRune2": {
- "value": null
- },
- "propertyRune3": {
- "value": null
- },
- "propertyRune4": {
- "value": null
- },
- "usage": {
- "value": "held-in-one-hand"
+ "runes": {
+ "potency": 0,
+ "striking": 0,
+ "property": []
},
+ "specific": null,
"property1": {
"value": "",
"dice": 0,
@@ -689,29 +719,13 @@
"group": null,
"acBonus": 0,
"strength": 0,
- "dexCap": 0,
- "checkPenalty": null,
- "speedPenalty": null,
- "potencyRune": {
- "value": 0
- },
- "resiliencyRune": {
- "value": ""
- },
- "propertyRune1": {
- "value": ""
- },
- "propertyRune2": {
- "value": ""
- },
- "propertyRune3": {
- "value": ""
- },
- "propertyRune4": {
- "value": ""
- },
- "usage": {
- "value": "wornarmor"
+ "dexCap": 5,
+ "checkPenalty": 0,
+ "speedPenalty": 0,
+ "runes": {
+ "potency": 0,
+ "resilient": 0,
+ "property": []
}
},
"melee": {
@@ -738,23 +752,23 @@
"common",
"physical"
],
- "consumableType": {
- "value": "other"
- },
- "charges": {
- "value": 0,
- "max": 0
- },
- "consume": {
- "value": ""
- },
- "autoDestroy": {
- "value": true
+ "category": "other",
+ "uses": {
+ "value": 1,
+ "max": 1,
+ "autoDestroy": true
},
+ "damage": null,
"usage": {
"value": "held-in-one-hand"
},
- "spell": null
+ "stackGroup": null,
+ "spell": null,
+ "traits": {
+ "value": [
+ "consumable"
+ ]
+ }
},
"equipment": {
"templates": [
@@ -889,7 +903,7 @@
"medium": 0,
"heavy": 0
},
- "classDC": 0,
+ "spellcasting": 0,
"ancestryFeatLevels": {
"value": [
1,
@@ -1003,14 +1017,23 @@
"actions": {
"value": null
},
- "requirements": {
- "value": ""
- },
- "trigger": {
- "value": ""
- },
"deathNote": false
},
+ "shield": {
+ "templates": [
+ "common",
+ "physical"
+ ],
+ "acBonus": 2,
+ "runes": {
+ "reinforcing": 0
+ },
+ "specific": null,
+ "speedPenalty": 0,
+ "traits": {
+ "integrated": null
+ }
+ },
"spell": {
"templates": [
"common",
@@ -1020,24 +1043,10 @@
"level": {
"value": 1
},
- "spellType": {
- "value": "attack"
- },
- "category": {
- "value": "spell"
- },
- "traditions": {
- "value": []
- },
- "components": {
- "focus": false,
- "material": false,
- "somatic": false,
- "verbal": false
- },
- "materials": {
- "value": ""
+ "traits": {
+ "traditions": []
},
+ "requirements": "",
"target": {
"value": ""
},
@@ -1049,27 +1058,18 @@
"value": "2"
},
"duration": {
- "value": ""
- },
- "damage": {
- "value": {}
- },
- "save": {
"value": "",
- "basic": ""
- },
- "sustained": {
- "value": false
+ "sustained": false
},
+ "damage": {},
+ "defense": null,
"cost": {
"value": ""
},
"location": {
"value": null
},
- "hasCounteractCheck": {
- "value": false
- }
+ "counteraction": false
},
"spellcastingEntry": {
"templates": [
@@ -1225,10 +1225,11 @@
"common"
],
"category": "deity",
- "alignment": {
- "own": "N",
- "follower": [
- "N"
+ "sanctification": {
+ "modal": "can",
+ "what": [
+ "holy",
+ "unholy"
]
},
"domains": {
@@ -1239,7 +1240,7 @@
"harm",
"heal"
],
- "ability": [],
+ "attribute": [],
"skill": null,
"weapons": [],
"spells": {}
diff --git a/Data/systems/pf2e/templates/actors/actions/base/chat-message-content.hbs b/Data/systems/pf2e/templates/actors/actions/base/chat-message-content.hbs
index a239ccb1..16eed15e 100644
--- a/Data/systems/pf2e/templates/actors/actions/base/chat-message-content.hbs
+++ b/Data/systems/pf2e/templates/actors/actions/base/chat-message-content.hbs
@@ -4,9 +4,9 @@
{{/if}}
{{localize name}}
-